@solidjs/signals 2.0.0-rc.0 → 2.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +1 -1
  2. package/dist/dev.js +4287 -2803
  3. package/dist/node.cjs +4563 -3756
  4. package/dist/prod/affects.js +16 -16
  5. package/dist/prod/boundaries.js +90 -90
  6. package/dist/prod/core/action.js +3 -3
  7. package/dist/prod/core/async.js +234 -178
  8. package/dist/prod/core/constants.js +39 -1
  9. package/dist/prod/core/core.js +362 -243
  10. package/dist/prod/core/effect.js +56 -56
  11. package/dist/prod/core/external.js +4 -4
  12. package/dist/prod/core/graph.js +65 -54
  13. package/dist/prod/core/heap.js +47 -39
  14. package/dist/prod/core/invariants.js +3 -2
  15. package/dist/prod/core/lanes.js +41 -34
  16. package/dist/prod/core/optimistic.js +78 -58
  17. package/dist/prod/core/owner.js +101 -100
  18. package/dist/prod/core/scheduler.js +249 -192
  19. package/dist/prod/core/verdict.js +185 -78
  20. package/dist/prod/index.js +7 -7
  21. package/dist/prod/map.js +108 -106
  22. package/dist/prod/signals.js +20 -1
  23. package/dist/prod/store/index.js +36 -0
  24. package/dist/prod/store/next/optimistic.js +385 -0
  25. package/dist/prod/store/next/projection.js +172 -0
  26. package/dist/prod/store/next/reconcile.js +331 -0
  27. package/dist/prod/store/next/store.js +1499 -0
  28. package/dist/prod/store/next/target.js +20 -0
  29. package/dist/prod/store/store.js +126 -882
  30. package/dist/prod/store/utils.js +59 -186
  31. package/dist/types/core/attribution-hooks.d.ts +52 -0
  32. package/dist/types/core/attribution.d.ts +186 -0
  33. package/dist/types/core/constants.d.ts +26 -0
  34. package/dist/types/core/core.d.ts +16 -1
  35. package/dist/types/core/dev.d.ts +20 -3
  36. package/dist/types/core/graph.d.ts +1 -0
  37. package/dist/types/core/lanes.d.ts +4 -16
  38. package/dist/types/core/scheduler.d.ts +12 -2
  39. package/dist/types/core/types.d.ts +85 -41
  40. package/dist/types/signals.d.ts +19 -0
  41. package/dist/types/store/index.d.ts +15 -5
  42. package/dist/types/store/next/optimistic.d.ts +20 -0
  43. package/dist/types/store/next/projection.d.ts +8 -0
  44. package/dist/types/store/next/reconcile.d.ts +3 -0
  45. package/dist/types/store/next/store.d.ts +77 -0
  46. package/dist/types/store/next/target.d.ts +117 -0
  47. package/dist/types/store/store.d.ts +26 -101
  48. package/dist/types/store/utils.d.ts +0 -40
  49. package/dist/types-cjs/core/attribution-hooks.d.cts +52 -0
  50. package/dist/types-cjs/core/attribution.d.cts +186 -0
  51. package/dist/types-cjs/core/constants.d.cts +26 -0
  52. package/dist/types-cjs/core/core.d.cts +16 -1
  53. package/dist/types-cjs/core/dev.d.cts +20 -3
  54. package/dist/types-cjs/core/graph.d.cts +1 -0
  55. package/dist/types-cjs/core/lanes.d.cts +4 -16
  56. package/dist/types-cjs/core/scheduler.d.cts +12 -2
  57. package/dist/types-cjs/core/types.d.cts +85 -41
  58. package/dist/types-cjs/signals.d.cts +19 -0
  59. package/dist/types-cjs/store/index.d.cts +15 -5
  60. package/dist/types-cjs/store/next/optimistic.d.cts +20 -0
  61. package/dist/types-cjs/store/next/projection.d.cts +8 -0
  62. package/dist/types-cjs/store/next/reconcile.d.cts +3 -0
  63. package/dist/types-cjs/store/next/store.d.cts +77 -0
  64. package/dist/types-cjs/store/next/target.d.cts +117 -0
  65. package/dist/types-cjs/store/store.d.cts +26 -101
  66. package/dist/types-cjs/store/utils.d.cts +0 -40
  67. package/package.json +2 -1
  68. package/dist/prod/store/optimistic.js +0 -217
  69. package/dist/prod/store/projection.js +0 -231
  70. package/dist/prod/store/reconcile.js +0 -707
@@ -1,5 +1,5 @@
1
- import { STORE_SNAPSHOT_PROPS, type Computed, type Refreshable, type Signal } from "../core/index.cjs";
2
- import { type Transition } from "../core/scheduler.cjs";
1
+ import { type Signal } from "../core/index.cjs";
2
+ import type { Refreshable } from "../core/index.cjs";
3
3
  /** A read-only view of a store's value as seen by consumers. Mutate it via the paired `StoreSetter`. */
4
4
  export type Store<T> = Readonly<T>;
5
5
  /**
@@ -58,21 +58,14 @@ type DataNodes = Record<PropertyKey, DataNode>;
58
58
  * @internal
59
59
  */
60
60
  export declare const $TRACK: unique symbol, $TARGET: unique symbol, $PROXY: unique symbol, $DELETED: unique symbol, $AFFECTS: unique symbol;
61
- export declare const STORE_VALUE = "v", STORE_OVERRIDE = "o", STORE_OPTIMISTIC_OVERRIDE = "x", STORE_NODE = "n", STORE_HAS = "h", STORE_CUSTOM_PROTO = "c", STORE_WRAP = "w", STORE_LOOKUP = "l", STORE_FIREWALL = "f", STORE_OPTIMISTIC = "p", STORE_OPTIMISTIC_OWNERS = "t", STORE_PARENT = "u", STORE_DESC = "d", STORE_SHALLOW = "s";
61
+ export declare const STORE_VALUE = "v", STORE_NODE = "n", STORE_HAS = "h", STORE_PARENT = "u", STORE_DESC = "d", STORE_SHALLOW = "s";
62
+ /** Structural view of a store target as shared machinery sees it (the real
63
+ * shape is `StoreNextTarget` in ./next/target.ts). */
62
64
  export type StoreNode = {
63
65
  [$PROXY]: any;
64
66
  [STORE_VALUE]: Record<PropertyKey, any>;
65
- [STORE_OVERRIDE]?: Record<PropertyKey, any>;
66
- [STORE_OPTIMISTIC_OVERRIDE]?: Record<PropertyKey, any>;
67
- [STORE_OPTIMISTIC_OWNERS]?: Record<PropertyKey, Transition | null>;
68
67
  [STORE_NODE]?: DataNodes;
69
68
  [STORE_HAS]?: DataNodes;
70
- [STORE_CUSTOM_PROTO]?: boolean;
71
- [STORE_WRAP]?: (value: any, target?: StoreNode) => any;
72
- [STORE_LOOKUP]?: WeakMap<any, any>;
73
- [STORE_FIREWALL]?: Computed<any>;
74
- [STORE_OPTIMISTIC]?: boolean;
75
- [STORE_SNAPSHOT_PROPS]?: Record<PropertyKey, any>;
76
69
  [STORE_PARENT]?: StoreNode;
77
70
  [STORE_SHALLOW]?: boolean;
78
71
  [STORE_DESC]?: boolean;
@@ -82,10 +75,6 @@ export declare namespace SolidStore {
82
75
  }
83
76
  }
84
77
  export type NotWrappable = string | number | bigint | symbol | boolean | Function | null | undefined | SolidStore.Unwrappable[keyof SolidStore.Unwrappable];
85
- export declare function createStoreProxy<T extends object>(value: T, traps?: ProxyHandler<StoreNode>, extend?: (target: StoreNode) => void): any;
86
- export declare const storeLookup: WeakMap<WeakKey, any>;
87
- export declare const symbolKeyedRecords: WeakSet<object>;
88
- export declare function lookupTarget(value: any, lookup?: WeakMap<any, any>): StoreNode | undefined;
89
78
  /**
90
79
  * Marks a value as raw: no store will ever wrap it — every store presents it
91
80
  * as-is, tracked by reference at whatever slot holds it and updated by
@@ -96,25 +85,33 @@ export declare function lookupTarget(value: any, lookup?: WeakMap<any, any>): St
96
85
  export declare let rawValuesUsed: boolean;
97
86
  export declare function isRawValue(value: any): boolean;
98
87
  export declare function markRaw<T>(value: T): T;
88
+ export declare function markRawOne(v: any): void;
99
89
  export declare function markRawIngest(container: any): void;
100
- export declare function wrap<T extends Record<PropertyKey, any>>(value: T, target?: StoreNode): T;
101
- export declare function wrapShallow<T extends Record<PropertyKey, any>>(value: T): T;
102
90
  export declare function isWrappable<T>(obj: T | NotWrappable): obj is T;
103
91
  export declare function setWriteOverride(value: boolean): void;
92
+ export declare function getWriteOverride(): boolean;
104
93
  export declare function ownEnumerableKeys(o: object): (string | symbol)[];
105
94
  /**
106
- * Single chokepoint for the store's layered value resolution: returns the
107
- * override layer (optimistic first, then regular) that shadows `property`, or
108
- * `undefined` when the base `STORE_VALUE` is authoritative. Every trap must
109
- * resolve through this hand-inlining the layer order is how the optimistic
110
- * layer gets missed (#2850).
95
+ * Scope inheritance for late-created nodes: every live mark whose identity
96
+ * scope contains the owning record's raw — and, for keyed marks, whose key
97
+ * is this property gets counted on the new node. Inherited marks live
98
+ * exactly as long as the scope's carrier the release hook below drops
99
+ * them with the entry.
111
100
  */
112
- export declare function getOverlayLayer(target: StoreNode, property: PropertyKey): Record<PropertyKey, any> | undefined;
113
- /**
114
- * The value a store leaf's backing signal currently shows to readers: active
115
- * override, else held pending value, else committed value.
116
- */
117
- export declare function visibleNodeValue(node: DataNode): any;
101
+ export declare function inheritAffectsMarks(node: DataNode, raw: object, property: PropertyKey): void;
102
+ /** Next-store node factory for affects carriers/slots: injected by the
103
+ * rewrite module (next targets alias the legacy field names, so everything
104
+ * here EXCEPT node creation works on them structurally). */
105
+ export declare let nextAffectsNodeResolver: ((target: any, key: PropertyKey) => DataNode) | null;
106
+ export declare function setNextAffectsNodeResolver(fn: (target: any, key: PropertyKey) => DataNode): void;
107
+ /** Next-store optimistic view for the declaration walk (optimistic rows
108
+ * pushed before the declaration are in motion too — legacy reads its write
109
+ * overlays; next composes armed-node overrides). */
110
+ export declare let nextOptimisticViewResolver: ((target: any, raw: any) => any) | null;
111
+ export declare function setNextOptimisticViewResolver(fn: (target: any, raw: any) => any): void;
112
+ /** @internal birth inheritance for nodes created inside a live mark window —
113
+ * exported for the rewrite's node factories. */
114
+ export declare function affectsScopesLive(): boolean;
118
115
  /**
119
116
  * Witness live mark coverage of a record into the active isPending() probe.
120
117
  * Tracked reads don't need this — they go through real signal nodes, which
@@ -138,76 +135,4 @@ export declare function witnessAffectsMark(target: StoreNode, property?: Propert
138
135
  * @internal
139
136
  */
140
137
  export declare function getStoreAffectsNodes(target: StoreNode, key?: PropertyKey): DataNode[];
141
- export declare function trackSelf(target: StoreNode, symbol?: symbol): void;
142
- export declare function notifySelf(target: StoreNode): void;
143
- /**
144
- * The write overlay a walk must read through: optimistic writes shadow
145
- * regular pending writes, the same resolution order as every proxy trap and
146
- * `reconcile` (#2850). Merging allocates only in the rare both-present case
147
- * (a derived optimistic store with an in-flight projection commit).
148
- */
149
- export declare function mergedOverlay(target: StoreNode): Record<PropertyKey, any> | undefined;
150
- export declare function getKeys(source: Record<PropertyKey, any>, override: Record<PropertyKey, any> | undefined, enumerable?: boolean): PropertyKey[];
151
- export declare function getStoreKeys(source: Record<PropertyKey, any>, override: Record<PropertyKey, any> | undefined): PropertyKey[];
152
- export declare function getStoreSymbols(source: Record<PropertyKey, any>, override: Record<PropertyKey, any> | undefined): symbol[];
153
- export declare function getPropertyDescriptor(source: Record<PropertyKey, any>, override: Record<PropertyKey, any> | undefined, property: PropertyKey): PropertyDescriptor | undefined;
154
- export declare const storeTraps: ProxyHandler<StoreNode>;
155
- export declare function storeSetter<T extends object>(store: Store<T>, fn: (draft: T) => T | void): void;
156
- /**
157
- * Creates a deeply-reactive store backed by a Proxy. Reads track each property
158
- * accessed; only the parts that change trigger updates.
159
- *
160
- * Store properties hold **plain values**, not accessors. The proxy already
161
- * tracks reads per-property — wrapping a value in `() => state.foo` produces
162
- * a getter that *won't* track when called, which looks like a reactivity bug
163
- * but is just a category error. If you have a signal-shaped piece of state,
164
- * make it a property of the store (`{ foo: 1 }`) rather than nesting an
165
- * accessor inside (`{ foo: () => signal() }`).
166
- *
167
- * The setter takes a **draft-mutating** function — mutate the draft in place
168
- * (canonical). The callback may also return a new value: arrays are replaced
169
- * by index (length adjusted), objects are shallow-diffed at the top level
170
- * (keys present in the returned value are written, missing keys deleted). Use
171
- * the return form for shapes where mutation is awkward — most commonly
172
- * removing items via `filter`. The setter does **not** do keyed reconciliation;
173
- * for that, use the derived/projection form (or `createProjection`).
174
- *
175
- * - Plain form: `createStore(initialValue)` — wraps a value in a reactive
176
- * proxy.
177
- * - Derived form: `createStore(fn, seed, options?)` — a *projection store*
178
- * whose contents are computed by `fn(draft)`. `fn` may be sync, async, or
179
- * an `AsyncIterable`; the projection's result reconciles against the
180
- * existing store by `options.key` (default `"id"`) for stable identity.
181
- *
182
- * @example
183
- * ```ts
184
- * const [state, setState] = createStore({
185
- * user: { name: "Ada", age: 36 },
186
- * todos: [] as { id: string; text: string; done: boolean }[]
187
- * });
188
- *
189
- * // Canonical: mutate the draft in place.
190
- * setState(s => { s.user.age = 37; });
191
- * setState(s => { s.todos.push({ id: "1", text: "x", done: false }); });
192
- *
193
- * // Return form: reach for it when mutation is awkward.
194
- * setState(s => s.todos.filter(t => !t.done)); // remove items
195
- * setState(s => ({ ...s, user: { name: "Grace", age: 85 } })); // shallow replace
196
- * ```
197
- *
198
- * @example
199
- * ```ts
200
- * // Derived store — auto-fetches & reconciles by `id`.
201
- * const [users] = createStore(
202
- * async () => fetch("/users").then(r => r.json()),
203
- * [] as User[]
204
- * );
205
- * ```
206
- *
207
- * @returns `[store: Store<T>, setStore: StoreSetter<T>]`
208
- */
209
- export declare function createStore<T extends object = {}>(store: NoFn<T> | Store<NoFn<T>>, options?: StoreOptions & {
210
- shallow?: boolean;
211
- }): StoreReturn<T>;
212
- 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): ProjectionStoreReturn<T>;
213
138
  export {};
@@ -1,43 +1,3 @@
1
- /**
2
- * Returns a plain (non-proxy, non-reactive) deep copy of a store value.
3
- * Reading via `snapshot` does **not** subscribe to changes — use this when you
4
- * need to hand a stable plain object to non-reactive code (logging,
5
- * serialization, structured-clone, network payloads, etc.).
6
- *
7
- * Returns the original object identity for any sub-tree that wasn't modified
8
- * relative to the proxy's underlying source.
9
- *
10
- * @example
11
- * ```ts
12
- * const [state] = createStore({ user: { name: "Ada" }, todos: [] });
13
- *
14
- * console.log(JSON.stringify(snapshot(state))); // safe, non-reactive copy
15
- * ```
16
- */
17
- export declare function snapshot<T>(item: T): T;
18
- export declare function snapshot<T>(item: T, map?: Map<unknown, unknown>, lookup?: WeakMap<any, any>): T;
19
- /**
20
- * Returns a plain (non-proxy) deep copy **and** subscribes the current
21
- * tracking scope to every nested change in the source store. Any write
22
- * anywhere in the subtree invalidates the consumer.
23
- *
24
- * Use this when you need plain data inside a reactive scope and want to
25
- * react to deep mutations (e.g. passing a snapshot to `reconcile()` or to a
26
- * memo that should rerun on any nested change). For most read paths, prefer
27
- * direct property access — Solid stores already track per-property reads
28
- * with no `deep()` wrapper needed.
29
- *
30
- * @example
31
- * ```ts
32
- * const [state] = createStore({ a: { b: { c: 1 } } });
33
- *
34
- * createEffect(
35
- * () => deep(state), // reruns on any nested change
36
- * plain => sendToWorker(plain) // worker gets a non-proxy copy
37
- * );
38
- * ```
39
- */
40
- export declare function deep<T extends object>(store: T): T;
41
1
  type DistributeOverride<T, F> = T extends undefined ? F : T;
42
2
  type Override<T, U> = T extends any ? U extends any ? {
43
3
  [K in keyof T]: K extends keyof U ? DistributeOverride<U[K], T[K]> : T[K];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidjs/signals",
3
- "version": "2.0.0-rc.0",
3
+ "version": "2.0.0-rc.2",
4
4
  "description": "Solid's reactive primitives: signals, memos, effects, stores, and async-aware computations.",
5
5
  "author": "Ryan Carniato",
6
6
  "license": "MIT",
@@ -40,6 +40,7 @@
40
40
  "./package.json": "./package.json"
41
41
  },
42
42
  "devDependencies": {
43
+ "@codspeed/vitest-plugin": "^5.4.0",
43
44
  "@ianvs/prettier-plugin-sort-imports": "^4.1.1",
44
45
  "@rollup/plugin-replace": "^6.0.3",
45
46
  "@rollup/plugin-typescript": "^12.3.0",
@@ -1,217 +0,0 @@
1
- import { STATUS_PENDING, CONFIG_AUTO_DISPOSE, NOT_PENDING } from "../core/constants.js";
2
-
3
- import { computed } from "../core/core.js";
4
-
5
- import { GlobalQueue, schedule, currentTransition, insertSubs, setProjectionWriteActive, projectionWriteActive } from "../core/scheduler.js";
6
-
7
- import "../core/invariants.js";
8
-
9
- import "../core/verdict.js";
10
-
11
- import "../core/effect.js";
12
-
13
- import { installOptimisticEngine } from "../core/optimistic.js";
14
-
15
- import { runProjectionComputed } from "./projection.js";
16
-
17
- import { $TARGET, STORE_FIREWALL, storeSetter, STORE_OPTIMISTIC_OVERRIDE, STORE_NODE, STORE_OPTIMISTIC_OWNERS, getOverlayLayer, STORE_VALUE, $DELETED, isWrappable, wrap, visibleNodeValue, $TRACK, notifySelf, STORE_WRAP, createStoreProxy, storeTraps, STORE_LOOKUP, STORE_SHALLOW, markRawIngest, STORE_OPTIMISTIC } from "./store.js";
18
-
19
- function createOptimisticStore(e, t, i) {
20
- // Register clear function with scheduler; store nodes marked
21
- // STORE_OPTIMISTIC take the engine's write path, so install it before any
22
- // node can be created.
23
- installOptimisticEngine();
24
- if (!GlobalQueue.Dt) {
25
- GlobalQueue.Dt = clearOptimisticStores;
26
- // Store half of the engine's override blockage (#2951): signal-form
27
- // createOptimistic carries the pending async and the override on ONE node,
28
- // so transitionBlocked sees both; a derived optimistic STORE splits them —
29
- // the layer sits on store targets while the in-flight truth lives on the
30
- // firewall computed. Without this, the transition adopting a bare store
31
- // write settled in the same flush that started the refetch and its settle
32
- // consumed the layer mid-flight (follow-up writes then drafted from base,
33
- // clobbering instead of composing). Optimistic state clears when truth
34
- // lands or its transaction ends — never mid-refetch. Wrapped here (engine
35
- // is already installed above) so store-free apps never carry the check.
36
- const e = GlobalQueue.Tn;
37
- GlobalQueue.Tn = t => {
38
- for (const e of t.cn) {
39
- if ((e[$TARGET]?.[STORE_FIREWALL]?.S ?? 0) & STATUS_PENDING) return true;
40
- }
41
- return e(t);
42
- };
43
- }
44
- const r = typeof e === "function";
45
- // Plain form: the second slot carries options.
46
- if (!r && i === undefined) i = t;
47
- const o = r ? t : e;
48
- const n = r ? e : undefined;
49
- // Create optimistic projection store
50
- const {store: c} = createOptimisticProjectionInternal(n, o, i);
51
- return [ c, e => storeSetter(c, e) ];
52
- }
53
-
54
- // Clear the optimistic overrides of a settling batch of stores and notify
55
- // signals. Owns the whole batch (iterate + clear + reschedule) so the
56
- // scheduler's flush tail carries only a size-guarded hook call. The
57
- // completing transition scopes each clear to its own layer keys (#2899).
58
- function clearOptimisticStores(e, t) {
59
- for (const i of e) {
60
- const e = i[$TARGET];
61
- if (e?.[STORE_OPTIMISTIC_OVERRIDE]) clearOptimisticOverride(e, t);
62
- }
63
- e.clear();
64
- schedule();
65
- }
66
-
67
- /**
68
- * Consume optimistic layer entries and reset their backing nodes to base.
69
- * With `completing` (settle path, #2899) only entries the settling
70
- * transaction owns are consumed — the layer is store-wide but concurrent
71
- * actions revert independently, so keys stamped by a still-in-flight
72
- * transition survive (node-level overrides already have this granularity via
73
- * _optimisticNodes; this is the layer's half). `null` consumes ambient
74
- * (transaction-less) entries at plain flush end. Omitted (projection landing:
75
- * fresh authoritative data) consumes everything — the correction supersedes
76
- * every tentative layer.
77
- */ function clearOptimisticOverride(e, t) {
78
- const i = e[STORE_OPTIMISTIC_OVERRIDE];
79
- if (!i) return;
80
- const r = e[STORE_NODE];
81
- const o = e[STORE_OPTIMISTIC_OWNERS];
82
- const n = t !== undefined;
83
- let c = false;
84
- let s = false;
85
- // Use projectionWriteActive to bypass optimistic signal behavior (no lane creation)
86
- // This ensures reversion effects go to regular queues, not lane queues
87
- const O = projectionWriteActive;
88
- setProjectionWriteActive(true);
89
- try {
90
- for (const O of Reflect.ownKeys(i)) {
91
- if (n) {
92
- let e = o?.[O] ?? null;
93
- // Resolve merge chains (entangled actions settle as one); path-compress
94
- // so later keys skip the walk. A dead owner (`_done === true`) settled
95
- // through some other path — never strand its entry. A null owner is an
96
- // ambient write: its batch belongs to whichever transaction adopted it
97
- // (initTransition mid-batch) or to the plain flush, so it clears on
98
- // whichever clear call reaches this store first.
99
- if (e) {
100
- if (typeof e.fn === "object") e = o[O] = currentTransition(e);
101
- if (e !== t && e.fn !== true) {
102
- s = true;
103
- continue;
104
- }
105
- }
106
- }
107
- delete i[O];
108
- if (o) delete o[O];
109
- c = true;
110
- const T = r?.[O];
111
- if (T) {
112
- // Clear lane association so effects go to regular queue
113
- T.Ke = undefined;
114
- // Re-read from base — this key left the optimistic layer above, so the
115
- // overlay resolves to STORE_OVERRIDE or STORE_VALUE.
116
- const t = getOverlayLayer(e, O);
117
- const i = t ? t[O] : e[STORE_VALUE][O];
118
- const r = i === $DELETED ? undefined : i;
119
- const o = isWrappable(r) ? wrap(r, e) : r;
120
- const n = visibleNodeValue(T);
121
- T._e = NOT_PENDING;
122
- T.sn = null;
123
- T.De = NOT_PENDING;
124
- T.Ue = o;
125
- if (!T.be || !T.be(n, o)) {
126
- insertSubs(T, true);
127
- schedule();
128
- }
129
- }
130
- }
131
- if (!s) {
132
- // Assignment, not delete: StoreNode targets share one pre-initialized
133
- // hidden class (see createStoreProxy) and a delete would demote it.
134
- e[STORE_OPTIMISTIC_OVERRIDE] = undefined;
135
- e[STORE_OPTIMISTIC_OWNERS] = undefined;
136
- }
137
- // Notify $TRACK
138
- if (c && r?.[$TRACK]) {
139
- r[$TRACK].Ke = undefined;
140
- notifySelf(e);
141
- }
142
- } finally {
143
- setProjectionWriteActive(O);
144
- }
145
- }
146
-
147
- function createOptimisticProjectionInternal(e, t, i) {
148
- let r;
149
- const o = new WeakMap;
150
- const n = !!i?.shallow;
151
- const wrapper = e => {
152
- e[STORE_WRAP] = wrapProjection;
153
- e[STORE_LOOKUP] = o;
154
- if (n) {
155
- e[STORE_SHALLOW] = true;
156
- markRawIngest(e[STORE_VALUE]);
157
- }
158
- e[STORE_OPTIMISTIC] = true;
159
- // Mark as optimistic store
160
- Object.defineProperty(e, STORE_FIREWALL, {
161
- get() {
162
- return r;
163
- },
164
- configurable: true
165
- });
166
- };
167
- const wrapProjection = e => {
168
- if (o.has(e)) return o.get(e);
169
- if (e[$TARGET]?.[STORE_WRAP] === wrapProjection) return e;
170
- const t = createStoreProxy(e, storeTraps, wrapper);
171
- o.set(e, t);
172
- return t;
173
- };
174
- const c = wrapProjection(t);
175
- // If there's a projection function, create a computed to drive it
176
- if (e) {
177
- // All writes inside firewall recompute must go to STORE_OVERRIDE (base), not
178
- // STORE_OPTIMISTIC_OVERRIDE. The outer wrap covers the sync body (including
179
- // `fn(draft)` and the initial commit); `wrapCommit` re-applies the flag for
180
- // async yields because they fire outside any enclosing try/finally. It also
181
- // consumes stale optimistic overlays once fresh projected data lands.
182
- const clearProjectionOverride = () => {
183
- const e = c[$TARGET];
184
- if (e?.[STORE_OPTIMISTIC_OVERRIDE]) clearOptimisticOverride(e);
185
- };
186
- const wrapCommit = e => {
187
- const t = projectionWriteActive;
188
- setProjectionWriteActive(true);
189
- try {
190
- e();
191
- clearProjectionOverride();
192
- } finally {
193
- setProjectionWriteActive(t);
194
- }
195
- };
196
- // seedLoadingValue: born-committed firewall, same as createProjection.
197
- let t;
198
- if (i?.seedLoadingValue) t = {
199
- loadingValue: undefined
200
- };
201
- r = computed(() => {
202
- setProjectionWriteActive(true);
203
- try {
204
- runProjectionComputed(c, e, i?.key === undefined ? "id" : i.key, wrapCommit, clearProjectionOverride);
205
- } finally {
206
- setProjectionWriteActive(false);
207
- }
208
- }, t);
209
- r.T &= ~CONFIG_AUTO_DISPOSE;
210
- }
211
- return {
212
- store: c,
213
- node: r
214
- };
215
- }
216
-
217
- export { createOptimisticStore };
@@ -1,231 +0,0 @@
1
- import { computed } from "../core/core.js";
2
-
3
- import { getOwner } from "../core/owner.js";
4
-
5
- import { setProjectionWriteActive } from "../core/scheduler.js";
6
-
7
- import { handleAsync } from "../core/async.js";
8
-
9
- import "../core/verdict.js";
10
-
11
- import "../core/effect.js";
12
-
13
- import { CONFIG_AUTO_DISPOSE } from "../core/constants.js";
14
-
15
- import { reconcileState } from "./reconcile.js";
16
-
17
- import { $TARGET, STORE_VALUE, storeSetter, STORE_WRAP, createStoreProxy, storeTraps, setWriteOverride, STORE_LOOKUP, STORE_SHALLOW, markRawIngest, STORE_FIREWALL } from "./store.js";
18
-
19
- function createProjectionInternal(e, t, r) {
20
- let o;
21
- const n = new WeakMap;
22
- // A shallow projection's children are raw and never wrapped, so the
23
- // wrapper only ever runs for the root — flagging unconditionally is safe.
24
- const i = !!r?.shallow;
25
- const wrapper = e => {
26
- e[STORE_WRAP] = wrapProjection;
27
- e[STORE_LOOKUP] = n;
28
- if (i) {
29
- e[STORE_SHALLOW] = true;
30
- markRawIngest(e[STORE_VALUE]);
31
- }
32
- Object.defineProperty(e, STORE_FIREWALL, {
33
- get() {
34
- return o;
35
- },
36
- configurable: true
37
- });
38
- };
39
- const wrapProjection = e => {
40
- if (n.has(e)) return n.get(e);
41
- if (e[$TARGET]?.[STORE_WRAP] === wrapProjection) return e;
42
- const t = createStoreProxy(e, storeTraps, wrapper);
43
- n.set(e, t);
44
- return t;
45
- };
46
- const c = wrapProjection(t);
47
- // seedLoadingValue: the firewall is born committed (the seed is commit #0);
48
- // the internal handleAsync serves it during the derive's first flight. The
49
- // node's own value channel is void, so the loading value itself is
50
- // `undefined` — presence of the key is what flips the mode.
51
- let s;
52
- if (r?.seedLoadingValue) s = {
53
- loadingValue: undefined
54
- };
55
- o = computed(() => {
56
- if (!o) o = getOwner();
57
- runProjectionComputed(c, e, r?.key === undefined ? "id" : r.key);
58
- }, s);
59
- o.T &= ~CONFIG_AUTO_DISPOSE;
60
- return {
61
- store: c,
62
- node: o
63
- };
64
- }
65
-
66
- /**
67
- * Creates a derived (projected) store. Like `createMemo` but for stores: the
68
- * derive function receives a mutable draft and either mutates it in place
69
- * (canonical) or returns a new value. Either way the result is reconciled
70
- * against the previous draft by `options.key` (default `"id"`), so surviving
71
- * items keep their proxy identity — only added/removed items are
72
- * created/disposed.
73
- *
74
- * If the derive returns a different entity than the one currently held (the
75
- * `/users/1` → `/users/2` shape), the store swaps to it rather than merging,
76
- * and nothing below it is treated as surviving.
77
- *
78
- * Returns the projected store directly (no setter — reads only).
79
- *
80
- * Use this when you want the structural-sharing / per-property tracking
81
- * behaviour of a store on top of a derived computation. For simple read-only
82
- * derivations, `createMemo` is lighter.
83
- *
84
- * @param fn receives the current draft; mutate it in place or return new
85
- * data. Return is convenient for filter/derive shapes where mutation is
86
- * awkward.
87
- * @param seed the backing store value to wrap and reconcile into
88
- * @param options `ProjectionOptions` — `name`, `key`. `key` defaults to
89
- * `"id"`; specify it only when your data uses a different identity field
90
- * (e.g. `{ key: "uuid" }` or `{ key: u => u.slug }`), or `null` to merge
91
- * positionally with no keyed pass.
92
- *
93
- * @example
94
- * ```ts
95
- * // Mutation form — update individual fields on the draft.
96
- * const summary = createProjection<{ total: number; active: number }>(
97
- * draft => {
98
- * draft.total = users().length;
99
- * draft.active = users().filter(u => u.active).length;
100
- * },
101
- * { total: 0, active: 0 }
102
- * );
103
- *
104
- * // Return form — produce a derived collection. Reconciled by `id` so each
105
- * // surviving user keeps the same store identity across recomputes.
106
- * const activeUsers = createProjection<User[]>(
107
- * () => allUsers().filter(u => u.active),
108
- * []
109
- * );
110
- * ```
111
- *
112
- * @see {@link https://github.com/solidjs/x-reactivity#createprojection}
113
- */ function createProjection(e, t, r) {
114
- return createProjectionInternal(e, t, r).store;
115
- }
116
-
117
- /**
118
- * Shared projection computed body used by both `createProjection` and the derived
119
- * form of `createOptimisticStore`. Encapsulates the write-trap draft, `storeSetter`
120
- * wrapping, the `handleAsync` subscription with a setter callback, and the commit
121
- * path (which must always go through `storeSetter` so the `writeOnly` guard is
122
- * engaged during `reconcile`'s property reads).
123
- *
124
- * `wrapCommit` is invoked for every commit (sync return and each async yield) and
125
- * lets callers layer extra context around the write — e.g. the optimistic store
126
- * re-enters `setProjectionWriteActive` so reconciles target `STORE_OVERRIDE`
127
- * instead of `STORE_OPTIMISTIC_OVERRIDE` even when an async yield fires outside
128
- * the outer `setProjectionWriteActive` scope.
129
- */ function runProjectionComputed(e, t, r, o, n) {
130
- const i = getOwner();
131
- let c = false;
132
- let s;
133
- // Open loading window (seedLoadingValue): the observable store IS commit #0
134
- // for the whole first flight, so the derive works a detached shadow of the
135
- // seed — draft writes (pre-await, or between yields) land on the shadow and
136
- // cannot tear through to readers (#2988; store reads resolve from the live
137
- // backing, and the born-committed firewall removed the status gate that hid
138
- // windowless drafts). Every commit point — sync return, each yield, the
139
- // async landing — reconciles the shadow through the normal commit path, so
140
- // a fully-sync derive still lands immediately (commit #0 superseded before
141
- // any observer runs, same as a sync answer superseding loadingValue). The
142
- // JSON round-trip matches the server's frozen-seed copy (seedLock): a
143
- // loading-window seed is renderable data by contract. Optimistic note:
144
- // onDraftWrite (override clearing) shifts from write-time to commit-time
145
- // for the shadow run — an invisible draft write must not clobber a visible
146
- // optimistic override mid-window.
147
- const u = i.Ee ? JSON.parse(JSON.stringify(e[$TARGET][STORE_VALUE])) : null;
148
- const a = new Proxy(e, createWriteTraps(() => !c || i.Te === s, n));
149
- storeSetter(a, n => {
150
- s = t(u ?? n);
151
- c = true;
152
- const commit = t => {
153
- // Shadow run: a void/self return is the mutation form — the shadow
154
- // carries the writes and is what commits. Commit a detached snapshot,
155
- // never the shadow itself: reconcile adopts a new root value by
156
- // identity, and handing it the live shadow would fuse the draft to the
157
- // observable store — later shadow writes would mutate the backing
158
- // silently and the next yield would diff the shadow against itself.
159
- if (u && (t === undefined || t === u)) t = JSON.parse(JSON.stringify(u));
160
- if (t === n || t === undefined) return;
161
- const write = () => storeSetter(e, e => reconcileState(t, e, r, true));
162
- o ? o(write) : write();
163
- };
164
- const a = handleAsync(i, s, commit);
165
- // A still-open window after handleAsync means the return was the
166
- // commit-#0 fall-through, not a landing — real landings arrive through
167
- // the setter. A closed one is a genuine sync landing (windowless nodes
168
- // were never open); commit it.
169
- if (!i.Ee) commit(a);
170
- });
171
- return i;
172
- }
173
-
174
- function createWriteTraps(e, t) {
175
- const r = {
176
- get(e, t) {
177
- let o;
178
- setWriteOverride(true);
179
- setProjectionWriteActive(true);
180
- try {
181
- o = e[t];
182
- } finally {
183
- setWriteOverride(false);
184
- setProjectionWriteActive(false);
185
- }
186
- if (t === $TARGET) return o;
187
- return typeof o === "object" && o !== null ? new Proxy(o, r) : o;
188
- },
189
- has(e, t) {
190
- let r;
191
- setWriteOverride(true);
192
- setProjectionWriteActive(true);
193
- try {
194
- r = t in e;
195
- } finally {
196
- setWriteOverride(false);
197
- setProjectionWriteActive(false);
198
- }
199
- return r;
200
- },
201
- set(r, o, n) {
202
- if (e && !e()) return true;
203
- setWriteOverride(true);
204
- setProjectionWriteActive(true);
205
- try {
206
- r[o] = n;
207
- t?.();
208
- } finally {
209
- setWriteOverride(false);
210
- setProjectionWriteActive(false);
211
- }
212
- return true;
213
- },
214
- deleteProperty(r, o) {
215
- if (e && !e()) return true;
216
- setWriteOverride(true);
217
- setProjectionWriteActive(true);
218
- try {
219
- delete r[o];
220
- t?.();
221
- } finally {
222
- setWriteOverride(false);
223
- setProjectionWriteActive(false);
224
- }
225
- return true;
226
- }
227
- };
228
- return r;
229
- }
230
-
231
- export { createProjection, createProjectionInternal, createWriteTraps, runProjectionComputed };