@seanhogg/builderforce-webcontainers-core 2026.10.9 → 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.
- package/dist/installer/tree.d.ts.map +1 -1
- package/dist/installer/tree.js +12 -5
- package/dist/installer/tree.js.map +1 -1
- package/dist/installer/wasmBuilds.d.ts +13 -6
- package/dist/installer/wasmBuilds.d.ts.map +1 -1
- package/dist/installer/wasmBuilds.js +17 -8
- package/dist/installer/wasmBuilds.js.map +1 -1
- package/dist/node/builtins.d.ts.map +1 -1
- package/dist/node/builtins.js +2 -0
- package/dist/node/builtins.js.map +1 -1
- package/dist/node/misc.d.ts.map +1 -1
- package/dist/node/misc.js +0 -1
- package/dist/node/misc.js.map +1 -1
- package/dist/node/wasi/abi.d.ts +82 -0
- package/dist/node/wasi/abi.d.ts.map +1 -0
- package/dist/node/wasi/abi.js +144 -0
- package/dist/node/wasi/abi.js.map +1 -0
- package/dist/node/wasi/files.d.ts +67 -0
- package/dist/node/wasi/files.d.ts.map +1 -0
- package/dist/node/wasi/files.js +319 -0
- package/dist/node/wasi/files.js.map +1 -0
- package/dist/node/wasi/index.d.ts +17 -0
- package/dist/node/wasi/index.d.ts.map +1 -0
- package/dist/node/wasi/index.js +129 -0
- package/dist/node/wasi/index.js.map +1 -0
- package/package.json +1 -1
- package/src/installer/tree.ts +13 -4
- package/src/installer/wasmBuilds.ts +24 -9
- package/src/node/builtins.ts +2 -0
- package/src/node/misc.ts +0 -1
- package/src/node/wasi/abi.ts +151 -0
- package/src/node/wasi/files.ts +350 -0
- package/src/node/wasi/index.ts +149 -0
package/src/installer/tree.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import type { PackageManifest } from './registry.js';
|
|
14
14
|
import { parseDependency, type PackageJson, type ParsedSpec } from './spec.js';
|
|
15
15
|
import { satisfies, validRange } from './semver.js';
|
|
16
|
-
import {
|
|
16
|
+
import { napiWasmSiblings, wasmBuildOf } from './wasmBuilds.js';
|
|
17
17
|
|
|
18
18
|
export type EdgeType = 'prod' | 'dev' | 'optional' | 'peer';
|
|
19
19
|
|
|
@@ -34,6 +34,8 @@ interface Dependency {
|
|
|
34
34
|
type: EdgeType;
|
|
35
35
|
/** Added by this installer (a napi-rs wasm binding), not declared: missing is silent. */
|
|
36
36
|
implied?: boolean;
|
|
37
|
+
/** Installed only when this preferred package did not resolve (the threaded wasm binding stands in for the single-threaded one). */
|
|
38
|
+
fallbackFor?: string;
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
interface Edge extends Dependency {
|
|
@@ -99,8 +101,10 @@ function dependenciesOf(m: PackageJson | PackageManifest, isRoot: boolean, produ
|
|
|
99
101
|
if (isRoot && !production) add((m as PackageJson).devDependencies, 'dev');
|
|
100
102
|
add(m.dependencies, 'prod');
|
|
101
103
|
add(m.optionalDependencies, 'optional');
|
|
102
|
-
const sibling
|
|
103
|
-
|
|
104
|
+
for (const sibling of napiWasmSiblings(m.optionalDependencies)) {
|
|
105
|
+
const listed = out.get(sibling.name);
|
|
106
|
+
out.set(sibling.name, listed ? { ...listed, fallbackFor: sibling.fallbackFor } : { name: sibling.name, range: sibling.range, type: 'optional', implied: true, fallbackFor: sibling.fallbackFor });
|
|
107
|
+
}
|
|
104
108
|
if (!isRoot) {
|
|
105
109
|
const meta = (m as PackageManifest).peerDependenciesMeta ?? {};
|
|
106
110
|
for (const [name, range] of Object.entries(m.peerDependencies ?? {})) {
|
|
@@ -108,7 +112,8 @@ function dependenciesOf(m: PackageJson | PackageManifest, isRoot: boolean, produ
|
|
|
108
112
|
}
|
|
109
113
|
}
|
|
110
114
|
const bundled = bundledNames(m as PackageManifest);
|
|
111
|
-
|
|
115
|
+
// A fallback resolves after the flavor it stands in for, so it can see whether that one landed.
|
|
116
|
+
return [...out.values()].filter((d) => !bundled.has(d.name)).sort((a, b) => Number(!!a.fallbackFor) - Number(!!b.fallbackFor) || (a.name < b.name ? -1 : 1));
|
|
112
117
|
}
|
|
113
118
|
|
|
114
119
|
/** A native-binary package's wasm twin when one fits the range (`wasmBuilds.ts`), else the package itself. */
|
|
@@ -183,6 +188,10 @@ export async function resolveTree(options: ResolveTreeOptions): Promise<Map<stri
|
|
|
183
188
|
for (const dep of deps) {
|
|
184
189
|
const spec = specs.get(dep.name);
|
|
185
190
|
if (!spec) continue;
|
|
191
|
+
if (dep.fallbackFor) {
|
|
192
|
+
const preferred = lookup(location, dep.fallbackFor);
|
|
193
|
+
if (preferred && matches(nodes.get(preferred)!.manifest.version, specs.get(dep.fallbackFor)?.range ?? spec.range)) continue;
|
|
194
|
+
}
|
|
186
195
|
const from = dep.type === 'peer' ? parentLocation(location) : location;
|
|
187
196
|
const existing = lookup(from, dep.name);
|
|
188
197
|
const edge = { ...dep, range: spec.range, owner: location, from };
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* requires `esbuild` gets `esbuild-wasm` at the same version, with the same
|
|
6
6
|
* JavaScript API. Vite, Nuxt, SvelteKit, tsx and tsup all reach for these.
|
|
7
7
|
* Data, not branches: another tool with an official wasm twin is one more row.
|
|
8
|
-
* - A napi-rs
|
|
8
|
+
* - A napi-rs WebAssembly binding (`napiWasmSiblings`), added beside the
|
|
9
9
|
* per-platform ones the package lists.
|
|
10
10
|
*/
|
|
11
11
|
import type { ParsedSpec } from './spec.js';
|
|
@@ -18,19 +18,34 @@ const WASM_BUILDS: Readonly<Record<string, string>> = {
|
|
|
18
18
|
/** A napi-rs per-platform binding name: `@oxc-parser/binding-linux-x64-gnu`, `lightningcss-darwin-arm64`. */
|
|
19
19
|
const NAPI_PLATFORM = /-(?:darwin|linux|win32|android|freebsd|openharmony|sunos|aix)-[a-z0-9_-]+$/;
|
|
20
20
|
|
|
21
|
+
/** WebAssembly binding flavors, preferred first: `wasip1` is single-threaded (no shared memory, so no cross-origin isolation); `wasi` needs threads. */
|
|
22
|
+
const NAPI_WASM_FLAVORS = ['-wasm32-wasip1', '-wasm32-wasi'] as const;
|
|
23
|
+
|
|
24
|
+
export interface NapiWasmSibling {
|
|
25
|
+
name: string;
|
|
26
|
+
range: string;
|
|
27
|
+
/** Install only when this preferred flavor did not resolve. */
|
|
28
|
+
fallbackFor?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
21
31
|
/**
|
|
22
32
|
* napi-rs packages list a binding per platform as optional dependencies, none of
|
|
23
|
-
* which fits here; most also publish
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
33
|
+
* which fits here; most also publish WebAssembly siblings they look for next but do
|
|
34
|
+
* not list (oxc-parser, rolldown, @tailwindcss/oxide). This names them, at the
|
|
35
|
+
* bindings' range, as optional dependencies: the single-threaded `-wasm32-wasip1`
|
|
36
|
+
* first, the threaded `-wasm32-wasi` only if that one is not published (a registry
|
|
37
|
+
* miss is skipped like any optional one). Nothing when the package lists the single-threaded one itself; one that lists only the threaded one gets the single-threaded one added, and its own entry becomes the fallback.
|
|
27
38
|
*/
|
|
28
|
-
export function
|
|
39
|
+
export function napiWasmSiblings(optional: Readonly<Record<string, string>> | undefined): NapiWasmSibling[] {
|
|
29
40
|
const bindings = Object.entries(optional ?? {}).filter(([name]) => NAPI_PLATFORM.test(name));
|
|
30
|
-
if (bindings.length < 2) return
|
|
41
|
+
if (bindings.length < 2) return [];
|
|
31
42
|
const [first, range] = bindings[0]!;
|
|
32
|
-
const
|
|
33
|
-
|
|
43
|
+
const base = first.replace(NAPI_PLATFORM, '');
|
|
44
|
+
if (bindings.some(([name]) => name.replace(NAPI_PLATFORM, '') !== base)) return [];
|
|
45
|
+
const [preferred, fallback] = NAPI_WASM_FLAVORS.map((flavor) => base + flavor) as [string, string];
|
|
46
|
+
if (optional![preferred]) return [];
|
|
47
|
+
// Listing only the threaded flavor still gets the single-threaded one added; the listed entry becomes its fallback.
|
|
48
|
+
return [{ name: preferred, range }, { name: fallback, range, fallbackFor: preferred }];
|
|
34
49
|
}
|
|
35
50
|
|
|
36
51
|
/**
|
package/src/node/builtins.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { createStdinRead } from './fs/stdinFd.js';
|
|
|
18
18
|
import { constants as fsConstants } from './fs/stats.js';
|
|
19
19
|
import { createCryptoModule } from './crypto.js';
|
|
20
20
|
import { createQuerystringModule, createUrlModule } from './urlqs.js';
|
|
21
|
+
import { createWasiModule } from './wasi/index.js';
|
|
21
22
|
import { createAssertModule } from './assert.js';
|
|
22
23
|
import { createZlibModule } from './zlib.js';
|
|
23
24
|
import { createHttpModule, createNetModule, createFetch } from './http/index.js';
|
|
@@ -107,6 +108,7 @@ export function createBuiltins(deps: BuiltinDeps) {
|
|
|
107
108
|
util: () => createUtilModule(env, (message) => proc.stderr.write(message + '\n')),
|
|
108
109
|
'util/types': () => utilTypes,
|
|
109
110
|
vm: () => createVmModule(),
|
|
111
|
+
wasi: (get) => createWasiModule({ fs: get('fs'), stdout: (bytes) => void proc.stdout.write(bytes), stderr: (bytes) => void proc.stderr.write(bytes), exit: (code) => proc.exit(code) }),
|
|
110
112
|
zlib: () => createZlibModule(),
|
|
111
113
|
};
|
|
112
114
|
for (const [name, mod] of Object.entries(stubs)) factories[name] ??= () => mod;
|
package/src/node/misc.ts
CHANGED
|
@@ -257,7 +257,6 @@ export function createStubModules(): Record<string, Record<string, unknown>> {
|
|
|
257
257
|
trace_events: { createTracing: () => ({ enable() {}, disable() {} }), getEnabledCategories: () => '' },
|
|
258
258
|
sqlite: { DatabaseSync: unavailable('sqlite.DatabaseSync') },
|
|
259
259
|
test: { test: unavailable('node:test'), describe: unavailable('node:test'), it: unavailable('node:test') },
|
|
260
|
-
wasi: { WASI: unavailable('wasi.WASI') },
|
|
261
260
|
repl: { start: unavailable('repl.start') },
|
|
262
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() {} }) },
|
|
263
262
|
};
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|