cross-state 0.55.5 → 0.56.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 (65) hide show
  1. package/dist/{diff-BQ8bB3Wk.d.cts → diff-D7XuntCn.d.cts} +2 -2
  2. package/dist/{diff-gZezL04N.d.ts → diff-qAkLCsnM.d.ts} +2 -2
  3. package/dist/index.cjs +3 -3
  4. package/dist/index.d.cts +4 -4
  5. package/dist/index.d.ts +4 -4
  6. package/dist/index.js +3 -3
  7. package/dist/mutative/index.d.cts +2 -2
  8. package/dist/mutative/index.d.ts +2 -2
  9. package/dist/mutative/register.cjs +1 -1
  10. package/dist/mutative/register.d.cts +2 -2
  11. package/dist/mutative/register.d.ts +2 -2
  12. package/dist/mutative/register.js +1 -1
  13. package/dist/{mutativeMethods-6QzygG3W.d.cts → mutativeMethods-Be_XPk5N.d.cts} +2 -2
  14. package/dist/{mutativeMethods-Br3xN2Iq.d.ts → mutativeMethods-DRYtjUcH.d.ts} +2 -2
  15. package/dist/{patchMethods-pw_OcPA8.d.cts → patchMethods-BlYtjRUU.d.cts} +3 -3
  16. package/dist/{patchMethods-CT9M507t.d.ts → patchMethods-Dr2OFh02.d.ts} +3 -3
  17. package/dist/patches/index.d.cts +3 -3
  18. package/dist/patches/index.d.ts +3 -3
  19. package/dist/patches/register.cjs +1 -1
  20. package/dist/patches/register.d.cts +3 -3
  21. package/dist/patches/register.d.ts +3 -3
  22. package/dist/patches/register.js +1 -1
  23. package/dist/persist/register.cjs +2 -2
  24. package/dist/persist/register.d.cts +2 -2
  25. package/dist/persist/register.d.ts +2 -2
  26. package/dist/persist/register.js +2 -2
  27. package/dist/{persist-CPjpg6D0.d.ts → persist-CIEYJ0rO.d.ts} +2 -2
  28. package/dist/{persist-CGLe7YUX.cjs → persist-CQhYPv4d.cjs} +2 -2
  29. package/dist/{persist-CGLe7YUX.cjs.map → persist-CQhYPv4d.cjs.map} +1 -1
  30. package/dist/{persist-D7MAsyyW.d.cts → persist-CR3mhti7.d.cts} +2 -2
  31. package/dist/{persist-Btgg3qGU.js → persist-DFzbvNoJ.js} +2 -2
  32. package/dist/{persist-Btgg3qGU.js.map → persist-DFzbvNoJ.js.map} +1 -1
  33. package/dist/react/index.cjs +127 -82
  34. package/dist/react/index.cjs.map +1 -1
  35. package/dist/react/index.d.cts +25 -47
  36. package/dist/react/index.d.ts +25 -47
  37. package/dist/react/index.js +127 -79
  38. package/dist/react/index.js.map +1 -1
  39. package/dist/react/register.cjs +3 -3
  40. package/dist/react/register.d.cts +3 -3
  41. package/dist/react/register.d.ts +3 -3
  42. package/dist/react/register.js +3 -3
  43. package/dist/{scope-BbUXgNW_.d.ts → scope-ByLCVzKk.d.ts} +2 -2
  44. package/dist/{scope-CoDFmhxK.cjs → scope-C9JXWddv.cjs} +6 -3
  45. package/dist/scope-C9JXWddv.cjs.map +1 -0
  46. package/dist/{scope-6B7-8lwa.d.cts → scope-DkO-RIMy.d.cts} +2 -2
  47. package/dist/{scope-CKXL9xoi.js → scope-Mhr133F_.js} +6 -3
  48. package/dist/scope-Mhr133F_.js.map +1 -0
  49. package/dist/{store-DKaeE840.d.ts → store-B3PWCx63.d.cts} +2 -1
  50. package/dist/{store-BEsiS8y7.d.cts → store-BJWoRQIs.d.ts} +2 -1
  51. package/dist/{store-BpMJxIHt.js → store-DOEc60aP.js} +9 -7
  52. package/dist/store-DOEc60aP.js.map +1 -0
  53. package/dist/{store-1TGlSyq4.cjs → store-DQcFfgKD.cjs} +9 -7
  54. package/dist/store-DQcFfgKD.cjs.map +1 -0
  55. package/dist/{storeMethods-CkvcMFoL.js → storeMethods-C7bswcgj.js} +2 -2
  56. package/dist/{storeMethods-CkvcMFoL.js.map → storeMethods-C7bswcgj.js.map} +1 -1
  57. package/dist/{storeMethods-Bg8nMBrf.d.cts → storeMethods-Dt_mJTe3.d.cts} +3 -3
  58. package/dist/{storeMethods-C_RzHBQL.cjs → storeMethods-YDnpa-6-.cjs} +2 -2
  59. package/dist/{storeMethods-C_RzHBQL.cjs.map → storeMethods-YDnpa-6-.cjs.map} +1 -1
  60. package/dist/{storeMethods-DWKSveN0.d.ts → storeMethods-wsbbfJzY.d.ts} +3 -3
  61. package/package.json +3 -3
  62. package/dist/scope-CKXL9xoi.js.map +0 -1
  63. package/dist/scope-CoDFmhxK.cjs.map +0 -1
  64. package/dist/store-1TGlSyq4.cjs.map +0 -1
  65. package/dist/store-BpMJxIHt.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-DOEc60aP.js","names":["state: ValueState<T> | ErrorState | PendingState","value","q: {\n action: Action<any>;\n resolve: (value: any) => void;\n reject: (error: unknown) => void;\n ref?: any;\n }[]","value: T | undefined","connection: { active: boolean; cancel?: Cancel } | undefined","value","cancel: Cancel | undefined","actions: AsyncConnectionActions<any>","_cancel: Cancel | undefined","run: (() => void) | undefined","timeout: ReturnType<typeof setTimeout> | undefined","timeoutStarted: number | undefined","debounce","arrayMethods: {\n [P in 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | 'reverse' | 'sort']: <\n T extends Array<any>,\n >(\n this: Store<T>,\n ...args: T[P] extends Function_ ? Parameters<T[P]> : never\n ) => T[P] extends Function_ ? ReturnType<T[P]> : never;\n}","timeout: ReturnType<typeof setTimeout> | undefined","getter: T | Calculate<T>","options: StoreOptions<T>","derivedFrom?: {\n store: Store<any>;\n selectors: (Selector<any, any> | AnyPath)[];\n updater: (state: any) => void;\n }","path: any","update: Update<any>","previousValue: { value: T } | undefined","timer: ReturnType<typeof setTimeout> | undefined","updater: ((value: any) => Update<T>) | undefined","active","methods: StoreMethods | undefined","createStore: typeof create & { defaultOptions: StoreOptions<any> }"],"sources":["../src/lib/autobind.ts","../src/lib/calcDuration.ts","../src/lib/deferred.ts","../src/lib/isPromise.ts","../src/lib/promiseWithState.ts","../src/lib/queue.ts","../src/lib/calculatedValue.ts","../src/lib/makeSelector.ts","../src/lib/debounce.ts","../src/lib/disposable.ts","../src/lib/forwardError.ts","../src/lib/promiseWithCancel.ts","../src/lib/standardMethods.ts","../src/lib/throttle.ts","../src/core/store.ts"],"sourcesContent":["const marker = Symbol('autobind');\n\nexport const autobind = <\n TClass extends abstract new (...args: any) => any = abstract new (...args: any) => any,\n>(\n _class: TClass,\n): TClass => {\n for (const key of Reflect.ownKeys(_class.prototype)) {\n if (key === 'constructor') {\n continue;\n }\n\n const descriptor = Reflect.getOwnPropertyDescriptor(_class.prototype, key);\n let method = descriptor?.get?.() ?? descriptor?.value;\n let isBinding = false;\n\n if (typeof method !== 'function' || method[marker]) {\n continue;\n }\n\n Reflect.defineProperty(_class.prototype, key, {\n configurable: true,\n get() {\n if (\n isBinding ||\n this === _class.prototype ||\n Object.prototype.hasOwnProperty.call(this, key) ||\n typeof method !== 'function'\n ) {\n return method;\n }\n\n const boundMethod = (...args: any[]) => Reflect.apply(method, this, args);\n boundMethod[marker] = true;\n isBinding = true;\n\n Object.defineProperty(this, key, {\n configurable: true,\n get() {\n return boundMethod;\n },\n });\n\n isBinding = false;\n return boundMethod;\n },\n set(v) {\n method = v;\n },\n });\n }\n\n return _class;\n};\n","import type { Duration } from '../core/commonTypes';\n\nexport function calcDuration(t: Duration): number {\n if (typeof t === 'number') return t;\n return (\n (t.milliseconds ?? 0) +\n (t.seconds ?? 0) * 1000 +\n (t.minutes ?? 0) * 60 * 1000 +\n (t.hours ?? 0) * 60 * 60 * 1000 +\n (t.days ?? 0) * 24 * 60 * 60 * 1000\n );\n}\n","export class Deferred<T = void> extends Promise<T> {\n resolve: (value: T | PromiseLike<T>) => void = () => undefined;\n reject: (reason?: any) => void = () => undefined;\n\n constructor() {\n Object.defineProperty(Deferred, Symbol.species, {\n value: Promise,\n });\n\n const that = {};\n\n super((resolve, reject) => {\n Object.assign(that, { resolve, reject });\n });\n\n Object.assign(this, that);\n }\n}\n","export default function isPromise(value: unknown): value is Promise<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof value.then === 'function'\n );\n}\n","import isPromise from '@lib/isPromise';\nimport { type ErrorState, type PendingState, type ValueState } from './cacheState';\nimport { type MaybePromise } from './maybePromise';\n\nexport class PromiseWithState<T> extends Promise<T> {\n static override resolve(): PromiseWithState<void>;\n\n static override resolve<T>(value: MaybePromise<T>): PromiseWithState<T>;\n\n static override resolve<T>(value?: MaybePromise<T>) {\n return new PromiseWithState<T>(value as MaybePromise<T>);\n }\n\n static override reject<T = never>(error: unknown): PromiseWithState<T> {\n return new PromiseWithState<T>(Promise.reject(error), { status: 'error', error });\n }\n\n constructor(\n value: MaybePromise<T>,\n public state: ValueState<T> | ErrorState | PendingState = { status: 'pending' },\n ) {\n super((resolve) => resolve(value));\n\n Object.defineProperty(PromiseWithState, Symbol.species, {\n value: Promise,\n });\n\n if (isPromise(value)) {\n value\n .then((value) => {\n this.state = { status: 'value', value: value };\n })\n .catch((error) => {\n this.state = { status: 'error', error };\n });\n } else {\n this.state = { status: 'value', value: value };\n }\n }\n}\n","import isPromise from '@lib/isPromise';\nimport type { MaybePromise } from './maybePromise';\nimport type { Listener } from '@core';\n\ntype Action<T> = () => MaybePromise<T>;\n\nexport interface Queue {\n <T>(action: Action<T>, ref?: any): Promise<T>;\n clear: () => void;\n whenDone: () => Promise<void>;\n size: number;\n getRefs: () => any[];\n}\n\nexport function queue(): Queue {\n const q: {\n action: Action<any>;\n resolve: (value: any) => void;\n reject: (error: unknown) => void;\n ref?: any;\n }[] = [];\n const completionListeners = new Set<Listener<void>>();\n let active = false;\n\n const notify = () => {\n for (const listener of completionListeners) {\n listener();\n }\n\n completionListeners.clear();\n };\n\n const run = async () => {\n if (!active) {\n active = true;\n\n let next;\n while ((next = q.shift())) {\n try {\n let result = next.action();\n if (isPromise(result)) {\n result = await result;\n }\n\n next.resolve(result);\n } catch (error) {\n next.reject(error);\n }\n }\n\n active = false;\n notify();\n }\n };\n\n return Object.assign(\n <T>(action: Action<T>, ref?: any) => {\n return new Promise<T>((resolve, reject) => {\n q.push({ action, resolve, reject, ref });\n run();\n });\n },\n {\n clear() {\n q.length = 0;\n },\n\n whenDone() {\n if (!active) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n completionListeners.add(resolve);\n });\n },\n\n get size() {\n return q.length;\n },\n\n getRefs() {\n return q.map((item) => item.ref).filter((x) => x !== undefined);\n },\n },\n );\n}\n","import type { Cache } from '@core';\nimport type { AsyncConnectionActions, Cancel, Connection, StoreLike } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { Deferred } from '@lib/deferred';\nimport isPromise from '@lib/isPromise';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport { queue } from '@lib/queue';\nimport { deepEqual } from './equals';\n\nexport interface CalculatedValue<T> {\n value: T;\n check: () => void;\n stop(): void;\n invalidateDependencies(recursive?: boolean): void;\n}\n\nexport function calculatedValue<T>(store: Store<T>, notify: () => void): CalculatedValue<T> {\n if (!(store.getter instanceof Function)) {\n return staticValue(store.getter);\n }\n\n let active = false;\n const deps = new Array<{ store: StoreLike<any>; value: any; on: () => void; off: () => void }>();\n let value: T | undefined;\n const whenConnected = new Deferred();\n const whenExecuted = new Deferred();\n const ac = new AbortController();\n let connection: { active: boolean; cancel?: Cancel } | undefined;\n const q = queue();\n q(() => whenExecuted);\n\n const cancelEffect = store.addEffect(() => {\n if (connection) {\n store.invalidate();\n return;\n }\n\n active = true;\n\n for (const dep of deps) {\n dep.on();\n }\n\n return () => {\n active = false;\n\n for (const dep of deps) {\n dep.off();\n }\n\n if (connection) {\n connection.active = false;\n connection.cancel?.();\n q.clear();\n\n if ('state' in store) {\n (store as unknown as Cache<any>).state.set((state) => ({\n ...state,\n isConnected: false,\n isStale: true,\n }));\n }\n }\n };\n });\n\n function use<S>(dep: StoreLike<S>) {\n const value = dep.get();\n let cancel: Cancel | undefined;\n\n const on = () => {\n cancel ||= dep.subscribe(() => store.invalidate(), { runNow: false });\n };\n\n const off = () => {\n cancel?.();\n cancel = undefined;\n };\n\n deps.push({ store: dep, value, on, off });\n\n if (active) {\n on();\n }\n\n return value;\n }\n\n async function connect(createConnection: Connection<T>) {\n if (!active) {\n connection = { active: false };\n return;\n }\n\n const actions: AsyncConnectionActions<any> = {\n set(_value) {\n q(() => {\n if (!connection?.active) {\n return;\n }\n\n value = _value;\n notify();\n });\n },\n updateValue(update) {\n q(async () => {\n if (!connection?.active) {\n return;\n }\n\n if (update instanceof Function) {\n const currentValue = await value;\n\n if (!connection?.active) {\n return;\n }\n\n try {\n update = update(currentValue);\n } catch (error) {\n value = PromiseWithState.reject(error) as T;\n notify();\n connection.active = false;\n connection.cancel?.();\n return;\n }\n }\n\n value = PromiseWithState.resolve(update) as T;\n notify();\n });\n },\n updateError(error) {\n q(() => {\n if (!connection?.active) {\n return;\n }\n\n connection.active = false;\n connection.cancel?.();\n\n if ('state' in store) {\n (store as unknown as Cache<any>).state.set({\n status: 'error',\n error,\n isConnected: false,\n isUpdating: false,\n isStale: false,\n });\n }\n\n value = PromiseWithState.reject(error) as T;\n notify();\n });\n },\n updateIsConnected(isConnected) {\n if (isConnected) {\n whenConnected.resolve();\n }\n\n q(() => {\n if (!connection?.active) {\n return;\n }\n\n if ('state' in store) {\n (store as unknown as Cache<any>).state.set('isConnected', isConnected);\n }\n });\n },\n close() {\n if (connection?.active) {\n store.invalidate();\n }\n },\n };\n\n connection = { active: true };\n let _cancel: Cancel | undefined = createConnection(actions as any);\n\n connection.cancel = () => {\n _cancel?.();\n _cancel = undefined;\n };\n\n if (!connection.active) {\n connection.cancel();\n }\n\n return whenConnected;\n }\n\n try {\n value = store.getter({ signal: ac.signal, use, connect });\n } catch (error) {\n value = PromiseWithState.reject(error) as T;\n\n if (connection) {\n connection.active = false;\n connection.cancel?.();\n q.clear();\n }\n }\n\n if (isPromise(value)) {\n value.finally(() => whenExecuted.resolve()).catch(() => undefined);\n } else {\n whenExecuted.resolve();\n }\n\n function check() {\n if (store.options.cacheValue === false) {\n return false;\n }\n\n for (const dep of deps) {\n if (!deepEqual(dep.store.get(), dep.value)) {\n return false;\n }\n }\n return true;\n }\n\n function stop() {\n cancelEffect();\n whenExecuted.resolve();\n whenConnected.resolve();\n ac.abort();\n\n if (connection) {\n connection.active = false;\n connection.cancel?.();\n q.clear();\n }\n }\n\n function invalidateDependencies(recursive?: boolean) {\n for (const dep of deps) {\n dep.store.invalidate(recursive);\n }\n }\n\n return {\n get value() {\n return value!;\n },\n check,\n stop,\n invalidateDependencies,\n };\n}\n\nexport function staticValue<T>(value: T): CalculatedValue<T> {\n return {\n value,\n check: () => true,\n stop: () => undefined,\n invalidateDependencies: () => undefined,\n };\n}\n\nexport function staleValue<T>(value: T): CalculatedValue<T> {\n return {\n value,\n check: () => false,\n stop: () => undefined,\n invalidateDependencies: () => undefined,\n };\n}\n","import type { AnyPath } from './path';\nimport { get } from './propAccess';\n\nexport function makeSelector<T, S>(selector?: ((value: T) => S) | AnyPath): (value: T) => S {\n if (!selector) {\n return (x) => x as any;\n }\n\n if (selector instanceof Function) {\n return selector;\n }\n\n return (x) => get(x, selector as any) as any;\n}\n","import { calcDuration } from './calcDuration';\nimport type { Duration } from '@core';\n\nexport type DebounceOptions =\n | Duration\n | {\n wait: Duration;\n maxWait?: Duration;\n waitOnRunNow?: boolean;\n };\n\nexport function debounce<Args extends any[]>(\n action: (...args: Args) => void,\n options: Duration | DebounceOptions,\n): {\n (...args: Args): void;\n flush(): void;\n cancel(): void;\n isScheduled(): boolean;\n} {\n const wait =\n typeof options === 'object' && 'wait' in options\n ? calcDuration(options.wait)\n : calcDuration(options);\n\n const maxWait =\n typeof options === 'object' && 'maxWait' in options && options.maxWait !== undefined\n ? calcDuration(options.maxWait)\n : undefined;\n\n let run: (() => void) | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timeoutStarted: number | undefined;\n\n function flush() {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n run?.();\n }\n\n function cancel() {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n run = undefined;\n timeout = undefined;\n timeoutStarted = undefined;\n }\n\n function isScheduled() {\n return timeout !== undefined;\n }\n\n function debounce(...args: Args) {\n const now = Date.now();\n timeoutStarted ??= now;\n\n const deadline = Math.min(\n //\n now + wait,\n timeoutStarted + (maxWait ?? Number.POSITIVE_INFINITY),\n );\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n run = () => {\n run = undefined;\n timeout = undefined;\n timeoutStarted = undefined;\n\n action(...args);\n };\n\n timeout = setTimeout(run, deadline - now);\n }\n\n return Object.assign(debounce, { flush, cancel, isScheduled });\n}\n","import type { Cancel } from '@core';\nimport type { DisposableCancel } from '@core/commonTypes';\n\nexport default function disposable(dispose: Cancel): DisposableCancel {\n return Object.assign(\n dispose,\n Symbol.dispose ? { [Symbol.dispose]: dispose } : {},\n ) as DisposableCancel;\n}\n","export function forwardError(error: unknown): void {\n setTimeout(() => {\n throw error;\n });\n}\n","import { autobind } from '@lib/autobind';\n\nexport class PromiseCancelError extends Error {\n constructor() {\n super('cancelled');\n }\n}\n\nexport class PromiseWithCancel<T> extends Promise<T> {\n private abortController;\n\n constructor(\n executor: (\n resolve: (value: T) => void,\n reject: (error: unknown) => void,\n signal: AbortSignal,\n ) => void,\n ) {\n autobind(PromiseWithCancel);\n const abortController = new AbortController();\n\n super((resolve, reject) => {\n executor(resolve, reject, abortController.signal);\n\n abortController.signal.addEventListener('abort', () => {\n reject(abortController.signal.reason);\n });\n });\n\n this.abortController = abortController;\n }\n\n cancel(reason: any = new PromiseCancelError()): void {\n this.abortController.abort(reason);\n }\n}\n","import type { Store } from '../core/store';\nimport type { OptionalProperties, OptionalPropertyOf } from './typeHelpers';\n\ntype Function_ = (...args: any) => any;\n\nfunction createArrayAction<P extends keyof Array<any>>(prop: P) {\n return function arrayAction<T extends Array<any>>(\n this: Store<T>,\n ...args: T[P] extends Function_ ? Parameters<T[P]> : never\n ): T[P] extends Function_ ? ReturnType<T[P]> : never {\n const newArray = this.get().slice() as T;\n const result = (newArray[prop] as Function_)(...(args as any));\n this.set(newArray);\n return result;\n };\n}\nexport const arrayMethods: {\n [P in 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | 'reverse' | 'sort']: <\n T extends Array<any>,\n >(\n this: Store<T>,\n ...args: T[P] extends Function_ ? Parameters<T[P]> : never\n ) => T[P] extends Function_ ? ReturnType<T[P]> : never;\n} = {\n splice: /* @__PURE__ */ createArrayAction('splice'),\n push: /* @__PURE__ */ createArrayAction('push'),\n pop: /* @__PURE__ */ createArrayAction('pop'),\n shift: /* @__PURE__ */ createArrayAction('shift'),\n unshift: /* @__PURE__ */ createArrayAction('unshift'),\n reverse: /* @__PURE__ */ createArrayAction('reverse'),\n sort: /* @__PURE__ */ createArrayAction('sort'),\n};\n\nexport const recordMethods = {\n delete<T extends Record<any, any>, K extends OptionalPropertyOf<T>>(\n this: Store<T>,\n key: K,\n ): void {\n const copy = { ...this.get() };\n delete copy[key];\n this.set(copy);\n },\n\n clear<T extends Record<any, any>>(\n this: OptionalProperties<T> extends T ? Store<T> : never,\n ): void {\n this.set({} as T);\n },\n};\n\nexport const mapMethods = {\n delete<K, V>(this: Store<Map<K, V>>, key: K): boolean {\n const newMap = new Map(this.get());\n const result = newMap.delete(key);\n this.set(newMap);\n return result;\n },\n\n clear<K, V>(this: Store<Map<K, V>>): void {\n this.set(new Map());\n },\n};\n\nexport const setMethods = {\n add<T>(this: Store<Set<T>>, value: T): void {\n const newSet = new Set(this.get());\n newSet.add(value);\n this.set(newSet);\n },\n\n delete<T>(this: Store<Set<T>>, value: T): void {\n const newSet = new Set(this.get());\n newSet.delete(value);\n this.set(newSet);\n },\n\n clear<T>(this: Store<Set<T>>): void {\n this.set(new Set());\n },\n};\n","import { calcDuration } from './calcDuration';\nimport type { Duration } from '@core';\n\nexport function throttle<Args extends any[]>(\n action: (...args: Args) => void,\n duration: Duration,\n): (...args: Args) => void {\n const ms = calcDuration(duration);\n\n let t = 0;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: Args) => {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n const dt = t + ms - Date.now();\n if (dt <= 0) {\n action(...args);\n t = Date.now();\n return;\n }\n\n timeout = setTimeout(() => {\n action(...args);\n t = Date.now();\n }, dt);\n };\n}\n","import { autobind } from '@lib/autobind';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue, staticValue, type CalculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { debounce } from '@lib/debounce';\nimport disposable from '@lib/disposable';\nimport { deepEqual } from '@lib/equals';\nimport { forwardError } from '@lib/forwardError';\nimport { isObject } from '@lib/helpers';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { AnyPath, Path, SettablePath, Value } from '@lib/path';\nimport { PromiseWithCancel } from '@lib/promiseWithCancel';\nimport { get, set } from '@lib/propAccess';\nimport { arrayMethods, mapMethods, recordMethods, setMethods } from '@lib/standardMethods';\nimport { throttle } from '@lib/throttle';\nimport type {\n CalculationActions,\n Cancel,\n DisposableCancel,\n Duration,\n Effect,\n Listener,\n Selector,\n SubscribeOptions,\n Update,\n} from './commonTypes';\n\nexport type StoreMethods = Record<string, (...args: any[]) => any>;\n\nexport type BoundStoreMethods<T, Methods extends StoreMethods> = Methods &\n ThisType<Store<T> & Methods>;\n\nexport interface StoreOptions<T> {\n retain?: Duration;\n equals?: SubscribeOptions['equals'];\n effect?: Effect<Store<T>> | { effect: Effect<Store<T>>; retain?: Duration };\n cacheValue?: boolean;\n}\n\nexport interface StoreOptionsWithMethods<T, Methods extends StoreMethods> extends StoreOptions<T> {\n methods?: Methods & ThisType<Store<T> & Methods & StandardMethods<T>>;\n}\n\nexport type Calculate<T> = (helpers: CalculationActions<T>) => T;\n\ntype StandardMethods<T> =\n T extends Map<any, any>\n ? typeof mapMethods\n : T extends Set<any>\n ? typeof setMethods\n : T extends Array<any>\n ? typeof arrayMethods\n : T extends Record<any, any>\n ? typeof recordMethods\n : Record<string, never>;\n\ntype StoreWithMethods<T, Methods extends StoreMethods> = Store<T> &\n Omit<BoundStoreMethods<T, Methods>, keyof Store<T>> &\n StandardMethods<T>;\n\nexport interface OnceOptions {\n signal?: AbortSignal;\n timeout?: Duration;\n}\n\nfunction noop() {\n return undefined;\n}\n\nexport class Store<T> {\n private static hooks?: Set<(this: Store<any>, store: Store<any>) => void>;\n\n static addHook(hook: (store: Store<any>) => void): DisposableCancel {\n this.hooks ??= new Set();\n this.hooks.add(hook);\n return disposable(() => this.hooks?.delete(hook));\n }\n\n version?: string;\n\n protected calculatedValue?: CalculatedValue<T>;\n protected defaultValue?: CalculatedValue<T>;\n\n protected listeners: Map<Listener, boolean> = new Map();\n\n protected effects: Map<\n Effect<Store<T>>,\n { handle?: Cancel; retain?: number; timeout?: ReturnType<typeof setTimeout> }\n > = new Map();\n\n protected notifyId = {};\n\n constructor(\n public readonly getter: T | Calculate<T>,\n public readonly options: StoreOptions<T> = {},\n public readonly derivedFrom?: {\n store: Store<any>;\n selectors: (Selector<any, any> | AnyPath)[];\n updater: (state: any) => void;\n },\n ) {\n autobind(Store);\n\n if (typeof getter !== 'function') {\n this.calculatedValue = this.defaultValue = staticValue(getter);\n }\n\n for (const hook of Store.hooks ?? []) {\n hook.apply(this, [this]);\n }\n\n if (options.effect instanceof Function) {\n this.addEffect(options.effect);\n } else if (options.effect) {\n this.addEffect(options.effect.effect, options.effect.retain);\n }\n }\n\n get(): T {\n if (!this.calculatedValue?.check()) {\n this.calculatedValue?.stop();\n this.calculatedValue = undefined;\n }\n\n if (!this.calculatedValue) {\n this.calculatedValue = calculatedValue(this, this.notify);\n }\n\n return this.calculatedValue.value;\n }\n\n set(update: Update<T>): void;\n\n set<const P>(path: Constrain<P, Path<T>>, update: Update<Value<T, P>>): void;\n\n set(...args: any[]): void {\n const path: any = args.length > 1 ? args[0] : [];\n let update: Update<any> = args.length > 1 ? args[1] : args[0];\n\n if (update instanceof Function) {\n const before = this.get();\n const valueBefore = get(before, path);\n const valueAfter = update(valueBefore);\n update = set(before, path, valueAfter);\n } else if (path.length > 0) {\n update = set(this.get(), path, update);\n }\n\n if (this.derivedFrom) {\n this.derivedFrom.updater(update);\n return;\n }\n\n this.calculatedValue?.stop();\n this.calculatedValue = staticValue(update);\n this.notify();\n }\n\n invalidate(recursive?: boolean): void {\n if (recursive) {\n this.calculatedValue?.invalidateDependencies(recursive);\n }\n\n this.calculatedValue?.stop();\n this.calculatedValue = this.defaultValue;\n this.notify();\n }\n\n subscribe(\n listener: Listener<T, { cancel: Cancel }>,\n options?: SubscribeOptions,\n ): DisposableCancel {\n const {\n passive,\n runNow = true,\n throttle: throttleOption,\n debounce: debounceOption,\n equals = this.options.equals ?? deepEqual,\n } = options ?? {};\n\n let isSetup = false;\n let previousValue: { value: T } | undefined;\n\n let innerListener = () => {\n if (!isSetup) {\n return;\n }\n\n const value = passive ? this.calculatedValue : { value: this.get() };\n\n if (!value) {\n return;\n }\n\n if (previousValue && equals(value.value, previousValue.value)) {\n return;\n }\n\n const _previousValue = previousValue?.value;\n previousValue = this.calculatedValue && { value: this.calculatedValue?.value };\n\n try {\n listener.apply({ cancel }, [value.value, _previousValue]);\n } catch (error) {\n forwardError(error);\n }\n };\n\n if (throttleOption) {\n innerListener = throttle(innerListener, throttleOption);\n } else if (debounceOption) {\n innerListener = debounce(innerListener, debounceOption);\n }\n\n this.listeners.set(innerListener, !passive);\n const cancel = () => {\n if (this.listeners.delete(innerListener) && !passive) {\n this.onUnsubscribe();\n }\n };\n\n if (!passive) {\n this.onSubscribe();\n }\n\n isSetup = true;\n\n if (runNow) {\n innerListener();\n\n if (\n !throttleOption &&\n typeof debounceOption === 'object' &&\n 'waitOnRunNow' in debounceOption &&\n debounceOption.waitOnRunNow === false &&\n 'flush' in innerListener\n ) {\n (innerListener as { flush: () => void }).flush();\n }\n } else {\n previousValue = passive\n ? this.calculatedValue && { value: this.calculatedValue.value }\n : { value: this.get() };\n }\n\n return disposable(cancel);\n }\n\n once<S extends T>(\n condition: (value: T) => value is S,\n options?: OnceOptions,\n ): PromiseWithCancel<S>;\n\n once(condition: (value: T) => boolean, options?: OnceOptions): PromiseWithCancel<T>;\n\n once(options?: OnceOptions): PromiseWithCancel<T>;\n\n once(\n ...args: [condition: (value: any) => boolean, options?: OnceOptions] | [options?: OnceOptions]\n ): PromiseWithCancel<any> {\n const condition = args[0] instanceof Function ? args[0] : Boolean;\n const options = args[0] instanceof Function ? args[1] : args[0];\n\n return new PromiseWithCancel<T>((resolve, reject, signal) => {\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const cancel = this.subscribe(\n (value) => {\n if (stopped || !condition(value)) {\n return;\n }\n\n resolve(value);\n stopped = true;\n if (timer) {\n clearTimeout(timer);\n }\n setTimeout(() => cancel());\n },\n {\n runNow: !!condition,\n },\n );\n\n if (stopped) {\n return;\n }\n\n signal.addEventListener('abort', cancel);\n\n options?.signal?.addEventListener('abort', () => {\n cancel();\n reject(options.signal?.reason ?? new Error('cancelled'));\n });\n\n if (options?.timeout !== undefined) {\n timer = setTimeout(() => {\n cancel();\n reject(new Error('timeout'));\n }, calcDuration(options.timeout));\n }\n });\n }\n\n map<S>(selector: Selector<T, S>, updater?: (value: S) => Update<T>): Store<S>;\n\n map<const P>(selector: Constrain<P, SettablePath<T>>): Store<Value<T, P>>;\n\n map(_selector: Selector<T, any> | SettablePath<any>, ...args: any[]): Store<any> {\n const updater: ((value: any) => Update<T>) | undefined =\n _selector instanceof Function\n ? args[0]\n : (value) => (state) => set(state, _selector as any, value);\n\n const selector = makeSelector(_selector);\n\n const derivedFrom = {\n store: this.derivedFrom ? this.derivedFrom.store : this,\n selectors: this.derivedFrom ? [...this.derivedFrom.selectors, _selector] : [_selector],\n\n updater: (value: any) => {\n if (!updater) {\n throw new TypeError(\n 'Can only update computed stores that either are derived from other stores using string selectors or have an updater function.',\n );\n }\n\n let update = updater(value);\n\n if (update instanceof Function) {\n update = update(this.get());\n }\n\n if (this.derivedFrom) {\n this.derivedFrom.updater(update);\n } else {\n this.set(update);\n }\n },\n };\n\n return new Store(\n ({ use }) => {\n return selector(use(this));\n },\n undefined,\n derivedFrom,\n );\n }\n\n /** Add an effect that will be executed when the store becomes active, which means when it has at least one subscriber.\n * @param effect\n * If there is already a subscriber, the effect will be executed immediately.\n * Otherweise it will be executed as soon as the first subscription is created.\n * Every time all subscriptions are removed and the first is created again, the effect will be executed again.\n * @param retain\n * If provided, delay tearing down effects when the last subscriber is removed. This is useful if a short gap in subscriber coverage is supposed to be ignored. E.g. when switching pages, the old page might unsubscribe, while the new page subscribes immediately after.\n * @returns\n * The effect can return a teardown callback, which will be executed when the last subscription is removed and potentially the ratain time has passed.\n */\n addEffect(\n effect: Effect<Store<T>>,\n retain: Duration | undefined = this.options.retain,\n ): DisposableCancel {\n this.effects.set(effect, {\n handle: this.isActive() ? (effect.apply(this, [this]) ?? noop) : undefined,\n retain: retain !== undefined ? calcDuration(retain) : undefined,\n });\n\n return disposable(() => {\n const { handle, timeout } = this.effects.get(effect) ?? {};\n handle?.();\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.delete(effect);\n });\n }\n\n /** Return whether the store is currently active, which means whether it has at least one subscriber. */\n isActive(): boolean {\n return [...this.listeners.values()].some(Boolean);\n }\n\n protected onSubscribe(): void {\n if ([...this.listeners.values()].filter(Boolean).length > 1) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.set(effect, {\n handle: handle ?? effect.apply(this, [this]) ?? noop,\n retain,\n timeout: undefined,\n });\n }\n }\n\n protected onUnsubscribe(): void {\n if ([...this.listeners.values()].some(Boolean)) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n if (!retain) {\n handle?.();\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.set(effect, {\n handle: undefined,\n retain,\n timeout: undefined,\n });\n\n continue;\n }\n\n const newTimeout =\n timeout ??\n (handle\n ? setTimeout(() => {\n handle();\n this.effects.set(effect, {\n handle: undefined,\n retain,\n timeout: undefined,\n });\n }, retain)\n : undefined);\n\n this.effects.set(effect, {\n handle,\n retain,\n timeout: newTimeout,\n });\n }\n }\n\n protected notify(): void {\n const n = {};\n this.notifyId = n;\n\n const snapshot = [...this.listeners.entries()];\n const active = snapshot.filter(([, active]) => active);\n const passive = snapshot.filter(([, active]) => !active);\n for (const [listener] of [...active, ...passive]) {\n listener();\n if (n !== this.notifyId) break;\n }\n }\n}\n\nfunction create<T>(calculate: Calculate<T>, options?: StoreOptions<T>): Store<T>;\nfunction create<T, Methods extends StoreMethods = {}>(\n initialState: T,\n options?: StoreOptionsWithMethods<T, Methods>,\n): StoreWithMethods<T, Methods>;\nfunction create<T, Methods extends StoreMethods>(\n initialState: T | Calculate<T>,\n options?: StoreOptionsWithMethods<T, Methods>,\n): StoreWithMethods<T, Methods> | Store<T> {\n options = { ...createStore.defaultOptions, ...options };\n\n const store = new Store(initialState, options);\n\n if (initialState instanceof Function) {\n return store;\n }\n\n let methods: StoreMethods | undefined = options?.methods;\n\n if (initialState instanceof Map) {\n methods = { ...mapMethods, ...methods };\n } else if (initialState instanceof Set) {\n methods = { ...setMethods, ...methods };\n } else if (Array.isArray(initialState)) {\n methods = { ...arrayMethods, ...methods };\n } else if (isObject(initialState)) {\n methods = { ...recordMethods, ...methods };\n }\n\n const boundMethods = Object.fromEntries(\n Object.entries(methods ?? ({} as BoundStoreMethods<T, any>))\n .filter(([name]) => !(name in store))\n .map(([name, action]) => [name, (action as any).bind(store)]),\n ) as BoundStoreMethods<T, any>;\n\n return Object.assign(store, boundMethods);\n}\n\nexport const createStore: typeof create & { defaultOptions: StoreOptions<any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: {\n equals: deepEqual,\n } as StoreOptions<any>,\n });\n"],"mappings":";;;AAAA,MAAM,SAAS,OAAO;AAEtB,MAAa,YAGX,WACW;AACX,MAAK,MAAM,OAAO,QAAQ,QAAQ,OAAO,YAAY;AACnD,MAAI,QAAQ,cACV;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AC/C,MAAM,UAAU,SAAS,QAAQ,GAAGA,cAAY,CAACA;AACjD,OAAK,MAAM,CAAC,aAAa,CAAC,GAAG,QAAQ,GAAG,UAAU;AAChD;AACA,OAAI,MAAM,KAAK,SAAU;;;;AAU/B,SAAS,OACP,cACA,SACyC;AACzC,WAAU;EAAE,GAAG,YAAY;EAAgB,GAAG;;CAE9C,MAAM,QAAQ,IAAI,MAAM,cAAc;AAEtC,KAAI,wBAAwB,SAC1B,QAAO;CAGT,IAAIC,UAAoC,SAAS;AAEjD,KAAI,wBAAwB,IAC1B,WAAU;EAAE,GAAG;EAAY,GAAG;;UACrB,wBAAwB,IACjC,WAAU;EAAE,GAAG;EAAY,GAAG;;UACrB,MAAM,QAAQ,cACvB,WAAU;EAAE,GAAG;EAAc,GAAG;;UACvB,SAAS,cAClB,WAAU;EAAE,GAAG;EAAe,GAAG;;CAGnC,MAAM,eAAe,OAAO,YAC1B,OAAO,QAAQ,WAAY,IACxB,QAAQ,CAAC,UAAU,EAAE,QAAQ,QAC7B,KAAK,CAAC,MAAM,YAAY,CAAC,MAAO,OAAe,KAAK;AAGzD,QAAO,OAAO,OAAO,OAAO;;AAG9B,MAAaC,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB,EACd,QAAQ"}
@@ -292,10 +292,9 @@ function calculatedValue(store, notify) {
292
292
  if (isPromise(value)) value.finally(() => whenExecuted.resolve()).catch(() => void 0);
293
293
  else whenExecuted.resolve();
294
294
  function check() {
295
- for (const dep of deps) if (!require_propAccess.deepEqual(dep.store.get(), dep.value)) {
296
- store.invalidate();
297
- return;
298
- }
295
+ if (store.options.cacheValue === false) return false;
296
+ for (const dep of deps) if (!require_propAccess.deepEqual(dep.store.get(), dep.value)) return false;
297
+ return true;
299
298
  }
300
299
  function stop() {
301
300
  cancelEffect();
@@ -323,7 +322,7 @@ function calculatedValue(store, notify) {
323
322
  function staticValue(value) {
324
323
  return {
325
324
  value,
326
- check: () => void 0,
325
+ check: () => true,
327
326
  stop: () => void 0,
328
327
  invalidateDependencies: () => void 0
329
328
  };
@@ -518,7 +517,10 @@ var Store = class Store {
518
517
  else if (options.effect) this.addEffect(options.effect.effect, options.effect.retain);
519
518
  }
520
519
  get() {
521
- this.calculatedValue?.check();
520
+ if (!this.calculatedValue?.check()) {
521
+ this.calculatedValue?.stop();
522
+ this.calculatedValue = void 0;
523
+ }
522
524
  if (!this.calculatedValue) this.calculatedValue = calculatedValue(this, this.notify);
523
525
  return this.calculatedValue.value;
524
526
  }
@@ -816,4 +818,4 @@ Object.defineProperty(exports, 'throttle', {
816
818
  return throttle;
817
819
  }
818
820
  });
819
- //# sourceMappingURL=store-1TGlSyq4.cjs.map
821
+ //# sourceMappingURL=store-DQcFfgKD.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store-DQcFfgKD.cjs","names":["state: ValueState<T> | ErrorState | PendingState","value","q: {\n action: Action<any>;\n resolve: (value: any) => void;\n reject: (error: unknown) => void;\n ref?: any;\n }[]","value: T | undefined","connection: { active: boolean; cancel?: Cancel } | undefined","value","cancel: Cancel | undefined","actions: AsyncConnectionActions<any>","_cancel: Cancel | undefined","deepEqual","get","run: (() => void) | undefined","timeout: ReturnType<typeof setTimeout> | undefined","timeoutStarted: number | undefined","debounce","arrayMethods: {\n [P in 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | 'reverse' | 'sort']: <\n T extends Array<any>,\n >(\n this: Store<T>,\n ...args: T[P] extends Function_ ? Parameters<T[P]> : never\n ) => T[P] extends Function_ ? ReturnType<T[P]> : never;\n}","timeout: ReturnType<typeof setTimeout> | undefined","getter: T | Calculate<T>","options: StoreOptions<T>","derivedFrom?: {\n store: Store<any>;\n selectors: (Selector<any, any> | AnyPath)[];\n updater: (state: any) => void;\n }","path: any","update: Update<any>","get","set","deepEqual","previousValue: { value: T } | undefined","timer: ReturnType<typeof setTimeout> | undefined","updater: ((value: any) => Update<T>) | undefined","active","methods: StoreMethods | undefined","isObject","createStore: typeof create & { defaultOptions: StoreOptions<any> }"],"sources":["../src/lib/autobind.ts","../src/lib/calcDuration.ts","../src/lib/deferred.ts","../src/lib/isPromise.ts","../src/lib/promiseWithState.ts","../src/lib/queue.ts","../src/lib/calculatedValue.ts","../src/lib/makeSelector.ts","../src/lib/debounce.ts","../src/lib/disposable.ts","../src/lib/forwardError.ts","../src/lib/promiseWithCancel.ts","../src/lib/standardMethods.ts","../src/lib/throttle.ts","../src/core/store.ts"],"sourcesContent":["const marker = Symbol('autobind');\n\nexport const autobind = <\n TClass extends abstract new (...args: any) => any = abstract new (...args: any) => any,\n>(\n _class: TClass,\n): TClass => {\n for (const key of Reflect.ownKeys(_class.prototype)) {\n if (key === 'constructor') {\n continue;\n }\n\n const descriptor = Reflect.getOwnPropertyDescriptor(_class.prototype, key);\n let method = descriptor?.get?.() ?? descriptor?.value;\n let isBinding = false;\n\n if (typeof method !== 'function' || method[marker]) {\n continue;\n }\n\n Reflect.defineProperty(_class.prototype, key, {\n configurable: true,\n get() {\n if (\n isBinding ||\n this === _class.prototype ||\n Object.prototype.hasOwnProperty.call(this, key) ||\n typeof method !== 'function'\n ) {\n return method;\n }\n\n const boundMethod = (...args: any[]) => Reflect.apply(method, this, args);\n boundMethod[marker] = true;\n isBinding = true;\n\n Object.defineProperty(this, key, {\n configurable: true,\n get() {\n return boundMethod;\n },\n });\n\n isBinding = false;\n return boundMethod;\n },\n set(v) {\n method = v;\n },\n });\n }\n\n return _class;\n};\n","import type { Duration } from '../core/commonTypes';\n\nexport function calcDuration(t: Duration): number {\n if (typeof t === 'number') return t;\n return (\n (t.milliseconds ?? 0) +\n (t.seconds ?? 0) * 1000 +\n (t.minutes ?? 0) * 60 * 1000 +\n (t.hours ?? 0) * 60 * 60 * 1000 +\n (t.days ?? 0) * 24 * 60 * 60 * 1000\n );\n}\n","export class Deferred<T = void> extends Promise<T> {\n resolve: (value: T | PromiseLike<T>) => void = () => undefined;\n reject: (reason?: any) => void = () => undefined;\n\n constructor() {\n Object.defineProperty(Deferred, Symbol.species, {\n value: Promise,\n });\n\n const that = {};\n\n super((resolve, reject) => {\n Object.assign(that, { resolve, reject });\n });\n\n Object.assign(this, that);\n }\n}\n","export default function isPromise(value: unknown): value is Promise<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof value.then === 'function'\n );\n}\n","import isPromise from '@lib/isPromise';\nimport { type ErrorState, type PendingState, type ValueState } from './cacheState';\nimport { type MaybePromise } from './maybePromise';\n\nexport class PromiseWithState<T> extends Promise<T> {\n static override resolve(): PromiseWithState<void>;\n\n static override resolve<T>(value: MaybePromise<T>): PromiseWithState<T>;\n\n static override resolve<T>(value?: MaybePromise<T>) {\n return new PromiseWithState<T>(value as MaybePromise<T>);\n }\n\n static override reject<T = never>(error: unknown): PromiseWithState<T> {\n return new PromiseWithState<T>(Promise.reject(error), { status: 'error', error });\n }\n\n constructor(\n value: MaybePromise<T>,\n public state: ValueState<T> | ErrorState | PendingState = { status: 'pending' },\n ) {\n super((resolve) => resolve(value));\n\n Object.defineProperty(PromiseWithState, Symbol.species, {\n value: Promise,\n });\n\n if (isPromise(value)) {\n value\n .then((value) => {\n this.state = { status: 'value', value: value };\n })\n .catch((error) => {\n this.state = { status: 'error', error };\n });\n } else {\n this.state = { status: 'value', value: value };\n }\n }\n}\n","import isPromise from '@lib/isPromise';\nimport type { MaybePromise } from './maybePromise';\nimport type { Listener } from '@core';\n\ntype Action<T> = () => MaybePromise<T>;\n\nexport interface Queue {\n <T>(action: Action<T>, ref?: any): Promise<T>;\n clear: () => void;\n whenDone: () => Promise<void>;\n size: number;\n getRefs: () => any[];\n}\n\nexport function queue(): Queue {\n const q: {\n action: Action<any>;\n resolve: (value: any) => void;\n reject: (error: unknown) => void;\n ref?: any;\n }[] = [];\n const completionListeners = new Set<Listener<void>>();\n let active = false;\n\n const notify = () => {\n for (const listener of completionListeners) {\n listener();\n }\n\n completionListeners.clear();\n };\n\n const run = async () => {\n if (!active) {\n active = true;\n\n let next;\n while ((next = q.shift())) {\n try {\n let result = next.action();\n if (isPromise(result)) {\n result = await result;\n }\n\n next.resolve(result);\n } catch (error) {\n next.reject(error);\n }\n }\n\n active = false;\n notify();\n }\n };\n\n return Object.assign(\n <T>(action: Action<T>, ref?: any) => {\n return new Promise<T>((resolve, reject) => {\n q.push({ action, resolve, reject, ref });\n run();\n });\n },\n {\n clear() {\n q.length = 0;\n },\n\n whenDone() {\n if (!active) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n completionListeners.add(resolve);\n });\n },\n\n get size() {\n return q.length;\n },\n\n getRefs() {\n return q.map((item) => item.ref).filter((x) => x !== undefined);\n },\n },\n );\n}\n","import type { Cache } from '@core';\nimport type { AsyncConnectionActions, Cancel, Connection, StoreLike } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { Deferred } from '@lib/deferred';\nimport isPromise from '@lib/isPromise';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport { queue } from '@lib/queue';\nimport { deepEqual } from './equals';\n\nexport interface CalculatedValue<T> {\n value: T;\n check: () => void;\n stop(): void;\n invalidateDependencies(recursive?: boolean): void;\n}\n\nexport function calculatedValue<T>(store: Store<T>, notify: () => void): CalculatedValue<T> {\n if (!(store.getter instanceof Function)) {\n return staticValue(store.getter);\n }\n\n let active = false;\n const deps = new Array<{ store: StoreLike<any>; value: any; on: () => void; off: () => void }>();\n let value: T | undefined;\n const whenConnected = new Deferred();\n const whenExecuted = new Deferred();\n const ac = new AbortController();\n let connection: { active: boolean; cancel?: Cancel } | undefined;\n const q = queue();\n q(() => whenExecuted);\n\n const cancelEffect = store.addEffect(() => {\n if (connection) {\n store.invalidate();\n return;\n }\n\n active = true;\n\n for (const dep of deps) {\n dep.on();\n }\n\n return () => {\n active = false;\n\n for (const dep of deps) {\n dep.off();\n }\n\n if (connection) {\n connection.active = false;\n connection.cancel?.();\n q.clear();\n\n if ('state' in store) {\n (store as unknown as Cache<any>).state.set((state) => ({\n ...state,\n isConnected: false,\n isStale: true,\n }));\n }\n }\n };\n });\n\n function use<S>(dep: StoreLike<S>) {\n const value = dep.get();\n let cancel: Cancel | undefined;\n\n const on = () => {\n cancel ||= dep.subscribe(() => store.invalidate(), { runNow: false });\n };\n\n const off = () => {\n cancel?.();\n cancel = undefined;\n };\n\n deps.push({ store: dep, value, on, off });\n\n if (active) {\n on();\n }\n\n return value;\n }\n\n async function connect(createConnection: Connection<T>) {\n if (!active) {\n connection = { active: false };\n return;\n }\n\n const actions: AsyncConnectionActions<any> = {\n set(_value) {\n q(() => {\n if (!connection?.active) {\n return;\n }\n\n value = _value;\n notify();\n });\n },\n updateValue(update) {\n q(async () => {\n if (!connection?.active) {\n return;\n }\n\n if (update instanceof Function) {\n const currentValue = await value;\n\n if (!connection?.active) {\n return;\n }\n\n try {\n update = update(currentValue);\n } catch (error) {\n value = PromiseWithState.reject(error) as T;\n notify();\n connection.active = false;\n connection.cancel?.();\n return;\n }\n }\n\n value = PromiseWithState.resolve(update) as T;\n notify();\n });\n },\n updateError(error) {\n q(() => {\n if (!connection?.active) {\n return;\n }\n\n connection.active = false;\n connection.cancel?.();\n\n if ('state' in store) {\n (store as unknown as Cache<any>).state.set({\n status: 'error',\n error,\n isConnected: false,\n isUpdating: false,\n isStale: false,\n });\n }\n\n value = PromiseWithState.reject(error) as T;\n notify();\n });\n },\n updateIsConnected(isConnected) {\n if (isConnected) {\n whenConnected.resolve();\n }\n\n q(() => {\n if (!connection?.active) {\n return;\n }\n\n if ('state' in store) {\n (store as unknown as Cache<any>).state.set('isConnected', isConnected);\n }\n });\n },\n close() {\n if (connection?.active) {\n store.invalidate();\n }\n },\n };\n\n connection = { active: true };\n let _cancel: Cancel | undefined = createConnection(actions as any);\n\n connection.cancel = () => {\n _cancel?.();\n _cancel = undefined;\n };\n\n if (!connection.active) {\n connection.cancel();\n }\n\n return whenConnected;\n }\n\n try {\n value = store.getter({ signal: ac.signal, use, connect });\n } catch (error) {\n value = PromiseWithState.reject(error) as T;\n\n if (connection) {\n connection.active = false;\n connection.cancel?.();\n q.clear();\n }\n }\n\n if (isPromise(value)) {\n value.finally(() => whenExecuted.resolve()).catch(() => undefined);\n } else {\n whenExecuted.resolve();\n }\n\n function check() {\n if (store.options.cacheValue === false) {\n return false;\n }\n\n for (const dep of deps) {\n if (!deepEqual(dep.store.get(), dep.value)) {\n return false;\n }\n }\n return true;\n }\n\n function stop() {\n cancelEffect();\n whenExecuted.resolve();\n whenConnected.resolve();\n ac.abort();\n\n if (connection) {\n connection.active = false;\n connection.cancel?.();\n q.clear();\n }\n }\n\n function invalidateDependencies(recursive?: boolean) {\n for (const dep of deps) {\n dep.store.invalidate(recursive);\n }\n }\n\n return {\n get value() {\n return value!;\n },\n check,\n stop,\n invalidateDependencies,\n };\n}\n\nexport function staticValue<T>(value: T): CalculatedValue<T> {\n return {\n value,\n check: () => true,\n stop: () => undefined,\n invalidateDependencies: () => undefined,\n };\n}\n\nexport function staleValue<T>(value: T): CalculatedValue<T> {\n return {\n value,\n check: () => false,\n stop: () => undefined,\n invalidateDependencies: () => undefined,\n };\n}\n","import type { AnyPath } from './path';\nimport { get } from './propAccess';\n\nexport function makeSelector<T, S>(selector?: ((value: T) => S) | AnyPath): (value: T) => S {\n if (!selector) {\n return (x) => x as any;\n }\n\n if (selector instanceof Function) {\n return selector;\n }\n\n return (x) => get(x, selector as any) as any;\n}\n","import { calcDuration } from './calcDuration';\nimport type { Duration } from '@core';\n\nexport type DebounceOptions =\n | Duration\n | {\n wait: Duration;\n maxWait?: Duration;\n waitOnRunNow?: boolean;\n };\n\nexport function debounce<Args extends any[]>(\n action: (...args: Args) => void,\n options: Duration | DebounceOptions,\n): {\n (...args: Args): void;\n flush(): void;\n cancel(): void;\n isScheduled(): boolean;\n} {\n const wait =\n typeof options === 'object' && 'wait' in options\n ? calcDuration(options.wait)\n : calcDuration(options);\n\n const maxWait =\n typeof options === 'object' && 'maxWait' in options && options.maxWait !== undefined\n ? calcDuration(options.maxWait)\n : undefined;\n\n let run: (() => void) | undefined;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timeoutStarted: number | undefined;\n\n function flush() {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n run?.();\n }\n\n function cancel() {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n run = undefined;\n timeout = undefined;\n timeoutStarted = undefined;\n }\n\n function isScheduled() {\n return timeout !== undefined;\n }\n\n function debounce(...args: Args) {\n const now = Date.now();\n timeoutStarted ??= now;\n\n const deadline = Math.min(\n //\n now + wait,\n timeoutStarted + (maxWait ?? Number.POSITIVE_INFINITY),\n );\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n run = () => {\n run = undefined;\n timeout = undefined;\n timeoutStarted = undefined;\n\n action(...args);\n };\n\n timeout = setTimeout(run, deadline - now);\n }\n\n return Object.assign(debounce, { flush, cancel, isScheduled });\n}\n","import type { Cancel } from '@core';\nimport type { DisposableCancel } from '@core/commonTypes';\n\nexport default function disposable(dispose: Cancel): DisposableCancel {\n return Object.assign(\n dispose,\n Symbol.dispose ? { [Symbol.dispose]: dispose } : {},\n ) as DisposableCancel;\n}\n","export function forwardError(error: unknown): void {\n setTimeout(() => {\n throw error;\n });\n}\n","import { autobind } from '@lib/autobind';\n\nexport class PromiseCancelError extends Error {\n constructor() {\n super('cancelled');\n }\n}\n\nexport class PromiseWithCancel<T> extends Promise<T> {\n private abortController;\n\n constructor(\n executor: (\n resolve: (value: T) => void,\n reject: (error: unknown) => void,\n signal: AbortSignal,\n ) => void,\n ) {\n autobind(PromiseWithCancel);\n const abortController = new AbortController();\n\n super((resolve, reject) => {\n executor(resolve, reject, abortController.signal);\n\n abortController.signal.addEventListener('abort', () => {\n reject(abortController.signal.reason);\n });\n });\n\n this.abortController = abortController;\n }\n\n cancel(reason: any = new PromiseCancelError()): void {\n this.abortController.abort(reason);\n }\n}\n","import type { Store } from '../core/store';\nimport type { OptionalProperties, OptionalPropertyOf } from './typeHelpers';\n\ntype Function_ = (...args: any) => any;\n\nfunction createArrayAction<P extends keyof Array<any>>(prop: P) {\n return function arrayAction<T extends Array<any>>(\n this: Store<T>,\n ...args: T[P] extends Function_ ? Parameters<T[P]> : never\n ): T[P] extends Function_ ? ReturnType<T[P]> : never {\n const newArray = this.get().slice() as T;\n const result = (newArray[prop] as Function_)(...(args as any));\n this.set(newArray);\n return result;\n };\n}\nexport const arrayMethods: {\n [P in 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | 'reverse' | 'sort']: <\n T extends Array<any>,\n >(\n this: Store<T>,\n ...args: T[P] extends Function_ ? Parameters<T[P]> : never\n ) => T[P] extends Function_ ? ReturnType<T[P]> : never;\n} = {\n splice: /* @__PURE__ */ createArrayAction('splice'),\n push: /* @__PURE__ */ createArrayAction('push'),\n pop: /* @__PURE__ */ createArrayAction('pop'),\n shift: /* @__PURE__ */ createArrayAction('shift'),\n unshift: /* @__PURE__ */ createArrayAction('unshift'),\n reverse: /* @__PURE__ */ createArrayAction('reverse'),\n sort: /* @__PURE__ */ createArrayAction('sort'),\n};\n\nexport const recordMethods = {\n delete<T extends Record<any, any>, K extends OptionalPropertyOf<T>>(\n this: Store<T>,\n key: K,\n ): void {\n const copy = { ...this.get() };\n delete copy[key];\n this.set(copy);\n },\n\n clear<T extends Record<any, any>>(\n this: OptionalProperties<T> extends T ? Store<T> : never,\n ): void {\n this.set({} as T);\n },\n};\n\nexport const mapMethods = {\n delete<K, V>(this: Store<Map<K, V>>, key: K): boolean {\n const newMap = new Map(this.get());\n const result = newMap.delete(key);\n this.set(newMap);\n return result;\n },\n\n clear<K, V>(this: Store<Map<K, V>>): void {\n this.set(new Map());\n },\n};\n\nexport const setMethods = {\n add<T>(this: Store<Set<T>>, value: T): void {\n const newSet = new Set(this.get());\n newSet.add(value);\n this.set(newSet);\n },\n\n delete<T>(this: Store<Set<T>>, value: T): void {\n const newSet = new Set(this.get());\n newSet.delete(value);\n this.set(newSet);\n },\n\n clear<T>(this: Store<Set<T>>): void {\n this.set(new Set());\n },\n};\n","import { calcDuration } from './calcDuration';\nimport type { Duration } from '@core';\n\nexport function throttle<Args extends any[]>(\n action: (...args: Args) => void,\n duration: Duration,\n): (...args: Args) => void {\n const ms = calcDuration(duration);\n\n let t = 0;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: Args) => {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n const dt = t + ms - Date.now();\n if (dt <= 0) {\n action(...args);\n t = Date.now();\n return;\n }\n\n timeout = setTimeout(() => {\n action(...args);\n t = Date.now();\n }, dt);\n };\n}\n","import { autobind } from '@lib/autobind';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue, staticValue, type CalculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { debounce } from '@lib/debounce';\nimport disposable from '@lib/disposable';\nimport { deepEqual } from '@lib/equals';\nimport { forwardError } from '@lib/forwardError';\nimport { isObject } from '@lib/helpers';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { AnyPath, Path, SettablePath, Value } from '@lib/path';\nimport { PromiseWithCancel } from '@lib/promiseWithCancel';\nimport { get, set } from '@lib/propAccess';\nimport { arrayMethods, mapMethods, recordMethods, setMethods } from '@lib/standardMethods';\nimport { throttle } from '@lib/throttle';\nimport type {\n CalculationActions,\n Cancel,\n DisposableCancel,\n Duration,\n Effect,\n Listener,\n Selector,\n SubscribeOptions,\n Update,\n} from './commonTypes';\n\nexport type StoreMethods = Record<string, (...args: any[]) => any>;\n\nexport type BoundStoreMethods<T, Methods extends StoreMethods> = Methods &\n ThisType<Store<T> & Methods>;\n\nexport interface StoreOptions<T> {\n retain?: Duration;\n equals?: SubscribeOptions['equals'];\n effect?: Effect<Store<T>> | { effect: Effect<Store<T>>; retain?: Duration };\n cacheValue?: boolean;\n}\n\nexport interface StoreOptionsWithMethods<T, Methods extends StoreMethods> extends StoreOptions<T> {\n methods?: Methods & ThisType<Store<T> & Methods & StandardMethods<T>>;\n}\n\nexport type Calculate<T> = (helpers: CalculationActions<T>) => T;\n\ntype StandardMethods<T> =\n T extends Map<any, any>\n ? typeof mapMethods\n : T extends Set<any>\n ? typeof setMethods\n : T extends Array<any>\n ? typeof arrayMethods\n : T extends Record<any, any>\n ? typeof recordMethods\n : Record<string, never>;\n\ntype StoreWithMethods<T, Methods extends StoreMethods> = Store<T> &\n Omit<BoundStoreMethods<T, Methods>, keyof Store<T>> &\n StandardMethods<T>;\n\nexport interface OnceOptions {\n signal?: AbortSignal;\n timeout?: Duration;\n}\n\nfunction noop() {\n return undefined;\n}\n\nexport class Store<T> {\n private static hooks?: Set<(this: Store<any>, store: Store<any>) => void>;\n\n static addHook(hook: (store: Store<any>) => void): DisposableCancel {\n this.hooks ??= new Set();\n this.hooks.add(hook);\n return disposable(() => this.hooks?.delete(hook));\n }\n\n version?: string;\n\n protected calculatedValue?: CalculatedValue<T>;\n protected defaultValue?: CalculatedValue<T>;\n\n protected listeners: Map<Listener, boolean> = new Map();\n\n protected effects: Map<\n Effect<Store<T>>,\n { handle?: Cancel; retain?: number; timeout?: ReturnType<typeof setTimeout> }\n > = new Map();\n\n protected notifyId = {};\n\n constructor(\n public readonly getter: T | Calculate<T>,\n public readonly options: StoreOptions<T> = {},\n public readonly derivedFrom?: {\n store: Store<any>;\n selectors: (Selector<any, any> | AnyPath)[];\n updater: (state: any) => void;\n },\n ) {\n autobind(Store);\n\n if (typeof getter !== 'function') {\n this.calculatedValue = this.defaultValue = staticValue(getter);\n }\n\n for (const hook of Store.hooks ?? []) {\n hook.apply(this, [this]);\n }\n\n if (options.effect instanceof Function) {\n this.addEffect(options.effect);\n } else if (options.effect) {\n this.addEffect(options.effect.effect, options.effect.retain);\n }\n }\n\n get(): T {\n if (!this.calculatedValue?.check()) {\n this.calculatedValue?.stop();\n this.calculatedValue = undefined;\n }\n\n if (!this.calculatedValue) {\n this.calculatedValue = calculatedValue(this, this.notify);\n }\n\n return this.calculatedValue.value;\n }\n\n set(update: Update<T>): void;\n\n set<const P>(path: Constrain<P, Path<T>>, update: Update<Value<T, P>>): void;\n\n set(...args: any[]): void {\n const path: any = args.length > 1 ? args[0] : [];\n let update: Update<any> = args.length > 1 ? args[1] : args[0];\n\n if (update instanceof Function) {\n const before = this.get();\n const valueBefore = get(before, path);\n const valueAfter = update(valueBefore);\n update = set(before, path, valueAfter);\n } else if (path.length > 0) {\n update = set(this.get(), path, update);\n }\n\n if (this.derivedFrom) {\n this.derivedFrom.updater(update);\n return;\n }\n\n this.calculatedValue?.stop();\n this.calculatedValue = staticValue(update);\n this.notify();\n }\n\n invalidate(recursive?: boolean): void {\n if (recursive) {\n this.calculatedValue?.invalidateDependencies(recursive);\n }\n\n this.calculatedValue?.stop();\n this.calculatedValue = this.defaultValue;\n this.notify();\n }\n\n subscribe(\n listener: Listener<T, { cancel: Cancel }>,\n options?: SubscribeOptions,\n ): DisposableCancel {\n const {\n passive,\n runNow = true,\n throttle: throttleOption,\n debounce: debounceOption,\n equals = this.options.equals ?? deepEqual,\n } = options ?? {};\n\n let isSetup = false;\n let previousValue: { value: T } | undefined;\n\n let innerListener = () => {\n if (!isSetup) {\n return;\n }\n\n const value = passive ? this.calculatedValue : { value: this.get() };\n\n if (!value) {\n return;\n }\n\n if (previousValue && equals(value.value, previousValue.value)) {\n return;\n }\n\n const _previousValue = previousValue?.value;\n previousValue = this.calculatedValue && { value: this.calculatedValue?.value };\n\n try {\n listener.apply({ cancel }, [value.value, _previousValue]);\n } catch (error) {\n forwardError(error);\n }\n };\n\n if (throttleOption) {\n innerListener = throttle(innerListener, throttleOption);\n } else if (debounceOption) {\n innerListener = debounce(innerListener, debounceOption);\n }\n\n this.listeners.set(innerListener, !passive);\n const cancel = () => {\n if (this.listeners.delete(innerListener) && !passive) {\n this.onUnsubscribe();\n }\n };\n\n if (!passive) {\n this.onSubscribe();\n }\n\n isSetup = true;\n\n if (runNow) {\n innerListener();\n\n if (\n !throttleOption &&\n typeof debounceOption === 'object' &&\n 'waitOnRunNow' in debounceOption &&\n debounceOption.waitOnRunNow === false &&\n 'flush' in innerListener\n ) {\n (innerListener as { flush: () => void }).flush();\n }\n } else {\n previousValue = passive\n ? this.calculatedValue && { value: this.calculatedValue.value }\n : { value: this.get() };\n }\n\n return disposable(cancel);\n }\n\n once<S extends T>(\n condition: (value: T) => value is S,\n options?: OnceOptions,\n ): PromiseWithCancel<S>;\n\n once(condition: (value: T) => boolean, options?: OnceOptions): PromiseWithCancel<T>;\n\n once(options?: OnceOptions): PromiseWithCancel<T>;\n\n once(\n ...args: [condition: (value: any) => boolean, options?: OnceOptions] | [options?: OnceOptions]\n ): PromiseWithCancel<any> {\n const condition = args[0] instanceof Function ? args[0] : Boolean;\n const options = args[0] instanceof Function ? args[1] : args[0];\n\n return new PromiseWithCancel<T>((resolve, reject, signal) => {\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const cancel = this.subscribe(\n (value) => {\n if (stopped || !condition(value)) {\n return;\n }\n\n resolve(value);\n stopped = true;\n if (timer) {\n clearTimeout(timer);\n }\n setTimeout(() => cancel());\n },\n {\n runNow: !!condition,\n },\n );\n\n if (stopped) {\n return;\n }\n\n signal.addEventListener('abort', cancel);\n\n options?.signal?.addEventListener('abort', () => {\n cancel();\n reject(options.signal?.reason ?? new Error('cancelled'));\n });\n\n if (options?.timeout !== undefined) {\n timer = setTimeout(() => {\n cancel();\n reject(new Error('timeout'));\n }, calcDuration(options.timeout));\n }\n });\n }\n\n map<S>(selector: Selector<T, S>, updater?: (value: S) => Update<T>): Store<S>;\n\n map<const P>(selector: Constrain<P, SettablePath<T>>): Store<Value<T, P>>;\n\n map(_selector: Selector<T, any> | SettablePath<any>, ...args: any[]): Store<any> {\n const updater: ((value: any) => Update<T>) | undefined =\n _selector instanceof Function\n ? args[0]\n : (value) => (state) => set(state, _selector as any, value);\n\n const selector = makeSelector(_selector);\n\n const derivedFrom = {\n store: this.derivedFrom ? this.derivedFrom.store : this,\n selectors: this.derivedFrom ? [...this.derivedFrom.selectors, _selector] : [_selector],\n\n updater: (value: any) => {\n if (!updater) {\n throw new TypeError(\n 'Can only update computed stores that either are derived from other stores using string selectors or have an updater function.',\n );\n }\n\n let update = updater(value);\n\n if (update instanceof Function) {\n update = update(this.get());\n }\n\n if (this.derivedFrom) {\n this.derivedFrom.updater(update);\n } else {\n this.set(update);\n }\n },\n };\n\n return new Store(\n ({ use }) => {\n return selector(use(this));\n },\n undefined,\n derivedFrom,\n );\n }\n\n /** Add an effect that will be executed when the store becomes active, which means when it has at least one subscriber.\n * @param effect\n * If there is already a subscriber, the effect will be executed immediately.\n * Otherweise it will be executed as soon as the first subscription is created.\n * Every time all subscriptions are removed and the first is created again, the effect will be executed again.\n * @param retain\n * If provided, delay tearing down effects when the last subscriber is removed. This is useful if a short gap in subscriber coverage is supposed to be ignored. E.g. when switching pages, the old page might unsubscribe, while the new page subscribes immediately after.\n * @returns\n * The effect can return a teardown callback, which will be executed when the last subscription is removed and potentially the ratain time has passed.\n */\n addEffect(\n effect: Effect<Store<T>>,\n retain: Duration | undefined = this.options.retain,\n ): DisposableCancel {\n this.effects.set(effect, {\n handle: this.isActive() ? (effect.apply(this, [this]) ?? noop) : undefined,\n retain: retain !== undefined ? calcDuration(retain) : undefined,\n });\n\n return disposable(() => {\n const { handle, timeout } = this.effects.get(effect) ?? {};\n handle?.();\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.delete(effect);\n });\n }\n\n /** Return whether the store is currently active, which means whether it has at least one subscriber. */\n isActive(): boolean {\n return [...this.listeners.values()].some(Boolean);\n }\n\n protected onSubscribe(): void {\n if ([...this.listeners.values()].filter(Boolean).length > 1) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.set(effect, {\n handle: handle ?? effect.apply(this, [this]) ?? noop,\n retain,\n timeout: undefined,\n });\n }\n }\n\n protected onUnsubscribe(): void {\n if ([...this.listeners.values()].some(Boolean)) return;\n\n for (const [effect, { handle, retain, timeout }] of this.effects.entries()) {\n if (!retain) {\n handle?.();\n\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n\n this.effects.set(effect, {\n handle: undefined,\n retain,\n timeout: undefined,\n });\n\n continue;\n }\n\n const newTimeout =\n timeout ??\n (handle\n ? setTimeout(() => {\n handle();\n this.effects.set(effect, {\n handle: undefined,\n retain,\n timeout: undefined,\n });\n }, retain)\n : undefined);\n\n this.effects.set(effect, {\n handle,\n retain,\n timeout: newTimeout,\n });\n }\n }\n\n protected notify(): void {\n const n = {};\n this.notifyId = n;\n\n const snapshot = [...this.listeners.entries()];\n const active = snapshot.filter(([, active]) => active);\n const passive = snapshot.filter(([, active]) => !active);\n for (const [listener] of [...active, ...passive]) {\n listener();\n if (n !== this.notifyId) break;\n }\n }\n}\n\nfunction create<T>(calculate: Calculate<T>, options?: StoreOptions<T>): Store<T>;\nfunction create<T, Methods extends StoreMethods = {}>(\n initialState: T,\n options?: StoreOptionsWithMethods<T, Methods>,\n): StoreWithMethods<T, Methods>;\nfunction create<T, Methods extends StoreMethods>(\n initialState: T | Calculate<T>,\n options?: StoreOptionsWithMethods<T, Methods>,\n): StoreWithMethods<T, Methods> | Store<T> {\n options = { ...createStore.defaultOptions, ...options };\n\n const store = new Store(initialState, options);\n\n if (initialState instanceof Function) {\n return store;\n }\n\n let methods: StoreMethods | undefined = options?.methods;\n\n if (initialState instanceof Map) {\n methods = { ...mapMethods, ...methods };\n } else if (initialState instanceof Set) {\n methods = { ...setMethods, ...methods };\n } else if (Array.isArray(initialState)) {\n methods = { ...arrayMethods, ...methods };\n } else if (isObject(initialState)) {\n methods = { ...recordMethods, ...methods };\n }\n\n const boundMethods = Object.fromEntries(\n Object.entries(methods ?? ({} as BoundStoreMethods<T, any>))\n .filter(([name]) => !(name in store))\n .map(([name, action]) => [name, (action as any).bind(store)]),\n ) as BoundStoreMethods<T, any>;\n\n return Object.assign(store, boundMethods);\n}\n\nexport const createStore: typeof create & { defaultOptions: StoreOptions<any> } =\n /* @__P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;;MAEV,UACH;AAEN,QAAK,QAAQ,IAAI,QAAQ;IACvB;IACA;IACA,SAAS;;;;CAKf,AAAU,SAAe;EACvB,MAAM,IAAI;AACV,OAAK,WAAW;EAEhB,MAAM,WAAW,CAAC,GAAG,KAAK,UAAU;EACpC,MAAM,SAAS,SAAS,QAAQ,GAAGK,cAAYA;EAC/C,MAAM,UAAU,SAAS,QAAQ,GAAGA,cAAY,CAACA;AACjD,OAAK,MAAM,CAAC,aAAa,CAAC,GAAG,QAAQ,GAAG,UAAU;AAChD;AACA,OAAI,MAAM,KAAK,SAAU;;;;AAU/B,SAAS,OACP,cACA,SACyC;AACzC,WAAU;EAAE,GAAG,YAAY;EAAgB,GAAG;;CAE9C,MAAM,QAAQ,IAAI,MAAM,cAAc;AAEtC,KAAI,wBAAwB,SAC1B,QAAO;CAGT,IAAIC,UAAoC,SAAS;AAEjD,KAAI,wBAAwB,IAC1B,WAAU;EAAE,GAAG;EAAY,GAAG;;UACrB,wBAAwB,IACjC,WAAU;EAAE,GAAG;EAAY,GAAG;;UACrB,MAAM,QAAQ,cACvB,WAAU;EAAE,GAAG;EAAc,GAAG;;UACvBC,4BAAS,cAClB,WAAU;EAAE,GAAG;EAAe,GAAG;;CAGnC,MAAM,eAAe,OAAO,YAC1B,OAAO,QAAQ,WAAY,IACxB,QAAQ,CAAC,UAAU,EAAE,QAAQ,QAC7B,KAAK,CAAC,MAAM,YAAY,CAAC,MAAO,OAAe,KAAK;AAGzD,QAAO,OAAO,OAAO,OAAO;;AAG9B,MAAaC,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB,EACd,QAAQP"}
@@ -1,4 +1,4 @@
1
- import { createStore, makeSelector } from "./store-BpMJxIHt.js";
1
+ import { createStore, makeSelector } from "./store-DOEc60aP.js";
2
2
  import { deepEqual, isPlainObject } from "./propAccess-B260LXN1.js";
3
3
  import { simpleHash } from "./hash-DNFM5y_h.js";
4
4
  import { createContext, useCallback, useContext, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef } from "react";
@@ -312,4 +312,4 @@ const storeMethods = {
312
312
 
313
313
  //#endregion
314
314
  export { LoadingBoundary, ScopeProvider, cacheMethods, scopeMethods, storeMethods, useCache, useLoadingBoundary, useProp, useScope, useStore };
315
- //# sourceMappingURL=storeMethods-CkvcMFoL.js.map
315
+ //# sourceMappingURL=storeMethods-C7bswcgj.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storeMethods-CkvcMFoL.js","names":["equals","selector","value","_listener: (value: any) => void","lastObservedValue: any","revoke: (() => void) | undefined","rootCache: Cache<any, any>","selector","scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n}","storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n}"],"sources":["../src/lib/trackingProxy.ts","../src/react/useStore.ts","../src/react/loadingBoundary.tsx","../src/react/useCache.ts","../src/react/cacheMethods.ts","../src/react/useProp.ts","../src/react/scope.tsx","../src/react/scopeMethods.ts","../src/react/storeMethods.ts"],"sourcesContent":["import { isPlainObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\n\nconst unwrapProxySymbol = /* @__PURE__ */ Symbol('unwrapProxy');\n\nexport type TrackingProxy<T> = [value: T, equals: (newValue: T) => boolean, revoke?: () => void];\ntype Object_ = Record<string | symbol, unknown>;\n\nexport function trackingProxy<T>(\n value: T,\n equals: (a: any, b: any) => boolean = deepEqual,\n): TrackingProxy<T> {\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [value, (other) => equals(value, other)];\n }\n\n // Unpack proxies, we don't want to nest them\n value = (value as any)[unwrapProxySymbol] ?? value;\n\n const deps = new Array<TrackingProxy<any>[1]>();\n const revokations = new Array<() => void>();\n let revoked = false;\n\n function trackComplexProp(function_: any, ...args: any[]) {\n const [proxiedValue, equals, revoke] = trackingProxy(function_(value, ...args));\n\n deps.push((otherValue) => {\n if (!isPlainObject(otherValue) && !Array.isArray(otherValue)) {\n return false;\n }\n\n return equals(function_(otherValue, ...args));\n });\n\n if (revoke) {\n revokations.push(revoke);\n }\n\n return proxiedValue;\n }\n\n function trackSimpleProp(function_: any, ...args: any[]) {\n const calculatedValue = function_(value, ...args);\n\n deps.push((otherValue) => {\n return function_(otherValue, ...args) === calculatedValue;\n });\n\n return calculatedValue;\n }\n\n const proxy = new Proxy(value as T & Object_, {\n get(target, p, receiver) {\n if (p === unwrapProxySymbol) {\n return value;\n }\n\n if (revoked) {\n return target[p];\n }\n\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return target[p];\n }\n\n return trackComplexProp(Reflect.get, p, receiver);\n },\n\n getOwnPropertyDescriptor(target, p) {\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return Reflect.getOwnPropertyDescriptor(target, p);\n }\n\n return trackComplexProp(Reflect.getOwnPropertyDescriptor, p);\n },\n\n ownKeys() {\n return trackComplexProp(Reflect.ownKeys);\n },\n\n getPrototypeOf() {\n return trackSimpleProp(Reflect.getPrototypeOf);\n },\n\n has(_target, p) {\n return trackSimpleProp(Reflect.has, p);\n },\n\n isExtensible() {\n return trackSimpleProp(Reflect.isExtensible);\n },\n });\n\n return [\n proxy,\n (other) => !!other && deps.every((equals) => equals(other)),\n () => {\n revoked = true;\n revokations.forEach((revoke) => revoke());\n },\n ];\n}\n","import type { Selector, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { simpleHash } from '@lib/hash';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type Path, type Value } from '@lib/path';\nimport { trackingProxy } from '@lib/trackingProxy';\nimport { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js';\n\nexport interface UseStoreOptions<S> extends Omit<SubscribeOptions, 'runNow' | 'passive'> {\n /**\n * If true, the cache content can be consumed but no fetch will be triggered.\n * @default false\n */\n passive?: boolean;\n\n disableTrackingProxy?: boolean;\n\n withViewTransition?: boolean | ((value: S) => unknown);\n}\n\nexport function useStore<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useStore<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useStore<T>(store: Store<T>, option?: UseStoreOptions<T>): T;\n\nexport function useStore<T, S>(store: Store<T>, argument1?: any, argument2?: any): S {\n const selector = makeSelector<T, S>(\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined,\n );\n\n const allOptions = (\n typeof argument1 === 'object' ? argument1 : (argument2 ?? {})\n ) as UseStoreOptions<S>;\n\n const lastEqualsRef = useRef<(newValue: S) => boolean | undefined>(undefined);\n\n if (store.derivedFrom) {\n return useStore(\n store.derivedFrom.store,\n (value) => {\n for (const selector of store.derivedFrom!.selectors) {\n value = makeSelector(selector)(value);\n }\n return selector(value);\n },\n allOptions,\n );\n }\n\n const {\n disableTrackingProxy = true,\n equals = store.options.equals ?? deepEqual,\n withViewTransition,\n ...options\n } = allOptions;\n\n const subOptions = { ...options, runNow: false };\n const subscribe = useCallback(\n (listener: () => void) => {\n let _listener: (value: any) => void = listener;\n let stopped = false;\n\n if (withViewTransition && (document as any).startViewTransition) {\n let lastObservedValue: any;\n\n _listener = (value: any) => {\n const observedValue =\n withViewTransition instanceof Function ? withViewTransition(value) : value;\n\n if (equals(lastObservedValue, observedValue)) {\n listener();\n return;\n }\n\n lastObservedValue = observedValue;\n\n let hasChanges = false;\n const mutationObserver = new MutationObserver(() => {\n hasChanges = true;\n mutationObserver.disconnect();\n });\n mutationObserver.observe(document.body, { childList: true, subtree: true });\n\n (document as any).startViewTransition(() => {\n mutationObserver.disconnect();\n\n if (!stopped) {\n listener();\n }\n\n if (!hasChanges) {\n throw new Error('no change');\n }\n });\n };\n }\n\n const cancel = store.subscribe(_listener, subOptions);\n return () => {\n stopped = true;\n cancel();\n };\n },\n [store, simpleHash(subOptions)],\n );\n\n let value = useSyncExternalStoreWithSelector<T, S>(\n //\n subscribe,\n store.get,\n undefined,\n (x) => selector(x),\n (_v, newValue) => lastEqualsRef.current?.(newValue) ?? false,\n );\n let lastEquals = (newValue: S) => equals(newValue, value);\n let revoke: (() => void) | undefined;\n\n if (!disableTrackingProxy) {\n [value, lastEquals, revoke] = trackingProxy(value, equals);\n }\n\n useLayoutEffect(() => {\n lastEqualsRef.current = lastEquals;\n revoke?.();\n });\n\n useDebugValue(value);\n return value;\n}\n","import { createStore } from '@core';\nimport { useStore } from '@react/useStore';\nimport { createContext, useContext, useLayoutEffect, useMemo, type ReactNode } from 'react';\n\nexport interface LoadingBoundaryEntry {\n label?: ReactNode;\n}\n\nexport interface LoadingBoundaryProps {\n /**\n * Fallback node to render when there are loading components within the boundary.\n */\n fallback?: ReactNode | ((entries: LoadingBoundaryEntry[]) => ReactNode);\n\n /**\n * Child node to render when there are no loading components within the boundary.\n */\n children?: ReactNode;\n\n /**\n * Add a loading state from outside the boundary. Useful for when you want to\n * show a loading state for a component that is not a child of the boundary.\n */\n isLoading?: boolean;\n}\n\nconst LoadingBoundaryContext = createContext(createStore(new Set<LoadingBoundaryEntry>()));\n\nexport function LoadingBoundary({\n fallback,\n children,\n isLoading: isLoadingExternal,\n}: LoadingBoundaryProps): React.JSX.Element {\n const store = useMemo(() => createStore(new Set<LoadingBoundaryEntry>()), []);\n const entries = useStore(store);\n const isLoading = entries.size > 0 || isLoadingExternal;\n\n const fallbackNode = isLoading\n ? typeof fallback === 'function'\n ? fallback([...entries])\n : fallback\n : undefined;\n\n return (\n <LoadingBoundaryContext.Provider value={store}>\n {fallbackNode !== undefined ? (\n <>\n {fallbackNode}\n <div style={{ display: 'none' }}>{children}</div>\n </>\n ) : (\n children\n )}\n </LoadingBoundaryContext.Provider>\n );\n}\n\nexport function useLoadingBoundary(isLoading: boolean | undefined, label?: ReactNode): void {\n const store = useContext(LoadingBoundaryContext);\n\n useLayoutEffect(() => {\n if (!isLoading) {\n return;\n }\n\n const entry = { label };\n store.set((entries) => new Set(entries).add(entry));\n\n return () => {\n store.set((entries) => {\n const newEntries = new Set(entries);\n newEntries.delete(entry);\n return newEntries;\n });\n };\n }, [isLoading]);\n}\n","import type { Cache } from '@core';\nimport type { CacheState } from '@lib/cacheState';\nimport { makeSelector } from '@lib/makeSelector';\nimport { useLoadingBoundary } from '@react/loadingBoundary';\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type UseCacheArray<T> = [\n value: T | undefined,\n error: unknown | undefined,\n isUpdating: boolean,\n isStale: boolean,\n];\n\nexport type UseCacheValue<T> = UseCacheArray<T> & CacheState<T>;\n\nexport interface UseCacheOptions<T> extends UseStoreOptions<UseCacheArray<T> & CacheState<T>> {\n /**\n * If true, will always return undefined as value and no fetch will be triggered.\n * @default false\n */\n disabled?: boolean;\n\n /**\n * If true, the cache will be invalidated when the component mounts.\n * @default false\n */\n updateOnMount?: boolean;\n\n /**\n * If true, `useCache` will throw a promise when the cache is pending. This can be used with React Suspense.\n * @see https://react.dev/reference/react/Suspense\n * @default false\n */\n suspense?: boolean;\n\n /**\n * If true, `useCache` will register its loading state with the nearest `LoadingBoundary`.\n * @default false\n */\n loadingBoundary?: boolean;\n}\n\nexport function useCache<T>(\n cache: Cache<T, any>,\n {\n passive,\n disabled,\n updateOnMount,\n withViewTransition,\n suspense,\n loadingBoundary,\n ...options\n }: UseCacheOptions<T> = {},\n): UseCacheValue<T> {\n if (withViewTransition === true) {\n withViewTransition = (state) => state.value;\n }\n\n const { rootCache, selector } = useMemo(() => {\n const rootCache: Cache<any, any> = cache.derivedFromCache?.cache ?? cache;\n let selector = (x: any) => x;\n\n if (cache.derivedFromCache) {\n selector = (value: any) => {\n for (const s of cache.derivedFromCache!.selectors) {\n value = makeSelector(s)(value);\n }\n return value;\n };\n }\n\n return { rootCache, selector };\n }, [cache]);\n\n const hasMounted = useRef(false);\n\n useEffect(() => {\n hasMounted.current = true;\n\n if (updateOnMount) {\n rootCache.invalidate();\n }\n }, []);\n\n const result = useStore(\n rootCache.state,\n (state) => {\n if (disabled) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, undefined, false, false],\n { status: 'pending', isUpdating: false, isStale: false, isConnected: false },\n );\n }\n\n const isStale = updateOnMount && !hasMounted.current ? true : state.isStale;\n try {\n const value = state.status === 'value' ? selector(state.value) : undefined;\n\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [value, state.error, state.isUpdating, isStale],\n { ...state, value, isStale },\n );\n } catch (error) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, error, state.isUpdating, isStale],\n {\n status: 'error',\n error,\n isUpdating: state.isUpdating,\n isStale: isStale,\n isConnected: state.isConnected,\n },\n );\n }\n },\n { ...options, withViewTransition, passive: passive || disabled },\n );\n\n useEffect(\n () => rootCache.subscribe(() => undefined, { passive: passive || disabled }),\n [rootCache, passive || disabled],\n );\n\n useLoadingBoundary(loadingBoundary && !disabled && result.status === 'pending');\n\n if (suspense && result.status === 'pending') {\n throw rootCache.get();\n }\n\n return result;\n}\n","import type { Cache } from '@core';\nimport { type UseCacheOptions, type UseCacheValue, useCache } from '@react/useCache';\n\nexport const cacheMethods = {\n useCache<T>(this: Cache<T, any>, options?: UseCacheOptions<T>): UseCacheValue<T> {\n return useCache(this, options);\n },\n};\n","import { type Selector, type Update } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { type Path, type Value } from '@lib/path';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport function useProp<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useProp<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useProp<T>(\n store: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useProp<T, S>(\n store: Store<T>,\n argument1?: any,\n argument2?: any,\n argument3?: any,\n): [value: S, setValue: Store<S>['set']] {\n const selector =\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined;\n const updater = typeof argument2 === 'function' ? argument2 : undefined;\n const options =\n typeof argument1 === 'object'\n ? argument1\n : typeof argument2 === 'object'\n ? argument2\n : argument3;\n\n if (selector) {\n store = store.map(selector, updater);\n }\n\n const value = useStore(store, options) as S;\n return [value, store.set as Store<S>['set']];\n}\n","import type { Scope, Selector, Update } from '@core';\nimport { createStore, type Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { createContext, useContext, useMemo, type Context, type ReactNode } from 'react';\nimport { useProp } from './useProp';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type ScopeProps<T> = { scope: Scope<T>; store?: Store<T>; children?: ReactNode };\n\ndeclare module '..' {\n interface Scope<T> {\n context?: Context<Store<T>>;\n }\n}\n\nfunction getScopeContext<T>(scope: Scope<T>): Context<Store<T>> {\n scope.context ??= createContext<Store<T>>(createStore(scope.defaultValue));\n return scope.context;\n}\n\nexport function ScopeProvider<T>({\n scope,\n store: inputStore,\n children,\n}: ScopeProps<T>): React.JSX.Element {\n const context = getScopeContext(scope);\n const currentStore = useMemo(\n () => inputStore ?? createStore(scope.defaultValue),\n [scope, inputStore],\n );\n\n return <context.Provider value={currentStore}>{children}</context.Provider>;\n}\n\nexport function useScope<T>(scope: Scope<T>): Store<T> {\n const context = getScopeContext(scope);\n return useContext(context);\n}\n\nexport function useScopeStore<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useScopeStore<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useScopeStore<T>(scope: Scope<T>, option?: UseStoreOptions<T>): T;\n\nexport function useScopeStore<T>(scope: Scope<T>, ...args: any[]): T {\n const store = useScope(scope);\n return useStore(store, ...args);\n}\n\nexport function useScopeProp<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useScopeProp<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n ...args: any[]\n): [value: T, setValue: Store<T>['set']] {\n const store = useScope(scope);\n return useProp(store, ...args);\n}\n","import type { Scope, Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport {\n ScopeProvider,\n useScope,\n useScopeProp,\n useScopeStore,\n type ScopeProps,\n} from '@react/scope';\nimport type { UseStoreOptions } from '@react/useStore';\n\nfunction boundUseScope<T>(this: Scope<T>): Store<T> {\n return useScope(this);\n}\n\nfunction boundUseScopeStore<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nfunction boundUseScopeStore<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nfunction boundUseScopeStore<T>(this: Scope<T>, option?: UseStoreOptions<T>): T;\n\nfunction boundUseScopeStore(this: Scope<any>, ...args: any[]) {\n return useScopeStore(this, ...args);\n}\n\nfunction boundUseScopeProp<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nfunction boundUseScopeProp<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nfunction boundUseScopeProp<T>(\n this: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nfunction boundUseScopeProp(this: Scope<any>, ...args: any[]) {\n return useScopeProp(this, ...args);\n}\n\nfunction Provider<T>(this: Scope<T>, props: Omit<ScopeProps<T>, 'scope'>): React.JSX.Element {\n return ScopeProvider({ ...props, scope: this });\n}\n\nexport const scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n} = {\n useScope: boundUseScope,\n useStore: boundUseScopeStore,\n useProp: boundUseScopeProp,\n Provider,\n};\n","import type { Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { useProp } from '@react/useProp';\nimport { type UseStoreOptions, useStore } from '@react/useStore';\n\nfunction boundUseStore<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\nfunction boundUseStore<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\nfunction boundUseStore<T>(this: Store<T>, option?: UseStoreOptions<T>): T;\nfunction boundUseStore(this: Store<any>, ...args: any[]) {\n return useStore(this, ...args);\n}\n\nfunction boundUseProp<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\nfunction boundUseProp<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\nfunction boundUseProp<T>(\n this: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\nfunction boundUseProp(this: Store<any>, ...args: any[]) {\n return useProp(this, ...args);\n}\n\nexport const storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n} = {\n useStore: boundUseStore,\n useProp: boundUseProp,\n};\n"],"mappings":";;;;;;;;AAGA,MAAM,oBAAoC,uBAAO;AAKjD,SAAgB,cACd,OACA,SAAsC,WACpB;AAClB,KAAI,CAAC,cAAc,UAAU,CAAC,MAAM,QAAQ,OAC1C,QAAO,CAAC,QAAQ,UAAU,OAAO,OAAO;AAI1C,SAAS,MAAc,sBAAsB;CAE7C,MAAM,OAAO,IAAI;CACjB,MAAM,cAAc,IAAI;CACxB,IAAI,UAAU;CAEd,SAAS,iBAAiB,WAAgB,GAAG,MAAa;EACxD,MAAM,CAAC,cAAcA,UAAQ,UAAU,cAAc,UAAU,OAAO,GAAG;AAEzE,OAAK,MAAM,eAAe;AACxB,OAAI,CAAC,cAAc,eAAe,CAAC,MAAM,QAAQ,YAC/C,QAAO;AAGT,UAAOA,SAAO,UAAU,YAAY,GAAG;;AAGzC,MAAI,OACF,aAAY,KAAK;AAGnB,SAAO;;CAGT,SAAS,gBAAgB,WAAgB,GAAG,MAAa;EACvD,MAAM,kBAAkB,UAAU,OAAO,GAAG;AAE5C,OAAK,MAAM,eAAe;AACxB,UAAO,UAAU,YAAY,GAAG,UAAU;;AAG5C,SAAO;;CAGT,MAAM,QAAQ,IAAI,MAAM,OAAsB;EAC5C,IAAI,QAAQ,GAAG,UAAU;AACvB,OAAI,MAAM,kBACR,QAAO;AAGT,OAAI,QACF,QAAO,OAAO;GAGhB,MAAM,EAAE,UAAU,iBAAiB,OAAO,yBAAyB,QAAQ,MAAM;AACjF,OAAI,aAAa,SAAS,iBAAiB,MACzC,QAAO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,cAAc;EAAE,GAAG;EAAO,OAAO;;;AAG1C,MAAaC,eAKT;CACF,UAAU;CACV,UAAU;CACV,SAAS;CACT;;;;;ACpDF,SAAS,cAAgC,GAAG,MAAa;AACvD,QAAO,SAAS,MAAM,GAAG;;AAkB3B,SAAS,aAA+B,GAAG,MAAa;AACtD,QAAO,QAAQ,MAAM,GAAG;;AAG1B,MAAaC,eAGT;CACF,UAAU;CACV,SAAS"}
1
+ {"version":3,"file":"storeMethods-C7bswcgj.js","names":["equals","selector","value","_listener: (value: any) => void","lastObservedValue: any","revoke: (() => void) | undefined","rootCache: Cache<any, any>","selector","scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n}","storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n}"],"sources":["../src/lib/trackingProxy.ts","../src/react/useStore.ts","../src/react/loadingBoundary.tsx","../src/react/useCache.ts","../src/react/cacheMethods.ts","../src/react/useProp.ts","../src/react/scope.tsx","../src/react/scopeMethods.ts","../src/react/storeMethods.ts"],"sourcesContent":["import { isPlainObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\n\nconst unwrapProxySymbol = /* @__PURE__ */ Symbol('unwrapProxy');\n\nexport type TrackingProxy<T> = [value: T, equals: (newValue: T) => boolean, revoke?: () => void];\ntype Object_ = Record<string | symbol, unknown>;\n\nexport function trackingProxy<T>(\n value: T,\n equals: (a: any, b: any) => boolean = deepEqual,\n): TrackingProxy<T> {\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [value, (other) => equals(value, other)];\n }\n\n // Unpack proxies, we don't want to nest them\n value = (value as any)[unwrapProxySymbol] ?? value;\n\n const deps = new Array<TrackingProxy<any>[1]>();\n const revokations = new Array<() => void>();\n let revoked = false;\n\n function trackComplexProp(function_: any, ...args: any[]) {\n const [proxiedValue, equals, revoke] = trackingProxy(function_(value, ...args));\n\n deps.push((otherValue) => {\n if (!isPlainObject(otherValue) && !Array.isArray(otherValue)) {\n return false;\n }\n\n return equals(function_(otherValue, ...args));\n });\n\n if (revoke) {\n revokations.push(revoke);\n }\n\n return proxiedValue;\n }\n\n function trackSimpleProp(function_: any, ...args: any[]) {\n const calculatedValue = function_(value, ...args);\n\n deps.push((otherValue) => {\n return function_(otherValue, ...args) === calculatedValue;\n });\n\n return calculatedValue;\n }\n\n const proxy = new Proxy(value as T & Object_, {\n get(target, p, receiver) {\n if (p === unwrapProxySymbol) {\n return value;\n }\n\n if (revoked) {\n return target[p];\n }\n\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return target[p];\n }\n\n return trackComplexProp(Reflect.get, p, receiver);\n },\n\n getOwnPropertyDescriptor(target, p) {\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return Reflect.getOwnPropertyDescriptor(target, p);\n }\n\n return trackComplexProp(Reflect.getOwnPropertyDescriptor, p);\n },\n\n ownKeys() {\n return trackComplexProp(Reflect.ownKeys);\n },\n\n getPrototypeOf() {\n return trackSimpleProp(Reflect.getPrototypeOf);\n },\n\n has(_target, p) {\n return trackSimpleProp(Reflect.has, p);\n },\n\n isExtensible() {\n return trackSimpleProp(Reflect.isExtensible);\n },\n });\n\n return [\n proxy,\n (other) => !!other && deps.every((equals) => equals(other)),\n () => {\n revoked = true;\n revokations.forEach((revoke) => revoke());\n },\n ];\n}\n","import type { Selector, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { simpleHash } from '@lib/hash';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type Path, type Value } from '@lib/path';\nimport { trackingProxy } from '@lib/trackingProxy';\nimport { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js';\n\nexport interface UseStoreOptions<S> extends Omit<SubscribeOptions, 'runNow' | 'passive'> {\n /**\n * If true, the cache content can be consumed but no fetch will be triggered.\n * @default false\n */\n passive?: boolean;\n\n disableTrackingProxy?: boolean;\n\n withViewTransition?: boolean | ((value: S) => unknown);\n}\n\nexport function useStore<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useStore<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useStore<T>(store: Store<T>, option?: UseStoreOptions<T>): T;\n\nexport function useStore<T, S>(store: Store<T>, argument1?: any, argument2?: any): S {\n const selector = makeSelector<T, S>(\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined,\n );\n\n const allOptions = (\n typeof argument1 === 'object' ? argument1 : (argument2 ?? {})\n ) as UseStoreOptions<S>;\n\n const lastEqualsRef = useRef<(newValue: S) => boolean | undefined>(undefined);\n\n if (store.derivedFrom) {\n return useStore(\n store.derivedFrom.store,\n (value) => {\n for (const selector of store.derivedFrom!.selectors) {\n value = makeSelector(selector)(value);\n }\n return selector(value);\n },\n allOptions,\n );\n }\n\n const {\n disableTrackingProxy = true,\n equals = store.options.equals ?? deepEqual,\n withViewTransition,\n ...options\n } = allOptions;\n\n const subOptions = { ...options, runNow: false };\n const subscribe = useCallback(\n (listener: () => void) => {\n let _listener: (value: any) => void = listener;\n let stopped = false;\n\n if (withViewTransition && (document as any).startViewTransition) {\n let lastObservedValue: any;\n\n _listener = (value: any) => {\n const observedValue =\n withViewTransition instanceof Function ? withViewTransition(value) : value;\n\n if (equals(lastObservedValue, observedValue)) {\n listener();\n return;\n }\n\n lastObservedValue = observedValue;\n\n let hasChanges = false;\n const mutationObserver = new MutationObserver(() => {\n hasChanges = true;\n mutationObserver.disconnect();\n });\n mutationObserver.observe(document.body, { childList: true, subtree: true });\n\n (document as any).startViewTransition(() => {\n mutationObserver.disconnect();\n\n if (!stopped) {\n listener();\n }\n\n if (!hasChanges) {\n throw new Error('no change');\n }\n });\n };\n }\n\n const cancel = store.subscribe(_listener, subOptions);\n return () => {\n stopped = true;\n cancel();\n };\n },\n [store, simpleHash(subOptions)],\n );\n\n let value = useSyncExternalStoreWithSelector<T, S>(\n //\n subscribe,\n store.get,\n undefined,\n (x) => selector(x),\n (_v, newValue) => lastEqualsRef.current?.(newValue) ?? false,\n );\n let lastEquals = (newValue: S) => equals(newValue, value);\n let revoke: (() => void) | undefined;\n\n if (!disableTrackingProxy) {\n [value, lastEquals, revoke] = trackingProxy(value, equals);\n }\n\n useLayoutEffect(() => {\n lastEqualsRef.current = lastEquals;\n revoke?.();\n });\n\n useDebugValue(value);\n return value;\n}\n","import { createStore } from '@core';\nimport { useStore } from '@react/useStore';\nimport { createContext, useContext, useLayoutEffect, useMemo, type ReactNode } from 'react';\n\nexport interface LoadingBoundaryEntry {\n label?: ReactNode;\n}\n\nexport interface LoadingBoundaryProps {\n /**\n * Fallback node to render when there are loading components within the boundary.\n */\n fallback?: ReactNode | ((entries: LoadingBoundaryEntry[]) => ReactNode);\n\n /**\n * Child node to render when there are no loading components within the boundary.\n */\n children?: ReactNode;\n\n /**\n * Add a loading state from outside the boundary. Useful for when you want to\n * show a loading state for a component that is not a child of the boundary.\n */\n isLoading?: boolean;\n}\n\nconst LoadingBoundaryContext = createContext(createStore(new Set<LoadingBoundaryEntry>()));\n\nexport function LoadingBoundary({\n fallback,\n children,\n isLoading: isLoadingExternal,\n}: LoadingBoundaryProps): React.JSX.Element {\n const store = useMemo(() => createStore(new Set<LoadingBoundaryEntry>()), []);\n const entries = useStore(store);\n const isLoading = entries.size > 0 || isLoadingExternal;\n\n const fallbackNode = isLoading\n ? typeof fallback === 'function'\n ? fallback([...entries])\n : fallback\n : undefined;\n\n return (\n <LoadingBoundaryContext.Provider value={store}>\n {fallbackNode !== undefined ? (\n <>\n {fallbackNode}\n <div style={{ display: 'none' }}>{children}</div>\n </>\n ) : (\n children\n )}\n </LoadingBoundaryContext.Provider>\n );\n}\n\nexport function useLoadingBoundary(isLoading: boolean | undefined, label?: ReactNode): void {\n const store = useContext(LoadingBoundaryContext);\n\n useLayoutEffect(() => {\n if (!isLoading) {\n return;\n }\n\n const entry = { label };\n store.set((entries) => new Set(entries).add(entry));\n\n return () => {\n store.set((entries) => {\n const newEntries = new Set(entries);\n newEntries.delete(entry);\n return newEntries;\n });\n };\n }, [isLoading]);\n}\n","import type { Cache } from '@core';\nimport type { CacheState } from '@lib/cacheState';\nimport { makeSelector } from '@lib/makeSelector';\nimport { useLoadingBoundary } from '@react/loadingBoundary';\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type UseCacheArray<T> = [\n value: T | undefined,\n error: unknown | undefined,\n isUpdating: boolean,\n isStale: boolean,\n];\n\nexport type UseCacheValue<T> = UseCacheArray<T> & CacheState<T>;\n\nexport interface UseCacheOptions<T> extends UseStoreOptions<UseCacheArray<T> & CacheState<T>> {\n /**\n * If true, will always return undefined as value and no fetch will be triggered.\n * @default false\n */\n disabled?: boolean;\n\n /**\n * If true, the cache will be invalidated when the component mounts.\n * @default false\n */\n updateOnMount?: boolean;\n\n /**\n * If true, `useCache` will throw a promise when the cache is pending. This can be used with React Suspense.\n * @see https://react.dev/reference/react/Suspense\n * @default false\n */\n suspense?: boolean;\n\n /**\n * If true, `useCache` will register its loading state with the nearest `LoadingBoundary`.\n * @default false\n */\n loadingBoundary?: boolean;\n}\n\nexport function useCache<T>(\n cache: Cache<T, any>,\n {\n passive,\n disabled,\n updateOnMount,\n withViewTransition,\n suspense,\n loadingBoundary,\n ...options\n }: UseCacheOptions<T> = {},\n): UseCacheValue<T> {\n if (withViewTransition === true) {\n withViewTransition = (state) => state.value;\n }\n\n const { rootCache, selector } = useMemo(() => {\n const rootCache: Cache<any, any> = cache.derivedFromCache?.cache ?? cache;\n let selector = (x: any) => x;\n\n if (cache.derivedFromCache) {\n selector = (value: any) => {\n for (const s of cache.derivedFromCache!.selectors) {\n value = makeSelector(s)(value);\n }\n return value;\n };\n }\n\n return { rootCache, selector };\n }, [cache]);\n\n const hasMounted = useRef(false);\n\n useEffect(() => {\n hasMounted.current = true;\n\n if (updateOnMount) {\n rootCache.invalidate();\n }\n }, []);\n\n const result = useStore(\n rootCache.state,\n (state) => {\n if (disabled) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, undefined, false, false],\n { status: 'pending', isUpdating: false, isStale: false, isConnected: false },\n );\n }\n\n const isStale = updateOnMount && !hasMounted.current ? true : state.isStale;\n try {\n const value = state.status === 'value' ? selector(state.value) : undefined;\n\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [value, state.error, state.isUpdating, isStale],\n { ...state, value, isStale },\n );\n } catch (error) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, error, state.isUpdating, isStale],\n {\n status: 'error',\n error,\n isUpdating: state.isUpdating,\n isStale: isStale,\n isConnected: state.isConnected,\n },\n );\n }\n },\n { ...options, withViewTransition, passive: passive || disabled },\n );\n\n useEffect(\n () => rootCache.subscribe(() => undefined, { passive: passive || disabled }),\n [rootCache, passive || disabled],\n );\n\n useLoadingBoundary(loadingBoundary && !disabled && result.status === 'pending');\n\n if (suspense && result.status === 'pending') {\n throw rootCache.get();\n }\n\n return result;\n}\n","import type { Cache } from '@core';\nimport { type UseCacheOptions, type UseCacheValue, useCache } from '@react/useCache';\n\nexport const cacheMethods = {\n useCache<T>(this: Cache<T, any>, options?: UseCacheOptions<T>): UseCacheValue<T> {\n return useCache(this, options);\n },\n};\n","import { type Selector, type Update } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { type Path, type Value } from '@lib/path';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport function useProp<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useProp<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useProp<T>(\n store: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useProp<T, S>(\n store: Store<T>,\n argument1?: any,\n argument2?: any,\n argument3?: any,\n): [value: S, setValue: Store<S>['set']] {\n const selector =\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined;\n const updater = typeof argument2 === 'function' ? argument2 : undefined;\n const options =\n typeof argument1 === 'object'\n ? argument1\n : typeof argument2 === 'object'\n ? argument2\n : argument3;\n\n if (selector) {\n store = store.map(selector, updater);\n }\n\n const value = useStore(store, options) as S;\n return [value, store.set as Store<S>['set']];\n}\n","import type { Scope, Selector, Update } from '@core';\nimport { createStore, type Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { createContext, useContext, useMemo, type Context, type ReactNode } from 'react';\nimport { useProp } from './useProp';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type ScopeProps<T> = { scope: Scope<T>; store?: Store<T>; children?: ReactNode };\n\ndeclare module '..' {\n interface Scope<T> {\n context?: Context<Store<T>>;\n }\n}\n\nfunction getScopeContext<T>(scope: Scope<T>): Context<Store<T>> {\n scope.context ??= createContext<Store<T>>(createStore(scope.defaultValue));\n return scope.context;\n}\n\nexport function ScopeProvider<T>({\n scope,\n store: inputStore,\n children,\n}: ScopeProps<T>): React.JSX.Element {\n const context = getScopeContext(scope);\n const currentStore = useMemo(\n () => inputStore ?? createStore(scope.defaultValue),\n [scope, inputStore],\n );\n\n return <context.Provider value={currentStore}>{children}</context.Provider>;\n}\n\nexport function useScope<T>(scope: Scope<T>): Store<T> {\n const context = getScopeContext(scope);\n return useContext(context);\n}\n\nexport function useScopeStore<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useScopeStore<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useScopeStore<T>(scope: Scope<T>, option?: UseStoreOptions<T>): T;\n\nexport function useScopeStore<T>(scope: Scope<T>, ...args: any[]): T {\n const store = useScope(scope);\n return useStore(store, ...args);\n}\n\nexport function useScopeProp<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useScopeProp<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n ...args: any[]\n): [value: T, setValue: Store<T>['set']] {\n const store = useScope(scope);\n return useProp(store, ...args);\n}\n","import type { Scope, Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport {\n ScopeProvider,\n useScope,\n useScopeProp,\n useScopeStore,\n type ScopeProps,\n} from '@react/scope';\nimport type { UseStoreOptions } from '@react/useStore';\n\nfunction boundUseScope<T>(this: Scope<T>): Store<T> {\n return useScope(this);\n}\n\nfunction boundUseScopeStore<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nfunction boundUseScopeStore<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nfunction boundUseScopeStore<T>(this: Scope<T>, option?: UseStoreOptions<T>): T;\n\nfunction boundUseScopeStore(this: Scope<any>, ...args: any[]) {\n return useScopeStore(this, ...args);\n}\n\nfunction boundUseScopeProp<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nfunction boundUseScopeProp<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nfunction boundUseScopeProp<T>(\n this: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nfunction boundUseScopeProp(this: Scope<any>, ...args: any[]) {\n return useScopeProp(this, ...args);\n}\n\nfunction Provider<T>(this: Scope<T>, props: Omit<ScopeProps<T>, 'scope'>): React.JSX.Element {\n return ScopeProvider({ ...props, scope: this });\n}\n\nexport const scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n} = {\n useScope: boundUseScope,\n useStore: boundUseScopeStore,\n useProp: boundUseScopeProp,\n Provider,\n};\n","import type { Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { useProp } from '@react/useProp';\nimport { type UseStoreOptions, useStore } from '@react/useStore';\n\nfunction boundUseStore<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\nfunction boundUseStore<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\nfunction boundUseStore<T>(this: Store<T>, option?: UseStoreOptions<T>): T;\nfunction boundUseStore(this: Store<any>, ...args: any[]) {\n return useStore(this, ...args);\n}\n\nfunction boundUseProp<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\nfunction boundUseProp<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\nfunction boundUseProp<T>(\n this: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\nfunction boundUseProp(this: Store<any>, ...args: any[]) {\n return useProp(this, ...args);\n}\n\nexport const storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n} = {\n useStore: boundUseStore,\n useProp: boundUseProp,\n};\n"],"mappings":";;;;;;;;AAGA,MAAM,oBAAoC,uBAAO;AAKjD,SAAgB,cACd,OACA,SAAsC,WACpB;AAClB,KAAI,CAAC,cAAc,UAAU,CAAC,MAAM,QAAQ,OAC1C,QAAO,CAAC,QAAQ,UAAU,OAAO,OAAO;AAI1C,SAAS,MAAc,sBAAsB;CAE7C,MAAM,OAAO,IAAI;CACjB,MAAM,cAAc,IAAI;CACxB,IAAI,UAAU;CAEd,SAAS,iBAAiB,WAAgB,GAAG,MAAa;EACxD,MAAM,CAAC,cAAcA,UAAQ,UAAU,cAAc,UAAU,OAAO,GAAG;AAEzE,OAAK,MAAM,eAAe;AACxB,OAAI,CAAC,cAAc,eAAe,CAAC,MAAM,QAAQ,YAC/C,QAAO;AAGT,UAAOA,SAAO,UAAU,YAAY,GAAG;;AAGzC,MAAI,OACF,aAAY,KAAK;AAGnB,SAAO;;CAGT,SAAS,gBAAgB,WAAgB,GAAG,MAAa;EACvD,MAAM,kBAAkB,UAAU,OAAO,GAAG;AAE5C,OAAK,MAAM,eAAe;AACxB,UAAO,UAAU,YAAY,GAAG,UAAU;;AAG5C,SAAO;;CAGT,MAAM,QAAQ,IAAI,MAAM,OAAsB;EAC5C,IAAI,QAAQ,GAAG,UAAU;AACvB,OAAI,MAAM,kBACR,QAAO;AAGT,OAAI,QACF,QAAO,OAAO;GAGhB,MAAM,EAAE,UAAU,iBAAiB,OAAO,yBAAyB,QAAQ,MAAM;AACjF,OAAI,aAAa,SA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4B,OAAwD;AAC3F,QAAO,cAAc;EAAE,GAAG;EAAO,OAAO;;;AAG1C,MAAaC,eAKT;CACF,UAAU;CACV,UAAU;CACV,SAAS;CACT;;;;;ACpDF,SAAS,cAAgC,GAAG,MAAa;AACvD,QAAO,SAAS,MAAM,GAAG;;AAkB3B,SAAS,aAA+B,GAAG,MAAa;AACtD,QAAO,QAAQ,MAAM,GAAG;;AAG1B,MAAaC,eAGT;CACF,UAAU;CACV,SAAS"}
@@ -1,5 +1,5 @@
1
- import { Cache, CacheState, Scope } from "./scope-6B7-8lwa.cjs";
2
- import { Constrain, Path, Selector, Store, SubscribeOptions, Update, Value } from "./store-BEsiS8y7.cjs";
1
+ import { Cache, CacheState, Scope } from "./scope-DkO-RIMy.cjs";
2
+ import { Constrain, Path, Selector, Store, SubscribeOptions, Update, Value } from "./store-B3PWCx63.cjs";
3
3
  import { Context, ReactNode } from "react";
4
4
 
5
5
  //#region src/react/useStore.d.ts
@@ -104,4 +104,4 @@ declare const storeMethods: {
104
104
  };
105
105
  //#endregion
106
106
  export { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore };
107
- //# sourceMappingURL=storeMethods-Bg8nMBrf.d.cts.map
107
+ //# sourceMappingURL=storeMethods-Dt_mJTe3.d.cts.map
@@ -1,5 +1,5 @@
1
1
  const require_chunk = require('./chunk-CUT6urMc.cjs');
2
- const require_store = require('./store-1TGlSyq4.cjs');
2
+ const require_store = require('./store-DQcFfgKD.cjs');
3
3
  const require_propAccess = require('./propAccess-BdLsqViO.cjs');
4
4
  const require_hash = require('./hash-Dv3XlmHn.cjs');
5
5
  const react = require_chunk.__toESM(require("react"));
@@ -372,4 +372,4 @@ Object.defineProperty(exports, 'useStore', {
372
372
  return useStore;
373
373
  }
374
374
  });
375
- //# sourceMappingURL=storeMethods-C_RzHBQL.cjs.map
375
+ //# sourceMappingURL=storeMethods-YDnpa-6-.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"storeMethods-C_RzHBQL.cjs","names":["deepEqual","isPlainObject","equals","makeSelector","selector","value","deepEqual","_listener: (value: any) => void","lastObservedValue: any","simpleHash","revoke: (() => void) | undefined","createStore","rootCache: Cache<any, any>","selector","makeSelector","createStore","scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n}","storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n}"],"sources":["../src/lib/trackingProxy.ts","../src/react/useStore.ts","../src/react/loadingBoundary.tsx","../src/react/useCache.ts","../src/react/cacheMethods.ts","../src/react/useProp.ts","../src/react/scope.tsx","../src/react/scopeMethods.ts","../src/react/storeMethods.ts"],"sourcesContent":["import { isPlainObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\n\nconst unwrapProxySymbol = /* @__PURE__ */ Symbol('unwrapProxy');\n\nexport type TrackingProxy<T> = [value: T, equals: (newValue: T) => boolean, revoke?: () => void];\ntype Object_ = Record<string | symbol, unknown>;\n\nexport function trackingProxy<T>(\n value: T,\n equals: (a: any, b: any) => boolean = deepEqual,\n): TrackingProxy<T> {\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [value, (other) => equals(value, other)];\n }\n\n // Unpack proxies, we don't want to nest them\n value = (value as any)[unwrapProxySymbol] ?? value;\n\n const deps = new Array<TrackingProxy<any>[1]>();\n const revokations = new Array<() => void>();\n let revoked = false;\n\n function trackComplexProp(function_: any, ...args: any[]) {\n const [proxiedValue, equals, revoke] = trackingProxy(function_(value, ...args));\n\n deps.push((otherValue) => {\n if (!isPlainObject(otherValue) && !Array.isArray(otherValue)) {\n return false;\n }\n\n return equals(function_(otherValue, ...args));\n });\n\n if (revoke) {\n revokations.push(revoke);\n }\n\n return proxiedValue;\n }\n\n function trackSimpleProp(function_: any, ...args: any[]) {\n const calculatedValue = function_(value, ...args);\n\n deps.push((otherValue) => {\n return function_(otherValue, ...args) === calculatedValue;\n });\n\n return calculatedValue;\n }\n\n const proxy = new Proxy(value as T & Object_, {\n get(target, p, receiver) {\n if (p === unwrapProxySymbol) {\n return value;\n }\n\n if (revoked) {\n return target[p];\n }\n\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return target[p];\n }\n\n return trackComplexProp(Reflect.get, p, receiver);\n },\n\n getOwnPropertyDescriptor(target, p) {\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return Reflect.getOwnPropertyDescriptor(target, p);\n }\n\n return trackComplexProp(Reflect.getOwnPropertyDescriptor, p);\n },\n\n ownKeys() {\n return trackComplexProp(Reflect.ownKeys);\n },\n\n getPrototypeOf() {\n return trackSimpleProp(Reflect.getPrototypeOf);\n },\n\n has(_target, p) {\n return trackSimpleProp(Reflect.has, p);\n },\n\n isExtensible() {\n return trackSimpleProp(Reflect.isExtensible);\n },\n });\n\n return [\n proxy,\n (other) => !!other && deps.every((equals) => equals(other)),\n () => {\n revoked = true;\n revokations.forEach((revoke) => revoke());\n },\n ];\n}\n","import type { Selector, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { simpleHash } from '@lib/hash';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type Path, type Value } from '@lib/path';\nimport { trackingProxy } from '@lib/trackingProxy';\nimport { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js';\n\nexport interface UseStoreOptions<S> extends Omit<SubscribeOptions, 'runNow' | 'passive'> {\n /**\n * If true, the cache content can be consumed but no fetch will be triggered.\n * @default false\n */\n passive?: boolean;\n\n disableTrackingProxy?: boolean;\n\n withViewTransition?: boolean | ((value: S) => unknown);\n}\n\nexport function useStore<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useStore<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useStore<T>(store: Store<T>, option?: UseStoreOptions<T>): T;\n\nexport function useStore<T, S>(store: Store<T>, argument1?: any, argument2?: any): S {\n const selector = makeSelector<T, S>(\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined,\n );\n\n const allOptions = (\n typeof argument1 === 'object' ? argument1 : (argument2 ?? {})\n ) as UseStoreOptions<S>;\n\n const lastEqualsRef = useRef<(newValue: S) => boolean | undefined>(undefined);\n\n if (store.derivedFrom) {\n return useStore(\n store.derivedFrom.store,\n (value) => {\n for (const selector of store.derivedFrom!.selectors) {\n value = makeSelector(selector)(value);\n }\n return selector(value);\n },\n allOptions,\n );\n }\n\n const {\n disableTrackingProxy = true,\n equals = store.options.equals ?? deepEqual,\n withViewTransition,\n ...options\n } = allOptions;\n\n const subOptions = { ...options, runNow: false };\n const subscribe = useCallback(\n (listener: () => void) => {\n let _listener: (value: any) => void = listener;\n let stopped = false;\n\n if (withViewTransition && (document as any).startViewTransition) {\n let lastObservedValue: any;\n\n _listener = (value: any) => {\n const observedValue =\n withViewTransition instanceof Function ? withViewTransition(value) : value;\n\n if (equals(lastObservedValue, observedValue)) {\n listener();\n return;\n }\n\n lastObservedValue = observedValue;\n\n let hasChanges = false;\n const mutationObserver = new MutationObserver(() => {\n hasChanges = true;\n mutationObserver.disconnect();\n });\n mutationObserver.observe(document.body, { childList: true, subtree: true });\n\n (document as any).startViewTransition(() => {\n mutationObserver.disconnect();\n\n if (!stopped) {\n listener();\n }\n\n if (!hasChanges) {\n throw new Error('no change');\n }\n });\n };\n }\n\n const cancel = store.subscribe(_listener, subOptions);\n return () => {\n stopped = true;\n cancel();\n };\n },\n [store, simpleHash(subOptions)],\n );\n\n let value = useSyncExternalStoreWithSelector<T, S>(\n //\n subscribe,\n store.get,\n undefined,\n (x) => selector(x),\n (_v, newValue) => lastEqualsRef.current?.(newValue) ?? false,\n );\n let lastEquals = (newValue: S) => equals(newValue, value);\n let revoke: (() => void) | undefined;\n\n if (!disableTrackingProxy) {\n [value, lastEquals, revoke] = trackingProxy(value, equals);\n }\n\n useLayoutEffect(() => {\n lastEqualsRef.current = lastEquals;\n revoke?.();\n });\n\n useDebugValue(value);\n return value;\n}\n","import { createStore } from '@core';\nimport { useStore } from '@react/useStore';\nimport { createContext, useContext, useLayoutEffect, useMemo, type ReactNode } from 'react';\n\nexport interface LoadingBoundaryEntry {\n label?: ReactNode;\n}\n\nexport interface LoadingBoundaryProps {\n /**\n * Fallback node to render when there are loading components within the boundary.\n */\n fallback?: ReactNode | ((entries: LoadingBoundaryEntry[]) => ReactNode);\n\n /**\n * Child node to render when there are no loading components within the boundary.\n */\n children?: ReactNode;\n\n /**\n * Add a loading state from outside the boundary. Useful for when you want to\n * show a loading state for a component that is not a child of the boundary.\n */\n isLoading?: boolean;\n}\n\nconst LoadingBoundaryContext = createContext(createStore(new Set<LoadingBoundaryEntry>()));\n\nexport function LoadingBoundary({\n fallback,\n children,\n isLoading: isLoadingExternal,\n}: LoadingBoundaryProps): React.JSX.Element {\n const store = useMemo(() => createStore(new Set<LoadingBoundaryEntry>()), []);\n const entries = useStore(store);\n const isLoading = entries.size > 0 || isLoadingExternal;\n\n const fallbackNode = isLoading\n ? typeof fallback === 'function'\n ? fallback([...entries])\n : fallback\n : undefined;\n\n return (\n <LoadingBoundaryContext.Provider value={store}>\n {fallbackNode !== undefined ? (\n <>\n {fallbackNode}\n <div style={{ display: 'none' }}>{children}</div>\n </>\n ) : (\n children\n )}\n </LoadingBoundaryContext.Provider>\n );\n}\n\nexport function useLoadingBoundary(isLoading: boolean | undefined, label?: ReactNode): void {\n const store = useContext(LoadingBoundaryContext);\n\n useLayoutEffect(() => {\n if (!isLoading) {\n return;\n }\n\n const entry = { label };\n store.set((entries) => new Set(entries).add(entry));\n\n return () => {\n store.set((entries) => {\n const newEntries = new Set(entries);\n newEntries.delete(entry);\n return newEntries;\n });\n };\n }, [isLoading]);\n}\n","import type { Cache } from '@core';\nimport type { CacheState } from '@lib/cacheState';\nimport { makeSelector } from '@lib/makeSelector';\nimport { useLoadingBoundary } from '@react/loadingBoundary';\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type UseCacheArray<T> = [\n value: T | undefined,\n error: unknown | undefined,\n isUpdating: boolean,\n isStale: boolean,\n];\n\nexport type UseCacheValue<T> = UseCacheArray<T> & CacheState<T>;\n\nexport interface UseCacheOptions<T> extends UseStoreOptions<UseCacheArray<T> & CacheState<T>> {\n /**\n * If true, will always return undefined as value and no fetch will be triggered.\n * @default false\n */\n disabled?: boolean;\n\n /**\n * If true, the cache will be invalidated when the component mounts.\n * @default false\n */\n updateOnMount?: boolean;\n\n /**\n * If true, `useCache` will throw a promise when the cache is pending. This can be used with React Suspense.\n * @see https://react.dev/reference/react/Suspense\n * @default false\n */\n suspense?: boolean;\n\n /**\n * If true, `useCache` will register its loading state with the nearest `LoadingBoundary`.\n * @default false\n */\n loadingBoundary?: boolean;\n}\n\nexport function useCache<T>(\n cache: Cache<T, any>,\n {\n passive,\n disabled,\n updateOnMount,\n withViewTransition,\n suspense,\n loadingBoundary,\n ...options\n }: UseCacheOptions<T> = {},\n): UseCacheValue<T> {\n if (withViewTransition === true) {\n withViewTransition = (state) => state.value;\n }\n\n const { rootCache, selector } = useMemo(() => {\n const rootCache: Cache<any, any> = cache.derivedFromCache?.cache ?? cache;\n let selector = (x: any) => x;\n\n if (cache.derivedFromCache) {\n selector = (value: any) => {\n for (const s of cache.derivedFromCache!.selectors) {\n value = makeSelector(s)(value);\n }\n return value;\n };\n }\n\n return { rootCache, selector };\n }, [cache]);\n\n const hasMounted = useRef(false);\n\n useEffect(() => {\n hasMounted.current = true;\n\n if (updateOnMount) {\n rootCache.invalidate();\n }\n }, []);\n\n const result = useStore(\n rootCache.state,\n (state) => {\n if (disabled) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, undefined, false, false],\n { status: 'pending', isUpdating: false, isStale: false, isConnected: false },\n );\n }\n\n const isStale = updateOnMount && !hasMounted.current ? true : state.isStale;\n try {\n const value = state.status === 'value' ? selector(state.value) : undefined;\n\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [value, state.error, state.isUpdating, isStale],\n { ...state, value, isStale },\n );\n } catch (error) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, error, state.isUpdating, isStale],\n {\n status: 'error',\n error,\n isUpdating: state.isUpdating,\n isStale: isStale,\n isConnected: state.isConnected,\n },\n );\n }\n },\n { ...options, withViewTransition, passive: passive || disabled },\n );\n\n useEffect(\n () => rootCache.subscribe(() => undefined, { passive: passive || disabled }),\n [rootCache, passive || disabled],\n );\n\n useLoadingBoundary(loadingBoundary && !disabled && result.status === 'pending');\n\n if (suspense && result.status === 'pending') {\n throw rootCache.get();\n }\n\n return result;\n}\n","import type { Cache } from '@core';\nimport { type UseCacheOptions, type UseCacheValue, useCache } from '@react/useCache';\n\nexport const cacheMethods = {\n useCache<T>(this: Cache<T, any>, options?: UseCacheOptions<T>): UseCacheValue<T> {\n return useCache(this, options);\n },\n};\n","import { type Selector, type Update } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { type Path, type Value } from '@lib/path';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport function useProp<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useProp<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useProp<T>(\n store: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useProp<T, S>(\n store: Store<T>,\n argument1?: any,\n argument2?: any,\n argument3?: any,\n): [value: S, setValue: Store<S>['set']] {\n const selector =\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined;\n const updater = typeof argument2 === 'function' ? argument2 : undefined;\n const options =\n typeof argument1 === 'object'\n ? argument1\n : typeof argument2 === 'object'\n ? argument2\n : argument3;\n\n if (selector) {\n store = store.map(selector, updater);\n }\n\n const value = useStore(store, options) as S;\n return [value, store.set as Store<S>['set']];\n}\n","import type { Scope, Selector, Update } from '@core';\nimport { createStore, type Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { createContext, useContext, useMemo, type Context, type ReactNode } from 'react';\nimport { useProp } from './useProp';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type ScopeProps<T> = { scope: Scope<T>; store?: Store<T>; children?: ReactNode };\n\ndeclare module '..' {\n interface Scope<T> {\n context?: Context<Store<T>>;\n }\n}\n\nfunction getScopeContext<T>(scope: Scope<T>): Context<Store<T>> {\n scope.context ??= createContext<Store<T>>(createStore(scope.defaultValue));\n return scope.context;\n}\n\nexport function ScopeProvider<T>({\n scope,\n store: inputStore,\n children,\n}: ScopeProps<T>): React.JSX.Element {\n const context = getScopeContext(scope);\n const currentStore = useMemo(\n () => inputStore ?? createStore(scope.defaultValue),\n [scope, inputStore],\n );\n\n return <context.Provider value={currentStore}>{children}</context.Provider>;\n}\n\nexport function useScope<T>(scope: Scope<T>): Store<T> {\n const context = getScopeContext(scope);\n return useContext(context);\n}\n\nexport function useScopeStore<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useScopeStore<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useScopeStore<T>(scope: Scope<T>, option?: UseStoreOptions<T>): T;\n\nexport function useScopeStore<T>(scope: Scope<T>, ...args: any[]): T {\n const store = useScope(scope);\n return useStore(store, ...args);\n}\n\nexport function useScopeProp<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useScopeProp<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n ...args: any[]\n): [value: T, setValue: Store<T>['set']] {\n const store = useScope(scope);\n return useProp(store, ...args);\n}\n","import type { Scope, Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport {\n ScopeProvider,\n useScope,\n useScopeProp,\n useScopeStore,\n type ScopeProps,\n} from '@react/scope';\nimport type { UseStoreOptions } from '@react/useStore';\n\nfunction boundUseScope<T>(this: Scope<T>): Store<T> {\n return useScope(this);\n}\n\nfunction boundUseScopeStore<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nfunction boundUseScopeStore<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nfunction boundUseScopeStore<T>(this: Scope<T>, option?: UseStoreOptions<T>): T;\n\nfunction boundUseScopeStore(this: Scope<any>, ...args: any[]) {\n return useScopeStore(this, ...args);\n}\n\nfunction boundUseScopeProp<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nfunction boundUseScopeProp<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nfunction boundUseScopeProp<T>(\n this: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nfunction boundUseScopeProp(this: Scope<any>, ...args: any[]) {\n return useScopeProp(this, ...args);\n}\n\nfunction Provider<T>(this: Scope<T>, props: Omit<ScopeProps<T>, 'scope'>): React.JSX.Element {\n return ScopeProvider({ ...props, scope: this });\n}\n\nexport const scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n} = {\n useScope: boundUseScope,\n useStore: boundUseScopeStore,\n useProp: boundUseScopeProp,\n Provider,\n};\n","import type { Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { useProp } from '@react/useProp';\nimport { type UseStoreOptions, useStore } from '@react/useStore';\n\nfunction boundUseStore<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\nfunction boundUseStore<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\nfunction boundUseStore<T>(this: Store<T>, option?: UseStoreOptions<T>): T;\nfunction boundUseStore(this: Store<any>, ...args: any[]) {\n return useStore(this, ...args);\n}\n\nfunction boundUseProp<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\nfunction boundUseProp<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\nfunction boundUseProp<T>(\n this: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\nfunction boundUseProp(this: Store<any>, ...args: any[]) {\n return useProp(this, ...args);\n}\n\nexport const storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n} = {\n useStore: boundUseStore,\n useProp: boundUseProp,\n};\n"],"mappings":";;;;;;;;;AAGA,MAAM,oBAAoC,uBAAO;AAKjD,SAAgB,cACd,OACA,SAAsCA,8BACpB;AAClB,KAAI,CAACC,iCAAc,UAAU,CAAC,MAAM,QAAQ,OAC1C,QAAO,CAAC,QAAQ,UAAU,OAAO,OAAO;AAI1C,SAAS,MAAc,sBAAsB;CAE7C,MAAM,OAAO,IAAI;CACjB,MAAM,cAAc,IAAI;CACxB,IAAI,UAAU;CAEd,SAAS,iBAAiB,WAAgB,GAAG,MAAa;EACxD,MAAM,CAAC,cAAcC,UAAQ,UAAU,cAAc,UAAU,OAAO,GAAG;AAEzE,OAAK,MAAM,eAAe;AACxB,OAAI,CAACD,iCAAc,eAAe,CAAC,MAAM,QAAQ,YAC/C,QAAO;AAGT,UAAOC,SAAO,UAAU,YAAY,GAAG;;AAGzC,MAAI,OACF,aAAY,KAAK;AAGnB,SAAO;;CAGT,SAAS,gBAAgB,WAAgB,GAAG,MAAa;EACvD,MAAM,kBAAkB,UAAU,OAAO,GAAG;AAE5C,OAAK,MAAM,eAAe;AACxB,UAAO,UAAU,YAAY,GAAG,UAAU;;AAG5C,SAAO;;CAGT,MAAM,QAAQ,IAAI,MAAM,OAAsB;EAC5C,IAAI,QAAQ,GAAG,UAAU;AACvB,OAAI,MAAM,kBACR,QAAO;AAGT,OAAI,QACF,QAAO,OAAO;GAGhB,MAAM,EAAE,UAAU,iBAAiB,OAAO,yBAAyB,QAAQ,MAAM;AACjF,OAAI,aAAa,SAAS,iBAAiB,MACzC,QAAO,OAAO;AAGhB,UAAO,iBAAiB,QAAQ,KAAK,GAAG;;EAG1C,yBAAyB,QAAQ,GAAG;GAClC,MAAM,EAAE,UAAU,iBAAiB,OAAO,yBAAyB,QAAQ,MAAM;AACjF,OAAI,aAAa,SAAS,iBAAiB,MACzC,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AAM,GAAG;;AAG1B,MAAaC,eAGT;CACF,UAAU;CACV,SAAS"}
1
+ {"version":3,"file":"storeMethods-YDnpa-6-.cjs","names":["deepEqual","isPlainObject","equals","makeSelector","selector","value","deepEqual","_listener: (value: any) => void","lastObservedValue: any","simpleHash","revoke: (() => void) | undefined","createStore","rootCache: Cache<any, any>","selector","makeSelector","createStore","scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n}","storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n}"],"sources":["../src/lib/trackingProxy.ts","../src/react/useStore.ts","../src/react/loadingBoundary.tsx","../src/react/useCache.ts","../src/react/cacheMethods.ts","../src/react/useProp.ts","../src/react/scope.tsx","../src/react/scopeMethods.ts","../src/react/storeMethods.ts"],"sourcesContent":["import { isPlainObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\n\nconst unwrapProxySymbol = /* @__PURE__ */ Symbol('unwrapProxy');\n\nexport type TrackingProxy<T> = [value: T, equals: (newValue: T) => boolean, revoke?: () => void];\ntype Object_ = Record<string | symbol, unknown>;\n\nexport function trackingProxy<T>(\n value: T,\n equals: (a: any, b: any) => boolean = deepEqual,\n): TrackingProxy<T> {\n if (!isPlainObject(value) && !Array.isArray(value)) {\n return [value, (other) => equals(value, other)];\n }\n\n // Unpack proxies, we don't want to nest them\n value = (value as any)[unwrapProxySymbol] ?? value;\n\n const deps = new Array<TrackingProxy<any>[1]>();\n const revokations = new Array<() => void>();\n let revoked = false;\n\n function trackComplexProp(function_: any, ...args: any[]) {\n const [proxiedValue, equals, revoke] = trackingProxy(function_(value, ...args));\n\n deps.push((otherValue) => {\n if (!isPlainObject(otherValue) && !Array.isArray(otherValue)) {\n return false;\n }\n\n return equals(function_(otherValue, ...args));\n });\n\n if (revoke) {\n revokations.push(revoke);\n }\n\n return proxiedValue;\n }\n\n function trackSimpleProp(function_: any, ...args: any[]) {\n const calculatedValue = function_(value, ...args);\n\n deps.push((otherValue) => {\n return function_(otherValue, ...args) === calculatedValue;\n });\n\n return calculatedValue;\n }\n\n const proxy = new Proxy(value as T & Object_, {\n get(target, p, receiver) {\n if (p === unwrapProxySymbol) {\n return value;\n }\n\n if (revoked) {\n return target[p];\n }\n\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return target[p];\n }\n\n return trackComplexProp(Reflect.get, p, receiver);\n },\n\n getOwnPropertyDescriptor(target, p) {\n const { writable, configurable } = Object.getOwnPropertyDescriptor(target, p) ?? {};\n if (writable === false && configurable === false) {\n return Reflect.getOwnPropertyDescriptor(target, p);\n }\n\n return trackComplexProp(Reflect.getOwnPropertyDescriptor, p);\n },\n\n ownKeys() {\n return trackComplexProp(Reflect.ownKeys);\n },\n\n getPrototypeOf() {\n return trackSimpleProp(Reflect.getPrototypeOf);\n },\n\n has(_target, p) {\n return trackSimpleProp(Reflect.has, p);\n },\n\n isExtensible() {\n return trackSimpleProp(Reflect.isExtensible);\n },\n });\n\n return [\n proxy,\n (other) => !!other && deps.every((equals) => equals(other)),\n () => {\n revoked = true;\n revokations.forEach((revoke) => revoke());\n },\n ];\n}\n","import type { Selector, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { simpleHash } from '@lib/hash';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type Path, type Value } from '@lib/path';\nimport { trackingProxy } from '@lib/trackingProxy';\nimport { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js';\n\nexport interface UseStoreOptions<S> extends Omit<SubscribeOptions, 'runNow' | 'passive'> {\n /**\n * If true, the cache content can be consumed but no fetch will be triggered.\n * @default false\n */\n passive?: boolean;\n\n disableTrackingProxy?: boolean;\n\n withViewTransition?: boolean | ((value: S) => unknown);\n}\n\nexport function useStore<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useStore<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useStore<T>(store: Store<T>, option?: UseStoreOptions<T>): T;\n\nexport function useStore<T, S>(store: Store<T>, argument1?: any, argument2?: any): S {\n const selector = makeSelector<T, S>(\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined,\n );\n\n const allOptions = (\n typeof argument1 === 'object' ? argument1 : (argument2 ?? {})\n ) as UseStoreOptions<S>;\n\n const lastEqualsRef = useRef<(newValue: S) => boolean | undefined>(undefined);\n\n if (store.derivedFrom) {\n return useStore(\n store.derivedFrom.store,\n (value) => {\n for (const selector of store.derivedFrom!.selectors) {\n value = makeSelector(selector)(value);\n }\n return selector(value);\n },\n allOptions,\n );\n }\n\n const {\n disableTrackingProxy = true,\n equals = store.options.equals ?? deepEqual,\n withViewTransition,\n ...options\n } = allOptions;\n\n const subOptions = { ...options, runNow: false };\n const subscribe = useCallback(\n (listener: () => void) => {\n let _listener: (value: any) => void = listener;\n let stopped = false;\n\n if (withViewTransition && (document as any).startViewTransition) {\n let lastObservedValue: any;\n\n _listener = (value: any) => {\n const observedValue =\n withViewTransition instanceof Function ? withViewTransition(value) : value;\n\n if (equals(lastObservedValue, observedValue)) {\n listener();\n return;\n }\n\n lastObservedValue = observedValue;\n\n let hasChanges = false;\n const mutationObserver = new MutationObserver(() => {\n hasChanges = true;\n mutationObserver.disconnect();\n });\n mutationObserver.observe(document.body, { childList: true, subtree: true });\n\n (document as any).startViewTransition(() => {\n mutationObserver.disconnect();\n\n if (!stopped) {\n listener();\n }\n\n if (!hasChanges) {\n throw new Error('no change');\n }\n });\n };\n }\n\n const cancel = store.subscribe(_listener, subOptions);\n return () => {\n stopped = true;\n cancel();\n };\n },\n [store, simpleHash(subOptions)],\n );\n\n let value = useSyncExternalStoreWithSelector<T, S>(\n //\n subscribe,\n store.get,\n undefined,\n (x) => selector(x),\n (_v, newValue) => lastEqualsRef.current?.(newValue) ?? false,\n );\n let lastEquals = (newValue: S) => equals(newValue, value);\n let revoke: (() => void) | undefined;\n\n if (!disableTrackingProxy) {\n [value, lastEquals, revoke] = trackingProxy(value, equals);\n }\n\n useLayoutEffect(() => {\n lastEqualsRef.current = lastEquals;\n revoke?.();\n });\n\n useDebugValue(value);\n return value;\n}\n","import { createStore } from '@core';\nimport { useStore } from '@react/useStore';\nimport { createContext, useContext, useLayoutEffect, useMemo, type ReactNode } from 'react';\n\nexport interface LoadingBoundaryEntry {\n label?: ReactNode;\n}\n\nexport interface LoadingBoundaryProps {\n /**\n * Fallback node to render when there are loading components within the boundary.\n */\n fallback?: ReactNode | ((entries: LoadingBoundaryEntry[]) => ReactNode);\n\n /**\n * Child node to render when there are no loading components within the boundary.\n */\n children?: ReactNode;\n\n /**\n * Add a loading state from outside the boundary. Useful for when you want to\n * show a loading state for a component that is not a child of the boundary.\n */\n isLoading?: boolean;\n}\n\nconst LoadingBoundaryContext = createContext(createStore(new Set<LoadingBoundaryEntry>()));\n\nexport function LoadingBoundary({\n fallback,\n children,\n isLoading: isLoadingExternal,\n}: LoadingBoundaryProps): React.JSX.Element {\n const store = useMemo(() => createStore(new Set<LoadingBoundaryEntry>()), []);\n const entries = useStore(store);\n const isLoading = entries.size > 0 || isLoadingExternal;\n\n const fallbackNode = isLoading\n ? typeof fallback === 'function'\n ? fallback([...entries])\n : fallback\n : undefined;\n\n return (\n <LoadingBoundaryContext.Provider value={store}>\n {fallbackNode !== undefined ? (\n <>\n {fallbackNode}\n <div style={{ display: 'none' }}>{children}</div>\n </>\n ) : (\n children\n )}\n </LoadingBoundaryContext.Provider>\n );\n}\n\nexport function useLoadingBoundary(isLoading: boolean | undefined, label?: ReactNode): void {\n const store = useContext(LoadingBoundaryContext);\n\n useLayoutEffect(() => {\n if (!isLoading) {\n return;\n }\n\n const entry = { label };\n store.set((entries) => new Set(entries).add(entry));\n\n return () => {\n store.set((entries) => {\n const newEntries = new Set(entries);\n newEntries.delete(entry);\n return newEntries;\n });\n };\n }, [isLoading]);\n}\n","import type { Cache } from '@core';\nimport type { CacheState } from '@lib/cacheState';\nimport { makeSelector } from '@lib/makeSelector';\nimport { useLoadingBoundary } from '@react/loadingBoundary';\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type UseCacheArray<T> = [\n value: T | undefined,\n error: unknown | undefined,\n isUpdating: boolean,\n isStale: boolean,\n];\n\nexport type UseCacheValue<T> = UseCacheArray<T> & CacheState<T>;\n\nexport interface UseCacheOptions<T> extends UseStoreOptions<UseCacheArray<T> & CacheState<T>> {\n /**\n * If true, will always return undefined as value and no fetch will be triggered.\n * @default false\n */\n disabled?: boolean;\n\n /**\n * If true, the cache will be invalidated when the component mounts.\n * @default false\n */\n updateOnMount?: boolean;\n\n /**\n * If true, `useCache` will throw a promise when the cache is pending. This can be used with React Suspense.\n * @see https://react.dev/reference/react/Suspense\n * @default false\n */\n suspense?: boolean;\n\n /**\n * If true, `useCache` will register its loading state with the nearest `LoadingBoundary`.\n * @default false\n */\n loadingBoundary?: boolean;\n}\n\nexport function useCache<T>(\n cache: Cache<T, any>,\n {\n passive,\n disabled,\n updateOnMount,\n withViewTransition,\n suspense,\n loadingBoundary,\n ...options\n }: UseCacheOptions<T> = {},\n): UseCacheValue<T> {\n if (withViewTransition === true) {\n withViewTransition = (state) => state.value;\n }\n\n const { rootCache, selector } = useMemo(() => {\n const rootCache: Cache<any, any> = cache.derivedFromCache?.cache ?? cache;\n let selector = (x: any) => x;\n\n if (cache.derivedFromCache) {\n selector = (value: any) => {\n for (const s of cache.derivedFromCache!.selectors) {\n value = makeSelector(s)(value);\n }\n return value;\n };\n }\n\n return { rootCache, selector };\n }, [cache]);\n\n const hasMounted = useRef(false);\n\n useEffect(() => {\n hasMounted.current = true;\n\n if (updateOnMount) {\n rootCache.invalidate();\n }\n }, []);\n\n const result = useStore(\n rootCache.state,\n (state) => {\n if (disabled) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, undefined, false, false],\n { status: 'pending', isUpdating: false, isStale: false, isConnected: false },\n );\n }\n\n const isStale = updateOnMount && !hasMounted.current ? true : state.isStale;\n try {\n const value = state.status === 'value' ? selector(state.value) : undefined;\n\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [value, state.error, state.isUpdating, isStale],\n { ...state, value, isStale },\n );\n } catch (error) {\n return Object.assign<UseCacheArray<T>, CacheState<T>>(\n [undefined, error, state.isUpdating, isStale],\n {\n status: 'error',\n error,\n isUpdating: state.isUpdating,\n isStale: isStale,\n isConnected: state.isConnected,\n },\n );\n }\n },\n { ...options, withViewTransition, passive: passive || disabled },\n );\n\n useEffect(\n () => rootCache.subscribe(() => undefined, { passive: passive || disabled }),\n [rootCache, passive || disabled],\n );\n\n useLoadingBoundary(loadingBoundary && !disabled && result.status === 'pending');\n\n if (suspense && result.status === 'pending') {\n throw rootCache.get();\n }\n\n return result;\n}\n","import type { Cache } from '@core';\nimport { type UseCacheOptions, type UseCacheValue, useCache } from '@react/useCache';\n\nexport const cacheMethods = {\n useCache<T>(this: Cache<T, any>, options?: UseCacheOptions<T>): UseCacheValue<T> {\n return useCache(this, options);\n },\n};\n","import { type Selector, type Update } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport { type Path, type Value } from '@lib/path';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport function useProp<T, S>(\n store: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useProp<T, const P>(\n store: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useProp<T>(\n store: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useProp<T, S>(\n store: Store<T>,\n argument1?: any,\n argument2?: any,\n argument3?: any,\n): [value: S, setValue: Store<S>['set']] {\n const selector =\n typeof argument1 === 'function' || typeof argument1 === 'string' ? argument1 : undefined;\n const updater = typeof argument2 === 'function' ? argument2 : undefined;\n const options =\n typeof argument1 === 'object'\n ? argument1\n : typeof argument2 === 'object'\n ? argument2\n : argument3;\n\n if (selector) {\n store = store.map(selector, updater);\n }\n\n const value = useStore(store, options) as S;\n return [value, store.set as Store<S>['set']];\n}\n","import type { Scope, Selector, Update } from '@core';\nimport { createStore, type Store } from '@core/store';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { createContext, useContext, useMemo, type Context, type ReactNode } from 'react';\nimport { useProp } from './useProp';\nimport { useStore, type UseStoreOptions } from './useStore';\n\nexport type ScopeProps<T> = { scope: Scope<T>; store?: Store<T>; children?: ReactNode };\n\ndeclare module '..' {\n interface Scope<T> {\n context?: Context<Store<T>>;\n }\n}\n\nfunction getScopeContext<T>(scope: Scope<T>): Context<Store<T>> {\n scope.context ??= createContext<Store<T>>(createStore(scope.defaultValue));\n return scope.context;\n}\n\nexport function ScopeProvider<T>({\n scope,\n store: inputStore,\n children,\n}: ScopeProps<T>): React.JSX.Element {\n const context = getScopeContext(scope);\n const currentStore = useMemo(\n () => inputStore ?? createStore(scope.defaultValue),\n [scope, inputStore],\n );\n\n return <context.Provider value={currentStore}>{children}</context.Provider>;\n}\n\nexport function useScope<T>(scope: Scope<T>): Store<T> {\n const context = getScopeContext(scope);\n return useContext(context);\n}\n\nexport function useScopeStore<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nexport function useScopeStore<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nexport function useScopeStore<T>(scope: Scope<T>, option?: UseStoreOptions<T>): T;\n\nexport function useScopeStore<T>(scope: Scope<T>, ...args: any[]): T {\n const store = useScope(scope);\n return useStore(store, ...args);\n}\n\nexport function useScopeProp<T, S>(\n scope: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nexport function useScopeProp<T, const P>(\n scope: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nexport function useScopeProp<T>(\n scope: Scope<T>,\n ...args: any[]\n): [value: T, setValue: Store<T>['set']] {\n const store = useScope(scope);\n return useProp(store, ...args);\n}\n","import type { Scope, Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport {\n ScopeProvider,\n useScope,\n useScopeProp,\n useScopeStore,\n type ScopeProps,\n} from '@react/scope';\nimport type { UseStoreOptions } from '@react/useStore';\n\nfunction boundUseScope<T>(this: Scope<T>): Store<T> {\n return useScope(this);\n}\n\nfunction boundUseScopeStore<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\n\nfunction boundUseScopeStore<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\n\nfunction boundUseScopeStore<T>(this: Scope<T>, option?: UseStoreOptions<T>): T;\n\nfunction boundUseScopeStore(this: Scope<any>, ...args: any[]) {\n return useScopeStore(this, ...args);\n}\n\nfunction boundUseScopeProp<T, S>(\n this: Scope<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\n\nfunction boundUseScopeProp<T, const P>(\n this: Scope<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\n\nfunction boundUseScopeProp<T>(\n this: Scope<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\n\nfunction boundUseScopeProp(this: Scope<any>, ...args: any[]) {\n return useScopeProp(this, ...args);\n}\n\nfunction Provider<T>(this: Scope<T>, props: Omit<ScopeProps<T>, 'scope'>): React.JSX.Element {\n return ScopeProvider({ ...props, scope: this });\n}\n\nexport const scopeMethods: {\n useScope: typeof boundUseScope;\n useStore: typeof boundUseScopeStore;\n useProp: typeof boundUseScopeProp;\n Provider: typeof Provider;\n} = {\n useScope: boundUseScope,\n useStore: boundUseScopeStore,\n useProp: boundUseScopeProp,\n Provider,\n};\n","import type { Selector, Store, Update } from '@core';\nimport type { Constrain } from '@lib/constrain';\nimport type { Path, Value } from '@lib/path';\nimport { useProp } from '@react/useProp';\nimport { type UseStoreOptions, useStore } from '@react/useStore';\n\nfunction boundUseStore<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n option?: UseStoreOptions<S>,\n): S;\nfunction boundUseStore<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n option?: UseStoreOptions<Value<T, P>>,\n): Value<T, P>;\nfunction boundUseStore<T>(this: Store<T>, option?: UseStoreOptions<T>): T;\nfunction boundUseStore(this: Store<any>, ...args: any[]) {\n return useStore(this, ...args);\n}\n\nfunction boundUseProp<T, S>(\n this: Store<T>,\n selector: Selector<T, S>,\n updater: (value: S) => Update<T>,\n options?: UseStoreOptions<S>,\n): [value: S, setValue: Store<S>['set']];\nfunction boundUseProp<T, const P>(\n this: Store<T>,\n selector: Constrain<P, Path<T>>,\n options?: UseStoreOptions<Value<T, P>>,\n): [value: Value<T, P>, setValue: Store<Value<T, P>>['set']];\nfunction boundUseProp<T>(\n this: Store<T>,\n options?: UseStoreOptions<T>,\n): [value: T, setValue: Store<T>['set']];\nfunction boundUseProp(this: Store<any>, ...args: any[]) {\n return useProp(this, ...args);\n}\n\nexport const storeMethods: {\n useStore: typeof boundUseStore;\n useProp: typeof boundUseProp;\n} = {\n useStore: boundUseStore,\n useProp: boundUseProp,\n};\n"],"mappings":";;;;;;;;;AAGA,MAAM,oBAAoC,uBAAO;AAKjD,SAAgB,cACd,OACA,SAAsCA,8BACpB;AAClB,KAAI,CAACC,iCAAc,UAAU,CAAC,MAAM,QAAQ,OAC1C,QAAO,CAAC,QAAQ,UAAU,OAAO,OAAO;AAI1C,SAAS,MAAc,sBAAsB;CAE7C,MAAM,OAAO,IAAI;CACjB,MAAM,cAAc,IAAI;CACxB,IAAI,UAAU;CAEd,SAAS,iBAAiB,WAAgB,GAAG,MAAa;EACxD,MAAM,CAAC,cAAcC,UAAQ,UAAU,cAAc,UAAU,OAAO,GAAG;AAEzE,OAAK,MAAM,eAAe;AACxB,OAAI,CAACD,iCAAc,eAAe,CAAC,MAAM,QAAQ,YAC/C,QAAO;AAGT,UAAOC,SAAO,UAAU,YAAY,GAAG;;AAGzC,MAAI,OACF,aAAY,KAAK;AAGnB,SAAO;;CAGT,SAAS,gBAAgB,WAAgB,GAAG,MAAa;EACvD,MAAM,kBAAkB,UAAU,OAAO,GAAG;AAE5C,OAAK,MAAM,eAAe;AACxB,UAAO,UAAU,YAAY,GAAG,UAAU;;AAG5C,SAAO;;CAGT,MAAM,QAAQ,IAAI,MAAM,OAAsB;EAC5C,IAAI,QAAQ,GAAG,UAAU;AACvB,OAAI,MAAM,kBACR,QAAO;AAGT,OAAI,QACF,QAAO,OAAO;GAGhB,MAAM,EAAE,UAAU,iBAAiB,OAAO,yBAAyB,QAAQ,MAAM;AACjF,OAAI,aAAa,SAAS,iBAAiB,MACzC,QAAO,OAAO;AAGhB,UAAO,iBAAiB,QAAQ,KAAK,GAAG;;EAG1C,yBAAyB,QAAQ,GAAG;GAClC,MAAM,EAAE,UAAU,iBAAiB,OAAO,yBAAyB,QA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