@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
@@ -0,0 +1,105 @@
1
+ /**
2
+ * ServerResponse, streamed: the head goes out on `writeHead`/`flushHeaders` or
3
+ * the first write, each `write` is a body chunk, `end` ends the body. So
4
+ * Server-Sent Events and chunked progress reach the client as they happen. A
5
+ * client that hangs up mid-response is seen the way Node reports it.
6
+ */
7
+ import type { HttpResponseHead } from '../../system/types.js';
8
+ import { STATUS_CODES } from './status.js';
9
+ import { FakeSocket, IncomingMessage, OutgoingHeaders } from './messages.js';
10
+
11
+ /** Where a response goes as it is written. */
12
+ export interface ResponseSink {
13
+ head(head: HttpResponseHead): void;
14
+ chunk(data: Uint8Array): void;
15
+ end(): void;
16
+ }
17
+
18
+ /** Statuses that never carry a body. */
19
+ const NO_BODY = new Set([101, 204, 304]);
20
+
21
+ export class ServerResponse extends OutgoingHeaders {
22
+ statusCode = 200;
23
+ statusMessage = '';
24
+ req: IncomingMessage;
25
+ socket: FakeSocket;
26
+ connection: FakeSocket;
27
+ chunkedEncoding = false;
28
+ shouldKeepAlive = false;
29
+ private headWritten = false;
30
+ private hungUp = false;
31
+
32
+ constructor(req: IncomingMessage, private readonly sink: ResponseSink) {
33
+ super({ decodeStrings: true });
34
+ this.req = req;
35
+ this.socket = req.socket;
36
+ this.connection = req.socket;
37
+ }
38
+
39
+ get finished(): boolean {
40
+ return this.writableEnded;
41
+ }
42
+
43
+ writeHead(status: number, message?: string | Record<string, unknown> | unknown[], headers?: Record<string, unknown> | unknown[]): this {
44
+ if (typeof message !== 'string') [headers, message] = [message, undefined];
45
+ this.statusCode = status;
46
+ if (message) this.statusMessage = message;
47
+ if (Array.isArray(headers)) {
48
+ for (let i = 0; i + 1 < headers.length; i += 2) this.setHeader(String(headers[i]), headers[i + 1] as string);
49
+ } else if (headers) {
50
+ for (const [k, v] of Object.entries(headers)) if (v !== undefined) this.setHeader(k, v as string);
51
+ }
52
+ this.sendHead();
53
+ return this;
54
+ }
55
+ override flushHeaders(): void {
56
+ this.sendHead();
57
+ }
58
+ /** Node internals that middleware (compression, on-headers) patch around: send the head now; is it out yet? */
59
+ _implicitHeader(): void {
60
+ this.sendHead();
61
+ }
62
+ get _header(): boolean {
63
+ return this.headersSent;
64
+ }
65
+ writeContinue(): void {}
66
+ writeProcessing(): void {}
67
+ writeEarlyHints(): void {}
68
+ addTrailers(): void {}
69
+ assignSocket(): void {}
70
+ detachSocket(): void {}
71
+
72
+ override _write(chunk: Uint8Array, _encoding: string, callback: () => void): void {
73
+ this.sendHead();
74
+ if (!this.hungUp && this.req.method !== 'HEAD' && !NO_BODY.has(this.statusCode)) this.sink.chunk(new Uint8Array(chunk));
75
+ callback();
76
+ }
77
+
78
+ override _final(callback: () => void): void {
79
+ this.sendHead();
80
+ if (!this.hungUp) this.sink.end();
81
+ callback();
82
+ }
83
+
84
+ /** The client went away (closed its EventSource, navigated off): `aborted`/`close` on the request, `close` here; later writes are dropped. */
85
+ _hangUp(): void {
86
+ if (this.hungUp || this.writableFinished) return;
87
+ this.hungUp = true;
88
+ this._writableState.emitClose = false;
89
+ this.req.aborted = true;
90
+ this.req.emit('aborted');
91
+ this.req.emit('close');
92
+ this.socket.destroyed = true;
93
+ this.socket.emit('close', false);
94
+ this.emit('close');
95
+ }
96
+
97
+ private sendHead(): void {
98
+ this.headersSent = true;
99
+ if (this.headWritten) return;
100
+ this.headWritten = true;
101
+ const headers: Record<string, string | string[]> = {};
102
+ for (const { name, value } of this._headers.values()) headers[name] = value;
103
+ this.sink.head({ status: this.statusCode, statusText: this.statusMessage || STATUS_CODES[this.statusCode] || '', headers });
104
+ }
105
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The socket an `http.Server` hands its `upgrade` listeners: a real Duplex
3
+ * over the upgraded connection's byte pipe, with the slice of net.Socket that
4
+ * WebSocket servers touch (`ws` writes its `101` reply and frames with
5
+ * `write(data, cb)`, corks, pauses, reads `_readableState`, and calls
6
+ * `setNoDelay`/`setTimeout`). Raw bytes only — framing is the package's job.
7
+ */
8
+ import { Buffer } from '../buffer.js';
9
+ import { Duplex } from '../stream/index.js';
10
+ import type { ByteChannel } from '../../system/types.js';
11
+
12
+ type Callback = (error?: Error | null) => void;
13
+
14
+ export class UpgradeSocket extends Duplex {
15
+ remoteAddress = '127.0.0.1';
16
+ remotePort = 50000 + Math.floor(Math.random() * 10000);
17
+ remoteFamily = 'IPv4';
18
+ localAddress = '127.0.0.1';
19
+ localPort: number;
20
+ encrypted = false;
21
+ connecting = false;
22
+ bytesRead = 0;
23
+ bytesWritten = 0;
24
+ private release?: () => void;
25
+
26
+ /** `hold` keeps the process alive while the connection is open, as a TCP socket would. */
27
+ constructor(private readonly channel: ByteChannel, port: number, hold?: () => () => void) {
28
+ super({ allowHalfOpen: false });
29
+ this.localPort = port;
30
+ this.release = hold?.();
31
+ channel.onData((data) => {
32
+ this.bytesRead += data.byteLength;
33
+ this.push(Buffer.from(data.buffer as ArrayBuffer, data.byteOffset, data.byteLength));
34
+ });
35
+ channel.onClose(() => {
36
+ this.push(null);
37
+ this.end();
38
+ });
39
+ this.once('close', () => {
40
+ this.release?.();
41
+ this.release = undefined;
42
+ });
43
+ }
44
+
45
+ override _read(): void {
46
+ // bytes are pushed as they arrive
47
+ }
48
+
49
+ _write(chunk: Uint8Array, _encoding: string, callback: Callback): void {
50
+ this.bytesWritten += chunk.byteLength;
51
+ this.channel.send(chunk);
52
+ callback();
53
+ }
54
+
55
+ _final(callback: Callback): void {
56
+ this.channel.close();
57
+ this.push(null);
58
+ callback();
59
+ }
60
+
61
+ override _destroy(error: Error | null, callback: Callback): void {
62
+ this.channel.close();
63
+ callback(error);
64
+ }
65
+
66
+ setTimeout(_ms: number, cb?: () => void): this {
67
+ if (cb) this.once('timeout', cb);
68
+ return this;
69
+ }
70
+ setNoDelay(): this { return this; }
71
+ setKeepAlive(): this { return this; }
72
+ address() { return { address: this.localAddress, family: 'IPv4', port: this.localPort }; }
73
+ ref(): this { return this; }
74
+ unref(): this {
75
+ this.release?.();
76
+ this.release = undefined;
77
+ return this;
78
+ }
79
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The Node face of a process's message channel (system/ipc.ts): `process.send`,
3
+ * `process.on('message')`, `process.connected` / `disconnect()` in a forked
4
+ * child, and the keep-alive rule both it and `worker_threads`' `parentPort` follow.
5
+ */
6
+ import type { EventEmitterBase } from './events.js';
7
+ import type { EventLoop } from './loop.js';
8
+ import type { NodeProcess } from './process.js';
9
+ import type { IpcEndpoint } from '../system/ipc.js';
10
+
11
+ export interface ChannelKeepAlive {
12
+ /** Re-check whether the channel should hold the process open. */
13
+ update(): void;
14
+ ref(): void;
15
+ unref(): void;
16
+ hasRef(): boolean;
17
+ }
18
+
19
+ /**
20
+ * Node keeps a process alive for an open channel only while something listens to
21
+ * it (`events`) and nobody `unref()`ed it. `onFirstListener` runs once, when the
22
+ * first such listener arrives — the moment to start receiving, so messages sent
23
+ * before then wait in the channel instead of being emitted to no one.
24
+ */
25
+ export function keepAliveWhileListened(emitter: EventEmitterBase, events: readonly string[], loop: EventLoop, open: () => boolean, onFirstListener: () => void): ChannelKeepAlive {
26
+ let release: (() => void) | undefined;
27
+ let referenced = true;
28
+ let started = false;
29
+ const listened = () => events.some((event) => emitter.listenerCount(event) > 0);
30
+ const update = () => {
31
+ if (!started && listened()) {
32
+ started = true;
33
+ onFirstListener();
34
+ }
35
+ const want = referenced && open() && listened();
36
+ if (want && !release) release = loop.hold();
37
+ else if (!want && release) {
38
+ release();
39
+ release = undefined;
40
+ }
41
+ };
42
+ // `newListener` fires before the listener is added: look once it is in place.
43
+ const changed = (event: string | symbol) => {
44
+ if (typeof event === 'string' && events.includes(event)) queueMicrotask(update);
45
+ };
46
+ emitter.on('newListener', changed);
47
+ emitter.on('removeListener', changed);
48
+ return {
49
+ update,
50
+ ref() {
51
+ referenced = true;
52
+ update();
53
+ },
54
+ unref() {
55
+ referenced = false;
56
+ update();
57
+ },
58
+ hasRef: () => referenced,
59
+ };
60
+ }
61
+
62
+ type Callback = (error: Error | null) => void;
63
+
64
+ /** Give a forked child's `process` its channel to the parent. */
65
+ export function attachProcessChannel(proc: NodeProcess, ipc: IpcEndpoint, loop: EventLoop): void {
66
+ const keepAlive = keepAliveWhileListened(proc, ['message', 'disconnect'], loop, () => ipc.connected, () => {
67
+ ipc.onMessage((message) => loop._run(() => proc.emit('message', message, undefined)));
68
+ });
69
+ ipc.onDisconnect(() => {
70
+ proc.connected = false;
71
+ loop._run(() => proc.emit('disconnect'));
72
+ keepAlive.update();
73
+ });
74
+ Object.assign(proc, {
75
+ connected: true,
76
+ channel: { ref: keepAlive.ref, unref: keepAlive.unref, hasRef: keepAlive.hasRef },
77
+ send(message: unknown, ...rest: unknown[]): boolean {
78
+ const callback = rest.find((arg): arg is Callback => typeof arg === 'function');
79
+ try {
80
+ ipc.send(message);
81
+ } catch (error) {
82
+ if (!callback) throw error;
83
+ queueMicrotask(() => loop._run(() => callback(error as Error)));
84
+ return false;
85
+ }
86
+ if (callback) queueMicrotask(() => loop._run(() => callback(null)));
87
+ return true;
88
+ },
89
+ disconnect: () => ipc.disconnect(),
90
+ });
91
+ }
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import type { VirtualFileSystem } from '../vfs.js';
13
13
  import { dirname, extname } from '../paths.js';
14
- import { esmToCjs, ESM_MARK, hasModuleSyntax, mayBeEsm } from './esm.js';
14
+ import { esmToCjs, ESM_MARK, hasModuleSyntax, mayBeEsm, rewriteDynamicImports } from './esm.js';
15
15
  import { findPackageScope, IMPORT_CONDITIONS, nodeModulePaths, REQUIRE_CONDITIONS, resolveNodeModule, type Resolution } from './resolve.js';
16
16
 
17
17
  export interface LoaderOptions {
@@ -21,6 +21,8 @@ export interface LoaderOptions {
21
21
  builtin(name: string): unknown;
22
22
  /** Injected into every module's wrapper by name. */
23
23
  globals: Record<string, unknown>;
24
+ /** Where processes share a realm: a `with` scope for module code, so names set on the process's `globalThis` resolve bare. */
25
+ scope?: object;
24
26
  }
25
27
 
26
28
  export interface NodeModule {
@@ -37,8 +39,6 @@ export interface NodeModule {
37
39
  __tla?: Promise<unknown>;
38
40
  }
39
41
 
40
- const AsyncFunction = Object.getPrototypeOf(async () => undefined).constructor as FunctionConstructor;
41
-
42
42
  function stripShebang(source: string): string {
43
43
  const text = source.charCodeAt(0) === 0xfeff ? source.slice(1) : source;
44
44
  return text.startsWith('#!') ? '//' + text.slice(2) : text;
@@ -160,31 +160,71 @@ export function createModuleSystem(options: LoaderOptions) {
160
160
  _compile(content: string, filename: string, esm = false): unknown {
161
161
  const require = makeRequire(this);
162
162
  const dir = dirname(filename);
163
- const names = ['exports', 'require', 'module', '__filename', '__dirname', ...globalNames];
164
- const values: unknown[] = [this.exports, require, this, filename, dir, ...globalValues];
163
+ const cjsNames = ['exports', 'require', 'module', '__filename', '__dirname'];
164
+ const cjsValues: unknown[] = [this.exports, require, this, filename, dir];
165
+ let source = content;
166
+ let helperNames: string[] = [];
167
+ let helperValues: unknown[] = [];
165
168
  if (esm) {
166
- names.push('__bfwc_import', '__bfwc_dynamic', '__bfwc_meta', '__bfwc_esm', '__bfwc_star', '__bfwc_get');
167
- values.push(...esmHelpers(this, filename));
169
+ helperNames = ['__bfwc_exports', '__bfwc_import', '__bfwc_dynamic', '__bfwc_meta', '__bfwc_esm', '__bfwc_star', '__bfwc_get'];
170
+ helperValues = [this.exports, ...esmHelpers(this, filename)];
171
+ } else if ((source = rewriteDynamicImports(content)) !== content) {
172
+ helperNames = ['__bfwc_dynamic'];
173
+ helperValues = [esmHelpers(this, filename)[1]];
168
174
  }
169
- const code = `${stripShebang(content)}\n//# sourceURL=${encodeURI('file://' + filename)}`;
175
+ const code = `${stripShebang(source)}\n//# sourceURL=${encodeURI('file://' + filename)}`;
176
+ // The process's globals are an OUTER scope, as real globals are, so module code may
177
+ // shadow them (`const process = require('process')`, `import { Buffer } from 'node:buffer'`).
178
+ // An ES module may also declare the CommonJS names itself (`const require =
179
+ // createRequire(import.meta.url)`, `const __filename = fileURLToPath(…)`), so for it
180
+ // those sit in the outer scope too and only the rewrite's own helpers are parameters.
181
+ // The module's body starts on the wrapper's line, so stack line numbers hold.
182
+ const [outerNames, outerValues, innerNames, innerValues] = esm
183
+ ? [[...globalNames, ...cjsNames], [...globalValues, ...cjsValues], helperNames, helperValues]
184
+ : [globalNames, globalValues, [...cjsNames, ...helperNames], [...cjsValues, ...helperValues]];
185
+ const wrapped = (async: boolean) => {
186
+ const body = `return ${async ? 'async ' : ''}function (${innerNames.join(', ')}) {${code}\n}`;
187
+ // The `with` sits outside the globals' parameters, so those (and the module's own
188
+ // declarations) still win; it only answers names set on `globalThis` since.
189
+ const fn = options.scope
190
+ ? new Function('__bfwc_scope', `with (__bfwc_scope) { return function (${outerNames.join(', ')}) { ${body} }; }`)(options.scope)(...outerValues)
191
+ : new Function(...outerNames, body)(...outerValues);
192
+ return fn as (...args: unknown[]) => unknown;
193
+ };
170
194
  let fn: (...args: unknown[]) => unknown;
171
195
  try {
172
- fn = new Function(...names, code) as typeof fn;
196
+ fn = wrapped(false);
173
197
  } catch (error) {
174
- if (esm && error instanceof SyntaxError && /await/.test(error.message)) fn = new AsyncFunction(...names, code) as typeof fn;
175
- else {
198
+ // Top-level await reads as a syntax error in a plain function, and V8 names the
199
+ // token after `await` (`Unexpected identifier '__bfwc_dynamic'`), not `await` itself.
200
+ let retried: ((...args: unknown[]) => unknown) | undefined;
201
+ if (esm && error instanceof SyntaxError && /\bawait\b/.test(source)) {
202
+ try {
203
+ retried = wrapped(true);
204
+ } catch {
205
+ // not top-level await after all: report the first error
206
+ }
207
+ }
208
+ if (!retried) {
176
209
  if (error instanceof Error) error.message = `${filename}: ${error.message}`;
177
210
  throw error;
178
211
  }
212
+ fn = retried;
179
213
  }
180
- const result = fn.apply(this.exports, values);
214
+ // An ES module's static imports evaluate first; one still in top-level await holds
215
+ // this module's body (and so, through its own `__tla`, whoever imports it).
216
+ const pending = esm ? importsAwaiting(this, source) : [];
217
+ const result = pending.length ? Promise.all(pending).then(() => fn.apply(this.exports, innerValues)) : fn.apply(this.exports, innerValues);
181
218
  if (result instanceof Promise) this.__tla = result;
182
219
  return result;
183
220
  }
184
221
  }
185
222
 
186
- function esmHelpers(module: Module, filename: string): unknown[] {
187
- const load = (specifier: string): { exports: any; __tla?: Promise<unknown> } => {
223
+ /** Load what an ES module imports, as `import` and `import()` do. */
224
+ function importLoader(module: Module) {
225
+ return (rawSpecifier: string): { exports: any; __tla?: Promise<unknown> } => {
226
+ // `import()` takes file URLs (`import(pathToFileURL(configPath).href)`); `require` does not.
227
+ const specifier = rawSpecifier.startsWith('file:') ? decodeURIComponent(new URL(rawSpecifier).pathname) : rawSpecifier;
188
228
  let target: string;
189
229
  try {
190
230
  target = Module._resolveFilename(specifier, module, false, { conditions: REQUIRE_CONDITIONS });
@@ -196,6 +236,30 @@ export function createModuleSystem(options: LoaderOptions) {
196
236
  }
197
237
  return loadResolved(target, module, false);
198
238
  };
239
+ }
240
+
241
+ /**
242
+ * Evaluate a rewritten module's static imports (`__bfwc_import("…")`, in order) and
243
+ * return the top-level awaits still running among them. One that fails to load is
244
+ * left for the module's own import statement to report.
245
+ */
246
+ function importsAwaiting(module: Module, rewritten: string): Promise<unknown>[] {
247
+ const load = importLoader(module);
248
+ const pending: Promise<unknown>[] = [];
249
+ for (const [, literal] of rewritten.matchAll(/__bfwc_import\(("(?:[^"\\]|\\.)*")\)/g)) {
250
+ if (!literal) continue;
251
+ try {
252
+ const loaded = load(JSON.parse(literal) as string);
253
+ if (loaded.__tla) pending.push(loaded.__tla);
254
+ } catch {
255
+ // reported where the module imports it
256
+ }
257
+ }
258
+ return pending;
259
+ }
260
+
261
+ function esmHelpers(module: Module, filename: string): unknown[] {
262
+ const load = importLoader(module);
199
263
  const importSync = (specifier: string) => namespaceOf(load(specifier).exports);
200
264
  const meta = {
201
265
  url: 'file://' + filename,
package/src/node/misc.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The small builtins: os, tty, timers (+promises), string_decoder, perf_hooks,
3
- * async_hooks, worker_threads, vm, dns, v8, diagnostics_channel and stubs for
3
+ * async_hooks, vm, dns, v8, diagnostics_channel and stubs for
4
4
  * the ones with nothing to offer in a browser (cluster, inspector). Each exists
5
5
  * so `require` succeeds and the common calls behave plausibly.
6
6
  */
@@ -8,6 +8,7 @@ import { EventEmitterBase } from './events.js';
8
8
  import type { EventLoop } from './loop.js';
9
9
  import { decode } from './buffer.js';
10
10
  import { callable } from './callable.js';
11
+ import { queueCallback } from './processExit.js';
11
12
 
12
13
  export function createOsModule(env: () => Record<string, string | undefined>): Record<string, unknown> {
13
14
  const cpus = Array.from({ length: Math.max(1, Math.min(16, globalThis.navigator?.hardwareConcurrency ?? 4)) }, () => ({
@@ -171,10 +172,24 @@ export function createAsyncHooksModule(): Record<string, unknown> {
171
172
  };
172
173
  }
173
174
 
175
+ const VM_CODE = '__bfwc_vm_code';
176
+
174
177
  export function createVmModule(): Record<string, unknown> {
178
+ // The context IS the code's global object: free names read it first (then the real
179
+ // builtins), assignments and `globalThis.x = …` land on it. Next.js reads its client
180
+ // manifests back off the context this way.
175
181
  const run = (code: string, context: Record<string, unknown> = {}) => {
176
- const names = Object.keys(context).filter((k) => /^[A-Za-z_$][\w$]*$/.test(k));
177
- return new Function(...names, `return eval(${JSON.stringify(code)})`)(...names.map((n) => context[n]));
182
+ const sandbox: Record<PropertyKey, unknown> = new Proxy(context, {
183
+ has: (_target, key) => key !== VM_CODE,
184
+ get: (target, key) => {
185
+ if (key === Symbol.unscopables) return undefined;
186
+ if (key === 'globalThis') return sandbox;
187
+ return key in target ? target[key as string] : Reflect.get(globalThis, key);
188
+ },
189
+ set: (target, key, value) => Reflect.set(target, key, value),
190
+ });
191
+ // Sloppy-mode function: `with` routes every free name through the sandbox.
192
+ return new Function(VM_CODE, `with (this) { return eval(${VM_CODE}); }`).call(sandbox, code);
178
193
  };
179
194
  class Script {
180
195
  constructor(private readonly code: string) {}
@@ -231,8 +246,7 @@ const unavailable = (name: string) => () => {
231
246
  export function createStubModules(): Record<string, Record<string, unknown>> {
232
247
  return {
233
248
  perf_hooks: { performance: globalThis.performance, PerformanceObserver: class { observe() {} disconnect() {} }, monitorEventLoopDelay: () => ({ enable() {}, disable() {}, percentile: () => 0, mean: 0, max: 0, min: 0 }), constants: {} },
234
- worker_threads: { isMainThread: true, parentPort: null, workerData: null, threadId: 0, resourceLimits: {}, Worker: unavailable('worker_threads.Worker'), MessageChannel, MessagePort: globalThis.MessagePort, BroadcastChannel: globalThis.BroadcastChannel, markAsUntransferable: () => undefined, SHARE_ENV: Symbol('SHARE_ENV') },
235
- dns: { lookup: (host: string, options: unknown, cb?: (e: Error | null, address: string, family: number) => void) => queueMicrotask(() => ((typeof options === 'function' ? options : cb) as NonNullable<typeof cb>)(null, host === 'localhost' ? '127.0.0.1' : host, 4)), resolve: unavailable('dns.resolve'), promises: { lookup: async (host: string) => ({ address: host === 'localhost' ? '127.0.0.1' : host, family: 4 }) }, setDefaultResultOrder: () => undefined },
249
+ dns: { lookup: (host: string, options: unknown, cb?: (e: Error | null, address: string, family: number) => void) => queueCallback(() => ((typeof options === 'function' ? options : cb) as NonNullable<typeof cb>)(null, host === 'localhost' ? '127.0.0.1' : host, 4)), resolve: unavailable('dns.resolve'), promises: { lookup: async (host: string) => ({ address: host === 'localhost' ? '127.0.0.1' : host, family: 4 }) }, setDefaultResultOrder: () => undefined },
236
250
  v8: { getHeapStatistics: () => ({ total_heap_size: 30e6, used_heap_size: 20e6, heap_size_limit: 2e9 }), getHeapSpaceStatistics: () => [], serialize: (v: unknown) => new TextEncoder().encode(JSON.stringify(v)), deserialize: (b: Uint8Array) => JSON.parse(new TextDecoder().decode(b)), setFlagsFromString: () => undefined, cachedDataVersionTag: () => 0 },
237
251
  cluster: { isMaster: true, isPrimary: true, isWorker: false, workers: {}, fork: unavailable('cluster.fork'), on: () => undefined, settings: {} },
238
252
  inspector: { open: () => undefined, close: () => undefined, url: () => undefined, Session: class { connect() {} post() {} disconnect() {} }, console: globalThis.console },
@@ -5,6 +5,7 @@
5
5
  * `process.platform`, `process.versions.node` and `process.stdout.isTTY`.
6
6
  */
7
7
  import { EventEmitterBase } from './events.js';
8
+ import { Buffer } from './buffer.js';
8
9
  import { Readable } from './stream/readable.js';
9
10
  import { Writable } from './stream/writable.js';
10
11
  import type { EventLoop } from './loop.js';
@@ -13,13 +14,11 @@ import type { VirtualFileSystem } from '../vfs.js';
13
14
  import { join, normalizePath } from '../paths.js';
14
15
  import { fsError } from './fs/stats.js';
15
16
  import { format } from './inspect.js';
17
+ import { ProcessExit, queueCallback } from './processExit.js';
16
18
 
17
19
  export const NODE_VERSION = '20.18.0';
18
20
 
19
- /** Thrown by `process.exit()` to unwind user code; the runtime catches it. */
20
- export class ProcessExit {
21
- constructor(readonly code: number) {}
22
- }
21
+ export { ProcessExit };
23
22
 
24
23
  let nextPid = 100;
25
24
 
@@ -64,7 +63,7 @@ class TtyWriteStream extends Writable {
64
63
  override write(chunk: unknown, encoding?: any, callback?: any): boolean {
65
64
  if (typeof encoding === 'function') callback = encoding;
66
65
  this.sink(typeof chunk === 'string' || chunk instanceof Uint8Array ? chunk : String(chunk));
67
- if (typeof callback === 'function') queueMicrotask(callback);
66
+ if (typeof callback === 'function') queueCallback(callback);
68
67
  return true;
69
68
  }
70
69
 
@@ -106,8 +105,9 @@ class StdinStream extends Readable {
106
105
  private subscription?: () => void;
107
106
  private release?: () => void;
108
107
 
108
+ // Buffers, as in Node, unless the program calls setEncoding: a binary protocol on stdin must arrive intact.
109
109
  constructor(private readonly io: ProgramIO, private readonly loop: EventLoop) {
110
- super({ encoding: 'utf8' });
110
+ super();
111
111
  this.isTTY = !!io.terminal;
112
112
  }
113
113
 
@@ -149,7 +149,7 @@ class StdinStream extends Readable {
149
149
  if (chunk === null) {
150
150
  this.stopListening();
151
151
  this.push(null);
152
- } else this.push(chunk);
152
+ } else this.push(Buffer.from(typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk));
153
153
  });
154
154
  }
155
155
 
@@ -167,11 +167,15 @@ export function createProcess(options: ProcessOptions): NodeProcess {
167
167
  const { io, loop, fs } = options;
168
168
  let cwd = normalizePath(options.cwd);
169
169
  let exited = false;
170
+ let gone = false;
170
171
  const started = performance.now();
171
172
  const proc = new EventEmitterBase() as NodeProcess;
172
173
  const pid = nextPid++;
173
174
 
174
175
  const exit = (code?: number) => {
176
+ // Already gone: a straggling callback (a host promise settling late) has no stack
177
+ // left to unwind, and throwing would surface as the HOST's unhandled rejection.
178
+ if (gone) return undefined as never;
175
179
  if (code !== undefined) proc.exitCode = code;
176
180
  if (!exited) {
177
181
  exited = true;
@@ -181,6 +185,7 @@ export function createProcess(options: ProcessOptions): NodeProcess {
181
185
  } catch {
182
186
  // an 'exit' listener that throws must not stop the exit
183
187
  }
188
+ gone = true;
184
189
  options.onExit(Number(proc.exitCode ?? final) || 0);
185
190
  }
186
191
  throw new ProcessExit(Number(proc.exitCode ?? 0) || 0);
@@ -208,7 +213,9 @@ export function createProcess(options: ProcessOptions): NodeProcess {
208
213
  Object.assign(proc, {
209
214
  title: 'node',
210
215
  version: `v${NODE_VERSION}`,
211
- versions: { node: NODE_VERSION, v8: '11.3.244.8-node.23', uv: '1.48.0', zlib: '1.3.0.1', modules: '115', napi: '9', unicode: '15.1' },
216
+ // `webcontainer` is the ecosystem's in-browser-runtime marker: tools that check it
217
+ // pick their WebAssembly builds over native binaries (Next.js loads @next/swc-wasm-nodejs).
218
+ versions: { node: NODE_VERSION, v8: '11.3.244.8-node.23', uv: '1.48.0', zlib: '1.3.0.1', modules: '115', napi: '9', unicode: '15.1', webcontainer: NODE_VERSION },
212
219
  release: { name: 'node', lts: 'Iron' },
213
220
  platform: 'linux',
214
221
  arch: 'x64',
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `process.exit()` unwinds user code by throwing {@link ProcessExit}. Callbacks a
3
+ * builtin queues into user code go through {@link queueCallback}, so an exit inside
4
+ * one ends there instead of escaping to whatever host runs the microtask.
5
+ */
6
+
7
+ /** Thrown by `process.exit()` to unwind user code; the runtime catches it. */
8
+ export class ProcessExit {
9
+ constructor(readonly code: number) {}
10
+ }
11
+
12
+ /** `queueMicrotask` for a builtin's callback into user code (a stream tick, an fs callback). */
13
+ export function queueCallback(fn: () => void): void {
14
+ queueMicrotask(() => {
15
+ try {
16
+ fn();
17
+ } catch (error) {
18
+ if (!(error instanceof ProcessExit)) throw error;
19
+ }
20
+ });
21
+ }
@@ -9,6 +9,7 @@ import { startNode, type NodeInstance } from './runtime.js';
9
9
  import { NODE_VERSION } from './process.js';
10
10
  import { inspect } from './inspect.js';
11
11
  import { parseDotenv } from '../projectConfig.js';
12
+ import { textChunks } from '../system/terminal.js';
12
13
 
13
14
  interface NodeCli {
14
15
  entry?: string;
@@ -66,12 +67,14 @@ Options: -v, -r <module>, --env-file=<file>. Running in BuilderForce WebContaine
66
67
  async function readAllStdin(ctx: ProgramContext): Promise<string> {
67
68
  let text = '';
68
69
  await new Promise<void>((resolve) => {
69
- const stop = ctx.io.onStdin((chunk) => {
70
- if (chunk === null) {
71
- stop();
72
- resolve();
73
- } else text += chunk;
74
- });
70
+ const stop = ctx.io.onStdin(
71
+ textChunks((chunk) => {
72
+ if (chunk === null) {
73
+ stop();
74
+ resolve();
75
+ } else text += chunk;
76
+ }),
77
+ );
75
78
  });
76
79
  return text;
77
80
  }
@@ -88,7 +91,7 @@ function startRepl(instance: NodeInstance, ctx: ProgramContext): void {
88
91
  release();
89
92
  instance.run(() => instance.process.exit(0));
90
93
  };
91
- const stop = io.onStdin((chunk) => {
94
+ const stop = io.onStdin(textChunks((chunk) => {
92
95
  if (chunk === null) return leave();
93
96
  for (const raw of chunk.split(/\r?\n/)) {
94
97
  const line = raw.trim();
@@ -99,7 +102,7 @@ function startRepl(instance: NodeInstance, ctx: ProgramContext): void {
99
102
  else io.stdout(inspect(result.value, { colors: false }) + '\n');
100
103
  }
101
104
  io.stdout('> ');
102
- });
105
+ }));
103
106
  }
104
107
 
105
108
  /** Evaluate `expression` inside the CommonJS wrapper, so it sees require, process, timers… of this process. */
@@ -136,7 +139,7 @@ export const nodeProgram: Program = async (ctx) => {
136
139
  }
137
140
  const source = cli.evaluate ?? (cli.entry === '-' || (!entry && !ctx.io.terminal) ? await readAllStdin(ctx) : undefined);
138
141
  const scriptPath = entry ?? (source !== undefined ? '[eval]' : undefined);
139
- const instance = await startNode({ system: ctx.system, io: ctx.io, cwd: ctx.cwd, env, installGlobals: ctx.system.ownsRealm, argv: scriptPath && scriptPath !== '[eval]' ? [scriptPath, ...cli.args] : cli.args });
142
+ const instance = await startNode({ system: ctx.system, io: ctx.io, cwd: ctx.cwd, env, installGlobals: ctx.system.ownsRealm, ipc: ctx.ipc, thread: ctx.thread, argv: scriptPath && scriptPath !== '[eval]' ? [scriptPath, ...cli.args] : cli.args });
140
143
  const onAbort = () => instance.kill(typeof ctx.signal.reason === 'string' ? ctx.signal.reason : 'SIGTERM');
141
144
  if (ctx.signal.aborted) onAbort();
142
145
  ctx.signal.addEventListener('abort', onAbort);