typescript-virtual-container 1.2.8 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (307) hide show
  1. package/.vscode/settings.json +0 -1
  2. package/README.md +462 -44
  3. package/biome.json +7 -0
  4. package/dist/SSHMimic/exec.d.ts.map +1 -1
  5. package/dist/SSHMimic/executor.d.ts.map +1 -1
  6. package/dist/SSHMimic/executor.js +35 -21
  7. package/dist/SSHMimic/index.d.ts.map +1 -1
  8. package/dist/SSHMimic/index.js +20 -6
  9. package/dist/VirtualFileSystem/binaryPack.d.ts.map +1 -1
  10. package/dist/VirtualFileSystem/binaryPack.js +29 -6
  11. package/dist/VirtualFileSystem/index.d.ts.map +1 -1
  12. package/dist/VirtualFileSystem/index.js +36 -13
  13. package/dist/VirtualPackageManager/index.d.ts +202 -0
  14. package/dist/VirtualPackageManager/index.d.ts.map +1 -0
  15. package/dist/VirtualPackageManager/index.js +825 -0
  16. package/dist/VirtualShell/index.d.ts +93 -12
  17. package/dist/VirtualShell/index.d.ts.map +1 -1
  18. package/dist/VirtualShell/index.js +95 -13
  19. package/dist/VirtualShell/shell.d.ts.map +1 -1
  20. package/dist/VirtualShell/shell.js +3 -1
  21. package/dist/VirtualShell/shellParser.d.ts.map +1 -1
  22. package/dist/VirtualUserManager/index.d.ts +52 -20
  23. package/dist/VirtualUserManager/index.d.ts.map +1 -1
  24. package/dist/VirtualUserManager/index.js +54 -20
  25. package/dist/commands/adduser.d.ts +6 -0
  26. package/dist/commands/adduser.d.ts.map +1 -1
  27. package/dist/commands/adduser.js +6 -0
  28. package/dist/commands/alias.d.ts +9 -0
  29. package/dist/commands/alias.d.ts.map +1 -0
  30. package/dist/commands/alias.js +63 -0
  31. package/dist/commands/apt.d.ts +9 -0
  32. package/dist/commands/apt.d.ts.map +1 -0
  33. package/dist/commands/apt.js +205 -0
  34. package/dist/commands/awk.d.ts +11 -0
  35. package/dist/commands/awk.d.ts.map +1 -1
  36. package/dist/commands/awk.js +15 -2
  37. package/dist/commands/base64.d.ts +5 -0
  38. package/dist/commands/base64.d.ts.map +1 -1
  39. package/dist/commands/base64.js +9 -1
  40. package/dist/commands/cat.d.ts +5 -0
  41. package/dist/commands/cat.d.ts.map +1 -1
  42. package/dist/commands/cat.js +35 -8
  43. package/dist/commands/cd.d.ts +5 -0
  44. package/dist/commands/cd.d.ts.map +1 -1
  45. package/dist/commands/cd.js +5 -0
  46. package/dist/commands/chmod.d.ts +5 -0
  47. package/dist/commands/chmod.d.ts.map +1 -1
  48. package/dist/commands/chmod.js +57 -3
  49. package/dist/commands/command-helpers.d.ts +78 -4
  50. package/dist/commands/command-helpers.d.ts.map +1 -1
  51. package/dist/commands/command-helpers.js +78 -4
  52. package/dist/commands/cp.d.ts +5 -0
  53. package/dist/commands/cp.d.ts.map +1 -1
  54. package/dist/commands/cp.js +5 -0
  55. package/dist/commands/curl.d.ts +5 -0
  56. package/dist/commands/curl.d.ts.map +1 -1
  57. package/dist/commands/curl.js +106 -26
  58. package/dist/commands/cut.d.ts +5 -0
  59. package/dist/commands/cut.d.ts.map +1 -1
  60. package/dist/commands/cut.js +8 -1
  61. package/dist/commands/date.d.ts +5 -0
  62. package/dist/commands/date.d.ts.map +1 -1
  63. package/dist/commands/date.js +7 -1
  64. package/dist/commands/declare.d.ts +3 -0
  65. package/dist/commands/declare.d.ts.map +1 -0
  66. package/dist/commands/declare.js +39 -0
  67. package/dist/commands/diff.d.ts +5 -0
  68. package/dist/commands/diff.d.ts.map +1 -1
  69. package/dist/commands/diff.js +5 -0
  70. package/dist/commands/dpkg.d.ts +9 -0
  71. package/dist/commands/dpkg.d.ts.map +1 -0
  72. package/dist/commands/dpkg.js +161 -0
  73. package/dist/commands/du.d.ts.map +1 -1
  74. package/dist/commands/du.js +8 -2
  75. package/dist/commands/echo.d.ts +5 -0
  76. package/dist/commands/echo.d.ts.map +1 -1
  77. package/dist/commands/echo.js +33 -12
  78. package/dist/commands/env.d.ts +5 -0
  79. package/dist/commands/env.d.ts.map +1 -1
  80. package/dist/commands/env.js +11 -1
  81. package/dist/commands/exit.d.ts +5 -0
  82. package/dist/commands/exit.d.ts.map +1 -1
  83. package/dist/commands/exit.js +12 -2
  84. package/dist/commands/export.d.ts.map +1 -1
  85. package/dist/commands/export.js +3 -1
  86. package/dist/commands/find.d.ts +5 -0
  87. package/dist/commands/find.d.ts.map +1 -1
  88. package/dist/commands/find.js +5 -0
  89. package/dist/commands/free.d.ts +8 -0
  90. package/dist/commands/free.d.ts.map +1 -0
  91. package/dist/commands/free.js +43 -0
  92. package/dist/commands/grep.d.ts +5 -0
  93. package/dist/commands/grep.d.ts.map +1 -1
  94. package/dist/commands/grep.js +12 -2
  95. package/dist/commands/gzip.d.ts +5 -0
  96. package/dist/commands/gzip.d.ts.map +1 -1
  97. package/dist/commands/gzip.js +18 -2
  98. package/dist/commands/head.d.ts +5 -0
  99. package/dist/commands/head.d.ts.map +1 -1
  100. package/dist/commands/head.js +5 -0
  101. package/dist/commands/help.d.ts.map +1 -1
  102. package/dist/commands/help.js +98 -45
  103. package/dist/commands/helpers.d.ts +3 -0
  104. package/dist/commands/helpers.d.ts.map +1 -1
  105. package/dist/commands/helpers.js +3 -0
  106. package/dist/commands/history.d.ts +8 -0
  107. package/dist/commands/history.d.ts.map +1 -0
  108. package/dist/commands/history.js +26 -0
  109. package/dist/commands/hostname.d.ts +5 -0
  110. package/dist/commands/hostname.d.ts.map +1 -1
  111. package/dist/commands/hostname.js +5 -0
  112. package/dist/commands/id.d.ts.map +1 -1
  113. package/dist/commands/id.js +4 -1
  114. package/dist/commands/index.d.ts +2 -10
  115. package/dist/commands/index.d.ts.map +1 -1
  116. package/dist/commands/index.js +2 -231
  117. package/dist/commands/ls.d.ts.map +1 -1
  118. package/dist/commands/ls.js +6 -3
  119. package/dist/commands/lsb-release.d.ts +3 -0
  120. package/dist/commands/lsb-release.d.ts.map +1 -0
  121. package/dist/commands/lsb-release.js +56 -0
  122. package/dist/commands/man.d.ts +3 -0
  123. package/dist/commands/man.d.ts.map +1 -0
  124. package/dist/commands/man.js +155 -0
  125. package/dist/commands/nano.js +1 -1
  126. package/dist/commands/neofetch.d.ts.map +1 -1
  127. package/dist/commands/neofetch.js +6 -1
  128. package/dist/commands/node.d.ts +9 -0
  129. package/dist/commands/node.d.ts.map +1 -0
  130. package/dist/commands/node.js +316 -0
  131. package/dist/commands/npm.d.ts +19 -0
  132. package/dist/commands/npm.d.ts.map +1 -0
  133. package/dist/commands/npm.js +109 -0
  134. package/dist/commands/ping.d.ts.map +1 -1
  135. package/dist/commands/ping.js +7 -2
  136. package/dist/commands/printf.d.ts +3 -0
  137. package/dist/commands/printf.d.ts.map +1 -0
  138. package/dist/commands/printf.js +113 -0
  139. package/dist/commands/ps.d.ts.map +1 -1
  140. package/dist/commands/ps.js +30 -6
  141. package/dist/commands/python.d.ts +30 -0
  142. package/dist/commands/python.d.ts.map +1 -0
  143. package/dist/commands/python.js +2058 -0
  144. package/dist/commands/read.d.ts +3 -0
  145. package/dist/commands/read.d.ts.map +1 -0
  146. package/dist/commands/read.js +34 -0
  147. package/dist/commands/registry.d.ts +8 -0
  148. package/dist/commands/registry.d.ts.map +1 -0
  149. package/dist/commands/registry.js +229 -0
  150. package/dist/commands/runtime.d.ts +6 -0
  151. package/dist/commands/runtime.d.ts.map +1 -0
  152. package/dist/commands/runtime.js +280 -0
  153. package/dist/commands/sed.d.ts.map +1 -1
  154. package/dist/commands/sed.js +11 -3
  155. package/dist/commands/set.d.ts.map +1 -1
  156. package/dist/commands/set.js +9 -3
  157. package/dist/commands/sh.d.ts.map +1 -1
  158. package/dist/commands/sh.js +69 -30
  159. package/dist/commands/shift.d.ts +5 -0
  160. package/dist/commands/shift.d.ts.map +1 -0
  161. package/dist/commands/shift.js +52 -0
  162. package/dist/commands/sleep.d.ts.map +1 -1
  163. package/dist/commands/sort.d.ts.map +1 -1
  164. package/dist/commands/sort.js +4 -2
  165. package/dist/commands/source.d.ts +3 -0
  166. package/dist/commands/source.d.ts.map +1 -0
  167. package/dist/commands/source.js +34 -0
  168. package/dist/commands/sudo.js +1 -1
  169. package/dist/commands/tar.d.ts.map +1 -1
  170. package/dist/commands/tar.js +11 -3
  171. package/dist/commands/tee.d.ts.map +1 -1
  172. package/dist/commands/tee.js +8 -6
  173. package/dist/commands/test.d.ts +3 -0
  174. package/dist/commands/test.d.ts.map +1 -0
  175. package/dist/commands/test.js +114 -0
  176. package/dist/commands/tr.d.ts.map +1 -1
  177. package/dist/commands/tr.js +3 -1
  178. package/dist/commands/true.d.ts +4 -0
  179. package/dist/commands/true.d.ts.map +1 -0
  180. package/dist/commands/true.js +14 -0
  181. package/dist/commands/type.d.ts +3 -0
  182. package/dist/commands/type.d.ts.map +1 -0
  183. package/dist/commands/type.js +34 -0
  184. package/dist/commands/uname.d.ts.map +1 -1
  185. package/dist/commands/uname.js +4 -1
  186. package/dist/commands/uniq.d.ts.map +1 -1
  187. package/dist/commands/uptime.d.ts +3 -0
  188. package/dist/commands/uptime.d.ts.map +1 -0
  189. package/dist/commands/uptime.js +43 -0
  190. package/dist/commands/wget.d.ts.map +1 -1
  191. package/dist/commands/wget.js +92 -96
  192. package/dist/commands/which.d.ts +3 -0
  193. package/dist/commands/which.d.ts.map +1 -0
  194. package/dist/commands/which.js +32 -0
  195. package/dist/commands/xargs.d.ts.map +1 -1
  196. package/dist/commands/xargs.js +1 -1
  197. package/dist/index.d.ts +15 -11
  198. package/dist/index.d.ts.map +1 -1
  199. package/dist/index.js +9 -8
  200. package/dist/modules/linuxRootfs.d.ts +41 -0
  201. package/dist/modules/linuxRootfs.d.ts.map +1 -0
  202. package/dist/modules/linuxRootfs.js +440 -0
  203. package/dist/modules/neofetch.d.ts.map +1 -1
  204. package/dist/modules/neofetch.js +1 -0
  205. package/dist/standalone-wo-sftp.d.ts +2 -0
  206. package/dist/standalone-wo-sftp.d.ts.map +1 -0
  207. package/dist/standalone-wo-sftp.js +30 -0
  208. package/dist/utils/expand.d.ts +50 -0
  209. package/dist/utils/expand.d.ts.map +1 -0
  210. package/dist/utils/expand.js +183 -0
  211. package/dist/utils/vfsDiff.d.ts +90 -0
  212. package/dist/utils/vfsDiff.d.ts.map +1 -0
  213. package/dist/utils/vfsDiff.js +177 -0
  214. package/package.json +3 -1
  215. package/src/SSHMimic/exec.ts +10 -1
  216. package/src/SSHMimic/executor.ts +105 -21
  217. package/src/SSHMimic/index.ts +49 -15
  218. package/src/VirtualFileSystem/binaryPack.ts +35 -8
  219. package/src/VirtualFileSystem/index.ts +78 -28
  220. package/src/VirtualPackageManager/index.ts +979 -0
  221. package/src/VirtualShell/index.ts +133 -14
  222. package/src/VirtualShell/shell.ts +23 -3
  223. package/src/VirtualShell/shellParser.ts +134 -36
  224. package/src/VirtualUserManager/index.ts +62 -22
  225. package/src/commands/adduser.ts +6 -0
  226. package/src/commands/alias.ts +64 -0
  227. package/src/commands/apt.ts +228 -0
  228. package/src/commands/awk.ts +20 -6
  229. package/src/commands/base64.ts +13 -2
  230. package/src/commands/cat.ts +40 -8
  231. package/src/commands/cd.ts +5 -0
  232. package/src/commands/chmod.ts +53 -3
  233. package/src/commands/command-helpers.ts +78 -4
  234. package/src/commands/cp.ts +5 -0
  235. package/src/commands/curl.ts +118 -33
  236. package/src/commands/cut.ts +8 -1
  237. package/src/commands/date.ts +7 -1
  238. package/src/commands/declare.ts +44 -0
  239. package/src/commands/diff.ts +17 -3
  240. package/src/commands/dpkg.ts +180 -0
  241. package/src/commands/du.ts +17 -5
  242. package/src/commands/echo.ts +41 -12
  243. package/src/commands/env.ts +11 -1
  244. package/src/commands/exit.ts +12 -2
  245. package/src/commands/export.ts +3 -1
  246. package/src/commands/find.ts +5 -0
  247. package/src/commands/free.ts +47 -0
  248. package/src/commands/grep.ts +12 -2
  249. package/src/commands/gzip.ts +28 -4
  250. package/src/commands/head.ts +5 -0
  251. package/src/commands/help.ts +121 -47
  252. package/src/commands/helpers.ts +8 -0
  253. package/src/commands/history.ts +34 -0
  254. package/src/commands/hostname.ts +5 -0
  255. package/src/commands/id.ts +4 -1
  256. package/src/commands/index.ts +9 -255
  257. package/src/commands/ls.ts +6 -3
  258. package/src/commands/lsb-release.ts +58 -0
  259. package/src/commands/man.ts +166 -0
  260. package/src/commands/nano.ts +1 -1
  261. package/src/commands/neofetch.ts +6 -1
  262. package/src/commands/node.ts +341 -0
  263. package/src/commands/npm.ts +132 -0
  264. package/src/commands/ping.ts +10 -3
  265. package/src/commands/printf.ts +112 -0
  266. package/src/commands/ps.ts +40 -6
  267. package/src/commands/python.ts +2229 -0
  268. package/src/commands/read.ts +41 -0
  269. package/src/commands/registry.ts +244 -0
  270. package/src/commands/runtime.ts +353 -0
  271. package/src/commands/sed.ts +27 -9
  272. package/src/commands/set.ts +9 -3
  273. package/src/commands/sh.ts +170 -44
  274. package/src/commands/shift.ts +53 -0
  275. package/src/commands/sleep.ts +2 -1
  276. package/src/commands/sort.ts +10 -6
  277. package/src/commands/source.ts +47 -0
  278. package/src/commands/sudo.ts +1 -1
  279. package/src/commands/tar.ts +28 -7
  280. package/src/commands/tee.ts +7 -1
  281. package/src/commands/test.ts +135 -0
  282. package/src/commands/tr.ts +3 -1
  283. package/src/commands/true.ts +17 -0
  284. package/src/commands/type.ts +43 -0
  285. package/src/commands/uname.ts +5 -1
  286. package/src/commands/uniq.ts +8 -2
  287. package/src/commands/uptime.ts +49 -0
  288. package/src/commands/wget.ts +105 -119
  289. package/src/commands/which.ts +37 -0
  290. package/src/commands/xargs.ts +11 -2
  291. package/src/index.ts +27 -18
  292. package/src/modules/linuxRootfs.ts +642 -0
  293. package/src/modules/neofetch.ts +1 -0
  294. package/src/standalone-wo-sftp.ts +38 -0
  295. package/src/utils/expand.ts +238 -0
  296. package/src/utils/vfsDiff.ts +275 -0
  297. package/standalone-wo-sftp.js +507 -0
  298. package/standalone-wo-sftp.js.map +7 -0
  299. package/standalone.js +486 -109
  300. package/standalone.js.map +4 -4
  301. package/tests/bun-test-shim.ts +9 -1
  302. package/tests/command-helpers.test.ts +1 -5
  303. package/tests/new-features.test.ts +1036 -0
  304. package/tests/parser-executor.test.ts +27 -27
  305. package/tests/sftp.test.ts +122 -42
  306. package/tests/users.test.ts +23 -5
  307. package/CHANGELOG.md +0 -150
@@ -0,0 +1,238 @@
1
+ /**
2
+ * expand.ts
3
+ *
4
+ * Centralised shell variable and expression expansion.
5
+ * Used by `runCommand` (index.ts), `echo`, and `sh.ts`.
6
+ *
7
+ * Handles (in order):
8
+ * ~ tilde to $HOME
9
+ * $? last exit code
10
+ * $$ mock PID
11
+ * $# argument count (0 outside scripts)
12
+ * ${#VAR} string length
13
+ * ${VAR:-def} default if unset/empty
14
+ * ${VAR:=def} assign default if unset/empty
15
+ * ${VAR:+val} alternate value if set
16
+ * ${VAR} simple braced reference
17
+ * $VAR simple reference
18
+ * $((expr)) arithmetic (integer)
19
+ */
20
+
21
+ // ─── arithmetic evaluator ────────────────────────────────────────────────────
22
+
23
+ /**
24
+ * Evaluate a simple integer arithmetic expression.
25
+ * Supports: + - * / % ** unary- ( )
26
+ * Variables are resolved from `env` before evaluation.
27
+ * Returns NaN on syntax error.
28
+ */
29
+ export function evalArith(expr: string, env: Record<string, string>): number {
30
+ // Substitute variable names before evaluating
31
+ const substituted = expr.replace(
32
+ /\b([A-Za-z_][A-Za-z0-9_]*)\b/g,
33
+ (_, name) => {
34
+ const val = env[name];
35
+ return val !== undefined && val !== "" ? val : "0";
36
+ },
37
+ );
38
+
39
+ // Whitelist: only digits, operators, spaces, parens
40
+ if (!/^[\d\s+\-*/%()^!&|<>=,. ]+$/.test(substituted)) return NaN;
41
+
42
+ try {
43
+ // Use Function constructor for safe subset (no identifiers remain)
44
+ // eslint-disable-next-line no-new-func
45
+ const result = Function(
46
+ `"use strict"; return (${substituted.replace(/\*\*/g, "**")});`,
47
+ )();
48
+ return typeof result === "number" ? Math.trunc(result) : NaN;
49
+ } catch {
50
+ return NaN;
51
+ }
52
+ }
53
+
54
+ // ─── synchronous expansion ───────────────────────────────────────────────────
55
+
56
+ /**
57
+ * Apply a replacer only to portions of `input` that are NOT inside single quotes.
58
+ * Single-quoted content is passed through verbatim (POSIX sh behaviour).
59
+ */
60
+ function outsideSingleQuotes(
61
+ input: string,
62
+ replacer: (chunk: string) => string,
63
+ ): string {
64
+ const parts: string[] = [];
65
+ let i = 0;
66
+ while (i < input.length) {
67
+ const sqIdx = input.indexOf("'", i);
68
+ if (sqIdx === -1) {
69
+ // No more single quotes — expand the rest
70
+ parts.push(replacer(input.slice(i)));
71
+ break;
72
+ }
73
+ // Expand the part before the single quote
74
+ parts.push(replacer(input.slice(i, sqIdx)));
75
+ // Find closing single quote — everything inside is literal
76
+ const closeIdx = input.indexOf("'", sqIdx + 1);
77
+ if (closeIdx === -1) {
78
+ // Unclosed quote — treat rest as literal
79
+ parts.push(input.slice(sqIdx));
80
+ break;
81
+ }
82
+ parts.push(input.slice(sqIdx, closeIdx + 1)); // include quotes
83
+ i = closeIdx + 1;
84
+ }
85
+ return parts.join("");
86
+ }
87
+
88
+ /**
89
+ * Expand all shell variable and expression forms synchronously.
90
+ * Does NOT handle `$(cmd)` — that requires async; see `expandAsync`.
91
+ * Content inside single quotes is left verbatim per POSIX sh rules.
92
+ *
93
+ * @param input Raw string possibly containing `$VAR`, `${...}`, `$((...))`.
94
+ * @param env Current session env vars.
95
+ * @param lastExit Last command exit code (for `$?`).
96
+ * @param home Home directory path (for `~`).
97
+ */
98
+ export function expandSync(
99
+ input: string,
100
+ env: Record<string, string>,
101
+ lastExit = 0,
102
+ home?: string,
103
+ ): string {
104
+ const homePath = home ?? env.HOME ?? "/home/user";
105
+
106
+ return outsideSingleQuotes(input, (chunk) => {
107
+ let s = chunk;
108
+
109
+ // Tilde expansion — only at start of token or after `:` or whitespace
110
+ s = s.replace(
111
+ /(^|[\s:])~(\/|$)/g,
112
+ (_, pre, post) => `${pre}${homePath}${post}`,
113
+ );
114
+
115
+ // $? $$ $#
116
+ s = s.replace(/\$\?/g, String(lastExit));
117
+ s = s.replace(/\$\$/g, "1");
118
+ s = s.replace(/\$#/g, "0");
119
+
120
+ // $(( arithmetic )) — must come before ${ and $VAR to avoid conflicts
121
+ s = s.replace(/\$\(\(([^)]+(?:\([^)]*\)[^)]*)*)\)\)/g, (_, expr) => {
122
+ const result = evalArith(expr, env);
123
+ return Number.isNaN(result) ? "0" : String(result);
124
+ });
125
+
126
+ // ${#VAR} — string length
127
+ s = s.replace(/\$\{#([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) =>
128
+ String((env[name] ?? "").length),
129
+ );
130
+
131
+ // ${VAR:-default}
132
+ s = s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*):-([^}]*)\}/g, (_, name, def) =>
133
+ env[name] !== undefined && env[name] !== "" ? (env[name] as string) : def,
134
+ );
135
+
136
+ // ${VAR:=default} — also assigns to env
137
+ s = s.replace(
138
+ /\$\{([A-Za-z_][A-Za-z0-9_]*):=([^}]*)\}/g,
139
+ (_, name, def) => {
140
+ if (env[name] === undefined || env[name] === "") env[name] = def;
141
+ return env[name] as string;
142
+ },
143
+ );
144
+
145
+ // ${VAR:+alternate}
146
+ s = s.replace(
147
+ /\$\{([A-Za-z_][A-Za-z0-9_]*):\+([^}]*)\}/g,
148
+ (_, name, alt) =>
149
+ env[name] !== undefined && env[name] !== "" ? alt : "",
150
+ );
151
+
152
+ // ${VAR}
153
+ s = s.replace(
154
+ /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
155
+ (_, name) => env[name] ?? "",
156
+ );
157
+
158
+ // $VAR
159
+ s = s.replace(/\$([A-Za-z_][A-Za-z0-9_]*)/g, (_, name) => env[name] ?? "");
160
+
161
+ return s;
162
+ });
163
+ }
164
+
165
+ // ─── async expansion (includes $(cmd)) ──────────────────────────────────────
166
+
167
+ /**
168
+ * Expand all shell forms including `$(cmd)` command substitution.
169
+ *
170
+ * Processes `$(...)` blocks depth-first, respecting single-quote boundaries.
171
+ * Then delegates to `expandSync` for the remaining forms.
172
+ *
173
+ * @param input Raw string.
174
+ * @param env Current session env vars.
175
+ * @param lastExit Last exit code.
176
+ * @param runCmd Async callback to execute a command and return its stdout.
177
+ */
178
+ export async function expandAsync(
179
+ input: string,
180
+ env: Record<string, string>,
181
+ lastExit: number,
182
+ runCmd: (cmd: string) => Promise<string>,
183
+ ): Promise<string> {
184
+ // $(cmd) substitution — skip content inside single quotes
185
+ if (input.includes("$(")) {
186
+ let result = "";
187
+ let inSingle = false;
188
+ let i = 0;
189
+
190
+ while (i < input.length) {
191
+ const ch = input[i]!;
192
+
193
+ if (ch === "'" && !inSingle) {
194
+ inSingle = true;
195
+ result += ch;
196
+ i++;
197
+ continue;
198
+ }
199
+ if (ch === "'" && inSingle) {
200
+ inSingle = false;
201
+ result += ch;
202
+ i++;
203
+ continue;
204
+ }
205
+
206
+ if (!inSingle && ch === "$" && input[i + 1] === "(") {
207
+ // $((expr)) arithmetic — NOT a $(cmd) substitution, skip it
208
+ if (input[i + 2] === "(") {
209
+ result += ch;
210
+ i++;
211
+ continue;
212
+ }
213
+ // Find matching ) with depth tracking
214
+ let depth = 0;
215
+ let j = i + 1;
216
+ while (j < input.length) {
217
+ if (input[j] === "(") depth++;
218
+ else if (input[j] === ")") {
219
+ depth--;
220
+ if (depth === 0) break;
221
+ }
222
+ j++;
223
+ }
224
+ const sub = input.slice(i + 2, j).trim();
225
+ const out = (await runCmd(sub)).replace(/\n$/, "");
226
+ result += out;
227
+ i = j + 1;
228
+ continue;
229
+ }
230
+
231
+ result += ch;
232
+ i++;
233
+ }
234
+ input = result;
235
+ }
236
+
237
+ return expandSync(input, env, lastExit);
238
+ }
@@ -0,0 +1,275 @@
1
+ /**
2
+ * vfsDiff.ts
3
+ *
4
+ * Snapshot diff tooling for `VirtualFileSystem`.
5
+ *
6
+ * Compares two VFS snapshots and returns structured diff results suitable
7
+ * for test assertions, audit logging, and deployment verification.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { diffSnapshots, formatDiff } from "typescript-virtual-container/utils/vfsDiff";
12
+ *
13
+ * const before = shell.vfs.toSnapshot();
14
+ * await client.exec("npm install && mkdir -p /app");
15
+ * const after = shell.vfs.toSnapshot();
16
+ *
17
+ * const diff = diffSnapshots(before, after);
18
+ * console.log(formatDiff(diff));
19
+ *
20
+ * // Test assertions
21
+ * expect(diff.added).toContain("/app");
22
+ * expect(diff.modified).toContain("/etc/hosts");
23
+ * expect(diff.removed).not.toContain("/tmp/needed-file");
24
+ * ```
25
+ */
26
+
27
+ import type {
28
+ VfsSnapshot,
29
+ VfsSnapshotNode,
30
+ VfsSnapshotFileNode,
31
+ VfsSnapshotDirectoryNode,
32
+ } from "../types/vfs";
33
+
34
+ // ─── types ────────────────────────────────────────────────────────────────────
35
+
36
+ /** A single changed file entry in a diff result. */
37
+ export interface VfsDiffEntry {
38
+ /** Absolute VFS path of the changed node. */
39
+ path: string;
40
+ /** Node type — `"file"` or `"directory"`. */
41
+ type: "file" | "directory";
42
+ }
43
+
44
+ /** A modified file entry — includes before/after content for files. */
45
+ export interface VfsDiffModified extends VfsDiffEntry {
46
+ type: "file";
47
+ /** Content before the change (decoded from base64). */
48
+ before: string;
49
+ /** Content after the change (decoded from base64). */
50
+ after: string;
51
+ }
52
+
53
+ /** Full result of a snapshot diff operation. */
54
+ export interface VfsDiff {
55
+ /** Paths present in `after` but not in `before`. */
56
+ added: VfsDiffEntry[];
57
+ /** Paths present in `before` but not in `after`. */
58
+ removed: VfsDiffEntry[];
59
+ /** Files whose content or mode changed between snapshots. */
60
+ modified: VfsDiffModified[];
61
+ /** True when there are no differences. */
62
+ clean: boolean;
63
+ }
64
+
65
+ // ─── internal helpers ─────────────────────────────────────────────────────────
66
+
67
+ function flattenSnapshot(
68
+ node: VfsSnapshotNode,
69
+ prefix: string,
70
+ out: Map<string, VfsSnapshotNode>,
71
+ ): void {
72
+ const path = prefix === "" ? "/" : prefix;
73
+ out.set(path, node);
74
+ if (node.type === "directory") {
75
+ for (const child of (node as VfsSnapshotDirectoryNode).children ?? []) {
76
+ flattenSnapshot(child, `${prefix}/${child.name}`, out);
77
+ }
78
+ }
79
+ }
80
+
81
+ function decodeContent(node: VfsSnapshotFileNode): string {
82
+ try {
83
+ return Buffer.from(node.contentBase64, "base64").toString("utf8");
84
+ } catch {
85
+ return node.contentBase64;
86
+ }
87
+ }
88
+
89
+ // ─── public API ───────────────────────────────────────────────────────────────
90
+
91
+ /**
92
+ * Compute the diff between two VFS snapshots.
93
+ *
94
+ * @param before Snapshot taken before the operation.
95
+ * @param after Snapshot taken after the operation.
96
+ * @param options Optional filtering options.
97
+ * @returns A structured `VfsDiff` result.
98
+ */
99
+ export function diffSnapshots(
100
+ before: VfsSnapshot,
101
+ after: VfsSnapshot,
102
+ options: {
103
+ /** Glob-style path prefixes to ignore (e.g. `["/proc", "/var/log"]`). */
104
+ ignore?: string[];
105
+ } = {},
106
+ ): VfsDiff {
107
+ const ignorePrefixes = options.ignore ?? [];
108
+
109
+ const shouldIgnore = (path: string): boolean =>
110
+ ignorePrefixes.some(
111
+ (prefix) => path === prefix || path.startsWith(`${prefix}/`),
112
+ );
113
+
114
+ const beforeMap = new Map<string, VfsSnapshotNode>();
115
+ const afterMap = new Map<string, VfsSnapshotNode>();
116
+
117
+ flattenSnapshot(before.root, "", beforeMap);
118
+ flattenSnapshot(after.root, "", afterMap);
119
+
120
+ const added: VfsDiffEntry[] = [];
121
+ const removed: VfsDiffEntry[] = [];
122
+ const modified: VfsDiffModified[] = [];
123
+
124
+ // Added — in after, not in before
125
+ for (const [path, node] of afterMap) {
126
+ if (shouldIgnore(path)) continue;
127
+ if (!beforeMap.has(path)) {
128
+ added.push({ path, type: node.type });
129
+ }
130
+ }
131
+
132
+ // Removed — in before, not in after
133
+ for (const [path, node] of beforeMap) {
134
+ if (shouldIgnore(path)) continue;
135
+ if (!afterMap.has(path)) {
136
+ removed.push({ path, type: node.type });
137
+ }
138
+ }
139
+
140
+ // Modified — in both, but content or mode changed
141
+ for (const [path, afterNode] of afterMap) {
142
+ if (shouldIgnore(path)) continue;
143
+ const beforeNode = beforeMap.get(path);
144
+ if (!beforeNode) continue; // already in added
145
+ if (afterNode.type !== beforeNode.type) continue; // type change = add+remove
146
+
147
+ if (afterNode.type === "file" && beforeNode.type === "file") {
148
+ const beforeContent = decodeContent(beforeNode as VfsSnapshotFileNode);
149
+ const afterContent = decodeContent(afterNode as VfsSnapshotFileNode);
150
+ const modeChanged = afterNode.mode !== beforeNode.mode;
151
+ if (beforeContent !== afterContent || modeChanged) {
152
+ modified.push({
153
+ path,
154
+ type: "file",
155
+ before: beforeContent,
156
+ after: afterContent,
157
+ });
158
+ }
159
+ }
160
+ }
161
+
162
+ // Sort all arrays for determinism
163
+ const sortByPath = (a: VfsDiffEntry, b: VfsDiffEntry) =>
164
+ a.path.localeCompare(b.path);
165
+
166
+ added.sort(sortByPath);
167
+ removed.sort(sortByPath);
168
+ modified.sort(sortByPath);
169
+
170
+ return {
171
+ added,
172
+ removed,
173
+ modified,
174
+ clean: added.length === 0 && removed.length === 0 && modified.length === 0,
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Format a `VfsDiff` as a human-readable string similar to `git diff --stat`.
180
+ *
181
+ * @param diff Result from `diffSnapshots`.
182
+ * @param options Formatting options.
183
+ */
184
+ export function formatDiff(
185
+ diff: VfsDiff,
186
+ options: {
187
+ /** Show file content changes inline. Default: false. */
188
+ showContent?: boolean;
189
+ /** Max chars of content to show per change. Default: 120. */
190
+ maxContentChars?: number;
191
+ } = {},
192
+ ): string {
193
+ if (diff.clean) return "(no changes)";
194
+
195
+ const { showContent = false, maxContentChars = 120 } = options;
196
+ const lines: string[] = [];
197
+
198
+ for (const entry of diff.added) {
199
+ lines.push(`+ ${entry.path} [${entry.type}]`);
200
+ }
201
+
202
+ for (const entry of diff.removed) {
203
+ lines.push(`- ${entry.path} [${entry.type}]`);
204
+ }
205
+
206
+ for (const entry of diff.modified) {
207
+ lines.push(`~ ${entry.path} [modified]`);
208
+ if (showContent) {
209
+ const before = entry.before.slice(0, maxContentChars);
210
+ const after = entry.after.slice(0, maxContentChars);
211
+ lines.push(
212
+ ` before: ${JSON.stringify(before)}${entry.before.length > maxContentChars ? "…" : ""}`,
213
+ );
214
+ lines.push(
215
+ ` after: ${JSON.stringify(after)}${entry.after.length > maxContentChars ? "…" : ""}`,
216
+ );
217
+ }
218
+ }
219
+
220
+ const summary = [
221
+ diff.added.length > 0 ? `${diff.added.length} added` : "",
222
+ diff.removed.length > 0 ? `${diff.removed.length} removed` : "",
223
+ diff.modified.length > 0 ? `${diff.modified.length} modified` : "",
224
+ ]
225
+ .filter(Boolean)
226
+ .join(", ");
227
+
228
+ lines.push(`\n${summary}`);
229
+ return lines.join("\n");
230
+ }
231
+
232
+ /**
233
+ * Assert that a diff contains specific paths, throwing on mismatch.
234
+ * Designed for use in test suites.
235
+ *
236
+ * @param diff Result from `diffSnapshots`.
237
+ * @param expect Expected paths in each category.
238
+ * @throws When any expectation is not met.
239
+ */
240
+ export function assertDiff(
241
+ diff: VfsDiff,
242
+ expect: {
243
+ added?: string[];
244
+ removed?: string[];
245
+ modified?: string[];
246
+ },
247
+ ): void {
248
+ const addedPaths = diff.added.map((e) => e.path);
249
+ const removedPaths = diff.removed.map((e) => e.path);
250
+ const modifiedPaths = diff.modified.map((e) => e.path);
251
+
252
+ for (const path of expect.added ?? []) {
253
+ if (!addedPaths.includes(path)) {
254
+ throw new Error(
255
+ `assertDiff: expected "${path}" to be added, but it was not.\nAdded: ${JSON.stringify(addedPaths)}`,
256
+ );
257
+ }
258
+ }
259
+
260
+ for (const path of expect.removed ?? []) {
261
+ if (!removedPaths.includes(path)) {
262
+ throw new Error(
263
+ `assertDiff: expected "${path}" to be removed, but it was not.\nRemoved: ${JSON.stringify(removedPaths)}`,
264
+ );
265
+ }
266
+ }
267
+
268
+ for (const path of expect.modified ?? []) {
269
+ if (!modifiedPaths.includes(path)) {
270
+ throw new Error(
271
+ `assertDiff: expected "${path}" to be modified, but it was not.\nModified: ${JSON.stringify(modifiedPaths)}`,
272
+ );
273
+ }
274
+ }
275
+ }