English · 简体中文
Browser runtime for the wasm-split toolchain — the Rust CLI
lives in the parent directory of this package inside the same repo,
and emits either a primary.wasm + secondary.wasm pair (split mode)
or a primary.archive.wasm + func_archive.bin pair (archive mode).
This package consumes both.
wasm-split supports two split modes; this runtime handles both:
splitmode — slice a.wasminto a hot primary that boots immediately plus a cold secondary fetched lazily. Both modules share memory / table / globals. The runtime provides the trampoline imports primary expects, fetches secondary, and instantiates it against primary's instance.archivemode (wasmcode2, for iOS WKWebView) — slice a.wasminto a primary plus afunc_archive.binarchive (verbatim Type/Import sections + per-cold-function body bytes, optionally Brotli-compressed per entry). The runtime does not instantiate the archive as one module — it assembles a micro-module per cold batch on demand, instantiates it, and uses an activeelemsegment to overwrite trampolines in the shared table. JSC never sees the whole cold set, so the iOS memory spike disappears.
npm install @wasm-split/runtime
ESM-first, ships CJS too. Browser-only (uses WebAssembly.instantiateStreaming,
fetch, etc.). Node 18+ also works for testing.
WasmSplitLoader is generic — declare your wasm module's public surface
once and every call site narrows to it:
// exports.d.ts — co-locate with the rest of your wasm glue code. export interface MyExports extends WebAssembly.Exports { // `WebAssembly.Exports` is `Record<string, ExportValue>`, so you need // to spell out the shapes yourself. Function signatures below are the // *JS-side* view — not the raw wasm type. // Hot path — available synchronously after `instantiate()` returns. bootstrap(): void; frame_step(dt: number): void; // Cold path — only safe to call after `await inst.secondaryReady`. openPlayerInventory(seed: number): number; // Shared memory / table / globals re-exported by primary. memory: WebAssembly.Memory; __indirect_function_table: WebAssembly.Table; }
import { WasmSplitLoader } from '@wasm-split/runtime'; import type { MyExports } from './exports'; const loader = new WasmSplitLoader<MyExports>({ /* ... */ }); const inst = await loader.instantiate(); // inst.exports is MyExports; TS now catches typos + wrong arity at // compile time instead of at wasm trap time.
If you don't care about types, drop the generic — inst.exports
defaults to WebAssembly.Exports.
import { WasmSplitLoader } from '@wasm-split/runtime'; // Split manifest must be a parsed object: the loader constructor // validates `schema_version` synchronously so mismatches fail fast. const manifest = await fetch('/dist/split-manifest.json').then((r) => r.json()); const loader = new WasmSplitLoader<MyExports>({ primary: '/dist/primary.wasm', secondary: '/dist/secondary.wasm', manifest, strategy: 'eager', // see "Loading strategies" below imports: { env: { // ...your existing env imports for the original wasm }, }, }); const inst = await loader.instantiate(); // `inst` is a discriminated union on `mode`: here it narrows to 'split'. if (inst.mode !== 'split') throw new Error('unreachable'); // Hot path is callable immediately. inst.exports.bootstrap(); // Gate cold UI on `secondaryReady` — calling cold paths before this throws // `SecondaryNotReadyError`. (Browsers can't block sync wasm calls on async // fetch, so this can't be auto-recovered.) await inst.secondaryReady; inst.exports.openPlayerInventory();
Swap secondary + manifest for a single archive option — the outward-facing
surface (exports, secondaryReady) is unchanged:
import { WasmSplitLoader } from '@wasm-split/runtime'; const archiveManifest = await fetch('/dist/archive-manifest.json').then((r) => r.json(), ); const loader = new WasmSplitLoader<MyExports>({ primary: '/dist/primary.archive.wasm', archive: { source: '/dist/func_archive.bin', // WSAR archive bytes manifest: archiveManifest, // parsed archive-manifest.json trampolineFill: 'eager', // 'eager' | 'incremental' | 'manual' // With Brotli on (default) and iOS < 17 (no DecompressionStream('br')), // plug in a sync Brotli decoder: // decompressBrotli: (bytes, uncompressedSize) => myBrotli.decode(bytes), }, imports: { env: { /* ... */ } }, onColdHit: (ev) => { // ev is a discriminated union — narrow on `ev.mode` to get the // archive-only / split-only fields. if (ev.mode === 'archive') telemetry.coldArchiveHit(ev.tableId); }, }); const inst = await loader.instantiate(); if (inst.mode !== 'archive') throw new Error('unreachable'); await inst.secondaryReady; // trampolines have been installed inst.exports.call_cold_a(5); // sync: inject batch → run → return // Advanced: drop an injected batch (releases its WebAssembly.Instance). // `evictByTableIndex` returns a boolean. inst.archive.evictByTableIndex(1);
Key facts:
secondaryReadyin archive mode means "trampolines have been installed pertrampolineFill", not "cold functions are instantiated". Cold functions are compiled synchronously on first call.archiveis aWasmArchiveLoaderinstance exposing low-level APIs —injectByTableIndex(slot)(async) /injectByTableIndexSync(slot)/evictByTableIndex(slot)/fillTableWithTrampolines()— for warm-up or manual memory control.archive.manifestmust already be a parsed object (ArchiveManifest). The constructor validatesschema_versionsynchronously; pass bytes / URLs yourself if you need to fetch them.- The
archiveandsplitoptions are mutually exclusive and validated by the constructor — passing both throws immediately.
| strategy | behaviour | use when |
|---|---|---|
eager (default) |
All cold slots get trampolines synchronously inside instantiate() |
Simple, predictable |
incremental |
Per-type-group fill, yielding to the event loop between groups | Low-end iOS: compiling ~100 trampolines in one shot can blow a frame budget |
manual |
Never fills; caller drives archive.fillTableWithTrampolines() / archive.injectByTableIndex() |
Fine-grained warm-up (only pre-compile one code path) |
strategy controls when secondary is fetched + instantiated. All three
strategies share the same secondaryReady / loadSecondary() surface, so
you can switch between them without changing call sites.
| strategy | when secondary loads | cold call before ready |
|---|---|---|
eager (default) |
in parallel with primary instantiation | throws SecondaryNotReadyError |
lazy |
only when you explicitly call loadSecondary() |
throws SecondaryNotReadyError |
on-demand |
the first cold stub auto-kicks loadSecondary() in the background |
throws SecondaryNotReadyError for the offending call; subsequent calls succeed after await secondaryReady |
The secondary option accepts more than a URL — anything "bytes-shaped" or
WebAssembly.Module-shaped works, including Promises and thunks. That
way the host-side prefetch (route-based, idle-callback, <link rel=prefetch>,
service worker, etc.) can hand the loader whatever shape it already has
without re-fetching:
// 1. Host-driven preload — just hand the in-flight fetch to the loader. const inflight = fetch('/dist/secondary.wasm'); new WasmSplitLoader({ /* ... */, secondary: inflight, strategy: 'eager' }); // 2. Pre-compiled at boot — skip compile on the critical path. const secondaryModule = await WebAssembly.compileStreaming( fetch('/dist/secondary.wasm'), ); new WasmSplitLoader({ /* ... */, secondary: secondaryModule }); // 3. Fully deferred — thunk is only invoked on the first cold hit. new WasmSplitLoader({ /* ... */, secondary: () => fetch('/dist/secondary.wasm'), strategy: 'on-demand', });
Top-level options (common to both modes):
| option | type | description |
|---|---|---|
primary |
WasmSource (string | URL | Response | Promise<Response> | ArrayBuffer | Uint8Array) |
Primary wasm source. Always fetched eagerly. |
imports |
WebAssembly.Imports |
User imports passed through to primary. |
fetch |
typeof fetch |
Override fetch — used by the test harness. |
onColdHit |
(ev: ColdHitEvent) => void |
Telemetry hook fired on every stub entry. ev is a discriminated union: { mode: 'split', tableId, secondaryReady } or { mode: 'archive', tableId, trampolinesReady }. |
The constructor is fail-fast: it validates options synchronously
(mutual exclusion of split / archive, required fields, manifest
schema_version) and throws before any I/O happens.
WasmSplitLoader is generic over exports — new WasmSplitLoader<MyExports>({...})
narrows inst.exports to your declared type.
Split-mode only (mutually exclusive with archive):
| option | type | description |
|---|---|---|
secondary |
DeferredWasmSource — any WasmSource, WebAssembly.Module, Promise of either, or a zero-arg thunk returning any of the above |
Secondary wasm. Thunks are only invoked when the load actually happens, which pairs with strategy: 'on-demand'. |
manifest |
SplitManifest |
Parsed split-manifest.json object. Fetch + parse it yourself before passing in. |
strategy |
'eager' | 'lazy' | 'on-demand' |
When to start fetching secondary. Default 'eager'. See "Loading strategies" above. |
Archive-mode only (mutually exclusive with secondary / manifest / strategy):
| option | type | description |
|---|---|---|
archive.source |
WasmSource |
WSAR archive bytes. |
archive.manifest |
ArchiveManifest |
Parsed archive-manifest.json object (validated against schema_version synchronously). |
archive.trampolineFill |
'eager' | 'incremental' | 'manual' |
See the trampolineFill table above. Default 'eager'. |
archive.batchSize |
number |
Overrides the manifest's batch_size. |
archive.bodyImports |
WebAssembly.Imports |
Extra imports to merge into every body micro-module. Useful when cold functions import host functions that aren't re-exported by primary. |
archive.decompressBrotli |
(bytes: Uint8Array, uncompressedSize: number) => Uint8Array |
Synchronous Brotli decoder. Required when the archive is per_function_brotli: true and the host lacks native synchronous Brotli decoding — the loader prints a one-shot warning if it detects this situation. |
WasmSplitInstance is a discriminated union on mode:
type WasmSplitInstance<T = WebAssembly.Exports> = | { mode: 'split'; instance: WebAssembly.Instance; exports: T; secondaryReady: Promise<void>; isSecondaryReady(): boolean; loadSecondary(): Promise<void>; } | { mode: 'archive'; instance: WebAssembly.Instance; exports: T; secondaryReady: Promise<void>; // resolves after trampoline fill isSecondaryReady(): boolean; loadSecondary(): Promise<void>; // same promise as secondaryReady archive: WasmArchiveLoader; // non-nullable in archive mode archiveFillReport: FillTrampolinesReport; };
- Split mode:
loadSecondary()is idempotent and returns the in-flight promise on subsequent calls. - Archive mode:
secondaryReadyresolves once trampolines have been installed pertrampolineFill;loadSecondary()returns the same promise.archive/archiveFillReportare guaranteed to be present and non-null once the union has narrowed tomode: 'archive'.
| method / property | description |
|---|---|
fillTableWithTrampolines(options?) |
Install one trampoline (de-duplicated by type signature) per cold slot. Returns { compiledModules, filledSlots }. async. Pass options.incremental: true to yield to the event loop between type-groups. |
injectByTableIndexSync(slot) |
Compile the body micro-module for slot's batch, new WebAssembly.Instance, active-elem overwrite every slot in the batch. Runs fully synchronously — this is what the trampoline's wait handler calls under the hood. Idempotent. |
injectByTableIndex(slot) |
Async wrapper around the sync version; convenient for pre-warming. |
evictByTableIndex(slot) |
Batch-level evict: restore trampolines for every slot in slot's batch and drop the shared WebAssembly.Instance reference so GC can reclaim the JIT. Returns true if anything was evicted. |
handleWait() |
Implementation of the wait import used by trampolines; already wired up by the loader. |
archive / manifest |
Parsed archive / manifest metadata. |
SecondaryNotReadyError— split-mode-only: a cold function ran before secondary was loaded. Never thrown in archive mode (injection is synchronous). Alwaysawait secondaryReadyfirst.IncompatiblePrimaryError— the primary module is missing the expectedmemory/tableexports. Almost always means the primary was built with a differentwasm-splitversion than this runtime.
When you instrument a wasm with wasm-split prepare (the profile-collection
mode), the instrumented module imports wasm_split_prepare.report and
optionally wasm_split_prepare.bitmap. This package ships a tiny helper:
import { createPrepareClient } from '@wasm-split/runtime/prepare'; const client = createPrepareClient({ endpoint: 'http://127.0.0.1:9876/report', // wasm-split collect bitmapPages: 1, // from prepare-manifest.json }); const { instance } = await WebAssembly.instantiate(wasmBytes, { env: { /* ... */ }, wasm_split_prepare: client.imports, }); // ...play through the hot path... await client.flush();
┌──────────────────┐
│ wasm-split │
1. profile │ prepare │ emits instrumented.wasm + prepare-client.js
└────────┬─────────┘
│
v
┌──────────────────┐
│ runtime in │ uses createPrepareClient -> POST /report
│ browser session │
└────────┬─────────┘
│
v
┌──────────────────┐
│ wasm-split │ accumulates fids -> hot-funcidx.txt
2. collect │ collect │
└────────┬─────────┘
│
v
┌──────────────────┐
│ wasm-split │ cold = local - hot
3. split │ split │ split mode: primary.wasm + secondary.wasm
│ │ archive mode: primary.archive.wasm +
│ │ func_archive.bin
└────────┬─────────┘
│
v
┌──────────────────┐
│ WasmSplitLoader │
4. ship │ in production │
└──────────────────┘
- All evergreen browsers (Chrome / Edge / Firefox / Safari) with
WebAssembly.instantiateStreaming. - Node 18+ (for SSR / test). The runtime falls back to
WebAssembly.instantiate(arrayBuffer)when streaming fails on Node-style responses.
MIT.