@seanhogg/builderforce-webcontainers-core 2026.10.9 → 2026.10.11

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 (47) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/installer/tree.d.ts.map +1 -1
  6. package/dist/installer/tree.js +12 -5
  7. package/dist/installer/tree.js.map +1 -1
  8. package/dist/installer/wasmBuilds.d.ts +13 -6
  9. package/dist/installer/wasmBuilds.d.ts.map +1 -1
  10. package/dist/installer/wasmBuilds.js +17 -8
  11. package/dist/installer/wasmBuilds.js.map +1 -1
  12. package/dist/node/builtins.d.ts.map +1 -1
  13. package/dist/node/builtins.js +2 -0
  14. package/dist/node/builtins.js.map +1 -1
  15. package/dist/node/misc.d.ts.map +1 -1
  16. package/dist/node/misc.js +0 -1
  17. package/dist/node/misc.js.map +1 -1
  18. package/dist/node/wasi/abi.d.ts +82 -0
  19. package/dist/node/wasi/abi.d.ts.map +1 -0
  20. package/dist/node/wasi/abi.js +144 -0
  21. package/dist/node/wasi/abi.js.map +1 -0
  22. package/dist/node/wasi/files.d.ts +67 -0
  23. package/dist/node/wasi/files.d.ts.map +1 -0
  24. package/dist/node/wasi/files.js +319 -0
  25. package/dist/node/wasi/files.js.map +1 -0
  26. package/dist/node/wasi/index.d.ts +17 -0
  27. package/dist/node/wasi/index.d.ts.map +1 -0
  28. package/dist/node/wasi/index.js +129 -0
  29. package/dist/node/wasi/index.js.map +1 -0
  30. package/dist/rootedFs.d.ts +19 -0
  31. package/dist/rootedFs.d.ts.map +1 -0
  32. package/dist/rootedFs.js +97 -0
  33. package/dist/rootedFs.js.map +1 -0
  34. package/dist/shell/devHandoff.d.ts.map +1 -1
  35. package/dist/shell/devHandoff.js +3 -1
  36. package/dist/shell/devHandoff.js.map +1 -1
  37. package/package.json +1 -1
  38. package/src/index.ts +1 -0
  39. package/src/installer/tree.ts +13 -4
  40. package/src/installer/wasmBuilds.ts +24 -9
  41. package/src/node/builtins.ts +2 -0
  42. package/src/node/misc.ts +0 -1
  43. package/src/node/wasi/abi.ts +151 -0
  44. package/src/node/wasi/files.ts +350 -0
  45. package/src/node/wasi/index.ts +149 -0
  46. package/src/rootedFs.ts +108 -0
  47. package/src/shell/devHandoff.ts +3 -1
@@ -0,0 +1,350 @@
1
+ /**
2
+ * WASI file descriptors over the process's `fs`: stdio on 0–2, one descriptor per
3
+ * preopened directory from 3, and the files and directories `path_open` opens
4
+ * relative to them. Every call answers a WASI errno and writes its results into the
5
+ * module's memory.
6
+ */
7
+ import { normalizePath } from '../../paths.js';
8
+ import { ALL_RIGHTS, ERRNO, FDFLAGS, FILETYPE, Memory, OFLAGS, WHENCE, attempt, errnoOf, guest, u64 } from './abi.js';
9
+
10
+ /** The slice of Node's `fs` this needs; the process's own module satisfies it. */
11
+ export interface WasiFs {
12
+ statSync(path: string, options?: { throwIfNoEntry?: boolean }): WasiStat | undefined;
13
+ fstatSync(fd: number): WasiStat;
14
+ /** `flags` as Node's string form: `'r+'` reads and writes, `'w+'` creates or truncates (`'wx+'`: and fails if it exists). */
15
+ openSync(path: string, flags: string): number;
16
+ /** Always at an explicit `position`: the cursor is the descriptor's own. */
17
+ readSync(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number;
18
+ writeSync(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number;
19
+ ftruncateSync(fd: number, length: number): void;
20
+ closeSync(fd: number): void;
21
+ readdirSync(path: string, options: { withFileTypes: true }): Array<{ name: string; isDirectory(): boolean }>;
22
+ mkdirSync(path: string): void;
23
+ rmdirSync(path: string): void;
24
+ unlinkSync(path: string): void;
25
+ renameSync(from: string, to: string): void;
26
+ }
27
+
28
+ interface WasiStat {
29
+ isDirectory(): boolean;
30
+ size: number;
31
+ mtimeMs: number;
32
+ ino?: number;
33
+ }
34
+
35
+ export interface WasiStdio {
36
+ stdout(bytes: Uint8Array): void;
37
+ stderr(bytes: Uint8Array): void;
38
+ }
39
+
40
+ interface Descriptor {
41
+ kind: 'stdio' | 'dir' | 'file';
42
+ /** Absolute path in the file system (directories and files). */
43
+ path: string;
44
+ /** The preopened directory this descends from: paths never leave it. */
45
+ root: string;
46
+ /** The guest-visible name of a preopened directory. */
47
+ preopen?: string;
48
+ /** The process fs's descriptor behind a file. */
49
+ host?: number;
50
+ position: number;
51
+ append: boolean;
52
+ }
53
+
54
+ const FILESTAT_SIZE = 64;
55
+
56
+ export function createWasiFiles(fs: WasiFs, stdio: WasiStdio, memory: Memory, preopens: Record<string, string>) {
57
+ const fds = new Map<number, Descriptor>([
58
+ [0, { kind: 'stdio', path: '', root: '', position: 0, append: false }],
59
+ [1, { kind: 'stdio', path: '', root: '', position: 0, append: false }],
60
+ [2, { kind: 'stdio', path: '', root: '', position: 0, append: false }],
61
+ ]);
62
+ let nextFd = 3;
63
+ for (const [guest, host] of Object.entries(preopens)) {
64
+ const path = normalizePath(host);
65
+ fds.set(nextFd++, { kind: 'dir', path, root: path, preopen: guest, position: 0, append: false });
66
+ }
67
+
68
+ const resolveAt = (dirFd: number, at: number, length: number): string | number => {
69
+ const dir = fds.get(dirFd);
70
+ if (!dir) return ERRNO.BADF;
71
+ if (dir.kind !== 'dir') return ERRNO.NOTDIR;
72
+ let relative: string;
73
+ try {
74
+ relative = memory.text(at, length);
75
+ } catch (error) {
76
+ return errnoOf(error);
77
+ }
78
+ if (relative.startsWith('/')) return ERRNO.NOTCAPABLE;
79
+ const path = normalizePath(`${dir.path}/${relative}`);
80
+ return path === dir.root || path.startsWith(dir.root === '/' ? '/' : `${dir.root}/`) ? path : ERRNO.NOTCAPABLE;
81
+ };
82
+
83
+ const writeFilestat = (at: number, stat: WasiStat, kind?: number) =>
84
+ guest(() => {
85
+ const view = memory.view;
86
+ memory.bytes(at, FILESTAT_SIZE).fill(0);
87
+ view.setBigUint64(at + 8, u64(stat.ino ?? 0), true);
88
+ view.setUint8(at + 16, kind ?? (stat.isDirectory() ? FILETYPE.DIRECTORY : FILETYPE.REGULAR_FILE));
89
+ view.setBigUint64(at + 24, 1n, true);
90
+ view.setBigUint64(at + 32, u64(stat.size), true);
91
+ const time = u64(stat.mtimeMs) * 1_000_000n;
92
+ for (const offset of [40, 48, 56]) view.setBigUint64(at + offset, time, true);
93
+ });
94
+
95
+ /** One fs read into a scratch buffer, scattered across the iovecs. */
96
+ const readInto = (file: Descriptor, buffers: Uint8Array[], position: number): number => {
97
+ const scratch = new Uint8Array(buffers.reduce((sum, b) => sum + b.length, 0));
98
+ const n = fs.readSync(file.host!, scratch, 0, scratch.length, position);
99
+ let at = 0;
100
+ for (const buffer of buffers) {
101
+ buffer.set(scratch.subarray(at, Math.min(n, at + buffer.length)));
102
+ at += buffer.length;
103
+ if (at >= n) break;
104
+ }
105
+ return n;
106
+ };
107
+
108
+ const writeFrom = (file: Descriptor, buffers: Uint8Array[], position: number): number => {
109
+ const bytes = concat(buffers);
110
+ return fs.writeSync(file.host!, bytes, 0, bytes.length, position);
111
+ };
112
+
113
+ return {
114
+ /** Close every host descriptor and forget them all (the module has finished). */
115
+ closeAll(): void {
116
+ for (const file of fds.values()) {
117
+ try {
118
+ if (file.host !== undefined) fs.closeSync(file.host);
119
+ } catch {
120
+ // already gone
121
+ }
122
+ }
123
+ fds.clear();
124
+ },
125
+
126
+ fd_write(fd: number, iovs: number, count: number, written: number): number {
127
+ const file = fds.get(fd);
128
+ if (!file) return ERRNO.BADF;
129
+ return attempt(() => {
130
+ const buffers = memory.iovecs(iovs, count);
131
+ let n: number;
132
+ if (file.kind === 'stdio') {
133
+ const bytes = concat(buffers);
134
+ if (fd === 1) stdio.stdout(bytes);
135
+ else if (fd === 2) stdio.stderr(bytes);
136
+ else return ERRNO.BADF;
137
+ n = bytes.length;
138
+ } else if (file.kind === 'file') {
139
+ const at = file.append ? fs.fstatSync(file.host!).size : file.position;
140
+ n = writeFrom(file, buffers, at);
141
+ file.position = at + n;
142
+ } else return ERRNO.ISDIR;
143
+ memory.u32(written, n);
144
+ });
145
+ },
146
+
147
+ fd_pwrite(fd: number, iovs: number, count: number, offset: bigint, written: number): number {
148
+ const file = fds.get(fd);
149
+ if (!file || file.kind !== 'file') return file ? ERRNO.INVAL : ERRNO.BADF;
150
+ return attempt(() => memory.u32(written, writeFrom(file, memory.iovecs(iovs, count), Number(offset))));
151
+ },
152
+
153
+ fd_read(fd: number, iovs: number, count: number, read: number): number {
154
+ const file = fds.get(fd);
155
+ if (!file) return ERRNO.BADF;
156
+ return attempt(() => {
157
+ // stdin reads as end of input: a WASI module cannot wait on the event loop.
158
+ const n = file.kind === 'file' ? readInto(file, memory.iovecs(iovs, count), file.position) : file.kind === 'stdio' ? 0 : -1;
159
+ if (n < 0) return ERRNO.ISDIR;
160
+ file.position += n;
161
+ memory.u32(read, n);
162
+ });
163
+ },
164
+
165
+ fd_pread(fd: number, iovs: number, count: number, offset: bigint, read: number): number {
166
+ const file = fds.get(fd);
167
+ if (!file || file.kind !== 'file') return file ? ERRNO.INVAL : ERRNO.BADF;
168
+ return attempt(() => memory.u32(read, readInto(file, memory.iovecs(iovs, count), Number(offset))));
169
+ },
170
+
171
+ fd_seek(fd: number, offset: bigint, whence: number, result: number): number {
172
+ const file = fds.get(fd);
173
+ if (!file) return ERRNO.BADF;
174
+ if (file.kind === 'stdio') return ERRNO.SPIPE;
175
+ if (file.kind !== 'file') return ERRNO.INVAL;
176
+ return attempt(() => {
177
+ const base = whence === WHENCE.SET ? 0 : whence === WHENCE.CUR ? file.position : whence === WHENCE.END ? fs.fstatSync(file.host!).size : -1;
178
+ if (base < 0 || base + Number(offset) < 0) return ERRNO.INVAL;
179
+ file.position = base + Number(offset);
180
+ memory.u64(result, BigInt(file.position));
181
+ });
182
+ },
183
+
184
+ fd_tell(fd: number, result: number): number {
185
+ const file = fds.get(fd);
186
+ if (!file) return ERRNO.BADF;
187
+ if (file.kind === 'stdio') return ERRNO.SPIPE;
188
+ return attempt(() => memory.u64(result, BigInt(file.position)));
189
+ },
190
+
191
+ fd_close(fd: number): number {
192
+ const file = fds.get(fd);
193
+ if (!file) return ERRNO.BADF;
194
+ fds.delete(fd);
195
+ return attempt(() => {
196
+ if (file.host !== undefined) fs.closeSync(file.host);
197
+ });
198
+ },
199
+
200
+ fd_fdstat_get(fd: number, at: number): number {
201
+ const file = fds.get(fd);
202
+ if (!file) return ERRNO.BADF;
203
+ return attempt(() =>
204
+ guest(() => {
205
+ const view = memory.view;
206
+ view.setUint8(at, file.kind === 'stdio' ? FILETYPE.CHARACTER_DEVICE : file.kind === 'dir' ? FILETYPE.DIRECTORY : FILETYPE.REGULAR_FILE);
207
+ view.setUint16(at + 2, file.append ? FDFLAGS.APPEND : 0, true);
208
+ view.setBigUint64(at + 8, ALL_RIGHTS, true);
209
+ view.setBigUint64(at + 16, ALL_RIGHTS, true);
210
+ }),
211
+ );
212
+ },
213
+
214
+ fd_fdstat_set_flags(fd: number, flags: number): number {
215
+ const file = fds.get(fd);
216
+ if (!file) return ERRNO.BADF;
217
+ file.append = (flags & FDFLAGS.APPEND) !== 0;
218
+ return ERRNO.SUCCESS;
219
+ },
220
+
221
+ fd_filestat_get(fd: number, at: number): number {
222
+ const file = fds.get(fd);
223
+ if (!file) return ERRNO.BADF;
224
+ if (file.kind === 'stdio') {
225
+ return attempt(() => writeFilestat(at, { isDirectory: () => false, size: 0, mtimeMs: 0 }, FILETYPE.CHARACTER_DEVICE));
226
+ }
227
+ return attempt(() => writeFilestat(at, file.host !== undefined ? fs.fstatSync(file.host) : fs.statSync(file.path)!));
228
+ },
229
+
230
+ fd_filestat_set_size(fd: number, size: bigint): number {
231
+ const file = fds.get(fd);
232
+ if (!file || file.kind !== 'file') return file ? ERRNO.INVAL : ERRNO.BADF;
233
+ return attempt(() => fs.ftruncateSync(file.host!, Number(size)));
234
+ },
235
+
236
+ fd_prestat_get(fd: number, at: number): number {
237
+ const file = fds.get(fd);
238
+ if (!file?.preopen) return ERRNO.BADF;
239
+ return attempt(() =>
240
+ guest(() => {
241
+ memory.view.setUint8(at, 0); // a directory
242
+ memory.view.setUint32(at + 4, new TextEncoder().encode(file.preopen!).length, true);
243
+ }),
244
+ );
245
+ },
246
+
247
+ fd_prestat_dir_name(fd: number, at: number, length: number): number {
248
+ const file = fds.get(fd);
249
+ if (!file?.preopen) return ERRNO.BADF;
250
+ return attempt(() => void memory.bytes(at, length).set(new TextEncoder().encode(file.preopen).subarray(0, length)));
251
+ },
252
+
253
+ fd_readdir(fd: number, buffer: number, length: number, cookie: bigint, used: number): number {
254
+ const dir = fds.get(fd);
255
+ if (!dir) return ERRNO.BADF;
256
+ if (dir.kind !== 'dir') return ERRNO.NOTDIR;
257
+ return attempt(() => {
258
+ const entries = fs.readdirSync(dir.path, { withFileTypes: true });
259
+ let at = 0;
260
+ for (let i = Number(cookie); i < entries.length && at < length; i++) {
261
+ const entry = entries[i]!;
262
+ const name = new TextEncoder().encode(entry.name);
263
+ const record = new Uint8Array(24 + name.length);
264
+ const header = new DataView(record.buffer);
265
+ header.setBigUint64(0, BigInt(i + 1), true);
266
+ header.setUint32(16, name.length, true);
267
+ header.setUint8(20, entry.isDirectory() ? FILETYPE.DIRECTORY : FILETYPE.REGULAR_FILE);
268
+ record.set(name, 24);
269
+ // A record that does not fit is cut short: the caller sees a full buffer and asks again.
270
+ const fits = Math.min(record.length, length - at);
271
+ memory.bytes(buffer + at, fits).set(record.subarray(0, fits));
272
+ at += fits;
273
+ }
274
+ memory.u32(used, at);
275
+ });
276
+ },
277
+
278
+ path_open(dirFd: number, _dirFlags: number, at: number, length: number, oflags: number, _base: bigint, _inheriting: bigint, fdflags: number, result: number): number {
279
+ const path = resolveAt(dirFd, at, length);
280
+ if (typeof path === 'number') return path;
281
+ return attempt(() => {
282
+ const stat = fs.statSync(path, { throwIfNoEntry: false });
283
+ const exclusive = !!(oflags & OFLAGS.EXCL && oflags & OFLAGS.CREAT);
284
+ if (stat && exclusive) return ERRNO.EXIST;
285
+ if (!stat && !(oflags & OFLAGS.CREAT)) return ERRNO.NOENT;
286
+ if (stat?.isDirectory()) {
287
+ if (oflags & OFLAGS.TRUNC) return ERRNO.ISDIR;
288
+ } else if (oflags & OFLAGS.DIRECTORY) return stat ? ERRNO.NOTDIR : ERRNO.NOENT;
289
+ const dir = fds.get(dirFd)!;
290
+ const isDir = !!stat?.isDirectory();
291
+ const fd = nextFd;
292
+ memory.u32(result, fd); // before anything opens: a bad pointer must not leak a descriptor
293
+ const host = isDir ? undefined : fs.openSync(path, exclusive ? 'wx+' : !stat || oflags & OFLAGS.TRUNC ? 'w+' : 'r+');
294
+ nextFd++;
295
+ fds.set(fd, { kind: isDir ? 'dir' : 'file', path, root: dir.root, host, position: 0, append: (fdflags & FDFLAGS.APPEND) !== 0 });
296
+ });
297
+ },
298
+
299
+ path_filestat_get(dirFd: number, _flags: number, at: number, length: number, result: number): number {
300
+ const path = resolveAt(dirFd, at, length);
301
+ if (typeof path === 'number') return path;
302
+ return attempt(() => {
303
+ const stat = fs.statSync(path, { throwIfNoEntry: false });
304
+ if (!stat) return ERRNO.NOENT;
305
+ writeFilestat(result, stat);
306
+ });
307
+ },
308
+
309
+ path_create_directory(dirFd: number, at: number, length: number): number {
310
+ const path = resolveAt(dirFd, at, length);
311
+ return typeof path === 'number' ? path : attempt(() => fs.mkdirSync(path));
312
+ },
313
+
314
+ path_remove_directory(dirFd: number, at: number, length: number): number {
315
+ const path = resolveAt(dirFd, at, length);
316
+ return typeof path === 'number' ? path : attempt(() => fs.rmdirSync(path));
317
+ },
318
+
319
+ path_unlink_file(dirFd: number, at: number, length: number): number {
320
+ const path = resolveAt(dirFd, at, length);
321
+ return typeof path === 'number' ? path : attempt(() => fs.unlinkSync(path));
322
+ },
323
+
324
+ path_rename(fromFd: number, fromAt: number, fromLength: number, toFd: number, toAt: number, toLength: number): number {
325
+ const from = resolveAt(fromFd, fromAt, fromLength);
326
+ const to = resolveAt(toFd, toAt, toLength);
327
+ if (typeof from === 'number') return from;
328
+ if (typeof to === 'number') return to;
329
+ return attempt(() => fs.renameSync(from, to));
330
+ },
331
+
332
+ fd_sync: (fd: number) => (fds.has(fd) ? ERRNO.SUCCESS : ERRNO.BADF),
333
+ fd_datasync: (fd: number) => (fds.has(fd) ? ERRNO.SUCCESS : ERRNO.BADF),
334
+ fd_advise: (fd: number) => (fds.has(fd) ? ERRNO.SUCCESS : ERRNO.BADF),
335
+ fd_allocate: (fd: number) => (fds.has(fd) ? ERRNO.SUCCESS : ERRNO.BADF),
336
+ fd_filestat_set_times: (fd: number) => (fds.has(fd) ? ERRNO.SUCCESS : ERRNO.BADF),
337
+ path_filestat_set_times: () => ERRNO.SUCCESS,
338
+ };
339
+ }
340
+
341
+ function concat(buffers: Uint8Array[]): Uint8Array {
342
+ if (buffers.length === 1) return buffers[0]!.slice();
343
+ const out = new Uint8Array(buffers.reduce((sum, b) => sum + b.length, 0));
344
+ let at = 0;
345
+ for (const b of buffers) {
346
+ out.set(b, at);
347
+ at += b.length;
348
+ }
349
+ return out;
350
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * `node:wasi`: Node's `WASI` class, preview1, over the process's file system and
3
+ * stdio. napi-rs `wasm32-wasip1` bindings (oxc-parser under Nuxt, and others) load
4
+ * through it — single-threaded builds that need no shared memory, so no
5
+ * cross-origin isolation.
6
+ *
7
+ * Imports this does not implement (sockets, `proc_raise`) answer ENOSYS instead of
8
+ * failing instantiation: `wasiImport` holds every preview1 name. `poll_oneoff` reports every subscription ready at once: a
9
+ * WASI call cannot block a process that runs on the event loop.
10
+ */
11
+ import { CLOCK, ERRNO, Memory, attempt, guest, u64 } from './abi.js';
12
+ import { createWasiFiles, type WasiFs } from './files.js';
13
+
14
+ /** Every `wasi_snapshot_preview1` function: a module imports by name, so each must exist (ENOSYS when not implemented). */
15
+ const WASI_FUNCTIONS = [
16
+ 'args_get', 'args_sizes_get', 'environ_get', 'environ_sizes_get', 'clock_res_get', 'clock_time_get', 'fd_advise', 'fd_allocate', 'fd_close', 'fd_datasync',
17
+ 'fd_fdstat_get', 'fd_fdstat_set_flags', 'fd_fdstat_set_rights', 'fd_filestat_get', 'fd_filestat_set_size', 'fd_filestat_set_times', 'fd_pread', 'fd_prestat_get',
18
+ 'fd_prestat_dir_name', 'fd_pwrite', 'fd_read', 'fd_readdir', 'fd_renumber', 'fd_seek', 'fd_sync', 'fd_tell', 'fd_write', 'path_create_directory', 'path_filestat_get',
19
+ 'path_filestat_set_times', 'path_link', 'path_open', 'path_readlink', 'path_remove_directory', 'path_rename', 'path_symlink', 'path_unlink_file', 'poll_oneoff',
20
+ 'proc_exit', 'proc_raise', 'sched_yield', 'random_get', 'sock_accept', 'sock_recv', 'sock_send', 'sock_shutdown',
21
+ ] as const;
22
+
23
+ export interface WasiOptions {
24
+ /** Only `preview1` exists here; `unstable` is rejected. */
25
+ version?: 'preview1';
26
+ args?: string[];
27
+ env?: Record<string, string | undefined>;
28
+ preopens?: Record<string, string>;
29
+ returnOnExit?: boolean;
30
+ }
31
+
32
+ export interface WasiDeps {
33
+ fs: WasiFs;
34
+ stdout(bytes: Uint8Array): void;
35
+ stderr(bytes: Uint8Array): void;
36
+ exit(code: number): void;
37
+ }
38
+
39
+ interface WasiInstance {
40
+ exports: Record<string, unknown> & { memory?: WebAssembly.Memory; _start?: () => void; _initialize?: () => void };
41
+ }
42
+
43
+ const knownClock = (id: number) => id === CLOCK.REALTIME || id === CLOCK.MONOTONIC || id === CLOCK.PROCESS_CPUTIME || id === CLOCK.THREAD_CPUTIME;
44
+
45
+ /** `proc_exit`: unwinds the module's stack back to `start()`. */
46
+ class WasiExit extends Error {
47
+ constructor(readonly code: number) {
48
+ super(`WASI exit ${code}`);
49
+ }
50
+ }
51
+
52
+ export function createWasiModule(deps: WasiDeps): Record<string, unknown> {
53
+ class WASI {
54
+ readonly wasiImport: Record<string, (...args: any[]) => number | void>;
55
+ private memory?: WebAssembly.Memory;
56
+ private readonly returnOnExit: boolean;
57
+ private started = false;
58
+ private readonly closeAll: () => void;
59
+
60
+ constructor(options: WasiOptions = {}) {
61
+ if (options.version !== undefined && options.version !== 'preview1') throw new TypeError(`WASI version "${options.version}" is not supported: only 'preview1' is`);
62
+ this.returnOnExit = options.returnOnExit ?? true;
63
+ const args = options.args ?? [];
64
+ const env = Object.entries(options.env ?? {}).flatMap(([key, value]) => (value === undefined ? [] : [`${key}=${value}`]));
65
+ const memory = new Memory(() => {
66
+ if (!this.memory) throw new Error('WASI: the instance has not been started or initialized');
67
+ return this.memory;
68
+ });
69
+ const { closeAll, ...files } = createWasiFiles(deps.fs, deps, memory, options.preopens ?? {});
70
+ this.closeAll = closeAll;
71
+ const calls: Record<string, (...args: any[]) => number | void> = {
72
+ ...files,
73
+ args_get: (pointers: number, buffer: number) => attempt(() => memory.strings(args, pointers, buffer)),
74
+ args_sizes_get: (count: number, size: number) => attempt(() => memory.sizes(args, count, size)),
75
+ environ_get: (pointers: number, buffer: number) => attempt(() => memory.strings(env, pointers, buffer)),
76
+ environ_sizes_get: (count: number, size: number) => attempt(() => memory.sizes(env, count, size)),
77
+ clock_res_get: (id: number, result: number) => (knownClock(id) ? attempt(() => memory.u64(result, 1000n)) : ERRNO.INVAL),
78
+ clock_time_get: (id: number, _precision: bigint, result: number) =>
79
+ knownClock(id) ? attempt(() => memory.u64(result, id === CLOCK.REALTIME ? u64(Date.now()) * 1_000_000n : u64(performance.now() * 1_000_000))) : ERRNO.INVAL,
80
+ random_get: (buffer: number, length: number) =>
81
+ attempt(() => {
82
+ // Filled outside the module's memory, which may be shared: getRandomValues rejects a view over it.
83
+ for (let at = 0; at < length; at += 65536) {
84
+ const chunk = new Uint8Array(Math.min(65536, length - at));
85
+ crypto.getRandomValues(chunk);
86
+ memory.bytes(buffer + at, chunk.length).set(chunk);
87
+ }
88
+ }),
89
+ poll_oneoff: (subscriptions: number, events: number, count: number, ready: number) =>
90
+ attempt(() =>
91
+ guest(() => {
92
+ const view = memory.view;
93
+ for (let i = 0; i < count; i++) {
94
+ const sub = subscriptions + i * 48;
95
+ const event = events + i * 32;
96
+ memory.bytes(event, 32).fill(0);
97
+ view.setBigUint64(event, view.getBigUint64(sub, true), true); // userdata
98
+ view.setUint8(event + 10, view.getUint8(sub + 8)); // the subscription's type
99
+ }
100
+ view.setUint32(ready, count, true);
101
+ }),
102
+ ),
103
+ proc_exit: (code: number) => {
104
+ throw new WasiExit(code);
105
+ },
106
+ sched_yield: () => ERRNO.SUCCESS,
107
+ };
108
+ this.wasiImport = Object.fromEntries(WASI_FUNCTIONS.map((name) => [name, calls[name] ?? (() => ERRNO.NOSYS)]));
109
+ }
110
+
111
+ getImportObject(): Record<string, unknown> {
112
+ return { wasi_snapshot_preview1: this.wasiImport };
113
+ }
114
+
115
+ /** Run a command module's `_start`; answers its exit code (or exits the process, without `returnOnExit`). */
116
+ start(instance: WasiInstance): number | undefined {
117
+ const { _start } = this.attach(instance);
118
+ if (typeof _start !== 'function') throw new TypeError('instance.exports._start is not a function');
119
+ try {
120
+ _start();
121
+ return 0;
122
+ } catch (error) {
123
+ if (!(error instanceof WasiExit)) throw error;
124
+ if (this.returnOnExit) return error.code;
125
+ deps.exit(error.code);
126
+ return undefined;
127
+ } finally {
128
+ this.closeAll();
129
+ }
130
+ }
131
+
132
+ /** Set up a reactor module (`_initialize`, no `_start`). */
133
+ initialize(instance: WasiInstance): void {
134
+ const { _start, _initialize } = this.attach(instance);
135
+ if (typeof _start === 'function') throw new TypeError('instance.exports._start must not be a function for initialize()');
136
+ if (typeof _initialize === 'function') _initialize();
137
+ }
138
+
139
+ private attach(instance: WasiInstance): WasiInstance['exports'] {
140
+ if (this.started) throw new Error('WASI instance has already started');
141
+ this.started = true;
142
+ const memory = instance.exports.memory;
143
+ if (!(memory instanceof WebAssembly.Memory)) throw new TypeError('instance.exports.memory must be a WebAssembly.Memory');
144
+ this.memory = memory;
145
+ return instance.exports;
146
+ }
147
+ }
148
+ return { WASI };
149
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * A directory of a {@link VirtualFileSystem}, seen as a whole file system:
3
+ * `/src/App.tsx` in the view is `<root>/src/App.tsx` in the base. Reads, writes
4
+ * and watch events pass straight through (the base stays the one store), and
5
+ * nothing outside `root` is visible.
6
+ *
7
+ * This is how a project lives below the file-system root (`/home/project`)
8
+ * while the dev server, builds, zips and the host's own file access keep
9
+ * addressing it as `/`. Node programs see the base, so `process.cwd()` is a real
10
+ * directory: tools that watch their project (chokidar under Vite) misbehave when
11
+ * it is `/` itself.
12
+ *
13
+ * A subclass so it is accepted wherever a `VirtualFileSystem` is; every public
14
+ * method is mapped (rootedFs.test.ts fails on one that is not).
15
+ */
16
+ import { VirtualFileSystem, type DirectoryEntry, type FileContent, type FlatFiles, type FsChange } from './vfs.js';
17
+ import { normalizePath } from './paths.js';
18
+
19
+ class RootedFileSystem extends VirtualFileSystem {
20
+ private readonly prefix: string;
21
+
22
+ constructor(private readonly base: VirtualFileSystem, private readonly root: string) {
23
+ super();
24
+ this.prefix = root + '/';
25
+ }
26
+
27
+ /** View path → base path. */
28
+ private real(path: string): string {
29
+ const key = normalizePath(path);
30
+ return key === '/' ? this.root : this.root + key;
31
+ }
32
+
33
+ /** Base path under `root` → view path. */
34
+ private local(path: string): string {
35
+ return path === this.root ? '/' : path.slice(this.root.length);
36
+ }
37
+
38
+ override writeFile(path: string, contents: FileContent): void {
39
+ if (normalizePath(path) === '/') throw new Error(`EISDIR: illegal operation on a directory, open '/'`);
40
+ this.base.writeFile(this.real(path), contents);
41
+ }
42
+
43
+ override readFile(path: string): FileContent | undefined {
44
+ return this.base.readFile(this.real(path));
45
+ }
46
+
47
+ override isFile(path: string): boolean {
48
+ return this.base.isFile(this.real(path));
49
+ }
50
+
51
+ override isDirectory(path: string): boolean {
52
+ return normalizePath(path) === '/' || this.base.isDirectory(this.real(path));
53
+ }
54
+
55
+ override mkdir(path: string): void {
56
+ if (normalizePath(path) !== '/') this.base.mkdir(this.real(path));
57
+ }
58
+
59
+ override readdir(path: string): string[] {
60
+ return this.base.readdir(this.real(path));
61
+ }
62
+
63
+ override entries(path: string): DirectoryEntry[] {
64
+ return this.base.entries(this.real(path));
65
+ }
66
+
67
+ override rename(from: string, to: string): void {
68
+ this.base.rename(this.real(from), this.real(to));
69
+ }
70
+
71
+ override list(): string[] {
72
+ return this.base.list().filter((path) => path.startsWith(this.prefix)).map((path) => this.local(path));
73
+ }
74
+
75
+ override explicitDirectories(): string[] {
76
+ return this.base.explicitDirectories().filter((dir) => dir.startsWith(this.prefix)).map((dir) => this.local(dir));
77
+ }
78
+
79
+ override rm(path: string): void {
80
+ this.base.rm(this.real(path));
81
+ }
82
+
83
+ override version(path: string): number | undefined {
84
+ return this.base.version(this.real(path));
85
+ }
86
+
87
+ override mtime(path: string): number | undefined {
88
+ return this.base.mtime(this.real(path));
89
+ }
90
+
91
+ override toFlat(): FlatFiles {
92
+ const out: FlatFiles = {};
93
+ for (const path of this.list()) out[path.slice(1)] = this.readFile(path)!;
94
+ return out;
95
+ }
96
+
97
+ override watch(listener: (change: FsChange) => void, options: { under?: string } = {}): () => void {
98
+ return this.base.watch((change) => {
99
+ if (change.path !== this.root) listener({ ...change, path: this.local(change.path) });
100
+ }, { under: this.real(options.under ?? '/') });
101
+ }
102
+ }
103
+
104
+ /** `fs` seen from `root` (`/` is `fs` itself). */
105
+ export function rootedFileSystem(fs: VirtualFileSystem, root: string): VirtualFileSystem {
106
+ const key = normalizePath(root);
107
+ return key === '/' ? fs : new RootedFileSystem(fs, key);
108
+ }
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import type { CommandContext } from './context.js';
14
14
  import { ownServerReason } from '../detectProject.js';
15
+ import { rootedFileSystem } from '../rootedFs.js';
15
16
 
16
17
  interface Handoff {
17
18
  tool: string;
@@ -30,7 +31,8 @@ export function matchDevServer(argv: string[]): Handoff | undefined {
30
31
  /** The handoff for this command line, when the attached preview can serve the project instead. */
31
32
  export function devServerHandoff(ctx: CommandContext, argv: string[]): Handoff | undefined {
32
33
  const handoff = matchDevServer(argv);
33
- return handoff && ctx.system.previewUrl && !ownServerReason(ctx.fs) ? handoff : undefined;
34
+ // The project is the working directory (`npm run` starts scripts in the package's own).
35
+ return handoff && ctx.system.previewUrl && !ownServerReason(rootedFileSystem(ctx.fs, ctx.cwd)) ? handoff : undefined;
34
36
  }
35
37
 
36
38
  function portOf(argv: string[], fallback: number, env: Record<string, string>): number {