@zakkster/lite-signal 1.6.0-preview.0 → 1.6.0-preview.1
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 +20 -11
- package/README.md +40 -4
- package/Signal.d.ts +28 -0
- package/llms.txt +664 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -66,6 +66,16 @@ mirroring `createRoot`.
|
|
|
66
66
|
|
|
67
67
|
### Verified
|
|
68
68
|
|
|
69
|
+
- **Full suite green** against the 1.6.0 engine: 443 tests, 442 pass, 0 fail,
|
|
70
|
+
1 skip (only the architecturally-N/A SSR case in `17-reactivity`). +4
|
|
71
|
+
`createScope` tests in `test/28-scope_test.mjs`; the 1.5.0 box and createRoot
|
|
72
|
+
suites carry forward unchanged. **Coverage** (c8@11, Node 22): `Signal.js`
|
|
73
|
+
100% statements / 96.96% branches / 100% functions / 100% lines; `Watch.js`
|
|
74
|
+
100% across all four. The branch drop vs 1.5.0 (97.35% -> 96.96%) is the
|
|
75
|
+
zero-cost gate on `flushPasses` / opcode 6 / opcode 7 -- the
|
|
76
|
+
`if (mutationHook !== null)` mutation-hook-attached branch is not exercised
|
|
77
|
+
by the active test suite, which never attaches a hook; the inert path is
|
|
78
|
+
covered.
|
|
69
79
|
- **`createScope` behavior** (4 tests, `node --expose-gc`): returns `fn`'s value and
|
|
70
80
|
runs the owner exactly once even when `fn` reads signals in its direct body
|
|
71
81
|
(untracked); inner effects/computeds track and update; `dispose()` cascade-disposes
|
|
@@ -271,7 +281,7 @@ as before (the reset keeps the arena warm); only the cumulative counts reset.
|
|
|
271
281
|
|
|
272
282
|
### Verified
|
|
273
283
|
|
|
274
|
-
- **Full suite green** against the 1.4.0 engine:
|
|
284
|
+
- **Full suite green** against the 1.4.0 engine: 429 tests, 419 pass, 0 fail,
|
|
275
285
|
10 skip (9 signalBox-staged-for-1.5.0 plus 1 architecturally-N/A SSR skip). The eager-default and the counter additions
|
|
276
286
|
changed no existing test outcome.
|
|
277
287
|
- **Counter correctness** confirmed directly: after building a signal ->
|
|
@@ -282,10 +292,10 @@ as before (the reset keeps the arena warm); only the cumulative counts reset.
|
|
|
282
292
|
- **Zero-GC steady state holds**: the counters bump only on acquire / dispose /
|
|
283
293
|
grow, none of which occur on the steady-state write path after warm-up. Writing
|
|
284
294
|
through a built graph allocates nothing and moves no counter.
|
|
285
|
-
- **`stats()` shape** is now the authoritative 11-key 1.4.x shape
|
|
286
|
-
|
|
287
|
-
(the 1.2.x/1.3.0
|
|
288
|
-
|
|
295
|
+
- **`stats()` shape** is now the authoritative 11-key 1.4.x shape, pinned by a
|
|
296
|
+
new shape-and-initial-zeros test in `03-pool` -- the first explicit pin for
|
|
297
|
+
the `stats()` surface (the 1.2.x / 1.3.0 entries described the absence of the
|
|
298
|
+
counters in prose; 1.4.0 codifies the new shape as a test assertion).
|
|
289
299
|
|
|
290
300
|
|
|
291
301
|
|
|
@@ -367,10 +377,10 @@ in 1.3.0.
|
|
|
367
377
|
|
|
368
378
|
### Verified
|
|
369
379
|
|
|
370
|
-
- **Full suite green** against the 1.3.0 engine:
|
|
371
|
-
|
|
372
|
-
1.
|
|
373
|
-
test outcome.
|
|
380
|
+
- **Full suite green** against the 1.3.0 engine: 423 tests, 413 pass, 0 fail,
|
|
381
|
+
10 skip (9 `24-signalbox` tests `{skip:true}` on 1.3.x -- those primitives
|
|
382
|
+
land in 1.5.0 -- plus 1 architecturally-N/A SSR skip). The eager-default flip
|
|
383
|
+
changed no test outcome.
|
|
374
384
|
- **Behavior-preservation difftest**: 20,000 direct + 10,000 batched writes
|
|
375
385
|
against the published 1.1.5 reference, 0 disagreements. Pool growth, chunked
|
|
376
386
|
refill, and the intrusive mark stack do not alter observable propagation.
|
|
@@ -380,8 +390,7 @@ in 1.3.0.
|
|
|
380
390
|
scenarios.
|
|
381
391
|
- **`stats()` shape unchanged from 1.2.x** (8 keys). The cumulative allocation
|
|
382
392
|
counters (`totalAllocations` / `totalDisposals` / `poolGrowths`) remain
|
|
383
|
-
reserved for 1.4.0 and are still absent here
|
|
384
|
-
test continues to pin their absence.
|
|
393
|
+
reserved for 1.4.0 and are still absent here.
|
|
385
394
|
|
|
386
395
|
|
|
387
396
|
|
package/README.md
CHANGED
|
@@ -244,6 +244,7 @@ import {
|
|
|
244
244
|
signalBox, computedBox, // 1.5.0 -- allocation-light, non-callable
|
|
245
245
|
batch, untrack, onCleanup, isTracking,
|
|
246
246
|
createRoot, // 1.5.0 -- detached ownership scope
|
|
247
|
+
createScope, // 1.6.0 -- detached, adopting scope (one disposer)
|
|
247
248
|
// Registry / lifecycle
|
|
248
249
|
createRegistry, setDefaultRegistry, dispose, destroy,
|
|
249
250
|
stats, CapacityError,
|
|
@@ -358,6 +359,36 @@ Runs `fn` in a **detached ownership scope** and returns whatever `fn` returns. E
|
|
|
358
359
|
|
|
359
360
|
The problem it solves: lazily spawning a *long-lived* node from *inside* a consumer effect is otherwise a footgun -- the spawned node is adopted by the consumer, so the consumer's next re-run cascade-disposes it. That is the ownership model working as designed (owned children dispose with their parent); `createRoot` is the sanctioned opt-out. Any consumer that creates a watcher/subscription inside a reactive scope and expects it to outlive that scope wraps the spawn in `createRoot(() => effect(...))` -- `lite-query`'s query-watcher being the first in the ecosystem. (The companion `runWithOwner`, for re-attaching to a captured owner, is named in the engine as the intended second half of this API and is not yet shipped.)
|
|
360
361
|
|
|
362
|
+
### createScope (1.6.0)
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
const items = signal([/* ... */]);
|
|
366
|
+
const itemDisposers = new Map();
|
|
367
|
+
|
|
368
|
+
// In a reconciler driver: each item gets its own per-item scope.
|
|
369
|
+
effect(() => {
|
|
370
|
+
for (const item of items()) {
|
|
371
|
+
if (!itemDisposers.has(item.id)) {
|
|
372
|
+
itemDisposers.set(item.id, createScope((dispose) => {
|
|
373
|
+
// The consumer's mapFn builds an arbitrary reactive subgraph here;
|
|
374
|
+
// every effect and computed it creates is owned by this scope.
|
|
375
|
+
effect(() => { /* render bindings */ });
|
|
376
|
+
return dispose;
|
|
377
|
+
}));
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
// Later, when an item leaves:
|
|
383
|
+
itemDisposers.get(removedId)(); // cascade-disposes the entire per-item subgraph
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
Runs `fn(dispose)` in a **detached, adopting scope** and returns whatever `fn` returns. The single `dispose` argument handed to `fn` cascade-disposes every effect and computed created inside `fn` -- one disposer tears down a subtree of *unknown* shape. This is the lifecycle complement to `createRoot`: `createRoot` only *detaches* (the caller must dispose each child by hand, correct for one known long-lived watcher), while `createScope` *adopts*, which is what a per-item scope in a keyed-list or scene reconciler needs where the item's reactive graph is the consumer's `mapFn`, not something the reconciler can enumerate.
|
|
387
|
+
|
|
388
|
+
Like `createRoot`, both ownership and tracking are detached for the duration of `fn`'s direct body; inner effect/computed bodies still establish their own scopes. Consistent with the 1.2.0 ownership rule, **plain signals created directly in `fn` are not adopted** -- dispose those explicitly or let them fall out of reference; computeds and effects are adopted and cascade. A scope created inside a consumer effect SURVIVES that consumer's re-run -- the reconciler-critical detach property. The disposer is the same gen-guarded, ABA-safe handle `effect()` returns and resolves to its owner effect under `describe` / `nodeId` / `forEachOwned`. Double-dispose is an idempotent no-op.
|
|
389
|
+
|
|
390
|
+
Implementation note: the scope owner is backed by a never-re-running effect node, so it counts as one effect in `stats()` and the pinned `signals + computeds + effects === activeNodes` invariant is untouched. No new node kind, flag, or `stats()` key.
|
|
391
|
+
|
|
361
392
|
### isTracking
|
|
362
393
|
|
|
363
394
|
```ts
|
|
@@ -435,6 +466,8 @@ const unsub = onGraphMutation((opcode, intA, intB) => {
|
|
|
435
466
|
case 3: devtools.onLinkAdd(intA, intB); break; // intA = source.id, intB = target.id
|
|
436
467
|
case 4: devtools.onLinkRemove(intA, intB); break;
|
|
437
468
|
case 5: devtools.onRecompute(intA); break; // before each effect re-run / computed re-eval
|
|
469
|
+
case 6: devtools.onFlushPass(intA, intB); break; // 1.6.0 -- (passCount, effectsToRun) at top of each drain pass
|
|
470
|
+
case 7: devtools.onEffectRunInPass(intA); break; // 1.6.0 -- (id, 0) before each effect re-run inside a pass
|
|
438
471
|
}
|
|
439
472
|
});
|
|
440
473
|
|
|
@@ -450,6 +483,8 @@ A registry-level (and top-level) debug hook for push-based tooling -- the connec
|
|
|
450
483
|
|
|
451
484
|
**Listener contract: observe only -- never throw, never mutate the graph from inside.** The hook fires synchronously inside mutation points; mutating from the callback corrupts the in-flight operation. Wrap any downstream work that could touch the registry in a microtask.
|
|
452
485
|
|
|
486
|
+
**1.6.0 -- flush-profiling opcodes.** Opcodes `6` (flush pass) and `7` (effect run in pass) extend the surface to cover the flush dimension lite-devtools 1.2 / lite-studio 1.2 read through `watchAllocations`. The matching `stats().flushPasses` counter (the 12th `stats()` key) advances once per drain pass. Both the counter bump and the opcode dispatch sit behind the same `mutationHook !== null` gate, so when no listener is attached they are inert and `flushPasses` is frozen -- the flush loop is byte-identical to 1.5.0.
|
|
487
|
+
|
|
453
488
|
### onCleanup
|
|
454
489
|
|
|
455
490
|
```ts
|
|
@@ -531,7 +566,7 @@ Default sizing for a Twitch-extension-style budget:
|
|
|
531
566
|
| Heavy dashboard (variable scale) | 2048 | 16384 | `"eager"` | `"grow"` |
|
|
532
567
|
| Per-viewer sandbox / short-lived | 512 | 2048 | `"lazy"` | `"throw"` |
|
|
533
568
|
|
|
534
|
-
`stats()` reports
|
|
569
|
+
`stats()` reports 12 keys: eight live gauges -- `signals`, `computeds`, `effects`, `activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity` (the capacity keys are ledgers under `"lazy"`) -- plus three cumulative lifecycle counters added in **1.4.0**: `totalAllocations`, `totalDisposals`, `poolGrowths`, and a fourth counter added in **1.6.0**: `flushPasses` (advances once per effect-flush drain pass, gated behind the mutation-hook check so it stays frozen when no listener is attached -- zero cost in steady state). All four counters are monotonic over the registry's life and reset only by `destroy()`. Sample them over time to chart allocation rate, pool-reuse ratio, graph churn, and flush activity; in a quiescent registry `totalAllocations - totalDisposals === activeNodes`. Drop it on screen for live observability.
|
|
535
570
|
|
|
536
571
|
</details>
|
|
537
572
|
|
|
@@ -695,7 +730,7 @@ These are the questions you'd ask in a code review, with the answers:
|
|
|
695
730
|
|
|
696
731
|
## Benchmarks
|
|
697
732
|
|
|
698
|
-
Honest numbers, against the same workload, with anti-DCE sinks and verified effect execution. All measurements: Node 22, **2016-era Intel MacBook Pro (4 cores, ~10 yr old hardware)**, **one engine per cold process**, median across reps. Newer/faster machines shift all libs up proportionally; the relative ordering between libs is what matters. Numbers below are lite-signal **@1.3.0** (default `prealloc: "eager"`) vs alien-signals on the same `benchmark.mjs` loop -- the harness now reports **median execution time + transient heap** rather than ops/s. 1.3.0's hot paths are byte-identical to 1.2.2, so these track the 1.2.2 measurement; the deltas are run-to-run noise on this old host, not engine changes. **1.4.0
|
|
733
|
+
Honest numbers, against the same workload, with anti-DCE sinks and verified effect execution. All measurements: Node 22, **2016-era Intel MacBook Pro (4 cores, ~10 yr old hardware)**, **one engine per cold process**, median across reps. Newer/faster machines shift all libs up proportionally; the relative ordering between libs is what matters. Numbers below are lite-signal **@1.3.0** (default `prealloc: "eager"`) vs alien-signals on the same `benchmark.mjs` loop -- the harness now reports **median execution time + transient heap** rather than ops/s. 1.3.0's hot paths are byte-identical to 1.2.2, so these track the 1.2.2 measurement; the deltas are run-to-run noise on this old host, not engine changes. **1.4.0, 1.5.0, and 1.6.0 carry these forward unchanged** -- 1.4.0 added three `stats()` counters on existing acquire/dispose/grow edges (never the steady-state read path); 1.5.0 added the box handle shape (allocation-light construction; the read/write hot path is the same pooled-node engine); 1.6.0 added `flushPasses` plus opcodes 6/7, all gated behind the existing `mutationHook !== null` check, so the flush loop is byte-identical to 1.5.0 when no listener is attached. Throughput is unchanged across all three additions (fresh 1.4.0 / 1.5.0 / 1.6.0 bench runs will be published when available). Full per-engine tables: [`results.txt`](./results.txt) (this propagation suite) and [`resultsReactive.txt`](./resultsReactive.txt) (the cross-framework reactivity suite).
|
|
699
734
|
|
|
700
735
|
| Scenario | What it stresses | lite-signal | alien-signals | lite vs alien | transient heap (lite / alien) |
|
|
701
736
|
| ---------- | -------------------------------- | ----------- | ------------- | ------------- | ----------------------------- |
|
|
@@ -763,7 +798,8 @@ Three tiers, all reproducible.
|
|
|
763
798
|
- **`22-mutation-hook_test.mjs`** -- 1.2.1 `onGraphMutation` semantics (12 tests across 2 suites). Registration: unsubscribe returns a function; `null` argument clears and the unsub restores the prior listener; non-function/non-null throws `TypeError`; multiple registrations stack LIFO; registries are isolated (no cross-talk). Opcode emission: `1` node-create fires with `(id, flags)` for signal (32) / computed (1) / effect (2); `2` node-dispose fires for cascade-disposed owned children; `3` link-add fires with `(source.id, target.id)` on dependency record; `4` link-remove fires when a dep-set flip severs the tail; `5` recompute fires on initial eval AND re-eval; the hook fires synchronously inside the mutation (listener sees its own event before the caller returns); payload is always three plain numbers -- no objects, no closures.
|
|
764
799
|
- **`23-owner-introspection_test.mjs`** -- 1.2.1 owner-tree introspection + effect-disposer regression (22 tests across 4 suites). `ownerOf`: undefined for top-level / garbage input / stale handle; returns the enclosing effect's descriptor for a child created inside an effect body. `forEachOwned`: no-op for handles with no owned children / garbage input / stale handle; iterates owned children as `{id, kind, value}` descriptors. Gen-guarded introspection (ABA fix): `nodeId` / `describe` / `hasObservers` return undefined / false for stale handles; `observeObservers` throws `TypeError`; `forEachObserver` / `forEachSource` are no-ops; descriptors returned by `describeNode` are themselves gen-stamped so a descriptor obtained pre-recycle correctly walks as a no-op post-recycle (the "descriptors are re-walkable handles" contract survives the guard). Plus the 1.2.1 effect-dispose-handle fix: passing the effect's disposer directly to `describe` / `nodeId` / `forEachSource` / `forEachOwned` / `ownerOf` / `hasObservers` works as a first-class introspection handle (pre-fix it was a bare closure and returned `undefined` for a *live* effect); after `fx()` dispose the same handle correctly goes stale on every entry point; the disposer's `NODE_GEN` mirrors the effect node's birthGen exactly.
|
|
765
800
|
- **`24-signalbox_test.mjs`** -- the `signalBox` / `computedBox` allocation-light handle API, **activated in 1.5.0** (committed `{skip:true}` since 1.3.0, now running against the real implementation). 12 tests: box get/set/peek/update, `computedBox` derive + memoize, peek-does-not-track, subscribe fires-and-untracks, box<->callable interop both directions, batch coalescing (including set-then-revert net no-op), dispose with ABA-safety, the `equals` short-circuit, `computedBox.peek`, and the top-level helpers bound to the default registry.
|
|
766
|
-
- **`27-create-root_test.mjs`** -- `createRoot` (1.5.0), the ownership escape hatch. A watcher spawned inside a consumer effect via `createRoot` survives the consumer's re-run (the exact `lite-query` lazy-watcher pattern); the contrast case confirms an *unwrapped* spawn is cascade-disposed; `createRoot` returns `fn`'s value, detaches tracking in `fn`'s direct body while inner effect bodies still track, and composes with box handles.
|
|
801
|
+
- **`27-create-root_test.mjs`** -- `createRoot` (1.5.0), the ownership escape hatch. A watcher spawned inside a consumer effect via `createRoot` survives the consumer's re-run (the exact `lite-query` lazy-watcher pattern); the contrast case confirms an *unwrapped* spawn is cascade-disposed; `createRoot` returns `fn`'s value, detaches tracking in `fn`'s direct body while inner effect bodies still track, and composes with box handles. 7 tests, including a top-level-export binding case that closes the otherwise-uncovered top-level `createRoot` path.
|
|
802
|
+
- **`28-scope_test.mjs`** -- `createScope` (1.6.0), the adopting counterpart to `createRoot`. 4 tests: the scope owner runs exactly once on creation; direct-body signal reads in `fn` are untracked while inner effect/computed bodies track normally; `dispose()` cascade-disposes the owned subtree (effects + computeds) while a directly-allocated signal correctly survives (the engine never owner-adopts signals); a scope created inside a consumer effect SURVIVES that consumer's re-run -- the reconciler-critical detach property; `dispose()` is idempotent; the disposer is introspection-stamped to its owner effect (`describe(dispose).kind === "effect"`); and `totalAllocations - totalDisposals === activeNodes` holds across the entire lifecycle.
|
|
767
803
|
- **`25-devtools-real-boot_test.mjs`** -- Devtools/Studio contract (10 tests). Boots the actual `Devtools.js` against the 1.5.0 engine and exercises all 19 Devtools exports plus the 10 symbols Studio imports from Devtools. Pins the ghost contract: heavy introspection (graph walk, owner-tree, observer descriptors) adds **zero** nodes to the live graph. Catches the real-rig failure mode where importing the package by its own name from a repo whose `package.json` declares `name: "@zakkster/lite-signal"` resolves to the published build instead of the local engine.
|
|
768
804
|
- **`26-free-list-invariant_test.mjs`** -- the 1.2.2 audit's cleanliness pins (3 invariant tests + 1 targeted coverage test). Asserts directly -- by inspecting freshly-allocated nodes through the documented `describe()` -> `NODE_PTR` introspection protocol -- that the `ReactiveNode` constructor and the fresh-pool-growth path initialize the ten fields the audit removed from `createNode` to identical values, so the deleted writes were defending against a state the engine cannot produce on a clean free list. The 4th test covers the swallow-on-self-dispose-then-throw branch in `pullComputed` (the path that lifted branch coverage from 98.07% to 98.43%).
|
|
769
805
|
|
|
@@ -1027,7 +1063,7 @@ The one remaining open item is a deliberate design choice (#179, below).
|
|
|
1027
1063
|
The exact post-1.2 pass count is being re-run against the upstream suite;
|
|
1028
1064
|
per-test results and the runner adapter live in `/conformance/`.
|
|
1029
1065
|
|
|
1030
|
-
**177 of 178 tests pass
|
|
1066
|
+
**177 of 178 tests pass**, placing lite-signal **in the second place of sixteen**
|
|
1031
1067
|
evaluated libraries -- just behind alien-signals (177).
|
|
1032
1068
|
|
|
1033
1069
|
We publish both passing and failing tests, because honesty about behavior is
|
package/Signal.d.ts
CHANGED
|
@@ -144,6 +144,16 @@ export interface RegistryStats {
|
|
|
144
144
|
* workload keeps this at 0. Reset only by {@link Registry.destroy}. Added in 1.4.0.
|
|
145
145
|
*/
|
|
146
146
|
poolGrowths: number;
|
|
147
|
+
/**
|
|
148
|
+
* Cumulative count of effect-flush drain passes. Advances once per pass, only
|
|
149
|
+
* while a mutation-hook listener is attached (gated by the same `mutationHook !==
|
|
150
|
+
* null` check that admits opcodes 6 and 7); frozen otherwise, so the steady-state
|
|
151
|
+
* write path is byte-identical to 1.5.0. Combined with `totalAllocations` and
|
|
152
|
+
* `poolGrowths`, lets devtools chart flush activity alongside allocation rate
|
|
153
|
+
* without the engine itself computing rates. Reset by {@link Registry.destroy}.
|
|
154
|
+
* Added in 1.6.0.
|
|
155
|
+
*/
|
|
156
|
+
flushPasses: number;
|
|
147
157
|
}
|
|
148
158
|
|
|
149
159
|
// --- Observer-lifecycle introspection (1.1.4) ---------------------------------
|
|
@@ -268,6 +278,22 @@ export interface Registry {
|
|
|
268
278
|
* effect (e.g. a query watcher). Returns whatever `fn` returns.
|
|
269
279
|
*/
|
|
270
280
|
createRoot<T>(fn: () => T): T;
|
|
281
|
+
/**
|
|
282
|
+
* Run `fn(dispose)` in a detached, untracked scope and return whatever `fn`
|
|
283
|
+
* returns (1.6.0). The single `dispose` argument cascade-disposes every effect
|
|
284
|
+
* and computed created inside `fn`. Lifecycle complement to {@link createRoot}:
|
|
285
|
+
* `createRoot` only *detaches* (caller must dispose each child by hand),
|
|
286
|
+
* `createScope` *adopts*, so one disposer tears down a subtree of unknown shape
|
|
287
|
+
* -- the per-item lifecycle a keyed-list or scene reconciler needs. Plain
|
|
288
|
+
* signals created directly in `fn` are NOT adopted (consistent with the 1.2.0
|
|
289
|
+
* ownership rule); computeds and effects are. The owner never re-runs, so
|
|
290
|
+
* direct-body reads in `fn` are untracked; reactive bindings belong in inner
|
|
291
|
+
* effect/computed bodies. A scope created inside a consumer effect SURVIVES
|
|
292
|
+
* that consumer's re-run -- the reconciler-critical detach property. The
|
|
293
|
+
* disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
|
|
294
|
+
* resolves to the owner effect under `describe` / `nodeId` / `forEachOwned`.
|
|
295
|
+
*/
|
|
296
|
+
createScope<T>(fn: (dispose: () => void) => T): T;
|
|
271
297
|
/**
|
|
272
298
|
* Universal disposal for anything created by this registry: signals,
|
|
273
299
|
* computeds, boxes, or effect dispose handles. Cross-registry calls are
|
|
@@ -348,6 +374,8 @@ export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
|
348
374
|
export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
349
375
|
/** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
|
|
350
376
|
export function createRoot<T>(fn: () => T): T;
|
|
377
|
+
/** Run `fn(dispose)` in a detached, adopting scope (1.6.0), bound to the default registry. See {@link Registry.createScope}. */
|
|
378
|
+
export function createScope<T>(fn: (dispose: () => void) => T): T;
|
|
351
379
|
/** Universal disposal -- see {@link Registry.dispose}. */
|
|
352
380
|
export function dispose(api: Disposable): void;
|
|
353
381
|
export function batch<T>(fn: () => T): T;
|
package/llms.txt
ADDED
|
@@ -0,0 +1,664 @@
|
|
|
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.6.0-preview** (current): the **observability-and-lifecycle minor**, shipping
|
|
56
|
+
on the `preview` dist-tag while it settles. Two additions, both on existing
|
|
57
|
+
hot-path-adjacent edges:
|
|
58
|
+
|
|
59
|
+
**1) `stats()` gains a twelfth key, `flushPasses`** -- advances once per
|
|
60
|
+
effect-flush drain pass. **2) Two new `onGraphMutation` opcodes for flush
|
|
61
|
+
profiling**: `6` flush pass `(passCount, effectsToRun)` at the top of each drain
|
|
62
|
+
pass, and `7` effect run in pass `(id, 0)` before each effect re-run inside a
|
|
63
|
+
pass. Both the `flushPasses` bump and the opcode dispatch sit behind the
|
|
64
|
+
existing `if (mutationHook !== null)` gate, so when no profiler is attached
|
|
65
|
+
they are inert: `flushPasses` is frozen and the flush loop is byte-identical
|
|
66
|
+
to 1.5.0. This is what lets lite-devtools 1.2 / lite-studio 1.2's
|
|
67
|
+
`watchAllocations` chart recompute/flush activity alongside the 1.4.0
|
|
68
|
+
allocation counters; only the flush series requires 1.6.
|
|
69
|
+
|
|
70
|
+
**3) `createScope(fn)` -- the disposable-owner counterpart to `createRoot`.**
|
|
71
|
+
Runs `fn(dispose)` in a detached, untracked scope and returns whatever `fn`
|
|
72
|
+
returns, having handed `fn` a single `dispose` that **cascade-disposes every
|
|
73
|
+
effect and computed created inside `fn`**. `createRoot` only *detaches* (caller
|
|
74
|
+
disposes each child by hand -- correct for one known long-lived watcher);
|
|
75
|
+
`createScope` *adopts*, so one disposer tears down a subtree of unknown shape
|
|
76
|
+
-- the per-item lifecycle a keyed-list or scene reconciler needs, where the
|
|
77
|
+
item's reactive graph is the consumer's `mapFn` (not something the reconciler
|
|
78
|
+
can enumerate). Consistent with 1.2.0 ownership, **plain signals created
|
|
79
|
+
directly in `fn` are not adopted** (engine never owner-adopts signals);
|
|
80
|
+
computeds and effects are. The scope owner is backed by a never-re-running
|
|
81
|
+
effect node, so it counts as one effect in `stats()` and the pinned
|
|
82
|
+
`signals + computeds + effects === activeNodes` invariant is untouched; the
|
|
83
|
+
disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
|
|
84
|
+
resolves to the owner under `describe` / `nodeId` / `forEachOwned`. A scope
|
|
85
|
+
created inside a consumer effect SURVIVES that consumer's re-run -- the
|
|
86
|
+
reconciler-critical detach property.
|
|
87
|
+
|
|
88
|
+
**The callable API and hot paths are unchanged**; this is purely additive
|
|
89
|
+
instrumentation and a second ownership primitive. Drop-in over 1.5.0.
|
|
90
|
+
**Tests:** 443 total, 442 pass, 0 fail, 1 skip (only the architecturally-N/A
|
|
91
|
+
SSR case in `17-reactivity`); +4 `createScope` tests in `test/28-scope_test.mjs`
|
|
92
|
+
and the 1.4.0 pool tests carry the 11-key shape pin forward to the new 12-key
|
|
93
|
+
shape with `flushPasses`. **Coverage:** `Signal.js` 100% statements / 96.96%
|
|
94
|
+
branches / 100% functions / 100% lines; `Watch.js` 100%. The branch drop vs
|
|
95
|
+
1.5.0 (97.35% -> 96.96%) is the `mutationHook !== null` gate on `flushPasses`
|
|
96
|
+
/ opcodes 6+7 -- the listener-attached branch is not exercised by the
|
|
97
|
+
default suite (which never attaches a hook). Drop-in over 1.5.0.
|
|
98
|
+
|
|
99
|
+
- **1.5.0** (drop-in over 1.4.0): the **API-surface minor**. Two non-callable,
|
|
100
|
+
allocation-light primitives -- `signalBox(initial, opts?)` returning
|
|
101
|
+
`{ get, set, peek, update, subscribe }` and `computedBox(fn, opts?)` returning
|
|
102
|
+
`{ get, peek, subscribe }` -- land alongside the callable `signal` / `computed`,
|
|
103
|
+
plus **`createRoot(fn)`** as the ownership escape hatch. **The callable API, hot
|
|
104
|
+
paths, and `stats()` shape (11 keys) are unchanged from 1.4.0**; this is an
|
|
105
|
+
additive surface, not a second engine. Boxes wrap the same `ReactiveNode` and
|
|
106
|
+
interoperate freely with callables in one graph (verified both directions);
|
|
107
|
+
ownership, batching, glitch-freedom, and introspection apply uniformly, and box
|
|
108
|
+
nodes count in `stats().signals` / `computeds` exactly as callable nodes. Box
|
|
109
|
+
construction is ~1.7x cheaper than the callable (an `Object.create(proto)` handle
|
|
110
|
+
with two own props added in fixed order -- never `setPrototypeOf`, which would
|
|
111
|
+
transition the object to dictionary mode and blow the method-call ICs to
|
|
112
|
+
megamorphic); the read/write hot path stays zero-GC (200k box writes through a
|
|
113
|
+
256-wide graph: 0 heap growth, 0 pool growths). `createRoot` runs `fn` with
|
|
114
|
+
`currentOwner` and `currentObserver` (and the tracking flag) nulled, so
|
|
115
|
+
effects/computeds created directly in `fn` are not adopted by the enclosing owner
|
|
116
|
+
and survive its re-runs/disposal -- the sanctioned opt-out for lazily spawning a
|
|
117
|
+
long-lived watcher from inside a consumer effect (`lite-query`'s pattern);
|
|
118
|
+
unwrapped, the consumer owns the watcher and cascade-disposes it. Inner
|
|
119
|
+
effect/computed bodies still establish their own scopes; `createRoot` returns
|
|
120
|
+
whatever `fn` returns. The owner/observer split (1.2.0) made `currentOwner` and
|
|
121
|
+
`currentObserver` distinct precisely so ownership could be detached without
|
|
122
|
+
affecting tracking; `createRoot` is the first of the two named primitives
|
|
123
|
+
(`runWithOwner`, the re-attach half, is not yet shipped). The `24-signalbox`
|
|
124
|
+
suite (staged `{skip:true}` since 1.3.0) now runs and passes. **Tests:** 439
|
|
125
|
+
total, 438 pass, 0 fail, **1 skip** (only the architecturally-N/A SSR case in
|
|
126
|
+
`17-reactivity`; the 9 originally-staged signalBox tests are now active and
|
|
127
|
+
the suite carries +3 box-coverage additions for a 12-test file, +7 `createRoot`
|
|
128
|
+
tests in `test/27-create-root_test.mjs`). **Coverage:** `Signal.js`
|
|
129
|
+
100% statements / 97.35% branches / 100% functions / 100% lines; `Watch.js` 100%.
|
|
130
|
+
Drop-in over 1.4.0.
|
|
131
|
+
|
|
132
|
+
- **1.4.0** (drop-in over 1.3.0): the **observability minor**. `stats()` gains three
|
|
133
|
+
cumulative lifecycle counters -- `totalAllocations`, `totalDisposals`,
|
|
134
|
+
`poolGrowths` -- the surface reserved for 1.4.0 in the 1.2.x/1.3.0 notes, now
|
|
135
|
+
delivered. **The hot paths and public callable API are byte-identical to 1.3.0**;
|
|
136
|
+
the counters bump on existing acquire / dispose / pool-grow edges that already
|
|
137
|
+
ran, never on the steady-state read path, so throughput and zero-GC are
|
|
138
|
+
unchanged. The 1.3.0 eager pool default carries forward (`prealloc: "eager"`).
|
|
139
|
+
**`stats()` now returns 11 keys** (the 8 live gauges plus the 3 counters).
|
|
140
|
+
`totalAllocations` counts every node acquired (pool pop OR fresh build);
|
|
141
|
+
`totalDisposals` counts every node returned to the pool, with
|
|
142
|
+
`totalAllocations - totalDisposals === activeNodes` in a quiescent registry;
|
|
143
|
+
`poolGrowths` counts pool-growth chunks (node OR link crossing its ledger) --
|
|
144
|
+
nonzero after warm-up means the initial pool was undersized, 0 means an eager pool
|
|
145
|
+
was sized right. All three are monotonic and reset only by `destroy()`. They are
|
|
146
|
+
exact, not sampled: a consumer sampling `stats()` over time derives allocation
|
|
147
|
+
rate (delta totalAllocations / delta t), pool-reuse ratio
|
|
148
|
+
(1 - poolGrowths*initialCap/totalAllocations), and churn without the engine
|
|
149
|
+
computing rates -- the series lite-devtools 1.2 / lite-studio 1.2 plot. **Tests:**
|
|
150
|
+
429 total, 419 pass, 0 fail, 10 skip (6 new counter tests in `test/03-pool_test.mjs`
|
|
151
|
+
cover the 11-key shape, the live invariant, poolGrowths firing on growth vs staying
|
|
152
|
+
0 on a sized eager pool, and destroy() reset). **Coverage:** `Signal.js` 100%
|
|
153
|
+
statements / 98.26% branches / 100% functions / 100% lines; `Watch.js` 100%.
|
|
154
|
+
Drop-in over 1.3.0.
|
|
155
|
+
|
|
156
|
+
- **1.3.0** (drop-in over 1.2.2): the **pool minor**. Node and link pools become
|
|
157
|
+
growable and incrementally populated; the propagation mark phase moves to an
|
|
158
|
+
intrusive linked-list stack (a `nextMark` field); a small registry config surface
|
|
159
|
+
(`prealloc`, `onCapacityExceeded`, `maxFlushPasses`) is exposed. The hot paths and
|
|
160
|
+
public callable API are byte-identical to 1.2.2 -- everything here is
|
|
161
|
+
pool mechanics, construction-time behavior, and new opt-in config. Steady-state
|
|
162
|
+
zero-GC is unchanged: after warm-up the pools recycle exactly as before.
|
|
163
|
+
**`prealloc` (`"eager"` default | `"lazy"`):** `"eager"` constructs the full
|
|
164
|
+
`maxNodes` / `maxLinks` pools up front -- deterministic latency, zero allocation
|
|
165
|
+
inside any subsequent hot path (the 16ms / 120fps render-frame contract), at the
|
|
166
|
+
cost of a larger resident heap every major GC traces. `"lazy"` treats the
|
|
167
|
+
capacities as ledgers, constructs nodes/links on first demand, recycles through
|
|
168
|
+
the free lists thereafter -- smaller heap, faster cold start, lighter GC marking,
|
|
169
|
+
identical zero-GC steady state after warm-up. **Growable pools
|
|
170
|
+
(`onCapacityExceeded: "grow"`):** pools extend past their initial capacity via
|
|
171
|
+
chunked refill -- contiguous runs of up to 1024 links / 256 nodes per free-list
|
|
172
|
+
miss, not a single doubling burst, so any one growth pause stays bounded
|
|
173
|
+
(~chunk x ~0.5us). The growth path no longer length-extends the effect queues
|
|
174
|
+
or mark stack (which permanently converted them PACKED->HOLEY). Link growth is
|
|
175
|
+
bounded by the hard `maxLinks * 16` ceiling; `"throw"` (default, now backed by a
|
|
176
|
+
named `CapacityError`) preserves the 1.2.x fail-fast behavior.
|
|
177
|
+
**`maxFlushPasses`** (default 100) is now a public config -- the cycle-protection
|
|
178
|
+
ceiling that throws an `Error` prefixed `"CycleError:"`. **Intrusive mark stack:**
|
|
179
|
+
`markDownstream` walks an iterative DFS backed by a `nextMark` field on each node
|
|
180
|
+
instead of an external `markStack` array; behaviorally identical (same nodes, same
|
|
181
|
+
order, same glitch-free guarantee), and the write lands in the cache line already
|
|
182
|
+
hot from reading `markEpoch`. `nextMark` is the only node-shape change in 1.3.0.
|
|
183
|
+
**`stats()` shape unchanged** (8 keys: `signals`, `computeds`, `effects`,
|
|
184
|
+
`activeNodes`, `activeLinks`, `pooledLinks`, `nodePoolCapacity`,
|
|
185
|
+
`linkPoolCapacity`); the capacity keys are ledgers under `"lazy"`. Cumulative
|
|
186
|
+
allocation counters (`totalAllocations` / `totalDisposals` / `poolGrowths`) remain
|
|
187
|
+
reserved for 1.4.0 and are still absent. **Tests:** 423 total, 413 pass, 0 fail,
|
|
188
|
+
10 skip (the 10 skips are 9 signalBox-staged-for-1.5.0 in
|
|
189
|
+
`test/24-signalbox_test.mjs` plus 1 architecturally-N/A SSR case in
|
|
190
|
+
`17-reactivity`); 4 new pool tests in `test/03-pool_test.mjs` cover the lazy
|
|
191
|
+
on-demand / never-allocated-destroy / grow-extends-ledger / link-ceiling paths.
|
|
192
|
+
**Coverage** (c8@11, Node 22): `Signal.js` 100% statements / 98.26% branches /
|
|
193
|
+
100% functions / 100% lines; `Watch.js` 100% across all four. Behavior-
|
|
194
|
+
preservation difftest: 20,000 direct + 10,000 batched writes vs the published
|
|
195
|
+
1.1.5 reference, 0 disagreements -- pool growth, chunked refill, and the intrusive
|
|
196
|
+
mark stack do not alter observable propagation. Drop-in over 1.2.2.
|
|
197
|
+
|
|
198
|
+
- **1.2.2**: `createNode` clean-free-list invariant audit. Removes
|
|
199
|
+
ten redundant field-writes that defended against a state the engine cannot
|
|
200
|
+
produce on a clean free-list: seven graph/batch fields (`headDep`, `tailDep`,
|
|
201
|
+
`headSub`, `tailSub`, `revertEpoch`, `preBatchValue`, `preBatchVersion`) and
|
|
202
|
+
three owner-tree fields (the non-adoption `firstOwned`, the adoption-path
|
|
203
|
+
`prevOwned`, and the else-branch `owner`). Both teardown paths
|
|
204
|
+
(`disposeNode` direct, `runCleanup` cascade) already null these fields, and
|
|
205
|
+
the `ReactiveNode` constructor initializes them to the same values on the
|
|
206
|
+
fresh-pool-growth path -- so the redundant writes in `createNode` were
|
|
207
|
+
defense against a state that cannot exist. **No public surface change, no
|
|
208
|
+
semantic change.** New `test/26-free-list-invariant_test.mjs` (3 invariant
|
|
209
|
+
tests + 1 targeted coverage test for the swallow-on-self-dispose-then-throw
|
|
210
|
+
branch in `pullComputed`) asserts the invariant directly by inspecting
|
|
211
|
+
freshly-allocated nodes via the documented `describe()` -> `NODE_PTR`
|
|
212
|
+
introspection protocol; new `test/25-devtools-real-boot_test.mjs` (10 tests)
|
|
213
|
+
boots the actual `Devtools.js` against the 1.2.2 engine and pins the 1.2.x
|
|
214
|
+
introspection contract for downstream tooling, including the 8-key
|
|
215
|
+
`stats()` shape (`signals`, `computeds`, `effects`, `activeNodes`,
|
|
216
|
+
`activeLinks`, `pooledLinks`, `nodePoolCapacity`, `linkPoolCapacity`).
|
|
217
|
+
408 tests total: 398 pass, 10 skip, 0 fail (the 10 skips are 9
|
|
218
|
+
signalBox-staged-for-1.5.0 in `test/24-signalbox_test.mjs` plus 1
|
|
219
|
+
architecturally-N/A SSR case in `17-reactivity`). Coverage on `Signal.js`:
|
|
220
|
+
100% statements / 98.43% branches / 100% functions / 100% lines; `Watch.js`
|
|
221
|
+
100% across all four (c8@11, Node 22) -- a branch-coverage gain over the
|
|
222
|
+
1.2.1 baseline (98.07%), from the targeted swallow-on-self-dispose-then-throw
|
|
223
|
+
test in `pullComputed`.
|
|
224
|
+
Version lineage:
|
|
225
|
+
this is the engine previously labeled `1.2.3` in dev -- renumbered to
|
|
226
|
+
`1.2.2` because the deletion is small, isolated, and intentionally
|
|
227
|
+
non-behavioral. Drop-in over 1.2.1. **Bench position** (third-party
|
|
228
|
+
[js-reactivity-benchmark](https://github.com/volynetstyle/js-reactivity-benchmark),
|
|
229
|
+
15 frameworks, 47 tests): #4 by geomean (75.5) at 1.77x behind alien-signals
|
|
230
|
+
(1.00x), reflex (1.15x), @reactively (1.39x); now ahead of 5th-place Preact
|
|
231
|
+
Signals (79.2, lite ~5% ahead -- the gap widened from 1.2.x). The only
|
|
232
|
+
object-pooled zero-GC engine in the field. Ahead of @vue/reactivity (1.5x),
|
|
233
|
+
Signia (1.7x), MobX (2.3x), @solidjs/signals (2.7x), SolidJS (4.2x). Top-3 on
|
|
234
|
+
21/47 tests; outright winner on `manyEffectsFromOneSource`,
|
|
235
|
+
`manySourcesIntoOneComputedEffect`, and
|
|
236
|
+
`manySourcesIntoOneComputedEffectWithDirect` (and edges the leader alien on a
|
|
237
|
+
fourth, the 1-source linear-chain pull). (The suite measures reactivity
|
|
238
|
+
libraries -- Vue reactivity core, MobX, Solid, Preact Signals -- not full UI
|
|
239
|
+
frameworks like React/Angular.)
|
|
240
|
+
In the community reactive suite (median-of-10), fastest of 5 frameworks
|
|
241
|
+
on the entire `dyn:*` family (the realistic large-DOM-framework shapes)
|
|
242
|
+
and the entire `S: updateComputations*` family. Behind on the
|
|
243
|
+
construction-cost path (`S: createComputations*`, `cellx`, `createDataSignals`).
|
|
244
|
+
|
|
245
|
+
- **1.2.1**: correctness-and-introspection patch. Drop-in over 1.2.0;
|
|
246
|
+
no public surface removed. **Stale-handle introspection (ABA fix):** the v1.2.0
|
|
247
|
+
owner tree made the engine recycle pool slots autonomously on owner re-run, so
|
|
248
|
+
holding a stale handle stopped being a user error and became a routine
|
|
249
|
+
occurrence. Pre-1.2.1, `nodeId`/`describe`/`forEachObserver`/`forEachSource`/
|
|
250
|
+
`hasObservers`/`observeObservers`/`peek()` would resolve `NODE_PTR` ungated
|
|
251
|
+
and happily report the recycled slot's NEW resident through an old handle
|
|
252
|
+
(wrong id, wrong value, wrong edges). All six entry points + `peek()` + `read()`
|
|
253
|
+
+ `set()` now resolve through a generation check (the same ABA discipline
|
|
254
|
+
`dispose()` already had); stale handles read as `undefined` (or throw the
|
|
255
|
+
documented `TypeError`, for `observeObservers`). `describe()` descriptors are
|
|
256
|
+
gen-stamped alongside `NODE_PTR`, so the "descriptors are re-walkable handles"
|
|
257
|
+
contract survives the guard: a fresh descriptor walks, one held across a
|
|
258
|
+
recycle correctly goes stale. **Added -- `onGraphMutation(fn)`:** registry-level
|
|
259
|
+
(and top-level) graph-mutation hook for push-based tooling. Single nullable
|
|
260
|
+
listener; every fire point is `if (mutationHook !== null) mutationHook(opcode, intA, intB)`
|
|
261
|
+
-- zero-cost gate when absent, allocation-free dispatch when present. Opcodes:
|
|
262
|
+
`1` node-create `(id, flags)`, `2` node-dispose `(id, flags)` (cascades
|
|
263
|
+
included), `3` link-add `(source.id, target.id)`, `4` link-remove `(source.id, target.id)`,
|
|
264
|
+
`5` recompute `(id, 0)` before each effect re-run / computed re-eval.
|
|
265
|
+
Contract: observe only -- never throw, never mutate the graph from inside.
|
|
266
|
+
This is the connection point lite-devtools 1.1 / lite-studio 1.1 use to go
|
|
267
|
+
push-based. **Added -- `forEachOwned(handle, fn)` / `ownerOf(handle)`:** owner-
|
|
268
|
+
tree introspection. `forEachOwned` iterates a node's owned children as
|
|
269
|
+
re-walkable descriptors; `ownerOf` returns the owner's descriptor or
|
|
270
|
+
`undefined` (top-level or stale). Same descriptor conventions as
|
|
271
|
+
`forEachObserver`/`forEachSource`; garbage input is a no-op/`undefined`.
|
|
272
|
+
Also: `Object.is` hoisted to a module-level const (one IC entry instead of
|
|
273
|
+
per-call lookup in `signal()`/`computed()`). 404 tests, **100% line / 98.07%
|
|
274
|
+
branch coverage** on `Signal.js` + `Watch.js`. New
|
|
275
|
+
`test/21-perf-pins.test.mjs` (6 tests -- construction-shape + ABA-guard pins),
|
|
276
|
+
`test/22-mutation-hook.test.mjs` (12 tests -- `onGraphMutation` registration,
|
|
277
|
+
the 5 opcodes, payload shape, registry isolation), and
|
|
278
|
+
`test/23-owner-introspection.test.mjs` (14 tests -- `forEachOwned`, `ownerOf`,
|
|
279
|
+
and gen-guarded behaviour across the introspection surface). Differential
|
|
280
|
+
fuzz vs the published 1.1.5: 0 disagreements over 30,000 writes.
|
|
281
|
+
|
|
282
|
+
- **1.2.0**: structural refactor (three named layers: graph topology /
|
|
283
|
+
ownership / propagation) plus four additive features built on top. Drop-in over
|
|
284
|
+
1.1.5; no public surface removed. **Owner tree:** an effect or computed that
|
|
285
|
+
creates nested observers (effect/computed) now owns them -- when the owner
|
|
286
|
+
re-runs or is disposed, the engine cascade-disposes those observers before
|
|
287
|
+
the new run. Plain signals are deliberately NOT owner-adopted so lazy-
|
|
288
|
+
allocation wrappers (lite-store keys, lite-form fields) continue to survive
|
|
289
|
+
re-runs of the computed that allocated them. **Pre-batch revert:** inside a
|
|
290
|
+
`batch(...)`, set X then set X back (under the signal's `equals`) reverts the
|
|
291
|
+
version bump -- downstream effects/computeds do not fire. **AggregateError on
|
|
292
|
+
multi-throw:** two or more effects throwing in the same flush pass aggregate to
|
|
293
|
+
`AggregateError` at the trigger; single-throw is unchanged. **Scheduler thunk
|
|
294
|
+
caching:** the scheduler closure is cached on the node and gen-bound, so async
|
|
295
|
+
schedules that fire post-dispose against a recycled slot are guaranteed no-ops
|
|
296
|
+
(ABA safe). Internal split: `currentObserver` and `currentOwner` are now
|
|
297
|
+
distinct pointers (today they move together, no behavioural change). **Perf:**
|
|
298
|
+
shared `peek` (one closure per registry instead of per primitive) shaves
|
|
299
|
+
10-14% off signal/computed creation on the `S:create*` micros, no hot-path or
|
|
300
|
+
behavioural change. 363 tests, 100% line / 98.62% branch coverage on
|
|
301
|
+
`Signal.js` + `Watch.js`. Differential fuzz vs the published 1.1.5: 0
|
|
302
|
+
disagreements over 30,000 writes. New `test/19-v12-additions.test.mjs`
|
|
303
|
+
(24 tests) and `test/20-axis-stress.test.mjs` (23 tests -- eight orthogonal
|
|
304
|
+
engine-invariant axes plus permanent conformance pins). **Conformance fixes
|
|
305
|
+
in 1.2.0**: #141 (dispose during execution then continue: no re-run), and
|
|
306
|
+
#238 / #241 / #243 (cleanup ordering on cascade: inner-before-outer,
|
|
307
|
+
deepest-first, and the inner-only-re-run regression). #141 was a latent
|
|
308
|
+
crash present in 1.1.5 too; the v1.2 owner tree exercised it more
|
|
309
|
+
aggressively. Fix is two-fold -- nullify the tracking cursor in `disposeNode`
|
|
310
|
+
when the disposed node is the active observer (plus a `gen`-snapshot guard
|
|
311
|
+
in `executeEffect`/`pullComputed`); and swap `runCleanup` to cascade
|
|
312
|
+
children first, then own.
|
|
313
|
+
|
|
314
|
+
- **1.1.5**: additive release in service of `@zakkster/lite-devtools` -- stable
|
|
315
|
+
node identity on the introspection surface. `nodeId(handle)` -> the node's stable
|
|
316
|
+
per-allocation id (the dedupe key for graph walks); `describe(handle)` -> the handle's
|
|
317
|
+
own `{ id, kind, value }` descriptor, **re-walkable** (pass it back into
|
|
318
|
+
`forEachObserver`/`forEachSource` to walk the full DAG); `forEach*` descriptors now carry
|
|
319
|
+
`id`. One SMI write at allocation, node shape kept monomorphic -- **zero steady-state
|
|
320
|
+
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.
|
|
321
|
+
|
|
322
|
+
- **1.1.4**: combined release -- a retracking rewrite plus an observer-lifecycle
|
|
323
|
+
introspection surface. Drop-in over 1.1.3. **Retracking:** version-stamped O(1)
|
|
324
|
+
reconciliation + a `markEpoch` clean-read short-circuit replace the cursor strategy's
|
|
325
|
+
O(N)-per-dep degradation under chaotic high-fan-in batched read-after-write; stable read
|
|
326
|
+
order is unchanged (still O(1), still zero-alloc). The two documented v1.1.x losses flipped
|
|
327
|
+
to wins and are now fastest of five frameworks -- `dyn: large web app` 6194ms->571ms, `dyn:
|
|
328
|
+
wide dense` 5115ms->912ms (verified by `retracking.difftest.mjs`: 20k direct + 10k batched, 0
|
|
329
|
+
disagreements; no regressions elsewhere). **Introspection:** `hasObservers`,
|
|
330
|
+
`observeObservers`, `forEachObserver`, `forEachSource` (top-level + per-registry), gated by
|
|
331
|
+
an internal counter so zero steady-state cost when unused. New `test/13-introspection_test.mjs`
|
|
332
|
+
(10 tests). Internally staged as 1.1.4 + 1.1.5; ships as a single 1.1.4.
|
|
333
|
+
|
|
334
|
+
- **1.1.3**: adds `isTracking()` (top-level + per-registry). Returns true iff a
|
|
335
|
+
read right now would record a dependency (`isTrackingDeps && currentObserver !== null`).
|
|
336
|
+
False inside `untrack`, `subscribe` callbacks, `onCleanup` bodies, `watch` /
|
|
337
|
+
`when` callbacks, and outside any observer. ~1-2 ns. For wrapper libraries
|
|
338
|
+
(lite-store, lite-query, lite-form) that allocate reactive primitives lazily
|
|
339
|
+
on property reads. Per-registry: wrappers operating against a non-default
|
|
340
|
+
registry must call THAT registry's `isTracking()`, not the top-level one.
|
|
341
|
+
No behavior or engine changes.
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
- **1.1.2**: hot-path micro-optimizations, no behavior/API change.
|
|
345
|
+
Inlined cursor fast-path in `signal`/`computed` reads (stable-order reads skip
|
|
346
|
+
the `allocateLink` call); zero-allocation creation path (`opts` read defensively
|
|
347
|
+
instead of defaulting to `{}`); single-closure `subscribe`. Owner-tree
|
|
348
|
+
conformance items #209/#210 are wired but skipped pending the v1.2 ownership
|
|
349
|
+
hybrid.
|
|
350
|
+
|
|
351
|
+
## When to use
|
|
352
|
+
|
|
353
|
+
- Animation loops, game HUDs, scoreboards, telemetry overlays.
|
|
354
|
+
- Twitch Extensions (1 MB bundle / 3 s cold start budget).
|
|
355
|
+
- Long-running browser sessions (millions of writes per session).
|
|
356
|
+
- Multi-tenant SDKs where each tenant needs an isolated reactive world.
|
|
357
|
+
- Any context where a GC pause breaks the frame budget.
|
|
358
|
+
|
|
359
|
+
## When NOT to use
|
|
360
|
+
|
|
361
|
+
- Server-side rendering -- no SSR story.
|
|
362
|
+
- 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.)
|
|
363
|
+
- 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.)
|
|
364
|
+
|
|
365
|
+
## API summary
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
// Default registry helpers
|
|
369
|
+
function signal<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): Signal<T>;
|
|
370
|
+
function computed<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): Computed<T>;
|
|
371
|
+
function effect(fn: () => void, opts?: { scheduler?: (run: () => void) => void }): Dispose;
|
|
372
|
+
function signalBox<T>(initial: T, opts?: { equals?: (a: T, b: T) => boolean }): SignalBox<T>; // 1.5.0
|
|
373
|
+
function computedBox<T>(fn: () => T, opts?: { equals?: (a: T, b: T) => boolean }): ComputedBox<T>; // 1.5.0
|
|
374
|
+
function createRoot<T>(fn: () => T): T; // 1.5.0 -- detached ownership scope; returns fn's value
|
|
375
|
+
function dispose(api: Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any> | Dispose): void;
|
|
376
|
+
function batch<T>(fn: () => T): T;
|
|
377
|
+
function untrack<T>(fn: () => T): T;
|
|
378
|
+
function isTracking(): boolean;
|
|
379
|
+
function hasObservers(handle: Signal<any> | Computed<any>): boolean;
|
|
380
|
+
function observeObservers(
|
|
381
|
+
handle: Signal<any> | Computed<any>,
|
|
382
|
+
hooks?: { onConnect?: () => void; onDisconnect?: () => void }
|
|
383
|
+
): () => void; // returns idempotent unobserve
|
|
384
|
+
function forEachObserver(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void;
|
|
385
|
+
function forEachSource(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void;
|
|
386
|
+
function forEachOwned(handle: Signal<any> | Computed<any>, fn: (d: NodeDescriptor) => void): void; // 1.2.1
|
|
387
|
+
function ownerOf(handle: Signal<any> | Computed<any>): NodeDescriptor | undefined; // 1.2.1
|
|
388
|
+
function nodeId(handle: Signal<any> | Computed<any>): number | undefined; // 1.1.5
|
|
389
|
+
function describe(handle: Signal<any> | Computed<any>): NodeDescriptor | undefined; // 1.1.5
|
|
390
|
+
function onGraphMutation( // 1.2.1
|
|
391
|
+
fn: ((opcode: 1|2|3|4|5, intA: number, intB: number) => void) | null
|
|
392
|
+
): () => void; // unsub restores prior listener
|
|
393
|
+
function onCleanup(fn: () => void): void;
|
|
394
|
+
function stats(): RegistryStats;
|
|
395
|
+
|
|
396
|
+
// Registry construction
|
|
397
|
+
function createRegistry(config?: RegistryConfig): Registry;
|
|
398
|
+
function setDefaultRegistry(r: Registry): void;
|
|
399
|
+
|
|
400
|
+
interface Signal<T> {
|
|
401
|
+
(): T; // tracked read
|
|
402
|
+
peek(): T; // untracked read
|
|
403
|
+
set(value: T): void;
|
|
404
|
+
update(fn: (prev: T) => T): void;
|
|
405
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
interface Computed<T> {
|
|
409
|
+
(): T; // tracked read
|
|
410
|
+
peek(): T; // untracked read
|
|
411
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
interface SignalBox<T> { // 1.5.0 -- non-callable, allocation-light
|
|
415
|
+
get(): T; // tracked read
|
|
416
|
+
set(value: T): void;
|
|
417
|
+
peek(): T; // untracked read
|
|
418
|
+
update(fn: (prev: T) => T): void;
|
|
419
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
interface ComputedBox<T> { // 1.5.0
|
|
423
|
+
get(): T; // tracked read
|
|
424
|
+
peek(): T; // untracked read
|
|
425
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
type Dispose = () => void;
|
|
429
|
+
|
|
430
|
+
interface NodeDescriptor { // yielded by forEachObserver / forEachSource / describe
|
|
431
|
+
id: number; // stable per-allocation id (1.1.5); dedupe + re-walk key
|
|
432
|
+
kind: "signal" | "computed" | "effect";
|
|
433
|
+
value: unknown; // node's current value
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
interface RegistryConfig {
|
|
437
|
+
maxNodes?: number; // default 1024 (ledger under "lazy")
|
|
438
|
+
maxLinks?: number; // default maxNodes * 4 (ledger under "lazy")
|
|
439
|
+
prealloc?: "eager" | "lazy"; // default "eager" (1.3.0): up-front vs on-demand pool construction
|
|
440
|
+
maxFlushPasses?: number; // default 100
|
|
441
|
+
onCapacityExceeded?: "throw" | "grow"; // default "throw"; "grow" = chunked refill, ledger doubles, 16x link ceiling
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
interface RegistryStats { // 11 keys as of 1.4.0
|
|
445
|
+
signals: number;
|
|
446
|
+
computeds: number;
|
|
447
|
+
effects: number;
|
|
448
|
+
activeLinks: number;
|
|
449
|
+
pooledLinks: number;
|
|
450
|
+
linkPoolCapacity: number; // ledger; doubles under "grow"
|
|
451
|
+
nodePoolCapacity: number; // ledger; doubles under "grow"
|
|
452
|
+
activeNodes: number; // live gauge
|
|
453
|
+
totalAllocations: number; // 1.4.0: cumulative node acquires; reset by destroy()
|
|
454
|
+
totalDisposals: number; // 1.4.0: cumulative node disposals; totalAllocations - totalDisposals === activeNodes
|
|
455
|
+
poolGrowths: number; // 1.4.0: cumulative pool-growth chunks; 0 if eager pool sized right
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
class CapacityError extends Error {
|
|
459
|
+
kind: "nodes" | "links";
|
|
460
|
+
capacity: number;
|
|
461
|
+
}
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
## Watchers (added in v1.1)
|
|
465
|
+
|
|
466
|
+
Three composable watcher primitives, all built from `effect` + `untrack`. Tree-shakeable.
|
|
467
|
+
|
|
468
|
+
### watch(source, callback, options?)
|
|
469
|
+
|
|
470
|
+
Fires callback on every change of the projected source value.
|
|
471
|
+
|
|
472
|
+
- **Signature**: `watch<T>(source: () => T, callback: (newValue: T, oldValue: T | undefined, stop: () => void) => void, options?: { immediate?: boolean }): () => void`
|
|
473
|
+
- **Returns**: dispose function. Idempotent. Safe to call synchronously inside the callback.
|
|
474
|
+
- **options.immediate**: when `true`, callback fires once on registration with `oldValue = undefined`. Default `false`.
|
|
475
|
+
- **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.
|
|
476
|
+
- **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".
|
|
477
|
+
- **Callback reads are untracked**: the callback can read other signals without registering them as dependencies.
|
|
478
|
+
- **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).
|
|
479
|
+
- **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.
|
|
480
|
+
|
|
481
|
+
### when(predicate, callback)
|
|
482
|
+
|
|
483
|
+
Fires callback exactly once when predicate first returns truthy, then auto-disposes.
|
|
484
|
+
|
|
485
|
+
- **Signature**: `when(predicate: () => unknown, callback: () => void): () => void`
|
|
486
|
+
- **Returns**: dispose function. Useful for cancelling before predicate fires; idempotent; no-op after callback has fired.
|
|
487
|
+
- **Synchronous fire**: if predicate is already truthy at registration, callback fires synchronously and watcher disposes immediately (same `wantsStopEarly` pattern as `watch`).
|
|
488
|
+
- **One-shot guarantee**: internal `fired` flag protects against double-fire even if dispose timing lets one more evaluation through.
|
|
489
|
+
- **Callback reads are untracked.**
|
|
490
|
+
- **Truthy/falsy semantics**: standard JS truthy check. `0`, `""`, `null`, `undefined`, `false`, `NaN` do not trigger; everything else does.
|
|
491
|
+
- **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.
|
|
492
|
+
|
|
493
|
+
### whenAsync(predicate)
|
|
494
|
+
|
|
495
|
+
Promise variant of `when`.
|
|
496
|
+
|
|
497
|
+
- **Signature**: `whenAsync(predicate: () => unknown): Promise<void>`
|
|
498
|
+
- **Returns**: Promise that resolves when predicate first becomes truthy.
|
|
499
|
+
- **Implementation**: `return new Promise((resolve) => when(predicate, resolve))`.
|
|
500
|
+
- **Foot-gun**: promise never rejects. If predicate never becomes truthy, promise never settles. Use `Promise.race` for timeout: `Promise.race([whenAsync(p), timeoutPromise])`.
|
|
501
|
+
- **! 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.
|
|
502
|
+
|
|
503
|
+
### Architecture note
|
|
504
|
+
|
|
505
|
+
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.
|
|
506
|
+
|
|
507
|
+
### Allocation profile summary
|
|
508
|
+
|
|
509
|
+
| Primitive | At registration | Per fire / check |
|
|
510
|
+
|---|---|---|
|
|
511
|
+
| `watch` | 3 closures | 0 |
|
|
512
|
+
| `when` | 2 closures | 0 |
|
|
513
|
+
| `whenAsync` | 1 Promise + executor + Promise internals + 2 closures (from `when`) | 0 |
|
|
514
|
+
|
|
515
|
+
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.
|
|
516
|
+
|
|
517
|
+
## Benchmark snapshot (Node 22, 2016-era Intel MacBook Pro, default eager, median across reps -- @1.3.0)
|
|
518
|
+
|
|
519
|
+
`benchmark.mjs` head-to-head vs alien-signals on app-shaped scenarios (time = median
|
|
520
|
+
execution; heap = average transient delta-heap per rep; lite-signal numbers are
|
|
521
|
+
@1.3.0, hot paths byte-identical to 1.2.2):
|
|
522
|
+
|
|
523
|
+
| Scenario | lite vs alien (time) | transient heap (lite / alien) |
|
|
524
|
+
| -------------------------------- | -------------------- | ----------------------------- |
|
|
525
|
+
| SELECTIVE DAG (set churn) | **+48% faster** | 1.5 MB / 37 MB |
|
|
526
|
+
| DYNAMIC DAG (FAN=6, read flips) | **+43% faster** | 5.1 MB / 24 MB |
|
|
527
|
+
| MUX (256 sigs -> sum -> effect) | **+38% faster** | 38 KB / 3.9 MB |
|
|
528
|
+
| SMALL SELECTIVE (~64x6) | **+29% faster** | 0.3 KB / 23.9 MB |
|
|
529
|
+
| KAIROS (1 -> 1000 computeds) | -1% (parity) | 178 KB / 1.1 MB |
|
|
530
|
+
| LARGE WEB APP (~1000x12) | -4% (parity) | 0.3 KB / 41 KB |
|
|
531
|
+
| WIDE DENSE (~1000x5) | -4% (parity) | 0.3 KB / 11.6 MB |
|
|
532
|
+
| BROADCAST (1 -> 1000 effects) | -10% | 72 KB / 21 KB |
|
|
533
|
+
| DEEP CHAIN (256-deep -> effect) | -18% | 18 KB / 905 KB |
|
|
534
|
+
|
|
535
|
+
lite-signal's time wins are the allocation-heavy dynamic shapes (object pool allocates
|
|
536
|
+
near-nothing; alien churns the nursery), plus MUX fan-in aggregation -- the patterns
|
|
537
|
+
that dominate live UI under input churn. Parity on the cheap stable wide shapes (within
|
|
538
|
+
run-to-run noise on this old host). Two losses: BROADCAST (pure fan-out, no retracking
|
|
539
|
+
for the pool to amortize) and DEEP CHAIN (alien's flatter representation wins when the
|
|
540
|
+
propagation path is long rather than wide). On allocation, lite wins 8/9 scenarios and
|
|
541
|
+
is alone in the zero-alloc band (~0.3 KB transient on the stable app shapes). NOTE: the
|
|
542
|
+
BROADCAST and KAIROS results are now parity-or-behind on 1.3.0's isolated harness;
|
|
543
|
+
earlier ops/s snapshots that showed lite ahead on those were measured under a different
|
|
544
|
+
(multi-engine, shared-heap) protocol.
|
|
545
|
+
|
|
546
|
+
The cross-framework reactivity suite (5 frameworks) re-run on 1.3.0 (default eager,
|
|
547
|
+
median-of-10): lite-signal is fastest on all five `dyn:*` rows -- `dyn: large web app`
|
|
548
|
+
544ms (+7% vs alien-signals' 586ms), `dyn: wide dense` 902ms (+3% vs 926ms), plus
|
|
549
|
+
simple component (+17%), dynamic component (+15%), deep (+14%) -- with preact 6-19x
|
|
550
|
+
slower and vue 15-32x slower on the app-shaped graphs. On the sub-60ms
|
|
551
|
+
`S: updateComputations` micro-rows lite and alien trade the lead within a few percent
|
|
552
|
+
(lite ahead on 3/7), noise-dominated on this host. Retracking verified correct by
|
|
553
|
+
`retracking.difftest.mjs` (20,000 direct + 10,000 batched writes, 0 disagreements vs
|
|
554
|
+
published 1.1.5). `prealloc: "lazy"` trades a little first-construction allocation on the
|
|
555
|
+
dynamic shapes for a smaller resident heap and faster cold start; steady state identical.
|
|
556
|
+
|
|
557
|
+
Retained heap after forced GC: typically negative for all libs (V8 compacts).
|
|
558
|
+
The one exception: lite-signal shows ~+71 KB retained on KAIROS, which is the
|
|
559
|
+
pre-allocated pool holding the live 1002-node graph in steady state. This is
|
|
560
|
+
the design: the pool IS the working memory. Not a leak.
|
|
561
|
+
|
|
562
|
+
## Common idioms
|
|
563
|
+
|
|
564
|
+
```js
|
|
565
|
+
// Glitch-free diamond
|
|
566
|
+
const a = signal(1);
|
|
567
|
+
const b = computed(() => a() + 1);
|
|
568
|
+
const c = computed(() => a() * 2);
|
|
569
|
+
const d = computed(() => b() + c()); // re-evaluates exactly once per a.set
|
|
570
|
+
|
|
571
|
+
// Conditional subscription (b only tracked when flag is true)
|
|
572
|
+
const flag = signal(true);
|
|
573
|
+
const a = signal(1);
|
|
574
|
+
const b = signal(2);
|
|
575
|
+
const sum = computed(() => flag() ? a() + b() : a());
|
|
576
|
+
|
|
577
|
+
// Scheduler integration (rAF batching)
|
|
578
|
+
let queued = false;
|
|
579
|
+
effect(() => render(state()), {
|
|
580
|
+
scheduler: run => {
|
|
581
|
+
if (queued) return;
|
|
582
|
+
queued = true;
|
|
583
|
+
requestAnimationFrame(() => { queued = false; run(); });
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
// Sandboxed plugin
|
|
588
|
+
const sandbox = createRegistry({ maxNodes: 256, onCapacityExceeded: "throw" });
|
|
589
|
+
plugin(sandbox.signal, sandbox.computed, sandbox.effect);
|
|
590
|
+
// later:
|
|
591
|
+
sandbox.destroy(); // entire reactive world reset
|
|
592
|
+
|
|
593
|
+
// 1.2.1: push-based devtools via onGraphMutation
|
|
594
|
+
// Single listener; opcodes 1=create, 2=dispose, 3=link-add, 4=link-remove, 5=recompute.
|
|
595
|
+
// Allocation-free dispatch with just three integers.
|
|
596
|
+
const unsubscribe = onGraphMutation((opcode, intA, intB) => {
|
|
597
|
+
switch (opcode) {
|
|
598
|
+
case 1: devtools.onNodeCreate(intA, intB); break; // intA=id, intB=flags
|
|
599
|
+
case 2: devtools.onNodeDispose(intA); break;
|
|
600
|
+
case 3: devtools.onLinkAdd(intA, intB); break; // intA=source.id, intB=target.id
|
|
601
|
+
case 4: devtools.onLinkRemove(intA, intB); break;
|
|
602
|
+
case 5: devtools.onRecompute(intA); break;
|
|
603
|
+
}
|
|
604
|
+
});
|
|
605
|
+
// Stop listening -- restores prior listener (or null), engine returns to zero-cost state.
|
|
606
|
+
unsubscribe();
|
|
607
|
+
|
|
608
|
+
// 1.2.1: walk the owner tree (cascade-disposal domains)
|
|
609
|
+
// forEachOwned + ownerOf complement forEachObserver + forEachSource:
|
|
610
|
+
// the dep/sub edges show DATA FLOW; the owner edges show LIFETIME BINDING.
|
|
611
|
+
function dumpOwnerTree(handle, depth = 0) {
|
|
612
|
+
const d = describe(handle);
|
|
613
|
+
if (!d) return;
|
|
614
|
+
console.log(" ".repeat(depth * 2), d.kind, d.id);
|
|
615
|
+
forEachOwned(d, (child) => dumpOwnerTree(child, depth + 1));
|
|
616
|
+
}
|
|
617
|
+
```
|
|
618
|
+
|
|
619
|
+
## File layout
|
|
620
|
+
|
|
621
|
+
- `Signal.js` -- full implementation, single file.
|
|
622
|
+
- `Signal.d.ts` -- TypeScript declarations for all public API.
|
|
623
|
+
- `test/01-core_test.mjs` -- signal/computed/effect basics, equality, untrack.
|
|
624
|
+
- `test/02-topology_test.mjs` -- diamonds, chains, fan-out/in, cycle detection.
|
|
625
|
+
- `test/03-pool_test.mjs` -- capacity errors, grow policy, pool reuse.
|
|
626
|
+
- `test/04-zero-gc_test.mjs` -- heap retention (run with --expose-gc).
|
|
627
|
+
- `test/05-scheduler_test.mjs` -- scheduler races, dispose, gen counter, version wrap.
|
|
628
|
+
- `test/06-nested-objects_test.mjs` -- nested-object & reference-identity behaviours.
|
|
629
|
+
- `test/07-dispose_test.mjs` -- universal disposal: registry.dispose(api).
|
|
630
|
+
- `test/08-watch_test.mjs` -- new watch reactivity tests.
|
|
631
|
+
- `test/09-conformance_test.mjs` -- johnsoncodehk/reactive-framework-test-suite conformance fixes tests.
|
|
632
|
+
- `test/10-is-tracking_test.mjs` -- `isTracking()` across observer bodies, untracked windows, and outside any observer.
|
|
633
|
+
- `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).
|
|
634
|
+
- `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.
|
|
635
|
+
- `test/13-introspection_test.mjs` -- observer-lifecycle surface: `hasObservers`, `observeObservers` auto-pause, `forEach*` enumeration (10 tests).
|
|
636
|
+
- `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).
|
|
637
|
+
- `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).
|
|
638
|
+
- `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).
|
|
639
|
+
- `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).
|
|
640
|
+
- `test/18-identity_test.mjs` -- node identity (1.1.5): `nodeId`/`describe`, descriptor `id`, re-walkable descriptors, non-perturbing (5 tests).
|
|
641
|
+
- `test/19-v12-additions_test.mjs` -- 1.2.0 surface coverage: shared-peek, owner-adoption rule, pre-batch revert (24 tests).
|
|
642
|
+
- `test/20-axis-stress_test.mjs` -- eight orthogonal stress axes (batch-under-exception, connect/disconnect re-entrancy, untrack vs owner cascade, etc.) (23 tests).
|
|
643
|
+
- `test/21-perf-pins_test.mjs` -- 1.2.1 construction-shape + ABA-guard pins (6 tests).
|
|
644
|
+
- `test/22-mutation-hook_test.mjs` -- 1.2.1 `onGraphMutation` registration + opcode emission (12 tests).
|
|
645
|
+
- `test/23-owner-introspection_test.mjs` -- `ownerOf`, `forEachOwned`, gen-guarded introspection (14 tests).
|
|
646
|
+
- `test/24-signalbox_test.mjs` -- staged for 1.5.0; all tests `{skip: true}` on 1.2.x.
|
|
647
|
+
- `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).
|
|
648
|
+
- `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).
|
|
649
|
+
- `bench/benchmark.mjs` -- anti-DCE throughput harness (ops/s; results.txt).
|
|
650
|
+
- `bench/benchmarkReactive.mjs` -- cross-framework reactivity suite vs alien-signals, preact, vue-reactivity, solid (resultsReactive.txt).
|
|
651
|
+
- `bench/dispose-recycle.mjs` -- 1.2.2 targeted microbench: create/dispose/recreate cycle (the free-list invariant audit target).
|
|
652
|
+
- `bench/torture/` -- crash-detection soaks: `graph-fuzzer`, `scheduler-bench`, `torture-soak`. Exit 0 iff zero errors AND post-teardown pool clean.
|
|
653
|
+
- `bench/run-all.sh` + `bench/aggregate.mjs` -- cold-process-per-engine protocol + per-scenario aggregation.
|
|
654
|
+
- `demo/index.html` -- interactive visualization of the reactive graph.
|
|
655
|
+
|
|
656
|
+
## Install
|
|
657
|
+
|
|
658
|
+
```bash
|
|
659
|
+
npm install @zakkster/lite-signal
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
## License
|
|
663
|
+
|
|
664
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zakkster/lite-signal",
|
|
3
|
-
"version": "1.6.0-preview.
|
|
3
|
+
"version": "1.6.0-preview.1",
|
|
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",
|