@seanhogg/builderforce-webcontainers-core 2026.10.8 → 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 (281) 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 +22 -4
  57. package/dist/installer/tree.js.map +1 -1
  58. package/dist/installer/wasmBuilds.d.ts +27 -0
  59. package/dist/installer/wasmBuilds.d.ts.map +1 -0
  60. package/dist/installer/wasmBuilds.js +32 -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 +15 -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 -5
  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/workerThreads.d.ts +31 -0
  142. package/dist/node/workerThreads.d.ts.map +1 -0
  143. package/dist/node/workerThreads.js +165 -0
  144. package/dist/node/workerThreads.js.map +1 -0
  145. package/dist/node/zlib.d.ts.map +1 -1
  146. package/dist/node/zlib.js +23 -2
  147. package/dist/node/zlib.js.map +1 -1
  148. package/dist/shell/context.d.ts.map +1 -1
  149. package/dist/shell/context.js +2 -2
  150. package/dist/shell/context.js.map +1 -1
  151. package/dist/shell/devHandoff.d.ts +10 -4
  152. package/dist/shell/devHandoff.d.ts.map +1 -1
  153. package/dist/shell/devHandoff.js +7 -5
  154. package/dist/shell/devHandoff.js.map +1 -1
  155. package/dist/shell/exec.d.ts.map +1 -1
  156. package/dist/shell/exec.js +6 -5
  157. package/dist/shell/exec.js.map +1 -1
  158. package/dist/shell/npm.js +2 -2
  159. package/dist/shell/npm.js.map +1 -1
  160. package/dist/shell/program.js +5 -5
  161. package/dist/shell/program.js.map +1 -1
  162. package/dist/styleModules.d.ts +2 -5
  163. package/dist/styleModules.d.ts.map +1 -1
  164. package/dist/styleModules.js +23 -14
  165. package/dist/styleModules.js.map +1 -1
  166. package/dist/styles/compile.d.ts +18 -0
  167. package/dist/styles/compile.d.ts.map +1 -0
  168. package/dist/styles/compile.js +34 -0
  169. package/dist/styles/compile.js.map +1 -0
  170. package/dist/styles/compilers.d.ts +75 -0
  171. package/dist/styles/compilers.d.ts.map +1 -0
  172. package/dist/styles/compilers.js +77 -0
  173. package/dist/styles/compilers.js.map +1 -0
  174. package/dist/styles/cssModules.d.ts +40 -0
  175. package/dist/styles/cssModules.d.ts.map +1 -0
  176. package/dist/styles/cssModules.js +239 -0
  177. package/dist/styles/cssModules.js.map +1 -0
  178. package/dist/styles/imports.d.ts +37 -0
  179. package/dist/styles/imports.d.ts.map +1 -0
  180. package/dist/styles/imports.js +88 -0
  181. package/dist/styles/imports.js.map +1 -0
  182. package/dist/styles/languages.d.ts +13 -0
  183. package/dist/styles/languages.d.ts.map +1 -0
  184. package/dist/styles/languages.js +20 -0
  185. package/dist/styles/languages.js.map +1 -0
  186. package/dist/styles/packageStyles.d.ts +19 -0
  187. package/dist/styles/packageStyles.d.ts.map +1 -0
  188. package/dist/styles/packageStyles.js +32 -0
  189. package/dist/styles/packageStyles.js.map +1 -0
  190. package/dist/svelteCompiler.d.ts.map +1 -1
  191. package/dist/svelteCompiler.js +19 -2
  192. package/dist/svelteCompiler.js.map +1 -1
  193. package/dist/system/commands.d.ts +2 -0
  194. package/dist/system/commands.d.ts.map +1 -1
  195. package/dist/system/commands.js +18 -0
  196. package/dist/system/commands.js.map +1 -1
  197. package/dist/system/index.d.ts +3 -1
  198. package/dist/system/index.d.ts.map +1 -1
  199. package/dist/system/index.js +1 -0
  200. package/dist/system/index.js.map +1 -1
  201. package/dist/system/ipc.d.ts +33 -0
  202. package/dist/system/ipc.d.ts.map +1 -0
  203. package/dist/system/ipc.js +65 -0
  204. package/dist/system/ipc.js.map +1 -0
  205. package/dist/system/kernel.d.ts.map +1 -1
  206. package/dist/system/kernel.js +6 -3
  207. package/dist/system/kernel.js.map +1 -1
  208. package/dist/system/process.d.ts +3 -0
  209. package/dist/system/process.d.ts.map +1 -1
  210. package/dist/system/process.js +50 -26
  211. package/dist/system/process.js.map +1 -1
  212. package/dist/system/terminal.d.ts +10 -4
  213. package/dist/system/terminal.d.ts.map +1 -1
  214. package/dist/system/terminal.js +21 -13
  215. package/dist/system/terminal.js.map +1 -1
  216. package/dist/system/types.d.ts +29 -7
  217. package/dist/system/types.d.ts.map +1 -1
  218. package/dist/vueCompiler.d.ts.map +1 -1
  219. package/dist/vueCompiler.js +11 -8
  220. package/dist/vueCompiler.js.map +1 -1
  221. package/package.json +4 -1
  222. package/src/build.ts +13 -1
  223. package/src/buildHost.ts +23 -10
  224. package/src/compileComponent.ts +4 -1
  225. package/src/compileScript.ts +30 -11
  226. package/src/components.ts +5 -0
  227. package/src/detectProject.ts +13 -6
  228. package/src/devServer.ts +148 -23
  229. package/src/devStyles.ts +70 -0
  230. package/src/hot/client.ts +70 -0
  231. package/src/hot/moduleGraph.ts +90 -0
  232. package/src/hot/planUpdate.ts +66 -0
  233. package/src/hot/reactRefresh.ts +93 -0
  234. package/src/html.ts +13 -19
  235. package/src/index.ts +19 -1
  236. package/src/installer/tree.ts +22 -4
  237. package/src/installer/wasmBuilds.ts +45 -0
  238. package/src/node/builtins.ts +21 -12
  239. package/src/node/childProcess.ts +73 -20
  240. package/src/node/crypto.ts +5 -4
  241. package/src/node/esm.ts +26 -2
  242. package/src/node/fs/index.ts +26 -103
  243. package/src/node/fs/stdinFd.ts +44 -0
  244. package/src/node/fs/streams.ts +177 -0
  245. package/src/node/fs/sync.ts +15 -0
  246. package/src/node/globalObject.ts +82 -0
  247. package/src/node/http/index.ts +4 -3
  248. package/src/node/http/server.ts +8 -5
  249. package/src/node/http/serverResponse.ts +7 -0
  250. package/src/node/ipc.ts +91 -0
  251. package/src/node/loader.ts +78 -14
  252. package/src/node/misc.ts +19 -5
  253. package/src/node/process.ts +15 -8
  254. package/src/node/processExit.ts +21 -0
  255. package/src/node/program.ts +12 -9
  256. package/src/node/runtime.ts +27 -15
  257. package/src/node/stream/readable.ts +2 -1
  258. package/src/node/urlqs.ts +10 -2
  259. package/src/node/workerThreads.ts +198 -0
  260. package/src/node/zlib.ts +24 -2
  261. package/src/shell/context.ts +2 -2
  262. package/src/shell/devHandoff.ts +16 -9
  263. package/src/shell/exec.ts +6 -5
  264. package/src/shell/npm.ts +2 -2
  265. package/src/shell/program.ts +5 -5
  266. package/src/styleModules.ts +30 -14
  267. package/src/styles/compile.ts +43 -0
  268. package/src/styles/compilers.ts +143 -0
  269. package/src/styles/cssModules.ts +254 -0
  270. package/src/styles/imports.ts +125 -0
  271. package/src/styles/languages.ts +29 -0
  272. package/src/styles/packageStyles.ts +35 -0
  273. package/src/svelteCompiler.ts +20 -3
  274. package/src/system/commands.ts +17 -0
  275. package/src/system/index.ts +4 -0
  276. package/src/system/ipc.ts +89 -0
  277. package/src/system/kernel.ts +6 -3
  278. package/src/system/process.ts +57 -30
  279. package/src/system/terminal.ts +34 -12
  280. package/src/system/types.ts +31 -7
  281. package/src/vueCompiler.ts +11 -8
@@ -8,21 +8,22 @@
8
8
  * cut short by the process exiting.
9
9
  */
10
10
  import { EventEmitterBase } from '../events.js';
11
- import { Buffer } from '../buffer.js';
12
- import { Readable } from '../stream/readable.js';
13
- import { Writable } from '../stream/writable.js';
14
11
  import { createSyncFs, type FsContext, type SyncFs } from './sync.js';
12
+ import { createFsStreams } from './streams.js';
15
13
  import { Dirent, Stats, constants } from './stats.js';
16
14
  import { normalizePath } from '../../paths.js';
15
+ import { queueCallback } from '../processExit.js';
16
+ import type { StdinRead } from './stdinFd.js';
17
17
 
18
18
  export interface FsModuleContext extends FsContext {
19
19
  /** Keep the process alive (a watcher is open); call the result to let go. */
20
20
  hold(): () => void;
21
+ /** fd 0 for `fs.read`: this process's stdin (stdinFd.ts). */
22
+ readStdin?: StdinRead;
21
23
  }
22
24
 
23
25
  type Fn = (...args: any[]) => any;
24
26
 
25
- const CHUNK = 64 * 1024;
26
27
 
27
28
  function lastCallback(args: unknown[]): Fn | undefined {
28
29
  return typeof args[args.length - 1] === 'function' ? (args.pop() as Fn) : undefined;
@@ -34,7 +35,7 @@ export function createFsModule(ctx: FsModuleContext): Record<string, any> {
34
35
  const toCallback = (fn: Fn, shape: (result: any, args: any[]) => any[] = (r) => [r]) =>
35
36
  (...args: any[]) => {
36
37
  const cb = lastCallback(args);
37
- queueMicrotask(() => {
38
+ queueCallback(() => {
38
39
  let result: unknown;
39
40
  try {
40
41
  result = fn(...args);
@@ -48,101 +49,7 @@ export function createFsModule(ctx: FsModuleContext): Record<string, any> {
48
49
 
49
50
  const toPromise = (fn: Fn) => async (...args: any[]) => fn(...args);
50
51
 
51
- class ReadStream extends Readable {
52
- bytesRead = 0;
53
- readonly path: string;
54
- fd: number | null = null;
55
- pending = true;
56
- private data?: Uint8Array;
57
- private offset: number;
58
- private readonly endAt: number;
59
-
60
- constructor(path: string | URL, options: { start?: number; end?: number; encoding?: string; highWaterMark?: number; fd?: number } | string = {}) {
61
- const opts = typeof options === 'string' ? { encoding: options } : options;
62
- super({ highWaterMark: opts.highWaterMark ?? CHUNK, encoding: opts.encoding });
63
- this.path = typeof options === 'object' && opts.fd !== undefined ? '' : sync._resolve(path);
64
- this.offset = opts.start ?? 0;
65
- this.endAt = opts.end ?? Infinity;
66
- queueMicrotask(() => {
67
- try {
68
- const contents = sync.readFileSync(this.path) as Buffer;
69
- this.data = contents;
70
- this.fd = -1;
71
- this.pending = false;
72
- this.emit('open', this.fd);
73
- this.emit('ready');
74
- this._pull();
75
- } catch (error) {
76
- this.destroy(error as Error);
77
- }
78
- });
79
- }
80
-
81
- override _read(): void {
82
- if (!this.data) {
83
- this._readableState.reading = false; // retried once the file is loaded
84
- return;
85
- }
86
- const end = Math.min(this.data.length, this.endAt + 1);
87
- if (this.offset >= end) {
88
- this.push(null);
89
- return;
90
- }
91
- const chunk = this.data.subarray(this.offset, Math.min(end, this.offset + this._readableState.highWaterMark));
92
- this.offset += chunk.length;
93
- this.bytesRead += chunk.length;
94
- this.push(Buffer.from(chunk));
95
- }
96
-
97
- close(callback?: Fn): void {
98
- this.destroy();
99
- if (callback) this.once('close', callback);
100
- }
101
- }
102
-
103
- class WriteStream extends Writable {
104
- bytesWritten = 0;
105
- readonly path: string;
106
- pending = false;
107
- private started = false;
108
-
109
- constructor(path: string | URL, private readonly options: { flags?: string; encoding?: string } | string = {}) {
110
- super({ decodeStrings: true });
111
- this.path = sync._resolve(path);
112
- queueMicrotask(() => {
113
- try {
114
- this.open();
115
- this.emit('open', -1);
116
- this.emit('ready');
117
- } catch (error) {
118
- this.destroy(error as Error);
119
- }
120
- });
121
- }
122
-
123
- private open(): void {
124
- if (this.started) return;
125
- this.started = true;
126
- const flags = typeof this.options === 'object' ? this.options.flags ?? 'w' : 'w';
127
- if (!flags.startsWith('a') || !ctx.vfs.isFile(this.path)) sync.writeFileSync(this.path, '', { flag: flags.includes('x') ? 'wx' : 'w' });
128
- }
129
-
130
- override _write(chunk: Buffer, _encoding: string, callback: (error?: Error | null) => void): void {
131
- try {
132
- this.open();
133
- sync.appendFileSync(this.path, chunk);
134
- this.bytesWritten += chunk.length;
135
- callback();
136
- } catch (error) {
137
- callback(error as Error);
138
- }
139
- }
140
-
141
- close(callback?: Fn): void {
142
- this.end();
143
- if (callback) this.once('close', callback);
144
- }
145
- }
52
+ const { ReadStream, WriteStream } = createFsStreams(sync, ctx);
146
53
 
147
54
  class FSWatcher extends EventEmitterBase {
148
55
  private readonly release: () => void;
@@ -217,11 +124,25 @@ export function createFsModule(ctx: FsModuleContext): Record<string, any> {
217
124
  if (!name.endsWith('Sync')) continue;
218
125
  const base = name.slice(0, -4);
219
126
  const fn = (sync as unknown as Record<string, Fn>)[name]!;
220
- if (base === 'exists') fs.exists = (p: string, cb: Fn) => queueMicrotask(() => cb(sync.existsSync(p)));
221
- else if (base === 'read') fs.read = toCallback(fn, (n, args) => [n, args[1]]);
222
- else if (base === 'write') fs.write = toCallback(fn, (n, args) => [n, args[1]]);
127
+ if (base === 'exists') fs.exists = (p: string, cb: Fn) => queueCallback(() => cb(sync.existsSync(p)));
128
+ // (err, bytes, buffer|buffers), as Node's callbacks report them.
129
+ else if (['read', 'write', 'readv', 'writev'].includes(base)) fs[base] = toCallback(fn, (n, args) => [n, args[1]]);
223
130
  else fs[base] = toCallback(fn);
224
131
  }
132
+ const readFile = fs.read;
133
+ // `fs.read(0, …)` reads stdin: it waits for input instead of failing with EBADF.
134
+ fs.read = (fd: number, ...args: any[]) => {
135
+ if (fd !== 0 || !ctx.readStdin) return readFile(fd, ...args);
136
+ const cb = lastCallback(args);
137
+ const options = args[0] && !ArrayBuffer.isView(args[0]) ? args[0] : typeof args[1] === 'object' && args[1] ? { buffer: args[0], ...args[1] } : { buffer: args[0], offset: args[1], length: args[2] };
138
+ const buffer = options.buffer as ArrayBufferView;
139
+ const offset = Number(options.offset ?? 0);
140
+ const length = Number(options.length ?? buffer.byteLength - offset);
141
+ void ctx.readStdin(new Uint8Array(buffer.buffer, buffer.byteOffset + offset, length)).then(
142
+ (count) => queueCallback(() => cb?.(null, count, buffer)),
143
+ (error: unknown) => queueCallback(() => cb?.(error, 0, buffer)),
144
+ );
145
+ };
225
146
  fs.realpath.native = fs.realpath;
226
147
  fs.createReadStream = (path: string, options?: object | string) => new ReadStream(path, options as object);
227
148
  fs.createWriteStream = (path: string, options?: object | string) => new WriteStream(path, options as object);
@@ -248,6 +169,8 @@ function fileHandle(sync: SyncFs, fd: number, path: string) {
248
169
  appendFile: async (data: string | Uint8Array) => void sync.appendFileSync(path, data),
249
170
  read: async (buffer: Uint8Array, offset?: number, length?: number, position?: number | null) => ({ bytesRead: sync.readSync(fd, buffer, offset, length, position), buffer }),
250
171
  write: async (data: string | Uint8Array, ...rest: any[]) => ({ bytesWritten: sync.writeSync(fd, data, ...rest), buffer: data }),
172
+ writev: async (buffers: Uint8Array[], position?: number | null) => ({ bytesWritten: sync.writevSync(fd, buffers, position), buffers }),
173
+ readv: async (buffers: Uint8Array[], position?: number | null) => ({ bytesRead: sync.readvSync(fd, buffers, position), buffers }),
251
174
  stat: async () => sync.fstatSync(fd),
252
175
  truncate: async (length?: number) => sync.ftruncateSync(fd, length),
253
176
  sync: async () => undefined,
@@ -0,0 +1,44 @@
1
+ /**
2
+ * fd 0 as a file: `fs.read(0, buffer, …, callback)` waits for the process's stdin
3
+ * and fills the buffer from it, as on a pipe. Go's WebAssembly runtime reads its
4
+ * input this way (esbuild-wasm's service process, which Vite drives).
5
+ */
6
+ import type { ProgramIO } from '../../system/types.js';
7
+
8
+ /** Read up to `into.length` bytes of stdin; resolves 0 at end of input. */
9
+ export type StdinRead = (into: Uint8Array) => Promise<number>;
10
+
11
+ export function createStdinRead(io: ProgramIO, hold: () => () => void): StdinRead {
12
+ const chunks: Uint8Array[] = [];
13
+ let ended = false;
14
+ let wake: Array<() => void> = [];
15
+ let subscribed = false;
16
+
17
+ const subscribe = () => {
18
+ if (subscribed) return;
19
+ subscribed = true;
20
+ io.onStdin((chunk) => {
21
+ if (chunk === null) ended = true;
22
+ else chunks.push(typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk);
23
+ const waiting = wake;
24
+ wake = [];
25
+ for (const resume of waiting) resume();
26
+ });
27
+ };
28
+
29
+ return async (into) => {
30
+ subscribe();
31
+ while (!chunks.length && !ended) {
32
+ const release = hold(); // a pending read keeps the process alive, as Node's does
33
+ await new Promise<void>((resolve) => wake.push(resolve));
34
+ release();
35
+ }
36
+ const head = chunks[0];
37
+ if (!head) return 0;
38
+ const count = Math.min(head.length, into.length);
39
+ into.set(head.subarray(0, count));
40
+ if (count === head.length) chunks.shift();
41
+ else chunks[0] = head.subarray(count);
42
+ return count;
43
+ };
44
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * `fs.ReadStream` / `fs.WriteStream`. Both are callable without `new`, as Node's are:
3
+ * graceful-fs (under webpack's cache and many CLIs) subclasses them the pre-class way,
4
+ * `fs$WriteStream.apply(this, arguments)` on an object it made, and replaces `open`.
5
+ */
6
+ import { Buffer } from '../buffer.js';
7
+ import { callable } from '../callable.js';
8
+ import { initReadable, Readable } from '../stream/readable.js';
9
+ import { initWritable, Writable } from '../stream/writable.js';
10
+ import { queueCallback } from '../processExit.js';
11
+ import type { FsContext, SyncFs } from './sync.js';
12
+
13
+ type Fn = (...args: any[]) => any;
14
+ type ReadOptions = { start?: number; end?: number; encoding?: string; highWaterMark?: number; fd?: number; flags?: string; mode?: number };
15
+ type WriteOptions = { flags?: string; encoding?: string; mode?: number };
16
+
17
+ const CHUNK = 64 * 1024;
18
+
19
+ const optionsOf = <T extends { encoding?: string }>(options: T | string | undefined): T => (typeof options === 'string' ? ({ encoding: options } as T) : options ?? ({} as T));
20
+
21
+ export interface FsStreams {
22
+ ReadStream: new (path: string | URL, options?: ReadOptions | string) => Readable;
23
+ WriteStream: new (path: string | URL, options?: WriteOptions | string) => Writable;
24
+ }
25
+
26
+ export function createFsStreams(sync: SyncFs, ctx: FsContext): FsStreams {
27
+ class ReadStream extends Readable {
28
+ declare bytesRead: number;
29
+ declare path: string;
30
+ declare fd: number | null;
31
+ declare flags: string;
32
+ declare mode: number;
33
+ declare pending: boolean;
34
+ declare data?: Uint8Array;
35
+ declare offset: number;
36
+ declare endAt: number;
37
+
38
+ constructor(path: string | URL, options?: ReadOptions | string) {
39
+ const opts = optionsOf(options);
40
+ super({ highWaterMark: opts.highWaterMark ?? CHUNK, encoding: opts.encoding });
41
+ startRead(this, path, opts);
42
+ }
43
+
44
+ /** Node's legacy hook; a subclass that replaces it opens the file itself. */
45
+ open(): void {}
46
+
47
+ override _read(): void {
48
+ if (!this.data) {
49
+ this._readableState.reading = false; // retried once the file is loaded
50
+ return;
51
+ }
52
+ const end = Math.min(this.data.length, this.endAt + 1);
53
+ if (this.offset >= end) {
54
+ this.push(null);
55
+ return;
56
+ }
57
+ const chunk = this.data.subarray(this.offset, Math.min(end, this.offset + this._readableState.highWaterMark));
58
+ this.offset += chunk.length;
59
+ this.bytesRead += chunk.length;
60
+ this.push(Buffer.from(chunk));
61
+ }
62
+
63
+ close(callback?: Fn): void {
64
+ this.destroy();
65
+ if (callback) this.once('close', callback);
66
+ }
67
+ }
68
+
69
+ function startRead(self: ReadStream, path: string | URL, opts: ReadOptions): void {
70
+ self.bytesRead = 0;
71
+ self.fd = null;
72
+ self.pending = true;
73
+ self.flags = opts.flags ?? 'r';
74
+ self.mode = opts.mode ?? 0o666;
75
+ self.path = opts.fd !== undefined ? '' : sync._resolve(path);
76
+ self.offset = opts.start ?? 0;
77
+ self.endAt = opts.end ?? Infinity;
78
+ queueCallback(() => {
79
+ try {
80
+ self.data = sync.readFileSync(self.path) as Buffer;
81
+ self.pending = false;
82
+ if (self.open !== ReadStream.prototype.open) self.open();
83
+ else {
84
+ self.fd = -1;
85
+ self.emit('open', self.fd);
86
+ self.emit('ready');
87
+ }
88
+ self._pull();
89
+ } catch (error) {
90
+ self.destroy(error as Error);
91
+ }
92
+ });
93
+ }
94
+
95
+ class WriteStream extends Writable {
96
+ declare bytesWritten: number;
97
+ declare path: string;
98
+ declare fd: number | null;
99
+ declare flags: string;
100
+ declare mode: number;
101
+ declare pending: boolean;
102
+ declare started: boolean;
103
+
104
+ constructor(path: string | URL, options?: WriteOptions | string) {
105
+ super({ decodeStrings: true });
106
+ startWrite(this, path, optionsOf(options));
107
+ }
108
+
109
+ /** Node's legacy hook; a subclass that replaces it opens the file itself. */
110
+ open(): void {}
111
+
112
+ /** Create or truncate the file once, as opening it with `flags` would. */
113
+ ensureFile(): void {
114
+ if (this.started) return;
115
+ this.started = true;
116
+ if (!this.flags.startsWith('a') || !ctx.vfs.isFile(this.path)) sync.writeFileSync(this.path, '', { flag: this.flags.includes('x') ? 'wx' : 'w' });
117
+ }
118
+
119
+ override _write(chunk: Buffer, encoding: string, callback: (error?: Error | null) => void): void {
120
+ // A replaced `open` opens (and truncates) later: writes wait for it, as Node's do.
121
+ if (this.fd === null && this.open !== WriteStream.prototype.open) {
122
+ this.once('open', () => this._write(chunk, encoding, callback));
123
+ return;
124
+ }
125
+ try {
126
+ this.ensureFile();
127
+ sync.appendFileSync(this.path, chunk);
128
+ this.bytesWritten += chunk.length;
129
+ callback();
130
+ } catch (error) {
131
+ callback(error as Error);
132
+ }
133
+ }
134
+
135
+ close(callback?: Fn): void {
136
+ this.end();
137
+ if (callback) this.once('close', callback);
138
+ }
139
+ }
140
+
141
+ function startWrite(self: WriteStream, path: string | URL, opts: WriteOptions): void {
142
+ self.bytesWritten = 0;
143
+ self.fd = null;
144
+ self.pending = false;
145
+ self.started = false;
146
+ self.flags = opts.flags ?? 'w';
147
+ self.mode = opts.mode ?? 0o666;
148
+ self.path = sync._resolve(path);
149
+ queueCallback(() => {
150
+ try {
151
+ if (self.open !== WriteStream.prototype.open) {
152
+ self.started = true; // the replacement opens (and truncates) the file
153
+ self.open();
154
+ return;
155
+ }
156
+ self.ensureFile();
157
+ self.fd = -1;
158
+ self.emit('open', self.fd);
159
+ self.emit('ready');
160
+ } catch (error) {
161
+ self.destroy(error as Error);
162
+ }
163
+ });
164
+ }
165
+
166
+ return {
167
+ ReadStream: callable(ReadStream, (self: ReadStream, path: string | URL, options?: ReadOptions | string) => {
168
+ const opts = optionsOf(options);
169
+ initReadable(self, { highWaterMark: opts.highWaterMark ?? CHUNK, encoding: opts.encoding });
170
+ startRead(self, path, opts);
171
+ }),
172
+ WriteStream: callable(WriteStream, (self: WriteStream, path: string | URL, options?: WriteOptions | string) => {
173
+ initWritable(self, { decodeStrings: true });
174
+ startWrite(self, path, optionsOf(options));
175
+ }),
176
+ };
177
+ }
@@ -311,6 +311,21 @@ export function createSyncFs(ctx: FsContext) {
311
311
  return chunk.length;
312
312
  },
313
313
  writeSync: writeFd,
314
+ // Vectored IO. Without `fs.writev`, tar/fs-minipass fall back to process.binding('fs').
315
+ writevSync(fd: number, buffers: readonly ArrayBufferView[], position?: number | null): number {
316
+ let total = 0;
317
+ for (const buffer of buffers) total += writeFd(fd, buffer, 0, buffer.byteLength, position == null ? null : position + total);
318
+ return total;
319
+ },
320
+ readvSync(fd: number, buffers: readonly ArrayBufferView[], position?: number | null): number {
321
+ let total = 0;
322
+ for (const buffer of buffers) {
323
+ const read = api.readSync(fd, buffer, 0, buffer.byteLength, position == null ? null : position + total);
324
+ total += read;
325
+ if (read < buffer.byteLength) break;
326
+ }
327
+ return total;
328
+ },
314
329
  opendirSync(p: PathLike) {
315
330
  const path = resolve(p);
316
331
  const entries = api.readdirSync(path, { withFileTypes: true }) as Dirent[];
@@ -0,0 +1,82 @@
1
+ /**
2
+ * A process's global object, as its code sees it (`global`, `globalThis`).
3
+ *
4
+ * - In a dedicated worker the real global object is the process's own: Node's
5
+ * names are installed on it.
6
+ * - Where several processes share one realm (tests, the in-process kernel), each
7
+ * gets a view: its own names first, everything else read from the real global
8
+ * WITH the real one as receiver, because host getters (`crypto`, `navigator`)
9
+ * check what `this` is. Code the process compiles with `new Function` sees the
10
+ * same view (esbuild-wasm's launcher compiles Go's loader that way and the two
11
+ * hand `globalThis.Go` and `globalThis.crypto` to each other).
12
+ *
13
+ * Either way, assigning a global works as in Node. A browser's `crypto` (and a
14
+ * host Node's) is a getter with no setter, so `globalThis.crypto = …` (Go's
15
+ * WebAssembly loader, which esbuild-wasm runs) would throw in strict code; Node's
16
+ * own globals let it replace the value.
17
+ *
18
+ * Adds `global` and `globalThis` to `globals` (and, for a view, `Function`), so
19
+ * module code finds them in its outer scope. For a view it returns the `with`
20
+ * scope module code is compiled in, so a bare name another module put on
21
+ * `globalThis` (Go's loader sets `globalThis.fs`, then calls `fs.writeSync`)
22
+ * resolves as it would on a real global.
23
+ */
24
+ export function installGlobalObject(globals: Record<string, unknown>, installOnRealGlobal: boolean): object | undefined {
25
+ makeAssignable(globalThis, ['crypto', 'performance', 'navigator']);
26
+ if (installOnRealGlobal) {
27
+ Object.assign(globalThis, globals, { global: globalThis });
28
+ globals.global = globals.globalThis = globalThis;
29
+ return undefined;
30
+ }
31
+ const own = Object.assign(Object.create(globalThis), globals) as Record<PropertyKey, unknown>;
32
+ const view: Record<PropertyKey, unknown> = new Proxy(own, {
33
+ get: (target, key) => (Object.hasOwn(target, key) ? target[key as string] : Reflect.get(globalThis, key)),
34
+ // An assignment lands on this process's view: never on the shared real global, and
35
+ // never refused by a getter-only accessor inherited from it.
36
+ set: (target, key, value) => Reflect.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true }),
37
+ // Redefining an inherited global without a value (`defineProperty(globalThis, 'crypto',
38
+ // { writable: true })`) keeps the value it had, as it would on the real global.
39
+ defineProperty: (target, key, descriptor) =>
40
+ Reflect.defineProperty(target, key, Object.hasOwn(target, key) || 'value' in descriptor || descriptor.get || descriptor.set ? descriptor : { value: Reflect.get(globalThis, key), ...descriptor }),
41
+ });
42
+ // For `with`: claims only the view's own names, so everything else falls through to the real global.
43
+ const scope = new Proxy(view, {
44
+ has: (_target, key) => typeof key === 'string' && Object.hasOwn(own, key),
45
+ get: (target, key) => (key === Symbol.unscopables ? undefined : Reflect.get(target, key)),
46
+ });
47
+ const scopedFunction = createScopedFunction(scope);
48
+ own.global = own.globalThis = view;
49
+ own.Function = scopedFunction;
50
+ globals.global = globals.globalThis = view;
51
+ globals.Function = scopedFunction;
52
+ return scope;
53
+ }
54
+
55
+ /**
56
+ * `Function` whose compiled code resolves free names through `scope` (the view's
57
+ * own names, then the real global), as code compiled in a process's own realm would.
58
+ */
59
+ function createScopedFunction(scope: object): FunctionConstructor {
60
+ const compile = (args: unknown[]) => {
61
+ const params = args.slice(0, -1).map(String).join(', ');
62
+ const body = args.length ? String(args[args.length - 1]) : '';
63
+ // Sloppy outer function: `with` routes free names through the view; the body may still be strict.
64
+ return new Function('__bfwc_scope', `with (__bfwc_scope) { return function anonymous(${params}\n) {\n${body}\n}; }`)(scope);
65
+ };
66
+ return new Proxy(Function, { apply: (_target, _this, args) => compile(args), construct: (_target, args) => compile(args) });
67
+ }
68
+
69
+ /** Give each getter-only global (own or inherited) a writable own value, as Node's are. */
70
+ function makeAssignable(target: object, names: readonly string[]): void {
71
+ for (const name of names) {
72
+ let holder: object | null = target;
73
+ let descriptor: PropertyDescriptor | undefined;
74
+ while (holder && !(descriptor = Object.getOwnPropertyDescriptor(holder, name))) holder = Object.getPrototypeOf(holder);
75
+ if (!descriptor || descriptor.set || 'value' in descriptor) continue;
76
+ try {
77
+ Object.defineProperty(target, name, { value: Reflect.get(target, name), writable: true, enumerable: true, configurable: true });
78
+ } catch {
79
+ // a non-configurable own accessor: leave it as the host made it
80
+ }
81
+ }
82
+ }
@@ -9,6 +9,7 @@ import { ClientRequest, createFetch, type ClientDeps } from './client.js';
9
9
  import { FakeSocket, IncomingMessage, OutgoingHeaders, Server, ServerResponse } from './server.js';
10
10
  import { METHODS, STATUS_CODES } from './status.js';
11
11
  import { textResponse } from '../../system/httpStream.js';
12
+ import { queueCallback } from '../processExit.js';
12
13
 
13
14
  export { createFetch };
14
15
 
@@ -77,12 +78,12 @@ export function createNetModule(deps: ClientDeps): Record<string, unknown> {
77
78
  try {
78
79
  this.reservation = deps.system.listen(port, async () => textResponse(502, 'Not an HTTP server'));
79
80
  } catch (error) {
80
- queueMicrotask(() => this.emit('error', error));
81
+ queueCallback(() => this.emit('error', error));
81
82
  return this;
82
83
  }
83
84
  this.listening = true;
84
85
  this.release = deps.loop.hold();
85
- queueMicrotask(() => this.emit('listening'));
86
+ queueCallback(() => this.emit('listening'));
86
87
  return this;
87
88
  }
88
89
  address() {
@@ -94,7 +95,7 @@ export function createNetModule(deps: ClientDeps): Record<string, unknown> {
94
95
  this.listening = false;
95
96
  this.release?.();
96
97
  if (callback) this.once('close', callback);
97
- queueMicrotask(() => this.emit('close'));
98
+ queueCallback(() => this.emit('close'));
98
99
  return this;
99
100
  }
100
101
  ref(): this { return this; }
@@ -14,6 +14,7 @@ import { pushStream } from '../../system/httpStream.js';
14
14
  import { FakeSocket, IncomingMessage } from './messages.js';
15
15
  import { ServerResponse } from './serverResponse.js';
16
16
  import { UpgradeSocket } from './upgradeSocket.js';
17
+ import { queueCallback } from '../processExit.js';
17
18
 
18
19
  export { FakeSocket, IncomingMessage, OutgoingHeaders } from './messages.js';
19
20
  export { ServerResponse } from './serverResponse.js';
@@ -48,12 +49,12 @@ export class Server extends EventEmitterBase {
48
49
  try {
49
50
  this.registration = this.deps.system.listen(port, (request) => this.handle(request), (request, socket) => this.upgrade(request, socket));
50
51
  } catch (error) {
51
- queueMicrotask(() => this.emit('error', error));
52
+ queueCallback(() => this.emit('error', error));
52
53
  return this;
53
54
  }
54
55
  this.listening = true;
55
56
  this.release = this.deps.loop.hold();
56
- queueMicrotask(() => this.emit('listening'));
57
+ queueCallback(() => this.emit('listening'));
57
58
  return this;
58
59
  }
59
60
 
@@ -63,7 +64,7 @@ export class Server extends EventEmitterBase {
63
64
 
64
65
  close(callback?: (error?: Error) => void): this {
65
66
  if (!this.registration) {
66
- if (callback) queueMicrotask(() => callback(Object.assign(new Error('Server is not running.'), { code: 'ERR_SERVER_NOT_RUNNING' })));
67
+ if (callback) queueCallback(() => callback(Object.assign(new Error('Server is not running.'), { code: 'ERR_SERVER_NOT_RUNNING' })));
67
68
  return this;
68
69
  }
69
70
  this.registration.close();
@@ -72,7 +73,7 @@ export class Server extends EventEmitterBase {
72
73
  this.release?.();
73
74
  this.release = undefined;
74
75
  if (callback) this.once('close', callback);
75
- queueMicrotask(() => this.emit('close'));
76
+ queueCallback(() => this.emit('close'));
76
77
  return this;
77
78
  }
78
79
 
@@ -100,7 +101,9 @@ export class Server extends EventEmitterBase {
100
101
  const req = new IncomingMessage(socket);
101
102
  req.method = request.method.toUpperCase();
102
103
  req.url = request.url;
103
- req._fill(headers, body);
104
+ // HTTP/1.1 always names the host; servers check it (Vite's `allowedHosts` answers 403 without it).
105
+ const named = Object.keys(headers).some((k) => k.toLowerCase() === 'host');
106
+ req._fill(named ? headers : { ...headers, host: `localhost:${socket.localPort}` }, body);
104
107
  return req;
105
108
  }
106
109
 
@@ -55,6 +55,13 @@ export class ServerResponse extends OutgoingHeaders {
55
55
  override flushHeaders(): void {
56
56
  this.sendHead();
57
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
+ }
58
65
  writeContinue(): void {}
59
66
  writeProcessing(): void {}
60
67
  writeEarlyHints(): void {}