svelte 5.58.0 → 5.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/compiler/index.js +1 -1
  2. package/package.json +1 -1
  3. package/src/compiler/phases/3-transform/client/utils.js +3 -2
  4. package/src/compiler/phases/3-transform/server/visitors/ExpressionStatement.js +8 -0
  5. package/src/compiler/print/index.js +45 -57
  6. package/src/index-client.js +3 -3
  7. package/src/internal/client/constants.js +8 -1
  8. package/src/internal/client/dev/debug.js +6 -6
  9. package/src/internal/client/dev/tracing.js +67 -11
  10. package/src/internal/client/dom/blocks/async.js +2 -1
  11. package/src/internal/client/dom/blocks/await.js +108 -18
  12. package/src/internal/client/dom/blocks/boundary.js +107 -70
  13. package/src/internal/client/dom/blocks/branches.js +15 -22
  14. package/src/internal/client/dom/blocks/each.js +88 -13
  15. package/src/internal/client/dom/elements/attributes.js +2 -1
  16. package/src/internal/client/dom/elements/bindings/input.js +19 -10
  17. package/src/internal/client/dom/elements/bindings/select.js +2 -7
  18. package/src/internal/client/dom/elements/events.js +27 -2
  19. package/src/internal/client/dom/operations.js +2 -3
  20. package/src/internal/client/error-handling.js +4 -12
  21. package/src/internal/client/errors.js +18 -2
  22. package/src/internal/client/index.js +0 -1
  23. package/src/internal/client/reactivity/async.js +247 -122
  24. package/src/internal/client/reactivity/batch.js +1102 -530
  25. package/src/internal/client/reactivity/deriveds.js +281 -177
  26. package/src/internal/client/reactivity/effects.js +44 -28
  27. package/src/internal/client/reactivity/sources.js +30 -124
  28. package/src/internal/client/reactivity/status.js +1 -1
  29. package/src/internal/client/render.js +11 -0
  30. package/src/internal/client/runtime.js +925 -152
  31. package/src/internal/client/validate.js +2 -2
  32. package/src/version.js +1 -1
  33. package/types/index.d.ts +1 -1
  34. package/types/index.d.ts.map +1 -1
  35. package/src/internal/client/reactivity/utils.js +0 -18
@@ -1,5 +1,6 @@
1
1
  /** @import { Fork } from 'svelte' */
2
- /** @import { Derived, Effect, Reaction, Source, Value } from '#client' */
2
+ /** @import { BatchRecord, BatchValue, Derived, DerivedRecord, Effect, Reaction, Source, Value } from '#client' */
3
+ /** @import { Boundary } from '../dom/blocks/boundary.js' */
3
4
  import {
4
5
  BLOCK_EFFECT,
5
6
  BRANCH_EFFECT,
@@ -7,7 +8,6 @@ import {
7
8
  DESTROYED,
8
9
  DIRTY,
9
10
  EFFECT,
10
- ASYNC,
11
11
  INERT,
12
12
  RENDER_EFFECT,
13
13
  ROOT_EFFECT,
@@ -17,31 +17,51 @@ import {
17
17
  ERROR_VALUE,
18
18
  MANAGED_EFFECT,
19
19
  REACTION_RAN,
20
- DESTROYING
20
+ DESTROYING,
21
+ EFFECT_OFFSCREEN,
22
+ ASSIGNED,
23
+ ASYNC,
24
+ REACTION_IS_UPDATING,
25
+ BOUNDARY_EFFECT
21
26
  } from '#client/constants';
22
27
  import { async_mode_flag } from '../../flags/index.js';
23
- import { deferred, define_property, includes } from '../../shared/utils.js';
28
+ import { deferred, define_property } from '../../shared/utils.js';
24
29
  import {
30
+ active_effect,
25
31
  active_reaction,
26
32
  get,
27
33
  increment_write_version,
34
+ is_destroying_effect,
28
35
  is_dirty,
29
- update_effect
36
+ is_outdated,
37
+ promote_record,
38
+ prune_edges,
39
+ untrack,
40
+ update_effect,
41
+ write_version,
42
+ abort_record
30
43
  } from '../runtime.js';
31
44
  import * as e from '../errors.js';
32
45
  import { flush_tasks, queue_micro_task } from '../dom/task.js';
33
46
  import { DEV } from 'esm-env';
34
47
  import { invoke_error_boundary } from '../error-handling.js';
35
- import { flush_eager_effects, old_values, set_eager_effects, source, update } from './sources.js';
48
+ import {
49
+ eager_effects,
50
+ eager_effects_deferred,
51
+ flush_eager_effects,
52
+ source,
53
+ update
54
+ } from './sources.js';
36
55
  import { eager_effect, teardown, unlink_effect } from './effects.js';
37
- import { defer_effect } from './utils.js';
38
56
  import { UNINITIALIZED } from '../../../constants.js';
39
- import { set_signal_status } from './status.js';
57
+ import { set_signal_status, update_derived_status } from './status.js';
40
58
  import { invariant } from '../../shared/dev.js';
41
59
  import { OBSOLETE } from './deriveds.js';
60
+ import { is_runes } from '../context.js';
61
+ import { merge_target } from './async.js';
42
62
 
43
63
  /** @type {Batch | null} */
44
- let first_batch = null;
64
+ export let first_batch = null;
45
65
 
46
66
  /** @type {Batch | null} */
47
67
  let last_batch = null;
@@ -50,24 +70,99 @@ let last_batch = null;
50
70
  export let current_batch = null;
51
71
 
52
72
  /**
53
- * This is needed to avoid overwriting inputs
73
+ * The batch currently being processed (see `#process`)
54
74
  * @type {Batch | null}
55
75
  */
56
- export let previous_batch = null;
76
+ export let processing_batch = null;
77
+
78
+ /**
79
+ * @typedef {Object} TeardownContext
80
+ * @property {Map<Value, BatchValue>} reverted_values What teardowns see instead of the values sources hold: the values
81
+ * from before the writes that caused the teardowns (the `previous` of the batch being processed, see `flush`). For
82
+ * block effects that re-run right away because of a user effect's writes, also the writes of the effects that ran
83
+ * before it in the same commit, which apply (see `flush_queued_effects`)
84
+ * @property {Map<Derived, BatchValue>} derived_cache The values of deriveds in this view (see `runtime.js#teardown_view`),
85
+ * until it changes
86
+ * @property {TeardownContext | null} parent The context to restore after a nested flush or eager block
87
+ */
88
+
89
+ /**
90
+ * Effect teardowns revert the writes that caused them (see `runtime.js#teardown_view`).
91
+ * (A teardown outside of a flush reverts nothing, but gets a context to cache its deriveds in, for as long as it
92
+ * runs — see `execute_effect_teardown`)
93
+ * @type {TeardownContext | null}
94
+ */
95
+ export let teardown_context = null;
96
+
97
+ /** @param {TeardownContext | null} context */
98
+ export function set_teardown_context(context) {
99
+ teardown_context = context;
100
+ }
101
+
102
+ /** @param {Map<Value, BatchValue>} [values] */
103
+ export function push_teardown_context(values) {
104
+ var context = (teardown_context = {
105
+ reverted_values: new Map(teardown_context?.reverted_values),
106
+ derived_cache: new Map(),
107
+ parent: teardown_context
108
+ });
109
+
110
+ for (const [source, value] of values ?? []) context.reverted_values.set(source, value);
111
+
112
+ return context;
113
+ }
114
+
115
+ /**
116
+ * A write in a teardown remains visible after returning to an enclosing teardown view,
117
+ * and the deriveds that teardowns evaluated may depend on it
118
+ * @param {Value} source
119
+ */
120
+ export function teardown_write(source) {
121
+ for (var context = teardown_context; context !== null; context = context.parent) {
122
+ context.reverted_values.delete(source);
123
+ context.derived_cache.clear();
124
+ }
125
+ }
57
126
 
58
127
  /**
59
128
  * When time travelling (i.e. working in one batch, while other batches
60
129
  * still have ongoing work), we ignore the real values of affected
61
- * signals in favour of their values within the batch
62
- * @type {Map<Value, any> | null}
130
+ * signals in favour of their values within the batch — along with their
131
+ * versions: the batch's writes, and the values from before the writes of
132
+ * other batches, which its view of the world undoes (see `activate`).
133
+ * `null` means that the real world (i.e. the latest values) applies.
134
+ * Doesn't contain computed deriveds, these are in {@link view_cache}.
135
+ * @type {Map<Value, BatchValue> | null}
63
136
  */
64
137
  export let batch_values = null;
65
138
 
139
+ /**
140
+ * The values of deriveds in the active view of the world, for as long as it is active (see `get_view`):
141
+ * a record of a run (in which case `e` tells whether its value is an error), the derived itself if its
142
+ * global state applies, or the write to it that holds (an assignment). Exists whenever `batch_values` does
143
+ * @type {Map<Derived, Derived | DerivedRecord | BatchValue> | null}
144
+ */
145
+ export let view_cache = null;
146
+
147
+ /**
148
+ * The batch whose view of the world is active (see `activate`). Block and async
149
+ * effects that run while it is processed, and deriveds evaluated with values
150
+ * that are not the latest, are recorded in this batch
151
+ * @type {Batch | null}
152
+ */
153
+ export let view_batch = null;
154
+
66
155
  /** @type {Effect | null} */
67
156
  let last_scheduled_effect = null;
68
157
 
158
+ /**
159
+ * Batches whose view of the world changed because another batch committed, and that
160
+ * therefore need to be processed again once the current flush is done (see `#commit`)
161
+ * @type {Set<Batch>}
162
+ */
163
+ var rebases = new Set();
164
+
69
165
  export let is_flushing_sync = false;
70
- let is_processing = false;
71
166
 
72
167
  /**
73
168
  * During traversal, this is an array. Newly created effects are (if not immediately
@@ -91,8 +186,22 @@ var flush_count = 0;
91
186
  /** Sources whose DEV update counts and stack traces need resetting after the flush. @type {Set<Value>} */
92
187
  export const source_stacks = new Set();
93
188
 
189
+ /**
190
+ * A set of signals we have already seen while traversing in `batch.mark`.
191
+ * Not always set to balance the common case of sources only having a couple
192
+ * of (transitive) dependencies (where always creating a Set would be bad for perf)
193
+ * with the edge case of extremely deep or wide dependency arrays with cycles.
194
+ * @type {Set<any> | null}
195
+ */
196
+ var seen = null;
197
+ /** Number of transitive dependencies, see {@link seen} for more info */
198
+ var count_deps = 0;
199
+
94
200
  let uid = 1;
95
201
 
202
+ /** @type {number | null} */
203
+ let last_processed = null;
204
+
96
205
  export class Batch {
97
206
  id = uid++;
98
207
 
@@ -111,43 +220,60 @@ export class Batch {
111
220
  async_deriveds = new Map();
112
221
 
113
222
  /**
114
- * The current values of any signals that are updated in this batch.
115
- * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)
116
- * The keys of this map are identical to `this.previous`
117
- * @type {Map<Value, [any, boolean]>}
223
+ * The current values (and their versions) of any sources that are updated in this batch,
224
+ * including deriveds that were overridden via assignment — until it commits them (see `#commit`).
225
+ * Its keys are those of `this.previous`, plus the sources this batch gave their first value. `e` says whether
226
+ * the value is an error
227
+ * @type {Map<Value, BatchValue>}
118
228
  */
119
229
  current = new Map();
120
230
 
121
231
  /**
122
- * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place.
123
- * The keys of this map are identical to `this.current`
124
- * @type {Map<Value, any>}
232
+ * The values (and their versions) of any sources that are updated in this batch _before_ those updates took place.
233
+ * For a derived, `assigned` says whether its value before was assigned, too (otherwise it was computed).
234
+ * A source that this batch gave its first value (e.g. an async expression that resolved for the first time) has
235
+ * no entry: there's no value from before it, so other views can't undo the write, and teardowns don't revert it.
236
+ * @type {Map<Value, BatchValue>}
125
237
  */
126
238
  previous = new Map();
127
239
 
128
240
  /**
129
- * When the batch is committed (and the DOM is updated), we need to remove old branches
130
- * and append new ones by calling the functions added inside (if/each/key/etc) blocks
131
- * @type {Set<(batch: Batch) => void>}
241
+ * Results of reactions that belong to this batch rather than to the real world:
242
+ * deriveds evaluated in this batch's view of the world with values that are not the
243
+ * latest ones, and block/async effects that ran while this batch was processed.
244
+ * Effect records become global state when the batch commits (see `promote_record`)
245
+ * @type {Map<Reaction, BatchRecord> | null}
132
246
  */
133
- #commit_callbacks = new Set();
247
+ records = null;
134
248
 
135
249
  /**
136
- * If a fork is discarded, we need to destroy any effects that are no longer needed
137
- * @type {Set<(batch: Batch) => void>}
250
+ * Earlier batches whose changes are part of this batch's view of the world, because
251
+ * they intersect with it (this batch will be merged into them, see `#merge`)
252
+ * @type {Batch[]}
138
253
  */
139
- #discard_callbacks = new Set();
254
+ folded = [];
140
255
 
141
256
  /**
142
- * The number of async effects that are currently in flight
257
+ * When the batch is committed (and the DOM is updated), we need to remove old branches
258
+ * and append new ones by calling the functions added inside (if/each/key/etc) blocks.
259
+ * Each callback maps to the writes that apply in the teardowns it causes, if it was added
260
+ * while block effects re-ran eagerly (see `eager_block_writes`)
261
+ * @type {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>}
262
+ */
263
+ #commit_callbacks = new Map();
264
+
265
+ /**
266
+ * If a fork is discarded, we need to destroy any effects that are no longer needed
267
+ * (see `#commit_callbacks`)
268
+ * @type {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>}
143
269
  */
144
- #pending = 0;
270
+ #discard_callbacks = new Map();
145
271
 
146
272
  /**
147
- * Async effects that are currently in flight, _not_ inside a pending boundary
273
+ * Async effects that are currently in flight
148
274
  * @type {Map<Effect, number>}
149
275
  */
150
- #blocking_pending = new Map();
276
+ #pending = new Map();
151
277
 
152
278
  /**
153
279
  * A deferred that resolves when the batch is committed, used with `settled()`
@@ -156,6 +282,14 @@ export class Batch {
156
282
  */
157
283
  #deferred = null;
158
284
 
285
+ /**
286
+ * Effects to (re-)validate when this batch is processed next, and their status (DIRTY or MAYBE_DIRTY):
287
+ * those that were scheduled while it wasn't being processed (see {@link schedule}), and those whose run
288
+ * was deferred because it has pending work (see `#defer_effects`)
289
+ * @type {Map<Effect, number>}
290
+ */
291
+ #unprocessed = new Map();
292
+
159
293
  /**
160
294
  * Effects that were scheduled in this batch but not yet 'resolved' into the
161
295
  * root effects that need to be flushed. Resolving — the upwards traversal that
@@ -170,33 +304,35 @@ export class Batch {
170
304
  #scheduled = [];
171
305
 
172
306
  /**
173
- * Effects created while this batch was active.
174
- * @type {Effect[]}
307
+ * Branches that still exist, but will be destroyed when this batch
308
+ * is committed — we skip over these during `#process`
309
+ * @type {Set<Effect>}
175
310
  */
176
- #new_effects = [];
311
+ #skipped_branches = new Set();
177
312
 
178
313
  /**
179
- * Deferred effects (which run after async work has completed) and their status (DIRTY or MAYBE_DIRTY)
180
- * @type {Map<Effect, number>}
314
+ * Branches that this batch selected (see `unskip_effect`). A branch that is offscreen until
315
+ * it is committed (see `EFFECT_OFFSCREEN`) only exists in the views of the batches that selected it
316
+ * @type {Set<Effect>}
181
317
  */
182
- #dirty_reactions = new Map();
318
+ #unskipped_branches = new Set();
319
+
320
+ is_fork = false;
183
321
 
184
322
  /**
185
- * A map of branches that still exist, but will be destroyed when this batch
186
- * is committed — we skip over these during `process`.
187
- * The value contains child effects that were dirty/maybe_dirty before being reset,
188
- * so they can be rescheduled if the branch survives.
189
- * @type {Map<Effect, { d: Effect[], m: Effect[] }>}
323
+ * The batch that this one was merged into, if any (see `#merge`). Its async work that is still in flight
324
+ * continues as part of that one
325
+ * @type {Batch | null}
190
326
  */
191
- #skipped_branches = new Map();
327
+ merged = null;
192
328
 
193
329
  /**
194
- * Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing
195
- * @type {Set<Effect>}
330
+ * Batches whose runs this batch aborted. Merge into them before waiting for pending work.
331
+ * Requests belong to this batch because a synchronous derived can abort outside traversal,
332
+ * before an unrelated batch is processed (e.g. a fork being committed).
333
+ * @type {Set<Batch>}
196
334
  */
197
- #unskipped_branches = new Set();
198
-
199
- is_fork = false;
335
+ merge_requests = new Set();
200
336
 
201
337
  #decrement_queued = false;
202
338
 
@@ -214,9 +350,8 @@ export class Batch {
214
350
  #is_deferred() {
215
351
  if (this.is_fork) return true;
216
352
 
217
- for (const effect of this.#blocking_pending.keys()) {
218
- // pending work inside a skipped branch doesn't block, the branch is going to be destroyed
219
- if (!this.#is_skipped(effect)) {
353
+ for (const effect of this.#pending.keys()) {
354
+ if (this.is_blocked_by(effect)) {
220
355
  return true;
221
356
  }
222
357
  }
@@ -225,50 +360,107 @@ export class Batch {
225
360
  }
226
361
 
227
362
  /**
228
- * Whether `effect` is inside a branch that this batch skips
363
+ * Whether `effect` is a branch that this batch skips, or that only exists offscreen for other batches
364
+ * @param {Effect} effect
365
+ */
366
+ #skips(effect) {
367
+ return (
368
+ this.#skipped_branches.has(effect) ||
369
+ ((effect.f & EFFECT_OFFSCREEN) !== 0 && !this.#unskipped_branches.has(effect))
370
+ );
371
+ }
372
+
373
+ /**
374
+ * Whether `effect` is inside a branch that this batch skips, i.e. doesn't exist in its view of the world
229
375
  * @param {Effect} effect
230
376
  */
231
- #is_skipped(effect) {
377
+ is_skipped(effect) {
232
378
  for (var e = /** @type {Effect | null} */ (effect); e !== null; e = e.parent) {
233
- if (this.#skipped_branches.has(e)) return true;
379
+ if (this.#skips(e)) return true;
234
380
  }
235
381
 
236
382
  return false;
237
383
  }
238
384
 
239
385
  /**
240
- * Add an effect to the #skipped_branches map and reset its children
386
+ * Whether async work in `effect` holds up this batch — or, with `root`, the boundary whose content `root` is.
387
+ * It doesn't if the effect is inside a branch that this batch skips (the branch is going to be destroyed),
388
+ * or inside a boundary that is pending (which shows its pending snippet in the meantime).
389
+ * Unlike a skipped branch, the content of a pending boundary does exist in the view of the batch: its
390
+ * effects are still re-validated (see `#revalidate`), they just don't keep the batch from committing
241
391
  * @param {Effect} effect
392
+ * @param {Effect | null} [root]
242
393
  */
243
- skip_effect(effect) {
244
- if (!this.#skipped_branches.has(effect)) {
245
- this.#skipped_branches.set(effect, { d: [], m: [] });
394
+ is_blocked_by(effect, root = null) {
395
+ for (var e = /** @type {Effect | null} */ (effect); e !== null && e !== root; e = e.parent) {
396
+ if (this.#skips(e)) return false;
397
+
398
+ if (
399
+ (e.f & (BOUNDARY_EFFECT | DESTROYED)) === BOUNDARY_EFFECT &&
400
+ /** @type {Boundary} */ (e.b).is_pending
401
+ ) {
402
+ return false;
403
+ }
246
404
  }
405
+
406
+ return true;
407
+ }
408
+
409
+ /**
410
+ * @param {Effect} effect
411
+ */
412
+ skip_effect(effect) {
413
+ this.#skipped_branches.add(effect);
247
414
  this.#unskipped_branches.delete(effect);
248
415
  }
249
416
 
250
417
  /**
251
- * Remove an effect from the #skipped_branches map and reschedule
252
- * any tracked dirty/maybe_dirty child effects
253
418
  * @param {Effect} effect
254
- * @param {(e: Effect) => void} callback
255
419
  */
256
- unskip_effect(effect, callback = (e) => this.schedule(e)) {
257
- var tracked = this.#skipped_branches.get(effect);
258
- if (tracked) {
259
- this.#skipped_branches.delete(effect);
260
-
261
- for (var e of tracked.d) {
262
- set_signal_status(e, DIRTY);
263
- callback(e);
264
- }
420
+ unskip_effect(effect) {
421
+ if (
422
+ this.#skipped_branches.delete(effect) ||
423
+ (!this.#unskipped_branches.has(effect) &&
424
+ ((effect.f & EFFECT_OFFSCREEN) !== 0 ||
425
+ this.folded.some((batch) => batch.#skipped_branches.has(effect))))
426
+ ) {
427
+ // This batch adopts a branch that it skipped (whose effects may have been reset, see `reset_branch`),
428
+ // that so far only existed offscreen (possibly for another batch, whose view of the world its
429
+ // effects ran in), or that a batch whose writes are part of its view skips (and so didn't run the
430
+ // effects that its writes affect, or reset them) — re-validate its effects in this batch's view
431
+ this.revalidate_branch(effect);
432
+ }
433
+
434
+ this.#unskipped_branches.add(effect);
435
+ }
436
+
437
+ /**
438
+ * Like `unskip_effect`, for a branch that was just created offscreen while this batch is processed.
439
+ * Its effects ran in this batch's view of the world when they were created, so there's nothing to re-validate
440
+ * TODO can we skip revalidation in `unskip_effect` in more cases, by detecting whether things changed
441
+ * inside a branch while it was skipped?
442
+ * @param {Effect} effect
443
+ */
444
+ unskip_new_effect(effect) {
445
+ this.#unskipped_branches.add(effect);
446
+ }
447
+
448
+ /**
449
+ * @param {Effect} effect
450
+ */
451
+ revalidate_branch(effect) {
452
+ for (var e = effect.first; e !== null; e = e.next) {
453
+ var flags = e.f;
454
+
455
+ // (branches nested inside that exist offscreen for other batches only are not adopted)
456
+ if ((flags & (DESTROYED | INERT)) === 0 && !this.#skips(e)) {
457
+ if ((flags & (BRANCH_EFFECT | ROOT_EFFECT | EAGER_EFFECT)) === 0 && e.fn !== null) {
458
+ this.schedule(e, MAYBE_DIRTY);
459
+ }
265
460
 
266
- for (e of tracked.m) {
267
- set_signal_status(e, MAYBE_DIRTY);
268
- callback(e);
461
+ this.revalidate_branch(e);
269
462
  }
270
463
  }
271
- this.#unskipped_branches.add(effect);
272
464
  }
273
465
 
274
466
  /**
@@ -320,18 +512,38 @@ export class Batch {
320
512
  }
321
513
 
322
514
  #process() {
515
+ current_batch = processing_batch = this;
516
+
517
+ // A different batch view may apply, even when processing continues within the same flush.
518
+ teardown_context?.derived_cache.clear();
519
+
520
+ if (async_mode_flag && this.started && last_processed !== this.id) {
521
+ // Since this batch last ran, reactions may have come to depend on its writes without it
522
+ // knowing (e.g. effects created by other batches), or have run in the view of other batches.
523
+ // Re-validate them in this batch's view — this only re-runs those that are out of date
524
+ this.#revalidate(this.current.keys());
525
+ }
526
+
323
527
  this.started = true;
528
+ last_processed = this.id;
529
+
530
+ // Deferred effects are rescheduled even if the batch still has pending work, because traversing the
531
+ // tree could make an if block that contains the last blocking pending effect falsy, causing the batch
532
+ // to no longer be deferred. If it still is, they are deferred again
533
+ if (this.#unprocessed.size > 0) {
534
+ for (const [e, status] of this.#unprocessed) this.#add(e, status);
535
+ this.#unprocessed.clear();
536
+ }
324
537
 
325
- // We always reschedule previously-deferred effects, not just when
326
- // #is_deferred() is true, because traversing the tree could make
327
- // an if block that contains the last blocking pending effect falsy,
328
- // causing the block to no longer be deferred.
329
- for (const [e, status] of this.#dirty_reactions) {
330
- set_signal_status(e, status);
331
- this.schedule(e);
538
+ if (DEV) {
539
+ // track all the values that were updated during this flush,
540
+ // so that they can be reset afterwards
541
+ for (const value of this.current.keys()) {
542
+ source_stacks.add(value);
543
+ }
332
544
  }
333
545
 
334
- this.apply();
546
+ this.activate();
335
547
 
336
548
  /** @type {Effect[]} */
337
549
  var effects = (collected_effects = []);
@@ -339,6 +551,9 @@ export class Batch {
339
551
  /** @type {Effect[]} */
340
552
  var render_effects = [];
341
553
 
554
+ /** @type {Boundary[]} */
555
+ var revealed_boundaries = [];
556
+
342
557
  /**
343
558
  * @type {Effect[]}
344
559
  * @deprecated when we get rid of legacy mode and stores, we can get rid of this
@@ -351,14 +566,14 @@ export class Batch {
351
566
  while (this.#scheduled.length > 0) {
352
567
  if (flush_count++ > 1000) {
353
568
  this.#unlink();
354
- infinite_loop_guard(); // TODO try to reset_all() here?
569
+ infinite_loop_guard(); // TODO try to reset the tree here?
355
570
  }
356
571
 
357
572
  for (const root of this.#resolve()) {
358
573
  try {
359
- this.#traverse(root, effects, render_effects);
574
+ this.#traverse(root, effects, render_effects, revealed_boundaries);
360
575
  } catch (e) {
361
- reset_all(root);
576
+ reset_branch(root, true);
362
577
  // If there's no async work left, this branch is now dead and needs
363
578
  // to be discarded to not become a zombie that is never cleaned up.
364
579
  // See https://github.com/sveltejs/svelte/issues/18221#issuecomment-4497918414
@@ -386,20 +601,48 @@ export class Batch {
386
601
  if (updates.length > 0) {
387
602
  var batch = Batch.ensure();
388
603
  for (const e of updates) {
389
- batch.schedule(e);
604
+ // these were marked during traversal already (see `mark_reactions`), unless they ran since
605
+ if ((e.f & CLEAN) === 0) batch.schedule(e, MAYBE_DIRTY);
390
606
  }
391
607
  }
392
608
 
393
609
  collected_effects = null;
394
610
  legacy_updates = null;
395
611
 
612
+ if (this.merge_requests.size > 0) {
613
+ const sorted = Array.from(this.merge_requests, merge_target)
614
+ .filter((batch) => batch !== this && batch.linked && !batch.is_fork)
615
+ .sort((a, b) => a.id - b.id);
616
+ this.merge_requests.clear();
617
+
618
+ if (sorted.length > 0) {
619
+ this.#defer_effects(render_effects);
620
+ this.#defer_effects(effects);
621
+
622
+ /** @type {Batch} */
623
+ var target = this;
624
+ var i = sorted.length;
625
+
626
+ while (i--) {
627
+ var earlier = sorted[i];
628
+ if (earlier === target) continue;
629
+ earlier.#merge(target);
630
+ target = earlier;
631
+ }
632
+
633
+ // Revalidate once all the writes and pending work belong to the same batch.
634
+ target.#process();
635
+ return;
636
+ }
637
+ }
638
+
396
639
  // if the batch has outstanding pending work, stash effects and bail
397
640
  if (this.#is_deferred()) {
398
641
  this.#defer_effects(render_effects);
399
642
  this.#defer_effects(effects);
400
643
 
401
- for (const [e, t] of this.#skipped_branches) {
402
- reset_branch(e, t);
644
+ for (const e of this.#skipped_branches) {
645
+ reset_branch(e);
403
646
  }
404
647
 
405
648
  if (updates.length > 0) {
@@ -417,53 +660,111 @@ export class Batch {
417
660
  this.#defer_effects(render_effects);
418
661
  this.#defer_effects(effects);
419
662
  earlier_batch.#merge(this);
663
+ earlier_batch.#process();
664
+
420
665
  return;
421
666
  }
422
667
 
423
- // clear effects. Those that are still needed will be rescheduled through unskipping the skipped branches.
424
- this.#dirty_reactions.clear();
668
+ for (const boundary of revealed_boundaries) {
669
+ // A later traversal may have restored an unresolved branch since this boundary was queued.
670
+ if (boundary.is_pending && boundary.is_ready(this)) {
671
+ boundary.reveal(effects);
672
+ }
673
+ }
674
+
675
+ // The results of this batch are about to become the real-world state
676
+ this.#release_records(true);
425
677
 
426
678
  // append/remove branches
427
- for (const fn of this.#commit_callbacks) fn(this);
428
- this.#commit_callbacks.clear();
679
+ this.#run_callbacks(this.#commit_callbacks);
429
680
 
430
- previous_batch = this;
431
- flush_queued_effects(render_effects);
432
- flush_queued_effects(effects);
433
- previous_batch = null;
681
+ var earlier_writes = flush_queued_effects(render_effects);
682
+ flush_queued_effects(effects, earlier_writes);
434
683
 
435
684
  this.#deferred?.resolve();
436
685
 
437
686
  var next_batch = /** @type {Batch | null} */ (/** @type {unknown} */ (current_batch));
438
687
 
439
- if (this.#pending === 0 && (this.#scheduled.length === 0 || next_batch !== null)) {
688
+ if (this.#pending.size === 0 && (this.#scheduled.length === 0 || next_batch !== null)) {
440
689
  this.#unlink();
690
+ }
441
691
 
442
- // Order matters here - we need to commit and THEN continue flushing new batches, not the other way around,
443
- // else we could start flushing a new batch and then, if it has pending work, rebase it right afterwards, which is wrong.
444
- // In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode
445
- // TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed
446
- if (async_mode_flag) {
447
- this.#commit();
448
- // Rebases can activate other batches or null it out, therefore restore the new one here
449
- current_batch = next_batch;
450
- }
692
+ // Order matters here - we need to commit and THEN continue flushing new batches, not the other way around,
693
+ // else we could start flushing a new batch and then, if it has pending work, rebase it right afterwards, which is wrong.
694
+ // In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode
695
+ // TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed
696
+ if (async_mode_flag) {
697
+ this.commit_writes();
451
698
  }
452
699
 
453
700
  if (next_batch !== null) {
454
- old_values.clear();
701
+ // The next batch holds the writes made while this one committed, which cause the teardowns that run
702
+ // when it's processed. So teardowns now revert those, and no longer this batch's: of the reverted
703
+ // values, keep those that are the next batch's values from before its writes. (Writes made in teardowns
704
+ // aren't among them, see `teardown_write`, so they stay visible)
705
+ if (teardown_context !== null) {
706
+ for (const [source, snapshot] of teardown_context.reverted_values) {
707
+ if (next_batch.previous.get(source)?.wv !== snapshot.wv) {
708
+ teardown_context.reverted_values.delete(source);
709
+ }
710
+ }
711
+ }
712
+
455
713
  next_batch.#process();
456
714
  }
457
715
  }
458
716
 
717
+ /**
718
+ * Schedule the reactions that (transitively) depend on `sources` for re-validation in this batch.
719
+ * They are marked MAYBE_DIRTY, which means that they are only re-run if the exact versions
720
+ * of their dependencies differ from the ones they last saw (in this batch's view of the world)
721
+ * @param {Iterable<Source>} sources
722
+ */
723
+ #revalidate(sources) {
724
+ // deriveds added during iteration are visited too, so this doubles as a worklist
725
+ /** @type {Set<Value>} */
726
+ var values = new Set(sources);
727
+
728
+ /** @type {Set<Effect>} */
729
+ var effects = new Set();
730
+
731
+ for (const value of values) {
732
+ var reactions = value.reactions;
733
+ if (reactions === null) continue;
734
+
735
+ for (const reaction of reactions) {
736
+ var flags = reaction.f;
737
+
738
+ if ((flags & DERIVED) !== 0) {
739
+ if ((flags & CLEAN) !== 0) set_signal_status(reaction, MAYBE_DIRTY);
740
+ values.add(/** @type {Derived} */ (reaction));
741
+ continue;
742
+ }
743
+
744
+ var effect = /** @type {Effect} */ (reaction);
745
+ if (effects.has(effect)) continue;
746
+ effects.add(effect);
747
+
748
+ if (
749
+ (flags & (EAGER_EFFECT | INERT | DESTROYED)) === 0 &&
750
+ // branches that this batch skips don't exist in its view of the world
751
+ !this.is_skipped(effect)
752
+ ) {
753
+ this.schedule(effect, MAYBE_DIRTY);
754
+ }
755
+ }
756
+ }
757
+ }
758
+
459
759
  /**
460
760
  * Traverse the effect tree, executing effects or stashing
461
761
  * them for later execution as appropriate
462
762
  * @param {Effect} root
463
763
  * @param {Effect[]} effects
464
764
  * @param {Effect[]} render_effects
765
+ * @param {Boundary[]} revealed_boundaries
465
766
  */
466
- #traverse(root, effects, render_effects) {
767
+ #traverse(root, effects, render_effects, revealed_boundaries) {
467
768
  root.f ^= CLEAN;
468
769
 
469
770
  var effect = root.first;
@@ -473,7 +774,9 @@ export class Batch {
473
774
  var is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
474
775
  var is_skippable_branch = is_branch && (flags & CLEAN) !== 0;
475
776
 
476
- var skip = is_skippable_branch || (flags & INERT) !== 0 || this.#skipped_branches.has(effect);
777
+ // (eager effects run in the real world, see `flush_eager_effects`, not in the view of the batch)
778
+ var skip =
779
+ is_skippable_branch || (flags & (INERT | EAGER_EFFECT)) !== 0 || this.#skips(effect);
477
780
 
478
781
  if (!skip && effect.fn !== null) {
479
782
  if (is_branch) {
@@ -483,7 +786,6 @@ export class Batch {
483
786
  } else if (async_mode_flag && (flags & (RENDER_EFFECT | MANAGED_EFFECT)) !== 0) {
484
787
  render_effects.push(effect);
485
788
  } else if (is_dirty(effect)) {
486
- if ((flags & BLOCK_EFFECT) !== 0) this.add_dirty_reaction(effect, MAYBE_DIRTY);
487
789
  update_effect(effect);
488
790
  }
489
791
 
@@ -496,6 +798,15 @@ export class Batch {
496
798
  }
497
799
 
498
800
  while (effect !== null) {
801
+ // if a pending boundary is now resolved, reveal it
802
+ if ((effect.f & (BOUNDARY_EFFECT | DESTROYED)) === BOUNDARY_EFFECT) {
803
+ var boundary = /** @type {Boundary} */ (effect.b);
804
+
805
+ if (boundary.is_pending && boundary.is_ready(this)) {
806
+ revealed_boundaries.push(boundary);
807
+ }
808
+ }
809
+
499
810
  var next = effect.next;
500
811
 
501
812
  if (next !== null) {
@@ -518,8 +829,7 @@ export class Batch {
518
829
 
519
830
  /** @param {Batch} batch */
520
831
  #intersects(batch) {
521
- for (const [source, [, is_derived]] of this.current) {
522
- if (is_derived) continue;
832
+ for (const source of this.current.keys()) {
523
833
  if (batch.current.has(source)) return true;
524
834
  }
525
835
 
@@ -527,73 +837,86 @@ export class Batch {
527
837
  }
528
838
 
529
839
  /**
840
+ * Take over the writes of a later batch that depends on this one, because it finished first
841
+ * or aborted one of this batch's runs.
842
+ * Values it produced (async results, deriveds) remain valid; block effects select their
843
+ * branches again for this batch, if needed (their selections are keyed by batch)
530
844
  * @param {Batch} batch
531
845
  */
532
846
  #merge(batch) {
533
- for (const [source, value] of batch.current) {
534
- if (!this.previous.has(source) && batch.previous.has(source)) {
535
- this.previous.set(source, batch.previous.get(source));
847
+ for (const target of batch.merge_requests) this.merge_requests.add(target);
848
+ batch.merge_requests.clear();
849
+
850
+ for (const [source, entry] of batch.current) {
851
+ if (!this.previous.has(source)) {
852
+ const previous = batch.previous.get(source);
853
+ if (previous) this.previous.set(source, previous);
536
854
  }
537
855
 
538
- this.current.set(source, value);
856
+ this.current.set(source, entry);
539
857
  }
540
858
 
541
859
  for (const [effect, deferred] of batch.async_deriveds) {
542
860
  const d = this.async_deriveds.get(effect);
543
- if (d) deferred.promise.then(d.resolve).catch(d.reject);
861
+ if (d && d !== deferred) deferred.promise.then(d.resolve, d.reject);
862
+ // The incoming run can still be pending. A subsequent replacement must reach
863
+ // this deferred too, not just the older waiters to which it forwards its result.
864
+ this.async_deriveds.set(effect, deferred);
865
+ }
866
+
867
+ for (const [reaction, record] of batch.records ?? []) {
868
+ if ((reaction.f & BLOCK_EFFECT) === 0) {
869
+ var replaced = this.records?.get(reaction);
870
+ (this.records ??= new Map()).set(reaction, record);
871
+
872
+ // the run moves to this batch
873
+ batch.records?.delete(reaction);
874
+
875
+ // (once it's replaced, as both batches may hold the same record, see `keep_global_run`)
876
+ abort_record(reaction, replaced);
877
+ }
544
878
  }
545
879
 
546
880
  // Clear them or else those that are still pending might get rejected on discard (after merged-into batch is done).
547
881
  // This can happen when batch Y merged into X and Y has a pending boundary and therefore still-pending async deriveds inside.
548
882
  batch.async_deriveds.clear();
549
883
 
550
- // Mark is not guaranteed not touch these, so we transfer them
551
- this.transfer_reactions(batch.#dirty_reactions);
552
-
553
- /**
554
- * mark all effects that depend on `batch.current`, except the
555
- * async effects that we just resolved (TODO unless they depend
556
- * on values in this batch that are NOT in the later batch?).
557
- * Through this we also will populate the correct #skipped_branches,
558
- * oncommit callbacks etc, so we don't need to merge them separately.
559
- * @param {Value} value
560
- */
561
- const mark = (value) => {
562
- var reactions = value.reactions;
563
- if (reactions === null) return;
564
- // skip if value is derived and is neither dirty nor maybe dirty. transitive
565
- // deriveds (a derived depending on another derived) are only MAYBE_DIRTY, so
566
- // we must continue traversing them to reach the effects that depend on them
567
- if ((value.f & DERIVED) !== 0 && (value.f & (DIRTY | MAYBE_DIRTY)) === 0) {
568
- return;
884
+ // That pending work is this batch's from now on: it decrements this batch's counts (see `increment_pending`),
885
+ // so this batch stays linked until the work is done, and receives the effects that a boundary defers until then
886
+ if (batch.#pending.size > 0) {
887
+ for (const [effect, count] of batch.#pending) {
888
+ this.#pending.set(effect, (this.#pending.get(effect) ?? 0) + count);
569
889
  }
570
890
 
571
- for (const reaction of reactions) {
572
- var flags = reaction.f;
573
-
574
- if ((flags & DERIVED) !== 0) {
575
- mark(/** @type {Derived} */ (reaction));
576
- } else {
577
- var effect = /** @type {Effect} */ (reaction);
891
+ batch.#pending.clear();
892
+ }
578
893
 
579
- if (flags & (ASYNC | BLOCK_EFFECT) && !this.async_deriveds.has(effect)) {
580
- this.#dirty_reactions.delete(effect);
581
- set_signal_status(effect, DIRTY);
582
- this.schedule(effect);
583
- }
584
- }
894
+ if (batch.#unprocessed.size > 0) {
895
+ for (const [effect, status] of batch.#unprocessed) {
896
+ this.#add_dirty_effect(effect, status);
585
897
  }
586
- };
587
898
 
588
- for (const source of this.current.keys()) {
589
- mark(source);
899
+ batch.#unprocessed.clear();
590
900
  }
591
901
 
592
- this.oncommit(() => batch.discard());
902
+ // What the merged batch did on its own (e.g. branches it selected) is obsolete once this batch is
903
+ // done — whether it commits or is discarded (e.g. because of an error)
904
+ const discard = () => batch.discard();
905
+ this.oncommit(discard);
906
+ this.ondiscard(discard);
907
+ batch.merged = this;
593
908
  batch.#unlink();
909
+ }
594
910
 
595
- current_batch = this;
596
- this.#process();
911
+ /**
912
+ * Note that `effect` needs to be (re-)validated, without downgrading a DIRTY effect to MAYBE_DIRTY
913
+ * @param {Effect} effect
914
+ * @param {number} status DIRTY or MAYBE_DIRTY
915
+ */
916
+ #add_dirty_effect(effect, status) {
917
+ if (status === DIRTY || this.#unprocessed.get(effect) !== DIRTY) {
918
+ this.#unprocessed.set(effect, status);
919
+ }
597
920
  }
598
921
 
599
922
  /**
@@ -601,59 +924,133 @@ export class Batch {
601
924
  */
602
925
  #defer_effects(effects) {
603
926
  for (var i = 0; i < effects.length; i += 1) {
604
- defer_effect(effects[i], this.#dirty_reactions);
927
+ var effect = effects[i];
928
+ var status = effect.f & (DIRTY | MAYBE_DIRTY);
929
+
930
+ if (status !== 0) {
931
+ this.#add_dirty_effect(effect, effect.dv === null ? MAYBE_DIRTY : status);
932
+
933
+ // mark as clean so they get scheduled if they depend on pending async state
934
+ set_signal_status(effect, CLEAN);
935
+ }
605
936
  }
606
937
  }
607
938
 
608
939
  /**
609
940
  * Associate a change to a given source with the current
610
- * batch, noting its previous and current values
941
+ * batch, noting its previous and current values (and versions).
942
+ * The source itself is only updated if this is its latest value, i.e. unless this
943
+ * is a fork (whose writes only exist in its own view of the world) or a later batch
944
+ * already wrote to it (e.g. because an async expression resolved in an earlier batch).
611
945
  * @param {Value} source
612
946
  * @param {any} value
613
- * @param {boolean} [is_derived]
947
+ * @param {boolean} same whether the value equals the real one (it can, if this batch sees another one, see
948
+ * `internal_set`) — in which case the source isn't updated, and the value gets the same version
949
+ * @param {boolean} [error] whether the value is an error (thrown when read, see `runtime.js#get`)
950
+ * @param {Effect[] | null} [updated_during_traversal]
614
951
  */
615
- capture(source, value, is_derived = false) {
616
- if (source.v !== UNINITIALIZED && !this.previous.has(source)) {
617
- this.previous.set(source, source.v);
952
+ capture(source, value, same, error = false, updated_during_traversal = null) {
953
+ var previous = this.previous.get(source);
954
+ var later = later_writer(this, source);
955
+
956
+ if (previous === undefined) {
957
+ // the value before this batch's change is the one before the later batch's change, if any
958
+ previous = later?.previous.get(source);
959
+
960
+ // (A first value has no value from before it, see `previous`. If the later batch's write is the first value,
961
+ // the value before this batch's write is taken to be that one: in the views of other batches and in
962
+ // teardowns, undoing this write then gives the real value, just like not undoing it would)
963
+ if (previous === undefined && source.v !== UNINITIALIZED) {
964
+ previous = {
965
+ v: source.v,
966
+ wv: source.wv,
967
+ e: (source.f & ERROR_VALUE) !== 0,
968
+ assigned: (source.f & ASSIGNED) !== 0
969
+ };
970
+ }
971
+
972
+ if (previous !== undefined) this.previous.set(source, previous);
618
973
  }
619
974
 
620
- // Don't save errors in `batch_values`, or they won't be thrown in `runtime.js#get`
621
- if ((source.f & ERROR_VALUE) === 0) {
622
- this.current.set(source, [value, is_derived]);
623
- batch_values?.set(source, value);
975
+ if (is_destroying_effect) {
976
+ teardown_write(source);
977
+ } else if (previous !== undefined) {
978
+ teardown_context?.reverted_values.set(source, previous);
979
+ teardown_context?.derived_cache.clear();
624
980
  }
625
981
 
626
- if (!this.is_fork) {
627
- source.v = value;
982
+ /** @type {BatchValue} */
983
+ var entry = {
984
+ v: value,
985
+ wv: same ? source.wv : increment_write_version(),
986
+ e: error,
987
+ // a write to a derived is an assignment
988
+ assigned: (source.f & DERIVED) !== 0,
989
+ async: (source.f & ASYNC) !== 0
990
+ };
991
+
992
+ this.current.set(source, entry);
993
+
994
+ // The active view of the world sees writes made while it's active, even if they don't belong to the batch whose
995
+ // view it is — e.g. those of effects that run while a batch commits, which go to a new batch. (Async results
996
+ // are only captured while no view is active, see `async_derived`)
997
+ batch_values?.set(source, entry);
998
+
999
+ // an assignment replaces the value of a derived that the active view of the world holds
1000
+ view_cache?.delete(/** @type {Derived} */ (source));
1001
+
1002
+ // in order, this batch's change comes before that of the later batch, which replaces it (this happens when a
1003
+ // result arrives in a batch that committed while it was pending, see `#move_to_front`)
1004
+ if (!this.is_fork && later !== null) later.previous.set(source, entry);
1005
+
1006
+ if (!this.is_fork && !same && later === null) {
1007
+ apply(source, entry);
628
1008
  }
629
- }
630
1009
 
631
- activate() {
632
- current_batch = this;
1010
+ // A value that equals the real one, with the same version, changes nothing that reactions
1011
+ // could read outside this batch's view — which is revalidated when the batch is processed
1012
+ if (!same) {
1013
+ seen = null;
1014
+ count_deps = 0;
1015
+ this.mark(source, DIRTY, updated_during_traversal);
1016
+ seen = null;
1017
+
1018
+ if (eager_effects.size > 0 && !eager_effects_deferred) {
1019
+ flush_eager_effects();
1020
+ }
1021
+ }
633
1022
  }
634
1023
 
635
1024
  deactivate() {
636
- current_batch = null;
637
- batch_values = null;
1025
+ current_batch = processing_batch = batch_values = view_cache = view_batch = null;
638
1026
  }
639
1027
 
640
1028
  flush() {
641
- try {
642
- is_processing = true;
643
- current_batch = this;
1029
+ // flushes can be nested, e.g. if an effect calls `flushSync`
1030
+ var context = push_teardown_context(this.previous);
644
1031
 
1032
+ try {
645
1033
  this.#process();
1034
+
1035
+ // (the size check avoids allocating an iterator in the common case)
1036
+ if (rebases.size > 0) {
1037
+ for (const batch of rebases) {
1038
+ rebases.delete(batch);
1039
+
1040
+ // the batch is processed again anyway if a flush is queued
1041
+ if (batch.linked && !batch.#decrement_queued) {
1042
+ batch.#process();
1043
+ }
1044
+ }
1045
+ }
646
1046
  } finally {
647
1047
  flush_count = 0;
648
1048
  last_scheduled_effect = null;
649
1049
  collected_effects = null;
650
1050
  legacy_updates = null;
651
- is_processing = false;
652
1051
 
653
- current_batch = null;
654
- batch_values = null;
655
-
656
- old_values.clear();
1052
+ teardown_context = context.parent;
1053
+ this.deactivate();
657
1054
 
658
1055
  if (DEV) {
659
1056
  for (const source of source_stacks) {
@@ -666,8 +1063,7 @@ export class Batch {
666
1063
  }
667
1064
 
668
1065
  discard() {
669
- for (const fn of this.#discard_callbacks) fn(this);
670
- this.#discard_callbacks.clear();
1066
+ this.#run_callbacks(this.#discard_callbacks);
671
1067
 
672
1068
  for (const deferred of this.async_deriveds.values()) {
673
1069
  deferred.reject(OBSOLETE);
@@ -677,34 +1073,29 @@ export class Batch {
677
1073
  this.#deferred?.resolve();
678
1074
  }
679
1075
 
680
- /**
681
- * @param {Effect} effect
682
- */
683
- register_created_effect(effect) {
684
- this.#new_effects.push(effect);
685
- }
686
-
687
1076
  #commit() {
688
1077
  // If there are other pending batches, they now need to be 'rebased' —
689
- // in other words, we re-run block/async effects with the newly
690
- // committed state, unless the batch in question has a more
691
- // recent value for a given source
1078
+ // in other words, their view of the world now includes the newly committed
1079
+ // state (unless the batch in question has a more recent value for a given source),
1080
+ // so everything that depends on it needs to be re-validated in their view
692
1081
  for (let batch = first_batch; batch !== null; batch = batch.next) {
1082
+ if (batch === this) continue;
1083
+
693
1084
  var is_earlier = batch.id < this.id;
694
1085
 
695
1086
  /** @type {Source[]} */
696
1087
  var sources = [];
697
1088
 
698
- for (const [source, [value, is_derived]] of this.current) {
699
- if (batch.current.has(source)) {
700
- var batch_value = /** @type {[any, boolean]} */ (batch.current.get(source))[0]; // faster than destructuring
1089
+ for (const [source, entry] of this.current) {
1090
+ var own = batch.current.get(source);
701
1091
 
702
- if (is_earlier && value !== batch_value) {
1092
+ if (own !== undefined) {
1093
+ if (is_earlier && entry.v !== own.v && !own.async) {
703
1094
  // bring the value up to date
704
- batch.current.set(source, [value, is_derived]);
1095
+ batch.current.set(source, entry);
705
1096
  } else {
706
- // same value or later batch has more recent value,
707
- // no need to re-run these effects
1097
+ // same value, later batch has more recent value, or the batch's own result
1098
+ // of an async expression — no need to re-run these effects
708
1099
  continue;
709
1100
  }
710
1101
  }
@@ -712,30 +1103,21 @@ export class Batch {
712
1103
  sources.push(source);
713
1104
  }
714
1105
 
715
- if (is_earlier) {
716
- // TODO do we need to restart these in some cases, instead of
717
- // immediately resolving them? Likely not because of how this.apply() works.
718
- for (const [effect, deferred] of this.async_deriveds) {
719
- const d = batch.async_deriveds.get(effect);
720
- if (d) deferred.promise.then(d.resolve).catch(d.reject);
721
- }
722
- }
723
-
724
- var current = [...batch.current.keys()].filter(
725
- (source) => !(/** @type {[any, boolean]} */ (batch.current.get(source))[1])
726
- );
727
-
728
1106
  // If not started yet or no sources to update (which is e.g. possible for the very first batch) then bail
729
- if (!batch.started || current.length === 0) continue;
1107
+ if (!batch.started || batch.current.size === 0) continue;
730
1108
 
731
- // Re-run async/block effects that depend on distinct values changed in both batches (ignoring deriveds)
732
- var others = current.filter((source) => !this.current.has(source));
1109
+ var obsolete = true;
733
1110
 
734
- if (others.length === 0) {
735
- if (is_earlier) {
736
- // this batch is now obsolete and can be discarded
737
- batch.discard();
1111
+ for (const source of batch.current.keys()) {
1112
+ if (!this.current.has(source)) {
1113
+ obsolete = false;
1114
+ break;
738
1115
  }
1116
+ }
1117
+
1118
+ if (obsolete && is_earlier) {
1119
+ // this batch is now obsolete and can be discarded
1120
+ batch.discard();
739
1121
  } else if (sources.length > 0) {
740
1122
  // The microtask queue can contain the batch already scheduled to run right
741
1123
  // after this one is finished, so throwing the invariant would be wrong here.
@@ -743,100 +1125,49 @@ export class Batch {
743
1125
  invariant(batch.#scheduled.length === 0, 'Batch has scheduled effects');
744
1126
  }
745
1127
 
746
- // A batch was unskipped in a later batch -> tell prior batches to unskip it, too
747
- if (is_earlier) {
748
- for (const unskipped of this.#unskipped_branches) {
749
- batch.unskip_effect(unskipped, (e) => {
750
- if ((e.f & (BLOCK_EFFECT | ASYNC)) !== 0) {
751
- batch.schedule(e);
752
- } else {
753
- batch.#defer_effects([e]);
754
- }
755
- });
756
- }
757
- }
758
-
759
- batch.activate();
760
-
761
- /** @type {Set<Value>} */
762
- var marked = new Set();
763
-
764
- /** @type {Map<Reaction, boolean>} */
765
- var checked = new Map();
766
-
767
- for (var source of sources) {
768
- mark_effects(source, others, marked, checked);
769
- }
770
-
771
- checked = new Map();
772
- var current_unequal = [...batch.current]
773
- .filter(([c, v1]) => {
774
- const v2 = this.current.get(c);
775
- if (!v2) return true;
776
- // Either their values are different or one is a derived but not the other
777
- return v2[0] !== v1[0] || v2[1] !== v1[1];
778
- })
779
- .map(([c]) => c);
780
-
781
- if (current_unequal.length > 0) {
782
- for (const effect of this.#new_effects) {
783
- if (
784
- (effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 &&
785
- depends_on(effect, current_unequal, checked)
786
- ) {
787
- if ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) {
788
- set_signal_status(effect, DIRTY);
789
- batch.schedule(effect);
790
- } else {
791
- batch.add_dirty_reaction(effect, DIRTY);
792
- }
793
- }
794
- }
795
- }
796
-
797
- // Only apply and traverse when we know we triggered async work with marking the effects
798
- // and know this won't run anyway right afterwards
799
- if (batch.#scheduled.length > 0 && !batch.#decrement_queued) {
800
- batch.apply();
801
-
802
- for (var root of batch.#resolve()) {
803
- batch.#traverse(root, [], []);
804
- }
805
- }
806
-
807
- batch.deactivate();
1128
+ // Everything that depends on the committed values needs to be re-validated in the
1129
+ // batch's view. The batch is processed again once the current flush is done (which
1130
+ // also re-validates what depends on its own writes, as the committed batch may have
1131
+ // created reactions that read them), so that block effects select their branches
1132
+ // and async work restarts in the new view right away
1133
+ batch.#revalidate(sources);
1134
+ rebases.add(batch);
808
1135
  }
809
1136
  }
1137
+
1138
+ // The writes are part of the real world now. A batch that is still linked (because of pending work)
1139
+ // only has writes again once that work resolves, which it then commits
1140
+ this.current.clear();
1141
+ this.previous.clear();
810
1142
  }
811
1143
 
812
1144
  /**
813
- * @param {boolean} blocking
814
- * @param {Effect} effect
1145
+ * Make this batch's writes the real world, part of every other batch's view (see `#commit`).
1146
+ * If it has pending work it stays linked, coming first from now on (see `#move_to_front`)
815
1147
  */
816
- increment(blocking, effect) {
817
- this.#pending += 1;
818
-
819
- if (blocking) {
820
- let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;
821
- this.#blocking_pending.set(effect, blocking_pending_count + 1);
822
- }
1148
+ commit_writes() {
1149
+ this.#commit();
1150
+ if (this.linked && this.prev !== null) this.#move_to_front();
823
1151
  }
824
1152
 
825
1153
  /**
826
- * @param {boolean} blocking
827
1154
  * @param {Effect} effect
828
1155
  */
829
- decrement(blocking, effect) {
830
- this.#pending -= 1;
1156
+ increment(effect) {
1157
+ var count = this.#pending.get(effect) ?? 0;
1158
+ this.#pending.set(effect, count + 1);
1159
+ }
831
1160
 
832
- if (blocking) {
833
- let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;
1161
+ /**
1162
+ * @param {Effect} effect
1163
+ */
1164
+ decrement(effect) {
1165
+ var count = this.#pending.get(effect) ?? 0;
834
1166
 
835
- if (blocking_pending_count === 1) {
836
- this.#blocking_pending.delete(effect);
837
- } else {
838
- this.#blocking_pending.set(effect, blocking_pending_count - 1);
839
- }
1167
+ if (count === 1) {
1168
+ this.#pending.delete(effect);
1169
+ } else {
1170
+ this.#pending.set(effect, count - 1);
840
1171
  }
841
1172
 
842
1173
  if (this.#decrement_queued) return;
@@ -851,35 +1182,48 @@ export class Batch {
851
1182
  });
852
1183
  }
853
1184
 
854
- /**
855
- * @param {Map<Effect, number>} dirty_reactions
856
- */
857
- transfer_reactions(dirty_reactions) {
858
- for (const [effect, status] of dirty_reactions) {
859
- this.add_dirty_reaction(effect, status);
860
- }
1185
+ /** @param {(batch: Batch) => void} fn */
1186
+ oncommit(fn) {
1187
+ this.#commit_callbacks.set(fn, eager_block_writes?.size ? eager_block_writes : null);
1188
+ }
861
1189
 
862
- dirty_reactions.clear();
1190
+ /** @param {(batch: Batch) => void} fn */
1191
+ ondiscard(fn) {
1192
+ this.#discard_callbacks.set(fn, eager_block_writes?.size ? eager_block_writes : null);
863
1193
  }
864
1194
 
865
1195
  /**
866
- * @param {Effect} effect
867
- * @param {number} status
1196
+ * Runs the commit/discard callbacks.
1197
+ * A callback that was added while block effects re-ran eagerly detaches the branches that such a run
1198
+ * deselected (see `flush_queued_effects`). The teardowns it causes see the writes that applied in the
1199
+ * run's view, like they would have during the run: of the values that the current teardown context
1200
+ * reverts, the writes of the effects that ran before the one whose writes caused the run are restored.
1201
+ * Callbacks run untracked, because a batch can commit while an effect runs (e.g. one that calls `flushSync`)
1202
+ * @param {Map<(batch: Batch) => void, Map<Value, BatchValue> | null>} callbacks
868
1203
  */
869
- add_dirty_reaction(effect, status) {
870
- if (status === DIRTY || this.#dirty_reactions.get(effect) !== DIRTY) {
871
- this.#dirty_reactions.set(effect, status);
872
- }
873
- }
1204
+ #run_callbacks(callbacks) {
1205
+ untrack(() => {
1206
+ for (const [fn, writes] of callbacks) {
1207
+ if (writes === null) {
1208
+ fn(this);
1209
+ continue;
1210
+ }
874
1211
 
875
- /** @param {(batch: Batch) => void} fn */
876
- oncommit(fn) {
877
- this.#commit_callbacks.add(fn);
878
- }
1212
+ var context = push_teardown_context();
879
1213
 
880
- /** @param {(batch: Batch) => void} fn */
881
- ondiscard(fn) {
882
- this.#discard_callbacks.add(fn);
1214
+ for (const [source, write] of writes) {
1215
+ if (context.reverted_values.has(source)) context.reverted_values.set(source, write);
1216
+ }
1217
+
1218
+ try {
1219
+ fn(this);
1220
+ } finally {
1221
+ teardown_context = context.parent;
1222
+ }
1223
+ }
1224
+ });
1225
+
1226
+ callbacks.clear();
883
1227
  }
884
1228
 
885
1229
  settled() {
@@ -890,7 +1234,7 @@ export class Batch {
890
1234
  if (current_batch === null) {
891
1235
  const batch = (current_batch = new Batch());
892
1236
 
893
- if (!is_processing && !is_flushing_sync) {
1237
+ if (processing_batch === null && !is_flushing_sync) {
894
1238
  queue_micro_task(() => {
895
1239
  if (!batch.started) {
896
1240
  batch.flush();
@@ -902,18 +1246,34 @@ export class Batch {
902
1246
  return current_batch;
903
1247
  }
904
1248
 
905
- apply() {
906
- if (!async_mode_flag || (!this.is_fork && this.prev === null && this.next === null)) {
907
- batch_values = null;
1249
+ /**
1250
+ * Make this the current batch, and its view of the world the active one
1251
+ */
1252
+ activate() {
1253
+ current_batch = this;
1254
+ view_batch = this;
1255
+
1256
+ // Async continuations can create or run reactions in another batch's view without
1257
+ // processing it. The next flush must re-validate those reactions in its own view.
1258
+ if (last_processed !== this.id) last_processed = null;
1259
+
1260
+ if (!async_mode_flag) {
1261
+ batch_values = view_cache = null;
1262
+ return;
1263
+ }
1264
+
1265
+ this.folded = [];
1266
+
1267
+ if (!this.is_fork && this.prev === null && this.next === null) {
1268
+ // this batch's view is the real world
1269
+ batch_values = view_cache = null;
908
1270
  return;
909
1271
  }
910
1272
 
911
1273
  // if there are multiple batches, we are 'time travelling' —
912
1274
  // we need to override values with the ones in this batch...
913
- batch_values = new Map();
914
- for (const [source, [value]] of this.current) {
915
- batch_values.set(source, value);
916
- }
1275
+ batch_values = new Map(this.current);
1276
+ view_cache = new Map();
917
1277
 
918
1278
  // ...and undo changes belonging to other batches unless they intersect
919
1279
  for (let batch = first_batch; batch !== null; batch = batch.next) {
@@ -924,9 +1284,16 @@ export class Batch {
924
1284
  // effects of the earlier batch in case they are merged.
925
1285
  // As a result you can think of batch_values as having the latest values of all intersecting
926
1286
  // batches up until this batch.
927
- if (batch.id >= this.id || !batch.#intersects(this)) {
1287
+ if (batch.id < this.id && batch.#intersects(this)) {
1288
+ this.folded.push(batch);
1289
+ } else {
928
1290
  for (const [source, previous] of batch.previous) {
929
- if (!batch_values.has(source)) {
1291
+ // (where the views agree on the value, the real one — and its version — applies. Not for an
1292
+ // assigned derived: its value before may have been computed in another view, see `get_view`)
1293
+ if (
1294
+ !batch_values.has(source) &&
1295
+ ((source.f & DERIVED) !== 0 || !source.equals(previous.v))
1296
+ ) {
930
1297
  batch_values.set(source, previous);
931
1298
  }
932
1299
  }
@@ -935,26 +1302,212 @@ export class Batch {
935
1302
  }
936
1303
 
937
1304
  /**
938
- *
1305
+ * The record of `reaction` in this batch's view of the world, i.e. that of this batch
1306
+ * or of the (earlier) batches whose changes it includes, if any
1307
+ * @param {Reaction} reaction
1308
+ * @returns {BatchRecord | undefined}
1309
+ */
1310
+ get_record(reaction) {
1311
+ var record = this.records?.get(reaction);
1312
+ var i = this.folded.length;
1313
+
1314
+ while (record === undefined && i--) {
1315
+ record = this.folded[i].records?.get(reaction);
1316
+ }
1317
+
1318
+ return record;
1319
+ }
1320
+
1321
+ /**
1322
+ * @param {Value} signal
1323
+ * @param {number} status should be DIRTY or MAYBE_DIRTY
1324
+ * @param {Effect[] | null} [updated_during_traversal]
1325
+ * @returns {void}
1326
+ */
1327
+ mark(signal, status, updated_during_traversal = null) {
1328
+ var reactions = signal.reactions;
1329
+ if (reactions === null) return;
1330
+
1331
+ var runes = is_runes();
1332
+ var length = reactions.length;
1333
+
1334
+ count_deps += length;
1335
+ // Activate the `seen` Set if we think from the unusually high number of deps that
1336
+ // there might be cycles in the graph, to avoid repeated lookups for reactions
1337
+ // Example: https://github.com/sveltejs/svelte/issues/16658 has a graph with one source
1338
+ // reaching ~10000 distinct deriveds/effects each, resulting in 65 million walks through repeated visits.
1339
+ if (count_deps > 100000 && seen === null) seen = new Set();
1340
+
1341
+ if (seen !== null) {
1342
+ if (seen.has(signal)) return;
1343
+ seen.add(signal);
1344
+ }
1345
+
1346
+ for (var i = 0; i < length; i++) {
1347
+ var reaction = reactions[i];
1348
+ var flags = reaction.f;
1349
+
1350
+ // In legacy mode, skip the current effect to prevent infinite loops
1351
+ if (!runes && reaction === active_effect) continue;
1352
+
1353
+ var not_dirty = (flags & DIRTY) === 0;
1354
+
1355
+ if ((flags & EAGER_EFFECT) !== 0) {
1356
+ if (!this.is_fork) {
1357
+ // don't set a DIRTY reaction to MAYBE_DIRTY
1358
+ if (not_dirty) {
1359
+ set_signal_status(reaction, status);
1360
+ }
1361
+
1362
+ // Eager effects need to run immediately:
1363
+ // - for $inspect so that the stack trace makes sense
1364
+ // - for $state.eager because they might be without an effect parent
1365
+ eager_effects.add(/** @type {Effect} */ (reaction));
1366
+ }
1367
+ } else if ((flags & DERIVED) !== 0) {
1368
+ // don't set a DIRTY reaction to MAYBE_DIRTY
1369
+ if (not_dirty) {
1370
+ set_signal_status(reaction, status);
1371
+ }
1372
+
1373
+ var derived = /** @type {Derived} */ (reaction);
1374
+
1375
+ view_cache?.delete(derived);
1376
+ this.mark(derived, MAYBE_DIRTY, updated_during_traversal);
1377
+ } else if (not_dirty) {
1378
+ var effect = /** @type {Effect} */ (reaction);
1379
+
1380
+ if ((flags & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {
1381
+ // these run right away to find out which branches the rest of the flush must skip
1382
+ // (see `flush_queued_effects`); the DOM changes when this batch commits
1383
+ set_signal_status(effect, status);
1384
+ eager_block_effects.add(effect);
1385
+ }
1386
+
1387
+ if (updated_during_traversal !== null) {
1388
+ set_signal_status(effect, status);
1389
+ updated_during_traversal.push(effect);
1390
+ } else {
1391
+ // the status is applied when the batch is processed
1392
+ this.schedule(effect, status);
1393
+ }
1394
+ }
1395
+ }
1396
+ }
1397
+
1398
+ /**
1399
+ * Schedule `effect` to be (re-)validated when this batch is processed. Its status only applies right
1400
+ * away if this is the batch that the current flush processes (next), or if a reaction is running (which
1401
+ * may have read what changed). Otherwise, whether an effect is dirty depends on this batch's view of the
1402
+ * world, so other batches (which may be processed first) mustn't see it: it is kept with this batch until
1403
+ * it is processed, and then checked against the exact versions of its dependencies (i.e. MAYBE_DIRTY)
939
1404
  * @param {Effect} effect
1405
+ * @param {number} status DIRTY or MAYBE_DIRTY
940
1406
  */
941
- schedule(effect) {
1407
+ schedule(effect, status) {
942
1408
  last_scheduled_effect = effect;
943
1409
 
944
- // defer render effects inside a pending boundary
945
- // TODO the `REACTION_RAN` check is only necessary because of legacy `$:` effects AFAICT — we can remove later
946
- if (
947
- effect.b?.is_pending &&
948
- (effect.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 &&
949
- (effect.f & REACTION_RAN) === 0
950
- ) {
951
- effect.b.defer_effect(effect);
1410
+ // While another batch is committed, effects that this batch's writes affect (other than the one
1411
+ // that is running, i.e. writing) wait for it to be processed, rather than running as part of that commit.
1412
+ // They may still run as part of it (for that batch's reasons) and see the write, so versions decide — unless
1413
+ // the effect is running, in which case it would record the version it didn't see (see `update_dependencies`)
1414
+ if (view_batch !== null && view_batch !== this && effect !== active_reaction) {
1415
+ this.#add_dirty_effect(
1416
+ effect,
1417
+ (effect.f & REACTION_IS_UPDATING) !== 0 ? status : MAYBE_DIRTY
1418
+ );
952
1419
  return;
953
1420
  }
954
1421
 
1422
+ if (processing_batch !== this && active_reaction === null) {
1423
+ if (this.prev !== null || this.next !== null || this.is_fork) {
1424
+ this.#add_dirty_effect(effect, MAYBE_DIRTY);
1425
+ return;
1426
+ }
1427
+
1428
+ status = MAYBE_DIRTY;
1429
+ }
1430
+
1431
+ this.#add(effect, status);
1432
+ }
1433
+
1434
+ /**
1435
+ * @param {Effect} effect
1436
+ * @param {number} status
1437
+ */
1438
+ #add(effect, status) {
1439
+ // don't set a DIRTY effect to MAYBE_DIRTY
1440
+ if ((effect.f & DIRTY) === 0) {
1441
+ set_signal_status(effect, status);
1442
+ }
1443
+
955
1444
  this.#scheduled.push(effect);
956
1445
  }
957
1446
 
1447
+ /** @param {boolean} commit whether the effects' runs become global state */
1448
+ #release_records(commit = false) {
1449
+ var records = this.records;
1450
+ if (records === null) return;
1451
+
1452
+ // Release ownership before pruning. Merged runs are retained by the receiving batch
1453
+ this.records = null;
1454
+ for (const [reaction, record] of records) {
1455
+ // A derived's record is a run in this batch's view: it is only the real-world value if its
1456
+ // dependencies still hold what it read, which is checked where a record is promoted on read
1457
+ // (see `update_derived`) and cannot be checked here. So it is dropped rather than promoted,
1458
+ // and its edges are left for its next global run to prune (see `prune_edges`). A destroyed
1459
+ // reaction has nothing left to update either
1460
+ if ((reaction.f & (DERIVED | DESTROYED)) === 0) {
1461
+ // Keep a newer committed async run instead of promoting an outdated record.
1462
+ // Otherwise, the effect would rerun and restart its async work in every batch.
1463
+ var replaced = (reaction.f & ASYNC) !== 0 && is_outdated(record) && !is_outdated(reaction);
1464
+
1465
+ if (commit && !replaced) {
1466
+ promote_record(reaction, record);
1467
+
1468
+ // The committed run is now what applies in the view of every batch without a run of the async
1469
+ // effect of its own (typically because the batch committed while its run was pending, inside a
1470
+ // pending boundary). Their in-flight runs are superseded: their results would overwrite this one
1471
+ // TODO feels pretty hacky and indication of an X-Y problem: This only works because !b.records?.has(reaction)
1472
+ // means "this would re-use the real world result, i.e. the one we just committed, so we can reject this old run".
1473
+ // This can reject runs too early in pending batches. The superseding batch eventually settles them,
1474
+ // but async/if blocks inside pending boundaries should be excluded.
1475
+ if ((reaction.f & ASYNC) !== 0) {
1476
+ for (let b = first_batch; b !== null; b = b.next) {
1477
+ if (b !== this && !b.records?.has(reaction)) {
1478
+ b.async_deriveds.get(/** @type {Effect} */ (reaction))?.reject(OBSOLETE);
1479
+ }
1480
+ }
1481
+ }
1482
+ }
1483
+
1484
+ prune_edges(reaction);
1485
+ }
1486
+
1487
+ // abort this run - if it was promoted to global, or another batch holds it, too, this is a noop
1488
+ abort_record(reaction, record);
1489
+ }
1490
+ }
1491
+
1492
+ /**
1493
+ * A batch that committed while work inside a pending boundary was in flight stays linked, so that the results
1494
+ * arrive in it. Its writes are the real world now, part of every other batch's view, so it comes first from now
1495
+ * on: This ensures logic about who sees what values in intersects/merge/etc work correctly.
1496
+ */
1497
+ #move_to_front() {
1498
+ var prev = /** @type {Batch} */ (this.prev);
1499
+ var first = /** @type {Batch} */ (first_batch);
1500
+
1501
+ prev.next = this.next;
1502
+ if (this.next === null) last_batch = prev;
1503
+ else this.next.prev = prev;
1504
+
1505
+ this.prev = null;
1506
+ this.next = first;
1507
+ first.prev = first_batch = this;
1508
+ this.id = first.id - 1;
1509
+ }
1510
+
958
1511
  #unlink() {
959
1512
  // #merge calls #unlink, discard later on does it again - prevent
960
1513
  // running it multiple times to not corrupt the linked list
@@ -976,6 +1529,7 @@ export class Batch {
976
1529
  }
977
1530
 
978
1531
  this.linked = false;
1532
+ this.#release_records();
979
1533
  }
980
1534
  }
981
1535
 
@@ -989,8 +1543,8 @@ export class Batch {
989
1543
  */
990
1544
  export function flushSync(fn) {
991
1545
  var was_flushing_sync = is_flushing_sync;
992
- var prev_previous_batch = previous_batch;
993
- previous_batch = null;
1546
+ // e.g. flushSync during effect flushing phase - we gotta restore the view_batch afterwards in that case
1547
+ var previous_view_batch = view_batch !== current_batch ? view_batch : null;
994
1548
  is_flushing_sync = true;
995
1549
 
996
1550
  try {
@@ -1013,7 +1567,7 @@ export function flushSync(fn) {
1013
1567
  }
1014
1568
  } finally {
1015
1569
  is_flushing_sync = was_flushing_sync;
1016
- previous_batch = prev_previous_batch;
1570
+ view_batch = previous_view_batch;
1017
1571
  }
1018
1572
  }
1019
1573
 
@@ -1060,21 +1614,64 @@ function infinite_loop_guard() {
1060
1614
  export let eager_block_effects = null;
1061
1615
 
1062
1616
  /**
1617
+ * While block effects re-run eagerly (see `flush_queued_effects`), the writes of the effects that ran before the one
1618
+ * whose writes caused the re-runs, which apply in their view (possibly none). `null` otherwise. The branches that
1619
+ * these runs select/unskip are only appended (and those they skip detached) when the batch with the writes commits
1620
+ * (see `should_defer_append`), and the teardowns that this causes see these writes, too (see `#run_callbacks`)
1621
+ * @type {Map<Value, BatchValue> | null}
1622
+ */
1623
+ export let eager_block_writes = null;
1624
+
1625
+ /**
1626
+ * An effect (as opposed to a render effect, which keeps the offscreen content up to date) inside a boundary
1627
+ * that is still pending doesn't run when the batch commits. The boundary keeps it until it is revealed,
1628
+ * and hands it to the batch that reveals it (see `Boundary#reveal`)
1629
+ * TODO I feel like there's probably a less roundabout way to achieve this
1630
+ * @param {Effect} effect
1631
+ * @returns {boolean} whether the effect was deferred
1632
+ */
1633
+ function defer_if_pending(effect) {
1634
+ // A boundary is only pending while its content is new, so an effect that
1635
+ // has run before can't be inside one, and we can skip the lookup
1636
+ if ((effect.f & (EFFECT | REACTION_RAN)) !== EFFECT) return false;
1637
+
1638
+ for (var boundary = effect.b; boundary !== null; boundary = boundary.parent) {
1639
+ if (boundary.is_pending) {
1640
+ boundary.defer_effect(effect);
1641
+ return true;
1642
+ }
1643
+ }
1644
+
1645
+ return false;
1646
+ }
1647
+
1648
+ /**
1649
+ * `earlier_writes` includes writes from the pre-effect phase. Eager block teardowns
1650
+ * revert the running effect's writes, but not these earlier writes.
1063
1651
  * @param {Array<Effect>} effects
1064
- * @returns {void}
1652
+ * @param {Map<Value, BatchValue> | null} [earlier_writes]
1653
+ * @returns {Map<Value, BatchValue> | null}
1065
1654
  */
1066
- function flush_queued_effects(effects) {
1655
+ function flush_queued_effects(effects, earlier_writes = null) {
1067
1656
  var length = effects.length;
1068
- if (length === 0) return;
1657
+ if (length === 0) return earlier_writes;
1069
1658
 
1070
1659
  var i = 0;
1071
1660
 
1072
1661
  while (i < length) {
1073
1662
  var effect = effects[i++];
1074
1663
 
1075
- if ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) {
1664
+ if (
1665
+ (effect.f & (DESTROYED | INERT)) === 0 &&
1666
+ // don't run if already marked for destruction in the next batch
1667
+ // (this can happen if an effect writes a value which e.g. makes an if block falsy)
1668
+ !current_batch?.is_skipped(effect) &&
1669
+ !defer_if_pending(effect) &&
1670
+ is_dirty(effect)
1671
+ ) {
1076
1672
  eager_block_effects = new Set();
1077
1673
 
1674
+ var version = write_version;
1078
1675
  update_effect(effect);
1079
1676
 
1080
1677
  // Effects with no dependencies or teardown do not get added to the effect tree.
@@ -1083,7 +1680,7 @@ function flush_queued_effects(effects) {
1083
1680
  // here (rather than in `update_effect`) allows us to skip the work for
1084
1681
  // immediate effects.
1085
1682
  if (
1086
- effect.deps === null &&
1683
+ effect.edges === null &&
1087
1684
  effect.first === null &&
1088
1685
  effect.nodes === null &&
1089
1686
  effect.teardown === null &&
@@ -1096,126 +1693,96 @@ function flush_queued_effects(effects) {
1096
1693
  // If update_effect() has a flushSync() in it, we may have flushed another flush_queued_effects(),
1097
1694
  // which already handled this logic and did set eager_block_effects to null.
1098
1695
  if (eager_block_effects?.size > 0) {
1099
- old_values.clear();
1100
-
1101
- for (const e of eager_block_effects) {
1102
- // Skip eager effects that have already been unmounted
1103
- if ((e.f & (DESTROYED | INERT)) !== 0) continue;
1104
-
1105
- // Run effects in order from ancestor to descendant, else we could run into nullpointers
1106
- /** @type {Effect[]} */
1107
- const ordered_effects = [e];
1108
- let ancestor = e.parent;
1109
- while (ancestor !== null) {
1110
- if (eager_block_effects.has(ancestor)) {
1111
- eager_block_effects.delete(ancestor);
1112
- ordered_effects.push(ancestor);
1696
+ // these run because of the writes of the effect, so their teardowns revert those
1697
+ var previous_teardown_context = teardown_context;
1698
+
1699
+ // if state was written by an effect before the one that caused the eager
1700
+ // block rerun, its writes apply in this view. Deriveds must be evaluated
1701
+ // afresh rather than reusing results cached before those writes.
1702
+ if (earlier_writes !== null) push_teardown_context(earlier_writes);
1703
+
1704
+ // (a copy, as `earlier_writes` grows while the flush continues)
1705
+ var previous_eager_block_writes = eager_block_writes;
1706
+ eager_block_writes = new Map(earlier_writes);
1707
+
1708
+ try {
1709
+ for (const e of eager_block_effects) {
1710
+ // Skip eager effects that have already been unmounted, or that are inside a
1711
+ // branch that an earlier eager run (e.g. of an ancestor block) skips
1712
+ if ((e.f & (DESTROYED | INERT)) !== 0 || current_batch?.is_skipped(e)) continue;
1713
+
1714
+ // Run effects in order from ancestor to descendant, else we could run into nullpointers
1715
+ /** @type {Effect[]} */
1716
+ const ordered_effects = [e];
1717
+ let ancestor = e.parent;
1718
+ while (ancestor !== null) {
1719
+ if (eager_block_effects.has(ancestor)) {
1720
+ eager_block_effects.delete(ancestor);
1721
+ ordered_effects.push(ancestor);
1722
+ }
1723
+ ancestor = ancestor.parent;
1113
1724
  }
1114
- ancestor = ancestor.parent;
1115
- }
1116
1725
 
1117
- for (let j = ordered_effects.length - 1; j >= 0; j--) {
1118
- const e = ordered_effects[j];
1119
- // Skip eager effects that have already been unmounted
1120
- if ((e.f & (DESTROYED | INERT)) !== 0) continue;
1121
- update_effect(e);
1726
+ for (let j = ordered_effects.length - 1; j >= 0; j--) {
1727
+ const e = ordered_effects[j];
1728
+ // a block run may have skipped/destroyed the branch that a later one is in
1729
+ if ((e.f & (DESTROYED | INERT)) !== 0 || current_batch?.is_skipped(e)) continue;
1730
+ update_effect(e);
1731
+ }
1122
1732
  }
1733
+ } finally {
1734
+ eager_block_writes = previous_eager_block_writes;
1735
+ eager_block_effects?.clear();
1736
+ teardown_context = previous_teardown_context;
1123
1737
  }
1124
-
1125
- eager_block_effects.clear();
1126
1738
  }
1127
- }
1128
- }
1129
1739
 
1130
- eager_block_effects = null;
1131
- }
1132
-
1133
- /**
1134
- * This is similar to `mark_reactions`, but it only marks async/block effects
1135
- * depending on `value` and at least one of the other `sources`, so that
1136
- * these effects can re-run after another batch has been committed
1137
- * @param {Value} value
1138
- * @param {Source[]} sources
1139
- * @param {Set<Value>} marked
1140
- * @param {Map<Reaction, boolean>} checked
1141
- */
1142
- function mark_effects(value, sources, marked, checked) {
1143
- if (marked.has(value)) return;
1144
- marked.add(value);
1145
-
1146
- if (value.reactions !== null) {
1147
- for (const reaction of value.reactions) {
1148
- const flags = reaction.f;
1149
-
1150
- if ((flags & DERIVED) !== 0) {
1151
- mark_effects(/** @type {Derived} */ (reaction), sources, marked, checked);
1152
- } else if (
1153
- (flags & (ASYNC | BLOCK_EFFECT)) !== 0 &&
1154
- (flags & DIRTY) === 0 &&
1155
- depends_on(reaction, sources, checked)
1156
- ) {
1157
- set_signal_status(reaction, DIRTY);
1158
- schedule_effect(/** @type {Effect} */ (reaction));
1740
+ // if the effect — or the block effects — wrote anything
1741
+ if (write_version !== version && current_batch !== null) {
1742
+ for (const [value, write] of current_batch.current) {
1743
+ if (write.wv > version) {
1744
+ (earlier_writes ??= new Map()).set(value, write);
1745
+ }
1746
+ }
1159
1747
  }
1160
1748
  }
1161
1749
  }
1162
- }
1163
1750
 
1164
- /**
1165
- * When committing a fork, we need to trigger eager effects so that
1166
- * any `$state.eager(...)` expressions update immediately. This
1167
- * function allows us to discover them
1168
- * @param {Value} value
1169
- * @param {Set<Effect>} effects
1170
- */
1171
- function mark_eager_effects(value, effects) {
1172
- if (value.reactions === null) return;
1173
-
1174
- for (const reaction of value.reactions) {
1175
- const flags = reaction.f;
1176
-
1177
- if ((flags & DERIVED) !== 0) {
1178
- mark_eager_effects(/** @type {Derived} */ (reaction), effects);
1179
- } else if ((flags & EAGER_EFFECT) !== 0) {
1180
- set_signal_status(reaction, DIRTY);
1181
- effects.add(/** @type {Effect} */ (reaction));
1182
- }
1183
- }
1751
+ eager_block_effects = null;
1752
+ return earlier_writes;
1184
1753
  }
1185
1754
 
1186
1755
  /**
1187
- * @param {Reaction} reaction
1188
- * @param {Source[]} sources
1189
- * @param {Map<Reaction, boolean>} checked
1756
+ * The next batch after `batch` that wrote `source`, if any. Its write comes after one of `batch` in order, so
1757
+ * that one isn't the real-world value. Forks are skipped: their writes only exist in their own view of the world
1758
+ * @param {Batch} batch
1759
+ * @param {Value} source
1190
1760
  */
1191
- function depends_on(reaction, sources, checked) {
1192
- const depends = checked.get(reaction);
1193
- if (depends !== undefined) return depends;
1194
-
1195
- if (reaction.deps !== null) {
1196
- for (const dep of reaction.deps) {
1197
- if (includes.call(sources, dep)) {
1198
- return true;
1199
- }
1761
+ function later_writer(batch, source) {
1762
+ var later = batch.next;
1200
1763
 
1201
- if ((dep.f & DERIVED) !== 0 && depends_on(/** @type {Derived} */ (dep), sources, checked)) {
1202
- checked.set(/** @type {Derived} */ (dep), true);
1203
- return true;
1204
- }
1205
- }
1764
+ while (later !== null && (later.is_fork || !later.current.has(source))) {
1765
+ later = later.next;
1206
1766
  }
1207
1767
 
1208
- checked.set(reaction, false);
1209
-
1210
- return false;
1768
+ return later;
1211
1769
  }
1212
1770
 
1213
1771
  /**
1214
- * @param {Effect} effect
1215
- * @returns {void}
1772
+ * Make a write the real-world value of `source`. A write to a derived is an assignment, whose
1773
+ * value holds until one of the derived's dependencies is written after it (see `changed_since`)
1774
+ * @param {Value} source
1775
+ * @param {BatchValue} entry
1216
1776
  */
1217
- export function schedule_effect(effect) {
1218
- /** @type {Batch} */ (current_batch).schedule(effect);
1777
+ function apply(source, entry) {
1778
+ source.v = entry.v;
1779
+ source.wv = entry.wv;
1780
+ source.f = entry.e ? source.f | ERROR_VALUE : source.f & ~ERROR_VALUE;
1781
+
1782
+ if ((source.f & DERIVED) !== 0) {
1783
+ source.f |= ASSIGNED;
1784
+ update_derived_status(/** @type {Derived} */ (source));
1785
+ }
1219
1786
  }
1220
1787
 
1221
1788
  /** @type {Source<number>[]} */
@@ -1263,30 +1830,26 @@ export function eager(fn) {
1263
1830
 
1264
1831
  get(version);
1265
1832
 
1266
- eager_effect(() => {
1267
- if (initial) {
1268
- // the first time this runs, we create an eager effect
1269
- // that will run eagerly whenever the expression changes
1270
- var previous_batch_values = batch_values;
1271
-
1272
- try {
1273
- batch_values = null;
1833
+ // evaluate in the real world — including recording the versions of the dependencies,
1834
+ // so that the eager effect is dirty-checked correctly later (see `flush_eager_effects`)
1835
+ in_real_world(() => {
1836
+ eager_effect(() => {
1837
+ if (initial) {
1838
+ // the first time this runs, we create an eager effect
1839
+ // that will run eagerly whenever the expression changes
1274
1840
  value = fn();
1275
- } finally {
1276
- batch_values = previous_batch_values;
1841
+ return;
1277
1842
  }
1278
1843
 
1279
- return;
1280
- }
1281
-
1282
- // the second time this effect runs, it's to schedule a
1283
- // `version` update. since this will recreate the effect,
1284
- // we don't need to evaluate the expression here
1285
- if (eager_versions.length === 0) {
1286
- queue_micro_task(eager_flush);
1287
- }
1844
+ // the second time this effect runs, it's to schedule a
1845
+ // `version` update. since this will recreate the effect,
1846
+ // we don't need to evaluate the expression here
1847
+ if (eager_versions.length === 0) {
1848
+ queue_micro_task(eager_flush);
1849
+ }
1288
1850
 
1289
- eager_versions.push(version);
1851
+ eager_versions.push(version);
1852
+ });
1290
1853
  });
1291
1854
 
1292
1855
  initial = false;
@@ -1295,43 +1858,43 @@ export function eager(fn) {
1295
1858
  }
1296
1859
 
1297
1860
  /**
1298
- * Mark all the effects inside a skipped branch CLEAN, so that
1299
- * they can be correctly rescheduled later. Tracks dirty and maybe_dirty
1300
- * effects so they can be rescheduled if the branch survives.
1301
- * @param {Effect} effect
1302
- * @param {{ d: Effect[], m: Effect[] }} tracked
1861
+ * Run `fn` with the real world (i.e. the latest values) as the active view, regardless of which batch is active
1862
+ * @param {() => void} fn
1303
1863
  */
1304
- function reset_branch(effect, tracked) {
1305
- // clean branch = nothing dirty inside, no need to traverse further
1306
- if ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {
1307
- return;
1308
- }
1864
+ export function in_real_world(fn) {
1865
+ var previous_batch_values = batch_values;
1866
+ var previous_view_cache = view_cache;
1867
+ var previous_view_batch = view_batch;
1309
1868
 
1310
- if ((effect.f & DIRTY) !== 0) {
1311
- tracked.d.push(effect);
1312
- } else if ((effect.f & MAYBE_DIRTY) !== 0) {
1313
- tracked.m.push(effect);
1314
- }
1869
+ // the real world doesn't belong to a batch, so what runs in it doesn't touch the active batch's records
1870
+ batch_values = view_cache = view_batch = null;
1315
1871
 
1316
- set_signal_status(effect, CLEAN);
1317
-
1318
- var e = effect.first;
1319
- while (e !== null) {
1320
- reset_branch(e, tracked);
1321
- e = e.next;
1872
+ try {
1873
+ fn();
1874
+ } finally {
1875
+ batch_values = previous_batch_values;
1876
+ view_cache = previous_view_cache;
1877
+ view_batch = previous_view_batch;
1322
1878
  }
1323
1879
  }
1324
1880
 
1325
1881
  /**
1326
- * Mark an entire effect tree clean following an error
1882
+ * Mark all the effects inside a skipped branch CLEAN, so that they can be correctly
1883
+ * rescheduled later (if the branch survives, its effects are re-validated, see `unskip_effect`)
1327
1884
  * @param {Effect} effect
1885
+ * @param {boolean} force reset even clean branches following an error
1328
1886
  */
1329
- function reset_all(effect) {
1887
+ function reset_branch(effect, force = false) {
1888
+ // clean branch = nothing dirty inside, no need to traverse further
1889
+ if (!force && (effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {
1890
+ return;
1891
+ }
1892
+
1330
1893
  set_signal_status(effect, CLEAN);
1331
1894
 
1332
1895
  var e = effect.first;
1333
1896
  while (e !== null) {
1334
- reset_all(e);
1897
+ reset_branch(e, force);
1335
1898
  e = e.next;
1336
1899
  }
1337
1900
  }
@@ -1360,21 +1923,34 @@ export function fork(fn) {
1360
1923
  e.experimental_async_required('fork');
1361
1924
  }
1362
1925
 
1363
- if (current_batch !== null) {
1926
+ if (active_effect !== null || current_batch?.is_fork) {
1364
1927
  e.fork_timing();
1365
1928
  }
1366
1929
 
1367
- flushSync();
1930
+ var batch = flushSync(() => {
1931
+ var batch = Batch.ensure();
1932
+ batch.is_fork = true;
1368
1933
 
1369
- var batch = Batch.ensure();
1370
- batch.is_fork = true;
1371
- batch_values = new Map();
1934
+ try {
1935
+ in_real_world(() => {
1936
+ batch_values = new Map();
1937
+ view_cache = new Map();
1938
+ view_batch = batch;
1372
1939
 
1373
- var committed = false;
1374
- var settled = batch.settled();
1940
+ fn();
1941
+ });
1942
+ } catch (error) {
1943
+ batch.discard();
1944
+ batch.deactivate();
1945
+ throw error;
1946
+ }
1375
1947
 
1376
- fn();
1377
- flushSync();
1948
+ return batch;
1949
+ });
1950
+
1951
+ var settled = batch.settled();
1952
+ var committed = false;
1953
+ var discarded = false;
1378
1954
 
1379
1955
  return {
1380
1956
  commit: async () => {
@@ -1383,51 +1959,47 @@ export function fork(fn) {
1383
1959
  return;
1384
1960
  }
1385
1961
 
1386
- if (!batch.linked) {
1962
+ if (discarded) {
1387
1963
  e.fork_discarded();
1388
1964
  }
1389
1965
 
1390
- committed = true;
1966
+ if (!batch.linked) {
1967
+ // batch was made obsolete by later changes
1968
+ committed = true;
1969
+ return;
1970
+ }
1391
1971
 
1972
+ committed = true;
1392
1973
  batch.is_fork = false;
1393
1974
 
1394
- // apply changes and update write versions so deriveds see the change
1395
- for (var [source, [value]] of batch.current) {
1396
- source.v = value;
1397
- source.wv = increment_write_version();
1398
- }
1975
+ // Apply the changes to the real world. They keep the versions they had in the fork,
1976
+ // so that everything the fork computed remains valid (processing the batch
1977
+ // re-validates everything that depends on them, see `#process`)
1978
+ for (const [source, entry] of batch.current) {
1979
+ const later = later_writer(batch, source);
1399
1980
 
1400
- // trigger any `$state.eager(...)` expressions with the new state.
1401
- // eager effects don't get scheduled like other effects, so we
1402
- // can't just encounter them during traversal, we need to
1403
- // proactively flush them
1404
- // TODO maybe there's a better implementation?
1405
- flushSync(() => {
1406
- /** @type {Set<Effect>} */
1407
- var eager_effects = new Set();
1408
-
1409
- for (var source of batch.current.keys()) {
1410
- mark_eager_effects(source, eager_effects);
1981
+ if (later !== null) {
1982
+ // in order, the fork's write comes before the later batch's, which replaces it
1983
+ later.previous.set(source, entry);
1984
+ } else {
1985
+ batch.mark(source, MAYBE_DIRTY);
1986
+ apply(source, entry);
1411
1987
  }
1988
+ }
1412
1989
 
1413
- set_eager_effects(eager_effects);
1990
+ if (eager_effects.size > 0) {
1414
1991
  flush_eager_effects();
1415
- });
1992
+ }
1416
1993
 
1417
1994
  batch.flush();
1418
1995
  await settled;
1419
1996
  },
1420
1997
  discard: () => {
1421
- // cause any MAYBE_DIRTY deriveds to update
1422
- // if they depend on things that changed
1423
- // inside the discarded fork
1424
- for (var source of batch.current.keys()) {
1425
- source.wv = increment_write_version();
1426
- }
1427
-
1428
1998
  if (!committed && batch.linked) {
1429
1999
  batch.discard();
1430
2000
  }
2001
+
2002
+ discarded = true;
1431
2003
  }
1432
2004
  };
1433
2005
  }