wasi_virt_layer-cli 0.2.2

CLI for the wasi_virt_layer crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use std::{collections::HashMap, io::Write as _};

use compact_str::CompactString;

/// Generates the HTML, TypeScript, and configuration files needed to run a thread-enabled WASM module in a browser/worker.
pub fn gen_threads_run(
    wasm_name: impl AsRef<str>,
    mem_size: HashMap<CompactString, (u64, u64)>,
    out_dir: impl AsRef<str>,
) {
    let wasm_name = wasm_name.as_ref();

    [
        ("common.ts", common_ts()),
        ("inst.ts", &custom_instantiate_ts(wasm_name)),
        ("test_run.ts", test_run_ts()),
        ("thread_spawn.ts", thread_spawn_ts()),
        ("tsconfig.json", tsconfig_json()),
        ("package.json", package_json()),
        ("worker_background_worker.ts", worker_background_worker_ts()),
        ("worker.ts", &worker_ts(wasm_name, &mem_size)),
        ("vite.config.ts", vite_config_ts()),
        ("index.html", index_html()),
    ]
    .iter()
    .for_each(|(name, content)| {
        let out_dir = out_dir.as_ref();
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .open(format!("{out_dir}/{name}"))
            .expect("Failed to create file")
            .write_all(content.as_bytes())
            .expect("Failed to write file");
    });
}

fn common_ts() -> &'static str {
    r#"
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
let _worker: any = null;
const set_fake_worker = async () => {
	if (
		(typeof process !== "undefined" &&
			process.versions &&
			process.versions.node &&
            typeof Deno === "undefined")
	) {
		_worker = _worker || (await import("node:worker_threads"));
		const { Worker, isMainThread, parentPort } = _worker;

        class FakeWorker {
            worker;
            onmessage;

            constructor(url) {
                let absolute_url;
                if (url instanceof URL) {
                    absolute_url = url;
                } else {
                    absolute_url = new URL(url, import.meta.url);
                }
                this.worker = new Worker(absolute_url, {
                    type: "module",
                });

                this.worker.on("message", (message) => {
                    if (this.onmessage) {
                        this.onmessage({ data: message });
                    }
                });
            }
            postMessage(message) {
                this.worker.postMessage(message);
            }
        }

		// biome-ignore lint/suspicious/noExplicitAny: <explanation>
		(globalThis as any).Worker = FakeWorker;
	}
};

export { set_fake_worker };
"#
    .trim()
}

fn custom_instantiate_ts(wasm_name: &str) -> String {
    let pre = format!(
        r#"
import {{ type ImportObject, instantiate }} from "./{wasm_name}.js";
"#
    );

    let post = r#"
function snakeToCamel(snakeCaseString) {
	return snakeCaseString
		.toLowerCase()
		.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
}

export const custom_instantiate = async (
	wasm_module: WebAssembly.Module,
	wasiImport: {
		[key: string]: (...args: unknown[]) => unknown;
	},
	wasiThreadImport: {
		"thread-spawn": (start_arg: number) => number;
	},
	memory: {
		[key: string]: WebAssembly.Memory;
	},
): Promise<WebAssembly.Instance> => {
	const imports = {};
	for (const key in wasiImport) {
		const inner_key = `${snakeToCamel(key)}Import`;
		imports[inner_key] = wasiImport[key];
	}

	const threadSpawnImports = {
		threadSpawnImport: (start_arg) => {
			const tid = wasiThreadImport["thread-spawn"](start_arg);
			return tid;
		},
	};

	let inst: WebAssembly.Instance | undefined = undefined;

	const root = await instantiate(
		(_path) => {
			return wasm_module;
		}, // instantiate has default function if undefined
		{
			"wasip1-vfs:host/virtual-file-system-wasip1-core": {
				Wasip1: imports,
			},
			"wasip1-vfs:host/virtual-file-system-wasip1-threads-import": {
				Wasip1Threads: threadSpawnImports,
			},
		} as ImportObject,
		async (module, imports) => {
			imports.env = {
				...memory,
			};

			inst = await WebAssembly.instantiate(module, imports);
			return inst;
		},
	);

	if (inst === undefined) {
		throw new Error("inst is not an instance");
	}
	inst = inst as WebAssembly.Instance;

	const fake = {
		exports: {
			memory: inst.exports.memory as WebAssembly.Memory,
			_start: () => {
				// init only
				if (root.main) {
					root.main();
				} else if (root._start) {
					root._start();
				} else if (inst.exports._start) {
					(inst.exports._start as Function)();
				} else if (inst.exports.main) {
					(inst.exports.main as Function)();
				}
				console.log("[WASI main] done.");
			},
			wasi_thread_start: (tid, arg) => {
				console.log("[WASI wasi_thread_start] tid", tid, "arg", arg);
				root.virtualFileSystemWasip1ThreadsExport.wasiThreadStart(tid, arg);
			},
		},
	};

	return fake;
};
"#;

    format!("{}{}", pre.trim(), post.trim())
}

fn test_run_ts() -> &'static str {
    r#"
// npx ts-node test_run.ts

import { ConsoleStdout, Fd, File, OpenFile } from "@bjorn3/browser_wasi_shim";
import { WASIFarm, wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";

import { set_fake_worker } from "./common.ts";

await set_fake_worker();

const isNode =
	(typeof process !== "undefined" && !!process.versions?.node) ||
	(typeof Deno !== "undefined");

let farm: WASIFarm;
if (!isNode) {
    await import("@xterm/xterm/css/xterm.css");
    const { FitAddon } = await import("xterm-addon-fit");
    const { Terminal } = await import("@xterm/xterm");

    wait_async_polyfill();

	const term = new Terminal({
		convertEol: true,
	});
	const terminalElement = document.getElementById("terminal");

	if (!terminalElement) {
		throw new Error("No terminal element found");
	}

	term.open(terminalElement);

	const fitAddon = new FitAddon();
	term.loadAddon(fitAddon);
	fitAddon.fit();

	class XtermStdio extends Fd {
		term: Terminal;

		constructor(term: Terminal) {
			super();
			this.term = term;
		}
		fd_write(data: Uint8Array) /*: {ret: number, nwritten: number}*/ {
			const str = new TextDecoder().decode(data);
			this.term.write(str);
			console.log(str);
			return { ret: 0, nwritten: data.byteLength };
		}
	}

	farm = new WASIFarm(
		new XtermStdio(term),
		new XtermStdio(term),
		new XtermStdio(term),
		[],
	);

	const worker = new Worker("./worker.ts", { type: "module" });

	worker.postMessage({
		wasi_ref: farm.get_ref(),
	});
} else {
	farm = new WASIFarm(
		new OpenFile(new File([])), // stdin
		ConsoleStdout.lineBuffered((msg) => console.log(`[WASI stdout] ${msg}`)),
		ConsoleStdout.lineBuffered((msg) => console.warn(`[WASI stderr] ${msg}`)),
		[],
	);

	const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });

	worker.postMessage({
        wasi_ref: farm.get_ref(),
	});
}
"#
    .trim()
}

fn thread_spawn_ts() -> &'static str {
    r#"
import { thread_spawn_on_worker } from "@oligami/browser_wasi_shim-threads";
import { set_fake_worker } from "./common.ts";
import { custom_instantiate } from "./inst.ts";

await set_fake_worker();

globalThis.onmessage = (event) => {
	thread_spawn_on_worker(
		event.data,
		async (
			thread_spawn_wasm: WebAssembly.Module,
			imports: {
				env: {
					[key: string]: WebAssembly.Memory;
				};
				wasi: { "thread-spawn": (start_arg: number) => number };
				// biome-ignore lint/suspicious/noExplicitAny: <explanation>
				wasi_snapshot_preview1: { [key: string]: (...args: any[]) => unknown };
			},
		) => {
			return custom_instantiate(
				thread_spawn_wasm,
				imports.wasi_snapshot_preview1,
				imports.wasi,
				imports.env,
			);
		},
	);
};
"#
    .trim()
}

fn tsconfig_json() -> &'static str {
    r#"
{
	"compilerOptions": {
		"target": "ESNext",
		"module": "NodeNext",
		"moduleResolution": "nodenext",
		"esModuleInterop": true,
		"skipLibCheck": true,
		"forceConsistentCasingInFileNames": true,
		"noEmit": true,
		"allowImportingTsExtensions": true
	},
	"include": ["**/*.ts"],
	"exclude": ["node_modules"]
}
"#
    .trim()
}

fn package_json() -> &'static str {
    r#"
{
	"scripts": {
		"run": "ts-node test_run.ts",
		"dev": "vite"
	},
	"type": "module",
	"dependencies": {
		"@bjorn3/browser_wasi_shim": "^0.4.2",
		"@oligami/browser_wasi_shim-threads": "^0.2.2",
		"@xterm/xterm": "^5.5",
		"xterm-addon-fit": "^0.8.0"
	},
	"devDependencies": {
		"ts-node": "^10.9.2",
		"vite": "^7.1.7"
	}
}
"#
    .trim()
}

fn worker_background_worker_ts() -> &'static str {
    r#"
import { wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";
// @ts-ignore
import run from "./node_modules/@oligami/browser_wasi_shim-threads/dist/worker_background_worker.min.js";

import { set_fake_worker } from "./common.ts";

await set_fake_worker();

wait_async_polyfill();

run();
"#
    .trim()
}

fn worker_ts(wasm_name: &str, mem_size: &HashMap<CompactString, (u64, u64)>) -> String {
    let mut memories = String::new();
    for (name, (init, max)) in mem_size {
        memories.push_str(&{
            let str = format!(
                r#"
                {name}: new WebAssembly.Memory({{
                    initial:{init},
                    maximum:{max},
                    shared:true,
                }}),"#
            );
            format!("                {}", str.trim())
        });
    }

    format!(
        r#"
import {{ WASIFarmAnimal }} from "@oligami/browser_wasi_shim-threads";
import {{ set_fake_worker }} from "./common.ts";
import {{ custom_instantiate }} from "./inst.ts";

await set_fake_worker();

const isNode =
	(typeof process !== "undefined" && !!process.versions?.node) ||
	(typeof Deno !== "undefined");
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
let _fs: any = null;
async function fetchCompile(url) {{
    if (isNode) {{
        _fs = _fs || (await import("node:fs/promises"));
        return WebAssembly.compile(await _fs.readFile(new URL(url, import.meta.url)));
    }}
    return fetch(url).then(WebAssembly.compileStreaming);
}}

globalThis.onmessage = async (message) => {{
	const {{ wasi_ref }} = message.data;

	const wasm_path = "./{wasm_name}.core.wasm";
	const wasm = await fetchCompile(wasm_path);

	const args = ["bin", "arg1", "arg2"];
	const env = ["FOO=bar"];

	const wasi = new WASIFarmAnimal(
		wasi_ref,
		args, // args
		env, // env
		{{
			can_thread_spawn: true,
			thread_spawn_worker_url: "./thread_spawn.ts",
			thread_spawn_wasm: wasm,
			worker_background_worker_url: "./worker_background_worker.ts",
            share_memory: {{
{memories}
            }},
        }},
	);

	await wasi.wait_worker_background_worker();

	const root = await custom_instantiate(
		wasm,
		wasi.wasiImport,
		wasi.wasiThreadImport,
		wasi.get_share_memory(),
	);

	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	wasi.start(root as any);

    globalThis.process?.exit(0);
    globalThis.Deno?.exit(0);
}};
"#
    )
    .trim()
    .to_string()
}

fn vite_config_ts() -> &'static str {
    r#"
import { defineConfig } from "vite";

export default defineConfig({
	server: {
		headers: {
			"Cross-Origin-Embedder-Policy": "require-corp",
			"Cross-Origin-Opener-Policy": "same-origin",
		},
	},
});
    "#
    .trim()
}

fn index_html() -> &'static str {
    r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<div id="terminal"></div>

<script type="module" src="./test_run.ts"></script>
</body>
</html>
    "#
    .trim()
}