h33-node-bindings
v1.0.0
Published
High-performance native Rust bindings for Node.js providing 10-100x speedups for cryptography, vector embeddings, text processing, image processing, JSON operations, and post-quantum cryptography
Maintainers
Readme
@h33/node-bindings
High-performance native Rust bindings for Node.js providing 10-100x speedups for compute-intensive operations including cryptography, vector embeddings, text processing, image processing, and JSON operations.
Built with NAPI-RS for seamless Node.js integration with zero-copy data transfer where possible.
Installation
npm install @h33/node-bindingsyarn add @h33/node-bindingspnpm add @h33/node-bindingsQuick Start
const h33 = require('@h33/node-bindings');
// Check if native bindings are available
console.log('Native available:', h33.isNativeAvailable());
console.log('Version:', h33.getVersion());
// Password hashing with Argon2id
const hash = h33.argon2Hash('my-secure-password');
const isValid = h33.argon2Verify('my-secure-password', hash);
// Vector similarity search
const query = [0.1, 0.2, 0.3, 0.4, 0.5];
const candidates = [
{ id: 'doc1', vector: [0.15, 0.25, 0.35, 0.45, 0.55] },
{ id: 'doc2', vector: [0.9, 0.8, 0.7, 0.6, 0.5] },
];
const similar = h33.findSimilar(query, candidates, 2, 'cosine');
// SIMD-accelerated JSON parsing
const result = h33.parseJson('{"key": "value"}');
console.log(result.data);API Reference
Utility Functions
isNativeAvailable(): boolean
Check if native bindings are loaded and available.
getVersion(): string
Get the version of the native bindings.
Cryptography
argon2Hash(password: string): string
Hash a password using Argon2id with OWASP-recommended parameters (19 MiB memory, 2 iterations).
- Performance: ~15ms in Rust vs ~500ms in pure JS
const hash = h33.argon2Hash('my-password');
// Returns: $argon2id$v=19$m=19456,t=2,p=1$...argon2Verify(password: string, hash: string): boolean
Verify a password against an Argon2 hash.
const isValid = h33.argon2Verify('my-password', hash);sha3256(data: Buffer): string
Compute SHA3-256 hash of data.
const hash = h33.sha3256(Buffer.from('hello'));sha3512(data: Buffer): string
Compute SHA3-512 hash of data.
hkdfDerive(ikm: Buffer, salt?: Buffer, info?: Buffer, length: number): Buffer
HKDF key derivation (RFC 5869) using SHA3-256.
const key = h33.hkdfDerive(
Buffer.from('input-key-material'),
Buffer.from('salt'),
Buffer.from('context-info'),
32
);chacha20Encrypt(plaintext: Buffer, key: Buffer): Buffer
Encrypt data using ChaCha20-Poly1305 (AEAD). Key must be 32 bytes. Returns nonce + ciphertext.
const key = Buffer.alloc(32); // Your 32-byte key
const encrypted = h33.chacha20Encrypt(Buffer.from('secret'), key);chacha20Decrypt(ciphertext: Buffer, key: Buffer): Buffer
Decrypt ChaCha20-Poly1305 encrypted data.
aesGcmEncrypt(plaintext: Buffer, key: Buffer): Buffer
Encrypt data using AES-256-GCM. Key must be 32 bytes.
aesGcmDecrypt(ciphertext: Buffer, key: Buffer): Buffer
Decrypt AES-256-GCM encrypted data.
Post-Quantum Cryptography
dilithiumKeygen(): { publicKey: string, secretKey: string }
Generate an ML-DSA (Dilithium) key pair for digital signatures.
const keys = h33.dilithiumKeygen();
// keys.publicKey - Base64-encoded public key
// keys.secretKey - Base64-encoded secret keydilithiumSign(message: Buffer, secretKey: string): string
Sign a message using ML-DSA. Returns Base64-encoded signature.
const signature = h33.dilithiumSign(Buffer.from('message'), keys.secretKey);dilithiumVerify(message: Buffer, signature: string, publicKey: string): boolean
Verify an ML-DSA signature.
const isValid = h33.dilithiumVerify(
Buffer.from('message'),
signature,
keys.publicKey
);kyberKeygen(): { publicKey: string, secretKey: string }
Generate an ML-KEM (Kyber) key pair for key encapsulation.
kyberEncapsulate(publicKey: string): { sharedSecret: string, ciphertext: string }
Encapsulate a shared secret using the recipient's public key.
const { sharedSecret, ciphertext } = h33.kyberEncapsulate(recipientPublicKey);kyberDecapsulate(ciphertext: string, secretKey: string): string
Decapsulate to recover the shared secret.
const sharedSecret = h33.kyberDecapsulate(ciphertext, keys.secretKey);Vector Embeddings
cosineSimilarity(a: number[], b: number[]): number
Calculate cosine similarity between two vectors.
- Performance: ~0.01ms in Rust vs ~1ms in JS (100x speedup)
const similarity = h33.cosineSimilarity([0.1, 0.2, 0.3], [0.3, 0.2, 0.1]);dotProduct(a: number[], b: number[]): number
Calculate dot product of two vectors.
euclideanDistance(a: number[], b: number[]): number
Calculate Euclidean distance between two vectors.
findSimilar(query: number[], candidates: VectorCandidate[], k: number, metric?: string): SimilarityResult[]
Find k most similar vectors using parallel processing.
- Performance: ~5ms for 10k vectors in Rust vs ~500ms in JS (100x speedup)
- Metrics: 'cosine' (default), 'dot', 'euclidean'
interface VectorCandidate {
id: string;
vector: number[];
}
interface SimilarityResult {
id: string;
score: number;
}const results = h33.findSimilar(queryVector, candidates, 10, 'cosine');batchSimilarity(query: number[], targets: number[][], metric?: string): number[]
Calculate similarities between query and multiple target vectors in parallel.
similarityMatrix(setA: number[][], setB: number[][], metric?: string): number[][]
Calculate pairwise similarity matrix between two sets of vectors.
l2Normalize(vector: number[]): number[]
Normalize vector to unit length (L2 normalization).
magnitude(vector: number[]): number
Calculate vector magnitude (L2 norm).
vectorAdd(a: number[], b: number[]): number[]
Add two vectors element-wise.
vectorScale(vector: number[], scalar: number): number[]
Scale vector by a scalar value.
centroid(vectors: number[][]): number[]
Calculate centroid (mean) of multiple vectors.
Text Processing
chunkText(text: string, options?: ChunkOptions): ChunkResult[]
Split text into semantic chunks for RAG/LLM applications.
- Performance: ~0.5ms per chunk in Rust vs ~25ms in JS (50x speedup)
interface ChunkOptions {
maxChunkSize?: number; // Default: 1000
overlap?: number; // Default: 100
splitBy?: 'sentence' | 'paragraph' | 'word'; // Default: 'sentence'
preserveWords?: boolean;
}
interface ChunkResult {
text: string;
index: number;
startPosition: number;
endPosition: number;
size: number;
}const chunks = h33.chunkText(text, {
maxChunkSize: 500,
overlap: 50,
splitBy: 'sentence'
});countTokens(text: string, model?: string): number
Count tokens using tiktoken cl100k_base approximation.
- Performance: ~0.1ms in Rust vs ~3ms in JS (30x speedup)
const tokenCount = h33.countTokens('Hello world!');countTokensBatch(texts: string[]): number[]
Count tokens for multiple texts.
textStatistics(text: string): TextStatistics
Calculate comprehensive text statistics.
- Performance: ~0.2ms in Rust vs ~8ms in JS (40x speedup)
interface TextStatistics {
characters: number;
charactersNoSpaces: number;
words: number;
uniqueWords: number;
sentences: number;
paragraphs: number;
syllables: number;
avgWordLength: number;
lexicalDiversity: number;
}detectLanguage(text: string): LanguageResult
Detect language of text using stopword analysis.
- Performance: ~0.1ms in Rust vs ~2ms in JS (20x speedup)
- Supported: English, Spanish, French, German, Portuguese, Italian
interface LanguageResult {
language: string;
confidence: number;
}Data Processing
parseCsv(data: string, options?: CsvParseOptions): CsvParseResult
Parse CSV data with configurable options.
- Performance: ~5ms per MB in Rust vs ~100ms in JS (20x speedup)
interface CsvParseOptions {
delimiter?: string; // Default: ','
hasHeaders?: boolean; // Default: true
skipEmpty?: boolean; // Default: true
trimValues?: boolean; // Default: true
maxRows?: number;
}
interface CsvParseResult {
headers?: string[];
rows: Record<string, string>[];
rowCount: number;
}const result = h33.parseCsv(csvString, { delimiter: ';', maxRows: 1000 });generateCsv(data: Record<string, string>[], delimiter?: string): string
Generate CSV string from array of objects.
JSON Operations (SIMD-Accelerated)
parseJson(data: string): JsonParseResult
Parse JSON using SIMD acceleration.
- Performance: ~2ms for 1MB in Rust vs ~15ms in JS (7x speedup)
interface JsonParseResult {
success: boolean;
data?: any;
error?: string;
}parseJsonBuffer(data: Buffer): JsonParseResult
Parse JSON from buffer with zero-copy optimization where possible.
validateJson(data: string): JsonValidationResult
Validate JSON syntax without full parsing.
- Performance: ~0.5ms for 1MB in Rust vs ~10ms in JS (20x speedup)
interface JsonValidationResult {
valid: boolean;
errorPosition?: number;
errorMessage?: string;
}jsonGetPath(data: string, path: string): any | null
Extract value at JSON path using dot notation.
const value = h33.jsonGetPath('{"user":{"name":"Alice"}}', 'user.name');
// Returns: "Alice"jsonGetPaths(data: string, paths: string[]): Record<string, any>
Extract multiple paths in a single pass.
jsonDiff(json1: string, json2: string): JsonDiffResult
Calculate structural diff between two JSON documents.
interface JsonDiffResult {
added: string[]; // Paths added in json2
removed: string[]; // Paths removed from json1
modified: string[]; // Paths with changed values
unchangedCount: number;
}stringifyJson(value: any, pretty?: boolean): string
Stringify JSON value with optional pretty-printing.
stringifyJsonBuffer(value: any): Buffer
Stringify JSON to buffer for streaming.
Image Processing
resizeImage(data: Buffer, srcWidth: number, srcHeight: number, dstWidth: number, dstHeight: number): Buffer
Resize RGBA image using Lanczos3 filter.
- Performance: ~5ms for 4K to HD in Rust vs ~150ms in JS (30x speedup)
const resized = h33.resizeImage(rgbaBuffer, 3840, 2160, 1920, 1080);extractFrameFeatures(data: Buffer, width: number, height: number): FrameFeatures
Extract features from video frame for liveness detection.
- Performance: ~2ms in Rust vs ~50ms in JS (25x speedup)
interface FrameFeatures {
brightness: number; // 0-1, normalized luminance
contrast: number; // Standard deviation of luminance
edgeDensity: number; // Ratio of edge pixels
}detectMotion(frame1: Buffer, frame2: Buffer, width: number, height: number): MotionResult
Detect motion between consecutive frames.
- Performance: ~1ms in Rust vs ~20ms in JS (20x speedup)
interface MotionResult {
motionScore: number; // Ratio of pixels with motion
motionIntensity: number; // Average motion magnitude
hasSignificantMotion: boolean;
}analyzePad(data: Buffer, width: number, height: number): PadAnalysis
Analyze frame for presentation attack detection (screen capture detection).
interface PadAnalysis {
isLive: boolean;
confidence: number;
unnaturalHistogram: boolean;
}enhanceDocument(data: Buffer, width: number, height: number): Buffer
Enhance document image for OCR using contrast stretching.
- Performance: ~10ms in Rust vs ~200ms in JS (20x speedup)
perceptualHash(data: Buffer, width: number, height: number): string
Calculate perceptual hash for image deduplication and similarity detection.
Performance Benchmarks
Benchmarks measured on Apple M1 Pro, Node.js v20.
| Operation | JavaScript | Rust | Speedup | |-----------|-----------|------|---------| | Password Hash (Argon2) | 500ms | 15ms | 33x | | Cosine Similarity (768D) | 1.0ms | 0.01ms | 100x | | k-NN Search (10k vectors) | 500ms | 5ms | 100x | | CSV Parse (1MB) | 100ms | 5ms | 20x | | JSON Parse (1MB) | 15ms | 2ms | 7x | | JSON Validate (1MB) | 10ms | 0.5ms | 20x | | Text Chunking | 25ms | 0.5ms | 50x | | Token Count | 3ms | 0.1ms | 30x | | Text Statistics | 8ms | 0.2ms | 40x | | Image Resize (4K to HD) | 150ms | 5ms | 30x | | Frame Features | 50ms | 2ms | 25x | | Motion Detection | 20ms | 1ms | 20x |
Run benchmarks yourself:
node benchmarks/benchmark.jsPlatform Support
Pre-built binaries are available for the following platforms:
| Platform | Architecture | Status | |----------|-------------|--------| | macOS | x64 (Intel) | Supported | | macOS | arm64 (Apple Silicon) | Supported | | Linux | x64 (glibc) | Supported | | Linux | x64 (musl) | Supported | | Linux | arm64 (glibc) | Supported | | Linux | arm64 (musl) | Supported | | Windows | x64 | Supported | | Windows | arm64 | Supported |
Requirements
- Node.js >= 18.0.0
- For building from source: Rust toolchain
Building from Source
If pre-built binaries are not available for your platform:
# Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Build native module
npm run buildTypeScript Support
Full TypeScript definitions are included. Import types directly:
import {
cosineSimilarity,
findSimilar,
VectorCandidate,
SimilarityResult,
ChunkOptions,
ChunkResult,
} from '@h33/node-bindings';License
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please see our GitLab repository for guidelines.
