@solidjs/signals 2.0.0-rc.0 → 2.0.0-rc.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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/dev.js +2622 -2438
  3. package/dist/node.cjs +3770 -3571
  4. package/dist/prod/core/async.js +186 -132
  5. package/dist/prod/core/core.js +118 -107
  6. package/dist/prod/core/effect.js +13 -13
  7. package/dist/prod/core/external.js +1 -1
  8. package/dist/prod/core/graph.js +8 -8
  9. package/dist/prod/core/heap.js +24 -24
  10. package/dist/prod/core/lanes.js +3 -3
  11. package/dist/prod/core/optimistic.js +38 -21
  12. package/dist/prod/core/owner.js +21 -21
  13. package/dist/prod/core/scheduler.js +55 -47
  14. package/dist/prod/core/verdict.js +40 -40
  15. package/dist/prod/index.js +7 -7
  16. package/dist/prod/map.js +81 -79
  17. package/dist/prod/signals.js +20 -1
  18. package/dist/prod/store/index.js +36 -0
  19. package/dist/prod/store/next/optimistic.js +377 -0
  20. package/dist/prod/store/next/projection.js +172 -0
  21. package/dist/prod/store/next/reconcile.js +327 -0
  22. package/dist/prod/store/next/store.js +1232 -0
  23. package/dist/prod/store/next/target.js +20 -0
  24. package/dist/prod/store/store.js +123 -879
  25. package/dist/prod/store/utils.js +59 -186
  26. package/dist/types/core/core.d.ts +8 -0
  27. package/dist/types/core/dev.d.ts +1 -1
  28. package/dist/types/core/scheduler.d.ts +4 -2
  29. package/dist/types/signals.d.ts +19 -0
  30. package/dist/types/store/index.d.ts +15 -5
  31. package/dist/types/store/next/optimistic.d.ts +20 -0
  32. package/dist/types/store/next/projection.d.ts +24 -0
  33. package/dist/types/store/next/reconcile.d.ts +3 -0
  34. package/dist/types/store/next/store.d.ts +71 -0
  35. package/dist/types/store/next/target.d.ts +99 -0
  36. package/dist/types/store/store.d.ts +26 -101
  37. package/dist/types/store/utils.d.ts +0 -40
  38. package/dist/types-cjs/core/core.d.cts +8 -0
  39. package/dist/types-cjs/core/dev.d.cts +1 -1
  40. package/dist/types-cjs/core/scheduler.d.cts +4 -2
  41. package/dist/types-cjs/signals.d.cts +19 -0
  42. package/dist/types-cjs/store/index.d.cts +15 -5
  43. package/dist/types-cjs/store/next/optimistic.d.cts +20 -0
  44. package/dist/types-cjs/store/next/projection.d.cts +24 -0
  45. package/dist/types-cjs/store/next/reconcile.d.cts +3 -0
  46. package/dist/types-cjs/store/next/store.d.cts +71 -0
  47. package/dist/types-cjs/store/next/target.d.cts +99 -0
  48. package/dist/types-cjs/store/store.d.cts +26 -101
  49. package/dist/types-cjs/store/utils.d.cts +0 -40
  50. package/package.json +2 -1
  51. package/dist/prod/store/optimistic.js +0 -217
  52. package/dist/prod/store/projection.js +0 -231
  53. package/dist/prod/store/reconcile.js +0 -707
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Store rewrite — target & ownership (INTERNALS-STORE-STATE.md §1, §5b).
3
+ *
4
+ * The proxy wraps this internal target, never the raw (proxy-target
5
+ * indirection, decision 2026-08-16d). `b` is the single committed home; `pb`
6
+ * is the per-target pending backing (RUL-1's pending home): the CoW clone
7
+ * created at first draft write, mutated natively by the draft, folded into
8
+ * `b` at flush commit. Adoption (setter replacement / reconcile) parks an
9
+ * UNOWNED incoming object in `pb` — fold swaps it in and ownership resets.
10
+ *
11
+ * Creation budget (§5b): one minimal target + one proxy + one storeLookup
12
+ * entry per read-through object; zero layer slots; nodes, has-nodes, and the
13
+ * key-set node are lazy, materialized only by subscription.
14
+ */
15
+ import type { Computed, Signal } from "../../core/types.cjs";
16
+ /** Projection family (§7b): children wrap into the family's own map (writes
17
+ * land in the projection, never the source family), and every node created
18
+ * under the family carries the projection computed as its firewall. */
19
+ export interface StoreNextFamily {
20
+ /** Optimistic family: nodes are born armed (`_overrideValue` slot) so every
21
+ * write rides the core optimistic engine — lanes, per-transaction ownership,
22
+ * reverts all core-native (§3, RUL-3). */
23
+ opt?: boolean;
24
+ /** Root proxy (registered with the scheduler's optimistic-store set for the
25
+ * transitionBlocked store-half, #2951). */
26
+ px?: any;
27
+ /** Targets currently carrying active node overrides (landing-consumption
28
+ * walk, RUL-2: visible landed truth replaces optimism). */
29
+ overlaid?: Set<any>;
30
+ map: WeakMap<object, StoreNextTarget>;
31
+ /** The projection computed — assigned after creation (accessor pattern). */
32
+ node: Computed<any> | null;
33
+ shallow?: boolean;
34
+ }
35
+ export interface StoreNextTarget {
36
+ /** Committed backing: source object (shared) or owned clone. */
37
+ v: Record<PropertyKey, any>;
38
+ /** Pending backing for the current flush (null when settled). */
39
+ pb: Record<PropertyKey, any> | null;
40
+ /** cached: committed backing is another store's proxy (§7b chained). */
41
+ ch: boolean;
42
+ /** live value-node count (deleted-key sweep fast-out in the fused walk). */
43
+ nc: number;
44
+ /** Lazy per-property subscription nodes (real core signals). */
45
+ n: Record<PropertyKey, Signal<any>> | null;
46
+ /** Lazy per-key presence nodes (`in` tracks presence, not value — R13). */
47
+ h: Record<PropertyKey, Signal<boolean>> | null;
48
+ /** Lazy key-set node: membership/iteration/$TRACK subscriptions (§6). */
49
+ k: Signal<number> | null;
50
+ /** Lazy deep-witness node: `deep()` subscribes ONE node per record instead
51
+ * of one per path; write paths bump it only when it exists. Separate from
52
+ * `k` so $TRACK/mapArray never rerun on leaf value changes (R9). */
53
+ dk: Signal<number> | null;
54
+ /** Parent target (path copying walks this at commit). */
55
+ u: StoreNextTarget | null;
56
+ /** Property key of this target in the parent's backing. */
57
+ pk: PropertyKey | null;
58
+ /** The proxy for this target (stable outward identity). */
59
+ px: any;
60
+ /** Sticky descendants flag (§6d). */
61
+ d: boolean;
62
+ /** Sticky accessors-seen flag: an own accessor property was observed on
63
+ * this target (first-read scan, defineProperty, or clone scan). Gates the
64
+ * fold diff's descriptor-safe path and the get trap's descriptor path. */
65
+ a: boolean;
66
+ /** Accessor scan performed (scan-once on first trap read; adopted data is
67
+ * not rescanned — legacy-parity behavior). */
68
+ sc: boolean;
69
+ /** Backing was swapped by adoption this batch (fold diff-notifies it). */
70
+ adopted: boolean;
71
+ /** Projection family, null for plain stores (§7b). */
72
+ fam: StoreNextFamily | null;
73
+ /** Shallow store root (values served raw). */
74
+ s: boolean;
75
+ }
76
+ /**
77
+ * Ownership (first cut, decision 2026-08-16d): one WeakSet of store-owned
78
+ * backings serving both the production identity-skip guard and the __TEST__
79
+ * no-mutation oracle.
80
+ */
81
+ export declare const ownedRaw: WeakSet<object>;
82
+ /** raw → target. The only raw-keyed lookup; boundary mechanism (O8). */
83
+ export declare const storeNextLookup: WeakMap<object, StoreNextTarget>;
84
+ /** __TEST__ oracle: every object ingested from a user (never mutate). */
85
+ export declare const ingestedRaw: WeakSet<object> | null;
86
+ export declare function devAssertNeverUserMutation(target: object): void;
87
+ /** Injection table for optimistic-only store machinery (next/optimistic.ts).
88
+ * Every call site is gated on `fam?.opt`, and optimistic families can only
89
+ * be created by createOptimisticStore — whose install populates this — so
90
+ * the non-null assertions at the sites hold by construction. Keeping the
91
+ * implementations out of next/store.ts lets plain-store bundles tree-shake
92
+ * the optimistic channel entirely. */
93
+ export interface OptStoreHooks {
94
+ notifyOptimisticWrites(t: any, pb: Record<PropertyKey, any>): void;
95
+ optimisticView(t: any, src: Record<PropertyKey, any>): Record<PropertyKey, any>;
96
+ applyTentative(t: any, incoming: any, keyFn: ((item: any) => any) | null): void;
97
+ }
98
+ export declare let optHooks: OptStoreHooks | null;
99
+ export declare function setOptHooks(h: OptStoreHooks): void;
@@ -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.1",
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 };