npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@enfyra/rust-wrapper

v0.0.5

Published

CLI tool to create, compile and publish Rust packages for Enfyra with JS wrapper

Downloads

9

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-addon

Build Native Addon

npm run build

Test

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-processor

Generated 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.md

2. 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 build

Output:

  • 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.js

5. 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

  1. Use #[napi] macro - Mark all exported functions
  2. Type safety - NAPI-RS handles type conversion
  3. Error handling - Use Result<T> for fallible operations
  4. Async operations - Use async fn for I/O operations
  5. 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.rs

Windows: "linker link.exe not found"

This means Visual Studio Build Tools is not installed:

  1. Download: https://visualstudio.microsoft.com/downloads/
  2. Install "Desktop development with C++"
  3. Restart terminal and try again

"Cannot find module '*.node'"

# Rebuild the addon
npm run build

# Check if .node file exists
ls -la *.node

Build 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-gnu

Optimize Binary Size

Add to Cargo.toml:

[profile.release]
lto = true
codegen-units = 1
strip = true

Add 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