svelte 5.57.3 → 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 (81) hide show
  1. package/README.md +1 -1
  2. package/compiler/index.js +1 -1
  3. package/elements.d.ts +1 -2
  4. package/package.json +2 -2
  5. package/src/compiler/phases/1-parse/acorn.js +4 -14
  6. package/src/compiler/phases/1-parse/index.js +8 -1
  7. package/src/compiler/phases/1-parse/read/context.js +3 -2
  8. package/src/compiler/phases/1-parse/read/expression.js +2 -4
  9. package/src/compiler/phases/1-parse/utils/bracket.js +6 -0
  10. package/src/compiler/phases/2-analyze/css/css-prune.js +0 -8
  11. package/src/compiler/phases/2-analyze/index.js +2 -1
  12. package/src/compiler/phases/2-analyze/visitors/AwaitExpression.js +17 -15
  13. package/src/compiler/phases/3-transform/client/transform-template/index.js +27 -9
  14. package/src/compiler/phases/3-transform/client/utils.js +3 -2
  15. package/src/compiler/phases/3-transform/client/visitors/EachBlock.js +1 -1
  16. package/src/compiler/phases/3-transform/client/visitors/Fragment.js +13 -1
  17. package/src/compiler/phases/3-transform/client/visitors/HtmlTag.js +10 -2
  18. package/src/compiler/phases/3-transform/client/visitors/RegularElement.js +11 -2
  19. package/src/compiler/phases/3-transform/client/visitors/RenderTag.js +15 -7
  20. package/src/compiler/phases/3-transform/client/visitors/SlotElement.js +19 -1
  21. package/src/compiler/phases/3-transform/client/visitors/SvelteComponent.js +0 -1
  22. package/src/compiler/phases/3-transform/client/visitors/VariableDeclaration.js +1 -1
  23. package/src/compiler/phases/3-transform/client/visitors/shared/element.js +1 -1
  24. package/src/compiler/phases/3-transform/client/visitors/shared/events.js +1 -1
  25. package/src/compiler/phases/3-transform/client/visitors/shared/utils.js +1 -1
  26. package/src/compiler/phases/3-transform/server/visitors/ExpressionStatement.js +8 -0
  27. package/src/compiler/phases/3-transform/server/visitors/Fragment.js +6 -1
  28. package/src/compiler/phases/3-transform/server/visitors/TitleElement.js +1 -1
  29. package/src/compiler/phases/3-transform/server/visitors/shared/element.js +2 -1
  30. package/src/compiler/phases/3-transform/server/visitors/shared/utils.js +1 -1
  31. package/src/compiler/phases/patterns.js +0 -1
  32. package/src/compiler/print/index.js +49 -73
  33. package/src/compiler/state.js +1 -1
  34. package/src/compiler/utils/builders.js +0 -1
  35. package/src/compiler/utils/mapped_code.js +1 -12
  36. package/src/constants.js +0 -8
  37. package/src/index-client.js +3 -3
  38. package/src/internal/client/constants.js +8 -1
  39. package/src/internal/client/dev/debug.js +6 -6
  40. package/src/internal/client/dev/elements.js +25 -9
  41. package/src/internal/client/dev/tracing.js +67 -11
  42. package/src/internal/client/dom/blocks/async.js +2 -1
  43. package/src/internal/client/dom/blocks/await.js +109 -20
  44. package/src/internal/client/dom/blocks/boundary.js +107 -70
  45. package/src/internal/client/dom/blocks/branches.js +17 -23
  46. package/src/internal/client/dom/blocks/each.js +88 -13
  47. package/src/internal/client/dom/blocks/html.js +44 -10
  48. package/src/internal/client/dom/blocks/slot.js +19 -1
  49. package/src/internal/client/dom/blocks/snippet.js +13 -0
  50. package/src/internal/client/dom/blocks/svelte-component.js +1 -1
  51. package/src/internal/client/dom/blocks/svelte-element.js +2 -1
  52. package/src/internal/client/dom/elements/attributes.js +4 -3
  53. package/src/internal/client/dom/elements/bindings/input.js +19 -10
  54. package/src/internal/client/dom/elements/bindings/select.js +3 -7
  55. package/src/internal/client/dom/elements/events.js +27 -2
  56. package/src/internal/client/dom/hydration.js +4 -1
  57. package/src/internal/client/dom/operations.js +2 -3
  58. package/src/internal/client/dom/template.js +0 -1
  59. package/src/internal/client/error-handling.js +4 -12
  60. package/src/internal/client/errors.js +18 -2
  61. package/src/internal/client/index.js +0 -1
  62. package/src/internal/client/reactivity/async.js +249 -123
  63. package/src/internal/client/reactivity/batch.js +1109 -538
  64. package/src/internal/client/reactivity/deriveds.js +281 -177
  65. package/src/internal/client/reactivity/effects.js +44 -28
  66. package/src/internal/client/reactivity/equality.js +0 -9
  67. package/src/internal/client/reactivity/props.js +0 -1
  68. package/src/internal/client/reactivity/sources.js +33 -125
  69. package/src/internal/client/reactivity/status.js +1 -1
  70. package/src/internal/client/render.js +11 -0
  71. package/src/internal/client/runtime.js +925 -152
  72. package/src/internal/client/validate.js +2 -2
  73. package/src/internal/server/renderer.js +52 -118
  74. package/src/internal/shared/utils.js +12 -0
  75. package/src/motion/spring.js +1 -1
  76. package/src/motion/tweened.js +1 -1
  77. package/src/reactivity/create-subscriber.js +1 -1
  78. package/src/version.js +1 -1
  79. package/types/index.d.ts +3 -3
  80. package/types/index.d.ts.map +1 -1
  81. package/src/internal/client/reactivity/utils.js +0 -18
@@ -1,4 +1,4 @@
1
- /** @import { Derived, Effect, Reaction, Source, Value } from '#client' */
1
+ /** @import { BatchRecord, BatchValue, Derived, DerivedRecord, Effect, Reaction, Source, Value } from '#client' */
2
2
  import { DEV } from 'esm-env';
3
3
  import { get_descriptors, get_prototype_of, includes, index_of } from '../shared/utils.js';
4
4
  import {
@@ -21,17 +21,20 @@ import {
21
21
  REACTION_IS_UPDATING,
22
22
  STALE_REACTION,
23
23
  ERROR_VALUE,
24
+ HAS_ABORT_CONTROLLER,
24
25
  MANAGED_EFFECT,
25
- REACTION_RAN
26
+ REACTION_RAN,
27
+ ASYNC,
28
+ ASSIGNED
26
29
  } from './constants.js';
27
- import { old_values } from './reactivity/sources.js';
28
30
  import {
29
31
  reactivity_loss_tracker,
30
32
  execute_derived,
31
33
  freeze_derived_effects,
32
34
  recent_async_deriveds,
33
35
  unfreeze_derived_effects,
34
- update_derived
36
+ update_derived,
37
+ get_view
35
38
  } from './reactivity/deriveds.js';
36
39
  import { async_mode_flag, tracing_mode_flag } from '../flags/index.js';
37
40
  import { tracing_expressions } from './dev/tracing.js';
@@ -49,24 +52,44 @@ import {
49
52
  Batch,
50
53
  batch_values,
51
54
  current_batch,
55
+ first_batch,
52
56
  flushSync,
53
- previous_batch,
54
- schedule_effect
57
+ push_teardown_context,
58
+ teardown_context,
59
+ view_batch,
60
+ view_cache
55
61
  } from './reactivity/batch.js';
56
62
  import { handle_error } from './error-handling.js';
57
63
  import { UNINITIALIZED } from '../../constants.js';
58
64
  import { captured_signals } from './legacy.js';
59
65
  import { without_reactive_context } from './dom/elements/bindings/shared.js';
60
66
  import { set_signal_status, update_derived_status } from './reactivity/status.js';
67
+ import { merge_target } from './reactivity/async.js';
68
+ import * as e from './errors.js';
61
69
  import * as w from './warnings.js';
62
70
 
63
71
  export let is_destroying_effect = false;
64
72
 
65
- /** @param {boolean} value */
66
- export function set_is_destroying_effect(value) {
73
+ /** The write version when the running teardown started — later writes happened in it, and aren't reverted */
74
+ export let teardown_version = 0;
75
+
76
+ /**
77
+ * @param {boolean} value
78
+ * @param {number} [version]
79
+ */
80
+ export function set_is_destroying_effect(value, version = write_version) {
67
81
  is_destroying_effect = value;
82
+ teardown_version = version;
68
83
  }
69
84
 
85
+ /**
86
+ * The result of the latest run of a derived in a teardown, which only the teardown sees: `update_dependencies` sets
87
+ * it — that's where the run's dependencies, which determine its version, are known — instead of storing the run, and
88
+ * `teardown_view` takes it right after `execute_derived`
89
+ * @type {BatchValue}
90
+ */
91
+ let teardown_run = { v: undefined, wv: 0, e: false, assigned: false };
92
+
70
93
  /** @type {null | Reaction} */
71
94
  export let active_reaction = null;
72
95
 
@@ -126,7 +149,9 @@ export function set_untracked_writes(value) {
126
149
  }
127
150
 
128
151
  /**
129
- * @type {number} Used by sources and deriveds for handling updates.
152
+ * @type {number} Used by sources and deriveds for handling updates: every new value — whether it is
153
+ * the real-world (i.e. latest) one, or only exists within a batch — gets a new version. Versions
154
+ * identify values, they are only ever compared for equality (except for `$inspect.trace`).
130
155
  * Version starts from 1 so that unowned deriveds differentiate between a created effect and a run one for tracing
131
156
  **/
132
157
  export let write_version = 1;
@@ -145,43 +170,158 @@ export function increment_write_version() {
145
170
  return ++write_version;
146
171
  }
147
172
 
173
+ /**
174
+ * The version `signal` has in the active view of the world, bringing deriveds up to date
175
+ * @param {Value} signal
176
+ */
177
+ export function version_of(signal) {
178
+ if (batch_values === null) {
179
+ update_derived(signal);
180
+ return signal.wv;
181
+ }
182
+
183
+ if ((signal.f & DERIVED) !== 0) {
184
+ return get_view(/** @type {Derived} */ (signal)).wv;
185
+ }
186
+
187
+ return (batch_values.get(signal) ?? signal).wv;
188
+ }
189
+
190
+ /**
191
+ * Whether the values with the given versions are (still) what `deps` hold in the active view of the world.
192
+ * Dependencies are checked in order and deriveds are brought up to date along the way, so that we
193
+ * don't evaluate a derived that the reaction would no longer read (e.g. `a ? b : c` where `a` changed)
194
+ * @param {Value[] | null} deps
195
+ * @param {number[]} dv
196
+ */
197
+ export function is_current(deps, dv) {
198
+ if (deps !== null) {
199
+ for (var i = 0; i < dv.length; i++) {
200
+ if (version_of(deps[i]) !== dv[i]) return false;
201
+ }
202
+ }
203
+
204
+ return true;
205
+ }
206
+
207
+ /**
208
+ * Whether none of `deps` has been written since the version `wv` in the active view of the world, which is
209
+ * how a value assigned to a derived (whose version is `wv`) holds: until one of the values read by the run
210
+ * that applies in the view (see `get_view`) is written after it. Comparing versions with those the
211
+ * dependencies had at the time of the assignment, like `is_current` does, wouldn't work: a view might undo
212
+ * a write the assignment saw, and a committed fork might apply one it didn't see — but both writes happened
213
+ * before the assignment, so they don't make it outdated.
214
+ *
215
+ * This (and its counterpart in `teardown_view`) is where versions are compared by order across views. That only works for versions of writes
216
+ * (including assignments), which are allocated when the write happens. A derived's version is allocated when it is
217
+ * evaluated, which can be after the assignment even if everything it read was written before it (e.g. because it is
218
+ * evaluated lazily, or again in another view). So a derived only counts as changed if, in addition, one of the
219
+ * values its run in the view read was written after the assignment
220
+ * @param {Value[] | null} deps
221
+ * @param {number} wv
222
+ * @param {Set<Derived | DerivedRecord | BatchValue> | null} [unchanged] runs that this walk found unchanged,
223
+ * to avoid walking a derived that is reachable by more than one path (e.g. a diamond) once per path. Only valid
224
+ * within one top-level call: `wv` and the view are fixed, and the walk itself doesn't write anything
225
+ */
226
+ export function changed_since(deps, wv, unchanged = null) {
227
+ if (deps !== null) {
228
+ for (var i = 0; i < deps.length; i++) {
229
+ var dep = deps[i];
230
+
231
+ if ((dep.f & DERIVED) === 0) {
232
+ if (version_of(dep) > wv) return true;
233
+ continue;
234
+ }
235
+
236
+ // the run of the derived that applies in the view, brought up to date — or a value assigned to it
237
+ /** @type {Derived | DerivedRecord | BatchValue} */
238
+ var run = /** @type {Derived} */ (dep);
239
+
240
+ if (batch_values === null) {
241
+ update_derived(/** @type {Derived} */ (dep));
242
+ } else {
243
+ run = get_view(/** @type {Derived} */ (dep));
244
+ }
245
+
246
+ // (an equal value keeps its version, so a derived whose value didn't change since doesn't count either)
247
+ if (run.wv > wv) {
248
+ var assigned = run === dep ? (dep.f & ASSIGNED) !== 0 : !('dv' in run);
249
+
250
+ if (assigned) return true;
251
+
252
+ // this run was already found to have no writes after `wv` below it
253
+ if (unchanged === null) {
254
+ unchanged = new Set();
255
+ } else if (unchanged.has(run)) {
256
+ continue;
257
+ }
258
+
259
+ if (changed_since(/** @type {DerivedRecord} */ (run).deps, wv, unchanged)) {
260
+ return true;
261
+ }
262
+
263
+ unchanged.add(run);
264
+ }
265
+ }
266
+ }
267
+
268
+ return false;
269
+ }
270
+
271
+ /**
272
+ * For block/async effects returns the record of the {@link view_batch} (if any), else reaction itself.
273
+ * @param {Reaction} reaction
274
+ * @returns {Reaction | BatchRecord}
275
+ */
276
+ export function run_of(reaction) {
277
+ return (
278
+ ((reaction.f & (BLOCK_EFFECT | ASYNC)) !== 0 && view_batch?.get_record(reaction)) || reaction
279
+ );
280
+ }
281
+
148
282
  /**
149
283
  * Determines whether a derived or effect is dirty.
150
- * If it is MAYBE_DIRTY, will set the status to CLEAN
284
+ * If it is MAYBE_DIRTY (or an assigned derived) and isn't, will set the status to CLEAN.
285
+ * Deriveds are only checked like this in the real world — within the view of a batch,
286
+ * see {@link get_view}. Effects are checked against the run that applies (see `run_of`).
151
287
  * @param {Reaction} reaction
152
288
  * @returns {boolean}
153
289
  */
154
290
  export function is_dirty(reaction) {
155
291
  var flags = reaction.f;
156
292
 
157
- if ((flags & DIRTY) !== 0) {
158
- return true;
293
+ if ((flags & (DIRTY | MAYBE_DIRTY)) === 0) {
294
+ return false;
159
295
  }
160
296
 
161
- if ((flags & MAYBE_DIRTY) !== 0) {
162
- var dependencies = /** @type {Value[]} */ (reaction.deps);
163
- var length = dependencies.length;
297
+ if ((flags & ASSIGNED) !== 0) {
298
+ // A value assigned to a derived holds until one of its dependencies is written after it, which its flags
299
+ // can't tell: writes that don't change the real world (e.g. those of a fork) mark the derived, too
300
+ if (changed_since(reaction.deps, reaction.wv)) return true;
301
+ } else if ((flags & DIRTY) !== 0) {
302
+ return true;
303
+ } else {
304
+ var run = run_of(reaction);
305
+ var deps = run.deps;
306
+ var dv = run.dv;
164
307
 
165
- for (var i = 0; i < length; i++) {
166
- var dependency = dependencies[i];
308
+ if (dv === null) return true;
167
309
 
168
- if (is_dirty(/** @type {Derived} */ (dependency))) {
169
- update_derived(/** @type {Derived} */ (dependency));
170
- }
310
+ if (batch_values === null) {
311
+ for (var i = 0, length = dv.length; i < length; i++) {
312
+ var dependency = /** @type {Value[]} */ (deps)[i];
171
313
 
172
- if (dependency.wv > reaction.wv) {
173
- return true;
314
+ update_derived(dependency);
315
+
316
+ if (dependency.wv !== dv[i]) return true;
174
317
  }
318
+ } else if (!is_current(deps, dv)) {
319
+ return true;
175
320
  }
321
+ }
176
322
 
177
- if (
178
- (flags & CONNECTED) !== 0 &&
179
- // During time traveling we don't want to reset the status so that
180
- // traversal of the graph in the other batches still happens
181
- batch_values === null
182
- ) {
183
- set_signal_status(reaction, CLEAN);
184
- }
323
+ if ((flags & CONNECTED) !== 0) {
324
+ set_signal_status(reaction, CLEAN);
185
325
  }
186
326
 
187
327
  return false;
@@ -206,18 +346,180 @@ function schedule_possible_effect_self_invalidation(signal, effect, root = true)
206
346
  if ((reaction.f & DERIVED) !== 0) {
207
347
  schedule_possible_effect_self_invalidation(/** @type {Derived} */ (reaction), effect, false);
208
348
  } else if (effect === reaction) {
209
- if (root) {
210
- set_signal_status(reaction, DIRTY);
211
- } else if ((reaction.f & CLEAN) !== 0) {
212
- set_signal_status(reaction, MAYBE_DIRTY);
213
- }
214
- schedule_effect(/** @type {Effect} */ (reaction));
349
+ /** @type {Batch} */ (current_batch).schedule(
350
+ /** @type {Effect} */ (reaction),
351
+ root ? DIRTY : MAYBE_DIRTY
352
+ );
353
+ }
354
+ }
355
+ }
356
+
357
+ /**
358
+ * The controller of the signal of the run in progress, if it asked for one (see `get_abort_signal`). Once the run is
359
+ * done, it's stored with the run: on the reaction for its global run, or on the record a batch holds of it
360
+ * @type {AbortController | null}
361
+ */
362
+ export let abort_controller = null;
363
+
364
+ /**
365
+ * The signal of the run of `reaction` that is in progress. Its controller is stored with the run once it's done
366
+ * (see `set_global_signal` and `update_record`) — `reaction.ac` is the previous global run's until then
367
+ * @param {Reaction} reaction
368
+ */
369
+ export function get_abort_signal(reaction) {
370
+ if ((reaction.f & REACTION_IS_UPDATING) === 0) {
371
+ // for now, disallow calling `getAbortSignal()` after an `await`. we could
372
+ // potentially relax this restriction in future, but it adds complexity
373
+ e.get_abort_signal_after_await();
374
+ }
375
+
376
+ reaction.f |= HAS_ABORT_CONTROLLER;
377
+
378
+ return (abort_controller ??= new AbortController()).signal;
379
+ }
380
+
381
+ /** @param {AbortController | null | undefined} controller */
382
+ function abort_signal(controller) {
383
+ if (controller) without_reactive_context(() => controller.abort(STALE_REACTION));
384
+ }
385
+
386
+ /**
387
+ * Abort the signal of a record of `reaction` that a batch replaces or drops — unless another batch holds the
388
+ * record, too (see `keep_global_run`), in which case it aborts once the last one lets go of it
389
+ * @param {Reaction} reaction
390
+ * @param {BatchRecord | undefined} record
391
+ * @param {boolean} [rerun] whether `reaction` is about to run again (see `abort_replaced`). The active batch
392
+ * and the batches that the new run supersedes still hold the record then, but don't count
393
+ */
394
+ export function abort_record(reaction, record, rerun = false) {
395
+ if (!record?.ac) return;
396
+
397
+ for (var b = first_batch; b !== null; b = b.next) {
398
+ if (
399
+ b.records?.get(reaction) === record &&
400
+ !(rerun && (b === view_batch || supersedes(current_batch, b)))
401
+ ) {
402
+ return;
403
+ }
404
+ }
405
+
406
+ abort_signal(record.ac);
407
+ record.ac = null;
408
+ }
409
+
410
+ /**
411
+ * Before `reaction` runs again, abort the signals of the runs it replaces: its run in the active batch (which the
412
+ * new run replaces either way, see `update_record`), its global run if the new run is going to replace that one,
413
+ * and the runs of earlier batches that a run in a real batch supersedes (see `supersedes`). (Forks stay
414
+ * independent until they're committed or discarded.) Whether a derived's run in a view replaces the global run
415
+ * is only known once it's done (see `set_global_signal`) — unless the global run is outdated in the real world
416
+ * anyway
417
+ * @param {Reaction} reaction
418
+ * @param {number} flags
419
+ */
420
+ function abort_replaced(reaction, flags) {
421
+ var batch = current_batch;
422
+ var is_derived = (flags & DERIVED) !== 0;
423
+
424
+ // a teardown's run of a derived doesn't replace anything (see `teardown_view`)
425
+ if (is_derived && is_destroying_effect) return;
426
+
427
+ var real = batch === null || !batch.is_fork;
428
+
429
+ abort_record(reaction, view_batch?.records?.get(reaction), true);
430
+
431
+ if (is_derived ? batch_values === null || (real && is_outdated(reaction)) : real) {
432
+ // (the controller stays referenced until the new run is stored, see `keep_global_run`)
433
+ abort_signal(reaction.ac);
434
+ }
435
+
436
+ for (var b = first_batch; b !== null; b = b.next) {
437
+ if (supersedes(batch, b)) abort_record(reaction, b.records?.get(reaction), true);
438
+ }
439
+ }
440
+
441
+ /**
442
+ * The run that just ended is the global state of `reaction`: its signal replaces the global run's, which aborts —
443
+ * unless other batches took that run over, along with its signal (see `keep_global_run`)
444
+ * @param {Reaction} reaction
445
+ */
446
+ function set_global_signal(reaction) {
447
+ abort_signal(reaction.ac);
448
+ reaction.ac = abort_controller;
449
+ }
450
+
451
+ /**
452
+ * Whether a run is invalid or a dependency's real-world version has changed.
453
+ * This does not evaluate derived dependencies, which may themselves be outdated.
454
+ * @param {Reaction | BatchRecord} run
455
+ */
456
+ export function is_outdated({ deps, dv }) {
457
+ return dv === null || dv.some((version, i) => /** @type {Value[]} */ (deps)[i].wv !== version);
458
+ }
459
+
460
+ /**
461
+ * Whether a run in `batch` supersedes the runs of batch `other`, so that their signals abort (see `abort_replaced`):
462
+ * a run in a real batch supersedes those of earlier batches whose writes it saw — because it ran in the real world,
463
+ * or in a view that folds them, or undoes none of their writes (e.g. because they committed, see `Batch#activate`).
464
+ * The runs of other earlier batches read their writes, which this run didn't see, so they still apply in their
465
+ * views. Forks stay independent until they're committed or discarded
466
+ * @param {Batch | null} batch
467
+ * @param {Batch} other
468
+ */
469
+ function supersedes(batch, other) {
470
+ return (
471
+ batch !== null &&
472
+ !batch.is_fork &&
473
+ !other.is_fork &&
474
+ other.id < batch.id &&
475
+ (batch_values === null || other.previous.size === 0 || batch.folded.includes(other))
476
+ );
477
+ }
478
+
479
+ /**
480
+ * Abort all signals of `reaction` (see `getAbortSignal`), e.g. because it's destroyed.
481
+ * Returns whether a run had requested a signal, even if it was already aborted
482
+ * @param {Reaction} reaction
483
+ */
484
+ export function abort_all(reaction) {
485
+ if ((reaction.f & HAS_ABORT_CONTROLLER) === 0) return false;
486
+ reaction.f ^= HAS_ABORT_CONTROLLER;
487
+
488
+ abort_signal(reaction.ac);
489
+ reaction.ac = null;
490
+
491
+ for (var b = first_batch; b !== null; b = b.next) {
492
+ var record = b.records?.get(reaction);
493
+
494
+ if (record?.ac) {
495
+ abort_signal(record.ac);
496
+ record.ac = null;
215
497
  }
216
498
  }
499
+
500
+ return true;
501
+ }
502
+
503
+ /**
504
+ * Whether or not we should unconditionally record a reaction run within a batch, as opposed
505
+ * to updating the signal directly. True for async effects, and previously-initialized
506
+ * block effects (as long as they run during traversal, rather than on commit)
507
+ * @param {number} flags
508
+ */
509
+ function is_recorded_effect(flags) {
510
+ if (
511
+ (flags & ASYNC) === 0 &&
512
+ (flags & (BLOCK_EFFECT | REACTION_RAN)) !== (BLOCK_EFFECT | REACTION_RAN)
513
+ ) {
514
+ return false;
515
+ }
516
+
517
+ return view_batch !== null && view_batch === current_batch;
217
518
  }
218
519
 
219
520
  /** @param {Reaction} reaction */
220
521
  export function update_reaction(reaction) {
522
+ const batch = current_batch;
221
523
  var previous_deps = new_deps;
222
524
  var previous_skipped_deps = skipped_deps;
223
525
  var previous_untracked_writes = untracked_writes;
@@ -239,12 +541,11 @@ export function update_reaction(reaction) {
239
541
  untracking = false;
240
542
  update_version = ++read_version;
241
543
 
242
- if (reaction.ac !== null) {
243
- without_reactive_context(() => {
244
- /** @type {AbortController} */ (reaction.ac).abort(STALE_REACTION);
245
- });
544
+ var previous_abort_controller = abort_controller;
545
+ abort_controller = null;
246
546
 
247
- reaction.ac = null;
547
+ if ((flags & HAS_ABORT_CONTROLLER) !== 0) {
548
+ abort_replaced(reaction, flags);
248
549
  }
249
550
 
250
551
  try {
@@ -252,7 +553,7 @@ export function update_reaction(reaction) {
252
553
  var fn = /** @type {Function} */ (reaction.fn);
253
554
  var result = fn();
254
555
  reaction.f |= REACTION_RAN;
255
- var deps = update_dependencies(reaction);
556
+ update_dependencies(reaction, flags, result, false);
256
557
 
257
558
  // If we're inside an effect and we have untracked writes, then we need to
258
559
  // ensure that if any of those untracked writes result in re-invalidation
@@ -261,7 +562,8 @@ export function update_reaction(reaction) {
261
562
  is_runes() &&
262
563
  untracked_writes !== null &&
263
564
  !untracking &&
264
- deps !== null &&
565
+ // bail out if the effect didn't read anything
566
+ (new_deps !== null || skipped_deps > 0) &&
265
567
  (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0
266
568
  ) {
267
569
  for (var i = 0; i < /** @type {Source[]} */ (untracked_writes).length; i++) {
@@ -302,17 +604,37 @@ export function update_reaction(reaction) {
302
604
  }
303
605
  }
304
606
 
305
- if ((reaction.f & ERROR_VALUE) !== 0) {
306
- reaction.f ^= ERROR_VALUE;
307
- }
308
-
309
607
  return result;
310
608
  } catch (error) {
311
- // still commit the deps read before the throw, otherwise deriveds connected by this run keep no reader and the reaction never re-runs when they change
312
- update_dependencies(reaction);
609
+ var value = error;
610
+
611
+ try {
612
+ value = handle_error(error);
613
+ } finally {
614
+ // Still commit the deps read before the throw, otherwise deriveds connected by this run keep no reader
615
+ // and the reaction never re-runs when they change. For a derived, the error is the value of the run
616
+ // (`get` throws it) — unless an error boundary took care of it
617
+ update_dependencies(reaction, flags, value, value === error);
618
+ }
313
619
 
314
- return handle_error(error);
620
+ return value;
315
621
  } finally {
622
+ var signal = /** @type {AbortController | null} */ (abort_controller)?.signal;
623
+
624
+ if (batch !== null && signal !== undefined) {
625
+ // The reaction that requested the signal identifies the merge target, even if
626
+ // another reaction awaits its result (e.g. `let promise = $derived(load(...))`).
627
+ signal.addEventListener('abort', () => {
628
+ if (current_batch !== null) {
629
+ const target = merge_target(batch);
630
+
631
+ if (target !== current_batch && target.linked && !target.is_fork) {
632
+ current_batch.merge_requests.add(target);
633
+ }
634
+ }
635
+ });
636
+ }
637
+
316
638
  reaction.f ^= REACTION_IS_UPDATING;
317
639
  new_deps = previous_deps;
318
640
  skipped_deps = previous_skipped_deps;
@@ -322,46 +644,435 @@ export function update_reaction(reaction) {
322
644
  set_component_context(previous_component_context);
323
645
  untracking = previous_untracking;
324
646
  update_version = previous_update_version;
647
+ abort_controller = previous_abort_controller;
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Store the result of the current run of `reaction` where it belongs — the versions of the
653
+ * values it read and, for a derived, its value — and update the edges of the graph.
654
+ *
655
+ * A run belongs to the real world — and becomes the reaction's global state — unless
656
+ * - it is a derived that read values which aren't the latest ones (it is then stored in the batch
657
+ * whose view of the world it ran in, see {@link get_view})
658
+ * - it is an effect run that belongs to a batch (see {@link update_record})
659
+ * - it is a derived evaluated in a teardown, in which case only the teardown sees it (see `teardown_view`)
660
+ *
661
+ * The edges of the graph (`reaction.edges` and the `reactions` of its dependencies) are a
662
+ * superset of the dependencies of every live record, so that changes to any of them reach
663
+ * the reaction. They are only pruned when a global run happens and no batch holds a record.
664
+ * @param {Reaction} reaction
665
+ * @param {number} flags the flags of the reaction before the run
666
+ * @param {any} value the value of the run (only relevant for deriveds)
667
+ * @param {boolean} error whether the value is an error
668
+ */
669
+ function update_dependencies(reaction, flags, value, error) {
670
+ var deps = reaction.deps;
671
+ var length = skipped_deps + (new_deps === null ? 0 : new_deps.length);
672
+ var dv = reaction.dv;
673
+
674
+ // an effect can be destroyed while it runs, e.g. by an error boundary
675
+ if ((reaction.f & DESTROYED) !== 0) {
676
+ abort_signal(abort_controller);
677
+ return;
678
+ }
679
+
680
+ // ...and so can the last reaction of a derived, which aborts the derived's signals, see `remove_reaction`.
681
+ // `abort_all` removed the flag that the run in progress set, so its signal is still to be aborted
682
+ if (abort_controller !== null && (reaction.f & HAS_ABORT_CONTROLLER) === 0) {
683
+ abort_signal(abort_controller);
684
+ abort_controller = null;
685
+ }
686
+
687
+ if ((flags & DERIVED) !== 0 && is_destroying_effect) {
688
+ // The run belongs to the teardown's view of the world (see `teardown_view`).
689
+ // Its value can't be more recent than what it read
690
+ var wv = 0;
691
+
692
+ for (var j = 0; j < length; j++) {
693
+ var dep =
694
+ j < skipped_deps
695
+ ? /** @type {Value[]} */ (deps)[j]
696
+ : /** @type {Value[]} */ (new_deps)[j - skipped_deps];
697
+
698
+ wv = Math.max(wv, teardown_version_of(dep));
699
+ }
700
+
701
+ // TODO: the run's signal (if any) is never aborted — should we abort when the teardown's view of the
702
+ // world is done with the run?
703
+ teardown_run = { v: value, wv, e: error, assigned: (flags & ASSIGNED) !== 0 };
704
+ return;
705
+ }
706
+
707
+ // A run of a derived in the real world is its new global state. Other batches may still see the current one
708
+ // (in a view, whether a derived's run is a global one is decided by `update_record`)
709
+ if (
710
+ (flags & DERIVED) !== 0 &&
711
+ batch_values === null &&
712
+ first_batch !== null &&
713
+ first_batch.next !== null
714
+ ) {
715
+ keep_global_run(/** @type {Derived} */ (reaction), flags);
716
+ }
717
+
718
+ // Fast path: the reaction read the same values as before, in the real world, and has no other edges
719
+ if (
720
+ new_deps === null &&
721
+ batch_values === null &&
722
+ dv !== null &&
723
+ length === deps?.length &&
724
+ reaction.edges === deps &&
725
+ (flags & (BLOCK_EFFECT | ASYNC)) === 0
726
+ ) {
727
+ // The run saw what its dependencies hold now — a write during the run after it read
728
+ // the value marks it dirty (see `Batch#schedule`), so it doesn't take effect here
729
+ for (var i = 0; i < length; i++) dv[i] = deps[i].wv;
730
+ if (dv.length !== length) dv.length = length;
731
+
732
+ if ((flags & DERIVED) !== 0) set_derived_value(/** @type {Derived} */ (reaction), value, error);
733
+ if (reaction.ac || abort_controller) set_global_signal(reaction);
734
+
735
+ return;
325
736
  }
737
+
738
+ update_record(reaction, flags, length, value, error);
326
739
  }
327
740
 
328
741
  /**
742
+ * Make `value` the (real-world) value of `derived` — it keeps its version if it is the same value
743
+ * @param {Derived} derived
744
+ * @param {any} value
745
+ * @param {boolean} error
746
+ */
747
+ function set_derived_value(derived, value, error) {
748
+ // a run replaces a value that was assigned to the derived
749
+ var flags = derived.f & ~ASSIGNED;
750
+
751
+ if (error || (flags & ERROR_VALUE) !== 0 || !derived.equals(value)) {
752
+ derived.v = value;
753
+ derived.wv = increment_write_version();
754
+ flags = error ? flags | ERROR_VALUE : flags & ~ERROR_VALUE;
755
+ }
756
+
757
+ derived.f = flags;
758
+ update_derived_status(derived);
759
+ }
760
+
761
+ /**
762
+ * The general case of `update_dependencies`, which
763
+ * 1. decides where the run belongs: to the batch whose view of the world is active (as a record, see
764
+ * `Batch#records`), or to the real world (as the reaction's global state)
765
+ * 2. records the versions of the values the run read (`dv`)
766
+ * 3. updates the edges of the graph
767
+ * 4. stores the run where it belongs
329
768
  * @param {Reaction} reaction
769
+ * @param {number} flags the flags of the reaction before the run
770
+ * @param {number} length the number of values the run read
771
+ * @param {any} value the value of the run (only relevant for deriveds)
772
+ * @param {boolean} error whether the value is an error
330
773
  */
331
- function update_dependencies(reaction) {
774
+ function update_record(reaction, flags, length, value, error) {
775
+ // Block and async effects that run while a batch is processed produce a result for that batch (the
776
+ // branch it selected, the value an async expression resolved to for it), which it keeps until it
777
+ // commits. The first run of a block effect is the exception — it creates (and commits) its initial
778
+ // branch. (Whether a derived's run belongs to a batch depends on what it read, see below)
779
+ var should_record = is_recorded_effect(flags);
780
+
781
+ // A derived that has another version in the view than in the real world — because the view undoes an
782
+ // assignment to it, or it was assigned in a fork — never runs for the real world (see `get_view`)
783
+ if (batch_values !== null && (flags & DERIVED) !== 0) {
784
+ var written = batch_values.get(/** @type {Derived} */ (reaction));
785
+
786
+ if (written !== undefined && written.wv !== /** @type {Derived} */ (reaction).wv) {
787
+ should_record = true;
788
+ }
789
+ }
790
+
332
791
  var deps = reaction.deps;
792
+ var read = deps;
793
+ if (new_deps !== null || skipped_deps !== deps?.length) {
794
+ read =
795
+ skipped_deps === 0
796
+ ? new_deps
797
+ : /** @type {Value[]} */ (deps).slice(0, skipped_deps).concat(new_deps ?? []);
798
+ }
333
799
 
334
- // Don't remove reactions during fork;
335
- // they must remain for when fork is discarded
336
- var is_fork = current_batch?.is_fork;
800
+ // A global run in the real world updates the versions in place. Anything else needs a new array:
801
+ // a record must not share it with the global state, and a derived's run can turn out to belong
802
+ // to the batch halfway through the loop
803
+ var dv = !should_record && batch_values === null && reaction.dv !== null ? reaction.dv : [];
337
804
 
338
- if (new_deps !== null) {
339
- var i;
805
+ for (var i = 0; i < length; i++) {
806
+ var dep = /** @type {Value[]} */ (read)[i];
807
+ dv[i] = seen_version(dep);
340
808
 
341
- if (!is_fork) {
342
- remove_reactions(reaction, skipped_deps);
809
+ // Within a batch's view, a derived's run belongs to the batch unless everything it read is the latest
810
+ // value: the version it saw is the real-world one, and — for a derived — that one is up to date
811
+ if (
812
+ batch_values !== null &&
813
+ (flags & DERIVED) !== 0 &&
814
+ (dv[i] !== dep.wv || (dep.f & (DERIVED | CLEAN)) === DERIVED)
815
+ ) {
816
+ should_record = true;
343
817
  }
818
+ }
344
819
 
345
- if (deps !== null && skipped_deps > 0) {
346
- deps.length = skipped_deps + new_deps.length;
347
- for (i = 0; i < new_deps.length; i++) {
348
- deps[skipped_deps + i] = new_deps[i];
820
+ if (dv.length !== length) dv.length = length;
821
+
822
+ if (!should_record && batch_values !== null && (flags & DERIVED) !== 0) {
823
+ keep_global_run(/** @type {Derived} */ (reaction), flags);
824
+ }
825
+
826
+ // The edges — `reaction.edges`, and `reaction` in the `reactions` of each of them — must cover what every
827
+ // live run of the reaction read (its global run, and the records batches hold of it), so that a change to
828
+ // any of those values reaches it. So unless this is a global run and no batch holds a record, edges are
829
+ // only added (and pruned by a later global run). Their order is independent of the run's reads
830
+ var keep = should_record || has_batch_record(reaction);
831
+ var tracking = effect_tracking() && (reaction.f & CONNECTED) !== 0;
832
+ var edges = reaction.edges;
833
+
834
+ if (keep && edges !== null) {
835
+ if (new_deps !== null) {
836
+ // the edges may be a run's `deps` as well, see `update_dependencies`
837
+ reaction.edges = edges = edges.slice();
838
+ for (dep of new_deps) {
839
+ if (!includes.call(edges, dep)) {
840
+ edges.push(dep);
841
+ if (tracking) (dep.reactions ??= []).push(reaction);
842
+ }
349
843
  }
350
- } else {
351
- reaction.deps = deps = new_deps;
352
844
  }
845
+ } else {
846
+ if (edges === deps) {
847
+ // The edges are exactly what the previous global run read (if anything), so — as on `main` —
848
+ // the values this run read again, in the same order, stay connected, and the rest is replaced
849
+ if (edges !== null) {
850
+ for (i = skipped_deps; i < edges.length; i++) remove_reaction(reaction, edges[i]);
851
+ }
852
+
853
+ if (tracking && new_deps !== null) {
854
+ for (dep of new_deps) (dep.reactions ??= []).push(reaction);
855
+ }
856
+ } else {
857
+ // The edges can include some that were retained for runs no batch holds anymore
858
+ var added = new Set(read);
859
+ for (dep of /** @type {Value[]} */ (edges)) {
860
+ if (!added.delete(dep)) remove_reaction(reaction, dep);
861
+ }
353
862
 
354
- if (effect_tracking() && (reaction.f & CONNECTED) !== 0) {
355
- for (i = skipped_deps; i < deps.length; i++) {
356
- (deps[i].reactions ??= []).push(reaction);
863
+ if (tracking) {
864
+ for (dep of added) (dep.reactions ??= []).push(reaction);
357
865
  }
358
866
  }
359
- } else if (!is_fork && deps !== null && skipped_deps < deps.length) {
360
- remove_reactions(reaction, skipped_deps);
361
- deps.length = skipped_deps;
867
+
868
+ reaction.edges = read;
869
+ }
870
+
871
+ if (should_record) {
872
+ var batch = /** @type {Batch} */ (view_batch);
873
+
874
+ (batch.records ??= new Map()).set(
875
+ reaction,
876
+ (flags & DERIVED) !== 0
877
+ ? {
878
+ deps: read,
879
+ dv,
880
+ v: value,
881
+ e: error,
882
+ wv: derived_version(/** @type {Derived} */ (reaction), batch, value, error),
883
+ ac: abort_controller
884
+ }
885
+ : { deps: read, dv, ac: abort_controller }
886
+ );
887
+ } else {
888
+ reaction.deps = read;
889
+ reaction.dv = dv;
890
+ if (reaction.ac || abort_controller) set_global_signal(reaction);
891
+
892
+ if ((flags & DERIVED) !== 0) {
893
+ set_derived_value(/** @type {Derived} */ (reaction), value, error);
894
+
895
+ // A record of the derived in the active batch is outdated now. (Effects never have one at this point:
896
+ // their runs only become global outside of processing, on their first run, or once the batch commits,
897
+ // whose records are promoted by then)
898
+ view_batch?.records?.delete(reaction);
899
+ }
900
+ }
901
+ }
902
+
903
+ /**
904
+ * A run of `derived` that becomes its global state replaces the current one, which other batches may still see:
905
+ * their views differ from the real world, and can undo the writes that made it outdated. It is kept as a record in
906
+ * each of them that doesn't have one, so that they don't evaluate the derived again — which would give an equal value
907
+ * a new version, and re-run what saw the current one (restarting async work, for example). That's also the case if
908
+ * the new value is equal, and so keeps its version: the derived itself would still run again, with whatever side
909
+ * effects it has (like asking for a new abort signal). (Like any record, it is only used where it `is_current`)
910
+ *
911
+ * If the derived uses an abort signal, the kept run's may have been aborted when the derived ran again. Only the batches
912
+ * that the new run supersedes (see `supersedes`) keep it regardless — it stays aborted for them until something it read
913
+ * changes in their view. The others (forks, later batches) evaluate the derived again.
914
+ *
915
+ * A fork's run supersedes nothing, though, so the run it replaces isn't aborted: a batch may still be waiting for it.
916
+ * Every other batch keeps it then, and the record takes over its signal, which aborts once no batch holds the record
917
+ * anymore (see `abort_record`)
918
+ * @param {Derived} derived
919
+ * @param {number} flags the flags of the derived before the run
920
+ */
921
+ function keep_global_run(derived, flags) {
922
+ var dv = derived.dv;
923
+
924
+ if (
925
+ // no valid run, or one that doesn't depend on anything — which is only run again if it was invalidated
926
+ dv === null ||
927
+ dv.length === 0 ||
928
+ // an assigned value isn't a run, see `get_view`
929
+ (flags & ASSIGNED) !== 0
930
+ ) {
931
+ return;
932
+ }
933
+
934
+ /** @type {DerivedRecord | undefined} */
935
+ var record;
936
+
937
+ var ac = derived.ac;
938
+
939
+ // whether the run's signal stays live, because a fork's view ran the derived (it's only aborted before the
940
+ // derived runs again if the run was in the real world, see `abort_replaced`)
941
+ var live = ac !== null && current_batch !== null && current_batch.is_fork && !ac.signal.aborted;
942
+
943
+ for (var batch = first_batch; batch !== null; batch = batch.next) {
944
+ if (
945
+ batch !== view_batch &&
946
+ !batch.records?.has(derived) &&
947
+ // otherwise, the run's signal was aborted when the derived ran again, or is about to be (see `set_global_signal`)
948
+ (ac === null || live || supersedes(current_batch, batch))
949
+ ) {
950
+ // All batches that retain this run share one record. (Its versions are copied: the
951
+ // derived's next global run in the real world updates its own in place)
952
+ record ??= {
953
+ deps: derived.deps,
954
+ dv: dv.slice(),
955
+ v: derived.v,
956
+ wv: derived.wv,
957
+ e: (flags & ERROR_VALUE) !== 0
958
+ };
959
+ (batch.records ??= new Map()).set(derived, record);
960
+ }
961
+ }
962
+
963
+ if (live && record !== undefined) {
964
+ // the signal belongs to the batches that kept the run now. (If none did, `set_global_signal` aborts it)
965
+ record.ac = ac;
966
+ derived.ac = null;
967
+ }
968
+ }
969
+
970
+ /**
971
+ * The version of `signal` that the current run saw. Recording it never evaluates anything: a derived that
972
+ * isn't in the view's cache (anymore) was invalidated by a write during the run, or can't be cached —
973
+ * the run then doesn't count as having seen its current version, just like in the real world, where
974
+ * a derived that changes during the run gets a new version only once it is evaluated again
975
+ * @param {Value} signal
976
+ */
977
+ function seen_version(signal) {
978
+ if (batch_values === null) return signal.wv;
979
+
980
+ if ((signal.f & DERIVED) !== 0) {
981
+ var cache = /** @type {Map<Derived, Derived | DerivedRecord | BatchValue>} */ (view_cache);
982
+ return cache.get(/** @type {Derived} */ (signal))?.wv ?? -1;
983
+ }
984
+
985
+ return (batch_values.get(signal) ?? signal).wv;
986
+ }
987
+
988
+ /**
989
+ * Reuse the version of an equal value in the batch's previous run, then the global value,
990
+ * or allocate a new one. Errors always get a new version
991
+ * @param {Derived} derived
992
+ * @param {Batch} batch
993
+ * @param {any} value
994
+ * @param {boolean} error
995
+ */
996
+ function derived_version(derived, batch, value, error) {
997
+ if (!error) {
998
+ var previous = /** @type {DerivedRecord | undefined} */ (batch.get_record(derived));
999
+ if (previous !== undefined && !previous.e && derived.equals.call(previous, value)) {
1000
+ return previous.wv;
1001
+ }
1002
+
1003
+ if ((derived.f & ERROR_VALUE) === 0 && derived.equals(value)) return derived.wv;
1004
+ }
1005
+
1006
+ return increment_write_version();
1007
+ }
1008
+
1009
+ /**
1010
+ * Make the record a batch holds of `reaction` its global state, e.g. because the batch
1011
+ * committed, which makes its results the real-world ones (for a derived, that includes its value)
1012
+ * @param {Reaction} reaction
1013
+ * @param {BatchRecord} record
1014
+ */
1015
+ export function promote_record(reaction, record) {
1016
+ reaction.deps = record.deps;
1017
+ // The global run updates its versions in place. An effect's record is dropped when it is promoted, but
1018
+ // other batches can still hold a derived's (see `keep_global_run`), so that one keeps its own
1019
+ reaction.dv = (reaction.f & DERIVED) !== 0 ? record.dv.slice() : record.dv;
1020
+
1021
+ if ((reaction.f & DERIVED) !== 0) {
1022
+ var derived = /** @type {Derived} */ (reaction);
1023
+
1024
+ derived.v = record.v;
1025
+ derived.wv = /** @type {number} */ (record.wv);
1026
+ derived.f = (record.e ? derived.f | ERROR_VALUE : derived.f & ~ERROR_VALUE) & ~ASSIGNED;
1027
+ update_derived_status(derived);
1028
+ }
1029
+
1030
+ // the run's signal replaces the global run's (so that dropping the record doesn't abort it, see `Batch#release_records`)
1031
+ abort_signal(reaction.ac);
1032
+ reaction.ac = record.ac ?? null;
1033
+ record.ac = null;
1034
+ }
1035
+
1036
+ /** @param {Reaction} reaction */
1037
+ function has_batch_record(reaction) {
1038
+ for (var batch = first_batch; batch !== null; batch = batch.next) {
1039
+ if (batch.records?.has(reaction)) return true;
362
1040
  }
363
1041
 
364
- return deps;
1042
+ return false;
1043
+ }
1044
+
1045
+ /**
1046
+ * Remove the edges of an effect that only runs no batch holds anymore needed (because the batch committed and
1047
+ * its record was promoted, or because it was dropped), once no batch holds a record of it, so that its edges are
1048
+ * what its global run read again. `update_record` only prunes edges in a global run that happens while no batch
1049
+ * holds a record, which block and async effects hardly ever have: they run in batches.
1050
+ * (Not for deriveds: their edges also notify the reactions that read the value of a record that was dropped. They
1051
+ * are pruned by their next global run)
1052
+ * @param {Reaction} effect
1053
+ */
1054
+ export function prune_edges(effect) {
1055
+ var edges = effect.edges;
1056
+ var deps = effect.deps;
1057
+
1058
+ if (edges === deps || has_batch_record(effect)) return;
1059
+
1060
+ // (the edges are a superset of `deps`, so nothing needs to be connected)
1061
+ for (var dep of /** @type {Value[]} */ (edges)) {
1062
+ if (deps === null || !includes.call(deps, dep)) remove_reaction(effect, dep);
1063
+ }
1064
+
1065
+ effect.edges = deps;
1066
+ }
1067
+
1068
+ /**
1069
+ * Connect a reaction outside its normal dependency update, without duplicating subscriptions
1070
+ * @param {Value} signal
1071
+ * @param {Reaction} reaction
1072
+ */
1073
+ function add_reaction(signal, reaction) {
1074
+ var reactions = (signal.reactions ??= []);
1075
+ if (!includes.call(reactions, reaction)) reactions.push(reaction);
365
1076
  }
366
1077
 
367
1078
  /**
@@ -411,34 +1122,34 @@ function remove_reaction(signal, dependency) {
411
1122
  update_derived_status(derived);
412
1123
  }
413
1124
 
414
- // Call abort controller, noone's listening to this derived anymore
415
- if (derived.ac !== null) {
416
- without_reactive_context(() => {
417
- /** @type {AbortController} */ (derived.ac).abort(STALE_REACTION);
418
- derived.ac = null;
419
- // ensure it reruns right away next time instead of potentially returning a rejected promise as its value
420
- set_signal_status(derived, DIRTY);
421
- });
1125
+ // Call abort controller, noone's listening to this derived anymore: no live run of any reaction, in any batch,
1126
+ // read it (the edges cover them all, see `Reaction#edges`). That includes the runs of it that batches hold
1127
+ if (abort_all(derived)) {
1128
+ // ensure it reruns right away next time instead of potentially returning a rejected promise as its value —
1129
+ // in the real world, and in every batch's view (which would otherwise reuse its record of the derived)
1130
+ set_signal_status(derived, DIRTY);
1131
+ derived.dv = null;
1132
+ for (var b = first_batch; b !== null; b = b.next) b.records?.delete(derived);
1133
+ view_cache?.delete(derived);
422
1134
  }
423
1135
 
424
1136
  // freeze any effects inside this derived
425
1137
  freeze_derived_effects(derived);
426
1138
 
427
1139
  // Disconnect any reactions owned by this reaction
428
- remove_reactions(derived, 0);
1140
+ remove_reactions(derived);
429
1141
  }
430
1142
  }
431
1143
 
432
1144
  /**
433
1145
  * @param {Reaction} signal
434
- * @param {number} start_index
435
1146
  * @returns {void}
436
1147
  */
437
- export function remove_reactions(signal, start_index) {
438
- var dependencies = signal.deps;
1148
+ export function remove_reactions(signal) {
1149
+ var dependencies = signal.edges;
439
1150
  if (dependencies === null) return;
440
1151
 
441
- for (var i = start_index; i < dependencies.length; i++) {
1152
+ for (var i = 0; i < dependencies.length; i++) {
442
1153
  remove_reaction(signal, dependencies[i]);
443
1154
  }
444
1155
  }
@@ -478,12 +1189,15 @@ export function update_effect(effect) {
478
1189
  execute_effect_teardown(effect);
479
1190
  var teardown = update_reaction(effect);
480
1191
  effect.teardown = typeof teardown === 'function' ? teardown : null;
1192
+
1193
+ // Whether an effect is dirty is determined by the exact versions of its dependencies (see
1194
+ // `update_dependencies`) — this only marks when it last ran, which `$inspect.trace` uses
481
1195
  effect.wv = write_version;
482
1196
 
483
1197
  // In DEV, increment versions of any sources that were written to during the effect,
484
1198
  // so that they are correctly marked as dirty when the effect re-runs
485
- if (DEV && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) {
486
- for (var dep of effect.deps) {
1199
+ if (DEV && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.edges !== null) {
1200
+ for (var dep of effect.edges) {
487
1201
  if (dep.set_during_effect) {
488
1202
  dep.wv = increment_write_version();
489
1203
  dep.set_during_effect = false;
@@ -543,6 +1257,9 @@ export function get(signal) {
543
1257
 
544
1258
  captured_signals?.add(signal);
545
1259
 
1260
+ /** The reaction that reads `signal` after an `await`, if any */
1261
+ var late_reader = null;
1262
+
546
1263
  // Register the dependency on the current reaction signal.
547
1264
  if (active_reaction !== null && !untracking) {
548
1265
  // if we're in a derived that is being read inside an _async_ derived,
@@ -570,23 +1287,15 @@ export function get(signal) {
570
1287
  }
571
1288
  }
572
1289
  } else {
573
- // We're adding a dependency outside the init/update cycle (i.e. after an `await`).
574
- // We have to deduplicate deps/reactions in this case or remove_reactions could
575
- // disconnect deps/reactions that are actually still in use (if skip_deps says
576
- // "disconnect all after this index" and some of the signals are also present in
577
- // list prior to the cutoff index, i.e. that should be kept).
578
- active_reaction.deps ??= [];
579
- if (!includes.call(active_reaction.deps, signal)) {
580
- active_reaction.deps.push(signal);
581
- }
1290
+ late_reader = active_reaction;
582
1291
 
583
- var reactions = signal.reactions;
584
-
585
- if (reactions === null) {
586
- signal.reactions = [active_reaction];
587
- } else if (!includes.call(reactions, active_reaction)) {
588
- reactions.push(active_reaction);
1292
+ // Late reads add an edge immediately, even if evaluating the value throws.
1293
+ var edges = active_reaction.edges;
1294
+ if (edges === null || !includes.call(edges, signal)) {
1295
+ active_reaction.edges = edges === null ? [signal] : [...edges, signal];
589
1296
  }
1297
+
1298
+ add_reaction(signal, active_reaction);
590
1299
  }
591
1300
  }
592
1301
  }
@@ -594,12 +1303,11 @@ export function get(signal) {
594
1303
  if (DEV) {
595
1304
  if (
596
1305
  !untracking &&
597
- reactivity_loss_tracker &&
598
- // By checking that current/previous batch are null we filter out false positives.
1306
+ // By checking that no batch is active we filter out false positives.
599
1307
  // reactivity_loss_tracker is only reset after a microtask, so if a flush happens
600
1308
  // before that, we get warnings for things we shouldn't warn on.
601
- current_batch === null &&
602
- previous_batch === null &&
1309
+ view_batch === null &&
1310
+ reactivity_loss_tracker &&
603
1311
  !reactivity_loss_tracker.warned &&
604
1312
  (reactivity_loss_tracker.effect.f & REACTION_IS_UPDATING) === 0 &&
605
1313
  !reactivity_loss_tracker.effect_deps.has(signal)
@@ -648,30 +1356,26 @@ export function get(signal) {
648
1356
  }
649
1357
  }
650
1358
 
651
- if (is_destroying_effect && old_values.has(signal)) {
652
- return old_values.get(signal);
1359
+ if (is_destroying_effect) {
1360
+ // teardowns have their own view of the world; nothing read here is recorded
1361
+ var held = teardown_view(signal);
1362
+
1363
+ if (held !== undefined) {
1364
+ if (held.e) throw held.v;
1365
+ return held.v;
1366
+ }
653
1367
  }
654
1368
 
1369
+ /**
1370
+ * The value (and version) as the active view of the world sees it, if it differs from the real
1371
+ * world — for a derived, this is the derived itself if its global state applies (see `get_view`)
1372
+ * @type {{ v: any, wv: number, e?: boolean } | undefined}
1373
+ */
1374
+ var view;
1375
+
655
1376
  if (is_derived) {
656
1377
  var derived = /** @type {Derived} */ (signal);
657
1378
 
658
- if (is_destroying_effect) {
659
- var value = derived.v;
660
-
661
- // if the derived is dirty and has reactions, or depends on the values that just changed, re-execute
662
- // (a derived can be maybe_dirty due to the effect destroy removing its last reaction)
663
- if (
664
- ((derived.f & CLEAN) === 0 && derived.reactions !== null) ||
665
- depends_on_old_values(derived)
666
- ) {
667
- value = execute_derived(derived);
668
- }
669
-
670
- old_values.set(derived, value);
671
-
672
- return value;
673
- }
674
-
675
1379
  // connect disconnected deriveds when reading them inside a connected reaction
676
1380
  var should_connect =
677
1381
  (derived.f & CONNECTED) === 0 &&
@@ -681,13 +1385,15 @@ export function get(signal) {
681
1385
 
682
1386
  var is_new = (derived.f & REACTION_RAN) === 0;
683
1387
 
684
- if (is_dirty(derived)) {
685
- if (should_connect) {
686
- // set the flag before `update_derived`, so that the derived
687
- // is added as a reaction to its dependencies
688
- derived.f |= CONNECTED;
689
- }
1388
+ if (should_connect) {
1389
+ // set the flag before the derived is (re)evaluated, so that
1390
+ // it is added as a reaction to its dependencies
1391
+ derived.f |= CONNECTED;
1392
+ }
690
1393
 
1394
+ if (batch_values !== null) {
1395
+ view = get_view(derived);
1396
+ } else {
691
1397
  update_derived(derived);
692
1398
  }
693
1399
 
@@ -695,10 +1401,17 @@ export function get(signal) {
695
1401
  unfreeze_derived_effects(derived);
696
1402
  reconnect(derived);
697
1403
  }
1404
+ } else if (batch_values !== null) {
1405
+ view = batch_values.get(signal);
1406
+ }
1407
+
1408
+ if (late_reader !== null) {
1409
+ record_late_read(late_reader, signal, view === undefined ? signal.wv : view.wv);
698
1410
  }
699
1411
 
700
- if (batch_values?.has(signal)) {
701
- return batch_values.get(signal);
1412
+ if (view !== undefined && view !== signal) {
1413
+ if (view.e) throw view.v;
1414
+ return view.v;
702
1415
  }
703
1416
 
704
1417
  if ((signal.f & ERROR_VALUE) !== 0) {
@@ -708,6 +1421,23 @@ export function get(signal) {
708
1421
  return signal.v;
709
1422
  }
710
1423
 
1424
+ /**
1425
+ * Record that `reaction` read `signal` (with the given version) after an `await`, i.e. after
1426
+ * its run — as part of the record of that run
1427
+ * @param {Reaction} reaction
1428
+ * @param {Value} signal
1429
+ * @param {number} version
1430
+ */
1431
+ function record_late_read(reaction, signal, version) {
1432
+ var run = run_of(reaction);
1433
+ var deps = run.deps;
1434
+
1435
+ if (run.dv !== null && (deps === null || !includes.call(deps, signal))) {
1436
+ run.deps = deps === null ? [signal] : [...deps, signal];
1437
+ run.dv.push(version);
1438
+ }
1439
+ }
1440
+
711
1441
  /**
712
1442
  * (Re)connect a disconnected derived, so that it is notified
713
1443
  * of changes in `mark_reactions`
@@ -716,16 +1446,10 @@ export function get(signal) {
716
1446
  function reconnect(derived) {
717
1447
  derived.f |= CONNECTED;
718
1448
 
719
- if (derived.deps === null) return;
720
-
721
- for (const dep of derived.deps) {
722
- var reactions = dep.reactions;
1449
+ if (derived.edges === null) return;
723
1450
 
724
- if (reactions === null) {
725
- dep.reactions = [derived];
726
- } else if (!includes.call(reactions, derived)) {
727
- reactions.push(derived);
728
- }
1451
+ for (const dep of derived.edges) {
1452
+ add_reaction(dep, derived);
729
1453
 
730
1454
  if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) {
731
1455
  unfreeze_derived_effects(/** @type {Derived} */ (dep));
@@ -734,22 +1458,71 @@ function reconnect(derived) {
734
1458
  }
735
1459
  }
736
1460
 
737
- /** @param {Derived} derived */
738
- function depends_on_old_values(derived) {
739
- if (derived.v === UNINITIALIZED) return true; // we don't know, so assume the worst
740
- if (derived.deps === null) return false;
1461
+ /**
1462
+ * The value of `signal` in the view of the world of the running teardown, if it differs from the active one:
1463
+ * teardowns revert the writes that caused them, apart from their own (see `TeardownContext`). Deriveds always
1464
+ * get one, since their runs in a teardown only belong to it, and it is cached until the view changes:
1465
+ * - a value written to the derived, while none of its dependencies is written after it (like in `get_view`)
1466
+ * - its global run, if its dependencies still have the versions that run read
1467
+ * - otherwise a new run (see `update_dependencies`), which keeps the version of the value it replaces if equal
1468
+ * @param {Value} signal
1469
+ * @returns {BatchValue | undefined}
1470
+ */
1471
+ function teardown_view(signal) {
1472
+ var written =
1473
+ signal.wv > teardown_version ? undefined : teardown_context?.reverted_values.get(signal);
1474
+
1475
+ if ((signal.f & DERIVED) === 0) return written;
1476
+
1477
+ var derived = /** @type {Derived} */ (signal);
1478
+ var cache = (teardown_context ?? push_teardown_context()).derived_cache;
1479
+ var record = cache.get(derived);
1480
+
1481
+ if (record !== undefined) return record;
1482
+
1483
+ // A value written to the derived — reverted, or the active view's — holds if it was assigned, like in `get_view`:
1484
+ // the value from before an assignment may have been computed, with values that the teardown reverts
1485
+ var held = written ?? batch_values?.get(derived);
1486
+ var assigned = held === undefined ? (derived.f & ASSIGNED) !== 0 : held.assigned;
1487
+ // (the versions its global run read, if that can apply)
1488
+ var dv = held === undefined && !assigned ? derived.dv : null;
1489
+ var deps = derived.deps ?? [];
1490
+ var holds = assigned || dv !== null;
1491
+ var length = dv?.length ?? deps.length;
1492
+
1493
+ held ??= {
1494
+ v: derived.v,
1495
+ wv: derived.wv,
1496
+ e: (derived.f & ERROR_VALUE) !== 0,
1497
+ assigned: (derived.f & ASSIGNED) !== 0
1498
+ };
1499
+
1500
+ for (var i = 0; holds && i < length; i++) {
1501
+ var version = teardown_version_of(deps[i]);
1502
+ holds = dv === null ? version <= held.wv : version === dv[i];
1503
+ }
741
1504
 
742
- for (const dep of derived.deps) {
743
- if (old_values.has(dep)) {
744
- return true;
745
- }
1505
+ if (holds) {
1506
+ record = held;
1507
+ } else {
1508
+ execute_derived(derived);
1509
+ record = teardown_run;
746
1510
 
747
- if ((dep.f & DERIVED) !== 0 && depends_on_old_values(/** @type {Derived} */ (dep))) {
748
- return true;
1511
+ if (held.wv < record.wv && !held.e && !record.e && derived.equals.call(held, record.v)) {
1512
+ record.wv = held.wv;
749
1513
  }
750
1514
  }
751
1515
 
752
- return false;
1516
+ cache.set(derived, record);
1517
+ return record;
1518
+ }
1519
+
1520
+ /**
1521
+ * The version of `signal` in the view of the world of the running teardown
1522
+ * @param {Value} signal
1523
+ */
1524
+ function teardown_version_of(signal) {
1525
+ return (teardown_view(signal) ?? batch_values?.get(signal) ?? signal).wv;
753
1526
  }
754
1527
 
755
1528
  /**