What are Extensions?
Extensions bundle together:- Ops - Rust functions callable from JavaScript
- JavaScript/TypeScript code - High-level APIs
- Dependencies - Other extensions required
- State - Extension-specific initialization
ext/ directory.
Extension Structure
A typical extension contains:Creating a New Extension
Step 1: Create the Directory
Step 2: Create Cargo.toml
Step 3: Define the Extension
Createlib.rs:
Step 4: Create JavaScript API
Create01_my_extension.js:
Step 5: Register in Runtime
Add toruntime/worker.rs:
Cargo.toml:
Step 6: Add to CLI Dependencies
Incli/Cargo.toml:
Writing Ops
Ops are the interface between Rust and JavaScript.Op Types
- Synchronous
- Asynchronous
- With State
- With Permissions
Op Parameters
Common parameter types:Op Return Types
Resources
Resources represent system handles like files and sockets.Defining a Resource
Creating Resources
Using Resources
Closing Resources
Example: File System Extension
Let’s look at a simplified version of the fs extension:Existing Extensions Reference
ext/fs
File system operations: read, write, stat, etc.
ext/net
Networking: TCP, UDP, TLS connections
ext/fetch
Fetch API implementation
ext/web
Web APIs: TextEncoder, URL, Events, etc.
ext/crypto
Web Crypto API
ext/http
HTTP server implementation
Best Practices
Use appropriate op types
- Use
#[op2(fast)]for hot paths with simple types - Use
#[op2(async)]for I/O operations - Use regular
#[op2]for everything else
Testing Extensions
Unit Tests
Add Rust unit tests:Integration Tests
Create spec tests intests/specs/my_extension/:
Common Patterns
Async operations with cancellation
Async operations with cancellation
Batching operations
Batching operations
Custom error types
Custom error types
Debugging Extensions
See Debugging for detailed debugging techniques. Quick tips:Next Steps
Testing
Learn how to test your extensions
Debugging
Debug extension issues