Skip to main content

js_component_bindgen/
lib.rs

1use std::collections::HashSet;
2
3use anyhow::{Context as _, Result, anyhow, bail, ensure};
4use heck::ToShoutySnakeCase;
5use ts_bindgen::ts_bindgen;
6use wasmtime_environ::component::{CanonicalOptions, ComponentTypesBuilder, StaticModuleIndex};
7use wasmtime_environ::wasmparser::WasmFeatures;
8use wasmtime_environ::{PrimaryMap, ScopeVec, Tunables};
9use wit_bindgen_core::wit_parser::Function;
10use wit_component::DecodedWasm;
11use wit_parser::{Package, Resolve, Stability, Type, TypeDefKind, TypeId, WorldId};
12
13mod core;
14mod files;
15mod transpile_bindgen;
16mod ts_bindgen;
17
18pub mod esm_bindgen;
19pub mod function_bindgen;
20pub mod names;
21pub mod script;
22pub mod source;
23
24pub mod intrinsics;
25use intrinsics::Intrinsic;
26
27pub use transpile_bindgen::{
28    AsyncMode, BindingsMode, ExportKind, InstantiationMode, TranspileOpts,
29};
30use transpile_bindgen::{TranspileBindgenResult, transpile_bindgen};
31
32fn enum_case_name(name: &str, screaming_snake_case: bool) -> String {
33    if screaming_snake_case {
34        name.to_shouty_snake_case()
35    } else {
36        name.to_string()
37    }
38}
39
40/// Calls [`write!`] with the passed arguments and unwraps the result.
41///
42/// Useful for writing to things with infallible `Write` implementations like
43/// `Source` and `String`.
44///
45/// [`write!`]: std::write
46#[macro_export]
47macro_rules! uwrite {
48    ($dst:expr, $($arg:tt)*) => {
49        write!($dst, $($arg)*).unwrap()
50    };
51}
52
53/// Calls [`writeln!`] with the passed arguments and unwraps the result.
54///
55/// Useful for writing to things with infallible `Write` implementations like
56/// `Source` and `String`.
57///
58/// [`writeln!`]: std::writeln
59#[macro_export]
60macro_rules! uwriteln {
61    ($dst:expr, $($arg:tt)*) => {
62        writeln!($dst, $($arg)*).unwrap()
63    };
64}
65
66pub struct Transpiled {
67    pub files: Vec<(String, Vec<u8>)>,
68    pub imports: Vec<String>,
69    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
70}
71
72pub struct ComponentInfo {
73    pub imports: Vec<String>,
74    pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
75}
76
77// TODO(breaking): merge TranspileOpts into this non-exhaustive configuration at
78// the next major release, so new options no longer need a separate type.
79/// Extensible configuration for `transpile_with_config`.
80///
81/// `TranspileOpts` keeps its published fields so existing struct literals remain
82/// valid. New options belong here, where fields can be added compatibly.
83#[derive(Debug, Default, Clone, bon::Builder)]
84#[non_exhaustive]
85pub struct TranspileConfig {
86    /// Options shared with `transpile` and [`generate_types`].
87    #[builder(default)]
88    pub opts: TranspileOpts,
89    /// ES module providing the Component Model runtime implementation used by
90    /// generated bindings. The module must export a `runtime` provider.
91    /// Intrinsics are generated inline when this is `None` (the default).
92    /// Requires the `external-runtime` Cargo feature.
93    #[cfg(feature = "external-runtime")]
94    pub cm_runtime_es_module: Option<String>,
95}
96
97pub fn generate_types(
98    name: &str,
99    resolve: Resolve,
100    world_id: WorldId,
101    mut opts: TranspileOpts,
102) -> Result<Vec<(String, Vec<u8>)>> {
103    normalize_namespace_object_options(&mut opts)?;
104    let mut files = files::Files::default();
105
106    ts_bindgen(name, &resolve, world_id, &opts, &mut files)
107        .context("failed to generate Typescript bindings")?;
108
109    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
110    for (name, source) in files.iter() {
111        files_out.push((name.to_string(), source.to_vec()));
112    }
113    Ok(files_out)
114}
115
116/// Generate the JS transpilation bindgen for a given Wasm component binary
117/// Outputs the file map and import and export metadata for the Transpilation
118#[cfg(feature = "transpile-bindgen")]
119pub fn transpile(component: &[u8], opts: TranspileOpts) -> Result<Transpiled> {
120    // TODO(breaking): accept the extensible configuration directly in transpile
121    // and remove this compatibility adapter at the next major release.
122    transpile_with_config(component, TranspileConfig::builder().opts(opts).build())
123}
124
125/// Transpile a component with additional configuration, including an optional
126/// external Component Model runtime provider.
127#[cfg(feature = "transpile-bindgen")]
128pub fn transpile_with_config(component: &[u8], mut config: TranspileConfig) -> Result<Transpiled> {
129    use wasmtime_environ::component::{Component, Translator};
130
131    normalize_transpile_config(&mut config)?;
132    let TranspileConfig {
133        mut opts,
134        #[cfg(feature = "external-runtime")]
135        cm_runtime_es_module,
136    } = config;
137    #[cfg(not(feature = "external-runtime"))]
138    let cm_runtime_es_module: Option<String> = None;
139    let name = opts.name.clone();
140    let mut files = files::Files::default();
141
142    // Use the `wit-component` crate here to parse `binary` and discover
143    // the type-level descriptions and `Resolve` corresponding to the
144    // component binary. This will synthesize a `Resolve` which has a top-level
145    // package which has a single document and `world` within it which describes
146    // the state of the component. This is then further used afterwards for
147    // bindings Transpilation as-if a `*.wit` file was input.
148    let decoded = wit_component::decode(component)
149        .context("failed to extract interface information from component")?;
150
151    let (resolve, world_id) = match decoded {
152        DecodedWasm::WitPackage(_, _) => bail!("unexpected wit package as input"),
153        DecodedWasm::Component(resolve, world_id) => (resolve, world_id),
154    };
155
156    // Components are complicated, there's no real way around that. To
157    // handle all the work of parsing a component and figuring out how to
158    // instantiate core wasm modules and such all the work is offloaded to
159    // Wasmtime itself. This crate generator is based on Wasmtime's
160    // low-level `wasmtime-environ` crate which is technically not a public
161    // dependency but the same author who worked on that in Wasmtime wrote
162    // this as well so... "seems fine".
163    //
164    // Note that we're not pulling in the entire Wasmtime engine here,
165    // moreso just the "spine" of validating a component. This enables using
166    // Wasmtime's internal `Component` representation as a much easier to
167    // process version of a component that has decompiled everything
168    // internal to a component to a straight linear list of initializers
169    // that need to be executed to instantiate a component.
170    let scope = ScopeVec::new();
171    let tunables = Tunables::default_u32();
172
173    // The validator that will be used on the component must enable support for all
174    // CM features we expect components to use.
175    //
176    // This does not require the correct execution of the related features post-transpilation,
177    // but without the right features specified, components won't load at all.
178    let mut features = WasmFeatures::WASM3
179        | WasmFeatures::WIDE_ARITHMETIC
180        | WasmFeatures::COMPONENT_MODEL
181        | WasmFeatures::CM_ASYNC
182        | WasmFeatures::CM_MORE_ASYNC_BUILTINS
183        | WasmFeatures::CM_ASYNC_STACKFUL
184        | WasmFeatures::CM_ERROR_CONTEXT
185        | WasmFeatures::CM_FIXED_LENGTH_LISTS
186        | WasmFeatures::CM_MAP
187        | WasmFeatures::CM_IMPLEMENTS
188        | WasmFeatures::CM_THREADING;
189
190    // Unless the target engine is known to support the exception handling
191    // proposal, mask exception handling off: with the feature enabled,
192    // wasmtime-environ's FACT-generated adapters wrap calls in exception
193    // barriers (`try_table`), which only runs behind a flag (e.g.
194    // --experimental-wasm-exnref) in today's JS engines.
195    if !opts.supports_wasm_exnref {
196        features = features.difference(WasmFeatures::EXCEPTIONS);
197    }
198
199    let mut validator = wasmtime_environ::wasmparser::Validator::new_with_features(features);
200
201    let mut types = ComponentTypesBuilder::new(&validator);
202
203    let (component, modules) = Translator::new(&tunables, &mut validator, &mut types, &scope)
204        .translate(component)
205        .map_err(|e| anyhow!(e).context("failed to translate component"))?;
206
207    let modules: PrimaryMap<StaticModuleIndex, core::Translation<'_>> = modules
208        .into_iter()
209        .map(|(_i, module)| core::Translation::new(module, opts.multi_memory))
210        .collect::<Result<_>>()?;
211
212    let wasmtime_component = Component::default();
213    let types = types.finish(&wasmtime_component);
214
215    // Insert all core wasm modules into the generated `Files` which will
216    // end up getting used in the `generate_instantiate` method.
217    for (i, module) in modules.iter() {
218        files.push(&core_file_name(&name, i.as_u32()), module.wasm());
219    }
220
221    let TranspileBindgenResult {
222        imports,
223        exports,
224        inferred_async_exports,
225    } = transpile_bindgen(
226        &name,
227        &component,
228        &modules,
229        &types.0,
230        &resolve,
231        world_id,
232        opts.clone(),
233        cm_runtime_es_module.as_deref(),
234        &mut files,
235    );
236
237    if !opts.no_typescript {
238        if let Some(AsyncMode::JavaScriptPromiseIntegration { exports, .. }) = &mut opts.async_mode
239        {
240            exports.extend(inferred_async_exports);
241        }
242        ts_bindgen(&name, &resolve, world_id, &opts, &mut files)
243            .context("failed to generate Typescript bindings")?;
244    }
245
246    let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
247    for (name, source) in files.iter() {
248        files_out.push((name.to_string(), source.to_vec()));
249    }
250    Ok(Transpiled {
251        files: files_out,
252        imports,
253        exports,
254    })
255}
256
257fn normalize_namespace_object_options(opts: &mut TranspileOpts) -> Result<()> {
258    ensure!(
259        !(opts.use_namespace_objects && opts.variants_inline_cases),
260        "useNamespaceObjects cannot be combined with variantsInlineCases"
261    );
262    if opts.use_namespace_objects {
263        opts.flags_as_bigint = true;
264    }
265    Ok(())
266}
267
268fn normalize_transpile_config(config: &mut TranspileConfig) -> Result<()> {
269    normalize_namespace_object_options(&mut config.opts)?;
270    #[cfg(feature = "external-runtime")]
271    if let Some(cm_runtime_es_module) = &config.cm_runtime_es_module {
272        ensure!(
273            !cm_runtime_es_module.is_empty() && !cm_runtime_es_module.chars().any(char::is_control),
274            "cmRuntimeEsModule must be a non-empty module specifier without control characters"
275        );
276    }
277    Ok(())
278}
279
280fn core_file_name(name: &str, idx: u32) -> String {
281    let i_str = if idx == 0 {
282        String::from("")
283    } else {
284        (idx + 1).to_string()
285    };
286    format!("{name}.core{i_str}.wasm")
287}
288
289pub fn dealias(resolve: &Resolve, mut id: TypeId) -> TypeId {
290    loop {
291        match &resolve.types[id].kind {
292            TypeDefKind::Type(Type::Id(that_id)) => id = *that_id,
293            _ => break id,
294        }
295    }
296}
297
298/// Check if an item (usually some form of [`WorldItem`]) should be allowed through the feature gate
299/// of a given package.
300fn feature_gate_allowed(
301    resolve: &Resolve,
302    package: &Package,
303    stability: &Stability,
304    item_name: &str,
305) -> Result<bool> {
306    Ok(match stability {
307        Stability::Unknown => true,
308        Stability::Stable { since, .. } => {
309            let Some(package_version) = package.name.version.as_ref() else {
310                // If the package version is missing (we're likely dealing with an unresolved package)
311                // and we can't really check much.
312                return Ok(true);
313            };
314
315            ensure!(
316                package_version >= since,
317                "feature gate on [{item_name}] refers to an unreleased (future) package version [{since}] (current package version is [{package_version}])"
318            );
319
320            // Stabilization (@since annotation) overrides features and deprecation
321            true
322        }
323        Stability::Unstable {
324            feature,
325            deprecated: _,
326        } => {
327            // If a @unstable feature is present but the related feature was not enabled
328            // or all features was not selected, exclude
329            resolve.all_features || resolve.features.contains(feature)
330        }
331    })
332}
333
334/// Utility function for deducing whether a type can throw
335pub fn get_thrown_type(
336    resolve: &Resolve,
337    return_type: Option<Type>,
338) -> Option<(Option<&Type>, Option<&Type>)> {
339    match return_type {
340        None => None,
341        Some(Type::Id(id)) => match &resolve.types[id].kind {
342            TypeDefKind::Result(r) => Some((r.ok.as_ref(), r.err.as_ref())),
343            _ => None,
344        },
345        _ => None,
346    }
347}
348
349/// Check whether a given function is an async fn
350///
351/// Functions that are designated as guest async represent use of
352/// the WASI p3 async feature.
353///
354/// These functions must be called from transpiled javsacript much differently
355/// than they would otherwise be, i.e. in accordance to the Component Model
356/// async feature.
357pub(crate) fn is_async_fn(func: &Function, canon_opts: &CanonicalOptions) -> bool {
358    if canon_opts.async_ {
359        return true;
360    }
361    func.kind.is_async()
362}
363
364/// Identifier for a function used
365enum FunctionIdentifier<'a> {
366    Fn(&'a Function),
367    CanonFnName(&'a str),
368}
369
370/// Check whether a function has been marked or async binding generation
371///
372/// When dealing with imports, functions that are designated to require async porcelain
373/// are usually asynchronous host functions -- they will have code generated
374/// that enables use of techniques like JSPI for exposing asynchronous host/platform
375/// imports to WebAssembly guests.
376///
377/// When dealing with an export, functions that require async porcelain simply provide
378/// an interface in the transpiled codebase that produces a `Promise`, i.e. one that can
379/// be called in an *already* asynchronous context (JS `async` function) or resolved with a`.then()`.
380///
381/// Exports do not indicate a use of JSPI, as JSPI is only for bridging asynchronous *host* behavior
382/// to synchronous WebAssembly modules
383///
384/// This function is *not* for detecting WASI P3 asynchronous behavior -- see [`is_guest_async_lifted_fn`].
385pub(crate) fn requires_async_porcelain(
386    func: FunctionIdentifier<'_>,
387    id: &str,
388    async_funcs: &HashSet<String>,
389) -> bool {
390    if async_funcs.contains("*") {
391        return true;
392    }
393
394    let name = match func {
395        FunctionIdentifier::Fn(func) => func.name.as_str(),
396        FunctionIdentifier::CanonFnName(name) => name,
397    }
398    .trim_start_matches("[async]");
399
400    if async_funcs.contains(name) {
401        return true;
402    }
403
404    let qualified_name = format!("{id}#{name}");
405    if async_funcs.contains(&qualified_name) {
406        return true;
407    }
408
409    if let Some(pos) = id.find('@') {
410        let namespace = &id[..pos];
411        let namespaced_name = format!("{namespace}#{name}");
412
413        if async_funcs.contains(&namespaced_name) {
414            return true;
415        }
416    }
417    false
418}
419
420/// Objects that can control the printing/setup of intrinsics (normally in some final codegen output)
421trait ManagesIntrinsics {
422    /// Add an intrinsic, supplying it's name afterwards
423    fn add_intrinsic(&mut self, intrinsic: Intrinsic);
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    const FLAGS_WIT: &str = r#"
431        package test:flag-values;
432
433        interface api {
434            flags permissions {
435                read,
436                write,
437            }
438            roundtrip: func(value: permissions) -> permissions;
439        }
440
441        world flag-values {
442            export api;
443        }
444    "#;
445
446    fn generated_javascript(transpiled: &Transpiled) -> &str {
447        transpiled
448            .files
449            .iter()
450            .find_map(|(name, contents)| {
451                name.ends_with(".js")
452                    .then(|| std::str::from_utf8(contents).unwrap())
453            })
454            .unwrap()
455    }
456
457    fn flags_interface(flags_as_bigint: bool) -> String {
458        let mut resolve = Resolve::default();
459        let package = resolve.push_str("flags.wit", FLAGS_WIT).unwrap();
460        let world = resolve
461            .select_world(&[package], Some("flag-values"))
462            .unwrap();
463        let files = generate_types(
464            "flags",
465            resolve,
466            world,
467            TranspileOpts::builder()
468                .name("flags".into())
469                .flags_as_bigint(flags_as_bigint)
470                .build(),
471        )
472        .unwrap();
473        let (_, contents) = files
474            .into_iter()
475            .find(|(name, _)| name.ends_with("api.d.ts"))
476            .unwrap();
477        String::from_utf8(contents).unwrap()
478    }
479
480    #[test]
481    fn flags_types_are_objects_by_default() {
482        let source = flags_interface(false);
483        assert!(source.contains("export interface Permissions"));
484        assert!(!source.contains("export const Permissions"));
485    }
486
487    #[test]
488    fn flags_types_can_be_bigints_with_constants() {
489        let source = flags_interface(true);
490        assert!(source.contains("export type Permissions = bigint;"));
491        assert!(source.contains("export const Permissions: {"));
492        assert!(source.contains("readonly Read: bigint"));
493        assert!(source.contains("readonly Write: bigint"));
494    }
495
496    #[test]
497    fn wildcard_marks_every_function_async() {
498        let async_funcs = HashSet::from(["*".to_string()]);
499        assert!(requires_async_porcelain(
500            FunctionIdentifier::CanonFnName("query"),
501            "jco:node/dns@0.1.0",
502            &async_funcs,
503        ));
504        assert!(requires_async_porcelain(
505            FunctionIdentifier::CanonFnName("run"),
506            "example:component/run@1.0.0",
507            &async_funcs,
508        ));
509    }
510
511    #[cfg(feature = "external-runtime")]
512    #[test]
513    fn validates_cm_runtime_es_module_specifiers() {
514        let mut default = TranspileConfig::default();
515        normalize_transpile_config(&mut default).unwrap();
516        assert!(default.cm_runtime_es_module.is_none());
517
518        let mut custom = TranspileConfig::builder()
519            .cm_runtime_es_module("./runtime.js".into())
520            .build();
521        normalize_transpile_config(&mut custom).unwrap();
522        assert_eq!(custom.cm_runtime_es_module.as_deref(), Some("./runtime.js"));
523
524        for invalid in ["", "runtime\nmodule"] {
525            let mut config = TranspileConfig::builder()
526                .cm_runtime_es_module(invalid.into())
527                .build();
528            assert!(normalize_transpile_config(&mut config).is_err());
529        }
530    }
531
532    #[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
533    #[test]
534    fn resource_rep_uses_external_runtime_provider() {
535        let component = wat::parse_str(
536            r#"
537                (component
538                    (core module $module
539                        (type $rep-type (func (param i32) (result i32)))
540                        (import "intrinsics" "rep" (func $rep (type $rep-type)))
541                        (func (export "run") (param i32) (result i32)
542                            local.get 0
543                            call $rep
544                        )
545                    )
546                    (type $resource (resource (rep i32)))
547                    (core func $rep (canon resource.rep $resource))
548                    (core instance $intrinsics
549                        (export "rep" (func $rep))
550                    )
551                    (core instance (instantiate $module
552                        (with "intrinsics" (instance $intrinsics))
553                    ))
554                )
555            "#,
556        )
557        .unwrap();
558        let direct = transpile(
559            &component,
560            TranspileOpts::builder()
561                .name("resource-runtime-direct".into())
562                .build(),
563        )
564        .unwrap();
565        let direct_source = generated_javascript(&direct);
566        assert!(direct_source.contains("function rscTableGet(table, handle)"));
567        assert!(!direct_source.contains("_jcoRuntimeProvider"));
568
569        let transpiled = transpile_with_config(
570            &component,
571            TranspileConfig::builder()
572                .opts(
573                    TranspileOpts::builder()
574                        .name("resource-runtime".into())
575                        .instantiation_mode(InstantiationMode::Sync)
576                        .build(),
577                )
578                .cm_runtime_es_module("./custom-runtime.js".into())
579                .build(),
580        )
581        .unwrap();
582        let source = generated_javascript(&transpiled);
583
584        let import_position = source
585            .find("import { runtime as _jcoRuntimeProvider } from \"./custom-runtime.js\";")
586            .unwrap();
587        let instantiate_position = source.find("export function instantiate(").unwrap();
588        let create_position = source.find("_jcoRuntimeProvider.create(").unwrap();
589        assert!(import_position < instantiate_position);
590        assert!(instantiate_position < create_position);
591        assert!(source.contains("const rscTableGet = (() => {"));
592        assert!(source.contains("return intrinsic.bind(receiver);"));
593        assert!(source.contains("rscTableGet("));
594        assert!(!source.contains("function rscTableGet(table, handle)"));
595        assert_eq!(source.matches("_jcoRuntimeProvider.create(").count(), 1);
596        assert!(
597            !transpiled
598                .imports
599                .contains(&"./custom-runtime.js".to_string())
600        );
601    }
602
603    #[cfg(feature = "transpile-bindgen")]
604    #[test]
605    fn unrelated_component_does_not_import_external_runtime() {
606        let component = wat::parse_str("(component)").unwrap();
607        let transpiled = transpile(
608            &component,
609            TranspileOpts::builder().name("adder".into()).build(),
610        )
611        .unwrap();
612        let source = generated_javascript(&transpiled);
613
614        assert!(!source.contains("_jcoRuntimeProvider"));
615        assert!(!source.contains("@bytecodealliance/jco-cm-runtime"));
616    }
617}