Skip to content
wasm-bindgenPublic

About

Automated TypeScript Bindgen

Resources

Stars

22 stars

Watchers

2 watching

Forks

Repository files navigation

ts-gen

Generate bindings from TypeScript .d.ts declaration files: Rust for wasm-bindgen, and, through the ts-gen IR and the tw bridge, Kotlin/Wasm and Zena.

Overview

ts-gen reads TypeScript .d.ts files. By default it runs a language generator on them: ts-gen-wasm-bindgen, which writes Rust source with #[wasm_bindgen] extern blocks (Rust). It also writes the ts-gen IR, a language-neutral description of a JS API that any Wasm language can bind against, and the later stages built on it.

.d.ts -ts-gen----------> Rust (#[wasm_bindgen])
.d.ts -ts-gen --ir-----> app.tw
app.tw -ts-gen --json--> JSON -> Kotlin / Zena bindings -> app.wasm
app.tw + app.wasm -ts-gen --bridge-> bridge.js + bridge.wasm

CLI

ts-gen --input <x.d.ts...|dir|app.tw> [--output <out>] [emit] [options] [-- <generator flags>]

The input is .d.ts files and directories, or one IR file (.tw). One flag picks what a run emits:

emit output --output
--lang <L> (default, wasm-bindgen) bindings, by running the generator ts-gen-<L> passed to the generator
--ir the IR; a .tw input is validated and printed again a file, or stdout
--json the IR lowered to JSON under --profile a file, or stdout
--bridge <language.wasm> bridge.js and bridge.wasm under --profile a directory

.d.ts input is lowered on the way, so ts-gen --input worker.d.ts --bridge worker.wasm -o out needs no .tw in between. ts-gen --help describes every option.

A language generator is its own binary. ts-gen passes it the input, the output, the .d.ts options it was given, and the arguments after --:

ts-gen --input types.d.ts --output src/bindings.rs -- --fallible

It finds ts-gen-<L> in this order:

  1. the path in TS_GEN_<L> (TS_GEN_WASM_BINDGEN), for a local build;
  2. ts-gen's cache directory, under its own version;
  3. cargo install ts-gen-<L> at the same version, into that cache.

PATH isn't searched, so the generator always matches the ts-gen running it.

The ts-gen IR

IR.md is the spec. An IR file declares classes, interfaces, enums, callbacks, generics, async and exceptions in a small text format. Each member is keyed by its canonical signature (Request#text()), which is also its Wasm import name. A profile fixes how values cross the boundary:

  • linear memory, WasmGC or host carriers;
  • the string encoding;
  • the exception and result conventions.

The ts-gen-abi crate holds the IR's parser, printer and validator, the profile and layout rules, and the tw protocol names. It lowers an IR to per-member wire layouts for generators that don't link it:

ts-gen --input worker.d.ts --provides ExportedHandler.fetch --ir -o worker.tw
ts-gen --input worker.tw --json --profile "all-host, results = single, throws = js" > worker.json

.d.ts input takes the producer options: --provides, --once, --no-cancel, --bound, --with, --emit-lib, --root and --strict-nullable. See ts-gen --help for each.

The tw bridge

ts-gen --bridge (ts-gen-bridge) generates the JS side for a compiled language module, its IR and its profile. bridge.js is the ESM glue: it converts and validates values, dispatches overloads and maps errors, and exports the IR's exports as JS classes and functions. bridge.wasm translates GC values that JS can't read. See bridge/README.md.

Languages

Each language is its own generator: it reads the IR, or ts-gen --json's lowering of it, and the bridge supplies the JS side. Rust's is ts-gen-wasm-bindgen, which ts-gen runs by default. Two example generators live under examples, to check the IR, the profiles and the bridge against real compilers.

language profile generator status
Rust wasm-bindgen ts-gen-wasm-bindgen the flags below; every type read from the IR
Kotlin/Wasm all-host, results = single, throws = js examples/kotlin-bindgen imports, exports and async, through the bridge
Zena all-gc with host strings examples/zena-bindgen imports, monomorphized generics

Kotlin: kotlin-bindgen <lowered.json> <out-dir> [--package <pkg>] [--runtime] writes Kotlin externals from ts-gen --json's output. Kotlin names its own imports, so it also writes a links.tsv, and kotlin-bindgen link renames the compiled module's imports to their keys. Build the generator with ./gradlew installDist in examples/kotlin-bindgen (JDK 21). examples/kotlin-bindgen/example runs a Worker end to end.

Zena: zena-bindgen <input.tw> [-o <out.zena>] writes @external declarations. They need the Zena compiler fork with the tw option on @external.

Development

just test          # unit, snapshot and bridge runtime tests (Node 26)
just test-kotlin   # the Kotlin generator: snapshots, Kotlin/Wasm compiles, runtime (JDK 21, Node 26)
just test-zena     # the Zena generator; compiles with ZENA=<zena-cli> ZENA_REPO_ROOT=<checkout>
just test-integration  # wasm-bindgen integration (wasm32 target, wasm-bindgen-cli)
just fmt-check && just clippy

just test runs the Kotlin and Zena tests too when their tools are present, and skips them otherwise. Under CI a missing tool is a failure, unless TSGEN_SKIP_KOTLIN or TSGEN_SKIP_ZENA is set. The main CI job sets both, and separate jobs run each toolchain. BLESS=1 re-blesses snapshots.

Rust (wasm-bindgen)

Pipeline

.d.ts files
  -> oxc_parser (AST)
  -> First Pass phase 1: collect all type names into TypeRegistry
  -> First Pass phase 2: populate full IR (resolve references, merge var+interface patterns)
  -> Assembly: group by ModuleContext, resolve inheritance chains, classify types
  -> Code Generation: IR -> syn::File -> prettyplease -> .rs files

Installation

CLI

cargo install ts-gen

ts-gen installs ts-gen-wasm-bindgen the first time it generates Rust. cargo install ts-gen-wasm-bindgen installs the generator alone, which takes the same flags without the --.

Library

cargo add ts-gen-wasm-bindgen --no-default-features
cargo add ts-gen --no-default-features

ts-gen holds the parser and ts-gen-wasm-bindgen the Rust generator. The cli feature of each (enabled by default) pulls in clap, and for ts-gen the bridge generator, for its binary. Disable it if you only need the library API.

Usage

CLI

ts-gen --input types.d.ts --output src/bindings.rs

The generator's own flags go after --. --lib-name, --annotate and --strict-nullable shape how the .d.ts is read for every output, so they are ts-gen's.

Process a directory of declaration files:

ts-gen --input ./typings/ --output src/bindings.rs --lib-name my-js-lib

Map external types from other crates:

ts-gen --input types.d.ts --output src/bindings.rs -- \
  --external "Blob=::web_sys::Blob" \
  --external "node:buffer=node_buffer_sys" \
  --external "Intl.DateTimeFormatOptions=::my_intl::Options"

Route untyped JS exceptions into your own error type (must implement From<JsValue>):

ts-gen --input types.d.ts --output src/bindings.rs -- --error-type crate::Error

Keep @throws {A | B} unions as a generated JsException enum instead of collapsing them to their common ancestor:

ts-gen --input types.d.ts --output src/bindings.rs -- --error-enum

Select the output surface. --input defines the type universe; --export picks what is emitted: a file (its global declarations), a JS module specifier (its declarations, in the module's pub mod), or a declaration name (that export of any file or module, plus the types its bindings reference):

ts-gen --input node_modules/@cloudflare/workers-types/index.d.ts --output src/bindings.rs -- \
  --export Request --export Response --export KVNamespace --export cloudflare:workers

Layer @tw-abi / @throws tags onto a large declaration file from a side file (see CONVENTIONS.md, "--annotate side files"):

ts-gen --input node_modules/@cloudflare/workers-types/index.d.ts \
  --output src/bindings.rs \
  --annotate types/annotations.d.ts

Opt generic imports into wasm-bindgen's experimental per-monomorphization codegen:

ts-gen --input types.d.ts --output src/bindings.rs -- --experimental-generic-mono

Emit one Result form per sync method and function instead of a trapping primary plus a try_<name> companion:

ts-gen --input types.d.ts --output src/bindings.rs -- --fallible

Choose how a Promise-returning method or function is bound. both, the default, binds an async fn name() beside a sync name_promise() that returns the promise, for a caller that needs the call started now (ctx.wait_until(..), Promise::race). promise binds one sync name() returning Promise<T, E>, started at the call and awaited with name().await. async binds only the async fn:

ts-gen --input types.d.ts --output src/bindings.rs -- --promise-returns promise

Keep T | null | undefined three-state. By default a return, awaited value or getter admitting null, undefined or both reads as Option<T>, and a T | null | undefined write passes undefined. With the flag the producer keeps it as the IR's T??, so it reads as Option<Nullable<T>> and its writes gain a _with_null variant. T | null and T | undefined are the same either way:

ts-gen --input types.d.ts --output src/bindings.rs --strict-nullable

Library API

use ts_gen::parse_source;
use ts_gen_wasm_bindgen::{generate, generate_with_options, GenerateOptions, PromiseReturns};

let source = r#"
  export declare class Greeter {
    constructor(name: string);
    greet(): string;
  }
"#;

let (module, gctx) = parse_source(source, Some("my-lib"))?;
let rust_code = generate(&module, &gctx)?;
println!("{rust_code}");

Options are set through GenerateOptions builder methods (its fields are private):

let options = GenerateOptions::new()
    .error_type("crate::Error")
    .experimental_generic_mono(true)
    .promise_returns(PromiseReturns::Both)
    .strict_nullable(false);
let rust_code = generate_with_options(&module, &gctx, &options)?;

Supported TypeScript constructs

  • Classes (including abstract classes and inheritance)
  • Interfaces (classified as class-like or dictionary types)
  • Functions and variables
  • String and numeric enums
  • Type aliases
  • Namespaces
  • Module declarations
  • Generics (JsGeneric erasure by default, with experimental per-monomorphization support)

Known limitations

  • External generic type arguments are not preserved unless the target is a recognized js_sys container; locally declared generic types keep theirs.
  • The parsed IR uses Rc<str> internally and is !Send / !Sync.

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

About

Automated TypeScript Bindgen

Resources

Stars

22 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages