@solidjs/signals 2.0.0-rc.11 → 2.0.0-rc.14

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 (118) hide show
  1. package/dist/dev-shared.js +2056 -3773
  2. package/dist/dev.attribution.js +159 -91
  3. package/dist/dev.js +7263 -8384
  4. package/dist/observe/affects.js +125 -104
  5. package/dist/observe/boundaries.js +458 -665
  6. package/dist/observe/core/action.js +63 -66
  7. package/dist/observe/core/async.js +240 -383
  8. package/dist/observe/core/attribution-queries.js +1 -1
  9. package/dist/observe/core/attribution.js +271 -199
  10. package/dist/observe/core/constants.js +115 -178
  11. package/dist/observe/core/context.js +3 -3
  12. package/dist/observe/core/core.js +840 -1428
  13. package/dist/observe/core/dev.js +41 -18
  14. package/dist/observe/core/effect.js +75 -86
  15. package/dist/observe/core/external.js +5 -5
  16. package/dist/observe/core/graph.js +61 -70
  17. package/dist/observe/core/heap.js +75 -98
  18. package/dist/observe/core/invariants.js +1 -34
  19. package/dist/observe/core/lanes.js +704 -181
  20. package/dist/observe/core/owner.js +80 -101
  21. package/dist/observe/core/scheduler.js +708 -1351
  22. package/dist/observe/core/verdict.js +302 -621
  23. package/dist/observe/flatten.js +79 -0
  24. package/dist/observe/index.js +15 -13
  25. package/dist/observe/map.js +232 -235
  26. package/dist/observe/reveal.js +212 -0
  27. package/dist/observe/signals.js +133 -215
  28. package/dist/observe/store/affects.js +135 -0
  29. package/dist/observe/store/index.js +29 -24
  30. package/dist/observe/store/optimistic.js +538 -0
  31. package/dist/observe/store/projection.js +302 -0
  32. package/dist/observe/store/reconcile.js +257 -0
  33. package/dist/observe/store/store.js +1945 -277
  34. package/dist/observe/store/storePath.js +1 -1
  35. package/dist/{prod/store/next → observe/store}/target.js +17 -18
  36. package/dist/observe/store/types.js +73 -0
  37. package/dist/observe/store/utils.js +1 -13
  38. package/dist/prod/affects.js +127 -106
  39. package/dist/prod/boundaries.js +442 -654
  40. package/dist/prod/core/action.js +71 -74
  41. package/dist/prod/core/async.js +307 -442
  42. package/dist/prod/core/constants.js +112 -177
  43. package/dist/prod/core/context.js +3 -3
  44. package/dist/prod/core/core.js +852 -1448
  45. package/dist/prod/core/effect.js +88 -99
  46. package/dist/prod/core/external.js +5 -5
  47. package/dist/prod/core/graph.js +61 -70
  48. package/dist/prod/core/heap.js +75 -98
  49. package/dist/prod/core/invariants.js +1 -32
  50. package/dist/prod/core/lanes.js +666 -181
  51. package/dist/prod/core/owner.js +75 -96
  52. package/dist/prod/core/scheduler.js +677 -1332
  53. package/dist/prod/core/verdict.js +297 -621
  54. package/dist/prod/flatten.js +77 -0
  55. package/dist/prod/index.js +15 -13
  56. package/dist/prod/map.js +143 -146
  57. package/dist/prod/reveal.js +212 -0
  58. package/dist/prod/signals.js +144 -226
  59. package/dist/prod/store/affects.js +135 -0
  60. package/dist/prod/store/index.js +28 -19
  61. package/dist/prod/store/optimistic.js +533 -0
  62. package/dist/prod/store/projection.js +295 -0
  63. package/dist/prod/store/reconcile.js +257 -0
  64. package/dist/prod/store/store.js +1840 -272
  65. package/dist/prod/store/storePath.js +1 -1
  66. package/dist/{observe/store/next → prod/store}/target.js +13 -17
  67. package/dist/prod/store/types.js +73 -0
  68. package/dist/prod/store/utils.js +1 -11
  69. package/dist/types/affects.d.ts +11 -30
  70. package/dist/types/boundaries.d.ts +62 -176
  71. package/dist/types/carved.d.ts +1 -0
  72. package/dist/types/core/action.d.ts +5 -6
  73. package/dist/types/core/async.d.ts +10 -5
  74. package/dist/types/core/attribution-hooks.d.ts +48 -1
  75. package/dist/types/core/attribution.d.ts +29 -9
  76. package/dist/types/core/constants.d.ts +125 -171
  77. package/dist/types/core/core.d.ts +104 -264
  78. package/dist/types/core/dev.d.ts +60 -7
  79. package/dist/types/core/effect.d.ts +0 -7
  80. package/dist/types/core/graph.d.ts +7 -1
  81. package/dist/types/core/heap.d.ts +5 -7
  82. package/dist/types/core/index.d.ts +6 -6
  83. package/dist/types/core/invariants.d.ts +0 -29
  84. package/dist/types/core/lanes.d.ts +65 -87
  85. package/dist/types/core/owner.d.ts +3 -3
  86. package/dist/types/core/scheduler.d.ts +249 -331
  87. package/dist/types/core/types.d.ts +51 -85
  88. package/dist/types/core/verdict.d.ts +3 -0
  89. package/dist/types/flatten.d.ts +8 -0
  90. package/dist/types/index.d.ts +7 -5
  91. package/dist/types/reveal.d.ts +19 -0
  92. package/dist/types/signals.d.ts +53 -92
  93. package/dist/types/store/affects.d.ts +1 -0
  94. package/dist/types/store/index.d.ts +35 -15
  95. package/dist/types/store/optimistic.d.ts +23 -0
  96. package/dist/types/store/projection.d.ts +18 -0
  97. package/dist/types/store/reconcile.d.ts +3 -0
  98. package/dist/types/store/store.d.ts +165 -143
  99. package/dist/types/store/storePath.d.ts +1 -1
  100. package/dist/types/store/target.d.ts +151 -0
  101. package/dist/types/store/types.d.ts +84 -0
  102. package/package.json +1 -1
  103. package/dist/observe/core/optimistic.js +0 -669
  104. package/dist/observe/store/next/optimistic.js +0 -717
  105. package/dist/observe/store/next/projection.js +0 -266
  106. package/dist/observe/store/next/reconcile.js +0 -375
  107. package/dist/observe/store/next/store.js +0 -2480
  108. package/dist/prod/core/optimistic.js +0 -658
  109. package/dist/prod/store/next/optimistic.js +0 -710
  110. package/dist/prod/store/next/projection.js +0 -257
  111. package/dist/prod/store/next/reconcile.js +0 -373
  112. package/dist/prod/store/next/store.js +0 -2356
  113. package/dist/types/core/optimistic.d.ts +0 -6
  114. package/dist/types/store/next/optimistic.d.ts +0 -25
  115. package/dist/types/store/next/projection.d.ts +0 -27
  116. package/dist/types/store/next/reconcile.d.ts +0 -10
  117. package/dist/types/store/next/store.d.ts +0 -143
  118. package/dist/types/store/next/target.d.ts +0 -196
@@ -1,2480 +0,0 @@
1
- import { attrHooks } from "../../core/attribution-hooks.js";
2
-
3
- import { unwrapOverride, $REFRESH, CONFIG_CHILDREN_FORBIDDEN, CONFIG_OWNED_WRITE, NOT_PENDING, CONFIG_OPTIMISTIC, STATUS_UNINITIALIZED, STATUS_ERROR, REACTIVE_RECOMPUTING_DEPS, CONFIG_OVERRIDE_SUPERSEDED, CONFIG_AUTHORITATIVE_READ } from "../../core/constants.js";
4
-
5
- import { setSlotUnobserved, setSignal, isEqual, rederiveHeld, suppressComputedRecompute, read, hasActiveOverride, pendingCheckActive, latestReadActive, readNodeFast, READ_SLOW, signal, unlinkFirewallChild, ext, visibleOverride, ownsHold, serve, setLatestReadActive, prepareComputed, slotSignal, stale, recordStaleReplay, enterStagedRead, context, currentOptimisticLane, heldDerivation } from "../../core/core.js";
6
-
7
- import { projectionWriteActive, setProjectionWriteActive, activeTransition, schedule, currentTransition, deferSlotRelease, setStoreCommitHook } from "../../core/scheduler.js";
8
-
9
- import "../../core/invariants.js";
10
-
11
- import { getOwner, getObserver } from "../../core/owner.js";
12
-
13
- import { registerGraph } from "../../core/dev.js";
14
-
15
- import { $TARGET, isWrappable, markRawIngest, $PROXY, getWriteOverride, markRawOne, $RECORD, witnessAffectsMark, $TRACK, affectsScopesLive, inheritAffectsMarks, $AFFECTS, rawValuesUsed, isRawValue, setNextAffectsNodeResolver } from "../store.js";
16
-
17
- import { lookupTarget, optHooks, storeNextLookup, $OWNER, isOwned, markDescendants, devAssertNeverUserMutation } from "./target.js";
18
-
19
- /**
20
- * Store rewrite — increment 2: plain deep stores with pending-backing writes.
21
- * Contract: INTERNALS-STORE-STATE.md.
22
- *
23
- * Write model (RUL-1, unified): the first draft write to a target creates its
24
- * pending backing `pb` — a descriptor-preserving CoW clone. The draft mutates
25
- * `pb` natively (array methods, defineProperty, deletes all just work).
26
- * Reads: drafts and owner-context reads see `pb`; context-free reads see the
27
- * committed `b` until flush. At flush commit (core's storeCommitHook), each
28
- * written target folds: diff old `b` vs new backing notifies exactly the
29
- * changed keys through equality-gated nodes, then `b` becomes the new
30
- * backing. Setter return-value replacement parks the UNOWNED incoming object
31
- * in `pb` — adoption: fold swaps it in, ownership resets (2026-08-16c).
32
- *
33
- * Nodes carry no pending state — they are pure subscription points; `pb` is
34
- * the pending home. Laziness: a written target with no subscriptions folds as
35
- * a pointer swap with zero node work.
36
- */
37
- // ---------------------------------------------------------------------------
38
- // wrap / dedupe
39
- /** Pre-shaped constructor for OBJECT proxy targets: V8 tips a bare `{}` into
40
- * dictionary mode once ~19 named properties are assigned onto it (the #3044
41
- * `ovl`/`del` fields crossed that line — every trap's field read became a
42
- * hash lookup, a 15% deep-dbmon tick regression). Declaring every field in a
43
- * constructor pre-allocates in-object slots so the map stays fast, with
44
- * headroom for future fields. The prototype is reset to `Object.prototype`
45
- * so proxy-forwarded semantics (getPrototypeOf, constructor) are exactly a
46
- * plain object's. Array targets keep the bare-`[]` path — they must carry
47
- * the array exotic class for `Array.isArray(proxy)`.
48
- *
49
- * ARRAY SHAPE RULE: arrays normalize their named properties to dictionary
50
- * mode as the count grows (V8 13.x: counts ≡ 0 mod 3 from 18 up), so the
51
- * target's named field count is capped at 20 — any future write-side state
52
- * beyond `wk` must ride an extension object (see target.ts), never new
53
- * named fields here. */
54
- function TargetShape() {
55
- this.v = undefined;
56
- this.ch = undefined;
57
- this.pb = undefined;
58
- this.n = undefined;
59
- this.h = undefined;
60
- this.k = undefined;
61
- this.dk = undefined;
62
- this.u = undefined;
63
- this.pk = undefined;
64
- this.px = undefined;
65
- this.d = undefined;
66
- this.a = undefined;
67
- this.sc = undefined;
68
- this.kc = undefined;
69
- this.nc = undefined;
70
- this.ab = undefined;
71
- this.fam = undefined;
72
- this.s = undefined;
73
- this.ovl = undefined;
74
- this.del = undefined;
75
- this.wk = undefined;
76
- this.hv = undefined;
77
- this.ht = undefined;
78
- }
79
-
80
- TargetShape.prototype = Object.prototype;
81
-
82
- function createTarget(e, t, n, r = t?.fam ?? null) {
83
- // The proxy target carries the array exotic class when the value is an
84
- // array, so Array.isArray(proxy) is true; the fields live on it directly.
85
- // Direct field assignment in one fixed order (no Object.assign literal
86
- // copy): every target shares a hidden-class transition chain — createTarget
87
- // was the #2 store cost in the uibench creation profile.
88
- const i = Array.isArray(e) ? [] : new TargetShape;
89
- i.v = e;
90
- // Chained-backing flag (backing IS another store's proxy, §7b) — cached so
91
- // the hot read path never does a per-read symbol lookup on the backing.
92
- i.ch = e[$TARGET] !== undefined;
93
- i.pb = null;
94
- i.n = null;
95
- i.h = null;
96
- i.k = null;
97
- i.dk = null;
98
- i.wk = null;
99
- i.u = t;
100
- i.pk = n;
101
- i.px = null;
102
- i.d = false;
103
- i.a = false;
104
- i.sc = 0;
105
- i.kc = 0;
106
- i.nc = 0;
107
- i.ab = null;
108
- i.fam = r;
109
- i.s = false;
110
- i.ovl = false;
111
- i.del = null;
112
- i.hv = null;
113
- i.ht = null;
114
- i.px = new Proxy(i, traps);
115
- // Legacy interop: shared machinery (affects walks, wrap dedupe) reads the
116
- // proxy off looked-up targets as a field.
117
- i[$PROXY] = i.px;
118
- (r?.map ?? storeNextLookup).set(e, i);
119
- return i;
120
- }
121
-
122
- function wrapNext(e, t = null, n = null, r = t?.fam ?? null) {
123
- // markRaw'd values never wrap through ANY store (R42; sticky raw-marking
124
- // is one half of the never-both-wrapped-and-raw invariant, RUL-12).
125
- if (rawValuesUsed && isRawValue(e)) return e;
126
- const i = lookupTarget(e, r);
127
- if (i !== undefined) return i.px;
128
- const o = e[$TARGET];
129
- if (o !== undefined && o.px === e) {
130
- // Foreign-family proxies re-wrap into THIS family (writes stay isolated);
131
- // same-family and plain-store proxies pass through.
132
- if (r === null || o.fam === r) return e;
133
- return createTarget(e, t, n, r).px;
134
- }
135
- return createTarget(e, t, n, r).px;
136
- }
137
-
138
- /** Unwrap our own proxies to their current backing; leave everything else. */ function unwrapValue(e) {
139
- if (e == null || typeof e !== "object") return e;
140
- const t = e[$TARGET];
141
- if (t !== undefined && t.px === e && t.v !== undefined) {
142
- // A draft escaping into other storage must be a REAL container that
143
- // becomes this target's committed backing at fold (the shared-raw
144
- // contract) — a prototype overlay is neither.
145
- if (t.ovl) materializePB(t);
146
- return t.pb ?? t.v;
147
- }
148
- return e;
149
- }
150
-
151
- // ---------------------------------------------------------------------------
152
- // nodes: pure subscription points (values used only for equality gating)
153
- // Shared slot-node equality (create-floor diet): ONE function for every
154
- // store node — `this` is the node (method-call convention at every _equals
155
- // site), `_host` is the baked-in target backref. Logical-slot equality:
156
- // values resolving to the same child target are the same slot
157
- // (privatization/adoption swap raw identity without changing the logical
158
- // value — only changed leaves notify, R9).
159
- const slotNodeEquals = function(e, t) {
160
- return isEqual(e, t) || sameLogicalSlot(this.Kt, e, t);
161
- };
162
-
163
- // Shared slot-node unobserved handler (create-floor diet): registered once;
164
- // the core sweep dispatches CONFIG_SLOT_NODE nodes here instead of holding a
165
- // per-node closure in a per-node NodeExtension.
166
- setSlotUnobserved(e => {
167
- // A live affects() mark keeps the node addressable (sweep parity).
168
- if (e.o?.t) return;
169
- // An active override or a staged write is state only the node holds (an
170
- // optimistic signal keeps its override whether or not anything reads it —
171
- // store parity, posture-store-parity S7): defer the release to the flush
172
- // that resolves it (the scheduler's transient-node sweep).
173
- if (hasActiveOverride(e) || e._e !== NOT_PENDING) return deferSlotRelease(e);
174
- const t = e.Kt;
175
- const n = e.zt;
176
- if (t.n && t.n[n] === e) {
177
- delete t.n[n];
178
- t.nc--;
179
- // Projection leaves also leave the firewall child chain (#3351): a
180
- // dropped node is unreachable through the store — a fresh read makes a
181
- // fresh node — so the chain would only retain it and its last value.
182
- unlinkFirewallChild(e);
183
- }
184
- });
185
-
186
- function getNode(e, t, n,
187
- // First-read dedupe (create-floor slice 2): the get trap probes
188
- // accessor-ness right before creating the node — pass the verdict through
189
- // so creation skips the second descriptor scan. -1 = unknown (other
190
- // callers), 0/1 = probed.
191
- r = -1) {
192
- const i = e.n ??= Object.create(null);
193
- let o = i[t];
194
- if (o === undefined) {
195
- // Born holding (#3330 store twin): a key first read while a live
196
- // transaction holds an ADOPTION on this target (adoptPB's `ht`) is
197
- // created as if it had existed when the hold was notified — the adopted
198
- // value already swapped into `v`, so committed is the held view
199
- // `hv[key]` and the adopted `v[key]` is staged under the transaction
200
- // (stageHeldKey). Its held-adoption notification (stageHeldAdoptions)
201
- // ran before the node existed and the drain has nothing left to say.
202
- // Without this the node was born from whichever view its first reader
203
- // saw and never learned the other. Two kinds of hold, one rule (#3336):
204
- // - a held FOLD (pb): a setter's write to an unobserved key landed only
205
- // in the pending backing; committed is `v[key]`, staged is `pb[key]`
206
- // (undefined for a deleted key);
207
- // - a held ADOPTION (ht): the adopted value already swapped into `v`;
208
- // committed is the held view `hv[key]`, staged is `v[key]`.
209
- const l = heldFoldTransition(e);
210
- let s = heldAdoptionTransition(e);
211
- if (s !== null) n = e.hv[t]; else if ((s = l) !== null) n = e.v[t];
212
- // Create-floor diet: slotSignal bakes the whole node into one literal —
213
- // no options object, no equals/unobserved closures, no NodeExtension,
214
- // no post-construction expandos (acc + the wrap cache px/pxv are
215
- // pre-shaped fields: the proxy last served for this key and the raw it
216
- // wrapped — one pointer compare replaces the per-read WeakMap lookup in
217
- // wrapNext). ownedWrite rides the literal's config: the setter carries
218
- // the owned-scope write guard; node-level setSignals are internal
219
- // notification machinery. Projection nodes carry the projection
220
- // computed as their firewall: reads through them link the derive's
221
- // status/lifecycle (§7b).
222
- const f = o = slotSignal(n, slotNodeEquals, e, t,
223
- // Accessor-ness resolved ONCE per node (no per-object descriptor
224
- // scan on reads): accessor keys serve through Reflect.get with the
225
- // proxy receiver.
226
- r === -1 ? isOwnAccessor(e.pb ?? e.v, t) : r === 1, e.fam?.node ?? undefined);
227
- // Attribution-only: name store property nodes by path segment so
228
- // attribution chains and wide-scope warnings read "store.todos" (or
229
- // "todos.title" when the store was declared with a name), not
230
- // "signal". Gated on the engine being installed — node creation is
231
- // the hottest store path, and the disabled cost must stay one null
232
- // check (nodes created before enable() stay generically named).
233
- if (attrHooks !== null) {
234
- f._name = storeLabel(e) + "." + String(t);
235
- stampNodeOwner(f, e);
236
- }
237
- // Optimistic families: arm the override slot — setSignal routes armed
238
- // nodes through the core engine (lanes, ownership, reverts all native).
239
- if (e.fam?.opt) {
240
- ext(f).we = NOT_PENDING;
241
- f.C |= CONFIG_OPTIMISTIC;
242
- }
243
- // A node born inside a live mark's identity scope inherits the mark
244
- // (the declaration walk could only cover nodes existing then).
245
- if (t !== $AFFECTS && affectsScopesLive()) inheritAffectsMarks(f, e.v, t);
246
- if (s !== null) stageHeldKey(f, l !== null ? e.del !== null && e.del.has(t) ? undefined : e.pb[t] : e.v[t], s);
247
- i[t] = o;
248
- e.nc++;
249
- markDescendants(e);
250
- }
251
- return o;
252
- }
253
-
254
- /** The live transaction holding an adoption on `target` (adoptPB's `ht`;
255
- * a latest()-pull PLAIN_HOLD is not a transaction), else null. */ function heldAdoptionTransition(e) {
256
- if (e.ht === null || e.ht === PLAIN_HOLD || heldMaskView(e) === null) return null;
257
- const t = currentTransition(e.ht);
258
- return t.Dt === false ? t : null;
259
- }
260
-
261
- /**
262
- * Materialization under a hold. A node created by a first tracked read while
263
- * a transaction holds this target must carry the same state a node that
264
- * existed when the hold was notified carries — a transaction-stamped
265
- * `_pendingValue` that core read() serves by ITS rules (a stale render reader
266
- * of a foreign transaction's write sees committed, an owner-context reader
267
- * inside the transaction sees the write) — or the reader's answer depends on
268
- * whether some OTHER reader had materialized the key before the hold. Stage
269
- * `nv` (the held value for the key — see getNode for which view it comes
270
- * from) as the holding transaction's write — directly, not through
271
- * setSignal: it is not a new write (it staged with the adoption's batch) and
272
- * it walks no subscriber (the node has none yet). Transition-stamped now, as
273
- * `runFolded` does — no parked-flush pass will stamp it.
274
- */
275
- /** The live transaction holding `target`'s pending backing (the #3089
276
- * write-time stamp, resolved through merges), else null. */ function liveFoldTransition(e) {
277
- if (e.pb === null) return null;
278
- const t = foldBatches.get(e);
279
- if (t === undefined) return null;
280
- const n = currentTransition(t);
281
- return n.Dt === false ? n : null;
282
- }
283
-
284
- /** liveFoldTransition for node materialization (stageHeldKey). Inside the
285
- * draft the backing is the setter's working copy, not a flushed hold — its
286
- * nodes take their writes at setter exit (notifyWrites). Optimistic families
287
- * hold at the backing: tentative writes are node overrides over a discarded
288
- * clone, and a truth-staged landing is served through the fold's own hold
289
- * (heldTruthMasked for lane passes, pendingBackingVisible's hold arms for
290
- * the rest) — neither is a plain staged write to mirror. Chained
291
- * backings serve the inner store's live value, never a node value. */ function heldFoldTransition(e) {
292
- if (e.ch || e.fam?.opt === true || inDraft(e)) return null;
293
- return liveFoldTransition(e);
294
- }
295
-
296
- /**
297
- * Rule 1 at the backing, the hold half (core serve()'s stale-of-foreign and
298
- * A29 arms, for a container instead of a node): given the transaction
299
- * holding what a reader `c` (a pass; callers serve context-free readers the
300
- * committed container themselves) is about to be served, is the STAGED
301
- * container its to see? Its own hold, or none — yes. A foreign hold — a
302
- * stale pass (render effect) keeps the committed frame and is recorded for
303
- * replay at the hold's commit (recordStaleReplay, A15 / A26); a deriving
304
- * pass takes the staged world and enters the transaction (enterStagedRead,
305
- * A29). Shared by both hold kinds: a setter's fold (committed `v`, staged
306
- * `pb`, the write-time stamp) and an adoption under a transaction
307
- * (committed = the held view `hv`, staged = the adopted `v`, #3074).
308
- */ function holdVisible(e, t) {
309
- if (e === null || ownsHold(e)) return true;
310
- if (stale) {
311
- recordStaleReplay(e, t);
312
- return false;
313
- }
314
- enterStagedRead(null, e);
315
- return true;
316
- }
317
-
318
- function stageHeldKey(e, t, n) {
319
- if (slotNodeEquals.call(e, e.ce, t)) return;
320
- e._e = t;
321
- e.me = n;
322
- n.In.push(e);
323
- }
324
-
325
- function sameLogicalSlot(e, t, n) {
326
- if (t === null || typeof t !== "object" || n === null || typeof n !== "object") return false;
327
- const r = lookupTarget(t, e.fam);
328
- return r !== undefined && r === lookupTarget(n, e.fam);
329
- }
330
-
331
- /**
332
- * Observe-tier: the owner each store root was created under. The proxy
333
- * cannot carry `_owner` itself (`registerGraph`'s stamp is swallowed by the
334
- * set trap outside a draft), so the root target keys it here and the store's
335
- * nodes copy it into `_owner` as they are created — an `OBSERVE.exclude`d
336
- * panel's store nodes are then excluded subjects, exactly like its signals.
337
- * Both ends are gated with the naming on the engine being installed: node
338
- * creation is the hottest store path, store creation is next, and the
339
- * disabled cost of each stays one null check. A store created before
340
- * `enable()` therefore has no recorded owner and its nodes are never excluded
341
- * subjects — the same boundary the naming draws; a panel enables first.
342
- */ const storeOwners = new WeakMap;
343
-
344
- function storeRoot(e) {
345
- let t = e;
346
- while (t.u !== null) t = t.u;
347
- return t;
348
- }
349
-
350
- function storeRootOwner(e) {
351
- return storeOwners.get(storeRoot(e));
352
- }
353
-
354
- function stampNodeOwner(e, t) {
355
- e.ie = storeRootOwner(t) ?? null;
356
- }
357
-
358
- // Attribution-only: the store's declared name (`createStore(v, { name })`,
359
- // what the compiler's `sourceNames.primitives` fills in). Property nodes are
360
- // named `<store>.<key>` from it so chains read "todos.title" instead of the
361
- // generic "store.title". Same gating and lifetime as storeOwners: recorded
362
- // only while the engine is installed, keyed by the root target.
363
- const storeNames = new WeakMap;
364
-
365
- /** Record a store proxy's declared name for attribution labels (observe tiers). */ function nameStore(e, t) {
366
- if (attrHooks !== null && t) storeNames.set(e[$TARGET], t);
367
- }
368
-
369
- function storeLabel(e) {
370
- return storeNames.get(storeRoot(e)) ?? "store";
371
- }
372
-
373
- function getHasNode(e, t, n) {
374
- const r = e.h ??= Object.create(null);
375
- let i = r[t];
376
- if (i === undefined) {
377
- const o = i = signal(n, {
378
- equals: isEqual,
379
- unobserved() {
380
- if (o.o?.t) return;
381
- // The structural twin of the value slot's rule (setSlotUnobserved,
382
- // S7): an optimistic add/delete lives on this presence node as its
383
- // override — releasing it with the override on would let `in`,
384
- // `Object.keys` and descriptors fall back to committed structure
385
- // while the action is live. Defer to the flush that resolves it.
386
- if (hasActiveOverride(o) || o._e !== NOT_PENDING) return deferSlotRelease(o);
387
- if (e.h && e.h[t] === o) {
388
- delete e.h[t];
389
- unlinkFirewallChild(o);
390
- }
391
- }
392
- }, e.fam?.node ?? undefined);
393
- o.C |= CONFIG_OWNED_WRITE;
394
- if (attrHooks !== null) stampNodeOwner(o, e);
395
- if (e.fam?.opt) {
396
- ext(o).we = NOT_PENDING;
397
- o.C |= CONFIG_OPTIMISTIC;
398
- }
399
- if (affectsScopesLive()) inheritAffectsMarks(o, e.v, t);
400
- r[t] = i;
401
- markDescendants(e);
402
- }
403
- return i;
404
- }
405
-
406
- /** Did `obs` link `target`'s key-set node in its CURRENT pass? The mirror of
407
- * link()'s O(1) repeat-touch check: the node's newest subscriber link is
408
- * this observer's, and — during a recompute — carries this pass's dep
409
- * generation (a link left from a previous pass is stale: the observer may
410
- * not re-read the key set this time). No dep-list scan, no allocation. A
411
- * probe observer (isPending()/latest() sentinel) never links, so it always
412
- * falls through to the presence read. */ function observerHoldsKeySet(e, t) {
413
- const n = e.k;
414
- if (n === null) return false;
415
- const r = n.Ht;
416
- return r !== null && r.Ae === t && (!(t.oe & REACTIVE_RECOMPUTING_DEPS) || r.Ze === t.We);
417
- }
418
-
419
- function getKeySetNode(e) {
420
- let t = e.k;
421
- if (t === null) {
422
- const n = t = signal(0, {
423
- equals: false,
424
- unobserved() {
425
- if (e.k === n) {
426
- e.k = null;
427
- unlinkFirewallChild(n);
428
- }
429
- }
430
- }, e.fam?.node ?? undefined);
431
- n.C |= CONFIG_OWNED_WRITE;
432
- if (attrHooks !== null) stampNodeOwner(n, e);
433
- if (e.fam?.opt) {
434
- ext(n).we = NOT_PENDING;
435
- n.C |= CONFIG_OPTIMISTIC;
436
- }
437
- e.k = t;
438
- markDescendants(e);
439
- }
440
- return t;
441
- }
442
-
443
- function getDeepNode(e) {
444
- let t = e.dk;
445
- if (t === null) {
446
- const n = t = signal(0, {
447
- equals: false,
448
- unobserved() {
449
- if (e.dk === n) {
450
- e.dk = null;
451
- unlinkFirewallChild(n);
452
- }
453
- }
454
- }, e.fam?.node ?? undefined);
455
- n.C |= CONFIG_OWNED_WRITE;
456
- if (attrHooks !== null) stampNodeOwner(n, e);
457
- if (e.fam?.opt) {
458
- ext(n).we = NOT_PENDING;
459
- n.C |= CONFIG_OPTIMISTIC;
460
- }
461
- if (affectsScopesLive()) inheritAffectsMarks(n, e.v, $TRACK);
462
- e.dk = t;
463
- markDescendants(e);
464
- }
465
- return t;
466
- }
467
-
468
- /** Deep-witness bump: any value/shape change on a record with a live deep()
469
- * subscriber notifies it. One null check when unused. */ function bumpDeep(e) {
470
- if (e.dk !== null) setSignal(e.dk, 1);
471
- }
472
-
473
- // ---------------------------------------------------------------------------
474
- // pending backing + fold (the single mutation point)
475
- /** target → committed backing at batch start (the fold diff's old side). */ const foldOlds = new Map;
476
-
477
- let hookInstalled = false;
478
-
479
- /** Shallow-clone `source` as a backing OWNED by `t` (stamped `$OWNER`, see
480
- * target.ts). Callers always pass their own committed backing as `source`. */ function cloneRaw(e, t) {
481
- // Plain-data fast path (#3360): a scanned `Object.prototype` container
482
- // whose own keys are all enumerable data clones by spread — the same
483
- // result as the descriptor walk below (own enumerable string+symbol keys,
484
- // normalized writable+configurable), at ~1/50th the cost.
485
- t.sc || scanAccessorsOnce(t);
486
- if (t.sc === 2) {
487
- const n = {
488
- ...e
489
- };
490
- n[$OWNER] = t;
491
- return n;
492
- }
493
- // Descriptor-preserving shallow clone (R29: installed getters stay live;
494
- // ruled 2026-08-17: frozen sources clone unfrozen — theirs stays frozen).
495
- // Data descriptors normalize to writable+configurable (the clone is OURS to
496
- // mutate — R51's "source-non-configurable is writable through the store");
497
- // enumerability and accessors are preserved. The scan doubles as the
498
- // accessor-flag detector (free — we're enumerating descriptors anyway).
499
- const n = Object.getOwnPropertyDescriptors(e);
500
- for (const r of Reflect.ownKeys(n)) {
501
- const i = n[r];
502
- if (r === "length" && Array.isArray(e)) continue;
503
- i.configurable = true;
504
- if (!i.get && !i.set) i.writable = true; else t.a = true;
505
- }
506
- const r = Array.isArray(e) ? Object.defineProperties([], n) : Object.create(Object.getPrototypeOf(e), n);
507
- r[$OWNER] = t;
508
- return r;
509
- }
510
-
511
- /** Copy own `key` from `from` onto `to`. A plain data slot (enumerable,
512
- * writable, configurable, no accessor) is a bare assignment — the common case
513
- * and the cheap one; anything else goes through defineProperty so accessors
514
- * and attribute flags survive the copy. */ function copyOwn(e, t, n) {
515
- const r = Object.getOwnPropertyDescriptor(t, n);
516
- if (r.get || r.set || !r.enumerable || !r.writable || !r.configurable) Object.defineProperty(e, n, r); else e[n] = r.value;
517
- }
518
-
519
- /** One-time own-accessor scan (Annex-B probes, no descriptor allocation);
520
- * returns true when the container is plain data (overlay-safe). Also grades
521
- * the container for the plain-data fast paths (`sc` = 2): `Object.prototype`
522
- * and every own key an enumerable data property — what a spread copies
523
- * exactly and what a bare assignment lands exactly. */ function scanAccessorsOnce(e) {
524
- const t = e.v;
525
- const n = Reflect.ownKeys(t);
526
- let r = Object.getPrototypeOf(t) === Object.prototype;
527
- for (const i of n) {
528
- // Own keys shadow prototype accessors, so the lookups are exact here.
529
- if (lookupGetter.call(t, i) !== undefined || lookupSetter.call(t, i) !== undefined) {
530
- e.a = true;
531
- r = false;
532
- break;
533
- }
534
- if (r && !propertyIsEnumerable.call(t, i)) r = false;
535
- }
536
- e.sc = r ? 2 : 1;
537
- e.kc = n.length;
538
- return !e.a;
539
- }
540
-
541
- /** Own-key count above which a draft opens as a prototype overlay rather
542
- * than a clone (#3360). Below it a spread clone of a plain container is
543
- * cheaper than the overlay's `Object.create` (V8 converts the committed
544
- * backing into a prototype, and every later flatten writes into that
545
- * prototype); above it the clone's O(keys) copy dominates (#3044). */ const OVERLAY_MIN_KEYS = 32;
546
-
547
- /** Downgrade a prototype-overlay pending backing to the clone path: builds
548
- * the real container (committed + overlay writes − deletes) that fold will
549
- * SWAP in as the committed backing, exactly as if the draft had started on
550
- * the clone path. Consumers that need a complete container (reconcile's
551
- * diff walks, drafts escaping into other storage) call this. */ function materializePB(e) {
552
- if (!e.ovl) return;
553
- const t = e.pb;
554
- const n = cloneRaw(e.v, e);
555
- for (const e of Reflect.ownKeys(t)) copyOwn(n, t, e);
556
- if (e.del !== null) {
557
- for (const t of e.del) delete n[t];
558
- e.del = null;
559
- }
560
- e.pb = n;
561
- e.ovl = false;
562
- }
563
-
564
- function ensurePB(e) {
565
- let t = e.pb;
566
- // Truth-staged backing hand-off (#3164 fold): a TENTATIVE draft opening on
567
- // a target whose pending backing is truth-staged (a landing folded into a
568
- // retaining transaction — it carries a foldBatches stamp) must not share
569
- // the container. Tentative writes would pollute staged truth, and the
570
- // tentative discard (notifyOptimisticWrites nulls pb) would destroy the
571
- // landing. Park the staged backing and open a fresh draft seeded from the
572
- // optimistic view below; the tentative discard restores it. The
573
- // tentativePBs guard scopes this to draft OPEN: the draft's own backing
574
- // (foldBatches-stamped by its first write when an action's transition is
575
- // ambient) must not be parked by its own later writes.
576
- if (t !== null && !tentativePBs.has(t) && e.fam?.opt === true && !projectionWriteActive && !getWriteOverride() && foldBatches.has(e)) {
577
- stagedTruthPB.set(e, t);
578
- t = e.pb = null;
579
- }
580
- if (activeTransition !== null) foldBatches.set(e, activeTransition);
581
- if (t === null) {
582
- // Prototype-chain overlay (#3044): plain-data non-array containers open
583
- // drafts in O(1) — own keys are the writes, reads fall through to
584
- // committed. Projection and derived-store families take it too (#3352:
585
- // a derive touching one root key of a wide keyed record paid an
586
- // O(keys) clone per recompute). Everything else keeps the descriptor
587
- // clone: arrays (splice/length semantics), OPTIMISTIC families (the
588
- // view-seeding below writes and deletes on the draft container, and the
589
- // tentative discard/truth-park hand whole backings around), chained
590
- // backings (the committed layer is another store's proxy — an overlay
591
- // would route every read-through into its traps), accessor containers
592
- // (live getters).
593
- // The overlay pays off only for a WIDE container over an OWNED committed
594
- // backing (#3360). Narrow containers clone cheaper than they overlay (a
595
- // spread is a fast-path copy; `Object.create` turns the backing into a
596
- // V8 prototype and every later flatten writes into that prototype). An
597
- // unowned backing has to be privatized (cloned) at commit anyway, so an
598
- // overlay there would cost the create PLUS the clone PLUS a per-key
599
- // copy — the clone path does the one clone and swaps it in. The first
600
- // write on a fresh store is exactly that case.
601
- const n = e.v;
602
- if (!e.fam?.opt && !e.ch && !Array.isArray(n) && (e.sc !== 0 ? !e.a : scanAccessorsOnce(e)) && e.kc > OVERLAY_MIN_KEYS && isOwned(n)) {
603
- // Inherits `v`'s $OWNER stamp — the overlay resolves and reads as
604
- // owned without a registration of its own.
605
- t = e.pb = Object.create(n);
606
- e.ovl = true;
607
- } else t = e.pb = cloneRaw(n, e);
608
- // Optimistic families: seed USER drafts from the OPTIMISTIC VIEW
609
- // (committed + active node overrides), so follow-up writes compose on
610
- // optimism instead of clobbering from base (#2951's compose half).
611
- // AUTHORITATIVE drafts (projection recompute / write-override landings)
612
- // seed from committed truth — seeding overrides there would fold a lane
613
- // value into the committed home ("authority wins at reveal" would break).
614
- if (e.fam?.opt && !projectionWriteActive && !getWriteOverride()) {
615
- tentativePBs.add(t);
616
- const n = e.n;
617
- if (n !== null) {
618
- for (const e of Reflect.ownKeys(n)) {
619
- const r = n[e];
620
- if (hasActiveOverride(r)) t[e] = unwrapOverride(r.o?.we);
621
- }
622
- }
623
- const r = e.h;
624
- if (r !== null) {
625
- for (const e of Reflect.ownKeys(r)) {
626
- const n = r[e];
627
- if (hasActiveOverride(n) && !unwrapOverride(n.o?.we)) delete t[e];
628
- }
629
- }
630
- }
631
- queueFold(e);
632
- }
633
- return t;
634
- }
635
-
636
- /** Sentinel holder for `t.ht`: a latest()-pull staged this adoption outside
637
- * any transition — the hold lasts until the fold commit (drainFolds). */ const PLAIN_HOLD = Symbol("plainHold");
638
-
639
- /** True while a latest() read is pulling the projection computed up to date
640
- * (see the get trap): adoptions landing during the pull are speculative
641
- * against the un-flushed batch and stage a held view. (Not injectable — the
642
- * derived createStore overload retains projection machinery in every store
643
- * bundle, see treeshake.test.ts.) */ let latestPullActive = false;
644
-
645
- /** Resolve the held committed view (#3074): answers the masked old backing
646
- * while the hold is live, and lazily clears a hold whose transition has
647
- * committed (transitions merge — resolve through currentTransition, same as
648
- * foldHeld's node stamps). */ function heldMaskView(e) {
649
- const t = e.ht;
650
- if (t === null) return null;
651
- if (t !== PLAIN_HOLD && currentTransition(t)?.Dt === true) return e.ht = e.hv = null;
652
- return e.hv;
653
- }
654
-
655
- /**
656
- * Adoption (2026-08-16c): the incoming object becomes the committed backing
657
- * IMMEDIATELY — reconcile is eagerly visible to every reader (shipped
658
- * contract; only its notifications batch), unlike setter writes which stay
659
- * pending until flush. Ownership resets (incoming is unowned/user data). Any
660
- * staged draft clone folds into the diff and is discarded — next is the
661
- * authoritative base (R21/R32).
662
- */ function adoptPB(e, t, n = false) {
663
- // Eager mode (plain-store adoption): the caller notifies inline after its
664
- // descent — no foldOlds queue/drain round trip (the reconcile diff IS the
665
- // fold diff; ~half of dbmon tick time was this duplication).
666
- if (!n) {
667
- queueFold(e);
668
- // records the pre-batch old before we swap
669
- // Diff base = the view the nodes were last told (#3296). A draft's
670
- // setter-exit notifications already moved them to its pending backing,
671
- // so a later adoption diffs against THAT — against committed, a key the
672
- // draft changed and the adoption restores would never re-notify. An
673
- // adoption with no draft leaves nodes where they were: keep an existing
674
- // base, else the pre-batch committed (foldOlds' entry itself stays the
675
- // committed identity for the path-copy CAS). Eager callers read t.pb
676
- // directly; this hand-off exists because pb is gone by drain time.
677
- if (e.pb !== null) {
678
- if (e.ovl) materializePB(e);
679
- e.ab = e.pb;
680
- } else e.ab ??= foldOlds.get(e);
681
- }
682
- // #3074/#3075: a projection recompute deriving from uncommitted inputs
683
- // swaps the backing SPECULATIVELY — committed-visibility readers must
684
- // keep the pre-hold view until the hold resolves (a source held by a
685
- // live transition, or a latest()-pull ahead of the flush). Post-await
686
- // landings (write-override) stay immediately visible — landed truth —
687
- // and clear any hold. Optimistic families hold too (#3330 store twin):
688
- // their tentative edits ride the lane machinery, but a sync derive
689
- // adopting under a transaction is held TRUTH like any projection's —
690
- // unheld, handlers read it early and an optimistic write equal to it
691
- // compared as a no-op against the swapped-in backing. A plain store's
692
- // reconcile inside an action holds the same way: its nodes stage under the
693
- // transaction (the inline notify), and the backing must not show handlers
694
- // and stale readers what the tracked read masks (signal parity, #3336).
695
- if (getWriteOverride()) {
696
- e.ht = e.hv = null;
697
- } else if (activeTransition !== null || !n && latestPullActive) {
698
- if (heldMaskView(e) === null) e.hv = e.v;
699
- e.ht = activeTransition ?? PLAIN_HOLD;
700
- if (!n && activeTransition !== null) heldAdoptions.add(e);
701
- }
702
- e.pb = null;
703
- // Overlay and accessor-scan state describe the OUTGOING backing — a
704
- // swapped container must not inherit them: a stale `ovl` beside a nulled
705
- // pb crashes materializePB (unwrapValue consults ovl before the
706
- // null-coalesce), a stale `del` would read the adoptee's keys as deleted
707
- // in the next draft, and a stale plain-data verdict (`sc`/`a`) could
708
- // admit an accessor-bearing adoptee to the overlay path. Reset; the next
709
- // draft rescans once (#3044 audit follow-up).
710
- e.ovl = false;
711
- e.del = null;
712
- e.sc = 0;
713
- e.a = false;
714
- e.wk = null;
715
- // adoption supersedes staged trap writes
716
- e.v = t;
717
- e.ch = t[$TARGET] !== undefined;
718
- // An adoptee we own within this family (a draft aliasing one of the
719
- // family's own backings) re-stamps to its new owner — the stamp is the
720
- // family's registration for it; everything else registers in the map.
721
- const r = t[$OWNER];
722
- if (r !== undefined && r.fam === e.fam) t[$OWNER] = e; else (e.fam?.map ?? storeNextLookup).set(t, e);
723
- }
724
-
725
- /** Sentinel for `t.wk`: the written-keys bound is unusable this batch (an
726
- * array length write implicitly deleted indices) — consumers full-scan. */ const WK_ALL = new Set;
727
-
728
- const plainProto = e => {
729
- const t = Object.getPrototypeOf(e);
730
- return t === Object.prototype || t === Array.prototype || t === null;
731
- };
732
-
733
- function queueFold(e) {
734
- if (foldOlds.has(e)) return;
735
- if (!hookInstalled) {
736
- hookInstalled = true;
737
- setStoreCommitHook(drainFolds);
738
- }
739
- // Always arm — "map non-empty ⇒ drain scheduled" is NOT an invariant: a
740
- // held re-queue, or an incomplete-transition flush (which skips
741
- // commitPendingNodes entirely), leaves entries behind after `scheduled`
742
- // was consumed. A size-gated arm then strands every LATER fold — queued
743
- // silently, never drained, committed base frozen at stale state while its
744
- // nodes commit (#3089). schedule() early-returns when already armed.
745
- schedule();
746
- foldOlds.set(e, e.v);
747
- }
748
-
749
- /** Fold write-attribution (#3089): a draft written while a transition is
750
- * active belongs to that transition — its fold must not commit before the
751
- * transition settles. Observed keys already defer through the held check in
752
- * drainFolds (their nodes carry _pendingValue); this write-time stamp is the
753
- * equivalent hold for UNOBSERVED keys, which have no node to consult.
754
- * Refreshed on every write; resolved through currentTransition at drain
755
- * (transitions merge — same rule as heldMaskView). */ const foldBatches = new WeakMap;
756
-
757
- /** Parked truth-staged pending backings (#3164 fold): a tentative draft that
758
- * opens while a folded landing's backing is live moves the staged container
759
- * here (see ensurePB); the tentative discard in notifyOptimisticWrites
760
- * restores it in place of the usual null. */ const stagedTruthPB = new WeakMap;
761
-
762
- /** Backings opened by TENTATIVE drafts (optimistic user setters): ensurePB's
763
- * truth-park must not fire against the draft's own container on its second
764
- * and later writes (the first write stamps foldBatches whenever an action's
765
- * transition is ambient). Entries die with their draft — tentative backings
766
- * are consumed at setter exit. */ const tentativePBs = new WeakSet;
767
-
768
- /** A draft read composes the live optimistic view until the draft has opened
769
- * its OWN view-seeded backing (ensurePB seeds that clone from the view and
770
- * registers it in tentativePBs; from then on reads must see the draft's
771
- * writes, not the overrides they superseded). A pending backing that exists
772
- * for any other reason is not that clone — a truth landing staged into a
773
- * retaining transaction (#3164 fold) is authoritative truth WITHOUT the
774
- * live overrides. ensurePB parks such a backing on the draft's first WRITE
775
- * and reseeds from the view, but the reads that precede that write went to
776
- * the staged truth: `votes++` read base, wrote base+1, and the override it
777
- * emitted landed on the value already displayed — a second in-flight
778
- * increment made after a sibling's landing was invisible (#2951's compose
779
- * half, one landing later). */ function draftSeesOverrides(e) {
780
- return e.pb === null || !tentativePBs.has(e.pb);
781
- }
782
-
783
- /** Committed-time privatization for parent-chain slot updates (path copying). */ function privatizeCommitted(e) {
784
- if (isOwned(e.v)) return;
785
- const t = e.v;
786
- const n = cloneRaw(t, e);
787
- e.v = n;
788
- e.ch = false;
789
- if (e.u) {
790
- privatizeCommitted(e.u);
791
- devAssertNeverUserMutation(e.u.v);
792
- // CAS, same as drainFolds' path copy: re-point the parent slot only
793
- // while it still holds the raw we cloned. A parent that folded EARLIER
794
- // in this drain may have replaced or deleted this slot (the same batch
795
- // wrote the child and then `parent.row = fresh` / `parent.length = 0`)
796
- // — an unconditional write resurrected the dropped child over it.
797
- const n = e.u.v;
798
- const r = parentSlotKey(e, t);
799
- if (n[r] === t) n[r] = e.v;
800
- }
801
- }
802
-
803
- /** Resolve the slot this child currently occupies in its parent's committed
804
- * backing (#3282). `pk` is stamped at wrap time and arrays MOVE: a reverse/
805
- * unshift/splice relocates the raw, and a fold that re-points the wrap-time
806
- * slot writes the clone over whichever row lives there now. Objects never
807
- * move keys, so the stamp is authoritative; for arrays, verify and re-locate
808
- * by identity when stale (fold-time only — never on a read path). */ function parentSlotKey(e, t) {
809
- const n = e.pk;
810
- const r = e.u.v;
811
- if (r[n] === t || !Array.isArray(r)) return n;
812
- const i = r.indexOf(t);
813
- if (i === -1) return n;
814
- e.pk = i;
815
- return i;
816
- }
817
-
818
- /** Overlay commit (#3044): apply the batch's writes onto an OWNED committed
819
- * backing in place — O(written), not O(container). Unowned backings
820
- * privatize first (clone once, parents re-slotted) — the never-mutate-user-
821
- * data contract holds. Shared by the deferred fold (drainFolds) and the
822
- * projection landing's immediate commit (notifyWrites). */ function flattenOverlay(e, t) {
823
- privatizeCommitted(e);
824
- const n = e.v;
825
- // Plain-data grade (sc 2): every own key on the overlay is an enumerable
826
- // writable data slot (set-trap writes; a non-plain defineProperty
827
- // downgrades the grade) — a bare assignment lands it without the
828
- // descriptor round trip.
829
- for (const r of Reflect.ownKeys(t)) e.sc === 2 ? n[r] = t[r] : copyOwn(n, t, r);
830
- if (e.del !== null) {
831
- for (const t of e.del) delete n[t];
832
- e.del = null;
833
- }
834
- e.pb = null;
835
- e.ovl = false;
836
- e.wk = null;
837
- // written-keys window closes with the commit
838
- }
839
-
840
- function drainFolds() {
841
- if (foldOlds.size === 0) return;
842
- const e = [ ...foldOlds ];
843
- foldOlds.clear();
844
- for (const [t, n] of e) {
845
- // A latest()-pull staging holds only until the fold commit: this flush
846
- // is committing the batch the pull ran ahead of. Transition holds stay —
847
- // they clear when their transition is done (heldMaskView).
848
- if (t.ht === PLAIN_HOLD) t.ht = t.hv = null;
849
- if (t.pb !== null) {
850
- // #3089: a fold written under a still-running transition defers to
851
- // that transition's settle (the write-time stamp covers unobserved
852
- // keys; observed keys also hit the pending-node held check below).
853
- const e = foldBatches.get(t);
854
- if (e !== undefined) {
855
- if (currentTransition(e).Dt === false) {
856
- foldOlds.set(t, n);
857
- continue;
858
- }
859
- foldBatches.delete(t);
860
- }
861
- // Setter path: nodes were setSignal'd at setter exit (write-time
862
- // notification — transitions/holds ride core machinery). Commit the
863
- // backing only for keys whose nodes have committed; a still-pending
864
- // node (transition-held) re-queues the target for the settling flush.
865
- let r = false;
866
- const i = t.pb;
867
- const o = t.n;
868
- if (o !== null) {
869
- // Only written keys can hold (their nodes took the setSignal); the
870
- // wk bound keeps this O(written) — see notifyWrites. Same fallback
871
- // rules as the notify (WK_ALL / accessors / non-plain prototypes).
872
- const e = t.wk;
873
- const n = e === null || e === WK_ALL || t.a === true ||
874
- // Overlay pbs chain to the COMMITTED object (#3044) — plainness is
875
- // the committed container's prototype, not the overlay's.
876
- !plainProto(t.ovl ? t.v : i) ? Reflect.ownKeys(o) : e;
877
- for (const e of n) {
878
- const t = o[e];
879
- if (t !== undefined && t._e !== NOT_PENDING) {
880
- r = true;
881
- break;
882
- }
883
- }
884
- }
885
- if (r) {
886
- foldOlds.set(t, n);
887
- // re-queue: commit happens when the hold settles
888
- continue;
889
- }
890
- if (t.ovl) {
891
- // Overlay flatten (#3044): the backing keeps its identity, so the
892
- // `t.v === old` gate below skips path copying (the parent slot
893
- // already points here) and the adopted-notify (setter notifications
894
- // happened at write time).
895
- flattenOverlay(t, i);
896
- } else if (t.v !== n) {
897
- // Privatized mid-batch (#3271): an earlier fold in this drain
898
- // path-copied THROUGH this target — privatizeCommitted cloned the
899
- // committed backing, re-pointed the parent slot at the clone, and
900
- // stitched the descendant's fold into it. The draft's pb predates
901
- // that: swapping it in would clobber the descendant's fold, and the
902
- // parent CAS below (still comparing against `old`) would fail and
903
- // orphan this fold entirely — a projection draft writing descendant-
904
- // then-ancestor silently lost the ancestor write. Merge the batch's
905
- // writes onto the current container instead (the parent slot already
906
- // points at it). privatize first: an adopt-then-write batch can land
907
- // here with an unowned adoptee as t.v.
908
- privatizeCommitted(t);
909
- const e = t.v;
910
- const r = t.wk;
911
- if (r !== null && r !== WK_ALL) {
912
- // The trap records every write/delete key — apply exactly those.
913
- for (const t of r) {
914
- if (hasOwn.call(i, t)) copyOwn(e, i, t); else delete e[t];
915
- }
916
- } else {
917
- // Array length write poisoned the bound (WK_ALL) — value-diff
918
- // against the pre-batch old. Slots the draft never touched hold
919
- // the same raw reference in both, so descendant folds stay put.
920
- // Not copyOwn: the plain-value write is GATED on "the draft changed
921
- // this slot" — an untouched slot in pb holds the pre-batch reference,
922
- // and writing it back would clobber a descendant fold stitched into v.
923
- for (const t of Reflect.ownKeys(i)) {
924
- const r = Object.getOwnPropertyDescriptor(i, t);
925
- if (r.get || r.set || !r.enumerable || !r.writable || !r.configurable) Object.defineProperty(e, t, r); else if (r.value !== n[t] || !hasOwn.call(n, t)) e[t] = r.value;
926
- }
927
- for (const t of Reflect.ownKeys(n)) {
928
- if (!hasOwn.call(i, t)) delete e[t];
929
- }
930
- }
931
- t.pb = null;
932
- t.wk = null;
933
- // written-keys window closes with the fold commit
934
- } else {
935
- t.v = i;
936
- t.ch = false;
937
- // pb is always a plain clone
938
- t.pb = null;
939
- t.wk = null;
940
- // written-keys window closes with the fold commit
941
- }
942
- }
943
- const e = t.ab;
944
- t.ab = null;
945
- if (t.v !== n) {
946
- // Path copying (CAS: see the eager-fold twin above). Slot resolved by
947
- // identity (#3282): an array move relocated the raw, so the wrap-time
948
- // pk may point at a sibling — a raw-slot CAS there both failed to
949
- // re-point AND (via privatizeCommitted's unguarded write) clobbered
950
- // the sibling.
951
- if (t.u) {
952
- const e = parentSlotKey(t, n);
953
- if (t.u.v[e] === n) {
954
- privatizeCommitted(t.u);
955
- devAssertNeverUserMutation(t.u.v);
956
- t.u.v[e] = t.v;
957
- }
958
- }
959
- }
960
- // Adoption notify against the base the nodes were last told (#3296). A
961
- // no-op adoption (A -> B -> A before flush, no draft) has base === v and
962
- // nothing to say; a draft superseded by an adoption back to the SAME raw
963
- // still has (base = pending backing) !== v and must notify.
964
- if (e !== null && e !== t.v) notifyFold(t, e, t.v);
965
- }
966
- }
967
-
968
- /** Dev: dotted path of a target from its store root (`store.user.address`). */ function storePath(e) {
969
- let t = "";
970
- for (let n = e; n !== null; n = n.u) t = n.pk === null ? "store" + t : "." + String(n.pk) + t;
971
- return t;
972
- }
973
-
974
- /**
975
- * Dev (attribution engine installed): announce written keys whose old and new
976
- * values are both containers but different logical slots — the raw material
977
- * for the spread-copy diagnostic. The engine owns the verdict.
978
- */ function reportReplacedContainers(e, t, n, r) {
979
- const i = r ?? Reflect.ownKeys(n);
980
- const o = Array.isArray(n);
981
- const l = storeRootOwner(e);
982
- for (const r of i) {
983
- if (o && r === "length" || r === $OWNER) continue;
984
- if (e.del !== null && e.del.has(r)) continue;
985
- const i = unwrapValue(t[r]);
986
- const s = unwrapValue(n[r]);
987
- if (i === null || s === null || typeof i !== "object" || typeof s !== "object" || i === s || targetsEqual(i, s)) continue;
988
- // Leaf census on the store side: leaves read through a draft are proxies
989
- // of the committed raws, so identity must be judged on unwrapped values.
990
- const f = Array.isArray(s);
991
- if (f !== Array.isArray(i)) continue;
992
- let u;
993
- let a = 0;
994
- if (f) {
995
- u = s.length;
996
- if (u > REPLACED_CENSUS_MAX) continue;
997
- const e = new Set;
998
- for (const t of i) e.add(unwrapValue(t));
999
- for (const t of s) if (e.has(unwrapValue(t))) a++;
1000
- } else {
1001
- const e = Object.keys(s);
1002
- u = e.length;
1003
- if (u > REPLACED_CENSUS_MAX) continue;
1004
- for (const t of e) if (sameLeaf(i[t], s[t])) a++;
1005
- }
1006
- attrHooks.storeReplaced(storePath(e) + "." + String(r), f, u, a, f ? i.length : Object.keys(i).length, l);
1007
- }
1008
- }
1009
-
1010
- const REPLACED_CENSUS_MAX = 64;
1011
-
1012
- function sameLeaf(e, t) {
1013
- if (e === t) return true;
1014
- if (e === null || t === null || typeof e !== "object" || typeof t !== "object") return false;
1015
- return unwrapValue(e) === unwrapValue(t) || targetsEqual(e, t);
1016
- }
1017
-
1018
- /**
1019
- * Setter-exit notification (write channel): diff the draft's pending backing
1020
- * against committed and setSignal every changed OBSERVED key — write-time
1021
- * notification with commit deferred to node commit, so transition holds,
1022
- * isPending, affects, and lane machinery ride the core natively (§3's
1023
- * "pending home = the node when a node exists"). Unobserved keys stay in the
1024
- * pending backing and fold directly at commit.
1025
- */ function notifyWrites(e) {
1026
- let t = e.pb;
1027
- if (t === null) return;
1028
- // Optimistic channel: user writes on an optimistic family become node-level
1029
- // engine writes (armed nodes route setSignal through optimisticWrite) — the
1030
- // committed backing is NEVER touched; the draft clone is discarded. Reverts,
1031
- // per-transaction ownership, and flash-at-flush are all core-native.
1032
- // Projection recompute writes (projectionWriteActive) and projection draft
1033
- // writes (write-override, incl. post-await async landings) are
1034
- // authoritative and take the plain channel below (they commit silently
1035
- // under overrides per the engine's no-revert-stash contract).
1036
- if (e.fam?.opt) {
1037
- if (!projectionWriteActive && !getWriteOverride()) {
1038
- optHooks.notifyOptimisticWrites(e, t);
1039
- return;
1040
- }
1041
- // Authoritative path on an optimistic family: armed nodes must commit
1042
- // silently (engine bypass) — without this, a landing's setSignals would
1043
- // create lanes and block their own transition's settle.
1044
- if (!projectionWriteActive) {
1045
- setProjectionWriteActive(true);
1046
- try {
1047
- notifyWrites(e);
1048
- } finally {
1049
- setProjectionWriteActive(false);
1050
- }
1051
- return;
1052
- }
1053
- }
1054
- const n = e.v;
1055
- const r = e.n;
1056
- // Written-keys bound: trap writes record their keys, so the notify visits
1057
- // O(written) nodes instead of every subscription on the record (a selection
1058
- // map with thousands of per-key subscribers pays two visits per select,
1059
- // not a full scan). Falls back to the full node scan when the bound can't
1060
- // hold: no trap granularity (wk null), an array length write (WK_ALL —
1061
- // implicit index deletes), accessors on the record (t.a — a getter node's
1062
- // value can change when ANY key is written), or a non-plain prototype
1063
- // (class instances: prototype getters derive from arbitrary fields).
1064
- const i = e.wk;
1065
- // Overlay pbs chain to the COMMITTED object (#3044): a prototype-overlay
1066
- // draft is plain data on its own layer, but its getPrototypeOf is the
1067
- // committed container — judge plainness by the COMMITTED prototype or the
1068
- // bound never engages for overlay writes (every plain-object setter batch
1069
- // would full-scan: the exact selection-map workload wk exists for; jf
1070
- // `select` regressed 2x on this).
1071
- const o = i === WK_ALL || e.a === true || !plainProto(e.ovl ? e.v : t) ? null : i;
1072
- if (attrHooks !== null) reportReplacedContainers(e, n, t, o);
1073
- if (r !== null) {
1074
- const i = o ?? Reflect.ownKeys(r);
1075
- for (const o of i) {
1076
- const i = r[o];
1077
- if (i === undefined) continue;
1078
- // Per-key accessor handling: the node's cached flag plus ONE getter
1079
- // probe on the incoming side (getters arriving via merge/adoption).
1080
- // Setter-only props read as data (value undefined) so lookupSetter is
1081
- // not consulted on this hot path; prototype getters never own nodes.
1082
- if (i.acc === true || hasOwn.call(t, o) && lookupGetter.call(t, o) !== undefined) {
1083
- i.acc = isOwnAccessor(t, o);
1084
- const e = Object.getOwnPropertyDescriptor(n, o);
1085
- const r = Object.getOwnPropertyDescriptor(t, o);
1086
- if (e && (e.get || e.set) || r && (r.get || r.set)) {
1087
- if (e?.get !== r?.get || e?.set !== r?.set || e?.value !== r?.value) setSignal(i, () => FORCE);
1088
- continue;
1089
- }
1090
- if (!isEqual(e?.value, r?.value)) setSignal(i, () => r?.value);
1091
- continue;
1092
- }
1093
- // No old-side pre-compare: t.v lags across multi-batch windows (a
1094
- // projection recompute can run before the prior fold commits) — the
1095
- // node's OWN current value is the true old side, and setSignal's
1096
- // internal equality already checks exactly that.
1097
- const l = e.del !== null && e.del.has(o) ? undefined : t[o];
1098
- // The derived store's setter reaching a leaf its own fold staged under
1099
- // another transaction: not a proposal — the fold re-runs (#3612).
1100
- if (derivedSetter !== null && i.Ne === derivedSetter && heldDerivation(i)) heldDerivationHit = true;
1101
- setSignal(i, () => l);
1102
- }
1103
- }
1104
- const l = e.h;
1105
- if (l !== null) {
1106
- const n = o ?? Reflect.ownKeys(l);
1107
- for (const r of n) {
1108
- const n = l[r];
1109
- if (n !== undefined) setSignal(n, r in t && !(e.del !== null && e.del.has(r)));
1110
- }
1111
- }
1112
- // Deep-witness (dk): setter writes must notify a deep() subscriber even on
1113
- // keys with no node. O(written/pb keys) equality only when a witness exists.
1114
- if (e.dk !== null) {
1115
- if (e.del !== null && e.del.size !== 0) bumpDeep(e); else for (const r of o ?? Reflect.ownKeys(t)) {
1116
- if (r === $OWNER) continue;
1117
- const i = t[r];
1118
- const o = n[r];
1119
- if (i !== null && typeof i === "object" ? !targetsEqual(o, i) : !isEqual(o, i)) {
1120
- bumpDeep(e);
1121
- break;
1122
- }
1123
- }
1124
- }
1125
- if (e.k !== null) {
1126
- let r;
1127
- if (e.ovl) {
1128
- // Overlay membership: only NEW own keys or deletes can change it.
1129
- r = e.del !== null && e.del.size !== 0;
1130
- if (!r) {
1131
- for (const e of Reflect.ownKeys(t)) {
1132
- if (!hasOwn.call(n, e)) {
1133
- r = true;
1134
- break;
1135
- }
1136
- }
1137
- }
1138
- } else {
1139
- r = Array.isArray(t) && Array.isArray(n) ? arrayStructureChanged(n, t) : membershipChanged(n, t);
1140
- }
1141
- if (r) setSignal(e.k, e => e + 1);
1142
- }
1143
- // Projection backing folds split by channel (two pinned contracts):
1144
- // - sync-derive drafts (recompute body): NEVER eager — a downstream async
1145
- // hold can form LATER in the same flush and the leaf must stay at stale
1146
- // committed for context-free readers (spec-async "pends only the written
1147
- // leaf"). drainFolds commits when held-ness is knowable.
1148
- // - post-await async LANDINGS (write-override per-op, microtask context —
1149
- // no enclosing flush can capture them): the data-level commit is
1150
- // IMMEDIATE — landed truth shows to untracked readers even while a
1151
- // downstream consumer's own async still holds the effect-level reveal
1152
- // (spec-async "verdicts never inherit consumers' in-flight state").
1153
- // EXCEPT under an active transaction (#3164 fold): a landing riding a
1154
- // retaining transaction (the optimistic module's aroundWrite binds it)
1155
- // stages instead — ensurePB stamped foldBatches, so the backing commits
1156
- // with the transaction and the reveal is atomic at settle. The pinned
1157
- // immediate-commit contract is stated over the no-transaction microtask
1158
- // posture, which `activeTransition === null` is exactly.
1159
- if (e.fam !== null && e.pb !== null && getWriteOverride() && activeTransition === null) {
1160
- // Landed truth (post-await write-override): immediately visible to every
1161
- // reader — any staged held view is superseded.
1162
- if (e.ht !== null) e.ht = e.hv = null;
1163
- // Overlay landing (#3352): flatten in place — identity-stable, and
1164
- // privatizeCommitted re-slots the parent itself when it has to clone an
1165
- // unowned seed, so no path copy is needed.
1166
- if (e.ovl) return flattenOverlay(e, t);
1167
- const n = e.v;
1168
- e.pb = null;
1169
- e.v = t;
1170
- e.ch = false;
1171
- if (e.u) {
1172
- // Identity-resolved slot (#3282) — see drainFolds' path-copy twin.
1173
- const r = parentSlotKey(e, n);
1174
- if (e.u.v[r] === n) {
1175
- privatizeCommitted(e.u);
1176
- devAssertNeverUserMutation(e.u.v);
1177
- e.u.v[r] = t;
1178
- }
1179
- }
1180
- }
1181
- }
1182
-
1183
- const FORCE = Symbol();
1184
-
1185
- /** Same logical slot: both values resolve to one (re-pointed) child target —
1186
- * adoption preserved identity, so the slot did not change (R9). */ function targetsEqual(e, t) {
1187
- if (e === null || typeof e !== "object" || t === null || typeof t !== "object") return false;
1188
- const n = lookupTarget(e, null);
1189
- return n !== undefined && n === lookupTarget(t, null);
1190
- }
1191
-
1192
- function arrayStructureChanged(e, t) {
1193
- if (e.length !== t.length) return true;
1194
- for (let n = 0; n < t.length; n++) {
1195
- const r = e[n];
1196
- const i = t[n];
1197
- if (!isEqual(r, i) && !targetsEqual(r, i)) return true;
1198
- }
1199
- return false;
1200
- }
1201
-
1202
- function membershipChanged(e, t) {
1203
- const n = Reflect.ownKeys(t);
1204
- // The $OWNER stamp is not membership: an owned side counts one key more.
1205
- if (Reflect.ownKeys(e).length - +isOwned(e) !== n.length - +isOwned(t)) return true;
1206
- for (const t of n) if (t !== $OWNER && !(t in e)) return true;
1207
- return false;
1208
- }
1209
-
1210
- /**
1211
- * The fold diff walks SUBSCRIPTION KEYS ONLY (legacy parity: `for key in
1212
- * nodes`): nodes exist exactly where something tracked, so unobserved data
1213
- * costs nothing here regardless of object size. Accessor safety rides the
1214
- * sticky `t.a` flag — a node's key was necessarily read, so the get trap has
1215
- * already seen whether it is an accessor.
1216
- */
1217
- /** One node's fold notification (shared by notifyFold's walk and the fused
1218
- * adoption walk): accessor-aware compare + equality/identity-gated setSignal. */ function notifyKeyDiff(e, t, n, r,
1219
- // The incoming-side getter probe covers SETTER-channel arrivals (return-
1220
- // form merges, defineProperty) — those flow through notifyWrites/
1221
- // notifyFold, which probe. The RECONCILE channel (fused walk) passes
1222
- // false: reconcile adopts immutable data by contract (R2a) and the pinned
1223
- // getter-preservation tests are all setter-channel; skipping ~2 Annex-B
1224
- // calls per key per tick is a measured dbmon win.
1225
- i = true) {
1226
- if (e.acc === true || i && hasOwn.call(r, t) && lookupGetter.call(r, t) !== undefined) {
1227
- e.acc = isOwnAccessor(r, t);
1228
- const i = Object.getOwnPropertyDescriptor(n, t);
1229
- const o = Object.getOwnPropertyDescriptor(r, t);
1230
- if (i && (i.get || i.set) || o && (o.get || o.set)) {
1231
- // Accessor involved: never invoke; force-notify on shape change so
1232
- // subscribers re-read (and re-track) through the trap.
1233
- if (i?.get !== o?.get || i?.set !== o?.set || i?.value !== o?.value) setSignal(e, () => FORCE);
1234
- return;
1235
- }
1236
- const l = i?.value;
1237
- const s = o?.value;
1238
- if (!isEqual(l, s) && !targetsEqual(l, s)) setSignal(e, typeof s === "function" ? () => s : s);
1239
- } else {
1240
- const i = n[t];
1241
- const o = r[t];
1242
- // Direct value write when not a function (setSignal treats functions as
1243
- // updaters) — saves a closure allocation per changed key on the fold
1244
- // hot path.
1245
- if (!isEqual(i, o) && !targetsEqual(i, o)) setSignal(e, typeof o === "function" ? () => o : o);
1246
- }
1247
- }
1248
-
1249
- /** Accessor-flag probe for the fused walk's early-continue (accessor keys
1250
- * can never identity-skip: their VALUE is the descriptor's product). */ function hasAccessorFlag(e) {
1251
- return e.acc === true;
1252
- }
1253
-
1254
- /** Fused-walk per-key notification with values already in hand: the caller
1255
- * fetched both sides and handled the identity skip; this applies the
1256
- * accessor branch (cached flag only — reconcile channel) or the plain
1257
- * equality/identity-gated write. */ function notifyKeyValue(e, t, n, r, i, o) {
1258
- if (e.acc === true) {
1259
- notifyKeyDiff(e, t, i, o, false);
1260
- return;
1261
- }
1262
- // The pre-compare is NOT redundant with the node's equals: setSignal parks
1263
- // a pending value and registers with the batch before equality applies at
1264
- // commit (RUL-1), so identity-preserved slots (adopted child containers —
1265
- // every row's fresh `queries` array) must be gated out HERE or each one
1266
- // pays the full write machinery every tick (measured: +0.5ms/tick dbmon).
1267
- if (!isEqual(n, r) && !targetsEqual(n, r)) setSignal(e, typeof r === "function" ? () => r : r);
1268
- }
1269
-
1270
- /** Presence + membership halves of a fold notification (shared tail). */ function notifyFoldTail(e, t, n) {
1271
- const r = e.h;
1272
- if (r !== null) {
1273
- for (const e of Reflect.ownKeys(r)) setSignal(r[e], e in n);
1274
- }
1275
- if (e.k !== null) {
1276
- const r = Array.isArray(n) && Array.isArray(t) ? arrayStructureChanged(t, n) : membershipChanged(t, n);
1277
- if (r) setSignal(e.k, e => e + 1);
1278
- }
1279
- }
1280
-
1281
- function notifyFold(e, t, n) {
1282
- if (e.dk !== null && t !== n) bumpDeep(e);
1283
- // Optimistic targets: adoption notifications are authoritative landings —
1284
- // bypass the engine (commit into _value; active overrides keep shadowing
1285
- // until their transaction settles, per the no-revert-stash contract).
1286
- if (e.fam?.opt && !projectionWriteActive) {
1287
- setProjectionWriteActive(true);
1288
- try {
1289
- notifyFold(e, t, n);
1290
- } finally {
1291
- setProjectionWriteActive(false);
1292
- }
1293
- return;
1294
- }
1295
- const r = e.n;
1296
- if (r !== null) {
1297
- for (const e of Reflect.ownKeys(r)) {
1298
- notifyKeyDiff(r[e], e, t, n);
1299
- }
1300
- }
1301
- const i = e.h;
1302
- if (i !== null) {
1303
- for (const e of Reflect.ownKeys(i)) setSignal(i[e], e in n);
1304
- }
1305
- if (e.k !== null) {
1306
- // Key-set/$TRACK: objects notify on membership; arrays on any index or
1307
- // length change (mapArray and iteration re-read values — R15).
1308
- const r = Array.isArray(n) && Array.isArray(t) ? arrayStructureChanged(t, n) : membershipChanged(t, n);
1309
- if (r) setSignal(e.k, e => e + 1);
1310
- }
1311
- }
1312
-
1313
- // ---------------------------------------------------------------------------
1314
- // traps
1315
- /** >0 while inside a setter: writes allowed, reads are read-your-writes. */ let writing = 0;
1316
-
1317
- /** Write scope keys (a family object or a plain store's root target): draft
1318
- * semantics — write permission, read-your-writes, tracking suppression —
1319
- * apply ONLY to targets under a scope being written. Reads of OTHER stores
1320
- * inside a setter track normally (they are dependencies: a projection derive
1321
- * reading another store must link it). */ let writeScopes = null;
1322
-
1323
- function scopeKey(e) {
1324
- if (e.fam !== null) return e.fam;
1325
- let t = e;
1326
- while (t.u !== null) t = t.u;
1327
- return t;
1328
- }
1329
-
1330
- function inDraft(e) {
1331
- return writeScopes !== null && writeScopes.has(scopeKey(e));
1332
- }
1333
-
1334
- /** Shallow serve rule (#2932): raw-marked data serves VERBATIM, but a
1335
- * store-proxy slot value gets a boundary wrapper in THIS store's own family —
1336
- * write isolation through derived chains (downstream writes must never land
1337
- * upstream). markRawOne skips proxies for exactly this reason. */ function serveShallow(e, t, n) {
1338
- if (n !== null && typeof n === "object" && n[$TARGET] !== undefined) return draftServe(e, wrapNext(n, e, t));
1339
- return n;
1340
- }
1341
-
1342
- /** Draft reads extend write permission to reachable stores (legacy Writing
1343
- * semantics: wrapping a child through a draft get admits it — cross-store
1344
- * writes like `s.inner.a = 10` work when `inner` is another store's proxy). */ function draftServe(e, t) {
1345
- if (writeScopes !== null && inDraft(e)) {
1346
- const e = t?.[$TARGET];
1347
- if (e !== undefined && e.v !== undefined) writeScopes.add(scopeKey(e));
1348
- }
1349
- return t;
1350
- }
1351
-
1352
- /** Targets written during the current (outermost) setter — notified at exit. */ const pendingNotify = new Set;
1353
-
1354
- /** Targets adopted under a live transaction this setter (adoptPB set a
1355
- * transaction hold) — their nodes are notified at the outermost exit. */ const heldAdoptions = new Set;
1356
-
1357
- /**
1358
- * Write-time notification for a transaction-held adoption (#3330 store twin;
1359
- * the setter path's notifyWrites twin for adoptions). A projection's fold
1360
- * normally notifies its nodes at the drain — and the drain of a batch parked
1361
- * in a live transaction is the transaction's COMMIT, so the nodes took the
1362
- * adopted values as fresh writes at commit time: every subscriber was
1363
- * re-marked and re-ran against a frame the lane had already published (a
1364
- * third `v=1 d=2`), where a signal's write had staged at write time and
1365
- * promoted silently. Staging here, inside the transaction's batch, makes the
1366
- * two paths one: the nodes carry transition-stamped `_pendingValue`s, their
1367
- * subscribers recompute in this flush and park with the transaction, and the
1368
- * commit promotes without re-notifying. `ab` moves to the adopted backing —
1369
- * the view the nodes were last told (#3296) — so the drain has nothing left
1370
- * to say and only path-copies.
1371
- */ function stageHeldAdoptions() {
1372
- const e = [ ...heldAdoptions ];
1373
- heldAdoptions.clear();
1374
- for (const t of e) {
1375
- const e = t.ab;
1376
- if (e === null || e === t.v) continue;
1377
- notifyFold(t, e, t.v);
1378
- t.ab = t.v;
1379
- }
1380
- }
1381
-
1382
- const UNSAFE_KEYS = new Set([ "__proto__", "prototype", "constructor" ]);
1383
-
1384
- /** Mirror of core read()'s context rule: the OWNER context (not the tracking
1385
- * observer) decides pending visibility, with Roots resolving to their parent
1386
- * computed (#2687 — untracked reads inside mapArray Roots see in-flight
1387
- * values mid-flush). CHILDREN_FORBIDDEN execution scopes (createTrackedEffect
1388
- * / onSettled callbacks) get COMMITTED visibility (#3006), same as core. */
1389
- /** Core read()'s reader: the current computation, a root reading as its
1390
- * parent computed (`context` persists under untrack — an untracked read
1391
- * inside an effect is still that effect's read). */ function readerContext() {
1392
- const e = getOwner();
1393
- return e === null ? null : e.Zt ? e.Yt ?? null : e;
1394
- }
1395
-
1396
- /** A pending fold is transition-held when any written node's parked value is
1397
- * stamped by a live transition (a plain batch parking — the lazy-recompute
1398
- * read case — has no transition stamp and serves fresh). */ function foldHeld(e) {
1399
- const t = e.n;
1400
- if (t === null) return false;
1401
- for (const e of Reflect.ownKeys(t)) {
1402
- const n = t[e];
1403
- if (n._e !== NOT_PENDING && n.me != null && n.me.Dt !== true) return true;
1404
- }
1405
- return false;
1406
- }
1407
-
1408
- function readSource(e) {
1409
- // Adoption hold first (#3074): an adoption staged under a live transaction
1410
- // (or a latest()-pull, PLAIN_HOLD) serves the pre-hold committed view to
1411
- // committed-visibility readers — context-free and children-forbidden ones,
1412
- // and stale passes off a foreign hold. Drafts, write-override and latest()
1413
- // see the adopted backing.
1414
- const t = e.ht;
1415
- if (t !== null && !latestReadActive && !inDraft(e) && !getWriteOverride()) {
1416
- const n = heldMaskView(e);
1417
- if (n !== null) {
1418
- const e = readerContext();
1419
- if (e === null || e.C & CONFIG_CHILDREN_FORBIDDEN || !holdVisible(t === PLAIN_HOLD ? null : currentTransition(t), e)) return n;
1420
- }
1421
- }
1422
- return pendingBackingVisible(e, false) ? e.pb : e.v;
1423
- }
1424
-
1425
- /** The single pb-vs-committed visibility decision (#3147), shared by per-key
1426
- * backing reads (readSource) and deep()/snapshot composition (snapshotWalk)
1427
- * so the two reader families can never disagree about a HELD landing.
1428
- *
1429
- * Signal-parity visibility (core read(): owner-context reads serve
1430
- * _pendingValue, context-free reads serve committed — effects recompute
1431
- * BEFORE commitPendingNodes in the flush, so the pending view must be
1432
- * servable). Drafts (setter window OR projection write-override) and
1433
- * owner-context reads see the pending backing; context-free reads see
1434
- * committed. Node reads apply the same rule, so all homes agree.
1435
- *
1436
- * `speculative` is deep()/snapshot's posture: an untrack/deep PEEK that sees
1437
- * ordinary pending staging regardless of owner context (the documented
1438
- * divergence from context-free per-key reads) — but never through a hold:
1439
- * held truth stays masked exactly as it is for per-key readers. */ function pendingBackingVisible(e, t) {
1440
- if (e.pb === null) return false;
1441
- // The writer's own channels compose on the pending backing regardless.
1442
- if (inDraft(e) || getWriteOverride()) return true;
1443
- // HELD truth on an optimistic family (#3164 fold) is masked from LANE
1444
- // passes until the transaction's reveal (the backing-level twin of core
1445
- // serve()'s CONFIG_HELD_TRUTH arm; authoritative postures and latest()
1446
- // tunnel through inside heldTruthMasked). Every other reader takes the
1447
- // hold arms below: committed for no pass, the staged backing for the
1448
- // holding pass, stale-of-foreign or A29 for a foreign one.
1449
- if (heldTruthMasked(e)) return false;
1450
- const n = readerContext();
1451
- if (n === null || n.C & CONFIG_CHILDREN_FORBIDDEN) {
1452
- // No pass, or a children-forbidden one: the committed frame (A32) —
1453
- // except the speculative peek (deep()/snapshot()), which sees ordinary
1454
- // pending staging but never through a live foreign hold, and a
1455
- // projection's pending backing, authoritative-elect for context-free
1456
- // readers UNLESS a transition holds the node commits (downstream async
1457
- // hold — stale committed is the contract; the write-time stamp covers
1458
- // keys with no node, #3336) or the scope is children-forbidden (#3082).
1459
- const r = liveFoldTransition(e);
1460
- if (t) return r === null || ownsHold(r);
1461
- return e.fam !== null && n === null && !foldHeld(e) && r === null;
1462
- }
1463
- return holdVisible(liveFoldTransition(e), n);
1464
- }
1465
-
1466
- /** #3164 fold: HELD truth on an optimistic family — a pending backing
1467
- * stamped by a live transition that retains optimism — is masked from LANE
1468
- * passes only (a lane paints display-ahead at the park, so it keeps
1469
- * committed until the transaction's reveal — owning transaction or not);
1470
- * the authoritative postures and latest() tunnel through, and every other
1471
- * reader is served by the ordinary hold arms (a deriving pass is held with
1472
- * the truth, A29). Un-stamped backings and optimism-free transitions keep
1473
- * ordinary mid-batch/speculation visibility. */ function heldTruthMasked(e) {
1474
- if (e.fam?.opt !== true || currentOptimisticLane === null || latestReadActive || authoritativeServe()) return false;
1475
- const t = foldBatches.get(e);
1476
- // opt families are only created by createOptimisticStore, whose module
1477
- // install populates optHooks — the assertion holds by construction.
1478
- return t !== undefined && optHooks.retainsOptimism(t);
1479
- }
1480
-
1481
- const hasOwn = Object.prototype.hasOwnProperty;
1482
-
1483
- // Allocation-free own-accessor probe (replaces eager descriptor scans — the
1484
- // single biggest creation cost in the uibench profile): Annex-B lookups
1485
- // return the fn or undefined with no descriptor object. Own data properties
1486
- // shadow prototype accessors, so hasOwn + lookup is an exact own-check.
1487
- const lookupGetter = Object.prototype.__lookupGetter__;
1488
-
1489
- const lookupSetter = Object.prototype.__lookupSetter__;
1490
-
1491
- const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
1492
-
1493
- function isOwnAccessor(e, t) {
1494
- return hasOwn.call(e, t) && (lookupGetter.call(e, t) !== undefined || lookupSetter.call(e, t) !== undefined);
1495
- }
1496
-
1497
- /** Authoritative-write wrapper exported for the optimistic module: sets the
1498
- * scheduler's projectionWriteActive through THIS module's binding (proven to
1499
- * share the instance core reads — cross-module live-binding writes from other
1500
- * store modules were observed not to propagate under the test transform). */ function runAuthoritative(e) {
1501
- const t = projectionWriteActive;
1502
- setProjectionWriteActive(true);
1503
- try {
1504
- return e();
1505
- } finally {
1506
- setProjectionWriteActive(t);
1507
- }
1508
- }
1509
-
1510
- /** The reading computation is until()'s authoritative-view predicate — same
1511
- * source of truth as core read()'s A17 carve-out (`context`, which persists
1512
- * under untrack). optimisticView()'s composition gate consults exactly this:
1513
- * write-side machinery (patch emission, tentative re-application) must keep
1514
- * composing even when it runs inside an authoritative-write bracket. */ function authoritativeRead() {
1515
- const e = context;
1516
- return e !== null && (e.C & CONFIG_AUTHORITATIVE_READ) !== 0;
1517
- }
1518
-
1519
- /** Serve-side authoritative gate: until()'s predicate PLUS truth authors —
1520
- * the projection derive's draft (wrapDraft trap brackets, runAuthoritative;
1521
- * the same posture pair ensurePB classifies drafts by). A source computing
1522
- * the next truth must never read its callers' tentative overlays: a derive
1523
- * continuation's `store.push` computing its index from an action's
1524
- * optimistic row landed truth in the wrong slot and corrupted committed
1525
- * state (#3108). Trap-level overlay serves gate on this so values, length,
1526
- * membership, and keys leave the authoritative view together. */ function authoritativeServe() {
1527
- return projectionWriteActive || getWriteOverride() || authoritativeRead();
1528
- }
1529
-
1530
- /** Context-aware node view for reads outside tracking: active override >
1531
- * held pending (owner context) > the BACKING value. Committed truth lives in
1532
- * the backing (single-home rule, O6) — node `_value` is never served here,
1533
- * so a lazy recompute's landing is immediately visible to the untracked
1534
- * reader that forced it (backing commits eagerly; node values fold at flush).
1535
- * FORCE sentinels never surface (they only bump subscribers of accessor
1536
- * keys, which are served by the trap, not the node). */ function nodeValue(e, t) {
1537
- // Store-only tunnels, ahead of Rule 1: truth authors (authoritativeServe —
1538
- // the projection derive's draft, the write-override continuation) see
1539
- // staged truth and never an override; latest() reaching this untracked
1540
- // path for a store key sees the in-flight parked value like an
1541
- // owner-context reader does (#3075), the visible override first.
1542
- let n;
1543
- if (authoritativeServe()) n = e._e !== NOT_PENDING ? e._e : t; else if (latestReadActive) n = visibleOverride(e) ? unwrapOverride(e.o?.we) : e._e !== NOT_PENDING ? e._e : t;
1544
- // Otherwise the one slow selection core read() uses (serve): override,
1545
- // lane gate, A28, readerSeesCommitted / A29 — with the BACKING as the
1546
- // committed value (single-home rule, O6).
1547
- else n = serve(e, readerContext(), e.Ne || e, t);
1548
- return n === FORCE ? t : n;
1549
- }
1550
-
1551
- /** The override a composed READER view (keys, descriptors, snapshot/deep,
1552
- * optimisticView) takes from an armed node whose override is active — the
1553
- * override itself, unless the node's own source superseded it (#3331,
1554
- * CONFIG_OVERRIDE_SUPERSEDED): then the reader-aware selection `serve`
1555
- * makes through nodeValue, so the composed view agrees with what `get`,
1556
- * `in` and `length` serve the same reader (a deriving pass: the staged
1557
- * truth; a lane pass or a context-free read: the override, A18). Composing
1558
- * the raw override left Object.keys / snapshot() / deep() one row behind the
1559
- * traps at a landing whose shape differed from the optimistic frame (F5
1560
- * parity cases). Draft and authoritative callers never reach here — the
1561
- * writer composes on hasActiveOverride, truth authors on the backing. */ function readerOverride(e, t) {
1562
- return e.C & CONFIG_OVERRIDE_SUPERSEDED ? nodeValue(e, t) : unwrapOverride(e.o?.we);
1563
- }
1564
-
1565
- /** §7b: a chained target's child found as a RAW — from its pending backing
1566
- * (a cloneRaw of the inner proxy, whose descriptors yield the inner store's
1567
- * raws) or from the deep() walk's descriptor read through the chain — must
1568
- * resolve to the inner family's proxy for that object before this family
1569
- * wraps it, so the overlay serves the same chained targets as the settled
1570
- * state. Otherwise every row re-wrapped as a fresh non-chained target keyed
1571
- * by the raw: identities churned for the life of an optimistic action and
1572
- * snapped back at settle, and writes landed on those orphans while deep()'s
1573
- * witnesses sat on the chained targets (#3323). The inner family owns the
1574
- * raw iff it has served it or its backing holds that exact object at `key`;
1575
- * anything else is a draft's own replacement object — view-owned, correctly
1576
- * non-chained — and is returned as is. Recurses down further chains. */ function resolveChainedRaw(e, t, n) {
1577
- const r = e.v[$TARGET];
1578
- if (r.ch) {
1579
- const e = resolveChainedRaw(r, t, n);
1580
- return e === n ? n : wrapNext(e, r, t);
1581
- }
1582
- const i = lookupTarget(n, r.fam);
1583
- if (i !== undefined) return i.px;
1584
- if ((r.v[t] === n || r.pb?.[t] === n) && isWrappable(n)) return wrapNext(n, r, t);
1585
- return n;
1586
- }
1587
-
1588
- /** Serve an own data key: node-first when a node exists (pending visibility,
1589
- * holds, lanes ride the node); backing otherwise. Chained backings (§7b: the
1590
- * backing IS another store's proxy) serve the read-through value — the outer
1591
- * node is linked only for adoption-swap notification, its value never
1592
- * shadows the live chain. */ function serveDataKey(e, t, n, r, i, o = -1) {
1593
- const l = e.ch && r === e.v;
1594
- let s = n;
1595
- // §6: on optimistic arrays LENGTH IS A VIEW, not a node value — one home
1596
- // (backing ± presence overrides) for both length and indices makes torn
1597
- // iteration impossible (a length node's value rides different visibility
1598
- // rails than index overrides mid-settle). The node carries subscriptions;
1599
- // its committed `_value` is never served here.
1600
- if (t === "length" && e.fam?.opt === true && !l && Array.isArray(r)) {
1601
- if (!inDraft(e)) {
1602
- const i = e.n?.length;
1603
- if (i !== undefined) {
1604
- // An override-covered length node answers through the node's
1605
- // reader-aware selection (serve: A17, the lane gate, A18
1606
- // supersession) with the backing's length as committed — the rule
1607
- // every index node takes through `get`, so `length` and indices
1608
- // resolve against ONE rule for this reader. The view composition
1609
- // below used to answer here and knows nothing of supersession
1610
- // (#3331): at a landing whose length differs from the optimistic
1611
- // frame, mapArray's tracked `length` (the get trap's node path) saw
1612
- // the staged truth while its untracked `slice` inside its owner saw
1613
- // the override, so `_items` came up short and the next pass keyed an
1614
- // undefined row (F5, optimistic-list-mutation-matrix `differ`).
1615
- if (getObserver() !== null) {
1616
- const e = read(i);
1617
- if (hasActiveOverride(i) && !authoritativeServe()) return e === FORCE ? r.length : e;
1618
- } else if (hasActiveOverride(i) && !authoritativeServe()) {
1619
- return nodeValue(i, r.length);
1620
- }
1621
- } else if (getObserver() !== null) {
1622
- read(getNode(e, t, n));
1623
- }
1624
- }
1625
- // Truth authors read the backing's own length — an optimistic row from
1626
- // the caller's transaction must not shift where the author's next write
1627
- // lands (#3108). A tentative draft that has seeded its backing from the
1628
- // view already carries the overrides in `src` (the draft arm every other
1629
- // channel gates on draftSeesOverrides — `get`, `has`, visibleKeys,
1630
- // snapshotWalk, #3665): composing them again put a slot the draft had
1631
- // just spliced out back on top of its shrunken backing, so `length` read
1632
- // one too long mid-splice and the second splice left a hole (F3,
1633
- // optimistic-list-mutation-matrix "move head->tail + move middle").
1634
- return (authoritativeServe() || inDraft(e) && !draftSeesOverrides(e) ? r : optHooks.optimisticView(e, r, inDraft(e))).length;
1635
- }
1636
- if (inDraft(e)) {
1637
- // Optimistic drafts before their first write have no pending backing yet;
1638
- // reads must still see the live optimistic view (compose, not clobber —
1639
- // #2951). Once ensurePB runs, the seeded clone carries the view.
1640
- // AUTHORITATIVE drafts (projection derive) never overlay — ensurePB's
1641
- // seeding rule, applied to the read side (#3108).
1642
- if (e.fam?.opt && draftSeesOverrides(e) && !authoritativeServe()) {
1643
- const n = e.n?.[t];
1644
- if (n !== undefined && hasActiveOverride(n)) s = unwrapOverride(n.o?.we);
1645
- }
1646
- } else {
1647
- // §7b: a lane value on the outer node SHADOWS read-through — an active
1648
- // override pierces the chained gate; otherwise chained backings always
1649
- // serve the live inner value.
1650
- if (getObserver() !== null) {
1651
- // First tracked read: create + link (the wrap-cache branch below
1652
- // populates px/pxv so read #2 skips wrapNext, slice 2). The value is
1653
- // served THROUGH the node from this read on — a node born under a held
1654
- // fold carries the hold (getNode, #3336), and the backing it was read
1655
- // from does not.
1656
- if (i === undefined) i = getNode(e, t, n, o);
1657
- // read()'s plain-signal fast path hoisted over the call (legacy trap
1658
- // parity): READ_SLOW = a global read window or non-plain node.
1659
- let r = readNodeFast(i);
1660
- if (r === READ_SLOW) r = read(i);
1661
- if (!l || hasActiveOverride(i)) s = r === FORCE ? n : r;
1662
- } else if (i !== undefined && (!l || hasActiveOverride(i))) {
1663
- s = nodeValue(i, n);
1664
- }
1665
- }
1666
- // Shallow stores serve data raw; store-proxy slots get boundary wrappers.
1667
- if (e.s) return serveShallow(e, t, s);
1668
- if (e.ch && !l && s !== null && typeof s === "object" && s[$TARGET] === undefined) s = resolveChainedRaw(e, t, s);
1669
- if (i !== undefined) {
1670
- // Wrap cache (see getNode): only wrappables are ever cached, so a hit
1671
- // skips isWrappable too — pointer-compare replaces both checks.
1672
- if (i.pxv === s && s !== undefined) return draftServe(e, i.px);
1673
- if (!isWrappable(s)) return s;
1674
- const n = wrapNext(s, e, t);
1675
- i.px = n;
1676
- i.pxv = s;
1677
- return draftServe(e, n);
1678
- }
1679
- if (!isWrappable(s)) return s;
1680
- return draftServe(e, wrapNext(s, e, t));
1681
- }
1682
-
1683
- /** §6c store-wide status gate for reads that DON'T flow through a node:
1684
- * untracked/raw fallthrough must still throw while the derive is
1685
- * uninitialized (seed invisibility, proj R23) or errored (memo parity).
1686
- * TRACKED reads never call this — store nodes carry `_firewall`, so core
1687
- * read() links the node and throws the firewall's error itself (the node
1688
- * link is what wakes async-memo readers when the landing writes values;
1689
- * the firewall link rides the same read). */ function firewallGate(e) {
1690
- // Own-draft ops are exempt: an async derive's continuation (generator body
1691
- // after an `await`/`yield`) runs OUTSIDE the sync write scope (inDraft is
1692
- // already false), but its draft-proxy traps mark every op with the write
1693
- // override. Those reads are the derive working its own draft (state.push
1694
- // reading .length) — gating them throws NotReadyError back into the derive
1695
- // itself, which the post-await read diagnostic (#2987) then escalates to a
1696
- // reactivity halt. The gate exists for EXTERNAL readers (seed invisibility,
1697
- // proj R23); the derive is the author.
1698
- if (projectionWriteActive || getWriteOverride()) return;
1699
- const t = e.fam?.node;
1700
- if (t != null && t.S & (STATUS_UNINITIALIZED | STATUS_ERROR)) read(t);
1701
- }
1702
-
1703
- /** latest() pull (#3075): bring the projection computed up to date so the
1704
- * read serves the IN-FLIGHT derivation — signal/memo parity, where core
1705
- * read() routes latest() through a companion that recomputes speculatively.
1706
- * The latest flag is suspended for the recompute (the derive's own reads
1707
- * are normal reads), and latestPullActive marks any adoption it commits as
1708
- * staged (see adoptPB) — the speculative swap must not leak to
1709
- * committed-visibility readers before the flush. */ function pullProjectionForLatest(e) {
1710
- const t = e.fam.node;
1711
- if (t == null) return;
1712
- const n = latestReadActive;
1713
- setLatestReadActive(false);
1714
- const r = latestPullActive;
1715
- latestPullActive = true;
1716
- try {
1717
- prepareComputed(t, true);
1718
- } finally {
1719
- latestPullActive = r;
1720
- setLatestReadActive(n);
1721
- }
1722
- }
1723
-
1724
- const traps = {
1725
- get(e, t, n) {
1726
- // One typeof gates every brand-symbol compare off the hot string path
1727
- // (four symbol comparisons per property read otherwise).
1728
- if (typeof t !== "string") {
1729
- if (t === $TARGET) return e;
1730
- if (t === $PROXY) return n;
1731
- if (t === $OWNER) return undefined;
1732
- // ownership stamp: never a user key
1733
- if (t === $RECORD) return undefined;
1734
- // a store is no view (see `viewOf`)
1735
- // refresh()/isPending resolve the projection computed through $REFRESH.
1736
- if (t === $REFRESH) return e.fam?.node ?? undefined;
1737
- if (t === $TRACK) {
1738
- if (pendingCheckActive) witnessAffectsMark(e, t);
1739
- if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1740
- if (!inDraft(e) && getObserver() !== null) {
1741
- read(getKeySetNode(e));
1742
- // Structural chaining (§7b, #2864 / core R21): a chained backing's
1743
- // $TRACK reads through to the INNER store's key-set — structural
1744
- // notifications land on the source's own node, never on this
1745
- // wrapper view's.
1746
- const t = readSource(e);
1747
- if (t[$TARGET] !== undefined) t[$TRACK];
1748
- }
1749
- return undefined;
1750
- }
1751
- // user symbols fall through to the generic path
1752
- }
1753
- if (pendingCheckActive) witnessAffectsMark(e, t);
1754
- if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1755
- // latest() pull (#3075): store traps never reach core read() without an
1756
- // observer, so bring the projection computed up to date here — signal/
1757
- // memo parity for latest() reads through a projection.
1758
- if (e.fam !== null && latestReadActive && !inDraft(e) && !getWriteOverride()) pullProjectionForLatest(e);
1759
- const r = readSource(e);
1760
- // Overlay delete (#3044): a prototype overlay cannot shadow a delete, so
1761
- // deleted keys are tracked aside and read as absent in the pending view.
1762
- if (e.del !== null && r === e.pb && e.del.has(t)) {
1763
- if (!inDraft(e) && getObserver() !== null) read(getNode(e, t, undefined));
1764
- return undefined;
1765
- }
1766
- // Hot inline case: existing PLAIN node (non-accessor), unchained backing,
1767
- // tracked read of a present data key — the dbmon/uibench effect re-read
1768
- // shape. Skips serveDataKey's frame, the FORCE compare (only accessor
1769
- // keys ever hold the sentinel), and isWrappable for primitives.
1770
- // ONE node-map lookup serves this block and the accessor probe below
1771
- // (nothing between them creates nodes).
1772
- const i = e.n?.[t];
1773
- if (e.ch === false && writeScopes === null) {
1774
- const n = i;
1775
- if (n !== undefined && n.acc !== true && getObserver() !== null) {
1776
- let r = readNodeFast(n);
1777
- if (r === READ_SLOW) r = read(n);
1778
- if (r === null || typeof r !== "object") return r;
1779
- if (e.s) return serveShallow(e, t, r);
1780
- if (n.pxv === r) return n.px;
1781
- if (isWrappable(r)) {
1782
- const i = wrapNext(r, e, t);
1783
- n.px = i;
1784
- n.pxv = r;
1785
- return i;
1786
- }
1787
- return r;
1788
- }
1789
- }
1790
- // Accessor keys serve through Reflect.get with the PROXY receiver
1791
- // (R20/R29: internal reads track; the node is linked for shape-change
1792
- // notification but its value is never served). Accessor-ness comes from
1793
- // the node's cached flag; the first TRACKED read (which creates the
1794
- // node) probes once — untracked node-less reads take the plain path,
1795
- // where a raw-receiver getter still returns correct committed values.
1796
- // Tracking suppression is PER-TARGET (inDraft), never global: `writing`
1797
- // counts every open setter anywhere, and a projection derive runs its
1798
- // whole body inside one — a global gate silently swallowed EXTERNAL
1799
- // absent-key/accessor subscriptions for every store read during any
1800
- // derive, leaving nested projections permanently dependency-less when
1801
- // their sources hadn't materialized yet (#3037).
1802
- // First-read dedupe (create-floor slice 2): remember the probe verdict —
1803
- // node creation downstream reuses it instead of re-scanning the
1804
- // descriptor, but only when the probed object IS the one getNode would
1805
- // scan (pb ?? v).
1806
- let o = -1;
1807
- {
1808
- let l;
1809
- if (i !== undefined) l = i.acc === true; else if (!inDraft(e) && getObserver() !== null) {
1810
- l = isOwnAccessor(r, t);
1811
- if (r === (e.pb ?? e.v)) o = l ? 1 : 0;
1812
- } else l = false;
1813
- if (l) {
1814
- if (!inDraft(e) && getObserver() !== null) read(i ?? getNode(e, t, undefined, o));
1815
- const l = Reflect.get(r, t, n);
1816
- if (e.s) return serveShallow(e, t, l);
1817
- return isWrappable(l) ? draftServe(e, wrapNext(l, e, t)) : l;
1818
- }
1819
- }
1820
- // Plain-data fast path: no descriptor allocation per read.
1821
- // Inherited pollution keys are never served (core R30) — checked before
1822
- // the proto-function branch can leak `constructor`. Interned-string
1823
- // compares beat a Set hash on this per-read path. Overlay pending
1824
- // backings chain to the committed backing, so "own in the view" means
1825
- // own on either layer (ownInView) — a genuine prototype method is one
1826
- // that is own on NEITHER.
1827
- const l = e.ovl && r === e.pb;
1828
- if ((t === "constructor" || t === "__proto__" || t === "prototype") && !hasOwn.call(r, t) && !(l && hasOwn.call(e.v, t))) return undefined;
1829
- let s = r[t];
1830
- if (s === undefined ? !hasOwn.call(r, t) && !(l && hasOwn.call(e.v, t)) : false) {
1831
- // Inherited: prototype getters/methods run with the proxy receiver.
1832
- s = Reflect.get(r, t, n);
1833
- if (typeof s === "function") return s;
1834
- // proto methods untracked
1835
- // Reading a currently-absent own key subscribes to it (R12) — for any
1836
- // target OUTSIDE its own draft scope, even mid-setter (#3037, above).
1837
- if (s === undefined && !inDraft(e)) {
1838
- if (getObserver() !== null) read(getNode(e, t, undefined, o));
1839
- const n = e.n?.[t];
1840
- if (n) {
1841
- const r = nodeValue(n, undefined);
1842
- if (e.s) return serveShallow(e, t, r);
1843
- return isWrappable(r) ? draftServe(e, wrapNext(r, e, t)) : r;
1844
- }
1845
- } else if (s === undefined && inDraft(e) && e.fam?.opt && draftSeesOverrides(e) &&
1846
- // AUTHORITATIVE drafts (landing folds) never seed from overrides —
1847
- // the caller's optimism is not truth (has-trap twin below).
1848
- !authoritativeServe()) {
1849
- const n = e.n?.[t];
1850
- // The draft is a WRITER channel (hasActiveOverride's rule): it
1851
- // composes on the tick's own unflushed adds, as the has trap's draft
1852
- // arm, visibleKeys and optimisticView do. Reader-gating this arm
1853
- // (visibleOverride) made a second setter in the same action read
1854
- // `undefined` where the first had pushed a row (#3665, rc.9).
1855
- if (n !== undefined && hasActiveOverride(n)) s = unwrapOverride(n.o?.we);
1856
- }
1857
- if (e.s) return serveShallow(e, t, s);
1858
- return isWrappable(s) ? draftServe(e, wrapNext(s, e, t)) : s;
1859
- }
1860
- if (typeof s === "function" && !hasOwn.call(r, t) && !(l && hasOwn.call(e.v, t))) return s;
1861
- // proto method
1862
- return serveDataKey(e, t, s, r, i, o);
1863
- },
1864
- has(e, t) {
1865
- if (t === $TARGET || t === $PROXY || t === $TRACK) return true;
1866
- if (t === $OWNER || t === $RECORD) return false;
1867
- if (pendingCheckActive) witnessAffectsMark(e, t);
1868
- if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1869
- const n = readSource(e);
1870
- let r = t in n;
1871
- // Overlay deletes read as absent in the pending view (#3044).
1872
- if (r && e.del !== null && n === e.pb && e.del.has(t)) r = false;
1873
- if (!inDraft(e)) {
1874
- if (getObserver() !== null) {
1875
- const n = getHasNode(e, t, r);
1876
- // Authoritative-view readers get the right answer for free: core read()
1877
- // skips the override arm for them, so nv is authoritative presence.
1878
- const i = read(n);
1879
- if (hasActiveOverride(n)) r = !!i;
1880
- } else if (!authoritativeServe()) {
1881
- const n = e.h?.[t];
1882
- // The get trap's untracked selection (nodeValue → serve), so `in`
1883
- // agrees with the tracked branch above and with `get`: a presence
1884
- // override the landing superseded (#3331 — an optimistic delete
1885
- // whose slot the truth refilled) answers the staged truth for a
1886
- // deriving reader. Reading the override directly said "absent" while
1887
- // `get` served the landed row, and HasProperty-driven copies (slice,
1888
- // spread, map) left a hole (F5 `differ: delete *`).
1889
- if (n !== undefined && hasActiveOverride(n)) r = !!nodeValue(n, r);
1890
- }
1891
- } else if (e.fam?.opt && draftSeesOverrides(e) && !authoritativeServe()) {
1892
- const n = e.h?.[t];
1893
- if (n !== undefined && hasActiveOverride(n)) r = !!unwrapOverride(n.o?.we);
1894
- }
1895
- return r;
1896
- },
1897
- ownKeys(e) {
1898
- if (pendingCheckActive) witnessAffectsMark(e);
1899
- if (e.fam !== null && getObserver() === null && !inDraft(e)) firewallGate(e);
1900
- if (!inDraft(e) && getObserver() !== null) read(getKeySetNode(e));
1901
- return visibleKeys(e, readSource(e));
1902
- },
1903
- getOwnPropertyDescriptor(e, t) {
1904
- if (t === $OWNER || t === $RECORD) return undefined;
1905
- // A descriptor read is a PRESENCE read: it subscribes to the key's
1906
- // presence node and witnesses affects()/isPending() exactly as `in` does
1907
- // (structural oracle, 2026-09-17 — the trap read no node before, so a
1908
- // render effect inspecting a key through getOwnPropertyDescriptor never
1909
- // re-ran for an optimistic add or delete, and an isPending() probe over
1910
- // it witnessed nothing). The value it reports rides the value node's
1911
- // view through visibleDescriptor.
1912
-
1913
- // EXCEPT for an enumerator (#3664): Object.keys / for...in / spread /
1914
- // Object.entries / JSON.stringify take this trap once per key right
1915
- // after `ownKeys`, which already subscribed the observer to the key-set
1916
- // node — and that node bumps on every membership change, committed or
1917
- // optimistic, so a presence node per key adds nothing the enumerator
1918
- // can observe (rc.9 birthed one per key per object: ~640 B and a graph
1919
- // node each, 10x the memory of a 30-key row's reader). When the
1920
- // observer holds the key-set node in THIS pass, skip the presence read;
1921
- // a lone descriptor read keeps its per-key precision.
1922
- if (pendingCheckActive) witnessAffectsMark(e, t);
1923
- const n = getObserver();
1924
- if (e.fam !== null && n === null && !inDraft(e)) firewallGate(e);
1925
- const r = readSource(e);
1926
- const i = visibleDescriptor(e, r, t);
1927
- if (!inDraft(e) && n !== null && !observerHoldsKeySet(e, n)) {
1928
- // The node is born from the source's presence (as `has` births it),
1929
- // not the override-adjusted answer.
1930
- let n = t in r;
1931
- if (n && e.del !== null && r === e.pb && e.del.has(t)) n = false;
1932
- read(getHasNode(e, t, n));
1933
- }
1934
- if (i === undefined) return undefined;
1935
- // Array targets carry a real non-configurable `length` the proxy
1936
- // invariant forces us to report faithfully; everything else reports
1937
- // configurable via target indirection (core R51).
1938
- if (!(t === "length" && Array.isArray(e))) i.configurable = true;
1939
- return i;
1940
- },
1941
- set(e, t, n) {
1942
- // Writes require the target's draft scope OR the projection write
1943
- // override (post-await async draft writes arrive outside any window);
1944
- // everything else is silently ignored (R23).
1945
- const r = inDraft(e);
1946
- const i = !r && getWriteOverride();
1947
- if (!r && !i) return true;
1948
- if (t === "__proto__") return true;
1949
- // pollution guard (core R30)
1950
- // Unwrap BEFORE ensurePB: unwrapValue materializes a self-referencing
1951
- // draft's overlay (replacing target.pb), so a pb local captured earlier
1952
- // would be the abandoned overlay and the write would vanish.
1953
- // Shallow slots store what was written VERBATIM — another store's proxy
1954
- // passes through by reference (#2932; markRawOne skips proxies), while
1955
- // deep stores unwrap to raw backings.
1956
- const o = e.s ? n : unwrapValue(n);
1957
- const l = ensurePB(e);
1958
- pendingNotify.add(e);
1959
- // Array length writes implicitly delete indices — the written-keys bound
1960
- // can't see them, so poison to the full scan for this batch. Index
1961
- // writes implicitly GROW length, so arrays always record it alongside.
1962
- if (Array.isArray(l)) {
1963
- if (t === "length") e.wk = WK_ALL; else if (e.wk !== WK_ALL) {
1964
- const n = e.wk ??= new Set;
1965
- n.add(t);
1966
- n.add("length");
1967
- }
1968
- } else {
1969
- if (e.wk !== WK_ALL) (e.wk ??= new Set).add(t);
1970
- // Live own-key estimate for the overlay/clone choice (#3360): `in`
1971
- // sees through an overlay to the committed keys, so this counts keys
1972
- // NEW to the container. Deletes are not un-counted (a stale high
1973
- // count only picks the overlay a little early).
1974
- if (!(t in l)) e.kc++;
1975
- }
1976
- // Own data keys literally named "prototype"/"constructor" land as data —
1977
- // defineProperty sidesteps a proto-chain setter named the same.
1978
- if (UNSAFE_KEYS.has(t)) {
1979
- Object.defineProperty(l, t, {
1980
- value: o,
1981
- writable: true,
1982
- enumerable: true,
1983
- configurable: true
1984
- });
1985
- if (e.del !== null) e.del.delete(t);
1986
- return true;
1987
- }
1988
- // Overlay first-write DEFINES the own key: assignment through the proto
1989
- // chain would reject on a non-writable committed property (the clone
1990
- // path normalized descriptors for exactly this — R51 parity). A
1991
- // plain-data-graded backing (sc 2, owned: every slot writable) takes the
1992
- // bare assignment — it lands as an own key on the overlay all the same.
1993
- if (e.ovl && e.sc !== 2 && !hasOwn.call(l, t)) {
1994
- Object.defineProperty(l, t, {
1995
- value: o,
1996
- writable: true,
1997
- enumerable: true,
1998
- configurable: true
1999
- });
2000
- } else l[t] = o;
2001
- if (e.del !== null) e.del.delete(t);
2002
- // Shallow ingest: written records are sticky raw-marked (one entity is
2003
- // never both deep-wrapped and raw — R41/#2932, shared invariant).
2004
- if (e.s && o !== null && typeof o === "object") markRawOne(o);
2005
- // Override-mode (post-await draft) writes have no setter exit — notify
2006
- // per-op (setSignal equality-gates repeats).
2007
- if (i) notifyWrites(e);
2008
- return true;
2009
- },
2010
- defineProperty(e, t, n) {
2011
- const r = inDraft(e);
2012
- const i = !r && getWriteOverride();
2013
- if (!r && !i) return true;
2014
- if (t === "__proto__") return true;
2015
- if (n.get || n.set) e.a = true;
2016
- // Unwrap before ensurePB (see the set trap: self-reference materializes).
2017
- if ("value" in n) n = {
2018
- ...n,
2019
- value: unwrapValue(n.value)
2020
- };
2021
- const o = ensurePB(e);
2022
- // A non-default data descriptor (or an accessor) leaves the plain-data
2023
- // grade: the key reaches the committed backing as defined, so the spread
2024
- // clone and bare-assignment paths no longer describe it.
2025
- if (e.a || !(n.enumerable && n.writable && n.configurable)) e.sc = 1;
2026
- pendingNotify.add(e);
2027
- if (e.wk !== WK_ALL) (e.wk ??= new Set).add(t);
2028
- Object.defineProperty(o, t, n);
2029
- if (e.del !== null) e.del.delete(t);
2030
- if (i) notifyWrites(e);
2031
- return true;
2032
- },
2033
- deleteProperty(e, t) {
2034
- const n = inDraft(e);
2035
- const r = !n && getWriteOverride();
2036
- if (!n && !r) return true;
2037
- const i = ensurePB(e);
2038
- pendingNotify.add(e);
2039
- if (e.wk !== WK_ALL) (e.wk ??= new Set).add(t);
2040
- delete i[t];
2041
- // A prototype overlay cannot shadow a delete of a committed key —
2042
- // record it aside (#3044); reads/has/ownKeys/commit consult the set.
2043
- if (e.ovl && hasOwn.call(e.v, t)) (e.del ??= new Set).add(t);
2044
- if (r) notifyWrites(e);
2045
- return true;
2046
- }
2047
- };
2048
-
2049
- /** Low-level setter primitive: opens write mode on a next proxy, runs `fn`,
2050
- * emits write-time notifications at outermost exit, applies returned
2051
- * replacements as adoptions. `guard=false` skips the dev guards (owned-scope
2052
- * write, thenable result) — projection recomputes legitimately write from
2053
- * inside their computed, and their async derive is handled by the recompute,
2054
- * not returned through here. */
2055
- /** The derived store (`createStore(fn)`) whose user setter is running, and
2056
- * whether one of its leaf notifications hit a staging another transaction
2057
- * holds as the fold's result (A34 amendment, #3612; core heldDerivation). */ let derivedSetter = null;
2058
-
2059
- let heldDerivationHit = false;
2060
-
2061
- /** The derived store's setter (CS-R31): within a synchronous frame the manual
2062
- * write wins — the projection's recompute is masked for the tick. Across a
2063
- * hold the write is not a proposal: a leaf the fold staged under another
2064
- * transaction re-runs the fold under it, the write being the draft's prior
2065
- * state (#3612). Decided from the leaf notifications, so the mask lands
2066
- * after them (in the `finally`: a throwing setter's writes before the throw
2067
- * were notified, and are masked as before). */ function derivedStoreWrite(e, t, n) {
2068
- derivedSetter = e;
2069
- heldDerivationHit = false;
2070
- try {
2071
- storeSetterNext(t, n);
2072
- } finally {
2073
- derivedSetter = null;
2074
- heldDerivationHit ? rederiveHeld(e) : suppressComputedRecompute(e);
2075
- }
2076
- }
2077
-
2078
- function storeSetterNext(e, t, n = true) {
2079
- const r = e[$TARGET];
2080
- const i = writeScopes;
2081
- writeScopes = new Set;
2082
- writeScopes.add(scopeKey(r));
2083
- writing++;
2084
- let o;
2085
- try {
2086
- // No untrack: the writing flag already disables store-node linking
2087
- // (draft reads never self-track, proj R2), while EXTERNAL reads (signals
2088
- // inside a projection derive) must keep tracking — they are the derive's
2089
- // dependencies.
2090
- o = t(e);
2091
- } finally {
2092
- writing--;
2093
- writeScopes = i;
2094
- // Outermost setter exit: emit write-time notifications (setSignal per
2095
- // changed observed key) so transition holds and lanes engage now.
2096
- if (writing === 0 && pendingNotify.size) {
2097
- const e = [ ...pendingNotify ];
2098
- pendingNotify.clear();
2099
- for (const t of e) notifyWrites(t);
2100
- }
2101
- }
2102
- if (o !== undefined && o !== e && isWrappable(o)) {
2103
- // Returned replacement: on an optimistic family (outside authoritative
2104
- // writes) the replacement is itself an optimistic edit — diff it against
2105
- // the visible view as engine writes (reverts at settle). Otherwise it is
2106
- // an adoption of the incoming object (unowned).
2107
- if (r.fam?.opt && !projectionWriteActive && !getWriteOverride()) {
2108
- optHooks.notifyOptimisticWrites(r, unwrapValue(o));
2109
- } else {
2110
- adoptPB(r, unwrapValue(o));
2111
- }
2112
- }
2113
- if (writing === 0 && heldAdoptions.size) stageHeldAdoptions();
2114
- }
2115
-
2116
- // Affects integration: the legacy affects machinery reads next targets
2117
- // structurally (aliased field names); only node CREATION dispatches here.
2118
- setNextAffectsNodeResolver((e, t) => t === $AFFECTS ? getNode(e, $AFFECTS, undefined) : getNode(e, t, (e.pb ?? e.v)[t]));
2119
-
2120
- function createStoreNext(e, t = false) {
2121
- const n = wrapNext(e);
2122
- if (t) {
2123
- n[$TARGET].s = true;
2124
- markRawIngest(e);
2125
- }
2126
- {
2127
- const e = getOwner();
2128
- // Dev-tier graph registration (owner signal lists, onGraph); the
2129
- // `_owner` write itself never reaches the proxy, see storeOwners.
2130
- registerGraph(n, e);
2131
- // Only once the engine is installed, like the node stamping it feeds: a
2132
- // WeakMap.set per fresh store is a growing ephemeron table (~+35% on the
2133
- // 2000-store create+commit shape, CodSpeed −11.7% on #3380's first cut)
2134
- // and, disabled, buys nothing — a store created before enable() has no
2135
- // excluded owner to inherit either way.
2136
- // The declared name is the public `createStore`'s to record (`nameStore`,
2137
- // same gate) — a parameter here would survive into the prod artifact.
2138
- if (attrHooks !== null) storeOwners.set(n[$TARGET], e);
2139
- }
2140
- const setter = e => storeSetterNext(n, e);
2141
- return [ n, setter ];
2142
- }
2143
-
2144
- // ---------------------------------------------------------------------------
2145
- // snapshot (next targets): the backing IS the plain raw graph — zero copy.
2146
- // Sees pending (R27) by reading pb. Chained/owned-copy caching lands with the
2147
- // utilities increment; this covers the createStore-suite contract.
2148
- /** True when `proxy` is a SHALLOW store (children served verbatim, slots
2149
- * replaced by reference — #2932). The list driver uses this to choose the
2150
- * slot-patch channel (collected row bodies) over per-record registration. */ function storeIsShallow(e) {
2151
- const t = e?.[$TARGET];
2152
- return t !== undefined && t.s === true;
2153
- }
2154
-
2155
- /** True when `proxy` belongs to a projection/optimistic FAMILY. The list
2156
- * driver must DECLINE family arrays (external audit finding): family
2157
- * structural changes never emit row/slot ops (the setter channel is
2158
- * fam-gated; optimistic writes ride node overrides), and the proxy identity
2159
- * is stable so the each-watch cannot catch the change either — an engaged
2160
- * list would freeze on optimistic/projection structural updates. Record-
2161
- * level family patches are unaffected (they have their own emission). */ function storeHasFamily(e) {
2162
- const t = e?.[$TARGET];
2163
- return t !== undefined && t.fam !== null;
2164
- }
2165
-
2166
- /** True when `proxy` belongs to an OPTIMISTIC family specifically. The list
2167
- * driver declines these (audit finding, narrowed): optimistic user writes
2168
- * ride node-level overrides — they never enter the reconcile walk, so no
2169
- * row/slot ops are emitted and an engaged list would freeze on optimistic
2170
- * structural changes. PROJECTION (non-optimistic) families are drivable:
2171
- * their recomputes go through the reconcile walk, whose emissions are
2172
- * transition-stamped in the apply queue like any other (equivalence-matrix
2173
- * gated). Re-admitting optimistic families requires a lane-timed structural
2174
- * emission mirroring emitPatchOptimistic, plus revert resync. */ function storeHasOptimisticFamily(e) {
2175
- const t = e?.[$TARGET];
2176
- return t !== undefined && t.fam?.opt === true;
2177
- }
2178
-
2179
- // ---------------------------------------------------------------------------
2180
- // visibility: what a reader sees on a record — ONE rule for the ownKeys /
2181
- // getOwnPropertyDescriptor traps and the deep() walk (#3323). The walk used
2182
- // to re-derive the trap rules over raw backings and missed each new one in
2183
- // turn (the #3044 overlay merge, then #3323's chain, then optimistic presence
2184
- // and value overrides); sharing the body makes parity structural.
2185
- /** Keys visible on `target` served from `src` (= readSource(target)): the
2186
- * pending-overlay merge (#3044) and, on optimistic families, presence-node
2187
- * overrides (§6, FINDING-2's fix). Draft reads before the first write overlay
2188
- * too (pb, once created, is seeded with the view). Authoritative-view reads
2189
- * (until()'s predicate, truth-author drafts) skip the overlay. */ function visibleKeys(e, t) {
2190
- let n;
2191
- if (e.ovl && t === e.pb) {
2192
- // Overlay merge (#3044): committed keys in their order, then this
2193
- // batch's NEW keys, minus deletes.
2194
- n = Reflect.ownKeys(e.v);
2195
- const r = e.del;
2196
- if (r !== null && r.size !== 0) n = n.filter(e => !r.has(e));
2197
- for (const r of Reflect.ownKeys(t)) {
2198
- if (!hasOwn.call(e.v, r)) n.push(r);
2199
- }
2200
- } else n = Reflect.ownKeys(t);
2201
- // Drop the $OWNER stamp (owned backings carry it as an own enumerable
2202
- // symbol). Symbols enumerate last, so the scan stops at the first string.
2203
- for (let e = n.length - 1; e >= 0 && typeof n[e] === "symbol"; e--) {
2204
- if (n[e] === $OWNER) {
2205
- n.splice(e, 1);
2206
- break;
2207
- }
2208
- }
2209
- if (!authoritativeServe() && e.fam?.opt && e.h !== null && (!inDraft(e) || draftSeesOverrides(e))) {
2210
- let t = null;
2211
- const r = inDraft(e);
2212
- for (const i of Reflect.ownKeys(e.h)) {
2213
- const o = e.h[i];
2214
- if (!(r ? hasActiveOverride(o) : visibleOverride(o))) continue;
2215
- t ??= new Set(n);
2216
- // Reader arm: a superseded presence override answers as `in` does
2217
- // (readerOverride, #3331) — Object.keys listed one row fewer than the
2218
- // traps served after a landing refilled an optimistically deleted slot.
2219
- const l = r ? unwrapOverride(o.o?.we) : readerOverride(o, t.has(i));
2220
- if (l) t.add(i); else t.delete(i);
2221
- }
2222
- if (t !== null) return [ ...t ];
2223
- }
2224
- return n;
2225
- }
2226
-
2227
- /** The data/accessor descriptor visible for `key` on `target` served from
2228
- * `src`: overlay (#3044 — unwritten keys live on the committed backing,
2229
- * deleted keys are absent) and optimistic presence overrides (an opt delete
2230
- * hides the key; an opt add synthesizes a data descriptor from the value
2231
- * node). `configurable` is the trap's concern (proxy invariant). */ function visibleDescriptor(e, t, n) {
2232
- let r = Object.getOwnPropertyDescriptor(t, n);
2233
- if (e.ovl && t === e.pb) {
2234
- if (e.del !== null && e.del.has(n)) return undefined;
2235
- if (r === undefined) r = Object.getOwnPropertyDescriptor(e.v, n);
2236
- }
2237
- // Draft arm, the twin of visibleKeys' (#3665): a draft still composing on
2238
- // the live view (no view-seeded backing yet) serves the writer rule
2239
- // (hasActiveOverride); once ensurePB has seeded the draft's own backing,
2240
- // `src` carries the view. Without it ownKeys listed a key the descriptor
2241
- // reported absent, and every enumerator — Object.keys, spread, entries,
2242
- // JSON.stringify, deep() — dropped the row a previous setter had added.
2243
- const i = inDraft(e);
2244
- if (!authoritativeServe() && e.fam?.opt && (!i || draftSeesOverrides(e))) {
2245
- const t = e.h?.[n];
2246
- if (t !== undefined && (i ? hasActiveOverride(t) : visibleOverride(t))) {
2247
- // Reader arm: presence as `in` serves it (readerOverride, #3331).
2248
- const o = i ? unwrapOverride(t.o?.we) : readerOverride(t, r !== undefined);
2249
- if (!o) return undefined;
2250
- // opt delete
2251
- if (r === undefined) {
2252
- const t = e.n?.[n];
2253
- return {
2254
- // In a draft the value is the override itself (nodeValue routes
2255
- // through serve — the reader rule — and would answer undefined).
2256
- value: t === undefined ? undefined : i ? hasActiveOverride(t) ? unwrapOverride(t.o?.we) : undefined : nodeValue(t, undefined),
2257
- writable: true,
2258
- enumerable: true,
2259
- configurable: true
2260
- };
2261
- }
2262
- }
2263
- }
2264
- return r;
2265
- }
2266
-
2267
- /** Tracking deep snapshot (`deep()` for next targets): subscribes to the
2268
- * key-set and deep-witness node at every reachable level, then returns the
2269
- * plain view. Shared references and cycles handled via the visited set. */ function deepNext(e) {
2270
- const t = e?.[$TARGET];
2271
- if (t === undefined || t.px !== e) return e;
2272
- const n = new Set;
2273
- // One membership node + one deep-witness node PER RECORD (legacy $TRACK
2274
- // parity): the walk stays O(records) in subscriptions instead of O(paths)
2275
- // in per-key nodes, and it walks TARGETS directly — no per-child proxy
2276
- // round-trip (wrapNext → proxy → $TARGET trap) on the re-walk every
2277
- // effect run performs.
2278
- // Resolve `child` (a raw or a stored proxy found under `t`) to the target
2279
- // that `t`'s family serves for it — created on first visit, as the get trap
2280
- // would. Undefined = leaf (unwrappable or raw-marked).
2281
- const childTarget = (e, t, n) => {
2282
- let r = lookupTarget(t, e.fam);
2283
- if (r === undefined) {
2284
- if (!isWrappable(t)) return undefined;
2285
- wrapNext(t, e, n);
2286
- // Stored proxies (chained slots) that this family passes through
2287
- // resolve to their own target.
2288
- r = lookupTarget(t, e.fam) ?? t[$TARGET];
2289
- }
2290
- return r;
2291
- };
2292
- const walkT = e => {
2293
- const t = readSource(e);
2294
- if (n.has(t)) return;
2295
- n.add(t);
2296
- read(getKeySetNode(e));
2297
- read(getDeepNode(e));
2298
- // Chained backing (§7b): the committed backing IS another store's proxy.
2299
- // Writes to the inner store bump the INNER record's witnesses; this
2300
- // target's k/dk hear only its own family's writes (optimistic overrides).
2301
- // Read through the whole chain — the $TRACK trap's rule (#2864 / R21)
2302
- // applied to deep() (#3323). From `t.v`, not `src`: a pending backing is a
2303
- // raw clone and would hide the chain. Non-chained targets pay one flag.
2304
- for (let t = e; t.ch; ) {
2305
- t = t.v[$TARGET];
2306
- read(getKeySetNode(t));
2307
- read(getDeepNode(t));
2308
- }
2309
- // Keys and children exactly as the traps serve them — the overlay merge
2310
- // (#3044/#3283: a bare ownKeys over a pending backing mid-flush dropped
2311
- // every untouched child from the re-subscribing effect's dependencies)
2312
- // and optimistic presence overrides (a row added under a held action
2313
- // lives in `h`/`n`, not the committed backing; the walk never reached its
2314
- // record, so deep() was deaf to every write on it until settle).
2315
- const r = e.fam?.opt === true;
2316
- for (const n of visibleKeys(e, t)) {
2317
- const i = visibleDescriptor(e, t, n);
2318
- if (i === undefined) continue;
2319
- if (i.get || i.set) {
2320
- e.a = true;
2321
- continue;
2322
- // accessors track through their own reads when invoked
2323
- }
2324
- let o = i.value;
2325
- // An active value override on an optimistic node shadows the backing's
2326
- // child (an optimistic replacement `d[i] = {...}`) — follow what reads
2327
- // serve, as nodeValue's leading arm does.
2328
- if (r) {
2329
- const t = e.n?.[n];
2330
- if (t !== undefined && hasActiveOverride(t) && !authoritativeServe()) o = unwrapOverride(t.o.we);
2331
- }
2332
- if (o === null || typeof o !== "object") continue;
2333
- // Through a chain the descriptor yields the INNERMOST raw: resolve it to
2334
- // the inner family's proxy so this level wraps the chained `view[i]` the
2335
- // get trap serves, never a fresh non-chained wrapper of the base raw.
2336
- if (e.ch && o[$TARGET] === undefined) o = resolveChainedRaw(e, n, o);
2337
- const l = childTarget(e, o, n);
2338
- if (l === undefined) continue;
2339
- // raw-marked: leaf by contract
2340
- walkT(l);
2341
- }
2342
- };
2343
- walkT(t);
2344
- return snapshotNext(e);
2345
- }
2346
-
2347
- /**
2348
- * Snapshot with per-object registration resolution (RUL-12 DAG ruling): every
2349
- * reachable wrappable resolves through its target's CURRENT backing, so
2350
- * privatized subtrees are seen through any parent path. Identity-preserving:
2351
- * a subtree with no substitutions below returns its own object (zero copy for
2352
- * settled, never-diverged graphs).
2353
- */ function snapshotNext(e) {
2354
- const t = e?.[$TARGET];
2355
- return snapshotWalk(e, new Map, t?.fam ?? null);
2356
- }
2357
-
2358
- function snapshotWalk(e, t, n) {
2359
- if (e === null || typeof e !== "object") return e;
2360
- // Resolve through the registration: proxies AND raws map to their target's
2361
- // current backing (stale raw pointers through other parents resolve here).
2362
- // Loops for chained backings (§7b: a projection's backing can be another
2363
- // store's proxy — snapshot unwraps to the base raw).
2364
- let r = e;
2365
- // Chained backings can pass through several targets; optimistic overrides
2366
- // on OUTER targets shadow the chain (§7b), so collect every opt target
2367
- // encountered and compose their views over the resolved base, innermost
2368
- // outward.
2369
- let i = null;
2370
- for (let e = true; ;e = false) {
2371
- const t = r?.[$TARGET]?.v !== undefined;
2372
- let o = t ? r[$TARGET] : undefined;
2373
- if (o === undefined && n !== null) o = lookupTarget(r, n);
2374
- if (o === undefined) o = lookupTarget(r, null);
2375
- if (o === undefined) break;
2376
- // Entering a level from a RAW below a chained family: the raw resolves to
2377
- // the INNER store's target, but this family's wrapper for it — keyed by
2378
- // the inner proxy, §7b — is where the outer overrides live. Start from
2379
- // the wrapper so they compose (#3323: a nested optimistic write on a view
2380
- // row was served by reads but missing from deep()/snapshot()). Entry only:
2381
- // the descent then runs wrapper → inner → raw and terminates.
2382
- if (e && !t && n !== null && o.fam !== n) {
2383
- const e = n.map.get(o.px);
2384
- if (e !== undefined) o = e;
2385
- }
2386
- if (o.fam !== null) n = o.fam;
2387
- if (o.fam?.opt === true) (i ??= []).push(o);
2388
- // The shared visibility decision (#3147): the speculative peek serves
2389
- // pending staging, but a HELD landing is masked to committed exactly as
2390
- // it is for per-key readers — the two families must answer alike while
2391
- // a transaction holds store landings.
2392
- const l = pendingBackingVisible(o, true);
2393
- // Snapshot runs mid-flush (tracked memos execute before commit), so a
2394
- // pending prototype overlay must present as a REAL merged container.
2395
- if (l && o.ovl) materializePB(o);
2396
- const s = l ? o.pb : o.v;
2397
- if (s === r) break;
2398
- r = s;
2399
- }
2400
- if (!isWrappable(r)) return r;
2401
- // Optimistic families: compose the visible view; a composed view is a fresh
2402
- // object and snapshots via the owned/copy path (pinned `not.toBe` identity).
2403
- if (i !== null) {
2404
- let e = r;
2405
- for (let t = i.length - 1; t >= 0; t--) {
2406
- const n = i[t];
2407
- // Draft twin (#3665): deep()/snapshot() inside a setter is the writer's
2408
- // channel and composes on the tick's own unflushed adds
2409
- // (hasActiveOverride). A draft that has seeded its own backing from
2410
- // the view already carries them in `src` — composing again would
2411
- // clobber the draft's later writes with the overrides they superseded.
2412
- const r = inDraft(n);
2413
- if (r && !draftSeesOverrides(n)) continue;
2414
- e = optHooks.optimisticView(n, e, r);
2415
- }
2416
- if (e !== r) {
2417
- const i = t.get(r);
2418
- if (i !== undefined) return i;
2419
- const o = Array.isArray(e);
2420
- const l = o ? [] : Object.create(Object.getPrototypeOf(e));
2421
- t.set(r, l);
2422
- for (const r of Reflect.ownKeys(e)) {
2423
- if (o && r === "length" || r === $OWNER) continue;
2424
- const i = e[r];
2425
- l[r] = i !== null && typeof i === "object" ? snapshotWalk(i, t, n) : i;
2426
- }
2427
- if (o) l.length = e.length;
2428
- return l;
2429
- }
2430
- }
2431
- const o = t.get(r);
2432
- if (o !== undefined) return o;
2433
- // OWNED (written) subtrees snapshot as copies (§7b: identity is only for
2434
- // subtrees "unmodified relative to source"): non-enumerable symbols are
2435
- // excluded (recon-snap R29), and the copy registers BEFORE descent so
2436
- // cycles keep identity (FINDING-3).
2437
- if (isOwned(r)) {
2438
- const e = Array.isArray(r);
2439
- const i = e ? [] : Object.create(Object.getPrototypeOf(r));
2440
- t.set(r, i);
2441
- for (const o of Reflect.ownKeys(r)) {
2442
- if (e && o === "length" || o === $OWNER) continue;
2443
- const l = Object.getOwnPropertyDescriptor(r, o);
2444
- if (typeof o === "symbol" && !l.enumerable) continue;
2445
- if (l.get || l.set) {
2446
- Object.defineProperty(i, o, l);
2447
- continue;
2448
- }
2449
- const s = l.value;
2450
- const f = s !== null && typeof s === "object" ? snapshotWalk(s, t, n) : s;
2451
- if (l.enumerable && l.writable && l.configurable) i[o] = f; else Object.defineProperty(i, o, {
2452
- ...l,
2453
- value: f
2454
- });
2455
- }
2456
- if (e && i.length !== r.length) i.length = r.length;
2457
- return i;
2458
- }
2459
- // UNOWNED (shared/user) subtrees keep identity unless a descendant
2460
- // substituted; copy-on-substitution preserves the documented CoW contract.
2461
- t.set(r, r);
2462
- let l = null;
2463
- for (const e of Reflect.ownKeys(r)) {
2464
- const i = Object.getOwnPropertyDescriptor(r, e);
2465
- if (!i || i.get || i.set) continue;
2466
- const o = i.value;
2467
- if (o === null || typeof o !== "object") continue;
2468
- const s = snapshotWalk(o, t, n);
2469
- if (s !== o) {
2470
- if (l === null) {
2471
- l = Array.isArray(r) ? [ ...r ] : Object.create(Object.getPrototypeOf(r), Object.getOwnPropertyDescriptors(r));
2472
- t.set(r, l);
2473
- }
2474
- l[e] = s;
2475
- }
2476
- }
2477
- return l ?? r;
2478
- }
2479
-
2480
- export { adoptPB, arrayStructureChanged, authoritativeRead, authoritativeServe, bumpDeep, createStoreNext, deepNext, derivedStoreWrite, getHasNode, getKeySetNode, getNode, hasAccessorFlag, hasActiveOverride, heldMaskView, materializePB, membershipChanged, nameStore, notifyFold, notifyFoldTail, notifyKeyDiff, notifyKeyValue, readerOverride, runAuthoritative, snapshotNext, stagedTruthPB, storeHasFamily, storeHasOptimisticFamily, storeIsShallow, storeSetterNext, targetsEqual, unwrapValue, visibleOverride, wrapNext };