@vielzeug/stateit 2.0.0 → 3.0.1

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 (60) hide show
  1. package/README.md +60 -290
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.ts +1 -19
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +2 -9
  6. package/dist/stateit.cjs +1 -1
  7. package/dist/stateit.cjs.map +1 -1
  8. package/dist/stateit.d.ts +68 -0
  9. package/dist/stateit.d.ts.map +1 -0
  10. package/dist/stateit.js +294 -228
  11. package/dist/stateit.js.map +1 -1
  12. package/package.json +6 -5
  13. package/dist/batch.cjs +0 -2
  14. package/dist/batch.cjs.map +0 -1
  15. package/dist/batch.d.ts +0 -5
  16. package/dist/batch.d.ts.map +0 -1
  17. package/dist/batch.js +0 -28
  18. package/dist/batch.js.map +0 -1
  19. package/dist/computed.cjs +0 -2
  20. package/dist/computed.cjs.map +0 -1
  21. package/dist/computed.d.ts +0 -58
  22. package/dist/computed.d.ts.map +0 -1
  23. package/dist/computed.js +0 -65
  24. package/dist/computed.js.map +0 -1
  25. package/dist/effect.cjs +0 -2
  26. package/dist/effect.cjs.map +0 -1
  27. package/dist/effect.d.ts +0 -31
  28. package/dist/effect.d.ts.map +0 -1
  29. package/dist/effect.js +0 -53
  30. package/dist/effect.js.map +0 -1
  31. package/dist/runtime.cjs +0 -2
  32. package/dist/runtime.cjs.map +0 -1
  33. package/dist/runtime.d.ts +0 -40
  34. package/dist/runtime.d.ts.map +0 -1
  35. package/dist/runtime.js +0 -47
  36. package/dist/runtime.js.map +0 -1
  37. package/dist/signal.cjs +0 -2
  38. package/dist/signal.cjs.map +0 -1
  39. package/dist/signal.d.ts +0 -26
  40. package/dist/signal.d.ts.map +0 -1
  41. package/dist/signal.js +0 -40
  42. package/dist/signal.js.map +0 -1
  43. package/dist/store.cjs +0 -2
  44. package/dist/store.cjs.map +0 -1
  45. package/dist/store.d.ts +0 -32
  46. package/dist/store.d.ts.map +0 -1
  47. package/dist/store.js +0 -51
  48. package/dist/store.js.map +0 -1
  49. package/dist/types.cjs +0 -2
  50. package/dist/types.cjs.map +0 -1
  51. package/dist/types.d.ts +0 -39
  52. package/dist/types.d.ts.map +0 -1
  53. package/dist/types.js +0 -6
  54. package/dist/types.js.map +0 -1
  55. package/dist/watch.cjs +0 -2
  56. package/dist/watch.cjs.map +0 -1
  57. package/dist/watch.d.ts +0 -36
  58. package/dist/watch.d.ts.map +0 -1
  59. package/dist/watch.js +0 -32
  60. package/dist/watch.js.map +0 -1
@@ -1 +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,CAC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M,EAAoB,GAAS,QAAU,OAAO,GAChD,EAAO,EAAO,MAAM,CAEpB,GAAS,WAAW,EAAG,EAAM,EAAK,CAGtC,IAAI,EAgBJ,MAbA,GAAO,MAAa,CAClB,IAAM,EAAO,EAAO,MAEpB,GAAI,CAAC,EAAG,EAAM,EAAK,CAAE,CACnB,IAAM,EAAM,EAEZ,EAAO,EACP,EAAG,EAAM,EAAI,CAET,GAAS,MAAM,GAAM,GAE3B,CAEK,GAYI,GACX,EACA,EACA,IAEA,IAAI,SAAY,EAAS,IAAW,CAClC,IAAM,EAAS,GAAS,OAExB,GAAI,CACF,GAAQ,gBAAgB,OACjB,EAAK,CACZ,EAAO,EAAI,CAEX,OAGF,IAAM,EAAO,EAAM,EAAS,GAAM,EAC5B,CAAC,GAAa,EAAU,EAAE,IAC5B,GAAM,CACN,GAAQ,oBAAoB,QAAS,EAAQ,CAC7C,EAAQ,EAAE,GAEZ,CAEI,MAAgB,CACpB,GAAM,CACN,EAAO,EAAQ,OAAO,EAGxB,GAAQ,iBAAiB,QAAS,EAAS,CAAE,KAAM,GAAM,CAAC,EAC1D"}
1
+ {"version":3,"file":"stateit.cjs","names":[],"sources":["../src/stateit.ts"],"sourcesContent":["// === TYPES ===\nexport type CleanupFn = () => void;\nexport type EffectCallback = () => CleanupFn | void;\nexport type EqualityFn<T> = (a: T, b: T) => boolean;\nexport type ReactiveOptions<T> = { equals?: EqualityFn<T> };\n\nexport interface Subscription {\n (): void;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n\nexport interface ReadonlySignal<T> {\n peek(): T;\n subscribe(onStoreChange: () => void): Subscription;\n readonly value: T;\n}\n\nexport interface Signal<T> extends ReadonlySignal<T> {\n update(fn: (current: T) => T): void;\n value: T;\n}\n\nexport interface ComputedSignal<T> extends ReadonlySignal<T> {\n dispose(): void;\n [Symbol.dispose](): void;\n}\n\nexport type WatchOptions<T> = {\n equals?: EqualityFn<T>;\n immediate?: boolean;\n};\n\nexport interface ObservableObserver<T> {\n complete?(): void;\n error?(error: unknown): void;\n next?(value: T): void;\n}\n\nexport interface Store<T extends object> extends ReadonlySignal<T> {\n patch(partial: Partial<T>): void;\n update(fn: (state: T) => T): void;\n reset(): void;\n}\n\nexport interface Scope {\n readonly run: <T>(fn: () => T) => T;\n readonly dispose: () => void;\n readonly [Symbol.dispose]: () => void;\n}\n\n// === CONSTANTS ===\nconst DEFAULT_MAX_ITERATIONS = 100;\nconst IS_SIGNAL = Symbol('stateit.is-signal');\nconst OBSERVABLE_SYMBOL: unique symbol = ((Symbol as typeof Symbol & { observable?: symbol }).observable ??\n Symbol.for('observable')) as never;\n\nexport const observableSymbol = OBSERVABLE_SYMBOL;\n\ntype EffectRunner = () => void;\ntype Subscriber = () => void;\n\nexport type ObservableLike<T> = {\n [observableSymbol](): ObservableLike<T>;\n subscribe(observer: ObservableObserver<T> | ((value: T) => void)): { unsubscribe(): void };\n};\n\n// === HELPERS ===\nexport const toSubscription = (dispose: () => void): Subscription =>\n Object.assign(dispose, { dispose, [Symbol.dispose]: dispose }) as Subscription;\n\nconst readonlyCache = new WeakMap<object, ReadonlySignal<unknown>>();\n\nconst ensureError = (error: unknown): Error => (error instanceof Error ? error : new Error(String(error)));\n\nconst ensureObject = (value: unknown, message: string): void => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new TypeError(message);\n }\n};\n\nconst runAll = (items: Iterable<() => void>, context: string): void => {\n const errors: unknown[] = [];\n\n for (const fn of items) {\n try {\n fn();\n } catch (e) {\n errors.push(e);\n }\n }\n\n if (errors.length === 1) throw errors[0];\n\n if (errors.length > 1) {\n throw new AggregateError(errors, `[stateit] ${context}`);\n }\n};\n\nconst rethrowWithCleanupErrors = (error: unknown, cleanupErrors: unknown[], context: string): never => {\n const rootCause = ensureError(error);\n\n if (cleanupErrors.length === 0) {\n throw rootCause;\n }\n\n throw new AggregateError([rootCause, ...cleanupErrors.map(ensureError)], `[stateit] ${context}`, {\n cause: rootCause,\n });\n};\n\nconst runCleanupAndCollectErrors = (items: Iterable<() => void>): unknown[] => {\n try {\n runAll(items, 'cleanup errors');\n\n return [];\n } catch (error) {\n return error instanceof AggregateError ? error.errors : [error];\n }\n};\n\n// === GLOBAL TRACKING STATE ===\nlet currentEffect: EffectRunner | null = null;\nlet currentComputed: ComputedImpl<any> | null = null;\nlet currentDeps: Set<CleanupFn> | null = null;\nlet currentCleanups: CleanupFn[] | null = null;\n\nconst withTracking = <T>(\n effect: EffectRunner | null,\n computed: ComputedImpl<any> | null,\n deps: Set<CleanupFn> | null,\n cleanups: CleanupFn[] | null,\n fn: () => T,\n): T => {\n const prevEffect = currentEffect;\n const prevComputed = currentComputed;\n const prevDeps = currentDeps;\n const prevCleanups = currentCleanups;\n\n currentEffect = effect;\n currentComputed = computed;\n currentDeps = deps;\n currentCleanups = cleanups;\n\n try {\n return fn();\n } finally {\n currentEffect = prevEffect;\n currentComputed = prevComputed;\n currentDeps = prevDeps;\n currentCleanups = prevCleanups;\n }\n};\n\n// === NOTIFICATION QUEUES ===\nlet batchDepth = 0;\nconst pendingSubscribers = new Set<Subscriber>();\nconst pendingDirtyComputeds = new Set<ComputedImpl<any>>();\n\nconst toTopologicalOrder = (dirtyComputeds: readonly ComputedImpl<any>[]): ComputedImpl<any>[] => {\n const pendingSet = new Set(dirtyComputeds);\n const indegree = new Map<ComputedImpl<any>, number>();\n\n for (const computed of dirtyComputeds) {\n indegree.set(computed, 0);\n }\n\n for (const computed of dirtyComputeds) {\n for (const downstream of computed.computedSubscribers()) {\n if (!pendingSet.has(downstream)) continue;\n\n indegree.set(downstream, (indegree.get(downstream) ?? 0) + 1);\n }\n }\n\n const queue: ComputedImpl<any>[] = [];\n\n for (const computed of dirtyComputeds) {\n if ((indegree.get(computed) ?? 0) === 0) {\n queue.push(computed);\n }\n }\n\n const ordered: ComputedImpl<any>[] = [];\n\n while (queue.length > 0) {\n const computed = queue.shift()!;\n\n ordered.push(computed);\n\n for (const downstream of computed.computedSubscribers()) {\n if (!pendingSet.has(downstream)) continue;\n\n const nextIndegree = (indegree.get(downstream) ?? 0) - 1;\n\n indegree.set(downstream, nextIndegree);\n\n if (nextIndegree === 0) {\n queue.push(downstream);\n }\n }\n }\n\n if (ordered.length < dirtyComputeds.length) {\n for (const computed of dirtyComputeds) {\n if (!ordered.includes(computed)) {\n ordered.push(computed);\n }\n }\n }\n\n return ordered;\n};\n\nconst queueEffectsFromNode = (node: ReactiveNode): void => {\n const dirtyComputeds: ComputedImpl<any>[] = [...node.computedSubscribers()];\n const seenComputeds = new Set<ComputedImpl<any>>();\n\n for (const subscriber of node.subscribers()) {\n pendingSubscribers.add(subscriber);\n }\n\n while (dirtyComputeds.length > 0) {\n const computed = dirtyComputeds.pop()!;\n\n if (seenComputeds.has(computed)) continue;\n\n seenComputeds.add(computed);\n\n if (!computed.markDirty()) continue;\n\n pendingDirtyComputeds.add(computed);\n\n for (const downstream of computed.computedSubscribers()) {\n dirtyComputeds.push(downstream);\n }\n }\n};\n\nconst flushDirtyComputeds = (): void => {\n while (pendingDirtyComputeds.size > 0) {\n const dirtyComputeds = toTopologicalOrder([...pendingDirtyComputeds]);\n\n pendingDirtyComputeds.clear();\n\n for (const computed of dirtyComputeds) {\n if (!computed.hasAnySubscribers()) continue;\n\n const changed = computed.refreshIfDirty();\n\n if (!changed) continue;\n\n for (const subscriber of computed.subscribers()) {\n pendingSubscribers.add(subscriber);\n }\n\n for (const downstream of computed.computedSubscribers()) {\n if (downstream.markDirty()) {\n pendingDirtyComputeds.add(downstream);\n }\n }\n }\n }\n};\n\nconst flushEffects = (): void => {\n let iterations = 0;\n\n while (pendingSubscribers.size > 0 || pendingDirtyComputeds.size > 0) {\n if (++iterations > DEFAULT_MAX_ITERATIONS) {\n throw new Error(`[stateit] infinite flush loop (> ${DEFAULT_MAX_ITERATIONS} iterations)`);\n }\n\n if (pendingDirtyComputeds.size > 0) {\n flushDirtyComputeds();\n }\n\n if (pendingSubscribers.size === 0) continue;\n\n const subscribersToRun = [...pendingSubscribers];\n\n pendingSubscribers.clear();\n runAll(subscribersToRun, 'subscriber errors');\n }\n};\n\nconst notifyNodeChange = (node: ReactiveNode): void => {\n if (!node.hasAnySubscribers()) return;\n\n queueEffectsFromNode(node);\n\n if (batchDepth === 0) {\n flushEffects();\n }\n};\n\n// === BASE REACTIVE NODE ===\nclass ReactiveNode {\n private computedSubs_ = new Set<ComputedImpl<any>>();\n private subscribers_ = new Set<Subscriber>();\n\n protected track(): void {\n if (!currentDeps) return;\n\n if (currentComputed !== null) {\n const owner = currentComputed;\n\n this.computedSubs_.add(owner);\n currentDeps.add(() => this.computedSubs_.delete(owner));\n\n return;\n }\n\n if (currentEffect !== null) {\n const owner = currentEffect;\n\n this.subscribers_.add(owner);\n currentDeps.add(() => this.subscribers_.delete(owner));\n }\n }\n\n protected notify(): void {\n notifyNodeChange(this);\n }\n\n hasAnySubscribers(): boolean {\n return this.computedSubs_.size > 0 || this.subscribers_.size > 0;\n }\n\n computedSubscribers(): ReadonlySet<ComputedImpl<any>> {\n return this.computedSubs_;\n }\n\n subscribers(): ReadonlySet<Subscriber> {\n return this.subscribers_;\n }\n\n subscribe(subscriber: Subscriber): Subscription {\n this.subscribers_.add(subscriber);\n\n return toSubscription(() => {\n this.subscribers_.delete(subscriber);\n });\n }\n}\n\n// === SIGNAL IMPLEMENTATION ===\nclass SignalImpl<T> extends ReactiveNode implements Signal<T> {\n private value_: T;\n private equals_: EqualityFn<T>;\n [IS_SIGNAL] = true;\n\n constructor(initial: T, equals?: EqualityFn<T>) {\n super();\n this.value_ = initial;\n this.equals_ = equals ?? Object.is;\n }\n\n get value(): T {\n this.track();\n\n return this.value_;\n }\n\n peek(): T {\n return this.value_;\n }\n\n readonly subscribe = (onStoreChange: () => void): Subscription => {\n return super.subscribe(onStoreChange);\n };\n\n update(fn: (current: T) => T): void {\n this.value = fn(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\n// === COMPUTED IMPLEMENTATION ===\nclass ComputedImpl<T> extends ReactiveNode implements ComputedSignal<T> {\n private hasValue_ = false;\n private value_!: T;\n private dirty_ = true;\n private computing_ = false;\n private disposed_ = false;\n private deps_ = new Set<CleanupFn>();\n private compute_: () => T;\n private equals_: EqualityFn<T>;\n [IS_SIGNAL] = true;\n\n constructor(compute: () => T, equals?: EqualityFn<T>) {\n super();\n this.compute_ = compute;\n this.equals_ = equals ?? Object.is;\n }\n\n markDirty(): boolean {\n if (this.disposed_ || this.dirty_) return false;\n\n this.dirty_ = true;\n\n return true;\n }\n\n refreshIfDirty(): boolean {\n return this.dirty_ ? this.recompute() : false;\n }\n\n private recompute(): boolean {\n if (this.computing_) {\n throw new Error('[stateit] computed cycle detected');\n }\n\n for (const unsub of this.deps_) unsub();\n this.deps_.clear();\n\n this.computing_ = true;\n\n try {\n const next = withTracking(null, this, this.deps_, null, this.compute_);\n\n this.dirty_ = false;\n\n if (!this.hasValue_ || !this.equals_(this.value_, next)) {\n this.hasValue_ = true;\n this.value_ = next;\n\n return true;\n }\n\n return false;\n } catch (error) {\n const cleanupErrors = runCleanupAndCollectErrors(this.deps_);\n\n this.deps_.clear();\n\n return rethrowWithCleanupErrors(error, cleanupErrors, 'computed failed dependency cleanup errors');\n } finally {\n this.computing_ = false;\n }\n }\n\n get value(): T {\n if (this.disposed_) {\n throw new Error('[stateit] Cannot read disposed computed signal');\n }\n\n this.refreshIfDirty();\n\n this.track();\n\n return this.value_;\n }\n\n peek(): T {\n if (this.disposed_) {\n throw new Error('[stateit] Cannot read disposed computed signal');\n }\n\n this.refreshIfDirty();\n\n return this.value_;\n }\n\n readonly subscribe = (onStoreChange: () => void): Subscription => {\n if (this.disposed_) {\n throw new Error('[stateit] Cannot subscribe to a disposed computed signal');\n }\n\n // Subscribing should be lazy in terms of callbacks, but computed dependencies\n // must be established so upstream writes can mark this node dirty.\n this.refreshIfDirty();\n\n return super.subscribe(onStoreChange);\n };\n\n dispose(): void {\n if (this.disposed_) return;\n\n this.disposed_ = true;\n\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// === CORE API ===\n\nexport const signal = <T>(initial: T, options?: ReactiveOptions<T>): Signal<T> =>\n new SignalImpl(initial, options?.equals);\n\nexport const computed = <T>(compute: () => T, options?: ReactiveOptions<T>): ComputedSignal<T> => {\n const comp = new ComputedImpl(compute, options?.equals);\n\n if (currentCleanups !== null) {\n onCleanup(() => comp.dispose());\n }\n\n return comp;\n};\n\nexport const batch = <T>(fn: () => T): T => {\n // Batch coalesces notifications. Writes that happen before an error are not rolled back.\n // Pending subscribers still flush, and caller-visible errors are aggregated.\n batchDepth++;\n\n let result: T | undefined;\n let bodyError: unknown;\n\n try {\n result = fn();\n } catch (e) {\n bodyError = e;\n }\n\n batchDepth--;\n\n if (batchDepth === 0) {\n try {\n flushEffects();\n } catch (flushError) {\n if (bodyError !== undefined) {\n throw new AggregateError([bodyError, flushError], '[stateit] batch error with flush errors', {\n cause: flushError,\n });\n }\n\n throw ensureError(flushError);\n }\n }\n\n if (bodyError !== undefined) {\n throw ensureError(bodyError);\n }\n\n return result as T;\n};\n\nexport const effect = (fn: EffectCallback): Subscription => {\n let cleanup: CleanupFn | undefined;\n const deps = new Set<CleanupFn>();\n let isRunning = false;\n let isDirty = false;\n let isDisposed = false;\n\n const teardown = (): void => {\n if (!cleanup && deps.size === 0) return;\n\n const callbacks = cleanup ? [cleanup, ...deps] : [...deps];\n\n cleanup = undefined;\n deps.clear();\n\n runAll(callbacks, 'effect teardown errors');\n };\n\n const run: EffectRunner = (): void => {\n if (isDisposed) return;\n\n if (isRunning) {\n isDirty = true;\n\n return;\n }\n\n isRunning = true;\n\n try {\n let iterations = 0;\n\n do {\n if (++iterations > DEFAULT_MAX_ITERATIONS) {\n throw new Error(`[stateit] infinite effect loop (> ${DEFAULT_MAX_ITERATIONS} iterations)`);\n }\n\n isDirty = false;\n teardown();\n\n const localCleanups: CleanupFn[] = [];\n let returnedCleanup: CleanupFn | void = undefined;\n\n try {\n returnedCleanup = withTracking(run, null, deps, localCleanups, fn);\n } catch (error) {\n const cleanupErrors = [...runCleanupAndCollectErrors(deps), ...runCleanupAndCollectErrors(localCleanups)];\n\n deps.clear();\n rethrowWithCleanupErrors(error, cleanupErrors, 'effect failure with cleanup errors');\n }\n\n if (typeof returnedCleanup === 'function') {\n localCleanups.push(returnedCleanup);\n }\n\n cleanup =\n localCleanups.length > 0\n ? () => {\n runAll(localCleanups, 'effect cleanup errors');\n }\n : undefined;\n } while (isDirty && !isDisposed);\n } finally {\n isRunning = false;\n }\n };\n\n run();\n\n return toSubscription(() => {\n if (isDisposed) return;\n\n isDisposed = true;\n teardown();\n });\n};\n\nexport const untrack = <T>(fn: () => T): T => withTracking(null, null, null, null, fn);\n\nexport const readonly = <T>(source: ReadonlySignal<T>): ReadonlySignal<T> => {\n const sourceObject = source as object;\n const cached = readonlyCache.get(sourceObject);\n\n if (cached) {\n return cached as ReadonlySignal<T>;\n }\n\n const view: ReadonlySignal<T> = {\n peek(): T {\n return source.peek();\n },\n subscribe(onStoreChange: () => void): Subscription {\n return source.subscribe(onStoreChange);\n },\n get value(): T {\n return source.value;\n },\n };\n\n readonlyCache.set(sourceObject, view as ReadonlySignal<unknown>);\n\n return view;\n};\n\nexport const toStore = <T>(source: ReadonlySignal<T>): { subscribe(run: (value: T) => void): Subscription } => ({\n subscribe(run) {\n run(source.value);\n\n return source.subscribe(() => run(source.value));\n },\n});\n\nexport const toObservable = <T>(source: ReadonlySignal<T>): ObservableLike<T> => {\n const subscribe = (observerOrNext: ObservableObserver<T> | ((value: T) => void)): { unsubscribe(): void } => {\n const observer: ObservableObserver<T> =\n typeof observerOrNext === 'function' ? { next: observerOrNext } : observerOrNext;\n\n observer.next?.(source.value);\n\n const subscription = source.subscribe(() => observer.next?.(source.value));\n\n return {\n unsubscribe(): void {\n subscription();\n },\n };\n };\n\n const observable = {\n [OBSERVABLE_SYMBOL](): ObservableLike<T> {\n return observable;\n },\n subscribe,\n };\n\n return observable;\n};\n\nexport const onCleanup = (fn: CleanupFn): void => {\n if (currentCleanups === null) {\n throw new Error('[stateit] onCleanup() must be called from within an active effect or scope.');\n }\n\n currentCleanups.push(fn);\n};\n\nexport const scope = (setup?: () => void): Scope => {\n const cleanups: CleanupFn[] = [];\n let disposed = false;\n\n const run = <T>(fn: () => T): T => {\n if (disposed) throw new Error('[stateit] Cannot run inside a disposed scope.');\n\n return withTracking(null, null, null, cleanups, fn);\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n\n runAll([...cleanups].reverse(), 'scope cleanup errors');\n cleanups.length = 0;\n };\n\n const api: Scope = { dispose, run, [Symbol.dispose]: dispose };\n\n if (setup) {\n run(setup);\n }\n\n return api;\n};\n\nfunction watch<T>(\n source: ReadonlySignal<T>,\n cb: (value: T, prev: T) => void,\n watchOptions?: WatchOptions<T>,\n): Subscription;\nfunction watch<T>(source: () => T, cb: (value: T, prev: T) => void, watchOptions?: WatchOptions<T>): Subscription;\nfunction watch<T>(\n source: ReadonlySignal<T> | (() => T),\n cb: (value: T, prev: T) => void,\n watchOptions?: WatchOptions<T>,\n): Subscription {\n const get = typeof source === 'function' ? source : () => source.value;\n const equals = watchOptions?.equals ?? Object.is;\n let initialized = false;\n let prev!: T;\n\n if (watchOptions?.immediate) {\n prev = untrack(get);\n initialized = true;\n cb(prev, prev);\n }\n\n return effect(() => {\n const next = get();\n\n if (!initialized) {\n initialized = true;\n prev = next;\n\n return;\n }\n\n if (equals(prev, next)) return;\n\n const old = prev;\n\n prev = next;\n cb(next, old);\n });\n}\nexport { watch };\n\nexport const store = <T extends object>(initial: T): Store<T> => {\n ensureObject(initial, '[stateit] store() requires a plain object initial state.');\n\n const initialSnapshot = structuredClone(initial);\n const state = signal(structuredClone(initial));\n const api: Store<T> & { [IS_SIGNAL]: true } = {\n [IS_SIGNAL]: true,\n patch(partial: Partial<T>): void {\n ensureObject(partial, '[stateit] store.patch() requires a plain object partial.');\n\n const current = untrack(() => state.value);\n const hasChange = (Object.keys(partial) as Array<keyof T>).some((k) => !Object.is(current[k], partial[k]));\n\n if (hasChange) state.value = { ...current, ...partial };\n },\n peek(): T {\n return state.peek();\n },\n reset(): void {\n state.value = structuredClone(initialSnapshot);\n },\n subscribe(onStoreChange: () => void): Subscription {\n return state.subscribe(onStoreChange);\n },\n update(fn: (current: T) => T): void {\n state.update(fn);\n },\n get value(): T {\n return state.value;\n },\n };\n\n return api;\n};\n\n// === TYPE HELPERS ===\n\nexport const isSignal = <T = unknown>(value: unknown): value is ReadonlySignal<T> =>\n typeof value === 'object' && value !== null && !!(value as Record<typeof IS_SIGNAL, unknown>)[IS_SIGNAL];\n"],"mappings":"mEAoDA,IAAM,EAAyB,IACzB,EAAY,OAAO,mBAAmB,EACtC,EAAqC,OAAmD,YAC5F,OAAO,IAAI,YAAY,EAEZ,EAAmB,EAWnB,EAAkB,GAC7B,OAAO,OAAO,EAAS,CAAE,WAAU,OAAO,SAAU,CAAQ,CAAC,EAEzD,EAAgB,IAAI,QAEpB,EAAe,GAA2B,aAAiB,MAAQ,EAAY,MAAM,OAAO,CAAK,CAAC,EAElG,GAAgB,EAAgB,IAA0B,CAC9D,GAAI,OAAO,GAAU,WAAY,GAAkB,MAAM,QAAQ,CAAK,EACpE,MAAU,UAAU,CAAO,CAE/B,EAEM,GAAU,EAA6B,IAA0B,CACrE,IAAM,EAAoB,CAAC,EAE3B,IAAK,IAAM,KAAM,EACf,GAAI,CACF,EAAG,CACL,OAAS,EAAG,CACV,EAAO,KAAK,CAAC,CACf,CAGF,GAAI,EAAO,SAAW,EAAG,MAAM,EAAO,GAEtC,GAAI,EAAO,OAAS,EAClB,MAAU,eAAe,EAAQ,aAAa,GAAS,CAE3D,EAEM,GAA4B,EAAgB,EAA0B,IAA2B,CACrG,IAAM,EAAY,EAAY,CAAK,EAMnC,MAJI,EAAc,SAAW,EACrB,EAGE,eAAe,CAAC,EAAW,GAAG,EAAc,IAAI,CAAW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,EAAM,MAAQ,CAAE,GAAG,EAAS,GAAG,CAAQ,EACxD,EACA,MAAU,CACR,OAAO,EAAM,KAAK,CACpB,EACA,OAAc,CACZ,EAAM,MAAQ,gBAAgB,CAAe,CAC/C,EACA,UAAU,EAAyC,CACjD,OAAO,EAAM,UAAU,CAAa,CACtC,EACA,OAAO,EAA6B,CAClC,EAAM,OAAO,CAAE,CACjB,EACA,IAAI,OAAW,CACb,OAAO,EAAM,KACf,CAGK,CACT,EAIa,EAAyB,GACpC,OAAO,GAAU,YAAY,GAAkB,CAAC,CAAE,EAA4C"}
@@ -0,0 +1,68 @@
1
+ export type CleanupFn = () => void;
2
+ export type EffectCallback = () => CleanupFn | void;
3
+ export type EqualityFn<T> = (a: T, b: T) => boolean;
4
+ export type ReactiveOptions<T> = {
5
+ equals?: EqualityFn<T>;
6
+ };
7
+ export interface Subscription {
8
+ (): void;
9
+ dispose(): void;
10
+ [Symbol.dispose](): void;
11
+ }
12
+ export interface ReadonlySignal<T> {
13
+ peek(): T;
14
+ subscribe(onStoreChange: () => void): Subscription;
15
+ readonly value: T;
16
+ }
17
+ export interface Signal<T> extends ReadonlySignal<T> {
18
+ update(fn: (current: T) => T): void;
19
+ value: T;
20
+ }
21
+ export interface ComputedSignal<T> extends ReadonlySignal<T> {
22
+ dispose(): void;
23
+ [Symbol.dispose](): void;
24
+ }
25
+ export type WatchOptions<T> = {
26
+ equals?: EqualityFn<T>;
27
+ immediate?: boolean;
28
+ };
29
+ export interface ObservableObserver<T> {
30
+ complete?(): void;
31
+ error?(error: unknown): void;
32
+ next?(value: T): void;
33
+ }
34
+ export interface Store<T extends object> extends ReadonlySignal<T> {
35
+ patch(partial: Partial<T>): void;
36
+ update(fn: (state: T) => T): void;
37
+ reset(): void;
38
+ }
39
+ export interface Scope {
40
+ readonly run: <T>(fn: () => T) => T;
41
+ readonly dispose: () => void;
42
+ readonly [Symbol.dispose]: () => void;
43
+ }
44
+ export declare const observableSymbol: symbol;
45
+ export type ObservableLike<T> = {
46
+ subscribe(observer: ObservableObserver<T> | ((value: T) => void)): {
47
+ unsubscribe(): void;
48
+ };
49
+ };
50
+ export declare const toSubscription: (dispose: () => void) => Subscription;
51
+ export declare const signal: <T>(initial: T, options?: ReactiveOptions<T>) => Signal<T>;
52
+ export declare const computed: <T>(compute: () => T, options?: ReactiveOptions<T>) => ComputedSignal<T>;
53
+ export declare const batch: <T>(fn: () => T) => T;
54
+ export declare const effect: (fn: EffectCallback) => Subscription;
55
+ export declare const untrack: <T>(fn: () => T) => T;
56
+ export declare const readonly: <T>(source: ReadonlySignal<T>) => ReadonlySignal<T>;
57
+ export declare const toStore: <T>(source: ReadonlySignal<T>) => {
58
+ subscribe(run: (value: T) => void): Subscription;
59
+ };
60
+ export declare const toObservable: <T>(source: ReadonlySignal<T>) => ObservableLike<T>;
61
+ export declare const onCleanup: (fn: CleanupFn) => void;
62
+ export declare const scope: (setup?: () => void) => Scope;
63
+ declare function watch<T>(source: ReadonlySignal<T>, cb: (value: T, prev: T) => void, watchOptions?: WatchOptions<T>): Subscription;
64
+ declare function watch<T>(source: () => T, cb: (value: T, prev: T) => void, watchOptions?: WatchOptions<T>): Subscription;
65
+ export { watch };
66
+ export declare const store: <T extends object>(initial: T) => Store<T>;
67
+ export declare const isSignal: <T = unknown>(value: unknown) => value is ReadonlySignal<T>;
68
+ //# sourceMappingURL=stateit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stateit.d.ts","sourceRoot":"","sources":["../src/stateit.ts"],"names":[],"mappings":"AACA,MAAM,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC;AACnC,MAAM,MAAM,cAAc,GAAG,MAAM,SAAS,GAAG,IAAI,CAAC;AACpD,MAAM,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,OAAO,CAAC;AACpD,MAAM,MAAM,eAAe,CAAC,CAAC,IAAI;IAAE,MAAM,CAAC,EAAE,UAAU,C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