@shadow-js/core 1.0.6 → 1.1.1

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 (136) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/dev/action.d.ts +1 -2
  3. package/dist/dev/cache.d.ts +1 -2
  4. package/dist/dev/context.d.ts +1 -2
  5. package/dist/dev/effect.d.ts +1 -2
  6. package/dist/dev/env.d.ts +1 -2
  7. package/dist/dev/events.d.ts +1 -2
  8. package/dist/dev/extend/index.d.ts +1 -2
  9. package/dist/dev/external-store.d.ts +1 -2
  10. package/dist/dev/internal/concurrency.d.ts +1 -2
  11. package/dist/dev/internal/devtools.d.ts +1 -2
  12. package/dist/dev/internal/diagnostics.d.ts +1 -2
  13. package/dist/dev/internal/dispose.d.ts +1 -2
  14. package/dist/dev/internal/dispose.js.map +1 -1
  15. package/dist/dev/internal/graph.d.ts +1 -2
  16. package/dist/dev/internal/graph.js.map +1 -1
  17. package/dist/dev/internal/hydration-flag.d.ts +1 -2
  18. package/dist/dev/internal/messages.d.ts +1 -2
  19. package/dist/dev/internal/owner.d.ts +1 -2
  20. package/dist/dev/internal/owner.js.map +1 -1
  21. package/dist/dev/internal/scheduler.d.ts +1 -2
  22. package/dist/dev/internal/state.d.ts +1 -2
  23. package/dist/dev/internal/suspension.d.ts +1 -2
  24. package/dist/dev/internal/types.d.ts +1 -2
  25. package/dist/dev/list.d.ts +1 -2
  26. package/dist/dev/list.js.map +1 -1
  27. package/dist/dev/memo.d.ts +1 -2
  28. package/dist/dev/optimistic.d.ts +1 -2
  29. package/dist/dev/ownership.d.ts +1 -2
  30. package/dist/dev/ownership.js.map +1 -1
  31. package/dist/dev/props.d.ts +1 -2
  32. package/dist/dev/reaction.d.ts +1 -2
  33. package/dist/dev/reaction.js.map +1 -1
  34. package/dist/dev/reducer.d.ts +1 -2
  35. package/dist/dev/refs.d.ts +1 -2
  36. package/dist/dev/resource.d.ts +1 -2
  37. package/dist/dev/resource.js.map +1 -1
  38. package/dist/dev/selector.d.ts +1 -2
  39. package/dist/dev/selector.js.map +1 -1
  40. package/dist/dev/signal.d.ts +1 -2
  41. package/dist/dev/store/nodes.js.map +1 -1
  42. package/dist/dev/store/proxies.js.map +1 -1
  43. package/dist/dev/store/read.d.ts +1 -2
  44. package/dist/dev/store/reconcile.d.ts +1 -2
  45. package/dist/dev/store/types.d.ts +1 -2
  46. package/dist/dev/store/use-store.d.ts +1 -2
  47. package/dist/dev/store/use-store.js.map +1 -1
  48. package/dist/dev/suspense.d.ts +1 -2
  49. package/dist/dev/transitions.d.ts +1 -2
  50. package/dist/prod/action.js.map +1 -1
  51. package/dist/prod/cache.js.map +1 -1
  52. package/dist/prod/context.js.map +1 -1
  53. package/dist/prod/effect.js.map +1 -1
  54. package/dist/prod/events.js.map +1 -1
  55. package/dist/prod/extend/index.js.map +1 -1
  56. package/dist/prod/external-store.js.map +1 -1
  57. package/dist/prod/internal/concurrency.js.map +1 -1
  58. package/dist/prod/internal/devtools.js.map +1 -1
  59. package/dist/prod/internal/diagnostics.js.map +1 -1
  60. package/dist/prod/internal/dispose.js.map +1 -1
  61. package/dist/prod/internal/graph.js.map +1 -1
  62. package/dist/prod/internal/hydration-flag.js.map +1 -1
  63. package/dist/prod/internal/messages.js.map +1 -1
  64. package/dist/prod/internal/owner.js.map +1 -1
  65. package/dist/prod/internal/queue.js.map +1 -1
  66. package/dist/prod/internal/scheduler.js.map +1 -1
  67. package/dist/prod/internal/state.js.map +1 -1
  68. package/dist/prod/internal/suspension.js.map +1 -1
  69. package/dist/prod/list.js.map +1 -1
  70. package/dist/prod/memo.js.map +1 -1
  71. package/dist/prod/optimistic.js.map +1 -1
  72. package/dist/prod/ownership.js.map +1 -1
  73. package/dist/prod/props.js.map +1 -1
  74. package/dist/prod/reaction.js.map +1 -1
  75. package/dist/prod/reducer.js.map +1 -1
  76. package/dist/prod/refs.js.map +1 -1
  77. package/dist/prod/resource.js.map +1 -1
  78. package/dist/prod/selector.js.map +1 -1
  79. package/dist/prod/signal.js.map +1 -1
  80. package/dist/prod/store/nodes.js.map +1 -1
  81. package/dist/prod/store/proxies.js.map +1 -1
  82. package/dist/prod/store/read.js.map +1 -1
  83. package/dist/prod/store/reconcile.js.map +1 -1
  84. package/dist/prod/store/use-store.js.map +1 -1
  85. package/dist/prod/suspense.js.map +1 -1
  86. package/dist/prod/transitions.js.map +1 -1
  87. package/dist/server/action.js.map +1 -1
  88. package/dist/server/cache.js.map +1 -1
  89. package/dist/server/context.js.map +1 -1
  90. package/dist/server/effect.js.map +1 -1
  91. package/dist/server/events.js.map +1 -1
  92. package/dist/server/extend/index.js.map +1 -1
  93. package/dist/server/external-store.js.map +1 -1
  94. package/dist/server/internal/concurrency.js.map +1 -1
  95. package/dist/server/internal/devtools.js.map +1 -1
  96. package/dist/server/internal/diagnostics.js.map +1 -1
  97. package/dist/server/internal/dispose.js.map +1 -1
  98. package/dist/server/internal/graph.js.map +1 -1
  99. package/dist/server/internal/hydration-flag.js.map +1 -1
  100. package/dist/server/internal/messages.js.map +1 -1
  101. package/dist/server/internal/owner.js.map +1 -1
  102. package/dist/server/internal/queue.js.map +1 -1
  103. package/dist/server/internal/scheduler.js.map +1 -1
  104. package/dist/server/internal/state.js.map +1 -1
  105. package/dist/server/internal/suspension.js.map +1 -1
  106. package/dist/server/list.js.map +1 -1
  107. package/dist/server/memo.js.map +1 -1
  108. package/dist/server/optimistic.js.map +1 -1
  109. package/dist/server/ownership.js.map +1 -1
  110. package/dist/server/props.js.map +1 -1
  111. package/dist/server/reaction.js.map +1 -1
  112. package/dist/server/reducer.js.map +1 -1
  113. package/dist/server/refs.js.map +1 -1
  114. package/dist/server/resource.js.map +1 -1
  115. package/dist/server/selector.js.map +1 -1
  116. package/dist/server/signal.js.map +1 -1
  117. package/dist/server/store/nodes.js.map +1 -1
  118. package/dist/server/store/proxies.js.map +1 -1
  119. package/dist/server/store/read.js.map +1 -1
  120. package/dist/server/store/reconcile.js.map +1 -1
  121. package/dist/server/store/use-store.js.map +1 -1
  122. package/dist/server/suspense.js.map +1 -1
  123. package/dist/server/transitions.js.map +1 -1
  124. package/dist/server-dev/effect.js.map +1 -1
  125. package/dist/server-dev/internal/dispose.js.map +1 -1
  126. package/dist/server-dev/internal/graph.js.map +1 -1
  127. package/dist/server-dev/internal/owner.js.map +1 -1
  128. package/dist/server-dev/list.js.map +1 -1
  129. package/dist/server-dev/ownership.js.map +1 -1
  130. package/dist/server-dev/reaction.js.map +1 -1
  131. package/dist/server-dev/resource.js.map +1 -1
  132. package/dist/server-dev/selector.js.map +1 -1
  133. package/dist/server-dev/store/nodes.js.map +1 -1
  134. package/dist/server-dev/store/proxies.js.map +1 -1
  135. package/dist/server-dev/store/use-store.js.map +1 -1
  136. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"resource.js","names":["SignalNode"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = new SignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":";;;;;;;;;;;;;AAkGA,SAAS,KAAQ,SAAY,UAAqD;CAChF,MAAM,OAAO,IAAIA,OAAc,SAAS,WAAW,OAAO,KAAK,KAAK;CACpE,OAAO,OACC,WAAW,IAAI,IACpB,SAAS;EACR,YAAY,MAAM,MAAM,EAAE,aAAa,KAAK,CAAC;CAC/C,CACF;AACF;AAEA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;AA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U;IACR,IAAI,SAAS,QAAQ;GACvB;GACA,OAAO;EACT,EACF;CACF,CAAC;CAID,SAAS;CAEO,SAAS,QAAQ,MAAM,CAAC;CAExC,gBAAgB;EACd,WAAW;EACX,YAAY,MAAM;EAClB,QAAQ;CACV,CAAC;CACD,OAAO;AACT"}
1
+ {"version":3,"file":"resource.js","names":["SignalNode","devtoolsReport"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = new SignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":";;;;;;;;;;;;;AAkGA,SAAS,KAAQ,SAAY,UAAqD;CAChF,MAAM,OAAO,IAAIA,OAAc,SAAS,WAAW,OAAO,KAAK,KAAK;CACpE,OAAO,OACC,WAAW,IAAI,IACpB,SAAS;EACR,YAAY,MAAM,MAAM,EAAE,aAAa,KAAK,CAAC;CAC/C,CACF;AACF;AAEA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;AAiFA,SAAgB,YACd,OACA,QACA,OACa;CACb,MAAM,YAAY,OAAO,WAAW;CAEpC,MAAM,SACJ,YAAa,OAAO,UAAU,aAAa,cAAc,cAAe;CAE1E,MAAM,UAAU;CAChB,MAAM,UAAW,YAAY,UAAU,QAAW,SAA0B,QAAQ,IAAI;CAIxF,MAAM,WAAW,YAAY,QAAS,WAA8C,CAAC;CAErF,MAAM,aAAa,kBAAkB;CAGrC,MAAM,CAAC,OAAO,YAAY,KAAoB,QAA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AAU,WAAW,eAAe;GAC1C,IAAI,YAAY,QAAQ,CAAC,QAAQ,IAAI,OAAO,GAAG;IAC7C,QAAQ,IAAI,OAAO;IACnB,QAAQ,UAAU;GACpB;GAGA,IAAI,YAAY,QAAQ,gBAAgB,MAAM,QAAQ,aAAa,GAAG,WAAW,OAAO;EAC1F;EACA,OAAO,MAAM;CACf;CAEA,OAAO,iBAAiB,MAAM;EAC5B,OAAO,EAAE,KAAK,MAAM;EACpB,SAAS,EAAE,WAAW,MAAM,MAAM,aAAa,MAAM,MAAM,aAAa;EACxE,OAAO,EAAE,KAAK,QAAQ;EACtB,QAAQ,EAAE,KAAK,MAAM;EACrB,SAAS,EACP,aAAqC;GAGnC,IAAI,UAAU,OAAO,QAAQ,QAAQ,KAAA,CAAS;GAC9C,MAAM,QAAQ,QAAQ,MAAM;GAC5B,IAAI,UAAU,SAAS,UAAU,QAAQ,UAAU,KAAA,GACjD,OAAO,QAAQ,QAAQ,KAAA,CAAS;GAElC,OAAO,KAAK,OAAO,QAAQ;EAC7B,EACF;EACA,QAAQ,EACN,QAAQ,SAAkD;GACxD,IAAI;GAEJ,IAAI,UAAU;GACd,IAAI;IACF,YAAY;KACV,WACE,OAAO,SAAS,aACZ,cAAe,KAAwC,MAAM,CAAC,CAAC,IAC/D;KACN,UAAU;KACV,YAAY,MAAM;KAClB,WAAW;KACX,WAAW;KACX,SAAS,QAAa;KACtB,WAAW,KAAA,CAAS;KACpB,SAAS,OAAO;IAClB,CAAC;GACH,UAAU;IACR,IAAI,SAAS,QAAQ;GACvB;GACA,OAAO;EACT,EACF;CACF,CAAC;CAID,SAAS;CAEO,SAAS,QAAQ,MAAM,CAAC;CAExC,gBAAgB;EACd,WAAW;EACX,YAAY,MAAM;EAClB,QAAQ;CACV,CAAC;CACD,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"selector.js","names":[],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n declare readonly key: unknown;\n /** Whether the key matches the selected value. */\n declare value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n // `equals` is a user callback: it must not subscribe the reader that happens to register the key.\n const entry = new Entry(\n key,\n untrack(() => matches(key, currentValue())),\n );\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,QAAN,MAAkC;;CAEhC,OAAgB;CAChB,YAAqC;CACrC,QAAQ;;CAER,cAAc;CAOd,YAAY,KAAc,OAAgB;EACxC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,YACd,QACA,QACqB;CACrB,MAAM,0BAAU,IAAI,IAAoB;CAIxC,MAAM,WAAW,KAAQ,UACvB,WAAW,KAAA,IAAa,QAAoB,QAAQ,OAAO,KAAK,KAAK;CAEvE,MAAM,qBAAyC,QAAQ,MAAM;CAE7D,MAAM,WAAW,UAAuB;EACtC,MAAM,eAAe;EACrB,IAAI,MAAM,gBAAgB,KAAK,QAAQ,IAAI,MAAM,GAAG,MAAM,OAAO,QAAQ,OAAO,MAAM,GAAG;CAC3F;CAEA,MAAM,UAAU,QAAkB;EAEhC,MAAM,QAAQ,IAAI,MAChB,KACA,cAAc,QAAQ,KAAK,aAAa,CAAC,CAAC,CAC5C;EACA,QAAQ,IAAI,KAAK,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAc,QAAoB;EACtC,IAAI,CAAC,WAAW,GAAG,OAAO,QAAQ,KAAK,OAAO,CAAC;EAC/C,MAAM,QAAQ,QAAQ,IAAI,GAAG,KAAK,OAAO,GAAG;EAC5C,MAAM,eAAe;EACrB,gBAAgB,QAAQ,KAAK,CAAC;EAC9B,MAAM,KAAK;EACX,OAAO,MAAM;CACf;CAqCA,OAAO;AACT"}
1
+ {"version":3,"file":"selector.js","names":[],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n declare readonly key: unknown;\n /** Whether the key matches the selected value. */\n declare value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n // `equals` is a user callback: it must not subscribe the reader that happens to register the key.\n const entry = new Entry(\n key,\n untrack(() => matches(key, currentValue())),\n );\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,QAAN,MAAkC;;CAEvB,OAAO;CAChB,YAAqC;CACrC,QAAQ;;CAER,cAAc;CAOd,YAAY,KAAc,OAAgB;EACxC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,YACd,QACA,QACqB;CACrB,MAAM,0BAAU,IAAI,IAAoB;CAIxC,MAAM,WAAW,KAAQ,UACvB,WAAW,KAAA,IAAa,QAAoB,QAAQ,OAAO,KAAK,KAAK;CAEvE,MAAM,qBAAyC,QAAQ,MAAM;CAE7D,MAAM,WAAW,UAAuB;EACtC,MAAM,eAAe;EACrB,IAAI,MAAM,gBAAgB,KAAK,QAAQ,IAAI,MAAM,GAAG,MAAM,OAAO,QAAQ,OAAO,MAAM,GAAG;CAC3F;CAEA,MAAM,UAAU,QAAkB;EAEhC,MAAM,QAAQ,IAAI,MAChB,KACA,cAAc,QAAQ,KAAK,aAAa,CAAC,CAAC,CAC5C;EACA,QAAQ,IAAI,KAAK,KAAK;EACtB,OAAO;CACT;CAEA,MAAM,cAAc,QAAoB;EACtC,IAAI,CAAC,WAAW,GAAG,OAAO,QAAQ,KAAK,OAAO,CAAC;EAC/C,MAAM,QAAQ,QAAQ,IAAI,GAAG,KAAK,OAAO,GAAG;EAC5C,MAAM,eAAe;EACrB,gBAAgB,QAAQ,KAAK,CAAC;EAC9B,MAAM,KAAK;EACX,OAAO,MAAM;CACf;CAqCA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"nodes.js","names":["SignalNode"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import { isTracking, notify as notifySource, SignalNode, track } from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = new SignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = new SignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/**\n * Deletes one own property of a raw object and notifies its signal and the key set. A reserved key is\n * refused unless `cleanup` is set: removing an own data property named `__proto__` (it arrived in parsed\n * JSON) cannot reach a prototype, and `reconcile` must be able to clear it like any other stale key.\n */\nexport function deleteRaw(target: object, key: string, cleanup = false): boolean {\n if (!cleanup && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":";;;;AAGA,MAAM,gCAAqC,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;;AAoB5F,MAAa,wBAAoC,IAAI,QAAQ;;AAG7D,MAAa,sBAA+B,IAAI,QAAQ;;AAGxD,SAAgB,cAAc,KAAsB;CAClD,OAAO,cAAc,IAAI,GAAG;AAC9B;;AAGA,SAAgB,YAAY,OAAiC;CAC3D,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,IAAI,UAAU,OAAO,WAAW,OAAO;CACvC,MAAM,YAAqB,OAAO,eAAe,KAAK;CACtD,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;AAGA,SAAgB,YAAY,OAAyB;CACnD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,IAAI,IAAI,KAAK,KAAK;AAC3B;;AAGA,SAAS,cAAc,MAAuB;CAC5C,MAAM,uBAAO,IAAI,IAAY,CAAC,IAAI,CAAC;CACnC,MAAM,QAAkB,CAAC,IAAI;CAC7B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,YAAY,MAAM,IAAI;EAC5B,KAAK,MAAM,OAAO,OAAO,KAAK,SAAS,GAAG;GACxC,MAAM,SAAkB,QAAQ,IAAI,WAAW,GAAG;GAClD,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM;GACnD,IAAI,IAAI,IAAI,MAAM,GAAG,OAAO;GAC5B,IAAI,YAAY,MAAM,KAAK,CAAC,KAAK,IAAI,MAAM,GAAG;IAC5C,KAAK,IAAI,MAAM;IACf,MAAM,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AEF,MAAM,OAAO,MAAM,IAAI,MAAM;CAC7B,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,OAAO,KAAK,SAAS,IAAI,GAAG,CAAC;CAC7B,OAAO,KAAK,IAAI;CAChB,OAAO;AACT"}
1
+ {"version":3,"file":"nodes.js","names":["SignalNode","notifySource"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import { isTracking, notify as notifySource, SignalNode, track } from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = new SignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = new SignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/**\n * Deletes one own property of a raw object and notifies its signal and the key set. A reserved key is\n * refused unless `cleanup` is set: removing an own data property named `__proto__` (it arrived in parsed\n * JSON) cannot reach a prototype, and `reconcile` must be able to clear it like any other stale key.\n */\nexport function deleteRaw(target: object, key: string, cleanup = false): boolean {\n if (!cleanup && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":";;;;AAGA,MAAM,gCAAqC,IAAI,IAAI;C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n isWrappable,\n nodeOf,\n RAW,\n readRaw,\n trackKeys,\n trackProperty,\n unwrapValue,\n writeRaw,\n} from \"./nodes\";\n\n/**\n * One `setStore` call. Drafts made for it are cached here, so a draft object keeps its identity\n * inside the update, and they stop accepting writes when the call returns.\n */\nexport class Transaction {\n readonly label: string;\n open: boolean;\n readonly drafts: Map<object, object>;\n readonly handler: ProxyHandler<object>;\n\n constructor(label: string) {\n this.label = label;\n this.open = true;\n this.drafts = new Map();\n this.handler = draftHandler(this);\n }\n}\n\nfunction readOnly(key: string | symbol): TypeError {\n const name = typeof key === \"symbol\" ? key.toString() : `\"${key}\"`;\n return new TypeError(\n __DEV__\n ? `ShadowStore: the store is read-only; ${name} can only be changed inside setStore((draft) => ...)`\n : \"SHADOW_STORE_READ_ONLY\",\n );\n}\n\n/**\n * Returns the value to hand out for `key`: a wrapped object when the value is an own, writable\n * wrappable slot, otherwise the raw value. Frozen slots must return the raw value because a proxy\n * may not report a different value for a non-writable, non-configurable property.\n */\nfunction childOf(\n target: object,\n key: string,\n value: unknown,\n wrap: (raw: object) => object,\n): unknown {\n if (!isWrappable(value) || !Object.hasOwn(target, key)) return value;\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (\n descriptor !== undefined &&\n descriptor.configurable === false &&\n descriptor.writable === false\n ) {\n return value;\n }\n return wrap(value);\n}\n\n/** Descriptor passthrough that wraps the value the same way `get` does. */\nfunction describeChild(\n target: object,\n key: string | symbol,\n wrap: (raw: object) => object,\n): PropertyDescriptor | undefined {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (descriptor === undefined || typeof key === \"symbol\") return descriptor;\n if (descriptor.configurable === false) return descriptor;\n const value: unknown = descriptor.value;\n if (!isWrappable(value)) return descriptor;\n return { ...descriptor, value: wrap(value) };\n}\n\n/** `__proto__` is only reachable through the prototype chain, so the store never exposes it. */\nfunction hidesPrototype(target: object, key: string): boolean {\n return key === \"__proto__\" && !Object.hasOwn(target, key);\n}\n\n/** True when `key` resolves to an accessor property (own or inherited). */\nfunction hasGetter(target: object, key: string): boolean {\n for (\n let object: object | null = target;\n object !== null;\n object = Object.getPrototypeOf(object)\n ) {\n const descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n if (descriptor !== undefined) return typeof descriptor.get === \"function\";\n }\n return false;\n}\n\n/** Read-only handler: every read subscribes the running computation to the property it touches. */\nconst READ_HANDLER: ProxyHandler<object> = {\n get(target, key, receiver) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n trackProperty(nodeOf(target), key);\n // A getter runs with the store view as `this`, so what it reads is tracked too.\n if (hasGetter(target, key)) return Reflect.get(target, key, receiver);\n return childOf(target, key, readRaw(target, key), readProxyOf);\n },\n has(target, key) {\n if (typeof key !== \"symbol\") trackProperty(nodeOf(target), key);\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n trackKeys(nodeOf(target));\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, readProxyOf);\n },\n set(_target, key) {\n throw readOnly(key);\n },\n deleteProperty(_target, key) {\n throw readOnly(key);\n },\n defineProperty(_target, key) {\n throw readOnly(key);\n },\n setPrototypeOf() {\n throw readOnly(\"[[Prototype]]\");\n },\n preventExtensions() {\n throw readOnly(\"[[Extensible]]\");\n },\n};\n\n/** Draft handler for one transaction: writes go through the notifying helpers. */\nfunction draftHandler(tx: Transaction): ProxyHandler<object> {\n const wrap = (raw: object): object => draftOf(raw, tx);\n /** Throws unless the draft is still inside its update and `key` is a string key. */\n const writable = (key: string | symbol): string => {\n if (!tx.open) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): a draft was used after its setStore() call returned; write only inside the update`\n : \"SHADOW_STORE_DRAFT_STALE\",\n );\n }\n if (typeof key === \"symbol\") {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): symbol keys cannot be written`\n : \"SHADOW_STORE_SYMBOL_KEY\",\n );\n }\n return key;\n };\n return {\n get(target, key) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n return childOf(target, key, readRaw(target, key), wrap);\n },\n has(target, key) {\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, wrap);\n },\n set(target, key, value) {\n const name = writable(key);\n if (isReservedKey(name)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): \"${name}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n writeRaw(target, name, unwrapValue(value));\n return true;\n },\n deleteProperty(target, key) {\n return deleteRaw(target, writable(key));\n },\n defineProperty(_target, key) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): defineProperty is not supported on drafts; assign the property instead (key \"${String(key)}\")`\n : \"SHADOW_STORE_DEFINE_PROPERTY\",\n );\n },\n setPrototypeOf() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot change their prototype`\n : \"SHADOW_STORE_PROTOTYPE\",\n );\n },\n preventExtensions() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot be made non-extensible`\n : \"SHADOW_STORE_NON_EXTENSIBLE\",\n );\n },\n };\n}\n\n/** Returns the read-only proxy of a raw object. The same raw object always yields the same proxy. */\nexport function readProxyOf(raw: object): object {\n const node = nodeOf(raw);\n if (node.proxy === null) {\n const proxy = new Proxy(raw, READ_HANDLER);\n RAW.set(proxy, raw);\n node.proxy = proxy;\n }\n return node.proxy;\n}\n\n/** Returns the draft proxy of a raw object for one transaction. */\nexport function draftOf(raw: object, tx: Transaction): object {\n const existing = tx.drafts.get(raw);\n if (existing !== undefined) return existing;\n const proxy = new Proxy(raw, tx.handler);\n RAW.set(proxy, raw);\n tx.drafts.set(raw, proxy);\n return proxy;\n}\n"],"mappings":";;;;;;AAiBA,IAAa,cAAb,MAAyB;CAC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CACvC,IAAI,IAAI,OAAO,GAAG;CAClB,GAAG,OAAO,IAAI,KAAK,KAAK;CACxB,OAAO;AACT"}
1
+ {"version":3,"file":"proxies.js","names":[],"sources":["../../../src/store/proxies.ts"],"sourcesContent":["import {\n deleteRaw,\n isReservedKey,\n isWrappable,\n nodeOf,\n RAW,\n readRaw,\n trackKeys,\n trackProperty,\n unwrapValue,\n writeRaw,\n} from \"./nodes\";\n\n/**\n * One `setStore` call. Drafts made for it are cached here, so a draft object keeps its identity\n * inside the update, and they stop accepting writes when the call returns.\n */\nexport class Transaction {\n readonly label: string;\n open: boolean;\n readonly drafts: Map<object, object>;\n readonly handler: ProxyHandler<object>;\n\n constructor(label: string) {\n this.label = label;\n this.open = true;\n this.drafts = new Map();\n this.handler = draftHandler(this);\n }\n}\n\nfunction readOnly(key: string | symbol): TypeError {\n const name = typeof key === \"symbol\" ? key.toString() : `\"${key}\"`;\n return new TypeError(\n __DEV__\n ? `ShadowStore: the store is read-only; ${name} can only be changed inside setStore((draft) => ...)`\n : \"SHADOW_STORE_READ_ONLY\",\n );\n}\n\n/**\n * Returns the value to hand out for `key`: a wrapped object when the value is an own, writable\n * wrappable slot, otherwise the raw value. Frozen slots must return the raw value because a proxy\n * may not report a different value for a non-writable, non-configurable property.\n */\nfunction childOf(\n target: object,\n key: string,\n value: unknown,\n wrap: (raw: object) => object,\n): unknown {\n if (!isWrappable(value) || !Object.hasOwn(target, key)) return value;\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (\n descriptor !== undefined &&\n descriptor.configurable === false &&\n descriptor.writable === false\n ) {\n return value;\n }\n return wrap(value);\n}\n\n/** Descriptor passthrough that wraps the value the same way `get` does. */\nfunction describeChild(\n target: object,\n key: string | symbol,\n wrap: (raw: object) => object,\n): PropertyDescriptor | undefined {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (descriptor === undefined || typeof key === \"symbol\") return descriptor;\n if (descriptor.configurable === false) return descriptor;\n const value: unknown = descriptor.value;\n if (!isWrappable(value)) return descriptor;\n return { ...descriptor, value: wrap(value) };\n}\n\n/** `__proto__` is only reachable through the prototype chain, so the store never exposes it. */\nfunction hidesPrototype(target: object, key: string): boolean {\n return key === \"__proto__\" && !Object.hasOwn(target, key);\n}\n\n/** True when `key` resolves to an accessor property (own or inherited). */\nfunction hasGetter(target: object, key: string): boolean {\n for (\n let object: object | null = target;\n object !== null;\n object = Object.getPrototypeOf(object)\n ) {\n const descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n if (descriptor !== undefined) return typeof descriptor.get === \"function\";\n }\n return false;\n}\n\n/** Read-only handler: every read subscribes the running computation to the property it touches. */\nconst READ_HANDLER: ProxyHandler<object> = {\n get(target, key, receiver) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n trackProperty(nodeOf(target), key);\n // A getter runs with the store view as `this`, so what it reads is tracked too.\n if (hasGetter(target, key)) return Reflect.get(target, key, receiver);\n return childOf(target, key, readRaw(target, key), readProxyOf);\n },\n has(target, key) {\n if (typeof key !== \"symbol\") trackProperty(nodeOf(target), key);\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n trackKeys(nodeOf(target));\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, readProxyOf);\n },\n set(_target, key) {\n throw readOnly(key);\n },\n deleteProperty(_target, key) {\n throw readOnly(key);\n },\n defineProperty(_target, key) {\n throw readOnly(key);\n },\n setPrototypeOf() {\n throw readOnly(\"[[Prototype]]\");\n },\n preventExtensions() {\n throw readOnly(\"[[Extensible]]\");\n },\n};\n\n/** Draft handler for one transaction: writes go through the notifying helpers. */\nfunction draftHandler(tx: Transaction): ProxyHandler<object> {\n const wrap = (raw: object): object => draftOf(raw, tx);\n /** Throws unless the draft is still inside its update and `key` is a string key. */\n const writable = (key: string | symbol): string => {\n if (!tx.open) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): a draft was used after its setStore() call returned; write only inside the update`\n : \"SHADOW_STORE_DRAFT_STALE\",\n );\n }\n if (typeof key === \"symbol\") {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): symbol keys cannot be written`\n : \"SHADOW_STORE_SYMBOL_KEY\",\n );\n }\n return key;\n };\n return {\n get(target, key) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n return childOf(target, key, readRaw(target, key), wrap);\n },\n has(target, key) {\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, wrap);\n },\n set(target, key, value) {\n const name = writable(key);\n if (isReservedKey(name)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): \"${name}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n writeRaw(target, name, unwrapValue(value));\n return true;\n },\n deleteProperty(target, key) {\n return deleteRaw(target, writable(key));\n },\n defineProperty(_target, key) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): defineProperty is not supported on drafts; assign the property instead (key \"${String(key)}\")`\n : \"SHADOW_STORE_DEFINE_PROPERTY\",\n );\n },\n setPrototypeOf() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot change their prototype`\n : \"SHADOW_STORE_PROTOTYPE\",\n );\n },\n preventExtensions() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot be made non-extensible`\n : \"SHADOW_STORE_NON_EXTENSIBLE\",\n );\n },\n };\n}\n\n/** Returns the read-only proxy of a raw object. The same raw object always yields the same proxy. */\nexport function readProxyOf(raw: object): object {\n const node = nodeOf(raw);\n if (node.proxy === null) {\n const proxy = new Proxy(raw, READ_HANDLER);\n RAW.set(proxy, raw);\n node.proxy = proxy;\n }\n return node.proxy;\n}\n\n/** Returns the draft proxy of a raw object for one transaction. */\nexport function draftOf(raw: object, tx: Transaction): object {\n const existing = tx.drafts.get(raw);\n if (existing !== undefined) return existing;\n const proxy = new Proxy(raw, tx.handler);\n RAW.set(proxy, raw);\n tx.drafts.set(raw, proxy);\n return proxy;\n}\n"],"mappings":";;;;;;AAiBA,IAAa,cAAb,MAAyB;CACd;CACT;CACS;CACA;CAET,YAAY,OAAe;EACzB,KAAK,QAAQ;EACb,KAAK,OAAO;EACZ,KAAK,yBAAS,IAAI,IAAI;EACtB,KAAK,UAAU,aAAa,IAAI;CAClC;AACF;AAEA,SAAS,SAAS,KAAiC;CACjD,MAAM,OAAO,OAAO,QAAQ,WAAW,IAAI,SAAS,IAAI,IAAI,IAAI;CAChE,uBAAO,IAAI,UAEL,wCAAwC,KAAK,qDAEnD;AACF;;;;;;AAOA,SAAS,QACP,QACA,KACA,OACA,MACS;CACT,IAAI,CAAC,YAAY,KAAK,KAAK,CAAC,OAAO,OAAO,QAAQ,GAAG,GAAG,OAAO;CAC/D,MAAM,aAAa,QAAQ,yBAAyB,QAAQ,GAAG;CAC/D,IACE,eAAe,KAAA,KACf,WAAW,iBAAiB,SAC5B,WAAW,aAAa,OAExB,OAAO;CAET,OAAO,KAAK,KAAK;AACnB;;AAGA,SAAS,cACP,QACA,KACA,MACgC;CAChC,MAAM,aAAa,QAAQ,yBAAyB,QAAQ,GAAG;CAC/D,IAAI,eAAe,KAAA,KAAa,OAAO,QAAQ,UAAU,OAAO;CAChE,IAAI,WAAW,iBAAiB,OAAO,OAAO;CAC9C,MAAM,QAAiB,WAAW;CAClC,IAAI,CAAC,YAAY,KAAK,GAAG,OAAO;CAChC,OAAO;EAAE,GAAG;EAAY,OAAO,KAAK,KAAK;CAAE;AAC7C;;AAGA,SAAS,eAAe,QAAgB,KAAsB;CAC5D,OAAO,QAAQ,eAAe,CAAC,OAAO,OAAO,QAAQ,GAAG;AAC1D;;AAGA,SAAS,UAAU,QAAgB,KAAsB;CACvD,KACE,IAAI,SAAwB,QAC5B,WAAW,MACX,SAAS,OAAO,eAAe,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AK;AACd;;AAGA,SAAgB,QAAQ,KAAa,IAAyB;CAC5D,MAAM,WAAW,GAAG,OAAO,IAAI,GAAG;CAClC,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,QAAQ,IAAI,MAAM,KAAK,GAAG,OAAO;CACvC,IAAI,IAAI,OAAO,GAAG;CAClB,GAAG,OAAO,IAAI,KAAK,KAAK;CACxB,OAAO;AACT"}
@@ -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/** Appends `items` to `keys` one by one: a spread into `push` overflows the call stack for a long list. */\nfunction appendKeys(keys: Array<string | number>, items: ReadonlyArray<string | number>): void {\n for (const item of items) keys.push(item);\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)) appendKeys(keys, step as number[]);\n else if (typeof step === \"object\" && step !== null)\n appendKeys(keys, 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 appendKeys(keys, 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":";;;;;;;;;;;AA4BA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,UAAU,OAAoD,QAA0B;CAC/F,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,KAAK,MAAM,MAAM,SAAS;CAChC,MAAM,KAAK,MAAM,MAAM;CACvB,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,OAAO,GACjC,MAAM,IAAI,UACE,4CACZ;CACF,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI;EACtD,KAAK,KAAK,CAAC;EACX,IAAI,KAAK,SAAS,SAAS,GAAG;CAChC;CACA,OAAO;AACT;;AAGA,SAAS,WAAW,MAA8B,OAA6C;CAC7F,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,IAAI;AAC1C;;AAGA,SAAS,SAAS,QAAgB,MAAe,OAAuC;CACtF,MAAM,OAA+B,CAAC;CACtC,IAAI,MAAM,QAAQ,MAAM,GAAG;EAC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,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
+ {"version":3,"file":"use-store.js","names":["devtoolsReport"],"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/** Appends `items` to `keys` one by one: a spread into `push` overflows the call stack for a long list. */\nfunction appendKeys(keys: Array<string | number>, items: ReadonlyArray<string | number>): void {\n for (const item of items) keys.push(item);\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)) appendKeys(keys, step as number[]);\n else if (typeof step === \"object\" && step !== null)\n appendKeys(keys, 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 appendKeys(keys, 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":";;;;;;;;;;;AA4BA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,UAAU,OAAoD,QAA0B;CAC/F,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,KAAK,MAAM,MAAM,SAAS;CAChC,MAAM,KAAK,MAAM,MAAM;CACvB,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,OAAO,GACjC,MAAM,IAAI,UACE,4CACZ;CACF,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI;EACtD,KAAK,KAAK,CAAC;EACX,IAAI,KAAK,SAAS,SAAS,GAAG;CAChC;CACA,OAAO;AACT;;AAGA,SAAS,WAAW,MAA8B,OAA6C;CAC7F,KAAK,MA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AgB,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shadow-js/core",
3
- "version": "1.0.6",
3
+ "version": "1.1.1",
4
4
  "description": "Signals, stores, memos and effects that update exactly what changed",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -114,15 +114,15 @@
114
114
  "url": "https://github.com/shadowjs-dev/shadow/issues"
115
115
  },
116
116
  "devDependencies": {
117
- "@biomejs/biome": "2.5.15",
117
+ "@biomejs/biome": "2.6.6",
118
118
  "@shadow-js/compiler": "*",
119
119
  "@shadow-js/web": "*",
120
120
  "@types/node": "^24.0.0",
121
- "esbuild": "0.27.0",
121
+ "esbuild": "0.28.2",
122
122
  "fast-check": "^4.10.2",
123
123
  "happy-dom": "21.0.4",
124
- "tsdown": "0.23.0",
124
+ "tsdown": "0.23.7",
125
125
  "typescript": "7.0.2",
126
- "vitest": "5.0.3"
126
+ "vitest": "5.1.0"
127
127
  }
128
128
  }