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