waclay 0.2.2

Runtime-agnostic WebAssembly Component Model implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
<div align="center">

# πŸš€ waclay


### WebAssembly Component Layer - Runtime Agnostic


[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org/)
[![Unsafe Forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)

*A maintained fork bringing the WebAssembly Component Model to life*

[Features](#-features) β€’
[Quick Start](#-quick-start) β€’
[Examples](#-examples) β€’
[Contributing](#-contributing) β€’
[Credits](#-credits)

</div>

> **⚠️ Experimental Warning:** This project is still experimental. Some features may work perfectly, others may not. It needs developer contributions to become stable.

---

## πŸ“– About This Project


**waclay** (WebAssembly Component Layer) is a **runtime-agnostic** implementation of the [WebAssembly Component Model](https://github.com/WebAssembly/component-model). This project enables you to load, link, and execute WASM components with full component model support across **any** WebAssembly runtime backend.

### 🎯 Why This Fork?


This is a **maintained fork** of the original `wasm_component_layer` project. After the original developer discontinued active maintenance, the project became difficult to compile and use with modern Rust toolchains. This fork aims to:

- βœ… **Keep it compiling** - Updated to work with latest Rust and dependencies (50+ commits of fixes and improvements)
- βœ… **Add new features** - Including the new `wit-bindgen-wcl` tool for generating host bindings
- βœ… **Maintain usability** - Making it a practical tool for plugin development and WASM-based applications
- βœ… **Stay runtime agnostic** - Preserving the brilliant design that works with Wasmi, Wasmtime, and other backends
- βœ… **Build community** - Welcoming contributions to help maintain and improve the project

### πŸ’‘ The Brilliant Design


The original author's vision of a **runtime-agnostic component layer** combined with the **wasm_runtime_layer** abstraction is truly innovative. This design allows you to:

- Switch between different WASM runtimes (Wasmi, Wasmtime, etc.) without changing your code
- Use the same Component Model API regardless of the underlying execution engine
- Build portable WASM applications that work across multiple platforms and backends

This architecture is **essential** for the WASM ecosystem as we wait for the Component Model to be finalized and fully supported across all runtimes.

---

## ✨ Features


### Core Capabilities


- πŸ”§ **Component Model Support** - Full implementation of WebAssembly Component Model
- πŸ”„ **Runtime Agnostic** - Works with Wasmi, Wasmtime, and any backend via `wasm_runtime_layer`
- 🎭 **Type System** - Complete support for WIT types: records, variants, enums, resources, etc.
- πŸš€ **Zero Unsafe Code** - 100% safe Rust implementation
- πŸ“¦ **Resource Management** - Proper handling of owned and borrowed resources with destructors
- πŸ”— **Dynamic Loading** - Runtime inspection and generation of component interface types
- ⚑ **Optimized Lists** - Specialized list types for faster lifting/lowering operations

### NEW: wit-bindgen-wcl


**`wit-bindgen-wcl`** is a command-line tool that generates ergonomic Rust host bindings from WIT files:

- ✨ **Type-Safe Bindings** - Generates strongly-typed Rust code from WIT definitions
- 🎯 **Easy Integration** - Simple workflow from WIT β†’ Rust bindings β†’ Host application
- πŸš€ **Top-Level Functions** - Full support for top-level function imports and exports (not just interfaces)
- πŸ”§ **Active Development** - Basic features working for simple use cases (see examples)
- 🀝 **Community Needed** - Heavy development in progress, contributions welcome!

**Current Status:** Works for simple to moderate complexity WIT files. Supports top-level functions, interfaces, records, variants, enums, options, results, and more. See the `examples/` directory for supported patterns.

---

## πŸ—οΈ Workspace Structure


This workspace contains two main crates:

```
waclay/
β”œβ”€β”€ crates/
β”‚   β”œβ”€β”€ waclay/             # 🎯 Core Component Layer Library
β”‚   β”‚   β”œβ”€β”€ src/            # Runtime-agnostic component model implementation
β”‚   β”‚   β”œβ”€β”€ examples/       # 10 comprehensive examples showing features
β”‚   β”‚   └── docs/           # API documentation and guides
β”‚   β”‚
β”‚   └── wit-bindgen-wcl/    # πŸ”§ WIT Binding Generator (NEW!)
β”‚       β”œβ”€β”€ src/            # Code generator for host bindings
β”‚       └── examples/       # 9 examples with generated bindings
β”‚
β”œβ”€β”€ test-waclay.ps1         # Test suite for core library
β”œβ”€β”€ test-wit-bindgen.ps1    # Test suite for binding generator
└── test-all.ps1            # Complete workspace tests
```

### πŸ“¦ Crates


#### `waclay` - Core Library


Runtime-agnostic WebAssembly Component Model implementation. Load and execute components on any WASM runtime!

- **Version:** 0.1.3
- **License:** Apache-2.0
- **Repository:** https://github.com/HemantKArya/waclay

#### `wit-bindgen-wcl` - Binding Generator


Generate type-safe Rust host bindings from WIT files. Makes working with components much more ergonomic!

- **Status:** Basic features working, contributions welcome
- **Use Cases:** Simple to moderate complexity WIT files (check examples)
- **Community:** Contributors needed to expand capabilities

---

## πŸš€ Quick Start


### Prerequisites


```bash
# Install Rust (if not already installed)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Install wasm-tools for building components

cargo install wasm-tools
```

### Installation

```bash
cargo build
```

### Installation


#### Option 1: Use in Your Project (Recommended)


Add to your `Cargo.toml`:

```toml
[dependencies]
waclay = { git = "https://github.com/HemantKArya/waclay" }
# Choose your runtime backend

wasmi_runtime_layer = "0.51.0"
# OR

# wasmtime_runtime_layer = "21.0.0"

```

> **Note:** Not yet published to crates.io - may be published in the future. Use git dependency for now.

**Optional: Install wit-bindgen-wcl for generating bindings**

If you want to generate host bindings from WIT files:

```bash
# Install the binding generator tool globally

cargo install --git https://github.com/HemantKArya/waclay wit-bindgen-wcl

# Now you can use it

wit-bindgen-wcl ./path/to/wit ./bindings.rs
```

#### Option 2: Build from Source


```bash
git clone https://github.com/HemantKArya/waclay.git
cd waclay

# Build the workspace

cargo build --release

# Install the binding generator

cargo install --path crates/wit-bindgen-wcl
```

### Basic Usage Example


### Basic Usage Example


Here's a simple example of loading and calling a WASM component:

**1. Define your WIT interface** (`guest.wit`)
**1. Define your WIT interface** (`guest.wit`)

```wit
package test:guest

interface foo {
    // Selects the item in position n within list x
    select-nth: func(x: list<string>, n: u32) -> string
}

world guest {
    export foo
}
```

**2. Load and call the component** (Rust host code)

```rust
use waclay::*;

// The bytes of the component.
const WASM: &[u8] = include_bytes!("single_component/component.wasm");

pub fn main() {
    // Create a new engine for instantiating a component.
    let engine = Engine::new(wasmi_runtime_layer::Engine::default());

    // Create a store for managing WASM data and any custom user-defined state.
    let mut store = Store::new(&engine, ());

    // Parse the component bytes and load its imports and exports.
    let component = Component::new(&engine, WASM).unwrap();
    // Create a linker that will be used to resolve the component's imports, if any.
    let linker = Linker::default();
    // Create an instance of the component using the linker.
    let instance = linker.instantiate(&mut store, &component).unwrap();

    // Get the interface that the interface exports.
    let interface = instance.exports().instance(&"test:guest/foo".try_into().unwrap()).unwrap();
    // Get the function for selecting a list element.
    let select_nth = interface.func("select-nth").unwrap().typed::<(Vec<String>, u32), String>().unwrap();

    // Create an example list to test upon.
    let example = ["a", "b", "c"].iter().map(ToString::to_string).collect::<Vec<_>>();

    println!("Calling select-nth({example:?}, 1) == {}", select_nth.call(&mut store, (example.clone(), 1)).unwrap());
    // Prints 'Calling select-nth(["a", "b", "c"], 1) == b'
}
```

That's it! You've successfully loaded and executed a WebAssembly component. πŸŽ‰

### Using wit-bindgen-wcl for Better Ergonomics


Generate type-safe bindings from WIT files:

```bash
# Generate bindings from WIT directory

wit-bindgen-wcl ./path/to/wit ./bindings.rs

# Use in your code

cargo run --bin wit-bindgen-wcl -- ./guest.wit ./bindings.rs
```

Then use the generated bindings for type-safe, ergonomic API:

```rust
mod bindings;
use bindings::*;  // Type-safe functions generated from WIT

// Much more ergonomic than raw Value manipulation!
```

#### Top-Level Function Support (NEW!)


wit-bindgen-wcl now supports top-level functions in WIT worlds:

```wit
world example {
    // Top-level imports (host provides)
    import multiply: func(a: f32, b: f32) -> f32;
    
    // Top-level exports (guest provides)
    export add: func(a: f32, b: f32) -> f32;
}
```

The generator creates:
- **For imports**: Host traits and registration functions using `linker.root_mut()`
- **For exports**: Helper functions to access via `instance.exports().root()`

This matches the wasmtime/wit-bindgen behavior and enables more flexible component designs.

---

## 🎯 How It Works


### The Runtime Agnostic Architecture


```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           Your Application                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚         waclay (Component Layer)            β”‚
β”‚  β€’ Component Model Implementation           β”‚
β”‚  β€’ Type System & Lifting/Lowering           β”‚
β”‚  β€’ Resource Management                      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    wasm_runtime_layer (Abstraction)         β”‚
β”‚  β€’ Common Runtime Interface                 β”‚
β”‚  β€’ Backend Agnostic API                     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Wasmi   β”‚ Wasmtime β”‚  Wasmer  β”‚  Browser   β”‚
β”‚ Runtime  β”‚  Runtime β”‚  Runtime β”‚   (JS)     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**Key Benefits:**

1. **Write once, run anywhere** - Your code works with any runtime
2. **Easy runtime switching** - Change one line to switch backends
3. **Future-proof** - As new runtimes emerge, they just work
4. **Testability** - Test with lightweight runtime, deploy with optimized one

---

## 🀝 Contributing


**We need your help!** This project is maintained and welcoming community contributions.

### Why Contribute?


- 🌟 **Shape the Future** - Help build critical WebAssembly infrastructure
- πŸ“š **Learn WASM** - Deep dive into Component Model internals
- 🎯 **Real Impact** - Used in production for plugin systems and WASM applications
- πŸ€— **Welcoming Community** - All skill levels welcome, we'll help you get started

### What We Need


| Area | Priority | Description |
|------|----------|-------------|
| πŸ”§ **wit-bindgen-wcl** | πŸ”΄ High | Expand binding generation for complex WIT patterns |
| πŸ“ **Documentation** | πŸ”΄ High | API docs, tutorials, and guides |
| πŸ§ͺ **Testing** | 🟑 Medium | More comprehensive tests and edge cases |
| πŸ› **Bug Fixes** | 🟒 Ongoing | Report and fix issues |
| πŸ’‘ **Features** | 🟒 Ongoing | String transcoders, subtyping support |
| 🎨 **Examples** | 🟒 Ongoing | More real-world use cases |

### Getting Started


1. **Fork the repository**
2. **Pick an issue** or create a new one
3. **Make your changes** with tests
4. **Submit a PR** with a clear description

Check out existing examples and tests to understand the codebase. Don't hesitate to ask questions in issues!

### Development Setup


```bash
# Clone your fork

git clone https://github.com/YourUsername/waclay.git
cd waclay

# Run tests to ensure everything works

.\test-all.ps1 -Fast

# Make your changes and test again

# ... your awesome contributions ...


.\test-all.ps1 -Fast
```

---

## πŸ—ΊοΈ Roadmap


### Current Focus (v0.1.x)


- [x] Maintain compatibility with latest Rust
- [x] Basic `wit-bindgen-wcl` functionality
- [ ] Comprehensive documentation
- [ ] More `wit-bindgen-wcl` features
- [ ] String transcoder support
- [ ] Subtyping support

### Future (v0.2.x+)


- [ ] Publish to crates.io
- [ ] Host binding macro (`#[derive(HostBindings)]`)
- [ ] Performance optimizations
- [ ] More runtime backend support
- [ ] WASI Preview 2 integration examples

**Note:** This project aims to bridge the gap until the Component Model is finalized by the WASI community and fully supported across all major runtimes. Community contributions are essential to keep it up-to-date.

---

## πŸ“š Examples


This repository includes **20 comprehensive examples** demonstrating various features:

### πŸ”Ή Core Library Examples (10 examples)


Using the raw component API - great for learning the fundamentals:

### πŸ”Ή Core Library Examples (10 examples)


Using the raw component API - great for learning the fundamentals:

```bash
# From workspace root

cargo run --example single_component     # βœ… Simple component instantiation
cargo run --example string_host_guest    # βœ… String passing between host/guest
cargo run --example func_param           # βœ… Function parameters
cargo run --example record_response      # βœ… Record types
cargo run --example option_result        # βœ… Option and Result types
cargo run --example variant_return       # βœ… Variant types
cargo run --example complex_return       # βœ… Complex return types
cargo run --example resource             # βœ… Resource handling
cargo run --example guest_resource       # βœ… Guest-defined resources
cargo run --example multilevel_resource  # βœ… Multi-level resources
```

### πŸ”Έ Generated Bindings Examples (10 examples)


Using `wit-bindgen-wcl` for type-safe, ergonomic code:

```bash
# From workspace root

cargo run --example bindgen-calculator         # βœ… Calculator with logging & error handling
cargo run --example bindgen-web-scraper        # βœ… Web scraping component
cargo run --example bindgen-single-component   # βœ… Basic binding generation
cargo run --example bindgen-string-host-guest  # βœ… String passing with bindings
cargo run --example bindgen-func-param         # βœ… Function parameters with bindings
cargo run --example bindgen-record-response    # βœ… Record types with bindings
cargo run --example bindgen-option-result      # βœ… Option and Result with bindings
cargo run --example bindgen-variant-return     # βœ… Variant types with bindings
cargo run --example bindgen-complex-return     # βœ… Complex return types with bindings

# NEW: Top-level function support

cd crates/wit-bindgen-wcl/examples/toplevel-functions/host && cargo run --release
                                                # βœ… Top-level function imports & exports
```

> **πŸ’‘ Tip:** Examples prefixed with `bindgen-` use generated bindings (more ergonomic), while others use the raw API (more flexible).

### Building Your Own Components


Want to build the example components yourself?

```bash
# Navigate to any component example

cd crates/wit-bindgen-wcl/examples/calculator/component

# Install nightly toolchain

rustup toolchain install nightly
rustup override set nightly

# Build the WASM module

cargo build --target wasm32-unknown-unknown --release

# Convert to component

wasm-tools component new \
  target/wasm32-unknown-unknown/release/calculator.wasm \
  -o component.wasm
```

---

## πŸ§ͺ Testing


Comprehensive test suite with cross-platform support:

```bash
# πŸš€ Quick tests (recommended for development)

.\test-all.ps1 -Fast

# 🌍 Full test suite (all platforms)

.\test-all.ps1

# 🎯 Test specific crate

.\test-waclay.ps1           # Test core library only
.\test-wit-bindgen.ps1      # Test binding generator only

# βš™οΈ Advanced options

.\test-waclay.ps1 -SkipAndroid -SkipLinux    # Skip cross-compilation
.\test-wit-bindgen.ps1 -SkipExamples         # Skip example builds
```

**Test Coverage:**
- βœ… Unit tests and integration tests
- βœ… All 19 examples build and run
- βœ… Cross-platform compatibility (Windows, Linux, Android)
- βœ… Multiple runtime backends

---

## βš™οΈ Optional Features


- **`serde`** - Enable serialization for types and values (resources excluded as they're instance-bound)

```toml
waclay = { git = "https://github.com/HemantKArya/waclay", features = ["serde"] }
```

---

## πŸ“‹ Supported Capabilities


> **πŸ“„ For a comprehensive feature comparison with wasmtime/wit-bindgen, see [FEATURES.md]FEATURES.md**

### βœ… Fully Supported


- βœ… Component parsing and instantiation
- βœ… All WIT types (records, variants, enums, options, results, etc.)
- βœ… Top-level functions (imports and exports)
- βœ… Specialized list types for performance
- βœ… Structural type equality
- βœ… Guest resources
- βœ… Host resources with destructors
- βœ… Runtime type inspection
- βœ… Multiple runtime backends

### 🚧 In Progress


- 🚧 Resource type bindings in `wit-bindgen-wcl`
- 🚧 Comprehensive testing suite
- 🚧 Documentation and tutorials

### ❌ Not Supported


- ❌ Future types (`future<T>`) - Requires async runtime support in core
- ❌ Stream types (`stream<T>`) - Requires async runtime support in core
- ❌ Async/await patterns - Fundamental limitation requiring core changes

### πŸ“‹ Planned


- πŸ“‹ Resource bindings generation in wit-bindgen-wcl
- πŸ“‹ String transcoders
- πŸ“‹ Host binding macros
- πŸ“‹ Subtyping support
- πŸ“‹ Performance benchmarks

> **Note**: For detailed feature comparison and workarounds, see [FEATURES.md]FEATURES.md

---

## πŸ“œ License


Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for details.

---

## πŸ™ Credits


### Original Author


**Huge thanks to [DouglasDwyer](https://github.com/DouglasDwyer)** for creating the original `wasm_component_layer` project. The core architecture and design are his brilliant work:

- πŸ’‘ **Visionary Design** - The runtime-agnostic component layer concept
- πŸ—οΈ **Solid Foundation** - Clean, well-structured codebase  
- πŸ”§ **wasm_runtime_layer** - The abstraction that makes it all possible

Without this foundation, this project wouldn't exist.

### This Fork


**Maintained by [HemantKArya](https://github.com/HemantKArya)** since the original project was discontinued:

- πŸš€ Trying to keep it compiling with modern Rust
- ✨ New `wit-bindgen-wcl` tool
- πŸ“š Improved documentation
- 🀝 Community building

### Built With


This project stands on the shoulders of giants:

- [wasmtime]https://github.com/bytecodealliance/wasmtime - Component Model implementation reference
- [wit-parser]https://github.com/bytecodealliance/wasm-tools - WIT parsing and validation
- [wasm_runtime_layer]https://github.com/DouglasDwyer/wasm_runtime_layer - Runtime abstraction
- All the runtime backends: Wasmi, Wasmtime, and others

---

## πŸ“ž Get in Touch


- πŸ› **Found a bug?** [Open an issue]https://github.com/HemantKArya/waclay/issues
- πŸ’‘ **Have an idea?** [Start a discussion]https://github.com/HemantKArya/waclay/discussions
- 🀝 **Want to contribute?** Check our [Contributing]#-contributing section
- ⭐ **Like the project?** Give us a star on GitHub!

---

<div align="center">

**Built with ❀️ for the WebAssembly community**

*Making Component Model accessible to everyone, one runtime at a time*

[⬆ Back to Top](#-waclay)

</div>