@slimlib/store 2.0.3 → 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.3",
3
+ "version": "2.1.0",
4
4
  "name": "@slimlib/store",
5
5
  "description": "Simple Proxy-based store for SPA",
6
6
  "license": "MIT",