@solidjs/signals 2.0.0-beta.8 → 2.0.0-beta.9

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 (38) hide show
  1. package/dist/dev.js +172 -79
  2. package/dist/node.cjs +1091 -1043
  3. package/dist/prod.js +802 -752
  4. package/dist/types/boundaries.d.ts +35 -0
  5. package/dist/types/core/action.d.ts +34 -0
  6. package/dist/types/core/constants.d.ts +17 -0
  7. package/dist/types/core/core.d.ts +106 -7
  8. package/dist/types/core/dev.d.ts +1 -1
  9. package/dist/types/core/owner.d.ts +54 -3
  10. package/dist/types/core/scheduler.d.ts +18 -2
  11. package/dist/types/core/types.d.ts +2 -5
  12. package/dist/types/index.d.ts +1 -1
  13. package/dist/types/map.d.ts +32 -3
  14. package/dist/types/signals.d.ts +264 -11
  15. package/dist/types/store/optimistic.d.ts +38 -12
  16. package/dist/types/store/projection.d.ts +40 -14
  17. package/dist/types/store/reconcile.d.ts +22 -0
  18. package/dist/types/store/store.d.ts +64 -14
  19. package/dist/types/store/storePath.d.ts +28 -0
  20. package/dist/types/store/utils.d.ts +78 -7
  21. package/dist/types-cjs/boundaries.d.cts +35 -0
  22. package/dist/types-cjs/core/action.d.cts +34 -0
  23. package/dist/types-cjs/core/constants.d.cts +17 -0
  24. package/dist/types-cjs/core/core.d.cts +106 -7
  25. package/dist/types-cjs/core/dev.d.cts +1 -1
  26. package/dist/types-cjs/core/owner.d.cts +54 -3
  27. package/dist/types-cjs/core/scheduler.d.cts +18 -2
  28. package/dist/types-cjs/core/types.d.cts +2 -5
  29. package/dist/types-cjs/index.d.cts +1 -1
  30. package/dist/types-cjs/map.d.cts +32 -3
  31. package/dist/types-cjs/signals.d.cts +264 -11
  32. package/dist/types-cjs/store/optimistic.d.cts +38 -12
  33. package/dist/types-cjs/store/projection.d.cts +40 -14
  34. package/dist/types-cjs/store/reconcile.d.cts +22 -0
  35. package/dist/types-cjs/store/store.d.cts +64 -14
  36. package/dist/types-cjs/store/storePath.d.cts +28 -0
  37. package/dist/types-cjs/store/utils.d.cts +78 -7
  38. package/package.json +4 -3
@@ -1,13 +1,56 @@
1
1
  import type { Disposable } from "./core/index.js";
2
+ /**
3
+ * Low-level reactive-cleanup primitive. Registers a callback that runs when
4
+ * the surrounding owner is disposed.
5
+ *
6
+ * **In 2.0 user code this is rare.** The two cases where you might reach for
7
+ * it have better-shaped tools:
8
+ *
9
+ * - **Component lifecycle (mount/unmount, listeners, intervals):** use
10
+ * {@link onSettled} and **return** a cleanup function. Setup and teardown
11
+ * stay paired in one block. This replaces the 1.x `onMount` + `onCleanup`
12
+ * pairing.
13
+ * - **Cleanup tied to an effect run:** `onCleanup` does not belong in
14
+ * `createEffect`'s apply phase. If a compute phase genuinely needs per-run
15
+ * teardown, that's usually a sign the work should be a memo/projection
16
+ * instead, or moved to `onSettled` if it's lifecycle-shaped.
17
+ *
18
+ * Where `onCleanup` is the right tool is **library / custom-primitive
19
+ * internals** — coordinating disposal inside a `createRoot` body, or wiring
20
+ * cleanup to a captured owner via `runWithOwner` from a custom factory.
21
+ * Application code rarely needs to write any of those shapes directly.
22
+ *
23
+ * Must be called inside an owner. Calling outside an owner is a no-op (with a
24
+ * dev-mode warning).
25
+ *
26
+ * Cannot be used inside `createTrackedEffect` or `onSettled` — return a
27
+ * cleanup function from the callback body instead.
28
+ */
2
29
  export declare function onCleanup(fn: Disposable): Disposable;
30
+ /**
31
+ * A zero-arg getter for a reactive value. Calling it inside a tracking scope
32
+ * (memo, effect compute, JSX expression) subscribes the scope to changes.
33
+ *
34
+ * Reading outside any tracking scope simply returns the current value without
35
+ * creating a subscription.
36
+ */
3
37
  export type Accessor<T> = () => T;
4
38
  export declare function accessor<T>(node: any): Accessor<T>;
39
+ /**
40
+ * A signal setter. Accepts either a new value or an updater `(prev) => next`.
41
+ *
42
+ * If the type permits `undefined`, `setState()` (no args) clears to `undefined`.
43
+ *
44
+ * To store a function as the value itself (rather than as an updater), wrap it
45
+ * with an updater: `setHandler(() => myHandler)`.
46
+ */
5
47
  export type Setter<in out T> = {
6
48
  <U extends T>(...args: undefined extends T ? [] : [value: Exclude<U, Function> | ((prev: T) => U)]): undefined extends T ? undefined : U;
7
49
  <U extends T>(value: (prev: T) => U): U;
8
50
  <U extends T>(value: Exclude<U, Function>): U;
9
51
  <U extends T>(value: Exclude<U, Function> | ((prev: T) => U)): U;
10
52
  };
53
+ /** A `[get, set]` pair returned from `createSignal` / `createOptimistic`. */
11
54
  export type Signal<T> = [get: Accessor<T>, set: Setter<T>];
12
55
  export type ComputeFunction<Prev, Next extends Prev = Prev> = (v: Prev) => PromiseLike<Next> | AsyncIterable<Next> | Next;
13
56
  export type EffectFunction<Prev, Next extends Prev = Prev> = (v: Next, p?: Prev) => (() => void) | void;
@@ -62,7 +105,14 @@ export interface MemoOptions<T> {
62
105
  equals?: false | ((prev: T, next: T) => boolean);
63
106
  /** Callback invoked when the computed loses all subscribers */
64
107
  unobserved?: () => void;
65
- /** When true, defers the initial computation until the value is first read */
108
+ /**
109
+ * When true, defers the initial computation until the value is first read,
110
+ * **and** opts the memo into autodisposal — once it has no remaining
111
+ * subscribers it is torn down and recomputed from scratch on the next read.
112
+ * Use it for compute-on-demand values that should not retain state across
113
+ * idle periods. Non-lazy owned memos live for their owner's lifetime and
114
+ * never autodispose.
115
+ */
66
116
  lazy?: boolean;
67
117
  }
68
118
  export type NoInfer<T extends any> = [T][T extends any ? 0 : never];
@@ -83,6 +133,23 @@ export type NoInfer<T extends any> = [T][T extends any ? 0 : never];
83
133
  *
84
134
  * @returns `[state: Accessor<T>, setState: Setter<T>]`
85
135
  *
136
+ * @example
137
+ * ```ts
138
+ * const [count, setCount] = createSignal(0);
139
+ *
140
+ * count(); // 0
141
+ * setCount(1); // explicit value
142
+ * setCount(c => c + 1); // updater
143
+ * ```
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * // Writable memo: starts as `fn()`, can be locally overwritten by setter.
148
+ * const [user, setUser] = createSignal(() => fetchUser(userId()));
149
+ *
150
+ * setUser({ ...user(), name: "Alice" }); // optimistic local edit
151
+ * ```
152
+ *
86
153
  * @description https://docs.solidjs.com/reference/basic-reactivity/create-signal
87
154
  */
88
155
  export declare function createSignal<T>(): Signal<T | undefined>;
@@ -97,22 +164,91 @@ export declare function createSignal<T>(fn: ComputeFunction<T>, options?: Signal
97
164
  * @param compute a function that receives its previous value and returns a new value used to react on a computation
98
165
  * @param options `MemoOptions` -- id, name, equals, unobserved, lazy
99
166
  *
167
+ * @example
168
+ * ```ts
169
+ * const [first, setFirst] = createSignal("Ada");
170
+ * const [last, setLast] = createSignal("Lovelace");
171
+ *
172
+ * const fullName = createMemo(() => `${first()} ${last()}`);
173
+ *
174
+ * fullName(); // "Ada Lovelace"
175
+ * ```
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * // Async memo — reads surface as pending inside <Loading>
180
+ * const user = createMemo(async () => {
181
+ * const res = await fetch(`/users/${id()}`);
182
+ * return res.json();
183
+ * });
184
+ * ```
185
+ *
100
186
  * @description https://docs.solidjs.com/reference/basic-reactivity/create-memo
101
187
  */
102
188
  export declare function createMemo<T>(compute: ComputeFunction<undefined | NoInfer<T>, T>, options?: MemoOptions<T>): Accessor<T>;
103
189
  /**
104
- * Creates a reactive effect that runs after the render phase.
190
+ * Creates a reactive effect with **separate compute and effect phases**.
191
+ *
192
+ * - `compute(prev)` runs reactively — *put all reactive reads here*. The
193
+ * returned value is passed to `effect` and is also the new "previous" value
194
+ * for the next run.
195
+ * - `effect(next, prev?)` runs imperatively (untracked) after the queue
196
+ * flushes. *Put DOM writes / fetch / logging / subscriptions here.* It may
197
+ * return a cleanup function which runs before the next effect or on
198
+ * disposal.
199
+ *
200
+ * Reactive reads inside `effect` will *not* re-trigger this effect — that's
201
+ * intentional. If you need a single-phase tracked effect, use
202
+ * `createTrackedEffect` (with the tradeoffs noted there).
203
+ *
204
+ * Pass an `EffectBundle` (`{ effect, error }`) instead of a plain function to
205
+ * intercept errors thrown from the compute or effect phases.
105
206
  *
106
207
  * ```typescript
107
208
  * createEffect<T>(compute, effectFn | { effect, error }, options?: EffectOptions);
108
209
  * ```
109
210
  * @param compute a function that receives its previous value and returns a new value used to react on a computation
110
211
  * @param effectFn a function that receives the new value and is used to perform side effects (return a cleanup function), or an `EffectBundle` with `effect` and `error` handlers
111
- * @param options `EffectOptions` -- name, defer
212
+ * @param options `EffectOptions` -- name, defer, schedule
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * const [count, setCount] = createSignal(0);
217
+ *
218
+ * createEffect(
219
+ * () => count(), // compute: tracks `count`
220
+ * value => console.log(value) // effect: side effect
221
+ * );
222
+ *
223
+ * setCount(1); // logs 1 after the next flush
224
+ * ```
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * createEffect(
229
+ * () => userId(),
230
+ * id => {
231
+ * const ctrl = new AbortController();
232
+ * fetch(`/users/${id}`, { signal: ctrl.signal });
233
+ * return () => ctrl.abort(); // cleanup before next run / disposal
234
+ * }
235
+ * );
236
+ * ```
112
237
  *
113
238
  * @description https://docs.solidjs.com/reference/basic-reactivity/create-effect
114
239
  */
115
240
  export declare function createEffect<T>(compute: ComputeFunction<undefined | NoInfer<T>, T>, effectFn: EffectFunction<NoInfer<T>, T> | EffectBundle<NoInfer<T>, T>, options?: EffectOptions): void;
241
+ /**
242
+ * @deprecated `createEffect(compute)` (single argument) is no longer supported.
243
+ * Pass a separate effect function as the second argument:
244
+ * `createEffect(compute, effect)`. See [MISSING_EFFECT_FN].
245
+ *
246
+ * - For a side effect that reacts to changes, split the work:
247
+ * `createEffect(() => signal(), value => doWork(value))`.
248
+ * - For a derived value, use `createMemo(() => signal())`.
249
+ * - For a one-shot side effect at construction time, just call the function.
250
+ */
251
+ export declare function createEffect<T>(compute: ComputeFunction<undefined | NoInfer<T>, T>): never;
116
252
  /**
117
253
  * Creates a reactive computation that runs during the render phase as DOM elements
118
254
  * are created and updated but not necessarily connected.
@@ -122,7 +258,7 @@ export declare function createEffect<T>(compute: ComputeFunction<undefined | NoI
122
258
  * ```
123
259
  * @param compute a function that receives its previous value and returns a new value used to react on a computation
124
260
  * @param effectFn a function that receives the new value and is used to perform side effects
125
- * @param options `EffectOptions` -- name, defer
261
+ * @param options `EffectOptions` -- name, defer, schedule
126
262
  *
127
263
  * @description https://docs.solidjs.com/reference/secondary-primitives/create-render-effect
128
264
  */
@@ -141,6 +277,19 @@ export declare function createRenderEffect<T>(compute: ComputeFunction<undefined
141
277
  * @param compute a function that contains reactive reads to track and returns an optional cleanup function to run on disposal or before next execution
142
278
  * @param options -- name
143
279
  *
280
+ * @example
281
+ * ```ts
282
+ * createTrackedEffect(() => {
283
+ * const target = focusedNode();
284
+ * if (!target) return;
285
+ *
286
+ * const handler = () => log(target.value());
287
+ * target.on("change", handler);
288
+ *
289
+ * return () => target.off("change", handler);
290
+ * });
291
+ * ```
292
+ *
144
293
  * @description https://docs.solidjs.com/reference/secondary-primitives/create-tracked-effect
145
294
  */
146
295
  export declare function createTrackedEffect(compute: () => void | (() => void), options?: BaseEffectOptions): void;
@@ -154,11 +303,40 @@ export declare function createTrackedEffect(compute: () => void | (() => void),
154
303
  * @param effectFn a function (or `EffectBundle`) that is called when tracked function is invalidated
155
304
  * @param options `EffectOptions` -- name, defer
156
305
  *
306
+ * @example
307
+ * ```ts
308
+ * const [count, setCount] = createSignal(0);
309
+ *
310
+ * const track = createReaction(() => {
311
+ * console.log("count changed once, re-arm to listen again");
312
+ * track(() => count()); // re-arm
313
+ * });
314
+ *
315
+ * track(() => count()); // initial arm
316
+ *
317
+ * setCount(1); // logs once, reaction re-armed for next change
318
+ * ```
319
+ *
157
320
  * @description https://docs.solidjs.com/reference/secondary-primitives/create-reaction
158
321
  */
159
322
  export declare function createReaction(effectFn: EffectFunction<undefined> | EffectBundle<undefined>, options?: EffectOptions): (tracking: () => void) => void;
160
323
  /**
161
- * Returns a promise of the resolved value of a reactive expression
324
+ * Awaits a reactive expression and returns its first fully-settled value as a
325
+ * `Promise`. Pending async reads (`createMemo` returning a promise, etc.) are
326
+ * waited on; once the expression returns synchronously without `NotReadyError`
327
+ * the promise resolves with that value.
328
+ *
329
+ * Must be called *outside* a tracking scope — it doesn't subscribe, it just
330
+ * resolves the current value once.
331
+ *
332
+ * @example
333
+ * ```ts
334
+ * const user = createMemo(() => fetch(`/users/${id()}`).then(r => r.json()));
335
+ *
336
+ * // outside any reactive scope
337
+ * const initial = await resolve(() => user());
338
+ * ```
339
+ *
162
340
  * @param fn a reactive expression to resolve
163
341
  */
164
342
  export declare function resolve<T>(fn: () => T): Promise<T>;
@@ -180,21 +358,96 @@ export declare function resolve<T>(fn: () => T): Promise<T>;
180
358
  *
181
359
  * @returns `[state: Accessor<T>, setState: Setter<T>]`
182
360
  *
361
+ * @example
362
+ * ```ts
363
+ * const [todos, setTodos] = createOptimistic(initialTodos);
364
+ *
365
+ * const addTodo = action(function* (text: string) {
366
+ * const tempId = crypto.randomUUID();
367
+ * setTodos(t => [...t, { id: tempId, text, pending: true }]); // optimistic
368
+ * const saved = yield api.createTodo(text);
369
+ * setTodos(t => t.map(x => (x.id === tempId ? saved : x))); // reconcile
370
+ * });
371
+ * ```
372
+ *
183
373
  * @description https://docs.solidjs.com/reference/basic-reactivity/create-optimistic-signal
184
374
  */
185
375
  export declare function createOptimistic<T>(): Signal<T | undefined>;
186
376
  export declare function createOptimistic<T>(value: Exclude<T, Function>, options?: SignalOptions<T>): Signal<T>;
187
377
  export declare function createOptimistic<T>(fn: ComputeFunction<T>, options?: SignalOptions<T> & MemoOptions<T>): Signal<T>;
188
378
  /**
189
- * Runs a callback after the current flush cycle completes.
379
+ * Schedules `callback` to run **once** after the reactive graph has fully
380
+ * settled — i.e. once every pending async read inside the current owner has
381
+ * resolved and the queue has flushed. Each call registers a single fire; it
382
+ * does not create an ongoing subscription.
190
383
  *
191
- * When called within a reactive context (owner), uses a tracked effect with untracked
192
- * reads - this means normal signal reads won't create subscriptions, but uninitialized
193
- * async values will throw NotReadyError, causing the callback to re-run when they settle.
384
+ * The canonical lifecycle primitive in 2.0. Three main usages:
194
385
  *
195
- * When called without an owner, runs once and immediately calls any returned cleanup.
386
+ * - **Component-level setup-and-teardown** *(the most common shape)*: run
387
+ * setup after the component's first stable render and **return a cleanup
388
+ * function** to dispose it on owner disposal. This is the replacement for
389
+ * the 1.x `onMount` + `onCleanup` pairing — setup and teardown live in one
390
+ * block, and `onCleanup` is no longer the right tool for component
391
+ * bodies. (`onMount` no longer exists in 2.0.)
392
+ * - **Post-settle "ready" hook:** run once after a component's first stable
393
+ * render — analytics ping, focus, scroll-into-view, etc. No cleanup needed.
394
+ * - **Inside an event handler:** schedule work to run after the action /
395
+ * transition triggered by the event has completed.
396
+ *
397
+ * Reactive reads inside the callback are *not* tracked — to react to
398
+ * subsequent settles, register a new `onSettled` each time.
399
+ *
400
+ * `onCleanup` is **not** allowed inside the callback — return a cleanup
401
+ * function instead. The returned cleanup runs on owner disposal.
402
+ *
403
+ * @example
404
+ * ```tsx
405
+ * // Component-level setup + teardown — replaces onMount + onCleanup.
406
+ * // Subscribe to an external source on mount, unsubscribe on dispose.
407
+ * function useViewportWidth() {
408
+ * const [width, setWidth] = createSignal(window.innerWidth);
409
+ * onSettled(() => {
410
+ * const onResize = () => setWidth(window.innerWidth);
411
+ * window.addEventListener("resize", onResize);
412
+ * return () => window.removeEventListener("resize", onResize);
413
+ * });
414
+ * return width;
415
+ * }
416
+ * ```
417
+ *
418
+ * @example
419
+ * ```tsx
420
+ * // Post-settle "ready" hook — no cleanup needed.
421
+ * function Dashboard() {
422
+ * const data = createMemo(async () => fetchData());
423
+ *
424
+ * onSettled(() => {
425
+ * analytics.track("dashboard.ready");
426
+ * });
427
+ *
428
+ * return <Loading fallback={<Spinner />}><pre>{data()}</pre></Loading>;
429
+ * }
430
+ * ```
431
+ *
432
+ * @example
433
+ * ```tsx
434
+ * // Event-handler — runs after the action settles.
435
+ * function SaveButton() {
436
+ * const save = action(function* () {
437
+ * yield api.save();
438
+ * });
439
+ *
440
+ * const handleClick = () => {
441
+ * save();
442
+ * onSettled(() => toast("Saved!"));
443
+ * };
444
+ *
445
+ * return <button onClick={handleClick}>Save</button>;
446
+ * }
447
+ * ```
196
448
  *
197
- * @param callback Function to run, may return a cleanup function
449
+ * @param callback Function to run; may return a cleanup function that fires
450
+ * on owner disposal
198
451
  */
199
452
  export declare function onSettled(callback: () => void | (() => void)): void;
200
453
  export {};
@@ -1,19 +1,45 @@
1
- import { $REFRESH } from "../core/index.js";
1
+ import { type Refreshable } from "../core/index.js";
2
2
  import { type NoFn, type ProjectionOptions, type Store, type StoreSetter } from "./store.js";
3
3
  /**
4
- * Creates an optimistic store that can be used to optimistically update a value
5
- * and then revert it back to the previous value at end of transition.
4
+ * The store equivalent of `createOptimistic`. Writes inside an `action`
5
+ * transition are tentative they show up immediately but auto-revert (or
6
+ * reconcile to the action's resolved value) once the transition finishes.
6
7
  *
7
- * When called with a plain value, creates an optimistic store.
8
- * When called with a function, creates a derived optimistic store with `ProjectionOptions` (name, key).
8
+ * Use this for optimistic UI on collection-shaped data. For single-value
9
+ * optimistic state, prefer `createOptimistic`.
9
10
  *
10
- * @param fn a function that receives the current store and can be used to mutate it directly inside a transition
11
- * @param store The plain store value, or the backing seed when using the derived-store form.
12
- * @param options Optional projection options for reconciliation.
11
+ * - Plain form: `createOptimisticStore(initialValue)`.
12
+ * - Derived form: `createOptimisticStore(fn, seed, options?)` a projection
13
+ * store whose authoritative value is recomputed by `fn` and whose
14
+ * optimistic overlay reverts after each transition.
13
15
  *
14
- * @returns A tuple containing a store accessor and a setter function to apply changes.
16
+ * `options.key` defaults to `"id"`; specify it only when your data uses a
17
+ * different identity field (e.g. `{ key: "uuid" }` or `{ key: t => t.slug }`).
18
+ * Restating the default just adds noise.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const [todos, setTodos] = createOptimisticStore<Todo[]>([]);
23
+ *
24
+ * // Mutation: optimistic add, then in-place reconcile to the saved row.
25
+ * const addTodo = action(function* (text: string) {
26
+ * const tempId = crypto.randomUUID();
27
+ * setTodos(t => { t.push({ id: tempId, text, pending: true }); });
28
+ * const saved = yield api.createTodo(text);
29
+ * setTodos(t => {
30
+ * const i = t.findIndex(x => x.id === tempId);
31
+ * if (i >= 0) t[i] = saved;
32
+ * });
33
+ * });
34
+ *
35
+ * // Return form: filter is the natural shape for removal.
36
+ * const removeTodo = action(function* (id: string) {
37
+ * setTodos(t => t.filter(x => x.id !== id));
38
+ * yield api.removeTodo(id);
39
+ * });
40
+ * ```
41
+ *
42
+ * @returns `[store: Store<T>, setStore: StoreSetter<T>]`
15
43
  */
16
44
  export declare function createOptimisticStore<T extends object = {}>(store: NoFn<T> | Store<NoFn<T>>): [get: Store<T>, set: StoreSetter<T>];
17
- export declare function createOptimisticStore<T extends object = {}>(fn: (store: T) => void | T | Promise<void | T> | AsyncIterable<void | T>, store: Partial<T> | Store<NoFn<T>>, options?: ProjectionOptions): [get: Store<T> & {
18
- [$REFRESH]: any;
19
- }, set: StoreSetter<T>];
45
+ export declare function createOptimisticStore<T extends object = {}>(fn: (store: T) => void | T | Promise<void | T> | AsyncIterable<void | T>, store: Partial<T> | Store<NoFn<T>>, options?: ProjectionOptions): [get: Refreshable<Store<T>>, set: StoreSetter<T>];
@@ -1,27 +1,53 @@
1
- import { $REFRESH, type Computed } from "../core/index.js";
1
+ import { type Computed, type Refreshable } from "../core/index.js";
2
2
  import { type ProjectionOptions, type Store } from "./store.js";
3
3
  export declare function createProjectionInternal<T extends object = {}>(fn: (draft: T) => void | T | Promise<void | T> | AsyncIterable<void | T>, seed: Partial<T>, options?: ProjectionOptions): {
4
- store: Store<T> & {
5
- [$REFRESH]: any;
6
- };
4
+ store: Refreshable<Store<T>>;
7
5
  node: Computed<void | T>;
8
6
  };
9
7
  /**
10
- * Creates a mutable derived store (projection). The derive function receives a mutable
11
- * draft and can mutate it directly or return a new value for reconciliation.
8
+ * Creates a derived (projected) store. Like `createMemo` but for stores: the
9
+ * derive function receives a mutable draft and either mutates it in place
10
+ * (canonical) or returns a new value. Either way the result is reconciled
11
+ * against the previous draft by `options.key` (default `"id"`), so surviving
12
+ * items keep their proxy identity — only added/removed items are
13
+ * created/disposed.
12
14
  *
13
- * ```typescript
14
- * const store = createProjection<T>(fn, seed, options?: ProjectionOptions);
15
+ * Returns the projected store directly (no setter — reads only).
16
+ *
17
+ * Use this when you want the structural-sharing / per-property tracking
18
+ * behaviour of a store on top of a derived computation. For simple read-only
19
+ * derivations, `createMemo` is lighter.
20
+ *
21
+ * @param fn receives the current draft; mutate it in place or return new
22
+ * data. Return is convenient for filter/derive shapes where mutation is
23
+ * awkward.
24
+ * @param seed the backing store value to wrap and reconcile into
25
+ * @param options `ProjectionOptions` — `name`, `key`. `key` defaults to
26
+ * `"id"`; specify it only when your data uses a different identity field
27
+ * (e.g. `{ key: "uuid" }` or `{ key: u => u.slug }`).
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * // Mutation form — update individual fields on the draft.
32
+ * const summary = createProjection<{ total: number; active: number }>(
33
+ * draft => {
34
+ * draft.total = users().length;
35
+ * draft.active = users().filter(u => u.active).length;
36
+ * },
37
+ * { total: 0, active: 0 }
38
+ * );
39
+ *
40
+ * // Return form — produce a derived collection. Reconciled by `id` so each
41
+ * // surviving user keeps the same store identity across recomputes.
42
+ * const activeUsers = createProjection<User[]>(
43
+ * () => allUsers().filter(u => u.active),
44
+ * []
45
+ * );
15
46
  * ```
16
- * @param fn a function that receives the current draft and mutates it or returns new data
17
- * @param seed the backing store host value to wrap and reconcile into
18
- * @param options `ProjectionOptions` -- name, key
19
47
  *
20
48
  * @see {@link https://github.com/solidjs/x-reactivity#createprojection}
21
49
  */
22
- export declare function createProjection<T extends object = {}>(fn: (draft: T) => void | T | Promise<void | T> | AsyncIterable<void | T>, seed: Partial<T>, options?: ProjectionOptions): Store<T> & {
23
- [$REFRESH]: any;
24
- };
50
+ export declare function createProjection<T extends object = {}>(fn: (draft: T) => void | T | Promise<void | T> | AsyncIterable<void | T>, seed: Partial<T>, options?: ProjectionOptions): Refreshable<Store<T>>;
25
51
  /**
26
52
  * Shared projection computed body used by both `createProjection` and the derived
27
53
  * form of `createOptimisticStore`. Encapsulates the write-trap draft, `storeSetter`
@@ -1 +1,23 @@
1
+ /**
2
+ * Returns a draft-mutating function that smart-merges `value` into a store,
3
+ * preserving the identity of items whose `key` field matches between old and
4
+ * new states. Useful when applying server payloads or full-replacement data
5
+ * onto an existing store without losing fine-grained reactivity.
6
+ *
7
+ * Items with the same key are updated in place (only changed properties
8
+ * trigger updates). Items added or removed update the corresponding signals.
9
+ *
10
+ * @param value the next state to merge in
11
+ * @param key property name (string) or extractor function for stable identity
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const [todos, setTodos] = createStore<Todo[]>([]);
16
+ *
17
+ * async function refresh() {
18
+ * const fresh = await api.getTodos();
19
+ * setTodos(reconcile(fresh, "id")); // diff-merge by `id`
20
+ * }
21
+ * ```
22
+ */
1
23
  export declare function reconcile<T extends U, U>(value: T, key: string | ((item: NonNullable<any>) => any)): (state: U) => void;
@@ -1,5 +1,21 @@
1
- import { $REFRESH, STORE_SNAPSHOT_PROPS, type Computed, type Signal } from "../core/index.js";
1
+ import { STORE_SNAPSHOT_PROPS, type Computed, type Refreshable, type Signal } from "../core/index.js";
2
+ /** A read-only view of a store's value as seen by consumers. Mutate it via the paired `StoreSetter`. */
2
3
  export type Store<T> = Readonly<T>;
4
+ /**
5
+ * A store setter. The callback receives a writable **draft** of the store.
6
+ *
7
+ * - **Mutate in place (canonical):** `s.foo = 1`, `s.list.push(x)`,
8
+ * `s.list.splice(i, 1)`. This is the default form for most updates.
9
+ * - **Return a new value:** for shapes where mutation is awkward, most
10
+ * commonly removing items (`s => s.list.filter(...)`). Arrays are replaced
11
+ * by index (length adjusted); objects are shallow-diffed at the top level
12
+ * (keys present in the returned value are written, missing keys deleted).
13
+ *
14
+ * The setter does **not** perform keyed reconciliation. If you need surviving
15
+ * items to keep their store identity across full-array replacement, use the
16
+ * projection form — `createStore(fn, seed, { key })` or `createProjection` —
17
+ * whose derive function reconciles its return by `options.key`.
18
+ */
3
19
  export type StoreSetter<T> = (fn: (state: T) => T | void) => void;
4
20
  /** Base options for store primitives. */
5
21
  export interface StoreOptions {
@@ -45,24 +61,58 @@ export declare function getPropertyDescriptor(source: Record<PropertyKey, any>,
45
61
  export declare const storeTraps: ProxyHandler<StoreNode>;
46
62
  export declare function storeSetter<T extends object>(store: Store<T>, fn: (draft: T) => T | void): void;
47
63
  /**
48
- * Creates a deeply reactive store with proxy-based tracking.
64
+ * Creates a deeply-reactive store backed by a Proxy. Reads track each property
65
+ * accessed; only the parts that change trigger updates.
66
+ *
67
+ * Store properties hold **plain values**, not accessors. The proxy already
68
+ * tracks reads per-property — wrapping a value in `() => state.foo` produces
69
+ * a getter that *won't* track when called, which looks like a reactivity bug
70
+ * but is just a category error. If you have a signal-shaped piece of state,
71
+ * make it a property of the store (`{ foo: 1 }`) rather than nesting an
72
+ * accessor inside (`{ foo: () => signal() }`).
49
73
  *
50
- * When called with a plain value, wraps it in a reactive proxy.
51
- * When called with a function, creates a derived projection store with `ProjectionOptions` (name, key).
74
+ * The setter takes a **draft-mutating** function mutate the draft in place
75
+ * (canonical). The callback may also return a new value: arrays are replaced
76
+ * by index (length adjusted), objects are shallow-diffed at the top level
77
+ * (keys present in the returned value are written, missing keys deleted). Use
78
+ * the return form for shapes where mutation is awkward — most commonly
79
+ * removing items via `filter`. The setter does **not** do keyed reconciliation;
80
+ * for that, use the derived/projection form (or `createProjection`).
81
+ *
82
+ * - Plain form: `createStore(initialValue)` — wraps a value in a reactive
83
+ * proxy.
84
+ * - Derived form: `createStore(fn, seed, options?)` — a *projection store*
85
+ * whose contents are computed by `fn(draft)`. `fn` may be sync, async, or
86
+ * an `AsyncIterable`; the projection's result reconciles against the
87
+ * existing store by `options.key` (default `"id"`) for stable identity.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * const [state, setState] = createStore({
92
+ * user: { name: "Ada", age: 36 },
93
+ * todos: [] as { id: string; text: string; done: boolean }[]
94
+ * });
95
+ *
96
+ * // Canonical: mutate the draft in place.
97
+ * setState(s => { s.user.age = 37; });
98
+ * setState(s => { s.todos.push({ id: "1", text: "x", done: false }); });
99
+ *
100
+ * // Return form: reach for it when mutation is awkward.
101
+ * setState(s => s.todos.filter(t => !t.done)); // remove items
102
+ * setState(s => ({ ...s, user: { name: "Grace", age: 85 } })); // shallow replace
103
+ * ```
52
104
  *
53
- * ```typescript
54
- * // Plain store
55
- * const [store, setStore] = createStore<T>(initialValue);
56
- * // Derived store (projection)
57
- * const [store, setStore] = createStore<T>(fn, seed, options?: ProjectionOptions);
105
+ * @example
106
+ * ```ts
107
+ * // Derived store auto-fetches & reconciles by `id`.
108
+ * const [users] = createStore(
109
+ * async () => fetch("/users").then(r => r.json()),
110
+ * [] as User[]
111
+ * );
58
112
  * ```
59
- * @param store initial value to wrap in a reactive proxy, or a derive function
60
- * @param options `ProjectionOptions` -- name, key (only for derived stores)
61
113
  *
62
114
  * @returns `[store: Store<T>, setStore: StoreSetter<T>]`
63
115
  */
64
116
  export declare function createStore<T extends object = {}>(store: NoFn<T> | Store<NoFn<T>>): [get: Store<T>, set: StoreSetter<T>];
65
- export declare function createStore<T extends object = {}>(fn: (store: T) => void | T | Promise<void | T> | AsyncIterable<void | T>, store: Partial<T> | Store<NoFn<T>>, options?: ProjectionOptions): [get: Store<T> & {
66
- [$REFRESH]: any;
67
- }, set: StoreSetter<T>];
117
+ export declare function createStore<T extends object = {}>(fn: (store: T) => void | T | Promise<void | T> | AsyncIterable<void | T>, store: Partial<T> | Store<NoFn<T>>, options?: ProjectionOptions): [get: Refreshable<Store<T>>, set: StoreSetter<T>];
68
118
  export {};
@@ -26,5 +26,33 @@ export interface storePath {
26
26
  <T, K1 extends KeyOf<W<T>>>(k1: Part<W<T>, K1>, setter: PathSetter<W<T>[K1]>): (state: T) => void;
27
27
  <T>(setter: PathSetter<T>): (state: T) => void;
28
28
  }
29
+ /**
30
+ * Path-based setter helper for `createStore`. Call `storePath(...path, value)`
31
+ * to produce a draft-mutating function suitable for passing to `setStore`.
32
+ *
33
+ * The canonical setter form in Solid 2.0 is the draft-mutating callback
34
+ * (`setStore(s => { s.user.name = "Ada"; })`). `storePath` is a backwards-
35
+ * compatibility helper for users porting from Solid 1.x's
36
+ * `setStore("user", "name", "Ada")` style — it's optional and you can mix the
37
+ * two styles freely.
38
+ *
39
+ * Path parts can be:
40
+ * - a single key — `"user"`, `0`
41
+ * - an array of keys — `[0, 1, 2]`
42
+ * - a range over an array — `{ from?, to?, by? }`
43
+ * - a filter `(item, index) => boolean` for arrays
44
+ *
45
+ * The final argument is the new value or an updater `(prev) => next`. Use
46
+ * `storePath.DELETE` to remove a property.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * const [state, setState] = createStore({ user: { name: "Ada" }, todos: [] });
51
+ *
52
+ * setState(storePath("user", "name", "Grace"));
53
+ * setState(storePath("todos", t => !t.done, "done", true)); // mark all undone as done
54
+ * setState(storePath("user", "nickname", storePath.DELETE));
55
+ * ```
56
+ */
29
57
  export declare const storePath: storePath;
30
58
  export {};