Skip to content
yuichkunPublic

About

A declarative framework for writing Audio Worklet-based DSP in TypeScript, compiled to WebAssembly with realtime-safety guarantees.

Resources

Stars

12 stars

Watchers

0 watching

Forks

Repository files navigation

unworklet
unworklet

Realtime-safe DSP in plain TypeScript — typed primitives compiled to
WebAssembly for any audio thread: browser, server, or microcontroller.


The audio thread is unforgiving: allocations, GC pauses, and invalid memory accesses can interrupt playback. unworklet compiles DSP into a constrained WASM program and tests the transport that connects it to the application.

You compose a processor from small, typed, reusable primitives in plain TypeScript — audio, params, state, events, MIDI. The emitted WASM DSP has preallocated memory and bounded loops, without JavaScript allocation or GC. The toolchain also supplies AudioWorkletProcessor glue and a typed main-thread node. No hand-written processor, no SharedArrayBuffer wrangling, no linear-memory bookkeeping. The postMessage compatibility transport can allocate while receiving messages and recycling buffers; it does not carry an allocation-free or GC-free guarantee for the complete audio thread.

The primitives snap together like Lego: build an effect, a synth, a MIDI device — whatever you need. Test it headless in Node / Bun / Deno against the exact WASM you ship, and X-ray the running audio thread live with zero-config DevTools.

Quick start

npm install @unworklet/core
npm install -D @unworklet/unplugin @unworklet/lang @unworklet/offline @unworklet/test
# ?worklet loader + .uwk.ts editor support + headless render + Vitest matchers
// vite.config.ts
import unworklet from "@unworklet/unplugin";

export default { plugins: [unworklet()] };

The loader is built on unplugin, and the type wiring below is plain tsconfig — the Vite integration is what ships today.

Add one line to your tsconfig.json. The plugin generates a .unworklet/tsconfig.json that wires up the main-thread types and the .uwk.ts editor checker, so node.params.<name> (and state / events / midi / inputs / outputs) are typed and the sugar type-checks with no @ts-nocheck — no vite-env.d.ts needed:

// tsconfig.json
{ "extends": "./.unworklet/tsconfig.json" }

The plugin writes .unworklet/ (the tsconfig above plus a worklets.d.ts carrying your processors' types) on vite dev / vite build; add .unworklet/ to .gitignore (a generated artifact, like Nuxt's .nuxt/). Adding processors only regrows worklets.d.ts — you never touch your tsconfig again. Don't put your own include on this tsconfig: extends doesn't merge include, so the generated one must own it (need your own? use the manual setup below).

In VS Code, run “TypeScript: Select TypeScript Version → Use Workspace Version” (the editor plugin loads only under the workspace TypeScript). For build / CI, @unworklet/lang ships unworklet-tsc, a drop-in tsc that checks .uwk.ts too.

Can’t extend (an existing tsconfig you can’t restructure)?

Write the same three settings into your own tsconfig.json directly — still no vite-env.d.ts:

// tsconfig.json
{
  "compilerOptions": {
    "types": ["@unworklet/unplugin/client"],
    "plugins": [{ "name": "@unworklet/lang/typescript-plugin" }],
  },
  "include": ["src", ".unworklet/worklets.d.ts"],
}

List .unworklet/worklets.d.ts explicitly in include — a **/* glob skips the dot-folder. If this is the first types entry in your config, also list the type packages you already rely on (e.g. "node"), since types disables automatic @types loading.

A processor is a .uwk.ts file — write the DSP as plain expressions and unworklet lowers it to the core primitives and compiles it to fixed-memory, bounded-work WASM:

// distortion.uwk.ts — soft-clip distortion, compiled to a WASM AudioWorklet
const input = audioInput({ channels: 2, name: "main" });
const out = audioOutput({ channels: 2, name: "main" });
const drive = param.f32({ default: 4, min: 1, max: 20, automationRate: "a-rate" }).named();

process(() => {
  forSample((i) => {
    const l = input.left[i] * drive[i];
    const r = input.right[i] * drive[i];
    out.left[i] = l > 1 ? 1 : l < -1 ? -1 : l; // soft clip
    out.right[i] = r > 1 ? 1 : r < -1 ? -1 : r;
  });
});
// main.ts — you get back a typed node
import { createNode } from "@unworklet/core";
import distortion from "./distortion.uwk.ts?worklet"; // the ?worklet query is required

// Any context works: the ?worklet build targets 48 kHz and 128-sample quanta, and
// createNode compiles for any other rate or renderSizeHint in a Web Worker.
const ctx = new AudioContext();
const node = await createNode(ctx, distortion);

// an unworklet node is a normal AudioNode — feed it anything, route it anywhere:
const osc = new OscillatorNode(ctx, { frequency: 110 });
osc.connect(node.inputs.main);
node.outputs.main.connect(ctx.destination);
node.params.drive.value = 8; // the AudioParam, fully typed
osc.start();

Browsers start an AudioContext only after a user gesture, so call ctx.resume() from a click handler to actually hear it.

.uwk.ts is the recommended authoring form. Prefer explicit method calls over the operators? Write the same processor as a plain .processor.ts with the core API (input.left.at(i).mul(drive.at(i))) — it lowers to exactly the same result.

Use it with an AI agent

unworklet ships an agent skill carrying the exact DSL forms, so an agent scaffolds a project and writes correct processors without hallucinating the API. Install it into your project once:

npx skills add https://github.com/yuichkun/unworklet/tree/main/skills/unworklet

That detects the coding agents you have and installs the skill for each of them — Claude Code, Codex, Cursor, opencode, Zed, Copilot and others. Then just ask — "make an FM synth with unworklet" — and the agent sets up the project and implements it. Update later with npx skills update.

Prefer not to run the installer? Copy skills/unworklet/ into your project as .agents/skills/unworklet/ — the directory layout is already the convention that Codex, Cursor, opencode, Zed, Copilot and Gemini CLI read. Claude Code reads .claude/skills/ instead, so copy it there for that one. Copy the whole folder either way: SKILL.md points at its siblings by filename.

For a chat LLM with no repository access (ChatGPT, Claude.ai), paste skills/unworklet/SKILL.md into the conversation and follow its links as you need them.

What you can build

The primitives — audioInput / param / state / state.buffer / event / event.midi, the math ops, forSample, and reusable defineSubgraph blocks — compose into anything: effects, synths, samplers, MIDI processors, sysex bridges. MIDI is first-class and sample-accurate, so a processor can receive notes and synthesize, or emit notes like an arpeggiator.

Here's a monophonic synth driven by Web MIDI — it receives noteOn / noteOff on the audio thread and oscillates:

// synth.uwk.ts — a monophonic MIDI sine voice
const out = audioOutput({ channels: 1, name: "main" });
const keys = event.midi({ from: "main", name: "keys" });

const hz = state.f32(440).named();
const gate = state.f32(0).named();
const phase = state.f32(0).named();

process(() => {
  keys.onEvent("noteOn", ({ note }) => {
    hz.write(exp(f32(note - 69) * (Math.LN2 / 12)) * 440); // MIDI note → Hz
    gate.write(1);
  });
  keys.onEvent("noteOff", () => gate.write(0));

  forSample((i) => {
    phase.write((phase + hz / ctx.sampleRate) % 1); // advance the oscillator
    out.ch(0)[i] = sin(phase * (Math.PI * 2)) * gate * 0.2;
  });
});
// wire it to a Web MIDI input — no app code on the audio thread
import synth from "./synth.uwk.ts?worklet";

const node = await createNode(ctx, synth);
node.outputs.main.connect(ctx.destination);

const midi = await navigator.requestMIDIAccess();
node.midi.keys.connectFromWebMIDI([...midi.inputs.values()][0]);

See examples/demo/ for live-editable .uwk.ts examples (distortion, tremolo, lowpass, MIDI synths, arpeggiator, granular voice, …) rendered in the browser.

Realtime-safe by construction

Writing real DSP for an AudioWorklet is a trap for a JavaScript developer. Allocation is invisible (a [], a closure — the GC does the rest), but on the audio thread it causes dropouts. Sharing state across threads means SharedArrayBuffer + Atomics + COOP/COEP headers. Reaching for WASM to go faster means managing linear-memory offsets and lifetimes by hand. And you can't even console.log to debug — that isn't realtime-safe either.

Your TypeScript runs at build time to capture the graph. The emitted DSP runs as WASM, surrounded by the framework's JavaScript worklet transport. The DSP is:

  • allocation-free — all state, buffers, and ringbuffers are pre-sized at compile time; memory.grow is never emitted.
  • bounded — every loop has a build-time-known iteration count; there is no unbounded-loop primitive in the surface.
  • non-blocking — it performs no I/O or synchronous main-thread wait. Runtime WASM traps are reported through onError and silence the failed processor.

The framework owns the SharedArrayBuffer transport, linear-memory layout, and worklet/main marshalling. These paths also require runtime and concurrency tests; a successful compile is not a guarantee against every implementation bug or browser scheduling delay. When shared memory is unavailable, postMessage keeps the application usable with bounded buffer reuse, but its message delivery and recycling can allocate and trigger GC.

Render & test — no browser needed

The emitted WASM runs under any host JS runtime, so you can render and test a processor headlessly. renderOffline runs the exact binary you ship — tests are real, deterministic, and bit-exact, not a simulation.

import { renderOffline, encodeWav } from "@unworklet/offline";
import distortion from "./distortion.uwk.ts?worklet";

const r = await renderOffline(distortion, {
  sampleRate: 48000,
  duration: 2,
  inputs: { main: [left, right] },
  params: { drive: [8] },
});

await Bun.write("out.wav", encodeWav(r.outputs.main, r.sampleRate));

@unworklet/test adds Vitest matchers on top — audio, events, MIDI, and state:

import { renderOffline } from "@unworklet/offline";
import { sine, expectNoNaN, expectStable } from "@unworklet/test";
import distortion from "./distortion.uwk.ts?worklet";

const r = await renderOffline(distortion, {
  sampleRate: 48000,
  duration: 0.5,
  inputs: { main: [sine({ freqHz: 220, durationSamples: 24000, sampleRate: 48000 })] },
  params: { drive: [8] },
});
expectNoNaN(r);
expectStable(r); // finite, no runaway DC / clipping

DevTools

The audio thread is normally a black box. unworklet's Vite DevTools panel X-rays it. Every value it shows is read bit-exact from WASM memory, so the inspector never lies; in a production build the plugin compiles to nothing and your app is byte-for-byte unchanged.

  • Live state — every state / buffer slot, live from WASM memory (waveform / bar / list per type)
  • Audio graph — the running AudioContext topology
  • Signals & performance — per-output waveform / spectrum + per-quantum latency
  • MIDI — event activity + a virtual keyboard to inject notes
DevTools — Live state
Live state — every state / buffer slot, live from WASM memory
DevTools — Audio graph
Audio graph — the running AudioContext topology
DevTools — Signals & performance
Signals & performance — per-output waveform / spectrum + latency
DevTools — MIDI
MIDI — event log + a virtual keyboard to inject notes

Enabling it

The panel is a dock inside the Vite DevTools overlay, so you install that host (plus its client kit, which the panel's page bridge imports) and add it to your config. The unworklet plugin itself needs no extra config — it auto-docks once the host is present.

npm install -D @vitejs/devtools@0.4 @vitejs/devtools-kit@0.4 \
  @vitejs/devtools-rolldown@0.4 @vitejs/devtools-oxc@0.4 \
  @vitejs/devtools-vitest@0.4 @vitejs/devtools-vite@0.4
// vite.config.ts
import { DevTools } from "@vitejs/devtools";
import unworklet from "@unworklet/unplugin";
import { defineConfig } from "vite";

export default defineConfig(({ command }) => ({
  plugins: [
    unworklet(),
    // Dev only — the DevTools host runs a long-lived server, pointless in a build
    // and it would keep the test runner from exiting. Vitest also passes
    // `command: "serve"`, so also gate on `!process.env.VITEST` or `vitest run`
    // hangs 10s at close.
    ...(command === "serve" && !process.env.VITEST ? [DevTools({ builtinDevTools: false })] : []),
  ],
}));

Run your dev server, open the Vite DevTools overlay, and pick the unworklet dock.

Two gotchas worth knowing up front:

  • Match the 0.4 major across all 6 packages. @unworklet/unplugin pins @vitejs/devtools-kit to ^0.4.0 (optional peerDependency): the live panels reach the dev server through an anonymous RPC scope whose prefix is coupled to the DevTools major (devframe:anonymous: on the current line), so a mismatched-major host silently rejects every push and the panels stay empty. The 0.3 line was Vite 6/7 only — Vite 8 requires the 0.4 line. The panel's page bridge also imports @vitejs/devtools-kit/client as a direct dependency, which must resolve from your app — a transitive copy is not enough.
  • Cross-origin isolation. The plugin makes the dev server cross-origin isolated by default (COOP same-origin + COEP credentialless) so SharedArrayBuffer works with no config — credentialless rather than require-corp, which would block the DevTools iframe (/__unworklet/). If isolation conflicts with a cross-origin resource or the DevTools panel, opt out with unworklet({ crossOriginIsolation: false }); unworklet then uses the postMessage transport in dev. Production headers remain your server's job.

The panels can't be deployed as a static demo: the host is a dev-time server, so clone the repo and start an example locally to try them live.

Packages

package what it does
@unworklet/core The DSL, the WASM compiler, the worklet runtime, and the typed main-thread node.
@unworklet/unplugin Loads .processor.ts / .uwk.ts via ?worklet; ships the DevTools panel.
@unworklet/lang The .uwk.ts authoring sugar (infix operators, index access) that lowers to core.
@unworklet/offline Render a processor to PCM headlessly in Node / Bun / Deno.
@unworklet/test Audio / event / MIDI / state assertions and signal generators for Vitest.

Docs

End-user / AI-agent guidance lives in skills/unworklet/ — the same files npx skills add installs into your agents:

skills/unworklet/ is the source of truth for how unworklet behaves: it is verified against the implementation, and CI compiles every complete example in it — the .uwk.ts ones through the lowering, the defineProcessor ones directly. docs/ holds only history — the decisions log (why each design question was settled) and the RFCs. Neither describes current behaviour, so neither can contradict it.

Contributing

A pnpm monorepo driven through the Vite+ CLI (vp):

vp install        # install dependencies
vp run build      # build the five packages in dependency order (tests need it)
vp check          # lint + format + typecheck (vp check --fix to auto-fix)
vp test run       # vitest (node-side + browser SAB / postMessage)

Conventions and design rationale: AGENTS.md.

License: MIT.

About

A declarative framework for writing Audio Worklet-based DSP in TypeScript, compiled to WebAssembly with realtime-safety guarantees.

Resources

Stars

12 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages