@seanhogg/builderforce-webcontainers-core 2026.10.7 → 2026.10.9

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 (385) hide show
  1. package/dist/archive.d.ts +2 -0
  2. package/dist/archive.d.ts.map +1 -1
  3. package/dist/archive.js +6 -4
  4. package/dist/archive.js.map +1 -1
  5. package/dist/build.d.ts +6 -0
  6. package/dist/build.d.ts.map +1 -1
  7. package/dist/build.js +9 -1
  8. package/dist/build.js.map +1 -1
  9. package/dist/buildHost.d.ts +3 -0
  10. package/dist/buildHost.d.ts.map +1 -1
  11. package/dist/buildHost.js +25 -12
  12. package/dist/buildHost.js.map +1 -1
  13. package/dist/compileComponent.d.ts.map +1 -1
  14. package/dist/compileComponent.js +4 -1
  15. package/dist/compileComponent.js.map +1 -1
  16. package/dist/compileScript.d.ts +12 -4
  17. package/dist/compileScript.d.ts.map +1 -1
  18. package/dist/compileScript.js +26 -13
  19. package/dist/compileScript.js.map +1 -1
  20. package/dist/components.d.ts +5 -0
  21. package/dist/components.d.ts.map +1 -1
  22. package/dist/components.js.map +1 -1
  23. package/dist/detectProject.d.ts +2 -0
  24. package/dist/detectProject.d.ts.map +1 -1
  25. package/dist/detectProject.js +13 -7
  26. package/dist/detectProject.js.map +1 -1
  27. package/dist/devServer.d.ts +38 -4
  28. package/dist/devServer.d.ts.map +1 -1
  29. package/dist/devServer.js +140 -24
  30. package/dist/devServer.js.map +1 -1
  31. package/dist/devStyles.d.ts +27 -0
  32. package/dist/devStyles.d.ts.map +1 -0
  33. package/dist/devStyles.js +52 -0
  34. package/dist/devStyles.js.map +1 -0
  35. package/dist/hot/client.d.ts +33 -0
  36. package/dist/hot/client.d.ts.map +1 -0
  37. package/dist/hot/client.js +46 -0
  38. package/dist/hot/client.js.map +1 -0
  39. package/dist/hot/moduleGraph.d.ts +39 -0
  40. package/dist/hot/moduleGraph.d.ts.map +1 -0
  41. package/dist/hot/moduleGraph.js +69 -0
  42. package/dist/hot/moduleGraph.js.map +1 -0
  43. package/dist/hot/planUpdate.d.ts +33 -0
  44. package/dist/hot/planUpdate.d.ts.map +1 -0
  45. package/dist/hot/planUpdate.js +43 -0
  46. package/dist/hot/planUpdate.js.map +1 -0
  47. package/dist/hot/reactRefresh.d.ts +45 -0
  48. package/dist/hot/reactRefresh.d.ts.map +1 -0
  49. package/dist/hot/reactRefresh.js +86 -0
  50. package/dist/hot/reactRefresh.js.map +1 -0
  51. package/dist/html.d.ts +4 -8
  52. package/dist/html.d.ts.map +1 -1
  53. package/dist/html.js +15 -19
  54. package/dist/html.js.map +1 -1
  55. package/dist/index.d.ts +20 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +12 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/installer/tree.d.ts.map +1 -1
  60. package/dist/installer/tree.js +22 -4
  61. package/dist/installer/tree.js.map +1 -1
  62. package/dist/installer/wasmBuilds.d.ts +27 -0
  63. package/dist/installer/wasmBuilds.d.ts.map +1 -0
  64. package/dist/installer/wasmBuilds.js +32 -0
  65. package/dist/installer/wasmBuilds.js.map +1 -0
  66. package/dist/node/builtins.d.ts +6 -1
  67. package/dist/node/builtins.d.ts.map +1 -1
  68. package/dist/node/builtins.js +15 -10
  69. package/dist/node/builtins.js.map +1 -1
  70. package/dist/node/childProcess.d.ts +3 -3
  71. package/dist/node/childProcess.d.ts.map +1 -1
  72. package/dist/node/childProcess.js +68 -16
  73. package/dist/node/childProcess.js.map +1 -1
  74. package/dist/node/crypto.d.ts.map +1 -1
  75. package/dist/node/crypto.js +5 -4
  76. package/dist/node/crypto.js.map +1 -1
  77. package/dist/node/esm.d.ts +7 -0
  78. package/dist/node/esm.d.ts.map +1 -1
  79. package/dist/node/esm.js +28 -2
  80. package/dist/node/esm.js.map +1 -1
  81. package/dist/node/fs/index.d.ts +3 -0
  82. package/dist/node/fs/index.d.ts.map +1 -1
  83. package/dist/node/fs/index.js +22 -106
  84. package/dist/node/fs/index.js.map +1 -1
  85. package/dist/node/fs/stdinFd.d.ts +10 -0
  86. package/dist/node/fs/stdinFd.d.ts.map +1 -0
  87. package/dist/node/fs/stdinFd.js +40 -0
  88. package/dist/node/fs/stdinFd.js.map +1 -0
  89. package/dist/node/fs/streams.d.ts +24 -0
  90. package/dist/node/fs/streams.d.ts.map +1 -0
  91. package/dist/node/fs/streams.js +144 -0
  92. package/dist/node/fs/streams.js.map +1 -0
  93. package/dist/node/fs/sync.d.ts +2 -0
  94. package/dist/node/fs/sync.d.ts.map +1 -1
  95. package/dist/node/fs/sync.js +17 -0
  96. package/dist/node/fs/sync.js.map +1 -1
  97. package/dist/node/globalObject.d.ts +25 -0
  98. package/dist/node/globalObject.d.ts.map +1 -0
  99. package/dist/node/globalObject.js +83 -0
  100. package/dist/node/globalObject.js.map +1 -0
  101. package/dist/node/http/client.d.ts +3 -1
  102. package/dist/node/http/client.d.ts.map +1 -1
  103. package/dist/node/http/client.js +74 -5
  104. package/dist/node/http/client.js.map +1 -1
  105. package/dist/node/http/index.d.ts.map +1 -1
  106. package/dist/node/http/index.js +6 -4
  107. package/dist/node/http/index.js.map +1 -1
  108. package/dist/node/http/messages.d.ts +87 -0
  109. package/dist/node/http/messages.d.ts.map +1 -0
  110. package/dist/node/http/messages.js +146 -0
  111. package/dist/node/http/messages.js.map +1 -0
  112. package/dist/node/http/server.d.ts +13 -98
  113. package/dist/node/http/server.d.ts.map +1 -1
  114. package/dist/node/http/server.js +41 -206
  115. package/dist/node/http/server.js.map +1 -1
  116. package/dist/node/http/serverResponse.d.ts +45 -0
  117. package/dist/node/http/serverResponse.d.ts.map +1 -0
  118. package/dist/node/http/serverResponse.js +96 -0
  119. package/dist/node/http/serverResponse.js.map +1 -0
  120. package/dist/node/http/upgradeSocket.d.ts +34 -0
  121. package/dist/node/http/upgradeSocket.d.ts.map +1 -0
  122. package/dist/node/http/upgradeSocket.js +73 -0
  123. package/dist/node/http/upgradeSocket.js.map +1 -0
  124. package/dist/node/ipc.d.ts +26 -0
  125. package/dist/node/ipc.d.ts.map +1 -0
  126. package/dist/node/ipc.js +76 -0
  127. package/dist/node/ipc.js.map +1 -0
  128. package/dist/node/loader.d.ts +2 -0
  129. package/dist/node/loader.d.ts.map +1 -1
  130. package/dist/node/loader.js +79 -14
  131. package/dist/node/loader.js.map +1 -1
  132. package/dist/node/misc.d.ts.map +1 -1
  133. package/dist/node/misc.js +20 -5
  134. package/dist/node/misc.js.map +1 -1
  135. package/dist/node/process.d.ts +2 -5
  136. package/dist/node/process.d.ts.map +1 -1
  137. package/dist/node/process.js +16 -11
  138. package/dist/node/process.js.map +1 -1
  139. package/dist/node/processExit.d.ts +13 -0
  140. package/dist/node/processExit.d.ts.map +1 -0
  141. package/dist/node/processExit.js +25 -0
  142. package/dist/node/processExit.js.map +1 -0
  143. package/dist/node/program.d.ts.map +1 -1
  144. package/dist/node/program.js +6 -5
  145. package/dist/node/program.js.map +1 -1
  146. package/dist/node/runtime.d.ts +6 -1
  147. package/dist/node/runtime.d.ts.map +1 -1
  148. package/dist/node/runtime.js +25 -17
  149. package/dist/node/runtime.js.map +1 -1
  150. package/dist/node/stream/readable.d.ts +2 -1
  151. package/dist/node/stream/readable.d.ts.map +1 -1
  152. package/dist/node/stream/readable.js +2 -1
  153. package/dist/node/stream/readable.js.map +1 -1
  154. package/dist/node/urlqs.d.ts +1 -1
  155. package/dist/node/urlqs.d.ts.map +1 -1
  156. package/dist/node/urlqs.js +11 -2
  157. package/dist/node/urlqs.js.map +1 -1
  158. package/dist/node/workerThreads.d.ts +31 -0
  159. package/dist/node/workerThreads.d.ts.map +1 -0
  160. package/dist/node/workerThreads.js +165 -0
  161. package/dist/node/workerThreads.js.map +1 -0
  162. package/dist/node/zlib.d.ts.map +1 -1
  163. package/dist/node/zlib.js +23 -2
  164. package/dist/node/zlib.js.map +1 -1
  165. package/dist/previewBridge.d.ts +42 -0
  166. package/dist/previewBridge.d.ts.map +1 -0
  167. package/dist/previewBridge.js +192 -0
  168. package/dist/previewBridge.js.map +1 -0
  169. package/dist/shell/ast.d.ts +101 -0
  170. package/dist/shell/ast.d.ts.map +1 -0
  171. package/dist/shell/ast.js +7 -0
  172. package/dist/shell/ast.js.map +1 -0
  173. package/dist/shell/builtins.d.ts +14 -0
  174. package/dist/shell/builtins.d.ts.map +1 -1
  175. package/dist/shell/builtins.js +87 -7
  176. package/dist/shell/builtins.js.map +1 -1
  177. package/dist/shell/compound.d.ts +30 -0
  178. package/dist/shell/compound.d.ts.map +1 -0
  179. package/dist/shell/compound.js +73 -0
  180. package/dist/shell/compound.js.map +1 -0
  181. package/dist/shell/context.d.ts.map +1 -1
  182. package/dist/shell/context.js +2 -2
  183. package/dist/shell/context.js.map +1 -1
  184. package/dist/shell/devHandoff.d.ts +10 -4
  185. package/dist/shell/devHandoff.d.ts.map +1 -1
  186. package/dist/shell/devHandoff.js +7 -5
  187. package/dist/shell/devHandoff.js.map +1 -1
  188. package/dist/shell/exec.d.ts +27 -6
  189. package/dist/shell/exec.d.ts.map +1 -1
  190. package/dist/shell/exec.js +133 -46
  191. package/dist/shell/exec.js.map +1 -1
  192. package/dist/shell/expand.d.ts +5 -1
  193. package/dist/shell/expand.d.ts.map +1 -1
  194. package/dist/shell/expand.js +7 -5
  195. package/dist/shell/expand.js.map +1 -1
  196. package/dist/shell/lineReader.d.ts +9 -0
  197. package/dist/shell/lineReader.d.ts.map +1 -0
  198. package/dist/shell/lineReader.js +42 -0
  199. package/dist/shell/lineReader.js.map +1 -0
  200. package/dist/shell/npm.js +2 -2
  201. package/dist/shell/npm.js.map +1 -1
  202. package/dist/shell/packageManagers.d.ts +20 -0
  203. package/dist/shell/packageManagers.d.ts.map +1 -0
  204. package/dist/shell/packageManagers.js +74 -0
  205. package/dist/shell/packageManagers.js.map +1 -0
  206. package/dist/shell/parse.d.ts +16 -66
  207. package/dist/shell/parse.d.ts.map +1 -1
  208. package/dist/shell/parse.js +244 -243
  209. package/dist/shell/parse.js.map +1 -1
  210. package/dist/shell/program.d.ts.map +1 -1
  211. package/dist/shell/program.js +7 -6
  212. package/dist/shell/program.js.map +1 -1
  213. package/dist/shell/testCommand.d.ts +9 -0
  214. package/dist/shell/testCommand.d.ts.map +1 -0
  215. package/dist/shell/testCommand.js +105 -0
  216. package/dist/shell/testCommand.js.map +1 -0
  217. package/dist/shell/tokenize.d.ts +25 -0
  218. package/dist/shell/tokenize.d.ts.map +1 -0
  219. package/dist/shell/tokenize.js +279 -0
  220. package/dist/shell/tokenize.js.map +1 -0
  221. package/dist/styleModules.d.ts +2 -5
  222. package/dist/styleModules.d.ts.map +1 -1
  223. package/dist/styleModules.js +23 -14
  224. package/dist/styleModules.js.map +1 -1
  225. package/dist/styles/compile.d.ts +18 -0
  226. package/dist/styles/compile.d.ts.map +1 -0
  227. package/dist/styles/compile.js +34 -0
  228. package/dist/styles/compile.js.map +1 -0
  229. package/dist/styles/compilers.d.ts +75 -0
  230. package/dist/styles/compilers.d.ts.map +1 -0
  231. package/dist/styles/compilers.js +77 -0
  232. package/dist/styles/compilers.js.map +1 -0
  233. package/dist/styles/cssModules.d.ts +40 -0
  234. package/dist/styles/cssModules.d.ts.map +1 -0
  235. package/dist/styles/cssModules.js +239 -0
  236. package/dist/styles/cssModules.js.map +1 -0
  237. package/dist/styles/imports.d.ts +37 -0
  238. package/dist/styles/imports.d.ts.map +1 -0
  239. package/dist/styles/imports.js +88 -0
  240. package/dist/styles/imports.js.map +1 -0
  241. package/dist/styles/languages.d.ts +13 -0
  242. package/dist/styles/languages.d.ts.map +1 -0
  243. package/dist/styles/languages.js +20 -0
  244. package/dist/styles/languages.js.map +1 -0
  245. package/dist/styles/packageStyles.d.ts +19 -0
  246. package/dist/styles/packageStyles.d.ts.map +1 -0
  247. package/dist/styles/packageStyles.js +32 -0
  248. package/dist/styles/packageStyles.js.map +1 -0
  249. package/dist/svelteCompiler.d.ts.map +1 -1
  250. package/dist/svelteCompiler.js +19 -2
  251. package/dist/svelteCompiler.js.map +1 -1
  252. package/dist/system/commands.d.ts +2 -0
  253. package/dist/system/commands.d.ts.map +1 -1
  254. package/dist/system/commands.js +18 -0
  255. package/dist/system/commands.js.map +1 -1
  256. package/dist/system/cookieJar.d.ts +59 -0
  257. package/dist/system/cookieJar.d.ts.map +1 -0
  258. package/dist/system/cookieJar.js +187 -0
  259. package/dist/system/cookieJar.js.map +1 -0
  260. package/dist/system/httpStream.d.ts +40 -0
  261. package/dist/system/httpStream.d.ts.map +1 -0
  262. package/dist/system/httpStream.js +156 -0
  263. package/dist/system/httpStream.js.map +1 -0
  264. package/dist/system/index.d.ts +11 -1
  265. package/dist/system/index.d.ts.map +1 -1
  266. package/dist/system/index.js +5 -0
  267. package/dist/system/index.js.map +1 -1
  268. package/dist/system/ipc.d.ts +33 -0
  269. package/dist/system/ipc.d.ts.map +1 -0
  270. package/dist/system/ipc.js +65 -0
  271. package/dist/system/ipc.js.map +1 -0
  272. package/dist/system/kernel.d.ts +10 -2
  273. package/dist/system/kernel.d.ts.map +1 -1
  274. package/dist/system/kernel.js +18 -6
  275. package/dist/system/kernel.js.map +1 -1
  276. package/dist/system/ports.d.ts +9 -4
  277. package/dist/system/ports.d.ts.map +1 -1
  278. package/dist/system/ports.js +21 -2
  279. package/dist/system/ports.js.map +1 -1
  280. package/dist/system/process.d.ts +3 -0
  281. package/dist/system/process.d.ts.map +1 -1
  282. package/dist/system/process.js +50 -26
  283. package/dist/system/process.js.map +1 -1
  284. package/dist/system/programs.d.ts +1 -1
  285. package/dist/system/programs.d.ts.map +1 -1
  286. package/dist/system/programs.js +2 -0
  287. package/dist/system/programs.js.map +1 -1
  288. package/dist/system/terminal.d.ts +10 -4
  289. package/dist/system/terminal.d.ts.map +1 -1
  290. package/dist/system/terminal.js +21 -13
  291. package/dist/system/terminal.js.map +1 -1
  292. package/dist/system/types.d.ts +65 -13
  293. package/dist/system/types.d.ts.map +1 -1
  294. package/dist/system/webSocketClient.d.ts +37 -0
  295. package/dist/system/webSocketClient.d.ts.map +1 -0
  296. package/dist/system/webSocketClient.js +152 -0
  297. package/dist/system/webSocketClient.js.map +1 -0
  298. package/dist/system/webSocketFrames.d.ts +39 -0
  299. package/dist/system/webSocketFrames.d.ts.map +1 -0
  300. package/dist/system/webSocketFrames.js +117 -0
  301. package/dist/system/webSocketFrames.js.map +1 -0
  302. package/dist/vueCompiler.d.ts.map +1 -1
  303. package/dist/vueCompiler.js +11 -8
  304. package/dist/vueCompiler.js.map +1 -1
  305. package/package.json +4 -1
  306. package/src/archive.ts +8 -4
  307. package/src/build.ts +13 -1
  308. package/src/buildHost.ts +23 -10
  309. package/src/compileComponent.ts +4 -1
  310. package/src/compileScript.ts +30 -11
  311. package/src/components.ts +5 -0
  312. package/src/detectProject.ts +13 -6
  313. package/src/devServer.ts +148 -23
  314. package/src/devStyles.ts +70 -0
  315. package/src/hot/client.ts +70 -0
  316. package/src/hot/moduleGraph.ts +90 -0
  317. package/src/hot/planUpdate.ts +66 -0
  318. package/src/hot/reactRefresh.ts +93 -0
  319. package/src/html.ts +17 -21
  320. package/src/index.ts +20 -1
  321. package/src/installer/tree.ts +22 -4
  322. package/src/installer/wasmBuilds.ts +45 -0
  323. package/src/node/builtins.ts +21 -12
  324. package/src/node/childProcess.ts +73 -20
  325. package/src/node/crypto.ts +5 -4
  326. package/src/node/esm.ts +26 -2
  327. package/src/node/fs/index.ts +26 -103
  328. package/src/node/fs/stdinFd.ts +44 -0
  329. package/src/node/fs/streams.ts +177 -0
  330. package/src/node/fs/sync.ts +15 -0
  331. package/src/node/globalObject.ts +82 -0
  332. package/src/node/http/client.ts +69 -6
  333. package/src/node/http/index.ts +6 -4
  334. package/src/node/http/messages.ts +150 -0
  335. package/src/node/http/server.ts +44 -206
  336. package/src/node/http/serverResponse.ts +105 -0
  337. package/src/node/http/upgradeSocket.ts +79 -0
  338. package/src/node/ipc.ts +91 -0
  339. package/src/node/loader.ts +78 -14
  340. package/src/node/misc.ts +19 -5
  341. package/src/node/process.ts +15 -8
  342. package/src/node/processExit.ts +21 -0
  343. package/src/node/program.ts +12 -9
  344. package/src/node/runtime.ts +29 -17
  345. package/src/node/stream/readable.ts +2 -1
  346. package/src/node/urlqs.ts +10 -2
  347. package/src/node/workerThreads.ts +198 -0
  348. package/src/node/zlib.ts +24 -2
  349. package/src/previewBridge.ts +194 -0
  350. package/src/shell/ast.ts +85 -0
  351. package/src/shell/builtins.ts +97 -7
  352. package/src/shell/compound.ts +89 -0
  353. package/src/shell/context.ts +2 -2
  354. package/src/shell/devHandoff.ts +16 -9
  355. package/src/shell/exec.ts +134 -45
  356. package/src/shell/expand.ts +8 -6
  357. package/src/shell/lineReader.ts +46 -0
  358. package/src/shell/npm.ts +2 -2
  359. package/src/shell/packageManagers.ts +75 -0
  360. package/src/shell/parse.ts +233 -236
  361. package/src/shell/program.ts +7 -6
  362. package/src/shell/testCommand.ts +105 -0
  363. package/src/shell/tokenize.ts +257 -0
  364. package/src/styleModules.ts +30 -14
  365. package/src/styles/compile.ts +43 -0
  366. package/src/styles/compilers.ts +143 -0
  367. package/src/styles/cssModules.ts +254 -0
  368. package/src/styles/imports.ts +125 -0
  369. package/src/styles/languages.ts +29 -0
  370. package/src/styles/packageStyles.ts +35 -0
  371. package/src/svelteCompiler.ts +20 -3
  372. package/src/system/commands.ts +17 -0
  373. package/src/system/cookieJar.ts +187 -0
  374. package/src/system/httpStream.ts +168 -0
  375. package/src/system/index.ts +28 -1
  376. package/src/system/ipc.ts +89 -0
  377. package/src/system/kernel.ts +22 -7
  378. package/src/system/ports.ts +23 -4
  379. package/src/system/process.ts +57 -30
  380. package/src/system/programs.ts +3 -1
  381. package/src/system/terminal.ts +34 -12
  382. package/src/system/types.ts +71 -13
  383. package/src/system/webSocketClient.ts +177 -0
  384. package/src/system/webSocketFrames.ts +118 -0
  385. package/src/vueCompiler.ts +11 -8
@@ -8,6 +8,15 @@ import type { CommandContext, Command } from './context.js';
8
8
  import { resolvePath } from './context.js';
9
9
  import { cat, cp, ls, mkdir, mv, pwd, rm, touch } from './fileCommands.js';
10
10
  import { basename, clear, dirname, echo, env, falseCommand, grep, head, printf, sleep, tail, trueCommand, wc } from './textCommands.js';
11
+ import { bracket, test } from './testCommand.js';
12
+ import { readLine } from './lineReader.js';
13
+ import type { Flow } from './compound.js';
14
+
15
+ /** A command started with `&`. */
16
+ export interface BackgroundJob {
17
+ id: number;
18
+ done: Promise<number>;
19
+ }
11
20
 
12
21
  /** The slice of the shell a builtin may change. */
13
22
  export interface ShellState {
@@ -17,6 +26,14 @@ export interface ShellState {
17
26
  lastStatus: number;
18
27
  /** Set by `exit`: the shell stops after the current command. */
19
28
  exitRequested?: number;
29
+ /** Set by `break`, `continue` and `return`; the loop or function it targets clears it. */
30
+ flow?: Flow;
31
+ /** `$1…`, `$@`; a function call swaps them for its arguments. */
32
+ positional: string[];
33
+ readonly functions: ReadonlyMap<string, unknown>;
34
+ readonly jobs: ReadonlyMap<number, BackgroundJob>;
35
+ /** One frame per running function (for `local`). */
36
+ readonly localFrames: Array<Map<string, string | undefined>>;
20
37
  /** Run a script in this shell (for `source`). */
21
38
  run(source: string): Promise<number>;
22
39
  }
@@ -25,21 +42,25 @@ export type Builtin = (ctx: CommandContext, shell: ShellState) => Promise<number
25
42
 
26
43
  /** Coreutils: plain commands, also spawnable as standalone programs. */
27
44
  export const COREUTILS: Record<string, Command> = {
28
- ls, cat, mkdir, rm, cp, mv, touch, pwd, echo, printf, head, tail, grep, wc, env, clear, sleep, basename, dirname,
45
+ ls, cat, mkdir, rm, cp, mv, touch, pwd, echo, printf, head, tail, grep, wc, env, clear, sleep, basename, dirname, test,
46
+ '[': bracket,
29
47
  true: trueCommand,
30
48
  false: falseCommand,
31
49
  };
32
50
 
33
51
  /** Programs the runtime provides besides coreutils (reported by `which`/`type`). */
34
- export const SYSTEM_PROGRAMS = ['node', 'npm', 'npx', 'bfsh', 'sh', 'bash'];
52
+ export const SYSTEM_PROGRAMS = ['node', 'npm', 'npx', 'pnpm', 'yarn', 'bfsh', 'sh', 'bash'];
35
53
 
36
54
  const HELP = `bfsh — BuilderForce WebContainers shell
37
55
 
38
- Builtins: cd, pwd, export, unset, exit, source, history, type, which, help
39
- Files: ls [-la], cat, mkdir [-p], rm [-rf], cp [-r], mv, touch
56
+ Builtins: cd, pwd, export, unset, exit, source, history, type, which, help,
57
+ read, local, shift, return, break, continue, jobs, wait
58
+ Files: ls [-la], cat, mkdir [-p], rm [-rf], cp [-r], mv, touch, test / [ … ]
40
59
  Text: echo, printf, head, tail, grep, wc, env, clear, sleep, basename, dirname
41
- Node: node <file>, npm install|ci|run|start|test, npx <bin>
60
+ Node: node <file>, npm install|ci|run|start|test, npx <bin>, pnpm, yarn
42
61
  Syntax: 'quotes' "\$VARS" a && b || c; a | b > out.txt >> log 2>&1 2> err; FOO=bar cmd; $(cmd); *.js
62
+ if …; then …; elif …; else …; fi while|until …; do …; done for x in …; do …; done
63
+ case $x in a|b) …;; *) …;; esac name() { …; } { …; } ( … ) cat <<EOF … EOF
43
64
 
44
65
  `;
45
66
 
@@ -116,10 +137,11 @@ export const BUILTINS: Record<string, Builtin> = {
116
137
  }
117
138
  return status;
118
139
  },
119
- async type(ctx) {
140
+ async type(ctx, shell) {
120
141
  let status = 0;
121
142
  for (const name of ctx.args) {
122
- if (name in BUILTINS) ctx.io.stdout(`${name} is a shell builtin\n`);
143
+ if (shell.functions.has(name)) ctx.io.stdout(`${name} is a function\n`);
144
+ else if (name in BUILTINS) ctx.io.stdout(`${name} is a shell builtin\n`);
123
145
  else if (name in COREUTILS || SYSTEM_PROGRAMS.includes(name)) ctx.io.stdout(`${name} is /usr/local/bin/${name}\n`);
124
146
  else {
125
147
  const file = findExecutable(ctx.fs, name, ctx.cwd, ctx.env);
@@ -135,7 +157,75 @@ export const BUILTINS: Record<string, Builtin> = {
135
157
  async set() {
136
158
  return 0; // options (-e, -x) are accepted and ignored
137
159
  },
160
+ async break(ctx, shell) {
161
+ return loopControl(ctx, shell, 'break');
162
+ },
163
+ async continue(ctx, shell) {
164
+ return loopControl(ctx, shell, 'continue');
165
+ },
166
+ async return(ctx, shell) {
167
+ if (!shell.localFrames.length) {
168
+ ctx.io.stderr('return: can only `return\' from a function or sourced script\n');
169
+ return 1;
170
+ }
171
+ const status = ctx.args[0] === undefined ? shell.lastStatus : Number(ctx.args[0]) & 255;
172
+ shell.flow = { kind: 'return', status };
173
+ return status;
174
+ },
175
+ async local(ctx, shell) {
176
+ const frame = shell.localFrames[shell.localFrames.length - 1];
177
+ if (!frame) {
178
+ ctx.io.stderr('local: can only be used in a function\n');
179
+ return 1;
180
+ }
181
+ for (const arg of ctx.args) {
182
+ const eq = arg.indexOf('=');
183
+ const name = eq > 0 ? arg.slice(0, eq) : arg;
184
+ if (!frame.has(name)) frame.set(name, shell.env[name]);
185
+ shell.env[name] = eq > 0 ? arg.slice(eq + 1) : '';
186
+ }
187
+ return 0;
188
+ },
189
+ async shift(ctx, shell) {
190
+ const count = ctx.args[0] === undefined ? 1 : Number(ctx.args[0]);
191
+ if (!Number.isInteger(count) || count < 0 || count > shell.positional.length) return 1;
192
+ shell.positional = shell.positional.slice(count);
193
+ return 0;
194
+ },
195
+ async read(ctx, shell) {
196
+ const raw = ctx.args.includes('-r');
197
+ const names = ctx.args.filter((a) => !a.startsWith('-'));
198
+ let line = await readLine(ctx.io.stdin, ctx.signal);
199
+ if (line === null) return 1;
200
+ if (!raw) line = line.replace(/\\(.)/g, '$1');
201
+ const targets = names.length ? names : ['REPLY'];
202
+ const fields = names.length ? line.trim().split(/\s+/) : [line];
203
+ targets.forEach((name, i) => {
204
+ shell.env[name] = i === targets.length - 1 ? fields.slice(i).join(' ') : fields[i] ?? '';
205
+ });
206
+ return 0;
207
+ },
208
+ async jobs(ctx, shell) {
209
+ for (const job of shell.jobs.values()) ctx.io.stdout(`[${job.id}] Running\n`);
210
+ return 0;
211
+ },
212
+ async wait(ctx, shell) {
213
+ const ids = ctx.args.map((a) => Number(a.replace(/^%/, '')));
214
+ const jobs = ids.length ? ids.map((id) => shell.jobs.get(id)).filter((j): j is BackgroundJob => !!j) : [...shell.jobs.values()];
215
+ const statuses = await Promise.all(jobs.map((job) => job.done));
216
+ return statuses.length ? statuses[statuses.length - 1]! : 0;
217
+ },
138
218
  };
219
+
220
+ function loopControl(ctx: CommandContext, shell: ShellState, kind: 'break' | 'continue'): number {
221
+ const levels = ctx.args[0] === undefined ? 1 : Number(ctx.args[0]);
222
+ if (!Number.isInteger(levels) || levels < 1) {
223
+ ctx.io.stderr(`${kind}: ${ctx.args[0]}: loop count out of range\n`);
224
+ return 1;
225
+ }
226
+ shell.flow = { kind, levels };
227
+ return 0;
228
+ }
139
229
  BUILTINS['.'] = BUILTINS.source!;
140
230
  BUILTINS[':'] = async () => 0;
141
231
 
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Running compound commands (`if`, `while`/`until`, `for`, `case`, `{ }`,
3
+ * `( )`) against a narrow {@link ScriptRunner}, so the executor stays a
4
+ * dispatcher. Loop control (`break`, `continue`) and `return` travel as a
5
+ * {@link Flow} the runner holds: lists stop running while one is set, and the
6
+ * construct it targets clears it.
7
+ */
8
+ import type { CompoundCommand, Script, Word } from './ast.js';
9
+ import type { JobInput, ShellIO } from './exec.js';
10
+ import { patternToRegExp } from './expand.js';
11
+
12
+ export type Flow = { kind: 'break' | 'continue'; levels: number } | { kind: 'return'; status: number };
13
+
14
+ export interface ScriptRunner {
15
+ flow?: Flow;
16
+ readonly positional: readonly string[];
17
+ runScript(script: Script, io: ShellIO, input: JobInput, signal: AbortSignal): Promise<number>;
18
+ /** Words with splitting and globbing, as command arguments. */
19
+ expandWords(words: Word[], io: ShellIO, signal: AbortSignal): Promise<string[]>;
20
+ /** One word as a single string: no splitting, no globbing. */
21
+ expandText(word: Word, io: ShellIO, signal: AbortSignal): Promise<string>;
22
+ setVar(name: string, value: string): void;
23
+ /** A copy of this shell for `( … )`: changes inside do not leak out. */
24
+ subshell(): ScriptRunner;
25
+ }
26
+
27
+ /** After one pass of a loop body: whether the loop goes on. Consumes the flow aimed at this loop. */
28
+ function continueLoop(runner: ScriptRunner): boolean {
29
+ const flow = runner.flow;
30
+ if (!flow) return true;
31
+ if (flow.kind === 'return') return false;
32
+ if (flow.levels > 1) {
33
+ runner.flow = { kind: flow.kind, levels: flow.levels - 1 };
34
+ return false;
35
+ }
36
+ runner.flow = undefined;
37
+ return flow.kind === 'continue';
38
+ }
39
+
40
+ export async function runCompound(node: CompoundCommand, runner: ScriptRunner, io: ShellIO, input: JobInput, signal: AbortSignal): Promise<number> {
41
+ switch (node.type) {
42
+ case 'group':
43
+ return runner.runScript(node.body, io, input, signal);
44
+ case 'subshell':
45
+ return runner.subshell().runScript(node.body, io, input, signal);
46
+ case 'if': {
47
+ for (const clause of node.clauses) {
48
+ const condition = await runner.runScript(clause.condition, io, input, signal);
49
+ if (runner.flow) return condition;
50
+ if (condition === 0) return runner.runScript(clause.body, io, input, signal);
51
+ }
52
+ return node.otherwise ? runner.runScript(node.otherwise, io, input, signal) : 0;
53
+ }
54
+ case 'while':
55
+ case 'until': {
56
+ let status = 0;
57
+ while (!signal.aborted) {
58
+ const condition = await runner.runScript(node.condition, io, input, signal);
59
+ if (runner.flow && !continueLoop(runner)) break;
60
+ if ((condition === 0) !== (node.type === 'while')) break;
61
+ status = await runner.runScript(node.body, io, input, signal);
62
+ if (!continueLoop(runner)) break;
63
+ }
64
+ return status;
65
+ }
66
+ case 'for': {
67
+ const items = node.items ? await runner.expandWords(node.items, io, signal) : [...runner.positional];
68
+ let status = 0;
69
+ for (const item of items) {
70
+ if (signal.aborted) break;
71
+ runner.setVar(node.name, item);
72
+ status = await runner.runScript(node.body, io, input, signal);
73
+ if (!continueLoop(runner)) break;
74
+ }
75
+ return status;
76
+ }
77
+ case 'case': {
78
+ const subject = await runner.expandText(node.subject, io, signal);
79
+ for (const arm of node.arms) {
80
+ for (const pattern of arm.patterns) {
81
+ if (patternToRegExp(await runner.expandText(pattern, io, signal), { slash: true }).test(subject)) {
82
+ return runner.runScript(arm.body, io, input, signal);
83
+ }
84
+ }
85
+ }
86
+ return 0;
87
+ }
88
+ }
89
+ }
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import type { VirtualFileSystem } from '../vfs.js';
7
7
  import type { Program, System } from '../system/types.js';
8
- import { InputQueue } from '../system/terminal.js';
8
+ import { InputQueue, textChunks } from '../system/terminal.js';
9
9
  import { join, normalizePath } from '../paths.js';
10
10
 
11
11
  export interface CommandIO {
@@ -70,7 +70,7 @@ export function parseFlags(args: string[], withValue: string[] = []): { flags: S
70
70
  export function asProgram(command: Command, name: string): Program {
71
71
  return async (ctx) => {
72
72
  const stdin = new InputQueue();
73
- const stop = ctx.io.onStdin((chunk) => stdin.push(chunk));
73
+ const stop = ctx.io.onStdin(textChunks((chunk) => stdin.push(chunk)));
74
74
  try {
75
75
  return await command({
76
76
  args: ctx.args,
@@ -1,12 +1,17 @@
1
1
  /**
2
2
  * Dev-server handoff. `vite`, `vite dev`, `react-scripts start` (what `npm run
3
- * dev` / `npm start` usually run) cannot run here as-is — Vite itself needs
4
- * esbuild's native binary — but the runtime already IS a Vite-style dev server:
5
- * the in-browser DevServer serving the preview. So these commands announce that
6
- * preview as their server (a listening announcement) and stay "running" until Ctrl-C,
3
+ * dev` / `npm start` usually run) need not boot a bundler at all: the runtime
4
+ * already IS a Vite-style dev server, the in-browser DevServer serving the
5
+ * preview, and it starts instantly. So these commands announce that preview as
6
+ * their server (a listening announcement) and stay "running" until Ctrl-C,
7
7
  * which is exactly what a host waiting on `npm run dev` expects.
8
+ *
9
+ * Not for a framework that runs its own server on top of Vite (SvelteKit, Nuxt…,
10
+ * `ownServerReason`): those run the real, installed Vite, on esbuild's and
11
+ * Rollup's wasm builds (installer/wasmBuilds.ts). Nor when no preview is attached.
8
12
  */
9
13
  import type { CommandContext } from './context.js';
14
+ import { ownServerReason } from '../detectProject.js';
10
15
 
11
16
  interface Handoff {
12
17
  tool: string;
@@ -22,6 +27,12 @@ export function matchDevServer(argv: string[]): Handoff | undefined {
22
27
  return undefined;
23
28
  }
24
29
 
30
+ /** The handoff for this command line, when the attached preview can serve the project instead. */
31
+ export function devServerHandoff(ctx: CommandContext, argv: string[]): Handoff | undefined {
32
+ const handoff = matchDevServer(argv);
33
+ return handoff && ctx.system.previewUrl && !ownServerReason(ctx.fs) ? handoff : undefined;
34
+ }
35
+
25
36
  function portOf(argv: string[], fallback: number, env: Record<string, string>): number {
26
37
  const at = argv.findIndex((a) => a === '--port' || a.startsWith('--port='));
27
38
  const value = at < 0 ? env.PORT : argv[at]!.includes('=') ? argv[at]!.split('=')[1] : argv[at + 1];
@@ -30,11 +41,7 @@ function portOf(argv: string[], fallback: number, env: Record<string, string>):
30
41
  }
31
42
 
32
43
  export async function runDevServerHandoff(ctx: CommandContext, argv: string[], handoff: Handoff): Promise<number> {
33
- const url = ctx.system.previewUrl;
34
- if (!url) {
35
- ctx.io.stderr(`${handoff.tool}: no in-browser preview is attached to this runtime, so there is nothing to serve.\n`);
36
- return 1;
37
- }
44
+ const url = ctx.system.previewUrl!; // devServerHandoff only matches with a preview attached
38
45
  const port = portOf(argv, handoff.defaultPort, ctx.env);
39
46
  const banner = handoff.tool === 'vite'
40
47
  ? `\n VITE (BuilderForce in-browser dev server) ready\n\n ➜ Local: ${url}\n\n`
package/src/shell/exec.ts CHANGED
@@ -1,18 +1,21 @@
1
1
  /**
2
2
  * The executor: runs a parsed script. Lists honour `&&`/`||`/`;`/`&`; pipeline
3
- * stages run concurrently, joined by in-memory pipes; redirects swap a stage's
4
- * stdin/stdout/stderr for files. Dispatch order per command: shell builtins,
3
+ * stages run concurrently, joined by in-memory pipes; redirects (here-documents
4
+ * included) swap a stage's stdin/stdout/stderr. Compound commands run through
5
+ * compound.ts. Dispatch order per simple command: shell functions, builtins,
5
6
  * extra in-process commands (npm, npx), the dev-server handoff, coreutils, and
6
7
  * finally `system.spawn` (node, scripts on PATH, `.bin` entries) — which in the
7
8
  * browser is a separate Web Worker.
8
9
  */
9
10
  import type { System } from '../system/types.js';
10
- import { InputQueue } from '../system/terminal.js';
11
- import { parse, ShellSyntaxError, type Command as CommandNode, type Pipeline, type Script } from './parse.js';
11
+ import { InputQueue, textChunks } from '../system/terminal.js';
12
+ import type { Command as CommandNode, FunctionDefinition, Pipeline, Redirect, Script, SimpleCommand, Word } from './ast.js';
13
+ import { parse, ShellSyntaxError } from './parse.js';
12
14
  import { expandWord, expandWords, type ExpandContext } from './expand.js';
13
- import { BUILTINS, COREUTILS, type ShellState } from './builtins.js';
15
+ import { BUILTINS, COREUTILS, type BackgroundJob, type ShellState } from './builtins.js';
14
16
  import { resolvePath, type CommandContext } from './context.js';
15
- import { matchDevServer, runDevServerHandoff } from './devHandoff.js';
17
+ import { devServerHandoff, runDevServerHandoff } from './devHandoff.js';
18
+ import { runCompound, type Flow, type ScriptRunner } from './compound.js';
16
19
 
17
20
  export interface ShellIO {
18
21
  stdout(text: string): void;
@@ -39,31 +42,44 @@ export interface ShellOptions {
39
42
  /** The terminal size, when attached to one. */
40
43
  terminalSize?: () => { cols: number; rows: number } | undefined;
41
44
  commands?: Record<string, ShellCommand>;
45
+ /** Functions inherited from a parent shell (subshells and `$(…)`). */
46
+ functions?: Map<string, FunctionDefinition>;
42
47
  }
43
48
 
44
49
  let nextShellPid = 500;
45
50
 
46
- export class Shell implements ShellState {
51
+ export class Shell implements ShellState, ScriptRunner {
47
52
  cwd: string;
48
53
  env: Record<string, string>;
49
54
  lastStatus = 0;
50
55
  history: string[] = [];
51
56
  exitRequested?: number;
57
+ flow?: Flow;
58
+ positional: string[];
59
+ readonly functions: Map<string, FunctionDefinition>;
60
+ readonly jobs = new Map<number, BackgroundJob>();
61
+ /** One frame per running function: names declared `local`, with the value to restore. */
62
+ readonly localFrames: Array<Map<string, string | undefined>> = [];
52
63
  readonly pid = nextShellPid++;
53
64
  readonly system: System;
54
- private readonly positional: string[];
65
+ private nextJob = 1;
55
66
  private current?: { io: ShellIO; input: JobInput; signal: AbortSignal };
56
67
 
57
68
  constructor(readonly options: ShellOptions) {
58
69
  this.system = options.system;
59
70
  this.cwd = options.cwd;
60
71
  this.env = { ...options.env, PWD: options.cwd };
61
- this.positional = options.positional ?? [];
72
+ this.positional = [...(options.positional ?? [])];
73
+ this.functions = new Map(options.functions);
62
74
  }
63
75
 
64
- /** A child shell for `npm run` / subshells: same IO, its own cwd and environment. */
76
+ /** A child shell for `npm run` / subshells: same IO, its own cwd, environment and functions. */
65
77
  fork(overrides: { cwd?: string; env?: Record<string, string>; positional?: string[] }): Shell {
66
- return new Shell({ ...this.options, cwd: overrides.cwd ?? this.cwd, env: { ...this.env, ...overrides.env }, positional: overrides.positional });
78
+ return new Shell({ ...this.options, cwd: overrides.cwd ?? this.cwd, env: { ...this.env, ...overrides.env }, positional: overrides.positional ?? this.positional, functions: this.functions });
79
+ }
80
+
81
+ subshell(): Shell {
82
+ return this.fork({});
67
83
  }
68
84
 
69
85
  /** Parse and run `source`. Syntax errors print and return 2. */
@@ -80,23 +96,11 @@ export class Shell implements ShellState {
80
96
  const previous = this.current;
81
97
  this.current = { io, input, signal };
82
98
  try {
83
- for (const list of script) {
84
- if (this.exitRequested !== undefined || signal.aborted) break;
85
- const run = async () => {
86
- let status = await this.runPipeline(list.first, io, input, signal);
87
- for (const { op, pipeline } of list.rest) {
88
- if (this.exitRequested !== undefined || signal.aborted) break;
89
- if ((op === '&&') === (status === 0)) status = await this.runPipeline(pipeline, io, input, signal);
90
- }
91
- return status;
92
- };
93
- if (list.background) {
94
- void run();
95
- this.lastStatus = 0;
96
- } else this.lastStatus = await run();
97
- }
99
+ await this.runScript(script, io, input, signal);
98
100
  } finally {
99
101
  this.current = previous;
102
+ // A `break`/`continue` outside any loop (or `return` outside a function) must not stop later lines.
103
+ if (!this.localFrames.length) this.flow = undefined;
100
104
  }
101
105
  if (signal.aborted && this.lastStatus === 0) this.lastStatus = 130;
102
106
  return this.exitRequested ?? this.lastStatus;
@@ -109,6 +113,40 @@ export class Shell implements ShellState {
109
113
  return this.exec(source, job.io, job.input, job.signal);
110
114
  }
111
115
 
116
+ async runScript(script: Script, io: ShellIO, input: JobInput, signal: AbortSignal): Promise<number> {
117
+ for (const list of script) {
118
+ if (this.exitRequested !== undefined || signal.aborted || this.flow) break;
119
+ const run = async () => {
120
+ let status = await this.runPipeline(list.first, io, input, signal);
121
+ for (const { op, pipeline } of list.rest) {
122
+ if (this.exitRequested !== undefined || signal.aborted || this.flow) break;
123
+ if ((op === '&&') === (status === 0)) status = await this.runPipeline(pipeline, io, input, signal);
124
+ }
125
+ return status;
126
+ };
127
+ if (list.background) {
128
+ const id = this.nextJob++;
129
+ const done = run();
130
+ this.jobs.set(id, { id, done });
131
+ void done.finally(() => this.jobs.delete(id));
132
+ this.lastStatus = 0;
133
+ } else this.lastStatus = await run();
134
+ }
135
+ return this.lastStatus;
136
+ }
137
+
138
+ expandWords(words: Word[], io: ShellIO, signal: AbortSignal): Promise<string[]> {
139
+ return expandWords(words, this.expandContext(io, signal));
140
+ }
141
+
142
+ async expandText(word: Word, io: ShellIO, signal: AbortSignal): Promise<string> {
143
+ return (await expandWord(word, this.expandContext(io, signal), { split: false, glob: false })).join('');
144
+ }
145
+
146
+ setVar(name: string, value: string): void {
147
+ this.env[name] = value;
148
+ }
149
+
112
150
  private expandContext(io: ShellIO, signal: AbortSignal): ExpandContext {
113
151
  return {
114
152
  fs: this.system.fs,
@@ -147,6 +185,21 @@ export class Shell implements ShellState {
147
185
  }
148
186
 
149
187
  private async runCommand(node: CommandNode, io: ShellIO, input: JobInput, signal: AbortSignal, alone: boolean): Promise<number> {
188
+ if (node.type === 'function') {
189
+ this.functions.set(node.name, node);
190
+ return 0;
191
+ }
192
+ if (node.type === 'simple') return this.runSimple(node, io, input, signal, alone);
193
+ const redirected = await this.applyRedirects(node.redirects, io, input, signal);
194
+ if (typeof redirected === 'number') return redirected;
195
+ try {
196
+ return await runCompound(node, this, redirected.io, redirected.input, signal);
197
+ } finally {
198
+ redirected.flush();
199
+ }
200
+ }
201
+
202
+ private async runSimple(node: SimpleCommand, io: ShellIO, input: JobInput, signal: AbortSignal, alone: boolean): Promise<number> {
150
203
  const ectx = this.expandContext(io, signal);
151
204
  const argv = await expandWords(node.words, ectx);
152
205
  const assigned: Record<string, string> = {};
@@ -155,14 +208,27 @@ export class Shell implements ShellState {
155
208
  Object.assign(this.env, assigned);
156
209
  return 0;
157
210
  }
211
+ const redirected = await this.applyRedirects(node.redirects, io, input, signal);
212
+ if (typeof redirected === 'number') return redirected;
213
+ try {
214
+ return await this.dispatch(argv, assigned, redirected.io, redirected.input, signal, alone && redirected.io.isTerminal);
215
+ } finally {
216
+ redirected.flush();
217
+ }
218
+ }
158
219
 
159
- // Redirects.
160
- let stdout = io.stdout;
161
- let stderr = io.stderr;
220
+ /** Apply redirects; returns the new IO, or an exit status when a redirect fails. */
221
+ private async applyRedirects(redirects: Redirect[], io: ShellIO, input: JobInput, signal: AbortSignal): Promise<number | { io: ShellIO; input: JobInput; flush(): void }> {
222
+ let { stdout, stderr, isTerminal } = io;
162
223
  let stdin = input;
163
- let isTerminal = io.isTerminal;
164
224
  const flushes: Array<() => void> = [];
165
- for (const redirect of node.redirects) {
225
+ const fromText = (text: string): JobInput => {
226
+ const queue = new InputQueue();
227
+ queue.push(text);
228
+ queue.push(null);
229
+ return { queue };
230
+ };
231
+ for (const redirect of redirects) {
166
232
  if (redirect.op === '2>&1') {
167
233
  stderr = stdout;
168
234
  continue;
@@ -171,7 +237,12 @@ export class Shell implements ShellState {
171
237
  stdout = stderr;
172
238
  continue;
173
239
  }
174
- const target = (await expandWord(redirect.target!, ectx)).join(' ');
240
+ if (redirect.heredoc) {
241
+ const text = await this.expandText(redirect.heredoc.body, io, signal);
242
+ stdin = fromText(text);
243
+ continue;
244
+ }
245
+ const target = (await expandWord(redirect.target!, this.expandContext(io, signal))).join(' ');
175
246
  const path = resolvePath(this, target);
176
247
  if (redirect.op === '<') {
177
248
  const text = this.system.fs.readText(path);
@@ -179,10 +250,7 @@ export class Shell implements ShellState {
179
250
  io.stderr(`bfsh: ${target}: No such file or directory\n`);
180
251
  return 1;
181
252
  }
182
- const queue = new InputQueue();
183
- queue.push(text);
184
- queue.push(null);
185
- stdin = { queue };
253
+ stdin = fromText(text);
186
254
  continue;
187
255
  }
188
256
  if (this.system.fs.isDirectory(path)) {
@@ -201,16 +269,13 @@ export class Shell implements ShellState {
201
269
  isTerminal = false;
202
270
  }
203
271
  }
204
-
205
- try {
206
- return await this.dispatch(argv, assigned, { stdout, stderr, isTerminal }, stdin, signal, alone && isTerminal);
207
- } finally {
208
- for (const flush of flushes) flush();
209
- }
272
+ return { io: { stdout, stderr, isTerminal }, input: stdin, flush: () => flushes.forEach((flush) => flush()) };
210
273
  }
211
274
 
212
275
  private async dispatch(argv: string[], assigned: Record<string, string>, io: ShellIO, input: JobInput, signal: AbortSignal, attachTerminal: boolean): Promise<number> {
213
276
  const [name, ...args] = argv as [string, ...string[]];
277
+ const fn = this.functions.get(name);
278
+ if (fn) return this.callFunction(fn, args, io, input, signal);
214
279
  const env = { ...this.env, ...assigned };
215
280
  const ctx: CommandContext = {
216
281
  args,
@@ -226,13 +291,36 @@ export class Shell implements ShellState {
226
291
  if (builtin) return builtin(ctx, this);
227
292
  const command = this.options.commands?.[name];
228
293
  if (command) return command(ctx, this, input);
229
- const handoff = matchDevServer(argv);
294
+ const handoff = devServerHandoff(ctx, argv);
230
295
  if (handoff) return runDevServerHandoff(ctx, argv, handoff);
231
296
  const coreutil = COREUTILS[name];
232
297
  if (coreutil) return coreutil(ctx);
233
298
  return this.spawnExternal(name, args, env, io, input, signal, attachTerminal);
234
299
  }
235
300
 
301
+ /** A shell function: its own positional parameters and `local` frame; `return` ends it. */
302
+ private async callFunction(fn: FunctionDefinition, args: string[], io: ShellIO, input: JobInput, signal: AbortSignal): Promise<number> {
303
+ const savedPositional = this.positional;
304
+ this.positional = args;
305
+ const frame = new Map<string, string | undefined>();
306
+ this.localFrames.push(frame);
307
+ try {
308
+ let status = await runCompound(fn.body, this, io, input, signal);
309
+ if (this.flow?.kind === 'return') {
310
+ status = this.flow.status;
311
+ this.flow = undefined;
312
+ }
313
+ return status;
314
+ } finally {
315
+ this.localFrames.pop();
316
+ for (const [name, value] of frame) {
317
+ if (value === undefined) delete this.env[name];
318
+ else this.env[name] = value;
319
+ }
320
+ this.positional = savedPositional;
321
+ }
322
+ }
323
+
236
324
  private async spawnExternal(name: string, args: string[], env: Record<string, string>, io: ShellIO, input: JobInput, signal: AbortSignal, attachTerminal: boolean): Promise<number> {
237
325
  const size = attachTerminal ? this.options.terminalSize?.() : undefined;
238
326
  let child;
@@ -243,8 +331,9 @@ export class Shell implements ShellState {
243
331
  io.stderr(`bfsh: command not found: ${name}\n`);
244
332
  return 127;
245
333
  }
246
- child.onStdout(io.stdout);
247
- child.onStderr(io.stderr);
334
+ // The shell's own IO is text; a child's bytes are decoded as they enter it.
335
+ child.onStdout(textChunks((text) => text !== null && io.stdout(text)));
336
+ child.onStderr(textChunks((text) => text !== null && io.stderr(text)));
248
337
  let stop: (() => void) | undefined;
249
338
  if (size && input.setRawSink) input.setRawSink((data) => child.write(data));
250
339
  else stop = input.queue.subscribe((chunk) => (chunk === null ? child.closeStdin() : child.write(chunk)));
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import type { VirtualFileSystem } from '../vfs.js';
8
8
  import { join, normalizePath } from '../paths.js';
9
- import type { Segment, Word } from './parse.js';
9
+ import type { Segment, Word } from './ast.js';
10
10
 
11
11
  export interface ExpandContext {
12
12
  fs: VirtualFileSystem;
@@ -49,12 +49,14 @@ async function paramValue(seg: Extract<Segment, { kind: 'var' }>, ctx: ExpandCon
49
49
 
50
50
  const GLOB_CHARS = /[*?[]/;
51
51
 
52
- function globToRegExp(pattern: string): RegExp {
52
+ /** A glob as a regular expression. `slash: true` lets `*`/`?` cross `/` (a `case` pattern, not a path). */
53
+ export function patternToRegExp(pattern: string, options: { slash?: boolean } = {}): RegExp {
54
+ const any = options.slash ? '.' : '[^/]';
53
55
  let source = '';
54
56
  for (let i = 0; i < pattern.length; i++) {
55
57
  const c = pattern[i]!;
56
- if (c === '*') source += '[^/]*';
57
- else if (c === '?') source += '[^/]';
58
+ if (c === '*') source += `${any}*`;
59
+ else if (c === '?') source += any;
58
60
  else if (c === '[') {
59
61
  const end = pattern.indexOf(']', i + 1);
60
62
  if (end < 0) source += '\\[';
@@ -64,7 +66,7 @@ function globToRegExp(pattern: string): RegExp {
64
66
  }
65
67
  } else source += c.replace(/[.+^${}()|\\]/g, '\\$&');
66
68
  }
67
- return new RegExp(`^${source}$`);
69
+ return new RegExp(`^${source}$`, 's');
68
70
  }
69
71
 
70
72
  export function glob(fs: VirtualFileSystem, cwd: string, pattern: string): string[] {
@@ -80,7 +82,7 @@ export function glob(fs: VirtualFileSystem, cwd: string, pattern: string): strin
80
82
  if (fs.exists(candidate.startsWith('/') ? candidate : join(cwd, candidate))) next.push(candidate);
81
83
  continue;
82
84
  }
83
- const re = globToRegExp(part);
85
+ const re = patternToRegExp(part);
84
86
  for (const name of fs.readdir(normalizePath(dir))) {
85
87
  if (name.startsWith('.') && !part.startsWith('.')) continue;
86
88
  if (re.test(name)) next.push(base ? (base.endsWith('/') ? base + name : `${base}/${name}`) : name);