cross-state 0.54.1 → 0.54.3
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.
- package/dist/mutative/register.cjs.map +1 -1
- package/dist/mutative/register.d.cts +1 -1
- package/dist/mutative/register.d.ts +1 -1
- package/dist/mutative/register.js.map +1 -1
- package/dist/{patchMethods-Dxad6HF6.d.ts → patchMethods-CT9M507t.d.ts} +2 -2
- package/dist/patchMethods-D5YJwcpn.cjs.map +1 -1
- package/dist/patchMethods-DRPfkhAe.js.map +1 -1
- package/dist/{patchMethods-C3L7Kh8T.d.cts → patchMethods-pw_OcPA8.d.cts} +2 -2
- package/dist/patches/index.d.cts +1 -1
- package/dist/patches/index.d.ts +1 -1
- package/dist/patches/register.cjs.map +1 -1
- package/dist/patches/register.d.cts +2 -2
- package/dist/patches/register.d.ts +2 -2
- package/dist/patches/register.js.map +1 -1
- package/dist/persist/register.cjs.map +1 -1
- package/dist/persist/register.d.cts +1 -1
- package/dist/persist/register.d.ts +1 -1
- package/dist/persist/register.js.map +1 -1
- package/dist/react/index.d.cts +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/react/register.cjs.map +1 -1
- package/dist/react/register.d.cts +2 -2
- package/dist/react/register.d.ts +2 -2
- package/dist/react/register.js.map +1 -1
- package/dist/storeMethods-AIJSwxHz.js.map +1 -1
- package/dist/{storeMethods-C4luym7C.d.ts → storeMethods-BjOAF4Pk.d.ts} +2 -2
- package/dist/{storeMethods-BQwU2Uia.d.cts → storeMethods-DIyKFgk1.d.cts} +2 -2
- package/dist/storeMethods-DVVsmUg1.cjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.cjs","names":["Store","mutativeMethods","autobind"],"sources":["../../src/mutative/register.ts"],"sourcesContent":["import { autobind } from '@lib/autobind';\nimport { mutativeMethods } from './mutativeMethods';\nimport { Store } from '@core';\n\ntype MutativeMethods = typeof mutativeMethods;\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.cjs","names":["Store","mutativeMethods","autobind"],"sources":["../../src/mutative/register.ts"],"sourcesContent":["import { autobind } from '@lib/autobind';\nimport { mutativeMethods } from './mutativeMethods';\nimport { Store } from '@core';\n\ntype MutativeMethods = typeof mutativeMethods;\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends MutativeMethods {}\n}\n\nObject.assign(Store.prototype, mutativeMethods);\nautobind(Store);\n"],"mappings":";;;;;AAWA,OAAO,OAAOA,oBAAM,WAAWC;AAC/BC,uBAASF"}
|
|
@@ -3,7 +3,7 @@ import { mutativeMethods } from "../mutativeMethods-6QzygG3W.cjs";
|
|
|
3
3
|
|
|
4
4
|
//#region src/mutative/register.d.ts
|
|
5
5
|
type MutativeMethods = typeof mutativeMethods;
|
|
6
|
-
declare module "
|
|
6
|
+
declare module ".." {
|
|
7
7
|
interface Store<T> extends MutativeMethods {}
|
|
8
8
|
}
|
|
9
9
|
//#endregion
|
|
@@ -3,7 +3,7 @@ import { mutativeMethods } from "../mutativeMethods-Br3xN2Iq.js";
|
|
|
3
3
|
|
|
4
4
|
//#region src/mutative/register.d.ts
|
|
5
5
|
type MutativeMethods = typeof mutativeMethods;
|
|
6
|
-
declare module "
|
|
6
|
+
declare module ".." {
|
|
7
7
|
interface Store<T> extends MutativeMethods {}
|
|
8
8
|
}
|
|
9
9
|
//# sourceMappingURL=register.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.js","names":[],"sources":["../../src/mutative/register.ts"],"sourcesContent":["import { autobind } from '@lib/autobind';\nimport { mutativeMethods } from './mutativeMethods';\nimport { Store } from '@core';\n\ntype MutativeMethods = typeof mutativeMethods;\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.js","names":[],"sources":["../../src/mutative/register.ts"],"sourcesContent":["import { autobind } from '@lib/autobind';\nimport { mutativeMethods } from './mutativeMethods';\nimport { Store } from '@core';\n\ntype MutativeMethods = typeof mutativeMethods;\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends MutativeMethods {}\n}\n\nObject.assign(Store.prototype, mutativeMethods);\nautobind(Store);\n"],"mappings":";;;;;AAWA,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS"}
|
|
@@ -10,7 +10,7 @@ interface SyncMessage {
|
|
|
10
10
|
interface HistoryEntry extends SyncMessage {
|
|
11
11
|
reversePatches: Patch[];
|
|
12
12
|
}
|
|
13
|
-
declare module "
|
|
13
|
+
declare module ".." {
|
|
14
14
|
interface Store<T> {
|
|
15
15
|
__patches?: {
|
|
16
16
|
value: T;
|
|
@@ -45,4 +45,4 @@ declare const patchMethods: {
|
|
|
45
45
|
};
|
|
46
46
|
//#endregion
|
|
47
47
|
export { SubscribePatchOptions, SyncMessage, patchMethods };
|
|
48
|
-
//# sourceMappingURL=patchMethods-
|
|
48
|
+
//# sourceMappingURL=patchMethods-CT9M507t.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patchMethods-D5YJwcpn.cjs","names":["remove","set","deepEqual","isObject","applyPatches","_applyPatches","toExtendedJson","fromExtendedJson","patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n}"],"sources":["../src/lib/applyPatches.ts","../src/lib/diff.ts","../src/lib/trie.ts","../src/patches/patchMethods.ts"],"sourcesContent":["import type { Patch } from './diff';\nimport { remove, set } from './propAccess';\n\nfunction applySinglePatch<T>(target: T, patch: Patch): T {\n if (patch.op === 'remove') {\n return remove(target, patch.path as any);\n }\n\n return set(target, patch.path as any, patch.value);\n}\n\nexport function applyPatches<T>(target: T, ...patches: Patch[]): T {\n for (const patch of patches) {\n target = applySinglePatch(target, patch);\n }\n\n return target;\n}\n","import { isObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\nimport type { KeyType } from './path';\n\nexport type Patch =\n | { op: 'add'; path: KeyType[]; value: any }\n | { op: 'remove'; path: KeyType[] }\n | { op: 'replace'; path: KeyType[]; value: any };\n\nexport interface DiffOptions {\n stopAt?: number | ((path: KeyType[]) => boolean);\n}\n\nexport function diff(\n a: any,\n b: any,\n options: DiffOptions = {},\n): [patches: Patch[], reversePatches: Patch[]] {\n const result = [..._diff(a, b, options)];\n const patches = result.map(([patch]) => patch);\n const reversePatches = result.map(([, reversePatch]) => reversePatch);\n\n return [patches, reversePatches];\n}\n\nfunction* _diff(\n a: any,\n b: any,\n options: DiffOptions,\n prefix: KeyType[] = [],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n if (a === b) {\n return;\n }\n\n if (\n (typeof options.stopAt === 'number' && prefix.length >= options.stopAt) ||\n (typeof options.stopAt === 'function' && options.stopAt(prefix))\n ) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Date && b instanceof Date) {\n if (a.getTime() === b.getTime()) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Map && b instanceof Map) {\n return yield* mapDiff(a, b, options, prefix);\n }\n\n if (a instanceof Set && b instanceof Set) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (isObject(a) && isObject(b) && !Array.isArray(a) && !Array.isArray(b)) {\n return yield* objectDiff(a, b, options, prefix);\n }\n\n yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n}\n\nfunction* mapDiff(\n a: Map<any, any>,\n b: Map<any, any>,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of a) {\n if (!b.has(key)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b.get(key), options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of b) {\n if (!a.has(key)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n\nfunction* objectDiff(\n a: any,\n b: any,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of Object.entries(a)) {\n if (!(key in b)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b[key], options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of Object.entries(b)) {\n if (!(key in a)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n","import type { KeyType } from '@lib/path';\n\nclass TrieNode {\n children: Map<KeyType, TrieNode> = new Map();\n isLeaf = false;\n}\n\nexport class Trie {\n root: TrieNode = new TrieNode();\n\n add(path: KeyType[]): void {\n let node = this.root;\n for (const key of path) {\n let next = node.children.get(key);\n if (!next) node.children.set(key, (next = new TrieNode()));\n node = next;\n }\n node.isLeaf = true;\n }\n\n hasSubPath(path: KeyType[]): boolean {\n let node = this.root;\n for (const key of path) {\n const next = node.children.get(key);\n if (!next) return false;\n node = next;\n }\n return node.isLeaf;\n }\n}\n","import type { Cancel, DisposableCancel, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { applyPatches as _applyPatches } from '@lib/applyPatches';\nimport { diff, type DiffOptions, type Patch } from '@lib/diff';\nimport { fromExtendedJson, toExtendedJson } from '@lib/extendedJson';\nimport { Trie } from '@lib/trie';\n\nexport interface SyncMessage {\n fromVersion?: string;\n toVersion: string;\n patches: Patch[];\n}\n\nexport interface HistoryEntry extends SyncMessage {\n reversePatches: Patch[];\n}\n\ndeclare module '@core' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> {\n __patches?: {\n value: T;\n version: string;\n history: HistoryEntry[];\n };\n }\n}\n\nexport interface SubscribePatchOptions extends SubscribeOptions, DiffOptions {\n /** @default false */\n runNow?: boolean;\n /** try to start from a specific version and only receive patches after that.\n * If the id is not found, it will start from the beginning */\n startAt?: string;\n}\n\nexport type InteropPatch = Patch | { op: 'add' | 'replace' | 'remove'; value?: any };\n\nconst genId = () => Math.random().toString(36).slice(2);\n\nexport function subscribePatches<T>(\n this: Store<T>,\n listener: (\n this: { cancel: Cancel },\n patches: Patch[],\n reversePatches: Patch[],\n version: string,\n previousVersion: string | undefined,\n ) => void,\n options: SubscribePatchOptions = {},\n): DisposableCancel {\n const patches = (this.__patches ??= {\n value: this.get(),\n version: genId(),\n history: [],\n });\n\n options = { ...options };\n options.runNow ??= false;\n let cursor = options.startAt ?? (options.runNow ? undefined : this.__patches.version);\n\n return this.subscribe(function (value) {\n if (patches.value !== value) {\n const result = diff(patches.value, value, options);\n patches.value = value;\n\n if (result[0].length > 0) {\n const newVersion = genId();\n\n patches.history = patches.history\n .concat({\n fromVersion: patches.version,\n toVersion: newVersion,\n patches: result[0],\n reversePatches: result[1],\n })\n .slice(-1000);\n\n patches.version = newVersion;\n }\n }\n\n if (cursor === patches.version) return;\n const index = patches.history.findIndex((h) => h.fromVersion === cursor);\n let forward, backward, previousVersion;\n\n if (index === -1) {\n [forward, backward] = diff(undefined, value, options);\n previousVersion = undefined;\n } else {\n forward = patches.history.slice(index).flatMap((h) => h.patches);\n backward = patches.history.slice(index).flatMap((h) => h.reversePatches);\n previousVersion = cursor;\n }\n\n cursor = patches.version;\n listener.apply(this, [forward, backward, cursor, previousVersion]);\n }, options);\n}\n\nexport function applyPatches<T>(this: Store<T>, patches: InteropPatch[]): void;\nexport function applyPatches<T>(this: Store<T>, ...patches: InteropPatch[]): void;\nexport function applyPatches<T>(\n this: Store<T>,\n ...patches: (InteropPatch | InteropPatch[])[]\n): void {\n this.set((value) => _applyPatches(value, ...(patches.flat() as Patch[])));\n}\n\nexport function sync<T>(\n this: Store<T>,\n listener: (syncMessage: SyncMessage) => void,\n options?: Omit<SubscribePatchOptions, 'runNow'>,\n): DisposableCancel {\n const debounce =\n typeof options?.debounce === 'object' && 'wait' in options.debounce\n ? { ...options.debounce }\n : options?.debounce !== undefined\n ? { wait: options.debounce }\n : undefined;\n\n if (debounce) {\n debounce.waitOnRunNow ??= false;\n }\n\n return subscribePatches.apply<\n Store<T>,\n Parameters<typeof subscribePatches<T>>,\n ReturnType<typeof subscribePatches<T>>\n >(this, [\n (patches, _, version, previousVersion) => {\n const trie = new Trie();\n\n patches = [...patches]\n .reverse()\n .filter((patch) => {\n if (trie.hasSubPath(patch.path)) {\n return false;\n }\n\n trie.add(patch.path);\n return true;\n })\n .reverse();\n\n listener({\n fromVersion: previousVersion,\n toVersion: version,\n patches: toExtendedJson(patches) as Patch[],\n });\n },\n { ...options, debounce, runNow: true },\n ]);\n}\n\nexport function acceptSync<T>(this: Store<T>, message: SyncMessage): void {\n if (message.fromVersion && message.fromVersion !== this.version) {\n throw new Error(\n `version mismatch! version=${this.version}, fromVersion=${message.fromVersion}`,\n );\n }\n\n const patches = fromExtendedJson(message.patches) as Patch[];\n\n this.version = message.toVersion;\n applyPatches.apply<Store<T>, Patch[], void>(this, patches);\n}\n\nexport const patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n} = {\n subscribePatches,\n applyPatches,\n sync,\n acceptSync,\n};\n"],"mappings":";;;;AAGA,SAAS,iBAAoB,QAAW,OAAiB;AACvD,KAAI,MAAM,OAAO,SACf,QAAOA,0BAAO,QAAQ,MAAM;AAG9B,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AAChB,IAAC,SAAS,YAAY,KAAK,QAAW,OAAO;AAC7C,qBAAkB;SACb;AACL,aAAU,QAAQ,QAAQ,MAAM,OAAO,SAAS,MAAM,EAAE;AACxD,cAAW,QAAQ,QAAQ,MAAM,OAAO,SAAS,MAAM,EAAE;AACzD,qBAAkB;;AAGpB,WAAS,QAAQ;AACjB,WAAS,MAAM,MAAM;GAAC;GAAS;GAAU;GAAQ;;IAChD;;AAKL,SAAgBC,eAEd,GAAG,SACG;AACN,MAAK,KAAK,UAAUC,aAAc,OAAO,GAAI,QAAQ;;AAGvD,SAAgB,KAEd,UACA,SACkB;CAClB,MAAM,WACJ,OAAO,SAAS,aAAa,YAAY,UAAU,QAAQ,WACvD,EAAE,GAAG,QAAQ,aACb,SAAS,aAAa,SACpB,EAAE,MAAM,QAAQ,aAChB;AAER,KAAI,SACF,UAAS,iBAAiB;AAG5B,QAAO,iBAAiB,MAItB,MAAM,EACL,SAAS,GAAG,SAAS,oBAAoB;EACxC,MAAM,OAAO,IAAI;AAEjB,YAAU,CAAC,GAAG,SACX,UACA,QAAQ,UAAU;AACjB,OAAI,KAAK,WAAW,MAAM,MACxB,QAAO;AAGT,QAAK,IAAI,MAAM;AACf,UAAO;KAER;AAEH,WAAS;GACP,aAAa;GACb,WAAW;GACX,SAASC,oCAAe;;IAG5B;EAAE,GAAG;EAAS;EAAU,QAAQ;;;AAIpC,SAAgB,WAA8B,SAA4B;AACxE,KAAI,QAAQ,eAAe,QAAQ,gBAAgB,KAAK,QACtD,OAAM,IAAI,MACR,6BAA6B,KAAK,QAAQ,gBAAgB,QAAQ;CAItE,MAAM,UAAUC,sCAAiB,QAAQ;AAEzC,MAAK,UAAU,QAAQ;AACvB,gBAAa,MAA+B,MAAM;;AAGpD,MAAaC,eAKT;CACF;CACA;CACA;CACA"}
|
|
1
|
+
{"version":3,"file":"patchMethods-D5YJwcpn.cjs","names":["remove","set","deepEqual","isObject","applyPatches","_applyPatches","toExtendedJson","fromExtendedJson","patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n}"],"sources":["../src/lib/applyPatches.ts","../src/lib/diff.ts","../src/lib/trie.ts","../src/patches/patchMethods.ts"],"sourcesContent":["import type { Patch } from './diff';\nimport { remove, set } from './propAccess';\n\nfunction applySinglePatch<T>(target: T, patch: Patch): T {\n if (patch.op === 'remove') {\n return remove(target, patch.path as any);\n }\n\n return set(target, patch.path as any, patch.value);\n}\n\nexport function applyPatches<T>(target: T, ...patches: Patch[]): T {\n for (const patch of patches) {\n target = applySinglePatch(target, patch);\n }\n\n return target;\n}\n","import { isObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\nimport type { KeyType } from './path';\n\nexport type Patch =\n | { op: 'add'; path: KeyType[]; value: any }\n | { op: 'remove'; path: KeyType[] }\n | { op: 'replace'; path: KeyType[]; value: any };\n\nexport interface DiffOptions {\n stopAt?: number | ((path: KeyType[]) => boolean);\n}\n\nexport function diff(\n a: any,\n b: any,\n options: DiffOptions = {},\n): [patches: Patch[], reversePatches: Patch[]] {\n const result = [..._diff(a, b, options)];\n const patches = result.map(([patch]) => patch);\n const reversePatches = result.map(([, reversePatch]) => reversePatch);\n\n return [patches, reversePatches];\n}\n\nfunction* _diff(\n a: any,\n b: any,\n options: DiffOptions,\n prefix: KeyType[] = [],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n if (a === b) {\n return;\n }\n\n if (\n (typeof options.stopAt === 'number' && prefix.length >= options.stopAt) ||\n (typeof options.stopAt === 'function' && options.stopAt(prefix))\n ) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Date && b instanceof Date) {\n if (a.getTime() === b.getTime()) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Map && b instanceof Map) {\n return yield* mapDiff(a, b, options, prefix);\n }\n\n if (a instanceof Set && b instanceof Set) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (isObject(a) && isObject(b) && !Array.isArray(a) && !Array.isArray(b)) {\n return yield* objectDiff(a, b, options, prefix);\n }\n\n yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n}\n\nfunction* mapDiff(\n a: Map<any, any>,\n b: Map<any, any>,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of a) {\n if (!b.has(key)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b.get(key), options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of b) {\n if (!a.has(key)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n\nfunction* objectDiff(\n a: any,\n b: any,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of Object.entries(a)) {\n if (!(key in b)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b[key], options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of Object.entries(b)) {\n if (!(key in a)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n","import type { KeyType } from '@lib/path';\n\nclass TrieNode {\n children: Map<KeyType, TrieNode> = new Map();\n isLeaf = false;\n}\n\nexport class Trie {\n root: TrieNode = new TrieNode();\n\n add(path: KeyType[]): void {\n let node = this.root;\n for (const key of path) {\n let next = node.children.get(key);\n if (!next) node.children.set(key, (next = new TrieNode()));\n node = next;\n }\n node.isLeaf = true;\n }\n\n hasSubPath(path: KeyType[]): boolean {\n let node = this.root;\n for (const key of path) {\n const next = node.children.get(key);\n if (!next) return false;\n node = next;\n }\n return node.isLeaf;\n }\n}\n","import type { Cancel, DisposableCancel, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { applyPatches as _applyPatches } from '@lib/applyPatches';\nimport { diff, type DiffOptions, type Patch } from '@lib/diff';\nimport { fromExtendedJson, toExtendedJson } from '@lib/extendedJson';\nimport { Trie } from '@lib/trie';\n\nexport interface SyncMessage {\n fromVersion?: string;\n toVersion: string;\n patches: Patch[];\n}\n\nexport interface HistoryEntry extends SyncMessage {\n reversePatches: Patch[];\n}\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> {\n __patches?: {\n value: T;\n version: string;\n history: HistoryEntry[];\n };\n }\n}\n\nexport interface SubscribePatchOptions extends SubscribeOptions, DiffOptions {\n /** @default false */\n runNow?: boolean;\n /** try to start from a specific version and only receive patches after that.\n * If the id is not found, it will start from the beginning */\n startAt?: string;\n}\n\nexport type InteropPatch = Patch | { op: 'add' | 'replace' | 'remove'; value?: any };\n\nconst genId = () => Math.random().toString(36).slice(2);\n\nexport function subscribePatches<T>(\n this: Store<T>,\n listener: (\n this: { cancel: Cancel },\n patches: Patch[],\n reversePatches: Patch[],\n version: string,\n previousVersion: string | undefined,\n ) => void,\n options: SubscribePatchOptions = {},\n): DisposableCancel {\n const patches = (this.__patches ??= {\n value: this.get(),\n version: genId(),\n history: [],\n });\n\n options = { ...options };\n options.runNow ??= false;\n let cursor = options.startAt ?? (options.runNow ? undefined : this.__patches.version);\n\n return this.subscribe(function (value) {\n if (patches.value !== value) {\n const result = diff(patches.value, value, options);\n patches.value = value;\n\n if (result[0].length > 0) {\n const newVersion = genId();\n\n patches.history = patches.history\n .concat({\n fromVersion: patches.version,\n toVersion: newVersion,\n patches: result[0],\n reversePatches: result[1],\n })\n .slice(-1000);\n\n patches.version = newVersion;\n }\n }\n\n if (cursor === patches.version) return;\n const index = patches.history.findIndex((h) => h.fromVersion === cursor);\n let forward, backward, previousVersion;\n\n if (index === -1) {\n [forward, backward] = diff(undefined, value, options);\n previousVersion = undefined;\n } else {\n forward = patches.history.slice(index).flatMap((h) => h.patches);\n backward = patches.history.slice(index).flatMap((h) => h.reversePatches);\n previousVersion = cursor;\n }\n\n cursor = patches.version;\n listener.apply(this, [forward, backward, cursor, previousVersion]);\n }, options);\n}\n\nexport function applyPatches<T>(this: Store<T>, patches: InteropPatch[]): void;\nexport function applyPatches<T>(this: Store<T>, ...patches: InteropPatch[]): void;\nexport function applyPatches<T>(\n this: Store<T>,\n ...patches: (InteropPatch | InteropPatch[])[]\n): void {\n this.set((value) => _applyPatches(value, ...(patches.flat() as Patch[])));\n}\n\nexport function sync<T>(\n this: Store<T>,\n listener: (syncMessage: SyncMessage) => void,\n options?: Omit<SubscribePatchOptions, 'runNow'>,\n): DisposableCancel {\n const debounce =\n typeof options?.debounce === 'object' && 'wait' in options.debounce\n ? { ...options.debounce }\n : options?.debounce !== undefined\n ? { wait: options.debounce }\n : undefined;\n\n if (debounce) {\n debounce.waitOnRunNow ??= false;\n }\n\n return subscribePatches.apply<\n Store<T>,\n Parameters<typeof subscribePatches<T>>,\n ReturnType<typeof subscribePatches<T>>\n >(this, [\n (patches, _, version, previousVersion) => {\n const trie = new Trie();\n\n patches = [...patches]\n .reverse()\n .filter((patch) => {\n if (trie.hasSubPath(patch.path)) {\n return false;\n }\n\n trie.add(patch.path);\n return true;\n })\n .reverse();\n\n listener({\n fromVersion: previousVersion,\n toVersion: version,\n patches: toExtendedJson(patches) as Patch[],\n });\n },\n { ...options, debounce, runNow: true },\n ]);\n}\n\nexport function acceptSync<T>(this: Store<T>, message: SyncMessage): void {\n if (message.fromVersion && message.fromVersion !== this.version) {\n throw new Error(\n `version mismatch! version=${this.version}, fromVersion=${message.fromVersion}`,\n );\n }\n\n const patches = fromExtendedJson(message.patches) as Patch[];\n\n this.version = message.toVersion;\n applyPatches.apply<Store<T>, Patch[], void>(this, patches);\n}\n\nexport const patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n} = {\n subscribePatches,\n applyPatches,\n sync,\n acceptSync,\n};\n"],"mappings":";;;;AAGA,SAAS,iBAAoB,QAAW,OAAiB;AACvD,KAAI,MAAM,OAAO,SACf,QAAOA,0BAAO,QAAQ,MAAM;AAG9B,QAAOC,uBAAI,QAAQ,MAAM,MAAa,MAAM;;AAG9C,SAAgB,aAAgB,QAAW,GAAG,SAAqB;AACjE,MAAK,MAAM,SAAS,QAClB,UAAS,iBAAiB,QAAQ;AAGpC,QAAO;;;;;ACHT,SAAgB,KACd,GACA,GACA,UAAuB,IACsB;CAC7C,MAAM,SAAS,CAAC,GAAG,MAAM,GAAG,GAAG;CAC/B,MAAM,UAAU,OAAO,KAAK,CAAC,WAAW;CACxC,MAAM,iBAAiB,OAAO,KAAK,GAAG,kBAAkB;AAExD,QAAO,CAAC,SAAS;;AAGnB,UAAU,MACR,GACA,GACA,SACA,SAAoB,IAC2B;AAC/C,KAAI,MAAM,EACR;AAGF,KACG,OAAO,QAAQ,WAAW,YAAY,OAAO,UAAU,QAAQ,UAC/D,OAAO,QAAQ,WAAW,cAAc,QAAQ,OAAO,SACxD;AACA,MAAIC,6BAAU,GAAG,GACf;AAGF,SAAO,MAAM,CACX;GAAE,IAAI;GAAW,MAAM;GAAQ,OAAO;KACtC;GAAE,IAAI;GAAW,MAAM;GAAQ,OAAO;;;AAI1C,KAAI,aAAa,QAAQ,aAAa,MAAM;AAC1C,MAAI,EAAE,cAAc,EAAE,UACpB;AAGF,SAAO,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AAEH,WAAS;GACP,aAAa;GACb,WAAW;GACX,SAASC,oCAAe;;IAG5B;EAAE,GAAG;EAAS;EAAU,QAAQ;;;AAIpC,SAAgB,WAA8B,SAA4B;AACxE,KAAI,QAAQ,eAAe,QAAQ,gBAAgB,KAAK,QACtD,OAAM,IAAI,MACR,6BAA6B,KAAK,QAAQ,gBAAgB,QAAQ;CAItE,MAAM,UAAUC,sCAAiB,QAAQ;AAEzC,MAAK,UAAU,QAAQ;AACvB,gBAAa,MAA+B,MAAM;;AAGpD,MAAaC,eAKT;CACF;CACA;CACA;CACA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patchMethods-DRPfkhAe.js","names":["applyPatches","_applyPatches","patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n}"],"sources":["../src/lib/applyPatches.ts","../src/lib/diff.ts","../src/lib/trie.ts","../src/patches/patchMethods.ts"],"sourcesContent":["import type { Patch } from './diff';\nimport { remove, set } from './propAccess';\n\nfunction applySinglePatch<T>(target: T, patch: Patch): T {\n if (patch.op === 'remove') {\n return remove(target, patch.path as any);\n }\n\n return set(target, patch.path as any, patch.value);\n}\n\nexport function applyPatches<T>(target: T, ...patches: Patch[]): T {\n for (const patch of patches) {\n target = applySinglePatch(target, patch);\n }\n\n return target;\n}\n","import { isObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\nimport type { KeyType } from './path';\n\nexport type Patch =\n | { op: 'add'; path: KeyType[]; value: any }\n | { op: 'remove'; path: KeyType[] }\n | { op: 'replace'; path: KeyType[]; value: any };\n\nexport interface DiffOptions {\n stopAt?: number | ((path: KeyType[]) => boolean);\n}\n\nexport function diff(\n a: any,\n b: any,\n options: DiffOptions = {},\n): [patches: Patch[], reversePatches: Patch[]] {\n const result = [..._diff(a, b, options)];\n const patches = result.map(([patch]) => patch);\n const reversePatches = result.map(([, reversePatch]) => reversePatch);\n\n return [patches, reversePatches];\n}\n\nfunction* _diff(\n a: any,\n b: any,\n options: DiffOptions,\n prefix: KeyType[] = [],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n if (a === b) {\n return;\n }\n\n if (\n (typeof options.stopAt === 'number' && prefix.length >= options.stopAt) ||\n (typeof options.stopAt === 'function' && options.stopAt(prefix))\n ) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Date && b instanceof Date) {\n if (a.getTime() === b.getTime()) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Map && b instanceof Map) {\n return yield* mapDiff(a, b, options, prefix);\n }\n\n if (a instanceof Set && b instanceof Set) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (isObject(a) && isObject(b) && !Array.isArray(a) && !Array.isArray(b)) {\n return yield* objectDiff(a, b, options, prefix);\n }\n\n yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n}\n\nfunction* mapDiff(\n a: Map<any, any>,\n b: Map<any, any>,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of a) {\n if (!b.has(key)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b.get(key), options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of b) {\n if (!a.has(key)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n\nfunction* objectDiff(\n a: any,\n b: any,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of Object.entries(a)) {\n if (!(key in b)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b[key], options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of Object.entries(b)) {\n if (!(key in a)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n","import type { KeyType } from '@lib/path';\n\nclass TrieNode {\n children: Map<KeyType, TrieNode> = new Map();\n isLeaf = false;\n}\n\nexport class Trie {\n root: TrieNode = new TrieNode();\n\n add(path: KeyType[]): void {\n let node = this.root;\n for (const key of path) {\n let next = node.children.get(key);\n if (!next) node.children.set(key, (next = new TrieNode()));\n node = next;\n }\n node.isLeaf = true;\n }\n\n hasSubPath(path: KeyType[]): boolean {\n let node = this.root;\n for (const key of path) {\n const next = node.children.get(key);\n if (!next) return false;\n node = next;\n }\n return node.isLeaf;\n }\n}\n","import type { Cancel, DisposableCancel, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { applyPatches as _applyPatches } from '@lib/applyPatches';\nimport { diff, type DiffOptions, type Patch } from '@lib/diff';\nimport { fromExtendedJson, toExtendedJson } from '@lib/extendedJson';\nimport { Trie } from '@lib/trie';\n\nexport interface SyncMessage {\n fromVersion?: string;\n toVersion: string;\n patches: Patch[];\n}\n\nexport interface HistoryEntry extends SyncMessage {\n reversePatches: Patch[];\n}\n\ndeclare module '@core' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> {\n __patches?: {\n value: T;\n version: string;\n history: HistoryEntry[];\n };\n }\n}\n\nexport interface SubscribePatchOptions extends SubscribeOptions, DiffOptions {\n /** @default false */\n runNow?: boolean;\n /** try to start from a specific version and only receive patches after that.\n * If the id is not found, it will start from the beginning */\n startAt?: string;\n}\n\nexport type InteropPatch = Patch | { op: 'add' | 'replace' | 'remove'; value?: any };\n\nconst genId = () => Math.random().toString(36).slice(2);\n\nexport function subscribePatches<T>(\n this: Store<T>,\n listener: (\n this: { cancel: Cancel },\n patches: Patch[],\n reversePatches: Patch[],\n version: string,\n previousVersion: string | undefined,\n ) => void,\n options: SubscribePatchOptions = {},\n): DisposableCancel {\n const patches = (this.__patches ??= {\n value: this.get(),\n version: genId(),\n history: [],\n });\n\n options = { ...options };\n options.runNow ??= false;\n let cursor = options.startAt ?? (options.runNow ? undefined : this.__patches.version);\n\n return this.subscribe(function (value) {\n if (patches.value !== value) {\n const result = diff(patches.value, value, options);\n patches.value = value;\n\n if (result[0].length > 0) {\n const newVersion = genId();\n\n patches.history = patches.history\n .concat({\n fromVersion: patches.version,\n toVersion: newVersion,\n patches: result[0],\n reversePatches: result[1],\n })\n .slice(-1000);\n\n patches.version = newVersion;\n }\n }\n\n if (cursor === patches.version) return;\n const index = patches.history.findIndex((h) => h.fromVersion === cursor);\n let forward, backward, previousVersion;\n\n if (index === -1) {\n [forward, backward] = diff(undefined, value, options);\n previousVersion = undefined;\n } else {\n forward = patches.history.slice(index).flatMap((h) => h.patches);\n backward = patches.history.slice(index).flatMap((h) => h.reversePatches);\n previousVersion = cursor;\n }\n\n cursor = patches.version;\n listener.apply(this, [forward, backward, cursor, previousVersion]);\n }, options);\n}\n\nexport function applyPatches<T>(this: Store<T>, patches: InteropPatch[]): void;\nexport function applyPatches<T>(this: Store<T>, ...patches: InteropPatch[]): void;\nexport function applyPatches<T>(\n this: Store<T>,\n ...patches: (InteropPatch | InteropPatch[])[]\n): void {\n this.set((value) => _applyPatches(value, ...(patches.flat() as Patch[])));\n}\n\nexport function sync<T>(\n this: Store<T>,\n listener: (syncMessage: SyncMessage) => void,\n options?: Omit<SubscribePatchOptions, 'runNow'>,\n): DisposableCancel {\n const debounce =\n typeof options?.debounce === 'object' && 'wait' in options.debounce\n ? { ...options.debounce }\n : options?.debounce !== undefined\n ? { wait: options.debounce }\n : undefined;\n\n if (debounce) {\n debounce.waitOnRunNow ??= false;\n }\n\n return subscribePatches.apply<\n Store<T>,\n Parameters<typeof subscribePatches<T>>,\n ReturnType<typeof subscribePatches<T>>\n >(this, [\n (patches, _, version, previousVersion) => {\n const trie = new Trie();\n\n patches = [...patches]\n .reverse()\n .filter((patch) => {\n if (trie.hasSubPath(patch.path)) {\n return false;\n }\n\n trie.add(patch.path);\n return true;\n })\n .reverse();\n\n listener({\n fromVersion: previousVersion,\n toVersion: version,\n patches: toExtendedJson(patches) as Patch[],\n });\n },\n { ...options, debounce, runNow: true },\n ]);\n}\n\nexport function acceptSync<T>(this: Store<T>, message: SyncMessage): void {\n if (message.fromVersion && message.fromVersion !== this.version) {\n throw new Error(\n `version mismatch! version=${this.version}, fromVersion=${message.fromVersion}`,\n );\n }\n\n const patches = fromExtendedJson(message.patches) as Patch[];\n\n this.version = message.toVersion;\n applyPatches.apply<Store<T>, Patch[], void>(this, patches);\n}\n\nexport const patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n} = {\n subscribePatches,\n applyPatches,\n sync,\n acceptSync,\n};\n"],"mappings":";;;;AAGA,SAAS,iBAAoB,QAAW,OAAiB;AACvD,KAAI,MAAM,OAAO,SACf,QAAO,OAAO,QAAQ,MAAM;AAG9B,QAAO,IAAI,QAAQ,MAAM,MAAa,MAAM;;AAG9C,SAAgB,aAAgB,QAAW,GAAG,SAAqB;AACjE,MAAK,MAAM,SAAS,QAClB,UAAS,iBAAiB,QAAQ;AAGpC,QAAO;;;;;ACHT,SAAgB,KACd,GACA,GACA,UAAuB,IACsB;CAC7C,MAAM,SAAS,CAAC,GAAG,MAAM,GAAG,GAAG;CAC/B,MAAM,UAAU,OAAO,KAAK,CAAC,WAAW;CACxC,MAAM,iBAAiB,OAA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C,aAAc,OAAO,GAAI,QAAQ;;AAGvD,SAAgB,KAEd,UACA,SACkB;CAClB,MAAM,WACJ,OAAO,SAAS,aAAa,YAAY,UAAU,QAAQ,WACvD,EAAE,GAAG,QAAQ,aACb,SAAS,aAAa,SACpB,EAAE,MAAM,QAAQ,aAChB;AAER,KAAI,SACF,UAAS,iBAAiB;AAG5B,QAAO,iBAAiB,MAItB,MAAM,EACL,SAAS,GAAG,SAAS,oBAAoB;EACxC,MAAM,OAAO,IAAI;AAEjB,YAAU,CAAC,GAAG,SACX,UACA,QAAQ,UAAU;AACjB,OAAI,KAAK,WAAW,MAAM,MACxB,QAAO;AAGT,QAAK,IAAI,MAAM;AACf,UAAO;KAER;AAEH,WAAS;GACP,aAAa;GACb,WAAW;GACX,SAAS,eAAe;;IAG5B;EAAE,GAAG;EAAS;EAAU,QAAQ;;;AAIpC,SAAgB,WAA8B,SAA4B;AACxE,KAAI,QAAQ,eAAe,QAAQ,gBAAgB,KAAK,QACtD,OAAM,IAAI,MACR,6BAA6B,KAAK,QAAQ,gBAAgB,QAAQ;CAItE,MAAM,UAAU,iBAAiB,QAAQ;AAEzC,MAAK,UAAU,QAAQ;AACvB,gBAAa,MAA+B,MAAM;;AAGpD,MAAaC,eAKT;CACF;CACA;CACA;CACA"}
|
|
1
|
+
{"version":3,"file":"patchMethods-DRPfkhAe.js","names":["applyPatches","_applyPatches","patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n}"],"sources":["../src/lib/applyPatches.ts","../src/lib/diff.ts","../src/lib/trie.ts","../src/patches/patchMethods.ts"],"sourcesContent":["import type { Patch } from './diff';\nimport { remove, set } from './propAccess';\n\nfunction applySinglePatch<T>(target: T, patch: Patch): T {\n if (patch.op === 'remove') {\n return remove(target, patch.path as any);\n }\n\n return set(target, patch.path as any, patch.value);\n}\n\nexport function applyPatches<T>(target: T, ...patches: Patch[]): T {\n for (const patch of patches) {\n target = applySinglePatch(target, patch);\n }\n\n return target;\n}\n","import { isObject } from '@lib/helpers';\nimport { deepEqual } from './equals';\nimport type { KeyType } from './path';\n\nexport type Patch =\n | { op: 'add'; path: KeyType[]; value: any }\n | { op: 'remove'; path: KeyType[] }\n | { op: 'replace'; path: KeyType[]; value: any };\n\nexport interface DiffOptions {\n stopAt?: number | ((path: KeyType[]) => boolean);\n}\n\nexport function diff(\n a: any,\n b: any,\n options: DiffOptions = {},\n): [patches: Patch[], reversePatches: Patch[]] {\n const result = [..._diff(a, b, options)];\n const patches = result.map(([patch]) => patch);\n const reversePatches = result.map(([, reversePatch]) => reversePatch);\n\n return [patches, reversePatches];\n}\n\nfunction* _diff(\n a: any,\n b: any,\n options: DiffOptions,\n prefix: KeyType[] = [],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n if (a === b) {\n return;\n }\n\n if (\n (typeof options.stopAt === 'number' && prefix.length >= options.stopAt) ||\n (typeof options.stopAt === 'function' && options.stopAt(prefix))\n ) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Date && b instanceof Date) {\n if (a.getTime() === b.getTime()) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (a instanceof Map && b instanceof Map) {\n return yield* mapDiff(a, b, options, prefix);\n }\n\n if (a instanceof Set && b instanceof Set) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (deepEqual(a, b)) {\n return;\n }\n\n return yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n }\n\n if (isObject(a) && isObject(b) && !Array.isArray(a) && !Array.isArray(b)) {\n return yield* objectDiff(a, b, options, prefix);\n }\n\n yield [\n { op: 'replace', path: prefix, value: b },\n { op: 'replace', path: prefix, value: a },\n ];\n}\n\nfunction* mapDiff(\n a: Map<any, any>,\n b: Map<any, any>,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of a) {\n if (!b.has(key)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b.get(key), options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of b) {\n if (!a.has(key)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n\nfunction* objectDiff(\n a: any,\n b: any,\n options: { stopAt?: number | ((path: KeyType[]) => boolean) },\n prefix: KeyType[],\n): Iterable<[patch: Patch, reversePatch: Patch]> {\n for (const [key, value] of Object.entries(a)) {\n if (!(key in b)) {\n yield [\n { op: 'remove', path: [...prefix, key] },\n { op: 'add', path: [...prefix, key], value },\n ];\n } else {\n yield* _diff(value, b[key], options, [...prefix, key]);\n }\n }\n\n for (const [key, value] of Object.entries(b)) {\n if (!(key in a)) {\n yield [\n { op: 'add', path: [...prefix, key], value },\n { op: 'remove', path: [...prefix, key] },\n ];\n }\n }\n}\n","import type { KeyType } from '@lib/path';\n\nclass TrieNode {\n children: Map<KeyType, TrieNode> = new Map();\n isLeaf = false;\n}\n\nexport class Trie {\n root: TrieNode = new TrieNode();\n\n add(path: KeyType[]): void {\n let node = this.root;\n for (const key of path) {\n let next = node.children.get(key);\n if (!next) node.children.set(key, (next = new TrieNode()));\n node = next;\n }\n node.isLeaf = true;\n }\n\n hasSubPath(path: KeyType[]): boolean {\n let node = this.root;\n for (const key of path) {\n const next = node.children.get(key);\n if (!next) return false;\n node = next;\n }\n return node.isLeaf;\n }\n}\n","import type { Cancel, DisposableCancel, SubscribeOptions } from '@core/commonTypes';\nimport type { Store } from '@core/store';\nimport { applyPatches as _applyPatches } from '@lib/applyPatches';\nimport { diff, type DiffOptions, type Patch } from '@lib/diff';\nimport { fromExtendedJson, toExtendedJson } from '@lib/extendedJson';\nimport { Trie } from '@lib/trie';\n\nexport interface SyncMessage {\n fromVersion?: string;\n toVersion: string;\n patches: Patch[];\n}\n\nexport interface HistoryEntry extends SyncMessage {\n reversePatches: Patch[];\n}\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> {\n __patches?: {\n value: T;\n version: string;\n history: HistoryEntry[];\n };\n }\n}\n\nexport interface SubscribePatchOptions extends SubscribeOptions, DiffOptions {\n /** @default false */\n runNow?: boolean;\n /** try to start from a specific version and only receive patches after that.\n * If the id is not found, it will start from the beginning */\n startAt?: string;\n}\n\nexport type InteropPatch = Patch | { op: 'add' | 'replace' | 'remove'; value?: any };\n\nconst genId = () => Math.random().toString(36).slice(2);\n\nexport function subscribePatches<T>(\n this: Store<T>,\n listener: (\n this: { cancel: Cancel },\n patches: Patch[],\n reversePatches: Patch[],\n version: string,\n previousVersion: string | undefined,\n ) => void,\n options: SubscribePatchOptions = {},\n): DisposableCancel {\n const patches = (this.__patches ??= {\n value: this.get(),\n version: genId(),\n history: [],\n });\n\n options = { ...options };\n options.runNow ??= false;\n let cursor = options.startAt ?? (options.runNow ? undefined : this.__patches.version);\n\n return this.subscribe(function (value) {\n if (patches.value !== value) {\n const result = diff(patches.value, value, options);\n patches.value = value;\n\n if (result[0].length > 0) {\n const newVersion = genId();\n\n patches.history = patches.history\n .concat({\n fromVersion: patches.version,\n toVersion: newVersion,\n patches: result[0],\n reversePatches: result[1],\n })\n .slice(-1000);\n\n patches.version = newVersion;\n }\n }\n\n if (cursor === patches.version) return;\n const index = patches.history.findIndex((h) => h.fromVersion === cursor);\n let forward, backward, previousVersion;\n\n if (index === -1) {\n [forward, backward] = diff(undefined, value, options);\n previousVersion = undefined;\n } else {\n forward = patches.history.slice(index).flatMap((h) => h.patches);\n backward = patches.history.slice(index).flatMap((h) => h.reversePatches);\n previousVersion = cursor;\n }\n\n cursor = patches.version;\n listener.apply(this, [forward, backward, cursor, previousVersion]);\n }, options);\n}\n\nexport function applyPatches<T>(this: Store<T>, patches: InteropPatch[]): void;\nexport function applyPatches<T>(this: Store<T>, ...patches: InteropPatch[]): void;\nexport function applyPatches<T>(\n this: Store<T>,\n ...patches: (InteropPatch | InteropPatch[])[]\n): void {\n this.set((value) => _applyPatches(value, ...(patches.flat() as Patch[])));\n}\n\nexport function sync<T>(\n this: Store<T>,\n listener: (syncMessage: SyncMessage) => void,\n options?: Omit<SubscribePatchOptions, 'runNow'>,\n): DisposableCancel {\n const debounce =\n typeof options?.debounce === 'object' && 'wait' in options.debounce\n ? { ...options.debounce }\n : options?.debounce !== undefined\n ? { wait: options.debounce }\n : undefined;\n\n if (debounce) {\n debounce.waitOnRunNow ??= false;\n }\n\n return subscribePatches.apply<\n Store<T>,\n Parameters<typeof subscribePatches<T>>,\n ReturnType<typeof subscribePatches<T>>\n >(this, [\n (patches, _, version, previousVersion) => {\n const trie = new Trie();\n\n patches = [...patches]\n .reverse()\n .filter((patch) => {\n if (trie.hasSubPath(patch.path)) {\n return false;\n }\n\n trie.add(patch.path);\n return true;\n })\n .reverse();\n\n listener({\n fromVersion: previousVersion,\n toVersion: version,\n patches: toExtendedJson(patches) as Patch[],\n });\n },\n { ...options, debounce, runNow: true },\n ]);\n}\n\nexport function acceptSync<T>(this: Store<T>, message: SyncMessage): void {\n if (message.fromVersion && message.fromVersion !== this.version) {\n throw new Error(\n `version mismatch! version=${this.version}, fromVersion=${message.fromVersion}`,\n );\n }\n\n const patches = fromExtendedJson(message.patches) as Patch[];\n\n this.version = message.toVersion;\n applyPatches.apply<Store<T>, Patch[], void>(this, patches);\n}\n\nexport const patchMethods: {\n subscribePatches: typeof subscribePatches;\n applyPatches: typeof applyPatches;\n sync: typeof sync;\n acceptSync: typeof acceptSync;\n} = {\n subscribePatches,\n applyPatches,\n sync,\n acceptSync,\n};\n"],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 interface SyncMessage {
|
|
|
10
10
|
interface HistoryEntry extends SyncMessage {
|
|
11
11
|
reversePatches: Patch[];
|
|
12
12
|
}
|
|
13
|
-
declare module "
|
|
13
|
+
declare module ".." {
|
|
14
14
|
interface Store<T> {
|
|
15
15
|
__patches?: {
|
|
16
16
|
value: T;
|
|
@@ -45,4 +45,4 @@ declare const patchMethods: {
|
|
|
45
45
|
};
|
|
46
46
|
//#endregion
|
|
47
47
|
export { SubscribePatchOptions, SyncMessage, patchMethods };
|
|
48
|
-
//# sourceMappingURL=patchMethods-
|
|
48
|
+
//# sourceMappingURL=patchMethods-pw_OcPA8.d.cts.map
|
package/dist/patches/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import "../store-BEsiS8y7.cjs";
|
|
2
2
|
import "../diff-BQ8bB3Wk.cjs";
|
|
3
|
-
import { SubscribePatchOptions, SyncMessage, patchMethods } from "../patchMethods-
|
|
3
|
+
import { SubscribePatchOptions, SyncMessage, patchMethods } from "../patchMethods-pw_OcPA8.cjs";
|
|
4
4
|
export { type SubscribePatchOptions, type SyncMessage, patchMethods };
|
package/dist/patches/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import "../store-DKaeE840.js";
|
|
2
2
|
import "../diff-gZezL04N.js";
|
|
3
|
-
import { SubscribePatchOptions, SyncMessage, patchMethods } from "../patchMethods-
|
|
3
|
+
import { SubscribePatchOptions, SyncMessage, patchMethods } from "../patchMethods-CT9M507t.js";
|
|
4
4
|
export { type SubscribePatchOptions, type SyncMessage, patchMethods };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.cjs","names":["Store","patchMethods","autobind"],"sources":["../../src/patches/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { patchMethods } from './patchMethods';\n\ntype PatchMethods = typeof patchMethods;\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.cjs","names":["Store","patchMethods","autobind"],"sources":["../../src/patches/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { patchMethods } from './patchMethods';\n\ntype PatchMethods = typeof patchMethods;\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends PatchMethods {}\n}\n\nObject.assign(Store.prototype, patchMethods);\nautobind(Store);\n"],"mappings":";;;;;;AAWA,OAAO,OAAOA,oBAAM,WAAWC;AAC/BC,uBAASF"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import "../store-BEsiS8y7.cjs";
|
|
2
2
|
import "../diff-BQ8bB3Wk.cjs";
|
|
3
|
-
import { patchMethods } from "../patchMethods-
|
|
3
|
+
import { patchMethods } from "../patchMethods-pw_OcPA8.cjs";
|
|
4
4
|
|
|
5
5
|
//#region src/patches/register.d.ts
|
|
6
6
|
type PatchMethods = typeof patchMethods;
|
|
7
|
-
declare module "
|
|
7
|
+
declare module ".." {
|
|
8
8
|
interface Store<T> extends PatchMethods {}
|
|
9
9
|
}
|
|
10
10
|
//#endregion
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import "../store-DKaeE840.js";
|
|
2
2
|
import "../diff-gZezL04N.js";
|
|
3
|
-
import { patchMethods } from "../patchMethods-
|
|
3
|
+
import { patchMethods } from "../patchMethods-CT9M507t.js";
|
|
4
4
|
|
|
5
5
|
//#region src/patches/register.d.ts
|
|
6
6
|
type PatchMethods = typeof patchMethods;
|
|
7
|
-
declare module "
|
|
7
|
+
declare module ".." {
|
|
8
8
|
interface Store<T> extends PatchMethods {}
|
|
9
9
|
}
|
|
10
10
|
//# sourceMappingURL=register.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.js","names":[],"sources":["../../src/patches/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { patchMethods } from './patchMethods';\n\ntype PatchMethods = typeof patchMethods;\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.js","names":[],"sources":["../../src/patches/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { patchMethods } from './patchMethods';\n\ntype PatchMethods = typeof patchMethods;\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends PatchMethods {}\n}\n\nObject.assign(Store.prototype, patchMethods);\nautobind(Store);\n"],"mappings":";;;;;;AAWA,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.cjs","names":["Store","persist"],"sources":["../../src/persist/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { persist, type Persist, type PersistOptions } from '@persist/persist';\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.cjs","names":["Store","persist"],"sources":["../../src/persist/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { persist, type Persist, type PersistOptions } from '@persist/persist';\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface StoreOptions<T> {\n persist?: PersistOptions<T>;\n }\n\n interface Store<T> {\n persistance?: Persist<T>;\n }\n}\n\nStore.addHook((store) => {\n if (store.options.persist) {\n store.persistance = persist(store, store.options.persist);\n }\n});\n"],"mappings":";;;;;;;AAcAA,oBAAM,SAAS,UAAU;AACvB,KAAI,MAAM,QAAQ,QAChB,OAAM,cAAcC,wBAAQ,OAAO,MAAM,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.js","names":[],"sources":["../../src/persist/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { persist, type Persist, type PersistOptions } from '@persist/persist';\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.js","names":[],"sources":["../../src/persist/register.ts"],"sourcesContent":["import { Store } from '@core';\nimport { persist, type Persist, type PersistOptions } from '@persist/persist';\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface StoreOptions<T> {\n persist?: PersistOptions<T>;\n }\n\n interface Store<T> {\n persistance?: Persist<T>;\n }\n}\n\nStore.addHook((store) => {\n if (store.options.persist) {\n store.persistance = persist(store, store.options.persist);\n }\n});\n"],"mappings":";;;;;;;AAcA,MAAM,SAAS,UAAU;AACvB,KAAI,MAAM,QAAQ,QAChB,OAAM,cAAc,QAAQ,OAAO,MAAM,QAAQ"}
|
package/dist/react/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../scope-DO5vpLPV.cjs";
|
|
2
2
|
import { Constrain, Duration, GetKeys, Join, MaybePromise, Object_, Path as Path$1, PathAsString, Selector, Store, Update, UpdateFunction, Value, WildcardPathAsString, WildcardValue } from "../store-BEsiS8y7.cjs";
|
|
3
|
-
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-
|
|
3
|
+
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-DIyKFgk1.cjs";
|
|
4
4
|
import React$1, { Component, ComponentPropsWithoutRef, Context, FormEvent, FunctionComponent, HTMLProps, ReactNode } from "react";
|
|
5
5
|
|
|
6
6
|
//#region src/react/form/customInput.d.ts
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../scope-DI1OFHcr.js";
|
|
2
2
|
import { Constrain, Duration, GetKeys, Join, MaybePromise, Object_, Path as Path$1, PathAsString, Selector, Store, Update, UpdateFunction, Value, WildcardPathAsString, WildcardValue } from "../store-DKaeE840.js";
|
|
3
|
-
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-
|
|
3
|
+
import { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore } from "../storeMethods-BjOAF4Pk.js";
|
|
4
4
|
import React$1, { Component, ComponentPropsWithoutRef, Context, FormEvent, FunctionComponent, HTMLProps, ReactNode } from "react";
|
|
5
5
|
|
|
6
6
|
//#region src/react/form/customInput.d.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.cjs","names":["Store","storeMethods","autobind","Cache","cacheMethods","Scope","scopeMethods"],"sources":["../../src/react/register.ts"],"sourcesContent":["import { Cache, Scope, Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { cacheMethods } from '@react/cacheMethods';\nimport { scopeMethods } from '@react/scopeMethods';\nimport { storeMethods } from './storeMethods';\n\ntype StoreMethods = typeof storeMethods;\ntype CacheMethods = typeof cacheMethods;\ntype ScopeMethods = typeof scopeMethods;\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.cjs","names":["Store","storeMethods","autobind","Cache","cacheMethods","Scope","scopeMethods"],"sources":["../../src/react/register.ts"],"sourcesContent":["import { Cache, Scope, Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { cacheMethods } from '@react/cacheMethods';\nimport { scopeMethods } from '@react/scopeMethods';\nimport { storeMethods } from './storeMethods';\n\ntype StoreMethods = typeof storeMethods;\ntype CacheMethods = typeof cacheMethods;\ntype ScopeMethods = typeof scopeMethods;\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends StoreMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Cache<T> extends CacheMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Scope<T> extends ScopeMethods {}\n}\n\nObject.assign(Store.prototype, storeMethods);\nautobind(Store);\n\nObject.assign(Cache.prototype, cacheMethods);\nautobind(Cache);\n\nObject.assign(Scope.prototype, scopeMethods);\nautobind(Scope);\n"],"mappings":";;;;;;;AAqBA,OAAO,OAAOA,oBAAM,WAAWC;AAC/BC,uBAASF;AAET,OAAO,OAAOG,oBAAM,WAAWC;AAC/BF,uBAASC;AAET,OAAO,OAAOE,oBAAM,WAAWC;AAC/BJ,uBAASG"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import "../scope-DO5vpLPV.cjs";
|
|
2
2
|
import "../store-BEsiS8y7.cjs";
|
|
3
|
-
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-
|
|
3
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-DIyKFgk1.cjs";
|
|
4
4
|
|
|
5
5
|
//#region src/react/register.d.ts
|
|
6
6
|
type StoreMethods = typeof storeMethods;
|
|
7
7
|
type CacheMethods = typeof cacheMethods;
|
|
8
8
|
type ScopeMethods = typeof scopeMethods;
|
|
9
|
-
declare module "
|
|
9
|
+
declare module ".." {
|
|
10
10
|
interface Store<T> extends StoreMethods {}
|
|
11
11
|
interface Cache<T> extends CacheMethods {}
|
|
12
12
|
interface Scope<T> extends ScopeMethods {}
|
package/dist/react/register.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import "../scope-DI1OFHcr.js";
|
|
2
2
|
import "../store-DKaeE840.js";
|
|
3
|
-
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-
|
|
3
|
+
import { cacheMethods, scopeMethods, storeMethods } from "../storeMethods-BjOAF4Pk.js";
|
|
4
4
|
|
|
5
5
|
//#region src/react/register.d.ts
|
|
6
6
|
type StoreMethods = typeof storeMethods;
|
|
7
7
|
type CacheMethods = typeof cacheMethods;
|
|
8
8
|
type ScopeMethods = typeof scopeMethods;
|
|
9
|
-
declare module "
|
|
9
|
+
declare module ".." {
|
|
10
10
|
interface Store<T> extends StoreMethods {}
|
|
11
11
|
interface Cache<T> extends CacheMethods {}
|
|
12
12
|
interface Scope<T> extends ScopeMethods {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register.js","names":[],"sources":["../../src/react/register.ts"],"sourcesContent":["import { Cache, Scope, Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { cacheMethods } from '@react/cacheMethods';\nimport { scopeMethods } from '@react/scopeMethods';\nimport { storeMethods } from './storeMethods';\n\ntype StoreMethods = typeof storeMethods;\ntype CacheMethods = typeof cacheMethods;\ntype ScopeMethods = typeof scopeMethods;\n\ndeclare module '
|
|
1
|
+
{"version":3,"file":"register.js","names":[],"sources":["../../src/react/register.ts"],"sourcesContent":["import { Cache, Scope, Store } from '@core';\nimport { autobind } from '@lib/autobind';\nimport { cacheMethods } from '@react/cacheMethods';\nimport { scopeMethods } from '@react/scopeMethods';\nimport { storeMethods } from './storeMethods';\n\ntype StoreMethods = typeof storeMethods;\ntype CacheMethods = typeof cacheMethods;\ntype ScopeMethods = typeof scopeMethods;\n\ndeclare module '..' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Store<T> extends StoreMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Cache<T> extends CacheMethods {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface Scope<T> extends ScopeMethods {}\n}\n\nObject.assign(Store.prototype, storeMethods);\nautobind(Store);\n\nObject.assign(Cache.prototype, cacheMethods);\nautobind(Cache);\n\nObject.assign(Scope.prototype, scopeMethods);\nautobind(Scope);\n"],"mappings":";;;;;;;AAqBA,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS;AAET,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS;AAET,OAAO,OAAO,MAAM,WAAW;AAC/B,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storeMethods-AIJSwxHz.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 '@core' {\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,sBAA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AoC;AAC9D,OAAM,YAAY,cAAwB,YAAY,MAAM;AAC5D,QAAO,MAAM;;AAGf,SAAgB,cAAiB,EAC/B,OACA,OAAO,YACP,YACmC;CACnC,MAAM,UAAU,gBAAgB;CAChC,MAAM,eAAe,cACb,cAAc,YAAY,MAAM,eACtC,CAAC,OAAO;AAGV,QAAO,oBAAC,QAAQ;EAAS,OAAO;EAAe;;;AAGjD,SAAgB,SAAY,OAA2B;CACrD,MAAM,UAAU,gBAAgB;AAChC,QAAO,WAAW;;AAiBpB,SAAgB,cAAiB,OAAiB,GAAG,MAAgB;CACnE,MAAM,QAAQ,SAAS;AACvB,QAAO,SAAS,OAAO,GAAG;;AAqB5B,SAAgB,aACd,OACA,GAAG,MACoC;CACvC,MAAM,QAAQ,SAAS;AACvB,QAAO,QAAQ,OAAO,GAAG;;;;;ACtE3B,SAAS,gBAA2C;AAClD,QAAO,SAAS;;AAiBlB,SAAS,mBAAqC,GAAG,MAAa;AAC5D,QAAO,cAAc,MAAM,GAAG;;AAqBhC,SAAS,kBAAoC,GAAG,MAAa;AAC3D,QAAO,aAAa,MAAM,GAAG;;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
|
+
{"version":3,"file":"storeMethods-AIJSwxHz.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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;;;;;AC7BvB,SAAS,gBAAmB,OAAoC;AAC9D,OAAM,YAAY,cAAwB,YAAY,MAAM;AAC5D,QAAO,MAAM;;AAGf,SAAgB,cAAiB,EAC/B,OACA,OAAO,YACP,YACmC;CACnC,MAAM,UAAU,gBAAgB;CAChC,MAAM,eAAe,cACb,cAAc,YAAY,MAAM,eACtC,CAAC,OAAO;AAGV,QAAO,oBAAC,QAAQ;EAAS,OAAO;EAAe;;;AAGjD,SAAgB,SAAY,OAA2B;CACrD,MAAM,UAAU,gBAAgB;AAChC,QAAO,WAAW;;AAiBpB,SAAgB,cAAiB,OAAiB,GAAG,MAAgB;CACnE,MAAM,QAAQ,SAAS;AACvB,QAAO,SAAS,OAAO,GAAG;;AAqB5B,SAAgB,aACd,OACA,GAAG,MACoC;CACvC,MAAM,QAAQ,SAAS;AACvB,QAAO,QAAQ,OAAO,GAAG;;;;;ACtE3B,SAAS,gBAA2C;AAClD,QAAO,SAAS;;AAiBlB,SAAS,mBAAqC,GAAG,MAAa;AAC5D,QAAO,cAAc,MAAM,GAAG;;AAqBhC,SAAS,kBAAoC,GAAG,MAAa;AAC3D,QAAO,aAAa,MAAM,GAAG;;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"}
|
|
@@ -63,7 +63,7 @@ type ScopeProps<T> = {
|
|
|
63
63
|
store?: Store<T>;
|
|
64
64
|
children?: ReactNode;
|
|
65
65
|
};
|
|
66
|
-
declare module "
|
|
66
|
+
declare module ".." {
|
|
67
67
|
interface Scope<T> {
|
|
68
68
|
context?: Context<Store<T>>;
|
|
69
69
|
}
|
|
@@ -104,4 +104,4 @@ declare const storeMethods: {
|
|
|
104
104
|
};
|
|
105
105
|
//#endregion
|
|
106
106
|
export { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore };
|
|
107
|
-
//# sourceMappingURL=storeMethods-
|
|
107
|
+
//# sourceMappingURL=storeMethods-BjOAF4Pk.d.ts.map
|
|
@@ -63,7 +63,7 @@ type ScopeProps<T> = {
|
|
|
63
63
|
store?: Store<T>;
|
|
64
64
|
children?: ReactNode;
|
|
65
65
|
};
|
|
66
|
-
declare module "
|
|
66
|
+
declare module ".." {
|
|
67
67
|
interface Scope<T> {
|
|
68
68
|
context?: Context<Store<T>>;
|
|
69
69
|
}
|
|
@@ -104,4 +104,4 @@ declare const storeMethods: {
|
|
|
104
104
|
};
|
|
105
105
|
//#endregion
|
|
106
106
|
export { ScopeProps, ScopeProvider, UseCacheArray, UseCacheValue, UseStoreOptions, cacheMethods, scopeMethods, storeMethods, useCache, useScope, useStore };
|
|
107
|
-
//# sourceMappingURL=storeMethods-
|
|
107
|
+
//# sourceMappingURL=storeMethods-DIyKFgk1.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storeMethods-DVVsmUg1.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 '@core' {\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,UA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AY,MAAM,eACtC,CAAC,OAAO;AAGV,QAAO,2CAAC,QAAQ;EAAS,OAAO;EAAe;;;AAGjD,SAAgB,SAAY,OAA2B;CACrD,MAAM,UAAU,gBAAgB;AAChC,8BAAkB;;AAiBpB,SAAgB,cAAiB,OAAiB,GAAG,MAAgB;CACnE,MAAM,QAAQ,SAAS;AACvB,QAAO,SAAS,OAAO,GAAG;;AAqB5B,SAAgB,aACd,OACA,GAAG,MACoC;CACvC,MAAM,QAAQ,SAAS;AACvB,QAAO,QAAQ,OAAO,GAAG;;;;;ACtE3B,SAAS,gBAA2C;AAClD,QAAO,SAAS;;AAiBlB,SAAS,mBAAqC,GAAG,MAAa;AAC5D,QAAO,cAAc,MAAM,GAAG;;AAqBhC,SAAS,kBAAoC,GAAG,MAAa;AAC3D,QAAO,aAAa,MAAM,GAAG;;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
|
+
{"version":3,"file":"storeMethods-DVVsmUg1.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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