use std::collections::HashSet;
use anyhow::{Context as _, Result, anyhow, bail, ensure};
use heck::ToShoutySnakeCase;
use ts_bindgen::ts_bindgen;
use wasmtime_environ::component::{CanonicalOptions, ComponentTypesBuilder, StaticModuleIndex};
use wasmtime_environ::wasmparser::WasmFeatures;
use wasmtime_environ::{PrimaryMap, ScopeVec, Tunables};
use wit_bindgen_core::wit_parser::Function;
use wit_component::DecodedWasm;
use wit_parser::{Package, Resolve, Stability, Type, TypeDefKind, TypeId, WorldId};
mod core;
mod files;
mod transpile_bindgen;
mod ts_bindgen;
pub mod esm_bindgen;
pub mod function_bindgen;
pub mod names;
pub mod script;
pub mod source;
pub mod intrinsics;
use intrinsics::Intrinsic;
pub use transpile_bindgen::{
AsyncMode, BindingsMode, ExportKind, InstantiationMode, TranspileOpts,
};
use transpile_bindgen::{TranspileBindgenResult, transpile_bindgen};
fn enum_case_name(name: &str, screaming_snake_case: bool) -> String {
if screaming_snake_case {
name.to_shouty_snake_case()
} else {
name.to_string()
}
}
#[macro_export]
macro_rules! uwrite {
($dst:expr, $($arg:tt)*) => {
write!($dst, $($arg)*).unwrap()
};
}
#[macro_export]
macro_rules! uwriteln {
($dst:expr, $($arg:tt)*) => {
writeln!($dst, $($arg)*).unwrap()
};
}
pub struct Transpiled {
pub files: Vec<(String, Vec<u8>)>,
pub imports: Vec<String>,
pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
}
pub struct ComponentInfo {
pub imports: Vec<String>,
pub exports: Vec<(String, transpile_bindgen::ExportKind)>,
}
#[derive(Debug, Default, Clone, bon::Builder)]
#[non_exhaustive]
pub struct TranspileConfig {
#[builder(default)]
pub opts: TranspileOpts,
#[cfg(feature = "external-runtime")]
pub cm_runtime_es_module: Option<String>,
}
pub fn generate_types(
name: &str,
resolve: Resolve,
world_id: WorldId,
mut opts: TranspileOpts,
) -> Result<Vec<(String, Vec<u8>)>> {
normalize_namespace_object_options(&mut opts)?;
let mut files = files::Files::default();
ts_bindgen(name, &resolve, world_id, &opts, &mut files)
.context("failed to generate Typescript bindings")?;
let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
for (name, source) in files.iter() {
files_out.push((name.to_string(), source.to_vec()));
}
Ok(files_out)
}
#[cfg(feature = "transpile-bindgen")]
pub fn transpile(component: &[u8], opts: TranspileOpts) -> Result<Transpiled> {
transpile_with_config(component, TranspileConfig::builder().opts(opts).build())
}
#[cfg(feature = "transpile-bindgen")]
pub fn transpile_with_config(component: &[u8], mut config: TranspileConfig) -> Result<Transpiled> {
use wasmtime_environ::component::{Component, Translator};
normalize_transpile_config(&mut config)?;
let TranspileConfig {
mut opts,
#[cfg(feature = "external-runtime")]
cm_runtime_es_module,
} = config;
#[cfg(not(feature = "external-runtime"))]
let cm_runtime_es_module: Option<String> = None;
let name = opts.name.clone();
let mut files = files::Files::default();
let decoded = wit_component::decode(component)
.context("failed to extract interface information from component")?;
let (resolve, world_id) = match decoded {
DecodedWasm::WitPackage(_, _) => bail!("unexpected wit package as input"),
DecodedWasm::Component(resolve, world_id) => (resolve, world_id),
};
let scope = ScopeVec::new();
let tunables = Tunables::default_u32();
let mut features = WasmFeatures::WASM3
| WasmFeatures::WIDE_ARITHMETIC
| WasmFeatures::COMPONENT_MODEL
| WasmFeatures::CM_ASYNC
| WasmFeatures::CM_MORE_ASYNC_BUILTINS
| WasmFeatures::CM_ASYNC_STACKFUL
| WasmFeatures::CM_ERROR_CONTEXT
| WasmFeatures::CM_FIXED_LENGTH_LISTS
| WasmFeatures::CM_MAP
| WasmFeatures::CM_IMPLEMENTS
| WasmFeatures::CM_THREADING;
if !opts.supports_wasm_exnref {
features = features.difference(WasmFeatures::EXCEPTIONS);
}
let mut validator = wasmtime_environ::wasmparser::Validator::new_with_features(features);
let mut types = ComponentTypesBuilder::new(&validator);
let (component, modules) = Translator::new(&tunables, &mut validator, &mut types, &scope)
.translate(component)
.map_err(|e| anyhow!(e).context("failed to translate component"))?;
let modules: PrimaryMap<StaticModuleIndex, core::Translation<'_>> = modules
.into_iter()
.map(|(_i, module)| core::Translation::new(module, opts.multi_memory))
.collect::<Result<_>>()?;
let num_resource_tables = types.num_resource_tables();
let wasmtime_component = Component::default();
let types = types.finish(&wasmtime_component);
for (i, module) in modules.iter() {
files.push(&core_file_name(&name, i.as_u32()), module.wasm());
}
let TranspileBindgenResult {
imports,
exports,
inferred_async_exports,
} = transpile_bindgen(
&name,
&component,
&modules,
&types.0,
num_resource_tables,
&resolve,
world_id,
opts.clone(),
cm_runtime_es_module.as_deref(),
&mut files,
);
if !opts.no_typescript {
if let Some(AsyncMode::JavaScriptPromiseIntegration { exports, .. }) = &mut opts.async_mode
{
exports.extend(inferred_async_exports);
}
ts_bindgen(&name, &resolve, world_id, &opts, &mut files)
.context("failed to generate Typescript bindings")?;
}
let mut files_out: Vec<(String, Vec<u8>)> = Vec::new();
for (name, source) in files.iter() {
files_out.push((name.to_string(), source.to_vec()));
}
Ok(Transpiled {
files: files_out,
imports,
exports,
})
}
fn normalize_namespace_object_options(opts: &mut TranspileOpts) -> Result<()> {
ensure!(
!(opts.use_namespace_objects && opts.variants_inline_cases),
"useNamespaceObjects cannot be combined with variantsInlineCases"
);
if opts.use_namespace_objects {
opts.flags_as_bigint = true;
}
Ok(())
}
fn normalize_transpile_config(config: &mut TranspileConfig) -> Result<()> {
normalize_namespace_object_options(&mut config.opts)?;
#[cfg(feature = "external-runtime")]
if let Some(cm_runtime_es_module) = &config.cm_runtime_es_module {
intrinsics::ext::module_specifier(cm_runtime_es_module, "runtime")?;
}
Ok(())
}
fn core_file_name(name: &str, idx: u32) -> String {
let i_str = if idx == 0 {
String::from("")
} else {
(idx + 1).to_string()
};
format!("{name}.core{i_str}.wasm")
}
pub fn dealias(resolve: &Resolve, mut id: TypeId) -> TypeId {
loop {
match &resolve.types[id].kind {
TypeDefKind::Type(Type::Id(that_id)) => id = *that_id,
_ => break id,
}
}
}
fn feature_gate_allowed(
resolve: &Resolve,
package: &Package,
stability: &Stability,
item_name: &str,
) -> Result<bool> {
Ok(match stability {
Stability::Unknown => true,
Stability::Stable { since, .. } => {
let Some(package_version) = package.name.version.as_ref() else {
return Ok(true);
};
ensure!(
package_version >= since,
"feature gate on [{item_name}] refers to an unreleased (future) package version [{since}] (current package version is [{package_version}])"
);
true
}
Stability::Unstable {
feature,
deprecated: _,
} => {
resolve.all_features || resolve.features.contains(feature)
}
})
}
pub fn get_thrown_type(
resolve: &Resolve,
return_type: Option<Type>,
) -> Option<(Option<&Type>, Option<&Type>)> {
match return_type {
None => None,
Some(Type::Id(id)) => match &resolve.types[id].kind {
TypeDefKind::Result(r) => Some((r.ok.as_ref(), r.err.as_ref())),
_ => None,
},
_ => None,
}
}
pub(crate) fn is_async_fn(func: &Function, canon_opts: &CanonicalOptions) -> bool {
if canon_opts.async_ {
return true;
}
func.kind.is_async()
}
enum FunctionIdentifier<'a> {
Fn(&'a Function),
CanonFnName(&'a str),
}
pub(crate) fn requires_async_porcelain(
func: FunctionIdentifier<'_>,
id: &str,
async_funcs: &HashSet<String>,
) -> bool {
if async_funcs.contains("*") {
return true;
}
let name = match func {
FunctionIdentifier::Fn(func) => func.name.as_str(),
FunctionIdentifier::CanonFnName(name) => name,
}
.trim_start_matches("[async]");
if async_funcs.contains(name) {
return true;
}
let qualified_name = format!("{id}#{name}");
if async_funcs.contains(&qualified_name) {
return true;
}
if let Some(pos) = id.find('@') {
let namespace = &id[..pos];
let namespaced_name = format!("{namespace}#{name}");
if async_funcs.contains(&namespaced_name) {
return true;
}
}
false
}
trait ManagesIntrinsics {
fn add_intrinsic(&mut self, intrinsic: Intrinsic);
}
#[cfg(test)]
mod tests {
use super::*;
const FLAGS_WIT: &str = r#"
package test:flag-values;
interface api {
flags permissions {
read,
write,
}
roundtrip: func(value: permissions) -> permissions;
}
world flag-values {
export api;
}
"#;
fn generated_javascript(transpiled: &Transpiled) -> &str {
transpiled
.files
.iter()
.find_map(|(name, contents)| {
name.ends_with(".js")
.then(|| std::str::from_utf8(contents).unwrap())
})
.unwrap()
}
fn flags_interface(flags_as_bigint: bool) -> String {
let mut resolve = Resolve::default();
let package = resolve.push_str("flags.wit", FLAGS_WIT).unwrap();
let world = resolve
.select_world(&[package], Some("flag-values"))
.unwrap();
let files = generate_types(
"flags",
resolve,
world,
TranspileOpts::builder()
.name("flags".into())
.flags_as_bigint(flags_as_bigint)
.build(),
)
.unwrap();
let (_, contents) = files
.into_iter()
.find(|(name, _)| name.ends_with("api.d.ts"))
.unwrap();
String::from_utf8(contents).unwrap()
}
#[test]
fn flags_types_are_objects_by_default() {
let source = flags_interface(false);
assert!(source.contains("export interface Permissions"));
assert!(!source.contains("export const Permissions"));
}
#[test]
fn flags_types_can_be_bigints_with_constants() {
let source = flags_interface(true);
assert!(source.contains("export type Permissions = bigint;"));
assert!(source.contains("export const Permissions: {"));
assert!(source.contains("readonly Read: bigint"));
assert!(source.contains("readonly Write: bigint"));
}
#[test]
fn wildcard_marks_every_function_async() {
let async_funcs = HashSet::from(["*".to_string()]);
assert!(requires_async_porcelain(
FunctionIdentifier::CanonFnName("query"),
"jco:node/dns@0.1.0",
&async_funcs,
));
assert!(requires_async_porcelain(
FunctionIdentifier::CanonFnName("run"),
"example:component/run@1.0.0",
&async_funcs,
));
}
#[cfg(feature = "external-runtime")]
#[test]
fn validates_cm_runtime_es_module_specifiers() {
let mut default = TranspileConfig::default();
normalize_transpile_config(&mut default).unwrap();
assert!(default.cm_runtime_es_module.is_none());
let mut custom = TranspileConfig::builder()
.cm_runtime_es_module("./runtime".into())
.build();
normalize_transpile_config(&mut custom).unwrap();
assert_eq!(custom.cm_runtime_es_module.as_deref(), Some("./runtime"));
for invalid in ["", "runtime\nmodule"] {
let mut config = TranspileConfig::builder()
.cm_runtime_es_module(invalid.into())
.build();
assert!(normalize_transpile_config(&mut config).is_err());
}
}
#[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
#[test]
fn resource_rep_uses_named_runtime_exports() {
let component = wat::parse_str(
r#"
(component
(core module $module
(type $rep-type (func (param i32) (result i32)))
(import "intrinsics" "rep" (func $rep (type $rep-type)))
(func (export "run") (param i32) (result i32)
local.get 0
call $rep
)
)
(type $resource (resource (rep i32)))
(core func $rep (canon resource.rep $resource))
(core instance $intrinsics
(export "rep" (func $rep))
)
(core instance (instantiate $module
(with "intrinsics" (instance $intrinsics))
))
)
"#,
)
.unwrap();
let direct = transpile(
&component,
TranspileOpts::builder()
.name("resource-runtime-direct".into())
.build(),
)
.unwrap();
let direct_source = generated_javascript(&direct);
assert!(direct_source.contains("function rscTableGet(table, handle)"));
assert!(!direct_source.contains("_jcoRuntimeProvider"));
let transpiled = transpile_with_config(
&component,
TranspileConfig::builder()
.opts(
TranspileOpts::builder()
.name("resource-runtime".into())
.instantiation_mode(InstantiationMode::Sync)
.build(),
)
.cm_runtime_es_module("./custom-runtime".into())
.build(),
)
.unwrap();
let source = generated_javascript(&transpiled);
let import_position = source
.find("import { tableGet as rscTableGet } from \"./custom-runtime/intrinsics/resource.js\";")
.unwrap();
let instantiate_position = source.find("export function instantiate(").unwrap();
let realm_position = source.find("const WebAssembly = options?").unwrap();
let context_position = source
.find("const _jcoResourceTableGetContext = { RuntimeError: WebAssembly.RuntimeError };")
.unwrap();
assert!(import_position < instantiate_position);
assert!(instantiate_position < realm_position);
assert!(realm_position < context_position);
assert!(
source.contains("rscTableGet(_jcoResourceTableGetContext, handleTable0, handle).rep")
);
assert!(!source.contains("function rscTableGet(table, handle)"));
assert!(!source.contains("_jcoRuntimeProvider"));
assert!(!source.contains(".bind(receiver)"));
assert_eq!(source.matches("tableGet as rscTableGet").count(), 1);
assert_eq!(
source.matches("const _jcoResourceTableGetContext").count(),
1
);
assert!(source.contains("from \"./custom-runtime/runtime.js\""));
assert!(!transpiled.imports.contains(&"./custom-runtime".to_string()));
}
#[cfg(all(feature = "transpile-bindgen", feature = "external-runtime"))]
#[test]
fn unrelated_component_does_not_import_external_runtime() {
let component = wat::parse_str("(component)").unwrap();
let transpiled = transpile_with_config(
&component,
TranspileConfig::builder()
.opts(TranspileOpts::builder().name("adder".into()).build())
.cm_runtime_es_module("unused-runtime".into())
.build(),
)
.unwrap();
let source = generated_javascript(&transpiled);
assert!(!source.contains("_jcoRuntimeProvider"));
assert!(!source.contains("unused-runtime"));
assert!(!source.contains("_jcoResourceTableGetContext"));
}
}