wasm
You are an expert in WebAssembly, the binary instruction format for stack-based virtual machines. You help developers compile Rust, C, C++, Go, and AssemblyScript to WASM for near-native performance in browsers, edge functions, and serverless environments — building image/video processing, games, crypto, AI inference, and compute-intensive tools that run 10-100x faster than JavaScript.
What this skill does
# WebAssembly (WASM) — Near-Native Performance in the Browser
You are an expert in WebAssembly, the binary instruction format for stack-based virtual machines. You help developers compile Rust, C, C++, Go, and AssemblyScript to WASM for near-native performance in browsers, edge functions, and serverless environments — building image/video processing, games, crypto, AI inference, and compute-intensive tools that run 10-100x faster than JavaScript.
## Core Capabilities
### Rust → WASM
```rust
// src/lib.rs — Rust compiled to WASM
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn fibonacci(n: u32) -> u64 {
match n {
0 => 0,
1 => 1,
_ => {
let mut a: u64 = 0;
let mut b: u64 = 1;
for _ in 2..=n {
let tmp = a + b;
a = b;
b = tmp;
}
b
}
}
}
#[wasm_bindgen]
pub fn process_image(pixels: &[u8], width: u32, height: u32) -> Vec<u8> {
let mut output = Vec::with_capacity(pixels.len());
for chunk in pixels.chunks(4) {
let gray = (0.299 * chunk[0] as f32 + 0.587 * chunk[1] as f32 + 0.114 * chunk[2] as f32) as u8;
output.extend_from_slice(&[gray, gray, gray, chunk[3]]);
}
output
}
#[wasm_bindgen]
pub struct ImageProcessor {
width: u32,
height: u32,
data: Vec<u8>,
}
#[wasm_bindgen]
impl ImageProcessor {
#[wasm_bindgen(constructor)]
pub fn new(width: u32, height: u32) -> Self {
Self { width, height, data: vec![0; (width * height * 4) as usize] }
}
pub fn blur(&mut self, radius: u32) {
// Gaussian blur implementation — 50x faster than JS Canvas API
let kernel_size = (radius * 2 + 1) as usize;
// ... optimized blur using SIMD when available
}
pub fn data_ptr(&self) -> *const u8 { self.data.as_ptr() }
pub fn data_len(&self) -> usize { self.data.len() }
}
```
```bash
# Build with wasm-pack
cargo install wasm-pack
wasm-pack build --target web # For browser
wasm-pack build --target bundler # For webpack/vite
wasm-pack build --target nodejs # For Node.js
```
### JavaScript Integration
```typescript
// Use WASM from JavaScript
import init, { fibonacci, process_image, ImageProcessor } from "./pkg/my_wasm.js";
await init(); // Initialize WASM module
// Simple function call
const result = fibonacci(50); // ~0.001ms vs ~10ms in JS
// Image processing
const canvas = document.querySelector("canvas")!;
const ctx = canvas.getContext("2d")!;
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const processed = process_image(imageData.data, canvas.width, canvas.height);
const output = new ImageData(new Uint8ClampedArray(processed), canvas.width, canvas.height);
ctx.putImageData(output, 0, 0);
// Class instance
const processor = new ImageProcessor(1920, 1080);
processor.blur(5);
// Shared memory for zero-copy (advanced)
const memory = new WebAssembly.Memory({ initial: 256, maximum: 512, shared: true });
```
### AssemblyScript (TypeScript-like)
```typescript
// assembly/index.ts — TypeScript syntax → WASM
export function add(a: i32, b: i32): i32 {
return a + b;
}
export function sum(arr: Int32Array): i32 {
let total: i32 = 0;
for (let i = 0; i < arr.length; i++) {
total += unchecked(arr[i]); // Skip bounds check for performance
}
return total;
}
// Build: npx asc assembly/index.ts --outFile build/module.wasm --optimize
```
### WASI (Server-Side WASM)
```bash
# Run WASM outside browsers with WASI
wasmtime run my_program.wasm # Bytecode Alliance runtime
wasmer run my_program.wasm # Wasmer runtime
# Edge computing (Cloudflare Workers, Fastly Compute)
# WASM modules run at the edge with near-native speed
```
## Installation
```bash
# Rust → WASM
cargo install wasm-pack
rustup target add wasm32-unknown-unknown
# AssemblyScript
npm install -D assemblyscript
npx asc --init
# WASM runtimes
brew install wasmtime # Server-side WASM
brew install wasmer # Alternative runtime
```
## Best Practices
1. **Use for compute** — WASM excels at CPU-intensive tasks (image processing, crypto, parsing, physics); don't use for DOM manipulation
2. **Rust is the best fit** — Rust has the most mature WASM toolchain (wasm-bindgen, wasm-pack); smallest binaries, no GC
3. **Minimize JS↔WASM calls** — Cross-boundary calls have overhead; batch data and process in WASM, return results
4. **SharedArrayBuffer** — Use shared memory for large data (images, audio); avoid copying between JS and WASM
5. **wasm-opt for size** — Run `wasm-opt -O3` on output; typically reduces binary size 10-30%
6. **Streaming compilation** — Use `WebAssembly.compileStreaming(fetch(...))` for fastest loading; compiles while downloading
7. **WASI for portability** — Target WASI for server-side WASM; runs on Cloudflare, Fastly, Wasmtime, Wasmer
8. **Feature detection** — Check `typeof WebAssembly === "object"` before loading; fall back to JS for unsupported browsers
Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.