Skip to main content

alef_e2e/codegen/
wasm.rs

1//! WebAssembly e2e test generator using vitest.
2//!
3//! Reuses the TypeScript test renderer for both HTTP and non-HTTP fixtures,
4//! configured with the `@kreuzberg/wasm` (or equivalent) package as the import
5//! path and `wasm` as the language key for skip/override resolution. Adds
6//! wasm-specific scaffolding: a `setup.ts` chdir to `test_documents/` so
7//! file_path fixtures resolve, and a `globalSetup.ts` that spawns the
8//! mock-server for HTTP fixtures. The wasm-pack `--target nodejs` CJS bundle
9//! initializes synchronously and does not require vite-plugin-wasm.
10
11use crate::config::E2eConfig;
12use crate::escape::sanitize_filename;
13use crate::field_access::FieldResolver;
14use crate::fixture::{Fixture, FixtureGroup};
15use alef_core::backend::GeneratedFile;
16use alef_core::config::ResolvedCrateConfig;
17use alef_core::hash::{self, CommentStyle};
18use alef_core::template_versions as tv;
19use anyhow::Result;
20use std::fmt::Write as FmtWrite;
21use std::path::PathBuf;
22
23use super::E2eCodegen;
24
25/// WebAssembly e2e code generator.
26pub struct WasmCodegen;
27
28impl E2eCodegen for WasmCodegen {
29    fn generate(
30        &self,
31        groups: &[FixtureGroup],
32        e2e_config: &E2eConfig,
33        config: &ResolvedCrateConfig,
34        type_defs: &[alef_core::ir::TypeDef],
35        enums: &[alef_core::ir::EnumDef],
36    ) -> Result<Vec<GeneratedFile>> {
37        let lang = self.language_name();
38        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
39        let tests_base = output_base.join("tests");
40
41        let mut files = Vec::new();
42
43        // Resolve call config with wasm-specific overrides.
44        let call = &e2e_config.call;
45        let overrides = call.overrides.get(lang);
46        let module_path = overrides
47            .and_then(|o| o.module.as_ref())
48            .cloned()
49            .unwrap_or_else(|| call.module.clone());
50        let function_name = overrides
51            .and_then(|o| o.function.as_ref())
52            .cloned()
53            .unwrap_or_else(|| snake_to_camel(&call.function));
54        let client_factory = overrides.and_then(|o| o.client_factory.as_deref());
55
56        // Resolve package config — defaults to a co-located pkg/ directory shipped
57        // by `wasm-pack build` next to the wasm crate.
58        // When `[crates.output] wasm` is set explicitly, derive the pkg path from
59        // that value so that renamed WASM crates resolve correctly without any
60        // hardcoded special cases.
61        let wasm_pkg = e2e_config.resolve_package("wasm");
62        // `pkg_path_is_explicit` distinguishes "user told us exactly where the
63        // npm-consumable package lives" from "fall back to the default
64        // wasm-pack output directory". The render below appends `/nodejs` only
65        // for the fallback case (`wasm_crate_path()` returns the crate's
66        // `pkg/` dir, whose npm-consumable subpackage is at `pkg/nodejs/`).
67        // For an explicit path the user is responsible for pointing at a
68        // directory that already has a valid `package.json`.
69        let (pkg_path, pkg_path_is_explicit) = match wasm_pkg.as_ref().and_then(|p| p.path.as_ref()) {
70            Some(p) => (p.clone(), true),
71            None => (config.wasm_crate_path(), false),
72        };
73        let pkg_name = wasm_pkg
74            .as_ref()
75            .and_then(|p| p.name.as_ref())
76            .cloned()
77            .unwrap_or_else(|| {
78                // Default: derive from WASM crate name (config.name + "-wasm")
79                // wasm-pack transforms the crate name to the package name by replacing
80                // dashes with the crate separator in Cargo (e.g., kreuzberg-wasm -> kreuzberg_wasm).
81                // However, the published npm package might use the module name, which is typically
82                // the crate name without "-wasm". Fall back to the module path.
83                module_path.clone()
84            });
85        let pkg_version = wasm_pkg
86            .as_ref()
87            .and_then(|p| p.version.as_ref())
88            .cloned()
89            .or_else(|| config.resolved_version())
90            .unwrap_or_else(|| "0.1.0".to_string());
91
92        // Determine which auxiliary scaffolding files we need based on the active
93        // fixture set. Doing this once up front lets us emit a self-contained vitest
94        // config that wires only the setup files we'll actually generate.
95        let active_per_group: Vec<Vec<&Fixture>> = groups
96            .iter()
97            .map(|group| {
98                group
99                    .fixtures
100                    .iter()
101                    .filter(|f| super::should_include_fixture(f, lang, e2e_config))
102                    // Honor per-call `skip_languages`: when the resolved call's
103                    // `skip_languages` contains `wasm`, the wasm binding doesn't
104                    // export that function and any test file referencing it
105                    // would fail TS resolution. Drop the fixture entirely.
106                    .filter(|f| {
107                        let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
108                        !cc.skip_languages.iter().any(|l| l == lang)
109                    })
110                    .filter(|f| {
111                        // Node fetch (undici) rejects pre-set Content-Length that
112                        // doesn't match the real body length — skip fixtures that
113                        // intentionally send a mismatched header.
114                        f.http.as_ref().is_none_or(|h| {
115                            !h.request
116                                .headers
117                                .iter()
118                                .any(|(k, _)| k.eq_ignore_ascii_case("content-length"))
119                        })
120                    })
121                    .filter(|f| {
122                        // Node fetch only supports a fixed set of HTTP methods;
123                        // TRACE and CONNECT throw before reaching the server.
124                        f.http.as_ref().is_none_or(|h| {
125                            let m = h.request.method.to_ascii_uppercase();
126                            m != "TRACE" && m != "CONNECT"
127                        })
128                    })
129                    .collect()
130            })
131            .collect();
132
133        let any_fixtures = active_per_group.iter().flat_map(|g| g.iter());
134        // The wasm globalSetup spawns the mock server. It must run for any fixture
135        // that interpolates `${process.env.MOCK_SERVER_URL}` into a base URL —
136        // i.e. anything with `mock_response` (liter-llm shape) or `http`
137        // (kreuzberg/kreuzcrawl shape), not just raw `is_http_test`. The
138        // comment block below this line states the same intent; the previous
139        // condition (`f.is_http_test()`) only detected the consumer-style
140        // `http: { ... }` shape and missed the entire liter-llm fixture set.
141        let has_http_fixtures = any_fixtures.clone().any(|f| f.needs_mock_server());
142        // file_path / bytes args are read off disk by the generated code at runtime;
143        // we add a setup.ts chdir to test_documents so relative paths resolve.
144        let has_file_fixtures = active_per_group.iter().flatten().any(|f| {
145            let cc = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
146            cc.args
147                .iter()
148                .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
149        });
150
151        // Generate package.json — adds vitest + rollup dev deps so that the test
152        // suite can import the wasm-pack nodejs CJS bundle by package name.
153        files.push(GeneratedFile {
154            path: output_base.join("package.json"),
155            content: render_package_json(
156                &pkg_name,
157                &pkg_path,
158                pkg_path_is_explicit,
159                &pkg_version,
160                e2e_config.dep_mode,
161            ),
162            generated_header: false,
163        });
164
165        // Generate vitest.config.ts — optional globalSetup (for HTTP fixtures and
166        // any function-call test that hits the mock server via MOCK_SERVER_URL)
167        // and setupFiles (for chdir). Function-call e2e tests construct request URLs via
168        // `${process.env.MOCK_SERVER_URL}/fixtures/<id>`, so the mock server must
169        // be running and the env var set even when no raw HTTP fixtures exist.
170        let needs_global_setup = has_http_fixtures;
171        files.push(GeneratedFile {
172            path: output_base.join("vitest.config.ts"),
173            content: render_vitest_config(needs_global_setup, has_file_fixtures),
174            generated_header: true,
175        });
176
177        // Generate globalSetup.ts when any fixture requires the mock server —
178        // either an HTTP fixture (the original consumer) or any function-call
179        // fixture that interpolates `${process.env.MOCK_SERVER_URL}` into a
180        // base URL. It spawns the rust mock-server binary.
181        if needs_global_setup {
182            files.push(GeneratedFile {
183                path: output_base.join("globalSetup.ts"),
184                content: render_global_setup(),
185                generated_header: true,
186            });
187        }
188
189        // Generate setup.ts when any active fixture takes a file_path / bytes arg.
190        // This chdir's to test_documents/ so relative fixture paths resolve.
191        if has_file_fixtures {
192            files.push(GeneratedFile {
193                path: output_base.join("setup.ts"),
194                content: render_file_setup(&e2e_config.test_documents_dir),
195                generated_header: true,
196            });
197        }
198
199        // Generate tsconfig.json — prevents Vite from walking up to a project-level
200        // tsconfig and pulling in unrelated compiler options.
201        files.push(GeneratedFile {
202            path: output_base.join("tsconfig.json"),
203            content: render_tsconfig(),
204            generated_header: false,
205        });
206
207        // Emit a local `pnpm-workspace.yaml` declaring `e2e/wasm/` as its own
208        // pnpm workspace root. Without this, `pnpm install` walks up to the
209        // repo-root `pnpm-workspace.yaml`, where polyglot repos commonly
210        // exclude `e2e/wasm` (it depends on a `wasm-pack build` artifact that
211        // is absent on fresh checkouts). The CLI flag `--ignore-workspace`
212        // would also work, but it forces every caller (Taskfile, CI step) to
213        // pass it; making `e2e/wasm/` self-rooted keeps the generated suite
214        // self-contained.
215        files.push(GeneratedFile {
216            path: output_base.join("pnpm-workspace.yaml"),
217            content: "packages:\n  - \".\"\n".to_string(),
218            generated_header: false,
219        });
220
221        // Resolve options_type from override (e.g. `WasmExtractionConfig`).
222        let options_type = overrides.and_then(|o| o.options_type.clone());
223        let field_resolver = FieldResolver::new(
224            &e2e_config.fields,
225            &e2e_config.fields_optional,
226            &e2e_config.result_fields,
227            &e2e_config.fields_array,
228            &std::collections::HashSet::new(),
229        );
230
231        // Generate test files per category. We delegate the per-fixture rendering
232        // to the typescript codegen (`render_test_file`), which already handles
233        // both HTTP and function-call fixtures correctly. Passing `lang = "wasm"`
234        // routes per-fixture override resolution and skip checks through the wasm
235        // language key. We then inject Node.js WASM initialization code to load
236        // the WASM binary from the pkg directory using fs.readFileSync.
237        let wasm_type_prefix = config.wasm_type_prefix();
238        for (group, active) in groups.iter().zip(active_per_group.iter()) {
239            if active.is_empty() {
240                continue;
241            }
242            let filename = format!("{}.test.ts", sanitize_filename(&group.category));
243            let content = super::typescript::render_test_file(
244                lang,
245                &group.category,
246                active,
247                &module_path,
248                &pkg_name,
249                &function_name,
250                &e2e_config.call.args,
251                options_type.as_deref(),
252                &field_resolver,
253                client_factory,
254                e2e_config,
255                type_defs,
256                enums,
257                &wasm_type_prefix,
258            );
259
260            // The local `pkg/` directory produced by `wasm-pack build --target nodejs`
261            // is already a Node-friendly self-initializing CJS module — `pkg/package.json`
262            // sets `"main"` to the JS entry, so test files can import the package by name
263            // (`from "<pkg_name>"`) with no subpath. The historical `dist-node` rewrite
264            // assumed a multi-distribution layout (`dist/`, `dist-node/`, `dist-web/`)
265            // that the alef-managed `wasm-pack build` does not produce; it is therefore
266            // intentionally absent here.
267            let _ = (&pkg_path, &config.name); // keep variables alive for future use
268
269            files.push(GeneratedFile {
270                path: tests_base.join(filename),
271                content,
272                generated_header: true,
273            });
274        }
275
276        Ok(files)
277    }
278
279    fn language_name(&self) -> &'static str {
280        "wasm"
281    }
282}
283
284fn snake_to_camel(s: &str) -> String {
285    let mut out = String::with_capacity(s.len());
286    let mut upper_next = false;
287    for ch in s.chars() {
288        if ch == '_' {
289            upper_next = true;
290        } else if upper_next {
291            out.push(ch.to_ascii_uppercase());
292            upper_next = false;
293        } else {
294            out.push(ch);
295        }
296    }
297    out
298}
299
300fn render_package_json(
301    pkg_name: &str,
302    pkg_path: &str,
303    pkg_path_is_explicit: bool,
304    pkg_version: &str,
305    dep_mode: crate::config::DependencyMode,
306) -> String {
307    let dep_value = match dep_mode {
308        crate::config::DependencyMode::Registry => pkg_version.to_string(),
309        // Fallback path: `wasm-pack build --target nodejs --out-dir pkg/nodejs` writes
310        // the npm-consumable package (its own package.json with `main`/`types` etc.)
311        // to `pkg/nodejs/`, not to `pkg/` directly. The fallback `wasm_crate_path()`
312        // points at `pkg/`, so we descend into `nodejs/` to find a valid
313        // package.json. When the user has set `[e2e.packages.wasm].path` explicitly,
314        // we trust they have already pointed at a directory with a valid package.json
315        // (the crate root, the wasm-pack out-dir, or another distribution layout) and
316        // do not mutate it.
317        crate::config::DependencyMode::Local => {
318            if pkg_path_is_explicit {
319                format!("file:{pkg_path}")
320            } else {
321                format!("file:{pkg_path}/nodejs")
322            }
323        }
324    };
325    crate::template_env::render(
326        "wasm/package.json.jinja",
327        minijinja::context! {
328            pkg_name => pkg_name,
329            dep_value => dep_value,
330            rollup => tv::npm::ROLLUP,
331            vitest => tv::npm::VITEST,
332        },
333    )
334}
335
336fn render_vitest_config(with_global_setup: bool, with_file_setup: bool) -> String {
337    let header = hash::header(CommentStyle::DoubleSlash);
338    crate::template_env::render(
339        "wasm/vitest.config.ts.jinja",
340        minijinja::context! {
341            header => header,
342            with_global_setup => with_global_setup,
343            with_file_setup => with_file_setup,
344        },
345    )
346}
347
348fn render_file_setup(test_documents_dir: &str) -> String {
349    let header = hash::header(CommentStyle::DoubleSlash);
350    let mut out = header;
351    out.push_str("import { createRequire } from 'module';\n");
352    out.push_str("import { fileURLToPath } from 'url';\n");
353    out.push_str("import { dirname, join } from 'path';\n\n");
354    out.push_str("// Patch CommonJS `require('env')` and `require('wasi_snapshot_preview1')` to\n");
355    out.push_str("// return shim objects. wasm-pack `--target nodejs` emits bare `require()`\n");
356    out.push_str("// calls for these from getrandom/wasi transitives, but they are not real\n");
357    out.push_str("// Node modules — the WASM module imports them by name and the host is\n");
358    out.push_str("// expected to satisfy them. Patch Module._load BEFORE the wasm bundle is\n");
359    out.push_str("// imported by any test file.\n");
360    out.push_str("// Note: setupFiles run per-test-worker; vitest imports the test files\n");
361    out.push_str("// AFTER setupFiles complete, so this hook installs in time.\n");
362    out.push_str("{\n");
363    out.push_str("  const _require = createRequire(import.meta.url);\n");
364    out.push_str("  const Module = _require('module');\n");
365    out.push_str("  // env.system / env.mkstemp come from C-runtime calls embedded in some\n");
366    out.push_str("  // WASM-compiled deps (e.g. tesseract-wasm). Tests that don't exercise\n");
367    out.push_str("  // those paths only need the imports to be callable for module instantiation.\n");
368    out.push_str("  const env = {\n");
369    out.push_str("    system: (_cmd: number) => -1,\n");
370    out.push_str("    mkstemp: (_template: number) => -1,\n");
371    out.push_str("  };\n");
372    out.push_str("  // WASI shims. Critical: clock_time_get and random_get must produce realistic\n");
373    out.push_str("  // values — returning 0 for all clock calls causes WASM-side timing loops to\n");
374    out.push_str("  // spin forever (e.g. getrandom's spin-until-elapsed retry), and zero-filled\n");
375    out.push_str("  // random buffers can cause init loops in deps expecting non-zero entropy.\n");
376    out.push_str("  const _wasiMemoryView = (): DataView | null => {\n");
377    out.push_str("    // Imports are wired before the WASM is instantiated; the bundle stashes\n");
378    out.push_str("    // its instance on a runtime-known global once available. We try to grab\n");
379    out.push_str("    // it lazily so writes to wasm memory go to the right place.\n");
380    out.push_str("    const g = globalThis as unknown as { __alef_wasm_memory__?: WebAssembly.Memory };\n");
381    out.push_str("    return g.__alef_wasm_memory__ ? new DataView(g.__alef_wasm_memory__.buffer) : null;\n");
382    out.push_str("  };\n");
383    out.push_str("  const _cryptoFill = (buf: Uint8Array) => {\n");
384    out.push_str("    const c = globalThis.crypto;\n");
385    out.push_str("    if (c && typeof c.getRandomValues === 'function') c.getRandomValues(buf);\n");
386    out.push_str("    else for (let i = 0; i < buf.length; i++) buf[i] = Math.floor(Math.random() * 256);\n");
387    out.push_str("  };\n");
388    out.push_str("  const wasi_snapshot_preview1 = {\n");
389    out.push_str("    proc_exit: () => {},\n");
390    out.push_str("    environ_get: () => 0,\n");
391    out.push_str("    environ_sizes_get: (countOut: number, _sizeOut: number) => {\n");
392    out.push_str("      const v = _wasiMemoryView();\n");
393    out.push_str("      if (v) v.setUint32(countOut, 0, true);\n");
394    out.push_str("      return 0;\n");
395    out.push_str("    },\n");
396    out.push_str("    // WASI fd_write must update `nwritten_ptr` with the total bytes consumed,\n");
397    out.push_str("    // otherwise libc-style callers (e.g. tesseract-compiled-to-wasm fputs)\n");
398    out.push_str("    // see 0 of N bytes written and retry forever, hanging the host.\n");
399    out.push_str("    fd_write: (_fd: number, iovsPtr: number, iovsLen: number, nwrittenPtr: number) => {\n");
400    out.push_str("      const v = _wasiMemoryView();\n");
401    out.push_str("      if (!v) return 0;\n");
402    out.push_str("      let total = 0;\n");
403    out.push_str("      for (let i = 0; i < iovsLen; i++) {\n");
404    out.push_str("        const off = iovsPtr + i * 8;\n");
405    out.push_str("        total += v.getUint32(off + 4, true);\n");
406    out.push_str("      }\n");
407    out.push_str("      v.setUint32(nwrittenPtr, total, true);\n");
408    out.push_str("      return 0;\n");
409    out.push_str("    },\n");
410    out.push_str("    // Mirror fd_write: callers retry on partial reads. Reporting 0 bytes\n");
411    out.push_str("    // read (EOF) is fine; just make sure `nread_ptr` is written.\n");
412    out.push_str("    fd_read: (_fd: number, _iovsPtr: number, _iovsLen: number, nreadPtr: number) => {\n");
413    out.push_str("      const v = _wasiMemoryView();\n");
414    out.push_str("      if (v) v.setUint32(nreadPtr, 0, true);\n");
415    out.push_str("      return 0;\n");
416    out.push_str("    },\n");
417    out.push_str("    fd_seek: () => 0,\n");
418    out.push_str("    fd_close: () => 0,\n");
419    out.push_str("    fd_prestat_get: () => 8, // EBADF — no preopens.\n");
420    out.push_str("    fd_prestat_dir_name: () => 0,\n");
421    out.push_str("    fd_fdstat_get: () => 0,\n");
422    out.push_str("    fd_fdstat_set_flags: () => 0,\n");
423    out.push_str("    path_open: () => 44, // ENOENT.\n");
424    out.push_str("    path_create_directory: () => 0,\n");
425    out.push_str("    path_remove_directory: () => 0,\n");
426    out.push_str("    path_unlink_file: () => 0,\n");
427    out.push_str("    path_filestat_get: () => 44, // ENOENT.\n");
428    out.push_str("    path_rename: () => 0,\n");
429    out.push_str("    clock_time_get: (_clockId: number, _precision: bigint, timeOut: number) => {\n");
430    out.push_str("      const ns = BigInt(Date.now()) * 1_000_000n + BigInt(performance.now() | 0) % 1_000_000n;\n");
431    out.push_str("      const v = _wasiMemoryView();\n");
432    out.push_str("      if (v) v.setBigUint64(timeOut, ns, true);\n");
433    out.push_str("      return 0;\n");
434    out.push_str("    },\n");
435    out.push_str("    clock_res_get: (_clockId: number, resOut: number) => {\n");
436    out.push_str("      const v = _wasiMemoryView();\n");
437    out.push_str("      if (v) v.setBigUint64(resOut, 1_000n, true);\n");
438    out.push_str("      return 0;\n");
439    out.push_str("    },\n");
440    out.push_str("    random_get: (bufPtr: number, bufLen: number) => {\n");
441    out.push_str("      const g = globalThis as unknown as { __alef_wasm_memory__?: WebAssembly.Memory };\n");
442    out.push_str("      if (!g.__alef_wasm_memory__) return 0;\n");
443    out.push_str("      _cryptoFill(new Uint8Array(g.__alef_wasm_memory__.buffer, bufPtr, bufLen));\n");
444    out.push_str("      return 0;\n");
445    out.push_str("    },\n");
446    out.push_str("    args_get: () => 0,\n");
447    out.push_str("    args_sizes_get: (countOut: number, _sizeOut: number) => {\n");
448    out.push_str("      const v = _wasiMemoryView();\n");
449    out.push_str("      if (v) v.setUint32(countOut, 0, true);\n");
450    out.push_str("      return 0;\n");
451    out.push_str("    },\n");
452    out.push_str("    poll_oneoff: () => 0,\n");
453    out.push_str("    sched_yield: () => 0,\n");
454    out.push_str("  };\n");
455    out.push_str("  const _origResolve = Module._resolveFilename;\n");
456    out.push_str("  Module._resolveFilename = function(request: string, parent: unknown, ...rest: unknown[]) {\n");
457    out.push_str("    if (request === 'env' || request === 'wasi_snapshot_preview1') return request;\n");
458    out.push_str("    return _origResolve.call(this, request, parent, ...rest);\n");
459    out.push_str("  };\n");
460    out.push_str("  const _origLoad = Module._load;\n");
461    out.push_str("  Module._load = function(request: string, parent: unknown, ...rest: unknown[]) {\n");
462    out.push_str("    if (request === 'env') return env;\n");
463    out.push_str("    if (request === 'wasi_snapshot_preview1') return wasi_snapshot_preview1;\n");
464    out.push_str("    return _origLoad.call(this, request, parent, ...rest);\n");
465    out.push_str("  };\n");
466    out.push_str("  // Capture the WASM linear memory at instantiation time so the WASI shims\n");
467    out.push_str("  // can read/write into it. Without this, every shim that needs memory\n");
468    out.push_str("  // (fd_write nwritten, clock_time_get, random_get, etc.) silently no-ops\n");
469    out.push_str("  // and the host-side C runtime hangs in a retry loop.\n");
470    out.push_str("  const _OrigInstance = WebAssembly.Instance;\n");
471    out.push_str("  const PatchedInstance = function(this: WebAssembly.Instance, mod: WebAssembly.Module, imports?: WebAssembly.Imports) {\n");
472    out.push_str("    const inst = new _OrigInstance(mod, imports);\n");
473    out.push_str("    const exportsMem = (inst.exports as Record<string, unknown>).memory;\n");
474    out.push_str("    if (exportsMem instanceof WebAssembly.Memory) {\n");
475    out.push_str("      (globalThis as unknown as { __alef_wasm_memory__?: WebAssembly.Memory }).__alef_wasm_memory__ = exportsMem;\n");
476    out.push_str("    }\n");
477    out.push_str("    return inst;\n");
478    out.push_str("  } as unknown as typeof WebAssembly.Instance;\n");
479    out.push_str("  PatchedInstance.prototype = _OrigInstance.prototype;\n");
480    out.push_str(
481        "  (WebAssembly as unknown as { Instance: typeof WebAssembly.Instance }).Instance = PatchedInstance;\n",
482    );
483    out.push_str("}\n\n");
484    out.push_str("// Change to the configured test-documents directory so that fixture file paths like\n");
485    out.push_str("// \"pdf/fake_memo.pdf\" resolve correctly when vitest runs from e2e/wasm/.\n");
486    out.push_str("// setup.ts lives in e2e/wasm/; the fixtures dir lives at the repository root,\n");
487    out.push_str("// two directories up: e2e/wasm/ -> e2e/ -> repo root.\n");
488    out.push_str("const __filename = fileURLToPath(import.meta.url);\n");
489    out.push_str("const __dirname = dirname(__filename);\n");
490    let _ = writeln!(
491        out,
492        "const testDocumentsDir = join(__dirname, '..', '..', '{test_documents_dir}');"
493    );
494    out.push_str("process.chdir(testDocumentsDir);\n");
495    out
496}
497
498fn render_global_setup() -> String {
499    let header = hash::header(CommentStyle::DoubleSlash);
500    crate::template_env::render(
501        "wasm/globalSetup.ts.jinja",
502        minijinja::context! {
503            header => header,
504        },
505    )
506}
507
508fn render_tsconfig() -> String {
509    crate::template_env::render("wasm/tsconfig.jinja", minijinja::context! {})
510}
511
512// The historical `inject_wasm_init` post-processor rewrote test imports to a
513// `<pkg>/dist-node` subpath. It was removed because the alef-managed
514// `wasm-pack build --target nodejs` artifact is a flat self-initializing CJS
515// module — its `package.json` already sets `"main"` to the JS entry, so the
516// emitted `import … from "<pkg>"` resolves directly.