Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Wasm bindings (#1073)

Aleksandr Golokozd48439c18db1
diff --git a/.config/platforms.toml b/.config/platforms.toml
index 58fde18e9..211f7046a 100644
--- a/.config/platforms.toml
+++ b/.config/platforms.toml
@@ -139,6 +139,11 @@ metadata = { image_url = "https://artifacts.trymirai.com/social/github/uzu-types
"typescript_downloads",
] }
+[languages.wasm]
+targets = ["wasm32-unknown-unknown"]
+tools = []
+bindings = ["wasm"]
+
[binaries.mirai]
crate = "cli"
targets = ["aarch64-apple-darwin", "x86_64-apple-darwin"]
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index dfed628d0..68c6e7133 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -104,16 +104,30 @@ jobs:
: "${NODE_AUTH_TOKEN:?NPM_TOKEN secret is required}"
- npm_package_name="@trymirai/uzu"
npm_username=$(npm whoami --registry=https://registry.npmjs.org)
- npm_package_owners=$(npm owner ls "$npm_package_name" --registry=https://registry.npmjs.org)
- npm_package_versions_json=$(npm view "$npm_package_name" versions --json --registry=https://registry.npmjs.org)
-
- NPM_PACKAGE_NAME="$npm_package_name" \
- NPM_PACKAGE_OWNERS="$npm_package_owners" \
- NPM_PACKAGE_VERSIONS_JSON="$npm_package_versions_json" \
- NPM_USERNAME="$npm_username" \
- node --input-type=module <<'NODE'
+ npm_view_stderr="$RUNNER_TEMP/npm-view-stderr"
+
+ # The umbrella package and its platform packages (one per [languages.typescript] target in
+ # .config/platforms.toml). @trymirai/uzu-wasm, which the umbrella re-exports for browsers,
+ # joins them once the WebGPU kernels land.
+ for npm_package_name in @trymirai/uzu @trymirai/uzu-darwin-arm64 @trymirai/uzu-darwin-x64; do
+ # With --json npm reports errors on stdout, so stderr is kept out of the JSON.
+ if ! npm_package_versions_json=$(npm view "$npm_package_name" versions --json --registry=https://registry.npmjs.org 2>"$npm_view_stderr"); then
+ if grep -q E404 <<<"$npm_package_versions_json"; then
+ echo "${npm_package_name} is not on npm yet; the first publish creates it in the @trymirai scope."
+ continue
+ fi
+ cat "$npm_view_stderr" >&2
+ echo "$npm_package_versions_json" >&2
+ exit 1
+ fi
+ npm_package_owners=$(npm owner ls "$npm_package_name" --registry=https://registry.npmjs.org)
+
+ NPM_PACKAGE_NAME="$npm_package_name" \
+ NPM_PACKAGE_OWNERS="$npm_package_owners" \
+ NPM_PACKAGE_VERSIONS_JSON="$npm_package_versions_json" \
+ NPM_USERNAME="$npm_username" \
+ node --input-type=module <<'NODE'
const packageName = process.env.NPM_PACKAGE_NAME;
const packageOwners = (process.env.NPM_PACKAGE_OWNERS ?? "")
.split("\n")
@@ -136,6 +150,7 @@ jobs:
console.log(`NPM user ${process.env.NPM_USERNAME} is an owner of ${packageName}.`);
NODE
+ done
- name: "Binaries: Import developer identity certificate"
shell: bash
@@ -196,6 +211,22 @@ jobs:
cargo tools install python
cargo tools install swift
+ # The wasm package needs wasm-bindgen-cli matching the wasm-bindgen crate, and uzu-engine's
+ # webgpu feature compiles shaders with Slang.
+ # - name: "Release: Install wasm tools"
+ # run: |
+ # set -euo pipefail
+ # wasm_bindgen_version=$(awk '$0 == "name = \"wasm-bindgen\"" { getline; gsub(/"/, "", $3); print $3; exit }' Cargo.lock)
+ # cargo install --locked "wasm-bindgen-cli@${wasm_bindgen_version}"
+ #
+ # slang_version="2026.20"
+ # slang_dir="$RUNNER_TEMP/slang"
+ # mkdir -p "$slang_dir"
+ # curl --fail --location --silent --show-error \
+ # "https://github.com/shader-slang/slang/releases/download/v${slang_version}/slang-${slang_version}-macos-aarch64.tar.gz" |
+ # tar -xz -C "$slang_dir"
+ # echo "SLANG_DIR=$slang_dir" >> "$GITHUB_ENV"
+
- name: "Release: Sync"
run: cargo tools sync
@@ -207,6 +238,11 @@ jobs:
- name: "Release: Build artifacts"
run: cargo tools release "${VERSION}" "$UZU_RELEASE_PATH"
+ # run: |
+ # The Slang libraries are loaded by uzu-engine's build script.
+ # Exported here rather than through GITHUB_ENV because macOS drops DYLD_* variables when it starts /bin/bash.
+ # export DYLD_FALLBACK_LIBRARY_PATH="$SLANG_DIR/lib"
+ # cargo tools release "${VERSION}" "$UZU_RELEASE_PATH"
- name: "Binaries: Codesign"
shell: bash
@@ -348,10 +384,16 @@ jobs:
# Publish TypeScript
# ---------------------------------------------------------------
- name: "Publish TypeScript"
- working-directory: ${{ env.UZU_RELEASE_PATH }}/typescript-npm
+ working-directory: ${{ env.UZU_RELEASE_PATH }}
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- run: pnpm publish --access public --no-git-checks
+ run: |
+ set -euo pipefail
+ # The umbrella package goes last: it depends on the platform packages. wasm-npm/ goes before it
+ # once the WebGPU kernels land.
+ for package_path in typescript-npm-platforms/*/ typescript-npm/; do
+ (cd "$package_path" && pnpm publish --access public --no-git-checks)
+ done
# ---------------------------------------------------------------
# Publish Python
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 748e57c22..43585d8f9 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -130,6 +130,13 @@ jobs:
${{ matrix.features && format('--features {0}', join(matrix.features, ',')) || '' }} \
${{ matrix.crates && format('-p {0}', join(matrix.crates, ' -p ')) || '' }}
+ # Test the layer that converts values between JavaScript and Rust in the wasm build
+ - name: Run wasm tests
+ if: ${{ matrix.target == 'wasm32-unknown-unknown' }}
+ env:
+ CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner
+ run: cargo +stable test --target wasm32-unknown-unknown -p bindings-types --features bindings-wasm --tests
+
- name: Check working tree
if: ${{ !cancelled() && steps.setup.outcome == 'success' }}
run: git diff --exit-code
diff --git a/Cargo.lock b/Cargo.lock
index e0231b5c8..124f48c68 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -711,6 +711,7 @@ dependencies = [
name = "bindings"
version = "0.6.17"
dependencies = [
+ "convert_case 0.12.0",
"heck 0.5.0",
"proc-macro2",
"quote",
@@ -721,6 +722,7 @@ dependencies = [
name = "bindings-types"
version = "0.6.17"
dependencies = [
+ "bindings",
"inventory",
"js-sys",
"napi",
@@ -730,11 +732,9 @@ dependencies = [
"pyo3-async-runtimes",
"pyo3-build-config",
"pyo3-stub-gen",
- "serde-wasm-bindgen",
- "tsify",
"uniffi",
"wasm-bindgen",
- "wasm-bindgen-futures",
+ "wasm-bindgen-test",
]
[[package]]
@@ -1812,7 +1812,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"
dependencies = [
"quote",
- "syn 2.0.119",
+ "syn 3.0.9",
]
[[package]]
@@ -2234,14 +2234,12 @@ dependencies = [
"reqwest 0.13.5",
"rstest",
"serde",
- "serde-wasm-bindgen",
"serde_json",
"tempfile",
"thiserror 2.0.21",
"tokio",
"tokio-stream",
"tracing",
- "tsify",
"uniffi",
"uuid",
"wasm-bindgen",
@@ -3129,19 +3127,6 @@ dependencies = [
"regex-syntax",
]
-[[package]]
-name = "gloo-utils"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b5555354113b18c547c1d3a98fbf7fb32a9ff4f6fa112ce823a21641a0ba3aa"
-dependencies = [
- "js-sys",
- "serde",
- "serde_json",
- "wasm-bindgen",
- "web-sys",
-]
-
[[package]]
name = "glow"
version = "0.17.0"
@@ -4698,6 +4683,16 @@ dependencies = [
"unicase",
]
+[[package]]
+name = "minicov"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
+dependencies = [
+ "cc",
+ "walkdir",
+]
+
[[package]]
name = "minijinja"
version = "3.0.1"
@@ -4977,7 +4972,6 @@ dependencies = [
"reqwest 0.13.5",
"schemars 1.2.3",
"serde",
- "serde-wasm-bindgen",
"serde_json",
"shoji",
"thiserror 2.0.21",
@@ -4985,7 +4979,6 @@ dependencies = [
"tokio",
"tokio-util",
"tracing",
- "tsify",
"uniffi",
"uuid",
"wasm-bindgen",
@@ -7715,17 +7708,6 @@ dependencies = [
"typeid",
]
-[[package]]
-name = "serde-wasm-bindgen"
-version = "0.6.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b"
-dependencies = [
- "js-sys",
- "serde",
- "wasm-bindgen",
-]
-
[[package]]
name = "serde_core"
version = "1.0.229"
@@ -7971,12 +7953,10 @@ dependencies = [
"pyo3-build-config",
"pyo3-stub-gen",
"serde",
- "serde-wasm-bindgen",
"serde_json",
"thiserror 2.0.21",
"tokenizers",
"tokio-util",
- "tsify",
"uniffi",
"wasm-bindgen",
"wasm-bindgen-futures",
@@ -9554,32 +9534,6 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
-[[package]]
-name = "tsify"
-version = "0.5.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ea3af6b48c5c5624f7eb3c2f578d1335fadac433321980cae0063e8eb0acaa44"
-dependencies = [
- "gloo-utils",
- "serde",
- "serde-wasm-bindgen",
- "serde_json",
- "tsify-macros",
- "wasm-bindgen",
-]
-
-[[package]]
-name = "tsify-macros"
-version = "0.5.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ef1e2e93369379d0a527c7d6632b58c55d52db7a106d8afbde3b354f3a57a9f1"
-dependencies = [
- "proc-macro2",
- "quote",
- "serde_derive_internals 0.29.1",
- "syn 2.0.119",
-]
-
[[package]]
name = "typeid"
version = "1.0.3"
@@ -10009,7 +9963,6 @@ dependencies = [
"rstest",
"schemars 1.2.3",
"serde",
- "serde-wasm-bindgen",
"serde_json",
"shoji",
"sysinfo",
@@ -10023,7 +9976,6 @@ dependencies = [
"tracing",
"tracing-appender",
"tracing-subscriber",
- "tsify",
"uniffi",
"uuid",
"uzu-engine",
@@ -10269,6 +10221,45 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "wasm-bindgen-test"
+version = "0.3.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42"
+dependencies = [
+ "async-trait",
+ "cast",
+ "js-sys",
+ "libm",
+ "minicov",
+ "nu-ansi-term",
+ "num-traits",
+ "oorandom",
+ "serde",
+ "serde_json",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-bindgen-test-macro",
+ "wasm-bindgen-test-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-test-macro"
+version = "0.3.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "wasm-bindgen-test-shared"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe"
+
[[package]]
name = "wasm-streams"
version = "0.4.2"
@@ -10641,7 +10632,7 @@ dependencies = [
"objc2-metal",
"objc2-quartz-core",
"once_cell",
- "ordered-float 4.6.0",
+ "ordered-float 5.5.0",
"parking_lot",
"portable-atomic",
"portable-atomic-util",
diff --git a/Cargo.toml b/Cargo.toml
index 9bffa5306..44b69ff56 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -179,9 +179,8 @@ pyo3-async-runtimes = { version = "0.29.0", features = ["tokio-runtime"] }
pyo3-stub-gen = "0.23.1"
inventory = "0.3.25"
wasm-bindgen = { version = "=0.2.129", features = ["serde-serialize"] }
-serde-wasm-bindgen = "0.6.5"
wasm-bindgen-futures = "0.4.79"
-tsify = { version = "0.5.8", features = ["js"] }
+wasm-bindgen-test = "=0.3.79" # Matches wasm-bindgen and wasm-bindgen-cli in flake.nix.
openai-harmony = "0.0.8"
dirs = "7.0.0"
dotenvy = "0.15.7"
@@ -195,6 +194,7 @@ async-openai = { version = "0.42.2", features = [
] }
hound = "3.5.1"
ignore = "0.4.33"
+convert_case = "0.12.0"
heck = "0.5.0"
confy = "2.0.0"
toml = "1.1.8"
diff --git a/apps/uzu-pi-extension/tests/provider.test.ts b/apps/uzu-pi-extension/tests/provider.test.ts
index 3bc07cc0a..5923282ec 100644
--- a/apps/uzu-pi-extension/tests/provider.test.ts
+++ b/apps/uzu-pi-extension/tests/provider.test.ts
@@ -297,7 +297,9 @@ test("tool declarations use the developer role while instructions and reasoning
const tool = messages[1]!.toolNamespaces[0]!.tools[0]!;
assert.ok(tool instanceof ToolDescriptionFunction);
assert.equal(tool.toolFunction.name, "read");
- assert.deepEqual(JSON.parse(tool.toolFunction.parameters.json), {
+ const parameters = tool.toolFunction.parameters;
+ assert.ok(parameters);
+ assert.deepEqual(JSON.parse(parameters.json), {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
diff --git a/crates/legacy/bindings-types/Cargo.toml b/crates/legacy/bindings-types/Cargo.toml
index 17435f026..5defc50d5 100644
--- a/crates/legacy/bindings-types/Cargo.toml
+++ b/crates/legacy/bindings-types/Cargo.toml
@@ -31,9 +31,6 @@ bindings-pyo3 = [
bindings-wasm = [
"dep:js-sys",
"dep:wasm-bindgen",
- "dep:serde-wasm-bindgen",
- "dep:wasm-bindgen-futures",
- "dep:tsify",
]
[dependencies]
@@ -46,9 +43,6 @@ pyo3-async-runtimes = { workspace = true, optional = true }
pyo3-stub-gen = { workspace = true, optional = true }
inventory = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
-serde-wasm-bindgen = { workspace = true, optional = true }
-wasm-bindgen-futures = { workspace = true, optional = true }
-tsify = { workspace = true, optional = true }
[build-dependencies]
napi-build = { workspace = true, optional = true }
@@ -56,3 +50,11 @@ pyo3-build-config = { workspace = true, optional = true }
[lints]
workspace = true
+
+[dev-dependencies]
+bindings.workspace = true
+wasm-bindgen-test.workspace = true
+
+[[test]]
+name = "wasm_conversions"
+required-features = ["bindings-wasm"]
diff --git a/crates/legacy/bindings-types/src/lib.rs b/crates/legacy/bindings-types/src/lib.rs
index 6e129a9a1..50e7b012e 100644
--- a/crates/legacy/bindings-types/src/lib.rs
+++ b/crates/legacy/bindings-types/src/lib.rs
@@ -8,5 +8,9 @@ pub struct PyClassRegistration {
#[cfg(feature = "bindings-pyo3")]
::inventory::collect!(PyClassRegistration);
+
#[cfg(feature = "bindings-wasm")]
pub use js_sys;
+
+#[cfg(feature = "bindings-wasm")]
+pub mod wasm;
diff --git a/crates/legacy/bindings-types/src/wasm.rs b/crates/legacy/bindings-types/src/wasm.rs
new file mode 100644
index 000000000..9b7bb508b
--- /dev/null
+++ b/crates/legacy/bindings-types/src/wasm.rs
@@ -0,0 +1,270 @@
+//! Conversions between Rust values and JavaScript values for the wasm bindings.
+//!
+//! `bindings::export` implements [`IntoJs`] and [`FromJs`] for every exported type, so that the
+//! wasm package exposes the same JavaScript shapes as the napi package: camelCase fields, one class
+//! per enum variant, string enums, `null` for a missing return value, and plain objects for maps.
+
+use std::{any::Any, cell::RefCell, collections::HashMap, hash::BuildHasher};
+
+use js_sys::{Array, Function, Object, Reflect};
+use wasm_bindgen::{JsCast, JsValue};
+
+pub type JsResult<T> = Result<T, JsValue>;
+
+pub trait IntoJs {
+ fn into_js(self) -> JsValue;
+}
+
+pub trait FromJs: Sized {
+ fn from_js(value: JsValue) -> JsResult<Self>;
+}
+
+/// The value a failed call rejects or throws with: an `Error` carrying the Rust error message.
+pub fn error(message: impl std::fmt::Display) -> JsValue {
+ js_sys::Error::new(&message.to_string()).into()
+}
+
+pub fn type_error(message: impl std::fmt::Display) -> JsValue {
+ js_sys::TypeError::new(&message.to_string()).into()
+}
+
+struct CloneTransfer {
+ token: JsValue,
+ value: Option<Box<dyn Any>>,
+}
+
+thread_local! {
+ static CLONE_TRANSFERS: RefCell<Vec<CloneTransfer>> = const { RefCell::new(Vec::new()) };
+}
+
+/// Ensures pending clones are dropped even when JavaScript throws or returns an invalid handle.
+struct CloneScope;
+
+impl Drop for CloneScope {
+ fn drop(&mut self) {
+ CLONE_TRANSFERS.with(|transfers| {
+ transfers.borrow_mut().pop();
+ });
+ }
+}
+
+/// Registers a typed clone for the active conversion and returns its opaque, instance-local token.
+/// Calling the hidden method outside a conversion does not allocate a Rust clone.
+pub fn clone_handle<T: Clone + 'static>(value: &T) -> JsValue {
+ CLONE_TRANSFERS.with(|transfers| {
+ let mut transfers = transfers.borrow_mut();
+ let Some(transfer) = transfers.last_mut() else {
+ return JsValue::UNDEFINED;
+ };
+ transfer.value = Some(Box::new(value.clone()));
+ transfer.token.clone()
+ })
+}
+
+/// Copies a Rust value through its hidden clone method, validating both token identity and type.
+/// Nested conversions have separate scopes; tokens cannot be replayed or shared across instances.
+pub fn take_clone<T: 'static>(
+ value: &JsValue,
+ method: &str,
+ type_name: &str,
+) -> JsResult<T> {
+ let expected = || type_error(format!("expected {type_name}"));
+ if !value.is_object() {
+ return Err(expected());
+ }
+ let function: Function = Reflect::get(value, &JsValue::from_str(method))?.dyn_into().map_err(|_| expected())?;
+ let token: JsValue = Object::new().into();
+ CLONE_TRANSFERS.with(|transfers| {
+ transfers.borrow_mut().push(CloneTransfer {
+ token: token.clone(),
+ value: None,
+ });
+ });
+ let _scope = CloneScope;
+ let returned = function.call0(value)?;
+ if returned != token {
+ return Err(expected());
+ }
+ let cloned =
+ CLONE_TRANSFERS.with(|transfers| transfers.borrow_mut().last_mut().and_then(|transfer| transfer.value.take()));
+ cloned.and_then(|value| value.downcast::<T>().ok()).map(|value| *value).ok_or_else(expected)
+}
+
+pub fn new_object() -> Object {
+ Object::new()
+}
+
+pub fn set_property(
+ object: &Object,
+ key: &str,
+ value: JsValue,
+) {
+ // Define an own property so "__proto__" never invokes the inherited setter.
+ let descriptor = Object::new();
+ Reflect::set(&descriptor, &JsValue::from_str("value"), &value).unwrap();
+ for flag in ["enumerable", "writable", "configurable"] {
+ Reflect::set(&descriptor, &JsValue::from_str(flag), &JsValue::TRUE).unwrap();
+ }
+ Object::define_property(object, &JsValue::from_str(key), &descriptor);
+}
+
+pub fn expect_object(
+ value: &JsValue,
+ type_name: &str,
+) -> JsResult<()> {
+ if value.is_object() {
+ Ok(())
+ } else {
+ Err(type_error(format!("expected {type_name}")))
+ }
+}
+
+pub fn get_property(
+ value: &JsValue,
+ key: &str,
+) -> JsResult<JsValue> {
+ Reflect::get(value, &JsValue::from_str(key))
+}
+
+/// Reads the `type` tag of an error value, see `bindings::export(Error)`.
+pub fn get_tag(
+ value: &JsValue,
+ type_name: &str,
+) -> JsResult<String> {
+ expect_object(value, type_name)?;
+ get_property(value, "type")?.as_string().ok_or_else(|| type_error(format!("expected {type_name}")))
+}
+
+pub fn unknown_variant(
+ type_name: &str,
+ variant: &str,
+) -> JsValue {
+ type_error(format!("unknown {type_name} variant: {variant}"))
+}
+
+impl IntoJs for JsValue {
+ fn into_js(self) -> JsValue {
+ self
+ }
+}
+
+impl FromJs for JsValue {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ Ok(value)
+ }
+}
+
+impl IntoJs for () {
+ fn into_js(self) -> JsValue {
+ JsValue::UNDEFINED
+ }
+}
+
+impl IntoJs for bool {
+ fn into_js(self) -> JsValue {
+ JsValue::from_bool(self)
+ }
+}
+
+impl FromJs for bool {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ value.as_bool().ok_or_else(|| type_error("expected a boolean"))
+ }
+}
+
+// napi passes every Rust integer as a JavaScript number, 64-bit ones included.
+macro_rules! number {
+ ($($number:ty),*) => {$(
+ impl IntoJs for $number {
+ fn into_js(self) -> JsValue {
+ JsValue::from_f64(self as f64)
+ }
+ }
+
+ impl FromJs for $number {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ value.as_f64().map(|number| number as $number).ok_or_else(|| type_error("expected a number"))
+ }
+ }
+ )*};
+}
+
+number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
+
+impl IntoJs for String {
+ fn into_js(self) -> JsValue {
+ JsValue::from_str(&self)
+ }
+}
+
+impl FromJs for String {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ value.as_string().ok_or_else(|| type_error("expected a string"))
+ }
+}
+
+impl<T: IntoJs> IntoJs for Option<T> {
+ fn into_js(self) -> JsValue {
+ self.map_or(JsValue::NULL, IntoJs::into_js)
+ }
+}
+
+impl<T: FromJs> FromJs for Option<T> {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ if value.is_null() || value.is_undefined() {
+ Ok(None)
+ } else {
+ T::from_js(value).map(Some)
+ }
+ }
+}
+
+impl<T: IntoJs> IntoJs for Box<T> {
+ fn into_js(self) -> JsValue {
+ (*self).into_js()
+ }
+}
+
+impl<T: FromJs> FromJs for Box<T> {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ T::from_js(value).map(Box::new)
+ }
+}
+
+impl<T: IntoJs> IntoJs for Vec<T> {
+ fn into_js(self) -> JsValue {
+ self.into_iter().map(IntoJs::into_js).collect::<Array>().into()
+ }
+}
+
+impl<T: FromJs> FromJs for Vec<T> {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ if !Array::is_array(&value) {
+ return Err(type_error("expected an array"));
+ }
+ Array::from(&value).iter().map(T::from_js).collect()
+ }
+}
+
+impl<V: IntoJs, S: BuildHasher> IntoJs for HashMap<String, V, S> {
+ fn into_js(self) -> JsValue {
+ let object = Object::new();
+ for (key, value) in self {
+ set_property(&object, &key, value.into_js());
+ }
+ object.into()
+ }
+}
+
+impl<V: FromJs, S: BuildHasher + Default> FromJs for HashMap<String, V, S> {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ expect_object(&value, "an object")?;
+ Object::entries(value.unchecked_ref())
+ .iter()
+ .map(|entry| {
+ let entry = Array::from(&entry);
+ Ok((String::from_js(entry.get(0))?, V::from_js(entry.get(1))?))
+ })
+ .collect()
+ }
+}
diff --git a/crates/legacy/bindings-types/tests/wasm_conversions.rs b/crates/legacy/bindings-types/tests/wasm_conversions.rs
new file mode 100644
index 000000000..47d4e981e
--- /dev/null
+++ b/crates/legacy/bindings-types/tests/wasm_conversions.rs
@@ -0,0 +1,230 @@
+//! Regression tests for the JavaScript conversions that `bindings::export` generates for wasm.
+//!
+//! `wasm-bindgen-test-runner` runs them in Node:
+//! `CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER=wasm-bindgen-test-runner cargo test -p bindings-types
+//! --features bindings-wasm --target wasm32-unknown-unknown --tests`.
+#![cfg(target_arch = "wasm32")]
+
+use std::{cell::RefCell, collections::HashMap, rc::Rc};
+
+use bindings_types::wasm::{FromJs, IntoJs, JsResult};
+use js_sys::{Array, Function, JSON, Object, Reflect};
+use wasm_bindgen::prelude::*;
+use wasm_bindgen_test::wasm_bindgen_test;
+
+#[bindings::export(Structure(Class))]
+#[derive(Clone)]
+pub struct Record {
+ pub name: String,
+}
+
+#[bindings::export(Structure(Class))]
+#[derive(Clone)]
+pub struct Other {
+ pub name: String,
+}
+
+#[bindings::export(Enumeration)]
+#[derive(Clone)]
+pub enum Choice {
+ Text {
+ value: String,
+ },
+ Empty {},
+}
+
+const CLONE_RECORD: &str = "__uzuCloneRecord";
+
+fn read_record(value: JsValue) -> JsResult<String> {
+ Ok(Record::from_js(value)?.name)
+}
+
+fn read_choice(value: JsValue) -> JsResult<String> {
+ Ok(match Choice::from_js(value)? {
+ Choice::Text {
+ value,
+ } => value,
+ Choice::Empty {} => String::new(),
+ })
+}
+
+fn record(name: &str) -> JsValue {
+ Record {
+ name: name.to_string(),
+ }
+ .into_js()
+}
+
+/// Calls a JavaScript function with the comma-separated `params` bound to `args`.
+fn js(
+ params: &str,
+ body: &str,
+ args: &[&JsValue],
+) -> JsValue {
+ let args: Array = args.iter().copied().collect();
+ Function::new_with_args(params, body).apply(&JsValue::UNDEFINED, &args).unwrap()
+}
+
+fn get(
+ object: &JsValue,
+ key: &str,
+) -> JsValue {
+ Reflect::get(object, &JsValue::from_str(key)).unwrap()
+}
+
+fn set(
+ object: &JsValue,
+ key: &str,
+ value: &JsValue,
+) -> JsResult<bool> {
+ Reflect::set(object, &JsValue::from_str(key), value)
+}
+
+#[track_caller]
+fn assert_type_error<T: std::fmt::Debug>(result: JsResult<T>) {
+ let error = result.expect_err("expected a TypeError");
+ assert!(error.is_instance_of::<js_sys::TypeError>(), "expected a TypeError, got {error:?}");
+}
+
+/// Checks `actual` is a plain object with the same own keys and values as `expected`.
+#[track_caller]
+fn assert_same_object(
+ actual: &JsValue,
+ expected: &JsValue,
+) {
+ assert_eq!(Object::get_prototype_of(actual), Object::get_prototype_of(&Object::new()));
+ let keys = |object: &JsValue| {
+ let mut keys: Vec<String> =
+ Object::keys(object.unchecked_ref::<Object>()).iter().map(|key| key.as_string().unwrap()).collect();
+ keys.sort();
+ keys
+ };
+ assert_eq!(keys(actual), keys(expected));
+ for key in keys(expected) {
+ let json = |object: &JsValue| JSON::stringify(&get(object, &key)).unwrap();
+ assert_eq!(json(actual), json(expected), "value of {key}");
+ }
+}
+
+#[wasm_bindgen_test]
+fn class_setter_rejects_wrong_type() {
+ let record = record("original");
+ assert_eq!(read_record(record.clone()).unwrap(), "original");
+ assert_type_error(set(&record, "name", &JsValue::from(42)));
+ assert_eq!(get(&record, "name"), "original");
+ set(&record, "name", &JsValue::from("updated")).unwrap();
+ assert_eq!(read_record(record).unwrap(), "updated");
+}
+
+#[wasm_bindgen_test]
+fn variant_setter_rejects_wrong_type() {
+ let choice = Choice::Text {
+ value: "text".to_string(),
+ }
+ .into_js();
+ assert_type_error(set(&choice, "value", &JsValue::from(42)));
+ assert_eq!(get(&choice, "value"), "text");
+ set(&choice, "value", &JsValue::from("changed")).unwrap();
+ assert_eq!(read_choice(choice).unwrap(), "changed");
+ assert_eq!(read_choice(Choice::Empty {}.into_js()).unwrap(), "");
+}
+
+#[wasm_bindgen_test]
+fn forged_clone_tokens_are_rejected() {
+ let invalid = [
+ JsValue::from(0),
+ JsValue::from(1),
+ JsValue::from(-1),
+ JsValue::from(f64::NAN),
+ JsValue::from(f64::INFINITY),
+ Object::new().into(),
+ JsValue::NULL,
+ JsValue::UNDEFINED,
+ ];
+ for token in &invalid {
+ let forged = js("token", "return { __uzuCloneRecord: () => token }", &[token]);
+ assert_type_error(read_record(forged));
+ }
+}
+
+#[wasm_bindgen_test]
+fn clone_of_another_class_is_rejected() {
+ let other = Other {
+ name: "wrong type".to_string(),
+ }
+ .into_js();
+ let forged = js("other", "return { __uzuCloneRecord: () => other.__uzuCloneOther() }", &[&other]);
+ assert_type_error(read_record(forged));
+}
+
+/// The runner loads a single module instance, so a value from a second instance can't be made here.
+/// Its clone method would run outside any conversion of its own instance and return `undefined`,
+/// which `forged_clone_tokens_are_rejected` covers.
+#[wasm_bindgen_test]
+fn clone_method_outside_conversion_returns_undefined() {
+ let record = record("original");
+ assert!(js("record", "return record.__uzuCloneRecord()", &[&record]).is_undefined());
+}
+
+#[wasm_bindgen_test]
+fn clone_tokens_cannot_be_replayed() {
+ let record = record("updated");
+ let forged: Array = js(
+ "record",
+ "let stale;
+ return [
+ { __uzuCloneRecord() { stale = record.__uzuCloneRecord(); return stale; } },
+ { __uzuCloneRecord: () => stale },
+ ];",
+ &[&record],
+ )
+ .unchecked_into();
+ assert_eq!(read_record(forged.get(0)).unwrap(), "updated");
+ assert_type_error(read_record(forged.get(1)));
+}
+
+#[wasm_bindgen_test]
+fn throwing_clone_method_leaves_no_pending_clone() {
+ let record = record("updated");
+ let throwing = js(
+ "record",
+ "return { __uzuCloneRecord() { record.__uzuCloneRecord(); throw new Error('failed clone'); } }",
+ &[&record],
+ );
+ let error: js_sys::Error = read_record(throwing).unwrap_err().unchecked_into();
+ assert_eq!(String::from(error.message()), "failed clone");
+ assert!(js("record", "return record.__uzuCloneRecord()", &[&record]).is_undefined());
+ assert_eq!(read_record(record).unwrap(), "updated");
+}
+
+#[wasm_bindgen_test]
+fn nested_conversions_use_separate_tokens() {
+ let record = record("updated");
+ let clone_record: Function = get(&record, CLONE_RECORD).unchecked_into();
+ let nested = Rc::new(RefCell::new(None));
+ let callback = {
+ let (record, nested) = (record.clone(), nested.clone());
+ Closure::<dyn FnMut() -> JsValue>::new(move || {
+ let token = clone_record.call0(&record).unwrap();
+ *nested.borrow_mut() = Some(read_record(record.clone()));
+ token
+ })
+ };
+ let reentrant = Object::new();
+ set(&reentrant, CLONE_RECORD, callback.as_ref()).unwrap();
+ assert_eq!(read_record(reentrant.into()).unwrap(), "updated");
+ assert_eq!(nested.take().unwrap().unwrap(), "updated");
+}
+
+#[wasm_bindgen_test]
+fn map_keys_named_like_prototype_members_stay_data() {
+ let roundtrip = |value: &JsValue| HashMap::<String, JsValue>::from_js(value.clone()).unwrap().into_js();
+ for value in [r#""text""#, r#"{ "nested": true }"#] {
+ // JSON.parse defines "__proto__" as an own property instead of setting the prototype.
+ let input = JSON::parse(&format!(r#"{{ "__proto__": {value}, "constructor": "ctor", "toString": "string" }}"#))
+ .unwrap();
+ let output = roundtrip(&input);
+ assert_same_object(&output, &input);
+ assert_same_object(&roundtrip(&output), &input);
+ }
+}
diff --git a/crates/legacy/bindings/Cargo.toml b/crates/legacy/bindings/Cargo.toml
index 4573d58ef..01f12a986 100644
--- a/crates/legacy/bindings/Cargo.toml
+++ b/crates/legacy/bindings/Cargo.toml
@@ -12,6 +12,7 @@ license.workspace = true
proc-macro = true
[dependencies]
+convert_case.workspace = true
heck.workspace = true
proc-macro2.workspace = true
quote.workspace = true
diff --git a/crates/legacy/bindings/src/backends/mod.rs b/crates/legacy/bindings/src/backends/mod.rs
index fe10b835e..f7c8f58d9 100644
--- a/crates/legacy/bindings/src/backends/mod.rs
+++ b/crates/legacy/bindings/src/backends/mod.rs
@@ -1,6 +1,7 @@
mod napi;
mod pyo3;
mod rust;
+mod typescript;
mod uniffi;
mod wasm;
@@ -12,12 +13,24 @@ pub use rust::Rust;
pub use uniffi::Uniffi;
pub use wasm::Wasm;
-use crate::contexts::{
- AliasContext, ClassContext, EnumerationContext, ErrorContext, ImplementationContext, MethodMetadata,
- StructureContext,
+use crate::{
+ contexts::{
+ AliasContext, ClassContext, EnumerationContext, ErrorContext, ImplementationContext, MethodMetadata,
+ StructureContext,
+ },
+ types::StructureFlavor,
};
pub trait Backend {
+ /// Adjusts an exported structure before any backend sees it, e.g. to annotate its fields.
+ fn prepare_structure(
+ _item: &mut syn::ItemStruct,
+ _flavor: &StructureFlavor,
+ ) {
+ }
+
+ fn prepare_class(_item: &mut syn::ItemStruct) {}
+
fn structure_attributes(_context: &StructureContext) -> TokenStream {
quote! {}
}
diff --git a/crates/legacy/bindings/src/backends/napi.rs b/crates/legacy/bindings/src/backends/napi.rs
index e554cb5be..668015668 100644
--- a/crates/legacy/bindings/src/backends/napi.rs
+++ b/crates/legacy/bindings/src/backends/napi.rs
@@ -3,7 +3,10 @@ use quote::{format_ident, quote};
use syn::{Ident, Token, Variant, punctuated::Punctuated};
use crate::{
- backends::Backend,
+ backends::{
+ Backend,
+ typescript::{option_inner, optional_class_field_type},
+ },
contexts::{
AliasContext, ClassContext, EnumerationContext, EnumerationShape, ErrorContext, ErrorShape,
ImplementationContext, MethodMetadata, StructureContext,
@@ -14,6 +17,15 @@ use crate::{
pub struct Napi;
impl Backend for Napi {
+ fn prepare_structure(
+ item: &mut syn::ItemStruct,
+ flavor: &StructureFlavor,
+ ) {
+ if matches!(flavor, StructureFlavor::Class) {
+ declare_nullable_fields(item);
+ }
+ }
+
fn structure_attributes(context: &StructureContext) -> TokenStream {
match context.flavor {
StructureFlavor::Plain => quote! {
@@ -127,6 +139,21 @@ impl Backend for Napi {
}
}
+/// napi-rs declares an `Option` field of a class as `name?: T`, but its getter returns `null` for
+/// `None`, so the public `Option` fields declare `T | null` as their type.
+fn declare_nullable_fields(item: &mut syn::ItemStruct) {
+ let type_name = item.ident.to_string();
+ for field in item.fields.iter_mut() {
+ if !matches!(field.vis, syn::Visibility::Public(_)) {
+ continue;
+ }
+ let Some(ts_type) = option_inner(&field.ty).map(|inner| optional_class_field_type(inner, &type_name)) else {
+ continue;
+ };
+ field.attrs.push(syn::parse_quote! { #[cfg_attr(feature = "bindings-napi", napi(ts_type = #ts_type))] });
+ }
+}
+
fn struct_value_implementations(type_name: &Ident) -> TokenStream {
quote! {
#[cfg(feature = "bindings-napi")]
@@ -225,7 +252,12 @@ fn enum_variant_classes(
.map(|field| {
let field_ident = field.ident.as_ref().expect("named field");
let field_type = &field.ty;
- quote! { pub #field_ident: #field_type }
+ // As for class structures, see `declare_nullable_fields`.
+ let ts_type = option_inner(field_type).map(|inner| {
+ let ts_type = optional_class_field_type(inner, &variant_class_ident.to_string());
+ quote! { #[napi(ts_type = #ts_type)] }
+ });
+ quote! { #ts_type pub #field_ident: #field_type }
})
.collect();
let field_idents: Vec<&Ident> =
diff --git a/crates/legacy/bindings/src/backends/typescript.rs b/crates/legacy/bindings/src/backends/typescript.rs
new file mode 100644
index 000000000..7ce9082d4
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/typescript.rs
@@ -0,0 +1,95 @@
+//! The TypeScript types napi declares for Rust types, shared by the napi and wasm backends so both
+//! packages declare the same API.
+
+/// The TypeScript type napi declares for a Rust type. `Option` maps to `T | null`, as for return
+/// values; fields and parameters handle a top-level `Option` themselves.
+pub fn typescript_type(
+ ty: &syn::Type,
+ self_name: &str,
+) -> String {
+ match ty {
+ syn::Type::Reference(reference) => typescript_type(&reference.elem, self_name),
+ syn::Type::Paren(paren) => typescript_type(&paren.elem, self_name),
+ syn::Type::Group(group) => typescript_type(&group.elem, self_name),
+ syn::Type::Tuple(tuple) if tuple.elems.is_empty() => "void".to_string(),
+ syn::Type::Slice(slice) => format!("Array<{}>", typescript_type(&slice.elem, self_name)),
+ syn::Type::Path(path) => path_type(path, self_name),
+ _ => "any".to_string(),
+ }
+}
+
+fn path_type(
+ path: &syn::TypePath,
+ self_name: &str,
+) -> String {
+ let Some(segment) = path.path.segments.last() else {
+ return "any".to_string();
+ };
+ let arguments = generic_arguments(segment);
+ let argument = |index: usize| {
+ arguments.get(index).map_or_else(|| "any".to_string(), |argument| typescript_type(argument, self_name))
+ };
+ match segment.ident.to_string().as_str() {
+ "bool" => "boolean".to_string(),
+ "u8" | "u16" | "u32" | "u64" | "usize" | "i8" | "i16" | "i32" | "i64" | "isize" | "f32" | "f64" => {
+ "number".to_string()
+ },
+ "String" | "str" | "char" => "string".to_string(),
+ "Option" => format!("{} | null", argument(0)),
+ "Vec" | "VecDeque" => format!("Array<{}>", argument(0)),
+ "HashMap" | "BTreeMap" | "IndexMap" => format!("Record<{}, {}>", argument(0), argument(1)),
+ "Box" | "Arc" | "Rc" | "Result" => argument(0),
+ "JsValue" => "any".to_string(),
+ "Self" => self_name.to_string(),
+ name => name.to_string(),
+ }
+}
+
+/// The type of a class field `name?: T | null`, for an `Option` field: its getter returns `null`
+/// for `None` in both packages, so the type includes `null` as well as the `?` napi gives it.
+pub fn optional_class_field_type(
+ inner: &syn::Type,
+ self_name: &str,
+) -> String {
+ format!("{} | null", typescript_type(inner, self_name))
+}
+
+fn generic_arguments(segment: &syn::PathSegment) -> Vec<&syn::Type> {
+ let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else {
+ return Vec::new();
+ };
+ arguments
+ .args
+ .iter()
+ .filter_map(|argument| match argument {
+ syn::GenericArgument::Type(ty) => Some(ty),
+ _ => None,
+ })
+ .collect()
+}
+
+fn wrapped_inner<'ty>(
+ ty: &'ty syn::Type,
+ wrapper: &str,
+) -> Option<&'ty syn::Type> {
+ let syn::Type::Path(path) = ty else {
+ return None;
+ };
+ let segment = path.path.segments.last()?;
+ if segment.ident != wrapper {
+ return None;
+ }
+ generic_arguments(segment).into_iter().next()
+}
+
+pub fn option_inner(ty: &syn::Type) -> Option<&syn::Type> {
+ wrapped_inner(ty, "Option")
+}
+
+pub fn result_inner(ty: &syn::Type) -> Option<&syn::Type> {
+ wrapped_inner(ty, "Result")
+}
+
+pub fn is_unit(ty: &syn::Type) -> bool {
+ matches!(ty, syn::Type::Tuple(tuple) if tuple.elems.is_empty())
+}
diff --git a/crates/legacy/bindings/src/backends/wasm.rs b/crates/legacy/bindings/src/backends/wasm.rs
deleted file mode 100644
index d9d642dd2..000000000
--- a/crates/legacy/bindings/src/backends/wasm.rs
+++ /dev/null
@@ -1,177 +0,0 @@
-use heck::ToLowerCamelCase;
-use proc_macro2::TokenStream;
-use quote::{format_ident, quote};
-
-use crate::{
- backends::Backend,
- contexts::{
- ClassContext, EnumerationContext, ErrorContext, ImplementationContext, MethodMetadata, StructureContext,
- },
- types::{MethodFlavor, StructureFlavor},
-};
-
-pub struct Wasm;
-
-impl Backend for Wasm {
- fn structure_attributes(context: &StructureContext) -> TokenStream {
- match context.flavor {
- StructureFlavor::Plain => quote! {
- #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]
- #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]
- },
- StructureFlavor::Class => quote! {
- #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen(getter_with_clone))]
- },
- }
- }
-
- fn class_attributes(_context: &ClassContext) -> TokenStream {
- quote! {
- #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]
- }
- }
-
- fn enumeration_attributes(_context: &EnumerationContext) -> TokenStream {
- quote! {
- #[cfg_attr(feature = "bindings-wasm", derive(tsify::Tsify))]
- #[cfg_attr(feature = "bindings-wasm", tsify(into_wasm_abi, from_wasm_abi))]
- }
- }
-
- fn implementation_attributes(_context: &ImplementationContext) -> TokenStream {
- quote! {
- #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]
- }
- }
-
- fn error_companions(context: &ErrorContext) -> TokenStream {
- let type_name = &context.item.ident;
- quote! {
- #[cfg(feature = "bindings-wasm")]
- impl From<#type_name> for wasm_bindgen::JsValue {
- fn from(error: #type_name) -> Self {
- wasm_bindgen::JsValue::from_str(&error.to_string())
- }
- }
- }
- }
-
- fn method_attributes(metadata: &MethodMetadata) -> TokenStream {
- if returns_map(metadata) {
- return quote! { #[cfg(not(feature = "bindings-wasm"))] };
- }
- let name = metadata.method.sig.ident.to_string().to_lower_camel_case();
- let getter = matches!(metadata.flavor, MethodFlavor::Getter).then(|| quote! { getter, });
- quote! {
- #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen(#getter js_name = #name))]
- }
- }
-
- fn method_companions(
- context: &ImplementationContext,
- metadata: &MethodMetadata,
- ) -> TokenStream {
- if matches!(metadata.flavor, MethodFlavor::FactoryWithCallback) {
- return callback_factory(&context.self_type, metadata);
- }
- if returns_map(metadata) {
- return map_method(&context.self_type, metadata);
- }
- if !matches!(metadata.flavor, MethodFlavor::Factory) {
- return quote! {};
- }
- let self_type = &context.self_type;
- let method_name = &metadata.method.sig.ident;
- let mut method = metadata.method.clone();
- method.sig.ident = format_ident!("__wasm_{}", method_name);
- let args = metadata.arg_idents();
- let await_call = metadata.is_async().then(|| quote! { .await });
- method.block = syn::parse_quote! { { Self::#method_name(#(#args),*) #await_call } };
- let attributes = Self::method_attributes(metadata);
- quote! {
- #[cfg(feature = "bindings-wasm")]
- #[wasm_bindgen::prelude::wasm_bindgen]
- impl #self_type {
- #attributes
- #method
- }
- }
- }
-}
-
-fn returns_map(metadata: &MethodMetadata) -> bool {
- let syn::ReturnType::Type(_, ty) = &metadata.method.sig.output else {
- return false;
- };
- let syn::Type::Path(path) = ty.as_ref() else {
- return false;
- };
- path.path.segments.last().is_some_and(|segment| segment.ident == "HashMap")
-}
-
-fn map_method(
- self_type: &syn::Type,
- metadata: &MethodMetadata,
-) -> TokenStream {
- let mut original = metadata.method.clone();
- original.attrs.clear();
- let name = &original.sig.ident;
- let js_name = name.to_string().to_lower_camel_case();
- let getter = matches!(metadata.flavor, MethodFlavor::Getter).then(|| quote! { getter, });
- let args = metadata.arg_idents();
- let await_call = metadata.is_async().then(|| quote! { .await });
- let call = if metadata.receiver().is_some() {
- quote! { self.#name(#(#args),*) }
- } else {
- quote! { Self::#name(#(#args),*) }
- };
- let mut wrapper = original.clone();
- wrapper.sig.ident = format_ident!("__wasm_{}", name);
- wrapper.sig.output = syn::parse_quote! { -> bindings_types::js_sys::Map };
- wrapper.block = syn::parse_quote! {{
- let entries = #call #await_call;
- let map = bindings_types::js_sys::Map::new();
- for (key, value) in entries {
- map.set(&wasm_bindgen::JsValue::from(key), &wasm_bindgen::JsValue::from(value));
- }
- map
- }};
- quote! {
- #[cfg(feature = "bindings-wasm")]
- impl #self_type { #original }
- #[cfg(feature = "bindings-wasm")]
- #[wasm_bindgen::prelude::wasm_bindgen]
- impl #self_type {
- #[wasm_bindgen::prelude::wasm_bindgen(#getter js_name = #js_name)]
- #wrapper
- }
- }
-}
-
-fn callback_factory(
- self_type: &syn::Type,
- metadata: &MethodMetadata,
-) -> TokenStream {
- let Some(inputs) = metadata.callback_inputs() else {
- return syn::Error::new_spanned(&metadata.method.sig, "expected a boxed void callback").to_compile_error();
- };
- let args: Vec<_> = (0..inputs.len()).map(|index| format_ident!("arg{index}")).collect();
- let name = &metadata.method.sig.ident;
- let js_name = name.to_string().to_lower_camel_case();
- let body = &metadata.method.block;
- quote! {
- #[cfg(feature = "bindings-wasm")]
- #[wasm_bindgen::prelude::wasm_bindgen]
- impl #self_type {
- #[wasm_bindgen::prelude::wasm_bindgen(js_name = #js_name)]
- pub fn #name(callback: bindings_types::js_sys::Function) -> Self {
- let callback: Box<dyn Fn(#(#inputs),*) + Send + Sync> = Box::new(move |#(#args: #inputs),*| {
- let arguments = bindings_types::js_sys::Array::new();
- #(arguments.push(&wasm_bindgen::JsValue::from(#args));)*
- let _ = callback.apply(&wasm_bindgen::JsValue::UNDEFINED, &arguments);
- });
- #body
- }
- }
- }
-}
diff --git a/crates/legacy/bindings/src/backends/wasm/enumeration.rs b/crates/legacy/bindings/src/backends/wasm/enumeration.rs
new file mode 100644
index 000000000..13f96801e
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/wasm/enumeration.rs
@@ -0,0 +1,213 @@
+use proc_macro2::TokenStream;
+use quote::{format_ident, quote};
+
+use super::{
+ fields::{
+ accessors, constructor_parameters, field_declarations, field_initializers, named_fields, reject_cfg_fields,
+ },
+ structure::clone_method,
+ typescript::{cfg_attributes, cfg_predicate, custom_sections},
+};
+
+/// An enum of unit variants as napi's string enum: each value is the variant name, the d.ts
+/// declares an enum, and a runtime object maps the variant names to their values. Not a `const enum`:
+/// TypeScript can't inline one under `isolatedModules`, see the napi package's generate-napi-wrappers.cjs.
+pub fn string_enumeration_companions(item: &syn::ItemEnum) -> TokenStream {
+ let name = &item.ident;
+ let type_name = name.to_string();
+ let object = format_ident!("__WasmEnum{}", name);
+
+ let mut into_arms = Vec::new();
+ let mut from_arms = Vec::new();
+ let mut getters = Vec::new();
+ for variant in &item.variants {
+ let ident = &variant.ident;
+ let value = ident.to_string();
+ let cfgs = cfg_attributes(&variant.attrs);
+ let pattern = match variant.fields {
+ syn::Fields::Unit => quote! { Self::#ident },
+ _ => quote! { Self::#ident {} },
+ };
+ into_arms.push(quote! { #(#cfgs)* #pattern => ::wasm_bindgen::JsValue::from_str(#value) });
+ from_arms.push(quote! { #(#cfgs)* #value => ::core::result::Result::Ok(#pattern) });
+ let getter = format_ident!("__wasm_variant_{}", ident);
+ getters.push(quote! {
+ #[cfg(feature = "bindings-wasm")]
+ #(#cfgs)*
+ #[wasm_bindgen::prelude::wasm_bindgen(js_class = #type_name)]
+ impl #object {
+ #[wasm_bindgen(getter = #value, skip_typescript)]
+ #[allow(non_snake_case)]
+ pub fn #getter() -> ::std::string::String {
+ ::std::string::String::from(#value)
+ }
+ }
+ });
+ }
+
+ let values: Vec<String> = item.variants.iter().map(|variant| variant.ident.to_string()).collect();
+ let predicates: Vec<_> = item.variants.iter().map(|variant| cfg_predicate(&variant.attrs)).collect();
+ let declarations = custom_sections(&type_name, &predicates, |included| {
+ let members: Vec<String> = values
+ .iter()
+ .zip(included)
+ .filter(|(_, included)| **included)
+ .map(|(value, _)| format!(" {value} = '{value}',\n"))
+ .collect();
+ format!("export declare enum {type_name} {{\n{}}}", members.concat())
+ });
+
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::IntoJs for #name {
+ fn into_js(self) -> ::wasm_bindgen::JsValue {
+ match self {
+ #(#into_arms),*
+ }
+ }
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::FromJs for #name {
+ fn from_js(value: ::wasm_bindgen::JsValue) -> ::bindings_types::wasm::JsResult<Self> {
+ let Some(value) = value.as_string() else {
+ return ::core::result::Result::Err(::bindings_types::wasm::type_error(concat!("expected ", #type_name)));
+ };
+ match value.as_str() {
+ #(#from_arms,)*
+ other => ::core::result::Result::Err(::bindings_types::wasm::unknown_variant(#type_name, other)),
+ }
+ }
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ #[doc(hidden)]
+ #[allow(non_camel_case_types)]
+ #[wasm_bindgen::prelude::wasm_bindgen(js_name = #type_name, skip_typescript)]
+ pub struct #object {}
+
+ #(#getters)*
+
+ #declarations
+ }
+}
+
+/// An enum with data as napi's variant classes: a class per variant named `{Enum}{Variant}` with
+/// its fields, and a union type of the variant classes under the enum's name.
+pub fn data_enumeration_companions(item: &syn::ItemEnum) -> TokenStream {
+ let name = &item.ident;
+ let type_name = name.to_string();
+ let clone_method = clone_method(&type_name);
+
+ let mut classes = Vec::new();
+ let mut into_arms = Vec::new();
+ for variant in &item.variants {
+ let variant_ident = &variant.ident;
+ let class_name = format!("{type_name}{variant_ident}");
+ let wrapper = format_ident!("__Wasm{}{}", name, variant_ident);
+ let cfgs = cfg_attributes(&variant.attrs);
+ let fields = named_fields(&variant.fields);
+ if let Some(error) = reject_cfg_fields(&fields) {
+ return error;
+ }
+ let parameters = constructor_parameters(&fields, &class_name);
+ let initializers = field_initializers(&fields);
+ let declarations = field_declarations(&class_name, &cfgs, &fields);
+ let accessors = accessors(
+ &fields,
+ |field| {
+ let ident = field.ident;
+ quote! {
+ match &self.inner {
+ #name::#variant_ident { #ident, .. } => #ident,
+ _ => ::core::unreachable!(),
+ }
+ }
+ },
+ |field| {
+ let ident = field.ident;
+ quote! {
+ if let #name::#variant_ident { #ident, .. } = &mut self.inner {
+ *#ident = __wasm_value;
+ }
+ }
+ },
+ );
+
+ classes.push(quote! {
+ #[cfg(feature = "bindings-wasm")]
+ #(#cfgs)*
+ #[doc(hidden)]
+ #[allow(non_camel_case_types)]
+ #[wasm_bindgen::prelude::wasm_bindgen(js_name = #class_name)]
+ pub struct #wrapper {
+ inner: #name,
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ #(#cfgs)*
+ #[allow(unreachable_patterns, irrefutable_let_patterns)]
+ #[wasm_bindgen::prelude::wasm_bindgen(js_class = #class_name)]
+ impl #wrapper {
+ #[wasm_bindgen(constructor)]
+ #[allow(non_snake_case)]
+ pub fn __wasm_new(#(#parameters),*) -> ::core::result::Result<#wrapper, ::wasm_bindgen::JsValue> {
+ ::core::result::Result::Ok(Self { inner: #name::#variant_ident { #(#initializers),* } })
+ }
+
+ #(#accessors)*
+
+ #[wasm_bindgen(js_name = #clone_method, skip_typescript)]
+ pub fn __wasm_clone_handle(&self) -> ::wasm_bindgen::JsValue {
+ ::bindings_types::wasm::clone_handle(&self.inner)
+ }
+ }
+
+ #declarations
+ });
+ into_arms.push(quote! {
+ #(#cfgs)*
+ value @ Self::#variant_ident { .. } => ::wasm_bindgen::JsValue::from(#wrapper { inner: value })
+ });
+ }
+
+ let class_names: Vec<String> =
+ item.variants.iter().map(|variant| format!("{type_name}{}", variant.ident)).collect();
+ let predicates: Vec<_> = item.variants.iter().map(|variant| cfg_predicate(&variant.attrs)).collect();
+ let declarations = custom_sections(&type_name, &predicates, |included| {
+ let members: Vec<&str> = class_names
+ .iter()
+ .zip(included)
+ .filter(|(_, included)| **included)
+ .map(|(class_name, _)| class_name.as_str())
+ .collect();
+ let union = if members.is_empty() {
+ "never".to_string()
+ } else {
+ members.join(" | ")
+ };
+ format!("export type {type_name} = {union};")
+ });
+
+ quote! {
+ #(#classes)*
+
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::IntoJs for #name {
+ fn into_js(self) -> ::wasm_bindgen::JsValue {
+ match self {
+ #(#into_arms),*
+ }
+ }
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::FromJs for #name {
+ fn from_js(value: ::wasm_bindgen::JsValue) -> ::bindings_types::wasm::JsResult<Self> {
+ ::bindings_types::wasm::take_clone(&value, #clone_method, #type_name)
+ }
+ }
+
+ #declarations
+ }
+}
diff --git a/crates/legacy/bindings/src/backends/wasm/error.rs b/crates/legacy/bindings/src/backends/wasm/error.rs
new file mode 100644
index 000000000..7ccea1d04
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/wasm/error.rs
@@ -0,0 +1,115 @@
+use proc_macro2::TokenStream;
+use quote::{format_ident, quote};
+
+use super::{
+ enumeration::string_enumeration_companions,
+ typescript::{cfg_attributes, cfg_predicate, custom_sections, js_name, object_member},
+};
+use crate::contexts::{ErrorContext, ErrorShape};
+
+pub fn error_companions(context: &ErrorContext) -> TokenStream {
+ let name = &context.item.ident;
+ let value = match context.shape {
+ ErrorShape::Unit => string_enumeration_companions(context.item),
+ ErrorShape::Data => tagged_error_companions(context.item),
+ };
+ quote! {
+ // A failed call throws or rejects with an `Error` carrying the message, as napi does.
+ #[cfg(feature = "bindings-wasm")]
+ impl From<#name> for ::wasm_bindgen::JsValue {
+ fn from(error: #name) -> Self {
+ ::bindings_types::wasm::error(error)
+ }
+ }
+
+ #value
+ }
+}
+
+/// An error as a value, e.g. in a stream chunk: napi's `{ type: 'Variant', field: value }`
+/// objects, with `field0` for tuple fields.
+fn tagged_error_companions(item: &syn::ItemEnum) -> TokenStream {
+ let name = &item.ident;
+ let type_name = name.to_string();
+
+ let mut into_arms = Vec::new();
+ let mut from_arms = Vec::new();
+ let mut members = Vec::new();
+ for variant in &item.variants {
+ let ident = &variant.ident;
+ let tag = ident.to_string();
+ let cfgs = cfg_attributes(&variant.attrs);
+ let fields: Vec<(syn::Ident, String, &syn::Type)> = variant
+ .fields
+ .iter()
+ .enumerate()
+ .map(|(index, field)| match &field.ident {
+ Some(field_ident) => (field_ident.clone(), js_name(&field_ident.to_string()), &field.ty),
+ None => (format_ident!("field{}", index), format!("field{index}"), &field.ty),
+ })
+ .collect();
+ let bindings: Vec<&syn::Ident> = fields.iter().map(|(binding, _, _)| binding).collect();
+ let keys: Vec<&String> = fields.iter().map(|(_, key, _)| key).collect();
+ let (pattern, constructor) = match &variant.fields {
+ syn::Fields::Named(_) => (
+ quote! { Self::#ident { #(#bindings),* } },
+ quote! { Self::#ident { #(#bindings: ::bindings_types::wasm::FromJs::from_js(::bindings_types::wasm::get_property(&value, #keys)?)?),* } },
+ ),
+ syn::Fields::Unnamed(_) => (
+ quote! { Self::#ident(#(#bindings),*) },
+ quote! { Self::#ident(#(::bindings_types::wasm::FromJs::from_js(::bindings_types::wasm::get_property(&value, #keys)?)?),*) },
+ ),
+ syn::Fields::Unit => (quote! { Self::#ident }, quote! { Self::#ident }),
+ };
+ into_arms.push(quote! {
+ #(#cfgs)*
+ #pattern => {
+ let object = ::bindings_types::wasm::new_object();
+ ::bindings_types::wasm::set_property(&object, "type", ::wasm_bindgen::JsValue::from_str(#tag));
+ #(::bindings_types::wasm::set_property(&object, #keys, ::bindings_types::wasm::IntoJs::into_js(#bindings));)*
+ object.into()
+ }
+ });
+ from_arms.push(quote! { #(#cfgs)* #tag => ::core::result::Result::Ok(#constructor) });
+ let mut member = format!("{{ type: '{tag}'");
+ for (_, key, ty) in &fields {
+ member.push_str(&format!("; {}", object_member(key, ty)));
+ }
+ member.push_str(" }");
+ members.push(member);
+ }
+
+ let predicates: Vec<_> = item.variants.iter().map(|variant| cfg_predicate(&variant.attrs)).collect();
+ let declarations = custom_sections(&type_name, &predicates, |included| {
+ let members: Vec<String> = members
+ .iter()
+ .zip(included)
+ .filter(|(_, included)| **included)
+ .map(|(member, _)| format!("\n | {member}"))
+ .collect();
+ format!("export type {type_name} ={};", members.concat())
+ });
+
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::IntoJs for #name {
+ fn into_js(self) -> ::wasm_bindgen::JsValue {
+ match self {
+ #(#into_arms),*
+ }
+ }
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::FromJs for #name {
+ fn from_js(value: ::wasm_bindgen::JsValue) -> ::bindings_types::wasm::JsResult<Self> {
+ match ::bindings_types::wasm::get_tag(&value, #type_name)?.as_str() {
+ #(#from_arms,)*
+ other => ::core::result::Result::Err(::bindings_types::wasm::unknown_variant(#type_name, other)),
+ }
+ }
+ }
+
+ #declarations
+ }
+}
diff --git a/crates/legacy/bindings/src/backends/wasm/fields.rs b/crates/legacy/bindings/src/backends/wasm/fields.rs
new file mode 100644
index 000000000..7cbe3670e
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/wasm/fields.rs
@@ -0,0 +1,183 @@
+use proc_macro2::TokenStream;
+use quote::{format_ident, quote};
+use syn::ext::IdentExt;
+
+use super::typescript::{cfg_attributes, class_member, custom_section, js_name, object_member};
+use crate::backends::typescript::{option_inner, typescript_type};
+
+pub struct Field<'item> {
+ pub ident: &'item syn::Ident,
+ pub ty: &'item syn::Type,
+ pub attributes: &'item [syn::Attribute],
+ /// The JavaScript name: camelCase for named fields, `field0` for tuple fields as napi does.
+ pub js_name: String,
+ pub parameter: syn::Ident,
+}
+
+pub fn named_fields(fields: &syn::Fields) -> Vec<Field<'_>> {
+ fields
+ .iter()
+ .filter_map(|field| {
+ let ident = field.ident.as_ref()?;
+ let js_name = js_name(&ident.unraw().to_string());
+ Some(Field {
+ ident,
+ ty: &field.ty,
+ attributes: &field.attrs,
+ parameter: format_ident!("{}", js_name),
+ js_name,
+ })
+ })
+ .collect()
+}
+
+/// Fields of a class can't be conditionally compiled: the constructor signature would change.
+pub fn reject_cfg_fields(fields: &[Field]) -> Option<TokenStream> {
+ let field = fields.iter().find(|field| !cfg_attributes(field.attributes).is_empty())?;
+ Some(
+ syn::Error::new_spanned(field.ident, "bindings::export does not support #[cfg] on fields of wasm classes")
+ .to_compile_error(),
+ )
+}
+
+/// Constructor parameters in field order, taking JavaScript values. A trailing run of `Option`
+/// fields becomes optional parameters, as in napi.
+pub fn constructor_parameters(
+ fields: &[Field],
+ self_name: &str,
+) -> Vec<TokenStream> {
+ let optional_from =
+ fields.iter().rposition(|field| option_inner(field.ty).is_none()).map_or(0, |position| position + 1);
+ fields
+ .iter()
+ .enumerate()
+ .map(|(index, field)| {
+ let parameter = &field.parameter;
+ match option_inner(field.ty) {
+ Some(inner) if index >= optional_from => {
+ let ty = format!("{} | null", typescript_type(inner, self_name));
+ quote! { #[wasm_bindgen(unchecked_optional_param_type = #ty)] #parameter: ::wasm_bindgen::JsValue }
+ },
+ Some(inner) => {
+ let ty = format!("{} | undefined | null", typescript_type(inner, self_name));
+ quote! { #[wasm_bindgen(unchecked_param_type = #ty)] #parameter: ::wasm_bindgen::JsValue }
+ },
+ None => {
+ let ty = typescript_type(field.ty, self_name);
+ quote! { #[wasm_bindgen(unchecked_param_type = #ty)] #parameter: ::wasm_bindgen::JsValue }
+ },
+ }
+ })
+ .collect()
+}
+
+/// `field: FromJs::from_js(parameter)?` initializers for the constructor parameters.
+pub fn field_initializers(fields: &[Field]) -> Vec<TokenStream> {
+ fields
+ .iter()
+ .map(|field| {
+ let ident = field.ident;
+ let parameter = &field.parameter;
+ quote! { #ident: ::bindings_types::wasm::FromJs::from_js(#parameter)? }
+ })
+ .collect()
+}
+
+/// A getter and setter for each field. `read` and `write` produce the expression for the field's
+/// value and the statement that assigns `__wasm_value` to it, so variant classes can reach into their
+/// enum (whose fields may themselves be called `value`).
+pub fn accessors(
+ fields: &[Field],
+ read: impl Fn(&Field) -> TokenStream,
+ write: impl Fn(&Field) -> TokenStream,
+) -> Vec<TokenStream> {
+ fields
+ .iter()
+ .map(|field| {
+ let js_name = &field.js_name;
+ let field_ty = field.ty;
+ let raw = field.ident.unraw();
+ let getter = format_ident!("__wasm_get_{}", raw);
+ let setter = format_ident!("__wasm_set_{}", raw);
+ let read = read(field);
+ let write = write(field);
+ // Declared by `field_declarations` instead: wasm-bindgen can't mark a property optional.
+ quote! {
+ #[wasm_bindgen(getter = #js_name, skip_typescript)]
+ pub fn #getter(&self) -> ::wasm_bindgen::JsValue {
+ ::bindings_types::wasm::IntoJs::into_js(::core::clone::Clone::clone(#read))
+ }
+
+ #[wasm_bindgen(setter = #js_name, skip_typescript)]
+ pub fn #setter(&mut self, value: ::wasm_bindgen::JsValue) -> ::bindings_types::wasm::JsResult<()> {
+ let __wasm_value = <#field_ty as ::bindings_types::wasm::FromJs>::from_js(value)?;
+ #write
+ Ok(())
+ }
+ }
+ })
+ .collect()
+}
+
+/// Statements setting each field of `source` (an expression path such as `self.` or a binding
+/// prefix) on `object`. `None` fields are left out, as napi does for objects.
+pub fn object_setters(
+ fields: &[Field],
+ value: impl Fn(&Field) -> TokenStream,
+) -> Vec<TokenStream> {
+ fields
+ .iter()
+ .map(|field| {
+ let js_name = &field.js_name;
+ let cfgs = cfg_attributes(field.attributes);
+ let value = value(field);
+ if option_inner(field.ty).is_some() {
+ quote! {
+ #(#cfgs)*
+ if let Some(value) = #value {
+ ::bindings_types::wasm::set_property(&object, #js_name, ::bindings_types::wasm::IntoJs::into_js(value));
+ }
+ }
+ } else {
+ quote! {
+ #(#cfgs)*
+ ::bindings_types::wasm::set_property(&object, #js_name, ::bindings_types::wasm::IntoJs::into_js(#value));
+ }
+ }
+ })
+ .collect()
+}
+
+/// `field: FromJs::from_js(value.field)?` initializers reading the fields of the object `value`.
+pub fn object_initializers(fields: &[Field]) -> Vec<TokenStream> {
+ fields
+ .iter()
+ .map(|field| {
+ let ident = field.ident;
+ let js_name = &field.js_name;
+ let cfgs = cfg_attributes(field.attributes);
+ quote! {
+ #(#cfgs)*
+ #ident: ::bindings_types::wasm::FromJs::from_js(::bindings_types::wasm::get_property(&value, #js_name)?)?
+ }
+ })
+ .collect()
+}
+
+/// The members of an object type, e.g. `name: string; description?: string`.
+pub fn object_members(fields: &[Field]) -> Vec<String> {
+ fields.iter().map(|field| object_member(&field.js_name, field.ty)).collect()
+}
+
+/// Declares the fields of a class as napi does (`name?: T | null` for an `Option`), in an interface
+/// that merges with the class wasm-bindgen declares.
+pub fn field_declarations(
+ class_name: &str,
+ cfgs: &[&syn::Attribute],
+ fields: &[Field],
+) -> TokenStream {
+ let members: String =
+ fields.iter().map(|field| format!(" {};\n", class_member(&field.js_name, field.ty))).collect();
+ let declaration = format!("export interface {class_name} {{\n{members}}}");
+ custom_section(&format!("{class_name}Fields"), cfgs, &declaration)
+}
diff --git a/crates/legacy/bindings/src/backends/wasm/method.rs b/crates/legacy/bindings/src/backends/wasm/method.rs
new file mode 100644
index 000000000..c8fb8b9e0
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/wasm/method.rs
@@ -0,0 +1,226 @@
+use proc_macro2::TokenStream;
+use quote::{format_ident, quote};
+
+use super::typescript::{cfg_attributes, custom_section, doc_attributes, js_name};
+use crate::{
+ backends::typescript::{is_unit, option_inner, result_inner, typescript_type},
+ contexts::{ImplementationContext, MethodMetadata},
+ types::MethodFlavor,
+};
+
+/// Static getter that marks a stream class, so the package entry can give it `Symbol.asyncIterator`.
+const STREAM_MARKER: &str = "__uzuStream";
+
+pub fn method_companions(
+ context: &ImplementationContext,
+ metadata: &MethodMetadata,
+) -> TokenStream {
+ let self_name = context.self_type_ident().map(ToString::to_string).unwrap_or_default();
+ match metadata.flavor {
+ MethodFlavor::FactoryWithCallback => callback_factory(&context.self_type, metadata),
+ MethodFlavor::StreamNext => {
+ let wrapper = wrapper(&context.self_type, &self_name, metadata);
+ let stream = stream_declarations(&context.self_type, &self_name, metadata);
+ quote! { #wrapper #stream }
+ },
+ _ => wrapper(&context.self_type, &self_name, metadata),
+ }
+}
+
+/// A `#[wasm_bindgen]` method calling the exported one, with napi's JavaScript name. Arguments arrive
+/// as JavaScript values and go through `FromJs`, except `&Class` ones, which wasm-bindgen borrows;
+/// the result goes through `IntoJs`. Each wrapper has its own impl block carrying the method's cfgs.
+fn wrapper(
+ self_type: &syn::Type,
+ self_name: &str,
+ metadata: &MethodMetadata,
+) -> TokenStream {
+ let method = &metadata.method;
+ let name = &method.sig.ident;
+ let wrapper_name = format_ident!("__wasm_{}", name);
+ let cfgs = cfg_attributes(&method.attrs);
+ let docs = doc_attributes(&method.attrs);
+ let asyncness = &method.sig.asyncness;
+ let await_call = metadata.is_async().then(|| quote! { .await });
+ let receiver = metadata.receiver().map(|receiver| quote! { #receiver, });
+
+ let arguments = metadata.typed_args();
+ let optional_from =
+ arguments.iter().rposition(|argument| option_inner(&argument.ty).is_none()).map_or(0, |position| position + 1);
+ let mut parameters = Vec::new();
+ let mut conversions = Vec::new();
+ let mut call_arguments = Vec::new();
+ for (index, argument) in arguments.iter().enumerate() {
+ let syn::Pat::Ident(pattern) = argument.pat.as_ref() else {
+ return syn::Error::new_spanned(&argument.pat, "bindings::export expects plain argument names")
+ .to_compile_error();
+ };
+ let parameter = format_ident!("{}", js_name(&pattern.ident.to_string()));
+ let ty = argument.ty.as_ref();
+ if let syn::Type::Reference(reference) = ty {
+ // An exported class, borrowed from the JavaScript object without copying it.
+ parameters.push(quote! { #parameter: #reference });
+ call_arguments.push(quote! { #parameter });
+ continue;
+ }
+ let declaration = match option_inner(ty) {
+ Some(inner) if index >= optional_from => {
+ let ty = format!("{} | null", typescript_type(inner, self_name));
+ quote! { #[wasm_bindgen(unchecked_optional_param_type = #ty)] }
+ },
+ Some(inner) => {
+ let ty = format!("{} | undefined | null", typescript_type(inner, self_name));
+ quote! { #[wasm_bindgen(unchecked_param_type = #ty)] }
+ },
+ None => {
+ let ty = typescript_type(ty, self_name);
+ quote! { #[wasm_bindgen(unchecked_param_type = #ty)] }
+ },
+ };
+ parameters.push(quote! { #declaration #parameter: ::wasm_bindgen::JsValue });
+ conversions.push(quote! { let #parameter = <#ty as ::bindings_types::wasm::FromJs>::from_js(#parameter)?; });
+ call_arguments.push(quote! { #parameter });
+ }
+
+ let call = if metadata.receiver().is_some() {
+ quote! { self.#name(#(#call_arguments),*) #await_call }
+ } else {
+ quote! { Self::#name(#(#call_arguments),*) #await_call }
+ };
+ let unit: syn::Type = syn::parse_quote! { () };
+ let output = match &method.sig.output {
+ syn::ReturnType::Default => &unit,
+ syn::ReturnType::Type(_, ty) => ty.as_ref(),
+ };
+ let (value_type, call) = match result_inner(output) {
+ Some(inner) => (inner, quote! { #call.map_err(::bindings_types::wasm::error)? }),
+ None => (output, call),
+ };
+
+ let js_name = match metadata.flavor {
+ // napi keeps the Rust name of factories.
+ MethodFlavor::Factory => name.to_string(),
+ MethodFlavor::StreamNext => "next".to_string(),
+ MethodFlavor::Setter => js_name(name.to_string().trim_start_matches("set_")),
+ _ => js_name(&name.to_string()),
+ };
+ let kind = match metadata.flavor {
+ MethodFlavor::Constructor => quote! { constructor },
+ MethodFlavor::Getter => quote! { getter = #js_name },
+ MethodFlavor::Setter => quote! { setter = #js_name },
+ _ => quote! { js_name = #js_name },
+ };
+
+ let (return_type, attributes, body) = if matches!(metadata.flavor, MethodFlavor::Constructor) {
+ (quote! { ::core::result::Result<Self, ::wasm_bindgen::JsValue> }, quote! { #kind }, quote! { Ok(#call) })
+ } else if is_unit(value_type) {
+ (
+ quote! { ::core::result::Result<(), ::wasm_bindgen::JsValue> },
+ quote! { #kind },
+ quote! {
+ #call;
+ Ok(())
+ },
+ )
+ } else {
+ let returned = typescript_type(value_type, self_name);
+ (
+ quote! { ::core::result::Result<::wasm_bindgen::JsValue, ::wasm_bindgen::JsValue> },
+ quote! { #kind, unchecked_return_type = #returned },
+ quote! { Ok(::bindings_types::wasm::IntoJs::into_js(#call)) },
+ )
+ };
+
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ #(#cfgs)*
+ #[wasm_bindgen::prelude::wasm_bindgen]
+ impl #self_type {
+ #(#docs)*
+ #[wasm_bindgen(#attributes)]
+ #[allow(non_snake_case, clippy::unused_unit)]
+ pub #asyncness fn #wrapper_name(#receiver #(#parameters),*) -> #return_type {
+ #(#conversions)*
+ #body
+ }
+ }
+ }
+}
+
+/// napi's `[Symbol.asyncIterator]` on stream classes: declared here and installed at runtime by the
+/// package entry on every class carrying the stream marker.
+fn stream_declarations(
+ self_type: &syn::Type,
+ self_name: &str,
+ metadata: &MethodMetadata,
+) -> TokenStream {
+ let cfgs = cfg_attributes(&metadata.method.attrs);
+ let item = match &metadata.method.sig.output {
+ syn::ReturnType::Type(_, ty) => option_inner(ty).map(|inner| typescript_type(inner, self_name)),
+ syn::ReturnType::Default => None,
+ };
+ let Some(item) = item else {
+ return syn::Error::new_spanned(&metadata.method.sig, "Method(StreamNext) must return `Option<T>`")
+ .to_compile_error();
+ };
+ let declaration = format!(
+ "export interface {self_name} {{\n [Symbol.asyncIterator](): AsyncGenerator<{item}, void, undefined>\n}}"
+ );
+ let section = custom_section(&format!("{self_name}AsyncIterator"), &cfgs, &declaration);
+ quote! {
+ #section
+
+ #[cfg(feature = "bindings-wasm")]
+ #(#cfgs)*
+ #[wasm_bindgen::prelude::wasm_bindgen]
+ impl #self_type {
+ #[wasm_bindgen(getter = #STREAM_MARKER, skip_typescript)]
+ pub fn __wasm_stream_marker() -> bool {
+ true
+ }
+ }
+ }
+}
+
+/// A static factory taking a JavaScript function, called without waiting for it.
+fn callback_factory(
+ self_type: &syn::Type,
+ metadata: &MethodMetadata,
+) -> TokenStream {
+ let Some(inputs) = metadata.callback_inputs() else {
+ return syn::Error::new_spanned(&metadata.method.sig, "expected a boxed void callback").to_compile_error();
+ };
+ let self_name = match self_type {
+ syn::Type::Path(path) => path.path.segments.last().map(|segment| segment.ident.to_string()),
+ _ => None,
+ }
+ .unwrap_or_default();
+ let arguments: Vec<_> = (0..inputs.len()).map(|index| format_ident!("arg{index}")).collect();
+ let signature = inputs
+ .iter()
+ .enumerate()
+ .map(|(index, input)| format!("arg{index}: {}", typescript_type(input, &self_name)))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let callback_type = format!("({signature}) => void");
+ let name = &metadata.method.sig.ident;
+ let js_name = js_name(&name.to_string());
+ let cfgs = cfg_attributes(&metadata.method.attrs);
+ let body = &metadata.method.block;
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ #(#cfgs)*
+ #[wasm_bindgen::prelude::wasm_bindgen]
+ impl #self_type {
+ #[wasm_bindgen(js_name = #js_name)]
+ pub fn #name(#[wasm_bindgen(unchecked_param_type = #callback_type)] callback: ::bindings_types::js_sys::Function) -> Self {
+ let callback: Box<dyn Fn(#(#inputs),*) + Send + Sync> = Box::new(move |#(#arguments: #inputs),*| {
+ let arguments = ::bindings_types::js_sys::Array::new();
+ #(arguments.push(&::bindings_types::wasm::IntoJs::into_js(#arguments));)*
+ let _ = callback.apply(&::wasm_bindgen::JsValue::UNDEFINED, &arguments);
+ });
+ #body
+ }
+ }
+ }
+}
diff --git a/crates/legacy/bindings/src/backends/wasm/mod.rs b/crates/legacy/bindings/src/backends/wasm/mod.rs
new file mode 100644
index 000000000..bcde60d49
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/wasm/mod.rs
@@ -0,0 +1,94 @@
+//! wasm-bindgen bindings with the same JavaScript API as the napi ones.
+//!
+//! Values cross the boundary through `bindings_types::wasm::{IntoJs, FromJs}` rather than through
+//! wasm-bindgen's own conversions or serde, so the shapes match napi (camelCase fields, a class per
+//! enum variant, string enums, `null` for a missing value) whatever the types' serde attributes say.
+//! Exported structures and classes are wasm-bindgen classes; every exported method gets a wrapper
+//! that converts its arguments and result, and TypeScript the wrapper can't express (unions, enums,
+//! interfaces) is emitted as custom d.ts sections.
+
+mod enumeration;
+mod error;
+mod fields;
+mod method;
+mod structure;
+mod typescript;
+
+use proc_macro2::TokenStream;
+use quote::quote;
+
+use crate::{
+ backends::{Backend, typescript::typescript_type},
+ contexts::{
+ AliasContext, ClassContext, EnumerationContext, EnumerationShape, ErrorContext, ImplementationContext,
+ MethodMetadata, StructureContext,
+ },
+ types::StructureFlavor,
+};
+
+pub struct Wasm;
+
+impl Backend for Wasm {
+ fn prepare_structure(
+ item: &mut syn::ItemStruct,
+ flavor: &StructureFlavor,
+ ) {
+ if matches!(flavor, StructureFlavor::Class) {
+ structure::skip_public_fields(item);
+ }
+ }
+
+ fn prepare_class(item: &mut syn::ItemStruct) {
+ structure::skip_public_fields(item);
+ }
+
+ fn structure_attributes(context: &StructureContext) -> TokenStream {
+ match context.flavor {
+ StructureFlavor::Plain => quote! {},
+ StructureFlavor::Class => quote! {
+ #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]
+ },
+ }
+ }
+
+ fn structure_companions(context: &StructureContext) -> TokenStream {
+ match context.flavor {
+ StructureFlavor::Plain => structure::plain_structure_companions(context.item),
+ StructureFlavor::Class => structure::class_structure_companions(context.item),
+ }
+ }
+
+ fn class_attributes(_context: &ClassContext) -> TokenStream {
+ quote! {
+ #[cfg_attr(feature = "bindings-wasm", wasm_bindgen::prelude::wasm_bindgen)]
+ }
+ }
+
+ fn class_companions(context: &ClassContext) -> TokenStream {
+ structure::class_companions(context.item)
+ }
+
+ fn enumeration_companions(context: &EnumerationContext) -> TokenStream {
+ match context.shape {
+ EnumerationShape::Unit => enumeration::string_enumeration_companions(context.item),
+ EnumerationShape::Data => enumeration::data_enumeration_companions(context.item),
+ }
+ }
+
+ fn alias_companions(context: &AliasContext) -> TokenStream {
+ let name = context.item.ident.to_string();
+ let declaration = format!("export type {name} = {};", typescript_type(&context.item.ty, &name));
+ typescript::custom_section(&name, &typescript::cfg_attributes(&context.item.attrs), &declaration)
+ }
+
+ fn error_companions(context: &ErrorContext) -> TokenStream {
+ error::error_companions(context)
+ }
+
+ fn method_companions(
+ context: &ImplementationContext,
+ metadata: &MethodMetadata,
+ ) -> TokenStream {
+ method::method_companions(context, metadata)
+ }
+}
diff --git a/crates/legacy/bindings/src/backends/wasm/structure.rs b/crates/legacy/bindings/src/backends/wasm/structure.rs
new file mode 100644
index 000000000..fa5f80288
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/wasm/structure.rs
@@ -0,0 +1,144 @@
+use proc_macro2::TokenStream;
+use quote::quote;
+
+use super::{
+ fields::{
+ accessors, constructor_parameters, field_declarations, field_initializers, named_fields, object_initializers,
+ object_members, object_setters, reject_cfg_fields,
+ },
+ typescript::{cfg_predicate, custom_sections},
+};
+
+/// The name of the hidden method that copies a class value out of a JavaScript object, see
+/// `bindings_types::wasm::take_clone`.
+pub fn clone_method(type_name: &str) -> String {
+ format!("__uzuClone{type_name}")
+}
+
+/// Annotates the public fields of a wasm class so wasm-bindgen doesn't generate its own
+/// snake_case accessors for them; ours are camelCase and convert values like napi.
+pub fn skip_public_fields(item: &mut syn::ItemStruct) {
+ for field in item.fields.iter_mut() {
+ if matches!(field.vis, syn::Visibility::Public(_)) {
+ field.attrs.push(syn::parse_quote! { #[cfg_attr(feature = "bindings-wasm", wasm_bindgen(skip))] });
+ }
+ }
+}
+
+/// A data structure exposed as a class: napi's constructor taking every field in order, a getter and
+/// setter per field, and conversions that copy the value in and out of JavaScript.
+pub fn class_structure_companions(item: &syn::ItemStruct) -> TokenStream {
+ let name = &item.ident;
+ let type_name = name.to_string();
+ let fields = named_fields(&item.fields);
+ if let Some(error) = reject_cfg_fields(&fields) {
+ return error;
+ }
+ let parameters = constructor_parameters(&fields, &type_name);
+ let initializers = field_initializers(&fields);
+ let declarations = field_declarations(&type_name, &[], &fields);
+ let accessors = accessors(
+ &fields,
+ |field| {
+ let ident = field.ident;
+ quote! { &self.#ident }
+ },
+ |field| {
+ let ident = field.ident;
+ quote! { self.#ident = __wasm_value; }
+ },
+ );
+ let clone_method = clone_method(&type_name);
+
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ #[wasm_bindgen::prelude::wasm_bindgen]
+ impl #name {
+ #[wasm_bindgen(constructor)]
+ #[allow(non_snake_case)]
+ pub fn __wasm_new(#(#parameters),*) -> ::core::result::Result<#name, ::wasm_bindgen::JsValue> {
+ ::core::result::Result::Ok(Self { #(#initializers),* })
+ }
+
+ #(#accessors)*
+
+ #[wasm_bindgen(js_name = #clone_method, skip_typescript)]
+ pub fn __wasm_clone_handle(&self) -> ::wasm_bindgen::JsValue {
+ ::bindings_types::wasm::clone_handle(self)
+ }
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::IntoJs for #name {
+ fn into_js(self) -> ::wasm_bindgen::JsValue {
+ ::wasm_bindgen::JsValue::from(self)
+ }
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::FromJs for #name {
+ fn from_js(value: ::wasm_bindgen::JsValue) -> ::bindings_types::wasm::JsResult<Self> {
+ ::bindings_types::wasm::take_clone(&value, #clone_method, #type_name)
+ }
+ }
+
+ #declarations
+ }
+}
+
+/// A data structure exposed as a plain object with camelCase keys, as napi's `object`.
+pub fn plain_structure_companions(item: &syn::ItemStruct) -> TokenStream {
+ let name = &item.ident;
+ let type_name = name.to_string();
+ let fields = named_fields(&item.fields);
+ let setters = object_setters(&fields, |field| {
+ let ident = field.ident;
+ quote! { self.#ident }
+ });
+ let initializers = object_initializers(&fields);
+ let members = object_members(&fields);
+ let predicates: Vec<_> = fields.iter().map(|field| cfg_predicate(field.attributes)).collect();
+ let declarations = custom_sections(&type_name, &predicates, |included| {
+ let members: Vec<_> = members
+ .iter()
+ .zip(included)
+ .filter(|(_, included)| **included)
+ .map(|(member, _)| format!(" {member};\n"))
+ .collect();
+ format!("export interface {type_name} {{\n{}}}", members.concat())
+ });
+
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::IntoJs for #name {
+ fn into_js(self) -> ::wasm_bindgen::JsValue {
+ let object = ::bindings_types::wasm::new_object();
+ #(#setters)*
+ object.into()
+ }
+ }
+
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::FromJs for #name {
+ fn from_js(value: ::wasm_bindgen::JsValue) -> ::bindings_types::wasm::JsResult<Self> {
+ ::bindings_types::wasm::expect_object(&value, #type_name)?;
+ ::core::result::Result::Ok(Self { #(#initializers),* })
+ }
+ }
+
+ #declarations
+ }
+}
+
+/// A class wrapping Rust state (an engine, a session): returned to JavaScript as is.
+pub fn class_companions(item: &syn::ItemStruct) -> TokenStream {
+ let name = &item.ident;
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ impl ::bindings_types::wasm::IntoJs for #name {
+ fn into_js(self) -> ::wasm_bindgen::JsValue {
+ ::wasm_bindgen::JsValue::from(self)
+ }
+ }
+ }
+}
diff --git a/crates/legacy/bindings/src/backends/wasm/typescript.rs b/crates/legacy/bindings/src/backends/wasm/typescript.rs
new file mode 100644
index 000000000..63355bb79
--- /dev/null
+++ b/crates/legacy/bindings/src/backends/wasm/typescript.rs
@@ -0,0 +1,122 @@
+use convert_case::{Case, Casing};
+use heck::ToShoutySnakeCase;
+use proc_macro2::TokenStream;
+use quote::{format_ident, quote};
+
+use crate::backends::typescript::{option_inner, optional_class_field_type, typescript_type};
+
+/// The JavaScript name of a field, parameter, or method, converted exactly as napi-derive does
+/// (same `convert_case` version), so that e.g. `crc32c` becomes `crc32C` in both packages.
+pub fn js_name(rust_name: &str) -> String {
+ rust_name.trim_start_matches("r#").trim_start_matches('_').to_case(Case::Camel)
+}
+
+/// A member of an object type literal or interface, e.g. `name?: string`.
+pub fn object_member(
+ name: &str,
+ ty: &syn::Type,
+) -> String {
+ match option_inner(ty) {
+ Some(inner) => format!("{name}?: {}", typescript_type(inner, "")),
+ None => format!("{name}: {}", typescript_type(ty, "")),
+ }
+}
+
+/// A field of a class, e.g. `name?: string | null`, see `optional_class_field_type`.
+pub fn class_member(
+ name: &str,
+ ty: &syn::Type,
+) -> String {
+ match option_inner(ty) {
+ Some(inner) => format!("{name}?: {}", optional_class_field_type(inner, "")),
+ None => object_member(name, ty),
+ }
+}
+
+/// The `#[cfg(...)]` attributes of an item, to repeat on the code generated for it.
+pub fn cfg_attributes(attributes: &[syn::Attribute]) -> Vec<&syn::Attribute> {
+ attributes.iter().filter(|attribute| attribute.path().is_ident("cfg")).collect()
+}
+
+pub fn doc_attributes(attributes: &[syn::Attribute]) -> Vec<&syn::Attribute> {
+ attributes.iter().filter(|attribute| attribute.path().is_ident("doc")).collect()
+}
+
+/// The combined `#[cfg(...)]` predicate of an item, or `None` when it is unconditional.
+pub fn cfg_predicate(attributes: &[syn::Attribute]) -> Option<TokenStream> {
+ let predicates: Vec<TokenStream> = cfg_attributes(attributes)
+ .into_iter()
+ .filter_map(|attribute| attribute.meta.require_list().ok().map(|list| list.tokens.clone()))
+ .collect();
+ match predicates.len() {
+ 0 => None,
+ 1 => predicates.into_iter().next(),
+ _ => Some(quote! { all(#(#predicates),*) }),
+ }
+}
+
+/// Emits a TypeScript declaration whose content depends on which entries (variants or fields) are
+/// compiled in. `render` receives, per entry, whether it is included. One custom section is emitted
+/// per combination of the entries' distinct `cfg` predicates, each gated on that combination, so the
+/// d.ts always matches what the wasm build contains.
+pub fn custom_sections(
+ type_name: &str,
+ predicates: &[Option<TokenStream>],
+ render: impl Fn(&[bool]) -> String,
+) -> TokenStream {
+ let mut distinct: Vec<(String, TokenStream)> = Vec::new();
+ for predicate in predicates.iter().flatten() {
+ let key = predicate.to_string();
+ if !distinct.iter().any(|(existing, _)| *existing == key) {
+ distinct.push((key, predicate.clone()));
+ }
+ }
+ if distinct.len() > 4 {
+ return syn::Error::new(
+ proc_macro2::Span::call_site(),
+ format!("{type_name} has more than 4 distinct cfg predicates, which bindings::export does not support"),
+ )
+ .to_compile_error();
+ }
+
+ let sections = (0..1usize << distinct.len()).map(|mask| {
+ let enabled = |key: &str| {
+ let index = distinct.iter().position(|(existing, _)| existing == key).expect("collected above");
+ mask & (1 << index) != 0
+ };
+ let gates = distinct.iter().map(|(key, predicate)| {
+ if enabled(key) {
+ quote! { #predicate }
+ } else {
+ quote! { not(#predicate) }
+ }
+ });
+ let included: Vec<bool> =
+ predicates.iter().map(|predicate| predicate.as_ref().is_none_or(|p| enabled(&p.to_string()))).collect();
+ let text = render(&included);
+ let ident = format_ident!("__UZU_TYPESCRIPT_{}_{}", type_name.to_shouty_snake_case(), mask);
+ quote! {
+ #[cfg(all(feature = "bindings-wasm", #(#gates),*))]
+ #[allow(non_upper_case_globals)]
+ #[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
+ const #ident: &'static str = #text;
+ }
+ });
+ quote! { #(#sections)* }
+}
+
+/// Emits one TypeScript declaration, gated like the item it belongs to.
+pub fn custom_section(
+ name: &str,
+ cfgs: &[&syn::Attribute],
+ text: &str,
+) -> TokenStream {
+ let ident = format_ident!("__UZU_TYPESCRIPT_{}", name.to_shouty_snake_case());
+ quote! {
+ #[cfg(feature = "bindings-wasm")]
+ #(#cfgs)*
+ #[allow(non_upper_case_globals)]
+ #[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
+ const #ident: &'static str = #text;
+ }
+}
diff --git a/crates/legacy/bindings/src/contexts/alias_context.rs b/crates/legacy/bindings/src/contexts/alias_context.rs
index bbc9b8121..b8d2404d7 100644
--- a/crates/legacy/bindings/src/contexts/alias_context.rs
+++ b/crates/legacy/bindings/src/contexts/alias_context.rs
@@ -1 +1,3 @@
-pub struct AliasContext;
+pub struct AliasContext<'item> {
+ pub item: &'item syn::ItemType,
+}
diff --git a/crates/legacy/bindings/src/lib.rs b/crates/legacy/bindings/src/lib.rs
index da8f5dd5d..8deb84e40 100644
--- a/crates/legacy/bindings/src/lib.rs
+++ b/crates/legacy/bindings/src/lib.rs
@@ -30,6 +30,16 @@ macro_rules! all_backends {
}};
}
+macro_rules! prepare_all_backends {
+ ($method:ident, $($args:expr),*) => {{
+ $crate::backends::Rust::$method($($args),*);
+ $crate::backends::Napi::$method($($args),*);
+ $crate::backends::Pyo3::$method($($args),*);
+ $crate::backends::Uniffi::$method($($args),*);
+ $crate::backends::Wasm::$method($($args),*);
+ }};
+}
+
#[proc_macro_attribute]
pub fn export(
arguments: TokenStream,
@@ -71,10 +81,11 @@ fn dispatch_structure(
item: TokenStream,
flavor: StructureFlavor,
) -> TokenStream {
- let parsed: syn::ItemStruct = match syn::parse(item) {
+ let mut parsed: syn::ItemStruct = match syn::parse(item) {
Ok(item_struct) => item_struct,
Err(error) => return error.to_compile_error().into(),
};
+ prepare_all_backends!(prepare_structure, &mut parsed, &flavor);
let context = StructureContext {
flavor,
item: &parsed,
@@ -93,10 +104,11 @@ fn dispatch_class(
item: TokenStream,
flavor: ClassFlavor,
) -> TokenStream {
- let parsed: syn::ItemStruct = match syn::parse(item) {
+ let mut parsed: syn::ItemStruct = match syn::parse(item) {
Ok(item_struct) => item_struct,
Err(error) => return error.to_compile_error().into(),
};
+ prepare_all_backends!(prepare_class, &mut parsed);
let context = ClassContext {
flavor,
item: &parsed,
@@ -116,7 +128,9 @@ fn dispatch_alias(item: TokenStream) -> TokenStream {
Ok(item_type) => item_type,
Err(error) => return error.to_compile_error().into(),
};
- let context = AliasContext;
+ let context = AliasContext {
+ item: &parsed,
+ };
let attributes = all_backends!(alias_attributes, &context);
let companions = all_backends!(alias_companions, &context);
quote! {
diff --git a/crates/legacy/cli-tools/src/configs/language.rs b/crates/legacy/cli-tools/src/configs/language.rs
index a16c09e9d..ffa2e8ce8 100644
--- a/crates/legacy/cli-tools/src/configs/language.rs
+++ b/crates/legacy/cli-tools/src/configs/language.rs
@@ -15,6 +15,8 @@ pub struct LanguageConfig {
pub targets: Vec<String>,
pub tools: Vec<String>,
pub bindings: Vec<Bindings>,
- pub examples_path: String,
- pub metadata: LanguageMetadata,
+ #[serde(default)]
+ pub examples_path: Option<String>,
+ #[serde(default)]
+ pub metadata: Option<LanguageMetadata>,
}
diff --git a/crates/legacy/cli-tools/src/configs/lockfile.rs b/crates/legacy/cli-tools/src/configs/lockfile.rs
new file mode 100644
index 000000000..bcef63dcd
--- /dev/null
+++ b/crates/legacy/cli-tools/src/configs/lockfile.rs
@@ -0,0 +1,43 @@
+use std::fs;
+
+use anyhow::{Context, Result, anyhow};
+use serde::{Deserialize, Serialize};
+
+use crate::configs::Paths;
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LockedPackage {
+ pub name: String,
+ pub version: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CargoLock {
+ pub package: Vec<LockedPackage>,
+}
+
+impl CargoLock {
+ pub fn load() -> Result<Self> {
+ let path = Paths::new()?.cargo_lock_path();
+ let body = fs::read_to_string(&path).with_context(|| format!("Failed to read {}", path.display()))?;
+ let lock: CargoLock = toml::from_str(&body)?;
+ Ok(lock)
+ }
+
+ pub fn package_version(
+ &self,
+ name: &str,
+ ) -> Result<String> {
+ let versions = self
+ .package
+ .iter()
+ .filter(|package| package.name == name)
+ .map(|package| package.version.clone())
+ .collect::<Vec<_>>();
+ match versions.as_slice() {
+ [version] => Ok(version.clone()),
+ [] => Err(anyhow!("Package `{name}` not found in Cargo.lock")),
+ _ => Err(anyhow!("Multiple versions of `{name}` in Cargo.lock: {versions:?}")),
+ }
+ }
+}
diff --git a/crates/legacy/cli-tools/src/configs/mod.rs b/crates/legacy/cli-tools/src/configs/mod.rs
index 4fe46eb99..3eed8e5c2 100644
--- a/crates/legacy/cli-tools/src/configs/mod.rs
+++ b/crates/legacy/cli-tools/src/configs/mod.rs
@@ -1,5 +1,6 @@
mod binary;
mod language;
+mod lockfile;
mod paths;
mod platforms;
mod target;
@@ -8,6 +9,7 @@ mod workspace;
pub use binary::BinaryConfig;
pub use language::{LanguageConfig, LanguageMetadata};
+pub use lockfile::{CargoLock, LockedPackage};
pub use paths::Paths;
pub use platforms::{ALL_TARGET, ExampleConfig, HOST_TARGET, PlatformsConfig};
pub use target::TargetConfig;
diff --git a/crates/legacy/cli-tools/src/configs/paths.rs b/crates/legacy/cli-tools/src/configs/paths.rs
index 6ba16ccfc..9f10c990f 100644
--- a/crates/legacy/cli-tools/src/configs/paths.rs
+++ b/crates/legacy/cli-tools/src/configs/paths.rs
@@ -2,7 +2,7 @@ use std::path::PathBuf;
use anyhow::{Context, Result};
-use crate::types::Language;
+use crate::types::{Configuration, Language};
pub struct Paths {
pub manifest_path: PathBuf,
@@ -37,6 +37,14 @@ impl Paths {
self.target_path().join("wheels")
}
+ pub fn target_profile_path(
+ &self,
+ target: &str,
+ configuration: Configuration,
+ ) -> PathBuf {
+ self.target_path().join(target).join(configuration.name())
+ }
+
pub fn artifacts_path(&self) -> PathBuf {
self.target_path().join("cli-tools")
}
@@ -61,6 +69,10 @@ impl Paths {
self.root_path.join("Cargo.toml")
}
+ pub fn cargo_lock_path(&self) -> PathBuf {
+ self.root_path.join("Cargo.lock")
+ }
+
pub fn bindings_path(&self) -> PathBuf {
self.crate_path(&self.main_crate).join("bindings")
}
@@ -94,6 +106,14 @@ impl Paths {
self.bindings_for_language_path(Language::TypeScript).join("src").join("napi")
}
+ pub fn wasm_output_path(&self) -> PathBuf {
+ self.bindings_for_language_path(Language::Wasm).join("src").join("wasm")
+ }
+
+ pub fn wasm_examples_path(&self) -> PathBuf {
+ self.bindings_for_language_path(Language::Wasm).join("examples")
+ }
+
pub fn swift_xcframework_path(&self) -> PathBuf {
self.bindings_for_language_path(Language::Swift).join(format!("{}.xcframework", self.main_crate))
}
diff --git a/crates/legacy/cli-tools/src/configs/platforms.rs b/crates/legacy/cli-tools/src/configs/platforms.rs
index a3c461e54..33e0e8fa3 100644
--- a/crates/legacy/cli-tools/src/configs/platforms.rs
+++ b/crates/legacy/cli-tools/src/configs/platforms.rs
@@ -116,7 +116,11 @@ impl PlatformsConfig {
language: Language,
) -> Result<PathBuf> {
let language_config = self.languages.get(&language).context("Language not found")?;
- Ok(Paths::new()?.root_path.join(&language_config.examples_path))
+ let examples_path = language_config
+ .examples_path
+ .as_ref()
+ .with_context(|| format!("Missing [languages.{}].examples_path", language.name()))?;
+ Ok(Paths::new()?.root_path.join(examples_path))
}
pub fn required_envs_for_target(
diff --git a/crates/legacy/cli-tools/src/languages/mod.rs b/crates/legacy/cli-tools/src/languages/mod.rs
index 94f513561..1b3dffb46 100644
--- a/crates/legacy/cli-tools/src/languages/mod.rs
+++ b/crates/legacy/cli-tools/src/languages/mod.rs
@@ -3,6 +3,7 @@ mod rust;
mod swift;
mod swift_extensions;
mod typescript;
+mod wasm;
use std::path::Path;
@@ -13,9 +14,10 @@ pub use rust::RustLanguageBackend;
pub use swift::SwiftLanguageBackend;
pub use swift_extensions::generate_swift_extensions;
pub use typescript::TypeScriptLanguageBackend;
+pub use wasm::WasmLanguageBackend;
use crate::{
- configs::PlatformsConfig,
+ configs::{HOST_TARGET, PlatformsConfig},
types::{Configuration, Language},
};
@@ -46,6 +48,10 @@ pub trait LanguageBackend {
true
}
+ fn default_targets(&self) -> Vec<String> {
+ vec![HOST_TARGET.to_string()]
+ }
+
fn install(&self) -> Result<()> {
let language = self.language();
let tools = self.config().tools_for_language(language)?;
@@ -100,9 +106,9 @@ pub trait LanguageBackend {
&self,
name: &str,
configuration: Configuration,
- target: String,
+ targets: Vec<String>,
) -> Result<()> {
- let targets = self.resolve_targets("example".to_string(), configuration, vec![target])?;
+ let targets = self.resolve_targets("example".to_string(), configuration, targets)?;
if targets.len() != 1 {
return Err(anyhow!("Expected 1 target for example, got {}", targets.len()));
}
diff --git a/crates/legacy/cli-tools/src/languages/typescript.rs b/crates/legacy/cli-tools/src/languages/typescript.rs
index 8076c56de..656463b16 100644
--- a/crates/legacy/cli-tools/src/languages/typescript.rs
+++ b/crates/legacy/cli-tools/src/languages/typescript.rs
@@ -6,7 +6,7 @@ use crate::{
configs::{ALL_TARGET, Paths, PlatformsConfig},
languages::{LanguageBackend, LanguageBackendTarget},
types::{Command, Configuration, Language},
- utilities::fs::copy_directory,
+ utilities::fs::{copy_directory, recreate_directory, remove_files_with_extension},
};
pub struct TypeScriptLanguageBackend {
@@ -92,16 +92,46 @@ impl LanguageBackend for TypeScriptLanguageBackend {
self.build(Configuration::Release, vec![ALL_TARGET.to_string()])?;
let paths = Paths::new()?;
- let source = paths.bindings_for_language_path(self.language()).join("dist");
+ let bindings_path = paths.bindings_for_language_path(self.language());
+ let source = bindings_path.join("dist");
if !source.exists() {
anyhow::bail!("Missing dist folder at {}", source.display());
}
+ // The umbrella package: the loader requires the binary for the platform it runs on from that
+ // platform's package, which package managers install from `optionalDependencies` when its
+ // `os` and `cpu` match.
let destination = release_path.join("typescript-npm");
- if destination.exists() {
- fs::remove_dir_all(&destination)?;
- }
+ recreate_directory(&destination)?;
copy_directory(&source, &destination)?;
- Ok(())
+ remove_files_with_extension(&destination, "node")?;
+
+ // A package per `napi.targets` entry holding its binary, published before the umbrella package.
+ let platforms_path = release_path.join("typescript-npm-platforms");
+ recreate_directory(&platforms_path)?;
+ Command::napi_create_npm_dirs(&platforms_path).with_current_path(&bindings_path).run()?;
+ copy_platform_binaries(&paths.napi_output_path(), &platforms_path)
+ }
+}
+
+/// Copies each platform package's binary (its `main`) from the napi build output. Fails when one
+/// is missing, which would publish a package that installs but can't load. (`napi artifacts`
+/// would do this, but it resolves absolute paths against its working directory.)
+fn copy_platform_binaries(
+ output_path: &Path,
+ platforms_path: &Path,
+) -> Result<()> {
+ for entry in fs::read_dir(platforms_path)? {
+ let package_path = entry?.path();
+ let manifest: serde_json::Value =
+ serde_json::from_str(&fs::read_to_string(package_path.join("package.json"))?)?;
+ let binary =
+ manifest["main"].as_str().ok_or_else(|| anyhow::anyhow!("Missing `main` in {}", package_path.display()))?;
+ let source = output_path.join(binary);
+ if !source.exists() {
+ anyhow::bail!("Missing {} for {}", source.display(), package_path.display());
+ }
+ fs::copy(&source, package_path.join(binary))?;
}
+ Ok(())
}
diff --git a/crates/legacy/cli-tools/src/languages/wasm.rs b/crates/legacy/cli-tools/src/languages/wasm.rs
new file mode 100644
index 000000000..42fbac1ff
--- /dev/null
+++ b/crates/legacy/cli-tools/src/languages/wasm.rs
@@ -0,0 +1,112 @@
+use std::path::Path;
+
+use anyhow::{Result, anyhow};
+
+use crate::{
+ configs::{ALL_TARGET, CargoLock, Paths, PlatformsConfig},
+ languages::{LanguageBackend, LanguageBackendTarget},
+ types::{Command, Configuration, Language},
+ utilities::fs::{copy_directory, recreate_directory},
+};
+
+pub struct WasmLanguageBackend {
+ config: PlatformsConfig,
+}
+
+impl WasmLanguageBackend {
+ pub fn new(config: PlatformsConfig) -> Self {
+ Self {
+ config,
+ }
+ }
+
+ fn check_wasm_bindgen(&self) -> Result<()> {
+ let required_version = CargoLock::load()?.package_version("wasm-bindgen")?;
+ let install_hint =
+ format!("Install it with: cargo install wasm-bindgen-cli --version {required_version} --locked");
+ let (output, _) = Command::wasm_bindgen_version()
+ .output()
+ .map_err(|_| anyhow!("wasm-bindgen-cli is not installed. {install_hint}"))?;
+ let installed_version = output.split_whitespace().nth(1);
+ if installed_version != Some(required_version.as_str()) {
+ return Err(anyhow!(
+ "wasm-bindgen-cli {required_version} is required (matches the `wasm-bindgen` crate in Cargo.lock), found `{output}`. {install_hint}"
+ ));
+ }
+ Ok(())
+ }
+}
+
+impl LanguageBackend for WasmLanguageBackend {
+ fn config(&self) -> PlatformsConfig {
+ self.config.clone()
+ }
+
+ fn language(&self) -> Language {
+ Language::Wasm
+ }
+
+ fn default_targets(&self) -> Vec<String> {
+ vec![ALL_TARGET.to_string()]
+ }
+
+ fn build_targets(
+ &self,
+ configuration: Configuration,
+ targets: Vec<LanguageBackendTarget>,
+ ) -> Result<()> {
+ self.check_wasm_bindgen()?;
+
+ let paths = Paths::new()?;
+ let bindings_path = paths.bindings_for_language_path(self.language());
+ let output_path = paths.wasm_output_path();
+
+ Command::pnpm_install().with_current_path(&bindings_path).run()?;
+
+ for target in targets {
+ Command::cargo_build(paths.main_crate.clone(), target.name.clone(), target.features.clone(), configuration)
+ .with_envs(self.config.required_envs_for_target(target.name.clone())?)
+ .run()?;
+ let wasm_path =
+ paths.target_profile_path(&target.name, configuration).join(format!("{}.wasm", paths.main_crate));
+ Command::wasm_bindgen(wasm_path, output_path.clone(), paths.main_crate.clone()).run()?;
+ Command::pnpm_run("build").with_current_path(&bindings_path).run()?;
+ }
+ Ok(())
+ }
+
+ fn release(
+ &self,
+ _version: &str,
+ release_path: &Path,
+ ) -> Result<()> {
+ self.build(Configuration::Release, vec![ALL_TARGET.to_string()])?;
+
+ let paths = Paths::new()?;
+ let source = paths.bindings_for_language_path(self.language()).join("dist");
+ if !source.exists() {
+ return Err(anyhow!("Missing dist folder at {}", source.display()));
+ }
+
+ // Published with the TypeScript packages: `@trymirai/uzu` re-exports it for browsers.
+ let destination = release_path.join("wasm-npm");
+ recreate_directory(&destination)?;
+ copy_directory(&source, &destination)
+ }
+
+ fn example_target(
+ &self,
+ name: &str,
+ _configuration: Configuration,
+ _target: LanguageBackendTarget,
+ ) -> Result<()> {
+ let paths = Paths::new()?;
+ let bindings_path = paths.bindings_for_language_path(self.language());
+ let name = self.language().convert_file_name(name);
+ let file_path = paths.wasm_examples_path().join(format!("{name}.{}", self.language().file_extension()));
+ if !file_path.exists() {
+ return Err(anyhow!("Example not found: {}", file_path.display()));
+ }
+ Command::pnpm_examples(&name).with_current_path(&bindings_path).run()
+ }
+}
diff --git a/crates/legacy/cli-tools/src/main.rs b/crates/legacy/cli-tools/src/main.rs
index c9a69de2d..112335f8a 100644
--- a/crates/legacy/cli-tools/src/main.rs
+++ b/crates/legacy/cli-tools/src/main.rs
@@ -1,10 +1,11 @@
use anyhow::{Result, anyhow};
use clap::{CommandFactory, Parser, Subcommand};
use cli_tools::{
- configs::{HOST_TARGET, PlatformsConfig},
+ configs::PlatformsConfig,
hanashi::export_tokenizers,
languages::{
LanguageBackend, PythonLanguageBackend, RustLanguageBackend, SwiftLanguageBackend, TypeScriptLanguageBackend,
+ WasmLanguageBackend,
},
release::run_release,
sync::run_sync,
@@ -37,7 +38,8 @@ enum Commands {
language: Language,
#[arg(value_enum, default_value = "release")]
configuration: Configuration,
- #[arg(long, value_delimiter = ',', default_value = HOST_TARGET)]
+ /// Defaults to `host` (`all` for wasm, which has no host target)
+ #[arg(long, value_delimiter = ',')]
targets: Vec<String>,
},
/// Run tests for a specific language
@@ -84,9 +86,13 @@ fn run_setup(include_platform_specific: bool) -> Result<()> {
}
fn run_verify(config: &PlatformsConfig) -> Result<()> {
+ let host_target = config.host_target()?;
for language in config.languages.keys() {
+ if config.targets_for_language(*language, vec![host_target.clone()])?.is_empty() {
+ continue;
+ }
let backend = language_backend(*language, config.clone())?;
- backend.build(Configuration::Release, vec![config.host_target()?])?;
+ backend.build(Configuration::Release, vec![host_target.clone()])?;
}
let (output, _) = Command::git_status_porcelain().output()?;
if !output.is_empty() {
@@ -105,6 +111,7 @@ fn language_backend(
Language::Python => Ok(Box::new(PythonLanguageBackend::new(config))),
Language::Swift => Ok(Box::new(SwiftLanguageBackend::new(config))),
Language::TypeScript => Ok(Box::new(TypeScriptLanguageBackend::new(config))),
+ Language::Wasm => Ok(Box::new(WasmLanguageBackend::new(config))),
}
}
@@ -125,7 +132,15 @@ async fn main() -> Result<()> {
language,
configuration,
targets,
- }) => language_backend(language, config)?.build(configuration, targets)?,
+ }) => {
+ let backend = language_backend(language, config)?;
+ let targets = if targets.is_empty() {
+ backend.default_targets()
+ } else {
+ targets
+ };
+ backend.build(configuration, targets)?
+ },
Some(Commands::Test {
language,
}) => {
@@ -142,10 +157,11 @@ async fn main() -> Result<()> {
}) => {
let configuration = Configuration::Release;
let backend = language_backend(language, config.clone())?;
+ let targets = backend.default_targets();
if backend.expects_prebuild_for_run() {
- backend.build(configuration, vec![host_target.clone()])?;
+ backend.build(configuration, targets.clone())?;
}
- backend.example(&name, configuration, host_target.clone())?
+ backend.example(&name, configuration, targets)?
},
Some(Commands::Sync {
check,
diff --git a/crates/legacy/cli-tools/src/release/mod.rs b/crates/legacy/cli-tools/src/release/mod.rs
index 279a1aa63..3cc1dee8d 100644
--- a/crates/legacy/cli-tools/src/release/mod.rs
+++ b/crates/legacy/cli-tools/src/release/mod.rs
@@ -11,6 +11,7 @@ use crate::{
configs::{Paths, PlatformsConfig, WorkspaceManifest},
languages::{
LanguageBackend, PythonLanguageBackend, RustLanguageBackend, SwiftLanguageBackend, TypeScriptLanguageBackend,
+ WasmLanguageBackend,
},
sync::run_sync,
types::{Command, Language},
@@ -41,6 +42,10 @@ pub fn run_release(
binaries::stage_binaries(&paths, &platforms, release_path)?;
for language in platforms.languages.keys() {
+ // Not released until the WebGPU kernels land: the package would install but couldn't run a model.
+ if *language == Language::Wasm {
+ continue;
+ }
let backend = backend_for_language(*language, platforms.clone());
backend.release(version, release_path)?;
}
@@ -57,5 +62,6 @@ fn backend_for_language(
Language::Python => Box::new(PythonLanguageBackend::new(config)),
Language::Swift => Box::new(SwiftLanguageBackend::new(config)),
Language::TypeScript => Box::new(TypeScriptLanguageBackend::new(config)),
+ Language::Wasm => Box::new(WasmLanguageBackend::new(config)),
}
}
diff --git a/crates/legacy/cli-tools/src/release/platform.rs b/crates/legacy/cli-tools/src/release/platform.rs
index 03c1cd2da..c7aeddef8 100644
--- a/crates/legacy/cli-tools/src/release/platform.rs
+++ b/crates/legacy/cli-tools/src/release/platform.rs
@@ -15,10 +15,14 @@ pub fn stage_platform(
}
for (language, language_config) in &platforms.languages {
+ let Some(examples_path) = &language_config.examples_path else {
+ continue;
+ };
+
let language_dir = root.join(language.name());
fs::create_dir_all(&language_dir)?;
- let examples_root = paths.root_path.join(&language_config.examples_path);
+ let examples_root = paths.root_path.join(examples_path);
for example_name in platforms.examples.keys() {
let converted_name = language.convert_file_name(example_name);
let source_path = examples_root.join(format!("{converted_name}.{}", language.file_extension()));
diff --git a/crates/legacy/cli-tools/src/sync/docs.rs b/crates/legacy/cli-tools/src/sync/docs.rs
index a534ff5ba..3bb9ebd52 100644
--- a/crates/legacy/cli-tools/src/sync/docs.rs
+++ b/crates/legacy/cli-tools/src/sync/docs.rs
@@ -25,7 +25,10 @@ pub fn sync_docs(
let mut check_errors = Vec::new();
- for language in platforms.languages.keys() {
+ for (language, language_config) in &platforms.languages {
+ if language_config.examples_path.is_none() {
+ continue;
+ }
let source_root = platforms.examples_path_for_language(*language)?;
for example_name in platforms.examples.keys() {
let converted_name = language.convert_file_name(example_name);
diff --git a/crates/legacy/cli-tools/src/sync/mod.rs b/crates/legacy/cli-tools/src/sync/mod.rs
index e8267365e..17b0bfd6e 100644
--- a/crates/legacy/cli-tools/src/sync/mod.rs
+++ b/crates/legacy/cli-tools/src/sync/mod.rs
@@ -11,6 +11,7 @@ mod pyproject;
mod readme;
mod swift_package;
mod toolchains;
+mod wasm_tool;
use anyhow::{Ok, Result, anyhow};
pub use jsr::JsrSyncTask;
@@ -22,6 +23,7 @@ pub use pyproject::PyprojectSyncTask;
pub use readme::ReadmeSyncTask;
pub use swift_package::SwiftPackageSyncTask;
pub use toolchains::ToolchainsSyncTask;
+pub use wasm_tool::WasmToolSyncTask;
use crate::configs::{Paths, PlatformsConfig, WorkspaceManifest};
@@ -90,7 +92,12 @@ pub fn run_sync(check: bool) -> Result<()> {
)?;
let typescript_bindings_path = paths.bindings_for_language_path(Language::TypeScript);
- PackageJsonSyncTask.run(&platforms, &workspace, &typescript_bindings_path.join("package.json"), check)?;
+ PackageJsonSyncTask::new(Language::TypeScript).run(
+ &platforms,
+ &workspace,
+ &typescript_bindings_path.join("package.json"),
+ check,
+ )?;
JsrSyncTask.run(&platforms, &workspace, &typescript_bindings_path.join("jsr.json"), check)?;
JsrSyncTask.run(&platforms, &workspace, &typescript_bindings_path.join("jsr.json.orig"), check)?;
LicenseSyncTask.run(&platforms, &workspace, &typescript_bindings_path.join("LICENSE"), check)?;
@@ -101,6 +108,21 @@ pub fn run_sync(check: bool) -> Result<()> {
check,
)?;
+ let wasm_bindings_path = paths.bindings_for_language_path(Language::Wasm);
+ PackageJsonSyncTask::new(Language::Wasm).run(
+ &platforms,
+ &workspace,
+ &wasm_bindings_path.join("package.json"),
+ check,
+ )?;
+ LicenseSyncTask.run(&platforms, &workspace, &wasm_bindings_path.join("LICENSE"), check)?;
+ WasmToolSyncTask::new(typescript_bindings_path.join("src/tool.ts")).run(
+ &platforms,
+ &workspace,
+ &wasm_bindings_path.join("src/tool.ts"),
+ check,
+ )?;
+
PlaygroundSyncTask.run(&platforms, &workspace, &root_path.join("apps/playground/Project.swift"), check)?;
pi_extension::PiExtensionSyncTask.run(
diff --git a/crates/legacy/cli-tools/src/sync/package_json.rs b/crates/legacy/cli-tools/src/sync/package_json.rs
index eed732f7f..2233f2846 100644
--- a/crates/legacy/cli-tools/src/sync/package_json.rs
+++ b/crates/legacy/cli-tools/src/sync/package_json.rs
@@ -1,5 +1,3 @@
-use std::collections::BTreeSet;
-
use anyhow::{Context, Result};
use regex::Regex;
@@ -9,7 +7,17 @@ use crate::{
types::Language,
};
-pub struct PackageJsonSyncTask;
+pub struct PackageJsonSyncTask {
+ language: Language,
+}
+
+impl PackageJsonSyncTask {
+ pub fn new(language: Language) -> Self {
+ Self {
+ language,
+ }
+ }
+}
impl SyncTask for PackageJsonSyncTask {
fn process(
@@ -27,49 +35,22 @@ impl SyncTask for PackageJsonSyncTask {
output = replace_string_field(&output, "repository", &package.repository)?;
output = replace_string_field(&output, "license", &package.license)?;
- let typescript_targets = platforms
- .languages
- .get(&Language::TypeScript)
- .context("Missing [languages.typescript] in platforms.toml")?
- .targets
- .clone();
-
- let cpu = unique(typescript_targets.iter().map(|target| target_cpu(target)).collect::<Result<Vec<_>>>()?);
- let os = unique(typescript_targets.iter().map(|target| target_os(target)).collect::<Result<Vec<_>>>()?);
-
- output = replace_string_array_field(&output, "cpu", cpu)?;
- output = replace_string_array_field(&output, "os", os)?;
+ // The umbrella package installs anywhere: each target's binary is its own package, which napi
+ // generates with that target's `os` and `cpu` (see the TypeScript release).
+ if self.language == Language::TypeScript {
+ let targets = platforms
+ .languages
+ .get(&self.language)
+ .with_context(|| format!("Missing [languages.{}] in platforms.toml", self.language.name()))?
+ .targets
+ .clone();
+ output = replace_string_array_field(&output, "targets", targets)?;
+ }
Ok(output)
}
}
-fn target_cpu(target: &str) -> Result<String> {
- if target.starts_with("aarch64-") {
- Ok("arm64".to_string())
- } else if target.starts_with("x86_64-") {
- Ok("x64".to_string())
- } else {
- Err(anyhow::anyhow!("Unsupported target arch: {target}"))
- }
-}
-
-fn target_os(target: &str) -> Result<String> {
- if target.contains("-apple-darwin") {
- Ok("darwin".to_string())
- } else if target.contains("-unknown-linux") {
- Ok("linux".to_string())
- } else if target.contains("-pc-windows") {
- Ok("win32".to_string())
- } else {
- Err(anyhow::anyhow!("Unsupported target os: {target}"))
- }
-}
-
-fn unique(values: Vec<String>) -> Vec<String> {
- BTreeSet::from_iter(values).into_iter().collect()
-}
-
fn replace_string_field(
input: &str,
key: &str,
@@ -82,14 +63,20 @@ fn replace_string_field(
Ok(regex.replace(input, replacement.as_str()).into_owned())
}
+/// Replaces the array at `key`, one item per line, indented one level (4 spaces) past the key.
fn replace_string_array_field(
input: &str,
key: &str,
values: Vec<String>,
) -> Result<String> {
- let pattern = format!(r#"("{key}"\s*:\s*)\[[^\]]*\]"#);
+ let pattern = format!(r#"(?m)^([ \t]*)("{key}"\s*:\s*)\[[^\]]*\]"#);
let regex = Regex::new(&pattern)?;
let items = values.iter().map(serde_json::to_string).collect::<Result<Vec<_>, _>>()?;
- let replacement = format!("$1[\n {}\n ]", items.join(",\n "));
- Ok(regex.replace(input, replacement.as_str()).into_owned())
+ Ok(regex
+ .replace(input, |captures: &regex::Captures| {
+ let indent = &captures[1];
+ let items: Vec<String> = items.iter().map(|item| format!("{indent} {item}")).collect();
+ format!("{indent}{}[\n{}\n{indent}]", &captures[2], items.join(",\n"))
+ })
+ .into_owned())
}
diff --git a/crates/legacy/cli-tools/src/sync/readme.rs b/crates/legacy/cli-tools/src/sync/readme.rs
index a9873c565..4cb5f7eff 100644
--- a/crates/legacy/cli-tools/src/sync/readme.rs
+++ b/crates/legacy/cli-tools/src/sync/readme.rs
@@ -57,7 +57,8 @@ impl SyncTask for ReadmeSyncTask {
.get(&primary_language)
.with_context(|| format!("Missing [languages.{}]", primary_language.name()))?
.metadata
- .clone();
+ .clone()
+ .with_context(|| format!("Missing [languages.{}].metadata", primary_language.name()))?;
let badges = resolve_badges(platforms, &metadata.badges, &workspace.workspace.package.version)?;
let template_body = fs::read_to_string(paths.readme_template_path())?;
@@ -124,13 +125,11 @@ fn language_context(
workspace: &WorkspaceManifest,
paths: &Paths,
) -> Result<LanguageContext> {
- let language_config =
- platforms.languages.get(&language).with_context(|| format!("Missing [languages.{}]", language.name()))?;
let fragments_root = paths.readme_fragments_path().join(language.name());
let dependency = render_fragment(&fragments_root.join("dependency.md"), &workspace.workspace.package.version)?;
- let examples_root = paths.root_path.join(&language_config.examples_path);
+ let examples_root = platforms.examples_path_for_language(language)?;
let mut examples = BTreeMap::new();
for name in platforms.examples.keys() {
examples.insert(name.clone(), read_example(&examples_root, language, name)?);
@@ -178,7 +177,10 @@ fn read_example(
fn validate_examples(platforms: &PlatformsConfig) -> Result<()> {
let paths = Paths::new()?;
for (language, language_config) in &platforms.languages {
- let examples_root = paths.root_path.join(&language_config.examples_path);
+ let Some(examples_path) = &language_config.examples_path else {
+ continue;
+ };
+ let examples_root = paths.root_path.join(examples_path);
for name in platforms.examples.keys() {
let converted_name = language.convert_file_name(name);
let path = examples_root.join(format!("{converted_name}.{}", language.file_extension()));
diff --git a/crates/legacy/cli-tools/src/sync/wasm_tool.rs b/crates/legacy/cli-tools/src/sync/wasm_tool.rs
new file mode 100644
index 000000000..27aa544b9
--- /dev/null
+++ b/crates/legacy/cli-tools/src/sync/wasm_tool.rs
@@ -0,0 +1,42 @@
+use std::path::PathBuf;
+
+use anyhow::{Result, anyhow};
+
+use crate::{
+ configs::{PlatformsConfig, WorkspaceManifest},
+ sync::SyncTask,
+};
+
+const NAPI_IMPORT: &str = "from './napi/index';";
+const WASM_IMPORT: &str = "from './wasm/uzu.js';";
+const HEADER: &str =
+ "// Generated by `cargo tools sync` from bindings/typescript/src/tool.ts: edit that file instead.\n\n";
+
+/// Keeps the wasm package's `tool.ts` a copy of the napi package's, importing the wasm bindings,
+/// so both packages offer the same zod tool helpers.
+pub struct WasmToolSyncTask {
+ source: PathBuf,
+}
+
+impl WasmToolSyncTask {
+ pub fn new(source: PathBuf) -> Self {
+ Self {
+ source,
+ }
+ }
+}
+
+impl SyncTask for WasmToolSyncTask {
+ fn process(
+ &self,
+ _platforms: &PlatformsConfig,
+ _workspace: &WorkspaceManifest,
+ _input: &str,
+ ) -> Result<String> {
+ let source = std::fs::read_to_string(&self.source)?;
+ if !source.contains(NAPI_IMPORT) {
+ return Err(anyhow!("Expected `{NAPI_IMPORT}` in {}", self.source.display()));
+ }
+ Ok(format!("{HEADER}{}", source.replace(NAPI_IMPORT, WASM_IMPORT)))
+ }
+}
diff --git a/crates/legacy/cli-tools/src/types/command.rs b/crates/legacy/cli-tools/src/types/command.rs
index 0fcdc644f..425b0cf93 100644
--- a/crates/legacy/cli-tools/src/types/command.rs
+++ b/crates/legacy/cli-tools/src/types/command.rs
@@ -361,6 +361,10 @@ impl Command {
Self::pnpm_run("tsn").with_argument(&path.to_string_lossy())
}
+ pub fn pnpm_examples(name: &str) -> Self {
+ Self::pnpm_run("examples").with_argument("--open").with_argument(&format!("/?example={name}"))
+ }
+
pub fn napi_build(
manifest_path: PathBuf,
target: String,
@@ -384,6 +388,15 @@ impl Command {
};
command
}
+
+ /// Creates a package per `napi.targets` entry under `npm_dir`, named and constrained (`os`, `cpu`)
+ /// the way the napi loader expects.
+ pub fn napi_create_npm_dirs(npm_dir: &Path) -> Self {
+ Self::pnpm_exec()
+ .with_argument("napi")
+ .with_argument("create-npm-dirs")
+ .with_arguments(vec!["--npm-dir".to_string(), npm_dir.to_string_lossy().to_string()])
+ }
}
impl Command {
@@ -467,6 +480,25 @@ impl Command {
}
}
+impl Command {
+ pub fn wasm_bindgen_version() -> Self {
+ Self::new("wasm-bindgen").with_argument("--version")
+ }
+
+ pub fn wasm_bindgen(
+ input_path: PathBuf,
+ output_path: PathBuf,
+ output_name: String,
+ ) -> Self {
+ Self::new("wasm-bindgen")
+ .with_argument(&input_path.to_string_lossy())
+ .with_arguments(vec!["--target".to_string(), "web".to_string()])
+ .with_arguments(vec!["--out-dir".to_string(), output_path.to_string_lossy().to_string()])
+ .with_arguments(vec!["--out-name".to_string(), output_name])
+ .with_argument("--typescript")
+ }
+}
+
impl Command {
pub fn git_status_porcelain() -> Self {
Self::new("git").with_argument("status").with_argument("--porcelain")
diff --git a/crates/legacy/cli-tools/src/types/language.rs b/crates/legacy/cli-tools/src/types/language.rs
index 72239ab61..51f8f701f 100644
--- a/crates/legacy/cli-tools/src/types/language.rs
+++ b/crates/legacy/cli-tools/src/types/language.rs
@@ -11,6 +11,7 @@ pub enum Language {
#[serde(rename = "typescript")]
#[value(name = "typescript")]
TypeScript,
+ Wasm,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -28,6 +29,7 @@ impl Language {
Language::Python => "python".to_string(),
Language::Swift => "swift".to_string(),
Language::TypeScript => "typescript".to_string(),
+ Language::Wasm => "wasm".to_string(),
}
}
@@ -37,6 +39,7 @@ impl Language {
Language::Python => "Python".to_string(),
Language::Swift => "Swift".to_string(),
Language::TypeScript => "TypeScript".to_string(),
+ Language::Wasm => "WebAssembly".to_string(),
}
}
@@ -45,14 +48,14 @@ impl Language {
Language::Rust => "rust",
Language::Python => "python",
Language::Swift => "swift",
- Language::TypeScript => "ts",
+ Language::TypeScript | Language::Wasm => "ts",
}
}
pub fn command_argument_case(&self) -> Case {
match self {
Language::Rust | Language::Python => Case::Snake,
- Language::TypeScript => Case::LowerCamel,
+ Language::TypeScript | Language::Wasm => Case::LowerCamel,
Language::Swift => Case::Kebab,
}
}
@@ -69,7 +72,7 @@ impl Language {
Language::Rust => "rs",
Language::Python => "py",
Language::Swift => "swift",
- Language::TypeScript => "ts",
+ Language::TypeScript | Language::Wasm => "ts",
}
}
diff --git a/crates/legacy/cli-tools/src/utilities/fs.rs b/crates/legacy/cli-tools/src/utilities/fs.rs
index a1efbd48d..73f192eaa 100644
--- a/crates/legacy/cli-tools/src/utilities/fs.rs
+++ b/crates/legacy/cli-tools/src/utilities/fs.rs
@@ -19,3 +19,28 @@ pub fn copy_directory(
}
Ok(())
}
+
+/// Removes `path` if it exists and creates it empty.
+pub fn recreate_directory(path: &Path) -> Result<()> {
+ if path.exists() {
+ fs::remove_dir_all(path)?;
+ }
+ fs::create_dir_all(path)?;
+ Ok(())
+}
+
+/// Removes every file with `extension` under `directory`, recursively.
+pub fn remove_files_with_extension(
+ directory: &Path,
+ extension: &str,
+) -> Result<()> {
+ for entry in fs::read_dir(directory)? {
+ let path = entry?.path();
+ if path.is_dir() {
+ remove_files_with_extension(&path, extension)?;
+ } else if path.extension().is_some_and(|candidate| candidate == extension) {
+ fs::remove_file(&path)?;
+ }
+ }
+ Ok(())
+}
diff --git a/crates/legacy/download-manager/Cargo.toml b/crates/legacy/download-manager/Cargo.toml
index 626a9ebb6..0482948d5 100644
--- a/crates/legacy/download-manager/Cargo.toml
+++ b/crates/legacy/download-manager/Cargo.toml
@@ -37,9 +37,7 @@ bindings-pyo3 = [
bindings-wasm = [
"bindings-types/bindings-wasm",
"dep:wasm-bindgen",
- "dep:serde-wasm-bindgen",
"dep:wasm-bindgen-futures",
- "dep:tsify",
]
[dependencies]
@@ -64,9 +62,7 @@ pyo3-async-runtimes = { workspace = true, optional = true }
pyo3-stub-gen = { workspace = true, optional = true }
inventory = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
-serde-wasm-bindgen = { workspace = true, optional = true }
wasm-bindgen-futures = { workspace = true, optional = true }
-tsify = { workspace = true, optional = true }
[target.'cfg(target_vendor = "apple")'.dependencies]
objc2.workspace = true
diff --git a/crates/legacy/nagare/Cargo.toml b/crates/legacy/nagare/Cargo.toml
index b0148d9ba..e88f554c8 100644
--- a/crates/legacy/nagare/Cargo.toml
+++ b/crates/legacy/nagare/Cargo.toml
@@ -45,9 +45,7 @@ bindings-wasm = [
"bindings-types/bindings-wasm",
"shoji/bindings-wasm",
"dep:wasm-bindgen",
- "dep:serde-wasm-bindgen",
"dep:wasm-bindgen-futures",
- "dep:tsify",
]
[dependencies]
@@ -78,9 +76,7 @@ pyo3-async-runtimes = { workspace = true, optional = true }
pyo3-stub-gen = { workspace = true, optional = true }
inventory = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
-serde-wasm-bindgen = { workspace = true, optional = true }
wasm-bindgen-futures = { workspace = true, optional = true }
-tsify = { workspace = true, optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
tokio = { workspace = true, features = ["full"] }
diff --git a/crates/legacy/nagare/src/chat/bindings_wasm.rs b/crates/legacy/nagare/src/chat/bindings_wasm.rs
index eee89b5df..059e5fc48 100644
--- a/crates/legacy/nagare/src/chat/bindings_wasm.rs
+++ b/crates/legacy/nagare/src/chat/bindings_wasm.rs
@@ -1,4 +1,7 @@
-use bindings_types::js_sys::{Error as JavaScriptError, Function, Promise};
+use bindings_types::{
+ js_sys::{Error as JavaScriptError, Function, Promise},
+ wasm::{FromJs, JsResult, clone_handle, take_clone},
+};
use kiban::rt::MakeSendFuture;
use shoji::types::basic::{ToolFunction, Value};
use uuid::Uuid;
@@ -21,6 +24,9 @@ impl Drop for JavaScriptInvocation {
}
}
+const NATIVE_TOOL_CLONE_METHOD: &str = "__uzuCloneNativeTool";
+
+#[derive(Clone)]
#[wasm_bindgen]
pub struct NativeTool {
descriptor: ToolDescriptor,
@@ -28,16 +34,15 @@ pub struct NativeTool {
#[wasm_bindgen]
impl NativeTool {
- /// The definition uses the serialized ToolFunction shape. The callback receives
- /// JSON arguments and an invocation ID, and returns JSON or a promise of JSON.
+ /// The callback receives the JSON arguments and an invocation ID, and returns JSON or a promise
+ /// of JSON. `cancel` receives the invocation ID when the call is cancelled.
#[wasm_bindgen(constructor)]
pub fn new(
- definition_json: &str,
- invoke_json: Function,
- cancel: Function,
+ #[wasm_bindgen(unchecked_param_type = "ToolFunction")] definition: JsValue,
+ #[wasm_bindgen(unchecked_param_type = "(arg0: string, arg1: string) => Promise<string>")] invoke_json: Function,
+ #[wasm_bindgen(unchecked_param_type = "(arg: string) => void")] cancel: Function,
) -> Result<Self, JsValue> {
- let definition: ToolFunction =
- serde_json::from_str(definition_json).map_err(|error| JavaScriptError::new(&error.to_string()))?;
+ let definition = ToolFunction::from_js(definition)?;
let descriptor = ToolDescriptor::new(
definition.name,
definition.description,
@@ -51,6 +56,17 @@ impl NativeTool {
descriptor,
})
}
+
+ #[wasm_bindgen(js_name = "__uzuCloneNativeTool", skip_typescript)]
+ pub fn clone_handle_bindings_wasm(&self) -> ::wasm_bindgen::JsValue {
+ clone_handle(self)
+ }
+}
+
+impl FromJs for NativeTool {
+ fn from_js(value: JsValue) -> JsResult<Self> {
+ take_clone(&value, NATIVE_TOOL_CLONE_METHOD, "NativeTool")
+ }
}
#[wasm_bindgen]
@@ -64,12 +80,12 @@ impl ChatSession {
session.add_tool(tool.descriptor.clone()).await.map_err(Into::into)
}
- /// Consumes the tool handles; the session retains their callbacks.
#[wasm_bindgen(js_name = addTools)]
pub async fn add_tools_bindings_wasm(
&self,
- tools: Vec<NativeTool>,
+ #[wasm_bindgen(unchecked_param_type = "Array<NativeTool>")] tools: JsValue,
) -> Result<(), JsValue> {
+ let tools = Vec::<NativeTool>::from_js(tools)?;
let mut session = self.clone();
session.add_tools(tools.into_iter().map(|tool| tool.descriptor).collect()).await.map_err(Into::into)
}
diff --git a/crates/legacy/nagare/src/lib.rs b/crates/legacy/nagare/src/lib.rs
index efaeba666..3284c5646 100644
--- a/crates/legacy/nagare/src/lib.rs
+++ b/crates/legacy/nagare/src/lib.rs
@@ -5,7 +5,6 @@ pub mod api;
pub mod chat;
#[cfg(not(target_family = "wasm"))]
pub mod classification;
-#[cfg(not(target_family = "wasm"))]
pub mod decision;
#[cfg(not(target_family = "wasm"))]
pub mod text_to_speech;
diff --git a/crates/legacy/shoji/Cargo.toml b/crates/legacy/shoji/Cargo.toml
index ddc87587e..b2c050782 100644
--- a/crates/legacy/shoji/Cargo.toml
+++ b/crates/legacy/shoji/Cargo.toml
@@ -37,9 +37,7 @@ bindings-pyo3 = [
bindings-wasm = [
"bindings-types/bindings-wasm",
"dep:wasm-bindgen",
- "dep:serde-wasm-bindgen",
"dep:wasm-bindgen-futures",
- "dep:tsify",
]
[dependencies]
@@ -60,9 +58,7 @@ pyo3-async-runtimes = { workspace = true, optional = true }
pyo3-stub-gen = { workspace = true, optional = true }
inventory = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
-serde-wasm-bindgen = { workspace = true, optional = true }
wasm-bindgen-futures = { workspace = true, optional = true }
-tsify = { workspace = true, optional = true }
tokenizers.workspace = true
[build-dependencies]
diff --git a/crates/legacy/uzu/Cargo.toml b/crates/legacy/uzu/Cargo.toml
index db517226b..c0688d644 100644
--- a/crates/legacy/uzu/Cargo.toml
+++ b/crates/legacy/uzu/Cargo.toml
@@ -58,9 +58,7 @@ bindings-wasm = [
"nagare/bindings-wasm",
"download-manager/bindings-wasm",
"dep:wasm-bindgen",
- "dep:serde-wasm-bindgen",
"dep:wasm-bindgen-futures",
- "dep:tsify",
]
[dependencies]
@@ -78,9 +76,7 @@ pyo3-async-runtimes = { workspace = true, optional = true }
pyo3-stub-gen = { workspace = true, optional = true }
inventory = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
-serde-wasm-bindgen = { workspace = true, optional = true }
wasm-bindgen-futures = { workspace = true, optional = true }
-tsify = { workspace = true, optional = true }
nagare.workspace = true
hanashi.workspace = true
bon.workspace = true
diff --git a/crates/legacy/uzu/bindings/typescript/eslint.config.mjs b/crates/legacy/uzu/bindings/typescript/eslint.config.mjs
index 8ce3ebece..1f4584c17 100644
--- a/crates/legacy/uzu/bindings/typescript/eslint.config.mjs
+++ b/crates/legacy/uzu/bindings/typescript/eslint.config.mjs
@@ -25,7 +25,7 @@ export default tseslint.config(
{
patterns: [
{
- regex: '^@trymirai/uzu(/.*)?',
+ regex: '^@trymirai/uzu(/.*)?$',
message: 'Use a relative import, not a package import.',
},
],
diff --git a/crates/legacy/uzu/bindings/typescript/package.json b/crates/legacy/uzu/bindings/typescript/package.json
index 6eaa9222c..c4b6aeee5 100644
--- a/crates/legacy/uzu/bindings/typescript/package.json
+++ b/crates/legacy/uzu/bindings/typescript/package.json
@@ -9,15 +9,12 @@
"repository": "https://github.com/trymirai/uzu",
"license": "MIT",
"packageManager": "[email protected]",
- "os": [
- "darwin"
- ],
- "cpu": [
- "arm64",
- "x64"
- ],
"napi": {
- "binaryName": "uzu"
+ "binaryName": "uzu",
+ "targets": [
+ "aarch64-apple-darwin",
+ "x86_64-apple-darwin"
+ ]
},
"files": [
"**/*"
@@ -62,6 +59,10 @@
},
"exports": {
".": {
+ "browser": {
+ "types": "./dist/browser.d.mts",
+ "default": "./dist/browser.mjs"
+ },
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
diff --git a/crates/legacy/uzu/bindings/typescript/scripts/build b/crates/legacy/uzu/bindings/typescript/scripts/build
index ab57ba085..ce72d3cd0 100755
--- a/crates/legacy/uzu/bindings/typescript/scripts/build
+++ b/crates/legacy/uzu/bindings/typescript/scripts/build
@@ -39,6 +39,9 @@ node scripts/utils/postprocess-files.cjs
mkdir -p dist/napi
cp dist/src/napi/* dist/napi/
+# The browser entry is plain ESM re-exporting the wasm package, see the `browser` export condition
+cp src/browser.mjs src/browser.d.mts dist/
+
# make sure that nothing crashes when we require the output CJS or
# import the output ESM
(cd dist && node -e 'require("@trymirai/uzu")')
diff --git a/crates/legacy/uzu/bindings/typescript/scripts/utils/generate-napi-wrappers.cjs b/crates/legacy/uzu/bindings/typescript/scripts/utils/generate-napi-wrappers.cjs
index 93601ed42..6ef52f2ce 100644
--- a/crates/legacy/uzu/bindings/typescript/scripts/utils/generate-napi-wrappers.cjs
+++ b/crates/legacy/uzu/bindings/typescript/scripts/utils/generate-napi-wrappers.cjs
@@ -39,6 +39,17 @@ function generateEsmDeclarations(commonJsDeclarationsPath, outputPath) {
fs.copyFileSync(commonJsDeclarationsPath, outputPath);
}
+// napi-rs declares string enums as `const enum`, which TypeScript rejects under `isolatedModules`
+// (TS2748) since it can't inline them, even though the binding exports a runtime object for each.
+// Its `constEnum: false` option turns them into string unions, so declare them as plain enums here.
+function declarePlainEnums(declarationsPath) {
+ const content = fs.readFileSync(declarationsPath, 'utf8');
+ const updated = content.replace(/^export declare const enum /gm, 'export declare enum ');
+ if (updated !== content) {
+ fs.writeFileSync(declarationsPath, updated);
+ }
+}
+
function main() {
const napiDir = path.join(__dirname, '../../src/napi');
const commonJsPath = path.join(napiDir, 'index.js');
@@ -62,6 +73,7 @@ function main() {
process.exit(1);
}
+ declarePlainEnums(commonJsDeclarationsPath);
generateEsmWrapper(runtimeExports, esmPath);
generateEsmDeclarations(commonJsDeclarationsPath, esmDeclarationsPath);
@@ -74,6 +86,7 @@ if (require.main === module) {
}
module.exports = {
+ declarePlainEnums,
extractRuntimeExportsFromCommonJs,
generateEsmDeclarations,
generateEsmWrapper,
diff --git a/crates/legacy/uzu/bindings/typescript/scripts/utils/make-dist-package-json.cjs b/crates/legacy/uzu/bindings/typescript/scripts/utils/make-dist-package-json.cjs
index 0bbfd4272..c5a05b1a7 100644
--- a/crates/legacy/uzu/bindings/typescript/scripts/utils/make-dist-package-json.cjs
+++ b/crates/legacy/uzu/bindings/typescript/scripts/utils/make-dist-package-json.cjs
@@ -13,6 +13,22 @@ for (const key of ['types', 'main', 'module']) {
if (typeof pkgJson[key] === 'string') pkgJson[key] = pkgJson[key].replace(/^(\.\/)?dist\//, './');
}
+// Each target's binary is published as its own package (see `napi create-npm-dirs`), named the way
+// the loader requires it. Package managers install the one whose `os` and `cpu` match.
+const { parseTriple } = require('@napi-rs/cli');
+pkgJson.optionalDependencies = Object.fromEntries(
+ pkgJson.napi.targets.map((target) => [
+ `${pkgJson.name}-${parseTriple(target).platformArchABI}`,
+ pkgJson.version,
+ ]),
+);
+
+// Browsers get the same API from the wasm package through the `browser` export condition. It's an
+// optional peer, so that Node installs don't download it.
+const wasmPackageName = require('../../../wasm/package.json').name;
+pkgJson.peerDependencies = { [wasmPackageName]: pkgJson.version };
+pkgJson.peerDependenciesMeta = { [wasmPackageName]: { optional: true } };
+
delete pkgJson.devDependencies;
delete pkgJson.scripts.prepack;
delete pkgJson.scripts.prepublishOnly;
diff --git a/crates/legacy/uzu/bindings/typescript/scripts/utils/postprocess-files.cjs b/crates/legacy/uzu/bindings/typescript/scripts/utils/postprocess-files.cjs
index 7808d35be..458298122 100644
--- a/crates/legacy/uzu/bindings/typescript/scripts/utils/postprocess-files.cjs
+++ b/crates/legacy/uzu/bindings/typescript/scripts/utils/postprocess-files.cjs
@@ -37,6 +37,11 @@ async function postprocess() {
const newExports = {
'.': {
+ // Browsers get the same API from the wasm package, see browser.mjs.
+ browser: {
+ types: './browser.d.mts',
+ default: './browser.mjs',
+ },
require: {
types: './index.d.ts',
default: './index.js',
diff --git a/crates/legacy/uzu/bindings/typescript/src/browser.d.mts b/crates/legacy/uzu/bindings/typescript/src/browser.d.mts
new file mode 100644
index 000000000..123e1f180
--- /dev/null
+++ b/crates/legacy/uzu/bindings/typescript/src/browser.d.mts
@@ -0,0 +1 @@
+export * from '@trymirai/uzu-wasm';
diff --git a/crates/legacy/uzu/bindings/typescript/src/browser.mjs b/crates/legacy/uzu/bindings/typescript/src/browser.mjs
new file mode 100644
index 000000000..80e236c63
--- /dev/null
+++ b/crates/legacy/uzu/bindings/typescript/src/browser.mjs
@@ -0,0 +1,3 @@
+// The browser entry, selected by the `browser` export condition: the same API from the WebAssembly
+// build, an optional peer dependency that browser apps install next to this package.
+export * from '@trymirai/uzu-wasm';
diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts
index 38aa77b44..33714807c 100644
--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts
+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts
@@ -42,7 +42,7 @@ export declare class DownloadState {
get name(): string
}
-export declare const enum DownloadManagerType {
+export declare enum DownloadManagerType {
Native = 'Native',
Universal = 'Universal'
}
@@ -160,7 +160,7 @@ export type ChatSessionError =
| { type: 'NoResponse' }
| { type: 'ToolTurnLimitExceeded'; limit: number }
-export declare const enum ChatSessionState {
+export declare enum ChatSessionState {
Idle = 'Idle',
Generation = 'Generation',
ToolCalling = 'ToolCalling',
@@ -176,7 +176,7 @@ export type ClassificationSessionError =
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
-export declare const enum ClassificationSessionState {
+export declare enum ClassificationSessionState {
Idle = 'Idle',
Classifying = 'Classifying'
}
@@ -190,7 +190,7 @@ export type DecisionSessionError =
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
-export declare const enum DecisionSessionState {
+export declare enum DecisionSessionState {
Idle = 'Idle',
Deciding = 'Deciding'
}
@@ -201,7 +201,7 @@ export type TextToSpeechSessionError =
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
-export declare const enum TextToSpeechSessionState {
+export declare enum TextToSpeechSessionState {
Idle = 'Idle',
Synthesizing = 'Synthesizing'
}
@@ -286,15 +286,15 @@ export declare class ChatContentBlockToolCall {
export declare class ChatContentBlockToolCallCandidate {
value: Value
- identifier?: string
- constructor(value: Value, identifier?: string)
+ identifier?: string | null
+ constructor(value: Value, identifier?: string | null)
}
export declare class ChatContentBlockToolCallResult {
- identifier?: string
- name?: string
+ identifier?: string | null
+ name?: string | null
value: Value
- constructor(identifier?: string, name?: string, value: Value)
+ constructor(identifier?: string | null, name?: string | null, value: Value)
}
export declare class ChatContentBlockTools {
@@ -353,22 +353,22 @@ export declare class ChatModelCapabilities {
export declare class ChatReply {
message: ChatMessage
stats: ChatReplyStats
- finishReason?: ChatReplyFinishReason
- constructor(message: ChatMessage, stats: ChatReplyStats, finishReason?: ChatReplyFinishReason)
+ finishReason?: ChatReplyFinishReason | null
+ constructor(message: ChatMessage, stats: ChatReplyStats, finishReason?: ChatReplyFinishReason | null)
}
export declare class ChatReplyConfig {
- tokenLimit?: number
+ tokenLimit?: number | null
samplingPolicy: SamplingPolicy
- grammar?: Grammar
+ grammar?: Grammar | null
/**
* Maximum number of automatic tool-call turns per reply.
* `None` allows unlimited turns; `Some(0)` prevents automatic tool execution.
*/
- toolTurnLimit?: number
+ toolTurnLimit?: number | null
/** Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`. */
samplingSeed: SamplingSeed
- constructor(tokenLimit?: number, samplingPolicy: SamplingPolicy, grammar?: Grammar, toolTurnLimit?: number, samplingSeed: SamplingSeed)
+ constructor(tokenLimit?: number | null, samplingPolicy: SamplingPolicy, grammar?: Grammar | null, toolTurnLimit?: number | null, samplingSeed: SamplingSeed)
static create(): ChatReplyConfig
withTokenLimit(tokenLimit?: number | undefined | null): ChatReplyConfig
@@ -400,17 +400,17 @@ export declare class ChatReplySpeculatorStats {
export declare class ChatReplyStats {
duration: number
- timeToFirstToken?: number
- prefillTokensPerSecond?: number
- generateTokensPerSecond?: number
- tokensCountInput?: number
- tokensCountInputCached?: number
- tokensCountOutput?: number
- memoryUsedBytes?: number
- speculatorStats?: ChatReplySpeculatorStats
- inputEnergy?: ReplyEnergy
- outputEnergy?: ReplyEnergy
- constructor(duration: number, timeToFirstToken?: number, prefillTokensPerSecond?: number, generateTokensPerSecond?: number, tokensCountInput?: number, tokensCountInputCached?: number, tokensCountOutput?: number, memoryUsedBytes?: number, speculatorStats?: ChatReplySpeculatorStats, inputEnergy?: ReplyEnergy, outputEnergy?: ReplyEnergy)
+ timeToFirstToken?: number | null
+ prefillTokensPerSecond?: number | null
+ generateTokensPerSecond?: number | null
+ tokensCountInput?: number | null
+ tokensCountInputCached?: number | null
+ tokensCountOutput?: number | null
+ memoryUsedBytes?: number | null
+ speculatorStats?: ChatReplySpeculatorStats | null
+ inputEnergy?: ReplyEnergy | null
+ outputEnergy?: ReplyEnergy | null
+ constructor(duration: number, timeToFirstToken?: number | null, prefillTokensPerSecond?: number | null, generateTokensPerSecond?: number | null, tokensCountInput?: number | null, tokensCountInputCached?: number | null, tokensCountOutput?: number | null, memoryUsedBytes?: number | null, speculatorStats?: ChatReplySpeculatorStats | null, inputEnergy?: ReplyEnergy | null, outputEnergy?: ReplyEnergy | null)
get tokensCount(): number | null
get totalJoules(): number | null
get inputJoulesPerToken(): ChatReplyJoulesPerToken | null
@@ -518,8 +518,8 @@ export declare class DecisionInput {
export declare class DecisionOption {
key: string
- description?: string
- constructor(key: string, description?: string)
+ description?: string | null
+ constructor(key: string, description?: string | null)
}
export declare class DecisionOutput {
@@ -528,22 +528,22 @@ export declare class DecisionOutput {
}
export declare class DecisionQuestionChoice {
- instructions?: string
+ instructions?: string | null
options: Array<DecisionOption>
- constructor(instructions?: string, options: Array<DecisionOption>)
+ constructor(instructions?: string | null, options: Array<DecisionOption>)
}
export declare class DecisionQuestionScore {
- instructions?: string
+ instructions?: string | null
levels: Array<string>
- constructor(instructions?: string, levels: Array<string>)
+ constructor(instructions?: string | null, levels: Array<string>)
}
export declare class DecisionQuestionYesNo {
- instructions?: string
- noDescription?: string
- yesDescription?: string
- constructor(instructions?: string, noDescription?: string, yesDescription?: string)
+ instructions?: string | null
+ noDescription?: string | null
+ yesDescription?: string | null
+ constructor(instructions?: string | null, noDescription?: string | null, yesDescription?: string | null)
}
export declare class DecisionResult {
@@ -556,8 +556,8 @@ export declare class DecisionStats {
tokensCount: number
prefillDuration: number
totalDuration: number
- energy?: ReplyEnergy
- constructor(tokensCount: number, prefillDuration: number, totalDuration: number, energy?: ReplyEnergy)
+ energy?: ReplyEnergy | null
+ constructor(tokensCount: number, prefillDuration: number, totalDuration: number, energy?: ReplyEnergy | null)
}
export declare class Feature {
@@ -600,18 +600,18 @@ export declare class Image {
url: string
theme: ImageTheme
format: ImageFormat
- description?: string
- width?: number
- height?: number
- constructor(id: string, url: string, theme: ImageTheme, format: ImageFormat, description?: string, width?: number, height?: number)
+ description?: string | null
+ width?: number | null
+ height?: number | null
+ constructor(id: string, url: string, theme: ImageTheme, format: ImageFormat, description?: string | null, width?: number | null, height?: number | null)
}
export declare class Metadata {
identifier: string
name: string
- description?: string
+ description?: string | null
icons: Array<Image>
- constructor(identifier: string, name: string, description?: string, icons: Array<Image>)
+ constructor(identifier: string, name: string, description?: string | null, icons: Array<Image>)
static external(name: string): Metadata
}
@@ -620,13 +620,13 @@ export declare class Model {
identifier: ModelIdentifier
registry: ModelRegistry
backends: Array<ModelBackend>
- family?: ModelFamily
- properties?: ModelProperties
- quantization?: ModelQuantization
+ family?: ModelFamily | null
+ properties?: ModelProperties | null
+ quantization?: ModelQuantization | null
specializations: Array<ModelSpecialization>
accessibility: ModelAccessibility
- encoding?: Value
- constructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: Value)
+ encoding?: Value | null
+ constructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily | null, properties?: ModelProperties | null, quantization?: ModelQuantization | null, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: Value | null)
get name(): string
get isOnDevice(): boolean
get isRemote(): boolean
@@ -651,8 +651,8 @@ export declare class ModelAccessibilityOnDevice {
}
export declare class ModelAccessibilityRemote {
- repository?: Repository
- constructor(repository?: Repository)
+ repository?: Repository | null
+ constructor(repository?: Repository | null)
}
export declare class ModelBackend {
@@ -674,9 +674,9 @@ export declare class ModelFamily {
export declare class ModelProperties {
identifier: string
size: number
- version?: string
+ version?: string | null
metadata: Metadata
- constructor(identifier: string, size: number, version?: string, metadata: Metadata)
+ constructor(identifier: string, size: number, version?: string | null, metadata: Metadata)
get name(): string
}
@@ -704,10 +704,10 @@ export declare class ModelSourceFilesystem {
export declare class ModelSourceRegistry {
toolchainVersion: string
- repository?: Repository
- sourceRepository?: Repository
+ repository?: Repository | null
+ sourceRepository?: Repository | null
files: Array<File>
- constructor(toolchainVersion: string, repository?: Repository, sourceRepository?: Repository, files: Array<File>)
+ constructor(toolchainVersion: string, repository?: Repository | null, sourceRepository?: Repository | null, files: Array<File>)
}
export declare class ModelSpecializationChat {
@@ -768,9 +768,9 @@ export declare class ReplyEnergyTotal {
export declare class Repository {
identifier: string
- commitHash?: string
- paths?: Array<string>
- constructor(identifier: string, commitHash?: string, paths?: Array<string>)
+ commitHash?: string | null
+ paths?: Array<string> | null
+ constructor(identifier: string, commitHash?: string | null, paths?: Array<string> | null)
}
export declare class SamplingMethodGreedy {
@@ -778,23 +778,23 @@ export declare class SamplingMethodGreedy {
}
export declare class SamplingMethodStochastic {
- temperature?: number
- topK?: number
- topP?: number
- minP?: number
- repetitionPenalty?: number
- suffixRepetitionLength?: number
- constructor(temperature?: number, topK?: number, topP?: number, minP?: number, repetitionPenalty?: number, suffixRepetitionLength?: number)
+ temperature?: number | null
+ topK?: number | null
+ topP?: number | null
+ minP?: number | null
+ repetitionPenalty?: number | null
+ suffixRepetitionLength?: number | null
+ constructor(temperature?: number | null, topK?: number | null, topP?: number | null, minP?: number | null, repetitionPenalty?: number | null, suffixRepetitionLength?: number | null)
}
export declare class SamplingParameters {
- temperature?: number
- topK?: number
- topP?: number
- minP?: number
- repetitionPenalty?: number
- suffixRepetitionLength?: number
- constructor(temperature?: number, topK?: number, topP?: number, minP?: number, repetitionPenalty?: number, suffixRepetitionLength?: number)
+ temperature?: number | null
+ topK?: number | null
+ topP?: number | null
+ minP?: number | null
+ repetitionPenalty?: number | null
+ suffixRepetitionLength?: number | null
+ constructor(temperature?: number | null, topK?: number | null, topP?: number | null, minP?: number | null, repetitionPenalty?: number | null, suffixRepetitionLength?: number | null)
}
export declare class SamplingPolicyCustom {
@@ -837,10 +837,10 @@ export declare class Token {
}
export declare class ToolCall {
- identifier?: string
+ identifier?: string | null
name: string
arguments: any
- constructor(identifier?: string, name: string, arguments: any)
+ constructor(identifier?: string | null, name: string, arguments: any)
}
export declare class ToolDescriptionFunction {
@@ -851,16 +851,16 @@ export declare class ToolDescriptionFunction {
export declare class ToolFunction {
name: string
description: string
- parameters?: any
- returnDefinition?: any
- constructor(name: string, description: string, parameters?: any, returnDefinition?: any)
+ parameters?: Value | null
+ returnDefinition?: Value | null
+ constructor(name: string, description: string, parameters?: Value | null, returnDefinition?: Value | null)
}
export declare class ToolNamespace {
name: string
- description?: string
+ description?: string | null
tools: Array<ToolDescription>
- constructor(name: string, description?: string, tools: Array<ToolDescription>)
+ constructor(name: string, description?: string | null, tools: Array<ToolDescription>)
}
export declare class TranslationPayloadImage {
@@ -892,7 +892,7 @@ export type BackendError =
export type ChatContentBlock =
ChatContentBlockIdentity | ChatContentBlockReasoningEffort | ChatContentBlockConversationStartDate | ChatContentBlockKnowledgeCutoff | ChatContentBlockBuiltinTools | ChatContentBlockTools | ChatContentBlockText | ChatContentBlockImage | ChatContentBlockVideo | ChatContentBlockAudio | ChatContentBlockFile | ChatContentBlockReasoning | ChatContentBlockToolCall | ChatContentBlockToolCallCandidate | ChatContentBlockToolCallResult | ChatContentBlockTranslation | ChatContentBlockCustom
-export declare const enum ChatContentBlockType {
+export declare enum ChatContentBlockType {
Identity = 'Identity',
ReasoningEffort = 'ReasoningEffort',
ConversationStartDate = 'ConversationStartDate',
@@ -916,7 +916,7 @@ export interface ChatMessageMetadata {
values: Record<string, Value>
}
-export declare const enum ChatReplyFinishReason {
+export declare enum ChatReplyFinishReason {
Stop = 'Stop',
Length = 'Length',
Cancelled = 'Cancelled',
@@ -935,7 +935,7 @@ export interface ClassificationOutputProbabilities {
values: Record<string, number>
}
-export declare const enum ClassificationRole {
+export declare enum ClassificationRole {
User = 'User',
Assistant = 'Assistant'
}
@@ -952,19 +952,19 @@ export type DecisionQuestion =
export type Grammar =
GrammarJsonAny | GrammarJsonSchema | GrammarRegex
-export declare const enum HashMethod {
+export declare enum HashMethod {
CRC32C = 'CRC32C',
Sha256 = 'Sha256',
GitBlobSha1 = 'GitBlobSha1'
}
-export declare const enum ImageFormat {
+export declare enum ImageFormat {
Png = 'Png',
Webp = 'Webp',
Svg = 'Svg'
}
-export declare const enum ImageTheme {
+export declare enum ImageTheme {
Light = 'Light',
Dark = 'Dark'
}
@@ -984,7 +984,7 @@ export type ModelSpecialization =
export type PcmBatchError =
| { type: 'UnableToSaveAsWav'; message: string }
-export declare const enum ReasoningEffort {
+export declare enum ReasoningEffort {
Disabled = 'Disabled',
Default = 'Default',
Low = 'Low',
@@ -1019,18 +1019,18 @@ export type TranslationPayload =
/** Chat metadata available without loading model weights or allocating a session. */
export declare class ChatModelInfo {
/** Architectural limit; absent before download or for models without a finite limit. */
- contextLength?: number
+ contextLength?: number | null
capabilities: ChatModelCapabilities
- defaultReasoningEffort?: ReasoningEffort
- constructor(contextLength?: number, capabilities: ChatModelCapabilities, defaultReasoningEffort?: ReasoningEffort)
+ defaultReasoningEffort?: ReasoningEffort | null
+ constructor(contextLength?: number | null, capabilities: ChatModelCapabilities, defaultReasoningEffort?: ReasoningEffort | null)
}
export declare class Device {
- osName?: string
- cpuName?: string
- memoryTotal?: number
+ osName?: string | null
+ cpuName?: string | null
+ memoryTotal?: number | null
homePath: string
- constructor(osName?: string, cpuName?: string, memoryTotal?: number, homePath: string)
+ constructor(osName?: string | null, cpuName?: string | null, memoryTotal?: number | null, homePath: string)
static create(): Device
}
@@ -1107,19 +1107,19 @@ export declare class EngineCallback {
}
export declare class EngineConfig {
- miraiApiKey?: string
- localPath?: string
- huggingfaceApiKey?: string
- openaiApiKey?: string
- anthropicApiKey?: string
- geminiApiKey?: string
- xaiApiKey?: string
- basetenApiKey?: string
- openrouterApiKey?: string
+ miraiApiKey?: string | null
+ localPath?: string | null
+ huggingfaceApiKey?: string | null
+ openaiApiKey?: string | null
+ anthropicApiKey?: string | null
+ geminiApiKey?: string | null
+ xaiApiKey?: string | null
+ basetenApiKey?: string | null
+ openrouterApiKey?: string | null
allowOllamaUsage: boolean
allowLmstudioUsage: boolean
downloadManagerType: DownloadManagerType
- constructor(miraiApiKey?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
+ constructor(miraiApiKey?: string | null, localPath?: string | null, huggingfaceApiKey?: string | null, openaiApiKey?: string | null, anthropicApiKey?: string | null, geminiApiKey?: string | null, xaiApiKey?: string | null, basetenApiKey?: string | null, openrouterApiKey?: string | null, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
static create(): EngineConfig
withMiraiApiKey(miraiApiKey: string): EngineConfig
diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts
index 38aa77b44..33714807c 100644
--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts
+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts
@@ -42,7 +42,7 @@ export declare class DownloadState {
get name(): string
}
-export declare const enum DownloadManagerType {
+export declare enum DownloadManagerType {
Native = 'Native',
Universal = 'Universal'
}
@@ -160,7 +160,7 @@ export type ChatSessionError =
| { type: 'NoResponse' }
| { type: 'ToolTurnLimitExceeded'; limit: number }
-export declare const enum ChatSessionState {
+export declare enum ChatSessionState {
Idle = 'Idle',
Generation = 'Generation',
ToolCalling = 'ToolCalling',
@@ -176,7 +176,7 @@ export type ClassificationSessionError =
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
-export declare const enum ClassificationSessionState {
+export declare enum ClassificationSessionState {
Idle = 'Idle',
Classifying = 'Classifying'
}
@@ -190,7 +190,7 @@ export type DecisionSessionError =
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
-export declare const enum DecisionSessionState {
+export declare enum DecisionSessionState {
Idle = 'Idle',
Deciding = 'Deciding'
}
@@ -201,7 +201,7 @@ export type TextToSpeechSessionError =
| { type: 'UnableToPerformOperationInCurrentState' }
| { type: 'NoResponse' }
-export declare const enum TextToSpeechSessionState {
+export declare enum TextToSpeechSessionState {
Idle = 'Idle',
Synthesizing = 'Synthesizing'
}
@@ -286,15 +286,15 @@ export declare class ChatContentBlockToolCall {
export declare class ChatContentBlockToolCallCandidate {
value: Value
- identifier?: string
- constructor(value: Value, identifier?: string)
+ identifier?: string | null
+ constructor(value: Value, identifier?: string | null)
}
export declare class ChatContentBlockToolCallResult {
- identifier?: string
- name?: string
+ identifier?: string | null
+ name?: string | null
value: Value
- constructor(identifier?: string, name?: string, value: Value)
+ constructor(identifier?: string | null, name?: string | null, value: Value)
}
export declare class ChatContentBlockTools {
@@ -353,22 +353,22 @@ export declare class ChatModelCapabilities {
export declare class ChatReply {
message: ChatMessage
stats: ChatReplyStats
- finishReason?: ChatReplyFinishReason
- constructor(message: ChatMessage, stats: ChatReplyStats, finishReason?: ChatReplyFinishReason)
+ finishReason?: ChatReplyFinishReason | null
+ constructor(message: ChatMessage, stats: ChatReplyStats, finishReason?: ChatReplyFinishReason | null)
}
export declare class ChatReplyConfig {
- tokenLimit?: number
+ tokenLimit?: number | null
samplingPolicy: SamplingPolicy
- grammar?: Grammar
+ grammar?: Grammar | null
/**
* Maximum number of automatic tool-call turns per reply.
* `None` allows unlimited turns; `Some(0)` prevents automatic tool execution.
*/
- toolTurnLimit?: number
+ toolTurnLimit?: number | null
/** Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`. */
samplingSeed: SamplingSeed
- constructor(tokenLimit?: number, samplingPolicy: SamplingPolicy, grammar?: Grammar, toolTurnLimit?: number, samplingSeed: SamplingSeed)
+ constructor(tokenLimit?: number | null, samplingPolicy: SamplingPolicy, grammar?: Grammar | null, toolTurnLimit?: number | null, samplingSeed: SamplingSeed)
static create(): ChatReplyConfig
withTokenLimit(tokenLimit?: number | undefined | null): ChatReplyConfig
@@ -400,17 +400,17 @@ export declare class ChatReplySpeculatorStats {
export declare class ChatReplyStats {
duration: number
- timeToFirstToken?: number
- prefillTokensPerSecond?: number
- generateTokensPerSecond?: number
- tokensCountInput?: number
- tokensCountInputCached?: number
- tokensCountOutput?: number
- memoryUsedBytes?: number
- speculatorStats?: ChatReplySpeculatorStats
- inputEnergy?: ReplyEnergy
- outputEnergy?: ReplyEnergy
- constructor(duration: number, timeToFirstToken?: number, prefillTokensPerSecond?: number, generateTokensPerSecond?: number, tokensCountInput?: number, tokensCountInputCached?: number, tokensCountOutput?: number, memoryUsedBytes?: number, speculatorStats?: ChatReplySpeculatorStats, inputEnergy?: ReplyEnergy, outputEnergy?: ReplyEnergy)
+ timeToFirstToken?: number | null
+ prefillTokensPerSecond?: number | null
+ generateTokensPerSecond?: number | null
+ tokensCountInput?: number | null
+ tokensCountInputCached?: number | null
+ tokensCountOutput?: number | null
+ memoryUsedBytes?: number | null
+ speculatorStats?: ChatReplySpeculatorStats | null
+ inputEnergy?: ReplyEnergy | null
+ outputEnergy?: ReplyEnergy | null
+ constructor(duration: number, timeToFirstToken?: number | null, prefillTokensPerSecond?: number | null, generateTokensPerSecond?: number | null, tokensCountInput?: number | null, tokensCountInputCached?: number | null, tokensCountOutput?: number | null, memoryUsedBytes?: number | null, speculatorStats?: ChatReplySpeculatorStats | null, inputEnergy?: ReplyEnergy | null, outputEnergy?: ReplyEnergy | null)
get tokensCount(): number | null
get totalJoules(): number | null
get inputJoulesPerToken(): ChatReplyJoulesPerToken | null
@@ -518,8 +518,8 @@ export declare class DecisionInput {
export declare class DecisionOption {
key: string
- description?: string
- constructor(key: string, description?: string)
+ description?: string | null
+ constructor(key: string, description?: string | null)
}
export declare class DecisionOutput {
@@ -528,22 +528,22 @@ export declare class DecisionOutput {
}
export declare class DecisionQuestionChoice {
- instructions?: string
+ instructions?: string | null
options: Array<DecisionOption>
- constructor(instructions?: string, options: Array<DecisionOption>)
+ constructor(instructions?: string | null, options: Array<DecisionOption>)
}
export declare class DecisionQuestionScore {
- instructions?: string
+ instructions?: string | null
levels: Array<string>
- constructor(instructions?: string, levels: Array<string>)
+ constructor(instructions?: string | null, levels: Array<string>)
}
export declare class DecisionQuestionYesNo {
- instructions?: string
- noDescription?: string
- yesDescription?: string
- constructor(instructions?: string, noDescription?: string, yesDescription?: string)
+ instructions?: string | null
+ noDescription?: string | null
+ yesDescription?: string | null
+ constructor(instructions?: string | null, noDescription?: string | null, yesDescription?: string | null)
}
export declare class DecisionResult {
@@ -556,8 +556,8 @@ export declare class DecisionStats {
tokensCount: number
prefillDuration: number
totalDuration: number
- energy?: ReplyEnergy
- constructor(tokensCount: number, prefillDuration: number, totalDuration: number, energy?: ReplyEnergy)
+ energy?: ReplyEnergy | null
+ constructor(tokensCount: number, prefillDuration: number, totalDuration: number, energy?: ReplyEnergy | null)
}
export declare class Feature {
@@ -600,18 +600,18 @@ export declare class Image {
url: string
theme: ImageTheme
format: ImageFormat
- description?: string
- width?: number
- height?: number
- constructor(id: string, url: string, theme: ImageTheme, format: ImageFormat, description?: string, width?: number, height?: number)
+ description?: string | null
+ width?: number | null
+ height?: number | null
+ constructor(id: string, url: string, theme: ImageTheme, format: ImageFormat, description?: string | null, width?: number | null, height?: number | null)
}
export declare class Metadata {
identifier: string
name: string
- description?: string
+ description?: string | null
icons: Array<Image>
- constructor(identifier: string, name: string, description?: string, icons: Array<Image>)
+ constructor(identifier: string, name: string, description?: string | null, icons: Array<Image>)
static external(name: string): Metadata
}
@@ -620,13 +620,13 @@ export declare class Model {
identifier: ModelIdentifier
registry: ModelRegistry
backends: Array<ModelBackend>
- family?: ModelFamily
- properties?: ModelProperties
- quantization?: ModelQuantization
+ family?: ModelFamily | null
+ properties?: ModelProperties | null
+ quantization?: ModelQuantization | null
specializations: Array<ModelSpecialization>
accessibility: ModelAccessibility
- encoding?: Value
- constructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: Value)
+ encoding?: Value | null
+ constructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily | null, properties?: ModelProperties | null, quantization?: ModelQuantization | null, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: Value | null)
get name(): string
get isOnDevice(): boolean
get isRemote(): boolean
@@ -651,8 +651,8 @@ export declare class ModelAccessibilityOnDevice {
}
export declare class ModelAccessibilityRemote {
- repository?: Repository
- constructor(repository?: Repository)
+ repository?: Repository | null
+ constructor(repository?: Repository | null)
}
export declare class ModelBackend {
@@ -674,9 +674,9 @@ export declare class ModelFamily {
export declare class ModelProperties {
identifier: string
size: number
- version?: string
+ version?: string | null
metadata: Metadata
- constructor(identifier: string, size: number, version?: string, metadata: Metadata)
+ constructor(identifier: string, size: number, version?: string | null, metadata: Metadata)
get name(): string
}
@@ -704,10 +704,10 @@ export declare class ModelSourceFilesystem {
export declare class ModelSourceRegistry {
toolchainVersion: string
- repository?: Repository
- sourceRepository?: Repository
+ repository?: Repository | null
+ sourceRepository?: Repository | null
files: Array<File>
- constructor(toolchainVersion: string, repository?: Repository, sourceRepository?: Repository, files: Array<File>)
+ constructor(toolchainVersion: string, repository?: Repository | null, sourceRepository?: Repository | null, files: Array<File>)
}
export declare class ModelSpecializationChat {
@@ -768,9 +768,9 @@ export declare class ReplyEnergyTotal {
export declare class Repository {
identifier: string
- commitHash?: string
- paths?: Array<string>
- constructor(identifier: string, commitHash?: string, paths?: Array<string>)
+ commitHash?: string | null
+ paths?: Array<string> | null
+ constructor(identifier: string, commitHash?: string | null, paths?: Array<string> | null)
}
export declare class SamplingMethodGreedy {
@@ -778,23 +778,23 @@ export declare class SamplingMethodGreedy {
}
export declare class SamplingMethodStochastic {
- temperature?: number
- topK?: number
- topP?: number
- minP?: number
- repetitionPenalty?: number
- suffixRepetitionLength?: number
- constructor(temperature?: number, topK?: number, topP?: number, minP?: number, repetitionPenalty?: number, suffixRepetitionLength?: number)
+ temperature?: number | null
+ topK?: number | null
+ topP?: number | null
+ minP?: number | null
+ repetitionPenalty?: number | null
+ suffixRepetitionLength?: number | null
+ constructor(temperature?: number | null, topK?: number | null, topP?: number | null, minP?: number | null, repetitionPenalty?: number | null, suffixRepetitionLength?: number | null)
}
export declare class SamplingParameters {
- temperature?: number
- topK?: number
- topP?: number
- minP?: number
- repetitionPenalty?: number
- suffixRepetitionLength?: number
- constructor(temperature?: number, topK?: number, topP?: number, minP?: number, repetitionPenalty?: number, suffixRepetitionLength?: number)
+ temperature?: number | null
+ topK?: number | null
+ topP?: number | null
+ minP?: number | null
+ repetitionPenalty?: number | null
+ suffixRepetitionLength?: number | null
+ constructor(temperature?: number | null, topK?: number | null, topP?: number | null, minP?: number | null, repetitionPenalty?: number | null, suffixRepetitionLength?: number | null)
}
export declare class SamplingPolicyCustom {
@@ -837,10 +837,10 @@ export declare class Token {
}
export declare class ToolCall {
- identifier?: string
+ identifier?: string | null
name: string
arguments: any
- constructor(identifier?: string, name: string, arguments: any)
+ constructor(identifier?: string | null, name: string, arguments: any)
}
export declare class ToolDescriptionFunction {
@@ -851,16 +851,16 @@ export declare class ToolDescriptionFunction {
export declare class ToolFunction {
name: string
description: string
- parameters?: any
- returnDefinition?: any
- constructor(name: string, description: string, parameters?: any, returnDefinition?: any)
+ parameters?: Value | null
+ returnDefinition?: Value | null
+ constructor(name: string, description: string, parameters?: Value | null, returnDefinition?: Value | null)
}
export declare class ToolNamespace {
name: string
- description?: string
+ description?: string | null
tools: Array<ToolDescription>
- constructor(name: string, description?: string, tools: Array<ToolDescription>)
+ constructor(name: string, description?: string | null, tools: Array<ToolDescription>)
}
export declare class TranslationPayloadImage {
@@ -892,7 +892,7 @@ export type BackendError =
export type ChatContentBlock =
ChatContentBlockIdentity | ChatContentBlockReasoningEffort | ChatContentBlockConversationStartDate | ChatContentBlockKnowledgeCutoff | ChatContentBlockBuiltinTools | ChatContentBlockTools | ChatContentBlockText | ChatContentBlockImage | ChatContentBlockVideo | ChatContentBlockAudio | ChatContentBlockFile | ChatContentBlockReasoning | ChatContentBlockToolCall | ChatContentBlockToolCallCandidate | ChatContentBlockToolCallResult | ChatContentBlockTranslation | ChatContentBlockCustom
-export declare const enum ChatContentBlockType {
+export declare enum ChatContentBlockType {
Identity = 'Identity',
ReasoningEffort = 'ReasoningEffort',
ConversationStartDate = 'ConversationStartDate',
@@ -916,7 +916,7 @@ export interface ChatMessageMetadata {
values: Record<string, Value>
}
-export declare const enum ChatReplyFinishReason {
+export declare enum ChatReplyFinishReason {
Stop = 'Stop',
Length = 'Length',
Cancelled = 'Cancelled',
@@ -935,7 +935,7 @@ export interface ClassificationOutputProbabilities {
values: Record<string, number>
}
-export declare const enum ClassificationRole {
+export declare enum ClassificationRole {
User = 'User',
Assistant = 'Assistant'
}
@@ -952,19 +952,19 @@ export type DecisionQuestion =
export type Grammar =
GrammarJsonAny | GrammarJsonSchema | GrammarRegex
-export declare const enum HashMethod {
+export declare enum HashMethod {
CRC32C = 'CRC32C',
Sha256 = 'Sha256',
GitBlobSha1 = 'GitBlobSha1'
}
-export declare const enum ImageFormat {
+export declare enum ImageFormat {
Png = 'Png',
Webp = 'Webp',
Svg = 'Svg'
}
-export declare const enum ImageTheme {
+export declare enum ImageTheme {
Light = 'Light',
Dark = 'Dark'
}
@@ -984,7 +984,7 @@ export type ModelSpecialization =
export type PcmBatchError =
| { type: 'UnableToSaveAsWav'; message: string }
-export declare const enum ReasoningEffort {
+export declare enum ReasoningEffort {
Disabled = 'Disabled',
Default = 'Default',
Low = 'Low',
@@ -1019,18 +1019,18 @@ export type TranslationPayload =
/** Chat metadata available without loading model weights or allocating a session. */
export declare class ChatModelInfo {
/** Architectural limit; absent before download or for models without a finite limit. */
- contextLength?: number
+ contextLength?: number | null
capabilities: ChatModelCapabilities
- defaultReasoningEffort?: ReasoningEffort
- constructor(contextLength?: number, capabilities: ChatModelCapabilities, defaultReasoningEffort?: ReasoningEffort)
+ defaultReasoningEffort?: ReasoningEffort | null
+ constructor(contextLength?: number | null, capabilities: ChatModelCapabilities, defaultReasoningEffort?: ReasoningEffort | null)
}
export declare class Device {
- osName?: string
- cpuName?: string
- memoryTotal?: number
+ osName?: string | null
+ cpuName?: string | null
+ memoryTotal?: number | null
homePath: string
- constructor(osName?: string, cpuName?: string, memoryTotal?: number, homePath: string)
+ constructor(osName?: string | null, cpuName?: string | null, memoryTotal?: number | null, homePath: string)
static create(): Device
}
@@ -1107,19 +1107,19 @@ export declare class EngineCallback {
}
export declare class EngineConfig {
- miraiApiKey?: string
- localPath?: string
- huggingfaceApiKey?: string
- openaiApiKey?: string
- anthropicApiKey?: string
- geminiApiKey?: string
- xaiApiKey?: string
- basetenApiKey?: string
- openrouterApiKey?: string
+ miraiApiKey?: string | null
+ localPath?: string | null
+ huggingfaceApiKey?: string | null
+ openaiApiKey?: string | null
+ anthropicApiKey?: string | null
+ geminiApiKey?: string | null
+ xaiApiKey?: string | null
+ basetenApiKey?: string | null
+ openrouterApiKey?: string | null
allowOllamaUsage: boolean
allowLmstudioUsage: boolean
downloadManagerType: DownloadManagerType
- constructor(miraiApiKey?: string, localPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
+ constructor(miraiApiKey?: string | null, localPath?: string | null, huggingfaceApiKey?: string | null, openaiApiKey?: string | null, anthropicApiKey?: string | null, geminiApiKey?: string | null, xaiApiKey?: string | null, basetenApiKey?: string | null, openrouterApiKey?: string | null, allowOllamaUsage: boolean, allowLmstudioUsage: boolean, downloadManagerType: DownloadManagerType)
static create(): EngineConfig
withMiraiApiKey(miraiApiKey: string): EngineConfig
diff --git a/crates/legacy/uzu/bindings/typescript/src/tool.ts b/crates/legacy/uzu/bindings/typescript/src/tool.ts
index 4ce0a4131..27677e128 100644
--- a/crates/legacy/uzu/bindings/typescript/src/tool.ts
+++ b/crates/legacy/uzu/bindings/typescript/src/tool.ts
@@ -90,7 +90,8 @@ export class UzuToolFunction<
const expiration = setTimeout(() => {
cancelledInvocations.delete(invocationId);
}, CANCELLED_INVOCATION_RETENTION_MS);
- expiration.unref?.();
+ // Don't keep Node alive for it; browser timers are numbers without `unref`.
+ (expiration as unknown as { unref?: () => void }).unref?.();
const previousExpiration = cancelledInvocations.get(invocationId);
if (previousExpiration !== undefined) {
clearTimeout(previousExpiration);
diff --git a/crates/legacy/uzu/bindings/wasm/.gitignore b/crates/legacy/uzu/bindings/wasm/.gitignore
new file mode 100644
index 000000000..d68508994
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/.gitignore
@@ -0,0 +1,6 @@
+node_modules
+dist
+/*.tgz
+*.wasm
+# wasm-bindgen output: `cargo tools build wasm` generates it, and nothing in CI regenerates it to keep a committed copy current
+src/wasm/
diff --git a/crates/legacy/uzu/bindings/wasm/LICENSE b/crates/legacy/uzu/bindings/wasm/LICENSE
new file mode 100644
index 000000000..4aac6c884
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Mirai Tech Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/crates/legacy/uzu/bindings/wasm/README.md b/crates/legacy/uzu/bindings/wasm/README.md
new file mode 100644
index 000000000..2dfc0efbe
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/README.md
@@ -0,0 +1,44 @@
+# uzu-wasm
+
+WebAssembly build of [uzu](https://github.com/trymirai/uzu) for the browser.
+
+## Usage
+
+Install it next to [`@trymirai/uzu`](https://www.npmjs.com/package/@trymirai/uzu), which re-exports it in browser builds (through the `browser` export condition), so the same import works in Node and in the browser:
+
+```bash
+pnpm add @trymirai/uzu @trymirai/uzu-wasm
+```
+
+```js
+import { Engine, EngineConfig } from '@trymirai/uzu';
+
+const engine = await Engine.create(EngineConfig.create());
+```
+
+Importing `@trymirai/uzu-wasm` directly works too.
+
+The API is the same as [`@trymirai/uzu`](https://www.npmjs.com/package/@trymirai/uzu), except for what the browser build doesn't include: text-to-speech, classification, `Player`, and the `Native` download manager.
+
+Importing the package loads `uzu_bg.wasm` from next to the bindings, so there is no `init()` to call. To load it from another location, import the bindings directly and pass its URL: `import init from '@trymirai/uzu-wasm/wasm/uzu.js'; await init({ module_or_path: url })`. That entry has no `for await` over streams and no zod tool helpers.
+
+## Building
+
+From the repository root:
+
+```bash
+cargo tools build wasm
+```
+
+This compiles `uzu` for `wasm32-unknown-unknown`, generates the bindings into `src/wasm` with `wasm-bindgen`, and builds the package into `dist`.
+
+## Checking the API
+
+This package is meant to have the same TypeScript API as [`@trymirai/uzu`](https://www.npmjs.com/package/@trymirai/uzu), so code written against one compiles against the other. To list where they differ:
+
+```bash
+pnpm check-api # one line per difference
+pnpm check-api --verbose # full TypeScript error chains
+```
+
+It compares the two packages' declarations, so it needs `pnpm install` in both packages and the wasm bindings built with `cargo tools build wasm`.
diff --git a/crates/legacy/uzu/bindings/wasm/examples/index.html b/crates/legacy/uzu/bindings/wasm/examples/index.html
new file mode 100644
index 000000000..a797a3da7
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/examples/index.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+<body>
+ <pre id="output"></pre>
+ <script type="module">
+ const example = new URLSearchParams(location.search).get('example') ?? 'quickStart';
+ import(/* @vite-ignore */ `./${example}.ts`);
+ </script>
+</body>
+</html>
diff --git a/crates/legacy/uzu/bindings/wasm/examples/quickStart.ts b/crates/legacy/uzu/bindings/wasm/examples/quickStart.ts
new file mode 100644
index 000000000..eb1e4fa57
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/examples/quickStart.ts
@@ -0,0 +1,36 @@
+import { ChatConfig, ChatMessage, ChatReplyConfig, Engine, EngineConfig } from '@trymirai/uzu-wasm';
+
+async function main() {
+ let output = document.getElementById('output')!;
+
+ let engineConfig = EngineConfig.create();
+ let engine = await Engine.create(engineConfig);
+
+ let model = await engine.model('alibaba:qwen3.5:0.8b:mirai:mirai-m:4');
+ if (!model) {
+ throw new Error('Model not found');
+ }
+
+ for await (const update of await engine.download(model)) {
+ output.textContent = `Download progress: ${(update.progress * 100).toFixed(2)}%`;
+ }
+
+ let session = await engine.chat(model, ChatConfig.create());
+
+ let messages = [
+ ChatMessage.system().withText('You are a helpful assistant'),
+ ChatMessage.user().withText('Tell me a short, funny story about a robot')
+ ];
+
+ let reply = await session.reply(messages, ChatReplyConfig.create());
+ let message = reply[0]?.message;
+
+ if (message) {
+ output.textContent += `\nReasoning: ${message.reasoning}\nText: ${message.text}`;
+ }
+}
+
+main().catch((error) => {
+ console.error(error);
+ document.getElementById('output')!.textContent += `\nError: ${error}`;
+});
diff --git a/crates/legacy/uzu/bindings/wasm/package.json b/crates/legacy/uzu/bindings/wasm/package.json
new file mode 100644
index 000000000..b829408f7
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/package.json
@@ -0,0 +1,40 @@
+{
+ "name": "@trymirai/uzu-wasm",
+ "version": "0.6.17",
+ "description": "A high-performance inference engine for AI models",
+ "author": "Mirai Tech Inc. <[email protected]>",
+ "types": "dist/index.d.ts",
+ "main": "dist/index.js",
+ "type": "module",
+ "repository": "https://github.com/trymirai/uzu",
+ "license": "MIT",
+ "packageManager": "[email protected]",
+ "files": [
+ "**/*"
+ ],
+ "private": false,
+ "publishConfig": {
+ "access": "public"
+ },
+ "scripts": {
+ "build": "./scripts/build",
+ "lint": "./scripts/lint",
+ "check-api": "./scripts/check-api",
+ "examples": "vite"
+ },
+ "dependencies": {
+ "zod": "^4.2.1"
+ },
+ "devDependencies": {
+ "publint": "^0.2.12",
+ "typescript": "5.8.3",
+ "vite": "^8.3.5"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "default": "./dist/index.js"
+ },
+ "./wasm/*": "./dist/wasm/*"
+ }
+}
diff --git a/crates/legacy/uzu/bindings/wasm/pnpm-lock.yaml b/crates/legacy/uzu/bindings/wasm/pnpm-lock.yaml
new file mode 100644
index 000000000..202256ddf
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/pnpm-lock.yaml
@@ -0,0 +1,743 @@
+---
+lockfileVersion: '9.0'
+
+importers:
+
+ .:
+ configDependencies: {}
+ packageManagerDependencies:
+ pnpm:
+ specifier: 12.9.0
+ version: 12.9.0
+
+packages:
+
+ resolution: {integrity: sha512-/53fHFwP1mBYQjli6h3LBZsocAMjrEY6hCDiomIwdLIFbtxHrWucPg/s8ozOG3K6Qt8yEA78v7fCcNrgZKTlEQ==}
+ cpu: [arm64]
+ os: [android]
+
+ resolution: {integrity: sha512-QI+Md3q3Df0WbDGpqciRw9ge0r7CGbxSlP3HcyIf34/YdZsbmUTl416oWOe3RrkZpVVVCA20f8B9esYrITpArA==}
+ cpu: [x64]
+ os: [android]
+
+ resolution: {integrity: sha512-mWr7fGPYJ12GuvU/q0SyJfj7X/9Eqa5dA6cc+yUUAKRdYEcqW4lQcsDd1ArfxJNSDYooz9X+UhFeVxKO9e/xDA==}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-fr4ns4FyMLptdYbWqW3yc/yvbfQP7D1RBCFUJpSPr7tOzd3JxZvl+Tkvg65kEAGU5wXI6vl3eCOofumEj/n3Gw==}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-4+hZPeJzSSw1oOrfUg+v4QylHv6qKhdgcCnKt9ooryE79p1Z9oyozVJ5em+g6ajbvv6jlH+epnht8/s9Cp5M3Q==}
+ cpu: [x64]
+ os: [freebsd]
+
+ resolution: {integrity: sha512-+mHQSbA6M6W71PyV0IxYu2T43lZA8rAhlw4Gy7EMlyiv8H2GWJAXtUXl2huw7tnsar2AhCRlPn/ZvUv+/mIBkA==}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-U1mBoG27+J/HuWYtVZOQrvbiKnTlDsDVzyroKQqHsJaTHTXi0H5Y+fU1GjUyMcNG5r/EXtbhp9iAwQt64uXTxQ==}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-P5bgei3i6wjlKq6s4PNg/0cvik354upY2wW3YGSfweYTABnAZP2zGzgMc0eO5SHTz934Cbya8Z0YFRdw6MfmCg==}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-oNx2uOo2gVrRckEvz7V+FKeq9HOF0rKNHcCyxRRHSXEXpmP6ZMMgJ+iU/m/zfSGp6bAcC5mvAE270FhAeIeKhA==}
+ cpu: [riscv64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-OChHS7hOlqdBMtZqjIB1QoZGNfzLPSsvTa2kYanf3qso5Q+KgnROQ+uV4a0wRGC6sdshSA63+Ui8MCylRy6iwA==}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-ubZPsDMXS+LEnPa7wZD18E+KTpOAZPt+ms/khfIROt+6Cp0A2kayQA8aIsvV7+jGZD0xoknvaGN/P3v9OisZUg==}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-ElANYUwQuMfWqMJR4m5L5h9zKjvGKcA8hi2put4J1DMx2smVaNGkGnxkgeIYgMjmF7UFxlZDcL4jItkScgsW4A==}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-cqnBKZg5e9fFghmYtgJLyZOAsS1EyLeDVJ0qNsjR7hcc+dq1mWRiDo0erqdj2PGoYaVogyF9WejZSJoKvlfXDw==}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-khqst6QGgHdKs2lEmz0N75qN/EoOcEywNQlRPfBrBrq1SytHra6ro/xViueJkVvDOz9gEO8oYcXTdZeAjErjMg==}
+ cpu: [x64]
+ os: [win32]
+
+ resolution: {integrity: sha512-j2TvoLeSmGypiuVoeRvNdyKAfidMTwwdmFPGIRZJXFhBGduYdioqU0OxaE02G5rib90W1VFmbXY1NG0/roMN3Q==}
+ engines: {node: '>=18.*'}
+ hasBin: true
+
+snapshots:
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optionalDependencies:
+ '@pnpm/exe.android-arm64': 12.9.0
+ '@pnpm/exe.android-x64': 12.9.0
+ '@pnpm/exe.darwin-arm64': 12.9.0
+ '@pnpm/exe.darwin-x64': 12.9.0
+ '@pnpm/exe.freebsd-x64': 12.9.0
+ '@pnpm/exe.linux-arm64': 12.9.0
+ '@pnpm/exe.linux-arm64-musl': 12.9.0
+ '@pnpm/exe.linux-ppc64': 12.9.0
+ '@pnpm/exe.linux-riscv64': 12.9.0
+ '@pnpm/exe.linux-s390x': 12.9.0
+ '@pnpm/exe.linux-x64': 12.9.0
+ '@pnpm/exe.linux-x64-musl': 12.9.0
+ '@pnpm/exe.win32-arm64': 12.9.0
+ '@pnpm/exe.win32-x64': 12.9.0
+
+---
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ dependencies:
+ zod:
+ specifier: ^4.2.1
+ version: 4.6.7
+ devDependencies:
+ publint:
+ specifier: ^0.2.12
+ version: 0.2.12
+ typescript:
+ specifier: 5.8.3
+ version: 5.8.3
+ vite:
+ specifier: ^8.3.5
+ version: 8.3.5
+
+packages:
+
+ '@oxc-project/[email protected]':
+ resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [android]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [android]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [linux]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [win32]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
+
+ resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
+
+ resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==}
+
+ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}
+
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
+ resolution: {integrity: sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==}
+ engines: {node: '>=12'}
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
+
+ resolution: {integrity: sha512-yemi4pMf51WKT7khInJqAvsIGzoqYXblnsz0ql8tM+yi1EKYTY1evX4NAbJrLL/Aanr2HyZeluqU+Oi7MGHokw==}
+ engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}
+
+ resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}
+ deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
+
+ resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
+
+ resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
+
+ resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
+
+ resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
+
+ resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
+
+ resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
+ engines: {node: '>= 12.0.0'}
+
+ resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==}
+ engines: {node: '>=4'}
+
+ resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
+ resolution: {integrity: sha512-gZLxXdjEzE/+mOstGDqR6b0EkhJ+kM6fxM6vUuckuctuVPh80Q6pw/rSZj9s4Gex9GxWtIicO1pc8DB9KZWudw==}
+ engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}
+
+ resolution: {integrity: sha512-awzfKUO7v0FscrSpRoogyNm0sajikhBWpU0QMrW09AMi9n1PoKU6WaIqUzuJSQnpciZZmJ/jMZ2Egfmb/9LiWQ==}
+ engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}
+
+ resolution: {integrity: sha512-263/0NGrn32YFYi4J533qzrQ/krmmrWwhKkzwTuM4f/07ug51odoaNjUexxO4vxlzURHcmYMH1QjvHjsNDKLVg==}
+ engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
+
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
+ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
+ engines: {node: ^10 || ^12 || >=14}
+
+ resolution: {integrity: sha512-YNeUtCVeM4j9nDiTT2OPczmlyzOkIXNtdDZnSuajAxS/nZ6j3t7Vs9SUB4euQNddiltIwu7Tdd3s+hr08fAsMw==}
+ engines: {node: '>=16'}
+ hasBin: true
+
+ resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^20.19.0 || >=22.12.0
+ '@vitejs/devtools': ^0.7.1 || ^0.8.0
+ esbuild: ^0.27.0 || ^0.28.0
+ jiti: '>=1.21.0'
+ less: ^4.0.0
+ sass: ^1.70.0
+ sass-embedded: ^1.70.0
+ stylus: '>=0.54.8'
+ sugarss: ^5.0.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ '@vitejs/devtools':
+ optional: true
+ esbuild:
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
+
+ resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
+
+snapshots:
+
+ '@oxc-project/[email protected]': {}
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]': {}
+
+
+ dependencies:
+ balanced-match: 1.0.2
+
+
+ optionalDependencies:
+ picomatch: 4.0.7
+
+
+ optional: true
+
+ dependencies:
+ fs.realpath: 1.0.0
+ inflight: 1.0.6
+ inherits: 2.0.4
+ minimatch: 5.1.9
+ once: 1.4.0
+
+ dependencies:
+ minimatch: 5.1.9
+
+ dependencies:
+ once: 1.4.0
+ wrappy: 1.0.2
+
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ lightningcss-android-arm64: 1.33.0
+ lightningcss-darwin-arm64: 1.33.0
+ lightningcss-darwin-x64: 1.33.0
+ lightningcss-freebsd-x64: 1.33.0
+ lightningcss-linux-arm-gnueabihf: 1.33.0
+ lightningcss-linux-arm64-gnu: 1.33.0
+ lightningcss-linux-arm64-musl: 1.33.0
+ lightningcss-linux-x64-gnu: 1.33.0
+ lightningcss-linux-x64-musl: 1.33.0
+ lightningcss-win32-arm64-msvc: 1.33.0
+ lightningcss-win32-x64-msvc: 1.33.0
+
+ dependencies:
+ brace-expansion: 2.1.7
+
+
+
+ dependencies:
+ npm-normalize-package-bin: 2.0.0
+
+
+ dependencies:
+ glob: 8.1.0
+ ignore-walk: 5.0.1
+ npm-bundled: 2.0.1
+ npm-normalize-package-bin: 2.0.0
+
+ dependencies:
+ wrappy: 1.0.2
+
+
+
+ dependencies:
+ nanoid: 3.3.20
+ picocolors: 1.1.1
+ source-map-js: 1.2.2
+
+ dependencies:
+ npm-packlist: 5.1.3
+ picocolors: 1.1.1
+ sade: 1.8.1
+
+ dependencies:
+ '@oxc-project/types': 0.156.0
+ '@rolldown/pluginutils': 1.0.1
+ optionalDependencies:
+ '@rolldown/binding-android-arm-eabi': 1.2.16
+ '@rolldown/binding-android-arm64': 1.2.16
+ '@rolldown/binding-darwin-arm64': 1.2.16
+ '@rolldown/binding-darwin-x64': 1.2.16
+ '@rolldown/binding-freebsd-x64': 1.2.16
+ '@rolldown/binding-linux-arm-gnueabihf': 1.2.16
+ '@rolldown/binding-linux-arm64-gnu': 1.2.16
+ '@rolldown/binding-linux-arm64-musl': 1.2.16
+ '@rolldown/binding-linux-ppc64-gnu': 1.2.16
+ '@rolldown/binding-linux-s390x-gnu': 1.2.16
+ '@rolldown/binding-linux-x64-gnu': 1.2.16
+ '@rolldown/binding-linux-x64-musl': 1.2.16
+ '@rolldown/binding-openharmony-arm64': 1.2.16
+ '@rolldown/binding-win32-arm64-msvc': 1.2.16
+ '@rolldown/binding-win32-x64-msvc': 1.2.16
+
+ dependencies:
+ mri: 1.2.0
+
+
+ dependencies:
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.7
+
+
+ dependencies:
+ lightningcss: 1.33.0
+ picomatch: 4.0.7
+ postcss: 8.5.32
+ rolldown: 1.2.16
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ fsevents: 2.3.3
+
+
diff --git a/crates/legacy/uzu/bindings/wasm/scripts/build b/crates/legacy/uzu/bindings/wasm/scripts/build
new file mode 100755
index 000000000..e0ecbdfbd
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/scripts/build
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+
+set -exuo pipefail
+
+cd "$(dirname "$0")/.."
+
+if [ ! -e src/wasm/uzu_bg.wasm ]; then
+ echo "Missing src/wasm/uzu_bg.wasm, run 'cargo tools build wasm' from the repository root" >&2
+ exit 1
+fi
+
+# Build into dist and publish the package from there
+rm -rf dist; mkdir dist
+for file in README.md LICENSE; do
+ if [ -e "${file}" ]; then cp "${file}" dist; fi
+done
+# this converts the export map paths for the dist directory
+node scripts/utils/make-dist-package-json.cjs > dist/package.json
+
+# build index.ts to .js/.d.ts files
+./node_modules/.bin/tsc -p tsconfig.build.json
+
+# wasm-bindgen output is already JS with its own .d.ts files, ship it as is
+mkdir -p dist/wasm
+cp src/wasm/* dist/wasm/
+
+# make sure that nothing crashes when we import the output ESM, which loads the wasm module
+(cd dist && node --input-type=module -e "$(cat ../scripts/utils/file-fetch.mjs)
+await import('@trymirai/uzu-wasm');")
diff --git a/crates/legacy/uzu/bindings/wasm/scripts/check-api b/crates/legacy/uzu/bindings/wasm/scripts/check-api
new file mode 100755
index 000000000..df2e514dd
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/scripts/check-api
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+
+# Compares this package's TypeScript API with @trymirai/uzu (napi), see scripts/utils/check-api.cjs.
+# Needs `pnpm install` in both bindings/wasm and bindings/typescript, and the wasm bindings built
+# with `cargo tools build wasm`.
+
+set -euo pipefail
+
+cd "$(dirname "$0")/.."
+
+node scripts/utils/check-api.cjs "$@"
diff --git a/crates/legacy/uzu/bindings/wasm/scripts/lint b/crates/legacy/uzu/bindings/wasm/scripts/lint
new file mode 100755
index 000000000..2392f5629
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/scripts/lint
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+
+set -e
+
+cd "$(dirname "$0")/.."
+
+echo "==> Building"
+./scripts/build
+
+echo "==> Checking types"
+./node_modules/.bin/tsc
+
+echo "==> Running publint"
+./node_modules/.bin/publint dist
diff --git a/crates/legacy/uzu/bindings/wasm/scripts/utils/check-api.cjs b/crates/legacy/uzu/bindings/wasm/scripts/utils/check-api.cjs
new file mode 100644
index 000000000..27dec588e
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/scripts/utils/check-api.cjs
@@ -0,0 +1,467 @@
+// Checks that @trymirai/uzu-wasm exposes the same TypeScript API as @trymirai/uzu (napi),
+// so code written against one package compiles against the other.
+//
+// The napi package is the reference: wasm may have extras (`free`, `initSync`, ...), but must
+// not lack or change anything napi has. For every napi export, this reports whether wasm is
+// missing it, lacks members, or declares an incompatible type. Incompatible types are found by
+// generating type-level assertions and type-checking them in memory.
+//
+// Types are compared after `Normalize`, which replaces string enums with their string values
+// (TypeScript treats const enums nominally, so identical enums from two packages never match)
+// and drops the members wasm-bindgen adds to every class.
+//
+// Only the declarations are compared. Runtime behavior that the .d.ts doesn't describe
+// (what errors are thrown, whether `init()` is required) needs a runtime test.
+//
+// Usage: node scripts/utils/check-api.cjs [--verbose]
+// Exits with 0 when the APIs match, 1 when they differ, 2 when the check can't run.
+
+const fs = require('fs');
+const path = require('path');
+const ts = require('typescript');
+
+const verbose = process.argv.includes('--verbose');
+
+const packageDirectory = path.resolve(__dirname, '../..');
+const napiEntry = path.resolve(packageDirectory, '../typescript/src/index.ts');
+const wasmEntry = path.resolve(packageDirectory, 'src/index.ts');
+const checkFile = path.join(packageDirectory, '__api_check__.ts');
+
+const compilerOptions = {
+ target: ts.ScriptTarget.ES2022,
+ lib: ['lib.esnext.d.ts', 'lib.dom.d.ts'],
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ strict: true,
+ skipLibCheck: true,
+ noEmit: true,
+ // Both packages take zod as a dependency; an app has one copy, but each package's node_modules
+ // may hold a different version, whose types wouldn't match.
+ baseUrl: packageDirectory,
+ paths: { zod: ['node_modules/zod'] },
+};
+
+// Members wasm-bindgen adds to every class.
+const WASM_BINDGEN_EXTRAS = new Set(['free', '[Symbol.dispose]']);
+
+const UNRESOLVED_MODULE_CODES = new Set([2307, 2792]);
+
+const HELPERS = `
+type Assignable<Expected, Actual extends Expected> = Actual;
+type WasmBindgenExtras = 'free' | typeof Symbol.dispose;
+type Opaque = ArrayBufferView | ArrayBufferLike | Date | RegExp | Error;
+type Normalize<T> = T extends string
+ ? \`\${T}\`
+ : T extends void
+ ? undefined
+ : T extends number | boolean | bigint | symbol | null | Opaque
+ ? T
+ : T extends (...args: infer A) => infer R
+ ? (...args: NormalizeTuple<A>) => Normalize<R>
+ : T extends Promise<infer U>
+ ? Promise<Normalize<U>>
+ : T extends ReadonlyArray<infer U>
+ ? Normalize<U>[]
+ : T extends object
+ ? { [K in keyof T as K extends WasmBindgenExtras ? never : K]: Normalize<T[K]> }
+ : T;
+type NormalizeTuple<T> = { [K in keyof T]: Normalize<T[K]> };
+type Statics<T> = Omit<T, 'prototype'>;
+type Constructor<T> = T extends new (...args: infer A) => infer R ? (...args: NormalizeTuple<A>) => Normalize<R> : never;
+type EnumValues<T> = { [K in keyof T]: T[K] extends string ? \`\${T[K]}\` : T[K] };
+type Common<Expected, Actual> = Pick<Expected, keyof Expected & keyof Actual>;
+`;
+
+function main() {
+ for (const entry of [napiEntry, wasmEntry]) {
+ if (!fs.existsSync(entry)) {
+ fail(`Missing ${path.relative(process.cwd(), entry)}`);
+ }
+ }
+ if (!fs.existsSync(path.join(packageDirectory, 'src/wasm/uzu.d.ts'))) {
+ fail('Missing src/wasm/uzu.d.ts: generate the wasm bindings first with `cargo tools build wasm`.');
+ }
+
+ const program = ts.createProgram([napiEntry, wasmEntry], compilerOptions);
+ const checker = program.getTypeChecker();
+ const napiExports = exportsOf(program, napiEntry);
+ const wasmExports = exportsOf(program, wasmEntry);
+
+ const missing = [];
+ const typeOnly = [];
+ const findings = new Map();
+ const assertions = [];
+ const addFinding = (name, label, message) => {
+ const entries = findings.get(name) ?? [];
+ entries.push({ label, message });
+ findings.set(name, entries);
+ };
+
+ for (const [name, symbol] of napiExports) {
+ const wasmSymbol = wasmExports.get(name);
+ if (!wasmSymbol) {
+ missing.push(name);
+ continue;
+ }
+ if (hasValue(symbol) && !hasValue(wasmSymbol)) {
+ typeOnly.push(name);
+ }
+ // napi exposes a Rust enum with data as a union of one class per variant. Comparing such
+ // a union structurally with anything else only yields `{}` noise, so compare the shape.
+ const napiVariants = variantClasses(checker, symbol);
+ if (napiVariants) {
+ const wasmVariants = variantClasses(checker, wasmSymbol);
+ if (!wasmVariants) {
+ const wasmShape = checker.typeToString(
+ checker.getDeclaredTypeOfSymbol(wasmSymbol),
+ undefined,
+ ts.TypeFormatFlags.InTypeAlias,
+ );
+ addFinding(
+ name,
+ 'shape',
+ `napi is a union of classes (${napiVariants.join(' | ')}), wasm is ${truncate(wasmShape, 160)}`,
+ );
+ continue;
+ }
+ const missingVariants = napiVariants.filter((variant) => !wasmVariants.includes(variant));
+ if (missingVariants.length > 0) {
+ addFinding(name, 'missing variants', missingVariants.join(', '));
+ }
+ }
+ for (const { label, names } of missingMembers(checker, symbol, wasmSymbol)) {
+ addFinding(name, label, names.join(', '));
+ }
+ if (isClass(symbol) && hasPublicConstructor(symbol) && hasValue(wasmSymbol) && !hasPublicConstructor(wasmSymbol)) {
+ addFinding(name, 'constructor', 'wasm has no public constructor');
+ }
+ for (const [label, code] of assertionsFor(name, symbol, wasmSymbol)) {
+ assertions.push({ name, label, code });
+ }
+ }
+
+ const diagnostics = typeCheck(assertions);
+ for (const { assertion, diagnostic } of diagnostics.assertionErrors) {
+ addFinding(assertion.name, assertion.label, describe(diagnostic));
+ }
+ if (diagnostics.setupErrors.length > 0) {
+ for (const diagnostic of diagnostics.setupErrors) {
+ console.error(formatDiagnostic(diagnostic));
+ }
+ fail(
+ 'The check itself failed to type-check. If a module is missing, run `pnpm install` in both ' +
+ 'bindings/typescript and bindings/wasm.',
+ );
+ }
+
+ const sortedFindings = new Map([...findings].sort(([left], [right]) => compareNames(left, right)));
+ report(napiExports.size, missing, typeOnly, sortedFindings);
+ process.exit(missing.length + typeOnly.length + findings.size === 0 ? 0 : 1);
+}
+
+function exportsOf(program, entry) {
+ const checker = program.getTypeChecker();
+ const moduleSymbol = checker.getSymbolAtLocation(program.getSourceFile(entry));
+ const exports = new Map();
+ for (const symbol of checker.getExportsOfModule(moduleSymbol)) {
+ const resolved = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
+ exports.set(symbol.name, resolved);
+ }
+ return new Map([...exports].sort(([left], [right]) => compareNames(left, right)));
+}
+
+function compareNames(left, right) {
+ return left.localeCompare(right, 'en', { sensitivity: 'base' }) || left.localeCompare(right);
+}
+
+function hasValue(symbol) {
+ return (symbol.flags & ts.SymbolFlags.Value) !== 0;
+}
+
+function hasType(symbol) {
+ return (symbol.flags & ts.SymbolFlags.Type) !== 0;
+}
+
+function isClass(symbol) {
+ return (symbol.flags & ts.SymbolFlags.Class) !== 0;
+}
+
+function isEnum(symbol) {
+ return (symbol.flags & ts.SymbolFlags.Enum) !== 0;
+}
+
+function isPublic(declaration) {
+ return !(ts.getCombinedModifierFlags(declaration) & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected));
+}
+
+function hasPublicConstructor(symbol) {
+ return (symbol.declarations ?? []).some(
+ (declaration) =>
+ ts.isClassDeclaration(declaration) &&
+ declaration.members.some((member) => ts.isConstructorDeclaration(member) && isPublic(member)),
+ );
+}
+
+// Returns the variant class names when `symbol` is a type alias for a class or a union of classes.
+function variantClasses(checker, symbol) {
+ if (!(symbol.flags & ts.SymbolFlags.TypeAlias)) {
+ return undefined;
+ }
+ const type = checker.getDeclaredTypeOfSymbol(symbol);
+ const names = (type.isUnion() ? type.types : [type]).map((member) =>
+ member.symbol && member.symbol.flags & ts.SymbolFlags.Class ? member.symbol.name : undefined,
+ );
+ return names.every(Boolean) ? names : undefined;
+}
+
+function typeArguments(symbol) {
+ const declaration = symbol.declarations?.find((candidate) => candidate.typeParameters);
+ const count = declaration?.typeParameters?.length ?? 0;
+ return count === 0 ? '' : `<${Array(count).fill('any').join(', ')}>`;
+}
+
+function memberNames(checker, type, { skip = [] } = {}) {
+ const names = new Set();
+ for (const property of checker.getPropertiesOfType(type)) {
+ if (property.declarations?.some((declaration) => !isPublic(declaration))) {
+ continue;
+ }
+ const name = checker.symbolToString(property);
+ if (!skip.includes(name)) {
+ names.add(name);
+ }
+ }
+ return names;
+}
+
+function missingMembers(checker, symbol, wasmSymbol) {
+ const result = [];
+ const compare = (label, napiType, wasmType, options) => {
+ const wasmNames = memberNames(checker, wasmType, options);
+ const names = [...memberNames(checker, napiType, options)].filter((name) => !wasmNames.has(name));
+ if (names.length > 0) {
+ result.push({ label, names });
+ }
+ };
+
+ const instanceLabel = isEnum(symbol) ? undefined : 'missing members';
+ if (instanceLabel && hasType(wasmSymbol) && !(symbol.flags & ts.SymbolFlags.TypeAlias)) {
+ compare(instanceLabel, checker.getDeclaredTypeOfSymbol(symbol), checker.getDeclaredTypeOfSymbol(wasmSymbol));
+ }
+ if ((isClass(symbol) || isEnum(symbol)) && hasValue(wasmSymbol)) {
+ compare(
+ isEnum(symbol) ? 'missing enum members' : 'missing static members',
+ checker.getTypeOfSymbol(symbol),
+ checker.getTypeOfSymbol(wasmSymbol),
+ { skip: ['prototype'] },
+ );
+ }
+ return result;
+}
+
+// Yields [label, type expression] pairs; each expression fails to type-check on a mismatch.
+function* assertionsFor(name, symbol, wasmSymbol) {
+ const napiType = `N.${name}${typeArguments(symbol)}`;
+ const wasmType = `W.${name}${typeArguments(wasmSymbol)}`;
+ const napiValue = `typeof N.${name}`;
+ const wasmValue = `typeof W.${name}`;
+
+ if (isClass(symbol)) {
+ if (hasType(wasmSymbol)) {
+ yield ['members', `Assignable<Normalize<Common<${napiType}, ${wasmType}>>, Normalize<${wasmType}>>`];
+ }
+ if (hasValue(wasmSymbol)) {
+ const napiStatics = `Statics<${napiValue}>`;
+ const wasmStatics = `Statics<${wasmValue}>`;
+ yield [
+ 'static members',
+ `Assignable<Normalize<Common<${napiStatics}, ${wasmStatics}>>, Normalize<${wasmStatics}>>`,
+ ];
+ if (hasPublicConstructor(symbol) && hasPublicConstructor(wasmSymbol)) {
+ yield ['constructor', `Assignable<Constructor<${napiValue}>, Constructor<${wasmValue}>>`];
+ }
+ }
+ return;
+ }
+
+ if (isEnum(symbol)) {
+ if (hasValue(wasmSymbol)) {
+ const napiMembers = `EnumValues<${napiValue}>`;
+ const wasmMembers = `EnumValues<${wasmValue}>`;
+ yield ['enum members', `Assignable<Common<${napiMembers}, ${wasmMembers}>, ${wasmMembers}>`];
+ }
+ if (hasType(wasmSymbol)) {
+ yield ['values wasm lacks', `Assignable<Normalize<${wasmType}>, Normalize<${napiType}>>`];
+ yield ['values napi lacks', `Assignable<Normalize<${napiType}>, Normalize<${wasmType}>>`];
+ }
+ return;
+ }
+
+ if (symbol.flags & (ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias)) {
+ if (hasType(wasmSymbol)) {
+ yield ['napi shape → wasm type', `Assignable<Normalize<${wasmType}>, Normalize<${napiType}>>`];
+ yield ['wasm shape → napi type', `Assignable<Normalize<${napiType}>, Normalize<${wasmType}>>`];
+ }
+ return;
+ }
+
+ if (symbol.flags & (ts.SymbolFlags.Function | ts.SymbolFlags.Variable) && hasValue(wasmSymbol)) {
+ yield ['signature', `Assignable<Normalize<${napiValue}>, Normalize<${wasmValue}>>`];
+ }
+}
+
+function typeCheck(assertions) {
+ const lines = [
+ `import type * as N from './${relativeImport(napiEntry)}';`,
+ `import type * as W from './${relativeImport(wasmEntry)}';`,
+ ...HELPERS.split('\n'),
+ ];
+ const assertionByLine = new Map();
+ assertions.forEach((assertion, index) => {
+ lines.push(`type _${index} = ${assertion.code};`);
+ assertionByLine.set(lines.length, assertion);
+ });
+ const source = lines.join('\n');
+
+ const host = ts.createCompilerHost(compilerOptions);
+ const getSourceFile = host.getSourceFile.bind(host);
+ host.getSourceFile = (fileName, languageVersion, ...rest) =>
+ fileName === checkFile
+ ? ts.createSourceFile(fileName, source, languageVersion, true)
+ : getSourceFile(fileName, languageVersion, ...rest);
+ const fileExists = host.fileExists.bind(host);
+ host.fileExists = (fileName) => fileName === checkFile || fileExists(fileName);
+ const readFile = host.readFile.bind(host);
+ host.readFile = (fileName) => (fileName === checkFile ? source : readFile(fileName));
+
+ const program = ts.createProgram([checkFile], compilerOptions, host);
+ const assertionErrors = [];
+ const setupErrors = [];
+ for (const diagnostic of ts.getPreEmitDiagnostics(program)) {
+ if (diagnostic.file?.fileName !== checkFile) {
+ // Errors inside the packages' own sources are for their own lint to catch (tool.ts,
+ // for example, relies on Node's timers), but a module that doesn't resolve turns
+ // types into `any` and would make assertions pass silently.
+ if (UNRESOLVED_MODULE_CODES.has(diagnostic.code)) {
+ setupErrors.push(diagnostic);
+ }
+ continue;
+ }
+ const line = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start).line + 1;
+ const assertion = assertionByLine.get(line);
+ if (assertion) {
+ assertionErrors.push({ assertion, diagnostic });
+ } else {
+ setupErrors.push(diagnostic);
+ }
+ }
+ return { assertionErrors, setupErrors };
+}
+
+function relativeImport(file) {
+ return path.relative(packageDirectory, file).replace(/\\/g, '/').replace(/\.ts$/, '');
+}
+
+// Condenses TypeScript's elaboration chain into "at <member path>: <innermost reason>". The
+// headline ("does not satisfy the constraint") only restates the assertion, so it is dropped.
+function describe(diagnostic) {
+ const lines = ts
+ .flattenDiagnosticMessageText(diagnostic.messageText, '\n')
+ .split('\n')
+ .map((line) => line.trim().replace(/import\("[^"]+"\)\./g, ''));
+ const chain = lines.length > 1 ? lines.slice(1) : lines;
+ if (verbose) {
+ return chain.join('\n');
+ }
+
+ const segments = [];
+ for (const line of chain) {
+ const match =
+ line.match(/^Types of property '(.+?)' are incompatible/) ??
+ line.match(/^The types of '(.+?)' are incompatible/) ??
+ line.match(/^The types returned by '(.+?)' are incompatible/);
+ if (match) {
+ segments.push(match[1]);
+ continue;
+ }
+ const parameter = line.match(/^Types of parameters '(.+?)' and '(.+?)' are incompatible/);
+ if (parameter) {
+ segments.push(`(${parameter[1]})`);
+ }
+ }
+ const reason = truncate(chain[chain.length - 1], 240);
+ const location = segments.join('.').replace(/\.\(/g, '(');
+ return location ? `at ${location}: ${reason}` : reason;
+}
+
+function truncate(text, length) {
+ return text.length <= length ? text : `${text.slice(0, length - 1)}…`;
+}
+
+function formatDiagnostic(diagnostic) {
+ return ts.formatDiagnostic(diagnostic, {
+ getCanonicalFileName: (fileName) => fileName,
+ getCurrentDirectory: () => process.cwd(),
+ getNewLine: () => '\n',
+ });
+}
+
+function report(total, missing, typeOnly, findings) {
+ const matching = total - new Set([...missing, ...typeOnly, ...findings.keys()]).size;
+ console.log(`API check: @trymirai/uzu-wasm against @trymirai/uzu (${total} exports, ${matching} match)\n`);
+
+ if (missing.length > 0) {
+ console.log(`Missing from wasm (${missing.length}):`);
+ console.log(wrap(missing.join(', '), ' '));
+ console.log();
+ }
+
+ if (typeOnly.length > 0) {
+ console.log(`Type only in wasm, no runtime value (${typeOnly.length}):`);
+ console.log(wrap(typeOnly.join(', '), ' '));
+ console.log();
+ }
+
+ if (findings.size > 0) {
+ console.log(`Different (${findings.size}):`);
+ for (const [name, entries] of findings) {
+ console.log(` ${name}`);
+ for (const { label, message } of entries) {
+ const [first, ...rest] = message.split('\n');
+ console.log(` ${label}: ${first}`);
+ for (const line of rest) {
+ console.log(` ${line}`);
+ }
+ }
+ }
+ console.log();
+ }
+
+ if (missing.length + typeOnly.length + findings.size === 0) {
+ console.log('The APIs match.');
+ }
+}
+
+function wrap(text, indent, width = 100) {
+ const lines = [];
+ let line = '';
+ for (const word of text.split(' ')) {
+ if (line && indent.length + line.length + word.length + 1 > width) {
+ lines.push(indent + line);
+ line = word;
+ } else {
+ line = line ? `${line} ${word}` : word;
+ }
+ }
+ if (line) {
+ lines.push(indent + line);
+ }
+ return lines.join('\n');
+}
+
+function fail(message) {
+ console.error(message);
+ process.exit(2);
+}
+
+main();
diff --git a/crates/legacy/uzu/bindings/wasm/scripts/utils/file-fetch.mjs b/crates/legacy/uzu/bindings/wasm/scripts/utils/file-fetch.mjs
new file mode 100644
index 000000000..1b9da564f
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/scripts/utils/file-fetch.mjs
@@ -0,0 +1,12 @@
+// The package entry fetches `uzu_bg.wasm` next to the bindings, but Node's fetch can't read file:
+// URLs. Prepend this to scripts that import the package in Node.
+import { readFile } from 'node:fs/promises';
+
+const networkFetch = globalThis.fetch;
+globalThis.fetch = async (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : String(input));
+ if (url.protocol !== 'file:') {
+ return networkFetch(input, init);
+ }
+ return new Response(await readFile(url), { headers: { 'Content-Type': 'application/wasm' } });
+};
diff --git a/crates/legacy/uzu/bindings/wasm/scripts/utils/make-dist-package-json.cjs b/crates/legacy/uzu/bindings/wasm/scripts/utils/make-dist-package-json.cjs
new file mode 100644
index 000000000..0bbfd4272
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/scripts/utils/make-dist-package-json.cjs
@@ -0,0 +1,21 @@
+const pkgJson = require(process.env['PKG_JSON_PATH'] || '../../package.json');
+
+function processExportMap(m) {
+ for (const key in m) {
+ const value = m[key];
+ if (typeof value === 'string') m[key] = value.replace(/^\.\/dist\//, './');
+ else processExportMap(value);
+ }
+}
+processExportMap(pkgJson.exports);
+
+for (const key of ['types', 'main', 'module']) {
+ if (typeof pkgJson[key] === 'string') pkgJson[key] = pkgJson[key].replace(/^(\.\/)?dist\//, './');
+}
+
+delete pkgJson.devDependencies;
+delete pkgJson.scripts.prepack;
+delete pkgJson.scripts.prepublishOnly;
+delete pkgJson.scripts.prepare;
+
+console.log(JSON.stringify(pkgJson, null, 2));
diff --git a/crates/legacy/uzu/bindings/wasm/src/index.ts b/crates/legacy/uzu/bindings/wasm/src/index.ts
new file mode 100644
index 000000000..858bcb250
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/src/index.ts
@@ -0,0 +1,33 @@
+import init, * as bindings from './wasm/uzu.js';
+
+// Like @trymirai/uzu, the package is ready once imported: this loads `uzu_bg.wasm` from next to the
+// bindings. To load it from elsewhere, import `@trymirai/uzu-wasm/wasm/uzu.js` and call its `init`.
+await init();
+
+installAsyncIterators();
+
+export * from './wasm/uzu.js';
+export * from './tool.js';
+
+interface Stream {
+ next(): Promise<unknown>;
+}
+
+// napi streams are async iterables. wasm-bindgen can't declare `[Symbol.asyncIterator]`, so the
+// bindings mark stream classes with a static `__uzuStream` getter and declare the method in the d.ts.
+function installAsyncIterators(): void {
+ for (const value of Object.values(bindings)) {
+ if (typeof value !== 'function' || (value as { __uzuStream?: unknown }).__uzuStream !== true) {
+ continue;
+ }
+ Object.defineProperty(value.prototype, Symbol.asyncIterator, {
+ configurable: true,
+ writable: true,
+ value: async function* (this: Stream) {
+ for (let item = await this.next(); item !== null && item !== undefined; item = await this.next()) {
+ yield item;
+ }
+ },
+ });
+ }
+}
diff --git a/crates/legacy/uzu/bindings/wasm/src/tool.ts b/crates/legacy/uzu/bindings/wasm/src/tool.ts
new file mode 100644
index 000000000..705cd0c01
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/src/tool.ts
@@ -0,0 +1,147 @@
+// Generated by `cargo tools sync` from bindings/typescript/src/tool.ts: edit that file instead.
+
+import * as z from 'zod';
+
+import { NativeTool, ToolFunction, Value } from './wasm/uzu.js';
+
+const CANCELLED_INVOCATION_RETENTION_MS = 30_000;
+
+export interface UzuToolContext {
+ readonly signal: AbortSignal;
+}
+
+export interface UzuToolInvokeOptions {
+ readonly signal?: AbortSignal;
+}
+
+export interface UzuToolFunctionOptions<Parameters extends z.ZodObject, ResultSchema extends z.ZodType> {
+ readonly name: string;
+ readonly description?: string;
+ readonly parameters: Parameters;
+ readonly returns: ResultSchema;
+ readonly handler: (
+ parameters: z.output<Parameters>,
+ context: UzuToolContext,
+ ) => z.input<ResultSchema> | Promise<z.input<ResultSchema>>;
+}
+
+export class UzuToolFunction<
+ Parameters extends z.ZodObject,
+ ResultSchema extends z.ZodType,
+> extends NativeTool {
+ readonly name: string;
+ readonly description: string;
+ readonly parameters: Parameters;
+ readonly returns: ResultSchema;
+ readonly parametersSchema: Record<string, unknown>;
+ readonly returnSchema: Record<string, unknown>;
+ readonly handler: UzuToolFunctionOptions<Parameters, ResultSchema>['handler'];
+
+ constructor(options: UzuToolFunctionOptions<Parameters, ResultSchema>) {
+ const name = options.name.trim();
+ if (!name) {
+ throw new TypeError('tool name must not be empty');
+ }
+
+ const description = options.description ?? '';
+ const parametersSchema = z.toJSONSchema(options.parameters);
+ const returnSchema = z.toJSONSchema(options.returns);
+ const activeInvocations = new Map<string, AbortController>();
+ const cancelledInvocations = new Map<string, ReturnType<typeof setTimeout>>();
+
+ const takeCancellation = (invocationId: string): boolean => {
+ const expiration = cancelledInvocations.get(invocationId);
+ if (expiration === undefined) {
+ return false;
+ }
+ clearTimeout(expiration);
+ cancelledInvocations.delete(invocationId);
+ return true;
+ };
+
+ const invokeJson = async (argumentsJson: string, invocationId: string): Promise<string> => {
+ const controller = new AbortController();
+ activeInvocations.set(invocationId, controller);
+ if (takeCancellation(invocationId)) {
+ controller.abort();
+ }
+
+ try {
+ const rawArguments: unknown = JSON.parse(argumentsJson);
+ const parameters = await options.parameters.parseAsync(rawArguments);
+ const rawResult = await options.handler(parameters, {
+ signal: controller.signal,
+ });
+ const result = await options.returns.parseAsync(rawResult);
+ return serializeResult(result);
+ } finally {
+ activeInvocations.delete(invocationId);
+ takeCancellation(invocationId);
+ }
+ };
+ const cancel = (invocationId: string): void => {
+ const controller = activeInvocations.get(invocationId);
+ if (controller) {
+ controller.abort();
+ return;
+ }
+
+ // Invocation and cancellation use separate nonblocking native callbacks, so
+ // cancellation can arrive before invocation starts. Retain it briefly for
+ // that case, but expire IDs from callbacks that arrive after completion.
+ const expiration = setTimeout(() => {
+ cancelledInvocations.delete(invocationId);
+ }, CANCELLED_INVOCATION_RETENTION_MS);
+ // Don't keep Node alive for it; browser timers are numbers without `unref`.
+ (expiration as unknown as { unref?: () => void }).unref?.();
+ const previousExpiration = cancelledInvocations.get(invocationId);
+ if (previousExpiration !== undefined) {
+ clearTimeout(previousExpiration);
+ }
+ cancelledInvocations.set(invocationId, expiration);
+ };
+
+ super(
+ new ToolFunction(
+ name,
+ description,
+ new Value(JSON.stringify(parametersSchema)),
+ new Value(JSON.stringify(returnSchema)),
+ ),
+ invokeJson,
+ cancel,
+ );
+
+ this.name = name;
+ this.description = description;
+ this.parameters = options.parameters;
+ this.returns = options.returns;
+ this.parametersSchema = parametersSchema;
+ this.returnSchema = returnSchema;
+ this.handler = options.handler;
+ }
+
+ async invoke(
+ input: z.input<Parameters>,
+ options: UzuToolInvokeOptions = {},
+ ): Promise<z.output<ResultSchema>> {
+ const parameters = await this.parameters.parseAsync(input);
+ const signal = options.signal ?? new AbortController().signal;
+ const rawResult = await this.handler(parameters, { signal });
+ return this.returns.parseAsync(rawResult);
+ }
+}
+
+export function uzuToolFunction<Parameters extends z.ZodObject, ResultSchema extends z.ZodType>(
+ options: UzuToolFunctionOptions<Parameters, ResultSchema>,
+): UzuToolFunction<Parameters, ResultSchema> {
+ return new UzuToolFunction(options);
+}
+
+function serializeResult(result: unknown): string {
+ const json = JSON.stringify(result === undefined ? null : result);
+ if (json === undefined) {
+ throw new TypeError('tool result must be JSON serializable');
+ }
+ return json;
+}
diff --git a/crates/legacy/uzu/bindings/wasm/tsconfig.build.json b/crates/legacy/uzu/bindings/wasm/tsconfig.build.json
new file mode 100644
index 000000000..df9411180
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/tsconfig.build.json
@@ -0,0 +1,11 @@
+{
+ "extends": "./tsconfig.json",
+ "include": ["src"],
+ "compilerOptions": {
+ "rootDir": "./src",
+ "noEmit": false,
+ "declaration": true,
+ "outDir": "dist",
+ "pretty": true
+ }
+}
diff --git a/crates/legacy/uzu/bindings/wasm/tsconfig.json b/crates/legacy/uzu/bindings/wasm/tsconfig.json
new file mode 100644
index 000000000..14d7b9b2d
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/tsconfig.json
@@ -0,0 +1,23 @@
+{
+ "include": ["src", "examples"],
+ "exclude": [],
+ "compilerOptions": {
+ "target": "es2020",
+ "lib": ["es2020", "DOM"],
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "paths": {
+ "@trymirai/uzu-wasm": ["./src/index.ts"]
+ },
+ "noEmit": true,
+ "forceConsistentCasingInFileNames": true,
+ "strict": true,
+ "noImplicitReturns": true,
+ "exactOptionalPropertyTypes": true,
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "isolatedModules": true,
+ "skipLibCheck": true
+ }
+}
diff --git a/crates/legacy/uzu/bindings/wasm/vite.config.ts b/crates/legacy/uzu/bindings/wasm/vite.config.ts
new file mode 100644
index 000000000..f8b57fd3a
--- /dev/null
+++ b/crates/legacy/uzu/bindings/wasm/vite.config.ts
@@ -0,0 +1,11 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from 'vite';
+
+export default defineConfig({
+ root: 'examples',
+ resolve: {
+ alias: {
+ '@trymirai/uzu-wasm': fileURLToPath(new URL('./src/index.ts', import.meta.url)),
+ },
+ },
+});
diff --git a/crates/legacy/uzu/src/engine/error.rs b/crates/legacy/uzu/src/engine/error.rs
index 7db8eaab4..f6d7cb388 100644
--- a/crates/legacy/uzu/src/engine/error.rs
+++ b/crates/legacy/uzu/src/engine/error.rs
@@ -21,7 +21,6 @@ pub enum EngineError {
#[cfg(not(target_family = "wasm"))]
#[error(transparent)]
ClassificationSession(#[from] nagare::classification::ClassificationSessionError),
- #[cfg(not(target_family = "wasm"))]
#[error(transparent)]
DecisionSession(#[from] nagare::decision::DecisionSessionError),
#[cfg(not(target_family = "wasm"))]
diff --git a/crates/legacy/uzu/src/engine/mod.rs b/crates/legacy/uzu/src/engine/mod.rs
index b729d0a5c..ba043d89e 100644
--- a/crates/legacy/uzu/src/engine/mod.rs
+++ b/crates/legacy/uzu/src/engine/mod.rs
@@ -30,9 +30,12 @@ use futures_util::stream::FuturesUnordered;
use indexmap::IndexSet;
use kiban::rt::RuntimeHandle;
pub use model_info::ChatModelInfo;
-use nagare::chat::{ChatInstance, ChatSession};
+use nagare::{
+ chat::{ChatInstance, ChatSession},
+ decision::DecisionSession,
+};
#[cfg(not(target_family = "wasm"))]
-use nagare::{classification::ClassificationSession, decision::DecisionSession, text_to_speech::TextToSpeechSession};
+use nagare::{classification::ClassificationSession, text_to_speech::TextToSpeechSession};
use shoji::{
traits::{Backend, Registry},
types::{
@@ -671,7 +674,6 @@ impl Engine {
}
}
- #[cfg(not(target_family = "wasm"))]
#[bindings::export(Method)]
pub async fn decision(
&self,