@slimlib/store 2.0.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -131,11 +131,12 @@ console.log(doubled()); // 10 - recomputes on demand
131
131
 
132
132
  Both patterns can coexist. A computed stays connected to its sources as long as it's referenced, regardless of whether any effect tracks it. This allows computeds to be used as derived getters in imperative code while still participating in the reactive graph when needed.
133
133
 
134
- #### `effect(callback: () => void | EffectCleanup): () => void`
134
+ #### `effect(callback: () => void | EffectCleanup, eager?: EffectOptions): () => void`
135
135
 
136
136
  Creates a reactive effect that runs when its dependencies change. Returns a dispose function.
137
137
 
138
138
  - `callback` - Effect function that optionally returns a cleanup function (`EffectCleanup = () => void`)
139
+ - `eager` - Optional. One of `EffectOptions.DEFERRED` (default, `0`) or `EffectOptions.EAGER` (`1`). Controls when and how the **first** run executes — see [Effect creation modes](#effect-creation-modes) below.
139
140
  - Effects run on the next microtask (not synchronously) by default
140
141
  - Multiple synchronous changes are automatically batched
141
142
  - The cleanup function runs before each re-execution and when the effect is disposed
@@ -161,6 +162,40 @@ store.count = 1; // Effect runs after microtask
161
162
  dispose(); // Stop the effect, run cleanup
162
163
  ```
163
164
 
165
+ ##### Effect creation modes
166
+
167
+ ```js
168
+ import { effect, EffectOptions } from "@slimlib/store";
169
+
170
+ effect(fn); // DEFERRED (default)
171
+ effect(fn, EffectOptions.EAGER); // first run is synchronous
172
+ ```
173
+
174
+ | Mode | Value | First run | Errors on first run |
175
+ | ---------- | ----- | -------------------------------------------------- | -------------------------------------------------------------------------- |
176
+ | `DEFERRED` | `0` | Scheduled on the active scheduler (default microtask). | Caught by the flush loop and logged via `console.error`. Caller never sees them — `queueMicrotask` callbacks have no `try/catch` boundary, so propagating them would surface as unhandled rejections. |
177
+ | `EAGER` | `1` | Runs synchronously inside the `effect()` call. | **Propagate synchronously to the caller** — preserves the stack trace, and you can wrap `effect()` in `try/catch` to recover. |
178
+
179
+ Shared by both modes:
180
+
181
+ - Dependency tracking is identical.
182
+ - Re-runs (after the first one) always go through the scheduler.
183
+ - The returned dispose function and optional cleanup-return contract are identical.
184
+
185
+ When to choose `EAGER`:
186
+
187
+ - You need the effect's side effects (DOM writes, signal initialisation, sub-scope setup) to be visible before `effect()` returns. This is how `@slimlib/jsx` wires reactive attributes and reactive children: the first paint must happen during `render()`, not on a later microtask.
188
+ - You want errors in the initial run to be catchable at the call site, not silently logged.
189
+
190
+ When to stick with `DEFERRED`:
191
+
192
+ - You want multiple synchronous signal mutations to coalesce into a single first run.
193
+ - You explicitly want the queueMicrotask error-swallowing semantics.
194
+
195
+ Scope is the same in both modes: the effect's callback always runs with `activeScope` restored to the scope that was active when `effect()` was called — both on the first run and on every re-run. Sub-scopes and grandchild effects created inside the callback default-parent to the creation scope consistently across runs.
196
+
197
+ The constants are also available as raw numeric literals (`0`, `1`). Internal slimlib packages pass the literal to keep the `EffectOptions` struct out of their bundle; library consumers should prefer the named constants for readability.
198
+
164
199
  For managing multiple effects, use a `scope`:
165
200
 
166
201
  ```js
package/index.d.ts CHANGED
@@ -39,9 +39,63 @@ declare module '@slimlib/store' {
39
39
  */
40
40
  export const debugConfig: (flags: number) => void;
41
41
  /**
42
- * Creates a reactive effect that runs when dependencies change
43
- */
44
- export const effect: (callback: () => void | EffectCleanup) => (() => void);
42
+ * Bitflag-style options controlling effect creation.
43
+ *
44
+ * Pass one of these values as the second argument to {@link effect}.
45
+ *
46
+ * Today only the first-run scheduling mode is encoded; future flags will be
47
+ * combinable via bitwise OR. Internal callers in @slimlib/* can also pass the
48
+ * raw numeric literals (`0` for DEFERRED, `1` for EAGER) to avoid pulling the
49
+ * enum-like struct into their bundle.
50
+ *
51
+ * | Member | Value | First run | Error handling |
52
+ * | ---------- | ----- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
53
+ * | `DEFERRED` | `0` | Scheduled on the active scheduler (default microtask). | Caught by the flush loop and logged via `console.error` — caller of `effect()` never sees them. |
54
+ * | `EAGER` | `1` | Runs synchronously inside the `effect()` call. | Thrown synchronously to the caller — preserves the stack trace and is catchable with try/catch. |
55
+ *
56
+ * Behavior shared by both modes:
57
+ * - Dependency tracking is identical: signals/state/computed reads inside the
58
+ * callback subscribe the effect to re-run on change.
59
+ * - Re-runs (after the first one) always go through the scheduler.
60
+ * - The returned dispose function and the optional cleanup-function-return
61
+ * contract are identical.
62
+ *
63
+ * Implications worth knowing:
64
+ * - Both modes run the callback with `activeScope` set to the scope that
65
+ * was active when `effect()` was called. This holds for the first run
66
+ * and every subsequent re-run, so sub-scopes and grandchild effects
67
+ * default-parent to the creation scope consistently.
68
+ * - `EAGER` makes signal mutations that synchronously trigger an effect
69
+ * cycle visible at the call site. With `DEFERRED` they're noticed only
70
+ * once the flush runs.
71
+ * - Choosing `EAGER` does not change re-run semantics; only the first run is
72
+ * promoted from a microtask to inline execution. The dispose function
73
+ * and cleanup-return contract are identical between modes.
74
+ */
75
+ export const EffectOptions: {
76
+ readonly DEFERRED: 0;
77
+ readonly EAGER: 1;
78
+ };
79
+ /**
80
+ * Numeric union of the values in {@link EffectOptions} (`0 | 1`). Accepted as
81
+ * the second argument to {@link effect}.
82
+ */
83
+ export type EffectOptions = (typeof EffectOptions)[keyof typeof EffectOptions];
84
+ /**
85
+ * Creates a reactive effect that runs when dependencies change.
86
+ *
87
+ * @param callback - Function to run; may return an {@link EffectCleanup} to be
88
+ * invoked before each re-run and on dispose.
89
+ * @param eager - One of {@link EffectOptions}. Default `DEFERRED` schedules
90
+ * the first run on the active scheduler. `EAGER` runs the
91
+ * first invocation synchronously inside `effect()` — errors
92
+ * propagate to the caller (catchable with try/catch),
93
+ * whereas errors in deferred first runs are caught by the
94
+ * flush loop and reported via `console.error`.
95
+ * @returns - Dispose function that stops re-runs and invokes the last
96
+ * cleanup.
97
+ */
98
+ export const effect: (callback: () => void | EffectCleanup, eager?: EffectOptions) => (() => void);
45
99
  /**
46
100
  * Active scope for effect tracking
47
101
  * When set, effects created will be tracked to this scope
package/index.mjs CHANGED
@@ -531,9 +531,14 @@ const computed = (getter, equals = Object.is) => {
531
531
  return () => computedRead(node);
532
532
  };
533
533
 
534
+ const EffectOptions = {
535
+ DEFERRED: 0,
536
+ EAGER: 1,
537
+ };
538
+
534
539
  let effectCreationCounter = 0;
535
540
 
536
- const effect = (callback) => {
541
+ const effect = (callback, eager = 0 ) => {
537
542
  let disposed = false;
538
543
 
539
544
  const gcToken = registerEffect();
@@ -541,6 +546,7 @@ const effect = (callback) => {
541
546
  warnIfNoActiveScope(activeScope);
542
547
 
543
548
  let node;
549
+ const effectScope = activeScope;
544
550
 
545
551
  const runner = () => {
546
552
 
@@ -560,15 +566,22 @@ const effect = (callback) => {
560
566
  return;
561
567
  }
562
568
  }
569
+ const previousScope = activeScope;
570
+ setActiveScope(effectScope);
563
571
 
564
- runWithTracking(node, () => {
572
+ try {
573
+ runWithTracking(node, () => {
565
574
 
566
- if (typeof node.l === 'function') {
567
- node.l();
568
- }
575
+ if (typeof node.l === 'function') {
576
+ node.l();
577
+ }
569
578
 
570
- node.l = callback();
571
- });
579
+ node.l = callback();
580
+ });
581
+ }
582
+ finally {
583
+ setActiveScope(previousScope);
584
+ }
572
585
  };
573
586
 
574
587
  node = {
@@ -595,12 +608,18 @@ const effect = (callback) => {
595
608
  clearSources(node);
596
609
  };
597
610
 
598
- if (activeScope) {
599
- activeScope[trackSymbol](dispose);
611
+ if (effectScope) {
612
+ effectScope[trackSymbol](dispose);
600
613
  }
601
614
 
602
- batchedAddNew(node, effectId);
603
- scheduleFlush();
615
+ if (eager === 0 ) {
616
+ batchedAddNew(node, effectId);
617
+ scheduleFlush();
618
+ }
619
+ else {
620
+
621
+ runner();
622
+ }
604
623
  return dispose;
605
624
  };
606
625
 
@@ -822,4 +841,4 @@ function state(object = {}) {
822
841
  return createProxy(object);
823
842
  }
824
843
 
825
- export { SUPPRESS_EFFECT_GC_WARNING, WARN_ON_UNTRACKED_EFFECT, WARN_ON_WRITE_IN_COMPUTED, activeScope, computed, debugConfig, effect, flushEffects, scope, setActiveScope, setScheduler, signal, state, untracked, unwrapValue };
844
+ export { EffectOptions, SUPPRESS_EFFECT_GC_WARNING, WARN_ON_UNTRACKED_EFFECT, WARN_ON_WRITE_IN_COMPUTED, activeScope, computed, debugConfig, effect, flushEffects, scope, setActiveScope, setScheduler, signal, state, untracked, unwrapValue };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "type": "module",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
4
4
  "name": "@slimlib/store",
5
5
  "description": "Simple Proxy-based store for SPA",
6
6
  "license": "MIT",
package/src/computed.ts DELETED
@@ -1,232 +0,0 @@
1
- import {
2
- checkComputedSources,
3
- clearSources,
4
- createSourceEntry,
5
- currentComputing,
6
- DepsSet,
7
- globalVersion,
8
- makeLive,
9
- noopGetter,
10
- runWithTracking,
11
- setTracked,
12
- tracked,
13
- } from './core';
14
- import { cycleMessage } from './debug';
15
- import { Flag } from './flags';
16
- import type { ReactiveNode, SourceEntry } from './internal-types';
17
- import type { Computed } from './types';
18
-
19
- /**
20
- * Read function for computed nodes
21
- */
22
- export function computedRead<T>(self: ReactiveNode): T {
23
- // ===== PULL PHASE: Register this computed as a dependency of the current consumer =====
24
- // Track if someone is reading us
25
- if (tracked && currentComputing !== undefined) {
26
- // Inline tracking for computed dependencies
27
- const consumerSources = currentComputing.$_sources;
28
- const skipIndex = currentComputing.$_skipped;
29
- const deps = self.$_deps;
30
- const existing = consumerSources[skipIndex];
31
- const noSource = existing === undefined;
32
-
33
- if (noSource || existing.$_dependents !== deps) {
34
- // Different dependency - clear old ones from this point and rebuild
35
- if (!noSource) {
36
- clearSources(currentComputing, skipIndex);
37
- }
38
-
39
- // Push source entry - version will be updated after source computes
40
- // Uses shared createSourceEntry factory for V8 hidden class monomorphism
41
- consumerSources.push(createSourceEntry(deps as DepsSet<ReactiveNode>, self, 0, undefined, undefined));
42
-
43
- // Only register with source if we're live
44
- if ((currentComputing.$_flags & (Flag.EFFECT | Flag.LIVE)) !== 0) {
45
- (deps as DepsSet<ReactiveNode>).add(currentComputing);
46
- // If source computed is not live, make it live
47
- if ((self.$_flags & Flag.LIVE) === 0) {
48
- makeLive(self);
49
- }
50
- }
51
- }
52
- // Mark that this node has computed sources (for version update loop optimization)
53
- currentComputing.$_flags |= Flag.HAS_COMPUTED_SOURCE;
54
- ++currentComputing.$_skipped;
55
- }
56
-
57
- let flags = self.$_flags;
58
- const sourcesArray = self.$_sources;
59
-
60
- // Cycle detection: if this computed is already being computed, we have a cycle
61
- // This matches TC39 Signals proposal behavior: throw an error on cyclic reads
62
- if ((flags & Flag.COMPUTING) !== 0) {
63
- throw new Error(cycleMessage);
64
- }
65
-
66
- // ===== PULL PHASE: Check if cached value can be returned =====
67
- // Combined check: node has cached result and doesn't need work
68
- const hasCached = (flags & (Flag.HAS_VALUE | Flag.HAS_ERROR)) !== 0;
69
-
70
- // biome-ignore lint/suspicious/noConfusingLabels: expected
71
- checkCache: if ((flags & (Flag.DIRTY | Flag.CHECK)) === 0 && hasCached) {
72
- // Fast-path: nothing has changed globally since last read
73
- if (self.$_stamp === globalVersion) {
74
- if ((flags & Flag.HAS_ERROR) !== 0) {
75
- throw self.$_value;
76
- }
77
- return self.$_value as T;
78
- }
79
-
80
- // ===== PULL PHASE: Poll sources for non-live computeds =====
81
- // Non-live nodes poll instead of receiving push notifications
82
- if ((flags & Flag.LIVE) === 0) {
83
- let sourceChanged = false;
84
-
85
- // Disable tracking while polling sources to avoid unnecessary dependency tracking
86
- const prevTracked = tracked;
87
- // TODO: inline after it combined to a single scope?
88
- setTracked(false);
89
- for (let i = 0, len = sourcesArray.length; i < len; ++i) {
90
- const source = sourcesArray[i] as SourceEntry;
91
- const sourceNode = source.$_node; // Extract once at loop start
92
- if (sourceNode === undefined) {
93
- // State source - check if deps version changed
94
- const currentDepsVersion = (source.$_dependents as DepsSet<ReactiveNode>).$_version as number;
95
- if (source.$_version !== currentDepsVersion) {
96
- // Deps version changed, check if actual value reverted (primitives only)
97
- const storedValue = source.$_storedValue;
98
- const storedType = typeof storedValue;
99
- if (storedValue === null || (storedType !== 'object' && storedType !== 'function')) {
100
- const currentValue = (source.$_getter as () => unknown)();
101
- if (Object.is(currentValue, storedValue)) {
102
- // Value reverted - update depsVersion and continue checking
103
- source.$_version = currentDepsVersion;
104
- continue;
105
- }
106
- }
107
- // Value actually changed - mark DIRTY and skip remaining
108
- sourceChanged = true;
109
- break;
110
- }
111
- } else {
112
- // Computed source - use sourceNode directly (already extracted above)
113
- try {
114
- computedRead(sourceNode);
115
- } catch {
116
- // Error counts as changed
117
- sourceChanged = true;
118
- break;
119
- }
120
- if (source.$_version !== sourceNode.$_version) {
121
- sourceChanged = true;
122
- break; // EXIT EARLY - don't process remaining sources
123
- }
124
- }
125
- }
126
- setTracked(prevTracked);
127
-
128
- if (sourceChanged) {
129
- // Source changed or threw - mark DIRTY and proceed to recompute
130
- self.$_flags = flags |= Flag.DIRTY;
131
- break checkCache;
132
- }
133
-
134
- // No sources changed - return cached value
135
- self.$_stamp = globalVersion;
136
- if ((flags & Flag.HAS_ERROR) !== 0) {
137
- throw self.$_value;
138
- }
139
- return self.$_value as T;
140
- }
141
- }
142
-
143
- // ===== PULL PHASE: Verify CHECK state for live computeds =====
144
- // Live computeds receive CHECK via push - verify sources before recomputing
145
- // Non-live computeds already verified above during polling
146
- // Note: Check for Flag.HAS_VALUE OR Flag.HAS_ERROR since cached errors should also use this path
147
- if ((flags & (Flag.DIRTY | Flag.CHECK | Flag.HAS_STATE_SOURCE)) === Flag.CHECK && hasCached) {
148
- if (checkComputedSources(sourcesArray)) {
149
- // Sources changed or errored - mark DIRTY and let getter run
150
- flags = (flags & ~Flag.CHECK) | Flag.DIRTY;
151
- } else {
152
- // Sources unchanged, clear CHECK flag and return cached value
153
- self.$_flags = flags & ~Flag.CHECK;
154
- // No sources changed - return cached value
155
- self.$_stamp = globalVersion;
156
- if ((flags & Flag.HAS_ERROR) !== 0) {
157
- throw self.$_value;
158
- }
159
- return self.$_value as T;
160
- }
161
- }
162
-
163
- // ===== PULL PHASE: Recompute value by pulling from sources =====
164
- // Recompute if dirty or check (sources actually changed)
165
- if ((flags & (Flag.DIRTY | Flag.CHECK)) !== 0) {
166
- const wasDirty = (flags & Flag.DIRTY) !== 0;
167
-
168
- runWithTracking(self, () => {
169
- try {
170
- const newValue = (self.$_fn as () => T)();
171
-
172
- // Check if value actually changed (common path: no error recovery)
173
- const changed = (flags & Flag.HAS_VALUE) === 0 || !(self.$_equals as (a: T, b: T) => boolean)(self.$_value as T, newValue);
174
-
175
- if (changed) {
176
- self.$_value = newValue;
177
- // Increment version to indicate value changed (for polling)
178
- ++self.$_version;
179
- self.$_flags = (self.$_flags | Flag.HAS_VALUE) & ~Flag.HAS_ERROR;
180
- // ===== PUSH PHASE (during pull): Mark CHECK-only dependents as DIRTY =====
181
- // When value changes during recomputation, upgrade dependent CHECK flags to DIRTY
182
- for (const dep of self.$_deps) {
183
- const depFlags = dep.$_flags;
184
- if ((depFlags & (Flag.COMPUTING | Flag.DIRTY | Flag.CHECK)) === Flag.CHECK) {
185
- dep.$_flags = depFlags | Flag.DIRTY;
186
- }
187
- }
188
- } else if (wasDirty) {
189
- self.$_flags |= Flag.HAS_VALUE;
190
- }
191
-
192
- // Update last seen global version
193
- self.$_stamp = globalVersion;
194
- } catch (e) {
195
- // Per TC39 Signals proposal: cache the error and mark as clean with error flag
196
- // The error will be rethrown on subsequent reads until a dependency changes
197
- // Reuse valueSymbol for error storage since a computed can't have both value and error
198
- // Increment version since the result changed (to error)
199
- ++self.$_version;
200
- self.$_value = e as T;
201
- self.$_flags = (self.$_flags & ~Flag.HAS_VALUE) | Flag.HAS_ERROR;
202
- self.$_stamp = globalVersion;
203
- }
204
- });
205
- }
206
-
207
- // Check if we have a cached error to rethrow (stored in valueSymbol)
208
- if ((self.$_flags & Flag.HAS_ERROR) !== 0) {
209
- throw self.$_value;
210
- }
211
-
212
- return self.$_value as T;
213
- }
214
-
215
- /**
216
- * Creates a computed value that automatically tracks dependencies and caches results
217
- */
218
- export const computed = <T>(getter: () => T, equals: (a: T, b: T) => boolean = Object.is): Computed<T> => {
219
- const node = {
220
- $_sources: [],
221
- $_deps: new DepsSet<ReactiveNode>(noopGetter),
222
- $_flags: Flag.DIRTY,
223
- $_skipped: 0,
224
- $_version: 0,
225
- $_value: undefined,
226
- $_stamp: 0,
227
- $_fn: getter,
228
- $_equals: equals,
229
- } as ReactiveNode;
230
-
231
- return () => computedRead(node);
232
- };