@zakkster/lite-signal 1.9.0-preview.3 → 1.9.0-preview.5
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 +109 -0
- package/README.md +14 -6
- package/Signal.d.ts +542 -0
- package/Signal.js +1 -1
- package/llms.txt +53 -7
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,115 @@ 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.9.0-preview.5] -- 2026-08-18
|
|
8
|
+
|
|
9
|
+
Packaging-only cut. **The engine is UNCHANGED** -- `Signal.js` is behaviourally
|
|
10
|
+
byte-identical to `preview.4`; the sole `Signal.js` edit is the header banner
|
|
11
|
+
version string (see below). This release makes the published package honour its
|
|
12
|
+
own `package.json`: since 1.5.0 the manifest has advertised `"types":
|
|
13
|
+
"./Signal.d.ts"` and listed `Signal.d.ts` in `files[]`, but the 1.9.0 line
|
|
14
|
+
shipped without the file (`preview.4` and earlier packed a `types` pointer to a
|
|
15
|
+
non-existent declaration, so `tsc` consumers got no types). No API, torture, or
|
|
16
|
+
test change from `preview.4`.
|
|
17
|
+
|
|
18
|
+
### Added -- the missing `Signal.d.ts` (the 1.9.0 type surface)
|
|
19
|
+
|
|
20
|
+
- **`Signal.d.ts`** now ships, modelled on the 1.8.0 declaration (1.9.0's export
|
|
21
|
+
surface is byte-identical to 1.8.0's) plus the 1.9.0 explicit-resource-management
|
|
22
|
+
delta: `[Symbol.dispose](): void` is typed on exactly the handles the engine
|
|
23
|
+
stamps -- both box prototypes (`SignalBox` :1495, `ComputedBox` :1496), every
|
|
24
|
+
`Dispose` function (the shared effect disposer at :1614, reached by `effect()`,
|
|
25
|
+
`.subscribe()`, and the `createScope` disposer at :1853), and the `Registry`
|
|
26
|
+
(-> `destroy`, :2087). Callable value handles (`Signal` / `Computed`) are left
|
|
27
|
+
UNSTAMPED, matching the engine. So `using r = createRegistry()`,
|
|
28
|
+
`using box = signalBox(0)`, and `using stop = effect(fn)` all typecheck.
|
|
29
|
+
- The `[Symbol.dispose]` slot is expressed through a `lib`-conditional helper
|
|
30
|
+
(`ExplicitDisposeSlot`): it resolves to the member only when the ambient
|
|
31
|
+
TypeScript `lib` knows `Symbol.dispose` (`esnext.disposable` -- required to use
|
|
32
|
+
`using` at all), and to `{}` otherwise, so the declaration NEVER forces a `lib`
|
|
33
|
+
upgrade on type-only consumers. Verified: compiles under
|
|
34
|
+
`--lib ES2022,ESNext.Disposable` with `using` on all four shapes; compiles clean
|
|
35
|
+
under `--lib ES2020` for a type-only consumer (zero errors); manual
|
|
36
|
+
`[Symbol.dispose]()` is typed.
|
|
37
|
+
|
|
38
|
+
### Changed -- header banner reconciled to the manifest
|
|
39
|
+
|
|
40
|
+
- **`Signal.js` header banner** now reads `v1.9.0-preview.5`, matching
|
|
41
|
+
`package.json` and this changelog. `preview.2` through `preview.4` shipped a
|
|
42
|
+
stale `preview.2` banner (a cosmetic drift in a comment; no code depended on
|
|
43
|
+
it). No other line of `Signal.js` changed -- torture stays 22/22 and the unit
|
|
44
|
+
suite is unaffected.
|
|
45
|
+
|
|
46
|
+
## [1.9.0-preview.4] -- 2026-08-18
|
|
47
|
+
|
|
48
|
+
Version-only re-tag over `preview.3`. `Signal.js` is byte-identical to
|
|
49
|
+
`preview.3` past the header banner; no engine, torture, test, API, or packaging
|
|
50
|
+
change (the `Signal.d.ts` gap and the stale `preview.2` banner were both still
|
|
51
|
+
present -- both are fixed in `preview.5`). Recorded here for continuity.
|
|
52
|
+
|
|
53
|
+
## [1.9.0-preview.3] -- 2026-08-18
|
|
54
|
+
|
|
55
|
+
Verification-only parity cut. **The engine is UNCHANGED** -- `Signal.js` (2209
|
|
56
|
+
lines) is byte-for-byte identical to `preview.2`; this cut only brings the
|
|
57
|
+
`bench/torture` suite and the unit tests to FULL PARITY with the shipped 1.4.4
|
|
58
|
+
canonical suite, then VERIFIES-then-PINS 1.9.0's actual behaviour (no assertion
|
|
59
|
+
softened, no budget widened).
|
|
60
|
+
|
|
61
|
+
### Added -- the last three torture scenarios + soak value-oracles + a throwing-equals pin
|
|
62
|
+
|
|
63
|
+
- **`error-torture`** -- throwing effect bodies under flush: a single throw is
|
|
64
|
+
re-thrown UNWRAPPED; two or more aggregate into one `AggregateError` carrying
|
|
65
|
+
EXACTLY those errors in order; the effect scheduled between two throwers still
|
|
66
|
+
runs; and the pre-allocated error buffer drains to a clean baseline over 4096
|
|
67
|
+
throw/clean cycles (`activeNodes` / `activeLinks` flat). Pinned against 1.9.0
|
|
68
|
+
`Signal.js` :928 (buffer append), :936-937 (finally clear), :941-951 (single
|
|
69
|
+
re-throw / AggregateError).
|
|
70
|
+
- **`deep-chain-torture`** -- `pullComputed` (1.9.0 :1092, recursing at :1113) is
|
|
71
|
+
call-stack recursive, so a computed chain ramped START 2000 / STEP 2000 /
|
|
72
|
+
CEILING 100000 fails CLOSED with a `RangeError` at some depth; the registry
|
|
73
|
+
stays usable, the re-read is deterministic, and the heap-iterative effect
|
|
74
|
+
cascade over an equally deep chain completes without throwing.
|
|
75
|
+
- **`zerogc-torture`** -- the zero-GC claim as a re-runnable gate via
|
|
76
|
+
`@zakkster/lite-gc-profiler` (added as a dev-only dependency): `measureAllocs` /
|
|
77
|
+
`checkAllocs` at `maxBytesPerCall: 0`, `measureOps` / `checkNoGc` at
|
|
78
|
+
`maxMajor: 0` / `maxPauseMs: 2`, and `stats()` poolGrowths/totalAllocations
|
|
79
|
+
deltas, over deep/wide/batch steady writes plus create/dispose churn on both the
|
|
80
|
+
callable form and `signalBox` (churn-box activates natively and reports a visible
|
|
81
|
+
"ok" verdict). `ZEROGC_BREAK=1` self-tests that the gate rejects a planted
|
|
82
|
+
allocation (exits non-zero).
|
|
83
|
+
- **`capacity-torture` section 9** -- the 16x link grow ceiling: `grow` mode still
|
|
84
|
+
fails closed at `maxLinks * 16` (confirmed 1.9.0 :312 / :471) with a `links`
|
|
85
|
+
`CapacityError`, growth terminating AT the ceiling, and a fail-closed re-throw
|
|
86
|
+
rather than a partial sum.
|
|
87
|
+
- **Soak value-oracles** -- `graph-fuzzer`, `scheduler-bench`, `torture-soak` now
|
|
88
|
+
assert VALUE-CORRECTNESS, not just resources: a single `Int32Array` shadow,
|
|
89
|
+
allocated ONCE before the loop, shadows every writable signal; a rotating fixed
|
|
90
|
+
window is checked per tick (no per-tick allocation) and a full sweep runs at
|
|
91
|
+
teardown; a mismatch exits 1 with the seed and index. The module-scoped int32
|
|
92
|
+
JIT sink replaces the former magic-constant "impossible" guard.
|
|
93
|
+
- **`test/30-throwing-equals.test.mjs`** -- a user `equals` that THROWS, pinned at
|
|
94
|
+
all five 1.9.0 sites: the three callable sites (signal set pre-check :1272, batch
|
|
95
|
+
revert :1279, computed re-eval :1143) with a CONTRAST anti-tautology test, and
|
|
96
|
+
the two `signalBox` `boxSet` sites (pre-check :1403, revert :1410).
|
|
97
|
+
|
|
98
|
+
### Changed -- introspect-torture forEachOwned pinned to an exact count
|
|
99
|
+
|
|
100
|
+
`introspect-torture` section 7 asserted `owned >= 2`; the owned count under one
|
|
101
|
+
scope owner (a computed + an effect) is DETERMINISTICALLY 2, so it is now pinned
|
|
102
|
+
`owned === 2`. No behavioural change -- a tightened assertion.
|
|
103
|
+
|
|
104
|
+
### Verified -- the whole superset runs natively on the 1.9.0 engine
|
|
105
|
+
|
|
106
|
+
`dispose`, `cleanup-return`, `owner`, `scope`, and `flush` all execute NATIVELY
|
|
107
|
+
here with zero feature-skips: 1.9.0 is the first engine to run the complete
|
|
108
|
+
torture superset.
|
|
109
|
+
|
|
110
|
+
- **Torture:** 22/22 -- `torture:semantic` 19/19 (all executed, zero skips),
|
|
111
|
+
`torture:soak` 3/3 (zero errors, value-oracle clean, every pool back to its
|
|
112
|
+
leaf-only floor).
|
|
113
|
+
- **Unit (`npm test`):** 512 tests, 511 pass, 0 fail, 1 skip.
|
|
114
|
+
- **Unit (`npm run test:gc`):** 520 tests, 519 pass, 0 fail, 1 skip.
|
|
115
|
+
|
|
7
116
|
## [1.9.0-preview.2] -- 2026-07-27
|
|
8
117
|
|
|
9
118
|
Rolls up the post-`1.9.0-preview` changes into the `preview.2` tag. The 1.9.0
|
package/README.md
CHANGED
|
@@ -813,7 +813,9 @@ Three tiers, all reproducible.
|
|
|
813
813
|
|
|
814
814
|
### Tier 1 -- Behavior (unit tests, fast)
|
|
815
815
|
|
|
816
|
-
`npm test`
|
|
816
|
+
On the 1.9.0 engine `npm test` reports **512 tests, 511 pass, 0 fail, 1 skip**, and
|
|
817
|
+
`npm run test:gc` (Tier 2, `--expose-gc`) reports **520 tests, 519 pass, 0 fail, 1
|
|
818
|
+
skip**. `npm test` runs the suite in `test/`, covering:
|
|
817
819
|
|
|
818
820
|
- **`01-core.test.mjs`** -- signal/computed/effect basics, equality semantics, NaN/+/-0, subscribe/peek/update, untrack, batch, cleanup ordering, first-run error recovery, nested object reference-identity gotchas.
|
|
819
821
|
- **`02-topology.test.mjs`** -- diamond glitch-freedom, 256-deep and 1024-deep computed chains, wide fan-out (1000 effects from one signal), dynamic dependency switching, conditional fan-out, nested effects, cycle detection (`CycleError`).
|
|
@@ -842,6 +844,7 @@ Three tiers, all reproducible.
|
|
|
842
844
|
- **`29-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.
|
|
843
845
|
- **`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.
|
|
844
846
|
- **`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%).
|
|
847
|
+
- **`30-throwing-equals.test.mjs`** -- a user `equals` that THROWS, pinned at all five 1.9.0 invocation sites (9 tests): the three callable sites (signal set pre-check, batch revert, computed re-eval -- with a CONTRAST anti-tautology test proving the batch-revert pin is caused by the throw, not the set-then-back shape) and the two `signalBox` `boxSet` sites (pre-check leaves the box unmutated; batch-revert strands the version bump so the net value fires downstream).
|
|
845
848
|
|
|
846
849
|
```bash
|
|
847
850
|
npm test
|
|
@@ -872,12 +875,12 @@ npm run bench
|
|
|
872
875
|
|
|
873
876
|
### Tier 4 -- Torture (correctness and resources under chaos)
|
|
874
877
|
|
|
875
|
-
`bench/torture/` holds the complete **
|
|
878
|
+
`bench/torture/` holds the complete **22-scenario suite (19 semantic + 3 soak)**
|
|
876
879
|
behind one runner (`run.mjs`). They are not perf benchmarks: the ops/sec figures
|
|
877
880
|
reflect random workload composition, not engine throughput -- `bench/benchmark.mjs`
|
|
878
881
|
remains the canonical perf harness. Every scenario feature-detects and skips
|
|
879
882
|
cleanly below the engine version that introduces its feature; on the **1.9.0
|
|
880
|
-
engine all
|
|
883
|
+
engine all 19 semantic scenarios execute with zero feature-skips** -- the first
|
|
881
884
|
engine version to run the complete superset, since `dispose` was the last gate.
|
|
882
885
|
|
|
883
886
|
```bash
|
|
@@ -905,10 +908,13 @@ Run these on every commit.
|
|
|
905
908
|
| `owner-torture` (1.6.0) | `getOwner`/`runWithOwner` capture-restore: the gen-stamped owner handle, adoption of nodes created inside `runWithOwner`, cascade-dispose when the captured owner is torn down |
|
|
906
909
|
| `lifecycle-torture` | `createRoot` (1.5.0+) detachment of an owned subtree, and the direct `destroy` (1.4.0+) reset contract -- both previously unexercised by any scenario |
|
|
907
910
|
| `async-torture` | `watch`/`when`/`whenAsync` contracts + a 300-seed projection-guard storm |
|
|
908
|
-
| `capacity-torture` | the fail-closed pool boundary: exact ceilings, re-throw-on-read, `grow` crossing the same boundary |
|
|
911
|
+
| `capacity-torture` | the fail-closed pool boundary: exact ceilings, re-throw-on-read, `grow` crossing the same boundary, and the 16x link grow ceiling (`maxLinks * 16`) that fails closed too |
|
|
912
|
+
| `error-torture` | throwing effect bodies under flush: a single throw re-thrown unwrapped, 2+ aggregated into an `AggregateError` carrying exactly those errors, the survivor still runs, and the error buffer drains to baseline over 4096 throw/clean cycles |
|
|
913
|
+
| `deep-chain-torture` | `pullComputed` recursion fails closed with a `RangeError` at a ramped depth (<= 100000) while the heap-iterative effect-cascade push path stays open at the same depth |
|
|
909
914
|
| `flush-torture` (1.7.0) | the three `flushStrategy` modes by cross-strategy differential, per-strategy scheduling, re-entrant/empty `flush()`, and the `.subscribe()` contract under each |
|
|
910
915
|
| `cleanup-return-torture` (1.8.0) | an effect's returned cleanup: timing at re-run/dispose, compose order after `onCleanup`, the self-dispose guard, and the computed exclusion |
|
|
911
916
|
| `dispose-torture` (1.9.0) | `Symbol.dispose` stamped at five sites (registry, effect stop handle, scope/root disposers, both box prototypes) driven through the TC39 `using` path; idempotent disposal, feature-detected via the box-prototype stamp |
|
|
917
|
+
| `zerogc-torture` | the zero-GC claim as a gate via `@zakkster/lite-gc-profiler`: `measureAllocs`/`checkAllocs` at `maxBytesPerCall: 0` + `measureOps`/`checkNoGc` at `maxMajor: 0`/`maxPauseMs: 2` + `stats()` deltas over steady + create/dispose churn (callable and `signalBox`); `ZEROGC_BREAK=1` self-tests that the gate rejects a planted allocation |
|
|
912
918
|
|
|
913
919
|
#### `soak` -- wall-clock bound, asserts on **resources**
|
|
914
920
|
|
|
@@ -918,8 +924,10 @@ effect rewires, nested-batch + untrack reads, and microtask-scheduled async
|
|
|
918
924
|
flushes -- for 5-10 seconds. What they assert, with a non-zero exit code on
|
|
919
925
|
failure:
|
|
920
926
|
|
|
921
|
-
- zero thrown exceptions during the run,
|
|
922
|
-
- after teardown, `activeNodes` / `activeLinks` return to the leaf-only baseline (the dispose path is sound under sustained churn)
|
|
927
|
+
- zero thrown exceptions during the run,
|
|
928
|
+
- after teardown, `activeNodes` / `activeLinks` return to the leaf-only baseline (the dispose path is sound under sustained churn),
|
|
929
|
+
- a module-scoped int32 JIT sink advanced (the work loops were not optimised away), and
|
|
930
|
+
- **value-correctness**: a single `Int32Array` shadow oracle -- allocated ONCE before the loop, a rotating fixed window checked per tick (no per-tick allocation) plus a full sweep at teardown -- confirms every writable signal read back its last written value.
|
|
923
931
|
|
|
924
932
|
```bash
|
|
925
933
|
node --expose-gc bench/torture/graph-fuzzer.mjs # 10s random-DAG fuzz, 1500 nodes
|
package/Signal.d.ts
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @zakkster/lite-signal -- zero-GC reactive graph.
|
|
3
|
+
*
|
|
4
|
+
* Public type surface for the JavaScript implementation in `Signal.js`.
|
|
5
|
+
*
|
|
6
|
+
* 1.9.0 adds explicit-resource-management (`using` / `Symbol.dispose`) on
|
|
7
|
+
* lifecycle objects. The engine is otherwise 1.8.0: same exports, same runtime
|
|
8
|
+
* surface. The only type-level delta is the `[Symbol.dispose]()` slot the 1.9.0
|
|
9
|
+
* engine stamps on every disposable handle -- both box prototypes, the
|
|
10
|
+
* `Registry`, and every `Dispose` function (effect / `.subscribe()` /
|
|
11
|
+
* `createScope`). Callable value handles (`Signal` / `Computed`) are NOT
|
|
12
|
+
* stamped, matching the engine. See {@link ExplicitDisposeSlot} for how the
|
|
13
|
+
* slot degrades on TypeScript `lib` targets that predate `Symbol.dispose`.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The `[Symbol.dispose]()` method the 1.9.0 engine stamps on every disposable
|
|
18
|
+
* handle. Expressed so it never forces a `lib` upgrade: when the ambient
|
|
19
|
+
* TypeScript `lib` knows `Symbol.dispose` (`esnext.disposable` -- required to
|
|
20
|
+
* use `using` at all) this resolves to `{ [Symbol.dispose](): void }` and the
|
|
21
|
+
* `using` declaration typechecks; on any older `lib` the key is `never`, the
|
|
22
|
+
* member vanishes, and these types stay usable as plain values. The runtime
|
|
23
|
+
* mirrors this exactly -- `Signal.js` feature-detects `Symbol.dispose` and only
|
|
24
|
+
* stamps the slot when the host provides it (Node 20+ for manual
|
|
25
|
+
* `[Symbol.dispose]()`, Node 24+ for `using`).
|
|
26
|
+
*/
|
|
27
|
+
export type ExplicitDisposeSlot = {
|
|
28
|
+
[K in typeof Symbol extends { readonly dispose: infer S } ? S : never]: () => void;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// --- Options ------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
/** Equality predicate. Returning `true` halts propagation. */
|
|
34
|
+
export type EqualsFn<T> = (a: T, b: T) => boolean;
|
|
35
|
+
|
|
36
|
+
/** Options accepted by {@link signal}. */
|
|
37
|
+
export interface SignalOptions<T> {
|
|
38
|
+
/** Custom equality predicate. Default: `Object.is`. */
|
|
39
|
+
equals?: EqualsFn<T>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Options accepted by {@link computed}. */
|
|
43
|
+
export interface ComputedOptions<T> {
|
|
44
|
+
/** Custom equality predicate. Default: `Object.is`. */
|
|
45
|
+
equals?: EqualsFn<T>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Scheduler trampoline. The implementation must call the supplied `run` callback
|
|
50
|
+
* at most once. `requestAnimationFrame`, `queueMicrotask`, and `setTimeout`
|
|
51
|
+
* shapes are all compatible (wrap them if their signature differs).
|
|
52
|
+
*/
|
|
53
|
+
export type EffectScheduler = (run: () => void) => void;
|
|
54
|
+
|
|
55
|
+
/** Options accepted by {@link effect}. */
|
|
56
|
+
export interface EffectOptions {
|
|
57
|
+
/** Optional scheduler. If supplied, the effect's first run and every
|
|
58
|
+
* subsequent re-run is deferred through this trampoline. */
|
|
59
|
+
scheduler?: EffectScheduler;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Idempotent dispose handle returned by {@link effect}, `.subscribe()`, and the
|
|
64
|
+
* scope disposer of {@link Registry.createScope}. Callable as a plain function;
|
|
65
|
+
* from 1.9.0 it ALSO carries `[Symbol.dispose]` (routing to the same idempotent,
|
|
66
|
+
* gen-guarded disposer), so `using stop = effect(...)` disposes at block exit.
|
|
67
|
+
*/
|
|
68
|
+
export type Dispose = (() => void) & ExplicitDisposeSlot;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Cleanup returned from an effect body (1.8.0, Reflex pattern A).
|
|
72
|
+
* Runs before the next re-run and once on dispose, appended after any
|
|
73
|
+
* `onCleanup(fn)` registered in the same body (they compose in call order).
|
|
74
|
+
*/
|
|
75
|
+
export type EffectCleanup = () => void;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* An effect body. Returning a function registers it as a cleanup (1.8.0);
|
|
79
|
+
* any other return value is ignored. Computeds are NOT affected -- a computed
|
|
80
|
+
* returning a function keeps treating that function as its value.
|
|
81
|
+
*/
|
|
82
|
+
export type EffectBody = () => void | EffectCleanup;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Anything that can be passed to {@link Registry.dispose}: a {@link Signal},
|
|
86
|
+
* a {@link Computed}, or an effect's {@link Dispose} function. Passing an
|
|
87
|
+
* unrelated value is a safe no-op.
|
|
88
|
+
*/
|
|
89
|
+
export type Disposable<T = unknown> = Signal<T> | Computed<T> | SignalBox<T> | ComputedBox<T> | Dispose;
|
|
90
|
+
|
|
91
|
+
// --- Reactive primitive shapes ------------------------------------------------
|
|
92
|
+
|
|
93
|
+
/** Reactive source of truth. */
|
|
94
|
+
export interface Signal<T> {
|
|
95
|
+
/** Read the current value, tracking the read if inside an effect or computed. */
|
|
96
|
+
(): T;
|
|
97
|
+
/** Read the value WITHOUT tracking. */
|
|
98
|
+
peek(): T;
|
|
99
|
+
/** Overwrite the value. No-op if equal under the signal's equality predicate. */
|
|
100
|
+
set(value: T): void;
|
|
101
|
+
/** Functional update: `set(fn(currentValue))`. Reads the current value without tracking. */
|
|
102
|
+
update(fn: (current: T) => T): void;
|
|
103
|
+
/** Subscribe to value changes. Fires immediately with the current value. */
|
|
104
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Lazy memoised derivation. */
|
|
108
|
+
export interface Computed<T> {
|
|
109
|
+
/** Resolve the value, tracking the read if inside an effect or computed. */
|
|
110
|
+
(): T;
|
|
111
|
+
/** Resolve the value WITHOUT tracking. */
|
|
112
|
+
peek(): T;
|
|
113
|
+
/** Subscribe to value changes. Fires immediately with the current value. */
|
|
114
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Method surface of {@link SignalBox}; see that type for the full contract. */
|
|
118
|
+
interface SignalBoxMembers<T> {
|
|
119
|
+
/** Read the current value, tracking the read if inside an effect or computed. */
|
|
120
|
+
get(): T;
|
|
121
|
+
/** Overwrite the value. No-op if equal under the box's equality predicate. */
|
|
122
|
+
set(value: T): void;
|
|
123
|
+
/** Read the value WITHOUT tracking. */
|
|
124
|
+
peek(): T;
|
|
125
|
+
/** Functional update: `set(fn(currentValue))`. Reads the current value without tracking. */
|
|
126
|
+
update(fn: (current: T) => T): void;
|
|
127
|
+
/** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
|
|
128
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Allocation-light, non-callable signal (1.5.0). A plain object on a shared
|
|
133
|
+
* prototype rather than a callable function -- cheaper to construct than
|
|
134
|
+
* {@link Signal} (no closure allocation), with an identical zero-GC read/write
|
|
135
|
+
* path. Interoperates freely with callable handles in the same graph.
|
|
136
|
+
*
|
|
137
|
+
* From 1.9.0 the shared prototype carries `[Symbol.dispose]` (-> `dispose(box)`),
|
|
138
|
+
* so `using box = signalBox(0)` disposes the box at block exit.
|
|
139
|
+
*/
|
|
140
|
+
export type SignalBox<T> = SignalBoxMembers<T> & ExplicitDisposeSlot;
|
|
141
|
+
|
|
142
|
+
/** Method surface of {@link ComputedBox}; see that type for the full contract. */
|
|
143
|
+
interface ComputedBoxMembers<T> {
|
|
144
|
+
/** Resolve the value, tracking the read if inside an effect or computed. */
|
|
145
|
+
get(): T;
|
|
146
|
+
/** Resolve the value WITHOUT tracking. */
|
|
147
|
+
peek(): T;
|
|
148
|
+
/** Subscribe to value changes. Fires immediately with the current value; the callback runs untracked. */
|
|
149
|
+
subscribe(fn: (value: T) => void): Dispose;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Allocation-light, non-callable computed (1.5.0). The derived counterpart to
|
|
154
|
+
* {@link SignalBox}: `{ get, peek, subscribe }`, no `set` / `update`.
|
|
155
|
+
*
|
|
156
|
+
* From 1.9.0 the shared prototype carries `[Symbol.dispose]` (-> `dispose(box)`),
|
|
157
|
+
* so `using box = computedBox(fn)` disposes the box at block exit.
|
|
158
|
+
*/
|
|
159
|
+
export type ComputedBox<T> = ComputedBoxMembers<T> & ExplicitDisposeSlot;
|
|
160
|
+
|
|
161
|
+
// --- Diagnostics --------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
export interface RegistryStats {
|
|
164
|
+
/** Number of signals created in this registry's lifetime. */
|
|
165
|
+
signals: number;
|
|
166
|
+
/** Number of computeds created in this registry's lifetime. */
|
|
167
|
+
computeds: number;
|
|
168
|
+
/** Number of effects currently alive (decrements on dispose). */
|
|
169
|
+
effects: number;
|
|
170
|
+
/** Number of dependency links currently in use. */
|
|
171
|
+
activeLinks: number;
|
|
172
|
+
/** Dependency links available in the pool (ledger-based: `linkPoolCapacity - activeLinks`). */
|
|
173
|
+
pooledLinks: number;
|
|
174
|
+
/** Link-pool capacity ledger. Doubles under the `"grow"` policy; under `"lazy"`
|
|
175
|
+
* prealloc it may exceed the count of physically constructed links. */
|
|
176
|
+
linkPoolCapacity: number;
|
|
177
|
+
/** Node-pool capacity ledger. Doubles under the `"grow"` policy; under `"lazy"`
|
|
178
|
+
* prealloc it may exceed the count of physically constructed nodes. */
|
|
179
|
+
nodePoolCapacity: number;
|
|
180
|
+
/** Number of nodes currently allocated (signals + computeds + alive effects). */
|
|
181
|
+
activeNodes: number;
|
|
182
|
+
/**
|
|
183
|
+
* Cumulative count of every node acquired over the registry's life -- whether
|
|
184
|
+
* popped from the free list or freshly constructed during a pool-growth chunk.
|
|
185
|
+
* Monotonic; reset only by {@link Registry.destroy}. The true total ever handed
|
|
186
|
+
* out, not the live count (`activeNodes` is the live gauge). Added in 1.4.0.
|
|
187
|
+
*/
|
|
188
|
+
totalAllocations: number;
|
|
189
|
+
/**
|
|
190
|
+
* Cumulative count of every node returned to the pool (`disposeNode`). Monotonic;
|
|
191
|
+
* reset only by {@link Registry.destroy}. In a quiescent registry
|
|
192
|
+
* `totalAllocations - totalDisposals === activeNodes`. Added in 1.4.0.
|
|
193
|
+
*/
|
|
194
|
+
totalDisposals: number;
|
|
195
|
+
/**
|
|
196
|
+
* Cumulative count of pool-growth chunks -- incremented whenever a node *or* link
|
|
197
|
+
* refill pushes capacity past its current ledger. Nonzero after warm-up means the
|
|
198
|
+
* initial pool was undersized and grew at runtime; an eager pool sized for its
|
|
199
|
+
* workload keeps this at 0. Reset only by {@link Registry.destroy}. Added in 1.4.0.
|
|
200
|
+
*/
|
|
201
|
+
poolGrowths: number;
|
|
202
|
+
/**
|
|
203
|
+
* Cumulative count of effect-flush drain passes. Advances once per pass, only
|
|
204
|
+
* while a mutation-hook listener is attached (gated by the same `mutationHook !==
|
|
205
|
+
* null` check that admits opcodes 6 and 7); frozen otherwise, so the steady-state
|
|
206
|
+
* write path is byte-identical to 1.5.0. Combined with `totalAllocations` and
|
|
207
|
+
* `poolGrowths`, lets devtools chart flush activity alongside allocation rate
|
|
208
|
+
* without the engine itself computing rates. Reset by {@link Registry.destroy}.
|
|
209
|
+
* Added in 1.6.0.
|
|
210
|
+
*/
|
|
211
|
+
flushPasses: number;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// --- Observer-lifecycle introspection (1.1.4) ---------------------------------
|
|
215
|
+
|
|
216
|
+
/** Whether a described node is a signal, a computed, or an effect. */
|
|
217
|
+
export type NodeKind = "signal" | "computed" | "effect";
|
|
218
|
+
|
|
219
|
+
/** Non-perturbing snapshot of a graph neighbour yielded by the `forEach*` walkers. */
|
|
220
|
+
export interface NodeDescriptor {
|
|
221
|
+
/** Stable per-allocation node id (1.1.5+). Dedupe key for graph traversal, and the
|
|
222
|
+
* re-walk handle: a descriptor may be passed back into forEachObserver/forEachSource. */
|
|
223
|
+
id: number;
|
|
224
|
+
kind: NodeKind;
|
|
225
|
+
/** The node's current value (last stored/computed value; an effect's is its body return). */
|
|
226
|
+
value: unknown;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Transition callbacks for {@link Registry.observeObservers}. */
|
|
230
|
+
export interface ObserveObserversHooks {
|
|
231
|
+
/** Fired on the 0->1 observer transition (after registration). */
|
|
232
|
+
onConnect?: () => void;
|
|
233
|
+
/** Fired on the 1->0 observer transition. */
|
|
234
|
+
onDisconnect?: () => void;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Stops an {@link Registry.observeObservers} subscription. Idempotent. */
|
|
238
|
+
export type Unobserve = () => void;
|
|
239
|
+
|
|
240
|
+
/** Anything carrying a node identity that the introspection surface can read. */
|
|
241
|
+
export type ReactiveHandle = Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any>;
|
|
242
|
+
|
|
243
|
+
// --- Graph-mutation hook (1.2.1) ----------------------------------------------
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Opcode passed as the first argument to a {@link GraphMutationListener}.
|
|
247
|
+
*
|
|
248
|
+
* - `1` node create. `(intA, intB) = (node.id, node.flags)`.
|
|
249
|
+
* - `2` node dispose. `(intA, intB) = (node.id, node.flags)` -- fires for every node
|
|
250
|
+
* disposed, including cascaded owner-tree children.
|
|
251
|
+
* - `3` link add. `(intA, intB) = (source.id, target.id)`.
|
|
252
|
+
* - `4` link remove. `(intA, intB) = (source.id, target.id)` -- `-1` if the link
|
|
253
|
+
* was already nulled (defensive, rare).
|
|
254
|
+
* - `5` recompute. `(intA, intB) = (node.id, 0)` -- fires just before an effect
|
|
255
|
+
* re-run or a computed re-eval.
|
|
256
|
+
*/
|
|
257
|
+
export type GraphMutationOpcode = 1 | 2 | 3 | 4 | 5;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Listener registered with {@link Registry.onGraphMutation}. Called synchronously
|
|
261
|
+
* inside each mutation point with three integers -- no objects allocated.
|
|
262
|
+
*
|
|
263
|
+
* **Contract: observe only.** Listeners MUST NOT throw and MUST NOT mutate the
|
|
264
|
+
* graph from inside the callback. Both will corrupt the engine's state. Wrap any
|
|
265
|
+
* downstream work in a microtask if it could touch the registry.
|
|
266
|
+
*/
|
|
267
|
+
export type GraphMutationListener = (opcode: GraphMutationOpcode, intA: number, intB: number) => void;
|
|
268
|
+
|
|
269
|
+
/** Idempotent unsubscriber returned by {@link Registry.onGraphMutation}. */
|
|
270
|
+
export type GraphMutationUnsubscribe = () => void;
|
|
271
|
+
|
|
272
|
+
// --- Errors -------------------------------------------------------------------
|
|
273
|
+
|
|
274
|
+
/** Thrown when a pool ceiling is hit. */
|
|
275
|
+
export class CapacityError extends Error {
|
|
276
|
+
readonly name: "CapacityError";
|
|
277
|
+
readonly kind: "nodes" | "links";
|
|
278
|
+
readonly capacity: number;
|
|
279
|
+
constructor(kind: "nodes" | "links", capacity: number);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// --- Registry -----------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
export interface RegistryConfig {
|
|
285
|
+
/** Initial node-pool capacity (a ledger under `prealloc: "lazy"`). Default: 1024. */
|
|
286
|
+
maxNodes?: number;
|
|
287
|
+
/** Initial link-pool capacity (a ledger under `prealloc: "lazy"`). Default: `maxNodes * 4`. */
|
|
288
|
+
maxLinks?: number;
|
|
289
|
+
/**
|
|
290
|
+
* Pool population strategy. Default: `"eager"`.
|
|
291
|
+
* - `"eager"`: construct the full `maxNodes` / `maxLinks` pools up front.
|
|
292
|
+
* Deterministic latency -- zero allocation inside any subsequent hot path
|
|
293
|
+
* (the contract for render loops, game ticks, and extension frame budgets),
|
|
294
|
+
* at the cost of a larger resident heap that every major GC traces.
|
|
295
|
+
* - `"lazy"`: treat `maxNodes` / `maxLinks` as capacity ledgers and construct
|
|
296
|
+
* nodes/links on first demand, recycling through the free lists thereafter.
|
|
297
|
+
* Smaller heap, faster cold start, lighter GC marking; identical zero-GC
|
|
298
|
+
* steady state after warm-up. Prefer for footprint-sensitive or short-lived
|
|
299
|
+
* registries.
|
|
300
|
+
*/
|
|
301
|
+
prealloc?: "eager" | "lazy";
|
|
302
|
+
/**
|
|
303
|
+
* Behaviour when a pool is exhausted. Default: `"throw"`.
|
|
304
|
+
* - `"throw"`: throw {@link CapacityError} immediately when the pool is full.
|
|
305
|
+
* - `"grow"`: extend the pool on demand. Growth is chunked and incremental
|
|
306
|
+
* (contiguous runs of up to 1024 links / 256 nodes per free-list miss),
|
|
307
|
+
* not a single doubling burst, so any one growth pause stays bounded. The
|
|
308
|
+
* capacity ledger still doubles, keeping {@link RegistryStats} semantics
|
|
309
|
+
* unchanged. Link growth is bounded by a hard ceiling of `maxLinks * 16`.
|
|
310
|
+
*/
|
|
311
|
+
onCapacityExceeded?: "throw" | "grow";
|
|
312
|
+
/** Max effect-queue drain passes before a flush-cycle `Error` (message prefixed `"CycleError:"`) is thrown. Default: 100. */
|
|
313
|
+
maxFlushPasses?: number;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Method surface of {@link Registry}; see that type for the full contract. */
|
|
317
|
+
interface RegistryMembers {
|
|
318
|
+
signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
|
|
319
|
+
computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
|
|
320
|
+
effect(fn: EffectBody, opts?: EffectOptions): Dispose;
|
|
321
|
+
/** Allocation-light, non-callable signal (1.5.0). See {@link SignalBox}. */
|
|
322
|
+
signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
323
|
+
/** Allocation-light, non-callable computed (1.5.0). See {@link ComputedBox}. */
|
|
324
|
+
computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
325
|
+
/**
|
|
326
|
+
* Run `fn` in a detached ownership scope (1.5.0). Effects/computeds created
|
|
327
|
+
* directly in `fn` are NOT adopted by the enclosing owner, so they survive
|
|
328
|
+
* the enclosing effect's re-runs and disposal -- the caller owns their
|
|
329
|
+
* lifecycle (`fn` typically returns a disposer or the created handle). Both
|
|
330
|
+
* ownership and tracking are detached for the duration of `fn`; inner
|
|
331
|
+
* effect/computed bodies still establish their own scopes. The ownership
|
|
332
|
+
* escape hatch for lazily spawning a long-lived node from inside a consumer
|
|
333
|
+
* effect (e.g. a query watcher). Returns whatever `fn` returns.
|
|
334
|
+
*/
|
|
335
|
+
createRoot<T>(fn: () => T): T;
|
|
336
|
+
/**
|
|
337
|
+
* Run `fn(dispose)` in a detached, untracked scope and return whatever `fn`
|
|
338
|
+
* returns (1.6.0). The single `dispose` argument cascade-disposes every effect
|
|
339
|
+
* and computed created inside `fn`. Lifecycle complement to {@link createRoot}:
|
|
340
|
+
* `createRoot` only *detaches* (caller must dispose each child by hand),
|
|
341
|
+
* `createScope` *adopts*, so one disposer tears down a subtree of unknown shape
|
|
342
|
+
* -- the per-item lifecycle a keyed-list or scene reconciler needs. Plain
|
|
343
|
+
* signals created directly in `fn` are NOT adopted (consistent with the 1.2.0
|
|
344
|
+
* ownership rule); computeds and effects are. The owner never re-runs, so
|
|
345
|
+
* direct-body reads in `fn` are untracked; reactive bindings belong in inner
|
|
346
|
+
* effect/computed bodies. A scope created inside a consumer effect SURVIVES
|
|
347
|
+
* that consumer's re-run -- the reconciler-critical detach property. The
|
|
348
|
+
* disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
|
|
349
|
+
* resolves to the owner effect under `describe` / `nodeId` / `forEachOwned`.
|
|
350
|
+
*/
|
|
351
|
+
createScope<T>(fn: (dispose: () => void) => T): T;
|
|
352
|
+
/**
|
|
353
|
+
* Universal disposal for anything created by this registry: signals,
|
|
354
|
+
* computeds, boxes, or effect dispose handles. Cross-registry calls are
|
|
355
|
+
* silent no-ops (each registry owns its own private node-identity Symbol).
|
|
356
|
+
* Passing an unrelated value is also a safe no-op.
|
|
357
|
+
*/
|
|
358
|
+
dispose(api: Disposable): void;
|
|
359
|
+
batch<T>(fn: () => T): T;
|
|
360
|
+
untrack<T>(fn: () => T): T;
|
|
361
|
+
/** True iff a read RIGHT NOW would record a dependency on this registry.
|
|
362
|
+
* False inside `untrack`, `subscribe` callbacks, `onCleanup` bodies, and
|
|
363
|
+
* outside any observer. Use for lazy-allocation wrappers like lite-store. */
|
|
364
|
+
isTracking(): boolean;
|
|
365
|
+
/** O(1): does this source have at least one live observer right now? A `peek` does not count. */
|
|
366
|
+
hasObservers(handle: ReactiveHandle): boolean;
|
|
367
|
+
/** Auto-pause hook: fires `onConnect` on the 0->1 observer transition and `onDisconnect`
|
|
368
|
+
* on 1->0, after registration (transition-only -- no immediate fire if already observed).
|
|
369
|
+
* Re-tracking a persistently-read source does not churn. Returns an idempotent unobserve.
|
|
370
|
+
* @throws TypeError if `handle` is not a reactive handle. */
|
|
371
|
+
observeObservers(handle: ReactiveHandle, hooks?: ObserveObserversHooks): Unobserve;
|
|
372
|
+
/** Walk the observers (subscribers) of `handle`, newest-first. No-op on a non-handle. */
|
|
373
|
+
forEachObserver(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
374
|
+
/** Walk the sources (dependencies) of `handle`. No-op on a non-handle. */
|
|
375
|
+
forEachSource(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
376
|
+
/** Walk the owned children of `handle` -- nodes whose lifetime is bound to this
|
|
377
|
+
* one by the 1.2 owner tree (1.2.1+). Top-level handles and signals have no
|
|
378
|
+
* owned children; effects/computeds may own nested observers created inside
|
|
379
|
+
* their bodies. No-op on a non-handle or stale handle. */
|
|
380
|
+
forEachOwned(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
381
|
+
/** Descriptor of `handle`'s owner, or `undefined` for top-level handles, stale
|
|
382
|
+
* handles, or non-handles (1.2.1+). The owner is the effect or computed inside
|
|
383
|
+
* whose body `handle` was created -- the node that will cascade-dispose it
|
|
384
|
+
* on re-run or explicit dispose. */
|
|
385
|
+
ownerOf(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
386
|
+
/** Stable node id of `handle` (1.1.5+), or undefined for a non-handle or stale handle. */
|
|
387
|
+
nodeId(handle: ReactiveHandle): number | undefined;
|
|
388
|
+
/** The own descriptor of `handle` (1.1.5+), or undefined for a non-handle or stale handle.
|
|
389
|
+
* Re-walkable: the returned descriptor may be passed back into forEachObserver/
|
|
390
|
+
* forEachSource/forEachOwned/ownerOf. Descriptors are gen-stamped (1.2.1+): a
|
|
391
|
+
* descriptor obtained pre-recycle goes stale and walks as undefined post-recycle. */
|
|
392
|
+
describe(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
393
|
+
/** Register a single graph-mutation listener (1.2.1+). Replaces any existing
|
|
394
|
+
* listener and returns an unsubscribe that restores the previous one on call.
|
|
395
|
+
* Listener is invoked synchronously at each mutation point with three integers:
|
|
396
|
+
* `(opcode, intA, intB)` -- see {@link GraphMutationOpcode}. Cost when no
|
|
397
|
+
* listener is registered: one branch-predicted `null` check per mutation point.
|
|
398
|
+
* @throws TypeError if `fn` is not a function or null. */
|
|
399
|
+
onGraphMutation(fn: GraphMutationListener | null): GraphMutationUnsubscribe;
|
|
400
|
+
onCleanup(fn: () => void): void;
|
|
401
|
+
stats(): RegistryStats;
|
|
402
|
+
/** Reset everything: nodes, links, queues, global clock. Outstanding dispose
|
|
403
|
+
* closures become safe no-ops. Outstanding read/set closures still reference
|
|
404
|
+
* pool slots -- they will silently misbehave; use a fresh registry afterwards. */
|
|
405
|
+
destroy(): void;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Isolated reactive graph. Created by {@link createRegistry}.
|
|
410
|
+
*
|
|
411
|
+
* From 1.9.0 the registry carries `[Symbol.dispose]` (-> `destroy`), so
|
|
412
|
+
* `using r = createRegistry()` resets its pools at block exit.
|
|
413
|
+
*/
|
|
414
|
+
export type Registry = RegistryMembers & ExplicitDisposeSlot;
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Create an isolated reactive registry.
|
|
418
|
+
*
|
|
419
|
+
* @example
|
|
420
|
+
* const r = createRegistry({ maxNodes: 4096, onCapacityExceeded: "grow" });
|
|
421
|
+
* const count = r.signal(0);
|
|
422
|
+
* r.effect(() => console.log(count()));
|
|
423
|
+
*/
|
|
424
|
+
export function createRegistry(config?: RegistryConfig): Registry;
|
|
425
|
+
|
|
426
|
+
/** Replace the default registry backing the top-level helpers. */
|
|
427
|
+
export function setDefaultRegistry(registry: Registry): void;
|
|
428
|
+
|
|
429
|
+
// --- Top-level helpers (delegate to default registry) ------------------------
|
|
430
|
+
|
|
431
|
+
export function signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
|
|
432
|
+
export function computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
|
|
433
|
+
export function effect(fn: EffectBody, opts?: EffectOptions): Dispose;
|
|
434
|
+
/** Allocation-light, non-callable signal (1.5.0), bound to the default registry. See {@link SignalBox}. */
|
|
435
|
+
export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
436
|
+
/** Allocation-light, non-callable computed (1.5.0), bound to the default registry. See {@link ComputedBox}. */
|
|
437
|
+
export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
438
|
+
/** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
|
|
439
|
+
export function createRoot<T>(fn: () => T): T;
|
|
440
|
+
/** Run `fn(dispose)` in a detached, adopting scope (1.6.0), bound to the default registry. See {@link Registry.createScope}. */
|
|
441
|
+
export function createScope<T>(fn: (dispose: () => void) => T): T;
|
|
442
|
+
/** Universal disposal -- see {@link Registry.dispose}. */
|
|
443
|
+
export function dispose(api: Disposable): void;
|
|
444
|
+
export function batch<T>(fn: () => T): T;
|
|
445
|
+
export function untrack<T>(fn: () => T): T;
|
|
446
|
+
/** Top-level binding of {@link Registry.isTracking} against the default registry. */
|
|
447
|
+
export function isTracking(): boolean;
|
|
448
|
+
/** Top-level binding of {@link Registry.hasObservers}. */
|
|
449
|
+
export function hasObservers(handle: ReactiveHandle): boolean;
|
|
450
|
+
/** Top-level binding of {@link Registry.observeObservers}. */
|
|
451
|
+
export function observeObservers(handle: ReactiveHandle, hooks?: ObserveObserversHooks): Unobserve;
|
|
452
|
+
/** Top-level binding of {@link Registry.forEachObserver}. */
|
|
453
|
+
export function forEachObserver(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
454
|
+
/** Top-level binding of {@link Registry.forEachSource}. */
|
|
455
|
+
export function forEachSource(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
456
|
+
/** Top-level binding of {@link Registry.forEachOwned} (1.2.1+). */
|
|
457
|
+
export function forEachOwned(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
458
|
+
/** Top-level binding of {@link Registry.ownerOf} (1.2.1+). */
|
|
459
|
+
export function ownerOf(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
460
|
+
/** Top-level binding of {@link Registry.nodeId}. */
|
|
461
|
+
export function nodeId(handle: ReactiveHandle): number | undefined;
|
|
462
|
+
/** Top-level binding of {@link Registry.describe}. */
|
|
463
|
+
export function describe(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
464
|
+
/** Top-level binding of {@link Registry.onGraphMutation} (1.2.1+). */
|
|
465
|
+
export function onGraphMutation(fn: GraphMutationListener | null): GraphMutationUnsubscribe;
|
|
466
|
+
export function onCleanup(fn: () => void): void;
|
|
467
|
+
export function stats(): RegistryStats;
|
|
468
|
+
export function destroy(): void;
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Configuration options for the watch utility.
|
|
472
|
+
*/
|
|
473
|
+
export interface WatchOptions {
|
|
474
|
+
/** * If true, fires the callback immediately upon registration
|
|
475
|
+
* with `oldValue` set to `undefined`.
|
|
476
|
+
*/
|
|
477
|
+
immediate?: boolean;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Track a reactive source and run a callback whenever its projected value
|
|
482
|
+
* changes. The callback receives `(newValue, oldValue, stop)` -- the third
|
|
483
|
+
* argument is a dispose function that can be called from inside the callback
|
|
484
|
+
* to terminate the watcher.
|
|
485
|
+
*
|
|
486
|
+
* Internal reads inside the callback are untracked.
|
|
487
|
+
*
|
|
488
|
+
* Uses `Object.is` to guard against the raw-getter case where a dep mutation
|
|
489
|
+
* fires the effect but the projected value is unchanged.
|
|
490
|
+
*
|
|
491
|
+
* @param source Reactive read function.
|
|
492
|
+
* @param callback Called with the new and previous values plus a stop handle.
|
|
493
|
+
* @param options `immediate: true` runs the callback once on registration
|
|
494
|
+
* with `oldValue = undefined`.
|
|
495
|
+
* @returns Dispose function. Idempotent and safe to call at any time, including
|
|
496
|
+
* synchronously during the immediate callback.
|
|
497
|
+
*/
|
|
498
|
+
export function watch<T>(
|
|
499
|
+
source: () => T,
|
|
500
|
+
callback: (newValue: T, oldValue: T | undefined, stop: () => void) => void,
|
|
501
|
+
options?: { immediate?: boolean }
|
|
502
|
+
): () => void;
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Fire `callback` exactly once when `predicate` first returns a truthy value,
|
|
506
|
+
* then auto-dispose. If `predicate` is already truthy at registration, fires
|
|
507
|
+
* synchronously.
|
|
508
|
+
*
|
|
509
|
+
* @param predicate Reactive read function; callback fires when truthy.
|
|
510
|
+
* @param callback Called once when predicate first truthy. Reads inside are untracked.
|
|
511
|
+
* @returns Dispose function. Call before predicate fires to cancel; idempotent.
|
|
512
|
+
*/
|
|
513
|
+
export function when(
|
|
514
|
+
predicate: () => unknown,
|
|
515
|
+
callback: () => void
|
|
516
|
+
): () => void;
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Promise-returning variant of {@link when}. The returned promise resolves
|
|
520
|
+
* when `predicate` first returns a truthy value.
|
|
521
|
+
*
|
|
522
|
+
* ! **HOT-PATH WARNING -- DO NOT USE PER FRAME.** This function calls
|
|
523
|
+
* `new Promise(...)`, which is a heap allocation (one Promise object plus
|
|
524
|
+
* executor closure plus internal infrastructure per call). Promises require
|
|
525
|
+
* heap allocation by the language spec -- this cost is unavoidable.
|
|
526
|
+
*
|
|
527
|
+
* **Use for:** high-level scene/UI orchestration, boot sequences, awaiting
|
|
528
|
+
* user input or network state, level transitions. Anything that runs once
|
|
529
|
+
* or rarely.
|
|
530
|
+
*
|
|
531
|
+
* **NEVER use for:** per-frame entity updates, render-loop logic, animation
|
|
532
|
+
* tick handlers. For zero-GC hot-path logic use {@link when} with a callback.
|
|
533
|
+
*
|
|
534
|
+
* Note: this promise never rejects. If the predicate never becomes truthy,
|
|
535
|
+
* the promise never settles. Wrap in `Promise.race` for timeout semantics.
|
|
536
|
+
*
|
|
537
|
+
* @param predicate Reactive read function; resolves promise when truthy.
|
|
538
|
+
* @returns Promise that resolves when predicate first truthy.
|
|
539
|
+
*/
|
|
540
|
+
export function whenAsync(
|
|
541
|
+
predicate: () => unknown
|
|
542
|
+
): Promise<void>;
|
package/Signal.js
CHANGED
package/llms.txt
CHANGED
|
@@ -53,7 +53,57 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
53
53
|
|
|
54
54
|
## Version notes
|
|
55
55
|
|
|
56
|
-
- **1.9.0-preview.
|
|
56
|
+
- **1.9.0-preview.5** (current): a **packaging-only cut** -- the engine is
|
|
57
|
+
behaviourally unchanged from preview.4 (`Signal.js` differs only in its header
|
|
58
|
+
banner string). Two fixes make the tarball honour its own manifest. (1) The
|
|
59
|
+
promised **`Signal.d.ts` now ships**: since 1.5.0 `package.json` has advertised
|
|
60
|
+
`"types": "./Signal.d.ts"` and listed it in `files[]`, but the 1.9.0 line packed
|
|
61
|
+
a `types` pointer to a file that did not exist, so `tsc` consumers got no types.
|
|
62
|
+
The declaration is modelled on 1.8.0's (1.9.0's export surface is byte-identical
|
|
63
|
+
to 1.8.0's) plus the 1.9.0 delta: `[Symbol.dispose](): void` typed on exactly the
|
|
64
|
+
handles the engine stamps -- both box prototypes, every `Dispose` function
|
|
65
|
+
(effect / `.subscribe()` / `createScope`), and the `Registry` (-> `destroy`) --
|
|
66
|
+
with callable `Signal`/`Computed` handles left UNSTAMPED, matching the engine, so
|
|
67
|
+
`using r = createRegistry()`, `using box = signalBox(0)`, and `using stop =
|
|
68
|
+
effect(fn)` all typecheck. The `[Symbol.dispose]` slot is behind a `lib`-conditional
|
|
69
|
+
helper that resolves to `{}` on TypeScript `lib` targets predating `Symbol.dispose`,
|
|
70
|
+
so it never forces a `lib` upgrade on type-only consumers (verified: `using`
|
|
71
|
+
compiles under `esnext.disposable`; a type-only consumer compiles clean under
|
|
72
|
+
`ES2020`). (2) The **`Signal.js` header banner** is reconciled to `preview.5`
|
|
73
|
+
(preview.2 through preview.4 carried a stale `preview.2` banner in the comment).
|
|
74
|
+
No API, torture, or test change: torture stays 22/22, unit **512/511/0/1** under
|
|
75
|
+
`npm test` and **520/519/0/1** under `npm run test:gc`. Drop-in over preview.4.
|
|
76
|
+
|
|
77
|
+
- **1.9.0-preview.4**: a **version-only re-tag** over preview.3. `Signal.js` is
|
|
78
|
+
byte-identical to preview.3 past the header banner; no engine, torture, test, API,
|
|
79
|
+
or packaging change (the missing `Signal.d.ts` and the stale `preview.2` banner
|
|
80
|
+
were both still present -- fixed in preview.5). Recorded for continuity.
|
|
81
|
+
|
|
82
|
+
- **1.9.0-preview.3**: the **verification-surface parity cut**. No engine
|
|
83
|
+
change from preview.2 -- `Signal.js` is byte-identical (at this cut the header
|
|
84
|
+
banner still read `preview.2`; reconciled in preview.5) and `bench/torture/` stays
|
|
85
|
+
out of `files[]`; for consumers preview.3 is preview.2 plus a version number. It brings the torture suite to full
|
|
86
|
+
parity with the shipped 1.4.4 canonical: a parity port of the last three scenarios
|
|
87
|
+
-- `error-torture` (throwing effect bodies: single re-thrown unwrapped, two-or-more
|
|
88
|
+
aggregated into an `AggregateError` carrying exactly those errors, survivors still
|
|
89
|
+
run, buffer drains over 4096 cycles), `deep-chain-torture` (`pullComputed`
|
|
90
|
+
recursion fails closed with a `RangeError` at ramped depth while the iterative push
|
|
91
|
+
path stays open), and `zerogc-torture` (the zero-GC gate via
|
|
92
|
+
`@zakkster/lite-gc-profiler` at `maxBytesPerCall: 0` / `maxMajor: 0` /
|
|
93
|
+
`maxPauseMs: 2` plus exact `stats()` deltas and an activating `churn-box`,
|
|
94
|
+
mutation-verified by `ZEROGC_BREAK=1`) -- a `grow-ceiling` section on
|
|
95
|
+
`capacity-torture` (the 16x link ceiling terminating exactly at `maxLinks*16`), an
|
|
96
|
+
`Int32Array` value-oracle added to all three soaks (so they assert value-correctness,
|
|
97
|
+
not just resources, at zero per-tick allocation), and a new
|
|
98
|
+
`test/30-throwing-equals.test.mjs` pinning a throwing user `equals` at all five
|
|
99
|
+
invocation sites (3 callable + 2 signalBox `boxSet`). This takes the suite to **22
|
|
100
|
+
scenarios (19 semantic + 3 soak)**, all 19 semantic executing on this engine with
|
|
101
|
+
no feature-skips (the first engine to run the complete superset). Verified green:
|
|
102
|
+
torture 22/22; unit **512 tests, 511 pass, 0 fail, 1 skip** under `npm test` and
|
|
103
|
+
**520 tests, 519 pass, 0 fail, 1 skip** under `npm run test:gc` (with the sibling
|
|
104
|
+
`@zakkster/lite-devtools` the `test/25` rig needs). Drop-in over preview.2.
|
|
105
|
+
|
|
106
|
+
- **1.9.0-preview.2**: the **explicit-resource-management minor**. A
|
|
57
107
|
single-feature engine cut: `Symbol.dispose` is stamped at five sites -- the
|
|
58
108
|
registry (-> `destroy`), an effect's stop handle (-> `stop`), a `createScope`
|
|
59
109
|
disposer, a `createRoot` disposer, and both box prototypes (-> `dispose`) -- so
|
|
@@ -66,11 +116,7 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
66
116
|
added two semantic scenarios -- `owner-torture` (`getOwner`/`runWithOwner`
|
|
67
117
|
capture-restore) and `lifecycle-torture` (`createRoot` detachment + the direct
|
|
68
118
|
`destroy` reset, both previously unexercised) -- bringing the suite to **19
|
|
69
|
-
scenarios (16 semantic + 3 soak)
|
|
70
|
-
no feature-skips (the first engine to run the complete superset). Verified green:
|
|
71
|
-
torture 19/19; unit **499 tests, 479 pass, 0 fail, 1 skip** (SSR N/A) -- 498 pass
|
|
72
|
-
with the sibling `@zakkster/lite-devtools` the 19-test `test/25` rig needs.
|
|
73
|
-
Drop-in over 1.8.0.
|
|
119
|
+
scenarios (16 semantic + 3 soak)**. Drop-in over 1.8.0.
|
|
74
120
|
|
|
75
121
|
- **1.8.0**: the **effect-cleanup-return minor**. An EFFECT body may `return` a
|
|
76
122
|
cleanup function (Solid/Vue/Reflex-compatible), run at the same points as
|
|
@@ -728,7 +774,7 @@ function dumpOwnerTree(handle, depth = 0) {
|
|
|
728
774
|
- `bench/benchmark.mjs` -- anti-DCE throughput harness (ops/s; results.txt).
|
|
729
775
|
- `bench/benchmarkReactive.mjs` -- cross-framework reactivity suite vs alien-signals, preact, vue-reactivity, solid (resultsReactive.txt).
|
|
730
776
|
- `bench/dispose-recycle.mjs` -- 1.2.2 targeted microbench: create/dispose/recreate cycle (the free-list invariant audit target).
|
|
731
|
-
- `bench/torture/` -- the complete **
|
|
777
|
+
- `bench/torture/` -- the complete **22-scenario suite (19 semantic + 3 soak)** behind one runner (`run.mjs`), two groups. Every scenario feature-detects and SKIPS cleanly below the engine version that introduces its feature; on the **1.9.0 engine ALL 19 semantic execute with zero skips** -- the first engine to run the whole superset (`dispose` was the last feature gate). `semantic` (deterministic, fast, asserts on MEANING; CI on every commit): `oracle-fuzzer` (every computed vs an independent uncached reference, 400 seeds x 120 ops), `glitch-hunter` (glitch freedom + exact wakeups), `work-accounting` (minimum body-execution counts over 10 topologies), `op-accounting` (structural work from the `onGraphMutation` opcode lane), `introspect-torture` (1.6.0: read-only introspection surface -- walk-agreement + ABA gen-stamp guard, `forEachOwned` pinned to an exact owned count), `concurrent-storm` (8 reentrancy / flush-ordering contracts), `scheduler-storm` (gen-bound thunk ABA guard, FLAG_QUEUED coalescing, throwing-scheduler containment), `box-torture` (1.5.0: signalBox/computedBox interop via oracle differential fuzz), `scope-torture` (1.6.0: `createScope` adoption + disposal-crash fuzz), `owner-torture` (1.6.0: `getOwner`/`runWithOwner` capture-restore -- gen-stamped handle, adoption inside `runWithOwner`, cascade-dispose), `lifecycle-torture` (`createRoot` 1.5.0+ detachment + the direct `destroy` 1.4.0+ reset -- both previously unexercised by any scenario), `async-torture` (watch/when/whenAsync + a 300-seed projection-guard storm), `capacity-torture` (the fail-closed pool boundary + CapacityError + the 16x grow ceiling), `error-torture` (throwing effect bodies under flush: a single throw re-thrown unwrapped, 2+ aggregated into an AggregateError carrying exactly those errors, the survivor still runs, and the pre-allocated error buffer drains to baseline over 4096 throw/clean cycles), `deep-chain-torture` (pullComputed recursion fails closed with a RangeError at a ramped depth <= 100000 while the heap-iterative effect-cascade push path stays open at the same depth), `flush-torture` (1.7.0: the three `flushStrategy` modes by cross-strategy differential + `.subscribe()`), `cleanup-return-torture` (1.8.0: an effect's returned cleanup -- timing, compose order, self-dispose guard, computed exclusion), `dispose-torture` (1.9.0: `Symbol.dispose` stamped at five sites driven through the TC39 `using` path, idempotent disposal, feature-detected via the box-prototype stamp), `zerogc-torture` (the zero-GC claim as a re-runnable gate via @zakkster/lite-gc-profiler -- measureAllocs/checkAllocs at `maxBytesPerCall: 0` + measureOps/checkNoGc at `maxMajor: 0`/`maxPauseMs: 2` + `stats()` poolGrowths/totalAllocations deltas, plus create/dispose churn on both callable and signalBox; the `ZEROGC_BREAK=1` self-test proves the gate rejects a planted allocation). `soak` (wall-clock bound, asserts on RESOURCES AND VALUE-CORRECTNESS; nightly): `graph-fuzzer`, `scheduler-bench`, `torture-soak` -- exit 0 iff zero errors AND post-teardown pool at or below its leaf-only floor AND the JIT sink (a module-scoped int32) advanced AND a once-allocated `Int32Array` shadow oracle (rotating fixed window per tick, full sweep at teardown) confirms every writable signal read back its last written value. Runner spawns each scenario as a child process and passes `--expose-gc` unconditionally. Scripts: `npm run torture`, `torture:semantic`, `torture:soak`.
|
|
732
778
|
- `bench/run-all.sh` + `bench/aggregate.mjs` -- cold-process-per-engine protocol + per-scenario aggregation.
|
|
733
779
|
- `harness/run.mjs` -- dispatcher for the run-on-demand probes (smoke, field, dispose, churn, owner, creation, perf, burst, pull, toe, all).
|
|
734
780
|
- `harness/smoke.mjs` -- 1.7 flushStrategy semantics (eager/sab/manual) + `flush()`, and the 1.8 effect-cleanup-return contract (fires before re-run + on dispose, composes with onCleanup in call order, non-function returns ignored, computed-returning-a-function still yields the VALUE). ASSERTS, so it fails loudly on a regression. First in `harness:all` and `verify`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zakkster/lite-signal",
|
|
3
|
-
"version": "1.9.0-preview.
|
|
3
|
+
"version": "1.9.0-preview.5",
|
|
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",
|
|
@@ -45,7 +45,10 @@
|
|
|
45
45
|
"profile:burst": "node --expose-gc harness/burst-dag.mjs ./Signal.js",
|
|
46
46
|
"profile:pull": "node --expose-gc harness/pull-stress.mjs",
|
|
47
47
|
"gate": "node harness/VersionMatrix/pre-publish.mjs",
|
|
48
|
-
"verify": "npm test && npm run harness:smoke && npm run bench"
|
|
48
|
+
"verify": "npm test && npm run harness:smoke && npm run bench",
|
|
49
|
+
"torture": "node bench/torture/run.mjs",
|
|
50
|
+
"torture:semantic": "node bench/torture/run.mjs --group semantic",
|
|
51
|
+
"torture:soak": "node bench/torture/run.mjs --group soak"
|
|
49
52
|
},
|
|
50
53
|
"keywords": [
|
|
51
54
|
"signal",
|
|
@@ -83,6 +86,7 @@
|
|
|
83
86
|
"sideEffects": false,
|
|
84
87
|
"devDependencies": {
|
|
85
88
|
"@zakkster/lite-devtools": "^1.2.0",
|
|
89
|
+
"@zakkster/lite-gc-profiler": "^1.15.0",
|
|
86
90
|
"@zakkster/lite-profiler": "^1.1.0",
|
|
87
91
|
"@zakkster/lite-profiler-signal": "^1.2.0",
|
|
88
92
|
"@zakkster/lite-signal": "^1.3.0 || >=1.4.0-beta.0 || >=1.6.0-preview.0",
|