@xaendar/signals 0.9.18 → 0.9.22

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.
@@ -0,0 +1,964 @@
1
+ (function(global, factory) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@xaendar/common")) : typeof define === "function" && define.amd ? define(["exports", "@xaendar/common"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["@xaendar/signals"] = {}, global._xaendar_common));
3
+ })(this, function(exports, _xaendar_common) {
4
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
5
+ //#region ../packages/signals/src/lib/utils/globals/globals.ts
6
+ /**
7
+ * Global state for the signals runtime.
8
+ * Tracks the currently computing `Computed` instance, whether the state is frozen,
9
+ * and the current generation counter.
10
+ *
11
+ * @internal
12
+ */
13
+ var GLOBAL_STATE = {
14
+ computing: null,
15
+ frozen: false
16
+ };
17
+ var computingStack = new _xaendar_common.Stack();
18
+ /**
19
+ * Pushes a `Computed` instance onto the computing stack and sets it as the
20
+ * currently active computation in `GLOBAL_STATE`.
21
+ *
22
+ * Should be called before executing a computed function to register
23
+ * dependency tracking.
24
+ *
25
+ * @param computed - The `Computed` instance entering the computation phase.
26
+ * @internal
27
+ */
28
+ function pushComputed(computed) {
29
+ computingStack.push(computed);
30
+ GLOBAL_STATE.computing = computed;
31
+ }
32
+ /**
33
+ * Pops the most recent `Computed` instance from the computing stack and
34
+ * restores the previous one as the active computation in `GLOBAL_STATE`.
35
+ *
36
+ * Should be called after a computed function finishes executing.
37
+ *
38
+ * @internal
39
+ */
40
+ function popComputed() {
41
+ computingStack.pop();
42
+ GLOBAL_STATE.computing = computingStack[computingStack.length - 1] ?? null;
43
+ }
44
+ //#endregion
45
+ //#region ../packages/signals/src/lib/utils/private-symbol/private-symbol.ts
46
+ /**
47
+ * Symbol not available in public API,
48
+ * used to call internal methods of `State` and `Computed` from `Watcher` without exposing them in the public API.
49
+ *
50
+ * @internal
51
+ */
52
+ var PRIVATE = Symbol("signals-private");
53
+ /**
54
+ * Asserts that the provided symbol matches the internal {@link PRIVATE} symbol,
55
+ * ensuring the caller has access to internal APIs.
56
+ *
57
+ * Throws if the symbol does not match, preventing external code from
58
+ * invoking methods intended for internal use only.
59
+ *
60
+ * @param symbol - The symbol to validate against {@link PRIVATE}.
61
+ * @throws {Error} If `symbol` does not match {@link PRIVATE}.
62
+ * @internal
63
+ */
64
+ function assertPrivateContext(symbol) {
65
+ if (symbol !== PRIVATE) throw new Error("Invalid symbol");
66
+ }
67
+ //#endregion
68
+ //#region ../packages/signals/src/lib/utils/dev-mode/dev-mode.ts
69
+ /**
70
+ * Whether the library is runnign in development mode
71
+ * Used to log extra information for example
72
+ * - Invalid transition states for {@link Computed} or {@link Watcher}
73
+ */
74
+ var devMode = false;
75
+ /**
76
+ * Sets the development mode flag.
77
+ * @param mode - `true` to enable dev mode, `false` to disable it.
78
+ */
79
+ function setDevMode(mode) {
80
+ devMode = mode;
81
+ }
82
+ /**
83
+ * Returns the current development mode state.
84
+ * @returns `true` if dev mode is enabled, `false` otherwise.
85
+ */
86
+ function isDevMode() {
87
+ return devMode;
88
+ }
89
+ //#endregion
90
+ //#region ../packages/signals/src/lib/models/computed/computed.ts
91
+ /**
92
+ * A read-only Signal whose value is derived lazily from other Signals.
93
+ *
94
+ * The value is recomputed only when explicitly read and only if one or more
95
+ * of its (recursive) dependencies have changed since the last evaluation.
96
+ * The result is cached and reused until the Signal becomes stale again.
97
+ *
98
+ * @template T The type of the computed value.
99
+ *
100
+ * @see Signal algorithms — "The Signal.Computed class"
101
+ */
102
+ var Computed = class Computed {
103
+ /**
104
+ * The current value of the signal.
105
+ *
106
+ * Uninitialised (`!`) until the first evaluation. After that, holds either
107
+ * the return value of `#callback` or a boxed error
108
+ * `{ isError: true; value: Error }` if the last evaluation threw.
109
+ *
110
+ * @internalSlot
111
+ * @see Signal algorithms — "Signal.Computed internal slots"
112
+ */
113
+ #value;
114
+ /**
115
+ * The current evaluation state of this Signal.
116
+ *
117
+ * - `~dirty~` — value is known to be stale or has never been evaluated.
118
+ * - `~checked~` — an indirect source changed; may or may not be stale.
119
+ * - `~computing~` — `#callback` is currently executing; guards against cycles.
120
+ * - `~clean~` — cached value is up-to-date.
121
+ *
122
+ * @internalSlot
123
+ * @see Signal algorithms — "Signal.Computed State machine"
124
+ */
125
+ #state;
126
+ /**
127
+ * The ordered set of Signals read during the last evaluation of
128
+ * `#callback`. Cleared and rebuilt on every re-evaluation so that
129
+ * conditional branches that are no longer taken stop being tracked.
130
+ *
131
+ * May contain both `State` and `Computed` instances.
132
+ *
133
+ * @internalSlot
134
+ * @see Signal algorithms — "Signal.Computed internal slots"
135
+ */
136
+ #sources;
137
+ /**
138
+ * Returns a snapshot of the current sources set for introspection.
139
+ *
140
+ * @param symbol - Private access symbol; rejects calls from outside the library.
141
+ * @returns An array of `State` and `Computed` instances that this Signal depends on.
142
+ * @internal
143
+ */
144
+ getSources(symbol) {
145
+ assertPrivateContext(symbol);
146
+ return [...this.#sources];
147
+ }
148
+ /**
149
+ * The set of Signals and Watchers that directly depend on this Signal.
150
+ *
151
+ * Populated only when this Signal is reachable from at least one active
152
+ * `Watcher`. An un-watched `Computed` has an empty sinks set, which allows
153
+ * it to be garbage-collected independently from the rest of the graph.
154
+ *
155
+ * @internalSlot
156
+ * @see Signal algorithms — "Signal.Computed internal slots"
157
+ * @see Method — `Signal.Computed.prototype.get` (NOTE on sinks)
158
+ */
159
+ #sinks;
160
+ /**
161
+ * Returns a snapshot of the current sinks set for introspection.
162
+ *
163
+ * @param symbol - Private access symbol; rejects calls from outside the library.
164
+ * @returns An array of `Computed` and `Watcher` instances that depend on this Signal.
165
+ * @internal
166
+ */
167
+ getSinks(symbol) {
168
+ assertPrivateContext(symbol);
169
+ return [...this.#sinks];
170
+ }
171
+ /**
172
+ * The equality function used to determine whether a newly computed value
173
+ * is meaningfully different from the previously cached one.
174
+ *
175
+ * Called as `equals.call(computed, oldValue, newValue)`. Returns `true` if
176
+ * the values are considered equal, in which case no downstream propagation
177
+ * occurs. Defaults to `Object.is` when not provided via options.
178
+ *
179
+ * If this function throws, the exception is cached as the Signal's value
180
+ * and the outcome is treated as `~dirty~`.
181
+ *
182
+ * @internalSlot
183
+ * @see Signal algorithms — "Signal.Computed internal slots"
184
+ * @see Algorithm — "Set Signal value"
185
+ */
186
+ #equals;
187
+ /**
188
+ * The pure function that produces this Signal's value. Evaluated lazily
189
+ * whenever the Signal is read while in a `~dirty~` or `~checked~` state.
190
+ *
191
+ * Called with `this` bound to the `Computed` instance itself so that
192
+ * internal methods (e.g. `addSource`) are accessible if needed.
193
+ * Any exception thrown by this function is caught and cached.
194
+ *
195
+ * @internalSlot
196
+ * @see Signal algorithms — "Signal.Computed internal slots"
197
+ */
198
+ #callback;
199
+ /**
200
+ * Creates a new `Computed` signal.
201
+ *
202
+ * The Signal starts in the `~dirty~` state with an uninitialised value, so
203
+ * `#callback` will be invoked on the first `get()`.
204
+ *
205
+ * @param cb - Pure function evaluated lazily to produce the value.
206
+ * Receives the `Computed` instance as `this`.
207
+ * @param options - Optional configuration:
208
+ * - `equals` — custom equality function; defaults to `Object.is`.
209
+ *
210
+ * @see Signal algorithms — "Signal.Computed Constructor"
211
+ */
212
+ constructor(cb, options) {
213
+ this.#callback = cb;
214
+ this.#equals = options?.equals ?? Object.is;
215
+ this.#sources = /* @__PURE__ */ new Set();
216
+ this.#sinks = /* @__PURE__ */ new Set();
217
+ this.#state = "dirty";
218
+ }
219
+ /**
220
+ * Returns the current value of this Signal, re-evaluating `#callback` if
221
+ * the cached value may be stale.
222
+ *
223
+ * Registers this Signal as a source of any outer `Computed` currently
224
+ * being evaluated (automatic dependency tracking).
225
+ *
226
+ * If the state is `~dirty~` or `~checked~`, walks the source graph
227
+ * depth-first to find and recalculate the deepest stale `Computed` first,
228
+ * then re-checks upward until this Signal is `~clean~`.
229
+ *
230
+ * @returns The current computed value, or a boxed error object if the last
231
+ * evaluation threw.
232
+ * @throws If `frozen` is `true`.
233
+ * @throws If the Signal is in the `~computing~` state (cyclic dependency).
234
+ *
235
+ * @see Signal algorithms — "Method: Signal.Computed.prototype.get"
236
+ */
237
+ get() {
238
+ if (GLOBAL_STATE.frozen) throw new Error("Cannot get value of a Computed signal while the global state is frozen");
239
+ if (this.#state === "computing") throw new Error("Circular dependency detected while computing a Computed signal");
240
+ GLOBAL_STATE.computing?.addSource(this, PRIVATE);
241
+ if (this.#sinks.size === 0) this.#computeValue();
242
+ else if (this.#state === "dirty" || this.#state === "checked") while (this.#state === "dirty" || this.#state === "checked") this.#findDeepestStale().#computeValue();
243
+ return this.#value;
244
+ }
245
+ /**
246
+ * Registers a Signal as a source of this `Computed`, discovered during the
247
+ * execution of `#callback`.
248
+ *
249
+ * If this `Computed` is currently being watched (has at least one sink),
250
+ * the source is also informed of this Signal as a new sink, building the
251
+ * live push-notification chain upward.
252
+ *
253
+ * @param source - The Signal read during evaluation.
254
+ * @param symbol - Private access symbol; rejects calls from outside the library.
255
+ * @internal
256
+ */
257
+ addSource(source, symbol) {
258
+ assertPrivateContext(symbol);
259
+ this.#sources.add(source);
260
+ source.addSink(this, PRIVATE);
261
+ }
262
+ /**
263
+ * Returns the current evaluation state of this Signal.
264
+ *
265
+ * @param symbol - Private access symbol; rejects calls from outside the library.
266
+ * @internal
267
+ * @see Signal algorithms — "Signal.Computed State machine"
268
+ */
269
+ getState(symbol) {
270
+ assertPrivateContext(symbol);
271
+ return this.#state;
272
+ }
273
+ /**
274
+ * Transitions this Signal to a new evaluation state.
275
+ *
276
+ * Only valid transitions (as defined by the state machine) are allowed.
277
+ * Invalid transitions throw an error.
278
+ *
279
+ * @param newState - The target state.
280
+ * @param symbol - Private access symbol; rejects calls from outside the library.
281
+ * @throws If the transition from the current state to `newState` is not allowed.
282
+ * @internal
283
+ * @see Signal algorithms — "Signal.Computed State machine"
284
+ */
285
+ setState(newState, symbol) {
286
+ assertPrivateContext(symbol);
287
+ if (this.#state === newState) return;
288
+ if (!this.#isValidTransition(this.#state, newState)) {
289
+ if (isDevMode()) {
290
+ console.warn(`Invalid state transition from ${this.#state} to ${newState} in Computed Signal`);
291
+ console.warn((/* @__PURE__ */ new Error()).stack);
292
+ }
293
+ return;
294
+ }
295
+ this.#state = newState;
296
+ if (this.#state === "dirty" || this.#state === "checked") for (const sink of this.#sinks) sink instanceof Computed ? sink.setState("checked", PRIVATE) : sink.notify(PRIVATE);
297
+ }
298
+ /**
299
+ * Registers a new sink (a `Computed` or `Watcher` that directly depends on
300
+ * this Signal) in the internal sinks set.
301
+ *
302
+ * If this is the first sink, propagates the sink registration recursively
303
+ * up through `#sources`, building the live dependency chain that enables
304
+ * push-based invalidation.
305
+ *
306
+ * @param sink - The dependent node to register.
307
+ * @param symbol - Private access symbol; rejects calls from outside the library.
308
+ * @internal
309
+ */
310
+ addSink(sink, symbol) {
311
+ assertPrivateContext(symbol);
312
+ if (this.#sinks.size === 0) for (const source of this.#sources) source.addSink(this, PRIVATE);
313
+ this.#sinks.add(sink);
314
+ }
315
+ /**
316
+ * Removes a sink from the internal sinks set.
317
+ *
318
+ * If the sinks set becomes empty after removal, propagates the removal
319
+ * recursively up through `#sources`, tearing down the live dependency
320
+ * chain and allowing garbage collection of un-watched nodes.
321
+ *
322
+ * @param sink - The dependent node to remove.
323
+ * @param symbol - Private access symbol; rejects calls from outside the library.
324
+ * @internal
325
+ */
326
+ removeSink(sink, symbol) {
327
+ assertPrivateContext(symbol);
328
+ this.#sinks.delete(sink);
329
+ if (this.#sinks.size === 0) for (const source of this.#sources) source.removeSink(this, PRIVATE);
330
+ }
331
+ /**
332
+ * Recursively walks the source graph depth-first to find the deepest,
333
+ * left-most `Computed` node that is in a `~dirty~` or `~checked~` state.
334
+ *
335
+ * This ensures that recalculation always starts from the bottom of the
336
+ * dependency graph, so every node sees already-updated dependencies —
337
+ * the core of glitch-free evaluation.
338
+ *
339
+ * Cuts off the search when hitting a `~clean~` `Computed` source, since
340
+ * its subtree is guaranteed to be up-to-date.
341
+ *
342
+ * @returns The deepest stale `Computed` found, or `node` itself if none of
343
+ * its sources are stale.
344
+ */
345
+ #findDeepestStale() {
346
+ const unclearNode = [...this.#sources].find((source) => source instanceof Computed && (source.#state === "dirty" || source.#state === "checked"));
347
+ return unclearNode ? unclearNode.#findDeepestStale() : this;
348
+ }
349
+ /**
350
+ * Executes `#callback` to recompute this Signal's value.
351
+ *
352
+ * Implements the "recalculate dirty computed Signal" algorithm:
353
+ * 1. Clears stale sources and removes this Signal from their sinks.
354
+ * 2. Sets `computing` to this Signal for automatic dependency tracking.
355
+ * 3. Runs the callback, caching the return value or any thrown exception.
356
+ * 4. Restores the previous `computing` value.
357
+ * 5. Runs the "set Signal value" algorithm to detect value changes.
358
+ * 6. Transitions state to `~clean~`.
359
+ * 7. Propagates `~dirty~` to sinks (or attempts `~clean~` if value unchanged).
360
+ *
361
+ * @see Signal algorithms — "Algorithm: recalculate dirty computed Signal"
362
+ */
363
+ #computeValue() {
364
+ for (const source of this.#sources) source.removeSink(this, PRIVATE);
365
+ this.#sources.clear();
366
+ pushComputed(this);
367
+ this.setState("computing", PRIVATE);
368
+ let newValue;
369
+ try {
370
+ newValue = this.#callback.call(this);
371
+ } catch (error) {
372
+ if (isDevMode()) console.error("Error thrown while computing a Computed signal:", error);
373
+ newValue = {
374
+ isError: true,
375
+ value: error
376
+ };
377
+ } finally {
378
+ popComputed();
379
+ }
380
+ const outcome = this.#setValue(newValue);
381
+ this.setState("clean", PRIVATE);
382
+ if (outcome === "dirty") for (const sink of this.#sinks) sink instanceof Computed ? sink.setState("dirty", PRIVATE) : sink.notify(PRIVATE);
383
+ else this.#propagateClean();
384
+ }
385
+ /**
386
+ * Implements the "set Signal value" algorithm.
387
+ *
388
+ * Compares the new value against the cached one using `#equals`. If equal,
389
+ * returns `~clean~` and leaves `#value` untouched. Otherwise updates
390
+ * `#value` and returns `~dirty~`.
391
+ *
392
+ * Special cases:
393
+ * - If `newValue` is a boxed error, `#equals` is skipped and the error is
394
+ * cached directly.
395
+ * - If `#equals` itself throws, the exception is cached as a boxed error
396
+ * and the outcome is `~dirty~`.
397
+ *
398
+ * @param newValue - The value (or boxed error) produced by `#callback`.
399
+ * @returns `~clean~` if the value is unchanged, `~dirty~` otherwise.
400
+ *
401
+ * @see Signal algorithms — "Set Signal value algorithm"
402
+ */
403
+ #setValue(newValue) {
404
+ const oldValue = this.#value;
405
+ if (this.#isErrorValue(newValue)) {
406
+ this.#value = newValue;
407
+ return "dirty";
408
+ }
409
+ try {
410
+ if (!this.#isErrorValue(oldValue) && this.#equals.call(this, oldValue, newValue)) return "clean";
411
+ } catch (equalsError) {
412
+ this.#value = {
413
+ isError: true,
414
+ value: equalsError
415
+ };
416
+ return "dirty";
417
+ }
418
+ this.#value = newValue;
419
+ return "dirty";
420
+ }
421
+ /**
422
+ * Recursively marks `~checked~` sinks as `~clean~` when all of their
423
+ * immediate sources are already `~clean~`.
424
+ *
425
+ * Called after a recalculation that produced an unchanged value (`~clean~`
426
+ * outcome from `#setValue`). Propagates the clean signal upward through
427
+ * the graph so that Computed nodes that were only transitively dirty — and
428
+ * whose dependencies have not actually changed — are not needlessly
429
+ * re-evaluated on the next read.
430
+ *
431
+ * @see Signal algorithms — "Algorithm: recalculate dirty computed Signal"
432
+ */
433
+ #propagateClean() {
434
+ for (const sink of this.#sinks) if (sink instanceof Computed && sink.#state === "checked") {
435
+ let allSourcesClean = true;
436
+ for (const source of sink.#sources) if (source instanceof Computed && source.#state !== "clean") {
437
+ allSourcesClean = false;
438
+ break;
439
+ }
440
+ if (allSourcesClean) {
441
+ sink.#state = "clean";
442
+ sink.#propagateClean();
443
+ }
444
+ }
445
+ }
446
+ /**
447
+ * Type guard that checks whether a value is a boxed error object.
448
+ *
449
+ * Used to distinguish a legitimately computed value from a cached
450
+ * exception produced by `#callback` or `#equals`.
451
+ *
452
+ * @param value - The value to inspect.
453
+ * @returns `true` if `value` is `{ isError: true; value: Error }`.
454
+ */
455
+ #isErrorValue(value) {
456
+ return typeof value === "object" && !!value && "isError" in value;
457
+ }
458
+ #isValidTransition(from, to) {
459
+ switch (from) {
460
+ case "checked": return to === "clean" || to === "dirty";
461
+ case "clean": return to === "checked" || to === "dirty";
462
+ case "dirty": return to === "computing";
463
+ case "computing": return to === "clean";
464
+ }
465
+ }
466
+ };
467
+ //#endregion
468
+ //#region ../packages/signals/src/lib/models/state/state.ts
469
+ var State = class {
470
+ /**
471
+ * The current value of the signal.
472
+ *
473
+ * Initialised to `initialValue` in the constructor and updated by `set`
474
+ * whenever the new value is not equal to the current one according to
475
+ * `#equals`.
476
+ *
477
+ * @internalSlot
478
+ * @see Signal algorithms — 'Signal.State internal slots'
479
+ */
480
+ #value;
481
+ /**
482
+ * The equality function used to determine whether a new value is
483
+ * meaningfully different from the current one.
484
+ *
485
+ * Called as `equals.call(signal, oldValue, newValue)`. If it returns
486
+ * `true` the signal is considered unchanged and no propagation occurs.
487
+ * Defaults to `Object.is` when not provided via options.
488
+ *
489
+ * @internalSlot
490
+ * @see Signal algorithms — 'Signal.State internal slots'
491
+ * @see Algorithm — 'Set Signal value'
492
+ */
493
+ #equals;
494
+ /**
495
+ * Optional callback invoked (with `frozen = true`) the first time this
496
+ * Signal gains a sink — i.e. when it transitions from un-observed to
497
+ * observed by at least one `Watcher` (directly or transitively).
498
+ *
499
+ * @internalSlot
500
+ * @see Signal algorithms — 'Signal.State internal slots'
501
+ * @see Method — `Signal.subtle.Watcher.prototype.watch`
502
+ */
503
+ #watched;
504
+ /**
505
+ * Optional callback invoked (with `frozen = true`) when this Signal loses
506
+ * its last sink — i.e. when it transitions from observed back to
507
+ * un-observed.
508
+ *
509
+ * @internalSlot
510
+ * @see Signal algorithms — 'Signal.State internal slots'
511
+ * @see Method — `Signal.subtle.Watcher.prototype.unwatch`
512
+ */
513
+ #unwatched;
514
+ /**
515
+ * The set of watched signals that directly depend on this one.
516
+ *
517
+ * Populated only when this Signal is reachable from at least one active
518
+ * `Watcher` — un-watched Signals have an empty sinks set, which allows
519
+ * them to be garbage-collected independently from the rest of the graph.
520
+ *
521
+ * Should contain both `Computed` and `Watcher` instances, as both can be
522
+ * direct dependents of a `State`.
523
+ *
524
+ * @internalSlot
525
+ * @see Signal algorithms — 'Signal.State internal slots'
526
+ * @see Method — `Signal.State.prototype.get` (NOTE on sinks)
527
+ */
528
+ #sinks;
529
+ /**
530
+ * Returns a snapshot of the current sinks set for introspection.
531
+ *
532
+ * @param symbol - Private access symbol; rejects calls from outside the library.
533
+ * @returns An array of `Computed` and `Watcher` instances that depend on this Signal.
534
+ * @internal
535
+ */
536
+ getSinks(symbol) {
537
+ assertPrivateContext(symbol);
538
+ return [...this.#sinks];
539
+ }
540
+ /**
541
+ * Creates a new `State` signal.
542
+ *
543
+ * @param initialValue - The initial value of the signal.
544
+ * @param options - Optional configuration:
545
+ * - `equals` — custom equality function; defaults to `Object.is`.
546
+ * - `watched` — called when the signal gains its first sink.
547
+ * - `unwatched` — called when the signal loses its last sink.
548
+ *
549
+ * @see Signal algorithms — 'Constructor: Signal.State(initialValue, options)'
550
+ */
551
+ constructor(initialValue, options) {
552
+ this.#value = initialValue;
553
+ this.#equals = options?.equals ?? Object.is;
554
+ this.#watched = options?.watched;
555
+ this.#unwatched = options?.unwatched;
556
+ this.#sinks = /* @__PURE__ */ new Set();
557
+ }
558
+ /**
559
+ * Returns the current value of the signal, registering this Signal as a
560
+ * source of the innermost `Computed` currently being evaluated (if any).
561
+ *
562
+ * @throws If `frozen` is `true` — reads are forbidden while a protected
563
+ * callback (`notify`, `watched`, `unwatched`) is executing.
564
+ *
565
+ * @see Signal algorithms — 'Method: Signal.State.prototype.get()'
566
+ */
567
+ get() {
568
+ if (GLOBAL_STATE.frozen) throw new Error("Cannot get value while signals are frozen");
569
+ GLOBAL_STATE.computing?.addSource(this, PRIVATE);
570
+ return this.#value;
571
+ }
572
+ /**
573
+ * Updates the signal's value and propagates changes to all dependent
574
+ * sinks.
575
+ *
576
+ * If `equals(currentValue, newValue)` returns `true` the call is a no-op
577
+ * and no propagation occurs. Otherwise `#value` is updated, all direct
578
+ * `Computed` sinks are marked `~dirty~`, indirect ones `~checked~`, and
579
+ * each reachable `Watcher` has its `notify` callback invoked synchronously
580
+ * (with `frozen = true`).
581
+ *
582
+ * @param newValue - The new value to set.
583
+ * @throws If `frozen` is `true` — writes are forbidden while a protected
584
+ * callback is executing.
585
+ *
586
+ * @see Signal algorithms — 'Method: Signal.State.prototype.set(newValue)'
587
+ * @see Algorithm — 'Set Signal value'
588
+ */
589
+ set(newValue) {
590
+ if (GLOBAL_STATE.frozen) throw new Error("Cannot set value while signals are frozen");
591
+ if (!this.#equals.call(this, this.#value, newValue)) {
592
+ this.#value = newValue;
593
+ for (const sink of this.#sinks) sink instanceof Computed ? sink.setState("dirty", PRIVATE) : sink.notify(PRIVATE);
594
+ }
595
+ }
596
+ /**
597
+ * Registers a new sink (a `Computed` or `Watcher` that depends on this
598
+ * Signal) in the internal sinks set.
599
+ *
600
+ * Called by `Watcher.prototype.watch` when building the live dependency
601
+ * chain, and by `Computed` when propagating sink registration up through
602
+ * its sources.
603
+ *
604
+ * @param sink - The dependent node to register.
605
+ * @param symbol - The private symbol for validation.
606
+ * @internal
607
+ */
608
+ addSink(sink, symbol) {
609
+ assertPrivateContext(symbol);
610
+ const empty = this.#sinks.size === 0;
611
+ this.#sinks.add(sink);
612
+ if (empty && this.#watched) {
613
+ GLOBAL_STATE.frozen = true;
614
+ try {
615
+ this.#watched();
616
+ } catch (error) {
617
+ if (isDevMode()) console.error("Error thrown while running a State Signal watched callback:", error);
618
+ throw error;
619
+ } finally {
620
+ GLOBAL_STATE.frozen = false;
621
+ }
622
+ }
623
+ }
624
+ /**
625
+ * Removes a sink from the internal sinks set.
626
+ *
627
+ * Called by `Watcher.prototype.unwatch` when tearing down the live
628
+ * dependency chain. If the sinks set becomes empty after removal, the
629
+ * caller is responsible for propagating the removal up through this
630
+ * Signal's sources.
631
+ *
632
+ * @param sink - The dependent node to remove.
633
+ * @param symbol - The private symbol for validation.
634
+ * @internal
635
+ */
636
+ removeSink(sink, symbol) {
637
+ assertPrivateContext(symbol);
638
+ this.#sinks.delete(sink);
639
+ if (this.#sinks.size === 0 && this.#unwatched) {
640
+ GLOBAL_STATE.frozen = true;
641
+ try {
642
+ this.#unwatched();
643
+ } catch (error) {
644
+ if (isDevMode()) console.error("Error thrown while running a State Signal unwatched callback:", error);
645
+ throw error;
646
+ } finally {
647
+ GLOBAL_STATE.frozen = false;
648
+ }
649
+ }
650
+ }
651
+ };
652
+ //#endregion
653
+ //#region ../packages/signals/src/lib/models/watcher/watcher.ts
654
+ /**
655
+ * A `Watcher` observes a set of Signals and fires a `notify` callback
656
+ * synchronously when any of their (recursive) dependencies change.
657
+ *
658
+ * It is the low-level primitive on top of which frameworks implement
659
+ * effects and scheduling. It does not hold a value and has no generic
660
+ * type parameter.
661
+ *
662
+ * @see Signal algorithms — 'The `Signal.subtle.Watcher` class'
663
+ */
664
+ var Watcher = class {
665
+ /**
666
+ * The current state of the Watcher.
667
+ *
668
+ * - `~waiting~` — newly created, or `notify` has already been called since
669
+ * the last `watch` call. Not actively observing changes.
670
+ * - `~watching~` — actively watching; no dependency has changed yet.
671
+ * - `~pending~` — a dependency has changed but `notify` has not yet run.
672
+ *
673
+ * @internalSlot
674
+ * @see Signal algorithms — 'Signal.subtle.Watcher State machine'
675
+ */
676
+ #state;
677
+ /**
678
+ * The ordered set of Signals this Watcher is currently watching.
679
+ * May contain both `State` and `Computed` instances.
680
+ *
681
+ * @internalSlot
682
+ * @see Signal algorithms — 'Signal.subtle.Watcher internal slots'
683
+ */
684
+ #signals;
685
+ /**
686
+ * Returns a snapshot of the current watched signals set for introspection.
687
+ *
688
+ * @param symbol - Private access symbol; rejects calls from outside the library.
689
+ * @returns An array of `State` and `Computed` instances that this Watcher is watching.
690
+ * @internal
691
+ */
692
+ getSources(symbol) {
693
+ assertPrivateContext(symbol);
694
+ return [...this.#signals];
695
+ }
696
+ /**
697
+ * The callback invoked synchronously when a watched Signal (or one of its
698
+ * recursive dependencies) changes for the first time since the last
699
+ * `watch` call.
700
+ *
701
+ * Receives the Watcher itself as `this`. No Signals may be read or written
702
+ * during its execution (`frozen` is `true` for its entire duration).
703
+ *
704
+ * @internalSlot
705
+ * @see Signal algorithms — 'Signal.subtle.Watcher internal slots'
706
+ */
707
+ #notifyCallback;
708
+ /**
709
+ * Creates a new Watcher.
710
+ *
711
+ * The Watcher starts in the `~waiting~` state with an empty signals set.
712
+ *
713
+ * @param notifyCallback - Called synchronously (with `frozen = true`) the
714
+ * first time a watched dependency changes after each `watch` call. No
715
+ * Signals may be read or written inside this callback.
716
+ *
717
+ * @see Signal algorithms — 'Constructor: new Signal.subtle.Watcher(callback)'
718
+ */
719
+ constructor(notifyCallback) {
720
+ this.#state = "waiting";
721
+ this.#signals = /* @__PURE__ */ new Set();
722
+ this.#notifyCallback = notifyCallback;
723
+ }
724
+ /**
725
+ * Returns the subset of watched Signals that are `Computed` instances
726
+ * currently in a `~dirty~` or `~checked~` state, meaning they may have a
727
+ * stale value that has not yet been re-evaluated.
728
+ *
729
+ * Typically called inside the microtask scheduled by the `notify` callback
730
+ * to know which Signals need to be pulled.
731
+ *
732
+ * @returns An array of `Computed` signals that are dirty or checked.
733
+ *
734
+ * @see Signal algorithms — 'Method: Signal.subtle.Watcher.prototype.getPending()'
735
+ */
736
+ getPending() {
737
+ const filteredSignals = new Array();
738
+ for (const signal of this.#signals) {
739
+ if (!(signal instanceof Computed)) continue;
740
+ const state = signal.getState(PRIVATE);
741
+ if (state === "dirty" || state === "checked") filteredSignals.push(signal);
742
+ }
743
+ return filteredSignals;
744
+ }
745
+ /**
746
+ * Adds the given Signals to the watched set and transitions the Watcher to
747
+ * the `~watching~` state.
748
+ *
749
+ * For each newly-watched Signal, the Watcher is registered as a sink and —
750
+ * if it is the first sink — the sink registration is propagated recursively
751
+ * up through the Signal's sources, building the live dependency chain.
752
+ *
753
+ * The `watched` callback of each Signal (if any) is called with
754
+ * `frozen = true`.
755
+ *
756
+ * @param signals - One or more `State` signals to start watching.
757
+ * @throws If `frozen` is `true` at the time of the call.
758
+ *
759
+ * @see Signal algorithms — 'Method: Signal.subtle.Watcher.prototype.watch(...signals)'
760
+ */
761
+ watch(...signals) {
762
+ if (GLOBAL_STATE.frozen) throw new Error("Cannot watch signals while frozen");
763
+ for (let i = 0; i < signals.length; i++) {
764
+ const signal = signals[i];
765
+ if (this.#signals.has(signal)) throw new Error("Cannot watch a signal that is already being watched");
766
+ this.#signals.add(signal);
767
+ signal.addSink(this, PRIVATE);
768
+ }
769
+ this.setState("watching", PRIVATE);
770
+ }
771
+ /**
772
+ * Removes the given Signals from the watched set.
773
+ *
774
+ * For each removed Signal, the Watcher is unregistered as a sink. If the
775
+ * Signal's sink set becomes empty as a result, the removal is propagated
776
+ * recursively up through its sources, tearing down the live dependency
777
+ * chain and allowing garbage collection of unwatched nodes.
778
+ *
779
+ * The `unwatched` callback of each Signal (if any) is called with
780
+ * `frozen = true`.
781
+ *
782
+ * If no Signals remain in the watched set, the Watcher transitions back to
783
+ * the `~waiting~` state.
784
+ *
785
+ * @param signals - One or more `State` signals to stop watching.
786
+ * @throws If `frozen` is `true` at the time of the call.
787
+ * @throws If any of the given Signals is not currently being watched.
788
+ *
789
+ * @see Signal algorithms — 'Method: Signal.subtle.Watcher.prototype.unwatch(...signals)'
790
+ */
791
+ unwatch(...signals) {
792
+ if (GLOBAL_STATE.frozen) throw new Error("Cannot unwatch signals while frozen");
793
+ for (let i = 0; i < signals.length; i++) {
794
+ const signal = signals[i];
795
+ if (!this.#signals.has(signal)) throw new Error("Cannot unwatch a signal that is not being watched");
796
+ this.#signals.delete(signal);
797
+ signal.removeSink(this, PRIVATE);
798
+ }
799
+ if (!this.#signals.size) this.setState("waiting", PRIVATE);
800
+ }
801
+ /**
802
+ * Get the current state of the Watcher.
803
+ * @param symbol - The private symbol for prevent external calls.
804
+ */
805
+ getState(symbol) {
806
+ assertPrivateContext(symbol);
807
+ return this.#state;
808
+ }
809
+ /**
810
+ * Set the current state of the Watcher.
811
+ * @param newState - The new state to set.
812
+ * @param symbol - The private symbol for prevent external calls.
813
+ * @throws If the transition from `pending` to `watching` is attempted.
814
+ */
815
+ setState(newState, symbol) {
816
+ assertPrivateContext(symbol);
817
+ if (this.#state === newState) return;
818
+ if (!this.#isValidTransition(this.#state, newState)) {
819
+ if (isDevMode()) {
820
+ console.warn(`Invalid state transition from ${this.#state} to ${newState} in Watcher`);
821
+ console.warn((/* @__PURE__ */ new Error()).stack);
822
+ }
823
+ return;
824
+ }
825
+ this.#state = newState;
826
+ }
827
+ /**
828
+ * Invoce the notify callback when a watched dependency changes
829
+ * @param symbol - The private symbol for prevent external calls.
830
+ */
831
+ notify(symbol) {
832
+ assertPrivateContext(symbol);
833
+ GLOBAL_STATE.frozen = true;
834
+ try {
835
+ this.setState("pending", PRIVATE);
836
+ this.#notifyCallback.call(this);
837
+ } catch (error) {
838
+ if (isDevMode()) console.error("Error thrown while running a Watcher notify callback:", error);
839
+ throw error;
840
+ } finally {
841
+ this.setState("waiting", PRIVATE);
842
+ GLOBAL_STATE.frozen = false;
843
+ }
844
+ }
845
+ #isValidTransition(from, to) {
846
+ switch (from) {
847
+ case "waiting": return to === "watching";
848
+ case "watching": return to === "pending" || to === "waiting";
849
+ case "pending": return to === "waiting";
850
+ }
851
+ }
852
+ };
853
+ //#endregion
854
+ //#region ../packages/signals/src/lib/subtle.ts
855
+ /**
856
+ * Executes a function without tracking any dependencies.
857
+ * @param fn - The function to execute without tracking.
858
+ * @returns The result of the function execution.
859
+ */
860
+ function untrack(fn) {
861
+ const prevComputing = GLOBAL_STATE.computing;
862
+ GLOBAL_STATE.computing = null;
863
+ try {
864
+ return fn();
865
+ } catch (error) {
866
+ if (isDevMode()) console.error("Error thrown while running an Untracked signal:", error);
867
+ throw error;
868
+ } finally {
869
+ GLOBAL_STATE.computing = prevComputing;
870
+ }
871
+ }
872
+ /**
873
+ * Returns the currently active `Computed` instance being evaluated, or `null`
874
+ * @returns The currently active `Computed` instance, or `null` if none is being evaluated.
875
+ */
876
+ function currentComputed() {
877
+ return GLOBAL_STATE.computing;
878
+ }
879
+ /**
880
+ * Returns the ordered list of all Signals which the given `Computed` or
881
+ * `Watcher` referenced during its last evaluation.
882
+ *
883
+ * - For a `Computed`, these are the Signals read inside its callback.
884
+ * - For a `Watcher`, these are the Signals it is currently watching.
885
+ *
886
+ * @param signal - The `Computed` or `Watcher` to introspect.
887
+ * @returns An array of `State` and `Computed` instances.
888
+ */
889
+ function introspectSources(signal) {
890
+ return signal.getSources(PRIVATE);
891
+ }
892
+ /**
893
+ * Returns the direct dependents of the given Signal — Watchers that contain
894
+ * it, plus any `Computed` Signals which read it during their last evaluation
895
+ * (if that `Computed` is recursively watched).
896
+ *
897
+ * @param signal - The `State` or `Computed` Signal to introspect.
898
+ * @returns An array of `Computed` and `Watcher` instances.
899
+ */
900
+ function introspectSinks(signal) {
901
+ return signal.getSinks(PRIVATE);
902
+ }
903
+ /**
904
+ * Returns `true` if the given Signal is 'live' — i.e. it is watched by a
905
+ * `Watcher`, or it is read by a `Computed` Signal which is (recursively)
906
+ * live.
907
+ *
908
+ * @param signal - The `State` or `Computed` Signal to check.
909
+ * @returns `true` if the Signal has at least one sink.
910
+ */
911
+ function hasSinks(signal) {
912
+ return signal.getSinks(PRIVATE).length > 0;
913
+ }
914
+ /**
915
+ * Returns `true` if the given node is 'reactive' — i.e. it depends on some
916
+ * other Signal. A `Computed` where `hasSources` is `false` will always
917
+ * return the same constant.
918
+ *
919
+ * @param signal - The `Computed` or `Watcher` to check.
920
+ * @returns `true` if the node has at least one source.
921
+ */
922
+ function hasSources(signal) {
923
+ return signal.getSources(PRIVATE).length > 0;
924
+ }
925
+ //#endregion
926
+ //#region ../packages/signals/src/lib/load-signals.ts
927
+ /**
928
+ * Loads the Signals library by defining the `Signal` global object with the following properties:
929
+ * - `State`: The `State` class for creating reactive state variables.
930
+ * - `Computed`: The `Computed` class for creating derived reactive values.
931
+ * - `Watcher`: The `Watcher` class for observing changes in signals.
932
+ * - `subtle`: An object containing internal utility functions for working with signals, including:
933
+ * - `untrack`: Executes a function without tracking dependencies.
934
+ * - `currentComputed`: Returns the currently active `Computed` instance being evaluated, or `null` if none.
935
+ * - `introspectSources`: Returns the list of sources for a given `Computed` or `Watcher`.
936
+ * - `introspectSinks`: Returns the list of sinks for a given `State` or `Computed`.
937
+ * - `hasSinks`: Returns `true` if a given `State` or `Computed` has at least one sink.
938
+ * - `hasSources`: Returns `true` if a given `Computed` or `Watcher` has at least one source.
939
+ * - `Watcher`: The `Watcher` class for observing changes in signals.
940
+ *
941
+ * This function should be called once to initialize the Signals library and make its API available globally.
942
+ *
943
+ * @param options - Optional configuration object.
944
+ * @param options.devMode - When `true`, enables development mode with extra runtime checks and logging.
945
+ */
946
+ function loadSignals(options) {
947
+ setDevMode(options?.devMode ?? false);
948
+ globalThis.Signal ??= {
949
+ State,
950
+ Computed,
951
+ subtle: {
952
+ untrack,
953
+ currentComputed,
954
+ introspectSources,
955
+ introspectSinks,
956
+ hasSinks,
957
+ hasSources,
958
+ Watcher
959
+ }
960
+ };
961
+ }
962
+ //#endregion
963
+ exports.loadSignals = loadSignals;
964
+ });