@enfyra/rust-wrapper
v0.0.5
Published
CLI tool to create, compile and publish Rust packages for Enfyra with JS wrapper
Downloads
9
Maintainers
Readme
@enfyra/rust-wrapper
🦀 CLI tool to create Rust-powered native addons for Enfyra using NAPI-RS.
🚀 Quick Start
Create Package
npx @enfyra/rust-wrapper init my-addon
cd my-addonBuild Native Addon
npm run buildTest
node index.js📋 How It Works
Uses NAPI-RS to compile Rust directly into a native Node.js addon (.node file).
Benefits:
- ⚡ 500-1000x faster than spawning processes
- 🚀 No IPC overhead
- 📦 Direct function calls in same process
- 🔧 Auto-generated TypeScript definitions
🎯 Workflow
1. Create Package
npx @enfyra/rust-wrapper init image-processor
cd image-processorGenerated structure:
image-processor/
├── Cargo.toml # Rust config with NAPI dependencies
├── build.rs # NAPI build script
├── src/
│ └── lib.rs # Rust functions with #[napi] macros
├── index.js # JS wrapper (imports native addon)
├── package.json # npm config with @napi-rs/cli
└── README.md2. Add Your Rust Functions
Edit src/lib.rs:
#![deny(clippy::all)]
use napi_derive::napi;
#[napi]
pub fn get_greeting() -> String {
"hello, this is Enfyra by rust".to_string()
}
#[napi]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}3. Build
npm run buildOutput:
image_processor.node- Native addon (~300 KB)
4. Use in JavaScript
Edit index.js:
const { getGreeting, add } = require('./image_processor.node');
module.exports = {
getGreeting,
add
};
if (require.main === module) {
console.log(getGreeting());
console.log('2 + 3 =', add(2, 3));
}Test:
node index.js5. Use in Enfyra
Register package:
INSERT INTO package_definition (name, version, path, isEnabled)
VALUES (
'image_processor',
'1.0.0',
'../packages/image-processor/index.js',
1
);Use in handlers:
const processor = %image_processor;
const greeting = processor.getGreeting();
@LOGS(greeting);
const sum = processor.add(10, 20);
@LOGS(`Sum: ${sum}`);
return { message: greeting, sum };📦 Supported Types
NAPI-RS supports many types out of the box:
- Numbers:
i32,i64,f64,u32 - Strings:
String,&str - Booleans:
bool - Arrays:
Vec<T> - Objects: Custom structs with
#[napi(object)] - Buffers:
Buffer - Promises:
async fn(auto-converted to JS Promise)
🎪 Examples
Example 1: Math Utils
#[napi]
pub fn factorial(n: u32) -> u64 {
(1..=n as u64).product()
}
#[napi]
pub fn fibonacci(n: u32) -> u64 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}Example 2: Async Operations
use napi::bindgen_prelude::*;
#[napi]
pub async fn fetch_data(url: String) -> Result<String> {
// Your async code here
Ok(format!("Fetched from {}", url))
}Example 3: Custom Objects
#[napi(object)]
pub struct User {
pub name: String,
pub age: u32,
}
#[napi]
pub fn create_user(name: String, age: u32) -> User {
User { name, age }
}⚡ Performance Comparison
Old Method (spawn child process):
- Each call spawns new process
- JSON serialization overhead
- IPC communication overhead
- ~50-100ms per call
New Method (NAPI native addon):
- Direct function call in same process
- No serialization needed
- No IPC overhead
- ~0.01-0.1ms per call
Result: 500-1000x faster!
🔧 Requirements
Automatic Installation
The CLI will automatically check and install Rust for you:
- macOS/Linux: Rust will be installed automatically via rustup
- Windows: You'll get instructions to install Rust and Visual Studio Build Tools
Manual Installation (if needed)
Node.js: >= 14.0.0 (required)
Rust: (auto-installed on macOS/Linux)
- Install from https://rustup.rs
- Or the CLI will install it for you automatically
Windows only:
- Visual Studio Build Tools required for compilation
- Download: https://visualstudio.microsoft.com/downloads/
- Install "Desktop development with C++"
Verify installation:
rustc --version
cargo --version
node --version📝 Best Practices
- Use
#[napi]macro - Mark all exported functions - Type safety - NAPI-RS handles type conversion
- Error handling - Use
Result<T>for fallible operations - Async operations - Use
async fnfor I/O operations - Documentation - Comment your Rust functions
🐛 Troubleshooting
"Cargo not found" or "Rust not installed"
The CLI will automatically install Rust on macOS/Linux. If it fails:
# macOS/Linux - Manual install
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
# Windows - Download installer
# https://rustup.rsWindows: "linker link.exe not found"
This means Visual Studio Build Tools is not installed:
- Download: https://visualstudio.microsoft.com/downloads/
- Install "Desktop development with C++"
- Restart terminal and try again
"Cannot find module '*.node'"
# Rebuild the addon
npm run build
# Check if .node file exists
ls -la *.nodeBuild fails on Apple Silicon
# Make sure Rust targets your architecture
rustup default stable
rustup update🎓 Advanced
Cross-Platform Builds
# Build for specific target
npm run build -- --target x86_64-unknown-linux-gnuOptimize Binary Size
Add to Cargo.toml:
[profile.release]
lto = true
codegen-units = 1
strip = trueAdd More Dependencies
Edit Cargo.toml:
[dependencies]
napi = "2"
napi-derive = "2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"📚 Resources
- NAPI-RS: https://napi.rs
- Rust Book: https://doc.rust-lang.org/book/
- Enfyra Docs: https://enfyra.com/docs
🤝 Contributing
Issues and PRs welcome!
📄 License
MIT
Made with 🦀 and ❤️ for Enfyra
