@zakkster/lite-signal 1.5.0-alpha.0 → 1.6.0-preview.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +84 -0
- package/Signal.js +86 -9
- package/package.json +1 -1
- package/llms.txt +0 -619
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,84 @@ All notable changes to `@zakkster/lite-signal` are documented here.
|
|
|
4
4
|
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
5
|
This project follows [Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## [1.6.0] -- 2026-06-26 (preview)
|
|
8
|
+
|
|
9
|
+
The observability-and-lifecycle minor, shipping on the `preview` dist-tag while it
|
|
10
|
+
settles. Two additions: `stats()` gains a twelfth key, **`flushPasses`**, plus two
|
|
11
|
+
flush-profiling mutation-hook opcodes -- the flush/recompute dimension
|
|
12
|
+
lite-devtools 1.2 / lite-studio 1.2 read through `watchAllocations`; and
|
|
13
|
+
**`createScope(fn)`** (landed in `preview.0`), the disposable-owner counterpart to
|
|
14
|
+
`createRoot` that a keyed-list / scene reconciler needs for per-item teardown.
|
|
15
|
+
Drop-in over 1.5.0: the callable API and hot paths are unchanged, and the new
|
|
16
|
+
instrumentation is frozen and zero-cost unless a mutation-hook listener is attached.
|
|
17
|
+
|
|
18
|
+
### Added -- `flushPasses` on `stats()` + flush-profiling opcodes
|
|
19
|
+
|
|
20
|
+
`stats()` now returns **12 keys**: the 11 from 1.4.x plus `flushPasses`, a counter
|
|
21
|
+
that advances once per effect-flush drain pass. Two `onGraphMutation` opcodes back
|
|
22
|
+
the flush dimension:
|
|
23
|
+
|
|
24
|
+
- **`6` flush pass** -- `(passCount, effectsToRun)`, at the top of each drain pass.
|
|
25
|
+
- **`7` effect run in pass** -- `(id, 0)`, before each effect re-run inside a pass.
|
|
26
|
+
|
|
27
|
+
Both the counter bump and the opcode dispatch sit behind the existing
|
|
28
|
+
`if (mutationHook !== null)` gate, so when no profiler is attached they are inert:
|
|
29
|
+
`flushPasses` is frozen and the flush loop is byte-identical to 1.5.0. This is what
|
|
30
|
+
lets `watchAllocations` chart recompute/flush activity alongside the 1.4.0
|
|
31
|
+
allocation counters (`totalAllocations` / `poolGrowths` / `totalDisposals`), which
|
|
32
|
+
remain available from 1.4.0 on every engine -- only the flush series requires 1.6.
|
|
33
|
+
|
|
34
|
+
### Added -- `createScope(fn)` (disposable owner scope) [preview.0]
|
|
35
|
+
|
|
36
|
+
`createScope` runs `fn(dispose)` in a detached scope and returns whatever `fn`
|
|
37
|
+
returns, having handed `fn` a single `dispose` that **cascade-disposes every effect
|
|
38
|
+
and computed created inside `fn`**. It is the lifecycle complement to `createRoot`:
|
|
39
|
+
|
|
40
|
+
- `createRoot(fn)` only **detaches** -- nodes created inside are unowned and the
|
|
41
|
+
caller must dispose each one by hand (there is no owner to do it automatically).
|
|
42
|
+
Correct for spawning one known long-lived watcher (lite-query's pattern).
|
|
43
|
+
- `createScope(fn)` **adopts** -- it owns whatever `fn` builds, so one disposer tears
|
|
44
|
+
down a subtree of *unknown* shape. This is what a per-item scope in a keyed-list or
|
|
45
|
+
scene reconciler requires, where the item's reactive graph is the consumer's
|
|
46
|
+
`mapFn`, not something the reconciler can enumerate.
|
|
47
|
+
|
|
48
|
+
**Semantics.** `fn` runs once in a detached, untracked context: no ownership and no
|
|
49
|
+
dependency leak from `fn`'s direct body into the enclosing scope, and the scope owner
|
|
50
|
+
never re-runs. Reactive bindings belong in inner effect/computed bodies inside `fn`
|
|
51
|
+
(those track normally and are owned by the scope); direct-body reads are untracked.
|
|
52
|
+
Consistent with the 1.2.0 ownership rule, **plain signals created directly in `fn` are
|
|
53
|
+
not adopted** -- dispose those explicitly (the creator holds the handle) or let them
|
|
54
|
+
fall out of reference; computeds and effects are adopted and cascade.
|
|
55
|
+
|
|
56
|
+
**Implementation.** The scope owner is backed by a never-re-running effect node, so it
|
|
57
|
+
counts as one effect in `stats()` and its disposer is the same gen-guarded, ABA-safe,
|
|
58
|
+
introspection-stamped handle `effect()` returns (`describe` / `nodeId` / `forEachOwned`
|
|
59
|
+
resolve it to the owner). No new node kind, flag, or `stats()` key -- the pinned
|
|
60
|
+
`signals + computeds + effects === activeNodes` invariant is untouched. The API
|
|
61
|
+
(`fn => dispose`) is the stable contract; a future engine may swap in a lighter
|
|
62
|
+
pure-owner node transparently.
|
|
63
|
+
|
|
64
|
+
Exported as a registry method and a top-level helper bound to the default registry,
|
|
65
|
+
mirroring `createRoot`.
|
|
66
|
+
|
|
67
|
+
### Verified
|
|
68
|
+
|
|
69
|
+
- **`createScope` behavior** (4 tests, `node --expose-gc`): returns `fn`'s value and
|
|
70
|
+
runs the owner exactly once even when `fn` reads signals in its direct body
|
|
71
|
+
(untracked); inner effects/computeds track and update; `dispose()` cascade-disposes
|
|
72
|
+
the owned subtree (effects + computeds) while an un-adopted signal correctly
|
|
73
|
+
survives; a disposed scope's inner effects stop firing; **a scope created inside a
|
|
74
|
+
consumer effect survives that consumer's re-run** (the reconciler-critical detach
|
|
75
|
+
property); `dispose()` is an idempotent no-op on the second call; the disposer is
|
|
76
|
+
introspection-stamped to its owner effect; and `totalAllocations - totalDisposals
|
|
77
|
+
=== activeNodes` holds after teardown. Plus a smoke confirming signal -> computed ->
|
|
78
|
+
effect is unaffected by the additive change.
|
|
79
|
+
- **Instrumentation is zero-cost when unobserved**: `flushPasses` advances and opcodes
|
|
80
|
+
6/7 fire only while a mutation-hook listener is attached; with none, the flush path
|
|
81
|
+
is unchanged from 1.5.0.
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
7
85
|
## [1.5.0] -- 2026-06-XX
|
|
8
86
|
|
|
9
87
|
The API-surface minor: two new **non-callable, allocation-light** reactive
|
|
@@ -135,6 +213,8 @@ survives consumer re-runs.
|
|
|
135
213
|
|
|
136
214
|
|
|
137
215
|
|
|
216
|
+
## [1.4.0] -- 2026-06-XX
|
|
217
|
+
|
|
138
218
|
The observability minor: `stats()` gains **three cumulative lifecycle counters**
|
|
139
219
|
(`totalAllocations`, `totalDisposals`, `poolGrowths`) -- the surface reserved for
|
|
140
220
|
1.4.0 in the 1.2.x and 1.3.0 notes, now delivered. This is what lite-devtools /
|
|
@@ -209,6 +289,8 @@ as before (the reset keeps the arena warm); only the cumulative counts reset.
|
|
|
209
289
|
|
|
210
290
|
|
|
211
291
|
|
|
292
|
+
## [1.3.0] -- 2026-06-XX
|
|
293
|
+
|
|
212
294
|
The pool minor: the node and link pools become **growable and incrementally
|
|
213
295
|
populated**, the propagation mark phase moves to an **intrusive linked-list
|
|
214
296
|
stack**, and a small **registry config surface** (`prealloc`,
|
|
@@ -303,6 +385,8 @@ in 1.3.0.
|
|
|
303
385
|
|
|
304
386
|
|
|
305
387
|
|
|
388
|
+
## [1.2.2] -- 2026-06-XX
|
|
389
|
+
|
|
306
390
|
A code-deletion ship: a `createNode` audit removes ten redundant field-writes
|
|
307
391
|
that defended against a state the engine cannot produce on a clean free-list.
|
|
308
392
|
No public surface change, no semantic change, no new tests required for new
|
package/Signal.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @zakkster/lite-signal v1.
|
|
2
|
+
* @zakkster/lite-signal v1.6.0
|
|
3
3
|
* --------------------
|
|
4
4
|
* Hybrid Doubly-Linked-List Reactive Graph Engine -- decoupled (Signal1_3) base
|
|
5
5
|
* with the two 1.1.3 performance fixes ported in:
|
|
@@ -250,6 +250,8 @@ export function createRegistry(config) {
|
|
|
250
250
|
let statTotalAllocations = 0; // bumped on every createNode (pool pop OR fresh build)
|
|
251
251
|
let statTotalDisposals = 0; // bumped on every disposeNode
|
|
252
252
|
let statPoolGrowths = 0; // bumped when a node/link chunk pushes capacity past its ledger
|
|
253
|
+
let statFlushPasses = 0; // 1.6: bumped per flush pass, ONLY while a mutation-hook
|
|
254
|
+
// listener is attached (gated -> zero cost when detached).
|
|
253
255
|
|
|
254
256
|
const effectQueueA = [];
|
|
255
257
|
const effectQueueB = [];
|
|
@@ -314,12 +316,13 @@ export function createRegistry(config) {
|
|
|
314
316
|
*
|
|
315
317
|
* @private
|
|
316
318
|
*/
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
319
|
+
// --- Graph-mutation hook (1.2.1 keystone prototype) ---------------------
|
|
320
|
+
// Single nullable listener; every fire point is `if (mutationHook !== null)`
|
|
321
|
+
// -- branch-predicted free when absent, allocation-free when present
|
|
322
|
+
// (opcode + two int args). Enables push-based devtools (watchGraph) and the
|
|
323
|
+
// recompute profiler. Opcodes: 1 node-create, 2 node-dispose, 3 link-add,
|
|
324
|
+
// 4 link-remove, 5 recompute, 6 flush-pass-start (a=pass#, b=effects this pass),
|
|
325
|
+
// 7 effect-enqueue (a=node id). 6/7 added in 1.6 for burst/flush profiling.
|
|
323
326
|
let mutationHook = null;
|
|
324
327
|
function onGraphMutation(fn) {
|
|
325
328
|
if (fn !== null && typeof fn !== "function") throw new TypeError("onGraphMutation: listener must be a function or null");
|
|
@@ -743,6 +746,9 @@ export function createRegistry(config) {
|
|
|
743
746
|
if ((flags & (FLAG_QUEUED | FLAG_COMPUTING)) === 0) {
|
|
744
747
|
t.flags = flags | FLAG_QUEUED;
|
|
745
748
|
activeQueue[activeQueueLen++] = t;
|
|
749
|
+
// 1.6: op 7, effect enqueued. Gated; the ONE insertion inside the
|
|
750
|
+
// markDownstream inner loop -> gate-check KAIROS/MUX before shipping.
|
|
751
|
+
if (mutationHook !== null) mutationHook(7, t.id, 0);
|
|
746
752
|
}
|
|
747
753
|
} else {
|
|
748
754
|
// Intrusive push: t.nextMark holds the prior head
|
|
@@ -773,6 +779,9 @@ export function createRegistry(config) {
|
|
|
773
779
|
while (activeQueueLen > 0) {
|
|
774
780
|
if (++passes > maxFlushPasses) throw new Error("CycleError: flush passes exceeded");
|
|
775
781
|
const toRun = activeQueueLen | 0;
|
|
782
|
+
// 1.6 burst/flush instrumentation. Gated on the hook -> zero cost when no
|
|
783
|
+
// profiler is attached; statFlushPasses advances only while observed.
|
|
784
|
+
if (mutationHook !== null) { statFlushPasses = (statFlushPasses + 1) | 0; mutationHook(6, passes, toRun); }
|
|
776
785
|
const currentQueue = activeQueue;
|
|
777
786
|
|
|
778
787
|
isQueueA = !isQueueA;
|
|
@@ -1473,6 +1482,66 @@ export function createRegistry(config) {
|
|
|
1473
1482
|
}
|
|
1474
1483
|
}
|
|
1475
1484
|
|
|
1485
|
+
/**
|
|
1486
|
+
* Create a DISPOSABLE reactive scope: an owner that ADOPTS the effects and
|
|
1487
|
+
* computeds created inside `fn`, so a single returned `dispose` tears the
|
|
1488
|
+
* whole subtree down at once. Where `createRoot` only DETACHES (leaving the
|
|
1489
|
+
* caller to dispose each created node by hand -- "there is no owner to do it
|
|
1490
|
+
* automatically"), `createScope` hands back one disposer that cascade-disposes
|
|
1491
|
+
* everything `fn` built. This is the lifecycle primitive a keyed list / scene
|
|
1492
|
+
* reconciler needs for per-item scopes of unknown internal shape.
|
|
1493
|
+
*
|
|
1494
|
+
* `fn` receives `dispose` and runs ONCE in a detached, untracked context: no
|
|
1495
|
+
* ownership and no dependency leak from `fn`'s direct body into the enclosing
|
|
1496
|
+
* scope, and the scope owner itself never re-runs. Put reactive bindings in
|
|
1497
|
+
* inner effect / computed bodies inside `fn` -- those establish their own
|
|
1498
|
+
* tracking scopes AND are owned by this scope, so they update normally and are
|
|
1499
|
+
* cascade-disposed on `dispose()`. Reads in `fn`'s direct body are untracked.
|
|
1500
|
+
* Returns whatever `fn` returns.
|
|
1501
|
+
*
|
|
1502
|
+
* Plain signals created directly in `fn` are NOT adopted -- the engine never
|
|
1503
|
+
* owner-adopts signals (the lazy-alloc rule, 1.2.0) -- so dispose those
|
|
1504
|
+
* explicitly (the creator holds the handle) or let them fall out of reference.
|
|
1505
|
+
* Computeds and effects ARE adopted and cascade.
|
|
1506
|
+
*
|
|
1507
|
+
* Implementation: the scope owner is backed by a never-re-running effect node,
|
|
1508
|
+
* so it counts as one effect in stats() and its disposer is the same
|
|
1509
|
+
* gen-guarded handle effect() returns -- ABA-safety and introspection match
|
|
1510
|
+
* effects exactly. The API (`fn => dispose`) is the stable contract; a future
|
|
1511
|
+
* engine may swap in a lighter pure-owner node transparently.
|
|
1512
|
+
*
|
|
1513
|
+
* @template T
|
|
1514
|
+
* @param {(dispose: () => void) => T} fn
|
|
1515
|
+
* @returns {T}
|
|
1516
|
+
*/
|
|
1517
|
+
function createScope(fn) {
|
|
1518
|
+
let stop;
|
|
1519
|
+
let result;
|
|
1520
|
+
// Forward-referenced disposer: `stop` is assigned only after effect()
|
|
1521
|
+
// returns, but `fn` runs synchronously DURING effect(). Callers stash this
|
|
1522
|
+
// and invoke it later, by which point `stop` is set. (Disposing the scope
|
|
1523
|
+
// synchronously from inside `fn` is a no-op -- not a supported pattern.)
|
|
1524
|
+
const dispose = function dispose() { if (stop !== undefined) stop(); };
|
|
1525
|
+
// createRoot detaches owner+observer+tracking; inside it effect() creates a
|
|
1526
|
+
// ROOT owner effect (unowned -> survives the enclosing scope's re-runs).
|
|
1527
|
+
// untrack keeps `fn`'s direct reads from handing the owner any dependency,
|
|
1528
|
+
// so the owner runs exactly once; `fn`'s inner effects/computeds are owned
|
|
1529
|
+
// by it and cascade on dispose.
|
|
1530
|
+
createRoot(function () {
|
|
1531
|
+
stop = effect(function scopeOwner() {
|
|
1532
|
+
untrack(function () { result = fn(dispose); });
|
|
1533
|
+
});
|
|
1534
|
+
});
|
|
1535
|
+
// Stamp the wrapper so describe / nodeId / forEachOwned resolve it to the
|
|
1536
|
+
// owner effect, matching the first-class-handle contract effects gained in
|
|
1537
|
+
// 1.2.1. (`stop` carries the symbols once effect() has returned.)
|
|
1538
|
+
if (stop !== undefined && stop[NODE_PTR] !== undefined) {
|
|
1539
|
+
dispose[NODE_PTR] = stop[NODE_PTR];
|
|
1540
|
+
dispose[NODE_GEN] = stop[NODE_GEN];
|
|
1541
|
+
}
|
|
1542
|
+
return result;
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1476
1545
|
/**
|
|
1477
1546
|
* Register a function to run when the enclosing effect/computed re-runs or
|
|
1478
1547
|
* is disposed. Cascade order on disposal is inside-out: an effect's owned
|
|
@@ -1521,7 +1590,10 @@ export function createRegistry(config) {
|
|
|
1521
1590
|
// 1 - poolGrowths*initialCap/totalAllocations; avgLifetime ~ totalDisposals/rate.
|
|
1522
1591
|
totalAllocations: statTotalAllocations,
|
|
1523
1592
|
totalDisposals: statTotalDisposals,
|
|
1524
|
-
poolGrowths: statPoolGrowths
|
|
1593
|
+
poolGrowths: statPoolGrowths,
|
|
1594
|
+
// 1.6: flush-pass counter; advances only while a mutation-hook listener is
|
|
1595
|
+
// attached (frozen + zero-cost otherwise). Feeds devtools watchAllocations.
|
|
1596
|
+
flushPasses: statFlushPasses
|
|
1525
1597
|
};
|
|
1526
1598
|
}
|
|
1527
1599
|
|
|
@@ -1605,6 +1677,7 @@ export function createRegistry(config) {
|
|
|
1605
1677
|
statTotalAllocations = 0;
|
|
1606
1678
|
statTotalDisposals = 0;
|
|
1607
1679
|
statPoolGrowths = 0;
|
|
1680
|
+
statFlushPasses = 0;
|
|
1608
1681
|
|
|
1609
1682
|
for (let i = 0; i < flushErrorCount; i++) flushErrorBuffer[i] = null;
|
|
1610
1683
|
flushErrorCount = 0;
|
|
@@ -1697,7 +1770,7 @@ export function createRegistry(config) {
|
|
|
1697
1770
|
while (l !== null) { const nx = l.nextDep; fn(describeNode(l.source)); l = nx; }
|
|
1698
1771
|
}
|
|
1699
1772
|
|
|
1700
|
-
return {signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
|
|
1773
|
+
return {signal, computed, effect, signalBox, computedBox, dispose, batch, untrack, createRoot, createScope, onCleanup, stats, destroy, isTracking, hasObservers, observeObservers, forEachObserver, forEachSource, forEachOwned, ownerOf, nodeId, describe, onGraphMutation};
|
|
1701
1774
|
}
|
|
1702
1775
|
|
|
1703
1776
|
// -----------------------------------------------------------------
|
|
@@ -1745,6 +1818,10 @@ export function createRoot(fn) {
|
|
|
1745
1818
|
return defaultRegistry.createRoot(fn);
|
|
1746
1819
|
}
|
|
1747
1820
|
|
|
1821
|
+
export function createScope(fn) {
|
|
1822
|
+
return defaultRegistry.createScope(fn);
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1748
1825
|
/**
|
|
1749
1826
|
* True iff a read RIGHT NOW would record a dependency on the default registry.
|
|
1750
1827
|
* See {@link createRegistry} for the per-registry version.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zakkster/lite-signal",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0-preview.0",
|
|
4
4
|
"description": "Zero-GC reactive graph. Monomorphic object pool, versioned push-pull propagation, 32-bit modular versioning. Built for hot paths and long-running processes.",
|
|
5
5
|
"author": "Zahary Shinikchiev <shinikchiev@yahoo.com>",
|
|
6
6
|
"license": "MIT",
|
package/llms.txt
DELETED
|
@@ -1,619 +0,0 @@
|
|
|
1
|
-
# @zakkster/lite-signal
|
|
2
|
-
|
|
3
|
-
> Zero-GC reactive graph library. Object-pooled nodes and links, versioned
|
|
4
|
-
> push-pull propagation, 32-bit modular epoch counters. Synchronous flush, no
|
|
5
|
-
> microtask scheduler, no allocations in hot path after warm-up. ESM-only.
|
|
6
|
-
> ~3.2 KB min+gz, zero dependencies, MIT licensed.
|
|
7
|
-
|
|
8
|
-
The library exposes a small reactive primitives API (signal, computed, effect,
|
|
9
|
-
batch, untrack, onCleanup) backed by pre-allocated pools. Built for animation
|
|
10
|
-
loops, Twitch Extensions, game HUDs, and other contexts where GC pauses break
|
|
11
|
-
the frame budget. Effects flush synchronously in the same call stack as the
|
|
12
|
-
triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
13
|
-
|
|
14
|
-
## Core concepts
|
|
15
|
-
|
|
16
|
-
- **Signal**: root reactive cell. `signal(initial, { equals? })` returns a function. Call it to read (tracked), use `.peek()` to read without tracking, `.set(v)` to notify downstream, `.update(fn)` for read-modify-write, `.subscribe(fn)` for an effect-backed listener.
|
|
17
|
-
- **Computed**: lazy memoized derivation. `computed(fn, { equals? })`. Cache hits return in O(deps) (version comparison only). Cache misses re-run the body and refresh `evalVersion`. Errors are cached via `FLAG_HAS_ERROR` and re-thrown on every read until a dep changes.
|
|
18
|
-
- **Effect**: side-effect runner. `effect(fn, { scheduler? })`. Runs immediately on creation, then on any tracked dep change. Returns a dispose function. Optional scheduler defers execution (e.g., to rAF, microtask, custom frame loop).
|
|
19
|
-
- **Box (1.5.0)**: non-callable, allocation-light variants. `signalBox(initial, { equals? })` returns `{ get, set, peek, update, subscribe }`; `computedBox(fn, { equals? })` returns `{ get, peek, subscribe }` (no set/update -- derived). Same `ReactiveNode` and zero-GC read/write path as the callable forms, full interop in one graph (a callable can read `box.get()` and vice versa). Construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle, not a closure). Built on a shared prototype from the start -- never `setPrototypeOf` (which would deopt the method-call ICs to megamorphic). Exported as registry methods and top-level helpers.
|
|
20
|
-
- **createRoot (1.5.0)**: `createRoot(fn)` runs `fn` in a detached ownership scope and returns `fn`'s value. Effects/computeds created directly in `fn` are NOT adopted by the enclosing owner, so they survive its re-runs/disposal (the caller owns their lifecycle). Both ownership and tracking are detached for `fn`'s direct body; inner effect/computed bodies still establish their own scopes. The escape hatch for lazily spawning a long-lived node from inside a consumer effect (e.g. `lite-query`'s query-watcher) -- without it, the consumer owns the watcher and cascade-disposes it on its next re-run. Mirrors Solid's `createRoot`. The re-attach companion `runWithOwner` is named in the engine as the intended second half and is not yet shipped.
|
|
21
|
-
- **dispose(api)**: universal disposal. Accepts a signal, computed, or effect dispose handle; idempotent; cross-registry calls are silent no-ops (per-registry `Symbol("node_ptr")` keys the node-identity slot on the returned API function, foreign signals fail the lookup and fall through). Passing an unrelated value is also safe; passing an arbitrary function invokes it (effect-handle contract).
|
|
22
|
-
- **Batch**: `batch(fn)` defers effect flush until the outermost batch closes. Nestable.
|
|
23
|
-
- **Untrack**: `untrack(fn)` reads without subscribing.
|
|
24
|
-
- **isTracking**: `isTracking()` returns true iff a read right now would record a dependency on this registry (for wrappers that lazily allocate signals).
|
|
25
|
-
- **onCleanup**: registers teardown for the current computation; fires before each re-run and once on dispose. Works in effects and computeds.
|
|
26
|
-
- **Observer-lifecycle introspection** (1.1.4; top-level + per-registry): `hasObservers(handle)` returns true iff a signal/computed has >=1 live observer right now (O(1); a `peek` does not count). `observeObservers(handle, { onConnect?, onDisconnect? })` fires on the 0->1 and 1->0 observer transitions (after registration; transition-only) and returns an idempotent unobserve -- the auto-pause hook for tickers (lite-time/lite-raf start a source only while it's watched). `forEachObserver(handle, fn)` / `forEachSource(handle, fn)` walk the live graph in either direction, passing a `{ kind, value }` descriptor (`kind` is `"signal" | "computed" | "effect"`) -- for inspection (lite-devtools). The surface is gated by an internal counter: zero steady-state cost when nothing is observed. `hasObservers`/`forEach*` no-op on a non-handle; `observeObservers` throws `TypeError`. **Node identity (1.1.5):** `nodeId(handle)` returns the node's stable per-allocation id, `describe(handle)` returns the handle's own `{ id, kind, value }` descriptor, and `forEach*` descriptors now carry `id` too; a descriptor is **re-walkable** (pass it back into `forEachObserver`/`forEachSource`) -- the recursion primitive lite-devtools uses to walk the full DAG. **Owner-tree introspection (1.2.1):** `forEachOwned(handle, fn)` walks a node's owned children (lifetime-binding edges from the 1.2 owner tree -- invisible through dep/sub); `ownerOf(handle)` returns the owner's descriptor or `undefined` for top-level / stale handles. **Stale-handle guard (1.2.1):** the entire introspection surface plus `peek()`/`read()`/`set()` is now generation-checked. A handle held across the 1.2 owner-cascade auto-dispose used to resolve `NODE_PTR` ungated and silently report the recycled slot's NEW resident; 1.2.1 surfaces stale handles as `undefined` (or `TypeError`, for `observeObservers`) -- same ABA discipline `dispose()` always had. Descriptors are gen-stamped so the re-walkable contract survives the guard. **Push-based mutation hook (1.2.1):** `onGraphMutation(fn)` registers a single nullable listener invoked synchronously at every mutation point with three integers `(opcode, intA, intB)` -- opcodes `1` node-create / `2` node-dispose / `3` link-add / `4` link-remove / `5` recompute. Zero-cost gate when no listener is registered (one branch-predicted null check); allocation-free dispatch when registered. The connection point for push-based devtools/studio. Contract: observe only -- never throw, never mutate.
|
|
27
|
-
- **Registry**: `createRegistry({ maxNodes, maxLinks, prealloc, onCapacityExceeded, maxFlushPasses })` creates an isolated reactive world with its own pools. Useful for tests, plugins, multi-tenant sandboxes. Top-level helpers use a default registry created at module load. `prealloc` (1.3.0; `"eager"` default | `"lazy"`) chooses up-front vs on-demand pool construction; `onCapacityExceeded` (`"throw"` default | `"grow"`) chooses fail-fast vs chunked-incremental growth bounded by the 16x link ceiling.
|
|
28
|
-
- **CapacityError**: thrown when a fixed-size pool is exhausted under the `"throw"` policy, or when a `"grow"` policy hits the 16× starting-capacity ceiling on links.
|
|
29
|
-
|
|
30
|
-
## Architecture invariants
|
|
31
|
-
|
|
32
|
-
- **Two object pools**: nodes (default 1024) and links (default 4×nodes). Singly-linked via `nextFree`, O(1) allocate/free.
|
|
33
|
-
- **Doubly-linked edge lists**: each link is in both a dep-list (on the target/observer) and a sub-list (on the source/dependency). O(1) unlink during cursor reconciliation.
|
|
34
|
-
- **Cursor reconciliation**: at the start of each computed/effect run, `activeObserverCurrentDep` points at the head of the existing dep list. As the body reads deps, matching links advance the cursor (zero alloc); non-matching links insert before the cursor and the displaced tail is severed at the end of the run.
|
|
35
|
-
- **Iterative mark phase**: `markDownstream` uses a pre-allocated `markStack` array for DFS -- no recursion, no call stack growth on wide fan-out.
|
|
36
|
-
- **Recursive computed pull**: `pullComputed` is call-stack recursive; deep chains beyond ~10,000 nodes will throw `RangeError`. Effects don't have this limit.
|
|
37
|
-
- **Double-buffered effect queue**: `effectQueueA` / `effectQueueB` alternate each flush pass -- effects *scheduled by* the current pass (cross-effect cascades) drain in the next pass. A **self-write** (an effect writing a signal it reads) is the exception: `markDownstream`'s `FLAG_COMPUTING` guard does **not** re-queue the writing effect, so a self-cycle runs exactly once -- while the write still propagates to the signal's other observers, and the effect stays responsive to later *external* writes (its `evalVersion` is bumped in the `executeEffect` finally). Mutual cross-effect write loops (A->B->A) are not self-cycles and trip `CycleError: flush passes exceeded` via `maxFlushPasses`.
|
|
38
|
-
- **maxFlushPasses ceiling**: default 100. Exceeding this throws `CycleError`. Prevents runaway effect loops.
|
|
39
|
-
- **32-bit modular versioning**: `globalVersion` and `node.version` are `(value + 1) | 0`, wrapping signed. Comparison via `((dep.version - evalVer) | 0) > 0` is wrap-safe and works in modular distance, not raw integer ordering. The engine never overflows.
|
|
40
|
-
- **Generation counter**: each node has a `gen` field incremented on dispose and destroy. Scheduler trampolines capture the current gen and no-op if it changes -- prevents stale callbacks from re-firing after dispose.
|
|
41
|
-
- **destroy()**: resets all pools, rebuilds free lists, bumps every node's gen, resets globalVersion to 1. Safe to call mid-flight (in-flight effects finish their current invocation, scheduled ones become no-ops).
|
|
42
|
-
|
|
43
|
-
## Performance characteristics
|
|
44
|
-
|
|
45
|
-
- `signal.set(v)` -- O(downstream observers), zero alloc after warm-up.
|
|
46
|
-
- `signal.peek()` -- O(1), zero alloc.
|
|
47
|
-
- `computed()` cache hit -- O(deps), zero alloc.
|
|
48
|
-
- `computed()` cache miss -- O(deps + body), zero alloc if dep structure is stable.
|
|
49
|
-
- Effect re-run with stable dep order -- zero alloc.
|
|
50
|
-
- Stable read order: O(1) per dep via cursor reuse.
|
|
51
|
-
- Chaotic/randomized read order: 1.1.4 added version-stamped per-source reconciliation plus a `markEpoch` clean-read short-circuit on the pull, so the prior O(N)-per-dep degradation no longer dominates high-fan-in batched read-after-write -- the `dyn: large web app` and `dyn: wide dense` shapes that were the v1.1.x weakness are now the fastest of the five benchmarked frameworks (see resultsReactive.txt). Correctness verified by `retracking.difftest.mjs` (20,000 direct + 10,000 batched writes, 0 disagreements).
|
|
52
|
-
|
|
53
|
-
## Version notes
|
|
54
|
-
|
|
55
|
-
- **1.5.0-alpha** (current): the **API-surface minor**. Two non-callable,
|
|
56
|
-
allocation-light primitives -- `signalBox(initial, opts?)` returning
|
|
57
|
-
`{ get, set, peek, update, subscribe }` and `computedBox(fn, opts?)` returning
|
|
58
|
-
`{ get, peek, subscribe }` -- land alongside the callable `signal` / `computed`,
|
|
59
|
-
plus **`createRoot(fn)`** as the ownership escape hatch. **The callable API, hot
|
|
60
|
-
paths, and `stats()` shape (11 keys) are unchanged from 1.4.0**; this is an
|
|
61
|
-
additive surface, not a second engine. Boxes wrap the same `ReactiveNode` and
|
|
62
|
-
interoperate freely with callables in one graph (verified both directions);
|
|
63
|
-
ownership, batching, glitch-freedom, and introspection apply uniformly, and box
|
|
64
|
-
nodes count in `stats().signals` / `computeds` exactly as callable nodes. Box
|
|
65
|
-
construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle
|
|
66
|
-
with two own props added in fixed order -- never `setPrototypeOf`, which would
|
|
67
|
-
transition the object to dictionary mode and blow the method-call ICs to
|
|
68
|
-
megamorphic); the read/write hot path stays zero-GC (200k box writes through a
|
|
69
|
-
256-wide graph: 0 heap growth, 0 pool growths). `createRoot` runs `fn` with
|
|
70
|
-
`currentOwner` and `currentObserver` (and the tracking flag) nulled, so
|
|
71
|
-
effects/computeds created directly in `fn` are not adopted by the enclosing owner
|
|
72
|
-
and survive its re-runs/disposal -- the sanctioned opt-out for lazily spawning a
|
|
73
|
-
long-lived watcher from inside a consumer effect (`lite-query`'s pattern);
|
|
74
|
-
unwrapped, the consumer owns the watcher and cascade-disposes it. Inner
|
|
75
|
-
effect/computed bodies still establish their own scopes; `createRoot` returns
|
|
76
|
-
whatever `fn` returns. The owner/observer split (1.2.0) made `currentOwner` and
|
|
77
|
-
`currentObserver` distinct precisely so ownership could be detached without
|
|
78
|
-
affecting tracking; `createRoot` is the first of the two named primitives
|
|
79
|
-
(`runWithOwner`, the re-attach half, is not yet shipped). The `24-signalbox`
|
|
80
|
-
suite (staged `{skip:true}` since 1.3.0) now runs and passes. **Tests:** 439
|
|
81
|
-
total, 438 pass, 0 fail, **1 skip** (only the architecturally-N/A SSR case in
|
|
82
|
-
`17-reactivity`; the 9 signalBox tests are now active, +6 `createRoot` tests in
|
|
83
|
-
`test/27-create-root_test.mjs`, +3 box-coverage tests). **Coverage:** `Signal.js`
|
|
84
|
-
100% statements / 97.35% branches / 100% functions / 100% lines; `Watch.js` 100%.
|
|
85
|
-
Drop-in over 1.4.0.
|
|
86
|
-
|
|
87
|
-
- **1.4.0-beta** (drop-in over 1.3.0): the **observability minor**. `stats()` gains three
|
|
88
|
-
cumulative lifecycle counters -- `totalAllocations`, `totalDisposals`,
|
|
89
|
-
`poolGrowths` -- the surface reserved for 1.4.0 in the 1.2.x/1.3.0 notes, now
|
|
90
|
-
delivered. **The hot paths and public callable API are byte-identical to 1.3.0**;
|
|
91
|
-
the counters bump on existing acquire / dispose / pool-grow edges that already
|
|
92
|
-
ran, never on the steady-state read path, so throughput and zero-GC are
|
|
93
|
-
unchanged. The 1.3.0 eager pool default carries forward (`prealloc: "eager"`).
|
|
94
|
-
**`stats()` now returns 11 keys** (the 8 live gauges plus the 3 counters).
|
|
95
|
-
`totalAllocations` counts every node acquired (pool pop OR fresh build);
|
|
96
|
-
`totalDisposals` counts every node returned to the pool, with
|
|
97
|
-
`totalAllocations - totalDisposals === activeNodes` in a quiescent registry;
|
|
98
|
-
`poolGrowths` counts pool-growth chunks (node OR link crossing its ledger) --
|
|
99
|
-
nonzero after warm-up means the initial pool was undersized, 0 means an eager pool
|
|
100
|
-
was sized right. All three are monotonic and reset only by `destroy()`. They are
|
|
101
|
-
exact, not sampled: a consumer sampling `stats()` over time derives allocation
|
|
102
|
-
rate (delta totalAllocations / delta t), pool-reuse ratio
|
|
103
|
-
(1 - poolGrowths*initialCap/totalAllocations), and churn without the engine
|
|
104
|
-
computing rates -- the series lite-devtools 1.2 / lite-studio 1.2 plot. **Tests:**
|
|
105
|
-
430 total, 420 pass, 0 fail, 10 skip (6 new counter tests in `test/03-pool_test.mjs`
|
|
106
|
-
cover the 11-key shape, the live invariant, poolGrowths firing on growth vs staying
|
|
107
|
-
0 on a sized eager pool, and destroy() reset). **Coverage:** `Signal.js` 100%
|
|
108
|
-
statements / 98.26% branches / 100% functions / 100% lines; `Watch.js` 100%.
|
|
109
|
-
Drop-in over 1.3.0.
|
|
110
|
-
|
|
111
|
-
- **1.3.0** (drop-in over 1.2.2): the **pool minor**. Node and link pools become
|
|
112
|
-
growable and incrementally populated; the propagation mark phase moves to an
|
|
113
|
-
intrusive linked-list stack (a `nextMark` field); a small registry config surface
|
|
114
|
-
(`prealloc`, `onCapacityExceeded`, `maxFlushPasses`) is exposed. The hot paths and
|
|
115
|
-
public callable API are byte-identical to 1.2.2 -- everything here is
|
|
116
|
-
pool mechanics, construction-time behavior, and new opt-in config. Steady-state
|
|
117
|
-
zero-GC is unchanged: after warm-up the pools recycle exactly as before.
|
|
118
|
-
**`prealloc` (`"eager"` default | `"lazy"`):** `"eager"` constructs the full
|
|
119
|
-
`maxNodes` / `maxLinks` pools up front -- deterministic latency, zero allocation
|
|
120
|
-
inside any subsequent hot path (the 16ms / 120fps render-frame contract), at the
|
|
121
|
-
cost of a larger resident heap every major GC traces. `"lazy"` treats the
|
|
122
|
-
capacities as ledgers, constructs nodes/links on first demand, recycles through
|
|
123
|
-
the free lists thereafter -- smaller heap, faster cold start, lighter GC marking,
|
|
124
|
-
identical zero-GC steady state after warm-up. **Growable pools
|
|
125
|
-
(`onCapacityExceeded: "grow"`):** pools extend past their initial capacity via
|
|
126
|
-
chunked refill -- contiguous runs of up to 1024 links / 256 nodes per free-list
|
|
127
|
-
miss, not a single doubling burst, so any one growth pause stays bounded
|
|
128
|
-
(~chunk x ~0.5us). The growth path no longer length-extends the effect queues
|
|
129
|
-
or mark stack (which permanently converted them PACKED->HOLEY). Link growth is
|
|
130
|
-
bounded by the hard `maxLinks * 16` ceiling; `"throw"` (default, now backed by a
|
|
131
|
-
named `CapacityError`) preserves the 1.2.x fail-fast behavior.
|
|
132
|
-
**`maxFlushPasses`** (default 100) is now a public config -- the cycle-protection
|
|
133
|
-
ceiling that throws an `Error` prefixed `"CycleError:"`. **Intrusive mark stack:**
|
|
134
|
-
`markDownstream` walks an iterative DFS backed by a `nextMark` field on each node
|
|
135
|
-
instead of an external `markStack` array; behaviorally identical (same nodes, same
|
|
136
|
-
order, same glitch-free guarantee), and the write lands in the cache line already
|
|
137
|
-
hot from reading `markEpoch`. `nextMark` is the only node-shape change in 1.3.0.
|
|
138
|
-
**`stats()` shape unchanged** (8 keys: `signals`, `computeds`, `effects`,
|
|
139
|
-
`activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`,
|
|
140
|
-
`linkPoolCapacity`); the capacity keys are ledgers under `"lazy"`. Cumulative
|
|
141
|
-
allocation counters (`totalAllocations` / `totalDisposals` / `poolGrowths`) remain
|
|
142
|
-
reserved for 1.4.0 and are still absent. **Tests:** 424 total, 414 pass, 0 fail,
|
|
143
|
-
10 skip (the 10 skips are 9 signalBox-staged-for-1.5.0 in
|
|
144
|
-
`test/24-signalbox_test.mjs` plus 1 architecturally-N/A SSR case in
|
|
145
|
-
`17-reactivity`); 4 new pool tests in `test/03-pool_test.mjs` cover the lazy
|
|
146
|
-
on-demand / never-allocated-destroy / grow-extends-ledger / link-ceiling paths.
|
|
147
|
-
**Coverage** (c8@11, Node 22): `Signal.js` 100% statements / 98.26% branches /
|
|
148
|
-
100% functions / 100% lines; `Watch.js` 100% across all four. Behavior-
|
|
149
|
-
preservation difftest: 20,000 direct + 10,000 batched writes vs the published
|
|
150
|
-
1.1.5 reference, 0 disagreements -- pool growth, chunked refill, and the intrusive
|
|
151
|
-
mark stack do not alter observable propagation. Drop-in over 1.2.2.
|
|
152
|
-
|
|
153
|
-
- **1.2.2**: `createNode` clean-free-list invariant audit. Removes
|
|
154
|
-
ten redundant field-writes that defended against a state the engine cannot
|
|
155
|
-
produce on a clean free-list: seven graph/batch fields (`headDep`, `tailDep`,
|
|
156
|
-
`headSub`, `tailSub`, `revertEpoch`, `preBatchValue`, `preBatchVersion`) and
|
|
157
|
-
three owner-tree fields (the non-adoption `firstOwned`, the adoption-path
|
|
158
|
-
`prevOwned`, and the else-branch `owner`). Both teardown paths
|
|
159
|
-
(`disposeNode` direct, `runCleanup` cascade) already null these fields, and
|
|
160
|
-
the `ReactiveNode` constructor initializes them to the same values on the
|
|
161
|
-
fresh-pool-growth path -- so the redundant writes in `createNode` were
|
|
162
|
-
defense against a state that cannot exist. **No public surface change, no
|
|
163
|
-
semantic change.** New `test/26-free-list-invariant_test.mjs` (3 invariant
|
|
164
|
-
tests + 1 targeted coverage test for the swallow-on-self-dispose-then-throw
|
|
165
|
-
branch in `pullComputed`) asserts the invariant directly by inspecting
|
|
166
|
-
freshly-allocated nodes via the documented `describe()` -> `NODE_PTR`
|
|
167
|
-
introspection protocol; new `test/25-devtools-real-boot_test.mjs` (10 tests)
|
|
168
|
-
boots the actual `Devtools.js` against the 1.2.2 engine and pins the 1.2.x
|
|
169
|
-
introspection contract for downstream tooling, including the 8-key
|
|
170
|
-
`stats()` shape (`signals`, `computeds`, `effects`, `activeNodes`,
|
|
171
|
-
`activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity`).
|
|
172
|
-
408 tests total: 398 pass, 10 skip, 0 fail (the 10 skips are 9
|
|
173
|
-
signalBox-staged-for-1.5.0 in `test/24-signalbox_test.mjs` plus 1
|
|
174
|
-
architecturally-N/A SSR case in `17-reactivity`). Coverage on `Signal.js`:
|
|
175
|
-
100% statements / 98.43% branches / 100% functions / 100% lines; `Watch.js`
|
|
176
|
-
100% across all four (c8@11, Node 22) -- a branch-coverage gain over the
|
|
177
|
-
1.2.1 baseline (98.07%), from the targeted swallow-on-self-dispose-then-throw
|
|
178
|
-
test in `pullComputed`.
|
|
179
|
-
Version lineage:
|
|
180
|
-
this is the engine previously labeled `1.2.3` in dev -- renumbered to
|
|
181
|
-
`1.2.2` because the deletion is small, isolated, and intentionally
|
|
182
|
-
non-behavioral. Drop-in over 1.2.1. **Bench position** (third-party
|
|
183
|
-
[js-reactivity-benchmark](https://github.com/volynetstyle/js-reactivity-benchmark),
|
|
184
|
-
15 frameworks, 47 tests): #4 by geomean (75.5) at 1.77x behind alien-signals
|
|
185
|
-
(1.00x), reflex (1.15x), @reactively (1.39x); now ahead of 5th-place Preact
|
|
186
|
-
Signals (79.2, lite ~5% ahead -- the gap widened from 1.2.x). The only
|
|
187
|
-
object-pooled zero-GC engine in the field. Ahead of @vue/reactivity (1.5x),
|
|
188
|
-
Signia (1.7x), MobX (2.3x), @solidjs/signals (2.7x), SolidJS (4.2x). Top-3 on
|
|
189
|
-
21/47 tests; outright winner on `manyEffectsFromOneSource`,
|
|
190
|
-
`manySourcesIntoOneComputedEffect`, and
|
|
191
|
-
`manySourcesIntoOneComputedEffectWithDirect` (and edges the leader alien on a
|
|
192
|
-
fourth, the 1-source linear-chain pull). (The suite measures reactivity
|
|
193
|
-
libraries -- Vue reactivity core, MobX, Solid, Preact Signals -- not full UI
|
|
194
|
-
frameworks like React/Angular.)
|
|
195
|
-
In the community reactive suite (median-of-10), fastest of 5 frameworks
|
|
196
|
-
on the entire `dyn:*` family (the realistic large-DOM-framework shapes)
|
|
197
|
-
and the entire `S: updateComputations*` family. Behind on the
|
|
198
|
-
construction-cost path (`S: createComputations*`, `cellx`, `createDataSignals`).
|
|
199
|
-
|
|
200
|
-
- **1.2.1**: correctness-and-introspection patch. Drop-in over 1.2.0;
|
|
201
|
-
no public surface removed. **Stale-handle introspection (ABA fix):** the v1.2.0
|
|
202
|
-
owner tree made the engine recycle pool slots autonomously on owner re-run, so
|
|
203
|
-
holding a stale handle stopped being a user error and became a routine
|
|
204
|
-
occurrence. Pre-1.2.1, `nodeId`/`describe`/`forEachObserver`/`forEachSource`/
|
|
205
|
-
`hasObservers`/`observeObservers`/`peek()` would resolve `NODE_PTR` ungated
|
|
206
|
-
and happily report the recycled slot's NEW resident through an old handle
|
|
207
|
-
(wrong id, wrong value, wrong edges). All six entry points + `peek()` + `read()`
|
|
208
|
-
+ `set()` now resolve through a generation check (the same ABA discipline
|
|
209
|
-
`dispose()` already had); stale handles read as `undefined` (or throw the
|
|
210
|
-
documented `TypeError`, for `observeObservers`). `describe()` descriptors are
|
|
211
|
-
gen-stamped alongside `NODE_PTR`, so the "descriptors are re-walkable handles"
|
|
212
|
-
contract survives the guard: a fresh descriptor walks, one held across a
|
|
213
|
-
recycle correctly goes stale. **Added -- `onGraphMutation(fn)`:** registry-level
|
|
214
|
-
(and top-level) graph-mutation hook for push-based tooling. Single nullable
|
|
215
|
-
listener; every fire point is `if (mutationHook !== null) mutationHook(opcode, intA, intB)`
|
|
216
|
-
-- zero-cost gate when absent, allocation-free dispatch when present. Opcodes:
|
|
217
|
-
`1` node-create `(id, flags)`, `2` node-dispose `(id, flags)` (cascades
|
|
218
|
-
included), `3` link-add `(source.id, target.id)`, `4` link-remove `(source.id, target.id)`,
|
|
219
|
-
`5` recompute `(id, 0)` before each effect re-run / computed re-eval.
|
|
220
|
-
Contract: observe only -- never throw, never mutate the graph from inside.
|
|
221
|
-
This is the connection point lite-devtools 1.1 / lite-studio 1.1 use to go
|
|
222
|
-
push-based. **Added -- `forEachOwned(handle, fn)` / `ownerOf(handle)`:** owner-
|
|
223
|
-
tree introspection. `forEachOwned` iterates a node's owned children as
|
|
224
|
-
re-walkable descriptors; `ownerOf` returns the owner's descriptor or
|
|
225
|
-
`undefined` (top-level or stale). Same descriptor conventions as
|
|
226
|
-
`forEachObserver`/`forEachSource`; garbage input is a no-op/`undefined`.
|
|
227
|
-
Also: `Object.is` hoisted to a module-level const (one IC entry instead of
|
|
228
|
-
per-call lookup in `signal()`/`computed()`). 404 tests, **100% line / 98.07%
|
|
229
|
-
branch coverage** on `Signal.js` + `Watch.js`. New
|
|
230
|
-
`test/21-perf-pins.test.mjs` (6 tests -- construction-shape + ABA-guard pins),
|
|
231
|
-
`test/22-mutation-hook.test.mjs` (12 tests -- `onGraphMutation` registration,
|
|
232
|
-
the 5 opcodes, payload shape, registry isolation), and
|
|
233
|
-
`test/23-owner-introspection.test.mjs` (14 tests -- `forEachOwned`, `ownerOf`,
|
|
234
|
-
and gen-guarded behaviour across the introspection surface). Differential
|
|
235
|
-
fuzz vs the published 1.1.5: 0 disagreements over 30,000 writes.
|
|
236
|
-
|
|
237
|
-
- **1.2.0**: structural refactor (three named layers: graph topology /
|
|
238
|
-
ownership / propagation) plus four additive features built on top. Drop-in over
|
|
239
|
-
1.1.5; no public surface removed. **Owner tree:** an effect or computed that
|
|
240
|
-
creates nested observers (effect/computed) now owns them -- when the owner
|
|
241
|
-
re-runs or is disposed, the engine cascade-disposes those observers before
|
|
242
|
-
the new run. Plain signals are deliberately NOT owner-adopted so lazy-
|
|
243
|
-
allocation wrappers (lite-store keys, lite-form fields) continue to survive
|
|
244
|
-
re-runs of the computed that allocated them. **Pre-batch revert:** inside a
|
|
245
|
-
`batch(...)`, set X then set X back (under the signal's `equals`) reverts the
|
|
246
|
-
version bump -- downstream effects/computeds do not fire. **AggregateError on
|
|
247
|
-
multi-throw:** two or more effects throwing in the same flush pass aggregate to
|
|
248
|
-
`AggregateError` at the trigger; single-throw is unchanged. **Scheduler thunk
|
|
249
|
-
caching:** the scheduler closure is cached on the node and gen-bound, so async
|
|
250
|
-
schedules that fire post-dispose against a recycled slot are guaranteed no-ops
|
|
251
|
-
(ABA safe). Internal split: `currentObserver` and `currentOwner` are now
|
|
252
|
-
distinct pointers (today they move together, no behavioural change). **Perf:**
|
|
253
|
-
shared `peek` (one closure per registry instead of per primitive) shaves
|
|
254
|
-
10-14% off signal/computed creation on the `S:create*` micros, no hot-path or
|
|
255
|
-
behavioural change. 363 tests, 100% line / 98.62% branch coverage on
|
|
256
|
-
`Signal.js` + `Watch.js`. Differential fuzz vs the published 1.1.5: 0
|
|
257
|
-
disagreements over 30,000 writes. New `test/19-v12-additions.test.mjs`
|
|
258
|
-
(24 tests) and `test/20-axis-stress.test.mjs` (23 tests -- eight orthogonal
|
|
259
|
-
engine-invariant axes plus permanent conformance pins). **Conformance fixes
|
|
260
|
-
in 1.2.0**: #141 (dispose during execution then continue: no re-run), and
|
|
261
|
-
#238 / #241 / #243 (cleanup ordering on cascade: inner-before-outer,
|
|
262
|
-
deepest-first, and the inner-only-re-run regression). #141 was a latent
|
|
263
|
-
crash present in 1.1.5 too; the v1.2 owner tree exercised it more
|
|
264
|
-
aggressively. Fix is two-fold -- nullify the tracking cursor in `disposeNode`
|
|
265
|
-
when the disposed node is the active observer (plus a `gen`-snapshot guard
|
|
266
|
-
in `executeEffect`/`pullComputed`); and swap `runCleanup` to cascade
|
|
267
|
-
children first, then own.
|
|
268
|
-
|
|
269
|
-
- **1.1.5**: additive release in service of `@zakkster/lite-devtools` -- stable
|
|
270
|
-
node identity on the introspection surface. `nodeId(handle)` -> the node's stable
|
|
271
|
-
per-allocation id (the dedupe key for graph walks); `describe(handle)` -> the handle's
|
|
272
|
-
own `{ id, kind, value }` descriptor, **re-walkable** (pass it back into
|
|
273
|
-
`forEachObserver`/`forEachSource` to walk the full DAG); `forEach*` descriptors now carry
|
|
274
|
-
`id`. One SMI write at allocation, node shape kept monomorphic -- **zero steady-state
|
|
275
|
-
cost**. Drop-in over 1.1.4, no breaking changes. New `test/18-identity_test.mjs` (5 tests); plus `14-lifecycle-teardown`, `16-alien-parity`, and the `17-reactivity` behavioral suite.
|
|
276
|
-
|
|
277
|
-
- **1.1.4**: combined release -- a retracking rewrite plus an observer-lifecycle
|
|
278
|
-
introspection surface. Drop-in over 1.1.3. **Retracking:** version-stamped O(1)
|
|
279
|
-
reconciliation + a `markEpoch` clean-read short-circuit replace the cursor strategy's
|
|
280
|
-
O(N)-per-dep degradation under chaotic high-fan-in batched read-after-write; stable read
|
|
281
|
-
order is unchanged (still O(1), still zero-alloc). The two documented v1.1.x losses flipped
|
|
282
|
-
to wins and are now fastest of five frameworks -- `dyn: large web app` 6194ms->571ms, `dyn:
|
|
283
|
-
wide dense` 5115ms->912ms (verified by `retracking.difftest.mjs`: 20k direct + 10k batched, 0
|
|
284
|
-
disagreements; no regressions elsewhere). **Introspection:** `hasObservers`,
|
|
285
|
-
`observeObservers`, `forEachObserver`, `forEachSource` (top-level + per-registry), gated by
|
|
286
|
-
an internal counter so zero steady-state cost when unused. New `test/13-introspection_test.mjs`
|
|
287
|
-
(10 tests). Internally staged as 1.1.4 + 1.1.5; ships as a single 1.1.4.
|
|
288
|
-
|
|
289
|
-
- **1.1.3**: adds `isTracking()` (top-level + per-registry). Returns true iff a
|
|
290
|
-
read right now would record a dependency (`isTrackingDeps && currentObserver !== null`).
|
|
291
|
-
False inside `untrack`, `subscribe` callbacks, `onCleanup` bodies, `watch` /
|
|
292
|
-
`when` callbacks, and outside any observer. ~1-2 ns. For wrapper libraries
|
|
293
|
-
(lite-store, lite-query, lite-form) that allocate reactive primitives lazily
|
|
294
|
-
on property reads. Per-registry: wrappers operating against a non-default
|
|
295
|
-
registry must call THAT registry's `isTracking()`, not the top-level one.
|
|
296
|
-
No behavior or engine changes.
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
- **1.1.2**: hot-path micro-optimizations, no behavior/API change.
|
|
300
|
-
Inlined cursor fast-path in `signal`/`computed` reads (stable-order reads skip
|
|
301
|
-
the `allocateLink` call); zero-allocation creation path (`opts` read defensively
|
|
302
|
-
instead of defaulting to `{}`); single-closure `subscribe`. Owner-tree
|
|
303
|
-
conformance items #209/#210 are wired but skipped pending the v1.2 ownership
|
|
304
|
-
hybrid.
|
|
305
|
-
|
|
306
|
-
## When to use
|
|
307
|
-
|
|
308
|
-
- Animation loops, game HUDs, scoreboards, telemetry overlays.
|
|
309
|
-
- Twitch Extensions (1 MB bundle / 3 s cold start budget).
|
|
310
|
-
- Long-running browser sessions (millions of writes per session).
|
|
311
|
-
- Multi-tenant SDKs where each tenant needs an isolated reactive world.
|
|
312
|
-
- Any context where a GC pause breaks the frame budget.
|
|
313
|
-
|
|
314
|
-
## When NOT to use
|
|
315
|
-
|
|
316
|
-
- Server-side rendering -- no SSR story.
|
|
317
|
-
- Graph *construction* is allocation-heavy (per-node closures): on create-many micro-benchmarks `alien-signals` builds faster. Real apps build once and update forever -- lite-signal leads every dynamic-topology (`dyn:*`) row and trades the lead with alien within a few percent on the sub-60ms `S: updateComputations` micro-rows (noise-dominated). (The former "chaotic read order" caveat was closed in 1.1.4.)
|
|
318
|
-
- If you want time-travel or serialization -- build those on top. (Graph-inspection devtools are now buildable on the 1.1.4 introspection surface; see lite-devtools.)
|
|
319
|
-
|
|
320
|
-
## API summary
|
|
321
|
-
|
|
322
|
-
```ts
|
|
323
|
-
// Default registry helpers
|
|
324
|
-
function signal<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): Signal<T>;
|
|
325
|
-
function computed<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): Computed<T>;
|
|
326
|
-
function effect(fn: () => void, opts?: { scheduler?: (run: () => void) => void }): Dispose;
|
|
327
|
-
function signalBox<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): SignalBox<T>; // 1.5.0
|
|
328
|
-
function computedBox<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): ComputedBox<T>; // 1.5.0
|
|
329
|
-
function createRoot<T>(fn: () => T): T; // 1.5.0 -- detached ownership scope; returns fn's value
|
|
330
|
-
function dispose(api: Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any> | Dispose): void;
|
|
331
|
-
function batch<T>(fn: () => T): T;
|
|
332
|
-
function untrack<T>(fn: () => T): T;
|
|
333
|
-
function isTracking(): boolean;
|
|
334
|
-
function hasObservers(handle: Signal<any> | Computed<any>): boolean;
|
|
335
|
-
function observeObservers(
|
|
336
|
-
handle: Signal<any> | Computed<any>,
|
|
337
|
-
hooks?: { onConnect?: () => void; onDisconnect?: () => void }
|
|
338
|
-
): () => void; // returns idempotent unobserve
|
|
339
|
-
function forEachObserver(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void;
|
|
340
|
-
function forEachSource(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void;
|
|
341
|
-
function forEachOwned(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void; // 1.2.1
|
|
342
|
-
function ownerOf(handle: Signal<any> | Computed<any>): NodeDescriptor | undefined; // 1.2.1
|
|
343
|
-
function nodeId(handle: Signal<any> | Computed<any>): number | undefined; // 1.1.5
|
|
344
|
-
function describe(handle: Signal<any> | Computed<any>): NodeDescriptor | undefined; // 1.1.5
|
|
345
|
-
function onGraphMutation( // 1.2.1
|
|
346
|
-
fn: ((opcode: 1|2|3|4|5, intA: number, intB: number) => void) | null
|
|
347
|
-
): () => void; // unsub restores prior listener
|
|
348
|
-
function onCleanup(fn: () => void): void;
|
|
349
|
-
function stats(): RegistryStats;
|
|
350
|
-
|
|
351
|
-
// Registry construction
|
|
352
|
-
function createRegistry(config?: RegistryConfig): Registry;
|
|
353
|
-
function setDefaultRegistry(r: Registry): void;
|
|
354
|
-
|
|
355
|
-
interface Signal<T> {
|
|
356
|
-
(): T; // tracked read
|
|
357
|
-
peek(): T; // untracked read
|
|
358
|
-
set(value: T): void;
|
|
359
|
-
update(fn: (prev: T) => T): void;
|
|
360
|
-
subscribe(fn: (value: T) => void): Dispose;
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
interface Computed<T> {
|
|
364
|
-
(): T; // tracked read
|
|
365
|
-
peek(): T; // untracked read
|
|
366
|
-
subscribe(fn: (value: T) => void): Dispose;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
interface SignalBox<T> { // 1.5.0 -- non-callable, allocation-light
|
|
370
|
-
get(): T; // tracked read
|
|
371
|
-
set(value: T): void;
|
|
372
|
-
peek(): T; // untracked read
|
|
373
|
-
update(fn: (prev: T) => T): void;
|
|
374
|
-
subscribe(fn: (value: T) => void): Dispose;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
interface ComputedBox<T> { // 1.5.0
|
|
378
|
-
get(): T; // tracked read
|
|
379
|
-
peek(): T; // untracked read
|
|
380
|
-
subscribe(fn: (value: T) => void): Dispose;
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
type Dispose = () => void;
|
|
384
|
-
|
|
385
|
-
interface NodeDescriptor { // yielded by forEachObserver / forEachSource / describe
|
|
386
|
-
id: number; // stable per-allocation id (1.1.5); dedupe + re-walk key
|
|
387
|
-
kind: "signal" | "computed" | "effect";
|
|
388
|
-
value: unknown; // node's current value
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
interface RegistryConfig {
|
|
392
|
-
maxNodes?: number; // default 1024 (ledger under "lazy")
|
|
393
|
-
maxLinks?: number; // default maxNodes * 4 (ledger under "lazy")
|
|
394
|
-
prealloc?: "eager" | "lazy"; // default "eager" (1.3.0): up-front vs on-demand pool construction
|
|
395
|
-
maxFlushPasses?: number; // default 100
|
|
396
|
-
onCapacityExceeded?: "throw" | "grow"; // default "throw"; "grow" = chunked refill, ledger doubles, 16x link ceiling
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
interface RegistryStats { // 11 keys as of 1.4.0
|
|
400
|
-
signals: number;
|
|
401
|
-
computeds: number;
|
|
402
|
-
effects: number;
|
|
403
|
-
activeLinks: number;
|
|
404
|
-
pooledLinks: number;
|
|
405
|
-
linkPoolCapacity: number; // ledger; doubles under "grow"
|
|
406
|
-
nodePoolCapacity: number; // ledger; doubles under "grow"
|
|
407
|
-
activeNodes: number; // live gauge
|
|
408
|
-
totalAllocations: number; // 1.4.0: cumulative node acquires; reset by destroy()
|
|
409
|
-
totalDisposals: number; // 1.4.0: cumulative node disposals; totalAllocations - totalDisposals === activeNodes
|
|
410
|
-
poolGrowths: number; // 1.4.0: cumulative pool-growth chunks; 0 if eager pool sized right
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
class CapacityError extends Error {
|
|
414
|
-
kind: "nodes" | "links";
|
|
415
|
-
capacity: number;
|
|
416
|
-
}
|
|
417
|
-
```
|
|
418
|
-
|
|
419
|
-
## Watchers (added in v1.1)
|
|
420
|
-
|
|
421
|
-
Three composable watcher primitives, all built from `effect` + `untrack`. Tree-shakeable.
|
|
422
|
-
|
|
423
|
-
### watch(source, callback, options?)
|
|
424
|
-
|
|
425
|
-
Fires callback on every change of the projected source value.
|
|
426
|
-
|
|
427
|
-
- **Signature**: `watch<T>(source: () => T, callback: (newValue: T, oldValue: T | undefined, stop: () => void) => void, options?: { immediate?: boolean }): () => void`
|
|
428
|
-
- **Returns**: dispose function. Idempotent. Safe to call synchronously inside the callback.
|
|
429
|
-
- **options.immediate**: when `true`, callback fires once on registration with `oldValue = undefined`. Default `false`.
|
|
430
|
-
- **Equality guard**: uses `Object.is(newValue, oldValue)` internally to avoid firing when the projected value is unchanged across dep mutations. Critical for raw getter sources like `() => health() <= 0` -- many dep changes can produce the same boolean. Wrapping the source in `computed()` would achieve the same via the computed's own equality check.
|
|
431
|
-
- **UNINITIALIZED sentinel**: uses `Symbol("watch.uninitialized")` instead of `undefined` to detect first-run. This means `signal(undefined)` is correctly distinguished from "watcher hasn't fired yet".
|
|
432
|
-
- **Callback reads are untracked**: the callback can read other signals without registering them as dependencies.
|
|
433
|
-
- **Stop in callback**: third callback argument is a stop handle. Safe to call at any point including synchronously during the immediate fire (the `wantsStopEarly` flag defers dispose until after the effect is registered).
|
|
434
|
-
- **Allocation profile**: 3 closures at registration (stop, effect body, hoisted untrack body). **Zero allocations per fire** -- the untrack body is hoisted with `currentNewValue` as shared mutable state. Hot-path safe at 120fps.
|
|
435
|
-
|
|
436
|
-
### when(predicate, callback)
|
|
437
|
-
|
|
438
|
-
Fires callback exactly once when predicate first returns truthy, then auto-disposes.
|
|
439
|
-
|
|
440
|
-
- **Signature**: `when(predicate: () => unknown, callback: () => void): () => void`
|
|
441
|
-
- **Returns**: dispose function. Useful for cancelling before predicate fires; idempotent; no-op after callback has fired.
|
|
442
|
-
- **Synchronous fire**: if predicate is already truthy at registration, callback fires synchronously and watcher disposes immediately (same `wantsStopEarly` pattern as `watch`).
|
|
443
|
-
- **One-shot guarantee**: internal `fired` flag protects against double-fire even if dispose timing lets one more evaluation through.
|
|
444
|
-
- **Callback reads are untracked.**
|
|
445
|
-
- **Truthy/falsy semantics**: standard JS truthy check. `0`, `""`, `null`, `undefined`, `false`, `NaN` do not trigger; everything else does.
|
|
446
|
-
- **Allocation profile**: 2 closures at registration (stop, effect body). **Zero allocations per check** -- `untrack(callback)` passes the user's callback directly without wrapping. Hot-path safe at 120fps.
|
|
447
|
-
|
|
448
|
-
### whenAsync(predicate)
|
|
449
|
-
|
|
450
|
-
Promise variant of `when`.
|
|
451
|
-
|
|
452
|
-
- **Signature**: `whenAsync(predicate: () => unknown): Promise<void>`
|
|
453
|
-
- **Returns**: Promise that resolves when predicate first becomes truthy.
|
|
454
|
-
- **Implementation**: `return new Promise((resolve) => when(predicate, resolve))`.
|
|
455
|
-
- **Foot-gun**: promise never rejects. If predicate never becomes truthy, promise never settles. Use `Promise.race` for timeout: `Promise.race([whenAsync(p), timeoutPromise])`.
|
|
456
|
-
- **! HOT-PATH WARNING**: `new Promise(...)` is a heap allocation. Each call allocates 1 Promise + 1 executor closure + Promise infrastructure (resolve fn, microtask state) + 2 closures from internal `when` call. This is unavoidable -- Promises require heap allocation by spec. **Do NOT call per frame.** Use for high-level orchestration (boot sequences, scene transitions, awaiting user input). For 60/120fps logic, use `when(predicate, callback)` directly -- it's zero-GC.
|
|
457
|
-
|
|
458
|
-
### Architecture note
|
|
459
|
-
|
|
460
|
-
None of these touch the reactive engine -- no `FLAG_WATCHER` on `ReactiveNode`, no extension to the object pool, no new internal primitive. They compose entirely from public API. This is the test that the core engine is structurally complete: when a higher-level pattern can be built without extending the engine, the engine has enough.
|
|
461
|
-
|
|
462
|
-
### Allocation profile summary
|
|
463
|
-
|
|
464
|
-
| Primitive | At registration | Per fire / check |
|
|
465
|
-
|---|---|---|
|
|
466
|
-
| `watch` | 3 closures | 0 |
|
|
467
|
-
| `when` | 2 closures | 0 |
|
|
468
|
-
| `whenAsync` | 1 Promise + executor + Promise internals + 2 closures (from `when`) | 0 |
|
|
469
|
-
|
|
470
|
-
The deliberate engineering for `watch`'s "0 per fire" is the hoisted `untrackedFire` closure with `currentNewValue` shared mutable state -- see source comment in `watch.js`. Inline arrow function inside the effect body would allocate per fire and break the zero-GC contract.
|
|
471
|
-
|
|
472
|
-
## Benchmark snapshot (Node 22, 2016-era Intel MacBook Pro, default eager, median across reps -- @1.3.0)
|
|
473
|
-
|
|
474
|
-
`benchmark.mjs` head-to-head vs alien-signals on app-shaped scenarios (time = median
|
|
475
|
-
execution; heap = average transient delta-heap per rep; lite-signal numbers are
|
|
476
|
-
@1.3.0, hot paths byte-identical to 1.2.2):
|
|
477
|
-
|
|
478
|
-
| Scenario | lite vs alien (time) | transient heap (lite / alien) |
|
|
479
|
-
| -------------------------------- | -------------------- | ----------------------------- |
|
|
480
|
-
| SELECTIVE DAG (set churn) | **+48% faster** | 1.5 MB / 37 MB |
|
|
481
|
-
| DYNAMIC DAG (FAN=6, read flips) | **+43% faster** | 5.1 MB / 24 MB |
|
|
482
|
-
| MUX (256 sigs -> sum -> effect) | **+38% faster** | 38 KB / 3.9 MB |
|
|
483
|
-
| SMALL SELECTIVE (~64x6) | **+29% faster** | 0.3 KB / 23.9 MB |
|
|
484
|
-
| KAIROS (1 -> 1000 computeds) | -1% (parity) | 178 KB / 1.1 MB |
|
|
485
|
-
| LARGE WEB APP (~1000x12) | -4% (parity) | 0.3 KB / 41 KB |
|
|
486
|
-
| WIDE DENSE (~1000x5) | -4% (parity) | 0.3 KB / 11.6 MB |
|
|
487
|
-
| BROADCAST (1 -> 1000 effects) | -10% | 72 KB / 21 KB |
|
|
488
|
-
| DEEP CHAIN (256-deep -> effect) | -18% | 18 KB / 905 KB |
|
|
489
|
-
|
|
490
|
-
lite-signal's time wins are the allocation-heavy dynamic shapes (object pool allocates
|
|
491
|
-
near-nothing; alien churns the nursery), plus MUX fan-in aggregation -- the patterns
|
|
492
|
-
that dominate live UI under input churn. Parity on the cheap stable wide shapes (within
|
|
493
|
-
run-to-run noise on this old host). Two losses: BROADCAST (pure fan-out, no retracking
|
|
494
|
-
for the pool to amortize) and DEEP CHAIN (alien's flatter representation wins when the
|
|
495
|
-
propagation path is long rather than wide). On allocation, lite wins 8/9 scenarios and
|
|
496
|
-
is alone in the zero-alloc band (~0.3 KB transient on the stable app shapes). NOTE: the
|
|
497
|
-
BROADCAST and KAIROS results are now parity-or-behind on 1.3.0's isolated harness;
|
|
498
|
-
earlier ops/s snapshots that showed lite ahead on those were measured under a different
|
|
499
|
-
(multi-engine, shared-heap) protocol.
|
|
500
|
-
|
|
501
|
-
The cross-framework reactivity suite (5 frameworks) re-run on 1.3.0 (default eager,
|
|
502
|
-
median-of-10): lite-signal is fastest on all five `dyn:*` rows -- `dyn: large web app`
|
|
503
|
-
544ms (+7% vs alien-signals' 586ms), `dyn: wide dense` 902ms (+3% vs 926ms), plus
|
|
504
|
-
simple component (+17%), dynamic component (+15%), deep (+14%) -- with preact 6-19x
|
|
505
|
-
slower and vue 15-32x slower on the app-shaped graphs. On the sub-60ms
|
|
506
|
-
`S: updateComputations` micro-rows lite and alien trade the lead within a few percent
|
|
507
|
-
(lite ahead on 3/7), noise-dominated on this host. Retracking verified correct by
|
|
508
|
-
`retracking.difftest.mjs` (20,000 direct + 10,000 batched writes, 0 disagreements vs
|
|
509
|
-
published 1.1.5). `prealloc: "lazy"` trades a little first-construction allocation on the
|
|
510
|
-
dynamic shapes for a smaller resident heap and faster cold start; steady state identical.
|
|
511
|
-
|
|
512
|
-
Retained heap after forced GC: typically negative for all libs (V8 compacts).
|
|
513
|
-
The one exception: lite-signal shows ~+71 KB retained on KAIROS, which is the
|
|
514
|
-
pre-allocated pool holding the live 1002-node graph in steady state. This is
|
|
515
|
-
the design: the pool IS the working memory. Not a leak.
|
|
516
|
-
|
|
517
|
-
## Common idioms
|
|
518
|
-
|
|
519
|
-
```js
|
|
520
|
-
// Glitch-free diamond
|
|
521
|
-
const a = signal(1);
|
|
522
|
-
const b = computed(() => a() + 1);
|
|
523
|
-
const c = computed(() => a() * 2);
|
|
524
|
-
const d = computed(() => b() + c()); // re-evaluates exactly once per a.set
|
|
525
|
-
|
|
526
|
-
// Conditional subscription (b only tracked when flag is true)
|
|
527
|
-
const flag = signal(true);
|
|
528
|
-
const a = signal(1);
|
|
529
|
-
const b = signal(2);
|
|
530
|
-
const sum = computed(() => flag() ? a() + b() : a());
|
|
531
|
-
|
|
532
|
-
// Scheduler integration (rAF batching)
|
|
533
|
-
let queued = false;
|
|
534
|
-
effect(() => render(state()), {
|
|
535
|
-
scheduler: run => {
|
|
536
|
-
if (queued) return;
|
|
537
|
-
queued = true;
|
|
538
|
-
requestAnimationFrame(() => { queued = false; run(); });
|
|
539
|
-
}
|
|
540
|
-
});
|
|
541
|
-
|
|
542
|
-
// Sandboxed plugin
|
|
543
|
-
const sandbox = createRegistry({ maxNodes: 256, onCapacityExceeded: "throw" });
|
|
544
|
-
plugin(sandbox.signal, sandbox.computed, sandbox.effect);
|
|
545
|
-
// later:
|
|
546
|
-
sandbox.destroy(); // entire reactive world reset
|
|
547
|
-
|
|
548
|
-
// 1.2.1: push-based devtools via onGraphMutation
|
|
549
|
-
// Single listener; opcodes 1=create, 2=dispose, 3=link-add, 4=link-remove, 5=recompute.
|
|
550
|
-
// Allocation-free dispatch with just three integers.
|
|
551
|
-
const unsubscribe = onGraphMutation((opcode, intA, intB) => {
|
|
552
|
-
switch (opcode) {
|
|
553
|
-
case 1: devtools.onNodeCreate(intA, intB); break; // intA=id, intB=flags
|
|
554
|
-
case 2: devtools.onNodeDispose(intA); break;
|
|
555
|
-
case 3: devtools.onLinkAdd(intA, intB); break; // intA=source.id, intB=target.id
|
|
556
|
-
case 4: devtools.onLinkRemove(intA, intB); break;
|
|
557
|
-
case 5: devtools.onRecompute(intA); break;
|
|
558
|
-
}
|
|
559
|
-
});
|
|
560
|
-
// Stop listening -- restores prior listener (or null), engine returns to zero-cost state.
|
|
561
|
-
unsubscribe();
|
|
562
|
-
|
|
563
|
-
// 1.2.1: walk the owner tree (cascade-disposal domains)
|
|
564
|
-
// forEachOwned + ownerOf complement forEachObserver + forEachSource:
|
|
565
|
-
// the dep/sub edges show DATA FLOW; the owner edges show LIFETIME BINDING.
|
|
566
|
-
function dumpOwnerTree(handle, depth = 0) {
|
|
567
|
-
const d = describe(handle);
|
|
568
|
-
if (!d) return;
|
|
569
|
-
console.log(" ".repeat(depth * 2), d.kind, d.id);
|
|
570
|
-
forEachOwned(d, (child) => dumpOwnerTree(child, depth + 1));
|
|
571
|
-
}
|
|
572
|
-
```
|
|
573
|
-
|
|
574
|
-
## File layout
|
|
575
|
-
|
|
576
|
-
- `Signal.js` -- full implementation, single file.
|
|
577
|
-
- `Signal.d.ts` -- TypeScript declarations for all public API.
|
|
578
|
-
- `test/01-core_test.mjs` -- signal/computed/effect basics, equality, untrack.
|
|
579
|
-
- `test/02-topology_test.mjs` -- diamonds, chains, fan-out/in, cycle detection.
|
|
580
|
-
- `test/03-pool_test.mjs` -- capacity errors, grow policy, pool reuse.
|
|
581
|
-
- `test/04-zero-gc_test.mjs` -- heap retention (run with --expose-gc).
|
|
582
|
-
- `test/05-scheduler_test.mjs` -- scheduler races, dispose, gen counter, version wrap.
|
|
583
|
-
- `test/06-nested-objects_test.mjs` -- nested-object & reference-identity behaviours.
|
|
584
|
-
- `test/07-dispose_test.mjs` -- universal disposal: registry.dispose(api).
|
|
585
|
-
- `test/08-watch_test.mjs` -- new watch reactivity tests.
|
|
586
|
-
- `test/09-conformance_test.mjs` -- johnsoncodehk/reactive-framework-test-suite conformance fixes tests.
|
|
587
|
-
- `test/10-is-tracking_test.mjs` -- `isTracking()` across observer bodies, untracked windows, and outside any observer.
|
|
588
|
-
- `test/11-adopted-reactive_test.mjs` -- engine-agnostic edge cases adopted from the wider ecosystem (alien-signals link-integrity #226-228, equality-predicate corners, `update()`/`peek()`/`subscribe` contracts).
|
|
589
|
-
- `test/12-coverage_test.mjs` -- targeted public-surface + hot-path branch coverage (top-level routing, clean-read short-circuit, tail severance, scheduler ABA); owner-tree block capability-gated.
|
|
590
|
-
- `test/13-introspection_test.mjs` -- observer-lifecycle surface: `hasObservers`, `observeObservers` auto-pause, `forEach*` enumeration (10 tests).
|
|
591
|
-
- `test/14-lifecycle-teardown_test.mjs` -- effect-teardown guards: stopped effect doesn't re-subscribe to a signal read later in the same run, self-dispose leaves no orphan link, throwing setup leaves no live subscription (4 tests).
|
|
592
|
-
- `test/15-owner-lazy-alloc_test.mjs` -- owner-adoption contract for the 1.2.0 owner tree (lazy signals never adopted; observers still auto-disposed); capability-gated, skipped on 1.1.x (4 tests).
|
|
593
|
-
- `test/16-alien-parity_test.mjs` -- differential guards vs alien-signals@3.2.0 fixed-bug classes: cleanup reads create no deps, inner write doesn't block computed-chain propagation, dynamic dep-set correct under dirty-check (3 tests).
|
|
594
|
-
- `test/17-reactivity_test.mjs` -- behavioral suite over universal signal-system bug classes (subscription lifecycle, cleanup ordering, stale-dep tracking, batching, equality, nested invalidation, memory, sync async-boundary, scheduler/loops, + differential-review additions); SSR is N/A (~30 tests).
|
|
595
|
-
- `test/18-identity_test.mjs` -- node identity (1.1.5): `nodeId`/`describe`, descriptor `id`, re-walkable descriptors, non-perturbing (5 tests).
|
|
596
|
-
- `test/19-v12-additions_test.mjs` -- 1.2.0 surface coverage: shared-peek, owner-adoption rule, pre-batch revert (24 tests).
|
|
597
|
-
- `test/20-axis-stress_test.mjs` -- eight orthogonal stress axes (batch-under-exception, connect/disconnect re-entrancy, untrack vs owner cascade, etc.) (23 tests).
|
|
598
|
-
- `test/21-perf-pins_test.mjs` -- 1.2.1 construction-shape + ABA-guard pins (6 tests).
|
|
599
|
-
- `test/22-mutation-hook_test.mjs` -- 1.2.1 `onGraphMutation` registration + opcode emission (12 tests).
|
|
600
|
-
- `test/23-owner-introspection_test.mjs` -- `ownerOf`, `forEachOwned`, gen-guarded introspection (14 tests).
|
|
601
|
-
- `test/24-signalbox_test.mjs` -- staged for 1.5.0; all tests `{skip: true}` on 1.2.x.
|
|
602
|
-
- `test/25-devtools-real-boot_test.mjs` -- 1.2.2: real `Devtools.js` boot against the engine, ghost-contract pin, `stats()` shape pin (10 tests).
|
|
603
|
-
- `test/26-free-list-invariant_test.mjs` -- 1.2.2: the audit's clean-free-list invariant, asserted by inspecting freshly-allocated nodes (4 tests).
|
|
604
|
-
- `bench/benchmark.mjs` -- anti-DCE throughput harness (ops/s; results.txt).
|
|
605
|
-
- `bench/benchmarkReactive.mjs` -- cross-framework reactivity suite vs alien-signals, preact, vue-reactivity, solid (resultsReactive.txt).
|
|
606
|
-
- `bench/dispose-recycle.mjs` -- 1.2.2 targeted microbench: create/dispose/recreate cycle (the free-list invariant audit target).
|
|
607
|
-
- `bench/torture/` -- crash-detection soaks: `graph-fuzzer`, `scheduler-bench`, `torture-soak`. Exit 0 iff zero errors AND post-teardown pool clean.
|
|
608
|
-
- `bench/run-all.sh` + `bench/aggregate.mjs` -- cold-process-per-engine protocol + per-scenario aggregation.
|
|
609
|
-
- `demo/index.html` -- interactive visualization of the reactive graph.
|
|
610
|
-
|
|
611
|
-
## Install
|
|
612
|
-
|
|
613
|
-
```bash
|
|
614
|
-
npm install @zakkster/lite-signal
|
|
615
|
-
```
|
|
616
|
-
|
|
617
|
-
## License
|
|
618
|
-
|
|
619
|
-
MIT
|