@seanhogg/builderforce-webcontainers-core 2026.10.8 → 2026.10.10

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 (296) hide show
  1. package/dist/build.d.ts +6 -0
  2. package/dist/build.d.ts.map +1 -1
  3. package/dist/build.js +9 -1
  4. package/dist/build.js.map +1 -1
  5. package/dist/buildHost.d.ts +3 -0
  6. package/dist/buildHost.d.ts.map +1 -1
  7. package/dist/buildHost.js +25 -12
  8. package/dist/buildHost.js.map +1 -1
  9. package/dist/compileComponent.d.ts.map +1 -1
  10. package/dist/compileComponent.js +4 -1
  11. package/dist/compileComponent.js.map +1 -1
  12. package/dist/compileScript.d.ts +12 -4
  13. package/dist/compileScript.d.ts.map +1 -1
  14. package/dist/compileScript.js +26 -13
  15. package/dist/compileScript.js.map +1 -1
  16. package/dist/components.d.ts +5 -0
  17. package/dist/components.d.ts.map +1 -1
  18. package/dist/components.js.map +1 -1
  19. package/dist/detectProject.d.ts +2 -0
  20. package/dist/detectProject.d.ts.map +1 -1
  21. package/dist/detectProject.js +13 -7
  22. package/dist/detectProject.js.map +1 -1
  23. package/dist/devServer.d.ts +38 -4
  24. package/dist/devServer.d.ts.map +1 -1
  25. package/dist/devServer.js +140 -24
  26. package/dist/devServer.js.map +1 -1
  27. package/dist/devStyles.d.ts +27 -0
  28. package/dist/devStyles.d.ts.map +1 -0
  29. package/dist/devStyles.js +52 -0
  30. package/dist/devStyles.js.map +1 -0
  31. package/dist/hot/client.d.ts +33 -0
  32. package/dist/hot/client.d.ts.map +1 -0
  33. package/dist/hot/client.js +46 -0
  34. package/dist/hot/client.js.map +1 -0
  35. package/dist/hot/moduleGraph.d.ts +39 -0
  36. package/dist/hot/moduleGraph.d.ts.map +1 -0
  37. package/dist/hot/moduleGraph.js +69 -0
  38. package/dist/hot/moduleGraph.js.map +1 -0
  39. package/dist/hot/planUpdate.d.ts +33 -0
  40. package/dist/hot/planUpdate.d.ts.map +1 -0
  41. package/dist/hot/planUpdate.js +43 -0
  42. package/dist/hot/planUpdate.js.map +1 -0
  43. package/dist/hot/reactRefresh.d.ts +45 -0
  44. package/dist/hot/reactRefresh.d.ts.map +1 -0
  45. package/dist/hot/reactRefresh.js +86 -0
  46. package/dist/hot/reactRefresh.js.map +1 -0
  47. package/dist/html.d.ts +2 -8
  48. package/dist/html.d.ts.map +1 -1
  49. package/dist/html.js +11 -17
  50. package/dist/html.js.map +1 -1
  51. package/dist/index.d.ts +19 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +11 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/installer/tree.d.ts.map +1 -1
  56. package/dist/installer/tree.js +30 -5
  57. package/dist/installer/tree.js.map +1 -1
  58. package/dist/installer/wasmBuilds.d.ts +34 -0
  59. package/dist/installer/wasmBuilds.d.ts.map +1 -0
  60. package/dist/installer/wasmBuilds.js +41 -0
  61. package/dist/installer/wasmBuilds.js.map +1 -0
  62. package/dist/node/builtins.d.ts +6 -1
  63. package/dist/node/builtins.d.ts.map +1 -1
  64. package/dist/node/builtins.js +17 -10
  65. package/dist/node/builtins.js.map +1 -1
  66. package/dist/node/childProcess.d.ts +3 -3
  67. package/dist/node/childProcess.d.ts.map +1 -1
  68. package/dist/node/childProcess.js +68 -16
  69. package/dist/node/childProcess.js.map +1 -1
  70. package/dist/node/crypto.d.ts.map +1 -1
  71. package/dist/node/crypto.js +5 -4
  72. package/dist/node/crypto.js.map +1 -1
  73. package/dist/node/esm.d.ts +7 -0
  74. package/dist/node/esm.d.ts.map +1 -1
  75. package/dist/node/esm.js +28 -2
  76. package/dist/node/esm.js.map +1 -1
  77. package/dist/node/fs/index.d.ts +3 -0
  78. package/dist/node/fs/index.d.ts.map +1 -1
  79. package/dist/node/fs/index.js +22 -106
  80. package/dist/node/fs/index.js.map +1 -1
  81. package/dist/node/fs/stdinFd.d.ts +10 -0
  82. package/dist/node/fs/stdinFd.d.ts.map +1 -0
  83. package/dist/node/fs/stdinFd.js +40 -0
  84. package/dist/node/fs/stdinFd.js.map +1 -0
  85. package/dist/node/fs/streams.d.ts +24 -0
  86. package/dist/node/fs/streams.d.ts.map +1 -0
  87. package/dist/node/fs/streams.js +144 -0
  88. package/dist/node/fs/streams.js.map +1 -0
  89. package/dist/node/fs/sync.d.ts +2 -0
  90. package/dist/node/fs/sync.d.ts.map +1 -1
  91. package/dist/node/fs/sync.js +17 -0
  92. package/dist/node/fs/sync.js.map +1 -1
  93. package/dist/node/globalObject.d.ts +25 -0
  94. package/dist/node/globalObject.d.ts.map +1 -0
  95. package/dist/node/globalObject.js +83 -0
  96. package/dist/node/globalObject.js.map +1 -0
  97. package/dist/node/http/index.d.ts.map +1 -1
  98. package/dist/node/http/index.js +4 -3
  99. package/dist/node/http/index.js.map +1 -1
  100. package/dist/node/http/server.d.ts.map +1 -1
  101. package/dist/node/http/server.js +8 -5
  102. package/dist/node/http/server.js.map +1 -1
  103. package/dist/node/http/serverResponse.d.ts +3 -0
  104. package/dist/node/http/serverResponse.d.ts.map +1 -1
  105. package/dist/node/http/serverResponse.js +7 -0
  106. package/dist/node/http/serverResponse.js.map +1 -1
  107. package/dist/node/ipc.d.ts +26 -0
  108. package/dist/node/ipc.d.ts.map +1 -0
  109. package/dist/node/ipc.js +76 -0
  110. package/dist/node/ipc.js.map +1 -0
  111. package/dist/node/loader.d.ts +2 -0
  112. package/dist/node/loader.d.ts.map +1 -1
  113. package/dist/node/loader.js +79 -14
  114. package/dist/node/loader.js.map +1 -1
  115. package/dist/node/misc.d.ts.map +1 -1
  116. package/dist/node/misc.js +20 -6
  117. package/dist/node/misc.js.map +1 -1
  118. package/dist/node/process.d.ts +2 -5
  119. package/dist/node/process.d.ts.map +1 -1
  120. package/dist/node/process.js +16 -11
  121. package/dist/node/process.js.map +1 -1
  122. package/dist/node/processExit.d.ts +13 -0
  123. package/dist/node/processExit.d.ts.map +1 -0
  124. package/dist/node/processExit.js +25 -0
  125. package/dist/node/processExit.js.map +1 -0
  126. package/dist/node/program.d.ts.map +1 -1
  127. package/dist/node/program.js +6 -5
  128. package/dist/node/program.js.map +1 -1
  129. package/dist/node/runtime.d.ts +6 -1
  130. package/dist/node/runtime.d.ts.map +1 -1
  131. package/dist/node/runtime.js +23 -15
  132. package/dist/node/runtime.js.map +1 -1
  133. package/dist/node/stream/readable.d.ts +2 -1
  134. package/dist/node/stream/readable.d.ts.map +1 -1
  135. package/dist/node/stream/readable.js +2 -1
  136. package/dist/node/stream/readable.js.map +1 -1
  137. package/dist/node/urlqs.d.ts +1 -1
  138. package/dist/node/urlqs.d.ts.map +1 -1
  139. package/dist/node/urlqs.js +11 -2
  140. package/dist/node/urlqs.js.map +1 -1
  141. package/dist/node/wasi/abi.d.ts +82 -0
  142. package/dist/node/wasi/abi.d.ts.map +1 -0
  143. package/dist/node/wasi/abi.js +144 -0
  144. package/dist/node/wasi/abi.js.map +1 -0
  145. package/dist/node/wasi/files.d.ts +67 -0
  146. package/dist/node/wasi/files.d.ts.map +1 -0
  147. package/dist/node/wasi/files.js +319 -0
  148. package/dist/node/wasi/files.js.map +1 -0
  149. package/dist/node/wasi/index.d.ts +17 -0
  150. package/dist/node/wasi/index.d.ts.map +1 -0
  151. package/dist/node/wasi/index.js +129 -0
  152. package/dist/node/wasi/index.js.map +1 -0
  153. package/dist/node/workerThreads.d.ts +31 -0
  154. package/dist/node/workerThreads.d.ts.map +1 -0
  155. package/dist/node/workerThreads.js +165 -0
  156. package/dist/node/workerThreads.js.map +1 -0
  157. package/dist/node/zlib.d.ts.map +1 -1
  158. package/dist/node/zlib.js +23 -2
  159. package/dist/node/zlib.js.map +1 -1
  160. package/dist/shell/context.d.ts.map +1 -1
  161. package/dist/shell/context.js +2 -2
  162. package/dist/shell/context.js.map +1 -1
  163. package/dist/shell/devHandoff.d.ts +10 -4
  164. package/dist/shell/devHandoff.d.ts.map +1 -1
  165. package/dist/shell/devHandoff.js +7 -5
  166. package/dist/shell/devHandoff.js.map +1 -1
  167. package/dist/shell/exec.d.ts.map +1 -1
  168. package/dist/shell/exec.js +6 -5
  169. package/dist/shell/exec.js.map +1 -1
  170. package/dist/shell/npm.js +2 -2
  171. package/dist/shell/npm.js.map +1 -1
  172. package/dist/shell/program.js +5 -5
  173. package/dist/shell/program.js.map +1 -1
  174. package/dist/styleModules.d.ts +2 -5
  175. package/dist/styleModules.d.ts.map +1 -1
  176. package/dist/styleModules.js +23 -14
  177. package/dist/styleModules.js.map +1 -1
  178. package/dist/styles/compile.d.ts +18 -0
  179. package/dist/styles/compile.d.ts.map +1 -0
  180. package/dist/styles/compile.js +34 -0
  181. package/dist/styles/compile.js.map +1 -0
  182. package/dist/styles/compilers.d.ts +75 -0
  183. package/dist/styles/compilers.d.ts.map +1 -0
  184. package/dist/styles/compilers.js +77 -0
  185. package/dist/styles/compilers.js.map +1 -0
  186. package/dist/styles/cssModules.d.ts +40 -0
  187. package/dist/styles/cssModules.d.ts.map +1 -0
  188. package/dist/styles/cssModules.js +239 -0
  189. package/dist/styles/cssModules.js.map +1 -0
  190. package/dist/styles/imports.d.ts +37 -0
  191. package/dist/styles/imports.d.ts.map +1 -0
  192. package/dist/styles/imports.js +88 -0
  193. package/dist/styles/imports.js.map +1 -0
  194. package/dist/styles/languages.d.ts +13 -0
  195. package/dist/styles/languages.d.ts.map +1 -0
  196. package/dist/styles/languages.js +20 -0
  197. package/dist/styles/languages.js.map +1 -0
  198. package/dist/styles/packageStyles.d.ts +19 -0
  199. package/dist/styles/packageStyles.d.ts.map +1 -0
  200. package/dist/styles/packageStyles.js +32 -0
  201. package/dist/styles/packageStyles.js.map +1 -0
  202. package/dist/svelteCompiler.d.ts.map +1 -1
  203. package/dist/svelteCompiler.js +19 -2
  204. package/dist/svelteCompiler.js.map +1 -1
  205. package/dist/system/commands.d.ts +2 -0
  206. package/dist/system/commands.d.ts.map +1 -1
  207. package/dist/system/commands.js +18 -0
  208. package/dist/system/commands.js.map +1 -1
  209. package/dist/system/index.d.ts +3 -1
  210. package/dist/system/index.d.ts.map +1 -1
  211. package/dist/system/index.js +1 -0
  212. package/dist/system/index.js.map +1 -1
  213. package/dist/system/ipc.d.ts +33 -0
  214. package/dist/system/ipc.d.ts.map +1 -0
  215. package/dist/system/ipc.js +65 -0
  216. package/dist/system/ipc.js.map +1 -0
  217. package/dist/system/kernel.d.ts.map +1 -1
  218. package/dist/system/kernel.js +6 -3
  219. package/dist/system/kernel.js.map +1 -1
  220. package/dist/system/process.d.ts +3 -0
  221. package/dist/system/process.d.ts.map +1 -1
  222. package/dist/system/process.js +50 -26
  223. package/dist/system/process.js.map +1 -1
  224. package/dist/system/terminal.d.ts +10 -4
  225. package/dist/system/terminal.d.ts.map +1 -1
  226. package/dist/system/terminal.js +21 -13
  227. package/dist/system/terminal.js.map +1 -1
  228. package/dist/system/types.d.ts +29 -7
  229. package/dist/system/types.d.ts.map +1 -1
  230. package/dist/vueCompiler.d.ts.map +1 -1
  231. package/dist/vueCompiler.js +11 -8
  232. package/dist/vueCompiler.js.map +1 -1
  233. package/package.json +4 -1
  234. package/src/build.ts +13 -1
  235. package/src/buildHost.ts +23 -10
  236. package/src/compileComponent.ts +4 -1
  237. package/src/compileScript.ts +30 -11
  238. package/src/components.ts +5 -0
  239. package/src/detectProject.ts +13 -6
  240. package/src/devServer.ts +148 -23
  241. package/src/devStyles.ts +70 -0
  242. package/src/hot/client.ts +70 -0
  243. package/src/hot/moduleGraph.ts +90 -0
  244. package/src/hot/planUpdate.ts +66 -0
  245. package/src/hot/reactRefresh.ts +93 -0
  246. package/src/html.ts +13 -19
  247. package/src/index.ts +19 -1
  248. package/src/installer/tree.ts +32 -5
  249. package/src/installer/wasmBuilds.ts +60 -0
  250. package/src/node/builtins.ts +23 -12
  251. package/src/node/childProcess.ts +73 -20
  252. package/src/node/crypto.ts +5 -4
  253. package/src/node/esm.ts +26 -2
  254. package/src/node/fs/index.ts +26 -103
  255. package/src/node/fs/stdinFd.ts +44 -0
  256. package/src/node/fs/streams.ts +177 -0
  257. package/src/node/fs/sync.ts +15 -0
  258. package/src/node/globalObject.ts +82 -0
  259. package/src/node/http/index.ts +4 -3
  260. package/src/node/http/server.ts +8 -5
  261. package/src/node/http/serverResponse.ts +7 -0
  262. package/src/node/ipc.ts +91 -0
  263. package/src/node/loader.ts +78 -14
  264. package/src/node/misc.ts +19 -6
  265. package/src/node/process.ts +15 -8
  266. package/src/node/processExit.ts +21 -0
  267. package/src/node/program.ts +12 -9
  268. package/src/node/runtime.ts +27 -15
  269. package/src/node/stream/readable.ts +2 -1
  270. package/src/node/urlqs.ts +10 -2
  271. package/src/node/wasi/abi.ts +151 -0
  272. package/src/node/wasi/files.ts +350 -0
  273. package/src/node/wasi/index.ts +149 -0
  274. package/src/node/workerThreads.ts +198 -0
  275. package/src/node/zlib.ts +24 -2
  276. package/src/shell/context.ts +2 -2
  277. package/src/shell/devHandoff.ts +16 -9
  278. package/src/shell/exec.ts +6 -5
  279. package/src/shell/npm.ts +2 -2
  280. package/src/shell/program.ts +5 -5
  281. package/src/styleModules.ts +30 -14
  282. package/src/styles/compile.ts +43 -0
  283. package/src/styles/compilers.ts +143 -0
  284. package/src/styles/cssModules.ts +254 -0
  285. package/src/styles/imports.ts +125 -0
  286. package/src/styles/languages.ts +29 -0
  287. package/src/styles/packageStyles.ts +35 -0
  288. package/src/svelteCompiler.ts +20 -3
  289. package/src/system/commands.ts +17 -0
  290. package/src/system/index.ts +4 -0
  291. package/src/system/ipc.ts +89 -0
  292. package/src/system/kernel.ts +6 -3
  293. package/src/system/process.ts +57 -30
  294. package/src/system/terminal.ts +34 -12
  295. package/src/system/types.ts +31 -7
  296. package/src/vueCompiler.ts +11 -8
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 },
@@ -243,7 +257,6 @@ export function createStubModules(): Record<string, Record<string, unknown>> {
243
257
  trace_events: { createTracing: () => ({ enable() {}, disable() {} }), getEnabledCategories: () => '' },
244
258
  sqlite: { DatabaseSync: unavailable('sqlite.DatabaseSync') },
245
259
  test: { test: unavailable('node:test'), describe: unavailable('node:test'), it: unavailable('node:test') },
246
- wasi: { WASI: unavailable('wasi.WASI') },
247
260
  repl: { start: unavailable('repl.start') },
248
261
  domain: { create: () => Object.assign(new EventEmitterBase(), { run: (fn: () => unknown) => fn(), add() {}, remove() {}, bind: <F>(fn: F) => fn, intercept: <F>(fn: F) => fn, enter() {}, exit() {}, dispose() {} }) },
249
262
  };
@@ -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);
@@ -4,7 +4,10 @@
4
4
  * entry and resolves `exit` with the code once the process exits — by
5
5
  * `process.exit()`, an uncaught exception, being killed, or the loop going idle.
6
6
  */
7
- import type { ProgramIO, System } from '../system/types.js';
7
+ import type { ProgramIO, System, ThreadInfo } from '../system/types.js';
8
+ import type { IpcEndpoint } from '../system/ipc.js';
9
+ import { attachProcessChannel } from './ipc.js';
10
+ import { threadErrorEnvelope } from './workerThreads.js';
8
11
  import { Buffer } from './buffer.js';
9
12
  import { createBuiltins } from './builtins.js';
10
13
  import { createModuleSystem, type ModuleSystem } from './loader.js';
@@ -12,6 +15,7 @@ import { EventLoop } from './loop.js';
12
15
  import { createConsole, createProcess, ProcessExit, type NodeProcess } from './process.js';
13
16
  import { esmReady } from './esm.js';
14
17
  import { inspect } from './inspect.js';
18
+ import { installGlobalObject } from './globalObject.js';
15
19
 
16
20
  export interface NodeOptions {
17
21
  system: System;
@@ -27,6 +31,10 @@ export interface NodeOptions {
27
31
  * share one realm.
28
32
  */
29
33
  installGlobals?: boolean;
34
+ /** The channel to the parent: `process.send` in a forked child, `parentPort` in a worker thread. */
35
+ ipc?: IpcEndpoint;
36
+ /** Set when this process is a worker thread. */
37
+ thread?: ThreadInfo;
30
38
  }
31
39
 
32
40
  export interface NodeInstance {
@@ -48,7 +56,14 @@ const SIGNAL_CODES: Record<string, number> = { SIGINT: 130, SIGTERM: 143, SIGKIL
48
56
 
49
57
  export async function startNode(options: NodeOptions): Promise<NodeInstance> {
50
58
  await esmReady;
51
- const { system, io } = options;
59
+ const { system } = options;
60
+ // Once the process has finished it prints nothing — a host promise settling late
61
+ // must not write past the exit the parent already saw.
62
+ const io: ProgramIO = {
63
+ ...options.io,
64
+ stdout: (chunk) => finished || options.io.stdout(chunk),
65
+ stderr: (chunk) => finished || options.io.stderr(chunk),
66
+ };
52
67
  let resolveExit!: (code: number) => void;
53
68
  const exit = new Promise<number>((resolve) => (resolveExit = resolve));
54
69
  let finished = false;
@@ -89,8 +104,12 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
89
104
  error = nested;
90
105
  }
91
106
  }
92
- const text = error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` : `Uncaught ${inspect(error)}`;
93
- io.stderr(`${text}\n\nNode.js v${proc.versions.node}\n`);
107
+ // A worker thread's fatal error is the parent's 'error' event, not output.
108
+ if (options.thread && options.ipc?.connected) options.ipc.send(threadErrorEnvelope(error));
109
+ else {
110
+ const text = error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` : `Uncaught ${inspect(error)}`;
111
+ io.stderr(`${text}\n\nNode.js v${proc.versions.node}\n`);
112
+ }
94
113
  exitQuietly(proc.exitCode && proc.exitCode !== 0 ? proc.exitCode : 1);
95
114
  };
96
115
 
@@ -125,8 +144,9 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
125
144
  loop,
126
145
  onExit: finish,
127
146
  });
147
+ if (options.ipc && !options.thread) attachProcessChannel(proc, options.ipc, loop);
128
148
  const console = createConsole(proc);
129
- const builtins = createBuiltins({ fs: system.fs, process: proc, loop, system: processSystem, io, console });
149
+ const builtins = createBuiltins({ fs: system.fs, process: proc, loop, system: processSystem, io, console, thread: options.thread, ipc: options.ipc });
130
150
 
131
151
  const globals: Record<string, unknown> = {
132
152
  process: proc,
@@ -140,17 +160,9 @@ export async function startNode(options: NodeOptions): Promise<NodeInstance> {
140
160
  clearImmediate: loop.clearImmediate,
141
161
  fetch: builtins.fetch,
142
162
  };
143
- if (options.installGlobals) {
144
- Object.assign(globalThis, globals, { global: globalThis });
145
- globals.global = globalThis;
146
- } else {
147
- // A per-process view of the global object: reads fall through to the real
148
- // one, Node's own names resolve to this process's.
149
- globals.global = Object.assign(Object.create(globalThis), globals);
150
- }
151
- globals.globalThis = globals.global;
163
+ const scope = installGlobalObject(globals, !!options.installGlobals);
152
164
 
153
- const modules = createModuleSystem({ fs: system.fs, isBuiltin: builtins.isBuiltin, builtin: builtins.get, globals });
165
+ const modules = createModuleSystem({ fs: system.fs, isBuiltin: builtins.isBuiltin, builtin: builtins.get, globals, scope });
154
166
  (modules.Module as unknown as { builtinModules: string[] }).builtinModules = builtins.names;
155
167
  Object.defineProperty(proc, 'mainModule', { get: () => modules.main, configurable: true });
156
168
 
@@ -6,8 +6,9 @@
6
6
  */
7
7
  import { EventEmitterBase } from '../events.js';
8
8
  import { Buffer } from '../buffer.js';
9
+ import { queueCallback } from '../processExit.js';
9
10
 
10
- export const tick = (fn: () => void) => queueMicrotask(fn);
11
+ export const tick = queueCallback;
11
12
 
12
13
  export interface ReadableOptions {
13
14
  highWaterMark?: number;
package/src/node/urlqs.ts CHANGED
@@ -62,7 +62,7 @@ export interface LegacyUrl {
62
62
  href: string;
63
63
  }
64
64
 
65
- export function createUrlModule(qs: Record<string, any>): Record<string, unknown> {
65
+ export function createUrlModule(qs: Record<string, any>, resolvePath: (path: string) => string): Record<string, unknown> {
66
66
  function parse(input: string, parseQueryString = false, slashesDenoteHost = false): LegacyUrl {
67
67
  let rest = input.trim();
68
68
  const out: LegacyUrl = { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: null, path: null, href: '' };
@@ -153,7 +153,15 @@ export function createUrlModule(qs: Record<string, any>): Record<string, unknown
153
153
  if (u.protocol !== 'file:') throw Object.assign(new TypeError('The URL must be of scheme file'), { code: 'ERR_INVALID_URL_SCHEME' });
154
154
  return decodeURIComponent(u.pathname);
155
155
  },
156
- pathToFileURL: (path: string) => new URL('file://' + encodeURI(path).replace(/[?#]/g, encodeURIComponent)),
156
+ // As Node: resolved against the working directory (a relative path never becomes the
157
+ // URL's host), a trailing slash kept, and the characters a pathname would misread escaped.
158
+ pathToFileURL: (path: string) => {
159
+ let resolved = resolvePath(path);
160
+ if (path.endsWith('/') && !resolved.endsWith('/')) resolved += '/';
161
+ const url = new URL('file://');
162
+ url.pathname = resolved.replace(/%/g, '%25').replace(/\\/g, '%5C').replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/\t/g, '%09');
163
+ return url;
164
+ },
157
165
  domainToASCII: (d: string) => d,
158
166
  domainToUnicode: (d: string) => d,
159
167
  urlToHttpOptions: (u: URL) => ({ protocol: u.protocol, hostname: u.hostname, hash: u.hash, search: u.search, pathname: u.pathname, path: u.pathname + u.search, href: u.href, port: u.port ? Number(u.port) : undefined }),
@@ -0,0 +1,151 @@
1
+ /**
2
+ * WASI preview1's numbers and memory layout: errno values, file types, flags, and a
3
+ * view over the module's memory that re-reads `memory.buffer` on every call (the
4
+ * buffer is replaced whenever the module grows its memory).
5
+ */
6
+
7
+ export const ERRNO = {
8
+ SUCCESS: 0,
9
+ ACCES: 2,
10
+ BADF: 8,
11
+ EXIST: 20,
12
+ FAULT: 21,
13
+ INVAL: 28,
14
+ IO: 29,
15
+ ISDIR: 31,
16
+ LOOP: 32,
17
+ NAMETOOLONG: 37,
18
+ NOENT: 44,
19
+ NOSPC: 51,
20
+ NOSYS: 52,
21
+ NOTDIR: 54,
22
+ NOTEMPTY: 55,
23
+ NOTSUP: 58,
24
+ PERM: 63,
25
+ SPIPE: 70,
26
+ NOTCAPABLE: 76,
27
+ } as const;
28
+
29
+ export const FILETYPE = { UNKNOWN: 0, CHARACTER_DEVICE: 2, DIRECTORY: 3, REGULAR_FILE: 4 } as const;
30
+ export const OFLAGS = { CREAT: 1, DIRECTORY: 2, EXCL: 4, TRUNC: 8 } as const;
31
+ export const FDFLAGS = { APPEND: 1 } as const;
32
+ export const WHENCE = { SET: 0, CUR: 1, END: 2 } as const;
33
+ export const CLOCK = { REALTIME: 0, MONOTONIC: 1, PROCESS_CPUTIME: 2, THREAD_CPUTIME: 3 } as const;
34
+
35
+ /** Every right: this runtime does not narrow capabilities per descriptor. */
36
+ export const ALL_RIGHTS = 0x1fffffffn;
37
+
38
+ /** A guest pointer or length outside the module's memory: answered as FAULT. */
39
+ export class Fault extends Error {}
40
+
41
+ /** Run guest-memory access, turning its RangeError into a `Fault` (an fs RangeError is not one). */
42
+ export function guest<T>(fn: () => T): T {
43
+ try {
44
+ return fn();
45
+ } catch (error) {
46
+ throw error instanceof RangeError ? new Fault(error.message) : error;
47
+ }
48
+ }
49
+
50
+ /** Run a syscall body, answering a thrown error as its errno. */
51
+ export function attempt(fn: () => number | void): number {
52
+ try {
53
+ return fn() ?? ERRNO.SUCCESS;
54
+ } catch (error) {
55
+ return errnoOf(error);
56
+ }
57
+ }
58
+
59
+ /** A number as the u64 WASI wants; NaN and infinities are 0. */
60
+ export const u64 = (n: number): bigint => (Number.isFinite(n) ? BigInt(Math.max(0, Math.round(n))) : 0n);
61
+
62
+ /** A Node error code (`ENOENT`) as a WASI errno. */
63
+ export function errnoOf(error: unknown): number {
64
+ if (error instanceof Fault) return ERRNO.FAULT;
65
+ if (error instanceof RangeError) return ERRNO.INVAL; // from fs work: a size or offset it cannot honor
66
+ const code = (error as { code?: string } | null)?.code;
67
+ switch (code) {
68
+ case 'ENOENT':
69
+ return ERRNO.NOENT;
70
+ case 'EEXIST':
71
+ return ERRNO.EXIST;
72
+ case 'EISDIR':
73
+ return ERRNO.ISDIR;
74
+ case 'ENOTDIR':
75
+ return ERRNO.NOTDIR;
76
+ case 'ENOTEMPTY':
77
+ return ERRNO.NOTEMPTY;
78
+ case 'EBADF':
79
+ return ERRNO.BADF;
80
+ case 'EINVAL':
81
+ return ERRNO.INVAL;
82
+ case 'EACCES':
83
+ return ERRNO.ACCES;
84
+ case 'EPERM':
85
+ return ERRNO.PERM;
86
+ case 'ENOSPC':
87
+ return ERRNO.NOSPC;
88
+ case 'ENAMETOOLONG':
89
+ return ERRNO.NAMETOOLONG;
90
+ case 'ELOOP':
91
+ return ERRNO.LOOP;
92
+ default:
93
+ return ERRNO.IO;
94
+ }
95
+ }
96
+
97
+ /** Little-endian access to the module's memory, current as of each call. */
98
+ export class Memory {
99
+ constructor(private readonly memory: () => WebAssembly.Memory) {}
100
+
101
+ get view(): DataView {
102
+ return new DataView(this.memory().buffer);
103
+ }
104
+
105
+ bytes(at: number, length: number): Uint8Array {
106
+ return guest(() => new Uint8Array(this.memory().buffer, at, length));
107
+ }
108
+
109
+ u32(at: number, value: number): void {
110
+ guest(() => this.view.setUint32(at, value, true));
111
+ }
112
+
113
+ u64(at: number, value: bigint): void {
114
+ guest(() => this.view.setBigUint64(at, value, true));
115
+ }
116
+
117
+ text(at: number, length: number): string {
118
+ // a copy: TextDecoder rejects a view over a SharedArrayBuffer
119
+ return new TextDecoder().decode(this.bytes(at, length).slice());
120
+ }
121
+
122
+ /** The buffers an `iovec` array points at (`fd_write`, `fd_read`). */
123
+ iovecs(at: number, count: number): Uint8Array[] {
124
+ return guest(() => {
125
+ const view = this.view;
126
+ const out: Uint8Array[] = [];
127
+ for (let i = 0; i < count; i++) out.push(this.bytes(view.getUint32(at + i * 8, true), view.getUint32(at + i * 8 + 4, true)));
128
+ return out;
129
+ });
130
+ }
131
+
132
+ /** Write strings as WASI lays out argv/environ: a pointer table, then NUL-terminated bytes. */
133
+ strings(values: readonly string[], pointers: number, buffer: number): void {
134
+ guest(() => {
135
+ const view = this.view;
136
+ let at = buffer;
137
+ values.forEach((value, i) => {
138
+ const encoded = new TextEncoder().encode(value + '\0');
139
+ view.setUint32(pointers + i * 4, at, true);
140
+ this.bytes(at, encoded.length).set(encoded);
141
+ at += encoded.length;
142
+ });
143
+ });
144
+ }
145
+
146
+ /** The sizes `args_sizes_get` / `environ_sizes_get` report. */
147
+ sizes(values: readonly string[], countAt: number, bytesAt: number): void {
148
+ this.u32(countAt, values.length);
149
+ this.u32(bytesAt, values.reduce((total, value) => total + new TextEncoder().encode(value).length + 1, 0));
150
+ }
151
+ }