cross-state 0.56.4 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/{diff-CElc7pJI.d.ts → diff-CAQaunfv.d.cts} +3 -3
  2. package/dist/{diff-BslUrJZE.d.cts → diff-DFvRd-Gf.d.ts} +3 -3
  3. package/dist/{extendedJson-BZkQBXEv.js → extendedJson-Dv9q6rps.js} +2 -2
  4. package/dist/{extendedJson-BZkQBXEv.js.map → extendedJson-Dv9q6rps.js.map} +1 -1
  5. package/dist/{extendedJson-Dn2F7Edo.cjs → extendedJson-ursQ8DbQ.cjs} +1 -1
  6. package/dist/{extendedJson-Dn2F7Edo.cjs.map → extendedJson-ursQ8DbQ.cjs.map} +1 -1
  7. package/dist/index.cjs +9 -11
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +4 -4
  10. package/dist/index.d.ts +4 -4
  11. package/dist/index.js +7 -9
  12. package/dist/index.js.map +1 -1
  13. package/dist/mutative/index.cjs +2 -1
  14. package/dist/mutative/index.d.cts +2 -2
  15. package/dist/mutative/index.d.ts +2 -2
  16. package/dist/mutative/index.js +2 -1
  17. package/dist/mutative/register.cjs +4 -3
  18. package/dist/mutative/register.cjs.map +1 -1
  19. package/dist/mutative/register.d.cts +2 -4
  20. package/dist/mutative/register.d.ts +2 -2
  21. package/dist/mutative/register.js +4 -3
  22. package/dist/mutative/register.js.map +1 -1
  23. package/dist/{mutativeMethods-Bhd1Yi22.d.ts → mutativeMethods-BT1Cim3p.d.ts} +3 -3
  24. package/dist/{mutativeMethods-DWhwZRzv.d.cts → mutativeMethods-C8VcZWED.d.cts} +3 -3
  25. package/dist/{mutativeMethods-CgXk_bMt.cjs → mutativeMethods-CkNycpO9.cjs} +6 -7
  26. package/dist/{mutativeMethods-CgXk_bMt.cjs.map → mutativeMethods-CkNycpO9.cjs.map} +1 -1
  27. package/dist/{mutativeMethods-CZKeRIDL.js → mutativeMethods-Jowr0Znn.js} +4 -6
  28. package/dist/{mutativeMethods-CZKeRIDL.js.map → mutativeMethods-Jowr0Znn.js.map} +1 -1
  29. package/dist/{patchMethods-hhlLwtqE.cjs → patchMethods-B7Hm5-Qh.cjs} +4 -6
  30. package/dist/{patchMethods-hhlLwtqE.cjs.map → patchMethods-B7Hm5-Qh.cjs.map} +1 -1
  31. package/dist/{patchMethods-DXWygPZ6.d.ts → patchMethods-BmyvvHnP.d.cts} +4 -4
  32. package/dist/{patchMethods-BT4Tg5aG.d.cts → patchMethods-CixmHmNt.d.ts} +4 -4
  33. package/dist/{patchMethods-C_f3PORQ.js → patchMethods-iK2F87G0.js} +5 -7
  34. package/dist/{patchMethods-C_f3PORQ.js.map → patchMethods-iK2F87G0.js.map} +1 -1
  35. package/dist/patches/index.cjs +3 -3
  36. package/dist/patches/index.d.cts +3 -3
  37. package/dist/patches/index.d.ts +3 -3
  38. package/dist/patches/index.js +3 -3
  39. package/dist/patches/register.cjs +4 -4
  40. package/dist/patches/register.cjs.map +1 -1
  41. package/dist/patches/register.d.cts +3 -5
  42. package/dist/patches/register.d.ts +3 -3
  43. package/dist/patches/register.js +4 -4
  44. package/dist/patches/register.js.map +1 -1
  45. package/dist/{chunk-CUT6urMc.cjs → path-B-Rq5q6m.cjs} +14 -1
  46. package/dist/path-B-Rq5q6m.cjs.map +1 -0
  47. package/dist/path-CyYq74W8.js +8 -0
  48. package/dist/path-CyYq74W8.js.map +1 -0
  49. package/dist/persist/register.cjs +5 -5
  50. package/dist/persist/register.cjs.map +1 -1
  51. package/dist/persist/register.d.cts +2 -4
  52. package/dist/persist/register.d.ts +2 -2
  53. package/dist/persist/register.js +5 -5
  54. package/dist/persist/register.js.map +1 -1
  55. package/dist/{persist-CLgS5Cqw.js → persist-Bunx8xfQ.js} +12 -15
  56. package/dist/persist-Bunx8xfQ.js.map +1 -0
  57. package/dist/{persist-olbNkcdZ.d.ts → persist-CHRYYolx.d.cts} +3 -3
  58. package/dist/{persist-DboMIMOK.cjs → persist-DMbVdqS_.cjs} +11 -14
  59. package/dist/persist-DMbVdqS_.cjs.map +1 -0
  60. package/dist/{persist-DVKRq8RQ.d.cts → persist-DyI_JLxZ.d.ts} +3 -3
  61. package/dist/{propAccess-BdLsqViO.cjs → propAccess-C2AIn9RC.cjs} +4 -6
  62. package/dist/{propAccess-BdLsqViO.cjs.map → propAccess-C2AIn9RC.cjs.map} +1 -1
  63. package/dist/{propAccess-B260LXN1.js → propAccess-DvWFpYoj.js} +5 -7
  64. package/dist/{propAccess-B260LXN1.js.map → propAccess-DvWFpYoj.js.map} +1 -1
  65. package/dist/react/index.cjs +66 -80
  66. package/dist/react/index.cjs.map +1 -1
  67. package/dist/react/index.d.cts +70 -70
  68. package/dist/react/index.d.ts +70 -70
  69. package/dist/react/index.js +62 -77
  70. package/dist/react/index.js.map +1 -1
  71. package/dist/react/register.cjs +5 -5
  72. package/dist/react/register.cjs.map +1 -1
  73. package/dist/react/register.d.cts +3 -5
  74. package/dist/react/register.d.ts +3 -3
  75. package/dist/react/register.js +5 -5
  76. package/dist/react/register.js.map +1 -1
  77. package/dist/{scope-CfLlLxo9.cjs → scope-C1bcfK8e.cjs} +32 -7
  78. package/dist/scope-C1bcfK8e.cjs.map +1 -0
  79. package/dist/{scope-D3jkIPgn.d.ts → scope-CESkVNvI.d.cts} +3 -3
  80. package/dist/{scope-7LeON9bZ.js → scope-CKGsCVn3.js} +20 -7
  81. package/dist/scope-CKGsCVn3.js.map +1 -0
  82. package/dist/{scope-CcBxgcrs.d.cts → scope-DJXSRsGy.d.ts} +3 -3
  83. package/dist/{store-MBrcOgtz.d.cts → store-BRHFhRPm.d.ts} +21 -21
  84. package/dist/{store-CdST5wJZ.cjs → store-C1NYHLgR.cjs} +12 -13
  85. package/dist/store-C1NYHLgR.cjs.map +1 -0
  86. package/dist/{store-DnZ6fsiJ.d.ts → store-XcnTdeiJ.d.cts} +21 -21
  87. package/dist/{store-Dx8w7yT-.js → store-v3RYWzVg.js} +13 -14
  88. package/dist/store-v3RYWzVg.js.map +1 -0
  89. package/dist/{storeMethods-B_RzvMaV.cjs → storeMethods-CNu7VD6w.cjs} +135 -60
  90. package/dist/storeMethods-CNu7VD6w.cjs.map +1 -0
  91. package/dist/{storeMethods-BrKuusQ2.js → storeMethods-CQhXlHpl.js} +115 -59
  92. package/dist/storeMethods-CQhXlHpl.js.map +1 -0
  93. package/dist/{storeMethods-CmWv1YMe.d.cts → storeMethods-Dsz0-Cda.d.ts} +4 -4
  94. package/dist/{storeMethods-Cb1ur5K3.d.ts → storeMethods-y3PlfTHV.d.cts} +4 -4
  95. package/package.json +26 -37
  96. package/dist/hash-DNFM5y_h.js +0 -19
  97. package/dist/hash-DNFM5y_h.js.map +0 -1
  98. package/dist/hash-Dv3XlmHn.cjs +0 -30
  99. package/dist/hash-Dv3XlmHn.cjs.map +0 -1
  100. package/dist/persist-CLgS5Cqw.js.map +0 -1
  101. package/dist/persist-DboMIMOK.cjs.map +0 -1
  102. package/dist/scope-7LeON9bZ.js.map +0 -1
  103. package/dist/scope-CfLlLxo9.cjs.map +0 -1
  104. package/dist/store-CdST5wJZ.cjs.map +0 -1
  105. package/dist/store-Dx8w7yT-.js.map +0 -1
  106. package/dist/storeMethods-B_RzvMaV.cjs.map +0 -1
  107. package/dist/storeMethods-BrKuusQ2.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"persist-DboMIMOK.cjs","names":["isPromise","value","entries: Map<KeyType, unknown>","path","isPromise","store: Store<T>","options: PersistOptions<T>","queue","castArrayPath","calcDuration","subscribePatches","path","shallowEqual","isPromise","fromExtendedJsonString","remove","set","get","value","toExtendedJsonString"],"sources":["../src/lib/promiseChain.ts","../src/persist/persistPathHelpers.ts","../src/persist/persistStorage.ts","../src/persist/persist.ts"],"sourcesContent":["import isPromise from '@lib/isPromise';\n\nexport interface Chain<T> {\n value: T;\n next<S>(fn: (value: Awaited<T>) => S): T extends Promise<any> ? Chain<Promise<S>> : Chain<S>;\n}\n\nexport default function promiseChain<T>(value: T | (() => T)): Chain<T> {\n if (value instanceof Function) {\n value = value();\n }\n\n return {\n value,\n next(fn) {\n const next = isPromise(value)\n ? value.then((value) => fn(value as Awaited<T>))\n : fn(value as Awaited<T>);\n\n return promiseChain(next) as any;\n },\n };\n}\n","import type { KeyType } from '@lib/path';\n\nexport const isAncestor = (ancestor: KeyType[], path: KeyType[]): boolean => {\n return (\n ancestor.length <= path.length &&\n ancestor.every((v, i) => v === '*' || path[i] === '*' || v === path[i])\n );\n};\n\nexport const split = (value: any, path: KeyType[]): { path: KeyType[]; value: unknown }[] => {\n const [first, ...rest] = path;\n if (first === undefined) return [{ path: [], value }];\n\n let entries: Map<KeyType, unknown>;\n if (value instanceof Map) {\n entries = value;\n } else if (value instanceof Set) {\n entries = new Map([...value].map((v, i) => [i, v]));\n } else if (Array.isArray(value)) {\n entries = new Map(value.map((v, i) => [i, v]));\n } else if (typeof value === 'object' && value !== null) {\n entries = new Map(Object.entries(value));\n } else {\n return [{ path: [], value }];\n }\n\n if (first === '*') {\n return [...entries].flatMap(([k, v]) =>\n split(v, rest).map(({ path, value }) => ({ path: [k, ...path], value })),\n );\n }\n\n const subValue = entries.get(first);\n if (subValue === undefined) return [{ path: [], value }];\n\n return split(subValue, rest).map(({ path, value }) => ({ path: [first, ...path], value }));\n};\n","import isPromise from '@lib/isPromise';\nimport promiseChain from '@lib/promiseChain';\n\nexport interface PersistStorageBase {\n getItem: (key: string) => string | null | Promise<string | null>;\n setItem: (key: string, value: string) => void | Promise<unknown>;\n removeItem: (key: string) => void | Promise<unknown>;\n}\n\nexport interface PersistStorageWithKeys extends PersistStorageBase {\n keys: () => string[] | Promise<string[]>;\n}\n\nexport interface PersistStorageWithLength extends PersistStorageBase {\n length: number | (() => number | Promise<number>);\n key: (keyIndex: number) => string | null | Promise<string | null>;\n}\n\nexport interface PersistStorageWithListItems extends PersistStorageBase {\n listItems: () => Map<string, string> | Promise<Map<string, string>>;\n}\n\nexport type PersistStorage =\n | PersistStorageWithKeys\n | PersistStorageWithLength\n | PersistStorageWithListItems;\n\nexport function normalizeStorage(storage: PersistStorage): PersistStorageWithListItems {\n return {\n getItem: storage.getItem.bind(storage),\n setItem: storage.setItem.bind(storage),\n removeItem: storage.removeItem.bind(storage),\n\n listItems() {\n if ('listItems' in storage) {\n return storage.listItems();\n }\n\n return promiseChain(() => {\n if ('keys' in storage) {\n return storage.keys();\n } else {\n return promiseChain(\n storage.length instanceof Function ? storage.length() : storage.length,\n )\n .next((length) => {\n const keys = Array.from({ length }, (_, index) => storage.key(index));\n return keys.some(isPromise) ? Promise.all(keys) : (keys as (string | null)[]);\n })\n .next((keys) => {\n return keys.filter((key): key is string => typeof key === 'string');\n }).value;\n }\n })\n .next((keys) => {\n const results = keys.map(\n (key) =>\n promiseChain(storage.getItem(key)).next((value) => [key, value] as const).value,\n );\n\n return results.some(isPromise)\n ? Promise.all(results)\n : (results as [string, string | null][]);\n })\n .next((results) => {\n return new Map(results.filter(([, value]) => value !== null) as [string, string][]);\n }).value;\n },\n };\n}\n","import { type Cancel, type Duration, type Store } from '@core';\nimport { calcDuration } from '@lib/calcDuration';\nimport { shallowEqual } from '@lib/equals';\nimport { fromExtendedJsonString, toExtendedJsonString } from '@lib/extendedJson';\nimport isPromise from '@lib/isPromise';\nimport type { KeyType, WildcardPath } from '@lib/path';\nimport promiseChain from '@lib/promiseChain';\nimport { castArrayPath, get, remove, set } from '@lib/propAccess';\nimport { queue } from '@lib/queue';\nimport { subscribePatches } from '@patches/patchMethods';\nimport { isAncestor, split } from '@persist/persistPathHelpers';\nimport {\n normalizeStorage,\n type PersistStorage,\n type PersistStorageWithListItems,\n} from './persistStorage';\n\ntype PathOption<T> =\n | WildcardPath<T>\n | {\n path: WildcardPath<T>;\n // throttle?: Duration;\n };\n\ntype Key = { type: 'internal'; path: string } | { type: 'data'; path: KeyType[] };\n\nexport interface PersistOptions<T> {\n id: string;\n storage: PersistStorage;\n paths?: PathOption<T>[];\n throttle?: Duration;\n persistInitialState?: boolean;\n}\n\nexport class Persist<T> {\n readonly storage: PersistStorageWithListItems;\n readonly [Symbol.dispose]!: Cancel;\n\n readonly paths: {\n path: KeyType[];\n throttle?: number;\n }[];\n\n readonly initialized: Promise<void>;\n\n private resolveInitialized?: () => void;\n\n private channel: BroadcastChannel;\n\n private queue = queue();\n\n private handles = new Set<Cancel>();\n\n private stopped = false;\n\n private updateInProgress = new Map<string, unknown>();\n\n private prefix;\n\n constructor(\n public readonly store: Store<T>,\n public readonly options: PersistOptions<T>,\n ) {\n this.storage = normalizeStorage(options.storage);\n this.channel = new BroadcastChannel(`cross-state-persist_${options.id}`);\n this.prefix = `${options.id}:`;\n\n if (Symbol.dispose) {\n this[Symbol.dispose] = () => this.stop();\n }\n\n this.paths = (options.paths ?? [])\n .map<{\n path: KeyType[];\n throttle?: number;\n }>((p) => {\n if (isPlainPath(p)) {\n return {\n path: castArrayPath(p),\n throttle: options.throttle && calcDuration(options.throttle),\n };\n }\n\n const _p = p as { path: KeyType[]; throttle?: Duration };\n\n return {\n path: castArrayPath(_p.path),\n throttle:\n (_p.throttle && calcDuration(_p.throttle)) ??\n (options.throttle && calcDuration(options.throttle)),\n };\n })\n .sort((a, b) => b.path.length - a.path.length);\n\n if (this.paths.length === 0) {\n this.paths.push({\n path: ['*'],\n throttle: options.throttle && calcDuration(options.throttle),\n });\n }\n\n this.initialized = new Promise((resolve) => {\n this.resolveInitialized = resolve;\n });\n\n this.watchStore();\n this.watchStorage();\n }\n\n private watchStore() {\n const throttle = Math.min(...this.paths.map((p) => p.throttle ?? 0)) || undefined;\n\n const cancel = subscribePatches.apply(this.store as Store<unknown>, [\n (patches, reversePatches) => {\n let i = 0;\n for (const patch of patches) {\n const reversePatch = reversePatches[i++];\n\n const stringPath = JSON.stringify(patch.path);\n if (\n this.updateInProgress.has(stringPath) &&\n this.updateInProgress.get(stringPath) ===\n (patch.op === 'remove' ? undefined : patch.value)\n ) {\n continue;\n }\n\n const matchingPaths = this.paths.filter(\n (p) => isAncestor(p.path, patch.path) || isAncestor(patch.path, p.path),\n );\n\n for (const { path } of matchingPaths) {\n if (path.length <= patch.path.length) {\n const pathToSave = patch.path.slice(0, path.length);\n this.queue(() => this.save(pathToSave), pathToSave);\n } else if (patch.op === 'remove') {\n const subValues = split(\n reversePatch?.op === 'add' ? reversePatch.value : {},\n path.slice(patch.path.length),\n );\n\n for (const { path } of subValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n } else {\n const updatedValues = split(patch.value, path.slice(patch.path.length));\n const removedValues = split(\n reversePatch?.op !== 'remove' ? (reversePatch?.value ?? {}) : {},\n path.slice(patch.path.length),\n ).filter((v) => !updatedValues.some((u) => shallowEqual(u.path, v.path)));\n\n for (const { path } of updatedValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n for (const { path } of removedValues) {\n this.queue(() => this.save([...patch.path, ...path]), [...patch.path, ...path]);\n }\n }\n }\n }\n },\n { runNow: this.options.persistInitialState ?? false, passive: true, throttle },\n ]);\n\n this.handles.add(cancel);\n }\n\n private async watchStorage() {\n if (!this.options.persistInitialState) {\n let items = this.storage.listItems();\n if (isPromise(items)) {\n items = await items;\n }\n\n if (this.stopped) {\n return;\n }\n\n const toLoad = new Map(\n [...items.entries()]\n .sort((a, b) => b[1].length - a[1].length)\n .map(([key, value]) => [this.parseKey(key), value])\n .filter(([key]) => key) as [Key, string][],\n );\n\n this.queue(() => this.load(toLoad));\n }\n\n this.queue(() => this.resolveInitialized?.());\n\n const listener = (event: MessageEvent) => {\n this.queue(() => this.load([{ type: 'data', path: event.data }]));\n };\n\n this.channel.addEventListener('message', listener);\n this.handles.add(() => this.channel.removeEventListener('message', listener));\n }\n\n private buildKey({ type, path }: Key) {\n return `${this.prefix}${type === 'internal' ? path : JSON.stringify(path)}`;\n }\n\n private parseKey(key: string): Key | undefined {\n if (!key.startsWith(this.prefix)) {\n return;\n }\n\n key = key.slice(this.prefix.length);\n\n if (!key.startsWith('[')) {\n return { type: 'internal', path: key };\n }\n\n return { type: 'data', path: JSON.parse(key) as KeyType[] };\n }\n\n private load(items: Key[] | Map<Key, string>): void | Promise<void> {\n return promiseChain(() => {\n if (Array.isArray(items)) {\n return promiseChain(() => {\n const entries = items.map(\n (key) =>\n promiseChain(() => {\n return this.storage.getItem(this.buildKey(key));\n }).next((value) => [key, value] as const).value,\n );\n\n return entries.some(isPromise)\n ? Promise.all(entries)\n : (entries as [Key, string | null][]);\n }).next((entries) => {\n return entries.filter((entry) => entry !== null) as [Key, string][];\n }).value;\n } else {\n return [...items.entries()];\n }\n }).next((entries) => {\n if (this.stopped) {\n return;\n }\n\n const toWrite = entries\n .filter(([key, value]) => {\n if (key.type !== 'data' || !value) {\n return;\n }\n\n if (\n !this.paths.find(\n (p) =>\n (p.path.length === 1 && p.path[0] === '*' && key.path.length === 0) ||\n (p.path.length === key.path.length && isAncestor(p.path, key.path)),\n )\n ) {\n return null;\n }\n\n const inSaveQueue = this.queue\n .getRefs()\n .find((ref) => isAncestor(ref, key.path) || isAncestor(key.path, ref));\n return !inSaveQueue;\n })\n .map(([key, value]) => {\n try {\n return {\n path: key.path,\n value: !value || value === 'undefined' ? undefined : fromExtendedJsonString(value),\n };\n } catch {\n return undefined;\n }\n })\n .filter(Boolean) as { path: KeyType[]; value: unknown }[];\n\n if (toWrite.length > 0) {\n for (const { path, value } of toWrite) {\n this.updateInProgress.set(JSON.stringify(path), value);\n }\n\n this.store.set((state) => {\n for (const { path, value } of toWrite) {\n if (value === undefined) {\n state = remove(state, path as any);\n } else {\n state = set(state, path as any, value);\n }\n }\n\n return state;\n });\n\n this.updateInProgress.clear();\n }\n\n const versionEntry = entries.find(\n ([key]) => key.type === 'internal' && key.path === 'version',\n );\n if (versionEntry) {\n this.store.version = versionEntry[1];\n }\n }).value;\n }\n\n private save(path: KeyType[]): void | Promise<unknown> {\n const key = this.buildKey({ type: 'data', path });\n const value = get(this.store.get() as any, path);\n\n return promiseChain(value)\n .next((value) => {\n if (value === undefined) {\n return this.storage.removeItem(key);\n } else {\n return this.storage.setItem(key, toExtendedJsonString(value));\n }\n })\n .next(() => {\n this.channel.postMessage(path);\n\n if (this.store.version) {\n return this.storage.setItem(\n this.buildKey({ type: 'internal', path: 'version' }),\n this.store.version,\n );\n } else {\n return this.storage.removeItem(this.buildKey({ type: 'internal', path: 'version' }));\n }\n }).value;\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n\n for (const handle of this.handles) {\n handle();\n }\n\n await this.queue.whenDone();\n this.channel.close();\n }\n}\n\nexport function persist<T>(store: Store<T>, options: PersistOptions<T>): Persist<T> {\n return new Persist<T>(store, options);\n}\n\nfunction isPlainPath<T>(p: PathOption<T>): p is WildcardPath<T> & (KeyType[] | string) {\n return typeof p === 'string' || Array.isArray(p);\n}\n"],"mappings":";;;;;;AAOA,SAAwB,aAAgB,OAAgC;AACtE,KAAI,iBAAiB,SACnB,SAAQ;AAGV,QAAO;EACL;EACA,KAAK,IAAI;GACP,MAAM,OAAOA,wBAAU,SACnB,MAAM,MAAM,YAAU,GAAGC,YACzB,GAAG;AAEP,UAAO,aAAa;;;;;;;ACjB1B,MAAa,cAAc,UAAqB,SAA6B;AAC3E,QACE,SAAS,UAAU,KAAK,UACxB,SAAS,OAAO,GAAG,MAAM,MAAM,OAAO,KAAK,OAAO,OAAO,MAAM,KAAK;;AAIxE,MAAa,SAAS,OAAY,SAA2D;CAC3F,MAAM,CAAC,OAAO,GAAG,QAAQ;AACzB,KAAI,UAAU,OAAW,QAAO,CAAC;EAAE,MAAM;EAAI;;CAE7C,IAAIC;AACJ,KAAI,iBAAiB,IACnB,WAAU;UACD,iBAAiB,IAC1B,WAAU,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,GAAG,MAAM,CAAC,GAAG;UACtC,MAAM,QAAQ,OACvB,WAAU,IAAI,IAAI,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG;UACjC,OAAO,UAAU,YAAY,UAAU,KAChD,WAAU,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b,QAAO,KAAK,QAAQ,WAAW,KAAK,SAAS;IAAE,MAAM;IAAY,MAAM;;KAExE;;CAGP,MAAM,OAAsB;AAC1B,OAAK,UAAU;AAEf,OAAK,MAAM,UAAU,KAAK,QACxB;AAGF,QAAM,KAAK,MAAM;AACjB,OAAK,QAAQ;;;AAIjB,SAAgB,QAAW,OAAiB,SAAwC;AAClF,QAAO,IAAI,QAAW,OAAO;;AAG/B,SAAS,YAAe,GAA+D;AACrF,QAAO,OAAO,MAAM,YAAY,MAAM,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"scope-7LeON9bZ.js","names":["factory: (...args: Args) => T","cacheTime?: number","name?: string","allResources: ResourceGroup","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","options","baseInstance: CacheBundle<T, Args, TCache> & TCache","defaultCacheOptions: CacheOptions<any, any>","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } 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(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\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): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\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(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\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 { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): 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 autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\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(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n if (!this.calculatedValue?.check()) {\n this.calculatedValue?.stop();\n this.calculatedValue = undefined;\n }\n\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\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.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = 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 !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<\n T,\n Args extends any[],\n TCache extends Cache<T, Args>,\n> = [] extends Args ? CacheBundle<T, Args, TCache> & TCache : CacheBundle<T, Args, TCache>;\n\nexport interface InvalidationOptions<T, Args extends any[], TCache extends Cache<T, Args>> {\n filter?: (cache: TCache) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[], TCache extends Cache<T, Args>> = {\n (...args: Args): TCache;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args, Cache<S, Args>>;\n mapValue<const P>(\n selector: Constrain<P, Path<T>>,\n ): CreateCacheResult<Value<T, P>, Args, Cache<Value<T, P>, Args>>;\n invalidateAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n clearAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n getInstances: () => TCache[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, Cache<T, Args>> {\n return internalCreate<T, Args, Cache<T, Args>>(\n (args, options) =>\n new Cache(\n (helpers) => {\n const result = cacheFunction.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n ),\n options,\n );\n}\n\nexport function internalCreate<T, Args extends any[], TCache extends Cache<T, Args>>(\n factory: (args: Args, options: CacheOptions<T, Args>) => TCache,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, TCache> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args, TCache> & TCache;\n\n const instanceCache = new InstanceCache<Args, TCache>(\n (...args) => factory(args, options),\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate<any, Args, Cache<any, Args>>((args: Args) =>\n mapValue(baseInstance(...args), selector),\n );\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args, TCache> & TCache;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const defaultCacheOptions: CacheOptions<any, any> = {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n};\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: defaultCacheOptions,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WAChB;EAFgB;EACA;+BARF,IAAI;kBAED,KAAK,YACpB,kBAAkB,KAAK,WAAW,KAAK,IAAI,KAAK,YAAY,IAAI,MAChE;;CAOJ,UAAgB;EACd,MAAM,SAAS,KAAK,SAAS,KAAK,aAAa;AAE/C,OAAK,MA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;AAGZ,QAAO;;AAGT,MAAaC,sBAA8C;CACzD,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQ;;AAGV,MAAaC,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;;;;ACnepB,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,WAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"scope-CfLlLxo9.cjs","names":["factory: (...args: Args) => T","cacheTime?: number","simpleHash","name?: string","allResources: ResourceGroup","Store","args: Args","options: CacheOptions<T, Args>","derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n }","createStore","calculatedValue","PromiseWithState","calcDuration","makeSelector","options","baseInstance: CacheBundle<T, Args, TCache> & TCache","defaultCacheOptions: CacheOptions<any, any>","deepEqual","createCache: typeof create & { defaultOptions: CacheOptions<any, any> }","defaultValue: T"],"sources":["../src/lib/instanceCache.ts","../src/core/resourceGroup.ts","../src/core/cache.ts","../src/core/scope.ts"],"sourcesContent":["import { simpleHash } 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(\n public readonly factory: (...args: Args) => T,\n public readonly cacheTime?: number,\n ) {}\n\n cleanup(): void {\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): T {\n return this.getWithKey(args, args);\n }\n\n getWithKey(args: Args, cacheKey: unknown): T {\n const key = simpleHash(cacheKey);\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(): T[] {\n return [...this.cache.values()]\n .map((entry) => entry.ref ?? entry.weakRef?.deref())\n .filter((value): value is T => !!value);\n }\n\n stop(): void {\n if (this.interval) {\n clearInterval(this.interval);\n }\n }\n\n stats(): { count: number; withRef: number; withWeakRef: number } {\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 { autobind } from '@lib/autobind';\n\nexport interface Resource {\n invalidateAll(): void;\n clearAll(): 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 autobind(ResourceGroup);\n }\n\n add(resource: Resource): void {\n const ref = new WeakRef(resource);\n this.refMap.set(resource, ref);\n this.refSet.add(ref);\n }\n\n delete(resource: Resource): void {\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(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.invalidateAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n\n clearAll(): void {\n for (const ref of this.refSet) {\n const resource = ref.deref();\n if (resource) {\n resource.clearAll();\n } else {\n this.refSet.delete(ref);\n }\n }\n }\n}\n\nexport const allResources: ResourceGroup = /* @__PURE__ */ new ResourceGroup();\n\nexport function createResourceGroup(name?: string): ResourceGroup {\n return new ResourceGroup(name);\n}\n","import { autobind } from '@lib/autobind';\nimport type { CacheState, ErrorState, ValueState } from '@lib/cacheState';\nimport { calcDuration } from '@lib/calcDuration';\nimport { calculatedValue } from '@lib/calculatedValue';\nimport type { Constrain } from '@lib/constrain';\nimport { deepEqual } from '@lib/equals';\nimport { InstanceCache } from '@lib/instanceCache';\nimport { makeSelector } from '@lib/makeSelector';\nimport { type MaybePromise } from '@lib/maybePromise';\nimport type { AnyPath, Path, Value } from '@lib/path';\nimport { PromiseWithState } from '@lib/promiseWithState';\nimport type { Duration, Selector } from './commonTypes';\nimport { allResources, type ResourceGroup } from './resourceGroup';\nimport { Store, createStore, type Calculate, type StoreOptions } from './store';\n\nexport interface CacheGetOptions {\n /**\n * How to handle the cache when getting the value.\n * - `whenMissing`: Only fetch a new value if there is no cached value.\n * - `whenStale`: Fetch a new value if there is no cached value or if the cached value is stale.\n * - `force`: Always fetch a new value, regardless of the cache state.\n */\n update?: 'whenMissing' | 'whenStale' | 'force';\n\n /**\n * If set to `true`, the cache will be updated in the background.\n * This means that a stale value will be returned immediately, if available, while the new value is being fetched.\n */\n backgroundUpdate?: boolean;\n}\n\nexport interface CacheFunction<T, Args extends any[] = []> {\n (...args: Args): Promise<T> | Calculate<Promise<T>>;\n}\n\nexport interface CacheOptions<T, Args extends any[]> extends StoreOptions<Promise<T>> {\n /**\n * How long to keep the cache entry before it is considered stale.\n * If set to `undefined` or `null`, the cache entry will never be invalidated automatically.\n *\n * @example\n * ```typescript\n * createCache(fetchData, {\n * invalidateAfter: { seconds: 10 },\n * });\n * ```\n */\n invalidateAfter?: Duration | ((state: ValueState<T> | ErrorState) => Duration | null) | null;\n\n /**\n * If set, the cache will be invalidated when the window gets focused.\n * This is useful for caches that are used in a browser environment and might become stale when the user switches tabs.\n */\n invalidateOnWindowFocus?: boolean;\n\n /**\n * If set, the cached value will be cleared when the cache is invalidated.\n * Without this option, the cache will keep the last value as stale until a new value becomes available.\n */\n clearOnInvalidate?: boolean;\n\n /**\n * If set, cache entries will be cleared after approximately the specified duration.\n * This is useful for long lived pages or applications and helps to prevent memory leaks.\n * The exact time when the entry is cleared is not guaranteed, since it will be cleared during garbage collection.\n */\n clearUnusedAfter?: Duration | null;\n\n /**\n * Add the cache to the specified resource group(s).\n * This allows you to invalidate or clear multiple caches that belong to the same group.\n * All caches are always added to the `allResources` group.\n */\n resourceGroup?: ResourceGroup | ResourceGroup[];\n\n /**\n * Function to generate a custom cache key based on the provided arguments.\n * This allows you to control how cache entries are identified and reused.\n * By default, the arguments array is used as the cache key.\n *\n * @example\n * ```typescript\n * // Will use the same instance when provided with `undefined`, `{ num: 0 }`, `{ bool: false }`, etc.\n * createCache((filter?: { num?: number, bool?: boolean }) => fetchData(filter), {\n * getCacheKey: (filter?) => ({\n * num: filter?.num ?? 0,\n * bool: filter?.bool ?? false,\n * }),\n * });\n * ```\n */\n getCacheKey?: (...args: NoInfer<Args>) => unknown;\n}\n\nexport class Cache<T, Args extends any[] = []> extends Store<Promise<T>> {\n readonly state: Store<CacheState<T>> = createStore<CacheState<T>>({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n\n protected stalePromise?: Promise<T>;\n\n protected invalidationTimer?: ReturnType<typeof setTimeout>;\n\n constructor(\n getter: Calculate<Promise<T>>,\n public readonly args: Args,\n public readonly options: CacheOptions<T, Args> = {},\n public readonly derivedFromCache?: {\n cache: Cache<any, any>;\n selectors: (Selector<any, any> | AnyPath)[];\n },\n ) {\n super(getter, options, undefined);\n autobind(Cache);\n\n this.watchPromise();\n this.watchFocus();\n }\n\n get({ update = 'whenStale', backgroundUpdate = false }: CacheGetOptions = {}): Promise<T> {\n if (!this.calculatedValue?.check()) {\n this.calculatedValue?.stop();\n this.calculatedValue = undefined;\n }\n\n const promise = this.calculatedValue?.value;\n const stalePromise = this.stalePromise;\n\n if (\n (update === 'whenMissing' && !promise && !stalePromise) ||\n (update === 'whenStale' && !promise) ||\n update === 'force'\n ) {\n this.calculatedValue = calculatedValue(this, this.notify);\n this.notify();\n\n if ((!promise && !stalePromise) || !backgroundUpdate) {\n return this.calculatedValue.value;\n }\n }\n\n if (!promise || (stalePromise && backgroundUpdate)) {\n return stalePromise!;\n }\n\n return promise;\n }\n\n updateValue(value: MaybePromise<T> | ((value: T | undefined) => T)): void {\n if (value instanceof Function) {\n value = value(this.state.get().value);\n }\n this.set(PromiseWithState.resolve(value));\n }\n\n updateError(error: unknown): void {\n this.set(PromiseWithState.reject(error));\n }\n\n invalidate(recursive?: boolean): void {\n const { clearOnInvalidate } = this.options;\n\n if (clearOnInvalidate) {\n return this.clear(recursive);\n }\n\n const { status, isStale, isUpdating } = this.state.get();\n if (status !== 'pending' && !isStale && !isUpdating) {\n this.stalePromise = this.calculatedValue?.value;\n }\n\n this.state.set((state) => ({\n ...state,\n isStale: true,\n isUpdating: false,\n }));\n\n super.invalidate(recursive);\n }\n\n clear(recursive?: boolean): void {\n this.state.set({\n status: 'pending',\n isStale: true,\n isUpdating: false,\n isConnected: false,\n });\n delete this.stalePromise;\n\n super.invalidate(recursive);\n }\n\n mapValue<S>(selector: Selector<T, S>): Cache<S, Args>;\n\n mapValue<const P extends AnyPath>(\n selector: P extends Path<T> ? P : Path<T>,\n ): Cache<Value<T, P>, Args>;\n\n mapValue(selector: Selector<any, any> | AnyPath) {\n return mapValue(this, selector);\n }\n\n protected watchPromise(): void {\n this.subscribe(\n async (promise) => {\n if (promise instanceof PromiseWithState && promise.state.status !== 'pending') {\n promise.catch(() => undefined);\n\n this.state.set((state) => ({\n ...promise.state,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n\n delete this.stalePromise;\n this.setTimers();\n return;\n }\n\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.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'value',\n value,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n } catch (error) {\n if (promise !== this.calculatedValue?.value) {\n return;\n }\n\n this.state.set((state) => ({\n status: 'error',\n error,\n isStale: false,\n isUpdating: false,\n isConnected: state.isConnected,\n }));\n delete this.stalePromise;\n this.setTimers();\n }\n },\n { passive: true },\n );\n }\n\n protected setTimers(): void {\n if (this.invalidationTimer) {\n clearTimeout(this.invalidationTimer);\n }\n this.invalidationTimer = undefined;\n\n const state = this.state.get();\n let { invalidateAfter } = 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 !== null && invalidateAfter !== undefined) {\n this.invalidationTimer = setTimeout(\n () => ref?.deref()?.invalidate(),\n calcDuration(invalidateAfter),\n );\n }\n }\n\n protected watchFocus(): void {\n const { invalidateOnWindowFocus } = this.options;\n\n if (\n !invalidateOnWindowFocus ||\n typeof document === 'undefined' ||\n typeof document.addEventListener === 'undefined'\n ) {\n return;\n }\n\n const ref = new WeakRef(this);\n\n const onFocus = () => {\n const that = ref?.deref();\n if (!that) {\n document.removeEventListener('visibilitychange', onFocus);\n return;\n }\n\n if (!document.hidden && !that.state.get().isConnected) {\n that.invalidate();\n }\n };\n\n document.addEventListener('visibilitychange', onFocus);\n }\n}\n\nfunction mapValue<T, S, Args extends any[]>(\n cache: Cache<T, Args>,\n _selector: Selector<T, S> | AnyPath,\n): Cache<S, Args> {\n const selector = makeSelector(_selector);\n const derivedFromCache = {\n cache: cache.derivedFromCache ? cache.derivedFromCache.cache : cache,\n selectors: cache.derivedFromCache\n ? [...cache.derivedFromCache.selectors, _selector]\n : [_selector],\n };\n\n return new Cache<S, Args>(\n async ({ use }) => {\n const value = await use(cache);\n return selector(value);\n },\n cache.args,\n {\n equals: cache.options.equals,\n },\n derivedFromCache,\n );\n}\n\nexport type CreateCacheResult<\n T,\n Args extends any[],\n TCache extends Cache<T, Args>,\n> = [] extends Args ? CacheBundle<T, Args, TCache> & TCache : CacheBundle<T, Args, TCache>;\n\nexport interface InvalidationOptions<T, Args extends any[], TCache extends Cache<T, Args>> {\n filter?: (cache: TCache) => boolean;\n}\n\nexport type CacheBundle<T, Args extends any[], TCache extends Cache<T, Args>> = {\n (...args: Args): TCache;\n mapCache<S>(selector: Selector<T, S>): CreateCacheResult<S, Args, Cache<S, Args>>;\n mapValue<const P>(\n selector: Constrain<P, Path<T>>,\n ): CreateCacheResult<Value<T, P>, Args, Cache<Value<T, P>, Args>>;\n invalidateAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n clearAll: (options?: InvalidationOptions<T, Args, TCache>) => void;\n getInstances: () => TCache[];\n};\n\nfunction create<T, Args extends any[] = []>(\n cacheFunction: CacheFunction<T, Args>,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, Cache<T, Args>> {\n return internalCreate<T, Args, Cache<T, Args>>(\n (args, options) =>\n new Cache(\n (helpers) => {\n const result = cacheFunction.apply(helpers, args);\n\n if (result instanceof Function) {\n return result(helpers);\n }\n\n return result;\n },\n args,\n options,\n undefined,\n ),\n options,\n );\n}\n\nexport function internalCreate<T, Args extends any[], TCache extends Cache<T, Args>>(\n factory: (args: Args, options: CacheOptions<T, Args>) => TCache,\n options?: CacheOptions<T, Args>,\n): CreateCacheResult<T, Args, TCache> {\n options = { ...createCache.defaultOptions, ...options };\n const { clearUnusedAfter, resourceGroup } = options ?? {};\n\n let baseInstance: CacheBundle<T, Args, TCache> & TCache;\n\n const instanceCache = new InstanceCache<Args, TCache>(\n (...args) => factory(args, options),\n clearUnusedAfter ? calcDuration(clearUnusedAfter) : undefined,\n );\n\n function get(...args: Args) {\n const sliceAfter = args.lastIndexOf(undefined);\n if (sliceAfter !== -1) {\n args = args.slice(0, sliceAfter) as Args;\n }\n\n const cacheKey = options?.getCacheKey ? options.getCacheKey(...args) : args;\n return instanceCache.getWithKey(args, cacheKey);\n }\n\n const mapCache = (selector: any) => {\n return internalCreate<any, Args, Cache<any, Args>>((args: Args) =>\n mapValue(baseInstance(...args), selector),\n );\n };\n\n const invalidateAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.invalidate();\n }\n }\n };\n\n const clearAll = ({ filter = () => true }: InvalidationOptions<T, Args, TCache> = {}) => {\n for (const instance of instanceCache.values()) {\n if (filter(instance)) {\n instance.clear();\n }\n }\n };\n\n const getInstances = () => {\n return instanceCache.values();\n };\n\n baseInstance = new Proxy(\n Object.assign(() => undefined, {\n mapCache,\n invalidateAll,\n clearAll,\n getInstances,\n }),\n {\n apply(_target, _thisArg, argArray) {\n return get(...(argArray as unknown as Args));\n },\n get(target, p, receiver) {\n if (Reflect.has(target, p)) {\n return Reflect.get(target, p, receiver);\n }\n\n const baseCache = get(...([] as unknown as Args));\n return Reflect.get(baseCache, p, baseCache);\n },\n },\n ) as unknown as CacheBundle<T, Args, TCache> & TCache;\n\n const groups = Array.isArray(resourceGroup)\n ? resourceGroup\n : resourceGroup\n ? [resourceGroup]\n : [];\n\n for (const group of groups.concat(allResources)) {\n group.add(baseInstance);\n }\n\n return baseInstance;\n}\n\nexport const defaultCacheOptions: CacheOptions<any, any> = {\n invalidateOnWindowFocus: true,\n clearUnusedAfter: { days: 1 },\n retain: { milliseconds: 1 },\n equals: deepEqual,\n};\n\nexport const createCache: typeof create & { defaultOptions: CacheOptions<any, any> } =\n /* @__PURE__ */ Object.assign(create, {\n defaultOptions: defaultCacheOptions,\n });\n","import { autobind } from '@lib/autobind';\n\nexport class Scope<T> {\n constructor(public readonly defaultValue: T) {\n autobind(Scope);\n }\n}\n\nexport function createScope<T>(defaultValue: T): Scope<T> {\n return new Scope(defaultValue);\n}\n"],"mappings":";;;;;AAEA,IAAa,gBAAb,MAAiE;CAO/D,YACE,AAAgBA,SAChB,AAAgBC,WAChB;EAFgB;EACA;+BARF,IAAI;kBAED,KAAK,YACpB,kBAAkB,KAAK,WAAW,KAAK,IAAI,KAAK,YAAY,IAAI,MAChE;;CAOJ,UAAgB;EACd,MAAM,SAAS,KA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iBACD;AAEN,MAAK,MAAM,SAAS,OAAO,OAAO,cAChC,OAAM,IAAI;AAGZ,QAAO;;AAGT,MAAaI,sBAA8C;CACzD,yBAAyB;CACzB,kBAAkB,EAAE,MAAM;CAC1B,QAAQ,EAAE,cAAc;CACxB,QAAQC;;AAGV,MAAaC,cACK,uBAAO,OAAO,QAAQ,EACpC,gBAAgB;;;;ACnepB,IAAa,QAAb,MAAa,MAAS;CACpB,YAAY,AAAgBC,cAAiB;EAAjB;AAC1B,yBAAS;;;AAIb,SAAgB,YAAe,cAA2B;AACxD,QAAO,IAAI,MAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"store-CdST5wJZ.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<Exclude<T, undefined>>;\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] : (x: T) => x !== undefined;\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"],"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ACA,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 +0,0 @@
1
- {"version":3,"file":"store-Dx8w7yT-.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<Exclude<T, undefined>>;\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] : (x: T) => x !== undefined;\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;EAGF,MAAM,aAAa,QAAQ,yBAAyB,OAAO,WAAW;EACtE,IAAI,SAAS,YAAY,WAAW,YAAY;EAChD,IAAI,YAAY;AAEhB,MAAI,OAAO,WAAW,cAAc,OAAO,QACzC;AAGF,UAAQ,eAAe,OAAO,WAAW,KAAK;GAC5C,cAAc;GACd,MAAM;AACJ,QACE,aACA,SAAS,OAAO,aAChB,OAAO,UAAU,eAAe,KAAK,MAAM,QAC3C,OAAO,WAAW,WAElB,QAAO;IAGT,MAAM,eAAe,GAAG,SAAgB,QAAQ,MAAM,QAAQ,MAAM;AACpE,gBAAY,UAAU;AACtB,gBAAY;AAEZ,WAAO,eAAe,MAAM,KAAK;KAC/B,cAAc;KACd,MAAM;AACJ,aAAO;;;AAIX,gBAAY;AACZ,WAAO;;GAET,IAAI,GAAG;AACL,aAAS;;;;AAKf,QAAO;;;;;AClDT,SAAgB,aAAa,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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"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"storeMethods-B_RzvMaV.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,i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;AAG/B,SAAS,SAA4B,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 +0,0 @@
1
- {"version":3,"file":"storeMethods-BrKuusQ2.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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