@lyku/para-signals
import { signal, derived, effect, batch, untrack, Signal } from "@lyku/para-signals";@lyku/para-signals is a small reactive primitive. signal(v) is a cell, derived(fn) is a read-only signal computed from others, and effect(fn) runs side effects when something it read changes. Reads inside an effect register a dependency; writes invalidate downstream and synchronously re-run subscribed effects before the write returns. Use batch to coalesce several writes into one re-run.
Pairs with the signal / effect { } / ~> / -> language extensions — those desugar to calls into this module. Plain .ts / .js files use the function form below; .pts / .pjs files can use either form.
signal(initial)
Section titled “signal(initial)”Creates a writable cell.
import { signal } from "@lyku/para-signals";
const count = signal(0);
count.get(); // read → 0count.set(1); // writecount.set(2); // writecount.update(n => n + 1); // read-modify-writesignal count = 0;
count; // read → 0 (bare reads desugar to .get())count = 1; // write (= desugars to .set())count++; // read-modify-writeSignals are objects: read with .get() and write with .set(value). Calling count() throws a TypeError. update(fn) is set(fn(get())) in one atomic-ish step. In .pts / .pjs files, signal NAME = … declarations make bare reads / writes desugar — same runtime, terser source.
derived(fn)
Section titled “derived(fn)”A read-only signal computed from others. Tracks every signal fn reads; re-evaluates when any of them changes.
const double = derived(() => count.get() * 2);double.get(); // 6 (after the update above)derived double = count * 2; // explicit form — keyword telegraphs read-onlysignal doubleAuto = count * 2; // also a derived (auto-promoted from RHS)double; // 4 (after count = 2)derived is lazy — it only re-evaluates when read after an invalidation. Multiple reads between writes return the cached value. In .pts / .pjs files you can spell deriveds two ways: explicit derived NAME = expr (keyword telegraphs that the binding is read-only and is the recommended form when clarity matters), or implicit signal NAME = expr whose RHS reads another in-scope signal (auto-promoted to a derived()). Same lowering, same runtime.
effect(fn)
Section titled “effect(fn)”Runs fn immediately, tracks its signal reads, and re-runs whenever any of them changes. Returns a disposer that removes the effect.
const dispose = effect(() => { console.log("count is", count.get()); // initially "count is 3"});
count.set(4); // logs "count is 4" before set() returnsdispose(); // stop watchingeffect { console.log("count is", count); // initially "count is 2"}
count = 3; // logs before the assignment completesEffects run synchronously after each changed write. Separate writes do not coalesce automatically; wrap related writes in batch(...) to defer re-runs until the outermost batch returns. The parabun effect { … } block sugar desugars to effect(() => { … }) — same runtime.
batch(fn)
Section titled “batch(fn)”Defers effect re-runs until fn returns:
const name = signal("bob");batch(() => { count.set(1); name.set("alice"); // no effects re-run yet});// effects re-run once with both new values visibleuntrack(fn)
Section titled “untrack(fn)”Reads inside fn don’t register as dependencies — useful inside an effect to read a signal “for context” without making the effect re-run when it changes.
effect(() => { console.log(count.get(), "for", untrack(() => name.get())); // re-runs on count changes; name changes alone do not trigger it});ParaBun-only driver and edge helpers
Section titled “ParaBun-only driver and edge helpers”The following five helpers (fromAsync, fromInterval, pump, when, and whenStart) belong to ParaBun’s bundled signals module. They are not exported by npm @lyku/para-signals@0.0.1-pre.4. These examples require ParaBun; Node and browser consumers can use the resource adapters in Stream adapters and the core effect API instead. The core object API and synchronous timing described above work in both implementations.
fromAsync(iterable, mapFn?, init?)
Section titled “fromAsync(iterable, mapFn?, init?)”Creates a signal driven by an async iterable. Saves the IIFE+for-await dance for “I want the most recent value as a Signal”.
import sigs from "@lyku/para-signals";
// Most recent value from a websocket-like source, exposed as a signal.const { signal: msg, dispose } = sigs.fromAsync(socket.messages(), m => m.body, "");
effect(() => console.log("latest:", msg.get()));
// Clean up when you're done.dispose();Returns { signal, dispose }. signal is read-only (the pump owns writes); dispose breaks the loop via the iterator’s return() and fires any generator finally block. Calling dispose twice is a no-op.
If mapFn is omitted, raw yielded values flow through unchanged. If init is omitted, the signal starts at undefined.
fromInterval(fn, periodMs)
Section titled “fromInterval(fn, periodMs)”Drive a signal from a periodic call. The IoT companion to fromAsync: takes a sync-or-async fn and a period in ms, calls it immediately and every periodMs, and exposes the latest resolved value as a Signal. Thrown errors are swallowed (the signal keeps its previous value).
The internal timer .unref()s itself, so a bare fromInterval(...) call doesn’t pin the event loop on its own — pair it with an effect { … } block or another keep-alive when you want the process to stay running on its account.
import sigs from "@lyku/para-signals";
// Poll an i2c sensor every 500 ms, expose latest reading as a signal.const temp = sigs.fromInterval( () => sensor.smbus.readWord(0xFA), 500,);
sigs.effect(() => console.log("temp:", temp.signal.get()));import sigs from "@lyku/para-signals";
const temp = sigs.fromInterval( () => sensor.smbus.readWord(0xFA), 500,);
effect { console.log("temp:", temp.signal.get()); }Same shape as fromAsync — returns { signal, dispose }. Common patterns: i2c / SPI sensor reads, periodic HTTP polls, anything where “the latest value of a periodic source” is what you want.
pump(iterable, signal, mapFn?)
Section titled “pump(iterable, signal, mapFn?)”Drive an existing signal from an async iterable — useful when the signal pre-exists, or when you want to switch sources at runtime.
const score = sigs.signal(0);const stop = sigs.pump(motionFrames, score, f => f.motionScore);// later: stop();Returns a disposer with the same semantics as fromAsync’s dispose.
The signal must be a writable one (returned by signal(...)); passing a derived(...) result throws.
when(source, fn)
Section titled “when(source, fn)”Edge-detection helper. when calls fn once each time source transitions from falsy to truthy (boolean-coerced). The falling edge is the rising edge of the negated predicate, so a single helper covers both directions: when(() => !s.get(), fn) fires on true→false. The block syntaxes when not EXPR { … } and the bare-paired when stop { … } rewrite to that form automatically.
source can be either a Signal<T> (a signal(...) cell, a derived(...), or any driver-handle signal) or a predicate function — passing () => a.get() && b.get() === "x" skips the explicit derived(...) wrapper. Reads inside the predicate are tracked the same way they would be inside an effect.
The initial value is treated as already-observed — a source that starts truthy does not fire on first run; only subsequent false→true transitions do.
import signals from "@lyku/para-signals";
// Greet on the rising edge of (motion present AND bot idle).signals.when( () => motion.detected.get() && bot.state.get() === "idle", () => bot.say("Welcome back!"),);
// Or, with an existing signal:signals.when(button.pressed, () => console.log("clicked"));
// Falling edge — negate the predicate.signals.when(() => !button.pressed.get(), () => console.log("released"));Returns a disposer with the same semantics as effect().
Common patterns: button-press detection, arrival/departure handlers, threshold crossings, “fire once when condition becomes true” without manual wasX = false flag bookkeeping.
whenStart(source, fn)
Section titled “whenStart(source, fn)”Same as when but also fires once at registration if source is initially truthy. Use it for “the dangerous state is the noteworthy one” alerts where you don’t want to silently miss a boot already in the bad state. The .pts keyword form is when EXPR start { … } — the trailing start modifier is the visible opt-in for the initial-truthy fire; signals.whenStart(...) is the direct call for .ts users.
import signals from "@lyku/para-signals";
// Boot-already-empty tank? Notify now AND on every empty event.signals.whenStart(tankEmpty, () => alert("tank EMPTY"));
// Boot with a healthy tank? `when not tankEmpty` skips the boot// observation so you don't get a fake "back above empty" message.signals.when(() => !tankEmpty.get(), () => log("tank refilled"));Pick plain when (or signals.when) for “user pressed button” / “page loaded” — anywhere faking the event at startup would be wrong. Reach for start / whenStart for safety, health, and connectivity alerts where missing the boot-bad case is worse than firing one extra time.
promiseSignal(thunk) — promise → { data, error, pending } cell
Section titled “promiseSignal(thunk) — promise → { data, error, pending } cell”The producer behind the .pui async signal x = EXPR form. The thunk fires
synchronously at construction (the request starts immediately) and
receives an AbortSignal; dispose() aborts it and drops a late settle —
no stale state after unmount. Fire-once-per-mount by design: it does not
re-run when a dependency changes (that’s querySignal, below).
import { promiseSignal } from "@lyku/para-signals";
const user = promiseSignal(s => fetch(`/api/user/${id}`, { signal: s }).then(r => r.json()));user.peek(); // { data, error, pending } — pending: true until the settlequerySignal(thunk, schema, opts?) — the tracked, gated sibling
Section titled “querySignal(thunk, schema, opts?) — the tracked, gated sibling”The producer behind derived NAME :: SCHEMA = EXPR
(spec §10.7): a client-pull async cell
whose settle crosses schema.parse — Ok stores the parsed value, Err
lands in error as a state, never a throw. One instance is one run: the
.pui bridge constructs it inside a tracked scope, so reading a signal in
the thunk makes a change re-key (dispose + fresh construct = latest-wins,
no run-id machinery). opts.prev seeds stale-while-revalidate — a refetch
shows the old data with pending: true instead of a flash to undefined.
import { querySignal } from "@lyku/para-signals";
const found = querySignal(s => api.search(q, { signal: s }), Post, { prev: last });// the .pui sugar — refetches when `id` changes, response gated by Userderived user :: User = graphql.userById(id);resource(setup) — explicit lifecycles
Section titled “resource(setup) — explicit lifecycles”Hardware modules emit signals tied to a real underlying resource (a mic, a camera, a file watcher, a websocket). When the resource closes, those signals should become inert and observers should unwind cleanly. resource() is the primitive that makes that lifecycle explicit:
import { resource } from "@lyku/para-signals";
const mic = resource(({ signal: sig, onDispose }) => { const peak = sig(0); const handle = openMic(); // pretend hardware handle.onPeak(v => peak.set(v)); onDispose(() => handle.close()); return { peak }; // becomes mic.peak});
mic.peak.get(); // current peak levelmic.alive.get(); // boolean signal — true until disposemic.use(() => console.log(mic.peak.get())); // effect bound to resource lifetimemic.dispose(); // close mic, run cleanups, alive flips to false, // bound effects auto-tear-downThe handle layers alive / dispose / [Symbol.dispose] / [Symbol.asyncDispose] / use(fn) on top of whatever the setup function returned. use(fn) is the key ergonomic — bound effects auto-dispose when the resource closes, so consumers don’t need defensive if (active.get()) guards everywhere.
Setup runs synchronously and may register cleanups via onDispose. Cleanups run in reverse-registration order on dispose(). If setup throws, any cleanups it had time to register are still run before the exception propagates.
See the resource lifecycle. A using declaration disposes the resource at scope exit:
{ using mic = openMicResource(); effect(() => render(mic.peak.get())); // mic disposed automatically at scope exit}Stream adapters
Section titled “Stream adapters”Hardware emits streams. These adapters lift the underlying primitive into a resource-tied signal — no manual pump loop in user code:
fromAsyncIter(iter, initial?): pumps each yielded value intoresult.value. Disposing calls the iterator’sreturn().fromStream(readableStream, initial?): same forReadableStream<T>. Cancels the reader on dispose.fromEventTarget(target, eventName, { initial?, map? }): listens for events; signal updates withmap(event). Removes the listener on dispose.
const live = fromStream(audioFrames, null);effect(() => process(live.value.get()));live.dispose(); // reader cancelled, stream gracefully releasedEach returns a resource handle, so .alive, .dispose(), .use() are available the same way.
Rate-limit operators
Section titled “Rate-limit operators”Hardware emits faster than UI consumers want — a mic’s peak level updates 1000 Hz; a UI wants 30 fps. These operators wrap a source signal and emit at controlled cadence:
throttled(source, ms): leading-edge; the first change emits immediately, and subsequent changes withinmscoalesce into a trailing emit at window end.debounced(source, ms): emits only aftermsof silence following the last change.
Both return resources whose result.value is the rate-limited signal:
const peakSlow = throttled(mic.peak, 33); // 30fps view of a 1000hz sourceeffect(() => render(peakSlow.value.get()));peakSlow.dispose();Writable and derived signals
Section titled “Writable and derived signals”A writable signal exposes .get(), .peek(), .set(value), .update(fn), and .subscribe(listener). In npm @lyku/para-signals@0.0.1-pre.4, a derived signal exposes .get() and .peek() but no .set(), .update(), or .subscribe(). ParaBun’s bundled derived signals also expose .subscribe() and a .set() method that throws; they remain read-only and have no .update(). The npm package exports Signal as the writable implementation class; prefer signal(...) for construction.
Composing with the rest of the stack
Section titled “Composing with the rest of the stack”- DOM-ish updates: pair with
~>(reactive assignment) to keep DOM elements / canvas state in step with signal values, or->(reactive call-binding) to push each new value into a sink function (process.stdout.write,socket.send, …). - Background work: an
effectcan dispatch a@lyku/para-parallelpmapand write the result back into a signal — the next read picks it up. - Server-rendered fragments:
derived(() => render(...))recomputes only when inputs change. - IoT control loops:
fromIntervalfor any periodic source (parabun:i2csensors, HTTP polls),pollHzonparabun:gpiolines for hardware-backed value signals.
Limits
Section titled “Limits”- Effects flush synchronously. Use
batch(...)when several writes must be observed together. - Avoid cyclic dependencies. Derived signals are lazy: mutually referring derived signals can be constructed without an error, then overflow the call stack when read. Do not rely on registration-time cycle detection.
- No ownership / scope — effects live forever unless
dispose()d. Wrap with@lyku/para-arena-style scoping in long-lived loops.