cross-state 0.6.3 → 0.6.4

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 (56) hide show
  1. package/README.md +3 -3
  2. package/dist/cjs/hash.cjs +364 -282
  3. package/dist/cjs/hash.cjs.map +1 -1
  4. package/dist/cjs/immer.cjs +1 -1
  5. package/dist/cjs/immer.cjs.map +1 -1
  6. package/dist/cjs/index.cjs +175 -172
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/react.cjs +44 -8
  9. package/dist/cjs/react.cjs.map +1 -1
  10. package/dist/es/hash.mjs +365 -283
  11. package/dist/es/hash.mjs.map +1 -1
  12. package/dist/es/immer.mjs +1 -1
  13. package/dist/es/immer.mjs.map +1 -1
  14. package/dist/es/index.mjs +178 -175
  15. package/dist/es/index.mjs.map +1 -1
  16. package/dist/es/react.mjs +53 -17
  17. package/dist/es/react.mjs.map +1 -1
  18. package/dist/types/core/cache.d.ts +56 -0
  19. package/dist/types/core/commonTypes.d.ts +5 -5
  20. package/dist/types/core/index.d.ts +5 -8
  21. package/dist/types/core/resourceGroup.d.ts +9 -6
  22. package/dist/types/core/store.d.ts +40 -21
  23. package/dist/types/immer/immerActions.d.ts +1 -1
  24. package/dist/types/index.d.ts +2 -2
  25. package/dist/types/lib/applyPatches.d.ts +2 -0
  26. package/dist/types/lib/cacheState.d.ts +19 -0
  27. package/dist/types/lib/calculationHelper.d.ts +3 -3
  28. package/dist/types/lib/clone.d.ts +1 -0
  29. package/dist/types/lib/debounce.d.ts +6 -0
  30. package/dist/types/lib/diff.d.ts +14 -7
  31. package/dist/types/lib/{cache.d.ts → instanceCache.d.ts} +1 -1
  32. package/dist/types/lib/makeSelector.d.ts +2 -1
  33. package/dist/types/lib/maybeAsync.d.ts +3 -0
  34. package/dist/types/lib/path.d.ts +14 -0
  35. package/dist/types/lib/propAccess.d.ts +5 -12
  36. package/dist/types/lib/queue.d.ts +4 -2
  37. package/dist/types/lib/standardMethods.d.ts +25 -0
  38. package/dist/types/lib/throttle.d.ts +2 -1
  39. package/dist/types/lib/typeHelpers.d.ts +8 -0
  40. package/dist/types/persist/index.d.ts +3 -0
  41. package/dist/types/persist/persist.d.ts +33 -0
  42. package/dist/types/persist/persistPathHelpers.d.ts +6 -0
  43. package/dist/types/persist/persistStorage.d.ts +14 -0
  44. package/dist/types/react/index.d.ts +3 -4
  45. package/dist/types/react/read.d.ts +3 -4
  46. package/dist/types/react/storeScope.d.ts +1 -1
  47. package/dist/types/react/useCache.d.ts +14 -0
  48. package/dist/types/react/useProp.d.ts +3 -3
  49. package/dist/types/react/useStore.d.ts +1 -1
  50. package/package.json +53 -44
  51. package/dist/types/core/derivedStore.d.ts +0 -38
  52. package/dist/types/core/fetchStore.d.ts +0 -76
  53. package/dist/types/core/once.d.ts +0 -13
  54. package/dist/types/lib/storeActions.d.ts +0 -28
  55. package/react.d.ts +0 -1
  56. package/react.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../src/lib/cache.ts","../../src/core/resourceGroup.ts","../../src/core/fetchStore.ts","../../src/core/once.ts"],"sourcesContent":["import { hash } from './hash';\n\nexport class Cache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef?: WeakRef<T> }>();\n private interval = this.cacheTime ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1)) : undefined;\n\n constructor(private factory: (...args: Args) => T, private cacheTime?: number) {}\n\n cleanup() {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of [...this.cache.entries()]) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args) {\n const key = hash(args);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: typeof WeakRef !== 'undefined' ? new WeakRef(value) : undefined,\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ?? value;\n }\n\n return value;\n }\n\n values() {\n return [...this.cache.values()].map((entry) => entry.ref ?? entry.weakRef?.deref()).filter((value): value is T => !!value);\n }\n\n stop() {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats() {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","export interface Resource {\n invalidate(): void;\n clear(): void;\n}\n\nexport class ResourceGroup extends Set<Resource> {\n invalidateAll() {\n for (const resource of this) {\n resource.invalidate();\n }\n }\n\n clearAll() {\n for (const resource of this) {\n resource.clear();\n }\n }\n}\n\nexport const _allResources = new ResourceGroup();\nexport const allResources = {\n invalidateAll: _allResources.invalidateAll.bind(_allResources),\n clearAll: _allResources.clearAll.bind(_allResources),\n};\n","import { Cache } from '@lib/cache';\nimport { calcDuration } from '@lib/calcDuration';\nimport { CalculationHelper } from '@lib/calculationHelper';\nimport { defaultEquals, simpleShallowEquals } from '@lib/equals';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/propAccess';\nimport type { Cancel, Duration, Listener, Selector, SubscribeOptions, Update, Use, UseFetch } from './commonTypes';\nimport type { ResourceGroup } from './resourceGroup';\nimport { _allResources } from './resourceGroup';\nimport { Store } from './store';\n\ntype Common<T> = { isUpdating: false; update?: undefined; ref: unknown } | { isUpdating: true; update: Promise<T>; ref: unknown };\ntype WithValue<T> = { status: 'value'; value: T; error?: undefined; isStale: boolean } & Common<T>;\ntype WithError<T> = { status: 'error'; value?: undefined; error: unknown; isStale: boolean } & Common<T>;\ntype Pending<T> = { status: 'pending'; value?: undefined; error?: undefined; isStale: true } & Common<T>;\nexport type FetchStoreState<T> = WithValue<T> | WithError<T> | Pending<T>;\n\nexport interface FetchOptions {\n cache?: 'updateWhenStale' | 'backgroundUpdate' | 'forceUpdate';\n}\n\nexport interface FetchFn<T, Args extends any[] = []> {\n (this: { use: Use; useFetch: UseFetch }, ...args: Args): Promise<T>;\n}\n\nexport interface FetchStoreOptions<T> {\n invalidateAfter?: Duration | ((state: FetchStoreState<T>) => Duration);\n clearAfter?: Duration | ((state: FetchStoreState<T>) => Duration);\n resourceGroup?: ResourceGroup | ResourceGroup[];\n retain?: number;\n clearUnusedAfter?: Duration;\n // parentStore?: { store: Store<any>; selectors: (Selector<any, any> | string)[] };\n}\n\nconst fetchStoreStateEquals =\n (equals = defaultEquals) =>\n (a: FetchStoreState<any>, b: FetchStoreState<any>) => {\n const { value: av, ...ar } = a;\n const { value: bv, ...br } = b;\n return simpleShallowEquals(ar, br) && (ar.status !== 'value' || equals(av, bv));\n };\n\nconst createRef = () => Math.random().toString(36).slice(2);\n\nexport class FetchStore<T> extends Store<FetchStoreState<T>> {\n calculationHelper = new CalculationHelper({\n calculate: ({ use, useFetch }) => {\n const promise = this.fetchFn.apply({ use, useFetch });\n this.setPromise(promise);\n },\n\n addEffect: this.addEffect,\n getValue: () => this.value.value,\n setValue: this.setValue,\n setError: this.setError,\n onInvalidate: this.invalidate,\n });\n\n constructor(protected fetchFn: FetchFn<T>, protected options: FetchStoreOptions<T> = {}) {\n super({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n ref: createRef(),\n });\n }\n\n update(value: Update<FetchStoreState<T>>): void {\n this.calculationHelper.stop();\n super.update(value);\n }\n\n async fetch(options?: FetchOptions): Promise<T> {\n this.calculationHelper.check();\n\n const { cache = 'updateWhenStale' } = options ?? {};\n const { status, value, error, update, isStale } = this.value;\n\n if (((status === 'pending' || isStale) && !update) || cache === 'forceUpdate') {\n this.calculationHelper.execute();\n\n if (status === 'pending' || cache !== 'backgroundUpdate') {\n return this.value.update!;\n }\n }\n\n if (status === 'value') {\n return value;\n }\n\n if (status === 'error') {\n throw error;\n }\n\n return update;\n }\n\n setValue(value: T | Promise<T>): void {\n if (value instanceof Promise) {\n this.calculationHelper.stop();\n this.setPromise(value);\n } else {\n this.update({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n ref: createRef(),\n });\n }\n }\n\n protected setPromise(promise: Promise<T>) {\n const ref = createRef();\n\n super.update({\n ...this.value,\n isUpdating: true,\n update: promise,\n ref,\n });\n\n promise\n .then((value) => {\n if (promise === this.value.update) {\n super.update({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n ref,\n });\n }\n })\n .catch((error) => {\n if (promise === this.value.update) {\n super.update({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n ref,\n });\n }\n });\n }\n\n setError(error: unknown): void {\n this.update({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n ref: createRef(),\n });\n }\n\n invalidate(): void {\n this.update({\n ...this.value,\n isStale: true,\n isUpdating: false,\n update: undefined,\n });\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n\n clear(): void {\n this.update({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n ref: createRef(),\n });\n\n if (this.isActive) {\n this.calculationHelper.execute();\n }\n }\n\n sub(listener: Listener<FetchStoreState<T>>, options?: SubscribeOptions): Cancel {\n return super.sub(listener, {\n ...options,\n equals: fetchStoreStateEquals(options?.equals),\n });\n }\n\n mapValue<S>(selector: Selector<T, S>): FetchStore<S>;\n mapValue<P extends Path<T>>(selector: P): FetchStore<Value<T, P>>;\n mapValue<S>(_selector: Selector<T, S> | string): FetchStore<S> {\n const selector = makeSelector(_selector);\n const that = this;\n\n return new FetchStore(async function () {\n const value: T = await this.useFetch(that);\n return selector(value);\n });\n }\n}\n\nconst defaultOptions: FetchStoreOptions<unknown> = {};\n\nfunction create<T>(fetch: FetchFn<T>, options?: FetchStoreOptions<T>): FetchStore<T> {\n return withArgs(fetch, options)();\n}\n\nfunction withArgs<T, Args extends any[]>(\n fetch: FetchFn<T, Args>,\n options?: FetchStoreOptions<T>\n): {\n (...args: Args): FetchStore<T>;\n invalidate: () => void;\n clear: () => void;\n} {\n const { clearUnusedAfter = defaultOptions.clearUnusedAfter ?? 0, resourceGroup } = options ?? {};\n\n const cache = new Cache(\n (...args: Args) =>\n new FetchStore(function () {\n return fetch.apply(this, args);\n }, options),\n calcDuration(clearUnusedAfter)\n );\n\n const get = (...args: Args) => {\n return cache.get(...args);\n };\n\n const invalidate = () => {\n for (const instance of cache.values()) {\n instance.invalidate();\n }\n };\n\n const clear = () => {\n for (const instance of cache.values()) {\n instance.clear();\n }\n };\n\n const resource = { invalidate, clear };\n const groups = Array.isArray(resourceGroup) ? resourceGroup : resourceGroup ? [resourceGroup] : [];\n for (const group of groups.concat(_allResources)) {\n group.add(resource);\n }\n\n return Object.assign(get, resource);\n}\n\nexport const fetchStore = Object.assign(create, {\n withArgs,\n defaultOptions,\n});\n","import type { Cancel, Listener } from './commonTypes';\n\ninterface Subscribe<T> {\n (listener: Listener<T>, options?: { runNow?: boolean }): Cancel;\n}\n\nexport function once<T, S extends T>(subscribe: Subscribe<T>, condition: (value: T) => value is S): Promise<S>;\nexport function once<T>(subscribe: Subscribe<T>, condition?: (value: T) => boolean): Promise<T>;\nexport function once<T>(subscribe: Subscribe<T>, condition?: (value: T) => boolean) {\n return new Promise<T>((resolve) => {\n let stopped = false;\n const cancel = subscribe(\n (value) => {\n if (stopped || (condition && !condition(value))) {\n return;\n }\n\n resolve(value);\n stopped = true;\n setTimeout(() => cancel());\n },\n {\n runNow: !!condition,\n }\n );\n });\n}\n\nexport function onceValue<T>(subscribe: Subscribe<{ value?: T; error?: unknown }>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let stopped = false;\n const cancel = subscribe(({ value, error }) => {\n if (stopped || (value === undefined && error === undefined)) {\n return;\n }\n\n if (value !== undefined) {\n resolve(value);\n } else {\n reject(error);\n }\n\n stopped = true;\n setTimeout(() => cancel());\n });\n });\n}\n"],"names":["a","b"],"mappings":";;AAEO,MAAM,MAA4C;AAAA,EAIv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AU;AACT,YAAI,WAAY,aAAa,CAAC,UAAU,KAAK,GAAI;AAC/C;AAAA,QACF;AAEA,gBAAQ,KAAK;AACH,kBAAA;AACC,mBAAA,MAAM,QAAQ;AAAA,MAC3B;AAAA,MACA;AAAA,QACE,QAAQ,CAAC,CAAC;AAAA,MACZ;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../src/core/resourceGroup.ts","../../src/lib/instanceCache.ts","../../src/core/cache.ts"],"sourcesContent":["import { bind } from '@lib/bind';\n\nexport interface Resource {\n invalidate(): void;\n clear(): void;\n}\n\nexport class ResourceGroup {\n private refMap = new WeakMap<Resource, WeakRef<Resource>>();\n\n private refSet = new Set<WeakRef<Resource>>();\n\n constructor(public readonly name?: string) {\n bind(this);\n }\n\n add(resource: Resource) {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource) {\n const ref = this.refMap.get(resource);\n if (ref) {\n this.refMap.delete(resource);\n this.refSet.delete(ref);\n }\n }\n\n invalidateAll() {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidate();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll() {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clear();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources = new ResourceGroup();\n\nexport function createResourceGroup(name?: string) {\n return new ResourceGroup(name);\n}\n","import { hash } from './hash';\n\nexport class InstanceCache<Args extends any[], T extends object> {\n private cache = new Map<string, { t: number; ref?: T; weakRef: WeakRef<T> }>();\n\n private interval = this.cacheTime\n ? setInterval(() => this.cleanup(), Math.max(this.cacheTime / 10, 1))\n : undefined;\n\n constructor(private factory: (...args: Args) => T, private cacheTime?: number) {}\n\n cleanup() {\n const cutoff = this.now() - (this.cacheTime ?? 0);\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.ref && entry.t <= cutoff) {\n delete entry.ref;\n }\n\n if (!entry.ref && !entry.weakRef?.deref()) {\n this.cache.delete(key);\n }\n }\n }\n\n get(...args: Args) {\n const key = hash(args);\n let entry = this.cache.get(key);\n let value = entry?.ref ?? entry?.weakRef?.deref();\n\n if (!entry || !value) {\n value = this.factory(...args);\n entry = {\n t: this.now(),\n ref: value,\n weakRef: new WeakRef(value),\n };\n\n this.cache.set(key, entry);\n } else {\n entry.t = this.now();\n entry.ref ??= value;\n }\n\n return value;\n }\n\n values() {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop() {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats() {\n return {\n count: this.cache.size,\n withRef: [...this.cache.values()].filter((x) => !!x.ref).length,\n withWeakRef: [...this.cache.values()].filter((x) => !!x.weakRef?.deref()).length,\n };\n }\n\n private now() {\n return performance.now();\n }\n}\n","import type { Duration, Selector, Use } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { createStore, Store } from './store';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport type { Path, Value } from '@lib/path';\n\nexport interface CacheGetOptions {\n update?: 'whenMissing' | 'whenStale' | 'force';\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (this: { use: Use }, ...args: Args): Promise<T>;\n}\n\nexport interface CacheOptions<T> {\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | undefined);\n clearAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | undefined);\n resourceGroup?: ResourceGroup | ResourceGroup[];\n retain?: number;\n clearUnusedAfter?: Duration;\n}\n\nexport class Cache<T> extends Store<Promise<T>> {\n readonly state = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected timers = new Set<ReturnType<typeof setTimeout>>();\n\n constructor(\n getter: CacheFunction<T>,\n public readonly options: CacheOptions<T> = {},\n derivedFrom?: { store: Store<any>; selectors: (Selector<any, any> | Path<any>)[] },\n ) {\n super(getter, options, derivedFrom);\n this.watchPromise();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}) {\n const promise = this._value?.v;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculationHelper.execute();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return super.get();\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n invalidate({ invalidateDependencies = true }: { invalidateDependencies?: boolean } = {}) {\n if (invalidateDependencies) {\n this.calculationHelper.invalidateDependencies();\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this._value?.v;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.reset();\n }\n\n clear({ invalidateDependencies = true }: { invalidateDependencies?: boolean } = {}): void {\n if (invalidateDependencies) {\n this.calculationHelper.invalidateDependencies();\n }\n\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n });\n delete this.stalePromise;\n super.reset();\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S>;\n\n mapValue<P extends Path<T>>(selector: P): Cache<Value<T, P>>;\n\n mapValue<S>(_selector: Selector<T, S> | Path<any>): Cache<S> {\n const selector = makeSelector(_selector);\n const that = this;\n\n return new Cache(async function () {\n const value = await this.use(that);\n return selector(value);\n });\n }\n\n protected watchPromise() {\n this.sub(\n async (promise) => {\n this.state.set((state) => ({\n ...state,\n isUpdating: true,\n }));\n\n this.setTimers();\n\n try {\n const value = await promise;\n\n if (promise !== this._value?.v) {\n return;\n }\n\n this.state.set({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n });\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this._value?.v) {\n return;\n }\n\n this.state.set({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n });\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers() {\n for (const timer of this.timers) {\n clearTimeout(timer);\n }\n this.timers.clear();\n\n const state = this.state.get();\n let { invalidateAfter, clearAfter } = this.options;\n const ref = new WeakRef(this);\n\n if (state.status === 'pending') {\n return;\n }\n\n if (invalidateAfter instanceof Function) {\n invalidateAfter = invalidateAfter(state);\n }\n\n if (invalidateAfter) {\n this.timers.add(setTimeout(() => ref?.deref()?.invalidate(), calcDuration(invalidateAfter)));\n }\n\n if (clearAfter instanceof Function) {\n clearAfter = clearAfter(state);\n }\n\n if (clearAfter) {\n this.timers.add(setTimeout(() => ref?.deref()?.clear(), calcDuration(clearAfter)));\n }\n }\n}\n\nconst defaultOptions: CacheOptions<unknown> = {};\n\nfunction create<T>(cacheFunction: CacheFunction<T>, options?: CacheOptions<T>): Cache<T> {\n return withArgs(cacheFunction, options)();\n}\n\nfunction withArgs<T, Args extends any[]>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T>,\n): {\n (...args: Args): Cache<T>;\n invalidate: () => void;\n clear: () => void;\n} {\n const { clearUnusedAfter = defaultOptions.clearUnusedAfter ?? 0, resourceGroup } = options ?? {};\n\n const cache = new InstanceCache(\n (...args: Args) =>\n new Cache(function () {\n return cacheFunction.apply(this, args);\n }, options),\n calcDuration(clearUnusedAfter),\n );\n\n const get = (...args: Args) => {\n return cache.get(...args);\n };\n\n const invalidate = () => {\n for (const instance of cache.values()) {\n instance.invalidate();\n }\n };\n\n const clear = () => {\n for (const instance of cache.values()) {\n instance.clear();\n }\n };\n\n const resource = { invalidate, clear };\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n for (const group of groups.concat(allResources)) {\n group.add(resource);\n }\n\n return Object.assign(get, resource);\n}\n\nexport const createCache = Object.assign(create, {\n withArgs,\n defaultOptions,\n});\n"],"names":[],"mappings":";;AAOO,MAAM,cAAc;AAAA,EAKzB,YAA4B,MAAe;AAAf,SAAA,OAAA;AAJpB,SAAA,6BAAa;AAEb,SAAA,6BAAa;AAGnB,SAAK,IAAI;AAAA,EACX;AAAA,EAEA,IAAI,UAAoB;AAChB,UAAA,MAAM,IAAI,QAAQ,QAAQ;AAC3B,SAAA,OAAO,IAAI,UAAU,GAAG;AACxB,SAAA,OAAO,IAAI,GAAG;AAAA,EACrB;AAAA,EAEA,OAAO,UAAoB;AACzB,UAAM,MAAM,KAAK,OAAO,IAAI,QAAQ;AACpC,QAAI,KAAK;AACF,WAAA,OAAO,OAAO,QAAQ;AACtB,WAAA,OAAO,OAAO,GAAG;AAAA,IACxB;AAAA,EACF;AAAA,EAEA,gBAAgB;AACH,eAAA,OAAO,KAAK,QAAQ;AACvB,YAAA,WAAW,IAAI;AACrB,UAAI,UAAU;AACZ,iBAAS,WAAW;AAAA,MAAA,OACf;AACA,aAAA,OAAO,OAAO,GAAG;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,WAAW;AACE,eAAA,OAAO,KAAK,QAAQ;AACvB,YAAA,WAAW,IAAI;AACrB,UAAI,UAAU;AACZ,iBAAS,MAAM;AAAA,MAAA,OACV;AACA,aAAA,OAAO,OAAO,GAAG;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AACF;AAEa,MAAA,eAAe,IAAI,cAAc;AAEvC,SAAS,oBAAoB,MAAe;AAC1C,SAAA,IAAI,cAAc,IAAI;AAC/B;ACvDO,MAAM,cAAoD;AAAA,EAO/D,YAAoB,SAAuC,WAAoB;AAA3D,SAAA,UAAA;AAAuC,SAAA,YAAA;AANnD,SAAA,4BAAY;AAEpB,SAAQ,WAAW,KAAK,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C,eAAS,WAAW;AAAA,IACtB;AAAA,EAAA;AAGF,QAAM,QAAQ,MAAM;AACP,eAAA,YAAY,MAAM,UAAU;AACrC,eAAS,MAAM;AAAA,IACjB;AAAA,EAAA;AAGI,QAAA,WAAW,EAAE,YAAY;AACzB,QAAA,SAAS,MAAM,QAAQ,aAAa,IACtC,gBACA,gBACA,CAAC,aAAa,IACd;AACJ,aAAW,SAAS,OAAO,OAAO,YAAY,GAAG;AAC/C,UAAM,IAAI,QAAQ;AAAA,EACpB;AAEO,SAAA,OAAO,OAAO,KAAK,QAAQ;AACpC;AAEa,MAAA,cAAc,OAAO,OAAO,QAAQ;AAAA,EAC/C;AAAA,EACA;AACF,CAAC;"}
package/dist/es/react.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { h as hash, t as trackingProxy, g as store } from "./hash.mjs";
2
- import require$$0, { useRef, useCallback, useLayoutEffect, useDebugValue, useMemo, useContext, createContext } from "react";
1
+ import require$$0, { useRef, useCallback, useLayoutEffect, useDebugValue, useMemo, useEffect, useContext, createContext } from "react";
2
+ import { h as hash, t as trackingProxy, c as createStore } from "./hash.mjs";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  var withSelectorExports = {};
5
5
  var withSelector = {
@@ -11,6 +11,15 @@ var withSelector = {
11
11
  }
12
12
  };
13
13
  var useSyncExternalStoreWithSelector_production_min = {};
14
+ /**
15
+ * @license React
16
+ * use-sync-external-store-with-selector.production.min.js
17
+ *
18
+ * Copyright (c) Facebook, Inc. and its affiliates.
19
+ *
20
+ * This source code is licensed under the MIT license found in the
21
+ * LICENSE file in the root directory of this source tree.
22
+ */
14
23
  var hasRequiredUseSyncExternalStoreWithSelector_production_min;
15
24
  function requireUseSyncExternalStoreWithSelector_production_min() {
16
25
  if (hasRequiredUseSyncExternalStoreWithSelector_production_min)
@@ -68,6 +77,15 @@ function requireUseSyncExternalStoreWithSelector_production_min() {
68
77
  return useSyncExternalStoreWithSelector_production_min;
69
78
  }
70
79
  var useSyncExternalStoreWithSelector_development = {};
80
+ /**
81
+ * @license React
82
+ * use-sync-external-store-with-selector.development.js
83
+ *
84
+ * Copyright (c) Facebook, Inc. and its affiliates.
85
+ *
86
+ * This source code is licensed under the MIT license found in the
87
+ * LICENSE file in the root directory of this source tree.
88
+ */
71
89
  var hasRequiredUseSyncExternalStoreWithSelector_development;
72
90
  function requireUseSyncExternalStoreWithSelector_development() {
73
91
  if (hasRequiredUseSyncExternalStoreWithSelector_development)
@@ -84,7 +102,7 @@ function requireUseSyncExternalStoreWithSelector_development() {
84
102
  }
85
103
  var objectIs = typeof Object.is === "function" ? Object.is : is;
86
104
  var useSyncExternalStore = React.useSyncExternalStore;
87
- var useRef2 = React.useRef, useEffect = React.useEffect, useMemo2 = React.useMemo, useDebugValue2 = React.useDebugValue;
105
+ var useRef2 = React.useRef, useEffect2 = React.useEffect, useMemo2 = React.useMemo, useDebugValue2 = React.useDebugValue;
88
106
  function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
89
107
  var instRef = useRef2(null);
90
108
  var inst;
@@ -141,7 +159,7 @@ function requireUseSyncExternalStoreWithSelector_development() {
141
159
  return [getSnapshotWithSelector, getServerSnapshotWithSelector];
142
160
  }, [getSnapshot, getServerSnapshot, selector, isEqual]), getSelection = _useMemo[0], getServerSelection = _useMemo[1];
143
161
  var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
144
- useEffect(function() {
162
+ useEffect2(function() {
145
163
  inst.hasValue = true;
146
164
  inst.value = value;
147
165
  }, [value]);
@@ -163,18 +181,19 @@ function requireUseSyncExternalStoreWithSelector_development() {
163
181
  module.exports = requireUseSyncExternalStoreWithSelector_development();
164
182
  }
165
183
  })(withSelector);
166
- function useStore(store2, options) {
184
+ function useStore(store, options) {
167
185
  const lastEqualsRef = useRef();
168
- const subOptions = { ...options, runNow: false, equals: void 0 };
186
+ const subOptions = { ...options, runNow: false, equals: void 0, passive: false };
169
187
  const subscribe = useCallback(
170
188
  (listener) => {
171
- return store2.sub(listener, subOptions);
189
+ return store.sub(listener, subOptions);
172
190
  },
173
- [store2, hash(subOptions)]
191
+ [store, hash(subOptions)]
174
192
  );
175
193
  const value = withSelectorExports.useSyncExternalStoreWithSelector(
194
+ //
176
195
  subscribe,
177
- store2.get,
196
+ store.get,
178
197
  void 0,
179
198
  (x) => x,
180
199
  (options == null ? void 0 : options.equals) ?? ((_v, newValue) => {
@@ -189,41 +208,58 @@ function useStore(store2, options) {
189
208
  useDebugValue(value);
190
209
  return proxiedValue;
191
210
  }
192
- function read(store2, options) {
193
- const { status, value, error } = useStore(store2, options);
211
+ function useCache(cache, { passive, ...options } = {}) {
212
+ const mappedStore = useMemo(
213
+ () => cache.state.map(
214
+ (state) => Object.assign(
215
+ [state.value, state.error, state.isUpdating, state.isStale],
216
+ state
217
+ )
218
+ ),
219
+ [cache]
220
+ );
221
+ useEffect(() => !passive ? cache.sub(() => void 0) : void 0, [cache, passive]);
222
+ return useStore(mappedStore, options);
223
+ }
224
+ function read(cache, options) {
225
+ const { status, value, error } = useCache(cache, options);
194
226
  if (status === "value") {
195
227
  return value;
196
228
  }
197
229
  if (status === "error") {
198
230
  throw error;
199
231
  }
200
- throw store2.fetch();
232
+ throw cache.state.once((state) => state.status !== "pending");
201
233
  }
202
234
  const contextMap = /* @__PURE__ */ new WeakMap();
203
235
  function getStoreScopeContext(scope) {
204
236
  let context = contextMap.get(scope);
205
237
  if (!context) {
206
- context = createContext(store(scope.defaultValue));
238
+ context = createContext(createStore(scope.defaultValue));
207
239
  contextMap.set(scope, context);
208
240
  }
209
241
  return context;
210
242
  }
211
243
  function StoreScopeProvider({ scope, store: inputStore, children }) {
212
244
  const context = getStoreScopeContext(scope);
213
- const currentStore = useMemo(() => inputStore ?? store(scope.defaultValue), [scope, inputStore]);
245
+ const currentStore = useMemo(
246
+ () => inputStore ?? createStore(scope.defaultValue),
247
+ [scope, inputStore]
248
+ );
214
249
  return /* @__PURE__ */ jsx(context.Provider, { value: currentStore, children });
215
250
  }
216
251
  function useStoreScope(scope) {
217
252
  const context = getStoreScopeContext(scope);
218
253
  return useContext(context);
219
254
  }
220
- function useProp(store2, options) {
221
- const value = useStore(store2, options);
222
- return [value, store2.update];
255
+ function useProp(store, options) {
256
+ const value = useStore(store, options);
257
+ return [value, store.set];
223
258
  }
224
259
  export {
225
260
  StoreScopeProvider,
226
261
  read,
262
+ useCache,
227
263
  useProp,
228
264
  useStore,
229
265
  useStoreScope
@@ -1 +1 @@
1
- {"version":3,"file":"react.mjs","sources":["../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.production.min.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.development.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/with-selector.js","../../src/react/useStore.ts","../../src/react/read.ts","../../src/react/storeScope.tsx","../../src/react/useProp.ts"],"sourcesContent":["/**\n * @license React\n * use-sync-external-store-with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var g=require(\"react\");function n(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var p=\"function\"===typeof Object.is?Object.is:n,q=g.useSyncExternalStore,r=g.useRef,t=g.useEffect,u=g.useMemo,v=g.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,h){var c=r(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=u(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==h&&f.hasValue){var b=f.value;if(h(b,a))return k=b}return k=a}b=k;if(p(d,a))return b;var e=l(a);if(void 0!==h&&h(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,h]);var d=q(a,c[0],c[1]);\nt(function(){f.hasValue=!0;f.value=d},[d]);v(d);return d};\n","/**\n * @license React\n * use-sync-external-store-with-selector.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar useSyncExternalStore = React.useSyncExternalStore;\n\n// for CommonJS interop.\n\nvar useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.\n\nfunction useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {\n // Use this to track the rendered snapshot.\n var instRef = useRef(null);\n var inst;\n\n if (instRef.current === null) {\n inst = {\n hasValue: false,\n value: null\n };\n instRef.current = inst;\n } else {\n inst = instRef.current;\n }\n\n var _useMemo = useMemo(function () {\n // Track the memoized state using closure variables that are local to this\n // memoized instance of a getSnapshot function. Intentionally not using a\n // useRef hook, because that state would be shared across all concurrent\n // copies of the hook/component.\n var hasMemo = false;\n var memoizedSnapshot;\n var memoizedSelection;\n\n var memoizedSelector = function (nextSnapshot) {\n if (!hasMemo) {\n // The first time the hook is called, there is no memoized result.\n hasMemo = true;\n memoizedSnapshot = nextSnapshot;\n\n var _nextSelection = selector(nextSnapshot);\n\n if (isEqual !== undefined) {\n // Even if the selector has changed, the currently rendered selection\n // may be equal to the new selection. We should attempt to reuse the\n // current value if possible, to preserve downstream memoizations.\n if (inst.hasValue) {\n var currentSelection = inst.value;\n\n if (isEqual(currentSelection, _nextSelection)) {\n memoizedSelection = currentSelection;\n return currentSelection;\n }\n }\n }\n\n memoizedSelection = _nextSelection;\n return _nextSelection;\n } // We may be able to reuse the previous invocation's result.\n\n\n // We may be able to reuse the previous invocation's result.\n var prevSnapshot = memoizedSnapshot;\n var prevSelection = memoizedSelection;\n\n if (objectIs(prevSnapshot, nextSnapshot)) {\n // The snapshot is the same as last time. Reuse the previous selection.\n return prevSelection;\n } // The snapshot has changed, so we need to compute a new selection.\n\n\n // The snapshot has changed, so we need to compute a new selection.\n var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n\n // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {\n return prevSelection;\n }\n\n memoizedSnapshot = nextSnapshot;\n memoizedSelection = nextSelection;\n return nextSelection;\n }; // Assigning this to a constant so that Flow knows it can't change.\n\n\n // Assigning this to a constant so that Flow knows it can't change.\n var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;\n\n var getSnapshotWithSelector = function () {\n return memoizedSelector(getSnapshot());\n };\n\n var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n };\n return [getSnapshotWithSelector, getServerSnapshotWithSelector];\n }, [getSnapshot, getServerSnapshot, selector, isEqual]),\n getSelection = _useMemo[0],\n getServerSelection = _useMemo[1];\n\n var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);\n useEffect(function () {\n inst.hasValue = true;\n inst.value = value;\n }, [value]);\n useDebugValue(value);\n return value;\n}\n\nexports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/use-sync-external-store-with-selector.production.min.js');\n} else {\n module.exports = require('./cjs/use-sync-external-store-with-selector.development.js');\n}\n","import type { SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { hash } from '@lib/hash';\nimport { trackingProxy } from '@lib/trackingProxy';\nimport { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';\n\nexport type UseStoreOptions = Omit<SubscribeOptions, 'runNow'>;\n\nexport function useStore<T>(store: Store<T>, options?: UseStoreOptions): T {\n const lastEqualsRef = useRef<(newValue: T) => boolean>();\n\n const subOptions = { ...options, runNow: false, equals: undefined };\n\n const subscribe = useCallback(\n (listener: () => void) => {\n return store.sub(listener, subOptions);\n },\n [store, hash(subOptions)]\n );\n\n const value = useSyncExternalStoreWithSelector(\n //\n subscribe,\n store.get,\n undefined,\n (x) => x,\n options?.equals ?? ((_v, newValue) => lastEqualsRef.current?.(newValue) ?? false)\n );\n const [proxiedValue, equals] = trackingProxy(value);\n\n useLayoutEffect(() => {\n lastEqualsRef.current = equals;\n });\n\n useDebugValue(value);\n return proxiedValue;\n}\n","import type { FetchStore } from '@core/fetchStore';\nimport type { SubscribeOptions } from '@core/commonTypes';\nimport { useStore } from './useStore';\n\nexport type UseStoreOptions = Omit<SubscribeOptions, 'runNow'>;\n\nexport function read<T>(store: FetchStore<T>, options?: UseStoreOptions): T {\n const { status, value, error } = useStore(store, options);\n\n if (status === 'value') {\n return value;\n }\n\n if (status === 'error') {\n throw error;\n }\n\n throw store.fetch();\n}\n","import type { Store } from '@core/store';\nimport { store } from '@core/store';\nimport type { StoreScope } from '@core/storeScope';\nimport type { Context, ReactNode } from 'react';\nimport { createContext, useContext, useMemo } from 'react';\n\nexport type StoreScopeProps<T> = { scope: StoreScope<T>; store?: Store<T>; children?: ReactNode };\n\nexport const contextMap = new WeakMap<StoreScope<any>, Context<Store<any>>>();\n\nexport function getStoreScopeContext<T>(scope: StoreScope<T>): Context<Store<T>> {\n let context = contextMap.get(scope);\n\n if (!context) {\n context = createContext<Store<T>>(store(scope.defaultValue));\n contextMap.set(scope, context);\n }\n\n return context;\n}\n\nexport function StoreScopeProvider<T>({ scope, store: inputStore, children }: StoreScopeProps<T>) {\n const context = getStoreScopeContext(scope);\n const currentStore = useMemo(() => inputStore ?? store(scope.defaultValue), [scope, inputStore]);\n\n return <context.Provider value={currentStore}>{children}</context.Provider>;\n}\n\nexport function useStoreScope<T>(scope: StoreScope<T>): Store<T> {\n const context = getStoreScopeContext(scope);\n return useContext(context);\n}\n","import type { Store } from '@core/store';\nimport type { UpdateFn } from '@core/commonTypes';\nimport type { UseStoreOptions } from './useStore';\nimport { useStore } from './useStore';\n\nexport function useProp<T>(store: Store<T>, options?: UseStoreOptions): [value: T, setValue: UpdateFn<T>] {\n const value = useStore(store, options);\n\n return [value, store.update];\n}\n"],"names":["a","c","d","b","e","useRef","useMemo","useDebugValue","require$$0","require$$1","store","useSyncExternalStoreWithSelector"],"mappings":";;;;;;;;;;;;;;;;;;AASa,MAAI,IAAE;AAAiB,WAAS,EAAE,GAAE,GAAE;AAAC,WAAO,MAAI,MAAI,MAAI,KAAG,IAAE,MAAI,IAAE,MA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A,QAAWA,QAAiB,SAA8D;AAClG,QAAA,QAAQ,SAASA,QAAO,OAAO;AAE9B,SAAA,CAAC,OAAOA,OAAM,MAAM;AAC7B;"}
1
+ {"version":3,"file":"react.mjs","sources":["../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.production.min.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.development.js","../../node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/with-selector.js","../../src/react/useStore.ts","../../src/react/useCache.ts","../../src/react/read.ts","../../src/react/storeScope.tsx","../../src/react/useProp.ts"],"sourcesContent":["/**\n * @license React\n * use-sync-external-store-with-selector.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var g=require(\"react\");function n(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var p=\"function\"===typeof Object.is?Object.is:n,q=g.useSyncExternalStore,r=g.useRef,t=g.useEffect,u=g.useMemo,v=g.useDebugValue;\nexports.useSyncExternalStoreWithSelector=function(a,b,e,l,h){var c=r(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f}else f=c.current;c=u(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==h&&f.hasValue){var b=f.value;if(h(b,a))return k=b}return k=a}b=k;if(p(d,a))return b;var e=l(a);if(void 0!==h&&h(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return[function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,h]);var d=q(a,c[0],c[1]);\nt(function(){f.hasValue=!0;f.value=d},[d]);v(d);return d};\n","/**\n * @license React\n * use-sync-external-store-with-selector.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nif (process.env.NODE_ENV !== \"production\") {\n (function() {\n\n 'use strict';\n\n/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());\n}\n var React = require('react');\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar useSyncExternalStore = React.useSyncExternalStore;\n\n// for CommonJS interop.\n\nvar useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.\n\nfunction useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {\n // Use this to track the rendered snapshot.\n var instRef = useRef(null);\n var inst;\n\n if (instRef.current === null) {\n inst = {\n hasValue: false,\n value: null\n };\n instRef.current = inst;\n } else {\n inst = instRef.current;\n }\n\n var _useMemo = useMemo(function () {\n // Track the memoized state using closure variables that are local to this\n // memoized instance of a getSnapshot function. Intentionally not using a\n // useRef hook, because that state would be shared across all concurrent\n // copies of the hook/component.\n var hasMemo = false;\n var memoizedSnapshot;\n var memoizedSelection;\n\n var memoizedSelector = function (nextSnapshot) {\n if (!hasMemo) {\n // The first time the hook is called, there is no memoized result.\n hasMemo = true;\n memoizedSnapshot = nextSnapshot;\n\n var _nextSelection = selector(nextSnapshot);\n\n if (isEqual !== undefined) {\n // Even if the selector has changed, the currently rendered selection\n // may be equal to the new selection. We should attempt to reuse the\n // current value if possible, to preserve downstream memoizations.\n if (inst.hasValue) {\n var currentSelection = inst.value;\n\n if (isEqual(currentSelection, _nextSelection)) {\n memoizedSelection = currentSelection;\n return currentSelection;\n }\n }\n }\n\n memoizedSelection = _nextSelection;\n return _nextSelection;\n } // We may be able to reuse the previous invocation's result.\n\n\n // We may be able to reuse the previous invocation's result.\n var prevSnapshot = memoizedSnapshot;\n var prevSelection = memoizedSelection;\n\n if (objectIs(prevSnapshot, nextSnapshot)) {\n // The snapshot is the same as last time. Reuse the previous selection.\n return prevSelection;\n } // The snapshot has changed, so we need to compute a new selection.\n\n\n // The snapshot has changed, so we need to compute a new selection.\n var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n\n // If a custom isEqual function is provided, use that to check if the data\n // has changed. If it hasn't, return the previous selection. That signals\n // to React that the selections are conceptually equal, and we can bail\n // out of rendering.\n if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {\n return prevSelection;\n }\n\n memoizedSnapshot = nextSnapshot;\n memoizedSelection = nextSelection;\n return nextSelection;\n }; // Assigning this to a constant so that Flow knows it can't change.\n\n\n // Assigning this to a constant so that Flow knows it can't change.\n var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;\n\n var getSnapshotWithSelector = function () {\n return memoizedSelector(getSnapshot());\n };\n\n var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n };\n return [getSnapshotWithSelector, getServerSnapshotWithSelector];\n }, [getSnapshot, getServerSnapshot, selector, isEqual]),\n getSelection = _useMemo[0],\n getServerSelection = _useMemo[1];\n\n var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);\n useEffect(function () {\n inst.hasValue = true;\n inst.value = value;\n }, [value]);\n useDebugValue(value);\n return value;\n}\n\nexports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\nif (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===\n 'function'\n) {\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());\n}\n \n })();\n}\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/use-sync-external-store-with-selector.production.min.js');\n} else {\n module.exports = require('./cjs/use-sync-external-store-with-selector.development.js');\n}\n","import { useCallback, useDebugValue, useLayoutEffect, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector.js';\nimport type { SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { hash } from '@lib/hash';\nimport { trackingProxy } from '@lib/trackingProxy';\n\nexport type UseStoreOptions = Omit<SubscribeOptions, 'runNow' | 'passive'>;\n\nexport function useStore<T>(store: Store<T>, options?: UseStoreOptions): T {\n const lastEqualsRef = useRef<(newValue: T) => boolean>();\n\n const subOptions = { ...options, runNow: false, equals: undefined, passive: false };\n\n const subscribe = useCallback(\n (listener: () => void) => {\n return store.sub(listener, subOptions);\n },\n [store, hash(subOptions)],\n );\n\n const value = useSyncExternalStoreWithSelector<T, T>(\n //\n subscribe,\n store.get,\n undefined,\n (x) => x,\n options?.equals ?? ((_v, newValue) => lastEqualsRef.current?.(newValue) ?? false),\n );\n const [proxiedValue, equals] = trackingProxy(value);\n\n useLayoutEffect(() => {\n lastEqualsRef.current = equals;\n });\n\n useDebugValue(value);\n return proxiedValue;\n}\n","import { useEffect, useMemo } from 'react';\nimport type { UseStoreOptions } from './useStore';\nimport { useStore } from './useStore';\nimport type { CacheState } from '@lib/cacheState';\nimport type { Cache } from '@core';\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 extends UseStoreOptions {\n passive?: boolean;\n}\n\nexport function useCache<T>(\n cache: Cache<T>,\n { passive, ...options }: UseCacheOptions = {},\n): UseCacheValue<T> {\n const mappedStore = useMemo(\n () =>\n cache.state.map((state) =>\n Object.assign<UseCacheArray<T>, CacheState<T>>(\n [state.value, state.error, state.isUpdating, state.isStale],\n state,\n ),\n ),\n [cache],\n );\n\n useEffect(() => (!passive ? cache.sub(() => undefined) : undefined), [cache, passive]);\n\n return useStore(mappedStore, options);\n}\n","import { useCache } from './useCache';\nimport type { UseStoreOptions } from './useStore';\nimport type { Cache } from '@core';\n\nexport function read<T>(cache: Cache<T>, options?: UseStoreOptions): T {\n const { status, value, error } = useCache(cache, options);\n\n if (status === 'value') {\n return value;\n }\n\n if (status === 'error') {\n throw error;\n }\n\n throw cache.state.once((state) => state.status !== 'pending');\n}\n","import type { Context, ReactNode } from 'react';\nimport { createContext, useContext, useMemo } from 'react';\nimport type { Store } from '@core/store';\nimport { createStore } from '@core/store';\nimport type { StoreScope } from '@core/storeScope';\n\nexport type StoreScopeProps<T> = { scope: StoreScope<T>; store?: Store<T>; children?: ReactNode };\n\nexport const contextMap = new WeakMap<StoreScope<any>, Context<Store<any>>>();\n\nexport function getStoreScopeContext<T>(scope: StoreScope<T>): Context<Store<T>> {\n let context = contextMap.get(scope);\n\n if (!context) {\n context = createContext<Store<T>>(createStore(scope.defaultValue));\n contextMap.set(scope, context);\n }\n\n return context;\n}\n\nexport function StoreScopeProvider<T>({ scope, store: inputStore, children }: StoreScopeProps<T>) {\n const context = getStoreScopeContext(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 useStoreScope<T>(scope: StoreScope<T>): Store<T> {\n const context = getStoreScopeContext(scope);\n return useContext(context);\n}\n","import type { UseStoreOptions } from './useStore';\nimport { useStore } from './useStore';\nimport type { Store } from '@core/store';\nimport type { UpdateFunction } from '@core/commonTypes';\n\nexport function useProp<T>(\n store: Store<T>,\n options?: UseStoreOptions,\n): [value: T, setValue: UpdateFunction<T>] {\n const value = useStore(store, options);\n\n return [value, store.set];\n}\n"],"names":["a","c","d","b","e","useRef","useEffect","useMemo","useDebugValue","require$$0","require$$1","useSyncExternalStoreWithSelector"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AASa,MAAI,IAAE;AAAiB,WAAS,EAAE,GAAE,GAAE;AAAC,WAAO,MAAI,MAAI,MAAI,KAAG,IAAE,MAAI,IAAE,MAAI,MAAI,KAAG,MAAI;AAAA,EAAC;AAAC,MAAI,IAAE,eAAa,OAAO,OAAO,KAAG,OAAO,KAAG,GAAE,IAAE,EAAE,sBAAqB,IAAE,EAAE,QAAO,IAAE,EAAE,WAAU,IAAE,EAAE,SAAQ,IAAE,EAAE;AACrN,kDAAA,mCAAyC,SAAS,GAAE,GAAE,GAAE,GAAE,GAAE;AAAC,QAAI,IAAE,EAAE,IAAI;AAAE,QAAG,SAAO,EAAE,SAAQ;AAAC,UAAI,IAAE,EAAC,UAAS,OAAG,OAAM,KAAI;AAAE,QAAE,UAAQ;AAAA,IAAC;AAAM,UAAE,EAAE;AAAQ,QAAE,EAAE,WAAU;AAAC,eAASA,GAAEA,IAAE;AAAC,YAAG,CAACC,IAAE;AAAC,UAAAA,KAAE;AAAG,UAAAC,KAAEF;AAAE,UAAAA,KAAE,EAAEA,EAAC;AAAE,cAAG,WAAS,KAAG,EAAE,UAAS;AAAC,gBAAIG,KAAE,EAAE;AAAM,gBAAG,EAAEA,IAAEH,EAAC;AAAE,qBAAO,IAAEG;AAAA,UAAC;AAAC,iBAAO,IAAEH;AAAA,QAAC;AAAC,QAAAG,KAAE;AAAE,YAAG,EAAED,IAAEF,EAAC;AAAE,iBAAOG;AAAE,YAAIC,KAAE,EAAEJ,EAAC;AAAE,YAAG,WAAS,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AAU,MAAM,IAAI,MAAM,MAAS,IAAI,QAAY,CAAC,OAAO,OAAO,CAAC;AAE9E,SAAA,SAAS,aAAa,OAAO;AACtC;ACjCgB,SAAA,KAAQ,OAAiB,SAA8B;AACrE,QAAM,EAAE,QAAQ,OAAO,MAAU,IAAA,SAAS,OAAO,OAAO;AAExD,MAAI,WAAW,SAAS;AACf,WAAA;AAAA,EACT;AAEA,MAAI,WAAW,SAAS;AAChB,UAAA;AAAA,EACR;AAEA,QAAM,MAAM,MAAM,KAAK,CAAC,UAAU,MAAM,WAAW,SAAS;AAC9D;ACRa,MAAA,iCAAiB;AAEvB,SAAS,qBAAwB,OAAyC;AAC3E,MAAA,UAAU,WAAW,IAAI,KAAK;AAElC,MAAI,CAAC,SAAS;AACZ,cAAU,cAAwB,YAAY,MAAM,YAAY,CAAC;AACtD,eAAA,IAAI,OAAO,OAAO;AAAA,EAC/B;AAEO,SAAA;AACT;AAEO,SAAS,mBAAsB,EAAE,OAAO,OAAO,YAAY,YAAgC;AAC1F,QAAA,UAAU,qBAAqB,KAAK;AAC1C,QAAM,eAAe;AAAA,IACnB,MAAM,cAAc,YAAY,MAAM,YAAY;AAAA,IAClD,CAAC,OAAO,UAAU;AAAA,EAAA;AAGpB,6BAAQ,QAAQ,UAAR,EAAiB,OAAO,cAAe,SAAS,CAAA;AAC1D;AAEO,SAAS,cAAiB,OAAgC;AACzD,QAAA,UAAU,qBAAqB,KAAK;AAC1C,SAAO,WAAW,OAAO;AAC3B;AC7BgB,SAAA,QACd,OACA,SACyC;AACnC,QAAA,QAAQ,SAAS,OAAO,OAAO;AAE9B,SAAA,CAAC,OAAO,MAAM,GAAG;AAC1B;"}
@@ -0,0 +1,56 @@
1
+ import type { Duration, Selector, Use } from './commonTypes';
2
+ import { type ResourceGroup } from './resourceGroup';
3
+ import { Store } from './store';
4
+ import type { CacheState, ErrorState, ValueState } from '../lib/cacheState';
5
+ import type { Path, Value } from '../lib/path';
6
+ export interface CacheGetOptions {
7
+ update?: 'whenMissing' | 'whenStale' | 'force';
8
+ backgroundUpdate?: boolean;
9
+ }
10
+ export interface CacheFunction<T, Args extends any[] = []> {
11
+ (this: {
12
+ use: Use;
13
+ }, ...args: Args): Promise<T>;
14
+ }
15
+ export interface CacheOptions<T> {
16
+ invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | undefined);
17
+ clearAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | undefined);
18
+ resourceGroup?: ResourceGroup | ResourceGroup[];
19
+ retain?: number;
20
+ clearUnusedAfter?: Duration;
21
+ }
22
+ export declare class Cache<T> extends Store<Promise<T>> {
23
+ readonly options: CacheOptions<T>;
24
+ readonly state: Store<CacheState<T>> & Omit<ThisType<Store<CacheState<T>>>, keyof Store<T_1>> & {
25
+ delete<T_2 extends Record<any, any>, K_1 extends Exclude<{ [K in keyof T_2]: T_2 extends Record<K, T_2[K]> ? never : K; }[keyof T_2], undefined>>(this: Store<T_2>, key: K_1): void;
26
+ clear<T_3 extends Record<any, any>>(this: Store<Partial<T_3>>): void;
27
+ };
28
+ protected stalePromise?: Promise<T>;
29
+ protected timers: Set<number>;
30
+ constructor(getter: CacheFunction<T>, options?: CacheOptions<T>, derivedFrom?: {
31
+ store: Store<any>;
32
+ selectors: (Selector<any, any> | Path<any>)[];
33
+ });
34
+ get({ update, backgroundUpdate }?: CacheGetOptions): Promise<T>;
35
+ invalidate({ invalidateDependencies }?: {
36
+ invalidateDependencies?: boolean;
37
+ }): void;
38
+ clear({ invalidateDependencies }?: {
39
+ invalidateDependencies?: boolean;
40
+ }): void;
41
+ mapValue<S>(selector: Selector<T, S>): Cache<S>;
42
+ mapValue<P extends Path<T>>(selector: P): Cache<Value<T, P>>;
43
+ protected watchPromise(): void;
44
+ protected setTimers(): void;
45
+ }
46
+ declare function create<T>(cacheFunction: CacheFunction<T>, options?: CacheOptions<T>): Cache<T>;
47
+ declare function withArgs<T, Args extends any[]>(cacheFunction: CacheFunction<T, Args>, options?: CacheOptions<T>): {
48
+ (...args: Args): Cache<T>;
49
+ invalidate: () => void;
50
+ clear: () => void;
51
+ };
52
+ export declare const createCache: typeof create & {
53
+ withArgs: typeof withArgs;
54
+ defaultOptions: CacheOptions<unknown>;
55
+ };
56
+ export {};
@@ -1,5 +1,5 @@
1
- import type { FetchStore } from './fetchStore';
2
1
  import type { Store } from './store';
2
+ import type { DebounceOptions } from '../lib/debounce';
3
3
  export interface Listener<T = void> {
4
4
  (value: T, previouseValue?: T): void;
5
5
  }
@@ -10,6 +10,7 @@ export interface Effect {
10
10
  (): void | Cancel;
11
11
  }
12
12
  export interface SubscribeOptions {
13
+ passive?: boolean;
13
14
  /** Whether to execute the callback immediately with the current store value.
14
15
  * @default true
15
16
  */
@@ -20,6 +21,8 @@ export interface SubscribeOptions {
20
21
  * subscribe(callback, { throttle: { seconds: 10 } }); // Will execute immediately and then at least 10 seconds havbe to pass. If the store changed during those 10 seconds, the callback will be executed again.
21
22
  */
22
23
  throttle?: Duration;
24
+ /** If set, callback execution is delayed. */
25
+ debounce?: DebounceOptions;
23
26
  /** Provide a custom equality function. By default a strict equals (===) will be used.
24
27
  */
25
28
  equals?: (a: any, b: any) => boolean;
@@ -37,7 +40,7 @@ export type Duration = number | {
37
40
  };
38
41
  export type UpdateFrom<Value, From extends any[]> = Value | ((...args: From) => Value);
39
42
  export type Update<Value> = UpdateFrom<Value, [Value]>;
40
- export interface UpdateFn<Value> {
43
+ export interface UpdateFunction<Value> {
41
44
  (update: Update<Value>): void;
42
45
  }
43
46
  export interface UseOptions {
@@ -46,6 +49,3 @@ export interface UseOptions {
46
49
  export interface Use {
47
50
  <T>(store: Store<T>, options?: UseOptions): T;
48
51
  }
49
- export interface UseFetch {
50
- <T>(fetchStore: FetchStore<T>): Promise<T>;
51
- }
@@ -1,10 +1,7 @@
1
+ export type { CacheFunction, CacheGetOptions, CacheOptions } from './cache';
2
+ export { Cache, createCache } from './cache';
1
3
  export type { Cancel, Duration, Effect, Listener, SubscribeOptions } from './commonTypes';
2
- export { derivedStore } from './derivedStore';
3
- export type { DerivedStore } from './derivedStore';
4
- export { fetchStore } from './fetchStore';
5
- export type { FetchFn, FetchOptions, FetchStore, FetchStoreOptions, FetchStoreState } from './fetchStore';
6
- export { once } from './once';
7
- export { allResources, ResourceGroup } from './resourceGroup';
8
4
  export type { Resource } from './resourceGroup';
9
- export { store } from './store';
10
- export type { BoundStoreActions, Store, StoreActions, StoreOptions, StoreOptionsWithActions } from './store';
5
+ export { allResources, createResourceGroup, ResourceGroup } from './resourceGroup';
6
+ export type { BoundStoreMethods, StoreMethods, StoreOptions, StoreOptionsWithMethods, } from './store';
7
+ export { createStore, Store } from './store';
@@ -2,12 +2,15 @@ export interface Resource {
2
2
  invalidate(): void;
3
3
  clear(): void;
4
4
  }
5
- export declare class ResourceGroup extends Set<Resource> {
5
+ export declare class ResourceGroup {
6
+ readonly name?: string | undefined;
7
+ private refMap;
8
+ private refSet;
9
+ constructor(name?: string | undefined);
10
+ add(resource: Resource): void;
11
+ delete(resource: Resource): void;
6
12
  invalidateAll(): void;
7
13
  clearAll(): void;
8
14
  }
9
- export declare const _allResources: ResourceGroup;
10
- export declare const allResources: {
11
- invalidateAll: () => void;
12
- clearAll: () => void;
13
- };
15
+ export declare const allResources: ResourceGroup;
16
+ export declare function createResourceGroup(name?: string): ResourceGroup;
@@ -1,34 +1,53 @@
1
- import type { Path, Value } from '../lib/propAccess';
2
- import { arrayActions, mapActions, recordActions, setActions } from '../lib/storeActions';
3
1
  import type { Cancel, Duration, Effect, Listener, Selector, SubscribeOptions, Update, Use, UseOptions } from './commonTypes';
4
- import { DerivedStore } from './derivedStore';
5
- export type StoreActions = Record<string, (...args: any[]) => any>;
6
- export type BoundStoreActions<T, Actions extends StoreActions> = Actions & ThisType<Store<T> & Actions>;
2
+ import { CalculationHelper } from '../lib/calculationHelper';
3
+ import type { Path, Value } from '../lib/path';
4
+ import { arrayMethods, mapMethods, recordMethods, setMethods } from '../lib/standardMethods';
5
+ export type StoreMethods = Record<string, (...args: any[]) => any>;
6
+ export type BoundStoreMethods<T, Methods extends StoreMethods> = Methods & ThisType<Store<T> & Methods>;
7
7
  export interface StoreOptions {
8
8
  retain?: number;
9
9
  }
10
- export interface StoreOptionsWithActions<T, Actions extends StoreActions> extends StoreOptions {
11
- methods?: Actions & ThisType<Store<T> & Actions & StandardActions<T>>;
10
+ export interface StoreOptionsWithMethods<T, Methods extends StoreMethods> extends StoreOptions {
11
+ methods?: Methods & ThisType<Store<T> & Methods & StandardMethods<T>>;
12
12
  }
13
- type StandardActions<T> = T extends Map<any, any> ? typeof mapActions : T extends Set<any> ? typeof setActions : T extends Array<any> ? typeof arrayActions : T extends Record<any, any> ? typeof recordActions : Record<string, never>;
14
- type StoreWithActions<T, Actions extends StoreActions> = Store<T> & Omit<BoundStoreActions<T, Actions>, keyof Store<T>> & StandardActions<T>;
13
+ export type Calculate<T> = (this: {
14
+ use: Use;
15
+ }, fns: {
16
+ use: Use;
17
+ }) => T;
18
+ type StandardMethods<T> = T extends Map<any, any> ? typeof mapMethods : T extends Set<any> ? typeof setMethods : T extends Array<any> ? typeof arrayMethods : T extends Record<any, any> ? typeof recordMethods : Record<string, never>;
19
+ type StoreWithMethods<T, Methods extends StoreMethods> = Store<T> & Omit<BoundStoreMethods<T, Methods>, keyof Store<T>> & StandardMethods<T>;
15
20
  export declare class Store<T> {
16
- protected readonly initialValue: T;
17
- protected readonly options: StoreOptions;
18
- protected value: T;
19
- protected listeners: Set<Listener<void>>;
21
+ readonly getter: T | Calculate<T>;
22
+ readonly options: StoreOptions;
23
+ protected derivedFrom?: {
24
+ store: Store<any>;
25
+ selectors: (Selector<any, any> | Path<any>)[];
26
+ } | undefined;
27
+ protected _value?: {
28
+ v: T;
29
+ };
30
+ protected listeners: Map<Listener<void>, boolean>;
20
31
  protected effects: Map<Effect, {
21
32
  handle?: Cancel | undefined;
22
33
  retain?: number | undefined;
23
34
  timeout?: number | undefined;
24
35
  }>;
25
36
  protected notifyId: {};
26
- constructor(initialValue: T, options?: StoreOptions);
37
+ protected calculationHelper: CalculationHelper<unknown>;
38
+ constructor(getter: T | Calculate<T>, options?: StoreOptions, derivedFrom?: {
39
+ store: Store<any>;
40
+ selectors: (Selector<any, any> | Path<any>)[];
41
+ } | undefined);
27
42
  get(): T;
28
- update(update: Update<T>): void;
43
+ set(update: Update<T>): void;
44
+ set<P extends Path<T>>(path: P, update: Update<Value<T, P>>): void;
45
+ protected reset(): void;
29
46
  sub(listener: Listener<T>, options?: SubscribeOptions): Cancel;
30
- map<S>(selector: Selector<T, S>, options?: UseOptions): DerivedStore<S>;
31
- map<P extends Path<T>>(selector: P, options?: UseOptions): DerivedStore<Value<T, P>>;
47
+ once<S extends T>(condition: (value: T) => value is S): Promise<S>;
48
+ once(condition?: (value: T) => boolean): Promise<T>;
49
+ map<S>(selector: Selector<T, S>, options?: UseOptions): Store<S>;
50
+ map<P extends Path<T>>(selector: P, options?: UseOptions): Store<Value<T, P>>;
32
51
  /** Add an effect that will be executed when the store becomes active, which means when it has at least one subscriber.
33
52
  * @param effect
34
53
  * If there is already a subscriber, the effect will be executed immediately.
@@ -46,13 +65,13 @@ export declare class Store<T> {
46
65
  protected onUnsubscribe(): void;
47
66
  protected notify(): void;
48
67
  }
49
- declare function _store<T>(calculate: (this: {
68
+ declare function create<T>(calculate: (this: {
50
69
  use: Use;
51
70
  }, fns: {
52
71
  use: Use;
53
- }) => T, options?: StoreOptions): DerivedStore<T>;
54
- declare function _store<T, Actions extends StoreActions = {}>(initialState: T, options?: StoreOptionsWithActions<T, Actions>): StoreWithActions<T, Actions>;
55
- export declare const store: typeof _store & {
72
+ }) => T, options?: StoreOptions): Store<T>;
73
+ declare function create<T, Methods extends StoreMethods = {}>(initialState: T, options?: StoreOptionsWithMethods<T, Methods>): StoreWithMethods<T, Methods>;
74
+ export declare const createStore: typeof create & {
56
75
  defaultOptions: StoreOptions;
57
76
  };
58
77
  export {};
@@ -1,5 +1,5 @@
1
- import type { Store } from '../core/store';
2
1
  import type { Draft, nothing } from '../immer';
2
+ import type { Store } from '../core/store';
3
3
  export declare const immerActions: {
4
4
  immerUpdate<T>(this: Store<T>, recipe: (draft: Draft<T>) => void | Draft<T> | (Draft<T> extends undefined ? import("immer/dist/internal").Nothing : never) | undefined): void;
5
5
  };
@@ -1,4 +1,4 @@
1
1
  export * from './core';
2
- export { Cache } from './lib/cache';
2
+ export { InstanceCache } from './lib/instanceCache';
3
3
  export { calcDuration } from './lib/calcDuration';
4
- export { arrayActions, mapActions, recordActions, setActions } from './lib/storeActions';
4
+ export { arrayMethods, mapMethods, recordMethods, setMethods } from './lib/standardMethods';
@@ -0,0 +1,2 @@
1
+ import type { Patch } from './diff';
2
+ export declare function applyPatches<T>(target: T, ...patches: Patch[]): T;
@@ -0,0 +1,19 @@
1
+ export type ValueState<T> = {
2
+ status: 'value';
3
+ value: T;
4
+ error?: undefined;
5
+ };
6
+ export type ErrorState = {
7
+ status: 'error';
8
+ value?: undefined;
9
+ error: unknown;
10
+ };
11
+ export type PendingState = {
12
+ status: 'pending';
13
+ value?: undefined;
14
+ error?: undefined;
15
+ };
16
+ export type CacheState<T> = (ValueState<T> | ErrorState | PendingState) & {
17
+ isStale: boolean;
18
+ isUpdating: boolean;
19
+ };
@@ -1,17 +1,16 @@
1
- import type { Cancel, UpdateFrom, Use, UseFetch } from '../core/commonTypes';
2
1
  import type { MaybePromise } from './maybePromise';
2
+ import type { Cancel, UpdateFrom, Use } from '../core/commonTypes';
3
3
  export declare class CalculationHelper<T> {
4
4
  private options;
5
5
  private current?;
6
6
  constructor(options: {
7
7
  calculate: (fns: {
8
8
  use: Use;
9
- useFetch: UseFetch;
10
9
  updateValue: (update: UpdateFrom<MaybePromise<T>, [T | undefined]>) => void;
11
10
  updateError: (error: unknown) => void;
12
11
  }) => Cancel | void;
13
12
  addEffect: (effect: () => Cancel | void) => Cancel;
14
- getValue: () => T | undefined;
13
+ getValue?: () => T | undefined;
15
14
  setValue?: (value: T) => void;
16
15
  setError?: (error: unknown) => void;
17
16
  onInvalidate?: () => void;
@@ -19,4 +18,5 @@ export declare class CalculationHelper<T> {
19
18
  execute(): void;
20
19
  stop(): void;
21
20
  check(): void;
21
+ invalidateDependencies(): void;
22
22
  }
@@ -0,0 +1 @@
1
+ export declare function flatClone<T>(object: T): T;
@@ -0,0 +1,6 @@
1
+ import type { Duration } from '../core';
2
+ export type DebounceOptions = Duration | {
3
+ wait: Duration;
4
+ maxWait?: Duration;
5
+ };
6
+ export declare function debounce<Args extends any[]>(action: (...args: Args) => void, options: Duration | DebounceOptions): (...args: Args) => void;