From a56ee35529a208db586a8a81e94d614246d5bc78 Mon Sep 17 00:00:00 2001 From: Spxg Date: Sat, 24 Jan 2026 02:44:36 +0800 Subject: [PATCH 01/73] Implement js-bindgen test runner --- TEST.md | 93 ++- client/.cargo/config.toml | 1 + client/Cargo.toml | 4 +- client/js-bindgen-test/Cargo.toml | 12 + client/js-bindgen-test/src/lib.rs | 69 ++ client/web-sys/Cargo.toml | 3 + client/web-sys/src/lib.rs | 25 + host/Cargo.toml | 12 +- host/js-bindgen-test-macro/Cargo.toml | 14 + host/js-bindgen-test-macro/src/lib.rs | 309 ++++++++ host/js-bindgen-test-runner/Cargo.toml | 13 + .../js/browser-runner.mjs | 293 ++++++++ .../js-bindgen-test-runner/js/node-runner.mjs | 83 +++ .../js/playwright-runner.mjs | 26 + .../js-bindgen-test-runner/js/runner-core.mjs | 116 +++ .../js/service-worker.mjs | 89 +++ host/js-bindgen-test-runner/js/shared.mjs | 120 ++++ .../js/worker-runner.mjs | 96 +++ host/js-bindgen-test-runner/src/main.rs | 674 ++++++++++++++++++ host/js-bindgen/src/lib.rs | 420 +---------- host/ld/src/main.rs | 11 +- host/macro-shared/src/lib.rs | 442 ++++++++++++ linker-shim/linker | 7 + linker-shim/linker.cmd | 2 +- linker-shim/test-runner | 7 + linker-shim/test-runner.cmd | 5 + 26 files changed, 2516 insertions(+), 430 deletions(-) create mode 100644 client/js-bindgen-test/Cargo.toml create mode 100644 client/js-bindgen-test/src/lib.rs create mode 100644 host/js-bindgen-test-macro/Cargo.toml create mode 100644 host/js-bindgen-test-macro/src/lib.rs create mode 100644 host/js-bindgen-test-runner/Cargo.toml create mode 100644 host/js-bindgen-test-runner/js/browser-runner.mjs create mode 100644 host/js-bindgen-test-runner/js/node-runner.mjs create mode 100644 host/js-bindgen-test-runner/js/playwright-runner.mjs create mode 100644 host/js-bindgen-test-runner/js/runner-core.mjs create mode 100644 host/js-bindgen-test-runner/js/service-worker.mjs create mode 100644 host/js-bindgen-test-runner/js/shared.mjs create mode 100644 host/js-bindgen-test-runner/js/worker-runner.mjs create mode 100644 host/js-bindgen-test-runner/src/main.rs create mode 100755 linker-shim/linker create mode 100755 linker-shim/test-runner create mode 100644 linker-shim/test-runner.cmd diff --git a/TEST.md b/TEST.md index 336be5ae..a0039ed5 100644 --- a/TEST.md +++ b/TEST.md @@ -1,17 +1,100 @@ -Manual testing commands until CI is set up: +Manual testing commands (CI not set up yet). + +Quick build (from repo root): + +```sh +cd client +cargo build --example basic +cargo build --example basic --release --timings +``` + +Test examples: + +```rust +#[js_bindgen_test::test] +fn test_wasm() {} + +#[js_bindgen_test::test] +#[ignore = "hah, it works"] +fn test_ignore() { + panic!("kaboom"); +} + +#[js_bindgen_test::test] +#[should_panic(expected = "kaboom")] +fn test_should_panic() { + panic!("kaboom"); +} +``` + +Wasm tests: Node runner (default): + +```sh +cargo test --target wasm32-unknown-unknown +``` + +Wasm tests: Browser runner (Playwright headless): + +```sh +JBTEST_BROWSER=chromium cargo test --target wasm32-unknown-unknown +``` + +Wasm tests: Browser server mode (open URL in a browser): ```sh -cargo build --example basic --release --timings && wasm-tools print -o examples/basic.wat target/wasm32-unknown-unknown/release/examples/basic.wasm && wasm-tools validate examples/basic.wat +JBTEST_SERVER=1 cargo test --target wasm32-unknown-unknown ``` +Runner options: + +- `JBTEST_BROWSER=chromium|firefox|webkit` +- `JBTEST_WORKER=dedicated|shared|service` +- `JBTEST_SERVER=1` (serve browser runner and print URL) +- `JBTEST_SERVER_ADDRESS=127.0.0.1:8000` (defaults to 8000; falls back to a random port if busy) + +List and filter tests: + +```sh +cargo test --target wasm32-unknown-unknown -- --list +cargo test --target wasm32-unknown-unknown -- --list --format terse +cargo test --target wasm32-unknown-unknown -- some_substring +cargo test --target wasm32-unknown-unknown -- --exact full::test::name +cargo test --target wasm32-unknown-unknown -- --ignored +``` + +Other test flags: + +```sh +cargo test --target wasm32-unknown-unknown -- --nocapture +``` + +Wasm tooling checks: + ```sh -CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS="-Ctarget-feature=+atomics -Clink-arg=--shared-memory -Clink-arg=--max-memory=4294967296" cargo +nightly build --example basic -Zbuild-std=panic_abort,std --release --timings && wasm-tools print -o examples/basic.wat target/wasm32-unknown-unknown/release/examples/basic.wasm && wasm-tools validate examples/basic.wat +cd client +wasm-tools print -o examples/basic.wat target/wasm32-unknown-unknown/debug/examples/basic.wasm +wasm-tools validate examples/basic.wat ``` +Shared-memory build (nightly): + ```sh -cargo +nightly build --example basic --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std --release --timings && wasm-tools print -o examples/basic.wat target/wasm64-unknown-unknown/release/examples/basic.wasm && wasm-tools validate examples/basic.wat +cd client +CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS="-Ctarget-feature=+atomics -Clink-arg=--shared-memory -Clink-arg=--max-memory=4294967296" \ + cargo +nightly build --example basic -Zbuild-std=panic_abort,std --release --timings ``` +Wasm64 builds (nightly): + ```sh -CARGO_TARGET_WASM64_UNKNOWN_UNKNOWN_RUSTFLAGS="-Ctarget-feature=+atomics -Clink-arg=--shared-memory -Clink-arg=--max-memory=17179869184" cargo +nightly build --example basic --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std --release --timings && wasm-tools print -o examples/basic.wat target/wasm64-unknown-unknown/release/examples/basic.wasm && wasm-tools validate examples/basic.wat +cd client +cargo +nightly build --example basic --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std --release --timings ``` + +```sh +cd client +CARGO_TARGET_WASM64_UNKNOWN_UNKNOWN_RUSTFLAGS="-Ctarget-feature=+atomics -Clink-arg=--shared-memory -Clink-arg=--max-memory=17179869184" \ + cargo +nightly build --example basic --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std --release --timings +``` + + diff --git a/client/.cargo/config.toml b/client/.cargo/config.toml index 05ba75a0..3dd8d5ce 100644 --- a/client/.cargo/config.toml +++ b/client/.cargo/config.toml @@ -3,3 +3,4 @@ target = "wasm32-unknown-unknown" [target.'cfg(all(target_family = "wasm", any(target_os = "none", target_os = "unknown")))'] linker = "../linker-shim/linker.cmd" +runner = "../linker-shim/test-runner" diff --git a/client/Cargo.toml b/client/Cargo.toml index 0173e15b..4777eb9a 100644 --- a/client/Cargo.toml +++ b/client/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["js-sys", "web-sys"] +members = ["js-bindgen-test","js-sys", "web-sys"] resolver = "2" [workspace.package] @@ -9,6 +9,8 @@ rust-version = "1.85" [workspace.dependencies] js-bindgen = { path = "../host/js-bindgen" } +js-bindgen-test-macro = { path = "../host/js-bindgen-test-macro" } +js-bindgen-test = { path = "js-bindgen-test" } js-sys = { path = "js-sys" } js-sys-macro = { path = "../host/js-sys-macro" } mini-alloc = "1" diff --git a/client/js-bindgen-test/Cargo.toml b/client/js-bindgen-test/Cargo.toml new file mode 100644 index 00000000..8bc4a326 --- /dev/null +++ b/client/js-bindgen-test/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "js-bindgen-test" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +js-sys = { workspace = true } +js-bindgen-test-macro = { workspace = true } + +[lints] +workspace = true diff --git a/client/js-bindgen-test/src/lib.rs b/client/js-bindgen-test/src/lib.rs new file mode 100644 index 00000000..1debcb19 --- /dev/null +++ b/client/js-bindgen-test/src/lib.rs @@ -0,0 +1,69 @@ +pub use js_bindgen_test_macro::test; +use js_sys::JsString; +use std::{cell::RefCell, panic::PanicHookInfo}; + +struct LastPanic { + payload: Option, + info: Option, +} + +thread_local! { + static LAST_PANIC: RefCell = const { RefCell::new(LastPanic { + payload: None, + info: None + }) }; +} + +js_sys::js_bindgen::embed_js!( + name = "panic.stack", + "(message) => {{", + " const error = new Error(message);", + " return error.stack || String(error);", + "}}" +); + +#[js_sys::js_sys(js_sys = js_sys)] +extern "C" { + #[js_sys(js_embed = "panic.stack")] + fn panic_stack(message: &JsString) -> JsString; +} + +pub fn set_panic_hook() { + fn payload_as_str<'a>(info: &'a PanicHookInfo) -> Option<&'a str> { + if let Some(s) = info.payload().downcast_ref::<&str>() { + Some(s) + } else if let Some(s) = info.payload().downcast_ref::() { + Some(s) + } else { + None + } + } + + static HOOK: std::sync::Once = std::sync::Once::new(); + HOOK.call_once(|| { + std::panic::set_hook(Box::new(|info| { + LAST_PANIC.with(|cell| { + *cell.borrow_mut() = LastPanic { + payload: payload_as_str(info).map(JsString::from_str), + info: Some(panic_stack(&JsString::from_str(&info.to_string()))), + } + }); + })); + }); +} + +#[unsafe(no_mangle)] +pub extern "C" fn last_panic_message() -> JsString { + match LAST_PANIC.with(|cell| cell.borrow_mut().info.take()) { + Some(info) => info, + None => JsString::from_str(""), + } +} + +#[unsafe(no_mangle)] +pub extern "C" fn last_panic_payload() -> JsString { + match LAST_PANIC.with(|cell| cell.borrow_mut().payload.take()) { + Some(payload) => payload, + None => JsString::from_str(""), + } +} diff --git a/client/web-sys/Cargo.toml b/client/web-sys/Cargo.toml index 82c22b59..ca708324 100644 --- a/client/web-sys/Cargo.toml +++ b/client/web-sys/Cargo.toml @@ -6,3 +6,6 @@ rust-version = { workspace = true } [dependencies] js-sys = { workspace = true } + +[dev-dependencies] +js-bindgen-test = { workspace = true } diff --git a/client/web-sys/src/lib.rs b/client/web-sys/src/lib.rs index 4a344f09..5ef62182 100644 --- a/client/web-sys/src/lib.rs +++ b/client/web-sys/src/lib.rs @@ -17,3 +17,28 @@ pub mod console { pub fn log2(data1: &JsValue, data2: &JsValue); } } + +#[cfg(test)] +mod tests { + use super::console; + use js_bindgen_test::test; + use js_sys::JsString; + + #[test] + fn test_console_log() { + let value = JsString::from_str("hello world"); + console::log(&value); + } + + #[test] + #[ignore = "hah, it works"] + fn test_ignore() { + panic!("kaboom"); + } + + #[test] + #[should_panic(expected = "kaboom")] + fn test_should_panic() { + panic!("kaboom"); + } +} diff --git a/host/Cargo.toml b/host/Cargo.toml index 902c1222..0037967c 100644 --- a/host/Cargo.toml +++ b/host/Cargo.toml @@ -1,5 +1,14 @@ [workspace] -members = ["js-bindgen", "js-sys-macro", "ld", "ld-shared", "macro-shared", "wasm-ld-opt"] +members = [ + "js-bindgen", + "js-sys-macro", + "js-bindgen-test-macro", + "js-bindgen-test-runner", + "ld", + "ld-shared", + "macro-shared", + "wasm-ld-opt", +] resolver = "2" [workspace.package] @@ -21,6 +30,7 @@ prettyplease = "0.2" proc-macro2 = { version = "1", default-features = false } quote = { version = "1", default-features = false } rand = { version = "0.9", default-features = false, features = ["thread_rng"] } +serde = { version = "1", default-features = false } serde_json = { version = "1", default-features = false, features = ["alloc"] } similar-asserts = { version = "1", default-features = false } syn = { version = "2", default-features = false, features = ["parsing", "printing"] } diff --git a/host/js-bindgen-test-macro/Cargo.toml b/host/js-bindgen-test-macro/Cargo.toml new file mode 100644 index 00000000..642deb41 --- /dev/null +++ b/host/js-bindgen-test-macro/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "js-bindgen-test-macro" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true + +[lib] +proc-macro = true + +[dependencies] +js-bindgen-macro-shared = { workspace = true } + +[lints] +workspace = true diff --git a/host/js-bindgen-test-macro/src/lib.rs b/host/js-bindgen-test-macro/src/lib.rs new file mode 100644 index 00000000..9b877971 --- /dev/null +++ b/host/js-bindgen-test-macro/src/lib.rs @@ -0,0 +1,309 @@ +use std::iter::{self, Peekable}; + +use js_bindgen_macro_shared::*; +use proc_macro::{ + Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree, token_stream, +}; + +struct TestAttributes { + ignore: Option>, + should_panic: Option>, +} + +impl TestAttributes { + fn new() -> Self { + Self { + ignore: None, + should_panic: None, + } + } +} + +#[proc_macro_attribute] +pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream { + test_internal(attr, item).unwrap_or_else(|e| e) +} + +fn test_internal(attr: TokenStream, item: TokenStream) -> Result { + let mut attr = attr.into_iter(); + if let Some(tok) = attr.next() { + return Err(compile_error(tok.span(), "expected empty attribute")); + } + + let (item, attrs) = strip_test_attributes(item)?; + let (ident, is_async) = find_test_ident(&item)?; + if is_async { + return Err(compile_error(ident.span(), "async tests are not supported")); + } + + let test_name_tokens = test_name_tokens(&ident); + + let section_data = [ + Argument { + cfg: None, + kind: ArgumentKind::Bytes(option_option_string(&attrs.ignore)), + }, + Argument { + cfg: None, + kind: ArgumentKind::Bytes(option_option_string(&attrs.should_panic)), + }, + Argument { + cfg: None, + kind: ArgumentKind::Interpolate(test_name_tokens), + }, + ]; + + let mut output = TokenStream::new(); + output.extend(item); + + let section = custom_section("js_bindgen.test", None, §ion_data); + output.extend(section); + + let wrapper = format!( + r#" +const _: () = {{ + #[unsafe(export_name = ::core::concat!(::core::module_path!(), "::", ::core::stringify!({ident})))] + extern "C" fn jbg_test() {{ + js_bindgen_test::set_panic_hook(); + {ident}(); + }} +}}; +"# + ); + output.extend(wrapper.parse::().unwrap()); + + Ok(output) +} + +fn option_option_string(option: &Option>) -> Vec { + match option { + Some(s) => { + if let Some(s) = s { + let len = u32::to_le_bytes(s.len() as u32); + [2].iter() + .chain(&len) + .chain(s.as_bytes()) + .copied() + .collect::>() + } else { + vec![1] + } + } + None => vec![0], + } +} + +fn find_test_ident(item: &TokenStream) -> Result<(Ident, bool), TokenStream> { + let mut iter = item.clone().into_iter().peekable(); + let mut saw_async = false; + let mut last_span = Span::mixed_site(); + + while let Some(tok) = iter.next() { + last_span = tok.span(); + if let TokenTree::Ident(ident) = &tok { + let name = ident.to_string(); + if name == "async" { + saw_async = true; + } + if name == "fn" { + let ident = parse_ident(&mut iter, ident.span(), "a function name")?; + return Ok((ident, saw_async)); + } + } + } + + Err(compile_error(last_span, "expected a function")) +} + +enum TestAttribute { + Ignore(Option), + ShouldPanic(Option), +} + +fn strip_test_attributes(item: TokenStream) -> Result<(TokenStream, TestAttributes), TokenStream> { + let mut iter = item.into_iter().peekable(); + let mut output = Vec::new(); + let mut attrs = TestAttributes::new(); + + while let Some(tok) = iter.next() { + let TokenTree::Punct(punct) = &tok else { + output.push(tok); + continue; + }; + + if punct.as_char() != '#' { + output.push(tok); + continue; + } + + let Some(TokenTree::Group(group)) = iter.peek() else { + output.push(tok); + continue; + }; + if group.delimiter() != Delimiter::Bracket { + output.push(tok); + continue; + } + + match parse_test_attribute(group)? { + Some(TestAttribute::Ignore(reason)) => { + if attrs.ignore.replace(reason).is_some() { + return Err(compile_error(group.span(), "duplicate `ignore` attribute")); + } + iter.next(); + } + Some(TestAttribute::ShouldPanic(message)) => { + if attrs.should_panic.replace(message).is_some() { + return Err(compile_error( + group.span(), + "duplicate `should_panic` attribute", + )); + } + iter.next(); + } + None => { + output.push(tok); + output.push(TokenTree::Group(group.clone())); + iter.next(); + } + } + } + + Ok((TokenStream::from_iter(output), attrs)) +} + +fn parse_test_attribute(group: &Group) -> Result, TokenStream> { + let mut stream = group.stream().into_iter().peekable(); + let Some(TokenTree::Ident(ident)) = stream.next() else { + return Ok(None); + }; + + match ident.to_string().as_str() { + "ignore" => { + let reason = parse_optional_reason(&mut stream, ident.span())?; + Ok(Some(TestAttribute::Ignore(reason))) + } + "should_panic" => { + let reason = parse_should_panic_reason(&mut stream, ident.span())?; + Ok(Some(TestAttribute::ShouldPanic(reason))) + } + _ => Ok(None), + } +} + +fn parse_optional_reason( + stream: &mut Peekable, + span: Span, +) -> Result, TokenStream> { + if let Some(TokenTree::Punct(punct)) = stream.peek() { + if punct.as_char() == '=' { + let punct = expect_punct(&mut *stream, '=', span, "`=`", false)?; + let (_, reason) = + parse_string_literal(&mut *stream, punct.span(), "a string literal", false)?; + if stream.peek().is_some() { + return Err(compile_error(span, "unexpected tokens")); + } + return Ok(Some(reason)); + } + } + if stream.peek().is_some() { + return Err(compile_error(span, "unexpected tokens")); + } + Ok(None) +} + +fn parse_should_panic_reason( + stream: &mut Peekable, + span: Span, +) -> Result, TokenStream> { + // Support `#[should_panic = "..."]` and `#[should_panic(expected = "...")]`. + if let Some(TokenTree::Punct(punct)) = stream.peek() { + if punct.as_char() == '=' { + let punct = expect_punct(&mut *stream, '=', span, "`=`", false)?; + let (_, reason) = + parse_string_literal(&mut *stream, punct.span(), "a string literal", false)?; + if stream.peek().is_some() { + return Err(compile_error(span, "unexpected tokens")); + } + return Ok(Some(reason)); + } + } + + if let Some(TokenTree::Group(group)) = stream.peek() { + if group.delimiter() != Delimiter::Parenthesis { + return Err(compile_error(span, "unexpected tokens")); + } + let group = match stream.next() { + Some(TokenTree::Group(group)) => group, + _ => return Err(compile_error(span, "unexpected tokens")), + }; + let mut inner = group.stream().into_iter().peekable(); + let Some(TokenTree::Ident(ident)) = inner.next() else { + return Err(compile_error(group.span(), "expected `expected`")); + }; + let name = ident.to_string(); + if name.as_str() != "expected" { + return Err(compile_error(ident.span(), "expected `expected = \"...\"`")); + } + let punct = expect_punct(&mut inner, '=', ident.span(), "`=`", false)?; + let (_, reason) = + parse_string_literal(&mut inner, punct.span(), "a string literal", false)?; + if inner.peek().is_some() || stream.peek().is_some() { + return Err(compile_error(span, "unexpected tokens")); + } + return Ok(Some(reason)); + } + + if stream.peek().is_some() { + return Err(compile_error(span, "unexpected tokens")); + } + + Ok(None) +} + +fn test_name_tokens(ident: &Ident) -> Vec { + let mut args = Vec::new(); + args.extend(path_tokens(&["core", "module_path"])); + args.push(Punct::new('!', Spacing::Alone).into()); + args.push(group(Delimiter::Parenthesis, iter::empty())); + args.push(Punct::new(',', Spacing::Alone).into()); + args.push(Literal::string("::").into()); + args.push(Punct::new(',', Spacing::Alone).into()); + args.extend(path_tokens(&["core", "stringify"])); + args.push(Punct::new('!', Spacing::Alone).into()); + args.push(group( + Delimiter::Parenthesis, + iter::once(ident.clone().into()), + )); + + let mut concat = Vec::new(); + concat.extend(path_tokens(&["core", "concat"])); + concat.push(Punct::new('!', Spacing::Alone).into()); + concat.push(group(Delimiter::Parenthesis, args)); + + concat +} + +fn path_tokens(segments: &[&str]) -> Vec { + let mut tokens = Vec::new(); + tokens.push(Punct::new(':', Spacing::Joint).into()); + tokens.push(Punct::new(':', Spacing::Alone).into()); + + for (index, segment) in segments.iter().enumerate() { + tokens.push(ident(segment)); + if index + 1 < segments.len() { + tokens.push(Punct::new(':', Spacing::Joint).into()); + tokens.push(Punct::new(':', Spacing::Alone).into()); + } + } + + tokens +} + +fn group(delimiter: Delimiter, inner: impl IntoIterator) -> TokenTree { + Group::new(delimiter, inner.into_iter().collect()).into() +} + +fn ident(string: &str) -> TokenTree { + Ident::new(string, Span::mixed_site()).into() +} diff --git a/host/js-bindgen-test-runner/Cargo.toml b/host/js-bindgen-test-runner/Cargo.toml new file mode 100644 index 00000000..d99383ae --- /dev/null +++ b/host/js-bindgen-test-runner/Cargo.toml @@ -0,0 +1,13 @@ +[package] +edition = { workspace = true } +name = "js-bindgen-test-runner" +rust-version = { workspace = true } + +[dependencies] +anyhow = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +wasmparser = { workspace = true } + +[lints] +workspace = true diff --git a/host/js-bindgen-test-runner/js/browser-runner.mjs b/host/js-bindgen-test-runner/js/browser-runner.mjs new file mode 100644 index 00000000..2b17b5f8 --- /dev/null +++ b/host/js-bindgen-test-runner/js/browser-runner.mjs @@ -0,0 +1,293 @@ +import { createTextFormatter } from "./shared.mjs"; +import { runTests } from "./runner-core.mjs"; + +export async function runBrowser({ nocapture, filtered, worker }) { + const mode = worker || "page"; + const baseLog = console.log; + const baseError = console.error; + const baseWarn = console.warn; + const baseInfo = console.info; + const baseDebug = console.debug; + + let result = + mode === "page" + ? await runInWindow({ nocapture, filtered }) + : await runInWorker({ + nocapture, + filtered, + mode, + baseLog, + baseError, + baseWarn, + baseInfo, + baseDebug, + }); + + if (typeof window !== "undefined") { + window.__jbtestDone = true; + window.__jbtestFailed = result.failed; + } + + return result; +} + +async function runInWindow({ nocapture, filtered }) { + const tests = await (await fetch("/tests.json")).json(); + const wasmBytes = await (await fetch("/wasm")).arrayBuffer(); + const { importObject } = await import("/import.js"); + + const lines = []; + const formatter = createTextFormatter({ + nocapture, + write(line) { + lines.push(line); + appendOutput(line); + }, + }); + + const testInputs = tests.map(test => ({ + ...test, + run(testFn, panicPayload, panicMessage) { + return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage, event => + formatter.onEvent(event) + ); + }, + })); + + const result = await runTests({ + wasmBytes, + importObject, + tests: testInputs, + filtered, + emit: event => formatter.onEvent(event), + }); + + return { lines, failed: result.failed }; +} + +async function runInWorker({ + nocapture, + filtered, + mode, + baseLog, + baseError, + baseWarn, + baseInfo, + baseDebug, +}) { + const lines = []; + + function handleMessage(event) { + const data = event.data || {}; + if (data.type === "user-output") { + switch (data.level) { + case "error": + baseError(data.line); + break; + case "warn": + baseWarn(data.line); + break; + case "info": + baseInfo(data.line); + break; + case "debug": + baseDebug(data.line); + break; + default: + baseLog(data.line); + } + return null; + } + if (data.type === "line") { + lines.push(data.line); + appendOutput(data.line); + return null; + } + if (data.type === "report") { + return { lines: data.lines || lines, failed: data.failed || 0 }; + } + return null; + } + + let reportPromise; + if (mode === "dedicated") { + reportPromise = runDedicatedWorker({ filtered, nocapture, handleMessage }); + } else if (mode === "shared") { + reportPromise = runSharedWorker({ filtered, nocapture, handleMessage }); + } else if (mode === "service") { + reportPromise = runServiceWorker({ filtered, nocapture, handleMessage }); + } else { + throw new Error(`unsupported worker mode: ${mode}`); + } + + const report = await reportPromise; + return report; +} + +function runDedicatedWorker({ filtered, nocapture, handleMessage }) { + return new Promise((resolve, reject) => { + let worker; + try { + worker = new Worker("/worker-runner.mjs", { type: "module" }); + } catch (error) { + reject(error); + return; + } + const timeout = setTimeout(() => { + reject(new Error("dedicated worker timed out")); + worker.terminate(); + }, 30000); + worker.onmessage = event => { + const report = handleMessage(event); + if (report) { + clearTimeout(timeout); + resolve(report); + worker.terminate(); + } + }; + worker.onerror = err => reject(err); + worker.postMessage({ filtered, nocapture }); + }); +} + +function runSharedWorker({ filtered, nocapture, handleMessage }) { + return new Promise((resolve, reject) => { + let shared; + try { + shared = new SharedWorker("/worker-runner.mjs", { type: "module" }); + } catch (error) { + reject(error); + return; + } + const port = shared.port; + const timeout = setTimeout(() => { + reject(new Error("shared worker timed out")); + port.close(); + }, 30000); + port.onmessage = event => { + const report = handleMessage(event); + if (report) { + clearTimeout(timeout); + resolve(report); + port.close(); + } + }; + port.onmessageerror = err => reject(err); + port.start(); + port.postMessage({ filtered, nocapture }); + }); +} + +async function runServiceWorker({ filtered, nocapture, handleMessage }) { + if (!navigator.serviceWorker) { + throw new Error("service workers are not supported"); + } + const registration = await navigator.serviceWorker.register("/service-worker.mjs", { + type: "module", + }); + await navigator.serviceWorker.ready; + + if (!navigator.serviceWorker.controller) { + if (!sessionStorage.getItem("jbtest-sw-reload")) { + sessionStorage.setItem("jbtest-sw-reload", "1"); + location.reload(); + return new Promise(() => { }); + } + throw new Error("service worker not controlling the page"); + } + + return new Promise((resolve, reject) => { + const channel = new MessageChannel(); + const timeout = setTimeout(() => { + reject(new Error("service worker timed out")); + channel.port1.close(); + channel.port2.close(); + }, 30000); + channel.port1.onmessage = event => { + const report = handleMessage(event); + if (report) { + clearTimeout(timeout); + resolve(report); + channel.port1.close(); + channel.port2.close(); + } + }; + channel.port1.onmessageerror = err => reject(err); + navigator.serviceWorker.controller.postMessage( + { filtered, nocapture }, + [channel.port2] + ); + }); +} + +function withConsoleCapture(name, run, panicPayload, panicMessage, emit) { + const originalLog = console.log; + const originalError = console.error; + const originalWarn = console.warn; + const originalInfo = console.info; + const originalDebug = console.debug; + + function emitOutput(line, stream, level) { + emit({ type: "test-output", name, line, stream }); + switch (level) { + case "error": + originalError(line); + break; + case "warn": + originalWarn(line); + break; + case "info": + originalInfo(line); + break; + case "debug": + originalDebug(line); + break; + default: + originalLog(line); + } + } + + console.log = (...args) => emitOutput(args.join(" "), "stdout", "log"); + console.error = (...args) => emitOutput(args.join(" "), "stderr", "error"); + console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn"); + console.info = (...args) => emitOutput(args.join(" "), "stdout", "info"); + console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug"); + + try { + run(); + return { ok: true }; + } catch (error) { + return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() }; + } finally { + console.log = originalLog; + console.error = originalError; + console.warn = originalWarn; + console.info = originalInfo; + console.debug = originalDebug; + } +} + +function appendOutput(line) { + const output = ensureOutput(); + if (output.textContent.length > 0) { + output.textContent += "\n"; + } + output.textContent += stripAnsi(line); +} + +function stripAnsi(line) { + return line.replace(/\x1b\[[0-9;]*m/g, ""); +} + +function ensureOutput() { + if (typeof document === "undefined") { + return { textContent: "" }; + } + let output = document.getElementById("output"); + if (!output) { + output = document.createElement("pre"); + output.id = "output"; + document.body.append(output); + } + return output; +} diff --git a/host/js-bindgen-test-runner/js/node-runner.mjs b/host/js-bindgen-test-runner/js/node-runner.mjs new file mode 100644 index 00000000..f7b01481 --- /dev/null +++ b/host/js-bindgen-test-runner/js/node-runner.mjs @@ -0,0 +1,83 @@ +import fs from "node:fs/promises"; +import { pathToFileURL } from "node:url"; +import { createTextFormatter } from "./shared.mjs"; +import { runTests } from "./runner-core.mjs"; + +const wasmPath = process.env.JS_BINDGEN_WASM; +const importsPath = process.env.JS_BINDGEN_IMPORTS; +const testsJson = process.env.JS_BINDGEN_TESTS; +const nocapture = process.env.JS_BINDGEN_NOCAPTURE === "1"; +const filtered = Number(process.env.JS_BINDGEN_FILTERED || "0"); + +if (!wasmPath || !importsPath || !testsJson) { + console.error("missing test runner environment"); + process.exit(1); +} + +const { importObject } = await import(pathToFileURL(importsPath)); +const wasmBytes = await fs.readFile(wasmPath); +const tests = JSON.parse(testsJson); + +const baseLog = console.log; +const baseError = console.error; +const formatter = createTextFormatter({ + nocapture, + write(line, stream) { + if (stream === "stderr") { + baseError(line); + } else { + baseLog(line); + } + }, +}); + +function emit(event) { + formatter.onEvent(event); +} + +const testInputs = tests.map(test => ({ + ...test, + run(testFn, panicPayload, panicMessage) { + return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage); + }, +})); + +const result = await runTests({ + wasmBytes, + importObject, + tests: testInputs, + filtered, + emit, +}); + +process.exit(result.failed === 0 ? 0 : 1); + +function withConsoleCapture(name, run, panicPayload, panicMessage) { + function emitOutput(line, stream, level) { + emit({ type: "test-output", name, line, stream, level }); + } + + const originalLog = console.log; + const originalError = console.error; + const originalWarn = console.warn; + const originalInfo = console.info; + const originalDebug = console.debug; + console.log = (...args) => emitOutput(args.join(" "), "stdout", "log"); + console.error = (...args) => emitOutput(args.join(" "), "stderr", "error"); + console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn"); + console.info = (...args) => emitOutput(args.join(" "), "stdout", "info"); + console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug"); + + try { + run(); + return { ok: true }; + } catch (error) { + return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() }; + } finally { + console.log = originalLog; + console.error = originalError; + console.warn = originalWarn; + console.info = originalInfo; + console.debug = originalDebug; + } +} diff --git a/host/js-bindgen-test-runner/js/playwright-runner.mjs b/host/js-bindgen-test-runner/js/playwright-runner.mjs new file mode 100644 index 00000000..140c566d --- /dev/null +++ b/host/js-bindgen-test-runner/js/playwright-runner.mjs @@ -0,0 +1,26 @@ +import { chromium, firefox, webkit } from "playwright"; + +const url = process.env.JBTEST_URL; +if (!url) { + throw new Error("missing JBTEST_URL"); +} + +const browserName = (process.env.JBTEST_BROWSER || "chromium").toLowerCase(); +const browserType = { + chromium, + firefox, + webkit, +}[browserName]; + +if (!browserType) { + throw new Error(`unsupported browser: ${browserName}`); +} + +const browser = await browserType.launch({ + headless: true, + chromiumSandbox: false, +}); +const page = await browser.newPage(); +await page.goto(url); +await page.waitForFunction("window.__jbtestDone === true"); +await browser.close(); diff --git a/host/js-bindgen-test-runner/js/runner-core.mjs b/host/js-bindgen-test-runner/js/runner-core.mjs new file mode 100644 index 00000000..6bdd7be0 --- /dev/null +++ b/host/js-bindgen-test-runner/js/runner-core.mjs @@ -0,0 +1,116 @@ +export async function runTests({ wasmBytes, importObject, tests, filtered, emit }) { + const startTime = Date.now(); + emit({ type: "run-start", total: tests.length, filtered }); + + const { instance } = await WebAssembly.instantiate(wasmBytes, importObject); + const panicPayload = instance.exports.last_panic_payload; + const panicMessage = instance.exports.last_panic_message; + const externrefTable = resolveExternrefTable(importObject); + + let failed = 0; + let ignored = 0; + + for (const test of tests) { + if (test.ignore) { + ignored += 1; + emit({ type: "test-ignored", name: test.name, reason: test.ignore_reason }); + continue; + } + + const testFn = instance.exports[test.name]; + if (typeof testFn !== "function") { + emit({ + type: "test-failed", + name: test.name, + error: `missing export: ${test.name}`, + }); + failed += 1; + continue; + } + + const result = test.run(testFn, panicPayload, panicMessage); + const shouldPanic = Boolean(test.should_panic); + if (shouldPanic) { + if (result.ok) { + emit({ + type: "test-failed", + name: test.name, + error: "test did not panic as expected", + should_panic: true, + }); + failed += 1; + continue; + } + + const expected = test.should_panic_reason; + const payload = coercePanicMessage(result.panic_payload, externrefTable); + const message = coercePanicMessage(result.panic_message, externrefTable); + const expectedText = expected || ""; + if (expectedText && !payload.includes(expectedText)) { + const displayPayload = escapeForDisplay(payload); + const displayExpected = escapeForDisplay(expectedText); + emit({ + type: "test-failed", + name: test.name, + error: + message + "\n\n" + + "note: panic did not contain expected string\n" + + ` panic message: "${displayPayload}"\n` + + ` expected substring: "${displayExpected}"`, + should_panic: true, + }); + failed += 1; + continue; + } + + emit({ type: "test-ok", name: test.name, should_panic: true }); + continue; + } + + if (result.ok) { + emit({ type: "test-ok", name: test.name, should_panic: false }); + } else { + const message = coercePanicMessage(result.panic_message, externrefTable); + emit({ type: "test-failed", name: test.name, error: message }); + failed += 1; + } + } + + emit({ + type: "run-end", + status: failed === 0 ? "ok" : "FAILED", + passed: tests.length - failed - ignored, + failed, + ignored, + filtered, + duration_ms: Date.now() - startTime, + }); + + return { failed }; +} + +function resolveExternrefTable(importObject) { + if (!importObject) { + return null; + } + return importObject["js_sys"]["externref.table"]; +} + +function coercePanicMessage(value, externrefTable) { + const ref = externrefTable.get(value); + if (typeof externrefTable.set === "function") { + externrefTable.set(value, null); + } + return String(ref); +} + +function escapeForDisplay(value) { + return String(value || "") + .replace(/\\/g, "\\\\") + .replace(/\r/g, "\\r") + .replace(/\n/g, "\\n") + .replace(/\t/g, "\\t") + .replace(/\0/g, "\\0") + .replace(/\x08/g, "\\b") + .replace(/\x0c/g, "\\f"); +} diff --git a/host/js-bindgen-test-runner/js/service-worker.mjs b/host/js-bindgen-test-runner/js/service-worker.mjs new file mode 100644 index 00000000..62fb0a0d --- /dev/null +++ b/host/js-bindgen-test-runner/js/service-worker.mjs @@ -0,0 +1,89 @@ +import { createTextFormatter } from "./shared.mjs"; +import { runTests } from "./runner-core.mjs"; +import { importObject } from "/import.js"; + +self.addEventListener("message", event => { + const port = event.ports && event.ports[0]; + if (!port) { + return; + } + execute(port, event.data).catch(error => { + port.postMessage({ type: "report", lines: [String(error)], failed: 1 }); + }); +}); + +async function execute(port, { nocapture, filtered }) { + const tests = await (await fetch("/tests.json")).json(); + const wasmBytes = await (await fetch("/wasm")).arrayBuffer(); + const lines = []; + const formatter = createTextFormatter({ + nocapture, + write(line) { + lines.push(line); + if (nocapture) { + port.postMessage({ type: "line", line }); + } + }, + }); + + function emit(event) { + if (event.type === "test-output") { + port.postMessage({ + type: "user-output", + line: event.line, + stream: event.stream, + level: event.level || (event.stream === "stderr" ? "error" : "log"), + }); + } + formatter.onEvent(event); + } + + const testInputs = tests.map(test => ({ + ...test, + run(testFn, panicPayload, panicMessage) { + return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage, event => + emit(event) + ); + }, + })); + + const result = await runTests({ + wasmBytes, + importObject, + tests: testInputs, + filtered, + emit, + }); + + port.postMessage({ type: "report", lines, failed: result.failed }); +} + +function withConsoleCapture(name, run, panicPayload, panicMessage, emit) { + function emitOutput(line, stream, level) { + emit({ type: "test-output", name, line, stream, level }); + } + + const originalLog = console.log; + const originalError = console.error; + const originalWarn = console.warn; + const originalInfo = console.info; + const originalDebug = console.debug; + console.log = (...args) => emitOutput(args.join(" "), "stdout", "log"); + console.error = (...args) => emitOutput(args.join(" "), "stderr", "error"); + console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn"); + console.info = (...args) => emitOutput(args.join(" "), "stdout", "info"); + console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug"); + + try { + run(); + return { ok: true }; + } catch (error) { + return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() }; + } finally { + console.log = originalLog; + console.error = originalError; + console.warn = originalWarn; + console.info = originalInfo; + console.debug = originalDebug; + } +} diff --git a/host/js-bindgen-test-runner/js/shared.mjs b/host/js-bindgen-test-runner/js/shared.mjs new file mode 100644 index 00000000..b2bcd077 --- /dev/null +++ b/host/js-bindgen-test-runner/js/shared.mjs @@ -0,0 +1,120 @@ +export function createTextFormatter({ nocapture, write }) { + const buffered = new Map(); + const failed = []; + const failure_reports = []; + const green = "\u001b[32m"; + const red = "\u001b[31m"; + const yellow = "\u001b[33m"; + const reset = "\u001b[0m"; + + function buffer(name, line, stream) { + if (!buffered.has(name)) { + buffered.set(name, []); + } + buffered.get(name).push({ line, stream }); + } + + function take_buffer(name) { + const entries = buffered.get(name); + if (!entries || entries.length === 0) { + return []; + } + buffered.delete(name); + return entries; + } + + return { + onEvent(event) { + switch (event.type) { + case "run-start": + write("", "stdout"); + write(`running ${event.total} tests`, "stdout"); + break; + case "test-output": + if (nocapture) { + write(event.line, event.stream); + } + if (!nocapture) { + buffer(event.name, event.line, event.stream); + } + break; + case "test-ok": + take_buffer(event.name); + if (event.should_panic) { + write( + `test ${event.name} - should panic ... ${green}ok${reset}`, + "stdout" + ); + } else { + write(`test ${event.name} ... ${green}ok${reset}`, "stdout"); + } + break; + case "test-ignored": + take_buffer(event.name); + if (event.reason) { + write( + `test ${event.name} ... ${yellow}ignored, ${event.reason}${reset}`, + "stdout" + ); + } else { + write(`test ${event.name} ... ${yellow}ignored${reset}`, "stdout"); + } + break; + case "test-failed": + failed.push(event.name); + if (event.should_panic) { + write( + `test ${event.name} - should panic ... ${red}FAILED${reset}`, + "stdout" + ); + } else { + write(`test ${event.name} ... ${red}FAILED${reset}`, "stdout"); + } + failure_reports.push({ + name: event.name, + entries: take_buffer(event.name), + error: event.error, + }); + break; + case "run-end": + write("", "stdout"); + if (failed.length > 0) { + write("failures:", "stdout"); + write("", "stdout"); + for (const report of failure_reports) { + write(`---- ${report.name} stdout ----`, "stdout"); + for (const entry of report.entries) { + write(entry.line, entry.stream); + } + if (report.error) { + write("", "stdout"); + write(report.error, "stdout"); + } + write("", "stdout"); + } + } + const status = + event.status === "ok" + ? `${green}${event.status}${reset}` + : `${red}${event.status}${reset}`; + const durationMs = typeof event.duration_ms === "number" ? event.duration_ms : 0; + const durationSeconds = (durationMs / 1000).toFixed(2); + if (failed.length > 0) { + write("failures:", "stdout"); + for (const name of failed) { + write(` ${name}`, "stdout"); + } + write("", "stdout"); + } + write( + `test result: ${status}. ${event.passed} passed; ${event.failed} failed; ${event.ignored} ignored; 0 measured; ${event.filtered} filtered out; finished in ${durationSeconds}s`, + "stdout" + ); + write("", "stdout"); + break; + default: + break; + } + }, + }; +} diff --git a/host/js-bindgen-test-runner/js/worker-runner.mjs b/host/js-bindgen-test-runner/js/worker-runner.mjs new file mode 100644 index 00000000..6c193f3c --- /dev/null +++ b/host/js-bindgen-test-runner/js/worker-runner.mjs @@ -0,0 +1,96 @@ +import { createTextFormatter } from "./shared.mjs"; +import { runTests } from "./runner-core.mjs"; + +async function execute(port, { nocapture, filtered }) { + const tests = await (await fetch("/tests.json")).json(); + const wasmBytes = await (await fetch("/wasm")).arrayBuffer(); + const { importObject } = await import("/import.js"); + + const lines = []; + const formatter = createTextFormatter({ + nocapture, + write(line) { + lines.push(line); + port.postMessage({ type: "line", line }); + }, + }); + + function emit(event) { + if (event.type === "test-output") { + port.postMessage({ + type: "user-output", + line: event.line, + stream: event.stream, + level: event.level || (event.stream === "stderr" ? "error" : "log"), + }); + } + formatter.onEvent(event); + } + + const testInputs = tests.map(test => ({ + ...test, + run(testFn, panicPayload, panicMessage) { + return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage, event => + emit(event) + ); + }, + })); + + const result = await runTests({ + wasmBytes, + importObject, + tests: testInputs, + filtered, + emit, + }); + + port.postMessage({ type: "report", lines, failed: result.failed }); +} + +if (typeof self.onconnect !== "undefined") { + self.onconnect = event => { + const port = event.ports[0]; + port.onmessage = msg => { + execute(port, msg.data).catch(error => { + port.postMessage({ type: "report", lines: [String(error)], failed: 1 }); + }); + }; + port.start(); + }; +} else { + self.onmessage = event => { + execute(self, event.data).catch(error => { + self.postMessage({ type: "report", lines: [String(error)], failed: 1 }); + }); + }; +} + +function withConsoleCapture(name, run, panicPayload, panicMessage, emit) { + function emitOutput(line, stream, level) { + emit({ type: "test-output", name, line, stream, level }); + } + + const originalLog = console.log; + const originalError = console.error; + const originalWarn = console.warn; + const originalInfo = console.info; + const originalDebug = console.debug; + console.log = (...args) => emitOutput(args.join(" "), "stdout", "log"); + console.error = (...args) => emitOutput(args.join(" "), "stderr", "error"); + console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn"); + console.info = (...args) => emitOutput(args.join(" "), "stdout", "info"); + console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug"); + + try { + run(); + return { ok: true }; + } catch (error) { + return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() }; + } finally { + console.log = originalLog; + console.error = originalError; + console.warn = originalWarn; + console.info = originalInfo; + console.debug = originalDebug; + } +} diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-test-runner/src/main.rs new file mode 100644 index 00000000..17f9b0a6 --- /dev/null +++ b/host/js-bindgen-test-runner/src/main.rs @@ -0,0 +1,674 @@ +use std::env; +use std::fs; +use std::io::{ErrorKind, Read, Write as IoWrite}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::{ + Arc, Condvar, Mutex, + atomic::{AtomicBool, Ordering}, +}; +use std::thread; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use wasmparser::{Parser, Payload}; + +const NODE_RUNNER: &str = "js/node-runner.mjs"; +const PLAYWRIGHT_RUNNER: &str = "js/playwright-runner.mjs"; +const BROWSER_RUNNER_SOURCE: &str = include_str!("../js/browser-runner.mjs"); +const RUNNER_CORE_SOURCE: &str = include_str!("../js/runner-core.mjs"); +const SHARED_JS_SOURCE: &str = include_str!("../js/shared.mjs"); +const WORKER_RUNNER_SOURCE: &str = include_str!("../js/worker-runner.mjs"); +const SERVICE_WORKER_SOURCE: &str = include_str!("../js/service-worker.mjs"); + +#[derive(Debug, serde::Serialize)] +struct TestEntry { + name: String, + ignore: bool, + ignore_reason: Option, + should_panic: bool, + should_panic_reason: Option, +} + +fn main() -> Result<()> { + let mut args = env::args().skip(1).collect::>(); + let wasm_path = args + .first() + .map(PathBuf::from) + .context("expected a wasm file path")?; + let extra_args = args.split_off(1); + + let args = parse_test_args(extra_args)?; + let wasm_bytes = fs::read(&wasm_path) + .with_context(|| format!("failed to read wasm file: {}", wasm_path.display()))?; + + let mut tests = read_tests(&wasm_bytes)?; + let filtered_count = apply_filters(&mut tests, &args.filters, args.ignored_only, args.exact); + + if args.list_only { + match args.list_format { + ListFormat::Standard => { + for test in &tests { + println!("{}: test", test.name); + } + println!(); + println!("{} tests, 0 benchmarks", tests.len()); + } + ListFormat::Terse => { + for test in &tests { + println!("{}: test", test.name); + } + } + } + return Ok(()); + } + + if tests.is_empty() { + println!(); + println!("running 0 tests"); + println!(); + println!( + "test result: \u{001b}[32mok\u{001b}[0m. 0 passed; 0 failed; 0 ignored; 0 measured; {filtered_count} filtered out; finished in 0.00s" + ); + println!(); + return Ok(()); + } + + // `web_sys-4e01138c76cd2a1a.wasm` to `web_sys-4e01138c76cd2a1a.js` + let imports_path = wasm_path.with_extension("js"); + let tests_json = serde_json::to_string(&tests).expect("checked"); + + match args.runner.kind { + RunnerKind::Node => run_node( + &wasm_path, + &imports_path, + tests_json, + filtered_count, + args.nocapture, + )?, + RunnerKind::Browser => run_playwright( + &wasm_path, + &imports_path, + tests_json, + filtered_count, + args.nocapture, + &args.runner, + )?, + RunnerKind::BrowserServer => run_browser_server( + &wasm_path, + &imports_path, + tests_json, + filtered_count, + args.nocapture, + &args.runner, + )?, + } + + Ok(()) +} + +fn parse_test_args(args: Vec) -> Result { + let mut output = TestArgs { + list_only: false, + nocapture: false, + filters: Vec::new(), + list_format: ListFormat::Standard, + ignored_only: false, + exact: false, + runner: RunnerConfig::from_env()?, + }; + + let mut iter = args.into_iter(); + while let Some(arg) = iter.next() { + if arg == "--list" { + output.list_only = true; + } else if arg == "--nocapture" { + output.nocapture = true; + } else if arg == "--ignored" { + output.ignored_only = true; + } else if arg == "--exact" { + output.exact = true; + } else if let Some(value) = arg.strip_prefix("--format=") { + if value == "terse" { + output.list_format = ListFormat::Terse; + } + } else if arg == "--format" { + if let Some(value) = iter.next() { + if value == "terse" { + output.list_format = ListFormat::Terse; + } + } + } else if arg.starts_with('-') { + continue; + } else { + output.filters.push(arg); + } + } + + Ok(output) +} + +enum ListFormat { + Standard, + Terse, +} + +struct TestArgs { + list_only: bool, + nocapture: bool, + filters: Vec, + list_format: ListFormat, + ignored_only: bool, + exact: bool, + runner: RunnerConfig, +} + +#[derive(Debug)] +struct RunnerConfig { + kind: RunnerKind, + browser: String, + worker: Option, +} + +impl RunnerConfig { + fn from_env() -> Result { + let mut config = RunnerConfig { + kind: RunnerKind::Node, + browser: "chromium".to_string(), + worker: None, + }; + + if let Ok(worker) = env::var("JBTEST_WORKER") { + if !matches!(worker.as_str(), "dedicated" | "shared" | "service") { + bail!("unsupported {worker}, supported dedicated, shared and service"); + } + config.worker = Some(worker); + } + + if let Ok(browser) = env::var("JBTEST_BROWSER") { + config.kind = RunnerKind::Browser; + if matches!(browser.as_str(), "chromium" | "firefox" | "webkit") { + config.browser = browser; + } + } + + if std::env::var("JBTEST_SERVER").is_ok() { + config.kind = RunnerKind::BrowserServer; + } + + Ok(config) + } +} + +#[derive(Debug)] +enum RunnerKind { + Node, + Browser, + BrowserServer, +} + +fn run_node( + wasm_path: &Path, + imports_path: &Path, + tests_json: String, + filtered_count: usize, + nocapture: bool, +) -> Result<()> { + ensure_module_package(imports_path); + let runner_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(NODE_RUNNER); + + let status = Command::new("node") + .arg(runner_path) + .env("JS_BINDGEN_WASM", wasm_path) + .env("JS_BINDGEN_IMPORTS", imports_path) + .env("JS_BINDGEN_TESTS", tests_json) + .env("JS_BINDGEN_FILTERED", filtered_count.to_string()) + .env("JS_BINDGEN_NOCAPTURE", if nocapture { "1" } else { "0" }) + .status() + .context("failed to run node")?; + + if !status.success() { + std::process::exit(status.code().unwrap_or(1)); + } + + Ok(()) +} + +fn ensure_module_package(imports_path: &Path) { + let Some(parent) = imports_path.parent() else { + return; + }; + let package_json = parent.join("package.json"); + if let Err(err) = fs::write(&package_json, r#"{"type": "module"}"#) { + eprintln!("failed to write package.json: {err}"); + } +} + +fn run_playwright( + wasm_path: &Path, + imports_path: &Path, + tests_json: String, + filtered_count: usize, + nocapture: bool, + runner: &RunnerConfig, +) -> Result<()> { + let assets = BrowserAssets::new( + wasm_path, + imports_path, + &tests_json, + filtered_count, + nocapture, + runner.worker.as_deref(), + )?; + let server = HttpServer::start(assets, env::var("JBTEST_SERVER_ADDRESS").ok().as_deref())?; + let url = build_browser_url(server.base_url.as_str()); + + let runner_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(PLAYWRIGHT_RUNNER); + let mut child = Command::new("node") + .arg(runner_path) + .env("JBTEST_URL", url) + .env("JBTEST_BROWSER", runner.browser.clone()) + .spawn() + .context("failed to run node")?; + + let report = server.wait_for_report(); + server.shutdown.store(true, Ordering::Relaxed); + + for line in report.lines { + println!("{line}"); + } + + let _ = child.kill(); + let _ = child.wait(); + + if report.failed > 0 { + std::process::exit(1); + } + + Ok(()) +} + +fn run_browser_server( + wasm_path: &Path, + imports_path: &Path, + tests_json: String, + filtered_count: usize, + nocapture: bool, + runner: &RunnerConfig, +) -> Result<()> { + let assets = BrowserAssets::new( + wasm_path, + imports_path, + &tests_json, + filtered_count, + nocapture, + runner.worker.as_deref(), + )?; + let server = HttpServer::start(assets, env::var("JBTEST_SERVER_ADDRESS").ok().as_deref())?; + let url = build_browser_url(server.base_url.as_str()); + + println!("open this URL in your browser to run tests:"); + println!("{url}"); + + loop { + let _ = server.wait_for_report(); + } +} + +fn build_browser_url(base_url: &str) -> String { + format!("{base_url}/index.html") +} + +#[derive(Debug, serde::Deserialize)] +struct Report { + lines: Vec, + failed: u64, +} + +struct ReportState { + result: Mutex>, + signal: Condvar, +} + +struct BrowserAssets { + wasm_bytes: Vec, + import_js: String, + tests_json: String, + runner_js: &'static str, + core_js: &'static str, + shared_js: &'static str, + worker_js: &'static str, + service_worker_js: &'static str, + index_html: String, +} + +impl BrowserAssets { + fn new( + wasm_path: &Path, + imports_path: &Path, + tests_json: &str, + filtered_count: usize, + nocapture: bool, + worker: Option<&str>, + ) -> Result { + let wasm_bytes = fs::read(wasm_path)?; + let import_js = fs::read_to_string(imports_path)?; + + let index_html = format!( + r#" + +js-bindgen test +

+
+"#,
+			filtered_count = filtered_count,
+			nocapture_flag = if nocapture { "true" } else { "false" },
+			worker = if let Some(worker) = worker {
+				format!("{worker:?}")
+			} else {
+				"null".to_owned()
+			},
+		);
+
+		Ok(Self {
+			wasm_bytes,
+			import_js,
+			tests_json: tests_json.to_string(),
+			runner_js: BROWSER_RUNNER_SOURCE,
+			core_js: RUNNER_CORE_SOURCE,
+			shared_js: SHARED_JS_SOURCE,
+			worker_js: WORKER_RUNNER_SOURCE,
+			service_worker_js: SERVICE_WORKER_SOURCE,
+			index_html,
+		})
+	}
+}
+
+struct HttpServer {
+	base_url: String,
+	shutdown: Arc,
+	report_state: Arc,
+}
+
+impl HttpServer {
+	fn start(assets: BrowserAssets, address: Option<&str>) -> Result {
+		let listener = bind_default_port(address).context("failed to bind server")?;
+		let local_addr = listener.local_addr()?;
+		let base_url = format!("http://{}:{}", local_addr.ip(), local_addr.port());
+		let shutdown = Arc::new(AtomicBool::new(false));
+		let shutdown_flag = Arc::clone(&shutdown);
+		let assets = Arc::new(assets);
+		let report_state = Arc::new(ReportState {
+			result: Mutex::new(None),
+			signal: Condvar::new(),
+		});
+		let report_state_thread = Arc::clone(&report_state);
+
+		listener
+			.set_nonblocking(true)
+			.context("failed to set nonblocking")?;
+
+		thread::spawn(move || {
+			while !shutdown_flag.load(Ordering::Relaxed) {
+				match listener.accept() {
+					Ok((stream, _)) => {
+						let assets = Arc::clone(&assets);
+						let report_state = Arc::clone(&report_state_thread);
+						let _ = handle_connection(stream, assets, report_state);
+					}
+					Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
+						thread::sleep(Duration::from_millis(5));
+					}
+					Err(_) => break,
+				}
+			}
+		});
+
+		Ok(Self {
+			base_url,
+			shutdown,
+			report_state,
+		})
+	}
+
+	fn wait_for_report(&self) -> Report {
+		let mut guard = self.report_state.result.lock().unwrap();
+		loop {
+			if let Some(report) = guard.take() {
+				return report;
+			}
+			guard = self.report_state.signal.wait(guard).unwrap();
+		}
+	}
+}
+
+fn bind_default_port(address: Option<&str>) -> Result {
+	let default_addr = address.unwrap_or("127.0.0.1:8000");
+	match TcpListener::bind(default_addr) {
+		Ok(listener) => Ok(listener),
+		Err(err) if err.kind() == ErrorKind::AddrInUse => {
+			let fallback_addr = address
+				.and_then(|addr| addr.split_once(':'))
+				.map(|(ip, _)| format!("{ip}:0"))
+				.unwrap_or_else(|| "127.0.0.1:0".to_string());
+			TcpListener::bind(&fallback_addr).context("failed to bind fallback port")
+		}
+		Err(err) => Err(err).context("failed to bind default port"),
+	}
+}
+
+fn handle_connection(
+	mut stream: TcpStream,
+	assets: Arc,
+	report_state: Arc,
+) -> Result<()> {
+	let mut buffer = [0u8; 4096];
+	let mut request = Vec::new();
+	let mut header_end = 0;
+
+	loop {
+		let size = stream.read(&mut buffer)?;
+		if size == 0 {
+			break;
+		}
+		let len = request.len();
+		request.extend_from_slice(&buffer[..size]);
+
+		if let Some(pos) = request[len.saturating_sub(3)..]
+			.windows(4)
+			.position(|window| window == b"\r\n\r\n")
+		{
+			header_end = pos;
+			break;
+		}
+	}
+
+	let (header_bytes, body) = request.split_at(header_end + 4);
+	let request_text = String::from_utf8_lossy(header_bytes);
+	let mut lines = request_text.lines();
+	let Some(request_line) = lines.next() else {
+		return Ok(());
+	};
+
+	// GET /index.html HTTP/1.1
+	let mut parts = request_line.split_whitespace();
+	let method = parts.next().unwrap_or_default();
+	let path = parts.next().unwrap_or("/");
+
+	let mut content_length = 0usize;
+	for line in lines {
+		if let Some(value) = line.strip_prefix("Content-Length:") {
+			content_length = value.trim().parse().unwrap_or(0);
+		}
+	}
+
+	if method == "POST" && path.starts_with("/report") {
+		let mut body_vec = body.to_vec();
+		while body_vec.len() < content_length {
+			let size = stream.read(&mut buffer)?;
+			if size == 0 {
+				break;
+			}
+			body_vec.extend_from_slice(&buffer[..size]);
+		}
+
+		let report = serde_json::from_slice(&body_vec)?;
+		*report_state.result.lock().unwrap() = Some(report);
+		report_state.signal.notify_all();
+
+		write_response(&mut stream, 200, "text/plain", b"OK")?;
+		return Ok(());
+	}
+
+	if method != "GET" {
+		write_response(&mut stream, 405, "text/plain", b"Method Not Allowed")?;
+		return Ok(());
+	}
+
+	let (body, content_type, status) = match path {
+		"/" | "/index.html" => (assets.index_html.as_bytes(), "text/html", 200),
+		"/browser-runner.mjs" => (assets.runner_js.as_bytes(), "application/javascript", 200),
+		"/runner-core.mjs" => (assets.core_js.as_bytes(), "application/javascript", 200),
+		"/shared.mjs" => (assets.shared_js.as_bytes(), "application/javascript", 200),
+		"/worker-runner.mjs" => (assets.worker_js.as_bytes(), "application/javascript", 200),
+		"/service-worker.mjs" => (
+			assets.service_worker_js.as_bytes(),
+			"application/javascript",
+			200,
+		),
+		"/import.js" => (assets.import_js.as_bytes(), "application/javascript", 200),
+		"/tests.json" => (assets.tests_json.as_bytes(), "application/json", 200),
+		"/wasm" => (assets.wasm_bytes.as_slice(), "application/wasm", 200),
+		_ => (b"Not Found".as_slice(), "text/plain", 404),
+	};
+
+	write_response(&mut stream, status, content_type, body)?;
+	Ok(())
+}
+
+fn write_response(
+	stream: &mut TcpStream,
+	status: u16,
+	content_type: &str,
+	body: &[u8],
+) -> Result<()> {
+	let status_text = match status {
+		200 => "OK",
+		404 => "Not Found",
+		405 => "Method Not Allowed",
+		_ => "OK",
+	};
+	write!(
+		stream,
+		"HTTP/1.1 {status} {status_text}\r\nContent-Length: {}\r\nContent-Type: {content_type}\r\n\r\n",
+		body.len()
+	)?;
+	stream.write_all(body)?;
+	Ok(())
+}
+
+fn read_tests(wasm_bytes: &[u8]) -> Result> {
+	/// None: `[0]`
+	///
+	/// Some(None): `[1]`
+	///
+	/// Some(Some(s)): `[2][len(s)][len]`
+	fn option_option_string(
+		data: &[u8],
+		mut offset: usize,
+	) -> Result<(Option>, usize)> {
+		offset += 1;
+		let value = match data[offset - 1] {
+			0 => None,
+			1 => Some(None),
+			2 => {
+				let len = u32::from_le_bytes(
+					data[offset..offset + 4]
+						.try_into()
+						.expect("slice length checked"),
+				) as usize;
+				offset += 4;
+				let s = std::str::from_utf8(&data[offset..offset + len])
+					.context("payload is not utf-8")?
+					.to_string();
+				offset += len;
+				Some(Some(s))
+			}
+			_ => bail!("mismatch flag value"),
+		};
+		Ok((value, offset))
+	}
+
+	let mut tests = Vec::new();
+
+	for payload in Parser::new(0).parse_all(wasm_bytes) {
+		if let Payload::CustomSection(section) = payload.context("failed to parse wasm")?
+			&& section.name() == "js_bindgen.test"
+		{
+			let mut offset = 0;
+			let data = section.data();
+
+			while offset < data.len() {
+				let len = u32::from_le_bytes(
+					data[offset..offset + 4]
+						.try_into()
+						.expect("slice length checked"),
+				) as usize;
+				offset += 4;
+				let end = offset + len;
+
+				let (ignore, offset1) = option_option_string(data, offset)?;
+				let (should_panic, offset2) = option_option_string(data, offset1)?;
+
+				let name =
+					std::str::from_utf8(&data[offset2..end]).context("test name is not utf-8")?;
+
+				tests.push(TestEntry {
+					name: name.to_string(),
+					ignore: ignore.is_some(),
+					ignore_reason: ignore.and_then(|s| s),
+					should_panic: should_panic.is_some(),
+					should_panic_reason: should_panic.and_then(|s| s),
+				});
+
+				offset = end;
+			}
+		}
+	}
+
+	Ok(tests)
+}
+
+fn apply_filters(
+	tests: &mut Vec,
+	filters: &[String],
+	ignored_only: bool,
+	exact: bool,
+) -> usize {
+	let initial = tests.len();
+	tests.retain(|test| {
+		let matches_ignore = !ignored_only || test.ignore;
+		let matches_filter = if filters.is_empty() {
+			true
+		} else if exact {
+			filters.contains(&test.name)
+		} else {
+			filters.iter().any(|filter| test.name.contains(filter))
+		};
+		matches_ignore && matches_filter
+	});
+	initial - tests.len()
+}
diff --git a/host/js-bindgen/src/lib.rs b/host/js-bindgen/src/lib.rs
index 279c7052..c2f0eb01 100644
--- a/host/js-bindgen/src/lib.rs
+++ b/host/js-bindgen/src/lib.rs
@@ -22,12 +22,10 @@ mod tests;
 #[cfg(not(test))]
 use std::env;
 use std::iter::Peekable;
-use std::{iter, mem};
+use std::mem;
 
 use js_bindgen_macro_shared::*;
-use proc_macro::{
-	Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree, token_stream,
-};
+use proc_macro::{Delimiter, Span, TokenStream, TokenTree, token_stream};
 
 #[cfg_attr(not(test), proc_macro)]
 pub fn unsafe_embed_asm(input: TokenStream) -> TokenStream {
@@ -82,16 +80,6 @@ fn import_js_internal(input: TokenStream) -> Result {
 	))
 }
 
-struct Argument {
-	cfg: Option<[TokenTree; 2]>,
-	kind: ArgumentKind,
-}
-
-enum ArgumentKind {
-	String(String),
-	Interpolate(Vec),
-}
-
 fn parse_string_arguments(
 	mut stream: &mut Peekable,
 	mut previous_span: Span,
@@ -291,385 +279,6 @@ fn parse_string_arguments(
 	}
 }
 
-/// ```"not rust"
-/// const _: () = {
-/// 	const LEN: u32 = {
-/// 		let mut len: usize = 0;
-/// 		#(len += LEN_;)*
-/// 		len as u32
-/// 	};
-///
-/// 	const _: () = {
-/// 		#[repr(C)]
-/// 		struct Layout([u8; 4], #([u8; LEN_]),*);
-///
-/// 		#[link_section = name]
-/// 		static CUSTOM_SECTION: Layout = Layout(::core::primitive::u32::to_le_bytes(LEN), #(ARR_),*);
-/// 	};
-/// };
-/// ```
-fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> TokenStream {
-	let span = Span::mixed_site();
-
-	// If a prefix is present:
-	// `const ARR_PREFIX: [u8; .len()] = *;`
-	let const_prefix = prefix
-		.into_iter()
-		.filter(|prefix| !prefix.is_empty())
-		.flat_map(|prefix| {
-			r#const(
-				"ARR_PREFIX",
-				iter::once(group(
-					Delimiter::Bracket,
-					[
-						ident("u8"),
-						Punct::new(';', Spacing::Alone).into(),
-						Literal::usize_unsuffixed(prefix.len()).into(),
-					],
-				)),
-				[
-					Punct::new('*', Spacing::Alone).into(),
-					Literal::byte_string(prefix.as_bytes()).into(),
-				],
-			)
-		});
-
-	// For every string we insert:
-	// ```
-	// const ARR_: [u8; .len()] = *;
-	// ```
-	//
-	// For every formatting argument we insert:
-	// ```
-	// const VAL_: &str = ;
-	// const LEN_: usize = ::core::primitive::str::len(VAL_);
-	// const PTR_: *const u8 = ::core::primitive::str::as_ptr(VAL_);
-	// const ARR_: [u8; LEN_] = unsafe { *(PTR_ as *const _) };
-	// ```
-	let consts = data
-		.iter()
-		.enumerate()
-		.flat_map(|(index, arg)| match &arg.kind {
-			ArgumentKind::String(string) => {
-				// `const ARR_: [u8; .len()] = *;`
-				arg.cfg
-					.clone()
-					.into_iter()
-					.flatten()
-					.chain(r#const(
-						&format!("ARR_{index}"),
-						iter::once(group(
-							Delimiter::Bracket,
-							[
-								ident("u8"),
-								Punct::new(';', Spacing::Alone).into(),
-								Literal::usize_unsuffixed(string.len()).into(),
-							],
-						)),
-						[
-							Punct::new('*', Spacing::Alone).into(),
-							Literal::byte_string(string.as_bytes()).into(),
-						],
-					))
-					.collect::>()
-			}
-			ArgumentKind::Interpolate(interpolate) => {
-				let value_name = format!("VAL_{index}");
-				let value = ident(&value_name);
-				let len_name = format!("LEN_{index}");
-				let ptr_name = format!("PTR_{index}");
-
-				// `const VAL_: &str = ;`
-				arg.cfg
-					.clone()
-					.into_iter()
-					.flatten()
-					.chain(r#const(
-						&value_name,
-						[Punct::new('&', Spacing::Alone).into(), ident("str")],
-						interpolate.iter().cloned(),
-					))
-					// `const LEN_: usize = ::core::primitive::str::len(VAL_);`
-					.chain(arg.cfg.clone().into_iter().flatten())
-					.chain(r#const(
-						&len_name,
-						iter::once(ident("usize")),
-						path(["core", "primitive", "str", "len"], span).chain(iter::once(group(
-							Delimiter::Parenthesis,
-							iter::once(value.clone()),
-						))),
-					))
-					// `const PTR_: *const u8 = ::core::primitive::str::as_ptr(VAL_);`
-					.chain(arg.cfg.clone().into_iter().flatten())
-					.chain(r#const(
-						&ptr_name,
-						[
-							Punct::new('*', Spacing::Alone).into(),
-							ident("const"),
-							ident("u8"),
-						],
-						path(["core", "primitive", "str", "as_ptr"], span)
-							.chain(iter::once(group(Delimiter::Parenthesis, iter::once(value)))),
-					))
-					// `const ARR_: [u8; LEN_] = unsafe { *(PTR_ as *const _)
-					// };`
-					.chain(arg.cfg.clone().into_iter().flatten())
-					.chain(r#const(
-						&format!("ARR_{index}"),
-						iter::once(group(
-							Delimiter::Bracket,
-							[
-								ident("u8"),
-								Punct::new(';', Spacing::Alone).into(),
-								ident(&len_name),
-							],
-						)),
-						[
-							ident("unsafe"),
-							group(
-								Delimiter::Brace,
-								[
-									Punct::new('*', Spacing::Alone).into(),
-									group(
-										Delimiter::Parenthesis,
-										[
-											ident(&ptr_name),
-											ident("as"),
-											Punct::new('*', Spacing::Alone).into(),
-											ident("const"),
-											ident("_"),
-										],
-									),
-								],
-							),
-						],
-					))
-					.collect::>()
-			}
-		});
-
-	// ```
-	// const LEN: u32 = {
-	//     let mut len: usize = 0;
-	//     #(len += LEN_;)*
-	//     len as u32
-	// };
-	// ```
-	let len = r#const(
-		"LEN",
-		iter::once(ident("u32")),
-		[group(
-			Delimiter::Brace,
-			[
-				ident("let"),
-				ident("mut"),
-				ident("len"),
-				Punct::new(':', Spacing::Alone).into(),
-				ident("usize"),
-				Punct::new('=', Spacing::Alone).into(),
-				Literal::usize_unsuffixed(0).into(),
-				Punct::new(';', Spacing::Alone).into(),
-			]
-			.into_iter()
-			.chain(data.iter().enumerate().flat_map(|(index, par)| {
-				par.cfg
-					.clone()
-					.into_iter()
-					.flatten()
-					.chain(iter::once(group(
-						Delimiter::Brace,
-						[
-							ident("len"),
-							Punct::new('+', Spacing::Joint).into(),
-							Punct::new('=', Spacing::Alone).into(),
-							match &par.kind {
-								ArgumentKind::String(string) => {
-									Literal::usize_unsuffixed(string.len()).into()
-								}
-								ArgumentKind::Interpolate(_) => ident(&format!("LEN_{index}")),
-							},
-							Punct::new(';', Spacing::Alone).into(),
-						],
-					)))
-			}))
-			.chain([ident("len"), ident("as"), ident("u32")]),
-		)],
-	);
-
-	// `[u8; 4], #([u8; LEN_]),*`
-	let tys = [
-		group(
-			Delimiter::Bracket,
-			[
-				ident("u8"),
-				Punct::new(';', Spacing::Alone).into(),
-				Literal::usize_unsuffixed(4).into(),
-			],
-		),
-		Punct::new(',', Spacing::Alone).into(),
-	]
-	.into_iter()
-	// Optional prefix length.
-	.chain(prefix.into_iter().flat_map(|prefix| {
-		[
-			group(
-				Delimiter::Bracket,
-				[
-					ident("u8"),
-					Punct::new(';', Spacing::Alone).into(),
-					Literal::usize_unsuffixed(2).into(),
-				],
-			),
-			Punct::new(',', Spacing::Alone).into(),
-		]
-		.into_iter()
-		.chain(
-			(!prefix.is_empty())
-				.then(|| {
-					[
-						group(
-							Delimiter::Bracket,
-							[
-								ident("u8"),
-								Punct::new(';', Spacing::Alone).into(),
-								Literal::usize_unsuffixed(prefix.len()).into(),
-							],
-						),
-						Punct::new(',', Spacing::Alone).into(),
-					]
-				})
-				.into_iter()
-				.flatten(),
-		)
-	}))
-	.chain(data.iter().enumerate().flat_map(move |(index, arg)| {
-		arg.cfg.clone().into_iter().flatten().chain([
-			group(
-				Delimiter::Bracket,
-				[
-					ident("u8"),
-					Punct::new(';', Spacing::Alone).into(),
-					match &arg.kind {
-						ArgumentKind::String(string) => {
-							Literal::usize_unsuffixed(string.len()).into()
-						}
-						ArgumentKind::Interpolate(_) => ident(&format!("LEN_{index}")),
-					},
-				],
-			),
-			Punct::new(',', Spacing::Alone).into(),
-		])
-	}));
-
-	// ```
-	// #[repr(C)]
-	// struct Layout(...);
-	// ```
-	let layout = [
-		Punct::new('#', Spacing::Alone).into(),
-		group(
-			Delimiter::Bracket,
-			[
-				ident("repr"),
-				group(Delimiter::Parenthesis, iter::once(ident("C"))),
-			],
-		),
-		ident("struct"),
-		ident("Layout"),
-		group(Delimiter::Parenthesis, tys),
-		Punct::new(';', Spacing::Alone).into(),
-	];
-
-	// `#[link_section = name]`
-	let link_section = [
-		Punct::new('#', Spacing::Alone).into(),
-		group(
-			Delimiter::Bracket,
-			[
-				ident("unsafe"),
-				group(
-					Delimiter::Parenthesis,
-					[
-						ident("link_section"),
-						Punct::new('=', Spacing::Alone).into(),
-						Literal::string(name).into(),
-					],
-				),
-			],
-		),
-	];
-
-	// (::core::primitive::u32::to_le_bytes(LEN), #(ARR_),*)
-	let values = group(
-		Delimiter::Parenthesis,
-		path(["core", "primitive", "u32", "to_le_bytes"], span)
-			.chain([
-				group(Delimiter::Parenthesis, iter::once(ident("LEN"))),
-				Punct::new(',', Spacing::Alone).into(),
-			])
-			// Optional prefix value.
-			.chain(prefix.into_iter().flat_map(|prefix| {
-				let len = u16::try_from(prefix.len()).unwrap().to_le_bytes();
-
-				[
-					group(
-						Delimiter::Bracket,
-						[
-							Literal::u8_unsuffixed(len[0]).into(),
-							Punct::new(',', Spacing::Alone).into(),
-							Literal::u8_unsuffixed(len[1]).into(),
-							Punct::new(',', Spacing::Alone).into(),
-						],
-					),
-					Punct::new(',', Spacing::Alone).into(),
-				]
-				.into_iter()
-				.chain(
-					(!prefix.is_empty())
-						.then(|| [ident("ARR_PREFIX"), Punct::new(',', Spacing::Alone).into()])
-						.into_iter()
-						.flatten(),
-				)
-			}))
-			.chain(data.iter().enumerate().flat_map(move |(index, arg)| {
-				arg.cfg.clone().into_iter().flatten().chain([
-					ident(&format!("ARR_{index}")),
-					Punct::new(',', Spacing::Alone).into(),
-				])
-			})),
-	);
-
-	// `static CUSTOM_SECTION: Layout = Layout(...);`
-	let custom_section = [
-		ident("static"),
-		ident("CUSTOM_SECTION"),
-		Punct::new(':', Spacing::Alone).into(),
-		ident("Layout"),
-		Punct::new('=', Spacing::Alone).into(),
-		ident("Layout"),
-		values,
-		Punct::new(';', Spacing::Alone).into(),
-	];
-
-	// `const _: () = { ... }`
-	r#const(
-		"_",
-		iter::once(group(Delimiter::Parenthesis, iter::empty())),
-		iter::once(group(
-			Delimiter::Brace,
-			const_prefix.chain(consts).chain(len).chain(r#const(
-				"_",
-				iter::once(group(Delimiter::Parenthesis, iter::empty())),
-				iter::once(group(
-					Delimiter::Brace,
-					layout.into_iter().chain(link_section).chain(custom_section),
-				)),
-			)),
-		)),
-	)
-	.collect()
-}
-
 fn expect_meta_name_value(
 	stream: &mut Peekable,
 	attribute: &str,
@@ -687,31 +296,6 @@ fn expect_meta_name_value(
 	Ok(string)
 }
 
-fn r#const(
-	name: &str,
-	ty: impl IntoIterator,
-	value: impl IntoIterator,
-) -> impl Iterator {
-	[
-		ident("const"),
-		ident(name),
-		Punct::new(':', Spacing::Alone).into(),
-	]
-	.into_iter()
-	.chain(ty)
-	.chain(iter::once(Punct::new('=', Spacing::Alone).into()))
-	.chain(value)
-	.chain(iter::once(Punct::new(';', Spacing::Alone).into()))
-}
-
-fn group(delimiter: Delimiter, inner: impl IntoIterator) -> TokenTree {
-	Group::new(delimiter, inner.into_iter().collect()).into()
-}
-
-fn ident(string: &str) -> TokenTree {
-	Ident::new(string, Span::mixed_site()).into()
-}
-
 #[cfg(not(test))]
 #[cfg_attr(coverage_nightly, coverage(off))]
 fn package() -> String {
diff --git a/host/ld/src/main.rs b/host/ld/src/main.rs
index 1d19d1e7..ea3c0b61 100644
--- a/host/ld/src/main.rs
+++ b/host/ld/src/main.rs
@@ -407,10 +407,9 @@ fn post_processing(output_path: &Path, main_memory: MainMemory<'_>) -> Vec {
 		"missing JS embed: {expected_embed:?}"
 	);
 
-	let mut js_output = BufWriter::new(
-		File::create(output_path.with_file_name(package).with_extension("js"))
-			.expect("output JS file should be writable"),
-	);
+	let js_output_path = output_path.with_file_name(package).with_extension("js");
+	let mut js_output =
+		BufWriter::new(File::create(&js_output_path).expect("output JS file should be writable"));
 
 	// Create our `WebAssembly.Memory`.
 	js_output
@@ -498,5 +497,9 @@ fn post_processing(output_path: &Path, main_memory: MainMemory<'_>) -> Vec {
 
 	js_output.into_inner().unwrap().sync_all().unwrap();
 
+	// We also need a js file with a fingerprint, otherwise the test files might overwrite each other.
+	fs::copy(js_output_path, output_path.with_extension("js"))
+		.expect("copy JS file should be success");
+
 	wasm_output
 }
diff --git a/host/macro-shared/src/lib.rs b/host/macro-shared/src/lib.rs
index 60e67efe..f83b503e 100644
--- a/host/macro-shared/src/lib.rs
+++ b/host/macro-shared/src/lib.rs
@@ -10,6 +10,448 @@ use proc_macro::{
 	Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree, token_stream,
 };
 
+pub struct Argument {
+	pub cfg: Option<[TokenTree; 2]>,
+	pub kind: ArgumentKind,
+}
+
+pub enum ArgumentKind {
+	Bytes(Vec),
+	String(String),
+	Interpolate(Vec),
+}
+
+/// ```"not rust"
+/// const _: () = {
+/// 	const LEN: u32 = {
+/// 		let mut len: usize = 0;
+/// 		#(len += LEN_;)*
+/// 		len as u32
+/// 	};
+///
+/// 	const _: () = {
+/// 		#[repr(C)]
+/// 		struct Layout([u8; 4], #([u8; LEN_]),*);
+///
+/// 		#[link_section = name]
+/// 		static CUSTOM_SECTION: Layout = Layout(::core::primitive::u32::to_le_bytes(LEN), #(ARR_),*);
+/// 	};
+/// };
+/// ```
+pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> TokenStream {
+	fn group(delimiter: Delimiter, inner: impl IntoIterator) -> TokenTree {
+		Group::new(delimiter, inner.into_iter().collect()).into()
+	}
+
+	fn r#const(
+		name: &str,
+		ty: impl IntoIterator,
+		value: impl IntoIterator,
+	) -> impl Iterator {
+		[
+			ident("const"),
+			ident(name),
+			Punct::new(':', Spacing::Alone).into(),
+		]
+		.into_iter()
+		.chain(ty)
+		.chain(iter::once(Punct::new('=', Spacing::Alone).into()))
+		.chain(value)
+		.chain(iter::once(Punct::new(';', Spacing::Alone).into()))
+	}
+
+	fn ident(string: &str) -> TokenTree {
+		Ident::new(string, Span::mixed_site()).into()
+	}
+
+	let span = Span::mixed_site();
+
+	// If a prefix is present:
+	// `const ARR_PREFIX: [u8; .len()] = *;`
+	let const_prefix = prefix
+		.into_iter()
+		.filter(|prefix| !prefix.is_empty())
+		.flat_map(|prefix| {
+			r#const(
+				"ARR_PREFIX",
+				iter::once(group(
+					Delimiter::Bracket,
+					[
+						ident("u8"),
+						Punct::new(';', Spacing::Alone).into(),
+						Literal::usize_unsuffixed(prefix.len()).into(),
+					],
+				)),
+				[
+					Punct::new('*', Spacing::Alone).into(),
+					Literal::byte_string(prefix.as_bytes()).into(),
+				],
+			)
+		});
+
+	// For every string we insert:
+	// ```
+	// const ARR_: [u8; .len()] = *;
+	// ```
+	//
+	// For every formatting argument we insert:
+	// ```
+	// const VAL_: &str = ;
+	// const LEN_: usize = ::core::primitive::str::len(VAL_);
+	// const PTR_: *const u8 = ::core::primitive::str::as_ptr(VAL_);
+	// const ARR_: [u8; LEN_] = unsafe { *(PTR_ as *const _) };
+	// ```
+	let consts = data
+		.iter()
+		.enumerate()
+		.flat_map(|(index, arg)| match &arg.kind {
+			ArgumentKind::Bytes(bytes) => {
+				// `const ARR_: [u8; .len()] = ;`
+				arg.cfg
+					.clone()
+					.into_iter()
+					.flatten()
+					.chain(r#const(
+						&format!("ARR_{index}"),
+						iter::once(group(
+							Delimiter::Bracket,
+							[
+								ident("u8"),
+								Punct::new(';', Spacing::Alone).into(),
+								Literal::usize_unsuffixed(bytes.len()).into(),
+							],
+						)),
+						[
+							Punct::new('*', Spacing::Alone).into(),
+							Literal::byte_string(bytes).into(),
+						],
+					))
+					.collect::>()
+			}
+			ArgumentKind::String(string) => {
+				// `const ARR_: [u8; .len()] = *;`
+				arg.cfg
+					.clone()
+					.into_iter()
+					.flatten()
+					.chain(r#const(
+						&format!("ARR_{index}"),
+						iter::once(group(
+							Delimiter::Bracket,
+							[
+								ident("u8"),
+								Punct::new(';', Spacing::Alone).into(),
+								Literal::usize_unsuffixed(string.len()).into(),
+							],
+						)),
+						[
+							Punct::new('*', Spacing::Alone).into(),
+							Literal::byte_string(string.as_bytes()).into(),
+						],
+					))
+					.collect::>()
+			}
+			ArgumentKind::Interpolate(interpolate) => {
+				let value_name = format!("VAL_{index}");
+				let value = ident(&value_name);
+				let len_name = format!("LEN_{index}");
+				let ptr_name = format!("PTR_{index}");
+
+				// `const VAL_: &str = ;`
+				arg.cfg
+					.clone()
+					.into_iter()
+					.flatten()
+					.chain(r#const(
+						&value_name,
+						[Punct::new('&', Spacing::Alone).into(), ident("str")],
+						interpolate.iter().cloned(),
+					))
+					// `const LEN_: usize = ::core::primitive::str::len(VAL_);`
+					.chain(arg.cfg.clone().into_iter().flatten())
+					.chain(r#const(
+						&len_name,
+						iter::once(ident("usize")),
+						path(["core", "primitive", "str", "len"], span).chain(iter::once(group(
+							Delimiter::Parenthesis,
+							iter::once(value.clone()),
+						))),
+					))
+					// `const PTR_: *const u8 = ::core::primitive::str::as_ptr(VAL_);`
+					.chain(arg.cfg.clone().into_iter().flatten())
+					.chain(r#const(
+						&ptr_name,
+						[
+							Punct::new('*', Spacing::Alone).into(),
+							ident("const"),
+							ident("u8"),
+						],
+						path(["core", "primitive", "str", "as_ptr"], span)
+							.chain(iter::once(group(Delimiter::Parenthesis, iter::once(value)))),
+					))
+					// `const ARR_: [u8; LEN_] = unsafe { *(PTR_ as *const _)
+					// };`
+					.chain(arg.cfg.clone().into_iter().flatten())
+					.chain(r#const(
+						&format!("ARR_{index}"),
+						iter::once(group(
+							Delimiter::Bracket,
+							[
+								ident("u8"),
+								Punct::new(';', Spacing::Alone).into(),
+								ident(&len_name),
+							],
+						)),
+						[
+							ident("unsafe"),
+							group(
+								Delimiter::Brace,
+								[
+									Punct::new('*', Spacing::Alone).into(),
+									group(
+										Delimiter::Parenthesis,
+										[
+											ident(&ptr_name),
+											ident("as"),
+											Punct::new('*', Spacing::Alone).into(),
+											ident("const"),
+											ident("_"),
+										],
+									),
+								],
+							),
+						],
+					))
+					.collect::>()
+			}
+		});
+
+	// ```
+	// const LEN: u32 = {
+	//     let mut len: usize = 0;
+	//     #(len += LEN_;)*
+	//     len as u32
+	// };
+	// ```
+	let len = r#const(
+		"LEN",
+		iter::once(ident("u32")),
+		[group(
+			Delimiter::Brace,
+			[
+				ident("let"),
+				ident("mut"),
+				ident("len"),
+				Punct::new(':', Spacing::Alone).into(),
+				ident("usize"),
+				Punct::new('=', Spacing::Alone).into(),
+				Literal::usize_unsuffixed(0).into(),
+				Punct::new(';', Spacing::Alone).into(),
+			]
+			.into_iter()
+			.chain(data.iter().enumerate().flat_map(|(index, par)| {
+				par.cfg
+					.clone()
+					.into_iter()
+					.flatten()
+					.chain(iter::once(group(
+						Delimiter::Brace,
+						[
+							ident("len"),
+							Punct::new('+', Spacing::Joint).into(),
+							Punct::new('=', Spacing::Alone).into(),
+							match &par.kind {
+								ArgumentKind::Bytes(bytes) => {
+									Literal::usize_unsuffixed(bytes.len()).into()
+								}
+								ArgumentKind::String(string) => {
+									Literal::usize_unsuffixed(string.len()).into()
+								}
+								ArgumentKind::Interpolate(_) => ident(&format!("LEN_{index}")),
+							},
+							Punct::new(';', Spacing::Alone).into(),
+						],
+					)))
+			}))
+			.chain([ident("len"), ident("as"), ident("u32")]),
+		)],
+	);
+
+	// `[u8; 4], #([u8; LEN_]),*`
+	let tys = [
+		group(
+			Delimiter::Bracket,
+			[
+				ident("u8"),
+				Punct::new(';', Spacing::Alone).into(),
+				Literal::usize_unsuffixed(4).into(),
+			],
+		),
+		Punct::new(',', Spacing::Alone).into(),
+	]
+	.into_iter()
+	// Optional prefix length.
+	.chain(prefix.into_iter().flat_map(|prefix| {
+		[
+			group(
+				Delimiter::Bracket,
+				[
+					ident("u8"),
+					Punct::new(';', Spacing::Alone).into(),
+					Literal::usize_unsuffixed(2).into(),
+				],
+			),
+			Punct::new(',', Spacing::Alone).into(),
+		]
+		.into_iter()
+		.chain(
+			(!prefix.is_empty())
+				.then(|| {
+					[
+						group(
+							Delimiter::Bracket,
+							[
+								ident("u8"),
+								Punct::new(';', Spacing::Alone).into(),
+								Literal::usize_unsuffixed(prefix.len()).into(),
+							],
+						),
+						Punct::new(',', Spacing::Alone).into(),
+					]
+				})
+				.into_iter()
+				.flatten(),
+		)
+	}))
+	.chain(data.iter().enumerate().flat_map(move |(index, arg)| {
+		arg.cfg.clone().into_iter().flatten().chain([
+			group(
+				Delimiter::Bracket,
+				[
+					ident("u8"),
+					Punct::new(';', Spacing::Alone).into(),
+					match &arg.kind {
+						ArgumentKind::Bytes(bytes) => Literal::usize_unsuffixed(bytes.len()).into(),
+						ArgumentKind::String(string) => {
+							Literal::usize_unsuffixed(string.len()).into()
+						}
+						ArgumentKind::Interpolate(_) => ident(&format!("LEN_{index}")),
+					},
+				],
+			),
+			Punct::new(',', Spacing::Alone).into(),
+		])
+	}));
+
+	// ```
+	// #[repr(C)]
+	// struct Layout(...);
+	// ```
+	let layout = [
+		Punct::new('#', Spacing::Alone).into(),
+		group(
+			Delimiter::Bracket,
+			[
+				ident("repr"),
+				group(Delimiter::Parenthesis, iter::once(ident("C"))),
+			],
+		),
+		ident("struct"),
+		ident("Layout"),
+		group(Delimiter::Parenthesis, tys),
+		Punct::new(';', Spacing::Alone).into(),
+	];
+
+	// `#[link_section = name]`
+	let link_section = [
+		Punct::new('#', Spacing::Alone).into(),
+		group(
+			Delimiter::Bracket,
+			[
+				ident("unsafe"),
+				group(
+					Delimiter::Parenthesis,
+					[
+						ident("link_section"),
+						Punct::new('=', Spacing::Alone).into(),
+						Literal::string(name).into(),
+					],
+				),
+			],
+		),
+	];
+
+	// (::core::primitive::u32::to_le_bytes(LEN), #(ARR_),*)
+	let values = group(
+		Delimiter::Parenthesis,
+		path(["core", "primitive", "u32", "to_le_bytes"], span)
+			.chain([
+				group(Delimiter::Parenthesis, iter::once(ident("LEN"))),
+				Punct::new(',', Spacing::Alone).into(),
+			])
+			// Optional prefix value.
+			.chain(prefix.into_iter().flat_map(|prefix| {
+				let len = u16::try_from(prefix.len()).unwrap().to_le_bytes();
+
+				[
+					group(
+						Delimiter::Bracket,
+						[
+							Literal::u8_unsuffixed(len[0]).into(),
+							Punct::new(',', Spacing::Alone).into(),
+							Literal::u8_unsuffixed(len[1]).into(),
+							Punct::new(',', Spacing::Alone).into(),
+						],
+					),
+					Punct::new(',', Spacing::Alone).into(),
+				]
+				.into_iter()
+				.chain(
+					(!prefix.is_empty())
+						.then(|| [ident("ARR_PREFIX"), Punct::new(',', Spacing::Alone).into()])
+						.into_iter()
+						.flatten(),
+				)
+			}))
+			.chain(data.iter().enumerate().flat_map(move |(index, arg)| {
+				arg.cfg.clone().into_iter().flatten().chain([
+					ident(&format!("ARR_{index}")),
+					Punct::new(',', Spacing::Alone).into(),
+				])
+			})),
+	);
+
+	// `static CUSTOM_SECTION: Layout = Layout(...);`
+	let custom_section = [
+		ident("static"),
+		ident("CUSTOM_SECTION"),
+		Punct::new(':', Spacing::Alone).into(),
+		ident("Layout"),
+		Punct::new('=', Spacing::Alone).into(),
+		ident("Layout"),
+		values,
+		Punct::new(';', Spacing::Alone).into(),
+	];
+
+	// `const _: () = { ... }`
+	r#const(
+		"_",
+		iter::once(group(Delimiter::Parenthesis, iter::empty())),
+		iter::once(group(
+			Delimiter::Brace,
+			const_prefix.chain(consts).chain(len).chain(r#const(
+				"_",
+				iter::once(group(Delimiter::Parenthesis, iter::empty())),
+				iter::once(group(
+					Delimiter::Brace,
+					layout.into_iter().chain(link_section).chain(custom_section),
+				)),
+			)),
+		)),
+	)
+	.collect()
+}
+
 pub fn parse_meta_name_value(
 	mut stream: &mut Peekable,
 ) -> Result<(Ident, String), TokenStream> {
diff --git a/linker-shim/linker b/linker-shim/linker
new file mode 100755
index 00000000..ca6e32ec
--- /dev/null
+++ b/linker-shim/linker
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+(
+  cd "$(dirname "$0")/../host" || exit 1
+  cargo run -q -p js-bindgen-ld -- "$@"
+)
+exit $?
diff --git a/linker-shim/linker.cmd b/linker-shim/linker.cmd
index 7be4a8f3..f94f1c78 100755
--- a/linker-shim/linker.cmd
+++ b/linker-shim/linker.cmd
@@ -13,6 +13,6 @@
 :: Never reached on UNIX because we execute `exit`.
 @echo off
 pushd "%~dp0..\host" || exit /b 1
-cargo +stable run -q -p js-bindgen-ld -- %*
+cargo run -q -p js-bindgen-ld -- %*
 popd
 exit /b %ERRORLEVEL%
diff --git a/linker-shim/test-runner b/linker-shim/test-runner
new file mode 100755
index 00000000..6f878ea3
--- /dev/null
+++ b/linker-shim/test-runner
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+(
+  cd "$(dirname "$0")/../host" || exit 1
+  cargo run -q -p js-bindgen-test-runner -- "$@"
+)
+exit $?
diff --git a/linker-shim/test-runner.cmd b/linker-shim/test-runner.cmd
new file mode 100644
index 00000000..f0f9cd3d
--- /dev/null
+++ b/linker-shim/test-runner.cmd
@@ -0,0 +1,5 @@
+@echo off
+pushd "%~dp0..\host" || exit /b 1
+cargo run -q -p js-bindgen-test-runner -- %*
+popd
+exit /b %ERRORLEVEL%

From d20f61b266cd1670b9c847b97eba9053f68de9de Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Mon, 26 Jan 2026 13:41:39 +0800
Subject: [PATCH 02/73] Remove js panic stack output

---
 client/js-bindgen-test/src/lib.rs             | 28 ++++++-------------
 .../js-bindgen-test-runner/js/runner-core.mjs |  2 +-
 2 files changed, 9 insertions(+), 21 deletions(-)

diff --git a/client/js-bindgen-test/src/lib.rs b/client/js-bindgen-test/src/lib.rs
index 1debcb19..3d8e4a1f 100644
--- a/client/js-bindgen-test/src/lib.rs
+++ b/client/js-bindgen-test/src/lib.rs
@@ -3,8 +3,8 @@ use js_sys::JsString;
 use std::{cell::RefCell, panic::PanicHookInfo};
 
 struct LastPanic {
-	payload: Option,
-	info: Option,
+	payload: Option,
+	info: Option,
 }
 
 thread_local! {
@@ -14,21 +14,8 @@ thread_local! {
 	}) };
 }
 
-js_sys::js_bindgen::embed_js!(
-	name = "panic.stack",
-	"(message) => {{",
-	"	const error = new Error(message);",
-	"	return error.stack || String(error);",
-	"}}"
-);
-
-#[js_sys::js_sys(js_sys = js_sys)]
-extern "C" {
-	#[js_sys(js_embed = "panic.stack")]
-	fn panic_stack(message: &JsString) -> JsString;
-}
-
 pub fn set_panic_hook() {
+	// TODO: Bump rustc to 1.91.0 and remove this func
 	fn payload_as_str<'a>(info: &'a PanicHookInfo) -> Option<&'a str> {
 		if let Some(s) = info.payload().downcast_ref::<&str>() {
 			Some(s)
@@ -40,12 +27,13 @@ pub fn set_panic_hook() {
 	}
 
 	static HOOK: std::sync::Once = std::sync::Once::new();
+
 	HOOK.call_once(|| {
 		std::panic::set_hook(Box::new(|info| {
 			LAST_PANIC.with(|cell| {
 				*cell.borrow_mut() = LastPanic {
-					payload: payload_as_str(info).map(JsString::from_str),
-					info: Some(panic_stack(&JsString::from_str(&info.to_string()))),
+					payload: payload_as_str(info).map(|s| s.to_owned()),
+					info: Some(info.to_string()),
 				}
 			});
 		}));
@@ -55,7 +43,7 @@ pub fn set_panic_hook() {
 #[unsafe(no_mangle)]
 pub extern "C" fn last_panic_message() -> JsString {
 	match LAST_PANIC.with(|cell| cell.borrow_mut().info.take()) {
-		Some(info) => info,
+		Some(info) => JsString::from_str(&info),
 		None => JsString::from_str(""),
 	}
 }
@@ -63,7 +51,7 @@ pub extern "C" fn last_panic_message() -> JsString {
 #[unsafe(no_mangle)]
 pub extern "C" fn last_panic_payload() -> JsString {
 	match LAST_PANIC.with(|cell| cell.borrow_mut().payload.take()) {
-		Some(payload) => payload,
+		Some(payload) => JsString::from_str(&payload),
 		None => JsString::from_str(""),
 	}
 }
diff --git a/host/js-bindgen-test-runner/js/runner-core.mjs b/host/js-bindgen-test-runner/js/runner-core.mjs
index 6bdd7be0..9f6f74c9 100644
--- a/host/js-bindgen-test-runner/js/runner-core.mjs
+++ b/host/js-bindgen-test-runner/js/runner-core.mjs
@@ -53,7 +53,7 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 					type: "test-failed",
 					name: test.name,
 					error:
-                        message + "\n\n" +
+                        message + "\n" +
 						"note: panic did not contain expected string\n" +
 						`      panic message: "${displayPayload}"\n` +
 						` expected substring: "${displayExpected}"`,

From 2d14d147ecc1814ec6d4322cd83a692fdbde1e1f Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Mon, 26 Jan 2026 21:02:00 +0800
Subject: [PATCH 03/73] Add error stack output

---
 .../js/browser-runner.mjs                     | 25 +++++++++++--------
 .../js-bindgen-test-runner/js/node-runner.mjs |  7 +++++-
 .../js-bindgen-test-runner/js/runner-core.mjs |  5 ++--
 .../js/service-worker.mjs                     |  7 +++++-
 host/js-bindgen-test-runner/js/shared.mjs     |  2 +-
 .../js/worker-runner.mjs                      |  7 +++++-
 6 files changed, 37 insertions(+), 16 deletions(-)

diff --git a/host/js-bindgen-test-runner/js/browser-runner.mjs b/host/js-bindgen-test-runner/js/browser-runner.mjs
index 2b17b5f8..b6d9699b 100644
--- a/host/js-bindgen-test-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-test-runner/js/browser-runner.mjs
@@ -13,15 +13,15 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 		mode === "page"
 			? await runInWindow({ nocapture, filtered })
 			: await runInWorker({
-					nocapture,
-					filtered,
-					mode,
-					baseLog,
-					baseError,
-					baseWarn,
-					baseInfo,
-					baseDebug,
-			  });
+				nocapture,
+				filtered,
+				mode,
+				baseLog,
+				baseError,
+				baseWarn,
+				baseInfo,
+				baseDebug,
+			});
 
 	if (typeof window !== "undefined") {
 		window.__jbtestDone = true;
@@ -257,7 +257,12 @@ function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
 		run();
 		return { ok: true };
 	} catch (error) {
-		return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() };
+		return {
+			ok: false,
+			panic_payload: panicPayload(),
+			panic_message: panicMessage(),
+			stack: error.stack
+		};
 	} finally {
 		console.log = originalLog;
 		console.error = originalError;
diff --git a/host/js-bindgen-test-runner/js/node-runner.mjs b/host/js-bindgen-test-runner/js/node-runner.mjs
index f7b01481..cbe7f09d 100644
--- a/host/js-bindgen-test-runner/js/node-runner.mjs
+++ b/host/js-bindgen-test-runner/js/node-runner.mjs
@@ -72,7 +72,12 @@ function withConsoleCapture(name, run, panicPayload, panicMessage) {
 		run();
 		return { ok: true };
 	} catch (error) {
-		return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() };
+		return {
+			ok: false,
+			panic_payload: panicPayload(),
+			panic_message: panicMessage(),
+			stack: error.stack
+		};
 	} finally {
 		console.log = originalLog;
 		console.error = originalError;
diff --git a/host/js-bindgen-test-runner/js/runner-core.mjs b/host/js-bindgen-test-runner/js/runner-core.mjs
index 9f6f74c9..4d0aad07 100644
--- a/host/js-bindgen-test-runner/js/runner-core.mjs
+++ b/host/js-bindgen-test-runner/js/runner-core.mjs
@@ -53,7 +53,8 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 					type: "test-failed",
 					name: test.name,
 					error:
-                        message + "\n" +
+						message + "\n" +
+						result.stack + "\n" +
 						"note: panic did not contain expected string\n" +
 						`      panic message: "${displayPayload}"\n` +
 						` expected substring: "${displayExpected}"`,
@@ -71,7 +72,7 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 			emit({ type: "test-ok", name: test.name, should_panic: false });
 		} else {
 			const message = coercePanicMessage(result.panic_message, externrefTable);
-			emit({ type: "test-failed", name: test.name, error: message });
+			emit({ type: "test-failed", name: test.name, error: message + "\n" + result.stack });
 			failed += 1;
 		}
 	}
diff --git a/host/js-bindgen-test-runner/js/service-worker.mjs b/host/js-bindgen-test-runner/js/service-worker.mjs
index 62fb0a0d..5cfd54a3 100644
--- a/host/js-bindgen-test-runner/js/service-worker.mjs
+++ b/host/js-bindgen-test-runner/js/service-worker.mjs
@@ -78,7 +78,12 @@ function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
 		run();
 		return { ok: true };
 	} catch (error) {
-		return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() };
+		return {
+			ok: false,
+			panic_payload: panicPayload(),
+			panic_message: panicMessage(),
+			stack: error.stack
+		};
 	} finally {
 		console.log = originalLog;
 		console.error = originalError;
diff --git a/host/js-bindgen-test-runner/js/shared.mjs b/host/js-bindgen-test-runner/js/shared.mjs
index b2bcd077..c52d85fe 100644
--- a/host/js-bindgen-test-runner/js/shared.mjs
+++ b/host/js-bindgen-test-runner/js/shared.mjs
@@ -73,7 +73,7 @@ export function createTextFormatter({ nocapture, write }) {
 					failure_reports.push({
 						name: event.name,
 						entries: take_buffer(event.name),
-                        error: event.error,
+						error: event.error,
 					});
 					break;
 				case "run-end":
diff --git a/host/js-bindgen-test-runner/js/worker-runner.mjs b/host/js-bindgen-test-runner/js/worker-runner.mjs
index 6c193f3c..a670ca9a 100644
--- a/host/js-bindgen-test-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-test-runner/js/worker-runner.mjs
@@ -85,7 +85,12 @@ function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
 		run();
 		return { ok: true };
 	} catch (error) {
-		return { ok: false, panic_payload: panicPayload(), panic_message: panicMessage() };
+		return {
+			ok: false,
+			panic_payload: panicPayload(),
+			panic_message: panicMessage(),
+			stack: error.stack
+		};
 	} finally {
 		console.log = originalLog;
 		console.error = originalError;

From 558458a5b9b6ecc81c7e7b782b50830ed68b8a1b Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Tue, 27 Jan 2026 01:54:19 +0800
Subject: [PATCH 04/73] Format tomls

---
 client/Cargo.toml                     | 4 ++--
 client/js-bindgen-test/Cargo.toml     | 6 +++---
 host/js-bindgen-test-macro/Cargo.toml | 4 ++--
 3 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/client/Cargo.toml b/client/Cargo.toml
index 4777eb9a..e57ed87d 100644
--- a/client/Cargo.toml
+++ b/client/Cargo.toml
@@ -1,5 +1,5 @@
 [workspace]
-members = ["js-bindgen-test","js-sys", "web-sys"]
+members = ["js-bindgen-test", "js-sys", "web-sys"]
 resolver = "2"
 
 [workspace.package]
@@ -9,8 +9,8 @@ rust-version = "1.85"
 
 [workspace.dependencies]
 js-bindgen = { path = "../host/js-bindgen" }
-js-bindgen-test-macro = { path = "../host/js-bindgen-test-macro" }
 js-bindgen-test = { path = "js-bindgen-test" }
+js-bindgen-test-macro = { path = "../host/js-bindgen-test-macro" }
 js-sys = { path = "js-sys" }
 js-sys-macro = { path = "../host/js-sys-macro" }
 mini-alloc = "1"
diff --git a/client/js-bindgen-test/Cargo.toml b/client/js-bindgen-test/Cargo.toml
index 8bc4a326..dd392edd 100644
--- a/client/js-bindgen-test/Cargo.toml
+++ b/client/js-bindgen-test/Cargo.toml
@@ -1,12 +1,12 @@
 [package]
-name = "js-bindgen-test"
-version = "0.1.0"
 edition.workspace = true
+name = "js-bindgen-test"
 rust-version.workspace = true
+version = "0.1.0"
 
 [dependencies]
-js-sys = { workspace = true }
 js-bindgen-test-macro = { workspace = true }
+js-sys = { workspace = true }
 
 [lints]
 workspace = true
diff --git a/host/js-bindgen-test-macro/Cargo.toml b/host/js-bindgen-test-macro/Cargo.toml
index 642deb41..b7f7b7ae 100644
--- a/host/js-bindgen-test-macro/Cargo.toml
+++ b/host/js-bindgen-test-macro/Cargo.toml
@@ -1,8 +1,8 @@
 [package]
-name = "js-bindgen-test-macro"
-version = "0.1.0"
 edition.workspace = true
+name = "js-bindgen-test-macro"
 rust-version.workspace = true
+version = "0.1.0"
 
 [lib]
 proc-macro = true

From 3eae2dccf8269b7c98e39e43dcbae85c82cd53e3 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Tue, 27 Jan 2026 13:46:57 +0800
Subject: [PATCH 05/73] Clean up

---
 .../js/browser-runner.mjs                     | 42 ++++++++-----------
 .../js-bindgen-test-runner/js/node-runner.mjs |  8 ++--
 .../js/playwright-runner.mjs                  |  1 -
 .../js-bindgen-test-runner/js/runner-core.mjs | 27 ++++--------
 .../js/service-worker.mjs                     |  8 ++--
 .../js/worker-runner.mjs                      |  8 ++--
 6 files changed, 36 insertions(+), 58 deletions(-)

diff --git a/host/js-bindgen-test-runner/js/browser-runner.mjs b/host/js-bindgen-test-runner/js/browser-runner.mjs
index b6d9699b..23c2fb77 100644
--- a/host/js-bindgen-test-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-test-runner/js/browser-runner.mjs
@@ -2,26 +2,22 @@ import { createTextFormatter } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 
 export async function runBrowser({ nocapture, filtered, worker }) {
-	const mode = worker || "page";
 	const baseLog = console.log;
 	const baseError = console.error;
 	const baseWarn = console.warn;
 	const baseInfo = console.info;
 	const baseDebug = console.debug;
 
-	let result =
-		mode === "page"
-			? await runInWindow({ nocapture, filtered })
-			: await runInWorker({
-				nocapture,
-				filtered,
-				mode,
-				baseLog,
-				baseError,
-				baseWarn,
-				baseInfo,
-				baseDebug,
-			});
+	let result = worker ? await runInWorker({
+		nocapture,
+		filtered,
+		worker,
+		baseLog,
+		baseError,
+		baseWarn,
+		baseInfo,
+		baseDebug,
+	}) : await runInWindow({ nocapture, filtered });
 
 	if (typeof window !== "undefined") {
 		window.__jbtestDone = true;
@@ -47,8 +43,8 @@ async function runInWindow({ nocapture, filtered }) {
 
 	const testInputs = tests.map(test => ({
 		...test,
-		run(testFn, panicPayload, panicMessage) {
-			return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage, event =>
+		run(testFn) {
+			return withConsoleCapture(test.name, () => testFn(), event =>
 				formatter.onEvent(event)
 			);
 		},
@@ -68,7 +64,7 @@ async function runInWindow({ nocapture, filtered }) {
 async function runInWorker({
 	nocapture,
 	filtered,
-	mode,
+	worker,
 	baseLog,
 	baseError,
 	baseWarn,
@@ -110,14 +106,14 @@ async function runInWorker({
 	}
 
 	let reportPromise;
-	if (mode === "dedicated") {
+	if (worker === "dedicated") {
 		reportPromise = runDedicatedWorker({ filtered, nocapture, handleMessage });
-	} else if (mode === "shared") {
+	} else if (worker === "shared") {
 		reportPromise = runSharedWorker({ filtered, nocapture, handleMessage });
-	} else if (mode === "service") {
+	} else if (worker === "service") {
 		reportPromise = runServiceWorker({ filtered, nocapture, handleMessage });
 	} else {
-		throw new Error(`unsupported worker mode: ${mode}`);
+		throw new Error(`unsupported worker worker: ${mode}`);
 	}
 
 	const report = await reportPromise;
@@ -220,7 +216,7 @@ async function runServiceWorker({ filtered, nocapture, handleMessage }) {
 	});
 }
 
-function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
+function withConsoleCapture(name, run, emit) {
 	const originalLog = console.log;
 	const originalError = console.error;
 	const originalWarn = console.warn;
@@ -259,8 +255,6 @@ function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
 	} catch (error) {
 		return {
 			ok: false,
-			panic_payload: panicPayload(),
-			panic_message: panicMessage(),
 			stack: error.stack
 		};
 	} finally {
diff --git a/host/js-bindgen-test-runner/js/node-runner.mjs b/host/js-bindgen-test-runner/js/node-runner.mjs
index cbe7f09d..31ac9004 100644
--- a/host/js-bindgen-test-runner/js/node-runner.mjs
+++ b/host/js-bindgen-test-runner/js/node-runner.mjs
@@ -37,8 +37,8 @@ function emit(event) {
 
 const testInputs = tests.map(test => ({
 	...test,
-	run(testFn, panicPayload, panicMessage) {
-		return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage);
+	run(testFn) {
+		return withConsoleCapture(test.name, () => testFn());
 	},
 }));
 
@@ -52,7 +52,7 @@ const result = await runTests({
 
 process.exit(result.failed === 0 ? 0 : 1);
 
-function withConsoleCapture(name, run, panicPayload, panicMessage) {
+function withConsoleCapture(name, run) {
 	function emitOutput(line, stream, level) {
 		emit({ type: "test-output", name, line, stream, level });
 	}
@@ -74,8 +74,6 @@ function withConsoleCapture(name, run, panicPayload, panicMessage) {
 	} catch (error) {
 		return {
 			ok: false,
-			panic_payload: panicPayload(),
-			panic_message: panicMessage(),
 			stack: error.stack
 		};
 	} finally {
diff --git a/host/js-bindgen-test-runner/js/playwright-runner.mjs b/host/js-bindgen-test-runner/js/playwright-runner.mjs
index 140c566d..19ea90c3 100644
--- a/host/js-bindgen-test-runner/js/playwright-runner.mjs
+++ b/host/js-bindgen-test-runner/js/playwright-runner.mjs
@@ -18,7 +18,6 @@ if (!browserType) {
 
 const browser = await browserType.launch({
 	headless: true,
-	chromiumSandbox: false,
 });
 const page = await browser.newPage();
 await page.goto(url);
diff --git a/host/js-bindgen-test-runner/js/runner-core.mjs b/host/js-bindgen-test-runner/js/runner-core.mjs
index 4d0aad07..00400d13 100644
--- a/host/js-bindgen-test-runner/js/runner-core.mjs
+++ b/host/js-bindgen-test-runner/js/runner-core.mjs
@@ -28,8 +28,8 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 			continue;
 		}
 
-		const result = test.run(testFn, panicPayload, panicMessage);
-		const shouldPanic = Boolean(test.should_panic);
+		const result = test.run(testFn);
+		const shouldPanic = test.should_panic;
 		if (shouldPanic) {
 			if (result.ok) {
 				emit({
@@ -42,10 +42,10 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 				continue;
 			}
 
-			const expected = test.should_panic_reason;
-			const payload = coercePanicMessage(result.panic_payload, externrefTable);
-			const message = coercePanicMessage(result.panic_message, externrefTable);
-			const expectedText = expected || "";
+			const expectedText = test.should_panic_reason;
+			const payload = coercePanicMessage(panicPayload(), externrefTable);
+			const message = coercePanicMessage(panicMessage(), externrefTable);
+
 			if (expectedText && !payload.includes(expectedText)) {
 				const displayPayload = escapeForDisplay(payload);
 				const displayExpected = escapeForDisplay(expectedText);
@@ -71,7 +71,7 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 		if (result.ok) {
 			emit({ type: "test-ok", name: test.name, should_panic: false });
 		} else {
-			const message = coercePanicMessage(result.panic_message, externrefTable);
+			const message = coercePanicMessage(panicMessage(), externrefTable);
 			emit({ type: "test-failed", name: test.name, error: message + "\n" + result.stack });
 			failed += 1;
 		}
@@ -91,27 +91,18 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 }
 
 function resolveExternrefTable(importObject) {
-	if (!importObject) {
-		return null;
-	}
 	return importObject["js_sys"]["externref.table"];
 }
 
 function coercePanicMessage(value, externrefTable) {
 	const ref = externrefTable.get(value);
-	if (typeof externrefTable.set === "function") {
-		externrefTable.set(value, null);
-	}
+	externrefTable.set(value, null);
 	return String(ref);
 }
 
 function escapeForDisplay(value) {
 	return String(value || "")
-		.replace(/\\/g, "\\\\")
 		.replace(/\r/g, "\\r")
 		.replace(/\n/g, "\\n")
-		.replace(/\t/g, "\\t")
-		.replace(/\0/g, "\\0")
-		.replace(/\x08/g, "\\b")
-		.replace(/\x0c/g, "\\f");
+		.replace(/\t/g, "\\t");
 }
diff --git a/host/js-bindgen-test-runner/js/service-worker.mjs b/host/js-bindgen-test-runner/js/service-worker.mjs
index 5cfd54a3..af1b0f8f 100644
--- a/host/js-bindgen-test-runner/js/service-worker.mjs
+++ b/host/js-bindgen-test-runner/js/service-worker.mjs
@@ -40,8 +40,8 @@ async function execute(port, { nocapture, filtered }) {
 
 	const testInputs = tests.map(test => ({
 		...test,
-		run(testFn, panicPayload, panicMessage) {
-			return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage, event =>
+		run(testFn) {
+			return withConsoleCapture(test.name, () => testFn(), event =>
 				emit(event)
 			);
 		},
@@ -58,7 +58,7 @@ async function execute(port, { nocapture, filtered }) {
 	port.postMessage({ type: "report", lines, failed: result.failed });
 }
 
-function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
+function withConsoleCapture(name, run, emit) {
 	function emitOutput(line, stream, level) {
 		emit({ type: "test-output", name, line, stream, level });
 	}
@@ -80,8 +80,6 @@ function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
 	} catch (error) {
 		return {
 			ok: false,
-			panic_payload: panicPayload(),
-			panic_message: panicMessage(),
 			stack: error.stack
 		};
 	} finally {
diff --git a/host/js-bindgen-test-runner/js/worker-runner.mjs b/host/js-bindgen-test-runner/js/worker-runner.mjs
index a670ca9a..49ab5394 100644
--- a/host/js-bindgen-test-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-test-runner/js/worker-runner.mjs
@@ -29,8 +29,8 @@ async function execute(port, { nocapture, filtered }) {
 
 	const testInputs = tests.map(test => ({
 		...test,
-		run(testFn, panicPayload, panicMessage) {
-			return withConsoleCapture(test.name, () => testFn(), panicPayload, panicMessage, event =>
+		run(testFn) {
+			return withConsoleCapture(test.name, () => testFn(), event =>
 				emit(event)
 			);
 		},
@@ -65,7 +65,7 @@ if (typeof self.onconnect !== "undefined") {
 	};
 }
 
-function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
+function withConsoleCapture(name, run, emit) {
 	function emitOutput(line, stream, level) {
 		emit({ type: "test-output", name, line, stream, level });
 	}
@@ -87,8 +87,6 @@ function withConsoleCapture(name, run, panicPayload, panicMessage, emit) {
 	} catch (error) {
 		return {
 			ok: false,
-			panic_payload: panicPayload(),
-			panic_message: panicMessage(),
 			stack: error.stack
 		};
 	} finally {

From 479b66fee02a717f8bfaceed4bd8d54302d1a1f7 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Tue, 27 Jan 2026 22:04:06 +0800
Subject: [PATCH 06/73] Update console capture

---
 .../js/browser-runner.mjs                     | 67 ++++++-------------
 .../js-bindgen-test-runner/js/node-runner.mjs | 34 +++-------
 .../js/service-worker.mjs                     | 37 ++++------
 host/js-bindgen-test-runner/js/shared.mjs     | 43 ++++++++++++
 .../js/worker-runner.mjs                      | 31 +++------
 5 files changed, 97 insertions(+), 115 deletions(-)

diff --git a/host/js-bindgen-test-runner/js/browser-runner.mjs b/host/js-bindgen-test-runner/js/browser-runner.mjs
index 23c2fb77..184fa62c 100644
--- a/host/js-bindgen-test-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-test-runner/js/browser-runner.mjs
@@ -1,12 +1,13 @@
-import { createTextFormatter } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 
 export async function runBrowser({ nocapture, filtered, worker }) {
-	const baseLog = console.log;
-	const baseError = console.error;
-	const baseWarn = console.warn;
-	const baseInfo = console.info;
-	const baseDebug = console.debug;
+	const consoleProxy = installConsoleProxy();
+	const baseLog = consoleProxy.base.log;
+	const baseError = consoleProxy.base.error;
+	const baseWarn = consoleProxy.base.warn;
+	const baseInfo = consoleProxy.base.info;
+	const baseDebug = consoleProxy.base.debug;
 
 	let result = worker ? await runInWorker({
 		nocapture,
@@ -17,7 +18,7 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 		baseWarn,
 		baseInfo,
 		baseDebug,
-	}) : await runInWindow({ nocapture, filtered });
+	}) : await runInWindow({ nocapture, filtered, consoleProxy });
 
 	if (typeof window !== "undefined") {
 		window.__jbtestDone = true;
@@ -27,7 +28,7 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 	return result;
 }
 
-async function runInWindow({ nocapture, filtered }) {
+async function runInWindow({ nocapture, filtered, consoleProxy }) {
 	const tests = await (await fetch("/tests.json")).json();
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
 	const { importObject } = await import("/import.js");
@@ -45,7 +46,8 @@ async function runInWindow({ nocapture, filtered }) {
 		...test,
 		run(testFn) {
 			return withConsoleCapture(test.name, () => testFn(), event =>
-				formatter.onEvent(event)
+				formatter.onEvent(event),
+				consoleProxy
 			);
 		},
 	}));
@@ -216,38 +218,15 @@ async function runServiceWorker({ filtered, nocapture, handleMessage }) {
 	});
 }
 
-function withConsoleCapture(name, run, emit) {
-	const originalLog = console.log;
-	const originalError = console.error;
-	const originalWarn = console.warn;
-	const originalInfo = console.info;
-	const originalDebug = console.debug;
-
-	function emitOutput(line, stream, level) {
-		emit({ type: "test-output", name, line, stream });
-		switch (level) {
-			case "error":
-				originalError(line);
-				break;
-			case "warn":
-				originalWarn(line);
-				break;
-			case "info":
-				originalInfo(line);
-				break;
-			case "debug":
-				originalDebug(line);
-				break;
-			default:
-				originalLog(line);
-		}
-	}
-
-	console.log = (...args) => emitOutput(args.join(" "), "stdout", "log");
-	console.error = (...args) => emitOutput(args.join(" "), "stderr", "error");
-	console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn");
-	console.info = (...args) => emitOutput(args.join(" "), "stdout", "info");
-	console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug");
+function withConsoleCapture(name, run, emit, consoleProxy) {
+	consoleProxy.setHook(
+		(level, args) => {
+			const line = args.join(" ");
+			const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
+			emit({ type: "test-output", name, line, stream, level });
+		},
+		true
+	);
 
 	try {
 		run();
@@ -258,11 +237,7 @@ function withConsoleCapture(name, run, emit) {
 			stack: error.stack
 		};
 	} finally {
-		console.log = originalLog;
-		console.error = originalError;
-		console.warn = originalWarn;
-		console.info = originalInfo;
-		console.debug = originalDebug;
+		consoleProxy.clearHook();
 	}
 }
 
diff --git a/host/js-bindgen-test-runner/js/node-runner.mjs b/host/js-bindgen-test-runner/js/node-runner.mjs
index 31ac9004..82409f29 100644
--- a/host/js-bindgen-test-runner/js/node-runner.mjs
+++ b/host/js-bindgen-test-runner/js/node-runner.mjs
@@ -1,6 +1,6 @@
 import fs from "node:fs/promises";
 import { pathToFileURL } from "node:url";
-import { createTextFormatter } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 
 const wasmPath = process.env.JS_BINDGEN_WASM;
@@ -14,12 +14,13 @@ if (!wasmPath || !importsPath || !testsJson) {
 	process.exit(1);
 }
 
+const consoleProxy = installConsoleProxy();
 const { importObject } = await import(pathToFileURL(importsPath));
 const wasmBytes = await fs.readFile(wasmPath);
 const tests = JSON.parse(testsJson);
 
-const baseLog = console.log;
-const baseError = console.error;
+const baseLog = consoleProxy.base.log;
+const baseError = consoleProxy.base.error;
 const formatter = createTextFormatter({
 	nocapture,
 	write(line, stream) {
@@ -38,7 +39,7 @@ function emit(event) {
 const testInputs = tests.map(test => ({
 	...test,
 	run(testFn) {
-		return withConsoleCapture(test.name, () => testFn());
+		return withConsoleCapture(test.name, () => testFn(), consoleProxy);
 	},
 }));
 
@@ -52,21 +53,12 @@ const result = await runTests({
 
 process.exit(result.failed === 0 ? 0 : 1);
 
-function withConsoleCapture(name, run) {
-	function emitOutput(line, stream, level) {
+function withConsoleCapture(name, run, consoleProxy) {
+	consoleProxy.setHook((level, args) => {
+		const line = args.join(" ");
+		const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
 		emit({ type: "test-output", name, line, stream, level });
-	}
-
-	const originalLog = console.log;
-	const originalError = console.error;
-	const originalWarn = console.warn;
-	const originalInfo = console.info;
-	const originalDebug = console.debug;
-	console.log = (...args) => emitOutput(args.join(" "), "stdout", "log");
-	console.error = (...args) => emitOutput(args.join(" "), "stderr", "error");
-	console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn");
-	console.info = (...args) => emitOutput(args.join(" "), "stdout", "info");
-	console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug");
+	}, false);
 
 	try {
 		run();
@@ -77,10 +69,6 @@ function withConsoleCapture(name, run) {
 			stack: error.stack
 		};
 	} finally {
-		console.log = originalLog;
-		console.error = originalError;
-		console.warn = originalWarn;
-		console.info = originalInfo;
-		console.debug = originalDebug;
+		consoleProxy.clearHook();
 	}
 }
diff --git a/host/js-bindgen-test-runner/js/service-worker.mjs b/host/js-bindgen-test-runner/js/service-worker.mjs
index af1b0f8f..05e09e78 100644
--- a/host/js-bindgen-test-runner/js/service-worker.mjs
+++ b/host/js-bindgen-test-runner/js/service-worker.mjs
@@ -1,6 +1,6 @@
-import { createTextFormatter } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
-import { importObject } from "/import.js";
+import { importObject } from "./import.js";
 
 self.addEventListener("message", event => {
 	const port = event.ports && event.ports[0];
@@ -13,6 +13,7 @@ self.addEventListener("message", event => {
 });
 
 async function execute(port, { nocapture, filtered }) {
+	const consoleProxy = installConsoleProxy();
 	const tests = await (await fetch("/tests.json")).json();
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
 	const lines = [];
@@ -20,9 +21,7 @@ async function execute(port, { nocapture, filtered }) {
 		nocapture,
 		write(line) {
 			lines.push(line);
-			if (nocapture) {
-				port.postMessage({ type: "line", line });
-			}
+			port.postMessage({ type: "line", line });
 		},
 	});
 
@@ -42,7 +41,8 @@ async function execute(port, { nocapture, filtered }) {
 		...test,
 		run(testFn) {
 			return withConsoleCapture(test.name, () => testFn(), event =>
-				emit(event)
+				emit(event),
+				consoleProxy
 			);
 		},
 	}));
@@ -58,21 +58,12 @@ async function execute(port, { nocapture, filtered }) {
 	port.postMessage({ type: "report", lines, failed: result.failed });
 }
 
-function withConsoleCapture(name, run, emit) {
-	function emitOutput(line, stream, level) {
+function withConsoleCapture(name, run, emit, consoleProxy) {
+	consoleProxy.setHook((level, args) => {
+		const line = args.join(" ");
+		const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
 		emit({ type: "test-output", name, line, stream, level });
-	}
-
-	const originalLog = console.log;
-	const originalError = console.error;
-	const originalWarn = console.warn;
-	const originalInfo = console.info;
-	const originalDebug = console.debug;
-	console.log = (...args) => emitOutput(args.join(" "), "stdout", "log");
-	console.error = (...args) => emitOutput(args.join(" "), "stderr", "error");
-	console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn");
-	console.info = (...args) => emitOutput(args.join(" "), "stdout", "info");
-	console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug");
+	}, false);
 
 	try {
 		run();
@@ -83,10 +74,6 @@ function withConsoleCapture(name, run, emit) {
 			stack: error.stack
 		};
 	} finally {
-		console.log = originalLog;
-		console.error = originalError;
-		console.warn = originalWarn;
-		console.info = originalInfo;
-		console.debug = originalDebug;
+		consoleProxy.clearHook();
 	}
 }
diff --git a/host/js-bindgen-test-runner/js/shared.mjs b/host/js-bindgen-test-runner/js/shared.mjs
index c52d85fe..c25ec06e 100644
--- a/host/js-bindgen-test-runner/js/shared.mjs
+++ b/host/js-bindgen-test-runner/js/shared.mjs
@@ -118,3 +118,46 @@ export function createTextFormatter({ nocapture, write }) {
 		},
 	};
 }
+
+export function installConsoleProxy() {
+	const base = {
+		log: console.log.bind(console),
+		error: console.error.bind(console),
+		warn: console.warn.bind(console),
+		info: console.info.bind(console),
+		debug: console.debug.bind(console),
+	};
+
+	let hook = null;
+	let forwardToConsole = false;
+	function make(level) {
+		return (...args) => {
+			if (hook) {
+				hook(level, args);
+				if (forwardToConsole) {
+					base[level](...args);
+				}
+			} else {
+				base[level](...args);
+			}
+		};
+	}
+	console.log = make("log");
+	console.error = make("error");
+	console.warn = make("warn");
+	console.info = make("info");
+	console.debug = make("debug");
+
+	const proxy = {
+		base,
+		setHook(fn, forward) {
+			hook = fn;
+			forwardToConsole = forward;
+		},
+		clearHook() {
+			hook = null;
+			forwardToConsole = false;
+		},
+	};
+	return proxy;
+}
diff --git a/host/js-bindgen-test-runner/js/worker-runner.mjs b/host/js-bindgen-test-runner/js/worker-runner.mjs
index 49ab5394..ff019919 100644
--- a/host/js-bindgen-test-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-test-runner/js/worker-runner.mjs
@@ -1,7 +1,8 @@
-import { createTextFormatter } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 
 async function execute(port, { nocapture, filtered }) {
+	const consoleProxy = installConsoleProxy();
 	const tests = await (await fetch("/tests.json")).json();
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
 	const { importObject } = await import("/import.js");
@@ -31,7 +32,8 @@ async function execute(port, { nocapture, filtered }) {
 		...test,
 		run(testFn) {
 			return withConsoleCapture(test.name, () => testFn(), event =>
-				emit(event)
+				emit(event),
+				consoleProxy
 			);
 		},
 	}));
@@ -65,21 +67,12 @@ if (typeof self.onconnect !== "undefined") {
 	};
 }
 
-function withConsoleCapture(name, run, emit) {
-	function emitOutput(line, stream, level) {
+function withConsoleCapture(name, run, emit, consoleProxy) {
+	consoleProxy.setHook((level, args) => {
+		const line = args.join(" ");
+		const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
 		emit({ type: "test-output", name, line, stream, level });
-	}
-
-	const originalLog = console.log;
-	const originalError = console.error;
-	const originalWarn = console.warn;
-	const originalInfo = console.info;
-	const originalDebug = console.debug;
-	console.log = (...args) => emitOutput(args.join(" "), "stdout", "log");
-	console.error = (...args) => emitOutput(args.join(" "), "stderr", "error");
-	console.warn = (...args) => emitOutput(args.join(" "), "stderr", "warn");
-	console.info = (...args) => emitOutput(args.join(" "), "stdout", "info");
-	console.debug = (...args) => emitOutput(args.join(" "), "stdout", "debug");
+	}, false);
 
 	try {
 		run();
@@ -90,10 +83,6 @@ function withConsoleCapture(name, run, emit) {
 			stack: error.stack
 		};
 	} finally {
-		console.log = originalLog;
-		console.error = originalError;
-		console.warn = originalWarn;
-		console.info = originalInfo;
-		console.debug = originalDebug;
+		consoleProxy.clearHook();
 	}
 }

From 956cea78b01076798084787bf72cc49a6fa6cc16 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Wed, 28 Jan 2026 00:20:45 +0800
Subject: [PATCH 07/73] Add COPE/COOP headers

---
 host/js-bindgen-test-runner/src/main.rs | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-test-runner/src/main.rs
index 17f9b0a6..e54ff3dc 100644
--- a/host/js-bindgen-test-runner/src/main.rs
+++ b/host/js-bindgen-test-runner/src/main.rs
@@ -533,6 +533,11 @@ fn handle_connection(
 		return Ok(());
 	}
 
+	if method == "OPTIONS" {
+		write_response(&mut stream, 204, "text/plain", b"")?;
+		return Ok(());
+	}
+
 	if method != "GET" {
 		write_response(&mut stream, 405, "text/plain", b"Method Not Allowed")?;
 		return Ok(());
@@ -567,13 +572,14 @@ fn write_response(
 ) -> Result<()> {
 	let status_text = match status {
 		200 => "OK",
+		204 => "No Content",
 		404 => "Not Found",
 		405 => "Method Not Allowed",
 		_ => "OK",
 	};
 	write!(
 		stream,
-		"HTTP/1.1 {status} {status_text}\r\nContent-Length: {}\r\nContent-Type: {content_type}\r\n\r\n",
+		"HTTP/1.1 {status} {status_text}\r\nContent-Length: {}\r\nContent-Type: {content_type}\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: Content-Type\r\nCross-Origin-Opener-Policy: same-origin\r\nCross-Origin-Embedder-Policy: require-corp\r\n\r\n",
 		body.len()
 	)?;
 	stream.write_all(body)?;

From 83b715dcf2a9447f561008e8a4c98536160c24f5 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Wed, 28 Jan 2026 00:50:58 +0800
Subject: [PATCH 08/73] Clean up

---
 .../js/browser-runner.mjs                     | 76 +++++++------------
 .../js-bindgen-test-runner/js/node-runner.mjs | 30 ++------
 .../js/service-worker.mjs                     | 33 ++------
 host/js-bindgen-test-runner/js/shared.mjs     | 42 ++++++++--
 .../js/worker-runner.mjs                      | 33 ++------
 5 files changed, 88 insertions(+), 126 deletions(-)

diff --git a/host/js-bindgen-test-runner/js/browser-runner.mjs b/host/js-bindgen-test-runner/js/browser-runner.mjs
index 184fa62c..483c4f9f 100644
--- a/host/js-bindgen-test-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-test-runner/js/browser-runner.mjs
@@ -1,4 +1,4 @@
-import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 
 export async function runBrowser({ nocapture, filtered, worker }) {
@@ -9,16 +9,18 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 	const baseInfo = consoleProxy.base.info;
 	const baseDebug = consoleProxy.base.debug;
 
-	let result = worker ? await runInWorker({
-		nocapture,
-		filtered,
-		worker,
-		baseLog,
-		baseError,
-		baseWarn,
-		baseInfo,
-		baseDebug,
-	}) : await runInWindow({ nocapture, filtered, consoleProxy });
+	let result = worker
+		? await runInWorker({
+			nocapture,
+			filtered,
+			worker,
+			baseLog,
+			baseError,
+			baseWarn,
+			baseInfo,
+			baseDebug,
+		})
+		: await runInWindow({ nocapture, filtered, consoleProxy });
 
 	if (typeof window !== "undefined") {
 		window.__jbtestDone = true;
@@ -45,10 +47,13 @@ async function runInWindow({ nocapture, filtered, consoleProxy }) {
 	const testInputs = tests.map(test => ({
 		...test,
 		run(testFn) {
-			return withConsoleCapture(test.name, () => testFn(), event =>
-				formatter.onEvent(event),
-				consoleProxy
-			);
+			return withConsoleCapture({
+				name: test.name,
+				run: () => testFn(),
+				emit: event => formatter.onEvent(event),
+				consoleProxy,
+				forwardToConsole: true,
+			});
 		},
 	}));
 
@@ -107,16 +112,16 @@ async function runInWorker({
 		return null;
 	}
 
-	let reportPromise;
-	if (worker === "dedicated") {
-		reportPromise = runDedicatedWorker({ filtered, nocapture, handleMessage });
-	} else if (worker === "shared") {
-		reportPromise = runSharedWorker({ filtered, nocapture, handleMessage });
-	} else if (worker === "service") {
-		reportPromise = runServiceWorker({ filtered, nocapture, handleMessage });
-	} else {
-		throw new Error(`unsupported worker worker: ${mode}`);
+	const workerRunners = {
+		dedicated: runDedicatedWorker,
+		shared: runSharedWorker,
+		service: runServiceWorker,
+	};
+	const runWorker = workerRunners[worker];
+	if (!runWorker) {
+		throw new Error(`unsupported worker worker: ${worker}`);
 	}
+	const reportPromise = runWorker({ filtered, nocapture, handleMessage });
 
 	const report = await reportPromise;
 	return report;
@@ -218,29 +223,6 @@ async function runServiceWorker({ filtered, nocapture, handleMessage }) {
 	});
 }
 
-function withConsoleCapture(name, run, emit, consoleProxy) {
-	consoleProxy.setHook(
-		(level, args) => {
-			const line = args.join(" ");
-			const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
-			emit({ type: "test-output", name, line, stream, level });
-		},
-		true
-	);
-
-	try {
-		run();
-		return { ok: true };
-	} catch (error) {
-		return {
-			ok: false,
-			stack: error.stack
-		};
-	} finally {
-		consoleProxy.clearHook();
-	}
-}
-
 function appendOutput(line) {
 	const output = ensureOutput();
 	if (output.textContent.length > 0) {
diff --git a/host/js-bindgen-test-runner/js/node-runner.mjs b/host/js-bindgen-test-runner/js/node-runner.mjs
index 82409f29..8704535e 100644
--- a/host/js-bindgen-test-runner/js/node-runner.mjs
+++ b/host/js-bindgen-test-runner/js/node-runner.mjs
@@ -1,6 +1,6 @@
 import fs from "node:fs/promises";
 import { pathToFileURL } from "node:url";
-import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 
 const wasmPath = process.env.JS_BINDGEN_WASM;
@@ -39,7 +39,13 @@ function emit(event) {
 const testInputs = tests.map(test => ({
 	...test,
 	run(testFn) {
-		return withConsoleCapture(test.name, () => testFn(), consoleProxy);
+		return withConsoleCapture({
+            name: test.name,
+            run: () => testFn(),
+			emit: event => formatter.onEvent(event),
+            consoleProxy,
+            forwardToConsole: false,
+        });
 	},
 }));
 
@@ -52,23 +58,3 @@ const result = await runTests({
 });
 
 process.exit(result.failed === 0 ? 0 : 1);
-
-function withConsoleCapture(name, run, consoleProxy) {
-	consoleProxy.setHook((level, args) => {
-		const line = args.join(" ");
-		const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
-		emit({ type: "test-output", name, line, stream, level });
-	}, false);
-
-	try {
-		run();
-		return { ok: true };
-	} catch (error) {
-		return {
-			ok: false,
-			stack: error.stack
-		};
-	} finally {
-		consoleProxy.clearHook();
-	}
-}
diff --git a/host/js-bindgen-test-runner/js/service-worker.mjs b/host/js-bindgen-test-runner/js/service-worker.mjs
index 05e09e78..2574b0e8 100644
--- a/host/js-bindgen-test-runner/js/service-worker.mjs
+++ b/host/js-bindgen-test-runner/js/service-worker.mjs
@@ -1,4 +1,4 @@
-import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 import { importObject } from "./import.js";
 
@@ -40,10 +40,13 @@ async function execute(port, { nocapture, filtered }) {
 	const testInputs = tests.map(test => ({
 		...test,
 		run(testFn) {
-			return withConsoleCapture(test.name, () => testFn(), event =>
-				emit(event),
-				consoleProxy
-			);
+			return withConsoleCapture({
+				name: test.name,
+				run: () => testFn(),
+				emit,
+				consoleProxy,
+				forwardToConsole: false,
+			});
 		},
 	}));
 
@@ -57,23 +60,3 @@ async function execute(port, { nocapture, filtered }) {
 
 	port.postMessage({ type: "report", lines, failed: result.failed });
 }
-
-function withConsoleCapture(name, run, emit, consoleProxy) {
-	consoleProxy.setHook((level, args) => {
-		const line = args.join(" ");
-		const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
-		emit({ type: "test-output", name, line, stream, level });
-	}, false);
-
-	try {
-		run();
-		return { ok: true };
-	} catch (error) {
-		return {
-			ok: false,
-			stack: error.stack
-		};
-	} finally {
-		consoleProxy.clearHook();
-	}
-}
diff --git a/host/js-bindgen-test-runner/js/shared.mjs b/host/js-bindgen-test-runner/js/shared.mjs
index c25ec06e..3c90cff0 100644
--- a/host/js-bindgen-test-runner/js/shared.mjs
+++ b/host/js-bindgen-test-runner/js/shared.mjs
@@ -1,7 +1,7 @@
 export function createTextFormatter({ nocapture, write }) {
 	const buffered = new Map();
 	const failed = [];
-	const failure_reports = [];
+	const failureReports = [];
 	const green = "\u001b[32m";
 	const red = "\u001b[31m";
 	const yellow = "\u001b[33m";
@@ -14,7 +14,7 @@ export function createTextFormatter({ nocapture, write }) {
 		buffered.get(name).push({ line, stream });
 	}
 
-	function take_buffer(name) {
+	function takeBuffer(name) {
 		const entries = buffered.get(name);
 		if (!entries || entries.length === 0) {
 			return [];
@@ -39,7 +39,7 @@ export function createTextFormatter({ nocapture, write }) {
 					}
 					break;
 				case "test-ok":
-					take_buffer(event.name);
+					takeBuffer(event.name);
 					if (event.should_panic) {
 						write(
 							`test ${event.name} - should panic ... ${green}ok${reset}`,
@@ -50,7 +50,7 @@ export function createTextFormatter({ nocapture, write }) {
 					}
 					break;
 				case "test-ignored":
-					take_buffer(event.name);
+					takeBuffer(event.name);
 					if (event.reason) {
 						write(
 							`test ${event.name} ... ${yellow}ignored, ${event.reason}${reset}`,
@@ -70,9 +70,9 @@ export function createTextFormatter({ nocapture, write }) {
 					} else {
 						write(`test ${event.name} ... ${red}FAILED${reset}`, "stdout");
 					}
-					failure_reports.push({
+					failureReports.push({
 						name: event.name,
-						entries: take_buffer(event.name),
+						entries: takeBuffer(event.name),
 						error: event.error,
 					});
 					break;
@@ -81,7 +81,7 @@ export function createTextFormatter({ nocapture, write }) {
 					if (failed.length > 0) {
 						write("failures:", "stdout");
 						write("", "stdout");
-						for (const report of failure_reports) {
+						for (const report of failureReports) {
 							write(`---- ${report.name} stdout ----`, "stdout");
 							for (const entry of report.entries) {
 								write(entry.line, entry.stream);
@@ -120,6 +120,10 @@ export function createTextFormatter({ nocapture, write }) {
 }
 
 export function installConsoleProxy() {
+	const existing = globalThis.__jbtestConsoleProxy;
+	if (existing) {
+		return existing;
+	}
 	const base = {
 		log: console.log.bind(console),
 		error: console.error.bind(console),
@@ -159,5 +163,29 @@ export function installConsoleProxy() {
 			forwardToConsole = false;
 		},
 	};
+	globalThis.__jbtestConsoleProxy = proxy;
 	return proxy;
 }
+
+export function withConsoleCapture({ name, run, emit, consoleProxy, forwardToConsole }) {
+	consoleProxy.setHook(
+		(level, args) => {
+			const line = args.join(" ");
+			const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
+			emit({ type: "test-output", name, line, stream, level });
+		},
+		forwardToConsole
+	);
+
+	try {
+		run();
+		return { ok: true };
+	} catch (error) {
+		return {
+			ok: false,
+			stack: error.stack
+		};
+	} finally {
+		consoleProxy.clearHook();
+	}
+}
diff --git a/host/js-bindgen-test-runner/js/worker-runner.mjs b/host/js-bindgen-test-runner/js/worker-runner.mjs
index ff019919..78853055 100644
--- a/host/js-bindgen-test-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-test-runner/js/worker-runner.mjs
@@ -1,4 +1,4 @@
-import { createTextFormatter, installConsoleProxy } from "./shared.mjs";
+import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
 
 async function execute(port, { nocapture, filtered }) {
@@ -31,10 +31,13 @@ async function execute(port, { nocapture, filtered }) {
 	const testInputs = tests.map(test => ({
 		...test,
 		run(testFn) {
-			return withConsoleCapture(test.name, () => testFn(), event =>
-				emit(event),
-				consoleProxy
-			);
+			return withConsoleCapture({
+				name: test.name,
+				run: () => testFn(),
+				emit,
+				consoleProxy,
+				forwardToConsole: false,
+			});
 		},
 	}));
 
@@ -66,23 +69,3 @@ if (typeof self.onconnect !== "undefined") {
 		});
 	};
 }
-
-function withConsoleCapture(name, run, emit, consoleProxy) {
-	consoleProxy.setHook((level, args) => {
-		const line = args.join(" ");
-		const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
-		emit({ type: "test-output", name, line, stream, level });
-	}, false);
-
-	try {
-		run();
-		return { ok: true };
-	} catch (error) {
-		return {
-			ok: false,
-			stack: error.stack
-		};
-	} finally {
-		consoleProxy.clearHook();
-	}
-}

From 14ff66e3a36a777457283cac62332625d85a3e1a Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Wed, 28 Jan 2026 02:52:44 +0800
Subject: [PATCH 09/73] Add console hook

---
 .../js/browser-runner.mjs                     | 20 +++---
 .../js/console-hook.mjs                       | 72 +++++++++++++++++++
 .../js-bindgen-test-runner/js/node-runner.mjs | 18 ++---
 .../js/service-worker.mjs                     |  6 +-
 host/js-bindgen-test-runner/js/shared.mjs     | 71 ------------------
 .../js/worker-runner.mjs                      |  6 +-
 host/js-bindgen-test-runner/src/main.rs       | 12 ++++
 7 files changed, 109 insertions(+), 96 deletions(-)
 create mode 100644 host/js-bindgen-test-runner/js/console-hook.mjs

diff --git a/host/js-bindgen-test-runner/js/browser-runner.mjs b/host/js-bindgen-test-runner/js/browser-runner.mjs
index 483c4f9f..75ecd804 100644
--- a/host/js-bindgen-test-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-test-runner/js/browser-runner.mjs
@@ -1,13 +1,13 @@
-import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
+import { createTextFormatter } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
 
 export async function runBrowser({ nocapture, filtered, worker }) {
-	const consoleProxy = installConsoleProxy();
-	const baseLog = consoleProxy.base.log;
-	const baseError = consoleProxy.base.error;
-	const baseWarn = consoleProxy.base.warn;
-	const baseInfo = consoleProxy.base.info;
-	const baseDebug = consoleProxy.base.debug;
+	const baseLog = consoleHook.base.log;
+	const baseError = consoleHook.base.error;
+	const baseWarn = consoleHook.base.warn;
+	const baseInfo = consoleHook.base.info;
+	const baseDebug = consoleHook.base.debug;
 
 	let result = worker
 		? await runInWorker({
@@ -20,7 +20,7 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 			baseInfo,
 			baseDebug,
 		})
-		: await runInWindow({ nocapture, filtered, consoleProxy });
+		: await runInWindow({ nocapture, filtered, consoleHook });
 
 	if (typeof window !== "undefined") {
 		window.__jbtestDone = true;
@@ -30,7 +30,7 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 	return result;
 }
 
-async function runInWindow({ nocapture, filtered, consoleProxy }) {
+async function runInWindow({ nocapture, filtered, consoleHook }) {
 	const tests = await (await fetch("/tests.json")).json();
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
 	const { importObject } = await import("/import.js");
@@ -51,7 +51,7 @@ async function runInWindow({ nocapture, filtered, consoleProxy }) {
 				name: test.name,
 				run: () => testFn(),
 				emit: event => formatter.onEvent(event),
-				consoleProxy,
+				consoleHook,
 				forwardToConsole: true,
 			});
 		},
diff --git a/host/js-bindgen-test-runner/js/console-hook.mjs b/host/js-bindgen-test-runner/js/console-hook.mjs
new file mode 100644
index 00000000..d1d6549f
--- /dev/null
+++ b/host/js-bindgen-test-runner/js/console-hook.mjs
@@ -0,0 +1,72 @@
+function installConsoleHook() {
+	const existing = globalThis.__jbtestConsoleHook;
+	if (existing) {
+		return existing;
+	}
+	const base = {
+		log: console.log.bind(console),
+		error: console.error.bind(console),
+		warn: console.warn.bind(console),
+		info: console.info.bind(console),
+		debug: console.debug.bind(console),
+	};
+
+	let hook = null;
+	let forwardToConsole = false;
+	function make(level) {
+		return (...args) => {
+			if (hook) {
+				hook(level, args);
+				if (forwardToConsole) {
+					base[level](...args);
+				}
+			} else {
+				base[level](...args);
+			}
+		};
+	}
+	console.log = make("log");
+	console.error = make("error");
+	console.warn = make("warn");
+	console.info = make("info");
+	console.debug = make("debug");
+
+	const h = {
+		base,
+		setHook(fn, forward) {
+			hook = fn;
+			forwardToConsole = forward;
+		},
+		clearHook() {
+			hook = null;
+			forwardToConsole = false;
+		},
+	};
+	globalThis.__jbtestConsoleHook = h;
+	return h;
+}
+
+export function withConsoleCapture({ name, run, emit, consoleHook, forwardToConsole }) {
+	consoleHook.setHook(
+		(level, args) => {
+			const line = args.join(" ");
+			const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
+			emit({ type: "test-output", name, line, stream, level });
+		},
+		forwardToConsole
+	);
+
+	try {
+		run();
+		return { ok: true };
+	} catch (error) {
+		return {
+			ok: false,
+			stack: error.stack
+		};
+	} finally {
+		consoleHook.clearHook();
+	}
+}
+
+export default installConsoleHook();
diff --git a/host/js-bindgen-test-runner/js/node-runner.mjs b/host/js-bindgen-test-runner/js/node-runner.mjs
index 8704535e..eb20d186 100644
--- a/host/js-bindgen-test-runner/js/node-runner.mjs
+++ b/host/js-bindgen-test-runner/js/node-runner.mjs
@@ -1,7 +1,8 @@
 import fs from "node:fs/promises";
 import { pathToFileURL } from "node:url";
-import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
+import { createTextFormatter } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
 
 const wasmPath = process.env.JS_BINDGEN_WASM;
 const importsPath = process.env.JS_BINDGEN_IMPORTS;
@@ -14,13 +15,12 @@ if (!wasmPath || !importsPath || !testsJson) {
 	process.exit(1);
 }
 
-const consoleProxy = installConsoleProxy();
 const { importObject } = await import(pathToFileURL(importsPath));
 const wasmBytes = await fs.readFile(wasmPath);
 const tests = JSON.parse(testsJson);
 
-const baseLog = consoleProxy.base.log;
-const baseError = consoleProxy.base.error;
+const baseLog = consoleHook.base.log;
+const baseError = consoleHook.base.error;
 const formatter = createTextFormatter({
 	nocapture,
 	write(line, stream) {
@@ -40,12 +40,12 @@ const testInputs = tests.map(test => ({
 	...test,
 	run(testFn) {
 		return withConsoleCapture({
-            name: test.name,
-            run: () => testFn(),
+			name: test.name,
+			run: () => testFn(),
 			emit: event => formatter.onEvent(event),
-            consoleProxy,
-            forwardToConsole: false,
-        });
+			consoleHook,
+			forwardToConsole: false,
+		});
 	},
 }));
 
diff --git a/host/js-bindgen-test-runner/js/service-worker.mjs b/host/js-bindgen-test-runner/js/service-worker.mjs
index 2574b0e8..72596acf 100644
--- a/host/js-bindgen-test-runner/js/service-worker.mjs
+++ b/host/js-bindgen-test-runner/js/service-worker.mjs
@@ -1,5 +1,6 @@
-import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
+import { createTextFormatter } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
 import { importObject } from "./import.js";
 
 self.addEventListener("message", event => {
@@ -13,7 +14,6 @@ self.addEventListener("message", event => {
 });
 
 async function execute(port, { nocapture, filtered }) {
-	const consoleProxy = installConsoleProxy();
 	const tests = await (await fetch("/tests.json")).json();
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
 	const lines = [];
@@ -44,7 +44,7 @@ async function execute(port, { nocapture, filtered }) {
 				name: test.name,
 				run: () => testFn(),
 				emit,
-				consoleProxy,
+				consoleHook,
 				forwardToConsole: false,
 			});
 		},
diff --git a/host/js-bindgen-test-runner/js/shared.mjs b/host/js-bindgen-test-runner/js/shared.mjs
index 3c90cff0..408a6fda 100644
--- a/host/js-bindgen-test-runner/js/shared.mjs
+++ b/host/js-bindgen-test-runner/js/shared.mjs
@@ -118,74 +118,3 @@ export function createTextFormatter({ nocapture, write }) {
 		},
 	};
 }
-
-export function installConsoleProxy() {
-	const existing = globalThis.__jbtestConsoleProxy;
-	if (existing) {
-		return existing;
-	}
-	const base = {
-		log: console.log.bind(console),
-		error: console.error.bind(console),
-		warn: console.warn.bind(console),
-		info: console.info.bind(console),
-		debug: console.debug.bind(console),
-	};
-
-	let hook = null;
-	let forwardToConsole = false;
-	function make(level) {
-		return (...args) => {
-			if (hook) {
-				hook(level, args);
-				if (forwardToConsole) {
-					base[level](...args);
-				}
-			} else {
-				base[level](...args);
-			}
-		};
-	}
-	console.log = make("log");
-	console.error = make("error");
-	console.warn = make("warn");
-	console.info = make("info");
-	console.debug = make("debug");
-
-	const proxy = {
-		base,
-		setHook(fn, forward) {
-			hook = fn;
-			forwardToConsole = forward;
-		},
-		clearHook() {
-			hook = null;
-			forwardToConsole = false;
-		},
-	};
-	globalThis.__jbtestConsoleProxy = proxy;
-	return proxy;
-}
-
-export function withConsoleCapture({ name, run, emit, consoleProxy, forwardToConsole }) {
-	consoleProxy.setHook(
-		(level, args) => {
-			const line = args.join(" ");
-			const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
-			emit({ type: "test-output", name, line, stream, level });
-		},
-		forwardToConsole
-	);
-
-	try {
-		run();
-		return { ok: true };
-	} catch (error) {
-		return {
-			ok: false,
-			stack: error.stack
-		};
-	} finally {
-		consoleProxy.clearHook();
-	}
-}
diff --git a/host/js-bindgen-test-runner/js/worker-runner.mjs b/host/js-bindgen-test-runner/js/worker-runner.mjs
index 78853055..5504cb01 100644
--- a/host/js-bindgen-test-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-test-runner/js/worker-runner.mjs
@@ -1,8 +1,8 @@
-import { createTextFormatter, installConsoleProxy, withConsoleCapture } from "./shared.mjs";
+import { createTextFormatter } from "./shared.mjs";
 import { runTests } from "./runner-core.mjs";
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
 
 async function execute(port, { nocapture, filtered }) {
-	const consoleProxy = installConsoleProxy();
 	const tests = await (await fetch("/tests.json")).json();
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
 	const { importObject } = await import("/import.js");
@@ -35,7 +35,7 @@ async function execute(port, { nocapture, filtered }) {
 				name: test.name,
 				run: () => testFn(),
 				emit,
-				consoleProxy,
+				consoleHook,
 				forwardToConsole: false,
 			});
 		},
diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-test-runner/src/main.rs
index e54ff3dc..de1b29e5 100644
--- a/host/js-bindgen-test-runner/src/main.rs
+++ b/host/js-bindgen-test-runner/src/main.rs
@@ -21,6 +21,7 @@ const RUNNER_CORE_SOURCE: &str = include_str!("../js/runner-core.mjs");
 const SHARED_JS_SOURCE: &str = include_str!("../js/shared.mjs");
 const WORKER_RUNNER_SOURCE: &str = include_str!("../js/worker-runner.mjs");
 const SERVICE_WORKER_SOURCE: &str = include_str!("../js/service-worker.mjs");
+const CONSOLE_HOOK_SOURCE: &str = include_str!("../js/console-hook.mjs");
 
 #[derive(Debug, serde::Serialize)]
 struct TestEntry {
@@ -340,6 +341,7 @@ struct BrowserAssets {
 	shared_js: &'static str,
 	worker_js: &'static str,
 	service_worker_js: &'static str,
+	console_hook_js: &'static str,
 	index_html: String,
 }
 
@@ -392,6 +394,7 @@ await fetch("/report", {{
 			shared_js: SHARED_JS_SOURCE,
 			worker_js: WORKER_RUNNER_SOURCE,
 			service_worker_js: SERVICE_WORKER_SOURCE,
+			console_hook_js: CONSOLE_HOOK_SOURCE,
 			index_html,
 		})
 	}
@@ -496,6 +499,10 @@ fn handle_connection(
 		}
 	}
 
+	if header_end == 0 {
+		return Ok(());
+	}
+
 	let (header_bytes, body) = request.split_at(header_end + 4);
 	let request_text = String::from_utf8_lossy(header_bytes);
 	let mut lines = request_text.lines();
@@ -554,6 +561,11 @@ fn handle_connection(
 			"application/javascript",
 			200,
 		),
+		"/console-hook.mjs" => (
+			assets.console_hook_js.as_bytes(),
+			"application/javascript",
+			200,
+		),
 		"/import.js" => (assets.import_js.as_bytes(), "application/javascript", 200),
 		"/tests.json" => (assets.tests_json.as_bytes(), "application/json", 200),
 		"/wasm" => (assets.wasm_bytes.as_slice(), "application/wasm", 200),

From d74ca8ff97fa283d672e8418d85a5e9950a7b91f Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Wed, 28 Jan 2026 20:36:31 +0800
Subject: [PATCH 10/73] Fix warning

---
 host/ld/src/main.rs | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/host/ld/src/main.rs b/host/ld/src/main.rs
index ea3c0b61..30077bc6 100644
--- a/host/ld/src/main.rs
+++ b/host/ld/src/main.rs
@@ -92,7 +92,8 @@ fn main() {
 		js_bindgen_ld_shared::ld_input_parser::(input, |path, data| {
 			process_object(&arch_str, &mut add_args, path, data);
 			Ok(())
-		});
+		})
+		.unwrap();
 	}
 
 	let status = Command::new("rust-lld")

From 75dfc98c5fbe0f133243ad2ca534f847b06ecef3 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 00:23:11 +0800
Subject: [PATCH 11/73] Add client test workflow

---
 .github/workflows/main.yml | 68 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 68 insertions(+)
 create mode 100644 .github/workflows/main.yml

diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
new file mode 100644
index 00000000..d7a514e3
--- /dev/null
+++ b/.github/workflows/main.yml
@@ -0,0 +1,68 @@
+name: CI
+on:
+  push:
+    branches: [main]
+  pull_request:
+    branches: [main]
+  workflow_dispatch:
+
+env:
+  CARGO_TERM_COLOR: always
+
+jobs:
+  test_wasm32:
+    name: wasm32
+    runs-on: ${{ matrix.os }}
+    strategy:
+      matrix:
+        os: [ubuntu-latest]
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v6
+      - name: Install Rust
+        uses: dtolnay/rust-toolchain@stable
+        with:
+          targets: wasm32-unknown-unknown
+      # llvm-mc used
+      - name: Install LLVM
+        uses: KyleMayes/install-llvm-action@v2
+        with:
+          # rustc 1.93.0
+          version: "21.1.8"
+      - name: Test js-sys
+        working-directory: client
+        run: cargo test -p js-sys --target wasm32-unknown-unknown
+      - name: Test web-sys
+        working-directory: client
+        run: cargo test -p web-sys --target wasm32-unknown-unknown
+
+  test_wasm64:
+    name: wasm64
+    runs-on: ${{ matrix.os }}
+    strategy:
+      matrix:
+        os: [ubuntu-latest]
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v6
+      - name: Install Rust
+        uses: dtolnay/rust-toolchain@nightly
+        with:
+          components: rust-src
+      # llvm-mc used
+      - name: Install LLVM
+        uses: KyleMayes/install-llvm-action@v2
+        with:
+          # rustc 1.93.0
+          version: "21.1.8"
+      - name: Setup Node.js
+        uses: actions/setup-node@v6
+        with:
+          node-version: 25
+      - name: Test js-sys
+        working-directory: client
+        run: cargo +nightly test -p js-sys --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std
+      - name: Test web-sys
+        working-directory: client
+        run: cargo +nightly test -p web-sys --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std
+

From 2724ab24639c105e827b4104c90d3ed2dea459d0 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 10:55:09 +0800
Subject: [PATCH 12/73] Update runner shim

---
 client/.cargo/config.toml   |  2 +-
 linker-shim/linker          |  7 -------
 linker-shim/linker.cmd      |  2 +-
 linker-shim/runner.cmd      | 18 ++++++++++++++++++
 linker-shim/test-runner     |  7 -------
 linker-shim/test-runner.cmd |  5 -----
 6 files changed, 20 insertions(+), 21 deletions(-)
 delete mode 100755 linker-shim/linker
 create mode 100755 linker-shim/runner.cmd
 delete mode 100755 linker-shim/test-runner
 delete mode 100644 linker-shim/test-runner.cmd

diff --git a/client/.cargo/config.toml b/client/.cargo/config.toml
index 3dd8d5ce..82c3f6d8 100644
--- a/client/.cargo/config.toml
+++ b/client/.cargo/config.toml
@@ -3,4 +3,4 @@ target = "wasm32-unknown-unknown"
 
 [target.'cfg(all(target_family = "wasm", any(target_os = "none", target_os = "unknown")))']
 linker = "../linker-shim/linker.cmd"
-runner = "../linker-shim/test-runner"
+runner = "../linker-shim/runner.cmd"
diff --git a/linker-shim/linker b/linker-shim/linker
deleted file mode 100755
index ca6e32ec..00000000
--- a/linker-shim/linker
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-(
-  cd "$(dirname "$0")/../host" || exit 1
-  cargo run -q -p js-bindgen-ld -- "$@"
-)
-exit $?
diff --git a/linker-shim/linker.cmd b/linker-shim/linker.cmd
index f94f1c78..7be4a8f3 100755
--- a/linker-shim/linker.cmd
+++ b/linker-shim/linker.cmd
@@ -13,6 +13,6 @@
 :: Never reached on UNIX because we execute `exit`.
 @echo off
 pushd "%~dp0..\host" || exit /b 1
-cargo run -q -p js-bindgen-ld -- %*
+cargo +stable run -q -p js-bindgen-ld -- %*
 popd
 exit /b %ERRORLEVEL%
diff --git a/linker-shim/runner.cmd b/linker-shim/runner.cmd
new file mode 100755
index 00000000..42031763
--- /dev/null
+++ b/linker-shim/runner.cmd
@@ -0,0 +1,18 @@
+#!/usr/bin/env -S =2>NUL sh
+:; # A very quirky solution until we find a better one.
+
+:; # UNIX
+:; # Lines starting with `:;` are ignored on Windows but are executed on UNIX.
+:; (
+:;   cd "$(dirname "$0")/../host" || exit 1
+:;   cargo +stable run -q -p js-bindgen-test-runner -- "$@"
+:; )
+:; exit $?
+
+:: Windows
+:: Never reached on UNIX because we execute `exit`.
+@echo off
+pushd "%~dp0..\host" || exit /b 1
+cargo +stable run -q -p js-bindgen-test-runner -- %*
+popd
+exit /b %ERRORLEVEL%
diff --git a/linker-shim/test-runner b/linker-shim/test-runner
deleted file mode 100755
index 6f878ea3..00000000
--- a/linker-shim/test-runner
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-(
-  cd "$(dirname "$0")/../host" || exit 1
-  cargo run -q -p js-bindgen-test-runner -- "$@"
-)
-exit $?
diff --git a/linker-shim/test-runner.cmd b/linker-shim/test-runner.cmd
deleted file mode 100644
index f0f9cd3d..00000000
--- a/linker-shim/test-runner.cmd
+++ /dev/null
@@ -1,5 +0,0 @@
-@echo off
-pushd "%~dp0..\host" || exit /b 1
-cargo run -q -p js-bindgen-test-runner -- %*
-popd
-exit /b %ERRORLEVEL%

From 45345f89dc9fc47d7a7afac4b8832b8c2b827392 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 11:06:20 +0800
Subject: [PATCH 13/73] Fix cargo format

---
 client/js-bindgen-test/Cargo.toml     | 6 +++---
 host/js-bindgen-test-macro/Cargo.toml | 5 ++---
 2 files changed, 5 insertions(+), 6 deletions(-)

diff --git a/client/js-bindgen-test/Cargo.toml b/client/js-bindgen-test/Cargo.toml
index dd392edd..55916e28 100644
--- a/client/js-bindgen-test/Cargo.toml
+++ b/client/js-bindgen-test/Cargo.toml
@@ -1,8 +1,8 @@
 [package]
-edition.workspace = true
+edition = { workspace = true }
 name = "js-bindgen-test"
-rust-version.workspace = true
-version = "0.1.0"
+
+rust-version = { workspace = true }
 
 [dependencies]
 js-bindgen-test-macro = { workspace = true }
diff --git a/host/js-bindgen-test-macro/Cargo.toml b/host/js-bindgen-test-macro/Cargo.toml
index b7f7b7ae..dbb25ece 100644
--- a/host/js-bindgen-test-macro/Cargo.toml
+++ b/host/js-bindgen-test-macro/Cargo.toml
@@ -1,8 +1,7 @@
 [package]
-edition.workspace = true
+edition = { workspace = true }
 name = "js-bindgen-test-macro"
-rust-version.workspace = true
-version = "0.1.0"
+rust-version = { workspace = true }
 
 [lib]
 proc-macro = true

From 827d10416e354ad614e1cee8d1bc2146543ca4be Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 11:17:11 +0800
Subject: [PATCH 14/73] No alias

---
 host/js-bindgen-test-runner/src/main.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-test-runner/src/main.rs
index de1b29e5..09c95971 100644
--- a/host/js-bindgen-test-runner/src/main.rs
+++ b/host/js-bindgen-test-runner/src/main.rs
@@ -1,6 +1,6 @@
 use std::env;
 use std::fs;
-use std::io::{ErrorKind, Read, Write as IoWrite};
+use std::io::{ErrorKind, Read, Write};
 use std::net::{TcpListener, TcpStream};
 use std::path::{Path, PathBuf};
 use std::process::Command;

From b2bfe58b8ebf62e14b10fdd24fff393e0f622a36 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 11:25:53 +0800
Subject: [PATCH 15/73] Update workflow

---
 .github/workflows/main.yml  | 68 -------------------------------------
 .github/workflows/test.yaml | 33 ++++++++++++++++++
 2 files changed, 33 insertions(+), 68 deletions(-)
 delete mode 100644 .github/workflows/main.yml

diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
deleted file mode 100644
index d7a514e3..00000000
--- a/.github/workflows/main.yml
+++ /dev/null
@@ -1,68 +0,0 @@
-name: CI
-on:
-  push:
-    branches: [main]
-  pull_request:
-    branches: [main]
-  workflow_dispatch:
-
-env:
-  CARGO_TERM_COLOR: always
-
-jobs:
-  test_wasm32:
-    name: wasm32
-    runs-on: ${{ matrix.os }}
-    strategy:
-      matrix:
-        os: [ubuntu-latest]
-    steps:
-      - name: Checkout
-        uses: actions/checkout@v6
-      - name: Install Rust
-        uses: dtolnay/rust-toolchain@stable
-        with:
-          targets: wasm32-unknown-unknown
-      # llvm-mc used
-      - name: Install LLVM
-        uses: KyleMayes/install-llvm-action@v2
-        with:
-          # rustc 1.93.0
-          version: "21.1.8"
-      - name: Test js-sys
-        working-directory: client
-        run: cargo test -p js-sys --target wasm32-unknown-unknown
-      - name: Test web-sys
-        working-directory: client
-        run: cargo test -p web-sys --target wasm32-unknown-unknown
-
-  test_wasm64:
-    name: wasm64
-    runs-on: ${{ matrix.os }}
-    strategy:
-      matrix:
-        os: [ubuntu-latest]
-    steps:
-      - name: Checkout
-        uses: actions/checkout@v6
-      - name: Install Rust
-        uses: dtolnay/rust-toolchain@nightly
-        with:
-          components: rust-src
-      # llvm-mc used
-      - name: Install LLVM
-        uses: KyleMayes/install-llvm-action@v2
-        with:
-          # rustc 1.93.0
-          version: "21.1.8"
-      - name: Setup Node.js
-        uses: actions/setup-node@v6
-        with:
-          node-version: 25
-      - name: Test js-sys
-        working-directory: client
-        run: cargo +nightly test -p js-sys --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std
-      - name: Test web-sys
-        working-directory: client
-        run: cargo +nightly test -p web-sys --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std
-
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index b0237e90..b7157597 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -44,3 +44,36 @@ jobs:
           llvm-version: 21
       - name: Run Tests
         run: cargo test --no-fail-fast
+
+  client:
+    name: Test Client ${{ matrix.os.description }}
+
+    runs-on: ${{ matrix.os.os }}
+
+    timeout-minutes: 10
+
+    strategy:
+      fail-fast: false
+      matrix:
+        os:
+          - { os: ubuntu-latest, description: Linux }
+          # - { os: macos-latest, description: MacOS }
+          # - { os: windows-latest, description: Windows }
+
+    defaults:
+      run:
+        working-directory: client
+
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v4
+      - name: Install Rust
+        run: rustup target add wasm32-unknown-unknown
+      - name: Install LLVM
+        uses: ZhongRuoyu/setup-llvm@ec41d6e5f3c15c96fa642a49c6e7effac6261778
+        with:
+          # Rustc v1.93
+          llvm-version: 21
+      - name: Run Tests
+        run: cargo test --target wasm32-unknown-unknown --no-fail-fast --workspace
+

From ea2b08fa51ea499320d3e92ff91bee61395713bd Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 12:07:27 +0800
Subject: [PATCH 16/73] Efficient parse arguments

---
 host/js-bindgen-test-runner/src/main.rs | 91 +++++++++++++------------
 1 file changed, 46 insertions(+), 45 deletions(-)

diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-test-runner/src/main.rs
index 09c95971..6a41a0f2 100644
--- a/host/js-bindgen-test-runner/src/main.rs
+++ b/host/js-bindgen-test-runner/src/main.rs
@@ -33,14 +33,14 @@ struct TestEntry {
 }
 
 fn main() -> Result<()> {
-	let mut args = env::args().skip(1).collect::>();
+	let mut args = env::args().skip(1);
+
 	let wasm_path = args
-		.first()
+		.next()
 		.map(PathBuf::from)
 		.context("expected a wasm file path")?;
-	let extra_args = args.split_off(1);
 
-	let args = parse_test_args(extra_args)?;
+	let args = TestArgs::new(args)?;
 	let wasm_bytes = fs::read(&wasm_path)
 		.with_context(|| format!("failed to read wasm file: {}", wasm_path.display()))?;
 
@@ -109,47 +109,6 @@ fn main() -> Result<()> {
 	Ok(())
 }
 
-fn parse_test_args(args: Vec) -> Result {
-	let mut output = TestArgs {
-		list_only: false,
-		nocapture: false,
-		filters: Vec::new(),
-		list_format: ListFormat::Standard,
-		ignored_only: false,
-		exact: false,
-		runner: RunnerConfig::from_env()?,
-	};
-
-	let mut iter = args.into_iter();
-	while let Some(arg) = iter.next() {
-		if arg == "--list" {
-			output.list_only = true;
-		} else if arg == "--nocapture" {
-			output.nocapture = true;
-		} else if arg == "--ignored" {
-			output.ignored_only = true;
-		} else if arg == "--exact" {
-			output.exact = true;
-		} else if let Some(value) = arg.strip_prefix("--format=") {
-			if value == "terse" {
-				output.list_format = ListFormat::Terse;
-			}
-		} else if arg == "--format" {
-			if let Some(value) = iter.next() {
-				if value == "terse" {
-					output.list_format = ListFormat::Terse;
-				}
-			}
-		} else if arg.starts_with('-') {
-			continue;
-		} else {
-			output.filters.push(arg);
-		}
-	}
-
-	Ok(output)
-}
-
 enum ListFormat {
 	Standard,
 	Terse,
@@ -165,6 +124,48 @@ struct TestArgs {
 	runner: RunnerConfig,
 }
 
+impl TestArgs {
+	pub fn new(mut iter: impl Iterator) -> Result {
+		let mut output = TestArgs {
+			list_only: false,
+			nocapture: false,
+			filters: Vec::new(),
+			list_format: ListFormat::Standard,
+			ignored_only: false,
+			exact: false,
+			runner: RunnerConfig::from_env()?,
+		};
+
+		while let Some(arg) = iter.next() {
+			if arg == "--list" {
+				output.list_only = true;
+			} else if arg == "--nocapture" {
+				output.nocapture = true;
+			} else if arg == "--ignored" {
+				output.ignored_only = true;
+			} else if arg == "--exact" {
+				output.exact = true;
+			} else if let Some(value) = arg.strip_prefix("--format=") {
+				if value == "terse" {
+					output.list_format = ListFormat::Terse;
+				}
+			} else if arg == "--format" {
+				if let Some(value) = iter.next() {
+					if value == "terse" {
+						output.list_format = ListFormat::Terse;
+					}
+				}
+			} else if arg.starts_with('-') {
+				continue;
+			} else {
+				output.filters.push(arg);
+			}
+		}
+
+		Ok(output)
+	}
+}
+
 #[derive(Debug)]
 struct RunnerConfig {
 	kind: RunnerKind,

From c466541eb6143bd407c364cf5a245bd616dc6a78 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 12:12:30 +0800
Subject: [PATCH 17/73] Add const for ascii color

---
 host/js-bindgen-test-runner/src/main.rs | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-test-runner/src/main.rs
index 6a41a0f2..75855604 100644
--- a/host/js-bindgen-test-runner/src/main.rs
+++ b/host/js-bindgen-test-runner/src/main.rs
@@ -23,6 +23,9 @@ const WORKER_RUNNER_SOURCE: &str = include_str!("../js/worker-runner.mjs");
 const SERVICE_WORKER_SOURCE: &str = include_str!("../js/service-worker.mjs");
 const CONSOLE_HOOK_SOURCE: &str = include_str!("../js/console-hook.mjs");
 
+const GREEN: &str = "\u{001b}[32m";
+const RESET: &str = "\u{001b}[0m";
+
 #[derive(Debug, serde::Serialize)]
 struct TestEntry {
 	name: String,
@@ -70,7 +73,7 @@ fn main() -> Result<()> {
 		println!("running 0 tests");
 		println!();
 		println!(
-			"test result: \u{001b}[32mok\u{001b}[0m. 0 passed; 0 failed; 0 ignored; 0 measured; {filtered_count} filtered out; finished in 0.00s"
+			"test result: {GREEN}ok{RESET}. 0 passed; 0 failed; 0 ignored; 0 measured; {filtered_count} filtered out; finished in 0.00s"
 		);
 		println!();
 		return Ok(());

From 5b4b16ca8c767f05820b1453154731121c56186e Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 12:23:08 +0800
Subject: [PATCH 18/73] Clean up

---
 host/js-bindgen-test-runner/js/index.html | 18 ++++++++
 host/js-bindgen-test-runner/src/main.rs   | 51 +++++++----------------
 2 files changed, 33 insertions(+), 36 deletions(-)
 create mode 100644 host/js-bindgen-test-runner/js/index.html

diff --git a/host/js-bindgen-test-runner/js/index.html b/host/js-bindgen-test-runner/js/index.html
new file mode 100644
index 00000000..9660cd91
--- /dev/null
+++ b/host/js-bindgen-test-runner/js/index.html
@@ -0,0 +1,18 @@
+
+
+js-bindgen test
+

+
+
diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-test-runner/src/main.rs
index 75855604..00cce46f 100644
--- a/host/js-bindgen-test-runner/src/main.rs
+++ b/host/js-bindgen-test-runner/src/main.rs
@@ -340,12 +340,6 @@ struct BrowserAssets {
 	wasm_bytes: Vec,
 	import_js: String,
 	tests_json: String,
-	runner_js: &'static str,
-	core_js: &'static str,
-	shared_js: &'static str,
-	worker_js: &'static str,
-	service_worker_js: &'static str,
-	console_hook_js: &'static str,
 	index_html: String,
 }
 
@@ -362,24 +356,7 @@ impl BrowserAssets {
 		let import_js = fs::read_to_string(imports_path)?;
 
 		let index_html = format!(
-			r#"
-
-js-bindgen test
-

-
-"#,
+			include_str!("../js/index.html"),
 			filtered_count = filtered_count,
 			nocapture_flag = if nocapture { "true" } else { "false" },
 			worker = if let Some(worker) = worker {
@@ -393,12 +370,6 @@ await fetch("/report", {{
 			wasm_bytes,
 			import_js,
 			tests_json: tests_json.to_string(),
-			runner_js: BROWSER_RUNNER_SOURCE,
-			core_js: RUNNER_CORE_SOURCE,
-			shared_js: SHARED_JS_SOURCE,
-			worker_js: WORKER_RUNNER_SOURCE,
-			service_worker_js: SERVICE_WORKER_SOURCE,
-			console_hook_js: CONSOLE_HOOK_SOURCE,
 			index_html,
 		})
 	}
@@ -556,17 +527,25 @@ fn handle_connection(
 
 	let (body, content_type, status) = match path {
 		"/" | "/index.html" => (assets.index_html.as_bytes(), "text/html", 200),
-		"/browser-runner.mjs" => (assets.runner_js.as_bytes(), "application/javascript", 200),
-		"/runner-core.mjs" => (assets.core_js.as_bytes(), "application/javascript", 200),
-		"/shared.mjs" => (assets.shared_js.as_bytes(), "application/javascript", 200),
-		"/worker-runner.mjs" => (assets.worker_js.as_bytes(), "application/javascript", 200),
+		"/browser-runner.mjs" => (
+			BROWSER_RUNNER_SOURCE.as_bytes(),
+			"application/javascript",
+			200,
+		),
+		"/runner-core.mjs" => (RUNNER_CORE_SOURCE.as_bytes(), "application/javascript", 200),
+		"/shared.mjs" => (SHARED_JS_SOURCE.as_bytes(), "application/javascript", 200),
+		"/worker-runner.mjs" => (
+			WORKER_RUNNER_SOURCE.as_bytes(),
+			"application/javascript",
+			200,
+		),
 		"/service-worker.mjs" => (
-			assets.service_worker_js.as_bytes(),
+			SERVICE_WORKER_SOURCE.as_bytes(),
 			"application/javascript",
 			200,
 		),
 		"/console-hook.mjs" => (
-			assets.console_hook_js.as_bytes(),
+			CONSOLE_HOOK_SOURCE.as_bytes(),
 			"application/javascript",
 			200,
 		),

From b3480f463c9a2ca21a7952e38e2a9a73237ae759 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 12:25:49 +0800
Subject: [PATCH 19/73] Rename to `js-bindgen-runner`

---
 host/Cargo.toml                                               | 2 +-
 host/{js-bindgen-test-runner => js-bindgen-runner}/Cargo.toml | 2 +-
 .../js/browser-runner.mjs                                     | 0
 .../js/console-hook.mjs                                       | 0
 .../js/index.html                                             | 0
 .../js/node-runner.mjs                                        | 0
 .../js/playwright-runner.mjs                                  | 0
 .../js/runner-core.mjs                                        | 0
 .../js/service-worker.mjs                                     | 0
 .../js/shared.mjs                                             | 0
 .../js/worker-runner.mjs                                      | 0
 .../{js-bindgen-test-runner => js-bindgen-runner}/src/main.rs | 0
 linker-shim/runner.cmd                                        | 4 ++--
 13 files changed, 4 insertions(+), 4 deletions(-)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/Cargo.toml (89%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/browser-runner.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/console-hook.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/index.html (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/node-runner.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/playwright-runner.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/runner-core.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/service-worker.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/shared.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/js/worker-runner.mjs (100%)
 rename host/{js-bindgen-test-runner => js-bindgen-runner}/src/main.rs (100%)

diff --git a/host/Cargo.toml b/host/Cargo.toml
index 0037967c..b74f0713 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -3,7 +3,7 @@ members = [
 	"js-bindgen",
 	"js-sys-macro",
 	"js-bindgen-test-macro",
-	"js-bindgen-test-runner",
+	"js-bindgen-runner",
 	"ld",
 	"ld-shared",
 	"macro-shared",
diff --git a/host/js-bindgen-test-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
similarity index 89%
rename from host/js-bindgen-test-runner/Cargo.toml
rename to host/js-bindgen-runner/Cargo.toml
index d99383ae..c7efbabc 100644
--- a/host/js-bindgen-test-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 edition = { workspace = true }
-name = "js-bindgen-test-runner"
+name = "js-bindgen-runner"
 rust-version = { workspace = true }
 
 [dependencies]
diff --git a/host/js-bindgen-test-runner/js/browser-runner.mjs b/host/js-bindgen-runner/js/browser-runner.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/browser-runner.mjs
rename to host/js-bindgen-runner/js/browser-runner.mjs
diff --git a/host/js-bindgen-test-runner/js/console-hook.mjs b/host/js-bindgen-runner/js/console-hook.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/console-hook.mjs
rename to host/js-bindgen-runner/js/console-hook.mjs
diff --git a/host/js-bindgen-test-runner/js/index.html b/host/js-bindgen-runner/js/index.html
similarity index 100%
rename from host/js-bindgen-test-runner/js/index.html
rename to host/js-bindgen-runner/js/index.html
diff --git a/host/js-bindgen-test-runner/js/node-runner.mjs b/host/js-bindgen-runner/js/node-runner.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/node-runner.mjs
rename to host/js-bindgen-runner/js/node-runner.mjs
diff --git a/host/js-bindgen-test-runner/js/playwright-runner.mjs b/host/js-bindgen-runner/js/playwright-runner.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/playwright-runner.mjs
rename to host/js-bindgen-runner/js/playwright-runner.mjs
diff --git a/host/js-bindgen-test-runner/js/runner-core.mjs b/host/js-bindgen-runner/js/runner-core.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/runner-core.mjs
rename to host/js-bindgen-runner/js/runner-core.mjs
diff --git a/host/js-bindgen-test-runner/js/service-worker.mjs b/host/js-bindgen-runner/js/service-worker.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/service-worker.mjs
rename to host/js-bindgen-runner/js/service-worker.mjs
diff --git a/host/js-bindgen-test-runner/js/shared.mjs b/host/js-bindgen-runner/js/shared.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/shared.mjs
rename to host/js-bindgen-runner/js/shared.mjs
diff --git a/host/js-bindgen-test-runner/js/worker-runner.mjs b/host/js-bindgen-runner/js/worker-runner.mjs
similarity index 100%
rename from host/js-bindgen-test-runner/js/worker-runner.mjs
rename to host/js-bindgen-runner/js/worker-runner.mjs
diff --git a/host/js-bindgen-test-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
similarity index 100%
rename from host/js-bindgen-test-runner/src/main.rs
rename to host/js-bindgen-runner/src/main.rs
diff --git a/linker-shim/runner.cmd b/linker-shim/runner.cmd
index 42031763..aca115e9 100755
--- a/linker-shim/runner.cmd
+++ b/linker-shim/runner.cmd
@@ -5,7 +5,7 @@
 :; # Lines starting with `:;` are ignored on Windows but are executed on UNIX.
 :; (
 :;   cd "$(dirname "$0")/../host" || exit 1
-:;   cargo +stable run -q -p js-bindgen-test-runner -- "$@"
+:;   cargo +stable run -q -p js-bindgen-runner -- "$@"
 :; )
 :; exit $?
 
@@ -13,6 +13,6 @@
 :: Never reached on UNIX because we execute `exit`.
 @echo off
 pushd "%~dp0..\host" || exit /b 1
-cargo +stable run -q -p js-bindgen-test-runner -- %*
+cargo +stable run -q -p js-bindgen-runner -- %*
 popd
 exit /b %ERRORLEVEL%

From 7999676899425beb5a67a6efdfcc81aabe7d20f8 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 12:28:41 +0800
Subject: [PATCH 20/73] Clean up

---
 host/js-bindgen-runner/src/main.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 00cce46f..751a62b2 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -273,7 +273,7 @@ fn run_playwright(
 	let mut child = Command::new("node")
 		.arg(runner_path)
 		.env("JBTEST_URL", url)
-		.env("JBTEST_BROWSER", runner.browser.clone())
+		.env("JBTEST_BROWSER", &runner.browser)
 		.spawn()
 		.context("failed to run node")?;
 

From d27f21ac1e110398e08ae3e928509859aa874a6b Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 17:34:44 +0800
Subject: [PATCH 21/73] Update workflow

---
 .github/workflows/test.yaml | 4 ++--
 linker-shim/runner.cmd      | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index b7157597..b9a97b9c 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -57,8 +57,8 @@ jobs:
       matrix:
         os:
           - { os: ubuntu-latest, description: Linux }
-          # - { os: macos-latest, description: MacOS }
-          # - { os: windows-latest, description: Windows }
+          - { os: macos-latest, description: MacOS }
+          - { os: windows-latest, description: Windows }
 
     defaults:
       run:
diff --git a/linker-shim/runner.cmd b/linker-shim/runner.cmd
index aca115e9..089f106f 100755
--- a/linker-shim/runner.cmd
+++ b/linker-shim/runner.cmd
@@ -1,5 +1,5 @@
-#!/usr/bin/env -S =2>NUL sh
-:; # A very quirky solution until we find a better one.
+#!/usr/bin/env -S DUMMY=2>NUL sh
+:; # A very quirky solution to make things run cross-platform.
 
 :; # UNIX
 :; # Lines starting with `:;` are ignored on Windows but are executed on UNIX.

From 10d241ddc57fdca6c31853398467e7d3c344ec94 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 19:08:33 +0800
Subject: [PATCH 22/73] Rename env

---
 TEST.md                                         | 12 ++++++------
 host/js-bindgen-runner/js/playwright-runner.mjs |  6 +++---
 host/js-bindgen-runner/src/main.rs              | 14 +++++++-------
 3 files changed, 16 insertions(+), 16 deletions(-)

diff --git a/TEST.md b/TEST.md
index a0039ed5..4f54bab3 100644
--- a/TEST.md
+++ b/TEST.md
@@ -36,21 +36,21 @@ cargo test --target wasm32-unknown-unknown
 Wasm tests: Browser runner (Playwright headless):
 
 ```sh
-JBTEST_BROWSER=chromium cargo test --target wasm32-unknown-unknown
+JBG_TEST_BROWSER=chromium cargo test --target wasm32-unknown-unknown
 ```
 
 Wasm tests: Browser server mode (open URL in a browser):
 
 ```sh
-JBTEST_SERVER=1 cargo test --target wasm32-unknown-unknown
+JBG_TEST_SERVER=1 cargo test --target wasm32-unknown-unknown
 ```
 
 Runner options:
 
-- `JBTEST_BROWSER=chromium|firefox|webkit`
-- `JBTEST_WORKER=dedicated|shared|service`
-- `JBTEST_SERVER=1` (serve browser runner and print URL)
-- `JBTEST_SERVER_ADDRESS=127.0.0.1:8000` (defaults to 8000; falls back to a random port if busy)
+- `JBG_TEST_BROWSER=chromium|firefox|webkit`
+- `JBG_TEST_WORKER=dedicated|shared|service`
+- `JBG_TEST_SERVER=1` (serve browser runner and print URL)
+- `JBG_TEST_SERVER_ADDRESS=127.0.0.1:8000` (defaults to 8000; falls back to a random port if busy)
 
 List and filter tests:
 
diff --git a/host/js-bindgen-runner/js/playwright-runner.mjs b/host/js-bindgen-runner/js/playwright-runner.mjs
index 19ea90c3..a05a8466 100644
--- a/host/js-bindgen-runner/js/playwright-runner.mjs
+++ b/host/js-bindgen-runner/js/playwright-runner.mjs
@@ -1,11 +1,11 @@
 import { chromium, firefox, webkit } from "playwright";
 
-const url = process.env.JBTEST_URL;
+const url = process.env.JBG_TEST_URL;
 if (!url) {
-	throw new Error("missing JBTEST_URL");
+	throw new Error("missing JBG_TEST_URL");
 }
 
-const browserName = (process.env.JBTEST_BROWSER || "chromium").toLowerCase();
+const browserName = (process.env.JBG_TEST_BROWSER || "chromium").toLowerCase();
 const browserType = {
 	chromium,
 	firefox,
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 751a62b2..0e940db9 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -184,21 +184,21 @@ impl RunnerConfig {
 			worker: None,
 		};
 
-		if let Ok(worker) = env::var("JBTEST_WORKER") {
+		if let Ok(worker) = env::var("JBG_TEST_WORKER") {
 			if !matches!(worker.as_str(), "dedicated" | "shared" | "service") {
 				bail!("unsupported {worker}, supported dedicated, shared and service");
 			}
 			config.worker = Some(worker);
 		}
 
-		if let Ok(browser) = env::var("JBTEST_BROWSER") {
+		if let Ok(browser) = env::var("JBG_TEST_BROWSER") {
 			config.kind = RunnerKind::Browser;
 			if matches!(browser.as_str(), "chromium" | "firefox" | "webkit") {
 				config.browser = browser;
 			}
 		}
 
-		if std::env::var("JBTEST_SERVER").is_ok() {
+		if std::env::var("JBG_TEST_SERVER").is_ok() {
 			config.kind = RunnerKind::BrowserServer;
 		}
 
@@ -266,14 +266,14 @@ fn run_playwright(
 		nocapture,
 		runner.worker.as_deref(),
 	)?;
-	let server = HttpServer::start(assets, env::var("JBTEST_SERVER_ADDRESS").ok().as_deref())?;
+	let server = HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref())?;
 	let url = build_browser_url(server.base_url.as_str());
 
 	let runner_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(PLAYWRIGHT_RUNNER);
 	let mut child = Command::new("node")
 		.arg(runner_path)
-		.env("JBTEST_URL", url)
-		.env("JBTEST_BROWSER", &runner.browser)
+		.env("JBG_TEST_URL", url)
+		.env("JBG_TEST_BROWSER", &runner.browser)
 		.spawn()
 		.context("failed to run node")?;
 
@@ -310,7 +310,7 @@ fn run_browser_server(
 		nocapture,
 		runner.worker.as_deref(),
 	)?;
-	let server = HttpServer::start(assets, env::var("JBTEST_SERVER_ADDRESS").ok().as_deref())?;
+	let server = HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref())?;
 	let url = build_browser_url(server.base_url.as_str());
 
 	println!("open this URL in your browser to run tests:");

From b4565689d2f50c663f851c9493a784296e9f9e7b Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 19:40:07 +0800
Subject: [PATCH 23/73] Reduce read

---
 host/js-bindgen-runner/src/main.rs | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 0e940db9..ba143b85 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -92,7 +92,7 @@ fn main() -> Result<()> {
 			args.nocapture,
 		)?,
 		RunnerKind::Browser => run_playwright(
-			&wasm_path,
+			wasm_bytes,
 			&imports_path,
 			tests_json,
 			filtered_count,
@@ -100,7 +100,7 @@ fn main() -> Result<()> {
 			&args.runner,
 		)?,
 		RunnerKind::BrowserServer => run_browser_server(
-			&wasm_path,
+			wasm_bytes,
 			&imports_path,
 			tests_json,
 			filtered_count,
@@ -251,7 +251,7 @@ fn ensure_module_package(imports_path: &Path) {
 }
 
 fn run_playwright(
-	wasm_path: &Path,
+	wasm_bytes: Vec,
 	imports_path: &Path,
 	tests_json: String,
 	filtered_count: usize,
@@ -259,7 +259,7 @@ fn run_playwright(
 	runner: &RunnerConfig,
 ) -> Result<()> {
 	let assets = BrowserAssets::new(
-		wasm_path,
+		wasm_bytes,
 		imports_path,
 		&tests_json,
 		filtered_count,
@@ -295,7 +295,7 @@ fn run_playwright(
 }
 
 fn run_browser_server(
-	wasm_path: &Path,
+	wasm_bytes: Vec,
 	imports_path: &Path,
 	tests_json: String,
 	filtered_count: usize,
@@ -303,7 +303,7 @@ fn run_browser_server(
 	runner: &RunnerConfig,
 ) -> Result<()> {
 	let assets = BrowserAssets::new(
-		wasm_path,
+		wasm_bytes,
 		imports_path,
 		&tests_json,
 		filtered_count,
@@ -345,7 +345,7 @@ struct BrowserAssets {
 
 impl BrowserAssets {
 	fn new(
-		wasm_path: &Path,
+		wasm_bytes: Vec,
 		imports_path: &Path,
 		tests_json: &str,
 		filtered_count: usize,

From 3096d69877ab5467b78883a35617576e43b0661f Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 19:42:58 +0800
Subject: [PATCH 24/73] Mmap

---
 host/js-bindgen-runner/Cargo.toml  | 1 +
 host/js-bindgen-runner/src/main.rs | 8 ++++----
 2 files changed, 5 insertions(+), 4 deletions(-)

diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index c7efbabc..0077a66d 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -8,6 +8,7 @@ anyhow = { workspace = true }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 wasmparser = { workspace = true }
+js-bindgen-ld-shared = { workspace = true }
 
 [lints]
 workspace = true
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index ba143b85..7a488b5c 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -12,6 +12,7 @@ use std::thread;
 use std::time::Duration;
 
 use anyhow::{Context, Result, bail};
+use js_bindgen_ld_shared::ReadFile;
 use wasmparser::{Parser, Payload};
 
 const NODE_RUNNER: &str = "js/node-runner.mjs";
@@ -44,7 +45,7 @@ fn main() -> Result<()> {
 		.context("expected a wasm file path")?;
 
 	let args = TestArgs::new(args)?;
-	let wasm_bytes = fs::read(&wasm_path)
+	let wasm_bytes = ReadFile::new(&wasm_path)
 		.with_context(|| format!("failed to read wasm file: {}", wasm_path.display()))?;
 
 	let mut tests = read_tests(&wasm_bytes)?;
@@ -92,7 +93,7 @@ fn main() -> Result<()> {
 			args.nocapture,
 		)?,
 		RunnerKind::Browser => run_playwright(
-			wasm_bytes,
+			wasm_bytes.to_vec(),
 			&imports_path,
 			tests_json,
 			filtered_count,
@@ -100,7 +101,7 @@ fn main() -> Result<()> {
 			&args.runner,
 		)?,
 		RunnerKind::BrowserServer => run_browser_server(
-			wasm_bytes,
+			wasm_bytes.to_vec(),
 			&imports_path,
 			tests_json,
 			filtered_count,
@@ -352,7 +353,6 @@ impl BrowserAssets {
 		nocapture: bool,
 		worker: Option<&str>,
 	) -> Result {
-		let wasm_bytes = fs::read(wasm_path)?;
 		let import_js = fs::read_to_string(imports_path)?;
 
 		let index_html = format!(

From cc01b38e9b5fed5fbb603d1e80c2a818a5868321 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 21:55:51 +0800
Subject: [PATCH 25/73] Update driver and worker parse

---
 TEST.md                                       |   4 +-
 .../js/playwright-runner.mjs                  |   8 +-
 host/js-bindgen-runner/src/main.rs            | 143 +++++++++++++-----
 3 files changed, 108 insertions(+), 47 deletions(-)

diff --git a/TEST.md b/TEST.md
index 4f54bab3..5f38e3de 100644
--- a/TEST.md
+++ b/TEST.md
@@ -36,7 +36,7 @@ cargo test --target wasm32-unknown-unknown
 Wasm tests: Browser runner (Playwright headless):
 
 ```sh
-JBG_TEST_BROWSER=chromium cargo test --target wasm32-unknown-unknown
+JBG_TEST_DRIVER=chrome cargo test --target wasm32-unknown-unknown
 ```
 
 Wasm tests: Browser server mode (open URL in a browser):
@@ -47,7 +47,7 @@ JBG_TEST_SERVER=1 cargo test --target wasm32-unknown-unknown
 
 Runner options:
 
-- `JBG_TEST_BROWSER=chromium|firefox|webkit`
+- `JBG_TEST_DRIVER=chrome|gecko|webkit`
 - `JBG_TEST_WORKER=dedicated|shared|service`
 - `JBG_TEST_SERVER=1` (serve browser runner and print URL)
 - `JBG_TEST_SERVER_ADDRESS=127.0.0.1:8000` (defaults to 8000; falls back to a random port if busy)
diff --git a/host/js-bindgen-runner/js/playwright-runner.mjs b/host/js-bindgen-runner/js/playwright-runner.mjs
index a05a8466..a6010bc6 100644
--- a/host/js-bindgen-runner/js/playwright-runner.mjs
+++ b/host/js-bindgen-runner/js/playwright-runner.mjs
@@ -5,11 +5,11 @@ if (!url) {
 	throw new Error("missing JBG_TEST_URL");
 }
 
-const browserName = (process.env.JBG_TEST_BROWSER || "chromium").toLowerCase();
+const browserName = (process.env.JBG_TEST_DRIVER || "chrome").toLowerCase();
 const browserType = {
-	chromium,
-	firefox,
-	webkit,
+	chrome: chromium,
+	gecko: firefox,
+	webkit
 }[browserName];
 
 if (!browserType) {
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 7a488b5c..604b7166 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -84,29 +84,30 @@ fn main() -> Result<()> {
 	let imports_path = wasm_path.with_extension("js");
 	let tests_json = serde_json::to_string(&tests).expect("checked");
 
-	match args.runner.kind {
-		RunnerKind::Node => run_node(
+	match args.runner {
+		RunnerConfig::Nodejs => run_node(
 			&wasm_path,
 			&imports_path,
 			tests_json,
 			filtered_count,
 			args.nocapture,
 		)?,
-		RunnerKind::Browser => run_playwright(
+		RunnerConfig::Browser { kind, worker } => run_playwright(
 			wasm_bytes.to_vec(),
 			&imports_path,
 			tests_json,
 			filtered_count,
 			args.nocapture,
-			&args.runner,
+			&kind,
+			worker.as_ref(),
 		)?,
-		RunnerKind::BrowserServer => run_browser_server(
+		RunnerConfig::Server { worker } => run_browser_server(
 			wasm_bytes.to_vec(),
 			&imports_path,
 			tests_json,
 			filtered_count,
 			args.nocapture,
-			&args.runner,
+			worker.as_ref(),
 		)?,
 	}
 
@@ -171,49 +172,108 @@ impl TestArgs {
 }
 
 #[derive(Debug)]
-struct RunnerConfig {
-	kind: RunnerKind,
-	browser: String,
-	worker: Option,
+enum RunnerConfig {
+	Nodejs,
+	Browser {
+		kind: DriverKind,
+		worker: Option,
+	},
+	Server {
+		worker: Option,
+	},
+}
+
+#[derive(Debug)]
+enum WorkerKind {
+	// https://developer.mozilla.org/en-US/docs/Web/API/Worker
+	Dedicated,
+	// https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker
+	Shared,
+	// https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker
+	Service,
+}
+
+impl WorkerKind {
+	fn from_str(worker: &str) -> Result {
+		Ok(match worker {
+			"dedicated" => WorkerKind::Dedicated,
+			"shared" => WorkerKind::Shared,
+			"service" => WorkerKind::Service,
+			worker => bail!("unsupported worker: {worker}"),
+		})
+	}
+
+	fn as_str(&self) -> &str {
+		match self {
+			WorkerKind::Dedicated => "dedicated",
+			WorkerKind::Shared => "shared",
+			WorkerKind::Service => "service",
+		}
+	}
+}
+
+#[derive(Debug)]
+enum DriverKind {
+	// https://developer.chrome.com/docs/chromedriver
+	Chrome,
+	// https://github.com/mozilla/geckodriver
+	Gecko,
+	// https://github.com/WebKit/WebKit
+	WebKit,
+}
+
+impl DriverKind {
+	fn from_str(driver: &str) -> Result {
+		Ok(match driver {
+			"chrome" => DriverKind::Chrome,
+			"gecko" => DriverKind::Gecko,
+			"webkit" => DriverKind::WebKit,
+			driver => bail!("unsupported driver: {driver}"),
+		})
+	}
+
+	fn as_str(&self) -> &str {
+		match self {
+			DriverKind::Chrome => "chrome",
+			DriverKind::Gecko => "gecko",
+			DriverKind::WebKit => "webkit",
+		}
+	}
 }
 
 impl RunnerConfig {
 	fn from_env() -> Result {
-		let mut config = RunnerConfig {
-			kind: RunnerKind::Node,
-			browser: "chromium".to_string(),
-			worker: None,
+		let driver = match env::var("JBG_TEST_DRIVER") {
+			Ok(driver) => Some(DriverKind::from_str(&driver)?),
+			Err(_) => None,
 		};
 
-		if let Ok(worker) = env::var("JBG_TEST_WORKER") {
-			if !matches!(worker.as_str(), "dedicated" | "shared" | "service") {
-				bail!("unsupported {worker}, supported dedicated, shared and service");
-			}
-			config.worker = Some(worker);
-		}
+		let worker = match env::var("JBG_TEST_WORKER") {
+			Ok(worker) => Some(WorkerKind::from_str(&worker)?),
+			Err(_) => None,
+		};
 
-		if let Ok(browser) = env::var("JBG_TEST_BROWSER") {
-			config.kind = RunnerKind::Browser;
-			if matches!(browser.as_str(), "chromium" | "firefox" | "webkit") {
-				config.browser = browser;
-			}
-		}
+		let server = env::var("JBG_TEST_SERVER").is_ok();
 
-		if std::env::var("JBG_TEST_SERVER").is_ok() {
-			config.kind = RunnerKind::BrowserServer;
-		}
+		let config = match (server, driver) {
+			(true, None) => RunnerConfig::Server { worker },
+			(true, Some(d)) => {
+				eprintln!("Because a server has been configured, the {d:?} option is not work.");
+				RunnerConfig::Server { worker }
+			}
+			(false, None) => {
+				if let Some(worker) = worker {
+					eprintln!("The {worker:?} option does not work in Node.js.");
+				}
+				RunnerConfig::Nodejs
+			}
+			(false, Some(kind)) => RunnerConfig::Browser { kind, worker },
+		};
 
 		Ok(config)
 	}
 }
 
-#[derive(Debug)]
-enum RunnerKind {
-	Node,
-	Browser,
-	BrowserServer,
-}
-
 fn run_node(
 	wasm_path: &Path,
 	imports_path: &Path,
@@ -257,7 +317,8 @@ fn run_playwright(
 	tests_json: String,
 	filtered_count: usize,
 	nocapture: bool,
-	runner: &RunnerConfig,
+	driver: &DriverKind,
+	worker: Option<&WorkerKind>,
 ) -> Result<()> {
 	let assets = BrowserAssets::new(
 		wasm_bytes,
@@ -265,7 +326,7 @@ fn run_playwright(
 		&tests_json,
 		filtered_count,
 		nocapture,
-		runner.worker.as_deref(),
+		worker.map(|s| s.as_str()),
 	)?;
 	let server = HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref())?;
 	let url = build_browser_url(server.base_url.as_str());
@@ -274,7 +335,7 @@ fn run_playwright(
 	let mut child = Command::new("node")
 		.arg(runner_path)
 		.env("JBG_TEST_URL", url)
-		.env("JBG_TEST_BROWSER", &runner.browser)
+		.env("JBG_TEST_DRIVER", driver.as_str())
 		.spawn()
 		.context("failed to run node")?;
 
@@ -301,7 +362,7 @@ fn run_browser_server(
 	tests_json: String,
 	filtered_count: usize,
 	nocapture: bool,
-	runner: &RunnerConfig,
+	worker: Option<&WorkerKind>,
 ) -> Result<()> {
 	let assets = BrowserAssets::new(
 		wasm_bytes,
@@ -309,7 +370,7 @@ fn run_browser_server(
 		&tests_json,
 		filtered_count,
 		nocapture,
-		runner.worker.as_deref(),
+		worker.map(|s| s.as_str()),
 	)?;
 	let server = HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref())?;
 	let url = build_browser_url(server.base_url.as_str());

From a732330c62c1ea9c35586cc8081f6acfe5d1b0f5 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 22:49:14 +0800
Subject: [PATCH 26/73] Read tests by path

---
 host/js-bindgen-runner/Cargo.toml         |  1 +
 host/js-bindgen-runner/js/index.html      | 20 ++++++++++----------
 host/js-bindgen-runner/js/node-runner.mjs |  7 ++++---
 host/js-bindgen-runner/src/main.rs        |  5 ++++-
 4 files changed, 19 insertions(+), 14 deletions(-)

diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index 0077a66d..17d48a29 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -9,6 +9,7 @@ serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 wasmparser = { workspace = true }
 js-bindgen-ld-shared = { workspace = true }
+tempfile = "3"
 
 [lints]
 workspace = true
diff --git a/host/js-bindgen-runner/js/index.html b/host/js-bindgen-runner/js/index.html
index 9660cd91..e55516ed 100644
--- a/host/js-bindgen-runner/js/index.html
+++ b/host/js-bindgen-runner/js/index.html
@@ -3,16 +3,16 @@
 js-bindgen test
 

 
 
diff --git a/host/js-bindgen-runner/js/node-runner.mjs b/host/js-bindgen-runner/js/node-runner.mjs
index eb20d186..c268192f 100644
--- a/host/js-bindgen-runner/js/node-runner.mjs
+++ b/host/js-bindgen-runner/js/node-runner.mjs
@@ -6,18 +6,19 @@ import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
 
 const wasmPath = process.env.JS_BINDGEN_WASM;
 const importsPath = process.env.JS_BINDGEN_IMPORTS;
-const testsJson = process.env.JS_BINDGEN_TESTS;
+const testsPath = process.env.JS_BINDGEN_TESTS_PATH;
 const nocapture = process.env.JS_BINDGEN_NOCAPTURE === "1";
 const filtered = Number(process.env.JS_BINDGEN_FILTERED || "0");
 
-if (!wasmPath || !importsPath || !testsJson) {
+if (!wasmPath || !importsPath || !testsPath) {
 	console.error("missing test runner environment");
 	process.exit(1);
 }
 
 const { importObject } = await import(pathToFileURL(importsPath));
 const wasmBytes = await fs.readFile(wasmPath);
-const tests = JSON.parse(testsJson);
+const testsText = await fs.readFile(testsPath, "utf8");
+const tests = JSON.parse(testsText);
 
 const baseLog = consoleHook.base.log;
 const baseError = consoleHook.base.error;
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 604b7166..28cccb04 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -283,12 +283,15 @@ fn run_node(
 ) -> Result<()> {
 	ensure_module_package(imports_path);
 	let runner_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(NODE_RUNNER);
+	let mut tests_file = tempfile::NamedTempFile::new()?;
+	tests_file.write_all(tests_json.as_bytes())?;
+	let tests_path = tests_file.path().to_path_buf();
 
 	let status = Command::new("node")
 		.arg(runner_path)
 		.env("JS_BINDGEN_WASM", wasm_path)
 		.env("JS_BINDGEN_IMPORTS", imports_path)
-		.env("JS_BINDGEN_TESTS", tests_json)
+		.env("JS_BINDGEN_TESTS_PATH", &tests_path)
 		.env("JS_BINDGEN_FILTERED", filtered_count.to_string())
 		.env("JS_BINDGEN_NOCAPTURE", if nocapture { "1" } else { "0" })
 		.status()

From 112de9f96c8d2c7d151e2a3b4e0b6ee6f2cd7071 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 23:17:33 +0800
Subject: [PATCH 27/73] Add comment

---
 host/ld/src/main.rs | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/host/ld/src/main.rs b/host/ld/src/main.rs
index 30077bc6..93a30574 100644
--- a/host/ld/src/main.rs
+++ b/host/ld/src/main.rs
@@ -408,6 +408,8 @@ fn post_processing(output_path: &Path, main_memory: MainMemory<'_>) -> Vec {
 		"missing JS embed: {expected_embed:?}"
 	);
 
+    // After the linker is done, Cargo copies the final output to be the name of the package without the fingerprint. We do the same for the JS file.
+    // TODO: Skip when detecting test.
 	let js_output_path = output_path.with_file_name(package).with_extension("js");
 	let mut js_output =
 		BufWriter::new(File::create(&js_output_path).expect("output JS file should be writable"));

From 25425276cd77cb2c2e3de812eb9ecc0037194d4e Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Thu, 29 Jan 2026 23:17:57 +0800
Subject: [PATCH 28/73] Move tempfile to workspace

---
 host/Cargo.toml                   | 1 +
 host/js-bindgen-runner/Cargo.toml | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/host/Cargo.toml b/host/Cargo.toml
index b74f0713..f5efeed0 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -37,6 +37,7 @@ syn = { version = "2", default-features = false, features = ["parsing", "printin
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
+tempfile = { version = "3", default-features = false}
 
 [patch.crates-io]
 # Detect unsupported platforms at run-time: https://github.com/RazrFalcon/memmap2-rs/pull/161.
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index 17d48a29..6361a9e6 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -9,7 +9,7 @@ serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 wasmparser = { workspace = true }
 js-bindgen-ld-shared = { workspace = true }
-tempfile = "3"
+tempfile = { workspace = true }
 
 [lints]
 workspace = true

From 9a2c2b7255b6f2838f4b7f575631806c6f367460 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Fri, 30 Jan 2026 16:54:00 +0800
Subject: [PATCH 29/73] Replace the code of creating js file

---
 host/ld/src/main.rs | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/host/ld/src/main.rs b/host/ld/src/main.rs
index 93a30574..86e6f56a 100644
--- a/host/ld/src/main.rs
+++ b/host/ld/src/main.rs
@@ -408,9 +408,8 @@ fn post_processing(output_path: &Path, main_memory: MainMemory<'_>) -> Vec {
 		"missing JS embed: {expected_embed:?}"
 	);
 
-    // After the linker is done, Cargo copies the final output to be the name of the package without the fingerprint. We do the same for the JS file.
-    // TODO: Skip when detecting test.
-	let js_output_path = output_path.with_file_name(package).with_extension("js");
+	// We also need a js file with a fingerprint, otherwise the test files might overwrite each other.
+	let js_output_path = output_path.with_extension("js");
 	let mut js_output =
 		BufWriter::new(File::create(&js_output_path).expect("output JS file should be writable"));
 
@@ -500,9 +499,13 @@ fn post_processing(output_path: &Path, main_memory: MainMemory<'_>) -> Vec {
 
 	js_output.into_inner().unwrap().sync_all().unwrap();
 
-	// We also need a js file with a fingerprint, otherwise the test files might overwrite each other.
-	fs::copy(js_output_path, output_path.with_extension("js"))
-		.expect("copy JS file should be success");
+	// After the linker is done, Cargo copies the final output to be the name of the package without the fingerprint. We do the same for the JS file.
+	// TODO: Skip when detecting test.
+	fs::copy(
+		js_output_path,
+		output_path.with_file_name(package).with_extension("js"),
+	)
+	.expect("copy JS file should be success");
 
 	wasm_output
 }

From 41ac558fdef7073615b5d94e3c99dfd19363e009 Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Fri, 30 Jan 2026 10:18:01 +0100
Subject: [PATCH 30/73] Nits

---
 .github/workflows/test.yaml            |  2 +-
 TODO.md                                |  7 +++++++
 {linker-shim => cargo-shim}/README.md  |  0
 {linker-shim => cargo-shim}/linker.cmd |  0
 {linker-shim => cargo-shim}/runner.cmd |  0
 client/.cargo/config.toml              |  4 ++--
 client/js-bindgen-test/Cargo.toml      |  1 -
 host/js-bindgen-runner/src/main.rs     |  2 +-
 host/ld/src/main.rs                    | 11 ++++++-----
 9 files changed, 17 insertions(+), 10 deletions(-)
 rename {linker-shim => cargo-shim}/README.md (100%)
 rename {linker-shim => cargo-shim}/linker.cmd (100%)
 rename {linker-shim => cargo-shim}/runner.cmd (100%)

diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index b9a97b9c..47e1c3b1 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -75,5 +75,5 @@ jobs:
           # Rustc v1.93
           llvm-version: 21
       - name: Run Tests
-        run: cargo test --target wasm32-unknown-unknown --no-fail-fast --workspace
+        run: cargo test --no-fail-fast
 
diff --git a/TODO.md b/TODO.md
index 8e328200..8074adf3 100644
--- a/TODO.md
+++ b/TODO.md
@@ -12,6 +12,10 @@
 
 # High Priority
 
+- Test Runner:
+  - Instead of Playwright, interface with Webdrivers directly. Use [Fantoccini] or [Thirtyfour].
+  - Add Deno support.
+  - Add Edge support.
 - E2E testing for the linker. Should also ensure deterministic output.
 - Add a `disable_hygiene` attribute to `#[js_sys]` to reduce the compile-time of the output to an
   absolute minimum. This can avoid all `interpolate`s.
@@ -39,6 +43,9 @@
     This seems to have failed. No build script instruction can reach the linker on Wasm.
 - Memory-mapped file reading should lock files to make it safe.
 
+[Fantoccini]: https://crates.io/crates/fantoccini
+[Thirtyfour]: https://crates.io/crates/thirtyfour
+
 # Medium Priority
 
 - Find a way to link to imports directly if no wrapper function is needed. This happens when no
diff --git a/linker-shim/README.md b/cargo-shim/README.md
similarity index 100%
rename from linker-shim/README.md
rename to cargo-shim/README.md
diff --git a/linker-shim/linker.cmd b/cargo-shim/linker.cmd
similarity index 100%
rename from linker-shim/linker.cmd
rename to cargo-shim/linker.cmd
diff --git a/linker-shim/runner.cmd b/cargo-shim/runner.cmd
similarity index 100%
rename from linker-shim/runner.cmd
rename to cargo-shim/runner.cmd
diff --git a/client/.cargo/config.toml b/client/.cargo/config.toml
index 82c3f6d8..e6cd89bc 100644
--- a/client/.cargo/config.toml
+++ b/client/.cargo/config.toml
@@ -2,5 +2,5 @@
 target = "wasm32-unknown-unknown"
 
 [target.'cfg(all(target_family = "wasm", any(target_os = "none", target_os = "unknown")))']
-linker = "../linker-shim/linker.cmd"
-runner = "../linker-shim/runner.cmd"
+linker = "../cargo-shim/linker.cmd"
+runner = "../cargo-shim/runner.cmd"
diff --git a/client/js-bindgen-test/Cargo.toml b/client/js-bindgen-test/Cargo.toml
index 55916e28..40f06664 100644
--- a/client/js-bindgen-test/Cargo.toml
+++ b/client/js-bindgen-test/Cargo.toml
@@ -1,7 +1,6 @@
 [package]
 edition = { workspace = true }
 name = "js-bindgen-test"
-
 rust-version = { workspace = true }
 
 [dependencies]
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 28cccb04..0d4b54a3 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -130,7 +130,7 @@ struct TestArgs {
 }
 
 impl TestArgs {
-	pub fn new(mut iter: impl Iterator) -> Result {
+	fn new(mut iter: impl Iterator) -> Result {
 		let mut output = TestArgs {
 			list_only: false,
 			nocapture: false,
diff --git a/host/ld/src/main.rs b/host/ld/src/main.rs
index 86e6f56a..7ebe46e9 100644
--- a/host/ld/src/main.rs
+++ b/host/ld/src/main.rs
@@ -92,8 +92,7 @@ fn main() {
 		js_bindgen_ld_shared::ld_input_parser::(input, |path, data| {
 			process_object(&arch_str, &mut add_args, path, data);
 			Ok(())
-		})
-		.unwrap();
+		});
 	}
 
 	let status = Command::new("rust-lld")
@@ -408,7 +407,8 @@ fn post_processing(output_path: &Path, main_memory: MainMemory<'_>) -> Vec {
 		"missing JS embed: {expected_embed:?}"
 	);
 
-	// We also need a js file with a fingerprint, otherwise the test files might overwrite each other.
+	// We also need a js file with a fingerprint, otherwise the test files might
+	// overwrite each other.
 	let js_output_path = output_path.with_extension("js");
 	let mut js_output =
 		BufWriter::new(File::create(&js_output_path).expect("output JS file should be writable"));
@@ -499,8 +499,9 @@ fn post_processing(output_path: &Path, main_memory: MainMemory<'_>) -> Vec {
 
 	js_output.into_inner().unwrap().sync_all().unwrap();
 
-	// After the linker is done, Cargo copies the final output to be the name of the package without the fingerprint. We do the same for the JS file.
-	// TODO: Skip when detecting test.
+	// After the linker is done, Cargo copies the final output to be the name of the
+	// package without the fingerprint. We do the same for the JS file. TODO: Skip
+	// when detecting test.
 	fs::copy(
 		js_output_path,
 		output_path.with_file_name(package).with_extension("js"),

From d8e7159e95287f5dfa52a263ad5d97b63efb4666 Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Fri, 30 Jan 2026 10:19:00 +0100
Subject: [PATCH 31/73] Format

---
 .github/workflows/test.yaml                   |   1 -
 TEST.md                                       |   2 -
 client/js-bindgen-test/src/lib.rs             |   4 +-
 client/web-sys/src/lib.rs                     |   3 +-
 host/Cargo.toml                               |   2 +-
 host/js-bindgen-runner/Cargo.toml             |   4 +-
 host/js-bindgen-runner/js/browser-runner.mjs  | 239 +++++++++---------
 host/js-bindgen-runner/js/console-hook.mjs    |  67 +++--
 host/js-bindgen-runner/js/index.html          |  23 +-
 host/js-bindgen-runner/js/node-runner.mjs     |  54 ++--
 .../js/playwright-runner.mjs                  |  24 +-
 host/js-bindgen-runner/js/runner-core.mjs     |  88 +++----
 host/js-bindgen-runner/js/service-worker.mjs  |  42 +--
 host/js-bindgen-runner/js/shared.mjs          | 111 ++++----
 host/js-bindgen-runner/js/worker-runner.mjs   |  50 ++--
 host/js-bindgen-runner/src/main.rs            |  19 +-
 16 files changed, 360 insertions(+), 373 deletions(-)

diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index 47e1c3b1..b22847de 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -76,4 +76,3 @@ jobs:
           llvm-version: 21
       - name: Run Tests
         run: cargo test --no-fail-fast
-
diff --git a/TEST.md b/TEST.md
index 5f38e3de..1ed9614d 100644
--- a/TEST.md
+++ b/TEST.md
@@ -96,5 +96,3 @@ cd client
 CARGO_TARGET_WASM64_UNKNOWN_UNKNOWN_RUSTFLAGS="-Ctarget-feature=+atomics -Clink-arg=--shared-memory -Clink-arg=--max-memory=17179869184" \
   cargo +nightly build --example basic --target wasm64-unknown-unknown -Zbuild-std=panic_abort,std --release --timings
 ```
-
-
diff --git a/client/js-bindgen-test/src/lib.rs b/client/js-bindgen-test/src/lib.rs
index 3d8e4a1f..34620c8b 100644
--- a/client/js-bindgen-test/src/lib.rs
+++ b/client/js-bindgen-test/src/lib.rs
@@ -1,6 +1,8 @@
+use std::cell::RefCell;
+use std::panic::PanicHookInfo;
+
 pub use js_bindgen_test_macro::test;
 use js_sys::JsString;
-use std::{cell::RefCell, panic::PanicHookInfo};
 
 struct LastPanic {
 	payload: Option,
diff --git a/client/web-sys/src/lib.rs b/client/web-sys/src/lib.rs
index 5ef62182..ba76b5e6 100644
--- a/client/web-sys/src/lib.rs
+++ b/client/web-sys/src/lib.rs
@@ -20,10 +20,11 @@ pub mod console {
 
 #[cfg(test)]
 mod tests {
-	use super::console;
 	use js_bindgen_test::test;
 	use js_sys::JsString;
 
+	use super::console;
+
 	#[test]
 	fn test_console_log() {
 		let value = JsString::from_str("hello world");
diff --git a/host/Cargo.toml b/host/Cargo.toml
index f5efeed0..b9501eb2 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -34,10 +34,10 @@ serde = { version = "1", default-features = false }
 serde_json = { version = "1", default-features = false, features = ["alloc"] }
 similar-asserts = { version = "1", default-features = false }
 syn = { version = "2", default-features = false, features = ["parsing", "printing"] }
+tempfile = { version = "3", default-features = false }
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
-tempfile = { version = "3", default-features = false}
 
 [patch.crates-io]
 # Detect unsupported platforms at run-time: https://github.com/RazrFalcon/memmap2-rs/pull/161.
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index 6361a9e6..609c688f 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -5,11 +5,11 @@ rust-version = { workspace = true }
 
 [dependencies]
 anyhow = { workspace = true }
+js-bindgen-ld-shared = { workspace = true }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
-wasmparser = { workspace = true }
-js-bindgen-ld-shared = { workspace = true }
 tempfile = { workspace = true }
+wasmparser = { workspace = true }
 
 [lints]
 workspace = true
diff --git a/host/js-bindgen-runner/js/browser-runner.mjs b/host/js-bindgen-runner/js/browser-runner.mjs
index 75ecd804..86ab9898 100644
--- a/host/js-bindgen-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-runner/js/browser-runner.mjs
@@ -1,48 +1,48 @@
-import { createTextFormatter } from "./shared.mjs";
-import { runTests } from "./runner-core.mjs";
-import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
+import { createTextFormatter } from "./shared.mjs"
+import { runTests } from "./runner-core.mjs"
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
 
 export async function runBrowser({ nocapture, filtered, worker }) {
-	const baseLog = consoleHook.base.log;
-	const baseError = consoleHook.base.error;
-	const baseWarn = consoleHook.base.warn;
-	const baseInfo = consoleHook.base.info;
-	const baseDebug = consoleHook.base.debug;
+	const baseLog = consoleHook.base.log
+	const baseError = consoleHook.base.error
+	const baseWarn = consoleHook.base.warn
+	const baseInfo = consoleHook.base.info
+	const baseDebug = consoleHook.base.debug
 
 	let result = worker
 		? await runInWorker({
-			nocapture,
-			filtered,
-			worker,
-			baseLog,
-			baseError,
-			baseWarn,
-			baseInfo,
-			baseDebug,
-		})
-		: await runInWindow({ nocapture, filtered, consoleHook });
+				nocapture,
+				filtered,
+				worker,
+				baseLog,
+				baseError,
+				baseWarn,
+				baseInfo,
+				baseDebug,
+			})
+		: await runInWindow({ nocapture, filtered, consoleHook })
 
 	if (typeof window !== "undefined") {
-		window.__jbtestDone = true;
-		window.__jbtestFailed = result.failed;
+		window.__jbtestDone = true
+		window.__jbtestFailed = result.failed
 	}
 
-	return result;
+	return result
 }
 
 async function runInWindow({ nocapture, filtered, consoleHook }) {
-	const tests = await (await fetch("/tests.json")).json();
-	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
-	const { importObject } = await import("/import.js");
+	const tests = await (await fetch("/tests.json")).json()
+	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
+	const { importObject } = await import("/import.js")
 
-	const lines = [];
+	const lines = []
 	const formatter = createTextFormatter({
 		nocapture,
 		write(line) {
-			lines.push(line);
-			appendOutput(line);
+			lines.push(line)
+			appendOutput(line)
 		},
-	});
+	})
 
 	const testInputs = tests.map(test => ({
 		...test,
@@ -53,9 +53,9 @@ async function runInWindow({ nocapture, filtered, consoleHook }) {
 				emit: event => formatter.onEvent(event),
 				consoleHook,
 				forwardToConsole: true,
-			});
+			})
 		},
-	}));
+	}))
 
 	const result = await runTests({
 		wasmBytes,
@@ -63,9 +63,9 @@ async function runInWindow({ nocapture, filtered, consoleHook }) {
 		tests: testInputs,
 		filtered,
 		emit: event => formatter.onEvent(event),
-	});
+	})
 
-	return { lines, failed: result.failed };
+	return { lines, failed: result.failed }
 }
 
 async function runInWorker({
@@ -78,172 +78,169 @@ async function runInWorker({
 	baseInfo,
 	baseDebug,
 }) {
-	const lines = [];
+	const lines = []
 
 	function handleMessage(event) {
-		const data = event.data || {};
+		const data = event.data || {}
 		if (data.type === "user-output") {
 			switch (data.level) {
 				case "error":
-					baseError(data.line);
-					break;
+					baseError(data.line)
+					break
 				case "warn":
-					baseWarn(data.line);
-					break;
+					baseWarn(data.line)
+					break
 				case "info":
-					baseInfo(data.line);
-					break;
+					baseInfo(data.line)
+					break
 				case "debug":
-					baseDebug(data.line);
-					break;
+					baseDebug(data.line)
+					break
 				default:
-					baseLog(data.line);
+					baseLog(data.line)
 			}
-			return null;
+			return null
 		}
 		if (data.type === "line") {
-			lines.push(data.line);
-			appendOutput(data.line);
-			return null;
+			lines.push(data.line)
+			appendOutput(data.line)
+			return null
 		}
 		if (data.type === "report") {
-			return { lines: data.lines || lines, failed: data.failed || 0 };
+			return { lines: data.lines || lines, failed: data.failed || 0 }
 		}
-		return null;
+		return null
 	}
 
 	const workerRunners = {
 		dedicated: runDedicatedWorker,
 		shared: runSharedWorker,
 		service: runServiceWorker,
-	};
-	const runWorker = workerRunners[worker];
+	}
+	const runWorker = workerRunners[worker]
 	if (!runWorker) {
-		throw new Error(`unsupported worker worker: ${worker}`);
+		throw new Error(`unsupported worker worker: ${worker}`)
 	}
-	const reportPromise = runWorker({ filtered, nocapture, handleMessage });
+	const reportPromise = runWorker({ filtered, nocapture, handleMessage })
 
-	const report = await reportPromise;
-	return report;
+	const report = await reportPromise
+	return report
 }
 
 function runDedicatedWorker({ filtered, nocapture, handleMessage }) {
 	return new Promise((resolve, reject) => {
-		let worker;
+		let worker
 		try {
-			worker = new Worker("/worker-runner.mjs", { type: "module" });
+			worker = new Worker("/worker-runner.mjs", { type: "module" })
 		} catch (error) {
-			reject(error);
-			return;
+			reject(error)
+			return
 		}
 		const timeout = setTimeout(() => {
-			reject(new Error("dedicated worker timed out"));
-			worker.terminate();
-		}, 30000);
+			reject(new Error("dedicated worker timed out"))
+			worker.terminate()
+		}, 30000)
 		worker.onmessage = event => {
-			const report = handleMessage(event);
+			const report = handleMessage(event)
 			if (report) {
-				clearTimeout(timeout);
-				resolve(report);
-				worker.terminate();
+				clearTimeout(timeout)
+				resolve(report)
+				worker.terminate()
 			}
-		};
-		worker.onerror = err => reject(err);
-		worker.postMessage({ filtered, nocapture });
-	});
+		}
+		worker.onerror = err => reject(err)
+		worker.postMessage({ filtered, nocapture })
+	})
 }
 
 function runSharedWorker({ filtered, nocapture, handleMessage }) {
 	return new Promise((resolve, reject) => {
-		let shared;
+		let shared
 		try {
-			shared = new SharedWorker("/worker-runner.mjs", { type: "module" });
+			shared = new SharedWorker("/worker-runner.mjs", { type: "module" })
 		} catch (error) {
-			reject(error);
-			return;
+			reject(error)
+			return
 		}
-		const port = shared.port;
+		const port = shared.port
 		const timeout = setTimeout(() => {
-			reject(new Error("shared worker timed out"));
-			port.close();
-		}, 30000);
+			reject(new Error("shared worker timed out"))
+			port.close()
+		}, 30000)
 		port.onmessage = event => {
-			const report = handleMessage(event);
+			const report = handleMessage(event)
 			if (report) {
-				clearTimeout(timeout);
-				resolve(report);
-				port.close();
+				clearTimeout(timeout)
+				resolve(report)
+				port.close()
 			}
-		};
-		port.onmessageerror = err => reject(err);
-		port.start();
-		port.postMessage({ filtered, nocapture });
-	});
+		}
+		port.onmessageerror = err => reject(err)
+		port.start()
+		port.postMessage({ filtered, nocapture })
+	})
 }
 
 async function runServiceWorker({ filtered, nocapture, handleMessage }) {
 	if (!navigator.serviceWorker) {
-		throw new Error("service workers are not supported");
+		throw new Error("service workers are not supported")
 	}
 	const registration = await navigator.serviceWorker.register("/service-worker.mjs", {
 		type: "module",
-	});
-	await navigator.serviceWorker.ready;
+	})
+	await navigator.serviceWorker.ready
 
 	if (!navigator.serviceWorker.controller) {
 		if (!sessionStorage.getItem("jbtest-sw-reload")) {
-			sessionStorage.setItem("jbtest-sw-reload", "1");
-			location.reload();
-			return new Promise(() => { });
+			sessionStorage.setItem("jbtest-sw-reload", "1")
+			location.reload()
+			return new Promise(() => {})
 		}
-		throw new Error("service worker not controlling the page");
+		throw new Error("service worker not controlling the page")
 	}
 
 	return new Promise((resolve, reject) => {
-		const channel = new MessageChannel();
+		const channel = new MessageChannel()
 		const timeout = setTimeout(() => {
-			reject(new Error("service worker timed out"));
-			channel.port1.close();
-			channel.port2.close();
-		}, 30000);
+			reject(new Error("service worker timed out"))
+			channel.port1.close()
+			channel.port2.close()
+		}, 30000)
 		channel.port1.onmessage = event => {
-			const report = handleMessage(event);
+			const report = handleMessage(event)
 			if (report) {
-				clearTimeout(timeout);
-				resolve(report);
-				channel.port1.close();
-				channel.port2.close();
+				clearTimeout(timeout)
+				resolve(report)
+				channel.port1.close()
+				channel.port2.close()
 			}
-		};
-		channel.port1.onmessageerror = err => reject(err);
-		navigator.serviceWorker.controller.postMessage(
-			{ filtered, nocapture },
-			[channel.port2]
-		);
-	});
+		}
+		channel.port1.onmessageerror = err => reject(err)
+		navigator.serviceWorker.controller.postMessage({ filtered, nocapture }, [channel.port2])
+	})
 }
 
 function appendOutput(line) {
-	const output = ensureOutput();
+	const output = ensureOutput()
 	if (output.textContent.length > 0) {
-		output.textContent += "\n";
+		output.textContent += "\n"
 	}
-	output.textContent += stripAnsi(line);
+	output.textContent += stripAnsi(line)
 }
 
 function stripAnsi(line) {
-	return line.replace(/\x1b\[[0-9;]*m/g, "");
+	return line.replace(/\x1b\[[0-9;]*m/g, "")
 }
 
 function ensureOutput() {
 	if (typeof document === "undefined") {
-		return { textContent: "" };
+		return { textContent: "" }
 	}
-	let output = document.getElementById("output");
+	let output = document.getElementById("output")
 	if (!output) {
-		output = document.createElement("pre");
-		output.id = "output";
-		document.body.append(output);
+		output = document.createElement("pre")
+		output.id = "output"
+		document.body.append(output)
 	}
-	return output;
+	return output
 }
diff --git a/host/js-bindgen-runner/js/console-hook.mjs b/host/js-bindgen-runner/js/console-hook.mjs
index d1d6549f..58b09d4e 100644
--- a/host/js-bindgen-runner/js/console-hook.mjs
+++ b/host/js-bindgen-runner/js/console-hook.mjs
@@ -1,7 +1,7 @@
 function installConsoleHook() {
-	const existing = globalThis.__jbtestConsoleHook;
+	const existing = globalThis.__jbtestConsoleHook
 	if (existing) {
-		return existing;
+		return existing
 	}
 	const base = {
 		log: console.log.bind(console),
@@ -9,64 +9,61 @@ function installConsoleHook() {
 		warn: console.warn.bind(console),
 		info: console.info.bind(console),
 		debug: console.debug.bind(console),
-	};
+	}
 
-	let hook = null;
-	let forwardToConsole = false;
+	let hook = null
+	let forwardToConsole = false
 	function make(level) {
 		return (...args) => {
 			if (hook) {
-				hook(level, args);
+				hook(level, args)
 				if (forwardToConsole) {
-					base[level](...args);
+					base[level](...args)
 				}
 			} else {
-				base[level](...args);
+				base[level](...args)
 			}
-		};
+		}
 	}
-	console.log = make("log");
-	console.error = make("error");
-	console.warn = make("warn");
-	console.info = make("info");
-	console.debug = make("debug");
+	console.log = make("log")
+	console.error = make("error")
+	console.warn = make("warn")
+	console.info = make("info")
+	console.debug = make("debug")
 
 	const h = {
 		base,
 		setHook(fn, forward) {
-			hook = fn;
-			forwardToConsole = forward;
+			hook = fn
+			forwardToConsole = forward
 		},
 		clearHook() {
-			hook = null;
-			forwardToConsole = false;
+			hook = null
+			forwardToConsole = false
 		},
-	};
-	globalThis.__jbtestConsoleHook = h;
-	return h;
+	}
+	globalThis.__jbtestConsoleHook = h
+	return h
 }
 
 export function withConsoleCapture({ name, run, emit, consoleHook, forwardToConsole }) {
-	consoleHook.setHook(
-		(level, args) => {
-			const line = args.join(" ");
-			const stream = level === "error" || level === "warn" ? "stderr" : "stdout";
-			emit({ type: "test-output", name, line, stream, level });
-		},
-		forwardToConsole
-	);
+	consoleHook.setHook((level, args) => {
+		const line = args.join(" ")
+		const stream = level === "error" || level === "warn" ? "stderr" : "stdout"
+		emit({ type: "test-output", name, line, stream, level })
+	}, forwardToConsole)
 
 	try {
-		run();
-		return { ok: true };
+		run()
+		return { ok: true }
 	} catch (error) {
 		return {
 			ok: false,
-			stack: error.stack
-		};
+			stack: error.stack,
+		}
 	} finally {
-		consoleHook.clearHook();
+		consoleHook.clearHook()
 	}
 }
 
-export default installConsoleHook();
+export default installConsoleHook()
diff --git a/host/js-bindgen-runner/js/index.html b/host/js-bindgen-runner/js/index.html
index e55516ed..e6cdfb28 100644
--- a/host/js-bindgen-runner/js/index.html
+++ b/host/js-bindgen-runner/js/index.html
@@ -1,18 +1,17 @@
 
-
+
 js-bindgen test
 

 
-
diff --git a/host/js-bindgen-runner/js/node-runner.mjs b/host/js-bindgen-runner/js/node-runner.mjs
index c268192f..e9f7a4a8 100644
--- a/host/js-bindgen-runner/js/node-runner.mjs
+++ b/host/js-bindgen-runner/js/node-runner.mjs
@@ -1,40 +1,40 @@
-import fs from "node:fs/promises";
-import { pathToFileURL } from "node:url";
-import { createTextFormatter } from "./shared.mjs";
-import { runTests } from "./runner-core.mjs";
-import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
-
-const wasmPath = process.env.JS_BINDGEN_WASM;
-const importsPath = process.env.JS_BINDGEN_IMPORTS;
-const testsPath = process.env.JS_BINDGEN_TESTS_PATH;
-const nocapture = process.env.JS_BINDGEN_NOCAPTURE === "1";
-const filtered = Number(process.env.JS_BINDGEN_FILTERED || "0");
+import fs from "node:fs/promises"
+import { pathToFileURL } from "node:url"
+import { createTextFormatter } from "./shared.mjs"
+import { runTests } from "./runner-core.mjs"
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
+
+const wasmPath = process.env.JS_BINDGEN_WASM
+const importsPath = process.env.JS_BINDGEN_IMPORTS
+const testsPath = process.env.JS_BINDGEN_TESTS_PATH
+const nocapture = process.env.JS_BINDGEN_NOCAPTURE === "1"
+const filtered = Number(process.env.JS_BINDGEN_FILTERED || "0")
 
 if (!wasmPath || !importsPath || !testsPath) {
-	console.error("missing test runner environment");
-	process.exit(1);
+	console.error("missing test runner environment")
+	process.exit(1)
 }
 
-const { importObject } = await import(pathToFileURL(importsPath));
-const wasmBytes = await fs.readFile(wasmPath);
-const testsText = await fs.readFile(testsPath, "utf8");
-const tests = JSON.parse(testsText);
+const { importObject } = await import(pathToFileURL(importsPath))
+const wasmBytes = await fs.readFile(wasmPath)
+const testsText = await fs.readFile(testsPath, "utf8")
+const tests = JSON.parse(testsText)
 
-const baseLog = consoleHook.base.log;
-const baseError = consoleHook.base.error;
+const baseLog = consoleHook.base.log
+const baseError = consoleHook.base.error
 const formatter = createTextFormatter({
 	nocapture,
 	write(line, stream) {
 		if (stream === "stderr") {
-			baseError(line);
+			baseError(line)
 		} else {
-			baseLog(line);
+			baseLog(line)
 		}
 	},
-});
+})
 
 function emit(event) {
-	formatter.onEvent(event);
+	formatter.onEvent(event)
 }
 
 const testInputs = tests.map(test => ({
@@ -46,9 +46,9 @@ const testInputs = tests.map(test => ({
 			emit: event => formatter.onEvent(event),
 			consoleHook,
 			forwardToConsole: false,
-		});
+		})
 	},
-}));
+}))
 
 const result = await runTests({
 	wasmBytes,
@@ -56,6 +56,6 @@ const result = await runTests({
 	tests: testInputs,
 	filtered,
 	emit,
-});
+})
 
-process.exit(result.failed === 0 ? 0 : 1);
+process.exit(result.failed === 0 ? 0 : 1)
diff --git a/host/js-bindgen-runner/js/playwright-runner.mjs b/host/js-bindgen-runner/js/playwright-runner.mjs
index a6010bc6..97c85a97 100644
--- a/host/js-bindgen-runner/js/playwright-runner.mjs
+++ b/host/js-bindgen-runner/js/playwright-runner.mjs
@@ -1,25 +1,25 @@
-import { chromium, firefox, webkit } from "playwright";
+import { chromium, firefox, webkit } from "playwright"
 
-const url = process.env.JBG_TEST_URL;
+const url = process.env.JBG_TEST_URL
 if (!url) {
-	throw new Error("missing JBG_TEST_URL");
+	throw new Error("missing JBG_TEST_URL")
 }
 
-const browserName = (process.env.JBG_TEST_DRIVER || "chrome").toLowerCase();
+const browserName = (process.env.JBG_TEST_DRIVER || "chrome").toLowerCase()
 const browserType = {
 	chrome: chromium,
 	gecko: firefox,
-	webkit
-}[browserName];
+	webkit,
+}[browserName]
 
 if (!browserType) {
-	throw new Error(`unsupported browser: ${browserName}`);
+	throw new Error(`unsupported browser: ${browserName}`)
 }
 
 const browser = await browserType.launch({
 	headless: true,
-});
-const page = await browser.newPage();
-await page.goto(url);
-await page.waitForFunction("window.__jbtestDone === true");
-await browser.close();
+})
+const page = await browser.newPage()
+await page.goto(url)
+await page.waitForFunction("window.__jbtestDone === true")
+await browser.close()
diff --git a/host/js-bindgen-runner/js/runner-core.mjs b/host/js-bindgen-runner/js/runner-core.mjs
index 00400d13..1c3c36be 100644
--- a/host/js-bindgen-runner/js/runner-core.mjs
+++ b/host/js-bindgen-runner/js/runner-core.mjs
@@ -1,35 +1,35 @@
 export async function runTests({ wasmBytes, importObject, tests, filtered, emit }) {
-	const startTime = Date.now();
-	emit({ type: "run-start", total: tests.length, filtered });
+	const startTime = Date.now()
+	emit({ type: "run-start", total: tests.length, filtered })
 
-	const { instance } = await WebAssembly.instantiate(wasmBytes, importObject);
-	const panicPayload = instance.exports.last_panic_payload;
-	const panicMessage = instance.exports.last_panic_message;
-	const externrefTable = resolveExternrefTable(importObject);
+	const { instance } = await WebAssembly.instantiate(wasmBytes, importObject)
+	const panicPayload = instance.exports.last_panic_payload
+	const panicMessage = instance.exports.last_panic_message
+	const externrefTable = resolveExternrefTable(importObject)
 
-	let failed = 0;
-	let ignored = 0;
+	let failed = 0
+	let ignored = 0
 
 	for (const test of tests) {
 		if (test.ignore) {
-			ignored += 1;
-			emit({ type: "test-ignored", name: test.name, reason: test.ignore_reason });
-			continue;
+			ignored += 1
+			emit({ type: "test-ignored", name: test.name, reason: test.ignore_reason })
+			continue
 		}
 
-		const testFn = instance.exports[test.name];
+		const testFn = instance.exports[test.name]
 		if (typeof testFn !== "function") {
 			emit({
 				type: "test-failed",
 				name: test.name,
 				error: `missing export: ${test.name}`,
-			});
-			failed += 1;
-			continue;
+			})
+			failed += 1
+			continue
 		}
 
-		const result = test.run(testFn);
-		const shouldPanic = test.should_panic;
+		const result = test.run(testFn)
+		const shouldPanic = test.should_panic
 		if (shouldPanic) {
 			if (result.ok) {
 				emit({
@@ -37,43 +37,45 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 					name: test.name,
 					error: "test did not panic as expected",
 					should_panic: true,
-				});
-				failed += 1;
-				continue;
+				})
+				failed += 1
+				continue
 			}
 
-			const expectedText = test.should_panic_reason;
-			const payload = coercePanicMessage(panicPayload(), externrefTable);
-			const message = coercePanicMessage(panicMessage(), externrefTable);
+			const expectedText = test.should_panic_reason
+			const payload = coercePanicMessage(panicPayload(), externrefTable)
+			const message = coercePanicMessage(panicMessage(), externrefTable)
 
 			if (expectedText && !payload.includes(expectedText)) {
-				const displayPayload = escapeForDisplay(payload);
-				const displayExpected = escapeForDisplay(expectedText);
+				const displayPayload = escapeForDisplay(payload)
+				const displayExpected = escapeForDisplay(expectedText)
 				emit({
 					type: "test-failed",
 					name: test.name,
 					error:
-						message + "\n" +
-						result.stack + "\n" +
+						message +
+						"\n" +
+						result.stack +
+						"\n" +
 						"note: panic did not contain expected string\n" +
 						`      panic message: "${displayPayload}"\n` +
 						` expected substring: "${displayExpected}"`,
 					should_panic: true,
-				});
-				failed += 1;
-				continue;
+				})
+				failed += 1
+				continue
 			}
 
-			emit({ type: "test-ok", name: test.name, should_panic: true });
-			continue;
+			emit({ type: "test-ok", name: test.name, should_panic: true })
+			continue
 		}
 
 		if (result.ok) {
-			emit({ type: "test-ok", name: test.name, should_panic: false });
+			emit({ type: "test-ok", name: test.name, should_panic: false })
 		} else {
-			const message = coercePanicMessage(panicMessage(), externrefTable);
-			emit({ type: "test-failed", name: test.name, error: message + "\n" + result.stack });
-			failed += 1;
+			const message = coercePanicMessage(panicMessage(), externrefTable)
+			emit({ type: "test-failed", name: test.name, error: message + "\n" + result.stack })
+			failed += 1
 		}
 	}
 
@@ -85,24 +87,24 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 		ignored,
 		filtered,
 		duration_ms: Date.now() - startTime,
-	});
+	})
 
-	return { failed };
+	return { failed }
 }
 
 function resolveExternrefTable(importObject) {
-	return importObject["js_sys"]["externref.table"];
+	return importObject["js_sys"]["externref.table"]
 }
 
 function coercePanicMessage(value, externrefTable) {
-	const ref = externrefTable.get(value);
-	externrefTable.set(value, null);
-	return String(ref);
+	const ref = externrefTable.get(value)
+	externrefTable.set(value, null)
+	return String(ref)
 }
 
 function escapeForDisplay(value) {
 	return String(value || "")
 		.replace(/\r/g, "\\r")
 		.replace(/\n/g, "\\n")
-		.replace(/\t/g, "\\t");
+		.replace(/\t/g, "\\t")
 }
diff --git a/host/js-bindgen-runner/js/service-worker.mjs b/host/js-bindgen-runner/js/service-worker.mjs
index 72596acf..7b0b56b9 100644
--- a/host/js-bindgen-runner/js/service-worker.mjs
+++ b/host/js-bindgen-runner/js/service-worker.mjs
@@ -1,29 +1,29 @@
-import { createTextFormatter } from "./shared.mjs";
-import { runTests } from "./runner-core.mjs";
-import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
-import { importObject } from "./import.js";
+import { createTextFormatter } from "./shared.mjs"
+import { runTests } from "./runner-core.mjs"
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
+import { importObject } from "./import.js"
 
 self.addEventListener("message", event => {
-	const port = event.ports && event.ports[0];
+	const port = event.ports && event.ports[0]
 	if (!port) {
-		return;
+		return
 	}
 	execute(port, event.data).catch(error => {
-		port.postMessage({ type: "report", lines: [String(error)], failed: 1 });
-	});
-});
+		port.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+	})
+})
 
 async function execute(port, { nocapture, filtered }) {
-	const tests = await (await fetch("/tests.json")).json();
-	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
-	const lines = [];
+	const tests = await (await fetch("/tests.json")).json()
+	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
+	const lines = []
 	const formatter = createTextFormatter({
 		nocapture,
 		write(line) {
-			lines.push(line);
-			port.postMessage({ type: "line", line });
+			lines.push(line)
+			port.postMessage({ type: "line", line })
 		},
-	});
+	})
 
 	function emit(event) {
 		if (event.type === "test-output") {
@@ -32,9 +32,9 @@ async function execute(port, { nocapture, filtered }) {
 				line: event.line,
 				stream: event.stream,
 				level: event.level || (event.stream === "stderr" ? "error" : "log"),
-			});
+			})
 		}
-		formatter.onEvent(event);
+		formatter.onEvent(event)
 	}
 
 	const testInputs = tests.map(test => ({
@@ -46,9 +46,9 @@ async function execute(port, { nocapture, filtered }) {
 				emit,
 				consoleHook,
 				forwardToConsole: false,
-			});
+			})
 		},
-	}));
+	}))
 
 	const result = await runTests({
 		wasmBytes,
@@ -56,7 +56,7 @@ async function execute(port, { nocapture, filtered }) {
 		tests: testInputs,
 		filtered,
 		emit,
-	});
+	})
 
-	port.postMessage({ type: "report", lines, failed: result.failed });
+	port.postMessage({ type: "report", lines, failed: result.failed })
 }
diff --git a/host/js-bindgen-runner/js/shared.mjs b/host/js-bindgen-runner/js/shared.mjs
index 408a6fda..b9323cce 100644
--- a/host/js-bindgen-runner/js/shared.mjs
+++ b/host/js-bindgen-runner/js/shared.mjs
@@ -1,120 +1,111 @@
 export function createTextFormatter({ nocapture, write }) {
-	const buffered = new Map();
-	const failed = [];
-	const failureReports = [];
-	const green = "\u001b[32m";
-	const red = "\u001b[31m";
-	const yellow = "\u001b[33m";
-	const reset = "\u001b[0m";
+	const buffered = new Map()
+	const failed = []
+	const failureReports = []
+	const green = "\u001b[32m"
+	const red = "\u001b[31m"
+	const yellow = "\u001b[33m"
+	const reset = "\u001b[0m"
 
 	function buffer(name, line, stream) {
 		if (!buffered.has(name)) {
-			buffered.set(name, []);
+			buffered.set(name, [])
 		}
-		buffered.get(name).push({ line, stream });
+		buffered.get(name).push({ line, stream })
 	}
 
 	function takeBuffer(name) {
-		const entries = buffered.get(name);
+		const entries = buffered.get(name)
 		if (!entries || entries.length === 0) {
-			return [];
+			return []
 		}
-		buffered.delete(name);
-		return entries;
+		buffered.delete(name)
+		return entries
 	}
 
 	return {
 		onEvent(event) {
 			switch (event.type) {
 				case "run-start":
-					write("", "stdout");
-					write(`running ${event.total} tests`, "stdout");
-					break;
+					write("", "stdout")
+					write(`running ${event.total} tests`, "stdout")
+					break
 				case "test-output":
 					if (nocapture) {
-						write(event.line, event.stream);
+						write(event.line, event.stream)
 					}
 					if (!nocapture) {
-						buffer(event.name, event.line, event.stream);
+						buffer(event.name, event.line, event.stream)
 					}
-					break;
+					break
 				case "test-ok":
-					takeBuffer(event.name);
+					takeBuffer(event.name)
 					if (event.should_panic) {
-						write(
-							`test ${event.name} - should panic ... ${green}ok${reset}`,
-							"stdout"
-						);
+						write(`test ${event.name} - should panic ... ${green}ok${reset}`, "stdout")
 					} else {
-						write(`test ${event.name} ... ${green}ok${reset}`, "stdout");
+						write(`test ${event.name} ... ${green}ok${reset}`, "stdout")
 					}
-					break;
+					break
 				case "test-ignored":
-					takeBuffer(event.name);
+					takeBuffer(event.name)
 					if (event.reason) {
-						write(
-							`test ${event.name} ... ${yellow}ignored, ${event.reason}${reset}`,
-							"stdout"
-						);
+						write(`test ${event.name} ... ${yellow}ignored, ${event.reason}${reset}`, "stdout")
 					} else {
-						write(`test ${event.name} ... ${yellow}ignored${reset}`, "stdout");
+						write(`test ${event.name} ... ${yellow}ignored${reset}`, "stdout")
 					}
-					break;
+					break
 				case "test-failed":
-					failed.push(event.name);
+					failed.push(event.name)
 					if (event.should_panic) {
-						write(
-							`test ${event.name} - should panic ... ${red}FAILED${reset}`,
-							"stdout"
-						);
+						write(`test ${event.name} - should panic ... ${red}FAILED${reset}`, "stdout")
 					} else {
-						write(`test ${event.name} ... ${red}FAILED${reset}`, "stdout");
+						write(`test ${event.name} ... ${red}FAILED${reset}`, "stdout")
 					}
 					failureReports.push({
 						name: event.name,
 						entries: takeBuffer(event.name),
 						error: event.error,
-					});
-					break;
+					})
+					break
 				case "run-end":
-					write("", "stdout");
+					write("", "stdout")
 					if (failed.length > 0) {
-						write("failures:", "stdout");
-						write("", "stdout");
+						write("failures:", "stdout")
+						write("", "stdout")
 						for (const report of failureReports) {
-							write(`---- ${report.name} stdout ----`, "stdout");
+							write(`---- ${report.name} stdout ----`, "stdout")
 							for (const entry of report.entries) {
-								write(entry.line, entry.stream);
+								write(entry.line, entry.stream)
 							}
 							if (report.error) {
-								write("", "stdout");
-								write(report.error, "stdout");
+								write("", "stdout")
+								write(report.error, "stdout")
 							}
-							write("", "stdout");
+							write("", "stdout")
 						}
 					}
 					const status =
 						event.status === "ok"
 							? `${green}${event.status}${reset}`
-							: `${red}${event.status}${reset}`;
-					const durationMs = typeof event.duration_ms === "number" ? event.duration_ms : 0;
-					const durationSeconds = (durationMs / 1000).toFixed(2);
+							: `${red}${event.status}${reset}`
+					const durationMs = typeof event.duration_ms === "number" ? event.duration_ms : 0
+					const durationSeconds = (durationMs / 1000).toFixed(2)
 					if (failed.length > 0) {
-						write("failures:", "stdout");
+						write("failures:", "stdout")
 						for (const name of failed) {
-							write(`    ${name}`, "stdout");
+							write(`    ${name}`, "stdout")
 						}
-						write("", "stdout");
+						write("", "stdout")
 					}
 					write(
 						`test result: ${status}. ${event.passed} passed; ${event.failed} failed; ${event.ignored} ignored; 0 measured; ${event.filtered} filtered out; finished in ${durationSeconds}s`,
 						"stdout"
-					);
-					write("", "stdout");
-					break;
+					)
+					write("", "stdout")
+					break
 				default:
-					break;
+					break
 			}
 		},
-	};
+	}
 }
diff --git a/host/js-bindgen-runner/js/worker-runner.mjs b/host/js-bindgen-runner/js/worker-runner.mjs
index 5504cb01..f83a4919 100644
--- a/host/js-bindgen-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-runner/js/worker-runner.mjs
@@ -1,20 +1,20 @@
-import { createTextFormatter } from "./shared.mjs";
-import { runTests } from "./runner-core.mjs";
-import consoleHook, { withConsoleCapture } from "./console-hook.mjs";
+import { createTextFormatter } from "./shared.mjs"
+import { runTests } from "./runner-core.mjs"
+import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
 
 async function execute(port, { nocapture, filtered }) {
-	const tests = await (await fetch("/tests.json")).json();
-	const wasmBytes = await (await fetch("/wasm")).arrayBuffer();
-	const { importObject } = await import("/import.js");
+	const tests = await (await fetch("/tests.json")).json()
+	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
+	const { importObject } = await import("/import.js")
 
-	const lines = [];
+	const lines = []
 	const formatter = createTextFormatter({
 		nocapture,
 		write(line) {
-			lines.push(line);
-			port.postMessage({ type: "line", line });
+			lines.push(line)
+			port.postMessage({ type: "line", line })
 		},
-	});
+	})
 
 	function emit(event) {
 		if (event.type === "test-output") {
@@ -23,9 +23,9 @@ async function execute(port, { nocapture, filtered }) {
 				line: event.line,
 				stream: event.stream,
 				level: event.level || (event.stream === "stderr" ? "error" : "log"),
-			});
+			})
 		}
-		formatter.onEvent(event);
+		formatter.onEvent(event)
 	}
 
 	const testInputs = tests.map(test => ({
@@ -37,9 +37,9 @@ async function execute(port, { nocapture, filtered }) {
 				emit,
 				consoleHook,
 				forwardToConsole: false,
-			});
+			})
 		},
-	}));
+	}))
 
 	const result = await runTests({
 		wasmBytes,
@@ -47,25 +47,25 @@ async function execute(port, { nocapture, filtered }) {
 		tests: testInputs,
 		filtered,
 		emit,
-	});
+	})
 
-	port.postMessage({ type: "report", lines, failed: result.failed });
+	port.postMessage({ type: "report", lines, failed: result.failed })
 }
 
 if (typeof self.onconnect !== "undefined") {
 	self.onconnect = event => {
-		const port = event.ports[0];
+		const port = event.ports[0]
 		port.onmessage = msg => {
 			execute(port, msg.data).catch(error => {
-				port.postMessage({ type: "report", lines: [String(error)], failed: 1 });
-			});
-		};
-		port.start();
-	};
+				port.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+			})
+		}
+		port.start()
+	}
 } else {
 	self.onmessage = event => {
 		execute(self, event.data).catch(error => {
-			self.postMessage({ type: "report", lines: [String(error)], failed: 1 });
-		});
-	};
+			self.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+		})
+	}
 }
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 0d4b54a3..a6fd9184 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -1,15 +1,11 @@
-use std::env;
-use std::fs;
 use std::io::{ErrorKind, Read, Write};
 use std::net::{TcpListener, TcpStream};
 use std::path::{Path, PathBuf};
 use std::process::Command;
-use std::sync::{
-	Arc, Condvar, Mutex,
-	atomic::{AtomicBool, Ordering},
-};
-use std::thread;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Condvar, Mutex};
 use std::time::Duration;
+use std::{env, fs, thread};
 
 use anyhow::{Context, Result, bail};
 use js_bindgen_ld_shared::ReadFile;
@@ -74,7 +70,8 @@ fn main() -> Result<()> {
 		println!("running 0 tests");
 		println!();
 		println!(
-			"test result: {GREEN}ok{RESET}. 0 passed; 0 failed; 0 ignored; 0 measured; {filtered_count} filtered out; finished in 0.00s"
+			"test result: {GREEN}ok{RESET}. 0 passed; 0 failed; 0 ignored; 0 measured; \
+			 {filtered_count} filtered out; finished in 0.00s"
 		);
 		println!();
 		return Ok(());
@@ -638,7 +635,11 @@ fn write_response(
 	};
 	write!(
 		stream,
-		"HTTP/1.1 {status} {status_text}\r\nContent-Length: {}\r\nContent-Type: {content_type}\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, POST, OPTIONS\r\nAccess-Control-Allow-Headers: Content-Type\r\nCross-Origin-Opener-Policy: same-origin\r\nCross-Origin-Embedder-Policy: require-corp\r\n\r\n",
+		"HTTP/1.1 {status} {status_text}\r\nContent-Length: {}\r\nContent-Type: \
+		 {content_type}\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, \
+		 POST, OPTIONS\r\nAccess-Control-Allow-Headers: \
+		 Content-Type\r\nCross-Origin-Opener-Policy: same-origin\r\nCross-Origin-Embedder-Policy: \
+		 require-corp\r\n\r\n",
 		body.len()
 	)?;
 	stream.write_all(body)?;

From 6041a5a9dba11d93f30a6b947fd5cbab5665bd39 Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Fri, 30 Jan 2026 11:31:37 +0100
Subject: [PATCH 32/73] Slight Improvements

---
 .github/workflows/test.yaml               |   2 +-
 TODO.md                                   |   4 +
 host/Cargo.toml                           |   2 +
 host/js-bindgen-runner/Cargo.toml         |   4 +-
 host/js-bindgen-runner/js/runner-core.mjs |   8 +-
 host/js-bindgen-runner/src/main.rs        | 106 +++++++++--------
 host/js-bindgen-test-macro/src/lib.rs     |  27 ++---
 host/js-bindgen/src/lib.rs                |  11 +-
 host/js-bindgen/src/tests/test.rs         |   9 +-
 host/js-sys-macro/Cargo.toml              |   3 +
 host/ld-shared/Cargo.toml                 |   1 +
 host/ld-shared/src/lib.rs                 |  42 +------
 host/ld/Cargo.toml                        |   1 +
 host/ld/src/main.rs                       |   3 +-
 host/macro-shared/Cargo.toml              |   3 +
 host/macro-shared/src/lib.rs              | 132 +++++++---------------
 host/shared/Cargo.toml                    |  11 ++
 host/shared/LICENSE-APACHE                |   1 +
 host/shared/LICENSE-MIT                   |   1 +
 host/shared/src/lib.rs                    |  42 +++++++
 20 files changed, 204 insertions(+), 209 deletions(-)
 create mode 100644 host/shared/Cargo.toml
 create mode 120000 host/shared/LICENSE-APACHE
 create mode 120000 host/shared/LICENSE-MIT
 create mode 100644 host/shared/src/lib.rs

diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index b22847de..f5e114f4 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -75,4 +75,4 @@ jobs:
           # Rustc v1.93
           llvm-version: 21
       - name: Run Tests
-        run: cargo test --no-fail-fast
+        run: cargo test --workspace --no-fail-fast
diff --git a/TODO.md b/TODO.md
index 8074adf3..3ccdd2cc 100644
--- a/TODO.md
+++ b/TODO.md
@@ -16,6 +16,10 @@
   - Instead of Playwright, interface with Webdrivers directly. Use [Fantoccini] or [Thirtyfour].
   - Add Deno support.
   - Add Edge support.
+  - Test output should happen between tests and not after all are finished.
+  - Use Clap.
+  - Use `axum-server`.
+  - E2E testing including output comparison with regular `cargo test`.
 - E2E testing for the linker. Should also ensure deterministic output.
 - Add a `disable_hygiene` attribute to `#[js_sys]` to reduce the compile-time of the output to an
   absolute minimum. This can avoid all `interpolate`s.
diff --git a/host/Cargo.toml b/host/Cargo.toml
index b9501eb2..79ff60dd 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -7,6 +7,7 @@ members = [
 	"ld",
 	"ld-shared",
 	"macro-shared",
+	"shared",
 	"wasm-ld-opt",
 ]
 resolver = "2"
@@ -22,6 +23,7 @@ cargo_metadata = "0.23"
 hashbrown = "0.16"
 indoc = "2"
 itertools = { version = "0.14", default-features = false }
+js-bindgen-shared = { path = "shared" }
 js-bindgen-ld-shared = { path = "ld-shared" }
 js-bindgen-macro-shared = { path = "macro-shared" }
 memmap2 = "0.9"
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index 609c688f..5fc08f68 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -1,11 +1,11 @@
 [package]
 edition = { workspace = true }
 name = "js-bindgen-runner"
-rust-version = { workspace = true }
+rust-version = "1.87"
 
 [dependencies]
 anyhow = { workspace = true }
-js-bindgen-ld-shared = { workspace = true }
+js-bindgen-shared = { workspace = true }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 tempfile = { workspace = true }
diff --git a/host/js-bindgen-runner/js/runner-core.mjs b/host/js-bindgen-runner/js/runner-core.mjs
index 1c3c36be..419bb8b0 100644
--- a/host/js-bindgen-runner/js/runner-core.mjs
+++ b/host/js-bindgen-runner/js/runner-core.mjs
@@ -13,7 +13,11 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 	for (const test of tests) {
 		if (test.ignore) {
 			ignored += 1
-			emit({ type: "test-ignored", name: test.name, reason: test.ignore_reason })
+			emit({
+				type: "test-ignored",
+				name: test.name,
+				reason: typeof test.ignore == "string" ? test.ignore : undefined,
+			})
 			continue
 		}
 
@@ -42,7 +46,7 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 				continue
 			}
 
-			const expectedText = test.should_panic_reason
+			const expectedText = typeof test.should_panic == "string" ? test.should_panic : undefined
 			const payload = coercePanicMessage(panicPayload(), externrefTable)
 			const message = coercePanicMessage(panicMessage(), externrefTable)
 
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index a6fd9184..d407cea2 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -5,10 +5,11 @@ use std::process::Command;
 use std::sync::atomic::{AtomicBool, Ordering};
 use std::sync::{Arc, Condvar, Mutex};
 use std::time::Duration;
-use std::{env, fs, thread};
+use std::{env, fs, str, thread};
 
 use anyhow::{Context, Result, bail};
-use js_bindgen_ld_shared::ReadFile;
+use js_bindgen_shared::ReadFile;
+use serde::{Serialize, Serializer};
 use wasmparser::{Parser, Payload};
 
 const NODE_RUNNER: &str = "js/node-runner.mjs";
@@ -20,16 +21,13 @@ const WORKER_RUNNER_SOURCE: &str = include_str!("../js/worker-runner.mjs");
 const SERVICE_WORKER_SOURCE: &str = include_str!("../js/service-worker.mjs");
 const CONSOLE_HOOK_SOURCE: &str = include_str!("../js/console-hook.mjs");
 
-const GREEN: &str = "\u{001b}[32m";
-const RESET: &str = "\u{001b}[0m";
-
-#[derive(Debug, serde::Serialize)]
+#[derive(Debug, Serialize)]
 struct TestEntry {
 	name: String,
-	ignore: bool,
-	ignore_reason: Option,
-	should_panic: bool,
-	should_panic_reason: Option,
+	#[serde(serialize_with = "option_option_string")]
+	ignore: Option>,
+	#[serde(serialize_with = "option_option_string")]
+	should_panic: Option>,
 }
 
 fn main() -> Result<()> {
@@ -69,6 +67,8 @@ fn main() -> Result<()> {
 		println!();
 		println!("running 0 tests");
 		println!();
+		const GREEN: &str = "\u{001b}[32m";
+		const RESET: &str = "\u{001b}[0m";
 		println!(
 			"test result: {GREEN}ok{RESET}. 0 passed; 0 failed; 0 ignored; 0 measured; \
 			 {filtered_count} filtered out; finished in 0.00s"
@@ -646,72 +646,78 @@ fn write_response(
 	Ok(())
 }
 
+fn option_option_string(value: &Option>, serializer: S) -> Result
+where
+	S: Serializer,
+{
+	match value {
+		None => serializer.serialize_unit(),
+		Some(None) => serializer.serialize_bool(true),
+		Some(Some(reason)) => serializer.serialize_str(reason),
+	}
+}
+
 fn read_tests(wasm_bytes: &[u8]) -> Result> {
-	/// None: `[0]`
-	///
-	/// Some(None): `[1]`
-	///
-	/// Some(Some(s)): `[2][len(s)][len]`
-	fn option_option_string(
-		data: &[u8],
-		mut offset: usize,
-	) -> Result<(Option>, usize)> {
-		offset += 1;
-		let value = match data[offset - 1] {
+	/// - None: `[0]`
+	/// - Some(None): `[1]`
+	/// - Some(Some(s)): `[2][len(s)][s]`
+	fn option_option_string(data: &mut &[u8]) -> Result>> {
+		let value = match data
+			.split_off_first()
+			.context("invalid test flag encoding")?
+		{
 			0 => None,
 			1 => Some(None),
 			2 => {
 				let len = u32::from_le_bytes(
-					data[offset..offset + 4]
-						.try_into()
-						.expect("slice length checked"),
+					data.split_off(..4)
+						.context("invalid test flag length encoding")?
+						.try_into()?,
 				) as usize;
-				offset += 4;
-				let s = std::str::from_utf8(&data[offset..offset + len])
-					.context("payload is not utf-8")?
-					.to_string();
-				offset += len;
+				let s = str::from_utf8(
+					data.split_off(..len)
+						.context("invalid test flag reason encoding")?,
+				)?
+				.to_string();
 				Some(Some(s))
 			}
 			_ => bail!("mismatch flag value"),
 		};
-		Ok((value, offset))
+		Ok(value)
 	}
 
 	let mut tests = Vec::new();
 
 	for payload in Parser::new(0).parse_all(wasm_bytes) {
-		if let Payload::CustomSection(section) = payload.context("failed to parse wasm")?
+		if let Payload::CustomSection(section) = payload?
 			&& section.name() == "js_bindgen.test"
 		{
-			let mut offset = 0;
-			let data = section.data();
+			let mut data = section.data();
 
-			while offset < data.len() {
+			while !data.is_empty() {
 				let len = u32::from_le_bytes(
-					data[offset..offset + 4]
-						.try_into()
-						.expect("slice length checked"),
+					data.split_off(..4)
+						.context("invalid test name length encoding")?
+						.try_into()?,
 				) as usize;
-				offset += 4;
-				let end = offset + len;
 
-				let (ignore, offset1) = option_option_string(data, offset)?;
-				let (should_panic, offset2) = option_option_string(data, offset1)?;
+				let ignore = option_option_string(&mut data)?;
+				let should_panic = option_option_string(&mut data)?;
 
-				let name =
-					std::str::from_utf8(&data[offset2..end]).context("test name is not utf-8")?;
+				let name = str::from_utf8(
+					data.split_off(..len)
+						.context("invalid test name encoding")?,
+				)?;
 
 				tests.push(TestEntry {
 					name: name.to_string(),
-					ignore: ignore.is_some(),
-					ignore_reason: ignore.and_then(|s| s),
-					should_panic: should_panic.is_some(),
-					should_panic_reason: should_panic.and_then(|s| s),
+					ignore,
+					should_panic,
 				});
-
-				offset = end;
 			}
+
+			// Section with the same name can never appear again.
+			break;
 		}
 	}
 
@@ -726,7 +732,7 @@ fn apply_filters(
 ) -> usize {
 	let initial = tests.len();
 	tests.retain(|test| {
-		let matches_ignore = !ignored_only || test.ignore;
+		let matches_ignore = !ignored_only || test.ignore.is_some();
 		let matches_filter = if filters.is_empty() {
 			true
 		} else if exact {
diff --git a/host/js-bindgen-test-macro/src/lib.rs b/host/js-bindgen-test-macro/src/lib.rs
index 9b877971..e4dee455 100644
--- a/host/js-bindgen-test-macro/src/lib.rs
+++ b/host/js-bindgen-test-macro/src/lib.rs
@@ -38,25 +38,20 @@ fn test_internal(attr: TokenStream, item: TokenStream) -> Result Result {
 		None
 	};
 
+	let len = u16::try_from(required_embed.as_deref().map(str::len).unwrap_or(0))
+		.expect("`required_embed` name too long")
+		.to_le_bytes();
+	let unstructured = [
+		&len,
+		required_embed.as_deref().map(str::as_bytes).unwrap_or(&[]),
+	]
+	.concat();
+
 	Ok(custom_section(
 		&format!("js_bindgen.import.{package}.{import_name}"),
-		Some(required_embed.as_deref().unwrap_or("")),
+		Some(&unstructured),
 		&parse_string_arguments(&mut input, Span::mixed_site())?,
 	))
 }
diff --git a/host/js-bindgen/src/tests/test.rs b/host/js-bindgen/src/tests/test.rs
index b26068fd..f77366f1 100644
--- a/host/js-bindgen/src/tests/test.rs
+++ b/host/js-bindgen/src/tests/test.rs
@@ -370,6 +370,7 @@ fn import() {
 		}),
 		quote! {
 			const _: () = {
+				const ARR_UNSTRUCTURED: [u8; 2] = *b"\0\0";
 				const ARR_0: [u8; 7] = *b"bar\nbaz";
 
 				const LEN: u32 = {
@@ -383,7 +384,7 @@ fn import() {
 					struct Layout([u8; 4], [u8; 2], [u8; 7]);
 
 					#[unsafe(link_section = "js_bindgen.import.test_crate.foo")]
-					static CUSTOM_SECTION: Layout = Layout(::core::primitive::u32::to_le_bytes(LEN), [0, 0], ARR_0);
+					static CUSTOM_SECTION: Layout = Layout(::core::primitive::u32::to_le_bytes(LEN), ARR_UNSTRUCTURED, ARR_0);
 				};
 			};
 		},
@@ -398,7 +399,7 @@ fn required_embed() {
 		}),
 		quote! {
 			const _: () = {
-				const ARR_PREFIX: [u8; 3] = *b"bar";
+				const ARR_UNSTRUCTURED: [u8; 5] = *b"\x03\0bar";
 				const LEN: u32 = {
 					let mut len: usize = 0;
 					len as u32
@@ -406,10 +407,10 @@ fn required_embed() {
 
 				const _: () = {
 					#[repr(C)]
-					struct Layout([u8; 4], [u8; 2], [u8; 3]);
+					struct Layout([u8; 4], [u8; 5]);
 
 					#[unsafe(link_section = "js_bindgen.import.test_crate.foo")]
-					static CUSTOM_SECTION: Layout = Layout(::core::primitive::u32::to_le_bytes(LEN), [3, 0], ARR_PREFIX);
+					static CUSTOM_SECTION: Layout = Layout(::core::primitive::u32::to_le_bytes(LEN), ARR_UNSTRUCTURED);
 				};
 			};
 		},
diff --git a/host/js-sys-macro/Cargo.toml b/host/js-sys-macro/Cargo.toml
index 9a9ca5eb..429a17b7 100644
--- a/host/js-sys-macro/Cargo.toml
+++ b/host/js-sys-macro/Cargo.toml
@@ -23,3 +23,6 @@ rand = { workspace = true }
 similar-asserts = { workspace = true }
 syn = { workspace = true }
 wasmparser = { workspace = true }
+
+[lints]
+workspace = true
diff --git a/host/ld-shared/Cargo.toml b/host/ld-shared/Cargo.toml
index 6fcc2f88..52df9b25 100644
--- a/host/ld-shared/Cargo.toml
+++ b/host/ld-shared/Cargo.toml
@@ -5,6 +5,7 @@ name = "js-bindgen-ld-shared"
 rust-version = "1.91"
 
 [dependencies]
+js-bindgen-shared = { workspace = true }
 memmap2 = { workspace = true }
 object = { workspace = true }
 wasmparser = { workspace = true }
diff --git a/host/ld-shared/src/lib.rs b/host/ld-shared/src/lib.rs
index 3d506a8d..4b33a9ef 100644
--- a/host/ld-shared/src/lib.rs
+++ b/host/ld-shared/src/lib.rs
@@ -1,12 +1,10 @@
 use std::ffi::OsStr;
 use std::fmt::{self, Debug, Formatter};
-use std::fs::File;
-use std::io::{self, Error, ErrorKind, Read, Write};
-use std::ops::Deref;
+use std::io::{self, Error, Read, Write};
 use std::path::Path;
 use std::process::{Command, Stdio};
 
-use memmap2::Mmap;
+use js_bindgen_shared::ReadFile;
 use object::read::archive::ArchiveFile;
 use wasmparser::CustomSectionReader;
 
@@ -166,42 +164,6 @@ pub fn ld_input_parser(
 	Ok(())
 }
 
-pub struct ReadFile(ReadInner);
-
-enum ReadInner {
-	Mmap(Mmap),
-	File(Vec),
-}
-
-impl ReadFile {
-	pub fn new(path: &Path) -> Result {
-		let mut file = File::open(path)?;
-		// SAFETY: the file is not mutated while the mapping is in use.
-		let result = unsafe { Mmap::map(&file) };
-
-		match result {
-			Ok(mmap) => Ok(Self(ReadInner::Mmap(mmap))),
-			Err(error) if matches!(error.kind(), ErrorKind::Unsupported) => {
-				let mut output = Vec::new();
-				file.read_to_end(&mut output)?;
-				Ok(Self(ReadInner::File(output)))
-			}
-			Err(error) => Err(error),
-		}
-	}
-}
-
-impl Deref for ReadFile {
-	type Target = [u8];
-
-	fn deref(&self) -> &Self::Target {
-		match &self.0 {
-			ReadInner::Mmap(mmap) => mmap.deref(),
-			ReadInner::File(data) => data.as_slice(),
-		}
-	}
-}
-
 #[derive(Clone)]
 pub struct CustomSectionParser<'cs> {
 	name: &'cs str,
diff --git a/host/ld/Cargo.toml b/host/ld/Cargo.toml
index 427ad8ce..c38bd280 100644
--- a/host/ld/Cargo.toml
+++ b/host/ld/Cargo.toml
@@ -8,6 +8,7 @@ rust-version = "1.91"
 hashbrown = { workspace = true }
 itertools = { workspace = true }
 js-bindgen-ld-shared = { workspace = true }
+js-bindgen-shared = { workspace = true }
 wasm-encoder = { workspace = true }
 wasmparser = { workspace = true }
 
diff --git a/host/ld/src/main.rs b/host/ld/src/main.rs
index 7ebe46e9..97ff5ac5 100644
--- a/host/ld/src/main.rs
+++ b/host/ld/src/main.rs
@@ -11,7 +11,8 @@ use std::{env, fs};
 
 use hashbrown::{HashMap, HashSet};
 use itertools::{Itertools, Position};
-use js_bindgen_ld_shared::{CustomSectionParser, ReadFile};
+use js_bindgen_ld_shared::CustomSectionParser;
+use js_bindgen_shared::ReadFile;
 use wasm_encoder::{EntityType, ImportSection, Module, RawSection, Section};
 use wasmparser::{Encoding, Parser, Payload, TypeRef};
 
diff --git a/host/macro-shared/Cargo.toml b/host/macro-shared/Cargo.toml
index 6232b0e6..c403dee4 100644
--- a/host/macro-shared/Cargo.toml
+++ b/host/macro-shared/Cargo.toml
@@ -6,3 +6,6 @@ rust-version = { workspace = true }
 
 [dev-dependencies]
 proc-macro2 = { workspace = true }
+
+[lints]
+workspace = true
diff --git a/host/macro-shared/src/lib.rs b/host/macro-shared/src/lib.rs
index f83b503e..049be895 100644
--- a/host/macro-shared/src/lib.rs
+++ b/host/macro-shared/src/lib.rs
@@ -1,3 +1,5 @@
+#![cfg_attr(test, allow(dead_code))]
+
 #[cfg(not(test))]
 extern crate proc_macro;
 #[cfg(test)]
@@ -16,7 +18,6 @@ pub struct Argument {
 }
 
 pub enum ArgumentKind {
-	Bytes(Vec),
 	String(String),
 	Interpolate(Vec),
 }
@@ -38,7 +39,7 @@ pub enum ArgumentKind {
 /// 	};
 /// };
 /// ```
-pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> TokenStream {
+pub fn custom_section(name: &str, unstructured: Option<&[u8]>, data: &[Argument]) -> TokenStream {
 	fn group(delimiter: Delimiter, inner: impl IntoIterator) -> TokenTree {
 		Group::new(delimiter, inner.into_iter().collect()).into()
 	}
@@ -66,25 +67,25 @@ pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> To
 
 	let span = Span::mixed_site();
 
-	// If a prefix is present:
-	// `const ARR_PREFIX: [u8; .len()] = *;`
-	let const_prefix = prefix
+	// If unstructered data is present:
+	// `const ARR_UNSTRUCTERED: [u8; .len()] = *;`
+	let const_unstructured = unstructured
 		.into_iter()
-		.filter(|prefix| !prefix.is_empty())
-		.flat_map(|prefix| {
+		.filter(|unstructured| !unstructured.is_empty())
+		.flat_map(|unstructured| {
 			r#const(
-				"ARR_PREFIX",
+				"ARR_UNSTRUCTURED",
 				iter::once(group(
 					Delimiter::Bracket,
 					[
 						ident("u8"),
 						Punct::new(';', Spacing::Alone).into(),
-						Literal::usize_unsuffixed(prefix.len()).into(),
+						Literal::usize_unsuffixed(unstructured.len()).into(),
 					],
 				)),
 				[
 					Punct::new('*', Spacing::Alone).into(),
-					Literal::byte_string(prefix.as_bytes()).into(),
+					Literal::byte_string(unstructured).into(),
 				],
 			)
 		});
@@ -105,29 +106,6 @@ pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> To
 		.iter()
 		.enumerate()
 		.flat_map(|(index, arg)| match &arg.kind {
-			ArgumentKind::Bytes(bytes) => {
-				// `const ARR_: [u8; .len()] = ;`
-				arg.cfg
-					.clone()
-					.into_iter()
-					.flatten()
-					.chain(r#const(
-						&format!("ARR_{index}"),
-						iter::once(group(
-							Delimiter::Bracket,
-							[
-								ident("u8"),
-								Punct::new(';', Spacing::Alone).into(),
-								Literal::usize_unsuffixed(bytes.len()).into(),
-							],
-						)),
-						[
-							Punct::new('*', Spacing::Alone).into(),
-							Literal::byte_string(bytes).into(),
-						],
-					))
-					.collect::>()
-			}
 			ArgumentKind::String(string) => {
 				// `const ARR_: [u8; .len()] = *;`
 				arg.cfg
@@ -261,9 +239,6 @@ pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> To
 							Punct::new('+', Spacing::Joint).into(),
 							Punct::new('=', Spacing::Alone).into(),
 							match &par.kind {
-								ArgumentKind::Bytes(bytes) => {
-									Literal::usize_unsuffixed(bytes.len()).into()
-								}
 								ArgumentKind::String(string) => {
 									Literal::usize_unsuffixed(string.len()).into()
 								}
@@ -290,39 +265,25 @@ pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> To
 		Punct::new(',', Spacing::Alone).into(),
 	]
 	.into_iter()
-	// Optional prefix length.
-	.chain(prefix.into_iter().flat_map(|prefix| {
-		[
-			group(
-				Delimiter::Bracket,
+	// Optional unstructured data.
+	.chain(
+		unstructured
+			.into_iter()
+			.filter(|unstructured| !unstructured.is_empty())
+			.flat_map(|unstructured| {
 				[
-					ident("u8"),
-					Punct::new(';', Spacing::Alone).into(),
-					Literal::usize_unsuffixed(2).into(),
-				],
-			),
-			Punct::new(',', Spacing::Alone).into(),
-		]
-		.into_iter()
-		.chain(
-			(!prefix.is_empty())
-				.then(|| {
-					[
-						group(
-							Delimiter::Bracket,
-							[
-								ident("u8"),
-								Punct::new(';', Spacing::Alone).into(),
-								Literal::usize_unsuffixed(prefix.len()).into(),
-							],
-						),
-						Punct::new(',', Spacing::Alone).into(),
-					]
-				})
-				.into_iter()
-				.flatten(),
-		)
-	}))
+					group(
+						Delimiter::Bracket,
+						[
+							ident("u8"),
+							Punct::new(';', Spacing::Alone).into(),
+							Literal::usize_unsuffixed(unstructured.len()).into(),
+						],
+					),
+					Punct::new(',', Spacing::Alone).into(),
+				]
+			}),
+	)
 	.chain(data.iter().enumerate().flat_map(move |(index, arg)| {
 		arg.cfg.clone().into_iter().flatten().chain([
 			group(
@@ -331,7 +292,6 @@ pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> To
 					ident("u8"),
 					Punct::new(';', Spacing::Alone).into(),
 					match &arg.kind {
-						ArgumentKind::Bytes(bytes) => Literal::usize_unsuffixed(bytes.len()).into(),
 						ArgumentKind::String(string) => {
 							Literal::usize_unsuffixed(string.len()).into()
 						}
@@ -389,30 +349,18 @@ pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> To
 				group(Delimiter::Parenthesis, iter::once(ident("LEN"))),
 				Punct::new(',', Spacing::Alone).into(),
 			])
-			// Optional prefix value.
-			.chain(prefix.into_iter().flat_map(|prefix| {
-				let len = u16::try_from(prefix.len()).unwrap().to_le_bytes();
-
-				[
-					group(
-						Delimiter::Bracket,
+			// Optional unstructured value.
+			.chain(
+				unstructured
+					.into_iter()
+					.filter(|unstructured| !unstructured.is_empty())
+					.flat_map(|_| {
 						[
-							Literal::u8_unsuffixed(len[0]).into(),
+							ident("ARR_UNSTRUCTURED"),
 							Punct::new(',', Spacing::Alone).into(),
-							Literal::u8_unsuffixed(len[1]).into(),
-							Punct::new(',', Spacing::Alone).into(),
-						],
-					),
-					Punct::new(',', Spacing::Alone).into(),
-				]
-				.into_iter()
-				.chain(
-					(!prefix.is_empty())
-						.then(|| [ident("ARR_PREFIX"), Punct::new(',', Spacing::Alone).into()])
-						.into_iter()
-						.flatten(),
-				)
-			}))
+						]
+					}),
+			)
 			.chain(data.iter().enumerate().flat_map(move |(index, arg)| {
 				arg.cfg.clone().into_iter().flatten().chain([
 					ident(&format!("ARR_{index}")),
@@ -439,7 +387,7 @@ pub fn custom_section(name: &str, prefix: Option<&str>, data: &[Argument]) -> To
 		iter::once(group(Delimiter::Parenthesis, iter::empty())),
 		iter::once(group(
 			Delimiter::Brace,
-			const_prefix.chain(consts).chain(len).chain(r#const(
+			const_unstructured.chain(consts).chain(len).chain(r#const(
 				"_",
 				iter::once(group(Delimiter::Parenthesis, iter::empty())),
 				iter::once(group(
diff --git a/host/shared/Cargo.toml b/host/shared/Cargo.toml
new file mode 100644
index 00000000..793bb4d8
--- /dev/null
+++ b/host/shared/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+edition = { workspace = true }
+license = { workspace = true }
+name = "js-bindgen-shared"
+rust-version = { workspace = true }
+
+[dependencies]
+memmap2 = { workspace = true }
+
+[lints]
+workspace = true
diff --git a/host/shared/LICENSE-APACHE b/host/shared/LICENSE-APACHE
new file mode 120000
index 00000000..1cd601d0
--- /dev/null
+++ b/host/shared/LICENSE-APACHE
@@ -0,0 +1 @@
+../../LICENSE-APACHE
\ No newline at end of file
diff --git a/host/shared/LICENSE-MIT b/host/shared/LICENSE-MIT
new file mode 120000
index 00000000..b2cfbdc7
--- /dev/null
+++ b/host/shared/LICENSE-MIT
@@ -0,0 +1 @@
+../../LICENSE-MIT
\ No newline at end of file
diff --git a/host/shared/src/lib.rs b/host/shared/src/lib.rs
new file mode 100644
index 00000000..950f11ae
--- /dev/null
+++ b/host/shared/src/lib.rs
@@ -0,0 +1,42 @@
+use std::fs::File;
+use std::io::{Error, ErrorKind, Read};
+use std::ops::Deref;
+use std::path::Path;
+
+use memmap2::Mmap;
+
+pub struct ReadFile(ReadInner);
+
+enum ReadInner {
+	Mmap(Mmap),
+	File(Vec),
+}
+
+impl ReadFile {
+	pub fn new(path: &Path) -> Result {
+		let mut file = File::open(path)?;
+		// SAFETY: the file is not mutated while the mapping is in use.
+		let result = unsafe { Mmap::map(&file) };
+
+		match result {
+			Ok(mmap) => Ok(Self(ReadInner::Mmap(mmap))),
+			Err(error) if matches!(error.kind(), ErrorKind::Unsupported) => {
+				let mut output = Vec::new();
+				file.read_to_end(&mut output)?;
+				Ok(Self(ReadInner::File(output)))
+			}
+			Err(error) => Err(error),
+		}
+	}
+}
+
+impl Deref for ReadFile {
+	type Target = [u8];
+
+	fn deref(&self) -> &Self::Target {
+		match &self.0 {
+			ReadInner::Mmap(mmap) => mmap.deref(),
+			ReadInner::File(data) => data.as_slice(),
+		}
+	}
+}

From 4ae9de62fde52050b5d7362e96054d6394933aa9 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Fri, 30 Jan 2026 19:48:26 +0800
Subject: [PATCH 33/73] Init instance for each test

---
 host/js-bindgen-runner/js/runner-core.mjs | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/host/js-bindgen-runner/js/runner-core.mjs b/host/js-bindgen-runner/js/runner-core.mjs
index 419bb8b0..3feef595 100644
--- a/host/js-bindgen-runner/js/runner-core.mjs
+++ b/host/js-bindgen-runner/js/runner-core.mjs
@@ -2,15 +2,15 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 	const startTime = Date.now()
 	emit({ type: "run-start", total: tests.length, filtered })
 
-	const { instance } = await WebAssembly.instantiate(wasmBytes, importObject)
-	const panicPayload = instance.exports.last_panic_payload
-	const panicMessage = instance.exports.last_panic_message
-	const externrefTable = resolveExternrefTable(importObject)
-
 	let failed = 0
 	let ignored = 0
 
 	for (const test of tests) {
+		const { instance } = await WebAssembly.instantiate(wasmBytes, importObject)
+		const panicPayload = instance.exports.last_panic_payload
+		const panicMessage = instance.exports.last_panic_message
+		const externrefTable = resolveExternrefTable(importObject)
+
 		if (test.ignore) {
 			ignored += 1
 			emit({

From 019e61fa29e1673a56693a7c636f83a41dff1b24 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Fri, 30 Jan 2026 20:11:47 +0800
Subject: [PATCH 34/73] Use clap to parse args

---
 TODO.md                            |   1 -
 host/Cargo.toml                    |   1 +
 host/js-bindgen-runner/Cargo.toml  |   1 +
 host/js-bindgen-runner/src/main.rs | 150 +++++++++++++++++------------
 4 files changed, 89 insertions(+), 64 deletions(-)

diff --git a/TODO.md b/TODO.md
index 3ccdd2cc..d675d934 100644
--- a/TODO.md
+++ b/TODO.md
@@ -17,7 +17,6 @@
   - Add Deno support.
   - Add Edge support.
   - Test output should happen between tests and not after all are finished.
-  - Use Clap.
   - Use `axum-server`.
   - E2E testing including output comparison with regular `cargo test`.
 - E2E testing for the linker. Should also ensure deterministic output.
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 79ff60dd..353688e5 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -40,6 +40,7 @@ tempfile = { version = "3", default-features = false }
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
+clap = { version = "4", -features = false, features = ["derive"] }
 
 [patch.crates-io]
 # Detect unsupported platforms at run-time: https://github.com/RazrFalcon/memmap2-rs/pull/161.
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index 5fc08f68..d35270b2 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -10,6 +10,7 @@ serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 tempfile = { workspace = true }
 wasmparser = { workspace = true }
+clap = { workspace = true }
 
 [lints]
 workspace = true
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index d407cea2..34e12a3a 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -7,10 +7,12 @@ use std::sync::{Arc, Condvar, Mutex};
 use std::time::Duration;
 use std::{env, fs, str, thread};
 
+use clap::{Parser, ValueEnum};
+
 use anyhow::{Context, Result, bail};
 use js_bindgen_shared::ReadFile;
 use serde::{Serialize, Serializer};
-use wasmparser::{Parser, Payload};
+use wasmparser::{Parser as WasmParser, Payload};
 
 const NODE_RUNNER: &str = "js/node-runner.mjs";
 const PLAYWRIGHT_RUNNER: &str = "js/playwright-runner.mjs";
@@ -21,6 +23,56 @@ const WORKER_RUNNER_SOURCE: &str = include_str!("../js/worker-runner.mjs");
 const SERVICE_WORKER_SOURCE: &str = include_str!("../js/service-worker.mjs");
 const CONSOLE_HOOK_SOURCE: &str = include_str!("../js/console-hook.mjs");
 
+/// Possible values for the `--format` option.
+#[derive(Debug, Clone, Copy, ValueEnum)]
+enum FormatSetting {
+	/// Display one character per test
+	Terse,
+}
+
+#[derive(Parser)]
+#[command(name = "js-bindgen-runner", version, about, long_about = None)]
+struct Cli {
+	#[arg(
+		index = 1,
+		help = "The file to test. `cargo test` passes this argument for you."
+	)]
+	file: PathBuf,
+	#[arg(long, conflicts_with = "ignored", help = "Run ignored tests")]
+	include_ignored: bool,
+	#[arg(long, conflicts_with = "include_ignored", help = "Run ignored tests")]
+	ignored: bool,
+	#[arg(long, help = "Exactly match filters rather than by substring")]
+	exact: bool,
+	#[arg(
+		long,
+		value_name = "FILTER",
+		help = "Skip tests whose names contain FILTER (this flag can be used multiple times)"
+	)]
+	skip: Vec,
+	#[arg(long, help = "List all tests and benchmarks")]
+	list: bool,
+	#[arg(
+		long,
+		help = "don't capture `console.*()` of each task, allow printing directly"
+	)]
+	nocapture: bool,
+	#[arg(
+		long,
+		value_enum,
+		value_name = "terse",
+		help = "Configure formatting of output"
+	)]
+	format: Option,
+	#[arg(
+		index = 2,
+		value_name = "FILTER",
+		help = "The FILTER string is tested against the name of all tests, and only those tests \
+                whose names contain the filter are run."
+	)]
+	filter: Option,
+}
+
 #[derive(Debug, Serialize)]
 struct TestEntry {
 	name: String,
@@ -31,33 +83,34 @@ struct TestEntry {
 }
 
 fn main() -> Result<()> {
-	let mut args = env::args().skip(1);
-
-	let wasm_path = args
-		.next()
-		.map(PathBuf::from)
-		.context("expected a wasm file path")?;
+	let cli = Cli::parse();
 
-	let args = TestArgs::new(args)?;
-	let wasm_bytes = ReadFile::new(&wasm_path)
+	let wasm_path = &cli.file;
+	let wasm_bytes = ReadFile::new(wasm_path)
 		.with_context(|| format!("failed to read wasm file: {}", wasm_path.display()))?;
+	let args = TestArgs::new(&cli)?;
 
 	let mut tests = read_tests(&wasm_bytes)?;
-	let filtered_count = apply_filters(&mut tests, &args.filters, args.ignored_only, args.exact);
+	let filtered_count = apply_filters(
+		&mut tests,
+		args.filter.as_ref(),
+		args.ignored_only,
+		args.exact,
+	);
 
 	if args.list_only {
 		match args.list_format {
-			ListFormat::Standard => {
+			Some(FormatSetting::Terse) => {
 				for test in &tests {
 					println!("{}: test", test.name);
 				}
-				println!();
-				println!("{} tests, 0 benchmarks", tests.len());
 			}
-			ListFormat::Terse => {
+			None => {
 				for test in &tests {
 					println!("{}: test", test.name);
 				}
+				println!();
+				println!("{} tests, 0 benchmarks", tests.len());
 			}
 		}
 		return Ok(());
@@ -83,7 +136,7 @@ fn main() -> Result<()> {
 
 	match args.runner {
 		RunnerConfig::Nodejs => run_node(
-			&wasm_path,
+			wasm_path,
 			&imports_path,
 			tests_json,
 			filtered_count,
@@ -111,59 +164,28 @@ fn main() -> Result<()> {
 	Ok(())
 }
 
-enum ListFormat {
-	Standard,
-	Terse,
-}
-
 struct TestArgs {
 	list_only: bool,
 	nocapture: bool,
-	filters: Vec,
-	list_format: ListFormat,
+	filter: Option,
+	list_format: Option,
 	ignored_only: bool,
 	exact: bool,
 	runner: RunnerConfig,
 }
 
 impl TestArgs {
-	fn new(mut iter: impl Iterator) -> Result {
-		let mut output = TestArgs {
-			list_only: false,
-			nocapture: false,
-			filters: Vec::new(),
-			list_format: ListFormat::Standard,
-			ignored_only: false,
-			exact: false,
+	fn new(cli: &Cli) -> Result {
+		let output = TestArgs {
+			list_only: cli.list,
+			nocapture: cli.nocapture,
+			filter: cli.filter.clone(),
+			list_format: cli.format,
+			ignored_only: cli.ignored,
+			exact: cli.exact,
 			runner: RunnerConfig::from_env()?,
 		};
 
-		while let Some(arg) = iter.next() {
-			if arg == "--list" {
-				output.list_only = true;
-			} else if arg == "--nocapture" {
-				output.nocapture = true;
-			} else if arg == "--ignored" {
-				output.ignored_only = true;
-			} else if arg == "--exact" {
-				output.exact = true;
-			} else if let Some(value) = arg.strip_prefix("--format=") {
-				if value == "terse" {
-					output.list_format = ListFormat::Terse;
-				}
-			} else if arg == "--format" {
-				if let Some(value) = iter.next() {
-					if value == "terse" {
-						output.list_format = ListFormat::Terse;
-					}
-				}
-			} else if arg.starts_with('-') {
-				continue;
-			} else {
-				output.filters.push(arg);
-			}
-		}
-
 		Ok(output)
 	}
 }
@@ -688,7 +710,7 @@ fn read_tests(wasm_bytes: &[u8]) -> Result> {
 
 	let mut tests = Vec::new();
 
-	for payload in Parser::new(0).parse_all(wasm_bytes) {
+	for payload in WasmParser::new(0).parse_all(wasm_bytes) {
 		if let Payload::CustomSection(section) = payload?
 			&& section.name() == "js_bindgen.test"
 		{
@@ -726,19 +748,21 @@ fn read_tests(wasm_bytes: &[u8]) -> Result> {
 
 fn apply_filters(
 	tests: &mut Vec,
-	filters: &[String],
+	filter: Option<&String>,
 	ignored_only: bool,
 	exact: bool,
 ) -> usize {
 	let initial = tests.len();
 	tests.retain(|test| {
 		let matches_ignore = !ignored_only || test.ignore.is_some();
-		let matches_filter = if filters.is_empty() {
-			true
-		} else if exact {
-			filters.contains(&test.name)
+		let matches_filter = if let Some(filter) = filter {
+			if exact {
+				filter == &test.name
+			} else {
+				test.name.contains(filter)
+			}
 		} else {
-			filters.iter().any(|filter| test.name.contains(filter))
+			true
 		};
 		matches_ignore && matches_filter
 	});

From 273c4f56b1836c0aba69aeadcfd266ad37c67c82 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Fri, 30 Jan 2026 20:46:56 +0800
Subject: [PATCH 35/73] typo

---
 host/Cargo.toml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/host/Cargo.toml b/host/Cargo.toml
index 353688e5..f281ec65 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -40,7 +40,7 @@ tempfile = { version = "3", default-features = false }
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
-clap = { version = "4", -features = false, features = ["derive"] }
+clap = { version = "4", default-features = false, features = ["std", "derive"] }
 
 [patch.crates-io]
 # Detect unsupported platforms at run-time: https://github.com/RazrFalcon/memmap2-rs/pull/161.

From 8be4f6404b52b63fbbe20b5d545f0ba534a09cd9 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Fri, 30 Jan 2026 22:02:13 +0800
Subject: [PATCH 36/73] Use axum

---
 TODO.md                            |   1 -
 host/Cargo.toml                    |   3 +
 host/js-bindgen-runner/Cargo.toml  |   3 +
 host/js-bindgen-runner/src/main.rs | 371 +++++++++++++++--------------
 4 files changed, 196 insertions(+), 182 deletions(-)

diff --git a/TODO.md b/TODO.md
index d675d934..fa640a69 100644
--- a/TODO.md
+++ b/TODO.md
@@ -17,7 +17,6 @@
   - Add Deno support.
   - Add Edge support.
   - Test output should happen between tests and not after all are finished.
-  - Use `axum-server`.
   - E2E testing including output comparison with regular `cargo test`.
 - E2E testing for the linker. Should also ensure deterministic output.
 - Add a `disable_hygiene` attribute to `#[js_sys]` to reduce the compile-time of the output to an
diff --git a/host/Cargo.toml b/host/Cargo.toml
index f281ec65..1907dd6d 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -37,10 +37,13 @@ serde_json = { version = "1", default-features = false, features = ["alloc"] }
 similar-asserts = { version = "1", default-features = false }
 syn = { version = "2", default-features = false, features = ["parsing", "printing"] }
 tempfile = { version = "3", default-features = false }
+tokio = { version = "1", default-features = false, features = ["rt-multi-thread"] }
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
 clap = { version = "4", default-features = false, features = ["std", "derive"] }
+parking_lot = { version = "0.12", default-features = false }
+axum = { version = "0.8", default-features = false, features = ["tokio", "json", "http1", "http2"]}
 
 [patch.crates-io]
 # Detect unsupported platforms at run-time: https://github.com/RazrFalcon/memmap2-rs/pull/161.
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index d35270b2..aa743412 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -5,12 +5,15 @@ rust-version = "1.87"
 
 [dependencies]
 anyhow = { workspace = true }
+axum = { workspace = true }
 js-bindgen-shared = { workspace = true }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 tempfile = { workspace = true }
 wasmparser = { workspace = true }
 clap = { workspace = true }
+tokio = { workspace = true }
+parking_lot = { workspace = true }
 
 [lints]
 workspace = true
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 34e12a3a..3bdf2708 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -1,17 +1,23 @@
-use std::io::{ErrorKind, Read, Write};
-use std::net::{TcpListener, TcpStream};
+use std::io::{ErrorKind, Write};
 use std::path::{Path, PathBuf};
 use std::process::Command;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Arc, Condvar, Mutex};
-use std::time::Duration;
-use std::{env, fs, str, thread};
+use std::sync::Arc;
+use std::{env, fs, str};
 
 use clap::{Parser, ValueEnum};
 
 use anyhow::{Context, Result, bail};
+use axum::{
+	Json, Router,
+	extract::State,
+	http::{HeaderValue, StatusCode, header},
+	response::Response,
+	routing::{get, post},
+};
 use js_bindgen_shared::ReadFile;
+use parking_lot::{Condvar, Mutex};
 use serde::{Serialize, Serializer};
+use tokio::net::TcpListener;
 use wasmparser::{Parser as WasmParser, Payload};
 
 const NODE_RUNNER: &str = "js/node-runner.mjs";
@@ -82,7 +88,8 @@ struct TestEntry {
 	should_panic: Option>,
 }
 
-fn main() -> Result<()> {
+#[tokio::main]
+async fn main() -> Result<()> {
 	let cli = Cli::parse();
 
 	let wasm_path = &cli.file;
@@ -142,23 +149,29 @@ fn main() -> Result<()> {
 			filtered_count,
 			args.nocapture,
 		)?,
-		RunnerConfig::Browser { kind, worker } => run_playwright(
-			wasm_bytes.to_vec(),
-			&imports_path,
-			tests_json,
-			filtered_count,
-			args.nocapture,
-			&kind,
-			worker.as_ref(),
-		)?,
-		RunnerConfig::Server { worker } => run_browser_server(
-			wasm_bytes.to_vec(),
-			&imports_path,
-			tests_json,
-			filtered_count,
-			args.nocapture,
-			worker.as_ref(),
-		)?,
+		RunnerConfig::Browser { kind, worker } => {
+			run_playwright(
+				wasm_bytes.to_vec(),
+				&imports_path,
+				tests_json,
+				filtered_count,
+				args.nocapture,
+				&kind,
+				worker.as_ref(),
+			)
+			.await?
+		}
+		RunnerConfig::Server { worker } => {
+			run_browser_server(
+				wasm_bytes.to_vec(),
+				&imports_path,
+				tests_json,
+				filtered_count,
+				args.nocapture,
+				worker.as_ref(),
+			)
+			.await?
+		}
 	}
 
 	Ok(())
@@ -333,7 +346,7 @@ fn ensure_module_package(imports_path: &Path) {
 	}
 }
 
-fn run_playwright(
+async fn run_playwright(
 	wasm_bytes: Vec,
 	imports_path: &Path,
 	tests_json: String,
@@ -350,7 +363,8 @@ fn run_playwright(
 		nocapture,
 		worker.map(|s| s.as_str()),
 	)?;
-	let server = HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref())?;
+	let server =
+		HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref()).await?;
 	let url = build_browser_url(server.base_url.as_str());
 
 	let runner_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(PLAYWRIGHT_RUNNER);
@@ -362,7 +376,6 @@ fn run_playwright(
 		.context("failed to run node")?;
 
 	let report = server.wait_for_report();
-	server.shutdown.store(true, Ordering::Relaxed);
 
 	for line in report.lines {
 		println!("{line}");
@@ -378,7 +391,7 @@ fn run_playwright(
 	Ok(())
 }
 
-fn run_browser_server(
+async fn run_browser_server(
 	wasm_bytes: Vec,
 	imports_path: &Path,
 	tests_json: String,
@@ -394,7 +407,8 @@ fn run_browser_server(
 		nocapture,
 		worker.map(|s| s.as_str()),
 	)?;
-	let server = HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref())?;
+	let server =
+		HttpServer::start(assets, env::var("JBG_TEST_SERVER_ADDRESS").ok().as_deref()).await?;
 	let url = build_browser_url(server.base_url.as_str());
 
 	println!("open this URL in your browser to run tests:");
@@ -460,212 +474,207 @@ impl BrowserAssets {
 
 struct HttpServer {
 	base_url: String,
-	shutdown: Arc,
+	report_state: Arc,
+}
+
+#[derive(Clone)]
+struct AppState {
+	assets: Arc,
 	report_state: Arc,
 }
 
 impl HttpServer {
-	fn start(assets: BrowserAssets, address: Option<&str>) -> Result {
-		let listener = bind_default_port(address).context("failed to bind server")?;
+	async fn start(assets: BrowserAssets, address: Option<&str>) -> Result {
+		let listener = bind_default_port(address)
+			.await
+			.context("failed to bind server")?;
 		let local_addr = listener.local_addr()?;
 		let base_url = format!("http://{}:{}", local_addr.ip(), local_addr.port());
-		let shutdown = Arc::new(AtomicBool::new(false));
-		let shutdown_flag = Arc::clone(&shutdown);
+
 		let assets = Arc::new(assets);
 		let report_state = Arc::new(ReportState {
 			result: Mutex::new(None),
 			signal: Condvar::new(),
 		});
-		let report_state_thread = Arc::clone(&report_state);
-
-		listener
-			.set_nonblocking(true)
-			.context("failed to set nonblocking")?;
-
-		thread::spawn(move || {
-			while !shutdown_flag.load(Ordering::Relaxed) {
-				match listener.accept() {
-					Ok((stream, _)) => {
-						let assets = Arc::clone(&assets);
-						let report_state = Arc::clone(&report_state_thread);
-						let _ = handle_connection(stream, assets, report_state);
-					}
-					Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
-						thread::sleep(Duration::from_millis(5));
-					}
-					Err(_) => break,
-				}
+		let state = AppState {
+			assets,
+			report_state: Arc::clone(&report_state),
+		};
+		let app = build_router(state);
+		let serve = axum::serve(listener, app);
+
+		tokio::spawn(async move {
+			if let Err(e) = serve.await {
+				panic!("failed to run server: {e:?}");
 			}
 		});
 
 		Ok(Self {
 			base_url,
-			shutdown,
 			report_state,
 		})
 	}
 
 	fn wait_for_report(&self) -> Report {
-		let mut guard = self.report_state.result.lock().unwrap();
+		let guard = &mut self.report_state.result.lock();
 		loop {
 			if let Some(report) = guard.take() {
 				return report;
 			}
-			guard = self.report_state.signal.wait(guard).unwrap();
+			self.report_state.signal.wait(guard);
 		}
 	}
 }
 
-fn bind_default_port(address: Option<&str>) -> Result {
+fn build_router(state: AppState) -> Router {
+	Router::new()
+		.route("/", get(index_handler))
+		.route("/index.html", get(index_handler))
+		.route("/browser-runner.mjs", get(browser_runner_handler))
+		.route("/runner-core.mjs", get(runner_core_handler))
+		.route("/shared.mjs", get(shared_handler))
+		.route("/worker-runner.mjs", get(worker_runner_handler))
+		.route("/service-worker.mjs", get(service_worker_handler))
+		.route("/console-hook.mjs", get(console_hook_handler))
+		.route("/import.js", get(import_handler))
+		.route("/tests.json", get(tests_handler))
+		.route("/wasm", get(wasm_handler))
+		.route("/report", post(report_handler))
+		.with_state(state)
+}
+
+async fn bind_default_port(address: Option<&str>) -> Result {
 	let default_addr = address.unwrap_or("127.0.0.1:8000");
-	match TcpListener::bind(default_addr) {
+	match TcpListener::bind(default_addr).await {
 		Ok(listener) => Ok(listener),
 		Err(err) if err.kind() == ErrorKind::AddrInUse => {
 			let fallback_addr = address
 				.and_then(|addr| addr.split_once(':'))
 				.map(|(ip, _)| format!("{ip}:0"))
 				.unwrap_or_else(|| "127.0.0.1:0".to_string());
-			TcpListener::bind(&fallback_addr).context("failed to bind fallback port")
+			TcpListener::bind(&fallback_addr)
+				.await
+				.context("failed to bind fallback port")
 		}
 		Err(err) => Err(err).context("failed to bind default port"),
 	}
 }
 
-fn handle_connection(
-	mut stream: TcpStream,
-	assets: Arc,
-	report_state: Arc,
-) -> Result<()> {
-	let mut buffer = [0u8; 4096];
-	let mut request = Vec::new();
-	let mut header_end = 0;
-
-	loop {
-		let size = stream.read(&mut buffer)?;
-		if size == 0 {
-			break;
-		}
-		let len = request.len();
-		request.extend_from_slice(&buffer[..size]);
-
-		if let Some(pos) = request[len.saturating_sub(3)..]
-			.windows(4)
-			.position(|window| window == b"\r\n\r\n")
-		{
-			header_end = pos;
-			break;
-		}
-	}
+async fn index_handler(State(state): State) -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"text/html",
+		state.assets.index_html.as_bytes(),
+	)
+}
 
-	if header_end == 0 {
-		return Ok(());
-	}
+async fn browser_runner_handler() -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/javascript",
+		BROWSER_RUNNER_SOURCE.as_bytes(),
+	)
+}
 
-	let (header_bytes, body) = request.split_at(header_end + 4);
-	let request_text = String::from_utf8_lossy(header_bytes);
-	let mut lines = request_text.lines();
-	let Some(request_line) = lines.next() else {
-		return Ok(());
-	};
+async fn runner_core_handler() -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/javascript",
+		RUNNER_CORE_SOURCE.as_bytes(),
+	)
+}
 
-	// GET /index.html HTTP/1.1
-	let mut parts = request_line.split_whitespace();
-	let method = parts.next().unwrap_or_default();
-	let path = parts.next().unwrap_or("/");
+async fn shared_handler() -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/javascript",
+		SHARED_JS_SOURCE.as_bytes(),
+	)
+}
 
-	let mut content_length = 0usize;
-	for line in lines {
-		if let Some(value) = line.strip_prefix("Content-Length:") {
-			content_length = value.trim().parse().unwrap_or(0);
-		}
-	}
+async fn worker_runner_handler() -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/javascript",
+		WORKER_RUNNER_SOURCE.as_bytes(),
+	)
+}
 
-	if method == "POST" && path.starts_with("/report") {
-		let mut body_vec = body.to_vec();
-		while body_vec.len() < content_length {
-			let size = stream.read(&mut buffer)?;
-			if size == 0 {
-				break;
-			}
-			body_vec.extend_from_slice(&buffer[..size]);
-		}
+async fn service_worker_handler() -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/javascript",
+		SERVICE_WORKER_SOURCE.as_bytes(),
+	)
+}
 
-		let report = serde_json::from_slice(&body_vec)?;
-		*report_state.result.lock().unwrap() = Some(report);
-		report_state.signal.notify_all();
+async fn console_hook_handler() -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/javascript",
+		CONSOLE_HOOK_SOURCE.as_bytes(),
+	)
+}
 
-		write_response(&mut stream, 200, "text/plain", b"OK")?;
-		return Ok(());
-	}
+async fn import_handler(State(state): State) -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/javascript",
+		state.assets.import_js.as_bytes(),
+	)
+}
 
-	if method == "OPTIONS" {
-		write_response(&mut stream, 204, "text/plain", b"")?;
-		return Ok(());
-	}
+async fn tests_handler(State(state): State) -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/json",
+		state.assets.tests_json.as_bytes(),
+	)
+}
 
-	if method != "GET" {
-		write_response(&mut stream, 405, "text/plain", b"Method Not Allowed")?;
-		return Ok(());
-	}
+async fn wasm_handler(State(state): State) -> Response {
+	bytes_response(
+		StatusCode::OK,
+		"application/wasm",
+		state.assets.wasm_bytes.as_slice(),
+	)
+}
 
-	let (body, content_type, status) = match path {
-		"/" | "/index.html" => (assets.index_html.as_bytes(), "text/html", 200),
-		"/browser-runner.mjs" => (
-			BROWSER_RUNNER_SOURCE.as_bytes(),
-			"application/javascript",
-			200,
-		),
-		"/runner-core.mjs" => (RUNNER_CORE_SOURCE.as_bytes(), "application/javascript", 200),
-		"/shared.mjs" => (SHARED_JS_SOURCE.as_bytes(), "application/javascript", 200),
-		"/worker-runner.mjs" => (
-			WORKER_RUNNER_SOURCE.as_bytes(),
-			"application/javascript",
-			200,
-		),
-		"/service-worker.mjs" => (
-			SERVICE_WORKER_SOURCE.as_bytes(),
-			"application/javascript",
-			200,
-		),
-		"/console-hook.mjs" => (
-			CONSOLE_HOOK_SOURCE.as_bytes(),
-			"application/javascript",
-			200,
-		),
-		"/import.js" => (assets.import_js.as_bytes(), "application/javascript", 200),
-		"/tests.json" => (assets.tests_json.as_bytes(), "application/json", 200),
-		"/wasm" => (assets.wasm_bytes.as_slice(), "application/wasm", 200),
-		_ => (b"Not Found".as_slice(), "text/plain", 404),
-	};
+async fn report_handler(State(state): State, Json(report): Json) -> Response {
+	*state.report_state.result.lock() = Some(report);
+	state.report_state.signal.notify_all();
+	bytes_response(StatusCode::OK, "text/plain", "OK".as_bytes())
+}
 
-	write_response(&mut stream, status, content_type, body)?;
-	Ok(())
+fn bytes_response(status: StatusCode, content_type: &'static str, body: &[u8]) -> Response {
+	let mut response = Response::new(axum::body::Body::from(body.to_vec()));
+	*response.status_mut() = status;
+	response
+		.headers_mut()
+		.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
+	with_headers(response)
 }
 
-fn write_response(
-	stream: &mut TcpStream,
-	status: u16,
-	content_type: &str,
-	body: &[u8],
-) -> Result<()> {
-	let status_text = match status {
-		200 => "OK",
-		204 => "No Content",
-		404 => "Not Found",
-		405 => "Method Not Allowed",
-		_ => "OK",
-	};
-	write!(
-		stream,
-		"HTTP/1.1 {status} {status_text}\r\nContent-Length: {}\r\nContent-Type: \
-		 {content_type}\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, \
-		 POST, OPTIONS\r\nAccess-Control-Allow-Headers: \
-		 Content-Type\r\nCross-Origin-Opener-Policy: same-origin\r\nCross-Origin-Embedder-Policy: \
-		 require-corp\r\n\r\n",
-		body.len()
-	)?;
-	stream.write_all(body)?;
-	Ok(())
+fn with_headers(mut response: Response) -> Response {
+	let headers = response.headers_mut();
+	headers.insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
+	headers.insert(
+		"Access-Control-Allow-Methods",
+		HeaderValue::from_static("GET, POST, OPTIONS"),
+	);
+	headers.insert(
+		"Access-Control-Allow-Headers",
+		HeaderValue::from_static("Content-Type"),
+	);
+	headers.insert(
+		"Cross-Origin-Opener-Policy",
+		HeaderValue::from_static("same-origin"),
+	);
+	headers.insert(
+		"Cross-Origin-Embedder-Policy",
+		HeaderValue::from_static("require-corp"),
+	);
+	response
 }
 
 fn option_option_string(value: &Option>, serializer: S) -> Result

From 09a71d20d78af9cc7c3d895b7373b906cf4bb4c4 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Fri, 30 Jan 2026 22:25:37 +0800
Subject: [PATCH 37/73] Add doctest

---
 client/web-sys/src/lib.rs | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/client/web-sys/src/lib.rs b/client/web-sys/src/lib.rs
index ba76b5e6..6216e9ca 100644
--- a/client/web-sys/src/lib.rs
+++ b/client/web-sys/src/lib.rs
@@ -3,6 +3,13 @@
 pub use js_sys;
 use js_sys::JsValue;
 
+/// ```rust
+/// # #[js_bindgen_test::test]
+/// # fn doctest() {
+/// let log = js_sys::JsString::from_str("hello world");
+/// web_sys::console::log(&log);
+/// # }
+/// ````
 pub mod console {
 	use super::*;
 

From a7f73aa3a0f87caa90da90f5e187af36437f833e Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Fri, 30 Jan 2026 16:56:22 +0100
Subject: [PATCH 38/73] Random Improvements

---
 TEST.md                                      |   2 +-
 TODO.md                                      |   2 +
 cargo-shim/linker.cmd                        |   5 +-
 cargo-shim/runner.cmd                        |   5 +-
 client/Cargo.toml                            |   6 +
 client/web-sys/Cargo.toml                    |   3 +
 host/Cargo.toml                              |   4 +-
 host/js-bindgen-runner/js/browser-runner.mjs |  26 +-
 host/js-bindgen-runner/js/index.html         |   4 +-
 host/js-bindgen-runner/js/node-runner.mjs    |   4 +-
 host/js-bindgen-runner/js/runner-core.mjs    |  12 +-
 host/js-bindgen-runner/js/service-worker.mjs |   4 +-
 host/js-bindgen-runner/js/shared.mjs         |  10 +-
 host/js-bindgen-runner/js/worker-runner.mjs  |   4 +-
 host/js-bindgen-runner/src/main.rs           | 243 +++++++++----------
 15 files changed, 169 insertions(+), 165 deletions(-)

diff --git a/TEST.md b/TEST.md
index 1ed9614d..e8b61083 100644
--- a/TEST.md
+++ b/TEST.md
@@ -65,7 +65,7 @@ cargo test --target wasm32-unknown-unknown -- --ignored
 Other test flags:
 
 ```sh
-cargo test --target wasm32-unknown-unknown -- --nocapture
+cargo test --target wasm32-unknown-unknown -- --no-capture
 ```
 
 Wasm tooling checks:
diff --git a/TODO.md b/TODO.md
index fa640a69..661201bf 100644
--- a/TODO.md
+++ b/TODO.md
@@ -18,6 +18,8 @@
   - Add Edge support.
   - Test output should happen between tests and not after all are finished.
   - E2E testing including output comparison with regular `cargo test`.
+  - Design a way to let users set the default driver, overwrite and whitelist drivers globally or
+    for specific tests.
 - E2E testing for the linker. Should also ensure deterministic output.
 - Add a `disable_hygiene` attribute to `#[js_sys]` to reduce the compile-time of the output to an
   absolute minimum. This can avoid all `interpolate`s.
diff --git a/cargo-shim/linker.cmd b/cargo-shim/linker.cmd
index 7be4a8f3..20906348 100755
--- a/cargo-shim/linker.cmd
+++ b/cargo-shim/linker.cmd
@@ -5,9 +5,8 @@
 :; # Lines starting with `:;` are ignored on Windows but are executed on UNIX.
 :; (
 :;   cd "$(dirname "$0")/../host" || exit 1
-:;   cargo +stable run -q -p js-bindgen-ld -- "$@"
-:; )
-:; exit $?
+:;   cargo +stable run -q -p js-bindgen-ld -- "$@"; exit $?
+:; ); exit $?
 
 :: Windows
 :: Never reached on UNIX because we execute `exit`.
diff --git a/cargo-shim/runner.cmd b/cargo-shim/runner.cmd
index 089f106f..e5d435a5 100755
--- a/cargo-shim/runner.cmd
+++ b/cargo-shim/runner.cmd
@@ -5,9 +5,8 @@
 :; # Lines starting with `:;` are ignored on Windows but are executed on UNIX.
 :; (
 :;   cd "$(dirname "$0")/../host" || exit 1
-:;   cargo +stable run -q -p js-bindgen-runner -- "$@"
-:; )
-:; exit $?
+:;   cargo +stable run -q -p js-bindgen-runner -- "$@"; exit $?
+:; ); exit $?
 
 :: Windows
 :: Never reached on UNIX because we execute `exit`.
diff --git a/client/Cargo.toml b/client/Cargo.toml
index e57ed87d..42670465 100644
--- a/client/Cargo.toml
+++ b/client/Cargo.toml
@@ -33,6 +33,12 @@ name = "basic"
 [workspace.lints.rust]
 linker_messages = "warn"
 
+[workspace.lints.clippy]
+obfuscated_if_else = "allow"
+tabs_in_doc_comments = "allow"
+undocumented_unsafe_blocks = "warn"
+use_self = "warn"
+
 [lints]
 workspace = true
 
diff --git a/client/web-sys/Cargo.toml b/client/web-sys/Cargo.toml
index ca708324..7492ddc4 100644
--- a/client/web-sys/Cargo.toml
+++ b/client/web-sys/Cargo.toml
@@ -9,3 +9,6 @@ js-sys = { workspace = true }
 
 [dev-dependencies]
 js-bindgen-test = { workspace = true }
+
+[lints]
+workspace = true
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 1907dd6d..c4a8cbb4 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -41,7 +41,7 @@ tokio = { version = "1", default-features = false, features = ["rt-multi-thread"
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
-clap = { version = "4", default-features = false, features = ["std", "derive"] }
+clap = { version = "4", features = ["derive"] }
 parking_lot = { version = "0.12", default-features = false }
 axum = { version = "0.8", default-features = false, features = ["tokio", "json", "http1", "http2"]}
 
@@ -52,9 +52,11 @@ memmap2 = { git = "https://github.com/RazrFalcon/memmap2-rs", rev = "01273a7c4ae
 ui_test = { git = "https://github.com/daxpedda/ui_test", branch = "js-bindgen" }
 
 [workspace.lints.rust]
+linker_messages = "warn"
 unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage_nightly)'] }
 
 [workspace.lints.clippy]
 obfuscated_if_else = "allow"
 tabs_in_doc_comments = "allow"
 undocumented_unsafe_blocks = "warn"
+use_self = "warn"
diff --git a/host/js-bindgen-runner/js/browser-runner.mjs b/host/js-bindgen-runner/js/browser-runner.mjs
index 86ab9898..2881c5fc 100644
--- a/host/js-bindgen-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-runner/js/browser-runner.mjs
@@ -2,7 +2,7 @@ import { createTextFormatter } from "./shared.mjs"
 import { runTests } from "./runner-core.mjs"
 import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
 
-export async function runBrowser({ nocapture, filtered, worker }) {
+export async function runBrowser({ noCapture, filtered, worker }) {
 	const baseLog = consoleHook.base.log
 	const baseError = consoleHook.base.error
 	const baseWarn = consoleHook.base.warn
@@ -11,7 +11,7 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 
 	let result = worker
 		? await runInWorker({
-				nocapture,
+				noCapture,
 				filtered,
 				worker,
 				baseLog,
@@ -20,7 +20,7 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 				baseInfo,
 				baseDebug,
 			})
-		: await runInWindow({ nocapture, filtered, consoleHook })
+		: await runInWindow({ noCapture, filtered, consoleHook })
 
 	if (typeof window !== "undefined") {
 		window.__jbtestDone = true
@@ -30,14 +30,14 @@ export async function runBrowser({ nocapture, filtered, worker }) {
 	return result
 }
 
-async function runInWindow({ nocapture, filtered, consoleHook }) {
+async function runInWindow({ noCapture, filtered, consoleHook }) {
 	const tests = await (await fetch("/tests.json")).json()
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
 	const { importObject } = await import("/import.js")
 
 	const lines = []
 	const formatter = createTextFormatter({
-		nocapture,
+		noCapture,
 		write(line) {
 			lines.push(line)
 			appendOutput(line)
@@ -69,7 +69,7 @@ async function runInWindow({ nocapture, filtered, consoleHook }) {
 }
 
 async function runInWorker({
-	nocapture,
+	noCapture,
 	filtered,
 	worker,
 	baseLog,
@@ -121,13 +121,13 @@ async function runInWorker({
 	if (!runWorker) {
 		throw new Error(`unsupported worker worker: ${worker}`)
 	}
-	const reportPromise = runWorker({ filtered, nocapture, handleMessage })
+	const reportPromise = runWorker({ filtered, noCapture, handleMessage })
 
 	const report = await reportPromise
 	return report
 }
 
-function runDedicatedWorker({ filtered, nocapture, handleMessage }) {
+function runDedicatedWorker({ filtered, noCapture, handleMessage }) {
 	return new Promise((resolve, reject) => {
 		let worker
 		try {
@@ -149,11 +149,11 @@ function runDedicatedWorker({ filtered, nocapture, handleMessage }) {
 			}
 		}
 		worker.onerror = err => reject(err)
-		worker.postMessage({ filtered, nocapture })
+		worker.postMessage({ filtered, noCapture })
 	})
 }
 
-function runSharedWorker({ filtered, nocapture, handleMessage }) {
+function runSharedWorker({ filtered, noCapture, handleMessage }) {
 	return new Promise((resolve, reject) => {
 		let shared
 		try {
@@ -177,11 +177,11 @@ function runSharedWorker({ filtered, nocapture, handleMessage }) {
 		}
 		port.onmessageerror = err => reject(err)
 		port.start()
-		port.postMessage({ filtered, nocapture })
+		port.postMessage({ filtered, noCapture })
 	})
 }
 
-async function runServiceWorker({ filtered, nocapture, handleMessage }) {
+async function runServiceWorker({ filtered, noCapture, handleMessage }) {
 	if (!navigator.serviceWorker) {
 		throw new Error("service workers are not supported")
 	}
@@ -216,7 +216,7 @@ async function runServiceWorker({ filtered, nocapture, handleMessage }) {
 			}
 		}
 		channel.port1.onmessageerror = err => reject(err)
-		navigator.serviceWorker.controller.postMessage({ filtered, nocapture }, [channel.port2])
+		navigator.serviceWorker.controller.postMessage({ filtered, noCapture }, [channel.port2])
 	})
 }
 
diff --git a/host/js-bindgen-runner/js/index.html b/host/js-bindgen-runner/js/index.html
index e6cdfb28..36f856bd 100644
--- a/host/js-bindgen-runner/js/index.html
+++ b/host/js-bindgen-runner/js/index.html
@@ -6,9 +6,9 @@
 	import {{ runBrowser }} from "/browser-runner.mjs";
 
 	const filtered = {filtered_count};
-	const nocapture = {nocapture_flag};
+	const noCapture = {no_capture_flag};
 	const worker = {worker};
-	const result = await runBrowser({{ filtered, nocapture, worker }});
+	const result = await runBrowser({{ filtered, noCapture, worker }});
 	await fetch("/report", {{
 	 method: "POST",
 	 headers: {{ "content-type": "application/json" }},
diff --git a/host/js-bindgen-runner/js/node-runner.mjs b/host/js-bindgen-runner/js/node-runner.mjs
index e9f7a4a8..ae22c19f 100644
--- a/host/js-bindgen-runner/js/node-runner.mjs
+++ b/host/js-bindgen-runner/js/node-runner.mjs
@@ -7,7 +7,7 @@ import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
 const wasmPath = process.env.JS_BINDGEN_WASM
 const importsPath = process.env.JS_BINDGEN_IMPORTS
 const testsPath = process.env.JS_BINDGEN_TESTS_PATH
-const nocapture = process.env.JS_BINDGEN_NOCAPTURE === "1"
+const noCapture = process.env.JS_BINDGEN_NO_CAPTURE === "1"
 const filtered = Number(process.env.JS_BINDGEN_FILTERED || "0")
 
 if (!wasmPath || !importsPath || !testsPath) {
@@ -23,7 +23,7 @@ const tests = JSON.parse(testsText)
 const baseLog = consoleHook.base.log
 const baseError = consoleHook.base.error
 const formatter = createTextFormatter({
-	nocapture,
+	noCapture,
 	write(line, stream) {
 		if (stream === "stderr") {
 			baseError(line)
diff --git a/host/js-bindgen-runner/js/runner-core.mjs b/host/js-bindgen-runner/js/runner-core.mjs
index 3feef595..4bb2909a 100644
--- a/host/js-bindgen-runner/js/runner-core.mjs
+++ b/host/js-bindgen-runner/js/runner-core.mjs
@@ -33,20 +33,20 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 		}
 
 		const result = test.run(testFn)
-		const shouldPanic = test.should_panic
+		const shouldPanic = test.shouldPanic
 		if (shouldPanic) {
 			if (result.ok) {
 				emit({
 					type: "test-failed",
 					name: test.name,
 					error: "test did not panic as expected",
-					should_panic: true,
+					shouldPanic: true,
 				})
 				failed += 1
 				continue
 			}
 
-			const expectedText = typeof test.should_panic == "string" ? test.should_panic : undefined
+			const expectedText = typeof test.shouldPanic == "string" ? test.shouldPanic : undefined
 			const payload = coercePanicMessage(panicPayload(), externrefTable)
 			const message = coercePanicMessage(panicMessage(), externrefTable)
 
@@ -64,18 +64,18 @@ export async function runTests({ wasmBytes, importObject, tests, filtered, emit
 						"note: panic did not contain expected string\n" +
 						`      panic message: "${displayPayload}"\n` +
 						` expected substring: "${displayExpected}"`,
-					should_panic: true,
+					shouldPanic: true,
 				})
 				failed += 1
 				continue
 			}
 
-			emit({ type: "test-ok", name: test.name, should_panic: true })
+			emit({ type: "test-ok", name: test.name, shouldPanic: true })
 			continue
 		}
 
 		if (result.ok) {
-			emit({ type: "test-ok", name: test.name, should_panic: false })
+			emit({ type: "test-ok", name: test.name, shouldPanic: false })
 		} else {
 			const message = coercePanicMessage(panicMessage(), externrefTable)
 			emit({ type: "test-failed", name: test.name, error: message + "\n" + result.stack })
diff --git a/host/js-bindgen-runner/js/service-worker.mjs b/host/js-bindgen-runner/js/service-worker.mjs
index 7b0b56b9..61a15292 100644
--- a/host/js-bindgen-runner/js/service-worker.mjs
+++ b/host/js-bindgen-runner/js/service-worker.mjs
@@ -13,12 +13,12 @@ self.addEventListener("message", event => {
 	})
 })
 
-async function execute(port, { nocapture, filtered }) {
+async function execute(port, { noCapture, filtered }) {
 	const tests = await (await fetch("/tests.json")).json()
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
 	const lines = []
 	const formatter = createTextFormatter({
-		nocapture,
+		noCapture,
 		write(line) {
 			lines.push(line)
 			port.postMessage({ type: "line", line })
diff --git a/host/js-bindgen-runner/js/shared.mjs b/host/js-bindgen-runner/js/shared.mjs
index b9323cce..3af9ad87 100644
--- a/host/js-bindgen-runner/js/shared.mjs
+++ b/host/js-bindgen-runner/js/shared.mjs
@@ -1,4 +1,4 @@
-export function createTextFormatter({ nocapture, write }) {
+export function createTextFormatter({ noCapture, write }) {
 	const buffered = new Map()
 	const failed = []
 	const failureReports = []
@@ -31,16 +31,16 @@ export function createTextFormatter({ nocapture, write }) {
 					write(`running ${event.total} tests`, "stdout")
 					break
 				case "test-output":
-					if (nocapture) {
+					if (noCapture) {
 						write(event.line, event.stream)
 					}
-					if (!nocapture) {
+					if (!noCapture) {
 						buffer(event.name, event.line, event.stream)
 					}
 					break
 				case "test-ok":
 					takeBuffer(event.name)
-					if (event.should_panic) {
+					if (event.shouldPanic) {
 						write(`test ${event.name} - should panic ... ${green}ok${reset}`, "stdout")
 					} else {
 						write(`test ${event.name} ... ${green}ok${reset}`, "stdout")
@@ -56,7 +56,7 @@ export function createTextFormatter({ nocapture, write }) {
 					break
 				case "test-failed":
 					failed.push(event.name)
-					if (event.should_panic) {
+					if (event.shouldPanic) {
 						write(`test ${event.name} - should panic ... ${red}FAILED${reset}`, "stdout")
 					} else {
 						write(`test ${event.name} ... ${red}FAILED${reset}`, "stdout")
diff --git a/host/js-bindgen-runner/js/worker-runner.mjs b/host/js-bindgen-runner/js/worker-runner.mjs
index f83a4919..c55698a4 100644
--- a/host/js-bindgen-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-runner/js/worker-runner.mjs
@@ -2,14 +2,14 @@ import { createTextFormatter } from "./shared.mjs"
 import { runTests } from "./runner-core.mjs"
 import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
 
-async function execute(port, { nocapture, filtered }) {
+async function execute(port, { noCapture, filtered }) {
 	const tests = await (await fetch("/tests.json")).json()
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
 	const { importObject } = await import("/import.js")
 
 	const lines = []
 	const formatter = createTextFormatter({
-		nocapture,
+		noCapture,
 		write(line) {
 			lines.push(line)
 			port.postMessage({ type: "line", line })
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 3bdf2708..b7632a28 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -2,18 +2,16 @@ use std::io::{ErrorKind, Write};
 use std::path::{Path, PathBuf};
 use std::process::Command;
 use std::sync::Arc;
-use std::{env, fs, str};
-
-use clap::{Parser, ValueEnum};
+use std::{env, fs, iter, str};
 
 use anyhow::{Context, Result, bail};
-use axum::{
-	Json, Router,
-	extract::State,
-	http::{HeaderValue, StatusCode, header},
-	response::Response,
-	routing::{get, post},
-};
+use axum::body::Body;
+use axum::extract::State;
+use axum::http::{HeaderValue, StatusCode, header};
+use axum::response::Response;
+use axum::routing::{get, post};
+use axum::{Json, Router};
+use clap::{Parser, ValueEnum};
 use js_bindgen_shared::ReadFile;
 use parking_lot::{Condvar, Mutex};
 use serde::{Serialize, Serializer};
@@ -30,7 +28,7 @@ const SERVICE_WORKER_SOURCE: &str = include_str!("../js/service-worker.mjs");
 const CONSOLE_HOOK_SOURCE: &str = include_str!("../js/console-hook.mjs");
 
 /// Possible values for the `--format` option.
-#[derive(Debug, Clone, Copy, ValueEnum)]
+#[derive(Clone, Copy, ValueEnum)]
 enum FormatSetting {
 	/// Display one character per test
 	Terse,
@@ -39,47 +37,37 @@ enum FormatSetting {
 #[derive(Parser)]
 #[command(name = "js-bindgen-runner", version, about, long_about = None)]
 struct Cli {
-	#[arg(
-		index = 1,
-		help = "The file to test. `cargo test` passes this argument for you."
-	)]
-	file: PathBuf,
-	#[arg(long, conflicts_with = "ignored", help = "Run ignored tests")]
+	/// Run ignored and not ignored tests.
+	#[arg(long, conflicts_with = "ignored")]
 	include_ignored: bool,
-	#[arg(long, conflicts_with = "include_ignored", help = "Run ignored tests")]
+	/// Run only ignored tests.
+	#[arg(long, conflicts_with = "include_ignored")]
 	ignored: bool,
-	#[arg(long, help = "Exactly match filters rather than by substring")]
+	/// Exactly match filters rather than by substring.
+	#[arg(long)]
 	exact: bool,
-	#[arg(
-		long,
-		value_name = "FILTER",
-		help = "Skip tests whose names contain FILTER (this flag can be used multiple times)"
-	)]
+	/// Skip tests whose names contain FILTER (this flag can be used multiple
+	/// times).
+	#[arg(long, value_name = "FILTER")]
 	skip: Vec,
-	#[arg(long, help = "List all tests and benchmarks")]
+	/// List all tests and benchmarks.
+	#[arg(long)]
 	list: bool,
-	#[arg(
-		long,
-		help = "don't capture `console.*()` of each task, allow printing directly"
-	)]
-	nocapture: bool,
-	#[arg(
-		long,
-		value_enum,
-		value_name = "terse",
-		help = "Configure formatting of output"
-	)]
+	/// don't capture `console.*()` of each task, allow printing directly.
+	#[arg(long)]
+	no_capture: bool,
+	/// Configure formatting of output.
+	#[arg(long, value_enum)]
 	format: Option,
-	#[arg(
-		index = 2,
-		value_name = "FILTER",
-		help = "The FILTER string is tested against the name of all tests, and only those tests \
-                whose names contain the filter are run."
-	)]
-	filter: Option,
+	/// The FILTER string is tested against the name of all tests, and only
+	/// those tests whose names contain the filter are run. Multiple filter
+	/// strings may be passed, which will run all tests matching any of the
+	/// filters.
+	filter: Vec,
 }
 
 #[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
 struct TestEntry {
 	name: String,
 	#[serde(serialize_with = "option_option_string")]
@@ -90,12 +78,21 @@ struct TestEntry {
 
 #[tokio::main]
 async fn main() -> Result<()> {
-	let cli = Cli::parse();
-
-	let wasm_path = &cli.file;
+	let mut args = env::args_os();
+	let binary = args
+		.next()
+		.context("expected the first argument to be present")?;
+	// We parse the file argument ourselves to prevent it from being shown on the
+	// help page.
+	let file = args.next();
+
+	let cli = Cli::parse_from(iter::once(binary).chain(args));
+
+	let file = file.context("expected a file to have been passed from `cargo run/test`")?;
+	let wasm_path = Path::new(&file);
 	let wasm_bytes = ReadFile::new(wasm_path)
-		.with_context(|| format!("failed to read wasm file: {}", wasm_path.display()))?;
-	let args = TestArgs::new(&cli)?;
+		.with_context(|| format!("failed to read Wasm file: {}", wasm_path.display()))?;
+	let args = TestArgs::new(cli)?;
 
 	let mut tests = read_tests(&wasm_bytes)?;
 	let filtered_count = apply_filters(
@@ -137,9 +134,9 @@ async fn main() -> Result<()> {
 		return Ok(());
 	}
 
-	// `web_sys-4e01138c76cd2a1a.wasm` to `web_sys-4e01138c76cd2a1a.js`
+	// The JS file has the same name, just a different file extension.
 	let imports_path = wasm_path.with_extension("js");
-	let tests_json = serde_json::to_string(&tests).expect("checked");
+	let tests_json = serde_json::to_string(&tests).unwrap();
 
 	match args.runner {
 		RunnerConfig::Nodejs => run_node(
@@ -147,28 +144,28 @@ async fn main() -> Result<()> {
 			&imports_path,
 			tests_json,
 			filtered_count,
-			args.nocapture,
+			args.no_capture,
 		)?,
 		RunnerConfig::Browser { kind, worker } => {
 			run_playwright(
-				wasm_bytes.to_vec(),
+				wasm_bytes,
 				&imports_path,
 				tests_json,
 				filtered_count,
-				args.nocapture,
-				&kind,
-				worker.as_ref(),
+				args.no_capture,
+				kind,
+				worker,
 			)
 			.await?
 		}
 		RunnerConfig::Server { worker } => {
 			run_browser_server(
-				wasm_bytes.to_vec(),
+				wasm_bytes,
 				&imports_path,
 				tests_json,
 				filtered_count,
-				args.nocapture,
-				worker.as_ref(),
+				args.no_capture,
+				worker,
 			)
 			.await?
 		}
@@ -179,8 +176,8 @@ async fn main() -> Result<()> {
 
 struct TestArgs {
 	list_only: bool,
-	nocapture: bool,
-	filter: Option,
+	no_capture: bool,
+	filter: Vec,
 	list_format: Option,
 	ignored_only: bool,
 	exact: bool,
@@ -188,11 +185,11 @@ struct TestArgs {
 }
 
 impl TestArgs {
-	fn new(cli: &Cli) -> Result {
-		let output = TestArgs {
+	fn new(cli: Cli) -> Result {
+		let output = Self {
 			list_only: cli.list,
-			nocapture: cli.nocapture,
-			filter: cli.filter.clone(),
+			no_capture: cli.no_capture,
+			filter: cli.filter,
 			list_format: cli.format,
 			ignored_only: cli.ignored,
 			exact: cli.exact,
@@ -203,7 +200,7 @@ impl TestArgs {
 	}
 }
 
-#[derive(Debug)]
+#[derive(Clone, Copy, Debug)]
 enum RunnerConfig {
 	Nodejs,
 	Browser {
@@ -215,60 +212,60 @@ enum RunnerConfig {
 	},
 }
 
-#[derive(Debug)]
+#[derive(Clone, Copy, Debug)]
 enum WorkerKind {
-	// https://developer.mozilla.org/en-US/docs/Web/API/Worker
+	/// https://developer.mozilla.org/en-US/docs/Web/API/Worker
 	Dedicated,
-	// https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker
+	/// https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker
 	Shared,
-	// https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker
+	/// https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker
 	Service,
 }
 
 impl WorkerKind {
 	fn from_str(worker: &str) -> Result {
 		Ok(match worker {
-			"dedicated" => WorkerKind::Dedicated,
-			"shared" => WorkerKind::Shared,
-			"service" => WorkerKind::Service,
+			"dedicated" => Self::Dedicated,
+			"shared" => Self::Shared,
+			"service" => Self::Service,
 			worker => bail!("unsupported worker: {worker}"),
 		})
 	}
 
-	fn as_str(&self) -> &str {
+	fn as_str(self) -> &'static str {
 		match self {
-			WorkerKind::Dedicated => "dedicated",
-			WorkerKind::Shared => "shared",
-			WorkerKind::Service => "service",
+			Self::Dedicated => "dedicated",
+			Self::Shared => "shared",
+			Self::Service => "service",
 		}
 	}
 }
 
-#[derive(Debug)]
+#[derive(Clone, Copy, Debug)]
 enum DriverKind {
-	// https://developer.chrome.com/docs/chromedriver
+	/// https://developer.chrome.com/docs/chromedriver
 	Chrome,
-	// https://github.com/mozilla/geckodriver
+	/// https://github.com/mozilla/geckodriver
 	Gecko,
-	// https://github.com/WebKit/WebKit
+	/// https://github.com/WebKit/WebKit
 	WebKit,
 }
 
 impl DriverKind {
 	fn from_str(driver: &str) -> Result {
 		Ok(match driver {
-			"chrome" => DriverKind::Chrome,
-			"gecko" => DriverKind::Gecko,
-			"webkit" => DriverKind::WebKit,
+			"chrome" => Self::Chrome,
+			"gecko" => Self::Gecko,
+			"webkit" => Self::WebKit,
 			driver => bail!("unsupported driver: {driver}"),
 		})
 	}
 
 	fn as_str(&self) -> &str {
 		match self {
-			DriverKind::Chrome => "chrome",
-			DriverKind::Gecko => "gecko",
-			DriverKind::WebKit => "webkit",
+			Self::Chrome => "chrome",
+			Self::Gecko => "gecko",
+			Self::WebKit => "webkit",
 		}
 	}
 }
@@ -288,18 +285,19 @@ impl RunnerConfig {
 		let server = env::var("JBG_TEST_SERVER").is_ok();
 
 		let config = match (server, driver) {
-			(true, None) => RunnerConfig::Server { worker },
-			(true, Some(d)) => {
-				eprintln!("Because a server has been configured, the {d:?} option is not work.");
-				RunnerConfig::Server { worker }
+			(true, None) => Self::Server { worker },
+			(true, Some(_)) => {
+				eprintln!("Because a server has been configured, `JBG_TEST_DRIVER` is ignored.");
+				Self::Server { worker }
 			}
 			(false, None) => {
-				if let Some(worker) = worker {
-					eprintln!("The {worker:?} option does not work in Node.js.");
+				if worker.is_some() {
+					eprintln!("because Node.js is selected, `JBG_TEST_WORKER` is ignored.");
 				}
-				RunnerConfig::Nodejs
+
+				Self::Nodejs
 			}
-			(false, Some(kind)) => RunnerConfig::Browser { kind, worker },
+			(false, Some(kind)) => Self::Browser { kind, worker },
 		};
 
 		Ok(config)
@@ -311,7 +309,7 @@ fn run_node(
 	imports_path: &Path,
 	tests_json: String,
 	filtered_count: usize,
-	nocapture: bool,
+	no_capture: bool,
 ) -> Result<()> {
 	ensure_module_package(imports_path);
 	let runner_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(NODE_RUNNER);
@@ -325,7 +323,7 @@ fn run_node(
 		.env("JS_BINDGEN_IMPORTS", imports_path)
 		.env("JS_BINDGEN_TESTS_PATH", &tests_path)
 		.env("JS_BINDGEN_FILTERED", filtered_count.to_string())
-		.env("JS_BINDGEN_NOCAPTURE", if nocapture { "1" } else { "0" })
+		.env("JS_BINDGEN_NOCAPTURE", if no_capture { "1" } else { "0" })
 		.status()
 		.context("failed to run node")?;
 
@@ -347,20 +345,20 @@ fn ensure_module_package(imports_path: &Path) {
 }
 
 async fn run_playwright(
-	wasm_bytes: Vec,
+	wasm_bytes: ReadFile,
 	imports_path: &Path,
 	tests_json: String,
 	filtered_count: usize,
-	nocapture: bool,
-	driver: &DriverKind,
-	worker: Option<&WorkerKind>,
+	no_capture: bool,
+	driver: DriverKind,
+	worker: Option,
 ) -> Result<()> {
 	let assets = BrowserAssets::new(
 		wasm_bytes,
 		imports_path,
 		&tests_json,
 		filtered_count,
-		nocapture,
+		no_capture,
 		worker.map(|s| s.as_str()),
 	)?;
 	let server =
@@ -392,19 +390,19 @@ async fn run_playwright(
 }
 
 async fn run_browser_server(
-	wasm_bytes: Vec,
+	wasm_bytes: ReadFile,
 	imports_path: &Path,
 	tests_json: String,
 	filtered_count: usize,
-	nocapture: bool,
-	worker: Option<&WorkerKind>,
+	no_capture: bool,
+	worker: Option,
 ) -> Result<()> {
 	let assets = BrowserAssets::new(
 		wasm_bytes,
 		imports_path,
 		&tests_json,
 		filtered_count,
-		nocapture,
+		no_capture,
 		worker.map(|s| s.as_str()),
 	)?;
 	let server =
@@ -435,7 +433,7 @@ struct ReportState {
 }
 
 struct BrowserAssets {
-	wasm_bytes: Vec,
+	wasm_bytes: ReadFile,
 	import_js: String,
 	tests_json: String,
 	index_html: String,
@@ -443,11 +441,11 @@ struct BrowserAssets {
 
 impl BrowserAssets {
 	fn new(
-		wasm_bytes: Vec,
+		wasm_bytes: ReadFile,
 		imports_path: &Path,
 		tests_json: &str,
 		filtered_count: usize,
-		nocapture: bool,
+		no_capture: bool,
 		worker: Option<&str>,
 	) -> Result {
 		let import_js = fs::read_to_string(imports_path)?;
@@ -455,7 +453,7 @@ impl BrowserAssets {
 		let index_html = format!(
 			include_str!("../js/index.html"),
 			filtered_count = filtered_count,
-			nocapture_flag = if nocapture { "true" } else { "false" },
+			no_capture_flag = if no_capture { "true" } else { "false" },
 			worker = if let Some(worker) = worker {
 				format!("{worker:?}")
 			} else {
@@ -633,11 +631,7 @@ async fn tests_handler(State(state): State) -> Response {
 }
 
 async fn wasm_handler(State(state): State) -> Response {
-	bytes_response(
-		StatusCode::OK,
-		"application/wasm",
-		state.assets.wasm_bytes.as_slice(),
-	)
+	bytes_response(StatusCode::OK, "application/wasm", &state.assets.wasm_bytes)
 }
 
 async fn report_handler(State(state): State, Json(report): Json) -> Response {
@@ -647,7 +641,7 @@ async fn report_handler(State(state): State, Json(report): Json Response {
-	let mut response = Response::new(axum::body::Body::from(body.to_vec()));
+	let mut response = Response::new(Body::from(body.to_vec()));
 	*response.status_mut() = status;
 	response
 		.headers_mut()
@@ -757,22 +751,21 @@ fn read_tests(wasm_bytes: &[u8]) -> Result> {
 
 fn apply_filters(
 	tests: &mut Vec,
-	filter: Option<&String>,
+	filter: &[String],
 	ignored_only: bool,
 	exact: bool,
 ) -> usize {
 	let initial = tests.len();
 	tests.retain(|test| {
 		let matches_ignore = !ignored_only || test.ignore.is_some();
-		let matches_filter = if let Some(filter) = filter {
-			if exact {
-				filter == &test.name
-			} else {
-				test.name.contains(filter)
-			}
-		} else {
-			true
-		};
+		let matches_filter = filter.is_empty()
+			|| filter.iter().any(|filter| {
+				if exact {
+					filter == &test.name
+				} else {
+					test.name.contains(filter)
+				}
+			});
 		matches_ignore && matches_filter
 	});
 	initial - tests.len()

From 5aa21b3d177bb787860a745ea7acc9c82df7be30 Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Fri, 30 Jan 2026 16:59:05 +0100
Subject: [PATCH 39/73] Run Taplo

---
 host/Cargo.toml                   | 8 ++++----
 host/js-bindgen-runner/Cargo.toml | 6 +++---
 2 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/host/Cargo.toml b/host/Cargo.toml
index c4a8cbb4..ce6eeb63 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -19,15 +19,18 @@ rust-version = "1.85"
 
 [workspace.dependencies]
 anyhow = "1"
+axum = { version = "0.8", default-features = false, features = ["tokio", "json", "http1", "http2"] }
 cargo_metadata = "0.23"
+clap = { version = "4", features = ["derive"] }
 hashbrown = "0.16"
 indoc = "2"
 itertools = { version = "0.14", default-features = false }
-js-bindgen-shared = { path = "shared" }
 js-bindgen-ld-shared = { path = "ld-shared" }
 js-bindgen-macro-shared = { path = "macro-shared" }
+js-bindgen-shared = { path = "shared" }
 memmap2 = "0.9"
 object = { version = "0.38", default-features = false, features = ["archive", "read_core", "std"] }
+parking_lot = { version = "0.12", default-features = false }
 prettyplease = "0.2"
 proc-macro2 = { version = "1", default-features = false }
 quote = { version = "1", default-features = false }
@@ -41,9 +44,6 @@ tokio = { version = "1", default-features = false, features = ["rt-multi-thread"
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
-clap = { version = "4", features = ["derive"] }
-parking_lot = { version = "0.12", default-features = false }
-axum = { version = "0.8", default-features = false, features = ["tokio", "json", "http1", "http2"]}
 
 [patch.crates-io]
 # Detect unsupported platforms at run-time: https://github.com/RazrFalcon/memmap2-rs/pull/161.
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index aa743412..b6af8caf 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -6,14 +6,14 @@ rust-version = "1.87"
 [dependencies]
 anyhow = { workspace = true }
 axum = { workspace = true }
+clap = { workspace = true }
 js-bindgen-shared = { workspace = true }
+parking_lot = { workspace = true }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
 tempfile = { workspace = true }
-wasmparser = { workspace = true }
-clap = { workspace = true }
 tokio = { workspace = true }
-parking_lot = { workspace = true }
+wasmparser = { workspace = true }
 
 [lints]
 workspace = true

From edf2a58b2dd9df74a3d12a003acd7e32a9a4450d Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Sat, 31 Jan 2026 01:26:14 +0800
Subject: [PATCH 40/73] Use Fantoccini

---
 TEST.md                                       |   6 +-
 TODO.md                                       |   1 -
 host/Cargo.toml                               |   3 +
 host/js-bindgen-runner/Cargo.toml             |   3 +
 host/js-bindgen-runner/js/browser-runner.mjs  |  20 +-
 host/js-bindgen-runner/js/index.html          |   1 +
 .../js/playwright-runner.mjs                  |  25 --
 host/js-bindgen-runner/src/driver.rs          | 247 ++++++++++++++++++
 host/js-bindgen-runner/src/main.rs            | 113 ++++----
 9 files changed, 309 insertions(+), 110 deletions(-)
 delete mode 100644 host/js-bindgen-runner/js/playwright-runner.mjs
 create mode 100644 host/js-bindgen-runner/src/driver.rs

diff --git a/TEST.md b/TEST.md
index e8b61083..265444ae 100644
--- a/TEST.md
+++ b/TEST.md
@@ -47,11 +47,15 @@ JBG_TEST_SERVER=1 cargo test --target wasm32-unknown-unknown
 
 Runner options:
 
-- `JBG_TEST_DRIVER=chrome|gecko|webkit`
+- `JBG_TEST_BROWSER=1` (run in headless browser, auto detect)
+- `JBG_TEST_GECKODRIVER=` (use firefix)
+- `JBG_TEST_CHROMEDRIVER=` (use chrome)
+- `JBG_TEST_MSEDGEDRIVER=` (use edge)
 - `JBG_TEST_WORKER=dedicated|shared|service`
 - `JBG_TEST_SERVER=1` (serve browser runner and print URL)
 - `JBG_TEST_SERVER_ADDRESS=127.0.0.1:8000` (defaults to 8000; falls back to a random port if busy)
 
+
 List and filter tests:
 
 ```sh
diff --git a/TODO.md b/TODO.md
index 661201bf..b85b888e 100644
--- a/TODO.md
+++ b/TODO.md
@@ -13,7 +13,6 @@
 # High Priority
 
 - Test Runner:
-  - Instead of Playwright, interface with Webdrivers directly. Use [Fantoccini] or [Thirtyfour].
   - Add Deno support.
   - Add Edge support.
   - Test output should happen between tests and not after all are finished.
diff --git a/host/Cargo.toml b/host/Cargo.toml
index ce6eeb63..f82bf378 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -22,6 +22,7 @@ anyhow = "1"
 axum = { version = "0.8", default-features = false, features = ["tokio", "json", "http1", "http2"] }
 cargo_metadata = "0.23"
 clap = { version = "4", features = ["derive"] }
+fantoccini = "0.22.0"
 hashbrown = "0.16"
 indoc = "2"
 itertools = { version = "0.14", default-features = false }
@@ -37,11 +38,13 @@ quote = { version = "1", default-features = false }
 rand = { version = "0.9", default-features = false, features = ["thread_rng"] }
 serde = { version = "1", default-features = false }
 serde_json = { version = "1", default-features = false, features = ["alloc"] }
+shlex = "1.3.0"
 similar-asserts = { version = "1", default-features = false }
 syn = { version = "2", default-features = false, features = ["parsing", "printing"] }
 tempfile = { version = "3", default-features = false }
 tokio = { version = "1", default-features = false, features = ["rt-multi-thread"] }
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
+url = "2.5.8"
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
 wasmparser = { version = "0.244", default-features = false }
 
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index b6af8caf..e2238a3e 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -7,12 +7,15 @@ rust-version = "1.87"
 anyhow = { workspace = true }
 axum = { workspace = true }
 clap = { workspace = true }
+fantoccini = { workspace = true }
 js-bindgen-shared = { workspace = true }
 parking_lot = { workspace = true }
 serde = { workspace = true, features = ["derive"] }
 serde_json = { workspace = true }
+shlex = { workspace = true }
 tempfile = { workspace = true }
 tokio = { workspace = true }
+url = { workspace = true }
 wasmparser = { workspace = true }
 
 [lints]
diff --git a/host/js-bindgen-runner/js/browser-runner.mjs b/host/js-bindgen-runner/js/browser-runner.mjs
index 2881c5fc..8c97d402 100644
--- a/host/js-bindgen-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-runner/js/browser-runner.mjs
@@ -221,26 +221,18 @@ async function runServiceWorker({ filtered, noCapture, handleMessage }) {
 }
 
 function appendOutput(line) {
-	const output = ensureOutput()
+	const output = document.getElementById("output");
 	if (output.textContent.length > 0) {
 		output.textContent += "\n"
 	}
-	output.textContent += stripAnsi(line)
+    if (window.__jbtestHeadless) {
+	    output.textContent += line
+    } else {
+        output.textContent += stripAnsi(line)
+    }
 }
 
 function stripAnsi(line) {
 	return line.replace(/\x1b\[[0-9;]*m/g, "")
 }
 
-function ensureOutput() {
-	if (typeof document === "undefined") {
-		return { textContent: "" }
-	}
-	let output = document.getElementById("output")
-	if (!output) {
-		output = document.createElement("pre")
-		output.id = "output"
-		document.body.append(output)
-	}
-	return output
-}
diff --git a/host/js-bindgen-runner/js/index.html b/host/js-bindgen-runner/js/index.html
index 36f856bd..d50f8ae7 100644
--- a/host/js-bindgen-runner/js/index.html
+++ b/host/js-bindgen-runner/js/index.html
@@ -5,6 +5,7 @@
 
diff --git a/host/js-bindgen-runner/js/service-worker.mjs b/host/js-bindgen-runner/js/service-worker.mjs
index b35770e3..c4887c1b 100644
--- a/host/js-bindgen-runner/js/service-worker.mjs
+++ b/host/js-bindgen-runner/js/service-worker.mjs
@@ -9,18 +9,16 @@ self.addEventListener("message", event => {
 		return
 	}
 	execute(port, event.data).catch(error => {
-		port.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+		port.postMessage({ type: "report", failed: 1 })
 	})
 })
 
 async function execute(port, { noCapture, filtered }) {
 	const tests = await (await fetch("/tests.json")).json()
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
-	const lines = []
 	const formatter = createTextFormatter({
 		noCapture,
 		write(line) {
-			lines.push(line)
 			port.postMessage({ type: "line", line })
 		},
 	})
@@ -58,5 +56,5 @@ async function execute(port, { noCapture, filtered }) {
 		emit,
 	})
 
-	port.postMessage({ type: "report", lines, failed: result.failed })
+	port.postMessage({ type: "report", failed: result.failed })
 }
diff --git a/host/js-bindgen-runner/js/worker-runner.mjs b/host/js-bindgen-runner/js/worker-runner.mjs
index 8f420881..a5a2d09c 100644
--- a/host/js-bindgen-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-runner/js/worker-runner.mjs
@@ -7,11 +7,9 @@ async function execute(port, { noCapture, filtered }) {
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
 	const { importObject } = await import("/import.mjs")
 
-	const lines = []
 	const formatter = createTextFormatter({
 		noCapture,
 		write(line) {
-			lines.push(line)
 			port.postMessage({ type: "line", line })
 		},
 	})
@@ -49,23 +47,11 @@ async function execute(port, { noCapture, filtered }) {
 		emit,
 	})
 
-	port.postMessage({ type: "report", lines, failed: result.failed })
+	port.postMessage({ type: "report", failed: result.failed })
 }
 
-if (typeof self.onconnect !== "undefined") {
-	self.onconnect = event => {
-		const port = event.ports[0]
-		port.onmessage = msg => {
-			execute(port, msg.data).catch(error => {
-				port.postMessage({ type: "report", lines: [String(error)], failed: 1 })
-			})
-		}
-		port.start()
-	}
-} else {
-	self.onmessage = event => {
-		execute(self, event.data).catch(error => {
-			self.postMessage({ type: "report", lines: [String(error)], failed: 1 })
-		})
-	}
+self.onmessage = event => {
+	execute(self, event.data).catch(error => {
+		self.postMessage({ type: "report", failed: 1 })
+	})
 }
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index aeed5294..4333ba56 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
 use std::process::{self, Command};
 use std::str::FromStr;
 use std::sync::Arc;
+use std::time::Duration;
 use std::{env, fs, iter, str};
 
 use anyhow::{Context, Result, bail};
@@ -19,11 +20,12 @@ use clap::{Parser, ValueEnum};
 use driver::Capabilities;
 use fantoccini::ClientBuilder;
 use js_bindgen_shared::ReadFile;
-use parking_lot::{Condvar, Mutex};
 use serde::{Serialize, Serializer};
 use tempfile::TempDir;
 use tokio::net::TcpListener;
 use tokio::runtime::Runtime;
+use tokio::sync::{Mutex, Notify};
+use tokio::time::interval;
 use wasmparser::{Parser as WasmParser, Payload};
 
 use crate::driver::Driver;
@@ -244,7 +246,7 @@ impl RunnerConfig {
 		};
 
 		if worker.is_some()
-			&& let Self::Browser { .. } | Self::Server { .. } = config
+			&& let Self::Node { .. } | Self::Deno { .. } = config
 		{
 			eprintln!(
 				"Only browser and server runners support worker types; `JBG_TEST_WORKER` is \
@@ -339,13 +341,37 @@ impl Runner {
 
 		client.goto(&url).await?;
 
-		let report = server.wait_for_report();
+		let print_output = || async {
+			let Ok(output) = client
+				.execute("return window.takeReportLines()", vec![])
+				.await
+			else {
+				// The function is waiting to be defined.
+				return Ok(());
+			};
+			let lines: Vec =
+				serde_json::from_value(output).context("failed to parse lines")?;
+			for line in lines {
+				println!("{line}");
+			}
+			anyhow::Ok(())
+		};
 
-		client.close().await?;
+		let mut ticker = interval(Duration::from_millis(100));
 
-		for line in report.lines {
-			println!("{line}");
-		}
+		let report = loop {
+			tokio::select! {
+				_ = ticker.tick() => print_output().await?,
+				report = server.wait_for_report() => {
+					break report;
+				}
+			}
+		};
+
+		// the remaining lines
+		print_output().await?;
+
+		client.close().await?;
 
 		if report.failed > 0 {
 			process::exit(1);
@@ -370,7 +396,7 @@ impl Runner {
 		println!("{url}");
 
 		loop {
-			let _ = server.wait_for_report();
+			server.wait_for_report().await;
 		}
 	}
 
@@ -417,13 +443,12 @@ impl NodeDir {
 
 #[derive(Debug, serde::Deserialize)]
 struct Report {
-	lines: Vec,
 	failed: u64,
 }
 
 struct ReportState {
 	result: Mutex>,
-	signal: Condvar,
+	signal: tokio::sync::Notify,
 }
 
 struct BrowserAssets {
@@ -486,7 +511,7 @@ impl HttpServer {
 		let assets = Arc::new(assets);
 		let report_state = Arc::new(ReportState {
 			result: Mutex::new(None),
-			signal: Condvar::new(),
+			signal: Notify::new(),
 		});
 		let state = AppState {
 			assets,
@@ -507,13 +532,12 @@ impl HttpServer {
 		})
 	}
 
-	fn wait_for_report(&self) -> Report {
-		let guard = &mut self.report_state.result.lock();
+	async fn wait_for_report(&self) -> Report {
 		loop {
-			if let Some(report) = guard.take() {
+			self.report_state.signal.notified().await;
+			if let Some(report) = self.report_state.result.lock().await.take() {
 				return report;
 			}
-			self.report_state.signal.wait(guard);
 		}
 	}
 }
@@ -628,8 +652,8 @@ async fn wasm_handler(State(state): State) -> Response {
 }
 
 async fn report_handler(State(state): State, Json(report): Json) -> Response {
-	*state.report_state.result.lock() = Some(report);
-	state.report_state.signal.notify_all();
+	*state.report_state.result.lock().await = Some(report);
+	state.report_state.signal.notify_one();
 	bytes_response(StatusCode::OK, "text/plain", "OK".as_bytes())
 }
 

From d7f23525ba6214c9de246034c5ab3505aeac69cb Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Sun, 1 Feb 2026 16:22:52 +0800
Subject: [PATCH 63/73] Remove parking_lot

---
 host/Cargo.toml                   | 1 -
 host/js-bindgen-runner/Cargo.toml | 1 -
 2 files changed, 2 deletions(-)

diff --git a/host/Cargo.toml b/host/Cargo.toml
index f3609456..72e08613 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -31,7 +31,6 @@ js-bindgen-macro-shared = { path = "macro-shared" }
 js-bindgen-shared = { path = "shared" }
 memmap2 = "0.9"
 object = { version = "0.38", default-features = false, features = ["archive", "read_core", "std"] }
-parking_lot = { version = "0.12", default-features = false }
 prettyplease = "0.2"
 proc-macro2 = { version = "1", default-features = false }
 quote = { version = "1", default-features = false }
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index 9185e130..5465a65e 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -9,7 +9,6 @@ axum = { workspace = true }
 clap = { workspace = true }
 fantoccini = { workspace = true }
 js-bindgen-shared = { workspace = true }
-parking_lot = { workspace = true }
 serde = { workspace = true }
 serde_json = { workspace = true }
 shlex = { workspace = true }

From b8a15e88fa56347e05027739098f08f1a352a333 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Sun, 1 Feb 2026 16:40:12 +0800
Subject: [PATCH 64/73] Fix shared worker

---
 host/js-bindgen-runner/js/worker-runner.mjs | 22 ++++++++++++++++-----
 1 file changed, 17 insertions(+), 5 deletions(-)

diff --git a/host/js-bindgen-runner/js/worker-runner.mjs b/host/js-bindgen-runner/js/worker-runner.mjs
index a5a2d09c..c5d186fa 100644
--- a/host/js-bindgen-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-runner/js/worker-runner.mjs
@@ -50,8 +50,20 @@ async function execute(port, { noCapture, filtered }) {
 	port.postMessage({ type: "report", failed: result.failed })
 }
 
-self.onmessage = event => {
-	execute(self, event.data).catch(error => {
-		self.postMessage({ type: "report", failed: 1 })
-	})
-}
+if (typeof self.onconnect !== "undefined") {
+	self.onconnect = event => {
+		const port = event.ports[0]
+		port.onmessage = msg => {
+			execute(port, msg.data).catch(error => {
+				port.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+			})
+		}
+		port.start()
+	}
+} else {
+	self.onmessage = event => {
+		execute(self, event.data).catch(error => {
+			self.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+		})
+	}
+}
\ No newline at end of file

From 6db8362ebb3377e4df3368d7db0e6b8ec2ca486e Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Sun, 1 Feb 2026 17:00:04 +0800
Subject: [PATCH 65/73] Clean up

---
 host/js-bindgen-runner/js/browser-runner.mjs |  2 +-
 host/js-bindgen-runner/js/console-hook.mjs   |  4 +-
 host/js-bindgen-runner/js/service-worker.mjs | 60 --------------------
 host/js-bindgen-runner/js/worker-runner.mjs  | 32 +++++++++--
 host/js-bindgen-runner/src/main.rs           | 10 ----
 5 files changed, 29 insertions(+), 79 deletions(-)
 delete mode 100644 host/js-bindgen-runner/js/service-worker.mjs

diff --git a/host/js-bindgen-runner/js/browser-runner.mjs b/host/js-bindgen-runner/js/browser-runner.mjs
index db815647..d9c1ad6f 100644
--- a/host/js-bindgen-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-runner/js/browser-runner.mjs
@@ -178,7 +178,7 @@ async function runServiceWorker({ filtered, noCapture, handleMessage }) {
 	if (!navigator.serviceWorker) {
 		throw new Error("service workers are not supported")
 	}
-	const registration = await navigator.serviceWorker.register("/service-worker.mjs", {
+	const registration = await navigator.serviceWorker.register("/worker-runner.mjs", {
 		type: "module",
 	})
 	await navigator.serviceWorker.ready
diff --git a/host/js-bindgen-runner/js/console-hook.mjs b/host/js-bindgen-runner/js/console-hook.mjs
index 58b09d4e..83f921af 100644
--- a/host/js-bindgen-runner/js/console-hook.mjs
+++ b/host/js-bindgen-runner/js/console-hook.mjs
@@ -1,5 +1,5 @@
 function installConsoleHook() {
-	const existing = globalThis.__jbtestConsoleHook
+	const existing = globalThis.consoleHook
 	if (existing) {
 		return existing
 	}
@@ -42,7 +42,7 @@ function installConsoleHook() {
 			forwardToConsole = false
 		},
 	}
-	globalThis.__jbtestConsoleHook = h
+	globalThis.consoleHook = h
 	return h
 }
 
diff --git a/host/js-bindgen-runner/js/service-worker.mjs b/host/js-bindgen-runner/js/service-worker.mjs
deleted file mode 100644
index c4887c1b..00000000
--- a/host/js-bindgen-runner/js/service-worker.mjs
+++ /dev/null
@@ -1,60 +0,0 @@
-import { createTextFormatter } from "./shared.mjs"
-import { runTests } from "./runner-core.mjs"
-import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
-import { importObject } from "./import.mjs"
-
-self.addEventListener("message", event => {
-	const port = event.ports && event.ports[0]
-	if (!port) {
-		return
-	}
-	execute(port, event.data).catch(error => {
-		port.postMessage({ type: "report", failed: 1 })
-	})
-})
-
-async function execute(port, { noCapture, filtered }) {
-	const tests = await (await fetch("/tests.json")).json()
-	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
-	const formatter = createTextFormatter({
-		noCapture,
-		write(line) {
-			port.postMessage({ type: "line", line })
-		},
-	})
-
-	function emit(event) {
-		if (event.type === "test-output") {
-			port.postMessage({
-				type: "user-output",
-				line: event.line,
-				stream: event.stream,
-				level: event.level || (event.stream === "stderr" ? "error" : "log"),
-			})
-		}
-		formatter.onEvent(event)
-	}
-
-	const testInputs = tests.map(test => ({
-		...test,
-		run(testFn) {
-			return withConsoleCapture({
-				name: test.name,
-				run: () => testFn(),
-				emit,
-				consoleHook,
-				forwardToConsole: false,
-			})
-		},
-	}))
-
-	const result = await runTests({
-		wasmBytes,
-		importObject,
-		tests: testInputs,
-		filtered,
-		emit,
-	})
-
-	port.postMessage({ type: "report", failed: result.failed })
-}
diff --git a/host/js-bindgen-runner/js/worker-runner.mjs b/host/js-bindgen-runner/js/worker-runner.mjs
index c5d186fa..0b4ad887 100644
--- a/host/js-bindgen-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-runner/js/worker-runner.mjs
@@ -1,11 +1,11 @@
 import { createTextFormatter } from "./shared.mjs"
 import { runTests } from "./runner-core.mjs"
 import consoleHook, { withConsoleCapture } from "./console-hook.mjs"
+import { importObject } from "./import.mjs"
 
 async function execute(port, { noCapture, filtered }) {
 	const tests = await (await fetch("/tests.json")).json()
 	const wasmBytes = await (await fetch("/wasm")).arrayBuffer()
-	const { importObject } = await import("/import.mjs")
 
 	const formatter = createTextFormatter({
 		noCapture,
@@ -50,20 +50,40 @@ async function execute(port, { noCapture, filtered }) {
 	port.postMessage({ type: "report", failed: result.failed })
 }
 
-if (typeof self.onconnect !== "undefined") {
+const isServiceWorker =
+	typeof ServiceWorkerGlobalScope !== "undefined" &&
+	self instanceof ServiceWorkerGlobalScope
+const isSharedWorker =
+	typeof SharedWorkerGlobalScope !== "undefined" &&
+	self instanceof SharedWorkerGlobalScope
+const isDedicatedWorker =
+	typeof DedicatedWorkerGlobalScope !== "undefined" &&
+	self instanceof DedicatedWorkerGlobalScope
+
+if (isServiceWorker) {
+	self.addEventListener("message", event => {
+		const port = event.ports && event.ports[0]
+		if (!port) {
+			return
+		}
+		execute(port, event.data).catch(error => {
+			port.postMessage({ type: "report", failed: 1 })
+		})
+	})
+} else if (isSharedWorker) {
 	self.onconnect = event => {
 		const port = event.ports[0]
 		port.onmessage = msg => {
 			execute(port, msg.data).catch(error => {
-				port.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+				port.postMessage({ type: "report", failed: 1 })
 			})
 		}
 		port.start()
 	}
-} else {
+} else if (isDedicatedWorker) {
 	self.onmessage = event => {
 		execute(self, event.data).catch(error => {
-			self.postMessage({ type: "report", lines: [String(error)], failed: 1 })
+			self.postMessage({ type: "report", failed: 1 })
 		})
 	}
-}
\ No newline at end of file
+}
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 4333ba56..65b5c3a4 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -35,7 +35,6 @@ const BROWSER_RUNNER: &str = include_str!("../js/browser-runner.mjs");
 const RUNNER_CORE: &str = include_str!("../js/runner-core.mjs");
 const SHARED_JS: &str = include_str!("../js/shared.mjs");
 const WORKER_RUNNER: &str = include_str!("../js/worker-runner.mjs");
-const SERVICE_WORKER: &str = include_str!("../js/service-worker.mjs");
 const CONSOLE_HOOK: &str = include_str!("../js/console-hook.mjs");
 
 /// Possible values for the `--format` option.
@@ -550,7 +549,6 @@ fn build_router(state: AppState) -> Router {
 		.route("/runner-core.mjs", get(runner_core_handler))
 		.route("/shared.mjs", get(shared_handler))
 		.route("/worker-runner.mjs", get(worker_runner_handler))
-		.route("/service-worker.mjs", get(service_worker_handler))
 		.route("/console-hook.mjs", get(console_hook_handler))
 		.route("/import.mjs", get(import_handler))
 		.route("/tests.json", get(tests_handler))
@@ -615,14 +613,6 @@ async fn worker_runner_handler() -> Response {
 	)
 }
 
-async fn service_worker_handler() -> Response {
-	bytes_response(
-		StatusCode::OK,
-		"application/javascript",
-		SERVICE_WORKER.as_bytes(),
-	)
-}
-
 async fn console_hook_handler() -> Response {
 	bytes_response(
 		StatusCode::OK,

From f8c7bc7bd2db8e60ca8b5a3889f144e1928998a8 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Sun, 1 Feb 2026 19:09:59 +0800
Subject: [PATCH 66/73] Add env prefix

---
 TODO.md                              |  1 -
 host/js-bindgen-runner/src/driver.rs | 13 +++++++------
 2 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/TODO.md b/TODO.md
index 7f271c9e..1d3b7d5e 100644
--- a/TODO.md
+++ b/TODO.md
@@ -26,7 +26,6 @@
   - Add support for `panic = "unwind"`.
   - Add support for `--force-run-in-process`.
   - Add support for `--skip`, `--quiet`, `--show-output`, `--color` and `--format pretty`.
-  - Connect to existing Webdriver. Important to make Nextest actually be performant.
   - E2E testing including output comparison with regular `cargo test`. Test output on failure
     especially carefully.
   - Design a way to let users set the default driver, overwrite and whitelist drivers globally or
diff --git a/host/js-bindgen-runner/src/driver.rs b/host/js-bindgen-runner/src/driver.rs
index d5acab33..00220255 100644
--- a/host/js-bindgen-runner/src/driver.rs
+++ b/host/js-bindgen-runner/src/driver.rs
@@ -156,16 +156,17 @@ impl Driver {
 	/// to execute tests with. Performs a number of heuristics to find one
 	/// available, including:
 	///
-	/// * Env vars like `GECKODRIVER_REMOTE` address of remote webdriver.
-	/// * Env vars like `GECKODRIVER` point to the path to a binary to execute.
+	/// * Env vars like `JBG_TEST_GECKODRIVER_REMOTE` address of remote webdriver.
+	/// * Env vars like `JBG_TEST_GECKODRIVER` point to the path to a binary to execute.
 	/// * Otherwise, `PATH` is searched for an appropriate binary.
 	///
 	/// In the last two cases a list of auxiliary arguments is also returned
-	/// which is configured through env vars like `GECKODRIVER_ARGS` to support
+	/// which is configured through env vars like `JBG_TEST_GECKODRIVER_ARGS` to support
 	/// extra arguments to the driver's invocation.
 	pub fn find() -> Result {
 		let env_args = |name: &str| {
-			let var = env::var(format!("{}_ARGS", name.to_uppercase())).unwrap_or_default();
+			let var =
+				env::var(format!("JBG_TEST_{}_ARGS", name.to_uppercase())).unwrap_or_default();
 
 			shlex::split(&var)
 				.unwrap_or_else(|| var.split_whitespace().map(|s| s.to_string()).collect())
@@ -178,10 +179,10 @@ impl Driver {
 			("msedgedriver", Driver::Edge as fn(Locate) -> Self),
 		];
 
-		// First up, if env vars like GECKODRIVER_REMOTE are present, use those
+		// First up, if env vars like JBG_TEST_GECKODRIVER_REMOTE are present, use those
 		// to allow forcing usage of a particular remote driver.
 		for (driver, ctor) in drivers.iter() {
-			let env = format!("{}_REMOTE", driver.to_uppercase());
+			let env = format!("JBG_TEST_{}_REMOTE", driver.to_uppercase());
 			let url = match env::var(&env) {
 				Ok(var) => Url::parse(&var).context(format!("failed to parse `{env}`"))?,
 				Err(_) => continue,

From 2563357062fa07763375de6eef466ecc6381a6ca Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Mon, 2 Feb 2026 00:56:40 +0100
Subject: [PATCH 67/73] Better WebDriver Error Handling

---
 TODO.md                              |   2 +
 host/Cargo.toml                      |   2 +-
 host/js-bindgen-runner/Cargo.toml    |   9 +-
 host/js-bindgen-runner/src/driver.rs | 380 +++++++++++++++++----------
 host/js-bindgen-runner/src/main.rs   | 105 ++++----
 host/ld-shared/src/lib.rs            |  13 +-
 6 files changed, 305 insertions(+), 206 deletions(-)

diff --git a/TODO.md b/TODO.md
index 1d3b7d5e..33fa4482 100644
--- a/TODO.md
+++ b/TODO.md
@@ -32,6 +32,8 @@
     for specific tests.
   - Add multithread support when running with `target_feature = "atomics"` where possible.
   - Crate feature to switch to `native-tls`.
+  - Add environment variable to set driver startup timeout.
+  - Properly emit errors when WebDrivers fail between startup and finish.
 - E2E testing for the linker. Should also ensure deterministic output.
 - Add a `disable_hygiene` attribute to `#[js_sys]` to reduce the compile-time of the output to an
   absolute minimum. This can avoid all `interpolate`s.
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 72e08613..9594c063 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -40,7 +40,7 @@ shlex = { version = "1.3.0", default-features = false }
 similar-asserts = { version = "1", default-features = false }
 syn = { version = "2", default-features = false, features = ["parsing", "printing"] }
 tempfile = "3"
-tokio = { version = "1", default-features = false, features = ["rt-multi-thread"] }
+tokio = "1"
 ui_test = { version = "0.30", default-features = false, features = ["rustc"] }
 url = { version = "2.5.8", default-features = false }
 wasm-encoder = { version = "0.244", default-features = false, features = ["wasmparser"] }
diff --git a/host/js-bindgen-runner/Cargo.toml b/host/js-bindgen-runner/Cargo.toml
index 5465a65e..46cf4108 100644
--- a/host/js-bindgen-runner/Cargo.toml
+++ b/host/js-bindgen-runner/Cargo.toml
@@ -13,7 +13,14 @@ serde = { workspace = true }
 serde_json = { workspace = true }
 shlex = { workspace = true }
 tempfile = { workspace = true }
-tokio = { workspace = true }
+tokio = { workspace = true, features = [
+	"io-util",
+	"net",
+	"process",
+	"rt-multi-thread",
+	"sync",
+	"time",
+] }
 url = { workspace = true }
 wasmparser = { workspace = true }
 
diff --git a/host/js-bindgen-runner/src/driver.rs b/host/js-bindgen-runner/src/driver.rs
index 00220255..65c69ae0 100644
--- a/host/js-bindgen-runner/src/driver.rs
+++ b/host/js-bindgen-runner/src/driver.rs
@@ -1,80 +1,85 @@
-use std::net::{TcpListener, TcpStream};
+use std::env;
+use std::env::VarError;
+use std::ffi::OsString;
 use std::path::PathBuf;
-use std::process::{Child, Command, Stdio};
+use std::process::{ExitStatus, Stdio};
 use std::time::{Duration, Instant};
-use std::{env, thread};
 
 use anyhow::{Context, Result, bail};
-use serde_json::{Map, Value as Json};
+use serde_json::{Map, Value};
+use tokio::net::{TcpListener, TcpStream};
+use tokio::process::{Child, Command};
+use tokio::sync::oneshot::{self, Receiver, Sender};
+use tokio::time;
 use url::Url;
 
 pub struct DriverGuard {
 	pub url: Url,
-	child: Option,
+	_child: Option,
 }
 
-impl Drop for DriverGuard {
-	fn drop(&mut self) {
-		if let Some(mut child) = self.child.take() {
-			let _ = child.kill();
-		}
-	}
-}
+pub async fn launch_driver(driver: &Driver) -> Result {
+	let locate = match driver {
+		Driver::Chrome(locate) => locate,
+		Driver::Edge(locate) => locate,
+		Driver::Gecko(locate) => locate,
+		Driver::Safari(locate) => locate,
+	};
 
-pub fn launch_driver(driver: &Driver) -> Result {
-	let guard = match driver.location() {
-		Locate::Remote(url) => DriverGuard {
+	let guard = match locate {
+		Location::Remote(url) => DriverGuard {
 			url: url.clone(),
-			child: None,
+			_child: None,
 		},
-		Locate::Local((path, args)) => {
+		Location::Local((path, args)) => {
 			// Wait for the driver to come online and bind its port before we try to
 			// connect to it.
 			let start = Instant::now();
-			let max = Duration::new(5, 0);
-
-			let (driver_addr, child) = 'outer: loop {
-				// Allow tests to run in parallel (in theory) by finding any open port
-				// available for our driver. We can't bind the port for the driver, but
-				// hopefully the OS gives this invocation unique ports across processes
-				let driver_addr = TcpListener::bind("127.0.0.1:0")?.local_addr()?;
-				// Spawn the driver binary, collecting its stdout/stderr in separate
-				// threads. We'll print this output later.
-				let mut cmd = Command::new(path);
-				cmd.stdout(Stdio::null())
-					.stderr(Stdio::null())
+			const MAX: Duration = Duration::from_secs(5);
+
+			let (driver_addr, child) = loop {
+				// Get a random open port to allow test runners to run in parallel.
+				let driver_addr = TcpListener::bind("127.0.0.1:0").await?.local_addr()?;
+				let child = Command::new(path)
+					.stdout(Stdio::piped())
+					.stderr(Stdio::piped())
 					.args(args)
-					.arg(format!("--port={}", driver_addr.port()));
-				let mut child = cmd.spawn()?;
-
-				// Wait for the driver to come online and bind its port before we try to
-				// connect to it.
-				loop {
-					if match child.try_wait() {
-						Ok(Some(status)) => !status.success(),
-						Ok(None) => false,
-						Err(_) => true,
-					} {
-						if start.elapsed() >= max {
-							bail!("failed to start driver")
+					.arg(format!("--port={}", driver_addr.port()))
+					.spawn()?;
+				let mut child = ChildWrapper::new(child);
+
+				let limit = time::sleep(MAX - start.elapsed());
+
+				tokio::select! {
+					_ = limit => {
+						child.output_error().await;
+						bail!("failed to bind driver port in timeout duration");
+					},
+					_ = TcpStream::connect(driver_addr) => break (driver_addr, child),
+					result = child.wait() => {
+						match result {
+							Ok(status) => if status.success() {
+								eprintln!("WebDriver exited prematurely with success");
+							} else {
+								eprintln!("WebDriver failed with status: {status}");
+							}
+							Err(error) => eprintln!("WebDriver failed with error: {error}"),
 						}
 
-						println!("failed to start driver, trying again ...");
+						child.output_error().await;
+
+						eprintln!("failed to start driver, trying again ...");
 
-						thread::sleep(Duration::from_millis(100));
-						break;
-					} else if TcpStream::connect(driver_addr).is_ok() {
-						break 'outer (driver_addr, child);
-					} else if start.elapsed() >= max {
-						bail!("failed to bind driver port during startup")
-					} else {
-						thread::sleep(Duration::from_millis(100));
+						// Back off. If something is really wrong we don't want to re-try in a
+						// hot loop.
+						time::sleep(Duration::from_millis(100)).await;
 					}
-				}
+				};
 			};
+
 			DriverGuard {
 				url: Url::parse(&format!("http://{driver_addr}"))?,
-				child: Some(child),
+				_child: Some(child),
 			}
 		}
 	};
@@ -82,173 +87,256 @@ pub fn launch_driver(driver: &Driver) -> Result {
 }
 
 /// Options that can use to customize and configure a WebDriver session.
-pub type Capabilities = Map;
+pub type Capabilities = Map;
 
 pub fn capabilities(driver: &Driver, mut cap: Capabilities) -> Result {
 	match driver {
 		Driver::Gecko(_) => cap
 			.entry("moz:firefoxOptions".to_string())
-			.or_insert_with(|| Json::Object(serde_json::Map::new()))
+			.or_insert_with(|| Value::Object(serde_json::Map::new()))
 			.as_object_mut()
 			.expect("moz:firefoxOptions wasn't a JSON object")
 			.entry("args".to_string())
-			.or_insert_with(|| Json::Array(vec![]))
+			.or_insert_with(|| Value::Array(vec![]))
 			.as_array_mut()
 			.expect("args wasn't a JSON array")
-			.extend(vec![Json::String("-headless".to_string())]),
+			.extend(vec![Value::String("-headless".to_string())]),
 		Driver::Safari(_) => (),
 		Driver::Chrome(_) => {
 			cap.entry("goog:chromeOptions".to_string())
-				.or_insert_with(|| Json::Object(serde_json::Map::new()))
+				.or_insert_with(|| Value::Object(serde_json::Map::new()))
 				.as_object_mut()
 				.expect("goog:chromeOptions wasn't a JSON object")
 				.entry("args".to_string())
-				.or_insert_with(|| Json::Array(vec![]))
+				.or_insert_with(|| Value::Array(vec![]))
 				.as_array_mut()
 				.expect("args wasn't a JSON array")
 				.extend(vec![
-					Json::String("headless".to_string()),
+					Value::String("headless".to_string()),
 					// See https://stackoverflow.com/questions/50642308/
 					// for what this funky `disable-dev-shm-usage`
 					// option is
-					Json::String("disable-dev-shm-usage".to_string()),
-					Json::String("no-sandbox".to_string()),
+					Value::String("disable-dev-shm-usage".to_string()),
+					Value::String("no-sandbox".to_string()),
 				])
 		}
 		Driver::Edge(_) => {
 			cap.entry("ms:edgeOptions".to_string())
-				.or_insert_with(|| Json::Object(serde_json::Map::new()))
+				.or_insert_with(|| Value::Object(serde_json::Map::new()))
 				.as_object_mut()
 				.expect("ms:edgeOptions wasn't a JSON object")
 				.entry("args".to_string())
-				.or_insert_with(|| Json::Array(vec![]))
+				.or_insert_with(|| Value::Array(vec![]))
 				.as_array_mut()
 				.expect("args wasn't a JSON array")
 				.extend(vec![
-					Json::String("headless".to_string()),
+					Value::String("headless".to_string()),
 					// See https://stackoverflow.com/questions/50642308/
 					// for what this funky `disable-dev-shm-usage`
 					// option is
-					Json::String("disable-dev-shm-usage".to_string()),
-					Json::String("no-sandbox".to_string()),
+					Value::String("disable-dev-shm-usage".to_string()),
+					Value::String("no-sandbox".to_string()),
 				])
 		}
 	}
 	Ok(cap)
 }
 
-#[derive(Debug)]
-pub enum Locate {
-	Local((PathBuf, Vec)),
+pub enum Location {
+	Local((PathBuf, Vec)),
 	Remote(Url),
 }
 
-#[derive(Debug)]
 pub enum Driver {
-	Gecko(Locate),
-	Safari(Locate),
-	Chrome(Locate),
-	Edge(Locate),
+	Chrome(Location),
+	Edge(Location),
+	Gecko(Location),
+	Safari(Location),
 }
 
 impl Driver {
-	/// Attempts to find an appropriate remote WebDriver server or server binary
-	/// to execute tests with. Performs a number of heuristics to find one
-	/// available, including:
+	/// Attempts to find a WebDriver.
 	///
-	/// * Env vars like `JBG_TEST_GECKODRIVER_REMOTE` address of remote webdriver.
-	/// * Env vars like `JBG_TEST_GECKODRIVER` point to the path to a binary to execute.
-	/// * Otherwise, `PATH` is searched for an appropriate binary.
-	///
-	/// In the last two cases a list of auxiliary arguments is also returned
-	/// which is configured through env vars like `JBG_TEST_GECKODRIVER_ARGS` to support
-	/// extra arguments to the driver's invocation.
+	/// An explicitly set WebDriver is searched for in `JBG_TEST_` and
+	/// `JBG_TEST__REMOTE`. If not found we look for the first WebDriver
+	/// in `PATH`.
 	pub fn find() -> Result {
-		let env_args = |name: &str| {
-			let var =
-				env::var(format!("JBG_TEST_{}_ARGS", name.to_uppercase())).unwrap_or_default();
+		fn env_args(name: &str) -> Result> {
+			let key = format!("JBG_TEST_{}_ARGS", name.to_uppercase());
+			let Some(var) = env::var_os(&key) else {
+				return Ok(Vec::new());
+			};
 
-			shlex::split(&var)
-				.unwrap_or_else(|| var.split_whitespace().map(|s| s.to_string()).collect())
-		};
+			let Some(args) = shlex::bytes::split(var.as_encoded_bytes()) else {
+				bail!("failed to parse `{key}`");
+			};
+
+			Ok(args
+				.into_iter()
+				.map(|arg|
+					// SAFETY: original source is a `OsString`.
+					unsafe { OsString::from_encoded_bytes_unchecked(arg) })
+				.collect())
+		}
 
 		let drivers = [
-			("geckodriver", Driver::Gecko as fn(Locate) -> Self),
-			("safaridriver", Driver::Safari as fn(Locate) -> Self),
-			("chromedriver", Driver::Chrome as fn(Locate) -> Self),
-			("msedgedriver", Driver::Edge as fn(Locate) -> Self),
+			("chromedriver", Driver::Chrome as fn(Location) -> Self),
+			("msedgedriver", Driver::Edge as _),
+			("geckodriver", Driver::Gecko as _),
+			("safaridriver", Driver::Safari as _),
 		];
 
-		// First up, if env vars like JBG_TEST_GECKODRIVER_REMOTE are present, use those
-		// to allow forcing usage of a particular remote driver.
-		for (driver, ctor) in drivers.iter() {
-			let env = format!("JBG_TEST_{}_REMOTE", driver.to_uppercase());
+		// Find out if the user is explicitely opting into a specific driver.
+		let mut driver = None;
+
+		for (key, ctor) in drivers.iter() {
+			let env = format!("JBG_TEST_{}_REMOTE", key.to_uppercase());
 			let url = match env::var(&env) {
 				Ok(var) => Url::parse(&var).context(format!("failed to parse `{env}`"))?,
-				Err(_) => continue,
+				Err(VarError::NotPresent) => continue,
+				Err(VarError::NotUnicode(_)) => bail!("unable to parse `{env}`"),
 			};
-			return Ok(ctor(Locate::Remote(url)));
+
+			if driver.replace(ctor(Location::Remote(url))).is_some() {
+				bail!("found multiple `JBG_TEST_` environment variables")
+			}
 		}
 
-		// Next, if env vars like JBG_TEST_GECKODRIVER are present, use those to
-		// allow forcing usage of a particular local driver.
-		for (driver, ctor) in drivers.iter() {
-			let env = driver.to_uppercase();
-			let path = match env::var_os(format!("JBG_TEST_{env}")) {
-				Some(path) => path,
-				None => continue,
+		for (key, ctor) in drivers.iter() {
+			let env = key.to_uppercase();
+			let Some(path) = env::var_os(format!("JBG_TEST_{env}")) else {
+				continue;
 			};
-			return Ok(ctor(Locate::Local((path.into(), env_args(driver)))));
+
+			if driver
+				.replace(ctor(Location::Local((path.into(), env_args(key)?))))
+				.is_some()
+			{
+				bail!("found multiple `JBG_TEST_` environment variables")
+			}
+		}
+
+		if let Some(driver) = driver {
+			return Ok(driver);
 		}
 
-		// Next, check PATH. If we can find any supported driver, use that by
-		// default.
+		// Otherwise pick a default by looking into the users `PATH`.
 		for path in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
-			let found = drivers.iter().find(|(name, _)| {
+			let Some((driver, ctor)) = drivers.iter().find(|(name, _)| {
 				path.join(name)
 					.with_extension(env::consts::EXE_EXTENSION)
 					.exists()
-			});
-			let (driver, ctor) = match found {
-				Some(p) => p,
-				None => continue,
+			}) else {
+				continue;
 			};
-			return Ok(ctor(Locate::Local((driver.into(), env_args(driver)))));
+
+			return Ok(ctor(Location::Local((driver.into(), env_args(driver)?))));
 		}
 
 		bail!(
-			"\
-failed to find a suitable WebDriver binary or remote running WebDriver to drive
-headless \
-			 testing; to configure the location of the webdriver binary you can use
-environment variables \
-			 like `GECKODRIVER=/path/to/geckodriver` or make sure that
-the binary is in `PATH`; to configure \
-			 the address of remote webdriver you can
-use environment variables like `GECKODRIVER_REMOTE=http://remote.host/`This \
-			 crate currently supports `geckodriver`, `chromedriver`, `safaridriver`, and
-`msedgedriver`, \
-			 although more driver support may be added! You can download these at:
-
-    * geckodriver \
-			 - https://github.com/mozilla/geckodriver/releases
-    * chromedriver - https://chromedriver.chromium.org/downloads* \
-			 msedgedriver - \
-			 https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/* safaridriver \
-			 - should be preinstalled on OSX
-
-If you're still having difficulty resolving this error, please feel free to open
-an issue against wasm-bindgen/js-bindgen!
-    "
+			"failed to find a suitable WebDriver binary or remote running WebDriver to drive headless testing; \
+			 to configure the location of the webdriver binary you can use environment variables \
+			 like `WBG_TEST_=/path/to/` or make sure that the binary is in `PATH`; \
+			 to configure the address of a remote WebDriver you can use environment variables \
+			 like `WBG_TEST__REMOTE=http://remote.host/`; \
+			 you can download currently supported drivers at:\n\
+			 * chromedriver - https://googlechromelabs.github.io/chrome-for-testing/\n\
+			 * geckodriver - https://github.com/mozilla/geckodriver/releases\n\
+			 * msedgedriver - https://developer.microsoft.com/microsoft-edge/tools/webdriver/\n\
+			 * safaridriver - pre-installed on MacOS"
 		)
 	}
+}
+
+struct ChildWrapper(Option);
+
+struct Inner {
+	child: Child,
+	stdout: (Sender<()>, Receiver>),
+	stderr: (Sender<()>, Receiver>),
+}
+
+impl Drop for ChildWrapper {
+	fn drop(&mut self) {
+		if let Some(mut inner) = self.0.take() {
+			let _ = inner.child.start_kill();
+		}
+	}
+}
+
+impl ChildWrapper {
+	fn new(mut child: Child) -> Self {
+		let (stdout_kill_tx, stdout_kill_rx) = oneshot::channel();
+		let (stdout_out_tx, stdout_out_rx) = oneshot::channel();
+		let mut stdout = child.stdout.take().unwrap();
+		tokio::spawn(async move {
+			let mut output = Vec::new();
+			tokio::select! {
+				_ = stdout_kill_rx => (),
+				_ = tokio::io::copy(&mut stdout, &mut output) => (),
+			}
+			let _ = stdout_out_tx.send(output);
+		});
+
+		let (stderr_kill_tx, stderr_kill_rx) = oneshot::channel();
+		let (stderr_out_tx, stderr_out_rx) = oneshot::channel();
+		let mut stderr = child.stderr.take().unwrap();
+		tokio::spawn(async move {
+			let mut output = Vec::new();
+			tokio::select! {
+				_ = stderr_kill_rx => (),
+				_ = tokio::io::copy(&mut stderr, &mut output) => (),
+			}
+			let _ = stderr_out_tx.send(output);
+		});
+
+		Self(Some(Inner {
+			child,
+			stdout: (stdout_kill_tx, stdout_out_rx),
+			stderr: (stderr_kill_tx, stderr_out_rx),
+		}))
+	}
 
-	pub fn location(&self) -> &Locate {
-		match self {
-			Self::Gecko(locate) => locate,
-			Self::Safari(locate) => locate,
-			Self::Chrome(locate) => locate,
-			Self::Edge(locate) => locate,
+	async fn wait(&mut self) -> tokio::io::Result {
+		self.0.as_mut().unwrap().child.wait().await
+	}
+
+	async fn output_error(mut self) {
+		let Inner {
+			mut child,
+			stdout,
+			stderr,
+		} = self.0.take().unwrap();
+
+		// Wait a moment in hope we can kill the child and get the complete output.
+		let _ = tokio::time::timeout(Duration::from_millis(100), child.kill()).await;
+
+		let _ = stdout.0.send(());
+		let stdout = stdout.1.await.unwrap();
+
+		if !stdout.is_empty() {
+			eprintln!(
+				"------ llvm-mc stdout ------\n{}",
+				String::from_utf8_lossy(&stdout)
+			);
+
+			if !stdout.ends_with(b"\n") {
+				eprintln!();
+			}
+		}
+
+		let _ = stderr.0.send(());
+		let stderr = stderr.1.await.unwrap();
+
+		if !stderr.is_empty() {
+			eprintln!(
+				"------ llvm-mc stderr ------\n{}",
+				String::from_utf8_lossy(&stderr)
+			);
+
+			if !stderr.ends_with(b"\n") {
+				eprintln!();
+			}
 		}
 	}
 }
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index 65b5c3a4..e51203f0 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -1,5 +1,6 @@
 mod driver;
 
+use std::env::VarError;
 use std::io::ErrorKind;
 use std::net::SocketAddr;
 use std::path::{Path, PathBuf};
@@ -212,7 +213,7 @@ impl WorkerKind {
 			"dedicated" => Self::Dedicated,
 			"shared" => Self::Shared,
 			"service" => Self::Service,
-			worker => bail!("unsupported worker: {worker}"),
+			worker => bail!("unrecognized worker: {worker}"),
 		})
 	}
 
@@ -229,19 +230,37 @@ impl RunnerConfig {
 	fn from_env() -> Result {
 		let worker = match env::var("JBG_TEST_WORKER") {
 			Ok(worker) => Some(WorkerKind::from_str(&worker)?),
-			Err(_) => None,
+			Err(VarError::NotPresent) => None,
+			Err(VarError::NotUnicode(_)) => bail!("unable to parse `JBG_TEST_WORKER`"),
 		};
 
-		let config = if let Ok(s) = env::var("JBG_TEST_RUNNER") {
-			match s.as_str() {
+		let config = match env::var("JBG_TEST_RUNNER") {
+			Ok(s) => match s.as_str() {
 				"browser" => Self::Browser { worker },
 				"server" => Self::Server { worker },
-				"node" => Self::Node,
 				"deno" => Self::Deno,
-				runner => bail!("unsupported runner: {runner}"),
+				"node" => Self::Node,
+				runner => bail!("unrecognized runner: {runner}"),
+			},
+			Err(VarError::NotPresent) => {
+				match env::var_os("PATH").and_then(|value| {
+					env::split_paths(&value).find_map(|path| {
+						["deno", "node"].into_iter().find(|name| {
+							path.join(name)
+								.with_extension(env::consts::EXE_EXTENSION)
+								.exists()
+						})
+					})
+				}) {
+					Some(name) => match name {
+						"deno" => Self::Deno,
+						"node" => Self::Node,
+						_ => unreachable!(),
+					},
+					None => bail!("unable to find a supported JS engine"),
+				}
 			}
-		} else {
-			Self::Node
+			Err(VarError::NotUnicode(_)) => bail!("unable to parse `JBG_TEST_RUNNER`"),
 		};
 
 		if worker.is_some()
@@ -308,19 +327,10 @@ impl Runner {
 	}
 
 	async fn run_browser(self, worker: Option) -> Result<()> {
-		let assets = BrowserAssets::new(
-			self.wasm_bytes,
-			&self.imports_path,
-			self.tests_json,
-			self.filtered_count,
-			self.no_capture,
-			worker.map(WorkerKind::as_str),
-		)?;
-		let server = HttpServer::start(assets, Self::server_address()?).await?;
-		let url = Self::browser_url(server.base_url.as_str());
+		let server = self.http_server(worker).await?;
 
 		let driver = Driver::find()?;
-		let guard = driver::launch_driver(&driver)?;
+		let guard = driver::launch_driver(&driver).await?;
 
 		let webdriver_json_path = env::var_os("JBG_TEST_WEBDRIVER_JSON").map(PathBuf::from);
 		let webdriver_json_path = webdriver_json_path
@@ -338,7 +348,7 @@ impl Runner {
 			.await
 			.context("failed to connect to WebDriver")?;
 
-		client.goto(&url).await?;
+		client.goto(&server.url).await?;
 
 		let print_output = || async {
 			let Ok(output) = client
@@ -380,37 +390,35 @@ impl Runner {
 	}
 
 	async fn run_server(self, worker: Option) -> Result<()> {
-		let assets = BrowserAssets::new(
-			self.wasm_bytes,
-			&self.imports_path,
-			self.tests_json,
-			self.filtered_count,
-			self.no_capture,
-			worker.map(WorkerKind::as_str),
-		)?;
-		let server = HttpServer::start(assets, Self::server_address()?).await?;
-		let url = Self::browser_url(server.base_url.as_str());
+		let server = self.http_server(worker).await?;
 
 		println!("open this URL in your browser to run tests:");
-		println!("{url}");
+		println!("{}", server.url);
 
 		loop {
 			server.wait_for_report().await;
 		}
 	}
 
-	fn server_address() -> Result> {
-		if let Ok(addr) = env::var("JBG_TEST_SERVER_ADDRESS") {
-			let addr =
-				SocketAddr::from_str(&addr).context("unable to parse `JBG_TEST_SERVER_ADDRESS`")?;
-			Ok(Some(addr))
-		} else {
-			Ok(None)
-		}
-	}
+	async fn http_server(self, worker: Option) -> Result {
+		let assets = BrowserAssets::new(
+			self.wasm_bytes,
+			&self.imports_path,
+			self.tests_json,
+			self.filtered_count,
+			self.no_capture,
+			worker.map(WorkerKind::as_str),
+		)?;
 
-	fn browser_url(base_url: &str) -> String {
-		format!("{base_url}/index.html")
+		let address = env::var_os("JBG_TEST_SERVER_ADDRESS")
+			.map(|var| {
+				var.into_string()
+					.ok()
+					.and_then(|string| SocketAddr::from_str(&string).ok())
+					.context("unable to parse `JBG_TEST_SERVER_ADDRESS`")
+			})
+			.transpose()?;
+		HttpServer::start(assets, address).await
 	}
 }
 
@@ -489,7 +497,7 @@ impl BrowserAssets {
 }
 
 struct HttpServer {
-	base_url: String,
+	url: String,
 	report_state: Arc,
 }
 
@@ -505,7 +513,11 @@ impl HttpServer {
 			.await
 			.context("failed to bind server")?;
 		let local_addr = listener.local_addr()?;
-		let base_url = format!("http://{}:{}", local_addr.ip(), local_addr.port());
+		let url = format!(
+			"http://{}:{}/index.html",
+			local_addr.ip(),
+			local_addr.port()
+		);
 
 		let assets = Arc::new(assets);
 		let report_state = Arc::new(ReportState {
@@ -525,10 +537,7 @@ impl HttpServer {
 			}
 		});
 
-		Ok(Self {
-			base_url,
-			report_state,
-		})
+		Ok(Self { url, report_state })
 	}
 
 	async fn wait_for_report(&self) -> Report {
diff --git a/host/ld-shared/src/lib.rs b/host/ld-shared/src/lib.rs
index 4b33a9ef..0b05494a 100644
--- a/host/ld-shared/src/lib.rs
+++ b/host/ld-shared/src/lib.rs
@@ -33,12 +33,8 @@ pub fn assembly_to_object(
 
 	let status = child.wait()?;
 
-	let mut child_stdout = child
-		.stdout
-		.ok_or_else(|| Error::other("`llvm-mc` process should have `stdout`"))?;
-
 	if status.success() {
-		io::copy(&mut child_stdout, output)?;
+		io::copy(&mut child.stdout.unwrap(), output)?;
 		Ok(())
 	} else {
 		eprintln!(
@@ -47,7 +43,7 @@ pub fn assembly_to_object(
 		);
 
 		let mut stdout = Vec::new();
-		child_stdout.read_to_end(&mut stdout)?;
+		child.stdout.unwrap().read_to_end(&mut stdout)?;
 
 		if !stdout.is_empty() {
 			eprintln!(
@@ -61,10 +57,7 @@ pub fn assembly_to_object(
 		}
 
 		let mut stderr = Vec::new();
-		child
-			.stderr
-			.ok_or_else(|| Error::other("`llvm-mc` process should have `stderr`"))?
-			.read_to_end(&mut stderr)?;
+		child.stderr.unwrap().read_to_end(&mut stderr)?;
 
 		if !stderr.is_empty() {
 			eprintln!(

From e1abb9d52a40487cf3ac3f999b7408d3bdda3097 Mon Sep 17 00:00:00 2001
From: Spxg 
Date: Mon, 2 Feb 2026 11:09:41 +0800
Subject: [PATCH 68/73] Clean up

---
 host/js-bindgen-runner/src/driver.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/host/js-bindgen-runner/src/driver.rs b/host/js-bindgen-runner/src/driver.rs
index 65c69ae0..b8d71113 100644
--- a/host/js-bindgen-runner/src/driver.rs
+++ b/host/js-bindgen-runner/src/driver.rs
@@ -316,7 +316,7 @@ impl ChildWrapper {
 
 		if !stdout.is_empty() {
 			eprintln!(
-				"------ llvm-mc stdout ------\n{}",
+				"------ webdriver stdout ------\n{}",
 				String::from_utf8_lossy(&stdout)
 			);
 
@@ -330,7 +330,7 @@ impl ChildWrapper {
 
 		if !stderr.is_empty() {
 			eprintln!(
-				"------ llvm-mc stderr ------\n{}",
+				"------ webdriver stderr ------\n{}",
 				String::from_utf8_lossy(&stderr)
 			);
 

From 560cf4340e7523b8b515e750ff2d8d5ac0ea749b Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Mon, 2 Feb 2026 08:56:42 +0100
Subject: [PATCH 69/73] Run Prettier

---
 host/js-bindgen-runner/js/browser-runner.mjs | 21 ++++++++++----------
 host/js-bindgen-runner/js/index.html         | 20 +++++++++----------
 host/js-bindgen-runner/js/worker-runner.mjs  |  9 +++------
 3 files changed, 23 insertions(+), 27 deletions(-)

diff --git a/host/js-bindgen-runner/js/browser-runner.mjs b/host/js-bindgen-runner/js/browser-runner.mjs
index d9c1ad6f..58aa4e73 100644
--- a/host/js-bindgen-runner/js/browser-runner.mjs
+++ b/host/js-bindgen-runner/js/browser-runner.mjs
@@ -11,15 +11,15 @@ export async function runBrowser({ noCapture, filtered, worker }) {
 
 	let result = worker
 		? await runInWorker({
-			noCapture,
-			filtered,
-			worker,
-			baseLog,
-			baseError,
-			baseWarn,
-			baseInfo,
-			baseDebug,
-		})
+				noCapture,
+				filtered,
+				worker,
+				baseLog,
+				baseError,
+				baseWarn,
+				baseInfo,
+				baseDebug,
+			})
 		: await runInWindow({ noCapture, filtered, consoleHook })
 
 	return result
@@ -72,7 +72,6 @@ async function runInWorker({
 	baseInfo,
 	baseDebug,
 }) {
-
 	function handleMessage(event) {
 		const data = event.data || {}
 		if (data.type === "user-output") {
@@ -187,7 +186,7 @@ async function runServiceWorker({ filtered, noCapture, handleMessage }) {
 		if (!sessionStorage.getItem("jbtest-sw-reload")) {
 			sessionStorage.setItem("jbtest-sw-reload", "1")
 			location.reload()
-			return new Promise(() => { })
+			return new Promise(() => {})
 		}
 		throw new Error("service worker not controlling the page")
 	}
diff --git a/host/js-bindgen-runner/js/index.html b/host/js-bindgen-runner/js/index.html
index d7328f54..9630e4c0 100644
--- a/host/js-bindgen-runner/js/index.html
+++ b/host/js-bindgen-runner/js/index.html
@@ -9,22 +9,22 @@
 	const noCapture = {no_capture_flag};
 	const worker = {worker};
 
-    window.reportLines = []
+	window.reportLines = []
 
-    window.takeReportLines = () => {{
-        const lines = window.reportLines
-        window.reportLines = []
-        return lines
-    }}
+	window.takeReportLines = () => {{
+		const lines = window.reportLines
+		window.reportLines = []
+		return lines
+	}}
 
-    window.pushReportLines = line => {{
-        window.reportLines.push(line)
-    }}
+	window.pushReportLines = line => {{
+		window.reportLines.push(line)
+	}}
 
 	const result = await runBrowser({{ filtered, noCapture, worker }});
 	await fetch("/report", {{
 		method: "POST",
 		headers: {{ "content-type": "application/json" }},
-	    body: JSON.stringify(result),
+		body: JSON.stringify(result),
 	}});
 
diff --git a/host/js-bindgen-runner/js/worker-runner.mjs b/host/js-bindgen-runner/js/worker-runner.mjs
index 0b4ad887..aa1e6b92 100644
--- a/host/js-bindgen-runner/js/worker-runner.mjs
+++ b/host/js-bindgen-runner/js/worker-runner.mjs
@@ -51,14 +51,11 @@ async function execute(port, { noCapture, filtered }) {
 }
 
 const isServiceWorker =
-	typeof ServiceWorkerGlobalScope !== "undefined" &&
-	self instanceof ServiceWorkerGlobalScope
+	typeof ServiceWorkerGlobalScope !== "undefined" && self instanceof ServiceWorkerGlobalScope
 const isSharedWorker =
-	typeof SharedWorkerGlobalScope !== "undefined" &&
-	self instanceof SharedWorkerGlobalScope
+	typeof SharedWorkerGlobalScope !== "undefined" && self instanceof SharedWorkerGlobalScope
 const isDedicatedWorker =
-	typeof DedicatedWorkerGlobalScope !== "undefined" &&
-	self instanceof DedicatedWorkerGlobalScope
+	typeof DedicatedWorkerGlobalScope !== "undefined" && self instanceof DedicatedWorkerGlobalScope
 
 if (isServiceWorker) {
 	self.addEventListener("message", event => {

From 9e978f83f4ea63c5c4af39301f8c768e26bb6a37 Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Mon, 2 Feb 2026 08:57:44 +0100
Subject: [PATCH 70/73] Move `js` Folder to `src`

---
 .../{ => src}/js/browser-runner.mjs                |  0
 .../{ => src}/js/console-hook.mjs                  |  0
 host/js-bindgen-runner/{ => src}/js/index.html     |  0
 .../js-bindgen-runner/{ => src}/js/node-runner.mjs |  0
 .../js-bindgen-runner/{ => src}/js/runner-core.mjs |  0
 host/js-bindgen-runner/{ => src}/js/shared.mjs     |  0
 .../{ => src}/js/worker-runner.mjs                 |  0
 host/js-bindgen-runner/src/main.rs                 | 14 +++++++-------
 8 files changed, 7 insertions(+), 7 deletions(-)
 rename host/js-bindgen-runner/{ => src}/js/browser-runner.mjs (100%)
 rename host/js-bindgen-runner/{ => src}/js/console-hook.mjs (100%)
 rename host/js-bindgen-runner/{ => src}/js/index.html (100%)
 rename host/js-bindgen-runner/{ => src}/js/node-runner.mjs (100%)
 rename host/js-bindgen-runner/{ => src}/js/runner-core.mjs (100%)
 rename host/js-bindgen-runner/{ => src}/js/shared.mjs (100%)
 rename host/js-bindgen-runner/{ => src}/js/worker-runner.mjs (100%)

diff --git a/host/js-bindgen-runner/js/browser-runner.mjs b/host/js-bindgen-runner/src/js/browser-runner.mjs
similarity index 100%
rename from host/js-bindgen-runner/js/browser-runner.mjs
rename to host/js-bindgen-runner/src/js/browser-runner.mjs
diff --git a/host/js-bindgen-runner/js/console-hook.mjs b/host/js-bindgen-runner/src/js/console-hook.mjs
similarity index 100%
rename from host/js-bindgen-runner/js/console-hook.mjs
rename to host/js-bindgen-runner/src/js/console-hook.mjs
diff --git a/host/js-bindgen-runner/js/index.html b/host/js-bindgen-runner/src/js/index.html
similarity index 100%
rename from host/js-bindgen-runner/js/index.html
rename to host/js-bindgen-runner/src/js/index.html
diff --git a/host/js-bindgen-runner/js/node-runner.mjs b/host/js-bindgen-runner/src/js/node-runner.mjs
similarity index 100%
rename from host/js-bindgen-runner/js/node-runner.mjs
rename to host/js-bindgen-runner/src/js/node-runner.mjs
diff --git a/host/js-bindgen-runner/js/runner-core.mjs b/host/js-bindgen-runner/src/js/runner-core.mjs
similarity index 100%
rename from host/js-bindgen-runner/js/runner-core.mjs
rename to host/js-bindgen-runner/src/js/runner-core.mjs
diff --git a/host/js-bindgen-runner/js/shared.mjs b/host/js-bindgen-runner/src/js/shared.mjs
similarity index 100%
rename from host/js-bindgen-runner/js/shared.mjs
rename to host/js-bindgen-runner/src/js/shared.mjs
diff --git a/host/js-bindgen-runner/js/worker-runner.mjs b/host/js-bindgen-runner/src/js/worker-runner.mjs
similarity index 100%
rename from host/js-bindgen-runner/js/worker-runner.mjs
rename to host/js-bindgen-runner/src/js/worker-runner.mjs
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index e51203f0..ba83be7d 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -31,12 +31,12 @@ use wasmparser::{Parser as WasmParser, Payload};
 
 use crate::driver::Driver;
 
-const NODE_RUNNER: &str = include_str!("../js/node-runner.mjs");
-const BROWSER_RUNNER: &str = include_str!("../js/browser-runner.mjs");
-const RUNNER_CORE: &str = include_str!("../js/runner-core.mjs");
-const SHARED_JS: &str = include_str!("../js/shared.mjs");
-const WORKER_RUNNER: &str = include_str!("../js/worker-runner.mjs");
-const CONSOLE_HOOK: &str = include_str!("../js/console-hook.mjs");
+const NODE_RUNNER: &str = include_str!("js/node-runner.mjs");
+const BROWSER_RUNNER: &str = include_str!("js/browser-runner.mjs");
+const RUNNER_CORE: &str = include_str!("js/runner-core.mjs");
+const SHARED_JS: &str = include_str!("js/shared.mjs");
+const WORKER_RUNNER: &str = include_str!("js/worker-runner.mjs");
+const CONSOLE_HOOK: &str = include_str!("js/console-hook.mjs");
 
 /// Possible values for the `--format` option.
 #[derive(Clone, Copy, ValueEnum)]
@@ -477,7 +477,7 @@ impl BrowserAssets {
 		let import_js = ReadFile::new(imports_path)?;
 
 		let index_html = format!(
-			include_str!("../js/index.html"),
+			include_str!("js/index.html"),
 			filtered_count = filtered_count,
 			no_capture_flag = if no_capture { "true" } else { "false" },
 			worker = if let Some(worker) = worker {

From 1a9c9843c5d6d0303055ce3bccac67d67c848c10 Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Mon, 2 Feb 2026 09:10:13 +0100
Subject: [PATCH 71/73] Move and Rename Some Stuff

---
 TEST.md                                       |  16 +-
 .../js/{node-runner.mjs => nodejs-runner.mjs} |   0
 host/js-bindgen-runner/src/main.rs            |  50 +--
 .../src/{driver.rs => web_driver.rs}          | 298 +++++++++---------
 4 files changed, 182 insertions(+), 182 deletions(-)
 rename host/js-bindgen-runner/src/js/{node-runner.mjs => nodejs-runner.mjs} (100%)
 rename host/js-bindgen-runner/src/{driver.rs => web_driver.rs} (69%)

diff --git a/TEST.md b/TEST.md
index 97c44c32..37e728f5 100644
--- a/TEST.md
+++ b/TEST.md
@@ -27,7 +27,7 @@ fn test_should_panic() {
 }
 ```
 
-Wasm tests: Node runner (default):
+Wasm tests: Node.js runner (default):
 
 ```sh
 cargo test --target wasm32-unknown-unknown
@@ -47,14 +47,14 @@ JBG_TEST_RUNNER=server cargo test --target wasm32-unknown-unknown
 
 Runner options:
 
-- `JBG_TEST_RUNNER=node` (run in nodejs, set by default)
-- `JBG_TEST_RUNNER=deno` (run in deno)
+- `JBG_TEST_RUNNER=nodejs` (run in Node.js)
+- `JBG_TEST_RUNNER=deno` (run in Deno)
 
-- `JBG_TEST_RUNNER=browser` (run in headless browser, auto detect driver)
-- `JBG_TEST_GECKODRIVER=` (use firefix)
-- `JBG_TEST_CHROMEDRIVER=` (use chrome)
-- `JBG_TEST_MSEDGEDRIVER=` (use edge)
-- `JBG_TEST_WEBDRIVER_JSON` (set driver conf)
+- `JBG_TEST_RUNNER=browser` (run in headless browser, auto detect WebDriver)
+- `JBG_TEST_GECKODRIVER=` (use Firefox)
+- `JBG_TEST_CHROMEDRIVER=` (use Chrome)
+- `JBG_TEST_MSEDGEDRIVER=` (use Edge)
+- `JBG_TEST_WEBDRIVER_JSON` (set WebDriver conf)
 - `JBG_TEST_WORKER=dedicated|shared|service`
 
 - `JBG_TEST_RUNNER=server` (serve browser runner and print URL)
diff --git a/host/js-bindgen-runner/src/js/node-runner.mjs b/host/js-bindgen-runner/src/js/nodejs-runner.mjs
similarity index 100%
rename from host/js-bindgen-runner/src/js/node-runner.mjs
rename to host/js-bindgen-runner/src/js/nodejs-runner.mjs
diff --git a/host/js-bindgen-runner/src/main.rs b/host/js-bindgen-runner/src/main.rs
index ba83be7d..7a15ee31 100644
--- a/host/js-bindgen-runner/src/main.rs
+++ b/host/js-bindgen-runner/src/main.rs
@@ -1,4 +1,4 @@
-mod driver;
+mod web_driver;
 
 use std::env::VarError;
 use std::io::ErrorKind;
@@ -18,7 +18,6 @@ use axum::response::Response;
 use axum::routing::{get, post};
 use axum::{Json, Router};
 use clap::{Parser, ValueEnum};
-use driver::Capabilities;
 use fantoccini::ClientBuilder;
 use js_bindgen_shared::ReadFile;
 use serde::{Serialize, Serializer};
@@ -28,23 +27,17 @@ use tokio::runtime::Runtime;
 use tokio::sync::{Mutex, Notify};
 use tokio::time::interval;
 use wasmparser::{Parser as WasmParser, Payload};
+use web_driver::Capabilities;
 
-use crate::driver::Driver;
+use crate::web_driver::WebDriver;
 
-const NODE_RUNNER: &str = include_str!("js/node-runner.mjs");
+const NODEJS_RUNNER: &str = include_str!("js/nodejs-runner.mjs");
 const BROWSER_RUNNER: &str = include_str!("js/browser-runner.mjs");
 const RUNNER_CORE: &str = include_str!("js/runner-core.mjs");
 const SHARED_JS: &str = include_str!("js/shared.mjs");
 const WORKER_RUNNER: &str = include_str!("js/worker-runner.mjs");
 const CONSOLE_HOOK: &str = include_str!("js/console-hook.mjs");
 
-/// Possible values for the `--format` option.
-#[derive(Clone, Copy, ValueEnum)]
-enum FormatSetting {
-	/// Display one character per test
-	Terse,
-}
-
 #[derive(Parser)]
 #[command(name = "js-bindgen-runner", version, about, long_about = None)]
 struct Cli {
@@ -73,6 +66,13 @@ struct Cli {
 	filter: Vec,
 }
 
+/// Possible values for the `--format` option.
+#[derive(Clone, Copy, ValueEnum)]
+enum FormatSetting {
+	/// Display one character per test
+	Terse,
+}
+
 #[derive(Debug, Serialize)]
 #[serde(rename_all = "camelCase")]
 struct TestEntry {
@@ -156,7 +156,7 @@ fn main() -> Result<()> {
 	};
 
 	match RunnerConfig::from_env()? {
-		RunnerConfig::Node => runner.run_node()?,
+		RunnerConfig::NodeJs => runner.run_node_js()?,
 		RunnerConfig::Deno => runner.run_deno()?,
 		RunnerConfig::Browser { worker } => Runtime::new()?.block_on(runner.run_browser(worker))?,
 		RunnerConfig::Server { worker } => Runtime::new()?.block_on(runner.run_server(worker))?,
@@ -191,7 +191,7 @@ impl TestArgs {
 
 #[derive(Clone, Copy, Debug)]
 enum RunnerConfig {
-	Node,
+	NodeJs,
 	Deno,
 	Browser { worker: Option },
 	Server { worker: Option },
@@ -239,7 +239,7 @@ impl RunnerConfig {
 				"browser" => Self::Browser { worker },
 				"server" => Self::Server { worker },
 				"deno" => Self::Deno,
-				"node" => Self::Node,
+				"nodejs" => Self::NodeJs,
 				runner => bail!("unrecognized runner: {runner}"),
 			},
 			Err(VarError::NotPresent) => {
@@ -254,7 +254,7 @@ impl RunnerConfig {
 				}) {
 					Some(name) => match name {
 						"deno" => Self::Deno,
-						"node" => Self::Node,
+						"node" => Self::NodeJs,
 						_ => unreachable!(),
 					},
 					None => bail!("unable to find a supported JS engine"),
@@ -264,7 +264,7 @@ impl RunnerConfig {
 		};
 
 		if worker.is_some()
-			&& let Self::Node { .. } | Self::Deno { .. } = config
+			&& let Self::NodeJs { .. } | Self::Deno { .. } = config
 		{
 			eprintln!(
 				"Only browser and server runners support worker types; `JBG_TEST_WORKER` is \
@@ -286,8 +286,8 @@ struct Runner {
 }
 
 impl Runner {
-	fn run_node(self) -> Result<()> {
-		let node_dir = NodeDir::new(&self.tests_json)?;
+	fn run_node_js(self) -> Result<()> {
+		let node_dir = NodeJsDir::new(&self.tests_json)?;
 
 		let status = Command::new("node")
 			.arg(node_dir.runner)
@@ -306,7 +306,7 @@ impl Runner {
 	}
 
 	fn run_deno(self) -> Result<()> {
-		let node_dir = NodeDir::new(&self.tests_json)?;
+		let node_dir = NodeJsDir::new(&self.tests_json)?;
 
 		let status = Command::new("deno")
 			.arg("run")
@@ -329,8 +329,8 @@ impl Runner {
 	async fn run_browser(self, worker: Option) -> Result<()> {
 		let server = self.http_server(worker).await?;
 
-		let driver = Driver::find()?;
-		let guard = driver::launch_driver(&driver).await?;
+		let driver = WebDriver::find()?;
+		let guard = driver.launch().await?;
 
 		let webdriver_json_path = env::var_os("JBG_TEST_WEBDRIVER_JSON").map(PathBuf::from);
 		let webdriver_json_path = webdriver_json_path
@@ -343,7 +343,7 @@ impl Runner {
 		};
 
 		let client = ClientBuilder::rustls()?
-			.capabilities(driver::capabilities(&driver, capabilities)?)
+			.capabilities(web_driver::capabilities(&driver, capabilities)?)
 			.connect(guard.url.as_str())
 			.await
 			.context("failed to connect to WebDriver")?;
@@ -422,17 +422,17 @@ impl Runner {
 	}
 }
 
-struct NodeDir {
+struct NodeJsDir {
 	_guard: TempDir,
 	runner: PathBuf,
 	tests: PathBuf,
 }
 
-impl NodeDir {
+impl NodeJsDir {
 	fn new(tests_json: &str) -> Result {
 		let dir = tempfile::tempdir()?;
 		let runner_path = dir.path().join("runner.mjs");
-		fs::write(&runner_path, NODE_RUNNER)?;
+		fs::write(&runner_path, NODEJS_RUNNER)?;
 		let tests_path = dir.path().join("tests.json");
 		fs::write(&tests_path, tests_json)?;
 
diff --git a/host/js-bindgen-runner/src/driver.rs b/host/js-bindgen-runner/src/web_driver.rs
similarity index 69%
rename from host/js-bindgen-runner/src/driver.rs
rename to host/js-bindgen-runner/src/web_driver.rs
index b8d71113..f01db642 100644
--- a/host/js-bindgen-runner/src/driver.rs
+++ b/host/js-bindgen-runner/src/web_driver.rs
@@ -13,133 +13,11 @@ use tokio::sync::oneshot::{self, Receiver, Sender};
 use tokio::time;
 use url::Url;
 
-pub struct DriverGuard {
-	pub url: Url,
-	_child: Option,
-}
-
-pub async fn launch_driver(driver: &Driver) -> Result {
-	let locate = match driver {
-		Driver::Chrome(locate) => locate,
-		Driver::Edge(locate) => locate,
-		Driver::Gecko(locate) => locate,
-		Driver::Safari(locate) => locate,
-	};
-
-	let guard = match locate {
-		Location::Remote(url) => DriverGuard {
-			url: url.clone(),
-			_child: None,
-		},
-		Location::Local((path, args)) => {
-			// Wait for the driver to come online and bind its port before we try to
-			// connect to it.
-			let start = Instant::now();
-			const MAX: Duration = Duration::from_secs(5);
-
-			let (driver_addr, child) = loop {
-				// Get a random open port to allow test runners to run in parallel.
-				let driver_addr = TcpListener::bind("127.0.0.1:0").await?.local_addr()?;
-				let child = Command::new(path)
-					.stdout(Stdio::piped())
-					.stderr(Stdio::piped())
-					.args(args)
-					.arg(format!("--port={}", driver_addr.port()))
-					.spawn()?;
-				let mut child = ChildWrapper::new(child);
-
-				let limit = time::sleep(MAX - start.elapsed());
-
-				tokio::select! {
-					_ = limit => {
-						child.output_error().await;
-						bail!("failed to bind driver port in timeout duration");
-					},
-					_ = TcpStream::connect(driver_addr) => break (driver_addr, child),
-					result = child.wait() => {
-						match result {
-							Ok(status) => if status.success() {
-								eprintln!("WebDriver exited prematurely with success");
-							} else {
-								eprintln!("WebDriver failed with status: {status}");
-							}
-							Err(error) => eprintln!("WebDriver failed with error: {error}"),
-						}
-
-						child.output_error().await;
-
-						eprintln!("failed to start driver, trying again ...");
-
-						// Back off. If something is really wrong we don't want to re-try in a
-						// hot loop.
-						time::sleep(Duration::from_millis(100)).await;
-					}
-				};
-			};
-
-			DriverGuard {
-				url: Url::parse(&format!("http://{driver_addr}"))?,
-				_child: Some(child),
-			}
-		}
-	};
-	Ok(guard)
-}
-
-/// Options that can use to customize and configure a WebDriver session.
-pub type Capabilities = Map;
-
-pub fn capabilities(driver: &Driver, mut cap: Capabilities) -> Result {
-	match driver {
-		Driver::Gecko(_) => cap
-			.entry("moz:firefoxOptions".to_string())
-			.or_insert_with(|| Value::Object(serde_json::Map::new()))
-			.as_object_mut()
-			.expect("moz:firefoxOptions wasn't a JSON object")
-			.entry("args".to_string())
-			.or_insert_with(|| Value::Array(vec![]))
-			.as_array_mut()
-			.expect("args wasn't a JSON array")
-			.extend(vec![Value::String("-headless".to_string())]),
-		Driver::Safari(_) => (),
-		Driver::Chrome(_) => {
-			cap.entry("goog:chromeOptions".to_string())
-				.or_insert_with(|| Value::Object(serde_json::Map::new()))
-				.as_object_mut()
-				.expect("goog:chromeOptions wasn't a JSON object")
-				.entry("args".to_string())
-				.or_insert_with(|| Value::Array(vec![]))
-				.as_array_mut()
-				.expect("args wasn't a JSON array")
-				.extend(vec![
-					Value::String("headless".to_string()),
-					// See https://stackoverflow.com/questions/50642308/
-					// for what this funky `disable-dev-shm-usage`
-					// option is
-					Value::String("disable-dev-shm-usage".to_string()),
-					Value::String("no-sandbox".to_string()),
-				])
-		}
-		Driver::Edge(_) => {
-			cap.entry("ms:edgeOptions".to_string())
-				.or_insert_with(|| Value::Object(serde_json::Map::new()))
-				.as_object_mut()
-				.expect("ms:edgeOptions wasn't a JSON object")
-				.entry("args".to_string())
-				.or_insert_with(|| Value::Array(vec![]))
-				.as_array_mut()
-				.expect("args wasn't a JSON array")
-				.extend(vec![
-					Value::String("headless".to_string()),
-					// See https://stackoverflow.com/questions/50642308/
-					// for what this funky `disable-dev-shm-usage`
-					// option is
-					Value::String("disable-dev-shm-usage".to_string()),
-					Value::String("no-sandbox".to_string()),
-				])
-		}
-	}
-	Ok(cap)
+pub enum WebDriver {
+	Chrome(Location),
+	Edge(Location),
+	Gecko(Location),
+	Safari(Location),
 }
 
 pub enum Location {
@@ -147,19 +25,12 @@ pub enum Location {
 	Remote(Url),
 }
 
-pub enum Driver {
-	Chrome(Location),
-	Edge(Location),
-	Gecko(Location),
-	Safari(Location),
-}
-
-impl Driver {
+impl WebDriver {
 	/// Attempts to find a WebDriver.
 	///
-	/// An explicitly set WebDriver is searched for in `JBG_TEST_` and
-	/// `JBG_TEST__REMOTE`. If not found we look for the first WebDriver
-	/// in `PATH`.
+	/// An explicitly set WebDriver is searched for in `JBG_TEST_`
+	/// and `JBG_TEST__REMOTE`. If not found we look for the first
+	/// WebDriver in `PATH`.
 	pub fn find() -> Result {
 		fn env_args(name: &str) -> Result> {
 			let key = format!("JBG_TEST_{}_ARGS", name.to_uppercase());
@@ -180,13 +51,13 @@ impl Driver {
 		}
 
 		let drivers = [
-			("chromedriver", Driver::Chrome as fn(Location) -> Self),
-			("msedgedriver", Driver::Edge as _),
-			("geckodriver", Driver::Gecko as _),
-			("safaridriver", Driver::Safari as _),
+			("chromedriver", Self::Chrome as fn(Location) -> Self),
+			("msedgedriver", Self::Edge as _),
+			("geckodriver", Self::Gecko as _),
+			("safaridriver", Self::Safari as _),
 		];
 
-		// Find out if the user is explicitely opting into a specific driver.
+		// Find out if the user is explicitely opting into a specific WebDriver.
 		let mut driver = None;
 
 		for (key, ctor) in drivers.iter() {
@@ -198,7 +69,7 @@ impl Driver {
 			};
 
 			if driver.replace(ctor(Location::Remote(url))).is_some() {
-				bail!("found multiple `JBG_TEST_` environment variables")
+				bail!("found multiple `JBG_TEST_` environment variables")
 			}
 		}
 
@@ -212,7 +83,7 @@ impl Driver {
 				.replace(ctor(Location::Local((path.into(), env_args(key)?))))
 				.is_some()
 			{
-				bail!("found multiple `JBG_TEST_` environment variables")
+				bail!("found multiple `JBG_TEST_` environment variables")
 			}
 		}
 
@@ -236,9 +107,9 @@ impl Driver {
 		bail!(
 			"failed to find a suitable WebDriver binary or remote running WebDriver to drive headless testing; \
 			 to configure the location of the webdriver binary you can use environment variables \
-			 like `WBG_TEST_=/path/to/` or make sure that the binary is in `PATH`; \
+			 like `WBG_TEST_=/path/to/` or make sure that the binary is in `PATH`; \
 			 to configure the address of a remote WebDriver you can use environment variables \
-			 like `WBG_TEST__REMOTE=http://remote.host/`; \
+			 like `WBG_TEST__REMOTE=http://remote.host/`; \
 			 you can download currently supported drivers at:\n\
 			 * chromedriver - https://googlechromelabs.github.io/chrome-for-testing/\n\
 			 * geckodriver - https://github.com/mozilla/geckodriver/releases\n\
@@ -246,6 +117,135 @@ impl Driver {
 			 * safaridriver - pre-installed on MacOS"
 		)
 	}
+
+	pub async fn launch(&self) -> Result {
+		let locate = match self {
+			Self::Chrome(locate) => locate,
+			Self::Edge(locate) => locate,
+			Self::Gecko(locate) => locate,
+			Self::Safari(locate) => locate,
+		};
+
+		let guard = match locate {
+			Location::Remote(url) => WebDriverGuard {
+				url: url.clone(),
+				_child: None,
+			},
+			Location::Local((path, args)) => {
+				// Wait for the WebDriver to come online and bind its port before we try to
+				// connect to it.
+				let start = Instant::now();
+				const MAX: Duration = Duration::from_secs(5);
+
+				let (driver_addr, child) = loop {
+					// Get a random open port to allow test runners to run in parallel.
+					let driver_addr = TcpListener::bind("127.0.0.1:0").await?.local_addr()?;
+					let child = Command::new(path)
+						.stdout(Stdio::piped())
+						.stderr(Stdio::piped())
+						.args(args)
+						.arg(format!("--port={}", driver_addr.port()))
+						.spawn()?;
+					let mut child = ChildWrapper::new(child);
+
+					let limit = time::sleep(MAX - start.elapsed());
+
+					tokio::select! {
+						_ = limit => {
+							child.output_error().await;
+							bail!("failed to bind WebDriver port in timeout duration");
+						},
+						_ = TcpStream::connect(driver_addr) => break (driver_addr, child),
+						result = child.wait() => {
+							match result {
+								Ok(status) => if status.success() {
+									eprintln!("WebDriver exited prematurely with success");
+								} else {
+									eprintln!("WebDriver failed with status: {status}");
+								}
+								Err(error) => eprintln!("WebDriver failed with error: {error}"),
+							}
+
+							child.output_error().await;
+
+							eprintln!("failed to start WebDriver, trying again ...");
+
+							// Back off. If something is really wrong we don't want to re-try in a
+							// hot loop.
+							time::sleep(Duration::from_millis(100)).await;
+						}
+					};
+				};
+
+				WebDriverGuard {
+					url: Url::parse(&format!("http://{driver_addr}"))?,
+					_child: Some(child),
+				}
+			}
+		};
+		Ok(guard)
+	}
+}
+
+pub struct WebDriverGuard {
+	pub url: Url,
+	_child: Option,
+}
+
+/// Options that can use to customize and configure a WebDriver session.
+pub type Capabilities = Map;
+
+pub fn capabilities(driver: &WebDriver, mut cap: Capabilities) -> Result {
+	match driver {
+		WebDriver::Chrome(_) => {
+			cap.entry("goog:chromeOptions".to_string())
+				.or_insert_with(|| Value::Object(serde_json::Map::new()))
+				.as_object_mut()
+				.expect("goog:chromeOptions wasn't a JSON object")
+				.entry("args".to_string())
+				.or_insert_with(|| Value::Array(vec![]))
+				.as_array_mut()
+				.expect("args wasn't a JSON array")
+				.extend(vec![
+					Value::String("headless".to_string()),
+					// See https://stackoverflow.com/questions/50642308/
+					// for what this funky `disable-dev-shm-usage`
+					// option is
+					Value::String("disable-dev-shm-usage".to_string()),
+					Value::String("no-sandbox".to_string()),
+				])
+		}
+		WebDriver::Edge(_) => {
+			cap.entry("ms:edgeOptions".to_string())
+				.or_insert_with(|| Value::Object(serde_json::Map::new()))
+				.as_object_mut()
+				.expect("ms:edgeOptions wasn't a JSON object")
+				.entry("args".to_string())
+				.or_insert_with(|| Value::Array(vec![]))
+				.as_array_mut()
+				.expect("args wasn't a JSON array")
+				.extend(vec![
+					Value::String("headless".to_string()),
+					// See https://stackoverflow.com/questions/50642308/
+					// for what this funky `disable-dev-shm-usage`
+					// option is
+					Value::String("disable-dev-shm-usage".to_string()),
+					Value::String("no-sandbox".to_string()),
+				])
+		}
+		WebDriver::Gecko(_) => cap
+			.entry("moz:firefoxOptions".to_string())
+			.or_insert_with(|| Value::Object(serde_json::Map::new()))
+			.as_object_mut()
+			.expect("moz:firefoxOptions wasn't a JSON object")
+			.entry("args".to_string())
+			.or_insert_with(|| Value::Array(vec![]))
+			.as_array_mut()
+			.expect("args wasn't a JSON array")
+			.extend(vec![Value::String("-headless".to_string())]),
+		WebDriver::Safari(_) => (),
+	}
+	Ok(cap)
 }
 
 struct ChildWrapper(Option);
@@ -316,7 +316,7 @@ impl ChildWrapper {
 
 		if !stdout.is_empty() {
 			eprintln!(
-				"------ webdriver stdout ------\n{}",
+				"------ WebDriver stdout ------\n{}",
 				String::from_utf8_lossy(&stdout)
 			);
 
@@ -330,7 +330,7 @@ impl ChildWrapper {
 
 		if !stderr.is_empty() {
 			eprintln!(
-				"------ webdriver stderr ------\n{}",
+				"------ WebDriver stderr ------\n{}",
 				String::from_utf8_lossy(&stderr)
 			);
 

From 7cb347cebeea361c26b7b2861f686cb49e600f29 Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Mon, 2 Feb 2026 09:24:52 +0100
Subject: [PATCH 72/73] Fix Windows Tests

---
 .gitattributes                     | 2 ++
 host/js-sys-macro/src/tests/mod.rs | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)
 create mode 100644 .gitattributes

diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..9dcb4766
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# See https://github.com/oli-obk/ui_test/issues/177.
+* text=auto eol=lf
diff --git a/host/js-sys-macro/src/tests/mod.rs b/host/js-sys-macro/src/tests/mod.rs
index 22a706f2..bd143b64 100644
--- a/host/js-sys-macro/src/tests/mod.rs
+++ b/host/js-sys-macro/src/tests/mod.rs
@@ -54,7 +54,7 @@ fn inner(tmp: &Path, source: &str) -> Result<(String, String)> {
 		resolver = "2"
 
 		[dependencies]
-		js-sys = {{ path = "{}" }}
+		js-sys = {{ path = '{}' }}
 		"#,
 		js_sys.display(),
 	);

From 1151c3e46548e3cda22e35becc274c190acf706e Mon Sep 17 00:00:00 2001
From: daxpedda 
Date: Mon, 2 Feb 2026 12:02:50 +0100
Subject: [PATCH 73/73] Fix MacOS CI

---
 host/js-sys-macro/src/tests/mod.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/host/js-sys-macro/src/tests/mod.rs b/host/js-sys-macro/src/tests/mod.rs
index bd143b64..c50f26bb 100644
--- a/host/js-sys-macro/src/tests/mod.rs
+++ b/host/js-sys-macro/src/tests/mod.rs
@@ -145,7 +145,7 @@ fn inner(tmp: &Path, source: &str) -> Result<(String, String)> {
 			filenames,
 			..
 		}) = message?
-			&& src_path == src
+			&& src_path.canonicalize()? == src.canonicalize()?
 		{
 			for filename in filenames {
 				js_bindgen_ld_shared::ld_input_parser(filename.as_os_str(), |_, data| {