@shadow-js/core 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/dev/cache.d.ts +2 -1
  3. package/dist/dev/cache.js +5 -3
  4. package/dist/dev/cache.js.map +1 -1
  5. package/dist/dev/effect.js +17 -33
  6. package/dist/dev/effect.js.map +1 -1
  7. package/dist/dev/extend/index.d.ts +7 -6
  8. package/dist/dev/extend/index.js +7 -7
  9. package/dist/dev/extend/index.js.map +1 -1
  10. package/dist/dev/external-store.js +8 -3
  11. package/dist/dev/external-store.js.map +1 -1
  12. package/dist/dev/internal/concurrency.js +42 -20
  13. package/dist/dev/internal/concurrency.js.map +1 -1
  14. package/dist/dev/internal/diagnostics.js +0 -2
  15. package/dist/dev/internal/diagnostics.js.map +1 -1
  16. package/dist/dev/internal/flags.js +1 -3
  17. package/dist/dev/internal/flags.js.map +1 -1
  18. package/dist/dev/internal/graph.d.ts +0 -1
  19. package/dist/dev/internal/graph.js +20 -37
  20. package/dist/dev/internal/graph.js.map +1 -1
  21. package/dist/dev/internal/owner.d.ts +7 -5
  22. package/dist/dev/internal/owner.js +12 -22
  23. package/dist/dev/internal/owner.js.map +1 -1
  24. package/dist/dev/internal/scheduler.js +33 -71
  25. package/dist/dev/internal/scheduler.js.map +1 -1
  26. package/dist/dev/list.js +0 -8
  27. package/dist/dev/list.js.map +1 -1
  28. package/dist/dev/memo.d.ts +2 -1
  29. package/dist/dev/memo.js +4 -4
  30. package/dist/dev/memo.js.map +1 -1
  31. package/dist/dev/ownership.d.ts +4 -2
  32. package/dist/dev/ownership.js +59 -3
  33. package/dist/dev/ownership.js.map +1 -1
  34. package/dist/dev/props.js +18 -11
  35. package/dist/dev/props.js.map +1 -1
  36. package/dist/dev/reaction.d.ts +1 -1
  37. package/dist/dev/reaction.js +5 -1
  38. package/dist/dev/reaction.js.map +1 -1
  39. package/dist/dev/reducer.js +1 -1
  40. package/dist/dev/reducer.js.map +1 -1
  41. package/dist/dev/resource.js +21 -12
  42. package/dist/dev/resource.js.map +1 -1
  43. package/dist/dev/selector.js +1 -5
  44. package/dist/dev/selector.js.map +1 -1
  45. package/dist/dev/signal.d.ts +3 -2
  46. package/dist/dev/signal.js.map +1 -1
  47. package/dist/dev/store/nodes.js +6 -0
  48. package/dist/dev/store/nodes.js.map +1 -1
  49. package/dist/dev/store/use-store.d.ts +5 -0
  50. package/dist/dev/store/use-store.js.map +1 -1
  51. package/dist/dev/transitions.js +1 -1
  52. package/dist/dev/transitions.js.map +1 -1
  53. package/dist/prod/cache.js +1 -1
  54. package/dist/prod/cache.js.map +1 -1
  55. package/dist/prod/effect.js +1 -1
  56. package/dist/prod/effect.js.map +1 -1
  57. package/dist/prod/extend/index.js +1 -1
  58. package/dist/prod/extend/index.js.map +1 -1
  59. package/dist/prod/external-store.js +1 -1
  60. package/dist/prod/external-store.js.map +1 -1
  61. package/dist/prod/internal/concurrency.js +1 -1
  62. package/dist/prod/internal/concurrency.js.map +1 -1
  63. package/dist/prod/internal/diagnostics.js +1 -1
  64. package/dist/prod/internal/diagnostics.js.map +1 -1
  65. package/dist/prod/internal/flags.js +1 -1
  66. package/dist/prod/internal/flags.js.map +1 -1
  67. package/dist/prod/internal/graph.js +1 -1
  68. package/dist/prod/internal/graph.js.map +1 -1
  69. package/dist/prod/internal/owner.js +1 -1
  70. package/dist/prod/internal/owner.js.map +1 -1
  71. package/dist/prod/internal/scheduler.js +1 -1
  72. package/dist/prod/internal/scheduler.js.map +1 -1
  73. package/dist/prod/list.js +1 -1
  74. package/dist/prod/list.js.map +1 -1
  75. package/dist/prod/memo.js +1 -1
  76. package/dist/prod/memo.js.map +1 -1
  77. package/dist/prod/ownership.js +1 -1
  78. package/dist/prod/ownership.js.map +1 -1
  79. package/dist/prod/props.js.map +1 -1
  80. package/dist/prod/reaction.js +1 -1
  81. package/dist/prod/reaction.js.map +1 -1
  82. package/dist/prod/reducer.js +1 -1
  83. package/dist/prod/reducer.js.map +1 -1
  84. package/dist/prod/resource.js +1 -1
  85. package/dist/prod/resource.js.map +1 -1
  86. package/dist/prod/selector.js +1 -1
  87. package/dist/prod/selector.js.map +1 -1
  88. package/dist/prod/signal.js.map +1 -1
  89. package/dist/prod/store/nodes.js +1 -1
  90. package/dist/prod/store/nodes.js.map +1 -1
  91. package/dist/prod/store/use-store.js.map +1 -1
  92. package/dist/prod/transitions.js +1 -1
  93. package/dist/prod/transitions.js.map +1 -1
  94. package/dist/server/cache.js +1 -1
  95. package/dist/server/cache.js.map +1 -1
  96. package/dist/server/effect.js.map +1 -1
  97. package/dist/server/extend/index.js +1 -1
  98. package/dist/server/extend/index.js.map +1 -1
  99. package/dist/server/external-store.js.map +1 -1
  100. package/dist/server/internal/concurrency.js +1 -1
  101. package/dist/server/internal/concurrency.js.map +1 -1
  102. package/dist/server/internal/diagnostics.js +1 -1
  103. package/dist/server/internal/diagnostics.js.map +1 -1
  104. package/dist/server/internal/flags.js +1 -1
  105. package/dist/server/internal/flags.js.map +1 -1
  106. package/dist/server/internal/graph.js +1 -1
  107. package/dist/server/internal/graph.js.map +1 -1
  108. package/dist/server/internal/owner.js +1 -1
  109. package/dist/server/internal/owner.js.map +1 -1
  110. package/dist/server/internal/scheduler.js +1 -1
  111. package/dist/server/internal/scheduler.js.map +1 -1
  112. package/dist/server/list.js +1 -1
  113. package/dist/server/list.js.map +1 -1
  114. package/dist/server/memo.js +1 -1
  115. package/dist/server/memo.js.map +1 -1
  116. package/dist/server/ownership.js +1 -1
  117. package/dist/server/ownership.js.map +1 -1
  118. package/dist/server/props.js.map +1 -1
  119. package/dist/server/reaction.js +1 -1
  120. package/dist/server/reaction.js.map +1 -1
  121. package/dist/server/reducer.js +1 -1
  122. package/dist/server/reducer.js.map +1 -1
  123. package/dist/server/resource.js +1 -1
  124. package/dist/server/resource.js.map +1 -1
  125. package/dist/server/selector.js +1 -1
  126. package/dist/server/selector.js.map +1 -1
  127. package/dist/server/signal.js.map +1 -1
  128. package/dist/server/store/nodes.js +1 -1
  129. package/dist/server/store/nodes.js.map +1 -1
  130. package/dist/server/store/use-store.js.map +1 -1
  131. package/dist/server/transitions.js.map +1 -1
  132. package/dist/server-dev/cache.js +5 -3
  133. package/dist/server-dev/cache.js.map +1 -1
  134. package/dist/server-dev/effect.js.map +1 -1
  135. package/dist/server-dev/extend/index.js +7 -7
  136. package/dist/server-dev/extend/index.js.map +1 -1
  137. package/dist/server-dev/external-store.js.map +1 -1
  138. package/dist/server-dev/internal/concurrency.js +42 -20
  139. package/dist/server-dev/internal/concurrency.js.map +1 -1
  140. package/dist/server-dev/internal/diagnostics.js +0 -2
  141. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  142. package/dist/server-dev/internal/flags.js +1 -3
  143. package/dist/server-dev/internal/flags.js.map +1 -1
  144. package/dist/server-dev/internal/graph.js +20 -37
  145. package/dist/server-dev/internal/graph.js.map +1 -1
  146. package/dist/server-dev/internal/owner.js +12 -22
  147. package/dist/server-dev/internal/owner.js.map +1 -1
  148. package/dist/server-dev/internal/scheduler.js +33 -71
  149. package/dist/server-dev/internal/scheduler.js.map +1 -1
  150. package/dist/server-dev/list.js +0 -8
  151. package/dist/server-dev/list.js.map +1 -1
  152. package/dist/server-dev/memo.js +4 -4
  153. package/dist/server-dev/memo.js.map +1 -1
  154. package/dist/server-dev/ownership.js +59 -3
  155. package/dist/server-dev/ownership.js.map +1 -1
  156. package/dist/server-dev/props.js +18 -11
  157. package/dist/server-dev/props.js.map +1 -1
  158. package/dist/server-dev/reaction.js +5 -1
  159. package/dist/server-dev/reaction.js.map +1 -1
  160. package/dist/server-dev/reducer.js +1 -1
  161. package/dist/server-dev/reducer.js.map +1 -1
  162. package/dist/server-dev/resource.js +21 -12
  163. package/dist/server-dev/resource.js.map +1 -1
  164. package/dist/server-dev/selector.js +1 -5
  165. package/dist/server-dev/selector.js.map +1 -1
  166. package/dist/server-dev/signal.js.map +1 -1
  167. package/dist/server-dev/store/nodes.js +6 -0
  168. package/dist/server-dev/store/nodes.js.map +1 -1
  169. package/dist/server-dev/store/use-store.js.map +1 -1
  170. package/dist/server-dev/transitions.js.map +1 -1
  171. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"use-store.js","names":[],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\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"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * A property read in a tracked context gets a small notifier. Reading many transient keys\n * (`store.byId[id]` with churning ids) does not grow it for the life of the store: once an object\n * has collected a few hundred notifiers, the ones nothing observes any more are dropped, and a key\n * read again gets a fresh one that reflects the current value.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":";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AAe,eAAe,QAAQ,aAAa,CAAC;CACrE;CACA,OAAO,CAAC,OAAO,QAAQ;AACzB;;AAGA,SAAS,YAAY,MAAc,OAAgB,OAAqB;CACtE,IAAI,MAAM,QAAQ,IAAI,GAAG;EACvB,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,MAAM,IAAI,UAEJ,cAAc,MAAM,wDAE1B;EAEF,MAAM,OAAO,OAAO,UAAU,KAAK,CAAC;EACpC,IAAI,SAAS,KAAA,GAAW,eAAe,MAAM,MAAM,KAAK;EACxD;CACF;CACA,IAAI,CAAC,cAAc,KAAK,GACtB,MAAM,IAAI,UAEJ,cAAc,MAAM,mEAE1B;CAEF,MAAM,KAAK,IAAI,YAAY,KAAK;CAChC,IAAI;EACF,UAAU,QAAQ,MAAM,EAAE,GAA8B,OAAO,KAAK;CACtE,UAAU;EACR,GAAG,OAAO;CACZ;AACF;AAoDA,SAAgB,SAAS,SAAkB,SAAiC;CAC1E,MAAM,QAAQ,SAAS,SAAS,KAAA,IAAY,KAAK,KAAK,QAAQ,KAAK;CACnE,MAAM,OAAO,YAAY,OAAO;CAChC,IAAI,YAAY,IAAI,GAAG,OAAO,gBAAgB,MAAM,KAAK;CAGzD,MAAM,CAAC,MAAM,SAAS,UACpB,SAAS,OAAO,GAChB,SAAS,SAAS,KAAA,IAAY,KAAA,IAAY,EAAE,MAAM,QAAQ,KAAK,CACjE;CACA,MAAM,OAAO,SACX,MACE,OAAO,SAAS,cACX,aAAsB,SAAU,KAAwC,QAAQ,CAAC,IAClF,SAAS,IAAI,CACnB;CACF,OAAO,CAAC,MAAM,GAAG;AACnB;;AAGA,SAAS,SAAS,OAAyB;CACzC,MAAM,MAAM,YAAY,KAAK;CAC7B,OAAO,YAAY,GAAG,IAAI,YAAY,GAAG,IAAI;AAC/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"transitions.js","names":[],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,gBAAwE;CACtF,MAAM,CAAC,SAAS,cAAc,UAAU,KAAK;CAC7C,IAAI,UAAU;CACd,MAAM,SAAS,OAAkC;EAC/C,WAAW;EAEX,cAAc,WAAW,IAAI,CAAC;EAC9B,IAAI;EACJ,IAAI;GACF,UAAU,gBAAgB,EAAE;EAC9B,SAAS,OAAO;GACd,WAAW;GACX,IAAI,YAAY,GAAG,cAAc,WAAW,KAAK,CAAC;GAClD,MAAM;EACR;EACA,OAAO,QAAQ,WAAW;GACxB,WAAW;GACX,IAAI,YAAY,GAAG,cAAc,WAAW,KAAK,CAAC;EACpD,CAAC;CACH;CACA,OAAO,CAAC,SAAS,KAAK;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,iBACd,QACA,SACa;CACG,OAAO;AAkBzB"}
1
+ {"version":3,"file":"transitions.js","names":[],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n name: options?.name,\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,gBAAwE;CACtF,MAAM,CAAC,SAAS,cAAc,UAAU,KAAK;CAC7C,IAAI,UAAU;CACd,MAAM,SAAS,OAAkC;EAC/C,WAAW;EAEX,cAAc,WAAW,IAAI,CAAC;EAC9B,IAAI;EACJ,IAAI;GACF,UAAU,gBAAgB,EAAE;EAC9B,SAAS,OAAO;GACd,WAAW;GACX,IAAI,YAAY,GAAG,cAAc,WAAW,KAAK,CAAC;GAClD,MAAM;EACR;EACA,OAAO,QAAQ,WAAW;GACxB,WAAW;GACX,IAAI,YAAY,GAAG,cAAc,WAAW,KAAK,CAAC;EACpD,CAAC;CACH;CACA,OAAO,CAAC,SAAS,KAAK;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,iBACd,QACA,SACa;CACG,OAAO;AAkBzB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shadow-js/core",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Signals, stores, memos and effects that update exactly what changed",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -118,6 +118,7 @@
118
118
  "@shadow-js/compiler": "*",
119
119
  "@shadow-js/web": "*",
120
120
  "@types/node": "^24.0.0",
121
+ "esbuild": "0.27.0",
121
122
  "fast-check": "^4.10.2",
122
123
  "happy-dom": "^21.0.3",
123
124
  "tsdown": "0.23.0",