@shadow-js/core 1.1.0 → 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 +6 -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","cell","node","Signal","initial","distinct","readSignal","writeSignal","next","isPromiseLike","value","useResource","hasSource","second","source","first","oneShot","fetcher","info","options","third","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","useContext","ResourceCacheContext","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","batch","apply","load","refetching","current","output","joined","untrack","input","error","result","immediate","applied","onSource","read","SuspenseContext","currentListener","inTransition","holdReader","resolved","changed","onCleanup"],"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":"A,uaAkGA,SAASC,EAAQ,EAAY,EAAqD,CAChF,I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,GAAS,WACZ2C,MAAe3C,EAAwCE,EAAM,CAAC,CAAC,EAC/DF,EACN,EAAU,GACV2B,GAAY,MAAM,EAClB,GAAW,EACX,EAAW,GACXb,EAASyC,CAAa,EACtBpC,EAAW,IAAA,EAAS,EACpBF,EAAS,OAAO,CAClB,CAAC,CACH,QAAU,CACJuC,GAASzB,EAAQ,CACvB,CACA,OAAOwB,CACT,CACF,CACF,CAAC,EAMeN,EAASN,EAAQrC,CAAM,CAAC,EAExCmD,MAAgB,CACd,EAAW,GACX9B,GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMmB,CACT,C"}
1
+ {"version":3,"file":"resource.js","names":["SignalNode","Signal","readSignal","batch","useContext","currentListener","writeSignal","onCleanup","untrack","holdReader","inTransition","ResourceCacheContext","SuspenseContext","cell","initial","distinct","node","next","isPromiseLike","value","useResource","first","second","third","hasSource","source","oneShot","fetcher","_input","info","options","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","apply","load","input","refetching","current","output","joined","error","result","immediate","applied","onSource","read","resolved","changed"],"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":"A,uaAkGA,SAASa,EAAQC,EAAYC,EAAqD,CAChF,IAAMC,EAAO,IAAIhB,EAAcc,EAASC,EAAW,OAAO,GAAK,EAAK,EACpE,MAAO,KACCb,EAAWc,CAAI,EACpBC,GAAS,CACRX,EAAYU,E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,GAAY,MAAM,EAClBD,GAAW,EACXG,EAAW,GACXb,EAASiC,CAAa,EACtB5B,EAAW,IAAA,EAAS,EACpBF,EAAS,OAAO,CAClB,CAAC,CACH,QAAU,CACJ+B,GAASnB,EAAQ,CACvB,CACA,OAAOkB,CACT,CACF,CACF,CAAC,EAMeF,EAASvD,EAAQiB,CAAM,CAAC,EAExClB,MAAgB,CACdqC,EAAW,GACXD,GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMiB,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"selector.js","names":["Entry","key","value","useSelector","entries","matches","equals","currentValue","untrack","source","release","entry","create","isTracking","onCleanup","track"],"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":"A,uKAQA,IAAMA,EAAN,KAAkC,CAEhC,KAAgB,EAChB,UAAqC,KACrC,MAAQ,EAER,YAAc,EAOd,YAAY,EAAc,EAAgB,CACxC,KAAK,IAAMC,EACX,KAAK,MAAQC,CACf,CACF,EAuCA,SAAgBC,EACd,EACA,EACqB,CACrB,IAAMC,kBAAU,IAAI,IAIdC,GAAW,EAAQ,IACvBC,IAAW,IAAA,GAAaL,IAAoBC,EAAQI,EAAOL,EAAKC,CAAK,EAEjEK,MAAyCC,EAAQC,CAAM,EAEvDC,EAAW,GAAuB,CACtC,IAAM,YACFC,EAAM,cAAgB,GAAKP,EAAQ,IAAIO,EAAM,GAAG,IAAMA,GAAOP,EAAQ,OAAOO,EAAM,GAAG,CAC3F,EAEMC,EAAU,GAAkB,CAEhC,IAAMD,EAAQ,IAAIX,EAChBC,EACAO,MAAcH,EAAQJ,EAAKM,EAAa,CAAC,CAAC,CAC5C,EAEA,OADAH,EAAQ,IAAIH,EAAKU,CAAK,EACfA,CACT,EA8CA,MA5CoB,IAAoB,CACtC,GAAI,CAACE,EAAW,EAAG,OAAOR,EAAQJ,EAAKQ,EAAO,CAAC,EAC/C,IAAME,EAAQP,EAAQ,IAAIH,CAAG,GAAKW,EAAOX,CAAG,EAI5C,MAHA,GAAM,aAAe,EACrBa,MAAgBJ,EAAQC,CAAK,CAAC,EAC9BI,EAAMJ,CAAK,EACJA,EAAM,KACf,CAsCF,C"}
1
+ {"version":3,"file":"selector.js","names":["track","isTracking","onCleanup","untrack","Entry","key","value","useSelector","source","equals","entries","matches","currentValue","release","entry","create"],"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":"A,uKAQA,IAAMI,EAAN,KAAkC,CAEvB,KAAO,EAChB,UAAqC,KACrC,MAAQ,EAER,YAAc,EAOd,YAAYC,EAAcC,EAAgB,CACxC,KAAK,IAAMD,EACX,KAAK,MAAQC,CACf,CACF,EAuCA,SAAgBC,EACdC,EACAC,EACqB,CACrB,IAAMC,kBAAU,IAAI,IAIdC,GAAWN,EAAQC,IACvBG,IAAW,IAAA,GAAaJ,IAAoBC,EAAQG,EAAOJ,EAAKC,CAAK,EAEjEM,MAAyCT,EAAQK,CAAM,EAEvDK,EAAWC,GAAuB,CACtCA,IAAM,YACFA,EAAM,cAAgB,GAAKJ,EAAQ,IAAII,EAAM,GAAG,IAAMA,GAAOJ,EAAQ,OAAOI,EAAM,GAAG,CAC3F,EAEMC,EAAUV,GAAkB,CAEhC,IAAMS,EAAQ,IAAIV,EAChBC,EACAF,MAAcQ,EAAQN,EAAKO,EAAa,CAAC,CAAC,CAC5C,EAEA,OADAF,EAAQ,IAAIL,EAAKS,CAAK,EACfA,CACT,EA8CA,MA5CoBT,IAAoB,CACtC,GAAI,CAACJ,EAAW,EAAG,OAAOU,EAAQN,EAAKG,EAAO,CAAC,EAC/C,IAAMM,EAAQJ,EAAQ,IAAIL,CAAG,GAAKU,EAAOV,CAAG,EAI5C,MAHAS,GAAM,aAAe,EACrBZ,MAAgBW,EAAQC,CAAK,CAAC,EAC9Bd,EAAMc,CAAK,EACJA,EAAM,KACf,CAsCF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"signal.js","names":["SignalNode","useSignal","equals","options","signal","Signal","value","readSignal","resolved","next","untrack","writeSignal"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n type Equals,\n readSignal,\n type Setter,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value. It runs untracked: a signal it reads\n * is not a dependency of the computation that writes.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string | undefined;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = new SignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":"A,sJAiDA,SAAgBC,EAAa,EAAU,EAAsD,CAC3F,IAAMC,EAAoBC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OACxEC,EAAS,IAAIJ,EAAcM,EAAOJ,EAAQC,GAAS,IAAI,EAS7D,MAAO,KARyBI,EAAWH,CAAM,GACjC,GAAkB,CAChC,IAAMI,EACJ,OAAOC,GAAS,WAAaC,MAAeD,EAAwBL,EAAO,KAAK,CAAC,EAAIK,EAGvF,OADAE,EAAYP,EAAQI,CAAQ,EACrBA,CACT,EACmB,CACrB,C"}
1
+ {"version":3,"file":"signal.js","names":["SignalNode","Signal","readSignal","writeSignal","untrack","useSignal","value","options","equals","signal","next","resolved"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n type Equals,\n readSignal,\n type Setter,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value. It runs untracked: a signal it reads\n * is not a dependency of the computation that writes.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string | undefined;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = new SignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":"A,sJAiDA,SAAgBK,EAAaC,EAAUC,EAAsD,CAC3F,IAAMC,EAAoBD,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OACxEE,EAAS,IAAIT,EAAcM,EAAOE,EAAQD,GAAS,IAAI,EAS7D,MAAO,KARyBL,EAAWO,CAAM,GACjCC,GAAkB,CAChC,IAAMC,EACJ,OAAOD,GAAS,WAAaN,MAAeM,EAAwBD,EAAO,KAAK,CAAC,EAAIC,EAGvF,OADAP,EAAYM,EAAQE,CAAQ,EACrBA,CACT,EACmB,CACrB,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"nodes.js","names":["SignalNode","notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","size","other","Signal","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw","cleanup"],"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":"A,qHAGA,MAAME,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAoB/EC,kBAAoC,IAAI,QAGxCC,kBAA+B,IAAI,QAGhD,SAAgBC,EAAc,EAAsB,CAClD,OAAOH,EAAc,IAAII,CAAG,CAC9B,CAGA,SAAgBC,EAAY,EAAiC,CAC3D,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,MAAM,QAAQA,CAAK,EAAG,MAAO,GACjC,GAAIA,IAAU,OAAO,UAAW,MAAO,GACvC,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAGA,SAAgBC,EAAY,EAAyB,CAEnD,OADI,OAAOF,GAAU,WAAYA,EAAuBA,EACjDJ,EAAI,IAAII,CAAK,GAAKA,CAC3B,CAGA,SAASG,EAAc,EAAuB,CAC5C,IAAMC,kBAAO,IAAI,IAAY,CAACC,CAAI,CAAC,EAC7BC,EAAkB,CAACD,CAAI,EAC7B,KAAOC,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAYD,EAAM,IAAI,EAC5B,IAAK,IAAMR,KAAO,OAAO,KAAKS,CAAS,EAAG,CACxC,IAAMC,EAAkB,QAAQ,IAAID,EAAWT,CAAG,EAClD,GAAI,OAAOU,GAAW,UAAYA,EAClC,IAAIZ,EAAI,IAAIY,CAAM,EAAG,MAA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,IAAIwB,CAAM,EAI7B,OAHIK,IAAS,IAAA,KACbW,EAAOX,EAAK,SAAS,IAAI1B,CAAG,CAAC,EAC7BqC,EAAOX,EAAK,IAAI,GACT,EACT,C"}
1
+ {"version":3,"file":"nodes.js","names":["SignalNode","notifySource","Signal","track","isTracking","notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","root","seen","stack","container","member","unwrapDeep","first","copies","copyOf","source","existing","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","size","other","trackProperty","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw","cleanup"],"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":"A,qHAGA,MAAMM,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAoB/EC,kBAAoC,IAAI,QAGxCC,kBAA+B,IAAI,QAGhD,SAAgBC,EAAcC,EAAsB,CAClD,OAAOJ,EAAc,IAAII,CAAG,CAC9B,CAGA,SAAgBC,EAAYC,EAAiC,CAC3D,GAAI,OAAOA,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,MAAM,QAAQA,CAAK,EAAG,MAAO,GACjC,GAAIA,IAAU,OAAO,UAAW,MAAO,GACvC,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAGA,SAAgBC,EAAYF,EAAyB,CAEnD,OADI,OAAOA,GAAU,WAAYA,EAAuBA,EACjDJ,EAAI,IAAII,CAAK,GAAKA,CAC3B,CAGA,SAASG,EAAcC,EAAuB,CAC5C,IAAMC,kBAAO,IAAI,IAAY,CAACD,CAAI,CAAC,EAC7BE,EAAkB,CAACF,CAAI,EAC7B,KAAOE,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAYD,EAAM,IAAI,EAC5B,IAAK,IAAMR,KAAO,OAAO,KAAKS,CAAS,EAAG,CACxC,IAAMC,EAAkB,QAAQ,IAAID,EAAWT,CAAG,EAClD,GAAI,OAAOU,GAAW,UAAYA,EAClC,IAAIZ,EAAI,IAAIY,CAAM,EAAG,MAAO,GACxBT,EAAYS,CAAM,GAAK,CAACH,EAAK,IAAIG,CAAM,IACzCH,EAAK,IAAIG,CAAM,EACfF,EAAM,KAAKE,CAAM,EAHS,CAK9B,CACF,CACA,MAAO,EACT,CAQA,SAAgBC,EAAW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IAAI,GACT,EACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"proxies.js","names":["Transaction","label","draftHandler","readOnly","key","childOf","isWrappable","value","target","descriptor","wrap","describeChild","hidesPrototype","hasGetter","object","READ_HANDLER","trackProperty","nodeOf","receiver","readRaw","readProxyOf","trackKeys","draftOf","raw","tx","writable","name","isReservedKey","writeRaw","unwrapValue","deleteRaw","node","proxy","RAW","existing"],"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":"A,8KAiBA,IAAaA,EAAb,KAAyB,CACvB,MACA,KACA,OACA,QAEA,YAAY,EAAe,CACzB,KAAK,MAAQC,EACb,KAAK,KAAO,GACZ,KAAK,uBAAS,IAAI,IAClB,KAAK,QAAUC,EAAa,IAAI,CAClC,CACF,EAEA,SAASC,EAAS,EAAiC,CAEjD,OADa,OAAOC,GAAQ,SAAWA,EAAI,SAAS,EAAI,GAAIA,IACrD,gBAAI,UAGL,wBACN,CACF,CAOA,SAASC,EACP,EACA,EACA,EACA,EACS,CACT,GAAI,CAACC,EAAYC,CAAK,GAAK,CAAC,OAAO,OAAOC,EAAQJ,CAAG,EAAG,OAAOG,EAC/D,IAAME,EAAa,QAAQ,yBAAyBD,EAAQJ,CAAG,EAQ/D,OANEK,IAAe,IAAA,IACfA,EAAW,eAAiB,IAC5BA,EAAW,WAAa,GAEjBF,EAEFG,EAAKH,CAAK,CACnB,CAGA,SAASI,EACP,EACA,EACA,EACgC,CAChC,IAAMF,EAAa,QAAQ,yBAAyBD,EAAQJ,CAAG,EAE/D,GADIK,IAAe,IAAA,IAAa,OAAOL,GAAQ,UAC3CK,EAAW,eAAiB,GAAO,OAAOA,EAC9C,IAAMF,EAAiBE,EAAW,MAElC,OADKH,EAAYC,CAAK,EACf,CAAE,GAAGE,EAAY,MAAOC,EAAKH,CAAK,CAAE,EADXE,CAElC,CAGA,SAASG,EAAe,EAAgB,EAAsB,CAC5D,OAAOR,IAAQ,aAAe,CAAC,OAAO,OAAOI,EAAQJ,CAAG,CAC1D,CAGA,SA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AAWV,EAAG,OAAO,IAAID,CAAG,EAClC,GAAIW,IAAa,IAAA,GAAW,OAAOA,EACnC,IAAMF,EAAQ,IAAI,MAAMT,EAAKC,EAAG,OAAO,EAGvC,OAFAS,EAAI,IAAID,EAAOT,CAAG,EAClBC,EAAG,OAAO,IAAID,EAAKS,CAAK,EACjBA,CACT,C"}
1
+ {"version":3,"file":"proxies.js","names":["RAW","deleteRaw","isReservedKey","isWrappable","nodeOf","readRaw","trackKeys","trackProperty","unwrapValue","writeRaw","Transaction","label","draftHandler","readOnly","key","childOf","target","value","wrap","descriptor","describeChild","hidesPrototype","hasGetter","object","READ_HANDLER","receiver","readProxyOf","_target","tx","raw","draftOf","writable","name","node","proxy","existing"],"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":"A,8KAiBA,IAAaU,EAAb,KAAyB,CACd,MACT,KACS,OACA,QAET,YAAYC,EAAe,CACzB,KAAK,MAAQA,EACb,KAAK,KAAO,GACZ,KAAK,uBAAS,IAAI,IAClB,KAAK,QAAUC,EAAa,IAAI,CAClC,CACF,EAEA,SAASC,EAASC,EAAiC,CAEjD,OADa,OAAOA,GAAQ,SAAWA,EAAI,SAAS,EAAI,GAAIA,IACrD,gBAAI,UAGL,wBACN,CACF,CAOA,SAASC,EACPC,EACAF,EACAG,EACAC,EACS,CACT,GAAI,CAACf,EAAYc,CAAK,GAAK,CAAC,OAAO,OAAOD,EAAQF,CAAG,EAAG,OAAOG,EAC/D,IAAME,EAAa,QAAQ,yBAAyBH,EAAQF,CAAG,EAQ/D,OANEK,IAAe,IAAA,IACfA,EAAW,eAAiB,IAC5BA,EAAW,WAAa,GAEjBF,EAEFC,EAAKD,CAAK,CACnB,CAGA,SAASG,EACPJ,EACAF,EACAI,EACgC,CAChC,IAAMC,EAAa,QAAQ,yBAAyBH,EAAQF,CAAG,EAE/D,GADIK,IAAe,IAAA,IAAa,OAAOL,GAAQ,UAC3CK,EAAW,eAAiB,GAAO,OAAOA,EAC9C,IAAMF,EAAiBE,EAAW,MAElC,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EAAK,QAAU,KAAM,CACvB,IAAMC,EAAQ,IAAI,MAAML,EAAKL,CAAY,EACzCxB,EAAI,IAAIkC,EAAOL,CAAG,EAClBI,EAAK,MAAQC,CACf,CACA,OAAOD,EAAK,KACd,CAGA,SAAgBH,EAAQD,EAAaD,EAAyB,CAC5D,IAAMO,EAAWP,EAAG,OAAO,IAAIC,CAAG,EAClC,GAAIM,IAAa,IAAA,GAAW,OAAOA,EACnC,IAAMD,EAAQ,IAAI,MAAML,EAAKD,EAAG,OAAO,EAGvC,OAFA5B,EAAI,IAAIkC,EAAOL,CAAG,EAClBD,EAAG,OAAO,IAAIC,EAAKK,CAAK,EACjBA,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"read.js","names":["unwrap","unwrapValue","store","shellOf","value","snapshot","root","isWrappable","copies","out","pending","source","copy","key","isReservedKey","readRaw","child"],"sources":["../../../src/store/read.ts"],"sourcesContent":["import { isReservedKey, isWrappable, readRaw, unwrapValue } from \"./nodes\";\nimport type { Mutable, Store } from \"./types\";\n\n/**\n * Returns the raw data behind a store. Reads and writes on the result bypass tracking and\n * notification, so writing to it is a bug; use it for identity checks and passing data on.\n *\n * @param store A store view. A value that is not a store view is returned as is.\n * @returns The underlying object, without proxies. It is the live data, not a copy.\n * @example\n * import { unwrap, useStore } from \"@shadow-js/core\";\n *\n * const initial = { items: [1, 2, 3] };\n * const [list] = useStore(initial);\n * console.log(unwrap(list) === initial); // true: the store wraps its data in place\n * @see snapshot\n * @since 1.0.0\n */\nexport function unwrap<T>(store: Store<T>): Mutable<T> {\n return unwrapValue(store) as Mutable<T>;\n}\n\n/** A new, empty container of the same kind as `value`, with the same length for arrays. */\nfunction shellOf(value: object): object {\n return Array.isArray(value) ? new Array<unknown>((value as unknown[]).length) : {};\n}\n\n/**\n * Returns a deep plain copy of a store's current data. It reads raw data directly, so it does\n * not subscribe the running computation, and the copy is independent of later writes. Cycles and\n * shared objects are preserved. The walk is iterative, so deep data cannot overflow the stack. Use\n * it to serialize a store, send it to a server or keep an undo history.\n *\n * @param store A store view. A value that is not plain data is returned as is.\n * @returns A plain, untracked deep copy.\n * @example\n * import { snapshot, useStore } from \"@shadow-js/core\";\n *\n * const [form, setForm] = useStore({ name: \"Ada\", tags: [\"admin\"] });\n * const saved = snapshot(form);\n * setForm({ name: \"Grace\" });\n * console.log(saved.name, JSON.stringify(saved)); // Ada {\"name\":\"Ada\",\"tags\":[\"admin\"]}\n * @see unwrap\n * @since 1.0.0\n */\nexport function snapshot<T>(store: Store<T>): Mutable<T> {\n const root = unwrapValue(store);\n if (!isWrappable(root)) return root as Mutable<T>;\n const copies = new Map<object, object>();\n const out: object = shellOf(root);\n copies.set(root, out);\n const pending: object[] = [root];\n for (let source = pending.pop(); source !== undefined; source = pending.pop()) {\n const copy = copies.get(source);\n if (copy === undefined) continue;\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(readRaw(source, key));\n if (isWrappable(value)) {\n let child = copies.get(value);\n if (child === undefined) {\n child = shellOf(value);\n copies.set(value, child);\n pending.push(value);\n }\n Reflect.set(copy, key, child);\n } else {\n Reflect.set(copy, key, value);\n }\n }\n }\n return out as Mutable<T>;\n}\n"],"mappings":"A,0FAkBA,SAAgBA,EAAU,EAA6B,CACrD,OAAOC,EAAYC,CAAK,CAC1B,CAGA,SAASC,EAAQ,EAAuB,CACtC,OAAO,MAAM,QAAQC,CAAK,EAAQ,MAAgBA,EAAoB,MAAM,EAAI,CAAC,CACnF,CAoBA,SAAgBC,EAAY,EAA6B,CACvD,IAAMC,EAAOL,EAAYC,CAAK,EAC9B,GAAI,CAACK,EAAYD,CAAI,EAAG,OAAOA,EAC/B,IAAME,kBAAS,IAAI,IACbC,EAAcN,EAAQG,CAAI,EAChCE,EAAO,IAAIF,EAAMG,CAAG,EACpB,IAAMC,EAAoB,CAACJ,CAAI,EAC/B,IAAK,IAAIK,EAASD,EAAQ,IAAI,EAAGC,IAAW,IAAA,GAAW,EAASD,EAAQ,IAAI,EAAG,CAC7E,IAAME,EAAOJ,EAAO,IAAIG,CAAM,EAC9B,GAAIC,IAAS,IAAA,GACb,IAAK,IAAMC,KAAO,OAAO,KAAKF,CAAM,EAAG,CACrC,GAAIG,EAAcD,CAAG,EAAG,SACxB,IAAMT,EAAQH,EAAYc,EAAQJ,EAAQE,CAAG,CAAC,EAC9C,GAAIN,EAAYH,CAAK,EAAG,CACtB,IAAIY,EAAQR,EAAO,IAAIJ,CAAK,EACxBY,IAAU,IAAA,KACZ,EAAQb,EAAQC,CAAK,EACrBI,EAAO,IAAIJ,EAAOY,CAAK,EACvBN,EAAQ,KAAKN,CAAK,GAEpB,QAAQ,IAAIQ,EAAMC,EAAKG,CAAK,CAC9B,MACE,QAAQ,IAAIJ,EAAMC,EAAKT,CAAK,CAEhC,CACF,CACA,OAAOK,CACT,C"}
1
+ {"version":3,"file":"read.js","names":["isReservedKey","isWrappable","readRaw","unwrapValue","unwrap","store","shellOf","value","snapshot","root","copies","out","pending","source","copy","key","child"],"sources":["../../../src/store/read.ts"],"sourcesContent":["import { isReservedKey, isWrappable, readRaw, unwrapValue } from \"./nodes\";\nimport type { Mutable, Store } from \"./types\";\n\n/**\n * Returns the raw data behind a store. Reads and writes on the result bypass tracking and\n * notification, so writing to it is a bug; use it for identity checks and passing data on.\n *\n * @param store A store view. A value that is not a store view is returned as is.\n * @returns The underlying object, without proxies. It is the live data, not a copy.\n * @example\n * import { unwrap, useStore } from \"@shadow-js/core\";\n *\n * const initial = { items: [1, 2, 3] };\n * const [list] = useStore(initial);\n * console.log(unwrap(list) === initial); // true: the store wraps its data in place\n * @see snapshot\n * @since 1.0.0\n */\nexport function unwrap<T>(store: Store<T>): Mutable<T> {\n return unwrapValue(store) as Mutable<T>;\n}\n\n/** A new, empty container of the same kind as `value`, with the same length for arrays. */\nfunction shellOf(value: object): object {\n return Array.isArray(value) ? new Array<unknown>((value as unknown[]).length) : {};\n}\n\n/**\n * Returns a deep plain copy of a store's current data. It reads raw data directly, so it does\n * not subscribe the running computation, and the copy is independent of later writes. Cycles and\n * shared objects are preserved. The walk is iterative, so deep data cannot overflow the stack. Use\n * it to serialize a store, send it to a server or keep an undo history.\n *\n * @param store A store view. A value that is not plain data is returned as is.\n * @returns A plain, untracked deep copy.\n * @example\n * import { snapshot, useStore } from \"@shadow-js/core\";\n *\n * const [form, setForm] = useStore({ name: \"Ada\", tags: [\"admin\"] });\n * const saved = snapshot(form);\n * setForm({ name: \"Grace\" });\n * console.log(saved.name, JSON.stringify(saved)); // Ada {\"name\":\"Ada\",\"tags\":[\"admin\"]}\n * @see unwrap\n * @since 1.0.0\n */\nexport function snapshot<T>(store: Store<T>): Mutable<T> {\n const root = unwrapValue(store);\n if (!isWrappable(root)) return root as Mutable<T>;\n const copies = new Map<object, object>();\n const out: object = shellOf(root);\n copies.set(root, out);\n const pending: object[] = [root];\n for (let source = pending.pop(); source !== undefined; source = pending.pop()) {\n const copy = copies.get(source);\n if (copy === undefined) continue;\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(readRaw(source, key));\n if (isWrappable(value)) {\n let child = copies.get(value);\n if (child === undefined) {\n child = shellOf(value);\n copies.set(value, child);\n pending.push(value);\n }\n Reflect.set(copy, key, child);\n } else {\n Reflect.set(copy, key, value);\n }\n }\n }\n return out as Mutable<T>;\n}\n"],"mappings":"A,0FAkBA,SAAgBI,EAAUC,EAA6B,CACrD,OAAOF,EAAYE,CAAK,CAC1B,CAGA,SAASC,EAAQC,EAAuB,CACtC,OAAO,MAAM,QAAQA,CAAK,EAAQ,MAAgBA,EAAoB,MAAM,EAAI,CAAC,CACnF,CAoBA,SAAgBC,EAAYH,EAA6B,CACvD,IAAMI,EAAON,EAAYE,CAAK,EAC9B,GAAI,CAACJ,EAAYQ,CAAI,EAAG,OAAOA,EAC/B,IAAMC,kBAAS,IAAI,IACbC,EAAcL,EAAQG,CAAI,EAChCC,EAAO,IAAID,EAAME,CAAG,EACpB,IAAMC,EAAoB,CAACH,CAAI,EAC/B,IAAK,IAAII,EAASD,EAAQ,IAAI,EAAGC,IAAW,IAAA,GAAWA,EAASD,EAAQ,IAAI,EAAG,CAC7E,IAAME,EAAOJ,EAAO,IAAIG,CAAM,EAC9B,GAAIC,IAAS,IAAA,GACb,IAAK,IAAMC,KAAO,OAAO,KAAKF,CAAM,EAAG,CACrC,GAAIb,EAAce,CAAG,EAAG,SACxB,IAAMR,EAAQJ,EAAYD,EAAQW,EAAQE,CAAG,CAAC,EAC9C,GAAId,EAAYM,CAAK,EAAG,CACtB,IAAIS,EAAQN,EAAO,IAAIH,CAAK,EACxBS,IAAU,IAAA,KACZA,EAAQV,EAAQC,CAAK,EACrBG,EAAO,IAAIH,EAAOS,CAAK,EACvBJ,EAAQ,KAAKL,CAAK,GAEpB,QAAQ,IAAIO,EAAMC,EAAKC,CAAK,CAC9B,MACE,QAAQ,IAAIF,EAAMC,EAAKR,CAAK,CAEhC,CACF,CACA,OAAOI,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"reconcile.js","names":["SPECS","specOf","update","reconcile","spec","options","reconciler","identityOf","isWrappable","item","key","sameKind","a","b","applyReconcile","next","unwrapValue","root","stack","seen","enqueue","targets","source","target","frame","mergeArray","mergeObject","isReservedKey","value","had","current","writeRaw","deleteRaw","list","incoming","original","identities","byIdentity","index","identity","used","matches","position","match","found","values","previous","produce"],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key, true);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":"A,0GAuCA,MAAMA,kBAAwC,IAAI,QAUlD,SAAgBC,EAAO,EAA2C,CAChE,OAAOD,EAAM,IAAIE,CAAM,CACzB,CA6BA,SAAgBC,EAAa,EAAS,EAA2C,CAC/E,IAAMC,EAAsB,CAC1B,OACA,IAAKC,GAAS,KAAO,KACrB,MAAOA,GAAS,QAAU,EAC5B,EACMC,MAAkC,CACtC,MAAU,UAGJ,wBACN,CACF,EAEA,OADAN,EAAM,IAAIM,EAAYF,CAAI,EACnBE,CACT,CAQA,SAASC,EAAW,EAAe,EAAqD,CACtF,GAAKC,EAAYC,CAAI,EAErB,OADI,OAAOC,GAAQ,WAAmBA,EAAID,CAAI,EACvC,OAAO,OAAOA,EAAMC,CAAG,EAA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AY,EAAG,CAChE,IAAMzB,EAAOO,EAAYkB,EAASQ,EAAS,EACrCC,EAAQF,EAAQC,IAAa,GACnC,GAAIC,IAAU,GAAI,CAChBE,EAAO,KAAKpC,CAAI,EAChB,QACF,CACA,IAAMqC,EAAWX,EAASQ,GACtBnC,EAAYsC,CAAQ,GAAKtC,EAAYC,CAAI,GAAKE,EAASmC,EAAUrC,CAAI,GACnEqC,IAAarC,GAAMW,EAAQ0B,EAAUrC,CAAI,EAC7CoC,EAAO,KAAKC,CAAQ,GAEpBD,EAAO,KAAKpC,CAAI,CAEpB,CACA,GAAIL,EAAK,MACF,IAAA,IAAIkC,EAAQ,EAAGA,EAAQH,EAAS,OAAQ,GAAS,EAChDK,EAAKF,KAAW,IAAMO,EAAO,KAAKV,EAASG,EAAM,EAIzD,IAAK,IAAII,EAAW,EAAGA,EAAWG,EAAO,OAAQ,GAAY,EAC3Dd,EAASR,EAAQ,OAAOmB,CAAQ,EAAGG,EAAOH,EAAS,EAEjDT,EAAK,OAASY,EAAO,QAAQd,EAASR,EAAQ,SAAUsB,EAAO,MAAM,CAC3E,CAsBA,SAAgBE,EAAW,EAAgD,CACzE,OAAO7C,CACT,C"}
1
+ {"version":3,"file":"reconcile.js","names":["deleteRaw","isReservedKey","isWrappable","unwrapValue","writeRaw","SPECS","specOf","update","reconcile","next","options","spec","reconciler","identityOf","item","key","sameKind","a","b","applyReconcile","root","label","stack","seen","enqueue","target","source","targets","frame","mergeArray","mergeObject","value","had","current","list","incoming","original","identities","byIdentity","index","identity","used","matches","position","match","found","values","previous","produce"],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key, true);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":"A,0GAuCA,MAAMK,kBAAwC,IAAI,QAUlD,SAAgBC,EAAOC,EAA2C,CAChE,OAAOF,EAAM,IAAIE,CAAM,CACzB,CA6BA,SAAgBC,EAAaC,EAASC,EAA2C,CAC/E,IAAMC,EAAsB,CAC1BF,OACA,IAAKC,GAAS,KAAO,KACrB,MAAOA,GAAS,QAAU,EAC5B,EACME,MAAkC,CACtC,MAAU,UAGJ,wBACN,CACF,EAEA,OADAP,EAAM,IAAIO,EAAYD,CAAI,EACnBC,CACT,CAQA,SAASC,EA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AQD,GAEnCC,IAAU,KAAIH,EAAKG,GAAS,IAChCF,EAAQ,KAAKE,CAAK,CACpB,CAEA,IAAME,EAAoB,CAAC,EAC3B,IAAK,IAAIH,EAAW,EAAGA,EAAWR,EAAS,OAAQQ,GAAY,EAAG,CAChE,IAAM7B,EAAOX,EAAYgC,EAASQ,EAAS,EACrCC,EAAQF,EAAQC,IAAa,GACnC,GAAIC,IAAU,GAAI,CAChBE,EAAO,KAAKhC,CAAI,EAChB,QACF,CACA,IAAMiC,EAAWX,EAASQ,GACtB1C,EAAY6C,CAAQ,GAAK7C,EAAYY,CAAI,GAAKE,EAAS+B,EAAUjC,CAAI,GACnEiC,IAAajC,GAAMU,EAAQuB,EAAUjC,CAAI,EAC7CgC,EAAO,KAAKC,CAAQ,GAEpBD,EAAO,KAAKhC,CAAI,CAEpB,CACA,GAAIH,EAAK,MACF,IAAA,IAAI4B,EAAQ,EAAGA,EAAQH,EAAS,OAAQG,GAAS,EAChDE,EAAKF,KAAW,IAAMO,EAAO,KAAKV,EAASG,EAAM,EAIzD,IAAK,IAAII,EAAW,EAAGA,EAAWG,EAAO,OAAQH,GAAY,EAC3DvC,EAASqB,EAAQ,OAAOkB,CAAQ,EAAGG,EAAOH,EAAS,EAEjDT,EAAK,OAASY,EAAO,QAAQ1C,EAASqB,EAAQ,SAAUqB,EAAO,MAAM,CAC3E,CAsBA,SAAgBE,EAAWzC,EAAgD,CACzE,OAAOA,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-store.js","names":["setStore","isPlainObject","value","prototype","rangeKeys","from","range","to","length","by","keys","i","appendKeys","item","items","stepKeys","target","step","filter","key","isReservedKey","applyPath","path","steps","walk","depth","label","holder","previous","spec","specOf","isWrappable","applyReconcile","unwrapValue","next","mergeInto","child","root","source","createDeepStore","initial","readProxyOf","args","first","group","untrack","tx","Transaction","draftOf","result","replaceWith","reconcile","useStore","options","read","write","useSignal","wrapCell","raw"],"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":"A,qWA4BA,SAASC,EAAc,EAAkD,CACvE,GAAI,OAAOC,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMC,EAAY,OAAO,eAAeD,CAAK,EAC7C,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAEA,SAASC,EAAU,EAAoD,EAA0B,CAC/F,IAAMC,EAAOC,EAAM,MAAQ,EACrBC,EAAKD,EAAM,IAAME,EAAS,EAC1BC,EAAKH,EAAM,IAAM,EACvB,GAAI,CAAC,OAAO,SAASG,CAAE,GAAKA,IAAO,EACjC,MAAU,UACiD,oBAC3D,EACF,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAIN,GAAMI,EAAK,EAAIE,GAAKJ,EAAKI,GAAKJ,KACzCG,EAAK,KAAKC,CAAC,EACP,IAAK,OAASH,EAAS,IAFkB,GAAKC,GAIpD,OAAOC,CACT,CAGA,SAASE,EAAW,EAA8B,EAA6C,CAC7F,IAAK,IAAMC,KAAQC,EAAOJ,EAAK,KAAKG,CAAI,CAC1C,CAGA,SAASE,EAAS,EAAgB,EAAe,EAAuC,CACtF,IAAML,EAA+B,CAAC,EACtC,GAAI,MAAM,QAAQM,CAAM,EAAG,CACzB,GAAI,OAAOC,GAAS,SAAUP,EAAK,KAAKO,CAAI,OACvC,GAAI,OAAOA,GAAS,WAAY,CACnC,IAAMC,EAASD,EACf,IAAK,IAAIN,EAAI,EAAGA,EAAIK,EAAO,OAAQ,GAAK,EAAOE,EAAOF,EAAOL,GAAIA,CAAC,GAAGD,EAAK,KAAKC,CAAC,CAClF,MAAO,GAAI,MAAM,QAAQM,CAAI,EAAGL,EAAWF,EAAMO,CAAgB,OAC5D,GAAI,OAAOA,GAAS,UAAYA,EACnCL,EAAWF,EAAMN,EAAUa,EA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EACxD,MACF,CACA,GAAI,CAACzB,EAAcC,CAAK,EACtB,MAAU,UAGJ,8BACN,EAEF,IAAM4C,EAAK,IAAIC,EAAYrB,CAAK,EAChC,GAAI,CACFS,EAAUa,EAAQX,EAAMS,CAAE,EAA8B5C,EAAOwB,CAAK,CACtE,QAAU,CACR,EAAG,KAAO,EACZ,CACF,CAoDA,SAAgB0B,EAAS,EAAkB,EAAiC,CAC1E,IAAM1B,EAAQ2B,GAAS,OAAS,IAAA,GAAY,GAAK,KAAKA,EAAQ,KAAK,GAC7DhB,EAAOJ,EAAYO,CAAO,EAChC,GAAIT,EAAYM,CAAI,EAAG,OAAOE,EAAgBF,EAAMX,CAAK,EAGzD,GAAM,CAAC4B,EAAMC,GAASC,EACpBC,EAASjB,CAAO,EAChBa,GAAS,OAAS,IAAA,GAAY,IAAA,GAAY,CAAE,KAAMA,EAAQ,IAAK,CACjE,EAOA,MAAO,CAACC,EANK,GACXC,EACE,OAAOrB,GAAS,WACX,GAAsBuB,EAAUvB,EAAwCN,CAAQ,CAAC,EAClF6B,EAASvB,CAAI,CACnB,CACe,CACnB,CAGA,SAASuB,EAAS,EAAyB,CACzC,IAAMC,EAAMzB,EAAY/B,CAAK,EAC7B,OAAO6B,EAAY2B,CAAG,EAAIjB,EAAYiB,CAAG,EAAIxD,CAC/C,C"}
1
+ {"version":3,"file":"use-store.js","names":["setStore","group","untrack","useSignal","isReservedKey","isWrappable","unwrapValue","Transaction","draftOf","readProxyOf","applyReconcile","reconcile","specOf","isPlainObject","value","prototype","rangeKeys","range","length","from","to","by","keys","i","appendKeys","items","item","stepKeys","target","step","label","filter","key","applyPath","root","path","steps","walk","depth","holder","previous","spec","next","mergeInto","child","source","createDeepStore","initial","args","first","tx","result","replaceWith","useStore","options","read","write","wrapCell","raw"],"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) ? readProxy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AI,CAACjB,EAAcC,CAAK,EACtB,MAAU,UAGJ,8BACN,EAEF,IAAMoC,EAAK,IAAI3C,EAAYuB,CAAK,EAChC,GAAI,CACFa,EAAUnC,EAAQ0B,EAAMgB,CAAE,EAA8BpC,EAAOgB,CAAK,CACtE,QAAU,CACRoB,EAAG,KAAO,EACZ,CACF,CAoDA,SAAgBG,EAASN,EAAkBO,EAAiC,CAC1E,IAAMxB,EAAQwB,GAAS,OAAS,IAAA,GAAY,GAAK,KAAKA,EAAQ,KAAK,GAC7DpB,EAAO5B,EAAYyC,CAAO,EAChC,GAAI1C,EAAY6B,CAAI,EAAG,OAAOY,EAAgBZ,EAAMJ,CAAK,EAGzD,GAAM,CAACyB,EAAMC,GAASrD,EACpBsD,EAASV,CAAO,EAChBO,GAAS,OAAS,IAAA,GAAY,IAAA,GAAY,CAAE,KAAMA,EAAQ,IAAK,CACjE,EAOA,MAAO,CAACC,EANKb,GACXc,EACE,OAAOd,GAAS,WACXF,GAAsBiB,EAAUf,EAAwCF,CAAQ,CAAC,EAClFiB,EAASf,CAAI,CACnB,CACe,CACnB,CAGA,SAASe,EAAS3C,EAAyB,CACzC,IAAM4C,EAAMpD,EAAYQ,CAAK,EAC7B,OAAOT,EAAYqD,CAAG,EAAIjD,EAAYiD,CAAG,EAAI5C,CAC/C,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"suspense.js","names":["SuspenseContext","ResourceCacheContext"],"sources":["../../src/suspense.ts"],"sourcesContent":["import { type Context, createContext } from \"./context\";\n\n/**\n * Counter protocol between asynchronous sources and the nearest `<Suspense>` boundary.\n * A source calls `increment()` when it starts blocking its readers and `decrement()` exactly once\n * when it settles.\n * @since 1.0.0\n */\nexport interface SuspenseTracker {\n /**\n * Records one more pending source. The boundary shows its fallback while the count is above\n * zero; call it once per source, the first time a reader sees that source pending.\n */\n increment(): void;\n /**\n * Records that one pending source settled (with a value or an error). Call it exactly once per\n * `increment()`; when the count returns to zero the boundary shows its content again.\n */\n decrement(): void;\n /**\n * Called when a transition reads pending data in this boundary. Returns true when the boundary keeps\n * its content meanwhile: the reader then throws the suspension and keeps its previous value until\n * the boundary releases it. Returns false (or is absent) to show the fallback as usual.\n * @default undefined (the boundary never holds its content: the fallback shows as usual)\n */\n hold?(): boolean;\n}\n\n/**\n * The context through which an asynchronous source finds the nearest `<Suspense>` boundary. Each\n * boundary provides its {@link SuspenseTracker}; the value is `null` outside any boundary. Read it\n * when building a data primitive that should hold the boundary while it loads, as `useResource`\n * does.\n *\n * @example\n * import { SuspenseContext, useContext } from \"@shadow-js/core\";\n *\n * function useLoadingHold(promise: Promise<unknown>): void {\n * const tracker = useContext(SuspenseContext); // null outside any <Suspense>\n * if (tracker === null) return;\n * tracker.increment(); // the boundary shows its fallback\n * promise.finally(() => tracker.decrement());\n * }\n * @see useResource\n * @since 1.0.0\n */\nexport const SuspenseContext: Context<SuspenseTracker | null> =\n /* @__PURE__ */ createContext<SuspenseTracker | null>(null, { name: \"Suspense\" });\n\n/**\n * Bridge between resources and the server/hydration runtime. During server rendering it collects\n * in-flight fetches and replays finished ones on the next pass; during hydration it serves the\n * values the server already fetched, so the client does not fetch them again.\n * @since 1.0.0\n */\nexport interface ResourceCache {\n /**\n * Deterministic key for a resource created at this point of the render. `explicit` is the\n * resource's `key` option, or `undefined` when it has none.\n */\n key(explicit: string | undefined): string;\n /** A cached value, wrapped so that `undefined` values are representable. */\n read(key: string): { value: unknown } | undefined;\n /**\n * A fetch started; the cache stores its value under `key` when it resolves. `options.deferStream` is\n * true for a resource that holds the first streamed flush (see `ResourceOptions.deferStream`).\n */\n track(key: string, promise: Promise<unknown>, options?: ResourceTrackOptions): void;\n /**\n * The fetch an earlier pass of the same render started for `key` and that has not settled, when there\n * is one. A resource that finds it waits for that fetch instead of starting another, so a pass that\n * renders again does not fetch twice. Optional: a cache that does not keep earlier fetches omits it.\n */\n pending?(key: string): Promise<unknown> | undefined;\n}\n\n/** What {@link ResourceCache.track} is told about a fetch. @since 1.0.0 */\nexport interface ResourceTrackOptions {\n /** True when the resource was created with `deferStream: true`. */\n readonly deferStream?: boolean | undefined;\n}\n\n/**\n * The context through which `useResource` reaches the renderer's {@link ResourceCache}. Server\n * renderers and hydration provide it; the value is `null` when resources should always fetch. Only\n * a custom renderer needs to provide it.\n *\n * @example\n * import { type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\n *\n * const values = new Map<string, unknown>();\n * let created = 0;\n * const cache: ResourceCache = {\n * key: (explicit) => explicit ?? `resource-${created++}`,\n * read: (key) => (values.has(key) ? { value: values.get(key) } : undefined),\n * track: (key, promise) => void promise.then((value) => values.set(key, value)),\n * };\n * const page = <ResourceCacheContext value={cache}><p>Loading data</p></ResourceCacheContext>;\n * @see useResource\n * @since 1.0.0\n */\nexport const ResourceCacheContext: Context<ResourceCache | null> =\n /* @__PURE__ */ createContext<ResourceCache | null>(null, { name: \"ResourceCache\" });\n"],"mappings":"A,6CA8CA,MAAaA,EACK,kBAAsC,KAAM,CAAE,KAAM,UAAW,CAAC,EAsDrEC,EACK,kBAAoC,KAAM,CAAE,KAAM,eAAgB,CAAC,E"}
1
+ {"version":3,"file":"suspense.js","names":["createContext","SuspenseContext","ResourceCacheContext"],"sources":["../../src/suspense.ts"],"sourcesContent":["import { type Context, createContext } from \"./context\";\n\n/**\n * Counter protocol between asynchronous sources and the nearest `<Suspense>` boundary.\n * A source calls `increment()` when it starts blocking its readers and `decrement()` exactly once\n * when it settles.\n * @since 1.0.0\n */\nexport interface SuspenseTracker {\n /**\n * Records one more pending source. The boundary shows its fallback while the count is above\n * zero; call it once per source, the first time a reader sees that source pending.\n */\n increment(): void;\n /**\n * Records that one pending source settled (with a value or an error). Call it exactly once per\n * `increment()`; when the count returns to zero the boundary shows its content again.\n */\n decrement(): void;\n /**\n * Called when a transition reads pending data in this boundary. Returns true when the boundary keeps\n * its content meanwhile: the reader then throws the suspension and keeps its previous value until\n * the boundary releases it. Returns false (or is absent) to show the fallback as usual.\n * @default undefined (the boundary never holds its content: the fallback shows as usual)\n */\n hold?(): boolean;\n}\n\n/**\n * The context through which an asynchronous source finds the nearest `<Suspense>` boundary. Each\n * boundary provides its {@link SuspenseTracker}; the value is `null` outside any boundary. Read it\n * when building a data primitive that should hold the boundary while it loads, as `useResource`\n * does.\n *\n * @example\n * import { SuspenseContext, useContext } from \"@shadow-js/core\";\n *\n * function useLoadingHold(promise: Promise<unknown>): void {\n * const tracker = useContext(SuspenseContext); // null outside any <Suspense>\n * if (tracker === null) return;\n * tracker.increment(); // the boundary shows its fallback\n * promise.finally(() => tracker.decrement());\n * }\n * @see useResource\n * @since 1.0.0\n */\nexport const SuspenseContext: Context<SuspenseTracker | null> =\n /* @__PURE__ */ createContext<SuspenseTracker | null>(null, { name: \"Suspense\" });\n\n/**\n * Bridge between resources and the server/hydration runtime. During server rendering it collects\n * in-flight fetches and replays finished ones on the next pass; during hydration it serves the\n * values the server already fetched, so the client does not fetch them again.\n * @since 1.0.0\n */\nexport interface ResourceCache {\n /**\n * Deterministic key for a resource created at this point of the render. `explicit` is the\n * resource's `key` option, or `undefined` when it has none.\n */\n key(explicit: string | undefined): string;\n /** A cached value, wrapped so that `undefined` values are representable. */\n read(key: string): { value: unknown } | undefined;\n /**\n * A fetch started; the cache stores its value under `key` when it resolves. `options.deferStream` is\n * true for a resource that holds the first streamed flush (see `ResourceOptions.deferStream`).\n */\n track(key: string, promise: Promise<unknown>, options?: ResourceTrackOptions): void;\n /**\n * The fetch an earlier pass of the same render started for `key` and that has not settled, when there\n * is one. A resource that finds it waits for that fetch instead of starting another, so a pass that\n * renders again does not fetch twice. Optional: a cache that does not keep earlier fetches omits it.\n */\n pending?(key: string): Promise<unknown> | undefined;\n}\n\n/** What {@link ResourceCache.track} is told about a fetch. @since 1.0.0 */\nexport interface ResourceTrackOptions {\n /** True when the resource was created with `deferStream: true`. */\n readonly deferStream?: boolean | undefined;\n}\n\n/**\n * The context through which `useResource` reaches the renderer's {@link ResourceCache}. Server\n * renderers and hydration provide it; the value is `null` when resources should always fetch. Only\n * a custom renderer needs to provide it.\n *\n * @example\n * import { type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\n *\n * const values = new Map<string, unknown>();\n * let created = 0;\n * const cache: ResourceCache = {\n * key: (explicit) => explicit ?? `resource-${created++}`,\n * read: (key) => (values.has(key) ? { value: values.get(key) } : undefined),\n * track: (key, promise) => void promise.then((value) => values.set(key, value)),\n * };\n * const page = <ResourceCacheContext value={cache}><p>Loading data</p></ResourceCacheContext>;\n * @see useResource\n * @since 1.0.0\n */\nexport const ResourceCacheContext: Context<ResourceCache | null> =\n /* @__PURE__ */ createContext<ResourceCache | null>(null, { name: \"ResourceCache\" });\n"],"mappings":"A,6CA8CA,MAAaC,EACKD,kBAAsC,KAAM,CAAE,KAAM,UAAW,CAAC,EAsDrEE,EACKF,kBAAoC,KAAM,CAAE,KAAM,eAAgB,CAAC,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"transitions.js","names":["useTransition","pending","setPending","useSignal","running","untrack","applied","startTransition","fn","error","useDeferredValue","source"],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n name: options?.name,\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":"A,6IAwDA,SAAgBA,GAAwE,CACtF,GAAM,CAACC,EAASC,GAAcC,EAAU,EAAK,EACzCC,EAAU,EAkBd,MAAO,CAACH,EAjBO,GAAkC,CAC/C,GAAW,EAEXI,MAAcH,EAAW,EAAI,CAAC,EAC9B,IAAII,EACJ,GAAI,CACF,EAAUC,EAAgBC,CAAE,CAC9B,OAASC,EAAO,CAGd,KAFA,IACIL,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,EAC5CO,CACR,CACA,OAAOH,EAAQ,SAAW,CACxB,IACIF,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,CACpD,CAAC,CACH,CACsB,CACxB,CA4BA,SAAgBQ,EACd,EACA,EACa,CACG,OAAOC,CAkBzB,C"}
1
+ {"version":3,"file":"transitions.js","names":["startTransition","untrack","useSignal","useTransition","pending","setPending","running","fn","applied","error","useDeferredValue","source","options"],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n name: options?.name,\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":"A,6IAwDA,SAAgBG,GAAwE,CACtF,GAAM,CAACC,EAASC,GAAcH,EAAU,EAAK,EACzCI,EAAU,EAkBd,MAAO,CAACF,EAjBOG,GAAkC,CAC/CD,GAAW,EAEXL,MAAcI,EAAW,EAAI,CAAC,EAC9B,IAAIG,EACJ,GAAI,CACFA,EAAUR,EAAgBO,CAAE,CAC9B,OAASE,EAAO,CAGd,KAFAH,IACIA,IAAY,GAAGL,MAAcI,EAAW,EAAK,CAAC,EAC5CI,CACR,CACA,OAAOD,EAAQ,SAAW,CACxBF,IACIA,IAAY,GAAGL,MAAcI,EAAW,EAAK,CAAC,CACpD,CAAC,CACH,CACsB,CACxB,CA4BA,SAAgBK,EACdC,EACAC,EACa,CACG,OAAOD,CAkBzB,C"}