Skip to main content

bomboni_wasm

WebAssembly utilities for the Bomboni library. This crate provides utilities for working with WebAssembly in Rust, including JavaScript interoperability, console logging, and TypeScript declaration generation for Rust types.

Main Exports

Wasm Trait

Trait for converting between Rust types and JavaScript values.
pub trait Wasm {
    type JsType: JsCast;
    
    fn to_js(&self) -> Result<Self::JsType, serde_wasm_bindgen::Error>
    where
        Self: serde::Serialize;
    
    fn from_js<T: Into<JsValue>>(js: T) -> Result<Self, serde_wasm_bindgen::Error>
    where
        Self: serde::de::DeserializeOwned;
}

Methods

to_js Converts this value to a JavaScript value.
  • Returns: Result<Self::JsType, serde_wasm_bindgen::Error>
  • Errors: Will return error if serialization fails
from_js Converts a JavaScript value to this Rust type.
  • Parameters:
    • js: JavaScript value (any type that implements Into<JsValue>)
  • Returns: Result<Self, serde_wasm_bindgen::Error>
  • Errors: Will return error if deserialization fails

Example

use bomboni_wasm::Wasm;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Wasm)]
pub struct User {
    name: String,
    age: u32,
}

// Convert to JavaScript
let user = User {
    name: "Alice".into(),
    age: 30,
};
let js_value = user.to_js().unwrap();

// Convert from JavaScript
let user: User = User::from_js(js_value).unwrap();

Console Logging

The macros module provides console logging utilities for WebAssembly.

Functions

log Logs a message to the browser console.
pub fn log(s: &str)
error Logs an error message to the browser console.
pub fn error(s: &str)

Macros

console_log! Logs a formatted message to the browser console.
console_log!("User: {}, Age: {}", name, age);
console_error! Logs a formatted error message to the browser console.
console_error!("Error: {}", error_message);

Example

use bomboni_wasm::console_log;

#[wasm_bindgen]
pub fn greet(name: &str) {
    console_log!("Hello, {}!", name);
}

Re-exports

When the derive feature is enabled, this crate re-exports the derive macro:
pub use bomboni_wasm_derive::*;
This allows you to use #[derive(Wasm)] directly.

TypeScript Declaration Generation

Types annotated with #[derive(Wasm)] automatically generate TypeScript declarations that can be exported alongside your WASM bindings.
#[derive(Serialize, Deserialize, Wasm)]
pub struct Config {
    enabled: bool,
    timeout: u32,
}

// Generated TypeScript:
// export interface Config {
//   enabled: boolean;
//   timeout: number;
// }

Build docs developers (and LLMs) love