@vielzeug/stateit 2.0.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.
Files changed (58) hide show
  1. package/README.md +337 -0
  2. package/dist/batch.cjs +2 -0
  3. package/dist/batch.cjs.map +1 -0
  4. package/dist/batch.d.ts +5 -0
  5. package/dist/batch.d.ts.map +1 -0
  6. package/dist/batch.js +28 -0
  7. package/dist/batch.js.map +1 -0
  8. package/dist/computed.cjs +2 -0
  9. package/dist/computed.cjs.map +1 -0
  10. package/dist/computed.d.ts +58 -0
  11. package/dist/computed.d.ts.map +1 -0
  12. package/dist/computed.js +65 -0
  13. package/dist/computed.js.map +1 -0
  14. package/dist/effect.cjs +2 -0
  15. package/dist/effect.cjs.map +1 -0
  16. package/dist/effect.d.ts +31 -0
  17. package/dist/effect.d.ts.map +1 -0
  18. package/dist/effect.js +53 -0
  19. package/dist/effect.js.map +1 -0
  20. package/dist/index.cjs +1 -0
  21. package/dist/index.d.ts +20 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +9 -0
  24. package/dist/runtime.cjs +2 -0
  25. package/dist/runtime.cjs.map +1 -0
  26. package/dist/runtime.d.ts +40 -0
  27. package/dist/runtime.d.ts.map +1 -0
  28. package/dist/runtime.js +47 -0
  29. package/dist/runtime.js.map +1 -0
  30. package/dist/signal.cjs +2 -0
  31. package/dist/signal.cjs.map +1 -0
  32. package/dist/signal.d.ts +26 -0
  33. package/dist/signal.d.ts.map +1 -0
  34. package/dist/signal.js +40 -0
  35. package/dist/signal.js.map +1 -0
  36. package/dist/stateit.cjs +2 -0
  37. package/dist/stateit.cjs.map +1 -0
  38. package/dist/stateit.js +270 -0
  39. package/dist/stateit.js.map +1 -0
  40. package/dist/store.cjs +2 -0
  41. package/dist/store.cjs.map +1 -0
  42. package/dist/store.d.ts +32 -0
  43. package/dist/store.d.ts.map +1 -0
  44. package/dist/store.js +51 -0
  45. package/dist/store.js.map +1 -0
  46. package/dist/types.cjs +2 -0
  47. package/dist/types.cjs.map +1 -0
  48. package/dist/types.d.ts +39 -0
  49. package/dist/types.d.ts.map +1 -0
  50. package/dist/types.js +6 -0
  51. package/dist/types.js.map +1 -0
  52. package/dist/watch.cjs +2 -0
  53. package/dist/watch.cjs.map +1 -0
  54. package/dist/watch.d.ts +36 -0
  55. package/dist/watch.d.ts.map +1 -0
  56. package/dist/watch.js +32 -0
  57. package/dist/watch.js.map +1 -0
  58. package/package.json +39 -0
package/dist/effect.js ADDED
@@ -0,0 +1,53 @@
1
+ import { _maxEffectIterations as e, _withCtx as t, scope as n } from "./runtime.js";
2
+ //#region src/effect.ts
3
+ var r = (n, r) => {
4
+ let i, a = /* @__PURE__ */ new Set(), o = !1, s = !1, c = !1, l = r?.maxIterations ?? e, u = () => {
5
+ i?.(), i = void 0;
6
+ for (let e of a) e();
7
+ a.clear();
8
+ }, d = () => {
9
+ s = !1, u();
10
+ let e = [], o, l = !1;
11
+ try {
12
+ t(f, a, e, () => {
13
+ let t = n();
14
+ typeof t == "function" && e.push(t);
15
+ });
16
+ } catch (e) {
17
+ if (r?.onError) l = !0, o = e;
18
+ else throw e;
19
+ }
20
+ return i = e.length > 0 ? () => {
21
+ for (let t of e) t();
22
+ } : void 0, l && (u(), r.onError(o), c = !0), l;
23
+ }, f = () => {
24
+ if (c || o) {
25
+ o && (s = !0);
26
+ return;
27
+ }
28
+ o = !0;
29
+ try {
30
+ let e = 0;
31
+ do {
32
+ if (++e > l) throw Error(`[stateit] effect: possible infinite reactive loop (> ${l} iterations)`);
33
+ if (d()) break;
34
+ } while (s);
35
+ } finally {
36
+ o = !1;
37
+ }
38
+ };
39
+ f();
40
+ let p = () => {
41
+ c || (c = !0, u());
42
+ };
43
+ return Object.assign(p, {
44
+ dispose: p,
45
+ [Symbol.dispose]: p
46
+ });
47
+ }, i = (e) => t(null, null, null, e), a = (e) => {
48
+ n.cleanups?.push(e);
49
+ };
50
+ //#endregion
51
+ export { r as effect, a as onCleanup, i as untrack };
52
+
53
+ //# sourceMappingURL=effect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effect.js","names":[],"sources":["../src/effect.ts"],"sourcesContent":["import { _DEV, _maxEffectIterations, _withCtx, scope } from './runtime';\nimport { type CleanupFn, type EffectCallback, type Subscription } from './types';\n\n/** Options for the `effect()` primitive. */\nexport type EffectOptions = {\n /**\n * Maximum re-entrant iterations before throwing to prevent infinite loops.\n * Overrides the global value set via `configureStateit` for this specific effect.\n */\n maxIterations?: number;\n /**\n * Called when the effect function throws. When provided, the effect is automatically\n * disposed after the first error — it won't re-run on subsequent dependency changes.\n */\n onError?: (error: unknown) => void;\n};\n\n/** Runs fn immediately and re-runs it whenever any Signal read inside it changes. Returns a dispose handle. */\nexport const effect = (fn: EffectCallback, options?: EffectOptions): Subscription => {\n let cleanup: CleanupFn | undefined;\n const deps = new Set<CleanupFn>();\n let running = false;\n let dirty = false;\n let disposed = false;\n const maxIter = options?.maxIterations ?? _maxEffectIterations;\n\n /** Tears down the current run: calls cleanup and unsubscribes all deps. */\n const teardown = (): void => {\n cleanup?.();\n cleanup = undefined;\n for (const unsub of deps) unsub();\n deps.clear();\n };\n\n /** Runs a single iteration: tears down previous deps/cleanup, re-executes fn, registers fresh deps.\n * Returns true if onError handled a throw (caller should break the loop). */\n const runIteration = (): boolean => {\n dirty = false;\n teardown();\n\n const cleanups: CleanupFn[] = [];\n let thrownError: unknown;\n let threw = false;\n\n try {\n _withCtx(runner, deps, cleanups, () => {\n const result = fn();\n\n if (typeof result === 'function') cleanups.push(result);\n });\n } catch (e) {\n if (options?.onError) {\n threw = true;\n thrownError = e;\n } else throw e;\n }\n\n cleanup =\n cleanups.length > 0\n ? () => {\n for (const c of cleanups) c();\n }\n : undefined;\n\n if (threw) {\n teardown(); // flush onCleanup registrations from the throwing run\n options!.onError!(thrownError);\n disposed = true;\n }\n\n return threw;\n };\n\n const runner: EffectCallback = () => {\n if (disposed || running) {\n if (running) dirty = true;\n\n return;\n }\n\n running = true;\n\n try {\n let iterations = 0;\n\n do {\n if (++iterations > maxIter)\n throw new Error(`[stateit] effect: possible infinite reactive loop (> ${maxIter} iterations)`);\n\n if (runIteration()) break;\n } while (dirty);\n } finally {\n running = false;\n }\n };\n\n runner();\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n teardown();\n };\n\n return Object.assign(dispose, { dispose, [Symbol.dispose]: dispose }) as Subscription;\n};\n\n/** Runs fn without registering any reactive dependencies. */\nexport const untrack = <T>(fn: () => T): T => _withCtx(null, null, null, fn);\n\n/**\n * Registers a cleanup function within the currently running effect.\n * Called before the effect re-runs and on final dispose.\n * Allows nested helpers to register teardown without needing the effect's return value.\n *\n * @example\n * effect(() => {\n * const id = setInterval(() => { ... }, 1000);\n * onCleanup(() => clearInterval(id));\n * });\n */\nexport const onCleanup = (fn: CleanupFn): void => {\n if (_DEV && scope.cleanups === null) {\n console.warn('[stateit] onCleanup() called outside of an active effect — the cleanup will never run.');\n }\n\n scope.cleanups?.push(fn);\n};\n"],"mappings":";;AAkBA,IAAa,KAAU,GAAoB,MAA0C;CACnF,IAAI,GACE,oBAAO,IAAI,KAAgB,EAC7B,IAAU,IACV,IAAQ,IACR,IAAW,IACT,IAAU,GAAS,iBAAiB,GAGpC,UAAuB;AAE3B,EADA,KAAW,EACX,IAAU,KAAA;AACV,OAAK,IAAM,KAAS,EAAM,IAAO;AACjC,IAAK,OAAO;IAKR,UAA8B;AAElC,EADA,IAAQ,IACR,GAAU;EAEV,IAAM,IAAwB,EAAE,EAC5B,GACA,IAAQ;AAEZ,MAAI;AACF,KAAS,GAAQ,GAAM,SAAgB;IACrC,IAAM,IAAS,GAAI;AAEnB,IAAI,OAAO,KAAW,cAAY,EAAS,KAAK,EAAO;KACvD;WACK,GAAG;AACV,OAAI,GAAS,QAEX,CADA,IAAQ,IACR,IAAc;OACT,OAAM;;AAgBf,SAbA,IACE,EAAS,SAAS,UACR;AACJ,QAAK,IAAM,KAAK,EAAU,IAAG;MAE/B,KAAA,GAEF,MACF,GAAU,EACV,EAAS,QAAS,EAAY,EAC9B,IAAW,KAGN;IAGH,UAA+B;AACnC,MAAI,KAAY,GAAS;AACvB,GAAI,MAAS,IAAQ;AAErB;;AAGF,MAAU;AAEV,MAAI;GACF,IAAI,IAAa;AAEjB,MAAG;AACD,QAAI,EAAE,IAAa,EACjB,OAAU,MAAM,wDAAwD,EAAQ,cAAc;AAEhG,QAAI,GAAc,CAAE;YACb;YACD;AACR,OAAU;;;AAId,IAAQ;CAER,IAAM,UAAsB;AACtB,QAEJ,IAAW,IACX,GAAU;;AAGZ,QAAO,OAAO,OAAO,GAAS;EAAE;GAAU,OAAO,UAAU;EAAS,CAAC;GAI1D,KAAc,MAAmB,EAAS,MAAM,MAAM,MAAM,EAAG,EAa/D,KAAa,MAAwB;AAKhD,GAAM,UAAU,KAAK,EAAG"}
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./runtime.cjs`),t=require(`./batch.cjs`),n=require(`./types.cjs`),r=require(`./computed.cjs`),i=require(`./effect.cjs`),a=require(`./signal.cjs`),o=require(`./store.cjs`),s=require(`./watch.cjs`);exports.ComputedNode=r.ComputedNode,exports.SignalImpl=a.SignalImpl,exports.WritableNode=r.WritableNode,exports._SIGNAL_BRAND=n._SIGNAL_BRAND,exports._STORE_BRAND=n._STORE_BRAND,exports._flushPending=t._flushPending,exports._resetContextForTesting=e._resetContextForTesting,exports.batch=t.batch,exports.computed=r.computed,exports.configureStateit=e.configureStateit,exports.derived=r.derived,exports.effect=i.effect,exports.isSignal=a.isSignal,exports.isStore=o.isStore,exports.nextValue=s.nextValue,exports.onCleanup=i.onCleanup,exports.peekValue=a.peekValue,exports.readonly=a.readonly,exports.shallowEqual=o.shallowEqual,exports.signal=a.signal,exports.store=o.store,exports.toValue=a.toValue,exports.untrack=i.untrack,exports.watch=s.watch,exports.writable=r.writable;
@@ -0,0 +1,20 @@
1
+ /** stateit -- Lightweight reactive state
2
+ *
3
+ * Reactive primitives:
4
+ * Signal<T> -- synchronous, fine-grained reactive atom
5
+ * ReadonlySignal<T> -- read-only view of a signal
6
+ * Store<T> -- object-state store with set/freeze/reset/select
7
+ *
8
+ * All primitives interoperate: computed, derived, effect, watch, batch,
9
+ * untrack, onCleanup, toValue, configureStateit work uniformly
10
+ * on Signal<T> and Store<T>.
11
+ */
12
+ export * from './batch';
13
+ export * from './computed';
14
+ export * from './effect';
15
+ export { _resetContextForTesting, configureStateit } from './runtime';
16
+ export * from './signal';
17
+ export * from './store';
18
+ export * from './types';
19
+ export * from './watch';
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AACtE,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ import { _resetContextForTesting as e, configureStateit as t } from "./runtime.js";
2
+ import { _flushPending as n, batch as r } from "./batch.js";
3
+ import { _SIGNAL_BRAND as i, _STORE_BRAND as a } from "./types.js";
4
+ import { ComputedNode as o, WritableNode as s, computed as c, derived as l, writable as u } from "./computed.js";
5
+ import { effect as d, onCleanup as f, untrack as p } from "./effect.js";
6
+ import { SignalImpl as m, isSignal as h, peekValue as g, readonly as _, signal as v, toValue as y } from "./signal.js";
7
+ import { isStore as b, shallowEqual as x, store as S } from "./store.js";
8
+ import { nextValue as C, watch as w } from "./watch.js";
9
+ export { o as ComputedNode, m as SignalImpl, s as WritableNode, i as _SIGNAL_BRAND, a as _STORE_BRAND, n as _flushPending, e as _resetContextForTesting, r as batch, c as computed, t as configureStateit, l as derived, d as effect, h as isSignal, b as isStore, C as nextValue, f as onCleanup, g as peekValue, _ as readonly, x as shallowEqual, v as signal, S as store, y as toValue, p as untrack, w as watch, u as writable };
@@ -0,0 +1,2 @@
1
+ var e=Symbol(`stateit.uninitialized`),t={cleanups:null,deps:null,effect:null},n={depth:0,pending:new Set},r=100,i=e=>{e.maxEffectIterations!==void 0&&(r=e.maxEffectIterations)},a=()=>{n.depth=0,t.deps=null,t.effect=null,t.cleanups=null,n.pending.clear()},o=class{#e=new Set;_track(){if(t.deps!==null&&t.effect!==null){let e=t.effect;this.#e.add(e),t.deps.add(()=>this.#e.delete(e))}}_notify(){if(this.#e.size===0)return;if(n.depth>0){for(let e of this.#e)n.pending.add(e);return}let e=[];for(let t of[...this.#e])try{t()}catch(t){e.push(t)}if(e.length)throw e.length===1?e[0]:AggregateError(e,`[stateit] multiple subscriber errors`)}},s=(e,n,r,i)=>{let a=t.effect,o=t.deps,s=t.cleanups;t.effect=e,t.deps=n,t.cleanups=r;try{return i()}finally{t.effect=a,t.deps=o,t.cleanups=s}};exports.ReactiveNode=o,exports._UNINITIALIZED=e,Object.defineProperty(exports,`_maxEffectIterations`,{enumerable:!0,get:function(){return r}}),exports._resetContextForTesting=a,exports._withCtx=s,exports.configureStateit=i,exports.queue=n,exports.scope=t;
2
+ //# sourceMappingURL=runtime.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.cjs","names":["#subscribers"],"sources":["../src/runtime.ts"],"sourcesContent":["import type { CleanupFn, EffectCallback } from './types';\n\n/** @internal True outside of production builds; gates dev-only warnings. */\nexport const _DEV = import.meta.env.DEV;\n\nexport const _UNINITIALIZED = Symbol('stateit.uninitialized');\n\n/** @internal Active reactive tracking scope — null outside any effect/computed. */\nexport const scope = {\n cleanups: null as CleanupFn[] | null,\n deps: null as Set<CleanupFn> | null,\n effect: null as EffectCallback | null,\n};\n\n/** @internal Deferred notification queue — active only during batch(). */\nexport const queue = {\n depth: 0,\n pending: new Set<EffectCallback>(),\n};\n\nexport let _maxEffectIterations = 100;\n\n/**\n * Configures global stateit behaviour.\n * @example configureStateit({ maxEffectIterations: 200 });\n */\nexport const configureStateit = (opts: { maxEffectIterations?: number }): void => {\n if (opts.maxEffectIterations !== undefined) _maxEffectIterations = opts.maxEffectIterations;\n};\n\n/**\n * Resets the shared reactive context. Use in test setup/teardown to prevent state\n * leaks between tests when a batch or effect throws without being fully cleaned up.\n */\nexport const _resetContextForTesting = (): void => {\n queue.depth = 0;\n scope.deps = null;\n scope.effect = null;\n scope.cleanups = null;\n queue.pending.clear();\n};\n\n/** @internal Base reactive node: manages a subscriber set and batch-aware notification. */\nexport class ReactiveNode {\n #subscribers = new Set<EffectCallback>();\n\n /** Register the current tracking scope as a subscriber and store an unsubscribe\n * function in scope.deps for automatic cleanup when the effect re-runs. */\n protected _track(): void {\n if (scope.deps !== null && scope.effect !== null) {\n const fn = scope.effect;\n\n this.#subscribers.add(fn);\n scope.deps.add(() => this.#subscribers.delete(fn));\n }\n }\n\n /** Notify all subscribers. Respects batch queue depth. */\n protected _notify(): void {\n if (this.#subscribers.size === 0) return;\n\n if (queue.depth > 0) {\n for (const fn of this.#subscribers) queue.pending.add(fn);\n\n return;\n }\n\n const errors: unknown[] = [];\n\n for (const fn of [...this.#subscribers]) {\n try {\n fn();\n } catch (e) {\n errors.push(e);\n }\n }\n\n if (errors.length) {\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, '[stateit] multiple subscriber errors');\n }\n }\n}\n\n/** @internal Save scope fields, swap to new tracking context, call fn, restore. */\nexport const _withCtx = <T>(\n eff: EffectCallback | null,\n deps: Set<CleanupFn> | null,\n cleanups: CleanupFn[] | null,\n fn: () => T,\n): T => {\n const pe = scope.effect;\n const pd = scope.deps;\n const pc = scope.cleanups;\n\n scope.effect = eff;\n scope.deps = deps;\n scope.cleanups = cleanups;\n\n try {\n return fn();\n } finally {\n scope.effect = pe;\n scope.deps =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internal True outside of production builds; gates dev-only warnings. */
3
+ export declare const _DEV: boolean;
4
+ export declare const _UNINITIALIZED: unique symbol;
5
+ /** @internal Active reactive tracking scope — null outside any effect/computed. */
6
+ export declare const scope: {
7
+ cleanups: CleanupFn[] | null;
8
+ deps: Set<CleanupFn> | null;
9
+ effect: EffectCallback | null;
10
+ };
11
+ /** @internal Deferred notification queue — active only during batch(). */
12
+ export declare const queue: {
13
+ depth: number;
14
+ pending: Set<EffectCallback>;
15
+ };
16
+ export declare let _maxEffectIterations: number;
17
+ /**
18
+ * Configures global stateit behaviour.
19
+ * @example configureStateit({ maxEffectIterations: 200 });
20
+ */
21
+ export declare const configureStateit: (opts: {
22
+ maxEffectIterations?: number;
23
+ }) => void;
24
+ /**
25
+ * Resets the shared reactive context. Use in test setup/teardown to prevent state
26
+ * leaks between tests when a batch or effect throws without being fully cleaned up.
27
+ */
28
+ export declare const _resetContextForTesting: () => void;
29
+ /** @internal Base reactive node: manages a subscriber set and batch-aware notification. */
30
+ export declare class ReactiveNode {
31
+ #private;
32
+ /** Register the current tracking scope as a subscriber and store an unsubscribe
33
+ * function in scope.deps for automatic cleanup when the effect re-runs. */
34
+ protected _track(): void;
35
+ /** Notify all subscribers. Respects batch queue depth. */
36
+ protected _notify(): void;
37
+ }
38
+ /** @internal Save scope fields, swap to new tracking context, call fn, restore. */
39
+ export declare const _withCtx: <T>(eff: EffectCallback | null, deps: Set<CleanupFn> | null, cleanups: CleanupFn[] | null, fn: () => T) => T;
40
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzD,4EAA4E;AAC5E,eAAO,MAAM,IAAI,SAAsB,CAAC;AAExC,eAAO,MAAM,cAAc,eAAkC,CAAC;AAE9D,mFAAmF;AACnF,eAAO,MAAM,KAAK;cACE,SAAS,EAAE,GAAG,IAAI;UACtB,GAAG,CAAC,SAAS,CAAC,GAAG,IAAI;YACnB,cAAc,GAAG,IAAI;CACtC,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,KAAK;;;CAGjB,CAAC;AAEF,eAAO,IAAI,oBAAoB,QAAM,CAAC;AAEtC;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,MAAM;IAAE,mBAAmB,CAAC,EAAE,MAAM,CAAA;CAAE,KAAG,IAEzE,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAAO,IAM1C,CAAC;AAEF,2FAA2F;AAC3F,qBAAa,YAAY;;IAGvB;gFAC4E;IAC5E,SAAS,CAAC,MAAM,IAAI,IAAI;IASxB,0DAA0D;IAC1D,SAAS,CAAC,OAAO,IAAI,IAAI;CAuB1B;AAED,mFAAmF;AACnF,eAAO,MAAM,QAAQ,GAAI,CAAC,EACxB,KAAK,cAAc,GAAG,IAAI,EAC1B,MAAM,GAAG,CAAC,SAAS,CAAC,GAAG,IAAI,EAC3B,UAAU,SAAS,EAAE,GAAG,IAAI,EAC5B,IAAI,MAAM,CAAC,KACV,CAgBF,CAAC"}
@@ -0,0 +1,47 @@
1
+ //#region src/runtime.ts
2
+ var e = Symbol("stateit.uninitialized"), t = {
3
+ cleanups: null,
4
+ deps: null,
5
+ effect: null
6
+ }, n = {
7
+ depth: 0,
8
+ pending: /* @__PURE__ */ new Set()
9
+ }, r = 100, i = (e) => {
10
+ e.maxEffectIterations !== void 0 && (r = e.maxEffectIterations);
11
+ }, a = () => {
12
+ n.depth = 0, t.deps = null, t.effect = null, t.cleanups = null, n.pending.clear();
13
+ }, o = class {
14
+ #e = /* @__PURE__ */ new Set();
15
+ _track() {
16
+ if (t.deps !== null && t.effect !== null) {
17
+ let e = t.effect;
18
+ this.#e.add(e), t.deps.add(() => this.#e.delete(e));
19
+ }
20
+ }
21
+ _notify() {
22
+ if (this.#e.size === 0) return;
23
+ if (n.depth > 0) {
24
+ for (let e of this.#e) n.pending.add(e);
25
+ return;
26
+ }
27
+ let e = [];
28
+ for (let t of [...this.#e]) try {
29
+ t();
30
+ } catch (t) {
31
+ e.push(t);
32
+ }
33
+ if (e.length) throw e.length === 1 ? e[0] : AggregateError(e, "[stateit] multiple subscriber errors");
34
+ }
35
+ }, s = (e, n, r, i) => {
36
+ let a = t.effect, o = t.deps, s = t.cleanups;
37
+ t.effect = e, t.deps = n, t.cleanups = r;
38
+ try {
39
+ return i();
40
+ } finally {
41
+ t.effect = a, t.deps = o, t.cleanups = s;
42
+ }
43
+ };
44
+ //#endregion
45
+ export { o as ReactiveNode, e as _UNINITIALIZED, r as _maxEffectIterations, a as _resetContextForTesting, s as _withCtx, i as configureStateit, n as queue, t as scope };
46
+
47
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","names":["#subscribers"],"sources":["../src/runtime.ts"],"sourcesContent":["import type { CleanupFn, EffectCallback } from './types';\n\n/** @internal True outside of production builds; gates dev-only warnings. */\nexport const _DEV = import.meta.env.DEV;\n\nexport const _UNINITIALIZED = Symbol('stateit.uninitialized');\n\n/** @internal Active reactive tracking scope — null outside any effect/computed. */\nexport const scope = {\n cleanups: null as CleanupFn[] | null,\n deps: null as Set<CleanupFn> | null,\n effect: null as EffectCallback | null,\n};\n\n/** @internal Deferred notification queue — active only during batch(). */\nexport const queue = {\n depth: 0,\n pending: new Set<EffectCallback>(),\n};\n\nexport let _maxEffectIterations = 100;\n\n/**\n * Configures global stateit behaviour.\n * @example configureStateit({ maxEffectIterations: 200 });\n */\nexport const configureStateit = (opts: { maxEffectIterations?: number }): void => {\n if (opts.maxEffectIterations !== undefined) _maxEffectIterations = opts.maxEffectIterations;\n};\n\n/**\n * Resets the shared reactive context. Use in test setup/teardown to prevent state\n * leaks between tests when a batch or effect throws without being fully cleaned up.\n */\nexport const _resetContextForTesting = (): void => {\n queue.depth = 0;\n scope.deps = null;\n scope.effect = null;\n scope.cleanups = null;\n queue.pending.clear();\n};\n\n/** @internal Base reactive node: manages a subscriber set and batch-aware notification. */\nexport class ReactiveNode {\n #subscribers = new Set<EffectCallback>();\n\n /** Register the current tracking scope as a subscriber and store an unsubscribe\n * function in scope.deps for automatic cleanup when the effect re-runs. */\n protected _track(): void {\n if (scope.deps !== null && scope.effect !== null) {\n const fn = scope.effect;\n\n this.#subscribers.add(fn);\n scope.deps.add(() => this.#subscribers.delete(fn));\n }\n }\n\n /** Notify all subscribers. Respects batch queue depth. */\n protected _notify(): void {\n if (this.#subscribers.size === 0) return;\n\n if (queue.depth > 0) {\n for (const fn of this.#subscribers) queue.pending.add(fn);\n\n return;\n }\n\n const errors: unknown[] = [];\n\n for (const fn of [...this.#subscribers]) {\n try {\n fn();\n } catch (e) {\n errors.push(e);\n }\n }\n\n if (errors.length) {\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, '[stateit] multiple subscriber errors');\n }\n }\n}\n\n/** @internal Save scope fields, swap to new tracking context, call fn, restore. */\nexport const _withCtx = <T>(\n eff: EffectCallback | null,\n deps: Set<CleanupFn> | null,\n cleanups: CleanupFn[] | null,\n fn: () => T,\n): T => {\n const pe = scope.effect;\n const pd = scope.deps;\n const pc = scope.cleanups;\n\n scope.effect = eff;\n scope.deps = deps;\n scope.cleanups = cleanups;\n\n try {\n return fn();\n } finally {\n scope.effect = pe;\n scope.deps = pd;\n scope.cleanups = pc;\n }\n};\n"],"mappings":";AAKA,IAAa,IAAiB,OAAO,wBAAwB,EAGhD,IAAQ;CACnB,UAAU;CACV,MAAM;CACN,QAAQ;CACT,EAGY,IAAQ;CACnB,OAAO;CACP,yBAAS,IAAI,KAAqB;CACnC,EAEU,IAAuB,KAMrB,KAAoB,MAAiD;AAChF,CAAI,EAAK,wBAAwB,KAAA,MAAW,IAAuB,EAAK;GAO7D,UAAsC;AAKjD,CAJA,EAAM,QAAQ,GACd,EAAM,OAAO,MACb,EAAM,SAAS,MACf,EAAM,WAAW,MACjB,EAAM,QAAQ,OAAO;GAIV,IAAb,MAA0B;CACxB,qBAAe,IAAI,KAAqB;CAIxC,SAAyB;AACvB,MAAI,EAAM,SAAS,QAAQ,EAAM,WAAW,MAAM;GAChD,IAAM,IAAK,EAAM;AAGjB,GADA,MAAA,EAAkB,IAAI,EAAG,EACzB,EAAM,KAAK,UAAU,MAAA,EAAkB,OAAO,EAAG,CAAC;;;CAKtD,UAA0B;AACxB,MAAI,MAAA,EAAkB,SAAS,EAAG;AAElC,MAAI,EAAM,QAAQ,GAAG;AACnB,QAAK,IAAM,KAAM,MAAA,EAAmB,GAAM,QAAQ,IAAI,EAAG;AAEzD;;EAGF,IAAM,IAAoB,EAAE;AAE5B,OAAK,IAAM,KAAM,CAAC,GAAG,MAAA,EAAkB,CACrC,KAAI;AACF,MAAI;WACG,GAAG;AACV,KAAO,KAAK,EAAE;;AAIlB,MAAI,EAAO,OACT,OAAM,EAAO,WAAW,IAAI,EAAO,KAAS,eAAe,GAAQ,uCAAuC;;GAMnG,KACX,GACA,GACA,GACA,MACM;CACN,IAAM,IAAK,EAAM,QACX,IAAK,EAAM,MACX,IAAK,EAAM;AAIjB,CAFA,EAAM,SAAS,GACf,EAAM,OAAO,GACb,EAAM,WAAW;AAEjB,KAAI;AACF,SAAO,GAAI;WACH;AAGR,EAFA,EAAM,SAAS,GACf,EAAM,OAAO,GACb,EAAM,WAAW"}
@@ -0,0 +1,2 @@
1
+ const e=require(`./runtime.cjs`),t=require(`./types.cjs`);var n=class extends e.ReactiveNode{[t._SIGNAL_BRAND]=!0;#e;#t;constructor(e,t){super(),this.#e=e,this.#t=t?.equals??Object.is}get value(){return this._track(),this.#e}set value(e){this.#t(this.#e,e)||(this.#e=e,this._notify())}update(e){this.value=e(this.#e)}peek(){return this.#e}},r=(e,t)=>new n(e,t),i=new WeakMap,a=e=>{let n=i.get(e);if(n)return n;let r={get[t._SIGNAL_BRAND](){return!0},peek:()=>e.peek(),get value(){return e.value}};return i.set(e,r),r},o=e=>typeof e==`object`&&!!e&&t._SIGNAL_BRAND in e,s=e=>o(e)?e.value:e,c=e=>o(e)?e.peek():e;exports.SignalImpl=n,exports.isSignal=o,exports.peekValue=c,exports.readonly=a,exports.signal=r,exports.toValue=s;
2
+ //# sourceMappingURL=signal.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal.cjs","names":["#value","#equals"],"sources":["../src/signal.ts"],"sourcesContent":["import { ReactiveNode } from './runtime';\nimport { type EqualityFn, type ReactiveOptions, type ReadonlySignal, type Signal, _SIGNAL_BRAND } from './types';\n\n/** @internal */\nexport class SignalImpl<T> extends ReactiveNode implements Signal<T> {\n readonly [_SIGNAL_BRAND] = true as const;\n #value: T;\n #equals: EqualityFn<T>;\n\n constructor(initial: T, options?: ReactiveOptions<T>) {\n super();\n this.#value = initial;\n this.#equals = options?.equals ?? Object.is;\n }\n\n get value(): T {\n this._track();\n\n return this.#value;\n }\n\n set value(next: T) {\n if (this.#equals(this.#value, next)) return;\n\n this.#value = next;\n this._notify();\n }\n\n update(fn: (current: T) => T): void {\n this.value = fn(this.#value);\n }\n\n peek(): T {\n return this.#value;\n }\n}\n\n/** Creates a reactive signal holding a single value. */\nexport const signal = <T>(initial: T, options?: ReactiveOptions<T>): Signal<T> => new SignalImpl(initial, options);\n\nconst _readonlyCache = new WeakMap<object, ReadonlySignal<unknown>>();\n\n/**\n * Returns a stable read-only view of a signal. Hides the setter at both type and runtime\n * level. The wrapper is cached — repeated calls with the same signal return the same reference.\n */\nexport const readonly = <T>(sig: ReadonlySignal<T>): ReadonlySignal<T> => {\n const cached = _readonlyCache.get(sig as object);\n\n if (cached) return cached as ReadonlySignal<T>;\n\n const wrapper: ReadonlySignal<T> = {\n get [_SIGNAL_BRAND]() {\n return true as const;\n },\n peek: () => sig.peek(),\n get value() {\n return sig.value;\n },\n };\n\n _readonlyCache.set(sig as object, wrapper as ReadonlySignal<unknown>);\n\n return wrapper;\n};\n\n/** Type guard -- identifies Signal instances (works through composition and subclasses). */\nexport const isSignal = <T = unknown>(value: unknown): value is ReadonlySignal<T> =>\n typeof value === 'object' && value !== null && _SIGNAL_BRAND in (value as object);\n\n/** Unwraps a plain value or Signal to its current value. Reads are tracked if called inside an effect. */\nexport const toValue = <T>(v: T | ReadonlySignal<T>): T => (isSignal<T>(v) ? v.value : v);\n\n/** Unwraps a plain value or Signal to its current value without registering a reactive subscription. */\nexport const peekValue = <T>(v: T | ReadonlySignal<T>): T => (isSignal<T>(v) ? v.peek() : v);\n"],"mappings":"0DAIA,IAAa,EAAb,cAAmC,EAAA,YAAkC,CACnE,CAAU,EAAA,eAAiB,GAC3B,GACA,GAEA,YAAY,EAAY,EAA8B,CACpD,OAAO,CACP,MAAA,EAAc,EACd,MAAA,EAAe,GAAS,QAAU,OAAO,GAG3C,IAAI,OAAW,CAGb,OAFA,KAAK,QAAQ,CAEN,MAAA,EAGT,IAAI,MAAM,EAAS,CACb,MAAA,EAAa,MAAA,EAAa,EAAK,GAEnC,MAAA,EAAc,EACd,KAAK,SAAS,EAGhB,OAAO,EAA6B,CAClC,KAAK,MAAQ,EAAG,MAAA,EAAY,CAG9B,MAAU,CACR,OAAO,MAAA,IAKE,GAAa,EAAY,IAA4C,IAAI,EAAW,EAAS,EAAQ,CAE5G,EAAiB,IAAI,QAMd,EAAe,GAA8C,CACxE,IAAM,EAAS,EAAe,IAAI,EAAc,CAEhD,GAAI,EAAQ,OAAO,EAEnB,IAAM,EAA6B,CACjC,IAAK,EAAA,gBAAiB,CACpB,MAAO,IAET,SAAY,EAAI,MAAM,CACtB,IAAI,OAAQ,CACV,OAAO,EAAI,OAEd,CAID,OAFA,EAAe,IAAI,EAAe,EAAmC,CAE9D,GAII,EAAyB,GACpC,OAAO,GAAU,YAAY,GAAkB,EAAA,iBAAkB,EAGtD,EAAc,GAAiC,EAAY,EAAE,CAAG,EAAE,MAAQ,EAG1E,EAAgB,GAAiC,EAAY,EAAE,CAAG,EAAE,MAAM,CAAG"}
@@ -0,0 +1,26 @@
1
+ import { ReactiveNode } from './runtime';
2
+ import { type ReactiveOptions, type ReadonlySignal, type Signal, _SIGNAL_BRAND } from './types';
3
+ /** @internal */
4
+ export declare class SignalImpl<T> extends ReactiveNode implements Signal<T> {
5
+ #private;
6
+ readonly [_SIGNAL_BRAND]: true;
7
+ constructor(initial: T, options?: ReactiveOptions<T>);
8
+ get value(): T;
9
+ set value(next: T);
10
+ update(fn: (current: T) => T): void;
11
+ peek(): T;
12
+ }
13
+ /** Creates a reactive signal holding a single value. */
14
+ export declare const signal: <T>(initial: T, options?: ReactiveOptions<T>) => Signal<T>;
15
+ /**
16
+ * Returns a stable read-only view of a signal. Hides the setter at both type and runtime
17
+ * level. The wrapper is cached — repeated calls with the same signal return the same reference.
18
+ */
19
+ export declare const readonly: <T>(sig: ReadonlySignal<T>) => ReadonlySignal<T>;
20
+ /** Type guard -- identifies Signal instances (works through composition and subclasses). */
21
+ export declare const isSignal: <T = unknown>(value: unknown) => value is ReadonlySignal<T>;
22
+ /** Unwraps a plain value or Signal to its current value. Reads are tracked if called inside an effect. */
23
+ export declare const toValue: <T>(v: T | ReadonlySignal<T>) => T;
24
+ /** Unwraps a plain value or Signal to its current value without registering a reactive subscription. */
25
+ export declare const peekValue: <T>(v: T | ReadonlySignal<T>) => T;
26
+ //# sourceMappingURL=signal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal.d.ts","sourceRoot":"","sources":["../src/signal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAmB,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,KAAK,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAEjH,gBAAgB;AAChB,qBAAa,UAAU,CAAC,CAAC,CAAE,SAAQ,YAAa,YAAW,MAAM,CAAC,CAAC,CAAC;;IAClE,QAAQ,CAAC,CAAC,aAAa,CAAC,EAAG,IAAI,CAAU;gBAI7B,OAAO,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC;IAMpD,IAAI,KAAK,IAAI,CAAC,CAIb;IAED,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,EAKhB;IAED,MAAM,CAAC,EAAE,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI;IAInC,IAAI,IAAI,CAAC;CAGV;AAED,wDAAwD;AACxD,eAAO,MAAM,MAAM,GAAI,CAAC,EAAE,SAAS,CAAC,EAAE,UAAU,eAAe,CAAC,CAAC,CAAC,KAAG,MAAM,CAAC,CAAC,CAAqC,CAAC;AAInH;;;GAGG;AACH,eAAO,MAAM,QAAQ,GAAI,CAAC,EAAE,KAAK,cAAc,CAAC,CAAC,CAAC,KAAG,cAAc,CAAC,CAAC,CAkBpE,CAAC;AAEF,4FAA4F;AAC5F,eAAO,MAAM,QAAQ,GAAI,CAAC,GAAG,OAAO,EAAE,OAAO,OAAO,KAAG,KAAK,IAAI,cAAc,CAAC,CAAC,CACG,CAAC;AAEpF,0GAA0G;AAC1G,eAAO,MAAM,OAAO,GAAI,CAAC,EAAE,GAAG,CAAC,GAAG,cAAc,CAAC,CAAC,CAAC,KAAG,CAAmC,CAAC;AAE1F,wGAAwG;AACxG,eAAO,MAAM,SAAS,GAAI,CAAC,EAAE,GAAG,CAAC,GAAG,cAAc,CAAC,CAAC,CAAC,KAAG,CAAoC,CAAC"}
package/dist/signal.js ADDED
@@ -0,0 +1,40 @@
1
+ import { ReactiveNode as e } from "./runtime.js";
2
+ import { _SIGNAL_BRAND as t } from "./types.js";
3
+ //#region src/signal.ts
4
+ var n = class extends e {
5
+ [t] = !0;
6
+ #e;
7
+ #t;
8
+ constructor(e, t) {
9
+ super(), this.#e = e, this.#t = t?.equals ?? Object.is;
10
+ }
11
+ get value() {
12
+ return this._track(), this.#e;
13
+ }
14
+ set value(e) {
15
+ this.#t(this.#e, e) || (this.#e = e, this._notify());
16
+ }
17
+ update(e) {
18
+ this.value = e(this.#e);
19
+ }
20
+ peek() {
21
+ return this.#e;
22
+ }
23
+ }, r = (e, t) => new n(e, t), i = /* @__PURE__ */ new WeakMap(), a = (e) => {
24
+ let n = i.get(e);
25
+ if (n) return n;
26
+ let r = {
27
+ get [t]() {
28
+ return !0;
29
+ },
30
+ peek: () => e.peek(),
31
+ get value() {
32
+ return e.value;
33
+ }
34
+ };
35
+ return i.set(e, r), r;
36
+ }, o = (e) => typeof e == "object" && !!e && t in e, s = (e) => o(e) ? e.value : e, c = (e) => o(e) ? e.peek() : e;
37
+ //#endregion
38
+ export { n as SignalImpl, o as isSignal, c as peekValue, a as readonly, r as signal, s as toValue };
39
+
40
+ //# sourceMappingURL=signal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signal.js","names":["#value","#equals"],"sources":["../src/signal.ts"],"sourcesContent":["import { ReactiveNode } from './runtime';\nimport { type EqualityFn, type ReactiveOptions, type ReadonlySignal, type Signal, _SIGNAL_BRAND } from './types';\n\n/** @internal */\nexport class SignalImpl<T> extends ReactiveNode implements Signal<T> {\n readonly [_SIGNAL_BRAND] = true as const;\n #value: T;\n #equals: EqualityFn<T>;\n\n constructor(initial: T, options?: ReactiveOptions<T>) {\n super();\n this.#value = initial;\n this.#equals = options?.equals ?? Object.is;\n }\n\n get value(): T {\n this._track();\n\n return this.#value;\n }\n\n set value(next: T) {\n if (this.#equals(this.#value, next)) return;\n\n this.#value = next;\n this._notify();\n }\n\n update(fn: (current: T) => T): void {\n this.value = fn(this.#value);\n }\n\n peek(): T {\n return this.#value;\n }\n}\n\n/** Creates a reactive signal holding a single value. */\nexport const signal = <T>(initial: T, options?: ReactiveOptions<T>): Signal<T> => new SignalImpl(initial, options);\n\nconst _readonlyCache = new WeakMap<object, ReadonlySignal<unknown>>();\n\n/**\n * Returns a stable read-only view of a signal. Hides the setter at both type and runtime\n * level. The wrapper is cached — repeated calls with the same signal return the same reference.\n */\nexport const readonly = <T>(sig: ReadonlySignal<T>): ReadonlySignal<T> => {\n const cached = _readonlyCache.get(sig as object);\n\n if (cached) return cached as ReadonlySignal<T>;\n\n const wrapper: ReadonlySignal<T> = {\n get [_SIGNAL_BRAND]() {\n return true as const;\n },\n peek: () => sig.peek(),\n get value() {\n return sig.value;\n },\n };\n\n _readonlyCache.set(sig as object, wrapper as ReadonlySignal<unknown>);\n\n return wrapper;\n};\n\n/** Type guard -- identifies Signal instances (works through composition and subclasses). */\nexport const isSignal = <T = unknown>(value: unknown): value is ReadonlySignal<T> =>\n typeof value === 'object' && value !== null && _SIGNAL_BRAND in (value as object);\n\n/** Unwraps a plain value or Signal to its current value. Reads are tracked if called inside an effect. */\nexport const toValue = <T>(v: T | ReadonlySignal<T>): T => (isSignal<T>(v) ? v.value : v);\n\n/** Unwraps a plain value or Signal to its current value without registering a reactive subscription. */\nexport const peekValue = <T>(v: T | ReadonlySignal<T>): T => (isSignal<T>(v) ? v.peek() : v);\n"],"mappings":";;;AAIA,IAAa,IAAb,cAAmC,EAAkC;CACnE,CAAU,KAAiB;CAC3B;CACA;CAEA,YAAY,GAAY,GAA8B;AAGpD,EAFA,OAAO,EACP,MAAA,IAAc,GACd,MAAA,IAAe,GAAS,UAAU,OAAO;;CAG3C,IAAI,QAAW;AAGb,SAFA,KAAK,QAAQ,EAEN,MAAA;;CAGT,IAAI,MAAM,GAAS;AACb,QAAA,EAAa,MAAA,GAAa,EAAK,KAEnC,MAAA,IAAc,GACd,KAAK,SAAS;;CAGhB,OAAO,GAA6B;AAClC,OAAK,QAAQ,EAAG,MAAA,EAAY;;CAG9B,OAAU;AACR,SAAO,MAAA;;GAKE,KAAa,GAAY,MAA4C,IAAI,EAAW,GAAS,EAAQ,EAE5G,oBAAiB,IAAI,SAA0C,EAMxD,KAAe,MAA8C;CACxE,IAAM,IAAS,EAAe,IAAI,EAAc;AAEhD,KAAI,EAAQ,QAAO;CAEnB,IAAM,IAA6B;EACjC,KAAK,KAAiB;AACpB,UAAO;;EAET,YAAY,EAAI,MAAM;EACtB,IAAI,QAAQ;AACV,UAAO,EAAI;;EAEd;AAID,QAFA,EAAe,IAAI,GAAe,EAAmC,EAE9D;GAII,KAAyB,MACpC,OAAO,KAAU,cAAY,KAAkB,KAAkB,GAGtD,KAAc,MAAiC,EAAY,EAAE,GAAG,EAAE,QAAQ,GAG1E,KAAgB,MAAiC,EAAY,EAAE,GAAG,EAAE,MAAM,GAAG"}
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Symbol(`stateit.uninitialized`),t={cleanups:null,deps:null,effect:null},n={depth:0,pending:new Set},r=100,i=e=>{e.maxEffectIterations!==void 0&&(r=e.maxEffectIterations)},a=()=>{n.depth=0,t.deps=null,t.effect=null,t.cleanups=null,n.pending.clear()},o=class{#e=new Set;_track(){if(t.deps!==null&&t.effect!==null){let e=t.effect;this.#e.add(e),t.deps.add(()=>this.#e.delete(e))}}_notify(){if(this.#e.size===0)return;if(n.depth>0){for(let e of this.#e)n.pending.add(e);return}let e=[];for(let t of[...this.#e])try{t()}catch(t){e.push(t)}if(e.length)throw e.length===1?e[0]:AggregateError(e,`[stateit] multiple subscriber errors`)}},s=(e,n,r,i)=>{let a=t.effect,o=t.deps,s=t.cleanups;t.effect=e,t.deps=n,t.cleanups=r;try{return i()}finally{t.effect=a,t.deps=o,t.cleanups=s}},c=()=>{let e=[...n.pending];n.pending.clear();let t=[];for(let n of e)try{n()}catch(e){t.push(e)}if(t.length)throw t.length===1?t[0]:AggregateError(t,`[stateit] batch errors`)},l=e=>{n.depth++;try{let t=e();return--n.depth===0&&c(),t}catch(e){if(--n.depth===0)try{c()}catch{}throw e}},u=Symbol(`stateit.signal`),d=Symbol(`stateit.store`),f=class extends o{[u]=!0;#e;#t=e;#n=!0;#r=!1;#i;#a=new Set;#o=()=>{this.#n||(this.#n=!0,this._notify())};constructor(e,t){super(),this.#e=e,this.#i=t?.equals??Object.is,t?.lazy||this.#s()}#s(){for(let e of this.#a)e();this.#a.clear();let t=s(this.#o,this.#a,null,this.#e);this.#n=!1,(this.#t===e||!this.#i(this.#t,t))&&(this.#t=t)}get value(){return this.#r?this.#t:(this.#n&&this.#s(),this._track(),this.#t)}peek(){if(this.#t===e){if(this.#r)return;this.#s()}return this.#t}get stale(){return this.#n||this.#r}dispose(){if(!this.#r){this.#r=!0;for(let e of this.#a)e();this.#a.clear()}}[Symbol.dispose](){this.dispose()}},p=(e,t)=>new f(e,t),m=class extends f{#e;constructor(e,t,n){super(e,n),this.#e=t}get value(){return super.value}set value(e){this.#e(e)}update(e){this.#e(e(this.peek()))}},h=(e,t,n)=>new m(e,t,n),g=(e,t,n)=>p(()=>t(...e.map(e=>e.value)),n),_=(e,t)=>{let n,i=new Set,a=!1,o=!1,c=!1,l=t?.maxIterations??r,u=()=>{n?.(),n=void 0;for(let e of i)e();i.clear()},d=()=>{o=!1,u();let r=[],a,l=!1;try{s(f,i,r,()=>{let t=e();typeof t==`function`&&r.push(t)})}catch(e){if(t?.onError)l=!0,a=e;else throw e}return n=r.length>0?()=>{for(let e of r)e()}:void 0,l&&(u(),t.onError(a),c=!0),l},f=()=>{if(c||a){a&&(o=!0);return}a=!0;try{let e=0;do{if(++e>l)throw Error(`[stateit] effect: possible infinite reactive loop (> ${l} iterations)`);if(d())break}while(o)}finally{a=!1}};f();let p=()=>{c||(c=!0,u())};return Object.assign(p,{dispose:p,[Symbol.dispose]:p})},v=e=>s(null,null,null,e),y=e=>{t.cleanups?.push(e)},b=class extends o{[u]=!0;#e;#t;constructor(e,t){super(),this.#e=e,this.#t=t?.equals??Object.is}get value(){return this._track(),this.#e}set value(e){this.#t(this.#e,e)||(this.#e=e,this._notify())}update(e){this.value=e(this.#e)}peek(){return this.#e}},x=(e,t)=>new b(e,t),S=new WeakMap,C=e=>{let t=S.get(e);if(t)return t;let n={get[u](){return!0},peek:()=>e.peek(),get value(){return e.value}};return S.set(e,n),n},w=e=>typeof e==`object`&&!!e&&u in e,T=e=>w(e)?e.value:e,E=e=>w(e)?e.peek():e,D=(e,t)=>{if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=`object`||typeof t!=`object`)return!1;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Object.is(e[r],t[r]))return!1;return!0},O=class extends b{[d]=!0;#e;#t=!1;constructor(e,t){super(e,{equals:t?.equals??D}),this.#e={...e}}get frozen(){return this.#t}get value(){return super.value}set value(e){this.#t||(super.value=e)}patch(e){this.value={...this.peek(),...e}}update(e){this.value=e({...this.peek()})}reset(){this.value={...this.#e}}select(e,t){return p(()=>e(this.value),t)}freeze(){this.#t=!0}},k=(e,t)=>new O(e,t),A=e=>typeof e==`object`&&!!e&&d in e,j=(e,t,n)=>{let r=n?.equals??Object.is,i=e.peek();n?.immediate&&t(i,i);let a;return a=_(()=>{let o=e.value;if(!r(i,o)){let e=i;i=o,t(o,e),n?.once&&a()}}),a},M=(e,t,n)=>new Promise((r,i)=>{let a=n?.signal;try{a?.throwIfAborted()}catch(e){i(e);return}let o=j(e,e=>{(!t||t(e))&&(o(),a?.removeEventListener(`abort`,s),r(e))}),s=()=>{o(),i(a.reason)};a?.addEventListener(`abort`,s,{once:!0})});exports.ComputedNode=f,exports.SignalImpl=b,exports.WritableNode=m,exports._SIGNAL_BRAND=u,exports._STORE_BRAND=d,exports._flushPending=c,exports._resetContextForTesting=a,exports.batch=l,exports.computed=p,exports.configureStateit=i,exports.derived=g,exports.effect=_,exports.isSignal=w,exports.isStore=A,exports.nextValue=M,exports.onCleanup=y,exports.peekValue=E,exports.readonly=C,exports.shallowEqual=D,exports.signal=x,exports.store=k,exports.toValue=T,exports.untrack=v,exports.watch=j,exports.writable=h;
2
+ //# sourceMappingURL=stateit.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stateit.cjs","names":["#subscribers","#onDepChange","#dirty","#compute","#equals","#recompute","#deps","#value","#disposed","#set","#value","#equals","#initial","#frozen"],"sources":["../src/runtime.ts","../src/batch.ts","../src/types.ts","../src/computed.ts","../src/effect.ts","../src/signal.ts","../src/store.ts","../src/watch.ts"],"sourcesContent":["import type { CleanupFn, EffectCallback } from './types';\n\n/** @internal True outside of production builds; gates dev-only warnings. */\nexport const _DEV = import.meta.env.DEV;\n\nexport const _UNINITIALIZED = Symbol('stateit.uninitialized');\n\n/** @internal Active reactive tracking scope — null outside any effect/computed. */\nexport const scope = {\n cleanups: null as CleanupFn[] | null,\n deps: null as Set<CleanupFn> | null,\n effect: null as EffectCallback | null,\n};\n\n/** @internal Deferred notification queue — active only during batch(). */\nexport const queue = {\n depth: 0,\n pending: new Set<EffectCallback>(),\n};\n\nexport let _maxEffectIterations = 100;\n\n/**\n * Configures global stateit behaviour.\n * @example configureStateit({ maxEffectIterations: 200 });\n */\nexport const configureStateit = (opts: { maxEffectIterations?: number }): void => {\n if (opts.maxEffectIterations !== undefined) _maxEffectIterations = opts.maxEffectIterations;\n};\n\n/**\n * Resets the shared reactive context. Use in test setup/teardown to prevent state\n * leaks between tests when a batch or effect throws without being fully cleaned up.\n */\nexport const _resetContextForTesting = (): void => {\n queue.depth = 0;\n scope.deps = null;\n scope.effect = null;\n scope.cleanups = null;\n queue.pending.clear();\n};\n\n/** @internal Base reactive node: manages a subscriber set and batch-aware notification. */\nexport class ReactiveNode {\n #subscribers = new Set<EffectCallback>();\n\n /** Register the current tracking scope as a subscriber and store an unsubscribe\n * function in scope.deps for automatic cleanup when the effect re-runs. */\n protected _track(): void {\n if (scope.deps !== null && scope.effect !== null) {\n const fn = scope.effect;\n\n this.#subscribers.add(fn);\n scope.deps.add(() => this.#subscribers.delete(fn));\n }\n }\n\n /** Notify all subscribers. Respects batch queue depth. */\n protected _notify(): void {\n if (this.#subscribers.size === 0) return;\n\n if (queue.depth > 0) {\n for (const fn of this.#subscribers) queue.pending.add(fn);\n\n return;\n }\n\n const errors: unknown[] = [];\n\n for (const fn of [...this.#subscribers]) {\n try {\n fn();\n } catch (e) {\n errors.push(e);\n }\n }\n\n if (errors.length) {\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, '[stateit] multiple subscriber errors');\n }\n }\n}\n\n/** @internal Save scope fields, swap to new tracking context, call fn, restore. */\nexport const _withCtx = <T>(\n eff: EffectCallback | null,\n deps: Set<CleanupFn> | null,\n cleanups: CleanupFn[] | null,\n fn: () => T,\n): T => {\n const pe = scope.effect;\n const pd = scope.deps;\n const pc = scope.cleanups;\n\n scope.effect = eff;\n scope.deps = deps;\n scope.cleanups = cleanups;\n\n try {\n return fn();\n } finally {\n scope.effect = pe;\n scope.deps = pd;\n scope.cleanups = pc;\n }\n};\n","import { _DEV, queue } from './runtime';\n\n/** @internal Drain and run all pending effects from the batch queue, collecting errors. */\nexport const _flushPending = (): void => {\n const toFlush = [...queue.pending];\n\n queue.pending.clear();\n\n const errors: unknown[] = [];\n\n for (const f of toFlush) {\n try {\n f();\n } catch (e) {\n errors.push(e);\n }\n }\n\n if (errors.length) throw errors.length === 1 ? errors[0] : new AggregateError(errors, '[stateit] batch errors');\n};\n\n/** Runs fn and defers all Signal notifications until fn returns, then flushes once. */\nexport const batch = <T>(fn: () => T): T => {\n queue.depth++;\n\n try {\n const result = fn();\n\n if (--queue.depth === 0) _flushPending();\n\n return result;\n } catch (e) {\n if (--queue.depth === 0) {\n try {\n _flushPending();\n } catch (flushErr) {\n if (_DEV)\n console.error(\n '[stateit] batch: a secondary flush error was suppressed (callback error takes precedence)',\n flushErr,\n );\n }\n }\n\n throw e;\n }\n};\n","/** A function that tears down a subscription or effect. */\nexport type CleanupFn = () => void;\n\n/** The shape of a function passed to `effect()`. Can return an optional cleanup. */\nexport type EffectCallback = () => CleanupFn | void;\n\nexport type EqualityFn<T> = (a: T, b: T) => boolean;\n\n/** Options accepted by signal(), computed(), writable(), and store(). */\nexport type ReactiveOptions<T> = { equals?: EqualityFn<T> };\n\n/** Shared interface for disposable reactive values (computed, writable). Supports the TC39 `using` declaration. */\nexport interface Disposable {\n dispose(): void;\n [Symbol.dispose](): void;\n}\n\n/**\n * A callable subscription handle returned by `effect()` and `watch()`.\n * Can be called directly or via `.dispose()` to stop the subscription.\n * Supports the TC39 `using` declaration via `[Symbol.dispose]`.\n */\nexport interface Subscription {\n (): void;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n\nexport const _SIGNAL_BRAND = Symbol('stateit.signal');\nexport const _STORE_BRAND = Symbol('stateit.store');\n\n/** Public read-only signal interface. */\nexport interface ReadonlySignal<T> {\n readonly [_SIGNAL_BRAND]: true;\n readonly value: T;\n peek(): T;\n}\n\n/** Public read/write signal interface. */\nexport interface Signal<T> extends ReadonlySignal<T> {\n value: T;\n /** Update the value by applying a function to the current value. */\n update(fn: (current: T) => T): void;\n}\n","import { ReactiveNode, _DEV, _UNINITIALIZED, _withCtx } from './runtime';\nimport {\n type CleanupFn,\n type Disposable,\n type EffectCallback,\n type EqualityFn,\n type ReactiveOptions,\n type ReadonlySignal,\n type Signal,\n _SIGNAL_BRAND,\n} from './types';\n\n/** A derived read-only signal with an explicit dispose method. */\nexport interface ComputedSignal<T> extends ReadonlySignal<T>, Disposable {\n /** True when the computed value is stale (deps changed but not yet re-read) or disposed. */\n readonly stale: boolean;\n}\n\n/** @internal\n * Lazy computed node. Seeded once at construction so .peek() is immediately valid\n * (unless { lazy: true } is passed, in which case first compute defers to first read).\n * - On dep change: marks dirty, notifies downstream (no recompute yet).\n * - On .value read: recomputes if dirty, re-tracks fresh deps.\n * - After dispose: _track() is skipped to prevent leaking outer effects.\n */\nexport class ComputedNode<T> extends ReactiveNode implements ComputedSignal<T> {\n readonly [_SIGNAL_BRAND] = true as const;\n #compute: () => T;\n #value: T | typeof _UNINITIALIZED = _UNINITIALIZED;\n #dirty = true;\n #disposed = false;\n #equals: EqualityFn<T>;\n #deps = new Set<CleanupFn>();\n\n readonly #onDepChange: EffectCallback = () => {\n if (!this.#dirty) {\n this.#dirty = true;\n this._notify();\n }\n };\n\n constructor(compute: () => T, options?: ReactiveOptions<T> & { lazy?: boolean }) {\n super();\n this.#compute = compute;\n this.#equals = options?.equals ?? Object.is;\n\n if (!options?.lazy) this.#recompute(); // seed: ensures peek() is valid immediately\n }\n\n #recompute(): void {\n for (const unsub of this.#deps) unsub();\n this.#deps.clear();\n\n const result = _withCtx(this.#onDepChange, this.#deps, null, this.#compute);\n\n this.#dirty = false;\n\n if (this.#value === _UNINITIALIZED || !this.#equals(this.#value as T, result)) {\n this.#value = result;\n }\n }\n\n get value(): T {\n if (this.#disposed) {\n if (_DEV) console.warn('[stateit] Reading a disposed ComputedSignal returns a stale value.');\n\n return this.#value as T;\n }\n\n if (this.#dirty) this.#recompute();\n\n this._track();\n\n return this.#value as T;\n }\n\n peek(): T {\n if (this.#value === _UNINITIALIZED) {\n if (this.#disposed) {\n if (_DEV)\n console.warn(\n '[stateit] peek() called on a disposed lazy ComputedSignal that was never read — returning undefined.',\n );\n\n return undefined as unknown as T;\n }\n\n this.#recompute();\n }\n\n return this.#value as T;\n }\n\n get stale(): boolean {\n return this.#dirty || this.#disposed;\n }\n\n dispose(): void {\n if (this.#disposed) return;\n\n this.#disposed = true;\n for (const unsub of this.#deps) unsub();\n this.#deps.clear();\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n}\n\n/** Creates a derived read-only Signal whose value is recomputed lazily on `.value` read\n * when dependencies have changed. Call `.dispose()` to stop tracking and free dependencies.\n * Pass `{ lazy: true }` to defer the initial computation until the first `.value` read. */\nexport const computed = <T>(compute: () => T, options?: ReactiveOptions<T> & { lazy?: boolean }): ComputedSignal<T> =>\n new ComputedNode(compute, options);\n\n/** A bidirectional computed Signal with an explicit dispose method. */\nexport interface WritableSignal<T> extends Signal<T>, Disposable {\n /** True when the backing computed value is stale (deps changed but not yet re-read) or disposed. */\n readonly stale: boolean;\n}\n\n/** @internal */\nexport class WritableNode<T> extends ComputedNode<T> implements WritableSignal<T> {\n readonly #set: (v: T) => void;\n\n constructor(get: () => T, set: (v: T) => void, options?: ReactiveOptions<T>) {\n super(get, options);\n this.#set = set;\n }\n\n override get value(): T {\n return super.value;\n }\n\n set value(v: T) {\n this.#set(v);\n }\n\n update(fn: (current: T) => T): void {\n this.#set(fn(this.peek()));\n }\n}\n\n/** Creates a bidirectional computed Signal. Reads track the getter reactively;\n * writes are forwarded to `set`. Call `.dispose()` to stop tracking and free dependencies. */\nexport const writable = <T>(get: () => T, set: (value: T) => void, options?: ReactiveOptions<T>): WritableSignal<T> =>\n new WritableNode(get, set, options);\n\n/**\n * Creates a derived ComputedSignal by combining multiple source signals through a projector\n * function. Each source is passed as a positional argument to `fn`; the projector is\n * re-evaluated whenever any source changes.\n *\n * @example\n * const total = derived([price, quantity, discount], (p, q, d) => p * q * (1 - d));\n */\nexport const derived = <const Srcs extends ReadonlyArray<ReadonlySignal<unknown>>, R>(\n sources: Srcs,\n fn: (...values: { [K in keyof Srcs]: Srcs[K] extends ReadonlySignal<infer V> ? V : never }) => R,\n options?: ReactiveOptions<R>,\n): ComputedSignal<R> => computed(() => (fn as (...args: any[]) => R)(...sources.map((s) => s.value)), options);\n","import { _DEV, _maxEffectIterations, _withCtx, scope } from './runtime';\nimport { type CleanupFn, type EffectCallback, type Subscription } from './types';\n\n/** Options for the `effect()` primitive. */\nexport type EffectOptions = {\n /**\n * Maximum re-entrant iterations before throwing to prevent infinite loops.\n * Overrides the global value set via `configureStateit` for this specific effect.\n */\n maxIterations?: number;\n /**\n * Called when the effect function throws. When provided, the effect is automatically\n * disposed after the first error — it won't re-run on subsequent dependency changes.\n */\n onError?: (error: unknown) => void;\n};\n\n/** Runs fn immediately and re-runs it whenever any Signal read inside it changes. Returns a dispose handle. */\nexport const effect = (fn: EffectCallback, options?: EffectOptions): Subscription => {\n let cleanup: CleanupFn | undefined;\n const deps = new Set<CleanupFn>();\n let running = false;\n let dirty = false;\n let disposed = false;\n const maxIter = options?.maxIterations ?? _maxEffectIterations;\n\n /** Tears down the current run: calls cleanup and unsubscribes all deps. */\n const teardown = (): void => {\n cleanup?.();\n cleanup = undefined;\n for (const unsub of deps) unsub();\n deps.clear();\n };\n\n /** Runs a single iteration: tears down previous deps/cleanup, re-executes fn, registers fresh deps.\n * Returns true if onError handled a throw (caller should break the loop). */\n const runIteration = (): boolean => {\n dirty = false;\n teardown();\n\n const cleanups: CleanupFn[] = [];\n let thrownError: unknown;\n let threw = false;\n\n try {\n _withCtx(runner, deps, cleanups, () => {\n const result = fn();\n\n if (typeof result === 'function') cleanups.push(result);\n });\n } catch (e) {\n if (options?.onError) {\n threw = true;\n thrownError = e;\n } else throw e;\n }\n\n cleanup =\n cleanups.length > 0\n ? () => {\n for (const c of cleanups) c();\n }\n : undefined;\n\n if (threw) {\n teardown(); // flush onCleanup registrations from the throwing run\n options!.onError!(thrownError);\n disposed = true;\n }\n\n return threw;\n };\n\n const runner: EffectCallback = () => {\n if (disposed || running) {\n if (running) dirty = true;\n\n return;\n }\n\n running = true;\n\n try {\n let iterations = 0;\n\n do {\n if (++iterations > maxIter)\n throw new Error(`[stateit] effect: possible infinite reactive loop (> ${maxIter} iterations)`);\n\n if (runIteration()) break;\n } while (dirty);\n } finally {\n running = false;\n }\n };\n\n runner();\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n teardown();\n };\n\n return Object.assign(dispose, { dispose, [Symbol.dispose]: dispose }) as Subscription;\n};\n\n/** Runs fn without registering any reactive dependencies. */\nexport const untrack = <T>(fn: () => T): T => _withCtx(null, null, null, fn);\n\n/**\n * Registers a cleanup function within the currently running effect.\n * Called before the effect re-runs and on final dispose.\n * Allows nested helpers to register teardown without needing the effect's return value.\n *\n * @example\n * effect(() => {\n * const id = setInterval(() => { ... }, 1000);\n * onCleanup(() => clearInterval(id));\n * });\n */\nexport const onCleanup = (fn: CleanupFn): void => {\n if (_DEV && scope.cleanups === null) {\n console.warn('[stateit] onCleanup() called outside of an active effect — the cleanup will never run.');\n }\n\n scope.cleanups?.push(fn);\n};\n","import { ReactiveNode } from './runtime';\nimport { type EqualityFn, type ReactiveOptions, type ReadonlySignal, type Signal, _SIGNAL_BRAND } from './types';\n\n/** @internal */\nexport class SignalImpl<T> extends ReactiveNode implements Signal<T> {\n readonly [_SIGNAL_BRAND] = true as const;\n #value: T;\n #equals: EqualityFn<T>;\n\n constructor(initial: T, options?: ReactiveOptions<T>) {\n super();\n this.#value = initial;\n this.#equals = options?.equals ?? Object.is;\n }\n\n get value(): T {\n this._track();\n\n return this.#value;\n }\n\n set value(next: T) {\n if (this.#equals(this.#value, next)) return;\n\n this.#value = next;\n this._notify();\n }\n\n update(fn: (current: T) => T): void {\n this.value = fn(this.#value);\n }\n\n peek(): T {\n return this.#value;\n }\n}\n\n/** Creates a reactive signal holding a single value. */\nexport const signal = <T>(initial: T, options?: ReactiveOptions<T>): Signal<T> => new SignalImpl(initial, options);\n\nconst _readonlyCache = new WeakMap<object, ReadonlySignal<unknown>>();\n\n/**\n * Returns a stable read-only view of a signal. Hides the setter at both type and runtime\n * level. The wrapper is cached — repeated calls with the same signal return the same reference.\n */\nexport const readonly = <T>(sig: ReadonlySignal<T>): ReadonlySignal<T> => {\n const cached = _readonlyCache.get(sig as object);\n\n if (cached) return cached as ReadonlySignal<T>;\n\n const wrapper: ReadonlySignal<T> = {\n get [_SIGNAL_BRAND]() {\n return true as const;\n },\n peek: () => sig.peek(),\n get value() {\n return sig.value;\n },\n };\n\n _readonlyCache.set(sig as object, wrapper as ReadonlySignal<unknown>);\n\n return wrapper;\n};\n\n/** Type guard -- identifies Signal instances (works through composition and subclasses). */\nexport const isSignal = <T = unknown>(value: unknown): value is ReadonlySignal<T> =>\n typeof value === 'object' && value !== null && _SIGNAL_BRAND in (value as object);\n\n/** Unwraps a plain value or Signal to its current value. Reads are tracked if called inside an effect. */\nexport const toValue = <T>(v: T | ReadonlySignal<T>): T => (isSignal<T>(v) ? v.value : v);\n\n/** Unwraps a plain value or Signal to its current value without registering a reactive subscription. */\nexport const peekValue = <T>(v: T | ReadonlySignal<T>): T => (isSignal<T>(v) ? v.peek() : v);\n","import { type ComputedSignal, computed } from './computed';\nimport { _DEV } from './runtime';\nimport { SignalImpl } from './signal';\nimport { type EqualityFn, type ReactiveOptions, type Signal, _STORE_BRAND } from './types';\n\n/**\n * Shallow structural equality — compares own enumerable keys by reference.\n * This is the default equality function used by `store()`. Export it to avoid\n * reimplementation when composing custom `StoreOptions.equals`.\n */\nexport const shallowEqual: EqualityFn<unknown> = (a, b) => {\n if (a === b) return true;\n\n if (a == null || b == null) return a === b;\n\n if (typeof a !== 'object' || typeof b !== 'object') return false;\n\n const keysA = Object.keys(a as object);\n const keysB = Object.keys(b as object);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n }\n\n return true;\n};\n\nexport type StoreOptions<T extends object> = {\n /** Custom equality for top-level change detection. Default: shallowEqual */\n equals?: EqualityFn<T>;\n};\n\n/** Reactive store for object state. Implements Signal<T> so all signal primitives work natively. */\nexport interface Store<T extends object> extends Signal<T> {\n readonly frozen: boolean;\n /** Shallow-merge a partial object into the current state. */\n patch(partial: Partial<T>): void;\n /** Derive the next state from the current state via an updater function.\n * Receives a shallow copy of the current state — mutations in the updater are safe. */\n update(fn: (s: T) => T): void;\n /** Reset to the original initial state. */\n reset(): void;\n /** Create a lazily recomputed derived signal from a slice of this store's state. */\n select<U>(selector: (s: T) => U, options?: ReactiveOptions<U>): ComputedSignal<U>;\n /** Freeze the store. Further writes via patch/update/reset are silently ignored. */\n freeze(): void;\n}\n\n/** @internal */\nclass StoreImpl<T extends object> extends SignalImpl<T> implements Store<T> {\n readonly [_STORE_BRAND] = true as const;\n\n readonly #initial: T;\n #frozen = false;\n\n constructor(initial: T, options?: StoreOptions<T>) {\n super(initial, { equals: options?.equals ?? (shallowEqual as EqualityFn<T>) });\n this.#initial = { ...initial }; // defensive copy — external mutation cannot corrupt reset()\n }\n\n get frozen(): boolean {\n return this.#frozen;\n }\n\n override get value(): T {\n return super.value;\n }\n\n override set value(next: T) {\n if (this.#frozen) {\n if (_DEV) console.warn('[stateit] store is frozen — write ignored.');\n\n return;\n }\n\n super.value = next;\n }\n\n patch(partial: Partial<T>): void {\n this.value = { ...this.peek(), ...partial };\n }\n\n update(fn: (s: T) => T): void {\n this.value = fn({ ...this.peek() });\n }\n\n reset(): void {\n this.value = { ...this.#initial };\n }\n\n select<U>(selector: (s: T) => U, options?: ReactiveOptions<U>): ComputedSignal<U> {\n return computed(() => selector(this.value), options);\n }\n\n freeze(): void {\n this.#frozen = true;\n }\n}\n\n/** Creates a reactive store for the object state. */\nexport const store = <T extends object>(initial: T, options?: StoreOptions<T>): Store<T> =>\n new StoreImpl(initial, options);\n\n/** Type guard -- identifies Store instances. */\nexport const isStore = <T extends object = Record<string, unknown>>(value: unknown): value is Store<T> =>\n typeof value === 'object' && value !== null && _STORE_BRAND in value;\n","import { effect } from './effect';\nimport { type EqualityFn, type ReadonlySignal, type Subscription } from './types';\n\nexport type WatchOptions<T> = {\n /** Custom equality; suppresses the callback when old and new values are equal. Default: Object.is */\n equals?: EqualityFn<T>;\n /** Fire the callback immediately with the current value on subscribe. */\n immediate?: boolean;\n /**\n * Auto-unsubscribe after the first *change* invocation.\n * When combined with `immediate`, the immediate call does not count against this quota —\n * the callback may fire up to twice total.\n */\n once?: boolean;\n};\n\n/**\n * Watches a Signal and calls cb when its value changes. Returns a dispose handle.\n * Does not fire on initial subscription unless `{ immediate: true }` is passed.\n * To watch a derived slice, compose with `store.select()` or `computed()`:\n *\n * @example\n * const stop = watch(count, (next, prev) => console.log(prev, '->', next));\n * const stop = watch(userStore.select(s => s.name), (name) => ...);\n */\nexport const watch = <T>(\n source: ReadonlySignal<T>,\n cb: (value: T, prev: T) => void,\n options?: WatchOptions<T>,\n): Subscription => {\n const eq: EqualityFn<T> = options?.equals ?? Object.is;\n let prev = source.peek();\n\n if (options?.immediate) cb(prev, prev);\n\n // Use `let` so the stop reference is readable inside the callback without TDZ risk.\n let stop: Subscription;\n\n // eslint-disable-next-line prefer-const\n stop = effect(() => {\n const next = source.value;\n\n if (!eq(prev, next)) {\n const old = prev;\n\n prev = next;\n cb(next, old);\n\n if (options?.once) stop();\n }\n });\n\n return stop;\n};\n\n/**\n * Returns a Promise that resolves with the next value of `source` that satisfies the optional predicate.\n * Disposes automatically after one emission — no cleanup needed.\n * Pass `{ signal: AbortSignal }` to cancel early; the promise rejects with the abort reason.\n *\n * @example\n * const name = await nextValue(userStore.select(s => s.name));\n * const nonZero = await nextValue(count, v => v > 0, { signal: AbortSignal.timeout(5000) });\n */\nexport const nextValue = <T>(\n source: ReadonlySignal<T>,\n predicate?: (v: T) => boolean,\n options?: { signal?: AbortSignal },\n): Promise<T> =>\n new Promise<T>((resolve, reject) => {\n const signal = options?.signal;\n\n try {\n signal?.throwIfAborted();\n } catch (err) {\n reject(err);\n\n return;\n }\n\n const stop = watch(source, (v) => {\n if (!predicate || predicate(v)) {\n stop();\n signal?.removeEventListener('abort', onAbort);\n resolve(v);\n }\n });\n\n const onAbort = () => {\n stop();\n reject(signal!.reason);\n };\n\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n"],"mappings":"mEAKA,IAAa,EAAiB,OAAO,wBAAwB,CAGhD,EAAQ,CACnB,SAAU,KACV,KAAM,KACN,OAAQ,KACT,CAGY,EAAQ,CACnB,MAAO,EACP,QAAS,IAAI,IACd,CAEU,EAAuB,IAMrB,EAAoB,GAAiD,CAC5E,EAAK,sBAAwB,IAAA,KAAW,EAAuB,EAAK,sBAO7D,MAAsC,CACjD,EAAM,MAAQ,EACd,EAAM,KAAO,KACb,EAAM,OAAS,KACf,EAAM,SAAW,KACjB,EAAM,QAAQ,OAAO,EAIV,EAAb,KAA0B,CACxB,GAAe,IAAI,IAInB,QAAyB,CACvB,GAAI,EAAM,OAAS,MAAQ,EAAM,SAAW,KAAM,CAChD,IAAM,EAAK,EAAM,OAEjB,MAAA,EAAkB,IAAI,EAAG,CACzB,EAAM,KAAK,QAAU,MAAA,EAAkB,OAAO,EAAG,CAAC,EAKtD,SAA0B,CACxB,GAAI,MAAA,EAAkB,OAAS,EAA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