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
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "svelte",
3
3
  "description": "Cybernetically enhanced web apps",
4
4
  "license": "MIT",
5
- "version": "5.58.0",
5
+ "version": "5.58.1",
6
6
  "type": "module",
7
7
  "types": "./types/index.d.ts",
8
8
  "engines": {
@@ -179,9 +179,10 @@ export function get_transform(scope, state) {
179
179
  for (const [name, binding] of scope.declarations) {
180
180
  if (
181
181
  binding.kind === 'normal' ||
182
- // Reads of `$state(...)` declarations are not
182
+ // Reads of `$state(...)` and `$state.raw(...)` declarations are not
183
183
  // transformed if they are never reassigned
184
- (binding.kind === 'state' && !is_state_source(binding, state.analysis))
184
+ ((binding.kind === 'state' || binding.kind === 'raw_state') &&
185
+ !is_state_source(binding, state.analysis))
185
186
  ) {
186
187
  delete transform[name];
187
188
  }
@@ -16,6 +16,14 @@ export function ExpressionStatement(node, context) {
16
16
  rune === '$effect.root' ||
17
17
  rune === '$inspect.trace'
18
18
  ) {
19
+ // These statements are removed from server output. Remove their comments as well,
20
+ // otherwise annotations inside them can attach to the next statement.
21
+ if (node.start !== undefined && node.end !== undefined) {
22
+ const { start, end } = node;
23
+ context.state.analysis.comments = context.state.analysis.comments.filter(
24
+ (comment) => comment.start < start || comment.end > end
25
+ );
26
+ }
19
27
  return b.empty;
20
28
  }
21
29
 
@@ -3,6 +3,7 @@
3
3
  import * as esrap from 'esrap';
4
4
  import ts from 'esrap/languages/ts';
5
5
  import { is_void } from '../../utils.js';
6
+ import { regex_ends_with_whitespaces, regex_starts_with_whitespaces } from '../phases/patterns.js';
6
7
 
7
8
  /** Threshold for when content should be formatted on separate lines */
8
9
  const LINE_BREAK_THRESHOLD = 50;
@@ -81,7 +82,9 @@ function escape_identifier(name) {
81
82
  */
82
83
  export function print(ast, options = undefined) {
83
84
  const comments = (ast.type === 'Root' && ast.comments) || [];
84
- const state = { preserve_whitespace: 0 };
85
+ const state = {
86
+ preserve_whitespace: ast.type === 'Root' && ast.options?.preserveWhitespace ? 1 : 0
87
+ };
85
88
  const css_comments =
86
89
  (ast.type === 'Root' ? ast.css?.comments : ast.type === 'StyleSheet' ? ast.comments : null) ||
87
90
  [];
@@ -122,7 +125,8 @@ function block(context, node, preserve_whitespace = false, allow_inline = false)
122
125
  return;
123
126
  }
124
127
 
125
- if (allow_inline && !child_context.multiline) {
128
+ // Wrapping at fragment edges is safe even when adjacent children must stay together.
129
+ if (allow_inline && !child_context.multiline && child_context.measure() <= LINE_BREAK_THRESHOLD) {
126
130
  context.append(child_context);
127
131
  } else {
128
132
  context.indent();
@@ -260,7 +264,11 @@ function print_element(node, context, comments, state) {
260
264
  const name = node.name.toLowerCase();
261
265
  const preserve =
262
266
  (node.type === 'RegularElement' || node.type === 'TitleElement') &&
263
- (name === 'pre' || name === 'textarea' || name === 'title');
267
+ (name === 'pre' ||
268
+ name === 'textarea' ||
269
+ name === 'title' ||
270
+ name === 'script' ||
271
+ name === 'style');
264
272
 
265
273
  if (preserve) state.preserve_whitespace += 1;
266
274
  base_element(node, context, comments, state);
@@ -552,12 +560,14 @@ const svelte_visitors = (comments, state) => ({
552
560
  for (const item of [node.module, node.instance, node.fragment, node.css]) {
553
561
  if (!item) continue;
554
562
 
555
- if (started) {
563
+ if (started && state.preserve_whitespace === 0) {
556
564
  context.margin();
557
565
  context.newline();
558
566
  }
559
567
 
560
- context.visit(item);
568
+ const child_context = context.new();
569
+ child_context.visit(item);
570
+ context.append(child_context);
561
571
  started = true;
562
572
  }
563
573
  },
@@ -566,7 +576,7 @@ const svelte_visitors = (comments, state) => ({
566
576
  context.write('<script');
567
577
  attributes(node, node.attributes, context, comments);
568
578
  context.write('>');
569
- block(context, node.content, state.preserve_whitespace > 0);
579
+ block(context, node.content);
570
580
  context.write('</script>');
571
581
  },
572
582
 
@@ -574,7 +584,6 @@ const svelte_visitors = (comments, state) => ({
574
584
  if (state.preserve_whitespace > 0) {
575
585
  for (const child of node.nodes) {
576
586
  context.visit(child);
577
- context.multiline ||= child.type === 'Text' && /[\r\n]/.test(child.data);
578
587
  }
579
588
  return;
580
589
  }
@@ -583,9 +592,9 @@ const svelte_visitors = (comments, state) => ({
583
592
  const last = node.nodes.at(-1);
584
593
  const has_surrounding_whitespace =
585
594
  first?.type === 'Text' &&
586
- /^\s/.test(first.data) &&
595
+ regex_starts_with_whitespaces.test(first.raw) &&
587
596
  last?.type === 'Text' &&
588
- /\s$/.test(last.data);
597
+ regex_ends_with_whitespaces.test(last.raw);
589
598
 
590
599
  /** @type {{ nodes: AST.SvelteNode[]; leading_whitespace: boolean }[]} */
591
600
  const items = [];
@@ -603,62 +612,40 @@ const svelte_visitors = (comments, state) => ({
603
612
  };
604
613
 
605
614
  for (let i = 0; i < node.nodes.length; i += 1) {
606
- let child_node = node.nodes[i];
607
-
615
+ const child_node = node.nodes[i];
608
616
  const prev = node.nodes[i - 1];
609
617
  const next = node.nodes[i + 1];
610
618
 
611
- if (child_node.type === 'Text') {
612
- child_node = { ...child_node }; // always clone, so we can safely mutate
619
+ if (child_node.type !== 'Text') {
620
+ sequence.push(child_node);
621
+ continue;
622
+ }
613
623
 
614
- child_node.data = child_node.data.replace(/[^\S]+/g, ' ');
624
+ let raw = child_node.raw;
615
625
 
616
- // trim fragment
617
- if (i === 0) {
618
- child_node.data = child_node.data.trimStart();
619
- }
626
+ // Like the compiler, trim fragment edges, but preserve whitespace inside
627
+ // text and next to expressions. In particular, do not trim non-breaking spaces.
628
+ if (i === 0) raw = raw.replace(regex_starts_with_whitespaces, '');
629
+ if (i === node.nodes.length - 1) raw = raw.replace(regex_ends_with_whitespaces, '');
630
+ if (raw === '') continue;
620
631
 
621
- if (i === node.nodes.length - 1) {
622
- child_node.data = child_node.data.trimEnd();
623
- }
624
-
625
- if (child_node.data === '') {
626
- continue;
627
- }
632
+ // Only split sequences where there was collapsible whitespace already.
633
+ // Inserting a newline between adjacent elements would introduce a space.
634
+ if (prev?.type !== 'ExpressionTag' && regex_starts_with_whitespaces.test(raw)) {
635
+ flush();
636
+ leading_whitespace = true;
637
+ raw = raw.replace(regex_starts_with_whitespaces, '');
638
+ }
628
639
 
629
- if (child_node.data.startsWith(' ') && prev && prev.type !== 'ExpressionTag') {
630
- flush();
631
- leading_whitespace = true;
632
- child_node.data = child_node.data.trimStart();
633
- }
640
+ const trailing_whitespace =
641
+ next?.type !== 'ExpressionTag' && regex_ends_with_whitespaces.test(raw);
634
642
 
635
- if (child_node.data !== '') {
636
- sequence.push({ ...child_node, data: child_node.data });
643
+ if (trailing_whitespace) raw = raw.replace(regex_ends_with_whitespaces, '');
644
+ if (raw !== '') sequence.push({ ...child_node, raw });
637
645
 
638
- if (child_node.data.endsWith(' ') && next && next.type !== 'ExpressionTag') {
639
- flush();
640
- child_node.data = child_node.data.trimStart();
641
- }
642
- }
643
- } else {
644
- const is_block_element =
645
- child_node.type === 'RegularElement' ||
646
- child_node.type === 'Component' ||
647
- child_node.type === 'SvelteBody' ||
648
- child_node.type === 'SvelteHead' ||
649
- child_node.type === 'SvelteFragment' ||
650
- child_node.type === 'SvelteBoundary' ||
651
- child_node.type === 'SvelteDocument' ||
652
- child_node.type === 'SvelteSelf' ||
653
- child_node.type === 'SvelteWindow' ||
654
- child_node.type === 'SvelteComponent' ||
655
- child_node.type === 'SvelteElement' ||
656
- child_node.type === 'SlotElement' ||
657
- child_node.type === 'TitleElement';
658
-
659
- if (is_block_element && sequence.length > 0) flush();
660
- sequence.push(child_node);
661
- if (is_block_element) flush();
646
+ if (trailing_whitespace) {
647
+ flush();
648
+ leading_whitespace = true;
662
649
  }
663
650
  }
664
651
 
@@ -1125,7 +1112,8 @@ const svelte_visitors = (comments, state) => ({
1125
1112
  },
1126
1113
 
1127
1114
  Text(node, context) {
1128
- context.write(node.data);
1115
+ context.write(node.raw);
1116
+ context.multiline ||= /[\r\n]/.test(node.raw);
1129
1117
  },
1130
1118
 
1131
1119
  TitleElement(node, context) {
@@ -1,7 +1,7 @@
1
1
  /** @import { ComponentContext, ComponentContextLegacy } from '#client' */
2
2
  /** @import { EventDispatcher } from './index.js' */
3
3
  /** @import { NotFunction } from './internal/types.js' */
4
- import { active_reaction, untrack } from './internal/client/runtime.js';
4
+ import { active_reaction, get_abort_signal, untrack } from './internal/client/runtime.js';
5
5
  import { is_array } from './internal/shared/utils.js';
6
6
  import { user_effect } from './internal/client/index.js';
7
7
  import * as e from './internal/client/errors.js';
@@ -46,7 +46,7 @@ if (DEV) {
46
46
  /**
47
47
  * Returns an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that aborts when the current [derived](https://svelte.dev/docs/svelte/$derived) or [effect](https://svelte.dev/docs/svelte/$effect) re-runs or is destroyed.
48
48
  *
49
- * Must be called while a derived or effect is running.
49
+ * Must be called while a derived or effect is running, before anything is awaited.
50
50
  *
51
51
  * ```svelte
52
52
  * <script>
@@ -71,7 +71,7 @@ export function getAbortSignal() {
71
71
  e.get_abort_signal_outside_reaction();
72
72
  }
73
73
 
74
- return (active_reaction.ac ??= new AbortController()).signal;
74
+ return get_abort_signal(active_reaction);
75
75
  }
76
76
 
77
77
  /**
@@ -19,7 +19,7 @@ export const BOUNDARY_EFFECT = 1 << 7;
19
19
  * Set on the effect that `pause_effect` was called on, i.e. the root of a paused subtree,
20
20
  * as opposed to its descendants which are merely `INERT`. This allows `resume_effect` on
21
21
  * an ancestor to skip subtrees that were paused for their own reasons (such as a block
22
- * whose condition is still false) rather than resurrecting them
22
+ * whose condition is still false) rather than resurrecting them.
23
23
  */
24
24
  export const PAUSED = 1 << 8;
25
25
  /**
@@ -57,6 +57,13 @@ export const ASYNC = 1 << 22;
57
57
 
58
58
  export const ERROR_VALUE = 1 << 23;
59
59
 
60
+ /** A run of the reaction asked for an abort signal (see `getAbortSignal`) */
61
+ export const HAS_ABORT_CONTROLLER = 1 << 27;
62
+
63
+ // Flags exclusive to deriveds
64
+ /** The global state of the derived is a value that was assigned to it, rather than a run of it */
65
+ export const ASSIGNED = 1 << 26;
66
+
60
67
  export const STATE_SYMBOL = Symbol('$state');
61
68
  /** Marks component export objects, so that `proxy(...)` leaves them untouched */
62
69
  export const COMPONENT_SYMBOL = Symbol('component');
@@ -113,11 +113,11 @@ export function log_effect_tree(effect, highlighted = [], depth = 0, is_reachabl
113
113
  console.groupEnd();
114
114
  }
115
115
 
116
- if (effect.deps !== null) {
116
+ if (effect.edges !== null) {
117
117
  // eslint-disable-next-line no-console
118
118
  console.groupCollapsed('%cdeps', 'font-weight: normal');
119
119
 
120
- for (const dep of effect.deps) {
120
+ for (const dep of effect.edges) {
121
121
  log_dep(dep);
122
122
  }
123
123
 
@@ -163,8 +163,8 @@ function log_dep(dep) {
163
163
  untrack(() => snapshot(derived.v))
164
164
  );
165
165
 
166
- if (derived.deps) {
167
- for (const d of derived.deps) {
166
+ if (derived.edges) {
167
+ for (const d of derived.edges) {
168
168
  log_dep(d);
169
169
  }
170
170
  }
@@ -459,10 +459,10 @@ export function log_inconsistent_branches(effect) {
459
459
  console.log('%cfn:', 'font-weight: bold', branch.effect.fn);
460
460
  }
461
461
 
462
- if (branch.effect.deps !== null) {
462
+ if (branch.effect.edges !== null) {
463
463
  // eslint-disable-next-line no-console
464
464
  console.groupCollapsed('%cdeps', 'font-weight: normal');
465
- for (const dep of branch.effect.deps) {
465
+ for (const dep of branch.effect.edges) {
466
466
  log_dep(dep);
467
467
  }
468
468
  // eslint-disable-next-line no-console
@@ -1,9 +1,11 @@
1
- /** @import { Derived, Reaction, Value } from '#client' */
1
+ /** @import { BatchRecord, BatchValue, Derived, DerivedRecord, Reaction, Value } from '#client' */
2
2
  import { UNINITIALIZED } from '../../../constants.js';
3
3
  import { snapshot } from '../../shared/clone.js';
4
4
  import { DERIVED, ASYNC, PROXY_PATH_SYMBOL, STATE_SYMBOL } from '#client/constants';
5
5
  import { effect_tracking } from '../reactivity/effects.js';
6
- import { active_reaction, untrack } from '../runtime.js';
6
+ import { batch_values, view_batch } from '../reactivity/batch.js';
7
+ import { get_view } from '../reactivity/deriveds.js';
8
+ import { active_reaction, run_of, untrack, version_of } from '../runtime.js';
7
9
 
8
10
  /**
9
11
  * @typedef {{
@@ -15,19 +17,67 @@ import { active_reaction, untrack } from '../runtime.js';
15
17
  export let tracing_expressions = null;
16
18
 
17
19
  /**
20
+ * The value of `signal`, with its version, as the active view of the world sees it (see `get`): for a
21
+ * derived, the run of it that applies — a record in the batch, or the derived itself — or an assigned value
18
22
  * @param {Value} signal
19
- * @param {TraceEntry} [entry]
23
+ * @returns {Value | DerivedRecord | BatchValue}
20
24
  */
21
- function log_entry(signal, entry) {
22
- const value = signal.v;
25
+ function view_of(signal) {
26
+ if (batch_values === null) return signal;
27
+ if ((signal.f & DERIVED) !== 0) return get_view(/** @type {Derived} */ (signal));
28
+ return batch_values.get(signal) ?? signal;
29
+ }
30
+
31
+ /**
32
+ * The run of `reaction` that applies in the active view of the world (see `run_of`), which for a derived
33
+ * in the view of a batch is its record in the batch if it has one (see `get_view`). While the reaction
34
+ * runs, that's its previous run
35
+ * @param {Reaction} reaction
36
+ * @returns {Reaction | BatchRecord}
37
+ */
38
+ function run_in_view(reaction) {
39
+ if ((reaction.f & DERIVED) !== 0 && batch_values !== null) {
40
+ return view_batch?.get_record(reaction) ?? reaction;
41
+ }
42
+
43
+ return run_of(reaction);
44
+ }
45
+
46
+ /**
47
+ * Whether `signal` changed in the active view of the world since the traced reaction last ran. If its previous
48
+ * run read it, that's whether the version it saw is no longer current. Otherwise (it's a dependency of a derived
49
+ * the reaction read, or the reaction didn't read it before), whether it was written since `since`: the one place
50
+ * where versions are compared by order, which is only a heuristic — a view can undo writes, which gives values
51
+ * older versions again
52
+ * @param {Value} signal
53
+ * @param {Reaction | BatchRecord} run the previous run of the traced reaction (see `run_in_view`)
54
+ * @param {number} since the version of the reaction's previous run (`0` if there's none)
55
+ */
56
+ function is_changed(signal, run, since) {
57
+ var i = run.deps?.indexOf(signal) ?? -1;
58
+ var seen = i === -1 ? undefined : run.dv?.[i];
59
+
60
+ if (seen !== undefined) return version_of(signal) !== seen;
61
+
62
+ return since === 0 || version_of(signal) > since;
63
+ }
64
+
65
+ /**
66
+ * @param {Value} signal
67
+ * @param {TraceEntry | undefined} entry
68
+ * @param {Reaction | BatchRecord} run the previous run of the traced reaction (see `run_in_view`)
69
+ * @param {number} since the version of the reaction's previous run (`0` if there's none)
70
+ */
71
+ function log_entry(signal, entry, run, since) {
72
+ const view = view_of(signal);
73
+ const value = view.v;
23
74
 
24
75
  if (value === UNINITIALIZED) {
25
76
  return;
26
77
  }
27
78
 
28
79
  const type = get_type(signal);
29
- const current_reaction = /** @type {Reaction} */ (active_reaction);
30
- const dirty = signal.wv > current_reaction.wv || current_reaction.wv === 0;
80
+ const dirty = is_changed(signal, run, since);
31
81
  const style = dirty
32
82
  ? 'color: CornflowerBlue; font-weight: bold'
33
83
  : 'color: grey; font-weight: normal';
@@ -42,10 +92,13 @@ function log_entry(signal, entry) {
42
92
  : value
43
93
  );
44
94
 
45
- if (type === '$derived') {
46
- const deps = new Set(/** @type {Derived} */ (signal).deps);
95
+ if ((signal.f & DERIVED) !== 0) {
96
+ const deps = new Set(
97
+ ('deps' in view ? view : run_in_view(/** @type {Derived} */ (signal))).deps
98
+ );
99
+
47
100
  for (const dep of deps) {
48
- log_entry(dep);
101
+ log_entry(dep, undefined, run, since);
49
102
  }
50
103
  }
51
104
 
@@ -111,10 +164,13 @@ export function trace(label, fn) {
111
164
  console.group(`${prefix} %c(${time}ms)`, 'color: grey');
112
165
 
113
166
  var entries = tracing_expressions.entries;
167
+ var reaction = /** @type {Reaction} */ (active_reaction);
168
+ var run = run_in_view(reaction);
169
+ var since = run.wv ?? reaction.wv;
114
170
 
115
171
  untrack(() => {
116
172
  for (const [signal, traces] of entries) {
117
- log_entry(signal, traces);
173
+ log_entry(signal, traces, run, since);
118
174
  }
119
175
  });
120
176
 
@@ -1,4 +1,5 @@
1
- /** @import { Blocker, TemplateNode, Value } from '#client' */
1
+ /** @import { TemplateNode, Value } from '#client' */
2
+ /** @import { Blocker } from '../../reactivity/async.js' */
2
3
  import { flatten } from '../../reactivity/async.js';
3
4
  import { get } from '../../runtime.js';
4
5
  import {
@@ -1,4 +1,4 @@
1
- /** @import { Source, TemplateNode } from '#client' */
1
+ /** @import { Effect, Source, TemplateNode } from '#client' */
2
2
  import { is_promise } from '../../../shared/utils.js';
3
3
  import { block } from '../../reactivity/effects.js';
4
4
  import { internal_set, mutable_source, source } from '../../reactivity/sources.js';
@@ -10,12 +10,15 @@ import {
10
10
  set_hydrating
11
11
  } from '../hydration.js';
12
12
  import { queue_micro_task } from '../task.js';
13
+ import { should_defer_append } from '../operations.js';
13
14
  import { HYDRATION_START_ELSE, UNINITIALIZED } from '../../../../constants.js';
15
+ import { ASYNC, DESTROYED, EFFECT_PRESERVED } from '#client/constants';
14
16
  import { is_runes } from '../../context.js';
15
17
  import { Batch, current_batch, flushSync, is_flushing_sync } from '../../reactivity/batch.js';
16
18
  import { BranchManager } from './branches.js';
17
- import { capture, unset_context } from '../../reactivity/async.js';
19
+ import { capture, merge_target, unset_context } from '../../reactivity/async.js';
18
20
  import { DEV } from 'esm-env';
21
+ import { active_effect } from '../../runtime.js';
19
22
 
20
23
  const PENDING = 0;
21
24
  const THEN = 1;
@@ -43,6 +46,11 @@ export function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
43
46
  var value = runes ? source(v) : mutable_source(v, false, false);
44
47
  var error = runes ? source(v) : mutable_source(v, false, false);
45
48
 
49
+ // like the result of an async expression, the states of a run belong to the batch
50
+ // that holds them: another batch's commit doesn't overwrite them (see `BatchValue#async`)
51
+ value.f |= ASYNC;
52
+ error.f |= ASYNC;
53
+
46
54
  if (DEV) {
47
55
  value.label = '{#await ...} value';
48
56
  error.label = '{#await ...} error';
@@ -50,11 +58,77 @@ export function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
50
58
 
51
59
  var branches = new BranchManager(node);
52
60
 
61
+ /** The latest run of the block in the real world */
62
+ var current = {};
63
+
64
+ /**
65
+ * The latest run of the block in each fork that ran it. Once the fork is committed, that's a run of the real
66
+ * world (and so are its later runs), until a later run in the real world supersedes it (`null`)
67
+ * @type {Map<Batch, {} | null>}
68
+ */
69
+ var forks = new Map();
70
+
71
+ /** @param {Batch} batch */
72
+ var commit = (batch) => {
73
+ var run = forks.get(batch);
74
+ if (run) current = run;
75
+ forks.delete(batch);
76
+ };
77
+
78
+ /** @param {Batch} batch */
79
+ var discard = (batch) => {
80
+ forks.delete(batch);
81
+ };
82
+
83
+ /**
84
+ * @param {{}} run
85
+ * @param {Batch} batch
86
+ */
87
+ var is_latest = (run, batch) => {
88
+ if (forks.has(batch)) return forks.get(batch) === run;
89
+ if (run !== current) return false;
90
+
91
+ // a fork that was committed since supersedes it
92
+ for (const [b, r] of forks) {
93
+ if (!b.is_fork && r !== null) return false;
94
+ }
95
+
96
+ return true;
97
+ };
98
+
99
+ /**
100
+ * The batch that the states of a run in `batch` go into, if they aren't their own batch: the fork, so that they
101
+ * don't show before it's committed — and once it is, the batch it became, so that they land along with the rest
102
+ * of its changes while those are pending (its later runs, too: they replace the states it holds)
103
+ * @param {Batch} batch
104
+ */
105
+ var owner = (batch) => {
106
+ var target = merge_target(batch);
107
+ return forks.has(batch) && target.linked ? target : null;
108
+ };
109
+
53
110
  block(() => {
111
+ var effect = /** @type {Effect} */ (active_effect);
54
112
  var batch = /** @type {Batch} */ (current_batch);
55
113
  var input = get_input();
114
+ var run = {};
115
+
116
+ // (not the first run, which creates the block for every batch's view, see `should_defer_append`)
117
+ var fork = batch.is_fork && should_defer_append();
118
+
119
+ if (fork || forks.has(batch)) {
120
+ forks.set(batch, run);
121
+ batch.oncommit(commit);
122
+ batch.ondiscard(discard);
123
+ }
124
+
125
+ if (!fork) {
126
+ for (const b of forks.keys()) {
127
+ if (!b.is_fork && b !== batch) forks.set(b, null);
128
+ }
56
129
 
57
- var destroyed = false;
130
+ current = run;
131
+ }
58
132
 
59
133
  /** Whether or not there was a hydration mismatch. Needs to be a `let` or else it isn't treeshaken out */
60
134
  // @ts-ignore coercing `node` to a `Comment` causes TypeScript and Prettier to fight
@@ -71,15 +145,33 @@ export function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
71
145
  var resolved = false;
72
146
 
73
147
  /**
74
- * @param {() => void} fn
148
+ * @param {(set: (source: Source, value: any) => void) => void} fn
75
149
  */
76
150
  const resolve = (fn) => {
77
- if (destroyed) return;
151
+ if ((effect.f & DESTROYED) !== 0 || !is_latest(run, batch)) return;
78
152
 
79
153
  resolved = true;
154
+
155
+ var target = owner(batch);
156
+
157
+ if (target !== null) {
158
+ var previous = current_batch;
159
+ restore(target);
160
+
161
+ try {
162
+ fn((source, v) => /** @type {Batch} */ (target).capture(source, v, source.equals(v)));
163
+ } finally {
164
+ unset_context(false);
165
+ target.flush();
166
+ if (previous?.linked) previous.activate();
167
+ }
168
+
169
+ return;
170
+ }
171
+
80
172
  // We don't want to restore the previous batch here; {#await} blocks don't follow the async logic
81
173
  // we have elsewhere, instead pending/resolve/fail states are each their own batch so to speak.
82
- restore(false);
174
+ restore(null);
83
175
  // ...but it might still be set here. That means a `save(...)` has restored it — but that batch will
84
176
  // likely already have been committed by the time it resolves, and this resolve should be processed
85
177
  // in a separate batch. We're not using batch.deactivate()/activate() above because get_input()
@@ -92,7 +184,7 @@ export function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
92
184
  Batch.ensure();
93
185
 
94
186
  try {
95
- fn();
187
+ fn(internal_set);
96
188
  } finally {
97
189
  unset_context(false);
98
190
 
@@ -104,19 +196,19 @@ export function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
104
196
 
105
197
  input.then(
106
198
  (v) => {
107
- resolve(() => {
108
- internal_set(value, v);
199
+ resolve((set) => {
200
+ set(value, v);
109
201
  branches.ensure(THEN, then_fn && ((target) => then_fn(target, value)));
110
202
  });
111
203
  },
112
204
  (e) => {
113
- resolve(() => {
114
- internal_set(error, e);
205
+ resolve((set) => {
206
+ set(error, e);
115
207
  branches.ensure(CATCH, catch_fn && ((target) => catch_fn(target, error)));
116
208
 
117
209
  if (!catch_fn) {
118
210
  // Rethrow the error if no catch block exists
119
- throw error.v;
211
+ throw e;
120
212
  }
121
213
  });
122
214
  }
@@ -136,7 +228,9 @@ export function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
136
228
  });
137
229
  }
138
230
  } else {
139
- internal_set(value, input);
231
+ if (owner(batch) === batch) batch.capture(value, input, value.equals(input));
232
+ else internal_set(value, input);
233
+
140
234
  branches.ensure(THEN, then_fn && ((target) => then_fn(target, value)));
141
235
  }
142
236
 
@@ -144,9 +238,5 @@ export function await_block(node, get_input, pending_fn, then_fn, catch_fn) {
144
238
  // continue in hydration mode
145
239
  set_hydrating(true);
146
240
  }
147
-
148
- return () => {
149
- destroyed = true;
150
- };
151
- });
241
+ }, EFFECT_PRESERVED); // states are selected asynchronously: keep the effect even without dependencies
152
242
  }