@zakkster/lite-signal 1.9.0-preview.4 → 1.9.0-preview.6
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 +87 -0
- package/Signal.d.ts +552 -0
- package/Signal.js +145 -1
- package/llms.txt +32 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,93 @@ 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.6] -- 2026-08-20
|
|
8
|
+
|
|
9
|
+
Backports the **1.4.5 `createRegistry` input validation** (all four findings) onto
|
|
10
|
+
the 1.9.0-preview.5 engine. Supersedes 1.9.0-preview.5. Only `createRegistry`'s *cold*
|
|
11
|
+
construction path changed -- the hot paths are byte-identical and the zero-GC gates
|
|
12
|
+
(`bench/torture/run.mjs` 22/22) are unchanged. If you had a typo in your registry
|
|
13
|
+
config, you will now hear about it.
|
|
14
|
+
|
|
15
|
+
### Added -- createRegistry validates its config (fail closed)
|
|
16
|
+
|
|
17
|
+
- **Bounded eager construction.** `prealloc:"eager"` with a non-finite or absurd
|
|
18
|
+
capacity (`maxNodes:Infinity`, `maxNodes:1e9`) previously ran an unbounded
|
|
19
|
+
construction loop and killed the process with an **uncatchable SIGABRT**. It now
|
|
20
|
+
throws a `TypeError` **by name**, before allocating, gated on `(maxNodes+maxLinks)`
|
|
21
|
+
against a ceiling of `1<<24` (16,777,216) objects. `prealloc:"lazy"` keeps its
|
|
22
|
+
unbounded on-demand ledger, untouched.
|
|
23
|
+
- **Per-option validation by name.** `maxNodes` / `maxLinks` / `maxFlushPasses` must
|
|
24
|
+
be finite integers `>= 1`; `prealloc` must be exactly `"eager"` | `"lazy"`;
|
|
25
|
+
`onCapacityExceeded` must be exactly `"throw"` | `"grow"`. Each bad value throws a
|
|
26
|
+
`TypeError` prefixed `createRegistry: "<option>"` at construction -- not a delayed
|
|
27
|
+
internal `nextFree` TypeError on first use.
|
|
28
|
+
- **Config-shape gate.** A non-object, `null`, or array `config` throws
|
|
29
|
+
`createRegistry: "config"` rather than dying later.
|
|
30
|
+
- **Unknown-key rejection with did-you-mean.** An unrecognized key throws with a
|
|
31
|
+
Levenshtein suggestion (`maxNods` -> `maxNodes`, `preAlloc` -> `prealloc`) instead
|
|
32
|
+
of being silently ignored.
|
|
33
|
+
- **`flushStrategy` stays a first-class option.** It is a recognized key (its own native value-guard is unchanged); only misspelled *keys* are rejected.
|
|
34
|
+
- **`stats()` gains `nodePoolPopulation` / `linkPoolPopulation`** -- the TRUE count
|
|
35
|
+
of physically constructed nodes/links, distinct from the `*Capacity` ledgers. A
|
|
36
|
+
silently mis-set `prealloc` is now observable (population 0 under lazy) instead of
|
|
37
|
+
telemetry-blind. **The one observable API change: `stats()` grows to 14 keys,
|
|
38
|
+
purely additive** -- no existing key changed; only an exact key-*count* assertion
|
|
39
|
+
is affected (updated in `test/03-pool.test.mjs`).
|
|
40
|
+
|
|
41
|
+
### Tests
|
|
42
|
+
|
|
43
|
+
New `test/*-config-validation.test.mjs` adds the full config matrix, the did-you-mean
|
|
44
|
+
cases, the eager ceiling, the population contract, and the three OOM rows as isolated
|
|
45
|
+
child-process cases proving the fixed engine throws + exits 0 under a 256 MB cap where
|
|
46
|
+
the unvalidated engine died.
|
|
47
|
+
|
|
48
|
+
## [1.9.0-preview.5] -- 2026-08-18
|
|
49
|
+
|
|
50
|
+
Packaging-only cut. **The engine is UNCHANGED** -- `Signal.js` is behaviourally
|
|
51
|
+
byte-identical to `preview.4`; the sole `Signal.js` edit is the header banner
|
|
52
|
+
version string (see below). This release makes the published package honour its
|
|
53
|
+
own `package.json`: since 1.5.0 the manifest has advertised `"types":
|
|
54
|
+
"./Signal.d.ts"` and listed `Signal.d.ts` in `files[]`, but the 1.9.0 line
|
|
55
|
+
shipped without the file (`preview.4` and earlier packed a `types` pointer to a
|
|
56
|
+
non-existent declaration, so `tsc` consumers got no types). No API, torture, or
|
|
57
|
+
test change from `preview.4`.
|
|
58
|
+
|
|
59
|
+
### Added -- the missing `Signal.d.ts` (the 1.9.0 type surface)
|
|
60
|
+
|
|
61
|
+
- **`Signal.d.ts`** now ships, modelled on the 1.8.0 declaration (1.9.0's export
|
|
62
|
+
surface is byte-identical to 1.8.0's) plus the 1.9.0 explicit-resource-management
|
|
63
|
+
delta: `[Symbol.dispose](): void` is typed on exactly the handles the engine
|
|
64
|
+
stamps -- both box prototypes (`SignalBox` :1495, `ComputedBox` :1496), every
|
|
65
|
+
`Dispose` function (the shared effect disposer at :1614, reached by `effect()`,
|
|
66
|
+
`.subscribe()`, and the `createScope` disposer at :1853), and the `Registry`
|
|
67
|
+
(-> `destroy`, :2087). Callable value handles (`Signal` / `Computed`) are left
|
|
68
|
+
UNSTAMPED, matching the engine. So `using r = createRegistry()`,
|
|
69
|
+
`using box = signalBox(0)`, and `using stop = effect(fn)` all typecheck.
|
|
70
|
+
- The `[Symbol.dispose]` slot is expressed through a `lib`-conditional helper
|
|
71
|
+
(`ExplicitDisposeSlot`): it resolves to the member only when the ambient
|
|
72
|
+
TypeScript `lib` knows `Symbol.dispose` (`esnext.disposable` -- required to use
|
|
73
|
+
`using` at all), and to `{}` otherwise, so the declaration NEVER forces a `lib`
|
|
74
|
+
upgrade on type-only consumers. Verified: compiles under
|
|
75
|
+
`--lib ES2022,ESNext.Disposable` with `using` on all four shapes; compiles clean
|
|
76
|
+
under `--lib ES2020` for a type-only consumer (zero errors); manual
|
|
77
|
+
`[Symbol.dispose]()` is typed.
|
|
78
|
+
|
|
79
|
+
### Changed -- header banner reconciled to the manifest
|
|
80
|
+
|
|
81
|
+
- **`Signal.js` header banner** now reads `v1.9.0-preview.5`, matching
|
|
82
|
+
`package.json` and this changelog. `preview.2` through `preview.4` shipped a
|
|
83
|
+
stale `preview.2` banner (a cosmetic drift in a comment; no code depended on
|
|
84
|
+
it). No other line of `Signal.js` changed -- torture stays 22/22 and the unit
|
|
85
|
+
suite is unaffected.
|
|
86
|
+
|
|
87
|
+
## [1.9.0-preview.4] -- 2026-08-18
|
|
88
|
+
|
|
89
|
+
Version-only re-tag over `preview.3`. `Signal.js` is byte-identical to
|
|
90
|
+
`preview.3` past the header banner; no engine, torture, test, API, or packaging
|
|
91
|
+
change (the `Signal.d.ts` gap and the stale `preview.2` banner were both still
|
|
92
|
+
present -- both are fixed in `preview.5`). Recorded here for continuity.
|
|
93
|
+
|
|
7
94
|
## [1.9.0-preview.3] -- 2026-08-18
|
|
8
95
|
|
|
9
96
|
Verification-only parity cut. **The engine is UNCHANGED** -- `Signal.js` (2209
|
package/Signal.d.ts
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
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
|
+
/** TRUE node-pool population: the number of `ReactiveNode`s physically constructed
|
|
181
|
+
* (`nodePool.length`), distinct from the `nodePoolCapacity` ledger. Under
|
|
182
|
+
* `prealloc:"lazy"` (or a silently-flipped `prealloc` typo) this stays 0 until
|
|
183
|
+
* first demand while capacity reads the ledger -- so a mis-set `prealloc` is
|
|
184
|
+
* observable here rather than telemetry-blind. Added in the 1.4.5 backport. */
|
|
185
|
+
nodePoolPopulation: number;
|
|
186
|
+
/** TRUE link-pool population: the number of `ReactiveLink`s physically constructed
|
|
187
|
+
* (`linkPool.length`), distinct from the `linkPoolCapacity` ledger. Added in the
|
|
188
|
+
* 1.4.5 backport. */
|
|
189
|
+
linkPoolPopulation: number;
|
|
190
|
+
/** Number of nodes currently allocated (signals + computeds + alive effects). */
|
|
191
|
+
activeNodes: number;
|
|
192
|
+
/**
|
|
193
|
+
* Cumulative count of every node acquired over the registry's life -- whether
|
|
194
|
+
* popped from the free list or freshly constructed during a pool-growth chunk.
|
|
195
|
+
* Monotonic; reset only by {@link Registry.destroy}. The true total ever handed
|
|
196
|
+
* out, not the live count (`activeNodes` is the live gauge). Added in 1.4.0.
|
|
197
|
+
*/
|
|
198
|
+
totalAllocations: number;
|
|
199
|
+
/**
|
|
200
|
+
* Cumulative count of every node returned to the pool (`disposeNode`). Monotonic;
|
|
201
|
+
* reset only by {@link Registry.destroy}. In a quiescent registry
|
|
202
|
+
* `totalAllocations - totalDisposals === activeNodes`. Added in 1.4.0.
|
|
203
|
+
*/
|
|
204
|
+
totalDisposals: number;
|
|
205
|
+
/**
|
|
206
|
+
* Cumulative count of pool-growth chunks -- incremented whenever a node *or* link
|
|
207
|
+
* refill pushes capacity past its current ledger. Nonzero after warm-up means the
|
|
208
|
+
* initial pool was undersized and grew at runtime; an eager pool sized for its
|
|
209
|
+
* workload keeps this at 0. Reset only by {@link Registry.destroy}. Added in 1.4.0.
|
|
210
|
+
*/
|
|
211
|
+
poolGrowths: number;
|
|
212
|
+
/**
|
|
213
|
+
* Cumulative count of effect-flush drain passes. Advances once per pass, only
|
|
214
|
+
* while a mutation-hook listener is attached (gated by the same `mutationHook !==
|
|
215
|
+
* null` check that admits opcodes 6 and 7); frozen otherwise, so the steady-state
|
|
216
|
+
* write path is byte-identical to 1.5.0. Combined with `totalAllocations` and
|
|
217
|
+
* `poolGrowths`, lets devtools chart flush activity alongside allocation rate
|
|
218
|
+
* without the engine itself computing rates. Reset by {@link Registry.destroy}.
|
|
219
|
+
* Added in 1.6.0.
|
|
220
|
+
*/
|
|
221
|
+
flushPasses: number;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// --- Observer-lifecycle introspection (1.1.4) ---------------------------------
|
|
225
|
+
|
|
226
|
+
/** Whether a described node is a signal, a computed, or an effect. */
|
|
227
|
+
export type NodeKind = "signal" | "computed" | "effect";
|
|
228
|
+
|
|
229
|
+
/** Non-perturbing snapshot of a graph neighbour yielded by the `forEach*` walkers. */
|
|
230
|
+
export interface NodeDescriptor {
|
|
231
|
+
/** Stable per-allocation node id (1.1.5+). Dedupe key for graph traversal, and the
|
|
232
|
+
* re-walk handle: a descriptor may be passed back into forEachObserver/forEachSource. */
|
|
233
|
+
id: number;
|
|
234
|
+
kind: NodeKind;
|
|
235
|
+
/** The node's current value (last stored/computed value; an effect's is its body return). */
|
|
236
|
+
value: unknown;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Transition callbacks for {@link Registry.observeObservers}. */
|
|
240
|
+
export interface ObserveObserversHooks {
|
|
241
|
+
/** Fired on the 0->1 observer transition (after registration). */
|
|
242
|
+
onConnect?: () => void;
|
|
243
|
+
/** Fired on the 1->0 observer transition. */
|
|
244
|
+
onDisconnect?: () => void;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Stops an {@link Registry.observeObservers} subscription. Idempotent. */
|
|
248
|
+
export type Unobserve = () => void;
|
|
249
|
+
|
|
250
|
+
/** Anything carrying a node identity that the introspection surface can read. */
|
|
251
|
+
export type ReactiveHandle = Signal<any> | Computed<any> | SignalBox<any> | ComputedBox<any>;
|
|
252
|
+
|
|
253
|
+
// --- Graph-mutation hook (1.2.1) ----------------------------------------------
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Opcode passed as the first argument to a {@link GraphMutationListener}.
|
|
257
|
+
*
|
|
258
|
+
* - `1` node create. `(intA, intB) = (node.id, node.flags)`.
|
|
259
|
+
* - `2` node dispose. `(intA, intB) = (node.id, node.flags)` -- fires for every node
|
|
260
|
+
* disposed, including cascaded owner-tree children.
|
|
261
|
+
* - `3` link add. `(intA, intB) = (source.id, target.id)`.
|
|
262
|
+
* - `4` link remove. `(intA, intB) = (source.id, target.id)` -- `-1` if the link
|
|
263
|
+
* was already nulled (defensive, rare).
|
|
264
|
+
* - `5` recompute. `(intA, intB) = (node.id, 0)` -- fires just before an effect
|
|
265
|
+
* re-run or a computed re-eval.
|
|
266
|
+
*/
|
|
267
|
+
export type GraphMutationOpcode = 1 | 2 | 3 | 4 | 5;
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Listener registered with {@link Registry.onGraphMutation}. Called synchronously
|
|
271
|
+
* inside each mutation point with three integers -- no objects allocated.
|
|
272
|
+
*
|
|
273
|
+
* **Contract: observe only.** Listeners MUST NOT throw and MUST NOT mutate the
|
|
274
|
+
* graph from inside the callback. Both will corrupt the engine's state. Wrap any
|
|
275
|
+
* downstream work in a microtask if it could touch the registry.
|
|
276
|
+
*/
|
|
277
|
+
export type GraphMutationListener = (opcode: GraphMutationOpcode, intA: number, intB: number) => void;
|
|
278
|
+
|
|
279
|
+
/** Idempotent unsubscriber returned by {@link Registry.onGraphMutation}. */
|
|
280
|
+
export type GraphMutationUnsubscribe = () => void;
|
|
281
|
+
|
|
282
|
+
// --- Errors -------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
/** Thrown when a pool ceiling is hit. */
|
|
285
|
+
export class CapacityError extends Error {
|
|
286
|
+
readonly name: "CapacityError";
|
|
287
|
+
readonly kind: "nodes" | "links";
|
|
288
|
+
readonly capacity: number;
|
|
289
|
+
constructor(kind: "nodes" | "links", capacity: number);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// --- Registry -----------------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
export interface RegistryConfig {
|
|
295
|
+
/** Initial node-pool capacity (a ledger under `prealloc: "lazy"`). Default: 1024. */
|
|
296
|
+
maxNodes?: number;
|
|
297
|
+
/** Initial link-pool capacity (a ledger under `prealloc: "lazy"`). Default: `maxNodes * 4`. */
|
|
298
|
+
maxLinks?: number;
|
|
299
|
+
/**
|
|
300
|
+
* Pool population strategy. Default: `"eager"`.
|
|
301
|
+
* - `"eager"`: construct the full `maxNodes` / `maxLinks` pools up front.
|
|
302
|
+
* Deterministic latency -- zero allocation inside any subsequent hot path
|
|
303
|
+
* (the contract for render loops, game ticks, and extension frame budgets),
|
|
304
|
+
* at the cost of a larger resident heap that every major GC traces.
|
|
305
|
+
* - `"lazy"`: treat `maxNodes` / `maxLinks` as capacity ledgers and construct
|
|
306
|
+
* nodes/links on first demand, recycling through the free lists thereafter.
|
|
307
|
+
* Smaller heap, faster cold start, lighter GC marking; identical zero-GC
|
|
308
|
+
* steady state after warm-up. Prefer for footprint-sensitive or short-lived
|
|
309
|
+
* registries.
|
|
310
|
+
*/
|
|
311
|
+
prealloc?: "eager" | "lazy";
|
|
312
|
+
/**
|
|
313
|
+
* Behaviour when a pool is exhausted. Default: `"throw"`.
|
|
314
|
+
* - `"throw"`: throw {@link CapacityError} immediately when the pool is full.
|
|
315
|
+
* - `"grow"`: extend the pool on demand. Growth is chunked and incremental
|
|
316
|
+
* (contiguous runs of up to 1024 links / 256 nodes per free-list miss),
|
|
317
|
+
* not a single doubling burst, so any one growth pause stays bounded. The
|
|
318
|
+
* capacity ledger still doubles, keeping {@link RegistryStats} semantics
|
|
319
|
+
* unchanged. Link growth is bounded by a hard ceiling of `maxLinks * 16`.
|
|
320
|
+
*/
|
|
321
|
+
onCapacityExceeded?: "throw" | "grow";
|
|
322
|
+
/** Max effect-queue drain passes before a flush-cycle `Error` (message prefixed `"CycleError:"`) is thrown. Default: 100. */
|
|
323
|
+
maxFlushPasses?: number;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Method surface of {@link Registry}; see that type for the full contract. */
|
|
327
|
+
interface RegistryMembers {
|
|
328
|
+
signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
|
|
329
|
+
computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
|
|
330
|
+
effect(fn: EffectBody, opts?: EffectOptions): Dispose;
|
|
331
|
+
/** Allocation-light, non-callable signal (1.5.0). See {@link SignalBox}. */
|
|
332
|
+
signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
333
|
+
/** Allocation-light, non-callable computed (1.5.0). See {@link ComputedBox}. */
|
|
334
|
+
computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
335
|
+
/**
|
|
336
|
+
* Run `fn` in a detached ownership scope (1.5.0). Effects/computeds created
|
|
337
|
+
* directly in `fn` are NOT adopted by the enclosing owner, so they survive
|
|
338
|
+
* the enclosing effect's re-runs and disposal -- the caller owns their
|
|
339
|
+
* lifecycle (`fn` typically returns a disposer or the created handle). Both
|
|
340
|
+
* ownership and tracking are detached for the duration of `fn`; inner
|
|
341
|
+
* effect/computed bodies still establish their own scopes. The ownership
|
|
342
|
+
* escape hatch for lazily spawning a long-lived node from inside a consumer
|
|
343
|
+
* effect (e.g. a query watcher). Returns whatever `fn` returns.
|
|
344
|
+
*/
|
|
345
|
+
createRoot<T>(fn: () => T): T;
|
|
346
|
+
/**
|
|
347
|
+
* Run `fn(dispose)` in a detached, untracked scope and return whatever `fn`
|
|
348
|
+
* returns (1.6.0). The single `dispose` argument cascade-disposes every effect
|
|
349
|
+
* and computed created inside `fn`. Lifecycle complement to {@link createRoot}:
|
|
350
|
+
* `createRoot` only *detaches* (caller must dispose each child by hand),
|
|
351
|
+
* `createScope` *adopts*, so one disposer tears down a subtree of unknown shape
|
|
352
|
+
* -- the per-item lifecycle a keyed-list or scene reconciler needs. Plain
|
|
353
|
+
* signals created directly in `fn` are NOT adopted (consistent with the 1.2.0
|
|
354
|
+
* ownership rule); computeds and effects are. The owner never re-runs, so
|
|
355
|
+
* direct-body reads in `fn` are untracked; reactive bindings belong in inner
|
|
356
|
+
* effect/computed bodies. A scope created inside a consumer effect SURVIVES
|
|
357
|
+
* that consumer's re-run -- the reconciler-critical detach property. The
|
|
358
|
+
* disposer is the same gen-guarded, ABA-safe handle `effect()` returns and
|
|
359
|
+
* resolves to the owner effect under `describe` / `nodeId` / `forEachOwned`.
|
|
360
|
+
*/
|
|
361
|
+
createScope<T>(fn: (dispose: () => void) => T): T;
|
|
362
|
+
/**
|
|
363
|
+
* Universal disposal for anything created by this registry: signals,
|
|
364
|
+
* computeds, boxes, or effect dispose handles. Cross-registry calls are
|
|
365
|
+
* silent no-ops (each registry owns its own private node-identity Symbol).
|
|
366
|
+
* Passing an unrelated value is also a safe no-op.
|
|
367
|
+
*/
|
|
368
|
+
dispose(api: Disposable): void;
|
|
369
|
+
batch<T>(fn: () => T): T;
|
|
370
|
+
untrack<T>(fn: () => T): T;
|
|
371
|
+
/** True iff a read RIGHT NOW would record a dependency on this registry.
|
|
372
|
+
* False inside `untrack`, `subscribe` callbacks, `onCleanup` bodies, and
|
|
373
|
+
* outside any observer. Use for lazy-allocation wrappers like lite-store. */
|
|
374
|
+
isTracking(): boolean;
|
|
375
|
+
/** O(1): does this source have at least one live observer right now? A `peek` does not count. */
|
|
376
|
+
hasObservers(handle: ReactiveHandle): boolean;
|
|
377
|
+
/** Auto-pause hook: fires `onConnect` on the 0->1 observer transition and `onDisconnect`
|
|
378
|
+
* on 1->0, after registration (transition-only -- no immediate fire if already observed).
|
|
379
|
+
* Re-tracking a persistently-read source does not churn. Returns an idempotent unobserve.
|
|
380
|
+
* @throws TypeError if `handle` is not a reactive handle. */
|
|
381
|
+
observeObservers(handle: ReactiveHandle, hooks?: ObserveObserversHooks): Unobserve;
|
|
382
|
+
/** Walk the observers (subscribers) of `handle`, newest-first. No-op on a non-handle. */
|
|
383
|
+
forEachObserver(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
384
|
+
/** Walk the sources (dependencies) of `handle`. No-op on a non-handle. */
|
|
385
|
+
forEachSource(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
386
|
+
/** Walk the owned children of `handle` -- nodes whose lifetime is bound to this
|
|
387
|
+
* one by the 1.2 owner tree (1.2.1+). Top-level handles and signals have no
|
|
388
|
+
* owned children; effects/computeds may own nested observers created inside
|
|
389
|
+
* their bodies. No-op on a non-handle or stale handle. */
|
|
390
|
+
forEachOwned(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
391
|
+
/** Descriptor of `handle`'s owner, or `undefined` for top-level handles, stale
|
|
392
|
+
* handles, or non-handles (1.2.1+). The owner is the effect or computed inside
|
|
393
|
+
* whose body `handle` was created -- the node that will cascade-dispose it
|
|
394
|
+
* on re-run or explicit dispose. */
|
|
395
|
+
ownerOf(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
396
|
+
/** Stable node id of `handle` (1.1.5+), or undefined for a non-handle or stale handle. */
|
|
397
|
+
nodeId(handle: ReactiveHandle): number | undefined;
|
|
398
|
+
/** The own descriptor of `handle` (1.1.5+), or undefined for a non-handle or stale handle.
|
|
399
|
+
* Re-walkable: the returned descriptor may be passed back into forEachObserver/
|
|
400
|
+
* forEachSource/forEachOwned/ownerOf. Descriptors are gen-stamped (1.2.1+): a
|
|
401
|
+
* descriptor obtained pre-recycle goes stale and walks as undefined post-recycle. */
|
|
402
|
+
describe(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
403
|
+
/** Register a single graph-mutation listener (1.2.1+). Replaces any existing
|
|
404
|
+
* listener and returns an unsubscribe that restores the previous one on call.
|
|
405
|
+
* Listener is invoked synchronously at each mutation point with three integers:
|
|
406
|
+
* `(opcode, intA, intB)` -- see {@link GraphMutationOpcode}. Cost when no
|
|
407
|
+
* listener is registered: one branch-predicted `null` check per mutation point.
|
|
408
|
+
* @throws TypeError if `fn` is not a function or null. */
|
|
409
|
+
onGraphMutation(fn: GraphMutationListener | null): GraphMutationUnsubscribe;
|
|
410
|
+
onCleanup(fn: () => void): void;
|
|
411
|
+
stats(): RegistryStats;
|
|
412
|
+
/** Reset everything: nodes, links, queues, global clock. Outstanding dispose
|
|
413
|
+
* closures become safe no-ops. Outstanding read/set closures still reference
|
|
414
|
+
* pool slots -- they will silently misbehave; use a fresh registry afterwards. */
|
|
415
|
+
destroy(): void;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Isolated reactive graph. Created by {@link createRegistry}.
|
|
420
|
+
*
|
|
421
|
+
* From 1.9.0 the registry carries `[Symbol.dispose]` (-> `destroy`), so
|
|
422
|
+
* `using r = createRegistry()` resets its pools at block exit.
|
|
423
|
+
*/
|
|
424
|
+
export type Registry = RegistryMembers & ExplicitDisposeSlot;
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Create an isolated reactive registry.
|
|
428
|
+
*
|
|
429
|
+
* @example
|
|
430
|
+
* const r = createRegistry({ maxNodes: 4096, onCapacityExceeded: "grow" });
|
|
431
|
+
* const count = r.signal(0);
|
|
432
|
+
* r.effect(() => console.log(count()));
|
|
433
|
+
*/
|
|
434
|
+
export function createRegistry(config?: RegistryConfig): Registry;
|
|
435
|
+
|
|
436
|
+
/** Replace the default registry backing the top-level helpers. */
|
|
437
|
+
export function setDefaultRegistry(registry: Registry): void;
|
|
438
|
+
|
|
439
|
+
// --- Top-level helpers (delegate to default registry) ------------------------
|
|
440
|
+
|
|
441
|
+
export function signal<T>(initial: T, opts?: SignalOptions<T>): Signal<T>;
|
|
442
|
+
export function computed<T>(fn: () => T, opts?: ComputedOptions<T>): Computed<T>;
|
|
443
|
+
export function effect(fn: EffectBody, opts?: EffectOptions): Dispose;
|
|
444
|
+
/** Allocation-light, non-callable signal (1.5.0), bound to the default registry. See {@link SignalBox}. */
|
|
445
|
+
export function signalBox<T>(initial: T, opts?: SignalOptions<T>): SignalBox<T>;
|
|
446
|
+
/** Allocation-light, non-callable computed (1.5.0), bound to the default registry. See {@link ComputedBox}. */
|
|
447
|
+
export function computedBox<T>(fn: () => T, opts?: ComputedOptions<T>): ComputedBox<T>;
|
|
448
|
+
/** Run `fn` in a detached ownership scope (1.5.0), bound to the default registry. See {@link Registry.createRoot}. */
|
|
449
|
+
export function createRoot<T>(fn: () => T): T;
|
|
450
|
+
/** Run `fn(dispose)` in a detached, adopting scope (1.6.0), bound to the default registry. See {@link Registry.createScope}. */
|
|
451
|
+
export function createScope<T>(fn: (dispose: () => void) => T): T;
|
|
452
|
+
/** Universal disposal -- see {@link Registry.dispose}. */
|
|
453
|
+
export function dispose(api: Disposable): void;
|
|
454
|
+
export function batch<T>(fn: () => T): T;
|
|
455
|
+
export function untrack<T>(fn: () => T): T;
|
|
456
|
+
/** Top-level binding of {@link Registry.isTracking} against the default registry. */
|
|
457
|
+
export function isTracking(): boolean;
|
|
458
|
+
/** Top-level binding of {@link Registry.hasObservers}. */
|
|
459
|
+
export function hasObservers(handle: ReactiveHandle): boolean;
|
|
460
|
+
/** Top-level binding of {@link Registry.observeObservers}. */
|
|
461
|
+
export function observeObservers(handle: ReactiveHandle, hooks?: ObserveObserversHooks): Unobserve;
|
|
462
|
+
/** Top-level binding of {@link Registry.forEachObserver}. */
|
|
463
|
+
export function forEachObserver(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
464
|
+
/** Top-level binding of {@link Registry.forEachSource}. */
|
|
465
|
+
export function forEachSource(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
466
|
+
/** Top-level binding of {@link Registry.forEachOwned} (1.2.1+). */
|
|
467
|
+
export function forEachOwned(handle: ReactiveHandle, fn: (descriptor: NodeDescriptor) => void): void;
|
|
468
|
+
/** Top-level binding of {@link Registry.ownerOf} (1.2.1+). */
|
|
469
|
+
export function ownerOf(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
470
|
+
/** Top-level binding of {@link Registry.nodeId}. */
|
|
471
|
+
export function nodeId(handle: ReactiveHandle): number | undefined;
|
|
472
|
+
/** Top-level binding of {@link Registry.describe}. */
|
|
473
|
+
export function describe(handle: ReactiveHandle): NodeDescriptor | undefined;
|
|
474
|
+
/** Top-level binding of {@link Registry.onGraphMutation} (1.2.1+). */
|
|
475
|
+
export function onGraphMutation(fn: GraphMutationListener | null): GraphMutationUnsubscribe;
|
|
476
|
+
export function onCleanup(fn: () => void): void;
|
|
477
|
+
export function stats(): RegistryStats;
|
|
478
|
+
export function destroy(): void;
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Configuration options for the watch utility.
|
|
482
|
+
*/
|
|
483
|
+
export interface WatchOptions {
|
|
484
|
+
/** * If true, fires the callback immediately upon registration
|
|
485
|
+
* with `oldValue` set to `undefined`.
|
|
486
|
+
*/
|
|
487
|
+
immediate?: boolean;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Track a reactive source and run a callback whenever its projected value
|
|
492
|
+
* changes. The callback receives `(newValue, oldValue, stop)` -- the third
|
|
493
|
+
* argument is a dispose function that can be called from inside the callback
|
|
494
|
+
* to terminate the watcher.
|
|
495
|
+
*
|
|
496
|
+
* Internal reads inside the callback are untracked.
|
|
497
|
+
*
|
|
498
|
+
* Uses `Object.is` to guard against the raw-getter case where a dep mutation
|
|
499
|
+
* fires the effect but the projected value is unchanged.
|
|
500
|
+
*
|
|
501
|
+
* @param source Reactive read function.
|
|
502
|
+
* @param callback Called with the new and previous values plus a stop handle.
|
|
503
|
+
* @param options `immediate: true` runs the callback once on registration
|
|
504
|
+
* with `oldValue = undefined`.
|
|
505
|
+
* @returns Dispose function. Idempotent and safe to call at any time, including
|
|
506
|
+
* synchronously during the immediate callback.
|
|
507
|
+
*/
|
|
508
|
+
export function watch<T>(
|
|
509
|
+
source: () => T,
|
|
510
|
+
callback: (newValue: T, oldValue: T | undefined, stop: () => void) => void,
|
|
511
|
+
options?: { immediate?: boolean }
|
|
512
|
+
): () => void;
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Fire `callback` exactly once when `predicate` first returns a truthy value,
|
|
516
|
+
* then auto-dispose. If `predicate` is already truthy at registration, fires
|
|
517
|
+
* synchronously.
|
|
518
|
+
*
|
|
519
|
+
* @param predicate Reactive read function; callback fires when truthy.
|
|
520
|
+
* @param callback Called once when predicate first truthy. Reads inside are untracked.
|
|
521
|
+
* @returns Dispose function. Call before predicate fires to cancel; idempotent.
|
|
522
|
+
*/
|
|
523
|
+
export function when(
|
|
524
|
+
predicate: () => unknown,
|
|
525
|
+
callback: () => void
|
|
526
|
+
): () => void;
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Promise-returning variant of {@link when}. The returned promise resolves
|
|
530
|
+
* when `predicate` first returns a truthy value.
|
|
531
|
+
*
|
|
532
|
+
* ! **HOT-PATH WARNING -- DO NOT USE PER FRAME.** This function calls
|
|
533
|
+
* `new Promise(...)`, which is a heap allocation (one Promise object plus
|
|
534
|
+
* executor closure plus internal infrastructure per call). Promises require
|
|
535
|
+
* heap allocation by the language spec -- this cost is unavoidable.
|
|
536
|
+
*
|
|
537
|
+
* **Use for:** high-level scene/UI orchestration, boot sequences, awaiting
|
|
538
|
+
* user input or network state, level transitions. Anything that runs once
|
|
539
|
+
* or rarely.
|
|
540
|
+
*
|
|
541
|
+
* **NEVER use for:** per-frame entity updates, render-loop logic, animation
|
|
542
|
+
* tick handlers. For zero-GC hot-path logic use {@link when} with a callback.
|
|
543
|
+
*
|
|
544
|
+
* Note: this promise never rejects. If the predicate never becomes truthy,
|
|
545
|
+
* the promise never settles. Wrap in `Promise.race` for timeout semantics.
|
|
546
|
+
*
|
|
547
|
+
* @param predicate Reactive read function; resolves promise when truthy.
|
|
548
|
+
* @returns Promise that resolves when predicate first truthy.
|
|
549
|
+
*/
|
|
550
|
+
export function whenAsync(
|
|
551
|
+
predicate: () => unknown
|
|
552
|
+
): Promise<void>;
|
package/Signal.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @zakkster/lite-signal v1.9.0-preview.
|
|
2
|
+
* @zakkster/lite-signal v1.9.0-preview.6
|
|
3
3
|
* Copyright (c) Zahary Shinikchiev <shinikchiev@yahoo.com>
|
|
4
4
|
* MIT License
|
|
5
5
|
* --------------------
|
|
@@ -301,10 +301,134 @@ export class CapacityError extends Error {
|
|
|
301
301
|
* Error prefixed `"CycleError:"`.
|
|
302
302
|
* @returns {Registry}
|
|
303
303
|
*/
|
|
304
|
+
/** The only config keys {@link createRegistry} recognizes. Anything else is
|
|
305
|
+
* rejected at construction with a did-you-mean hint (fail closed on an
|
|
306
|
+
* unverified state -- an unknown key is an error, never a silent ignore). */
|
|
307
|
+
const ALLOWED_KEYS = ["maxNodes", "maxLinks", "prealloc", "onCapacityExceeded", "maxFlushPasses", "flushStrategy"];
|
|
308
|
+
|
|
309
|
+
/** Ceiling on eager pool construction: `(maxNodes + maxLinks)` objects. A finite
|
|
310
|
+
* but absurd `maxNodes` (e.g. `1e9`, a plausible typo for `1e5`) that would
|
|
311
|
+
* otherwise OOM the process is refused BY NAME at construction rather than
|
|
312
|
+
* allocating forever. Only the `"eager"` path is bounded; `"lazy"` keeps its
|
|
313
|
+
* unbounded ledger. `1 << 24` == 16777216. */
|
|
314
|
+
const EAGER_CONSTRUCT_CEILING = 1 << 24;
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Levenshtein edit distance between two short strings. Cold: called only on the
|
|
318
|
+
* constructor error path, over the known option names, so its per-call array
|
|
319
|
+
* allocation never touches any hot path.
|
|
320
|
+
* @param {string} a
|
|
321
|
+
* @param {string} b
|
|
322
|
+
* @returns {number}
|
|
323
|
+
*/
|
|
324
|
+
function editDistance(a, b) {
|
|
325
|
+
const m = a.length;
|
|
326
|
+
const n = b.length;
|
|
327
|
+
const prev = new Array(n + 1);
|
|
328
|
+
const cur = new Array(n + 1);
|
|
329
|
+
for (let j = 0; j <= n; j++) prev[j] = j;
|
|
330
|
+
for (let i = 1; i <= m; i++) {
|
|
331
|
+
cur[0] = i;
|
|
332
|
+
for (let j = 1; j <= n; j++) {
|
|
333
|
+
const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
|
|
334
|
+
let min = prev[j] + 1;
|
|
335
|
+
if (cur[j - 1] + 1 < min) min = cur[j - 1] + 1;
|
|
336
|
+
if (prev[j - 1] + cost < min) min = prev[j - 1] + cost;
|
|
337
|
+
cur[j] = min;
|
|
338
|
+
}
|
|
339
|
+
for (let j = 0; j <= n; j++) prev[j] = cur[j];
|
|
340
|
+
}
|
|
341
|
+
return prev[n];
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* The closest known config key to `key` within edit distance 2 (case-folded so
|
|
346
|
+
* `preAlloc`/`MAXNODES` resolve), or null when nothing is close. Cold path only.
|
|
347
|
+
* @param {string} key
|
|
348
|
+
* @returns {string|null}
|
|
349
|
+
*/
|
|
350
|
+
function suggestKey(key) {
|
|
351
|
+
const lk = key.toLowerCase();
|
|
352
|
+
let best = null;
|
|
353
|
+
let bestD = 3;
|
|
354
|
+
for (let i = 0; i < ALLOWED_KEYS.length; i++) {
|
|
355
|
+
const d = editDistance(lk, ALLOWED_KEYS[i].toLowerCase());
|
|
356
|
+
if (d < bestD) { bestD = d; best = ALLOWED_KEYS[i]; }
|
|
357
|
+
}
|
|
358
|
+
return bestD <= 2 ? best : null;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Render a rejected value for an error message, e.g. `42 (number)`.
|
|
363
|
+
* Cold: this runs only on a throw path, never on any hot path. `String(symbol)`
|
|
364
|
+
* throws, so symbols are stringified defensively.
|
|
365
|
+
* @param {*} v
|
|
366
|
+
* @returns {string}
|
|
367
|
+
*/
|
|
368
|
+
function received(v) {
|
|
369
|
+
return (typeof v === "symbol" ? v.toString() : String(v)) + " (" + typeof v + ")";
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Validate that a numeric option is a finite integer >= 1. Cold: constructor
|
|
374
|
+
* error path only. Throws a {@link TypeError} prefixed `createRegistry: "<name>"`.
|
|
375
|
+
* @param {*} v
|
|
376
|
+
* @param {string} name
|
|
377
|
+
*/
|
|
378
|
+
function requirePositiveInt(v, name) {
|
|
379
|
+
if (!Number.isInteger(v) || v < 1) {
|
|
380
|
+
throw new TypeError(
|
|
381
|
+
'createRegistry: "' + name + '" must be a finite integer >= 1, received ' + received(v) + '.'
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
304
386
|
export function createRegistry(config) {
|
|
305
387
|
const NODE_PTR = Symbol("node_ptr");
|
|
306
388
|
const NODE_GEN = Symbol("node_gen");
|
|
307
389
|
|
|
390
|
+
// --- 1.4.5 backport: createRegistry input validation (all cold, constructor-only).
|
|
391
|
+
// Config-shape gate: accept `undefined` or a non-null, non-array object; reject
|
|
392
|
+
// `null`, primitives and arrays BY NAME rather than dying later on `config.maxNodes`
|
|
393
|
+
// or an internal `nextFree` read (fail closed on an unverified state).
|
|
394
|
+
if (config !== undefined && (config === null || typeof config !== "object" || Array.isArray(config))) {
|
|
395
|
+
throw new TypeError(
|
|
396
|
+
'createRegistry: "config" must be a plain object or undefined, received ' + received(config) + '.'
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
if (config !== undefined) {
|
|
400
|
+
// Per-option validation BY NAME -- a bad value throws `createRegistry: "<option>"`
|
|
401
|
+
// at construction, not a delayed internal TypeError on first use.
|
|
402
|
+
if (config.maxNodes !== undefined) requirePositiveInt(config.maxNodes, "maxNodes");
|
|
403
|
+
if (config.maxLinks !== undefined) requirePositiveInt(config.maxLinks, "maxLinks");
|
|
404
|
+
if (config.maxFlushPasses !== undefined) requirePositiveInt(config.maxFlushPasses, "maxFlushPasses");
|
|
405
|
+
if (config.prealloc !== undefined && config.prealloc !== "eager" && config.prealloc !== "lazy") {
|
|
406
|
+
throw new TypeError(
|
|
407
|
+
'createRegistry: "prealloc" must be "eager" or "lazy", received ' + received(config.prealloc) + '.'
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
if (config.onCapacityExceeded !== undefined && config.onCapacityExceeded !== "throw" && config.onCapacityExceeded !== "grow") {
|
|
411
|
+
throw new TypeError(
|
|
412
|
+
'createRegistry: "onCapacityExceeded" must be "throw" or "grow", received ' + received(config.onCapacityExceeded) + '.'
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
// Unknown-key rejection with a did-you-mean hint (`preAlloc` -> `prealloc`,
|
|
416
|
+
// `maxNods` -> `maxNodes`). Own enumerable keys only; cold path.
|
|
417
|
+
const badKeys = Object.keys(config);
|
|
418
|
+
for (let bi = 0; bi < badKeys.length; bi++) {
|
|
419
|
+
const bk = badKeys[bi];
|
|
420
|
+
if (ALLOWED_KEYS.indexOf(bk) === -1) {
|
|
421
|
+
const hint = suggestKey(bk);
|
|
422
|
+
throw new TypeError(
|
|
423
|
+
'createRegistry: "' + bk + '" is not a recognized option' +
|
|
424
|
+
(hint !== null ? ' (did you mean "' + hint + '"?)' : '') +
|
|
425
|
+
'. Allowed: ' + ALLOWED_KEYS.join(", ") + '.'
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
// --- end 1.4.5 backport.
|
|
431
|
+
|
|
308
432
|
let currentNodesCapacity = (config !== undefined && config.maxNodes !== undefined) ? config.maxNodes : 1024;
|
|
309
433
|
let currentLinkCapacity = (config !== undefined && config.maxLinks !== undefined) ? config.maxLinks : currentNodesCapacity * 4;
|
|
310
434
|
const policy = (config !== undefined && config.onCapacityExceeded !== undefined) ? config.onCapacityExceeded : "throw";
|
|
@@ -328,6 +452,20 @@ export function createRegistry(config) {
|
|
|
328
452
|
// steady state is identical after warm-up, but the heap no longer carries
|
|
329
453
|
// never-used live objects for every major GC to mark.
|
|
330
454
|
const prealloc = (config !== undefined && config.prealloc !== undefined) ? config.prealloc : "eager";
|
|
455
|
+
// Eager-construction ceiling (cold): `"eager"` builds `(maxNodes + maxLinks)`
|
|
456
|
+
// objects up front; a finite-but-absurd capacity (e.g. `1e9`) would OOM the
|
|
457
|
+
// process with an uncatchable SIGABRT, not a throw. Refuse BY NAME before
|
|
458
|
+
// allocating. Named for the larger driver. `"lazy"` keeps its unbounded ledger.
|
|
459
|
+
if (prealloc === "eager" && (currentNodesCapacity + currentLinkCapacity) > EAGER_CONSTRUCT_CEILING) {
|
|
460
|
+
const driver = currentLinkCapacity > currentNodesCapacity ? "maxLinks" : "maxNodes";
|
|
461
|
+
throw new TypeError(
|
|
462
|
+
'createRegistry: "' + driver + '" eager construction of ' +
|
|
463
|
+
(currentNodesCapacity + currentLinkCapacity) + ' objects (maxNodes ' +
|
|
464
|
+
currentNodesCapacity + ' + maxLinks ' + currentLinkCapacity + ') exceeds the ceiling of ' +
|
|
465
|
+
EAGER_CONSTRUCT_CEILING + '. Use prealloc:"lazy" for an unbounded on-demand ledger, ' +
|
|
466
|
+
'or lower the capacity.'
|
|
467
|
+
);
|
|
468
|
+
}
|
|
331
469
|
const nodePool = [];
|
|
332
470
|
let freeNodeHead = null;
|
|
333
471
|
const linkPool = [];
|
|
@@ -1896,6 +2034,12 @@ export function createRegistry(config) {
|
|
|
1896
2034
|
pooledLinks: currentLinkCapacity - activeLinks,
|
|
1897
2035
|
linkPoolCapacity: currentLinkCapacity,
|
|
1898
2036
|
nodePoolCapacity: currentNodesCapacity,
|
|
2037
|
+
// 1.4.5 backport: TRUE pool population (nodePool.length / linkPool.length),
|
|
2038
|
+
// distinct from the *Capacity ledgers above. Under prealloc:"lazy" (or a
|
|
2039
|
+
// silently-flipped `prealloc` typo) population stays 0 while capacity reads
|
|
2040
|
+
// the ledger -- so a mis-set prealloc is now observable, not telemetry-blind.
|
|
2041
|
+
nodePoolPopulation: nodePool.length,
|
|
2042
|
+
linkPoolPopulation: linkPool.length,
|
|
1899
2043
|
activeNodes,
|
|
1900
2044
|
// 1.4: cumulative lifecycle counters (monotonic; reset by destroy()).
|
|
1901
2045
|
// Derive: allocationRate = deltatotalAllocations/deltat; poolReuseRate =
|
package/llms.txt
CHANGED
|
@@ -25,7 +25,7 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
25
25
|
- **onCleanup**: registers teardown for the current computation; fires before each re-run and once on dispose. Works in effects and computeds.
|
|
26
26
|
- **Returned cleanup (1.8.0)**: an EFFECT body may `return` a cleanup function (Solid/Vue/Reflex-compatible). Runs at the same points as onCleanup (before each re-run, once on dispose) and is APPENDED after any onCleanup registered in the same body, so the two styles compose in call order. Non-function returns are ignored; a self-disposed body registers nothing (gen-guarded). COMPUTEDS ARE EXCLUDED: a computed returning a function keeps treating it as the VALUE. Cost: one `typeof` per effect run, off the mark/pull path; `executeEffect` is the only body whose sha256 changed 1.7.0 -> 1.8.0.
|
|
27
27
|
- **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.
|
|
28
|
-
- **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
|
+
- **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. **Config is validated at construction (1.9.0-preview.6, backported from 1.4.5):** every option is checked BY NAME (the six recognized keys include `flushStrategy`), a bad shape or unknown key throws a `TypeError` prefixed `createRegistry: "<name>"` with a did-you-mean hint, and an absurd eager capacity (`maxNodes:Infinity`/`1e9`) is refused before it can OOM the process. `stats()` gains `nodePoolPopulation` / `linkPoolPopulation` (true constructed-object counts, distinct from the `*Capacity` ledgers) -> **14 keys**.
|
|
29
29
|
- **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.
|
|
30
30
|
|
|
31
31
|
## Architecture invariants
|
|
@@ -53,10 +53,37 @@ triggering write -- no `queueMicrotask`, no promises, no scheduler ticks.
|
|
|
53
53
|
|
|
54
54
|
## Version notes
|
|
55
55
|
|
|
56
|
-
- **1.9.0-preview.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
- **1.9.0-preview.6** (current): backports the **1.4.5 `createRegistry` input validation** (all four findings) onto the 1.9.0-preview.5 engine. Only `createRegistry`'s *cold* path moved; hot paths stay byte-identical and `bench/torture/run.mjs` is unchanged at 22/22. Bad config now throws a named `TypeError` (unknown keys get a did-you-mean); an absurd eager capacity is refused before it can OOM the process; `stats()` grows to 14 keys (adds `nodePoolPopulation`/`linkPoolPopulation`, purely additive). New `test/*-config-validation.test.mjs` (matrix + ceiling + population + OOM child processes). See CHANGELOG `[1.9.0-preview.6]`.
|
|
57
|
+
- **1.9.0-preview.5**: a **packaging-only cut** -- the engine is
|
|
58
|
+
behaviourally unchanged from preview.4 (`Signal.js` differs only in its header
|
|
59
|
+
banner string). Two fixes make the tarball honour its own manifest. (1) The
|
|
60
|
+
promised **`Signal.d.ts` now ships**: since 1.5.0 `package.json` has advertised
|
|
61
|
+
`"types": "./Signal.d.ts"` and listed it in `files[]`, but the 1.9.0 line packed
|
|
62
|
+
a `types` pointer to a file that did not exist, so `tsc` consumers got no types.
|
|
63
|
+
The declaration is modelled on 1.8.0's (1.9.0's export surface is byte-identical
|
|
64
|
+
to 1.8.0's) plus the 1.9.0 delta: `[Symbol.dispose](): void` typed on exactly the
|
|
65
|
+
handles the engine stamps -- both box prototypes, every `Dispose` function
|
|
66
|
+
(effect / `.subscribe()` / `createScope`), and the `Registry` (-> `destroy`) --
|
|
67
|
+
with callable `Signal`/`Computed` handles left UNSTAMPED, matching the engine, so
|
|
68
|
+
`using r = createRegistry()`, `using box = signalBox(0)`, and `using stop =
|
|
69
|
+
effect(fn)` all typecheck. The `[Symbol.dispose]` slot is behind a `lib`-conditional
|
|
70
|
+
helper that resolves to `{}` on TypeScript `lib` targets predating `Symbol.dispose`,
|
|
71
|
+
so it never forces a `lib` upgrade on type-only consumers (verified: `using`
|
|
72
|
+
compiles under `esnext.disposable`; a type-only consumer compiles clean under
|
|
73
|
+
`ES2020`). (2) The **`Signal.js` header banner** is reconciled to `preview.5`
|
|
74
|
+
(preview.2 through preview.4 carried a stale `preview.2` banner in the comment).
|
|
75
|
+
No API, torture, or test change: torture stays 22/22, unit **512/511/0/1** under
|
|
76
|
+
`npm test` and **520/519/0/1** under `npm run test:gc`. Drop-in over preview.4.
|
|
77
|
+
|
|
78
|
+
- **1.9.0-preview.4**: a **version-only re-tag** over preview.3. `Signal.js` is
|
|
79
|
+
byte-identical to preview.3 past the header banner; no engine, torture, test, API,
|
|
80
|
+
or packaging change (the missing `Signal.d.ts` and the stale `preview.2` banner
|
|
81
|
+
were both still present -- fixed in preview.5). Recorded for continuity.
|
|
82
|
+
|
|
83
|
+
- **1.9.0-preview.3**: the **verification-surface parity cut**. No engine
|
|
84
|
+
change from preview.2 -- `Signal.js` is byte-identical (at this cut the header
|
|
85
|
+
banner still read `preview.2`; reconciled in preview.5) and `bench/torture/` stays
|
|
86
|
+
out of `files[]`; for consumers preview.3 is preview.2 plus a version number. It brings the torture suite to full
|
|
60
87
|
parity with the shipped 1.4.4 canonical: a parity port of the last three scenarios
|
|
61
88
|
-- `error-torture` (throwing effect bodies: single re-thrown unwrapped, two-or-more
|
|
62
89
|
aggregated into an `AggregateError` carrying exactly those errors, survivors still
|
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.6",
|
|
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",
|