brumate 0.4.4 → 0.5.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 (63) hide show
  1. package/dist/{boot-D3NjfyUX.d.ts → boot-Difa0qdg.d.ts} +2 -8
  2. package/dist/cli.js +2 -2
  3. package/dist/{client-iZ9a1Nut.js → client-BYHGusTe.js} +990 -369
  4. package/dist/client-BYHGusTe.js.map +1 -0
  5. package/dist/{client-DNva05jp.d.ts → client-DvsU9qxG.d.ts} +107 -23
  6. package/dist/{defer-DP7dMS2y.js → defer-B63oF5Oa.js} +2 -2
  7. package/dist/{defer-DP7dMS2y.js.map → defer-B63oF5Oa.js.map} +1 -1
  8. package/dist/{devtools-BJB_MMeL.js → devtools-D_SQpXTg.js} +4 -4
  9. package/dist/{devtools-BJB_MMeL.js.map → devtools-D_SQpXTg.js.map} +1 -1
  10. package/dist/{devtools-panel-CUV6A4ZE.js → devtools-panel-B9yokst5.js} +2 -2
  11. package/dist/{devtools-panel-CUV6A4ZE.js.map → devtools-panel-B9yokst5.js.map} +1 -1
  12. package/dist/{features-CHY5Ekku.js → features-D5kLyihb.js} +19 -2
  13. package/dist/features-D5kLyihb.js.map +1 -0
  14. package/dist/{files-BZRjz9Mx.js → files-s4wmjcZV.js} +2 -2
  15. package/dist/{files-BZRjz9Mx.js.map → files-s4wmjcZV.js.map} +1 -1
  16. package/dist/index.d.ts +1 -8
  17. package/dist/index.js +1 -1
  18. package/dist/{inspect-BLOdfj7o.js → inspect-BLPt-dZZ.js} +891 -142
  19. package/dist/inspect-BLPt-dZZ.js.map +1 -0
  20. package/dist/{loader-CheV6t0N.js → loader-DKxhLjJw.js} +4 -4
  21. package/dist/{loader-CheV6t0N.js.map → loader-DKxhLjJw.js.map} +1 -1
  22. package/dist/{navigate-CfOr-TRF.js → navigate-BcV1qkkx.js} +2 -2
  23. package/dist/navigate-BcV1qkkx.js.map +1 -0
  24. package/dist/{produce-DS-dQaUX.js → produce-Cq6KKi7b.js} +2 -2
  25. package/dist/{produce-DS-dQaUX.js.map → produce-Cq6KKi7b.js.map} +1 -1
  26. package/dist/{rpc-DvTwGfL_.js → rpc-CIVU4Ktx.js} +5 -5
  27. package/dist/rpc-CIVU4Ktx.js.map +1 -0
  28. package/dist/runtime/bundles.d.ts +9 -0
  29. package/dist/runtime/bundles.js +60 -0
  30. package/dist/runtime/bundles.js.map +1 -0
  31. package/dist/runtime/client.d.ts +2 -2
  32. package/dist/runtime/client.js +3 -3
  33. package/dist/runtime/devtools.d.ts +1 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/loader.d.ts +2 -2
  37. package/dist/runtime/loader.js +2 -2
  38. package/dist/runtime/server.d.ts +3 -3
  39. package/dist/runtime/server.js +4 -4
  40. package/dist/runtime/static-loader.d.ts +2 -2
  41. package/dist/runtime/static-loader.js +1 -1
  42. package/dist/runtime/testing.d.ts +2 -2
  43. package/dist/runtime/testing.js +2 -2
  44. package/dist/{server-BXMH3Z9T.d.ts → server-CAwIqrXl.d.ts} +44 -5
  45. package/dist/{server-O_rC-RRL.js → server-Doy5HR7r.js} +106 -17
  46. package/dist/server-Doy5HR7r.js.map +1 -0
  47. package/dist/{static-loader-BiUaZaag.d.ts → static-loader-9Nc1GvF0.d.ts} +2 -2
  48. package/dist/{static-loader-BLJYvTKc.js → static-loader-Bdet7g76.js} +3 -26
  49. package/dist/static-loader-Bdet7g76.js.map +1 -0
  50. package/dist/{stream-JGRPr7u5.js → stream-BdhzvPQO.js} +2 -2
  51. package/dist/{stream-JGRPr7u5.js.map → stream-BdhzvPQO.js.map} +1 -1
  52. package/dist/vite.d.ts +1 -1
  53. package/dist/vite.js +129 -51
  54. package/dist/vite.js.map +1 -1
  55. package/package.json +5 -1
  56. package/skills/brumate/references/errors.md +19 -5
  57. package/dist/client-iZ9a1Nut.js.map +0 -1
  58. package/dist/features-CHY5Ekku.js.map +0 -1
  59. package/dist/inspect-BLOdfj7o.js.map +0 -1
  60. package/dist/navigate-CfOr-TRF.js.map +0 -1
  61. package/dist/rpc-DvTwGfL_.js.map +0 -1
  62. package/dist/server-O_rC-RRL.js.map +0 -1
  63. package/dist/static-loader-BLJYvTKc.js.map +0 -1
@@ -292,7 +292,7 @@ const REACTIVE = /* @__PURE__ */ new Set([
292
292
  /** The module of the wrappers of event handlers, which the compiler reads. */
293
293
  const EVENTS_MODULE = "brumate/events";
294
294
  /** The wrappers that `brumate/events` exports. */
295
- const WRAPPERS$1 = /* @__PURE__ */ new Set([
295
+ const WRAPPERS$2 = /* @__PURE__ */ new Set([
296
296
  "prevent",
297
297
  "stop",
298
298
  "once",
@@ -405,6 +405,34 @@ function bindableNames(type, file) {
405
405
  function isBindableType(annotation) {
406
406
  return annotation?.type === "TSTypeReference" && annotation.typeName.type === "Identifier" && annotation.typeName.name === "Bindable";
407
407
  }
408
+ /**
409
+ * True for an expression that the compiler sees gives a promise: `new Promise(…)`, a call of a
410
+ * method of `Promise` or of `fetch`, a call of a server function or of an async function of the
411
+ * file, and a prop typed as a promise.
412
+ */
413
+ function givesPromise(node, scope) {
414
+ switch (node.type) {
415
+ case "ParenthesizedExpression":
416
+ case "TSAsExpression":
417
+ case "TSSatisfiesExpression":
418
+ case "TSNonNullExpression": return givesPromise(node.expression, scope);
419
+ case "NewExpression": return node.callee.type === "Identifier" && node.callee.name === "Promise";
420
+ case "Identifier": return lookup(scope, node.name)?.promise === true;
421
+ case "CallExpression": {
422
+ const callee = node.callee;
423
+ if (callee.type === "MemberExpression") return callee.object.type === "Identifier" && callee.object.name === "Promise";
424
+ if (callee.type !== "Identifier") return false;
425
+ if (callee.name === "fetch") return true;
426
+ const declaration = lookup(scope, callee.name);
427
+ return declaration?.kind === "server-function" || declaration?.serverImport !== void 0 || declaration?.kind === "function" && (declaration.site?.node)?.async === true;
428
+ }
429
+ default: return false;
430
+ }
431
+ }
432
+ /** The message of BRM188, for `code` at `place`. */
433
+ function promiseMessage(code, place) {
434
+ return `"${code}" gives a promise, and ${place} cannot wait for one. Await it in the code that runs, or read its value with $memo`;
435
+ }
408
436
  /** True for `Promise<...>`, or a union that holds one. */
409
437
  function isPromiseType(annotation) {
410
438
  if (annotation?.type === "TSUnionType") {
@@ -483,8 +511,10 @@ var Analyzer = class {
483
511
  this.markPromiseProps();
484
512
  for (const site of this.sites) new Resolver(this, site).run();
485
513
  this.addPendingReads();
514
+ this.checkLoadingHeaders();
486
515
  this.resolveRefs();
487
516
  this.check();
517
+ this.checkPromises();
488
518
  return {
489
519
  module: this.module,
490
520
  component: this.component,
@@ -516,6 +546,57 @@ var Analyzer = class {
516
546
  reference.site.reads.push(read);
517
547
  }
518
548
  }
549
+ /**
550
+ * The header of `#loading (posts) { … }` names memos that markup in the body reads. The block
551
+ * shows its fallback again while one of them, or a memo upstream of it, loads, so the header
552
+ * reads those memos too, as `$isPending(memo)` does.
553
+ */
554
+ checkLoadingHeaders() {
555
+ for (const site of this.sites) {
556
+ const block = site.block;
557
+ if (site.kind !== "block" || block?.kind !== "loading" || !block.on) continue;
558
+ let body;
559
+ for (const scope of this.scopes) if (scope.block === block && scope.body === block.body) body = scope;
560
+ const ast = unwrapTypes(block.on.ast);
561
+ const names = ast.type === "SequenceExpression" ? ast.expressions : [ast];
562
+ const reads = [...site.reads];
563
+ for (const name of names) {
564
+ const node = unwrapTypes(name);
565
+ let read;
566
+ for (const item of reads) if (node.type === "Identifier" && item.range.start === node.start) read = item;
567
+ const declaration = read?.declaration;
568
+ if (!declaration || declaration.kind !== "memo" && declaration.kind !== "async-memo" || !body || !this.markupReads(declaration, body)) {
569
+ this.report("error", `"${this.file.source.slice(name.start, name.end)}" in the #loading header is not a memo that markup in the body reads. Name a $memo of the component or of a block script around the block`, name);
570
+ continue;
571
+ }
572
+ const upstream = upstreamMemos(declaration);
573
+ for (const item of [declaration, ...upstream]) if (item.timing) {
574
+ this.report("warning", `#loading (${declaration.name}) shows its fallback while the $${item.timing.kind} memo "${item.name}" waits, at each change of its value`, name);
575
+ break;
576
+ }
577
+ for (const item of upstream) {
578
+ const added = {
579
+ ...read,
580
+ declaration: item,
581
+ range: {
582
+ start: name.end,
583
+ end: name.end
584
+ }
585
+ };
586
+ item.reads.push(added);
587
+ site.reads.push(added);
588
+ }
589
+ }
590
+ }
591
+ }
592
+ /** True when markup or a memo inside `body` reads `declaration`, so it renders from it. */
593
+ markupReads(declaration, body) {
594
+ for (const read of declaration.reads) {
595
+ const kind = read.site.kind;
596
+ if (read.range.start !== read.range.end && kind !== "function" && kind !== "server-function" && kind !== "event" && kind !== "effect" && kind !== "client" && isWithin(read.site.scope, body)) return true;
597
+ }
598
+ return false;
599
+ }
519
600
  /** Marks the props that the type of `$props<T>()` writes as `Promise<...>`. */
520
601
  markPromiseProps() {
521
602
  const names = /* @__PURE__ */ new Set();
@@ -626,7 +707,7 @@ var Analyzer = class {
626
707
  node = node.arguments[0];
627
708
  continue;
628
709
  }
629
- if (name === void 0 || !WRAPPERS$1.has(name)) break;
710
+ if (name === void 0 || !WRAPPERS$2.has(name)) break;
630
711
  const [handler, ...rest] = node.arguments;
631
712
  if (!handler || name !== "prevent" && rest.length > 0) {
632
713
  this.report("error", `${name} takes a handler`, node);
@@ -995,7 +1076,7 @@ var Analyzer = class {
995
1076
  node = handler;
996
1077
  continue;
997
1078
  }
998
- if (name === void 0 || !WRAPPERS$1.has(name) || !handler) break;
1079
+ if (name === void 0 || !WRAPPERS$2.has(name) || !handler) break;
999
1080
  const names = [];
1000
1081
  let unnamed = false;
1001
1082
  for (const key of keys) {
@@ -1198,10 +1279,7 @@ var Analyzer = class {
1198
1279
  });
1199
1280
  break;
1200
1281
  case "loading":
1201
- if (block.on) {
1202
- this.report("error", "#loading does not take a header yet. Write #loading { … }, since the header would be dropped", block.on);
1203
- this.header(block, scope, block.on, "loading");
1204
- }
1282
+ if (block.on) this.header(block, scope, block.on, "loading");
1205
1283
  this.visitBody(block.body, scope, block);
1206
1284
  if (block.fallback) this.visitBody(block.fallback, scope, block);
1207
1285
  break;
@@ -1236,6 +1314,20 @@ var Analyzer = class {
1236
1314
  else declaration.refs.push(ref);
1237
1315
  }
1238
1316
  }
1317
+ /**
1318
+ * Reports a promise where markup cannot wait for it: an event handler, the key of a `#for`, and
1319
+ * the name that `ref` or `$bind` binds. Markup waits for a promise in text and attributes only.
1320
+ */
1321
+ checkPromises() {
1322
+ for (const site of this.sites) {
1323
+ let place;
1324
+ if (site.kind === "event" || site.handlerProp) place = "an event handler";
1325
+ else if (site.kind === "block" && site.label === "for key") place = "the key of a #for";
1326
+ if (place && givesPromise(site.node, site.scope)) this.report("error", promiseMessage(this.file.source.slice(site.node.start, site.node.end), place), site.range);
1327
+ }
1328
+ for (const binding of this.bindings) if (binding.declaration.promise) this.report("error", promiseMessage(binding.declaration.name, "a binding"), binding.call);
1329
+ for (const declaration of this.declarations) if (declaration.promise) for (const ref of declaration.refs) this.report("error", promiseMessage(declaration.name, "a ref"), ref.attribute);
1330
+ }
1239
1331
  check() {
1240
1332
  for (const declaration of this.declarations) if (declaration.kind === "action") {
1241
1333
  if (lookup(declaration.scope, declaration.action)?.kind !== "server-function") this.report("error", `$action needs a server function of this file, and ${declaration.action} is not one`, declaration.range);
@@ -1794,12 +1886,13 @@ const SYNTAX = [
1794
1886
  entry("BRM021", "Expected an attribute name", "A tag has a character where an attribute name belongs.", "<input disabled>"),
1795
1887
  entry("BRM022", "Unknown event modifier \":{modifier}\"", "The modifier after an event name is not one of the known ones.", "<form onSubmit=(prevent(send))></form>"),
1796
1888
  entry("BRM180", "\"{name}\" is not an event name. Write \"{camel}\"", "An event of more than one word is written in camel case. The lower-case form is an error.", "<input onKeyDown=(handle) onFocusOut=(handle) />"),
1797
- entry("BRM181", "#loading does not take a header yet. Write #loading { … }, since the header would be dropped", "A `#loading` block has a header in parentheses. The compiler reads no meaning from it.", "#loading (data) {\n <p>{data.name}</p>\n} #else {\n <p>Loading</p>\n}"),
1889
+ entry("BRM186", "\"{name}\" in the #loading header is not a memo that markup in the body reads. Name a $memo of the component or of a block script around the block", "The header of `#loading (…)` names something other than a memo, or a memo that no markup in the body reads, so its loads would not show the fallback for that body.", "const posts = $memo(loadPosts(id));\n#loading (posts) {\n <p>{posts.length} posts</p>\n} #else {\n <p>Loading</p>\n}"),
1798
1890
  entry("BRM182", "The handler reads \"{name}\", a memo that can lack a value. Wait for it with await $resolve({name}), or check $isPending({name}) first", "A handler, a handler prop or a `$client` callback reads an async memo that may still be loading, with no `$isPending` check or `await $resolve` before the read.", "<script>\n const user = $memo(getUser(id));\n async function save() {\n await $resolve(user);\n send(user.name);\n }\n<\/script>"),
1799
1891
  entry("BRM183", "$resolve needs a $memo and, as an option, a timeout or a signal", "`$resolve` takes the name of a memo, and one object of options at most.", "async function save() {\n const profile = await $resolve(user, { timeout: 5000 });\n}"),
1800
1892
  entry("BRM184", "$resolve cannot run where a memo computes or markup renders. Call it in a handler, an effect or a $client callback", "`$resolve` waits, so it is called where an event starts the code, not where a memo computes or markup renders.", "async function save() {\n await $resolve(user);\n}"),
1801
1893
  entry("BRM185", "<{tag}> cannot be inside <{parent}>: the HTML parser closes or moves it before the page runs. Move it out of the <{parent}>, or use a <span> or as=\"span\"", "The HTML parser does not keep this nesting. A `<p>` ends at a block element such as `<div>`, an `<a>` or a `<form>` inside the same tag starts again, and a table keeps only table parts. The browser builds a page that differs from the markup, and the start and end markers of a block can land in different parents.", "<p>Total: <span>{total}</span></p>\n<div>\n <p>Total</p>\n</div>"),
1802
1894
  entry("BRM187", "The {kind} {name} of {component} did not settle: it writes a value that it reads, and runs again without end. Wrap the read or the write in $untrack, or write only when the value changes", "In the browser, an effect or an update writes a value that it reads, so each run schedules the next. Past 1000 rounds of effects, or 10000 rounds of updates, in one change, the page stops the loop and sends this error to the nearest `#try` in place of hanging the tab. A production build sends the short form `Update loop {scope}:{name} [BRM187]`.", "<script>\n import { $effect, $signal, $untrack } from 'brumate/signals';\n\n let query = $signal('');\n let saves = $signal(0);\n\n $effect(() => {\n void query;\n $untrack(saves++);\n });\n<\/script>"),
1895
+ entry("BRM188", "\"{name}\" gives a promise, and {place} cannot wait for one. Await it in the code that runs, or read its value with $memo", "Markup waits for a promise in text and in attribute values only. An event handler, the key of a `#for`, a `ref` and a `$bind` need the value at once, and the compiler sees that this expression gives a promise: `new Promise(…)`, a call of a server function or of an async function, or a prop typed as a promise.", "<button onClick=(() => save(draft))>Save</button>\n#for (user of users by user.id) {\n <p>{user.name}</p>\n}"),
1803
1896
  entry("BRM023", "Modifiers apply to elements. Put \":{modifier}\" on the element that the component renders", "An event modifier is on a component, which only passes the handler on.", "<form onSubmit=(prevent(send))></form>"),
1804
1897
  entry("BRM024", "Expected an event handler", "An event attribute has no `=` and no value.", "<button onClick=(() => count++)>Add</button>"),
1805
1898
  entry("BRM025", "An event handler must be an expression, not a string", "The value of an event attribute is a quoted string.", "<button onClick=(() => count++)>Add</button>"),
@@ -4116,7 +4209,7 @@ const SENDABLE = /* @__PURE__ */ new Set([
4116
4209
  "Boolean"
4117
4210
  ]);
4118
4211
  /** Compile-time functions whose argument is the value, such as `$signal(new Foo())`. */
4119
- const WRAPPERS = /* @__PURE__ */ new Set([
4212
+ const WRAPPERS$1 = /* @__PURE__ */ new Set([
4120
4213
  "$signal",
4121
4214
  "$memo",
4122
4215
  "$debounced",
@@ -4128,7 +4221,7 @@ function initializers(file) {
4128
4221
  function visit(node) {
4129
4222
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
4130
4223
  let init = node.init;
4131
- if (init.type === "CallExpression" && init.callee.type === "Identifier" && WRAPPERS.has(init.callee.name) && init.arguments[0]) init = init.arguments[0];
4224
+ if (init.type === "CallExpression" && init.callee.type === "Identifier" && WRAPPERS$1.has(init.callee.name) && init.arguments[0]) init = init.arguments[0];
4132
4225
  result.set(node.id.start, init);
4133
4226
  }
4134
4227
  for (const [, child] of children(node)) visit(child);
@@ -5467,7 +5560,7 @@ function isAsync(declaration) {
5467
5560
  /** The starts of the memo names in `$isPending(…)` and `$resolve(…)` calls of the file. */
5468
5561
  let checkedStarts = /* @__PURE__ */ new Set();
5469
5562
  /** The sites that render markup, which the server waits for outside `#loading`. */
5470
- const MARKUP_SITES = /* @__PURE__ */ new Set([
5563
+ const MARKUP_SITES$1 = /* @__PURE__ */ new Set([
5471
5564
  "insert",
5472
5565
  "attribute",
5473
5566
  "tag",
@@ -5493,7 +5586,7 @@ function waitedFor(declaration, seen = /* @__PURE__ */ new Set()) {
5493
5586
  if (read.range.start === read.range.end || checkedStarts.has(read.range.start)) continue;
5494
5587
  const site = read.site;
5495
5588
  const isHandlerProp = site.kind === "prop" && (site.handlerProp === true || site.node.type === "ArrowFunctionExpression" || site.node.type === "FunctionExpression");
5496
- if (MARKUP_SITES.has(site.kind) && !isHandlerProp && !inStreamedBody(site)) return true;
5589
+ if (MARKUP_SITES$1.has(site.kind) && !isHandlerProp && !inStreamedBody(site)) return true;
5497
5590
  if (site.kind === "memo" && site.declaration && waitedFor(site.declaration, seen)) return true;
5498
5591
  }
5499
5592
  return false;
@@ -6287,7 +6380,7 @@ function createPlan(file, graph, path, hideNames = false) {
6287
6380
  }
6288
6381
  }
6289
6382
  if (block.kind === "try" && tryCatchesClient(model, block)) scopes.get(bodyScopes.get(block.body)).needsId = true;
6290
- if (live && block.kind === "offscreen") scopes.get(bodyScopes.get(block.body)).needsId = true;
6383
+ if (live && (block.kind === "offscreen" || block.kind === "loading")) scopes.get(bodyScopes.get(block.body)).needsId = true;
6291
6384
  if (block.kind === "portal" || block.kind === "head") scopes.get(bodyScopes.get(block.body)).needsId = true;
6292
6385
  const inner = block.kind === "portal" || block.kind === "head" ? void 0 : outer;
6293
6386
  for (const body of blockBodies(block)) {
@@ -6666,13 +6759,19 @@ function clonedTemplate(parts) {
6666
6759
  kind: "attribute",
6667
6760
  name: attribute[1],
6668
6761
  value: attribute[2],
6669
- settled: part.settled
6762
+ settled: part.settled,
6763
+ promise: part.promise
6670
6764
  });
6671
6765
  continue;
6672
6766
  }
6673
6767
  const spread = SPREAD.exec(code);
6674
6768
  if (spread && reader.inTag) {
6675
- add({
6769
+ if (spread[1] === "spread" && part.promise) add({
6770
+ kind: "call",
6771
+ call: `$$b.fillSpread($$q, $$m, ${spread[2]})`,
6772
+ promise: part.promise
6773
+ });
6774
+ else add({
6676
6775
  kind: "call",
6677
6776
  call: `$$b.${spread[1] === "spread" ? "setSpread" : "setOn"}($$m, ${spread[2]})`
6678
6777
  });
@@ -6686,7 +6785,8 @@ function clonedTemplate(parts) {
6686
6785
  kind: "content",
6687
6786
  value: insert[1],
6688
6787
  at: insert[2],
6689
- settled: part.settled
6788
+ settled: part.settled,
6789
+ promise: part.promise
6690
6790
  });
6691
6791
  continue;
6692
6792
  }
@@ -6704,7 +6804,8 @@ function clonedTemplate(parts) {
6704
6804
  scope: code,
6705
6805
  anchor: Number(textEnd[1]),
6706
6806
  value: textInsert[1],
6707
- at: textInsert[2]
6807
+ at: textInsert[2],
6808
+ promise: value.promise
6708
6809
  }, parent);
6709
6810
  list[index + 3] = { static: rest };
6710
6811
  index += 2;
@@ -6716,7 +6817,8 @@ function clonedTemplate(parts) {
6716
6817
  scope: code,
6717
6818
  anchor: Number(textEnd[1]),
6718
6819
  value: textInsert[1],
6719
- at: textInsert[2]
6820
+ at: textInsert[2],
6821
+ promise: value.promise
6720
6822
  }]);
6721
6823
  reader.append(`<!--x${mark}-->`);
6722
6824
  list[index + 3] = { static: close.static.slice(9) };
@@ -6870,7 +6972,8 @@ function clonedTemplate(parts) {
6870
6972
  kind: "put",
6871
6973
  value: insert[1],
6872
6974
  at: insert[2],
6873
- settled: part.settled
6975
+ settled: part.settled,
6976
+ promise: part.promise
6874
6977
  }]);
6875
6978
  reader.append(`<!--x${mark}-->`);
6876
6979
  continue;
@@ -6899,6 +7002,13 @@ function clonedTemplate(parts) {
6899
7002
  };
6900
7003
  }
6901
7004
  /**
7005
+ * A write of cloned markup, as a statement. With `scope`, its value can be a promise, which
7006
+ * `fillValue` waits for, with `key` naming its place among the places of the scope.
7007
+ */
7008
+ function promised(scope, key, value, write) {
7009
+ return scope ? `$$b.fillValue(${scope}, ${key}, ${value}, ($$v) => ${write("$$v")});` : `${write(value)};`;
7010
+ }
7011
+ /**
6902
7012
  * Replaces the `$$html +=` lines of a render with a clone of a template, and the writes on the
6903
7013
  * elements that it marks. `hoist` makes a constant of the module. Returns false when the markup
6904
7014
  * needs HTML, such as markup in a branch or a loop of the render.
@@ -6990,19 +7100,26 @@ function cloneLines(emitter, hoist, fn = 0) {
6990
7100
  for (const write of writes) if (write.kind === "call") ordered.push(write);
6991
7101
  for (const write of writes) if (write.kind !== "call") ordered.push(write);
6992
7102
  for (const write of ordered) if (write.kind === "anchor") lines.push(`${indent}$$b.keep(${write.scope}, ${write.anchor}, $$e[${index}]${write.named ? ", true" : ""});`);
7103
+ else if (write.kind === "last" && write.promise) lines.push(`${indent}$$b.keepValue(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}, ${write.at ?? "undefined"}, true);`);
6993
7104
  else if (write.kind === "last") lines.push(`${indent}$$b.appendText(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`);
6994
- else if (write.kind === "text") lines.push(`${indent}$$b.keepText(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`);
6995
- else if (write.kind === "attribute") addLine(`$$b.setAttr($$e[${index}], ${write.name}, ${write.value});`, write.settled);
6996
- else if (write.kind === "component") addLine(`$$b.place($$e[${index}], ${write.call});`, write.settled);
7105
+ else if (write.kind === "text") {
7106
+ const helper = write.promise ? "keepValue" : "keepText";
7107
+ lines.push(`${indent}$$b.${helper}(${write.scope}, ${write.anchor}, $$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`);
7108
+ } else if (write.kind === "attribute") {
7109
+ const key = anchored?.kind === "anchor" ? `${anchored.anchor} ${JSON.parse(write.name)}` : `x${index} ${JSON.parse(write.name)}`;
7110
+ addLine(promised(write.promise && (anchored?.kind === "anchor" ? anchored.scope : write.promise), JSON.stringify(key), write.value, (value) => `$$b.setAttr($$e[${index}], ${write.name}, ${value})`), write.settled);
7111
+ } else if (write.kind === "component") addLine(`$$b.place($$e[${index}], ${write.call});`, write.settled);
6997
7112
  else if (write.kind === "comment") lines.push(`${indent}$$b.nameComment($$e[${index}], ${write.data});`);
6998
- else if (write.kind === "put") addLine(`$$b.putText($$e[${index}], ${write.value}${write.at ? `, ${write.at}` : ""});`, write.settled);
6999
- else if (write.kind === "call") lines.push(`${indent}${write.call.replace("$$m", () => `$$e[${index}]`)};`);
7000
- else if (write.kind === "marker") lines.push(`${indent}$$b.markBlock($$e[${index}], ${write.scope}, ${write.anchor}, ${JSON.stringify(write.suffix)});`);
7113
+ else if (write.kind === "put") addLine(promised(write.promise, JSON.stringify(`x${index}`), write.value, (value) => `$$b.putText($$e[${index}], ${value}${write.at ? `, ${write.at}` : ""})`), write.settled);
7114
+ else if (write.kind === "call") {
7115
+ const place = anchored?.kind === "anchor" ? `${anchored.scope}, ${anchored.anchor}` : `${write.promise}, ${JSON.stringify(`x${index}`)}`;
7116
+ lines.push(`${indent}${write.call.replace("$$q", () => place).replace("$$m", () => `$$e[${index}]`)};`);
7117
+ } else if (write.kind === "marker") lines.push(`${indent}$$b.markBlock($$e[${index}], ${write.scope}, ${write.anchor}, ${JSON.stringify(write.suffix)});`);
7001
7118
  else if (write.kind === "block") {
7002
7119
  const call = emitter.fills.get(`${write.scope}:${write.anchor}`);
7003
7120
  if (call === void 0) missing = true;
7004
7121
  else fills.push(`${indent}${call.replace("$$m", () => `$$e[${index}]`)};`);
7005
- } else addLine(`$$b.setContent($$e[${index}], ${write.value}${write.at ? `, ${write.at}` : at});`, write.settled);
7122
+ } else addLine(promised(write.promise && (anchored?.kind === "anchor" ? anchored.scope : write.promise), anchored?.kind === "anchor" ? String(anchored.anchor) : JSON.stringify(`x${index}`), write.value, (value) => `$$b.setContent($$e[${index}], ${value}${write.at ? `, ${write.at}` : at})`), write.settled);
7006
7123
  }
7007
7124
  for (const group of settled.values()) {
7008
7125
  const names = group.names.join(", ");
@@ -7052,6 +7169,172 @@ function cloneLines(emitter, hoist, fn = 0) {
7052
7169
  return true;
7053
7170
  }
7054
7171
  //#endregion
7172
+ //#region src/codegen/starts.ts
7173
+ /**
7174
+ * Finds, for each statement of awaited memos (`loads`), the last statement
7175
+ * before it that its loads must run after. The memos of a statement read
7176
+ * names: those of their expressions, and those that the local functions
7177
+ * and memos they call or read read and write, followed through.
7178
+ *
7179
+ * A statement holds the load when it declares one of those names (or the
7180
+ * load would throw a TDZ `ReferenceError`), or can change one: a write such
7181
+ * as `q = x`, a call such as `params.set(…)`, an argument of a call, or a
7182
+ * mention of a local function that mentions it. A plain read does not hold
7183
+ * it. A function declaration does not hold
7184
+ * it, since it runs nothing where it is written. `runs` is false for the
7185
+ * statements that run nothing where they are written, such as `$effect` on
7186
+ * the server, which do not hold it either.
7187
+ *
7188
+ * An awaited memo of another load is not followed: the load reads it as a
7189
+ * memo, so it waits for it on its own. It is listed in `memos`, as its
7190
+ * memo must exist before the load starts.
7191
+ */
7192
+ function findLoadStarts(statements, scope, loads, runs) {
7193
+ const awaited = /* @__PURE__ */ new Set();
7194
+ for (const declarations of loads.values()) for (const declaration of declarations) awaited.add(declaration);
7195
+ const touched = [];
7196
+ const declares = [];
7197
+ const changing = /* @__PURE__ */ new Set();
7198
+ for (const statement of statements) {
7199
+ touched.push(/* @__PURE__ */ new Set());
7200
+ declares.push(/* @__PURE__ */ new Set());
7201
+ if (statement.type !== "FunctionDeclaration") addChanging(changing, statement, false);
7202
+ }
7203
+ for (let current = scope; current; current = current.parent) for (const declaration of current.declarations.values()) {
7204
+ const at = findStatement(statements, declaration.range.start);
7205
+ if (at !== -1 && statements[at].type !== "FunctionDeclaration") declares[at].add(declaration);
7206
+ const isFunction = declaration.kind === "function" || declaration.kind === "server-function";
7207
+ for (const reference of [...declaration.reads, ...declaration.writes]) {
7208
+ const index = findStatement(statements, reference.range.start);
7209
+ const changes = isFunction || changing.has(reference.range.start) || declaration.writes.includes(reference);
7210
+ if (index !== -1 && changes) addMentions(touched[index], declaration, awaited);
7211
+ }
7212
+ }
7213
+ const result = /* @__PURE__ */ new Map();
7214
+ for (const [index, statement] of statements.entries()) {
7215
+ const declarations = loads.get(statement);
7216
+ if (!declarations) continue;
7217
+ const names = /* @__PURE__ */ new Set();
7218
+ const memos = [];
7219
+ for (const declaration of declarations) if (declaration.site) addSiteNames(names, memos, declaration.site, awaited, /* @__PURE__ */ new Set());
7220
+ let after = -1;
7221
+ for (let before = index - 1; before >= 0; before--) {
7222
+ const other = statements[before];
7223
+ if (loads.has(other) || !runs(other) || other.type === "FunctionDeclaration" || !(overlaps(touched[before], names) || overlaps(declares[before], names))) continue;
7224
+ after = before;
7225
+ break;
7226
+ }
7227
+ result.set(statement, {
7228
+ after,
7229
+ memos
7230
+ });
7231
+ }
7232
+ return result;
7233
+ }
7234
+ const WRAPPERS = /* @__PURE__ */ new Set([
7235
+ "ParenthesizedExpression",
7236
+ "ChainExpression",
7237
+ "TSAsExpression",
7238
+ "TSSatisfiesExpression",
7239
+ "TSNonNullExpression",
7240
+ "TSTypeAssertion"
7241
+ ]);
7242
+ /**
7243
+ * Adds the positions of the names that code can change: the root of the
7244
+ * target of a write, of a callee and of an argument, such as `q` in `q = x`,
7245
+ * `params` in `params.set(…)`, and every name in an argument, such as
7246
+ * `list` in `fill({ list })`. `root` is true
7247
+ * when the node is in such a place.
7248
+ */
7249
+ function addChanging(into, node, root) {
7250
+ switch (node.type) {
7251
+ case "Identifier":
7252
+ if (root) into.add(node.start);
7253
+ return;
7254
+ case "MemberExpression":
7255
+ addChanging(into, node.object, root);
7256
+ if (node.computed) addChanging(into, node.property, false);
7257
+ return;
7258
+ case "AssignmentExpression":
7259
+ addChanging(into, node.left, true);
7260
+ addChanging(into, node.right, false);
7261
+ return;
7262
+ case "UpdateExpression":
7263
+ addChanging(into, node.argument, true);
7264
+ return;
7265
+ case "UnaryExpression":
7266
+ addChanging(into, node.argument, node.operator === "delete");
7267
+ return;
7268
+ case "CallExpression":
7269
+ case "NewExpression":
7270
+ addChanging(into, node.callee, true);
7271
+ for (const argument of node.arguments) addEvery(into, argument);
7272
+ return;
7273
+ case "TaggedTemplateExpression":
7274
+ addChanging(into, node.tag, true);
7275
+ for (const expression of node.quasi.expressions) addEvery(into, expression);
7276
+ return;
7277
+ }
7278
+ const keep = root && (WRAPPERS.has(node.type) || node.type.endsWith("Pattern") || node.type === "SpreadElement" || node.type === "Property" || node.type === "RestElement");
7279
+ for (const [key, child] of children(node)) {
7280
+ if (node.type === "Property" && key === "key" && !node.computed) continue;
7281
+ addChanging(into, child, keep);
7282
+ }
7283
+ }
7284
+ /** Adds the position of every name in an argument, which the callee can change through it. */
7285
+ function addEvery(into, node) {
7286
+ if (node.type === "Identifier") {
7287
+ into.add(node.start);
7288
+ return;
7289
+ }
7290
+ for (const [, child] of children(node)) addEvery(into, child);
7291
+ }
7292
+ /** The index of the statement that holds a position, or -1. */
7293
+ function findStatement(statements, position) {
7294
+ for (const [index, statement] of statements.entries()) if (position >= statement.start && position < statement.end) return index;
7295
+ return -1;
7296
+ }
7297
+ /** Adds a name that a statement mentions, and the names that a local function it mentions mentions. */
7298
+ function addMentions(into, declaration, awaited) {
7299
+ if (into.has(declaration)) return;
7300
+ into.add(declaration);
7301
+ const site = declaration.site;
7302
+ if (site && (declaration.kind === "function" || declaration.kind === "server-function")) {
7303
+ for (const reference of [...site.reads, ...site.writes]) if (!awaited.has(reference.declaration)) addMentions(into, reference.declaration, awaited);
7304
+ }
7305
+ }
7306
+ /** Adds the names that a site reads and writes, and those of the functions and memos it reads. */
7307
+ function addSiteNames(names, memos, site, awaited, seen) {
7308
+ if (seen.has(site)) return;
7309
+ seen.add(site);
7310
+ for (const reference of [...site.reads, ...site.writes]) {
7311
+ const declaration = reference.declaration;
7312
+ if (awaited.has(declaration)) {
7313
+ if (declaration.site !== site && !memos.includes(declaration)) memos.push(declaration);
7314
+ continue;
7315
+ }
7316
+ names.add(declaration);
7317
+ if (declaration.site && declaration.kind !== "import") addSiteNames(names, memos, declaration.site, awaited, seen);
7318
+ }
7319
+ }
7320
+ /** True when two sets share a value. */
7321
+ function overlaps(left, right) {
7322
+ for (const value of left) if (right.has(value)) return true;
7323
+ return false;
7324
+ }
7325
+ const FUNCTIONS = /* @__PURE__ */ new Set([
7326
+ "FunctionDeclaration",
7327
+ "FunctionExpression",
7328
+ "ArrowFunctionExpression"
7329
+ ]);
7330
+ /** True when code waits where it runs: an `await` or a `for await` outside the functions it declares. */
7331
+ function hasAwait(node) {
7332
+ if (node.type === "AwaitExpression" || node.type === "ForOfStatement" && node.await) return true;
7333
+ if (FUNCTIONS.has(node.type)) return false;
7334
+ for (const [, child] of children(node)) if (hasAwait(child)) return true;
7335
+ return false;
7336
+ }
7337
+ //#endregion
7055
7338
  //#region src/codegen/scopes.ts
7056
7339
  /** Returns the nearest scope, from `scope` outwards, that gets an ID at render time. */
7057
7340
  function instanceScope(plan, scope) {
@@ -7101,6 +7384,13 @@ function isMemo(declaration) {
7101
7384
  return declaration.kind === "memo" || declaration.kind === "async-memo";
7102
7385
  }
7103
7386
  /**
7387
+ * True for the header of `#loading (memo)`, which reads whether its memos are pending, not their
7388
+ * values, so the render does not wait for them.
7389
+ */
7390
+ function isLoadingHeader(site) {
7391
+ return site.kind === "block" && site.block?.kind === "loading";
7392
+ }
7393
+ /**
7104
7394
  * The scope whose render waits for a read. A read with `await` inside a
7105
7395
  * `#loading` body makes the render around the block wait, so it counts as
7106
7396
  * a read in the scope that holds the block. Inside a `#defer` body, the
@@ -7128,7 +7418,7 @@ function blockingMemos(plan) {
7128
7418
  continue;
7129
7419
  }
7130
7420
  for (const read of declaration.reads) {
7131
- if (read.range.start === read.range.end) continue;
7421
+ if (read.range.start === read.range.end || isLoadingHeader(read.site)) continue;
7132
7422
  const site = read.site;
7133
7423
  if (DEFERRED_SITES$1.has(site.kind) || site.kind === "memo") continue;
7134
7424
  let template = false;
@@ -7175,7 +7465,7 @@ function awaitedMemos(plan, body, blocking) {
7175
7465
  for (const site of plan.graph.model.sites) {
7176
7466
  if (DEFERRED_SITES$1.has(site.kind)) continue;
7177
7467
  for (const read of site.reads) {
7178
- if (read.range.start === read.range.end || loadingBody(readScope(read)) !== body) continue;
7468
+ if (read.range.start === read.range.end || isLoadingHeader(site) || loadingBody(readScope(read)) !== body) continue;
7179
7469
  if (isMemo(read.declaration) && !blocking.has(read.declaration)) result.add(read.declaration);
7180
7470
  }
7181
7471
  }
@@ -7187,17 +7477,88 @@ function awaitedMemos(plan, body, blocking) {
7187
7477
  function findSite(plan, node) {
7188
7478
  for (const item of plan.graph.model.sites) if (item.node === node) return item;
7189
7479
  }
7480
+ /** Global functions whose result is never a promise. */
7481
+ const PLAIN_FUNCTIONS = /* @__PURE__ */ new Set([
7482
+ "Boolean",
7483
+ "Number",
7484
+ "String",
7485
+ "decodeURIComponent",
7486
+ "encodeURIComponent",
7487
+ "parseFloat",
7488
+ "parseInt"
7489
+ ]);
7490
+ /** Methods of strings, numbers and arrays whose result is never a promise. */
7491
+ const PLAIN_METHODS = /* @__PURE__ */ new Set([
7492
+ "concat",
7493
+ "endsWith",
7494
+ "filter",
7495
+ "includes",
7496
+ "indexOf",
7497
+ "join",
7498
+ "map",
7499
+ "padEnd",
7500
+ "padStart",
7501
+ "repeat",
7502
+ "replace",
7503
+ "replaceAll",
7504
+ "slice",
7505
+ "split",
7506
+ "startsWith",
7507
+ "toFixed",
7508
+ "toLocaleString",
7509
+ "toLowerCase",
7510
+ "toString",
7511
+ "toUpperCase",
7512
+ "trim",
7513
+ "trimEnd",
7514
+ "trimStart"
7515
+ ]);
7516
+ /**
7517
+ * True if a value of markup can be a promise, which the browser writes once it settles: a call,
7518
+ * such as `{load(id)}` or `title=getTitle()`, or a read of a prop typed as a promise. A call of a
7519
+ * macro of brumate, such as `$isPending`, of `String` or of a method of strings and arrays, such
7520
+ * as `name.toUpperCase()`, gives no promise, nor does a string, a number or a property. An
7521
+ * object can hold one, for a spread.
7522
+ */
7523
+ function mayBePromise(node, site) {
7524
+ switch (node.type) {
7525
+ case "ParenthesizedExpression":
7526
+ case "TSAsExpression":
7527
+ case "TSSatisfiesExpression":
7528
+ case "TSNonNullExpression": return mayBePromise(node.expression, site);
7529
+ case "ConditionalExpression": return mayBePromise(node.consequent, site) || mayBePromise(node.alternate, site);
7530
+ case "LogicalExpression": return mayBePromise(node.left, site) || mayBePromise(node.right, site);
7531
+ case "SequenceExpression": return mayBePromise(node.expressions.at(-1), site);
7532
+ case "NewExpression": return node.callee.type === "Identifier" && node.callee.name === "Promise";
7533
+ case "TaggedTemplateExpression":
7534
+ case "ImportExpression": return true;
7535
+ case "ObjectExpression":
7536
+ for (const property of node.properties) if (mayBePromise(property.type === "SpreadElement" ? property.argument : property.value, site)) return true;
7537
+ return false;
7538
+ case "CallExpression": {
7539
+ const callee = node.callee;
7540
+ if (callee.type === "Identifier") return !callee.name.startsWith("$") && !PLAIN_FUNCTIONS.has(callee.name);
7541
+ return !(callee.type === "MemberExpression" && callee.property.type === "Identifier" && PLAIN_METHODS.has(callee.property.name));
7542
+ }
7543
+ case "Identifier":
7544
+ for (const reference of site?.reads ?? []) if (reference.declaration.promise === true && reference.range.start === node.start) return true;
7545
+ return false;
7546
+ default: return false;
7547
+ }
7548
+ }
7190
7549
  /**
7191
7550
  * True if the markup of a `#loading` body may wait for something other than
7192
7551
  * the memos it reads, so the body cannot render in place when those memos
7193
- * are ready: a child component, a dynamic tag, a template, or an insert of
7194
- * a prop, which can be a promise or the children of a parent. Bodies that
7195
- * render later, such as those of a `#loading` or a `#defer` inside it, wait
7196
- * on their own.
7552
+ * are ready: a child component, a dynamic tag, a template, an insert of
7553
+ * a prop, which can be a promise or the children of a parent, or an insert or
7554
+ * attribute whose value can be a promise, such as a call. Bodies that render
7555
+ * later, such as those of a `#loading` or a `#defer` inside it, wait on their
7556
+ * own.
7197
7557
  */
7198
7558
  function mayWait(plan, nodes) {
7199
7559
  function insertWaits(node) {
7200
7560
  const site = findSite(plan, node.expression.ast);
7561
+ if (mayBePromise(node.expression.ast, site)) return true;
7201
7562
  if (!site) return false;
7202
7563
  for (const read of site.reads) {
7203
7564
  const kind = read.declaration.kind;
@@ -7205,6 +7566,13 @@ function mayWait(plan, nodes) {
7205
7566
  }
7206
7567
  return false;
7207
7568
  }
7569
+ function attributesWait(node) {
7570
+ for (const attribute of node.attributes) {
7571
+ const value = attribute.kind === "value" || attribute.kind === "spread" || attribute.kind === "computed" ? attribute.value : true;
7572
+ if (value !== true && mayBePromise(value.ast, findSite(plan, value.ast))) return true;
7573
+ }
7574
+ return false;
7575
+ }
7208
7576
  for (const node of nodes) switch (node.kind) {
7209
7577
  case "component":
7210
7578
  case "dynamic": return true;
@@ -7212,6 +7580,8 @@ function mayWait(plan, nodes) {
7212
7580
  if (insertWaits(node)) return true;
7213
7581
  break;
7214
7582
  case "element":
7583
+ if (attributesWait(node) || mayWait(plan, node.children)) return true;
7584
+ break;
7215
7585
  case "fragment":
7216
7586
  if (mayWait(plan, node.children)) return true;
7217
7587
  break;
@@ -7375,10 +7745,38 @@ const NEVER_PROMISE = /* @__PURE__ */ new Set([
7375
7745
  * a function. A memo with `await` inside is an async function, so its value is a promise whatever
7376
7746
  * its expression gives, as in ``$memo(`Hi ${(await load()).name}`)`` or `$memo([await load()])`.
7377
7747
  */
7748
+ /** The sites of markup, whose `await` of a memo the browser waits for at the start of the markup. */
7749
+ const MARKUP_SITES = /* @__PURE__ */ new Set([
7750
+ "insert",
7751
+ "attribute",
7752
+ "tag",
7753
+ "spread",
7754
+ "style",
7755
+ "block",
7756
+ "prop"
7757
+ ]);
7378
7758
  function isNeverPromise(declaration) {
7379
7759
  const node = declaration.site?.node;
7380
7760
  return declaration.kind === "memo" && node !== void 0 && (isPrimitive(node) || NEVER_PROMISE.has(node.type));
7381
7761
  }
7762
+ /**
7763
+ * True for a memo that can hold a promise in the browser: an `await` in it makes one, and others
7764
+ * give one unless they always give a primitive, an array or a function.
7765
+ */
7766
+ function mayLoad(declaration) {
7767
+ return (declaration.kind === "memo" || declaration.kind === "async-memo") && !isNeverPromise(declaration);
7768
+ }
7769
+ /**
7770
+ * True if markup can render a `#loading` block: one of its own, or one in a component, or in
7771
+ * children or a template that an insert renders.
7772
+ */
7773
+ function mayReveal(nodes) {
7774
+ let found = false;
7775
+ forEachNode(nodes, (node) => {
7776
+ found ||= node.kind === "loading" || node.kind === "component" || node.kind === "dynamic" || node.kind === "insert";
7777
+ });
7778
+ return found;
7779
+ }
7382
7780
  /** The static or value attribute named `style`. */
7383
7781
  function findStyleAttribute(attributes) {
7384
7782
  for (const attribute of attributes) if ((attribute.kind === "static" || attribute.kind === "value") && attribute.name === "style") return attribute;
@@ -7517,6 +7915,23 @@ var Emitter = class {
7517
7915
  /** The kinds of the `{` that are open: of a function, a branch or loop, or a plain block. */
7518
7916
  braces = [];
7519
7917
  fnCount = 0;
7918
+ /** The number of `$$b.wait` calls that the render opened, which its end closes. */
7919
+ waits = 0;
7920
+ /** Declarations that the rest of a render after `await` can assign: `let` before the split. */
7921
+ reassignable = /* @__PURE__ */ new Set();
7922
+ /**
7923
+ * The scope whose script the function that is being written splits at `await $memo`: the
7924
+ * component in the render module, or the body of a render function of a block.
7925
+ */
7926
+ splitScope;
7927
+ /** The awaited memos that a split waits for, so markup after it reads their values. */
7928
+ splitMemos = /* @__PURE__ */ new Set();
7929
+ /** In the browser, the awaited memos whose loads start before their `await`, in `$$w_<name>`. */
7930
+ startedMemos = /* @__PURE__ */ new Set();
7931
+ /** The memos that hold a primitive on the server, for the start points of loads in the browser. */
7932
+ serverInline;
7933
+ /** In the browser, the awaited memos of other loads that the load of a statement reads. */
7934
+ loadMemos = /* @__PURE__ */ new Map();
7520
7935
  /**
7521
7936
  * The calls that fill the nested blocks of a clone, by the scope and the anchor of each block.
7522
7937
  * `$$m` in a call is the start comment of the block.
@@ -7559,6 +7974,7 @@ var Emitter = class {
7559
7974
  this.ctxArgument = options.mode === "server" ? "$$ctx" : "undefined";
7560
7975
  this.inParagraph = options.mode === "server" && !plan.hideNames ? paragraphComponents(file) : /* @__PURE__ */ new Set();
7561
7976
  this.blocking = blockingMemos(plan);
7977
+ this.splitScope = options.waits ? plan.graph.model.component : void 0;
7562
7978
  this.inline = options.mode === "server" ? plainValues(plan, this.blocking) : /* @__PURE__ */ new Set();
7563
7979
  for (const site of plan.graph.model.sites) this.sitesByNode.set(site.node, site);
7564
7980
  for (const node of plan.graph.nodes) if (node.kind !== "source" && plan.graph.live.has(node)) this.liveSites.add(node.site);
@@ -7637,6 +8053,34 @@ var Emitter = class {
7637
8053
  else this.braces.push({ kind: "control" });
7638
8054
  }
7639
8055
  }
8056
+ /** Opens the rest of a render after `await`, which stays in the function that holds it. */
8057
+ openRest(code) {
8058
+ this.flush();
8059
+ const fn = this.currentFn;
8060
+ this.push(`${" ".repeat(this.depth)}${code}`);
8061
+ this.depth++;
8062
+ this.braces.push({
8063
+ kind: "fn",
8064
+ fn
8065
+ });
8066
+ this.waits++;
8067
+ }
8068
+ /**
8069
+ * Writes the body of a render function whose script `await $memo` splits: `content` writes
8070
+ * the body of `scope`, and the rests that it opened close after `end`, the return line.
8071
+ */
8072
+ splitBody(scope, content, end) {
8073
+ const outer = this.splitScope;
8074
+ const waits = this.waits;
8075
+ const memos = [...this.splitMemos];
8076
+ this.splitScope = scope;
8077
+ content();
8078
+ this.splitScope = outer;
8079
+ end();
8080
+ this.splitMemos.clear();
8081
+ for (const memo of memos) this.splitMemos.add(memo);
8082
+ for (; this.waits > waits; this.waits--) this.close("});");
8083
+ }
7640
8084
  close(code = "}") {
7641
8085
  this.flush();
7642
8086
  this.depth--;
@@ -7701,11 +8145,21 @@ var Emitter = class {
7701
8145
  if (last && "static" in last) last.static += text;
7702
8146
  else this.parts.push({ static: text });
7703
8147
  }
7704
- code(code, settled) {
7705
- this.parts.push(settled ? {
8148
+ code(code, settled, promise) {
8149
+ const part = settled ? {
7706
8150
  code,
7707
8151
  settled
7708
- } : { code });
8152
+ } : { code };
8153
+ if (promise) part.promise = promise;
8154
+ this.parts.push(part);
8155
+ }
8156
+ /**
8157
+ * In the browser, the scope of a value of markup that can be a promise: one that calls code,
8158
+ * such as `{load(id)}`, or reads a prop typed as a promise. The clone writes its value once it
8159
+ * settles, and a `#loading` around it shows its fallback until then.
8160
+ */
8161
+ promiseScope(expression, scope) {
8162
+ return this.options.mode === "client" && mayBePromise(expression.ast, this.sitesByNode.get(expression.ast)) ? this.scopeVar(instanceScope(this.plan, scope)) : void 0;
7709
8163
  }
7710
8164
  /**
7711
8165
  * In the browser, the memos that values of the markup read that never change and can be a
@@ -7720,7 +8174,7 @@ var Emitter = class {
7720
8174
  if (!site || this.liveSites.has(site)) return;
7721
8175
  for (const reference of site.reads) {
7722
8176
  const declaration = reference.declaration;
7723
- if (isMemo(declaration) && !isNeverPromise(declaration) && !names.includes(declaration.name)) names.push(declaration.name);
8177
+ if (isMemo(declaration) && !isNeverPromise(declaration) && !this.splitMemos.has(declaration) && !names.includes(declaration.name)) names.push(declaration.name);
7724
8178
  }
7725
8179
  }
7726
8180
  return names.length > 0 ? {
@@ -7812,6 +8266,11 @@ var Emitter = class {
7812
8266
  const names = this.options.mode === "server" ? `, ${JSON.stringify(slotNames)}` : "";
7813
8267
  this.line(`${this.helper("slots")}(${this.scopeVar(scope)}, [${values.join(", ")}]${names});`);
7814
8268
  }
8269
+ if (this.options.mode === "client") {
8270
+ const loads = [];
8271
+ for (const declaration of scope.declarations.values()) if (this.blocking.has(declaration) && mayLoad(declaration)) loads.push(declaration.name);
8272
+ if (loads.length > 0) this.line(`$$b.countLoads(${this.scopeVar(instanceScope(this.plan, scope))}, [${loads.join(", ")}]);`);
8273
+ }
7815
8274
  if (scope.kind === "component") {
7816
8275
  const bindable = this.bindableProps(scope);
7817
8276
  if (bindable.length > 0) this.line(`${this.helper("bindings")}(${this.scopeVar(scope)}, $$props, { ${bindable.join(", ")} });`);
@@ -7836,8 +8295,9 @@ var Emitter = class {
7836
8295
  * markup makes the page wait for, without the keyword, is awaited on its
7837
8296
  * own, as the code reads.
7838
8297
  */
7839
- blockingDeclarations(statement) {
7840
- if (this.options.mode !== "server" || statement.type !== "VariableDeclaration") return;
8298
+ blockingDeclarations(statement, server = this.options.mode === "server") {
8299
+ if (!server || statement.type !== "VariableDeclaration") return;
8300
+ const inline = this.options.mode === "server" ? this.inline : this.serverInline ??= plainValues(this.plan, this.blocking);
7841
8301
  const declarations = [];
7842
8302
  let awaited = true;
7843
8303
  for (const declarator of statement.declarations) {
@@ -7850,7 +8310,7 @@ var Emitter = class {
7850
8310
  continue;
7851
8311
  }
7852
8312
  awaited &&= declaration.awaited === true;
7853
- if (!this.inline.has(declaration)) declarations.push(declaration);
8313
+ if (!inline.has(declaration)) declarations.push(declaration);
7854
8314
  }
7855
8315
  return declarations.length === 0 ? void 0 : {
7856
8316
  declarations,
@@ -7878,6 +8338,117 @@ var Emitter = class {
7878
8338
  this.line(`if (($$t = $$b.waitAll([${names.join(", ")}])) !== undefined) await $$t;`);
7879
8339
  for (const declaration of run) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
7880
8340
  }
8341
+ /**
8342
+ * True for a statement that runs nothing where it is written on the server,
8343
+ * such as `$effect`, an import or a type. It does not end a run of awaits.
8344
+ */
8345
+ isQuiet(statement) {
8346
+ if (statement.type === "ImportDeclaration" || TYPE_DECLARATIONS.has(statement.type)) return true;
8347
+ if (statement.type !== "ExpressionStatement") return false;
8348
+ const expression = statement.expression;
8349
+ return expression.type === "CallExpression" && expression.callee.type === "Identifier" && (expression.callee.name === "$effect" || expression.callee.name === "$client");
8350
+ }
8351
+ /**
8352
+ * The awaited memos whose loads start before statements that do not hold
8353
+ * them, by the index of the statement that they start after (-1 for the
8354
+ * top). Each `await` still waits where it is written. The browser, where
8355
+ * the script splits at each `await`, places them as the server does. A
8356
+ * load there reads the values of the memos whose loads it waits for as
8357
+ * parameters, so one that reads such a memo through a function or another
8358
+ * memo starts after that memo's `await`.
8359
+ */
8360
+ earlyLoads(statements, scope, splits) {
8361
+ const moved = /* @__PURE__ */ new Map();
8362
+ const server = this.options.mode === "server";
8363
+ if (!server && !splits) return moved;
8364
+ const loads = /* @__PURE__ */ new Map();
8365
+ const declaredAt = /* @__PURE__ */ new Map();
8366
+ for (const [index, statement] of statements.entries()) {
8367
+ const blocking = this.blockingDeclarations(statement, true);
8368
+ if (blocking?.awaited && statement.type === "VariableDeclaration" && blocking.declarations.length === statement.declarations.length && (server || this.awaitedMemos(statement, scope)?.every(Boolean))) {
8369
+ loads.set(statement, blocking.declarations);
8370
+ for (const declaration of blocking.declarations) declaredAt.set(declaration, index);
8371
+ }
8372
+ }
8373
+ if (loads.size === 0) return moved;
8374
+ const starts = findLoadStarts(statements, scope, loads, (statement) => !this.isQuiet(statement));
8375
+ const runs = /* @__PURE__ */ new Map();
8376
+ if (!server) {
8377
+ let members = [];
8378
+ const endRun = () => {
8379
+ if (members.length > 1) for (const member of members) runs.set(member, members[0]);
8380
+ members = [];
8381
+ };
8382
+ for (const [index, statement] of statements.entries()) if (this.blockingDeclarations(statement, true)?.awaited) members.push(index);
8383
+ else if (!this.isQuiet(statement)) endRun();
8384
+ endRun();
8385
+ }
8386
+ const placed = /* @__PURE__ */ new Map();
8387
+ for (const [index, statement] of statements.entries()) {
8388
+ const start = starts.get(statement);
8389
+ if (!start) continue;
8390
+ let after = start.after;
8391
+ for (const memo of start.memos) after = Math.max(after, placed.get(memo) ?? index - 1);
8392
+ if (!server) {
8393
+ const reads = /* @__PURE__ */ new Set();
8394
+ for (const declaration of loads.get(statement)) for (const reference of declaration.site?.reads ?? []) reads.add(reference.declaration);
8395
+ for (const memo of start.memos) {
8396
+ const at = declaredAt.get(memo) ?? -1;
8397
+ if (at > after && !reads.has(memo)) after = at;
8398
+ }
8399
+ this.loadMemos.set(statement, start.memos);
8400
+ }
8401
+ let ends = false;
8402
+ let inRun = false;
8403
+ for (let between = after + 1; between < index && !ends; between++) {
8404
+ const other = statements[between];
8405
+ const blocking = this.blockingDeclarations(other, true);
8406
+ if (blocking?.awaited) inRun = true;
8407
+ else if (!this.isQuiet(other)) ends = inRun || blocking !== void 0 || hasAwait(other);
8408
+ }
8409
+ const first = runs.get(index);
8410
+ if (!ends && first !== void 0) {
8411
+ after = Math.max(after, first - 1);
8412
+ ends = true;
8413
+ }
8414
+ const at = ends ? after : index;
8415
+ for (const declaration of loads.get(statement)) placed.set(declaration, at);
8416
+ if (ends) {
8417
+ const list = moved.get(after) ?? [];
8418
+ list.push(statement);
8419
+ moved.set(after, list);
8420
+ }
8421
+ }
8422
+ return moved;
8423
+ }
8424
+ /**
8425
+ * Declares the memos of a load that starts early, and starts them. In the browser, the load
8426
+ * goes in `$$w_<name>`, which its `await` waits for, and it waits for the loads of the memos
8427
+ * that it reads which have not reached their `await`.
8428
+ */
8429
+ startLoads(statements) {
8430
+ for (const statement of statements ?? []) {
8431
+ if (this.options.mode === "client") {
8432
+ const declarations = statement.type === "VariableDeclaration" ? statement.declarations : [];
8433
+ for (const declarator of declarations) {
8434
+ const declaration = this.awaitedMemos(statement, this.splitScope)[declarations.indexOf(declarator)];
8435
+ const load = this.source(declarator.init);
8436
+ const waits = [];
8437
+ const names = [];
8438
+ for (const memo of this.loadMemos.get(statement) ?? []) if (this.startedMemos.has(memo) && !this.splitMemos.has(memo)) {
8439
+ waits.push(`$$w_${memo.name}`);
8440
+ names.push(memo.name);
8441
+ }
8442
+ const value = waits.length > 0 ? `$$b.after([${waits.join(", ")}], (${names.join(", ")}) => ${load})` : `$$b.started(() => ${load})`;
8443
+ this.line(`const $$w_${declaration.name} = ${value};`);
8444
+ this.startedMemos.add(declaration);
8445
+ }
8446
+ continue;
8447
+ }
8448
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
8449
+ for (const declaration of this.blockingDeclarations(statement).declarations) this.line(`$$b.start(${promiseName(declaration.name)});`);
8450
+ }
8451
+ }
7881
8452
  emitStatements(statements, scope) {
7882
8453
  let run = [];
7883
8454
  const endRun = () => {
@@ -7886,13 +8457,30 @@ var Emitter = class {
7886
8457
  run = [];
7887
8458
  }
7888
8459
  };
7889
- for (const statement of statements) {
8460
+ const splits = this.options.mode === "client" && scope === this.splitScope;
8461
+ const early = this.earlyLoads(statements, scope, splits);
8462
+ const started = /* @__PURE__ */ new Set();
8463
+ for (const list of early.values()) for (const statement of list) started.add(statement);
8464
+ this.startLoads(early.get(-1));
8465
+ let lastAwait = -1;
8466
+ for (const [index, statement] of statements.entries()) if (splits && this.awaitedMemos(statement, scope)) lastAwait = index;
8467
+ if (splits) {
8468
+ for (const declaration of this.markupAwaits(scope)) if (declaration.scope === scope) lastAwait = statements.length;
8469
+ }
8470
+ for (const [index, statement] of statements.entries()) {
8471
+ if (index > 0) this.startLoads(early.get(index - 1));
8472
+ const awaited = splits ? this.awaitedMemos(statement, scope) : void 0;
8473
+ if (awaited) {
8474
+ this.splitAtAwait(statement, awaited, scope);
8475
+ continue;
8476
+ }
7890
8477
  const blocking = this.blockingDeclarations(statement);
7891
8478
  if (blocking?.awaited) {
7892
- this.raw(this.patch.slice(statement.start, statement.end), statement.start);
8479
+ if (!started.has(statement)) this.raw(this.patch.slice(statement.start, statement.end), statement.start);
7893
8480
  run.push(...blocking.declarations);
7894
8481
  continue;
7895
8482
  }
8483
+ if (this.options.mode === "server" && this.isQuiet(statement)) continue;
7896
8484
  endRun();
7897
8485
  if (blocking) {
7898
8486
  this.raw(this.patch.slice(statement.start, statement.end), statement.start);
@@ -7922,12 +8510,126 @@ var Emitter = class {
7922
8510
  if (this.isServerStatement(statement)) continue;
7923
8511
  if (!this.options.functions && this.isFunctionStatement(statement)) continue;
7924
8512
  }
7925
- this.raw(this.patch.slice(statement.start, statement.end), statement.start);
7926
- if (this.options.mode === "client" && statement.type === "VariableDeclaration") this.watchUnreadMemos(statement, scope);
8513
+ let code = this.patch.slice(statement.start, statement.end);
8514
+ if (index < lastAwait && statement.type === "VariableDeclaration") {
8515
+ if (statement.kind === "const") code = `let${this.patch.slice(statement.start + 5, statement.end)}`;
8516
+ for (const declaration of scope.declarations.values()) if (declaration.range.start >= statement.start && declaration.range.end <= statement.end) this.reassignable.add(declaration);
8517
+ }
8518
+ this.raw(code, statement.start);
8519
+ if (this.options.mode === "client" && statement.type === "VariableDeclaration") this.watchUnreadMemos(statement, scope, splits);
7927
8520
  }
7928
8521
  endRun();
7929
8522
  }
7930
8523
  /**
8524
+ * Emits a body that renders inline, in the function of the markup around it. In the browser,
8525
+ * a body that waits at `await` renders through a function of its own, which can split.
8526
+ */
8527
+ emitInlineBody(body) {
8528
+ const own = this.plan.bodyScopes.get(body);
8529
+ if (this.options.mode !== "client" || !this.options.hoist || !this.splitsScript(body, own, own)) {
8530
+ this.emitBody(body);
8531
+ return;
8532
+ }
8533
+ const fn = this.bodyFunction("", () => this.emitBody(body), own);
8534
+ this.code(`$$b.nodes($$b.branchNodes(undefined, undefined, 0, [${fn}]))`);
8535
+ }
8536
+ /** True when the script of a body splits its render function at `await $memo`. */
8537
+ splitsScript(body, scope, splitScope = this.splitScope) {
8538
+ if (this.options.mode !== "client" || scope !== splitScope) return false;
8539
+ for (const statement of body.script?.program.body ?? []) if (this.awaitedMemos(statement, scope)) return true;
8540
+ return this.markupAwaits(scope).length > 0;
8541
+ }
8542
+ /** The memos that the markup of a scope awaits, which no split before it waited for. */
8543
+ markupAwaits(scope) {
8544
+ const result = [];
8545
+ for (const site of this.plan.graph.model.sites) {
8546
+ if (site.scope !== scope || !MARKUP_SITES.has(site.kind)) continue;
8547
+ for (const read of site.reads) {
8548
+ const declaration = read.declaration;
8549
+ if (read.await && isMemo(declaration) && !this.splitMemos.has(declaration) && !result.includes(declaration)) result.push(declaration);
8550
+ }
8551
+ }
8552
+ return result;
8553
+ }
8554
+ /**
8555
+ * In the browser, markup that reads a memo with `await` waits for it at the start of the
8556
+ * markup, after the script, as the server waits for the memos that a `#loading` body reads at
8557
+ * its start. A memo of the scope is assigned its value. One of a scope around it is a constant
8558
+ * of the rest, with the value, since the scope that waits holds it after its slots.
8559
+ */
8560
+ awaitMarkup(scope, end) {
8561
+ if (this.options.mode !== "client" || scope !== this.splitScope) return;
8562
+ const slots = this.plan.scopes.get(scope)?.slots ?? [];
8563
+ for (const declaration of this.markupAwaits(scope)) {
8564
+ const own = declaration.scope === scope;
8565
+ let at = own ? slots.indexOf(declaration) : -1;
8566
+ if (at === -1) at = slots.length;
8567
+ const values = [];
8568
+ const names = [];
8569
+ for (const [slot, declared] of slots.entries()) {
8570
+ const before = declared.range.start < end;
8571
+ values[slot] = before ? declared.name : "";
8572
+ names[slot] = before && this.reassignable.has(declared) ? declared.name : "";
8573
+ }
8574
+ values[at] = declaration.name;
8575
+ names[at] = own ? declaration.name : "";
8576
+ while (values.at(-1) === "") values.pop();
8577
+ while (names.at(-1) === "") names.pop();
8578
+ this.openRest(`return $$b.wait(${this.scopeVar(scope)}, [${values.join(", ")}], ${at}, ($$v) => {`);
8579
+ if (names.length > 0) this.line(`[${names.join(", ")}] = $$v;`);
8580
+ if (!own) this.line(`const [${",".repeat(at)}${declaration.name}] = $$v;`);
8581
+ this.splitMemos.add(declaration);
8582
+ }
8583
+ }
8584
+ /** The awaited memos that the declarators of a statement declare, by declarator. */
8585
+ awaitedMemos(statement, scope) {
8586
+ if (statement.type !== "VariableDeclaration") return;
8587
+ const awaited = [];
8588
+ let any = false;
8589
+ for (const declarator of statement.declarations) {
8590
+ const declaration = declarator.init?.type === "AwaitExpression" && declarator.id.type === "Identifier" ? scope.declarations.get(declarator.id.name) : void 0;
8591
+ const found = declaration && isMemo(declaration) && declaration.awaited ? declaration : void 0;
8592
+ awaited.push(found);
8593
+ any ||= found !== void 0;
8594
+ }
8595
+ return any ? awaited : void 0;
8596
+ }
8597
+ /**
8598
+ * In the render module, a declaration of `await $memo(...)` ends the code that runs now: the
8599
+ * rest of the render goes in `$$b.wait`, which gets the slots that the code so far set, with
8600
+ * the load at the slot of the memo. The memo is a `let` before the call, so a function
8601
+ * declared before the `await` reads it, and the rest assigns it and the slots that can change
8602
+ * during the wait, such as props.
8603
+ */
8604
+ splitAtAwait(statement, awaited, scope) {
8605
+ const slots = this.plan.scopes.get(scope)?.slots ?? [];
8606
+ for (const [index, declarator] of statement.declarations.entries()) {
8607
+ const declaration = awaited[index];
8608
+ if (!declaration) {
8609
+ this.line(`${statement.kind} ${this.source(declarator)};`);
8610
+ continue;
8611
+ }
8612
+ let at = slots.indexOf(declaration);
8613
+ if (at === -1) at = slots.length;
8614
+ const values = [];
8615
+ const names = [];
8616
+ for (const [slot, declared] of slots.entries()) {
8617
+ const before = declared.range.start < declarator.start;
8618
+ values[slot] = before ? declared.name : "";
8619
+ names[slot] = before && this.reassignable.has(declared) ? declared.name : "";
8620
+ }
8621
+ values[at] = this.startedMemos.has(declaration) ? `$$w_${declaration.name}` : this.source(declarator.init);
8622
+ names[at] = declaration.name;
8623
+ while (values.at(-1) === "") values.pop();
8624
+ while (names.at(-1) === "") names.pop();
8625
+ this.line(`let ${declaration.name};`);
8626
+ this.openRest(`return $$b.wait(${this.scopeVar(scope)}, [${values.join(", ")}], ${at}, ($$v) => {`);
8627
+ this.line(`[${names.join(", ")}] = $$v;`);
8628
+ this.reassignable.add(declaration);
8629
+ this.splitMemos.add(declaration);
8630
+ }
8631
+ }
8632
+ /**
7931
8633
  * In the browser, a memo that nothing reads has no slot, so no load takes its promise. Its
7932
8634
  * rejection goes to the nearest `#try`, which is where a memo that throws sends its error. A
7933
8635
  * memo that always gives a primitive, such as `count * 2`, is never a promise, unless it has
@@ -7935,10 +8637,11 @@ var Emitter = class {
7935
8637
  * the read is the whole value of another memo, as in `$memo(await memo)`, which then holds the
7936
8638
  * same promise.
7937
8639
  */
7938
- watchUnreadMemos(statement, scope) {
8640
+ watchUnreadMemos(statement, scope, splits) {
8641
+ const awaited = splits ? this.markupAwaits(scope) : [];
7939
8642
  for (const declarator of statement.declarations) {
7940
8643
  const declaration = declarator.id.type === "Identifier" ? scope.declarations.get(declarator.id.name) : void 0;
7941
- if (declaration && (declaration.kind === "memo" || declaration.kind === "async-memo") && declaration.reads.every((read) => read.await && (read.site.kind !== "memo" || read.site.node.start !== read.await.start || read.site.node.end !== read.await.end)) && slotIndex(this.plan, declaration) === -1 && !isNeverPromise(declaration)) {
8644
+ if (declaration && !awaited.includes(declaration) && (declaration.kind === "memo" || declaration.kind === "async-memo") && declaration.reads.every((read) => read.await && (read.site.kind !== "memo" || read.site.node.start !== read.await.start || read.site.node.end !== read.await.end)) && slotIndex(this.plan, declaration) === -1 && !isNeverPromise(declaration)) {
7942
8645
  const target = this.scopeVar(instanceScope(this.plan, scope));
7943
8646
  this.line(`$$b.unreadMemo(${target}, ${declaration.name});`);
7944
8647
  }
@@ -8051,6 +8754,7 @@ var Emitter = class {
8051
8754
  else this.code(`${this.helper("style")}(${JSON.stringify(this.plan.id)}, $$css)`);
8052
8755
  }
8053
8756
  this.emitStatements(setup, component);
8757
+ this.awaitMarkup(component, this.file.instanceScript?.program.end ?? 0);
8054
8758
  this.emitBound(component);
8055
8759
  for (const template of this.file.templates) this.emitTemplate(template);
8056
8760
  this.emitClientAnchors(component);
@@ -8058,11 +8762,16 @@ var Emitter = class {
8058
8762
  this.emitSlots(component);
8059
8763
  this.flush();
8060
8764
  }
8061
- /** Emits a body: its scope, script, templates, markup and slots. */
8062
- emitBody(body, createScope = true) {
8765
+ /**
8766
+ * Emits a body: its scope, script, templates, markup and slots. `markup` writes what goes
8767
+ * before the markup, after the script.
8768
+ */
8769
+ emitBody(body, createScope = true, markup) {
8063
8770
  const scope = this.plan.bodyScopes.get(body);
8064
- if (this.plan.scopes.get(scope).needsId && createScope) this.createScope(scope);
8771
+ if ((this.plan.scopes.get(scope).needsId || this.splitsScript(body, scope)) && createScope) this.createScope(scope);
8065
8772
  if (body.script) this.emitStatements(body.script.program.body, scope);
8773
+ this.awaitMarkup(scope, body.script?.program.end ?? body.start);
8774
+ markup?.();
8066
8775
  for (const template of body.templates) this.emitTemplate(template);
8067
8776
  this.emitClientAnchors(scope);
8068
8777
  this.emitNodes(body.children, scope);
@@ -8100,17 +8809,21 @@ var Emitter = class {
8100
8809
  const anchored = this.plan.anchors.has(block) && !this.plan.elementItems.has(block);
8101
8810
  if (block.kind === "for") this.line(`const ${copy(this.file.source, block.item.start, block.item.end)} = ${item};`);
8102
8811
  if (block.index) this.line(`const ${block.index.name} = ${index};`);
8103
- if (this.plan.scopes.get(scope).needsId) this.createScope(scope);
8104
- if (anchored) {
8105
- this.html("<!--i");
8106
- this.code(this.scopeVar(scope));
8107
- this.html("-->");
8108
- }
8109
- this.emitBody(block.body, false);
8110
- if (this.plan.anchors.has(block)) {
8111
- const from = source ? `, ${source}` : "";
8112
- this.line(`${this.helper("item")}(${this.scopeVar(scope)}, ${item}${from});`);
8113
- }
8812
+ const splits = this.splitsScript(block.body, scope);
8813
+ if (this.plan.scopes.get(scope).needsId || splits) this.createScope(scope);
8814
+ const from = source ? `, ${source}` : "";
8815
+ const setItem = `${this.helper("item")}(${this.scopeVar(scope)}, ${item}${from});`;
8816
+ if (splits && this.plan.anchors.has(block)) this.line(setItem);
8817
+ const open = () => {
8818
+ if (anchored) {
8819
+ this.html("<!--i");
8820
+ this.code(this.scopeVar(scope));
8821
+ this.html("-->");
8822
+ }
8823
+ };
8824
+ if (!splits) open();
8825
+ this.emitBody(block.body, false, splits ? open : void 0);
8826
+ if (this.plan.anchors.has(block) && !splits) this.line(setItem);
8114
8827
  if (anchored) this.html("<!--/i-->");
8115
8828
  }
8116
8829
  emitTemplate(template) {
@@ -8155,7 +8868,8 @@ var Emitter = class {
8155
8868
  const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${this.expression(node.expression)})` : this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
8156
8869
  const text = literalText(node.expression.ast);
8157
8870
  const settled = this.settledMemos([node.expression], scope);
8158
- const emitValue = () => text === void 0 ? this.code(value, settled) : this.html(text);
8871
+ const promise = this.promiseScope(node.expression, scope);
8872
+ const emitValue = () => text === void 0 ? this.code(value, settled, promise) : this.html(text);
8159
8873
  if (anchor && !this.plan.contents.has(node)) {
8160
8874
  this.html("<!--t");
8161
8875
  this.code(anchor.scope);
@@ -8181,6 +8895,11 @@ var Emitter = class {
8181
8895
  this.line("$$ctx.revealEnd();");
8182
8896
  return;
8183
8897
  }
8898
+ if (node.reveal && this.options.mode === "client" && mayReveal(node.children)) {
8899
+ const body = this.bodyFunction("", () => this.emitNodes(node.children, scope));
8900
+ this.code(`$$b.nodes($$b.reveal(${JSON.stringify(node.reveal.order)}, ${node.reveal.collapsed}, ${body}))`);
8901
+ return;
8902
+ }
8184
8903
  this.emitNodes(node.children, scope);
8185
8904
  return;
8186
8905
  case "listener": {
@@ -8370,16 +9089,17 @@ var Emitter = class {
8370
9089
  this.emitClasses(classes);
8371
9090
  break;
8372
9091
  }
8373
- this.code(`$$b.attribute(${JSON.stringify(attribute.name)}, ${this.expression(attribute.value)})`, this.settledMemos([attribute.value], scope));
9092
+ const call = `$$b.attribute(${JSON.stringify(attribute.name)}, ${this.expression(attribute.value)})`;
9093
+ this.code(isPrimitive(attribute.value.ast) ? call : this.ready(call), this.settledMemos([attribute.value], scope), this.promiseScope(attribute.value, scope));
8374
9094
  const bound = this.bindEntry(node, attribute, scope);
8375
9095
  if (bound) events.unshift(bound);
8376
9096
  break;
8377
9097
  }
8378
9098
  case "spread":
8379
- this.code(`$$b.spread(${this.expression(attribute.value)}${spreadArguments(spreadHandlers)})`);
9099
+ this.code(this.ready(`$$b.spread(${this.expression(attribute.value)}${spreadArguments(spreadHandlers)})`), void 0, this.promiseScope(attribute.value, scope));
8380
9100
  break;
8381
9101
  case "computed":
8382
- this.code(`$$b.attribute(${this.expression(attribute.name)}, ${attribute.value === true ? "true" : this.expression(attribute.value)})`);
9102
+ this.code(this.ready(`$$b.attribute(${this.expression(attribute.name)}, ${attribute.value === true ? "true" : this.expression(attribute.value)})`));
8383
9103
  break;
8384
9104
  case "event":
8385
9105
  events.push(this.eventEntry(attribute));
@@ -8390,7 +9110,9 @@ var Emitter = class {
8390
9110
  if (merged) {
8391
9111
  const forwards = anchor !== void 0 && this.spreadsRest(node.attributes);
8392
9112
  const attributes = `$$b.mergeAttributes([${merged.join(", ")}]${variables ? `, ${variables}` : ""})`;
8393
- this.code(`$$b.spread(${forwards ? `${this.helper("restRef")}(${attributes}, ${anchor.scope}, ${anchor.index})` : attributes}${spreadArguments(spreadHandlers)})`);
9113
+ let promise;
9114
+ for (const attribute of node.attributes) if (attribute.kind === "value" || attribute.kind === "spread") promise ??= this.promiseScope(attribute.value, scope);
9115
+ this.code(this.ready(`$$b.spread(${forwards ? `${this.helper("restRef")}(${attributes}, ${anchor.scope}, ${anchor.index})` : attributes}${spreadArguments(spreadHandlers)})`), void 0, promise);
8394
9116
  }
8395
9117
  if (anchor && !spreadHandlers) {
8396
9118
  this.html(" b-b=\"");
@@ -8753,7 +9475,7 @@ var Emitter = class {
8753
9475
  const inPlace = !mayWait(this.plan, block.body.children);
8754
9476
  if (inPlace && memos.length === 0) {
8755
9477
  this.line("$$ctx.enter();");
8756
- this.emitBody(block.body);
9478
+ this.emitLoadingBody(block, scope);
8757
9479
  this.line("$$ctx.leave();");
8758
9480
  return;
8759
9481
  }
@@ -8762,11 +9484,10 @@ var Emitter = class {
8762
9484
  this.line(`if ($$b.settled([${names.join(", ")}]) && $$ctx.mayShow()) {`);
8763
9485
  this.line(`$$ctx.enter(${boundary});`);
8764
9486
  for (const declaration of memos) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
8765
- this.emitBody(block.body);
9487
+ this.emitLoadingBody(block, scope);
8766
9488
  this.line("$$ctx.leave();");
8767
9489
  this.close("} else {");
8768
9490
  }
8769
- this.open(scope, block);
8770
9491
  this.html("<!--l");
8771
9492
  this.code(boundary);
8772
9493
  this.html("-->");
@@ -8778,17 +9499,43 @@ var Emitter = class {
8778
9499
  this.code(`$$ctx.fallbackEnd(${boundary})`);
8779
9500
  }
8780
9501
  this.html("<!--/l-->");
8781
- this.end(block);
8782
9502
  this.line(`$$ctx.defer(${boundary}, async ($$ctx) => {`);
8783
9503
  this.line(`let $$html = '';`);
8784
9504
  for (const declaration of memos) this.awaitHeld(declaration);
8785
- this.emitBody(block.body);
9505
+ this.emitLoadingBody(block, scope);
8786
9506
  this.flush();
8787
9507
  this.line("return $$html;");
8788
9508
  this.close("});");
8789
9509
  if (inPlace) this.close();
8790
9510
  }
8791
9511
  /**
9512
+ * In the browser, a `#loading` block renders as a streamed one shows: `$$b.loading` renders the
9513
+ * body in a boundary, and the fallback while a wait of the body has not ended. The body counts
9514
+ * the memos that it reads from outside, which the server waits for in the block. The block
9515
+ * joins the `#reveal` block whose body renders it.
9516
+ */
9517
+ emitClientLoading(block, scope) {
9518
+ const body = this.plan.bodyScopes.get(block.body);
9519
+ const reads = [];
9520
+ for (const declaration of awaitedMemos(this.plan, body, this.blocking)) if (mayLoad(declaration)) reads.push(declaration.name);
9521
+ const args = [this.bodyFunction("", () => {
9522
+ if (reads.length > 0) this.line(`$$b.countLoads(${this.scopeVar(instanceScope(this.plan, scope))}, [${reads.join(", ")}]);`);
9523
+ this.emitLoadingBody(block, scope);
9524
+ }, body)];
9525
+ const fallback = block.fallback;
9526
+ if (fallback) args.push(this.bodyFunction("", () => this.emitBody(fallback), this.plan.bodyScopes.get(fallback)));
9527
+ this.code(`$$b.nodes($$b.loading(${args.join(", ")}))`);
9528
+ }
9529
+ /**
9530
+ * The body of a `#loading` block. With a header, its markers carry the scope and the anchor of
9531
+ * the block, so the browser finds the body to hide while a memo of the header loads.
9532
+ */
9533
+ emitLoadingBody(block, scope) {
9534
+ this.open(scope, block, "1");
9535
+ this.emitBody(block.body);
9536
+ this.end(block);
9537
+ }
9538
+ /**
8792
9539
  * Registers the `#catch` body of a `#try` on the server, and returns the name of the function
8793
9540
  * that ends the registration. The body renders again here for an error that comes after the
8794
9541
  * page is sent, in a context of its own.
@@ -8870,15 +9617,16 @@ var Emitter = class {
8870
9617
  * Emits a function that renders a body, as a constant, and returns its name. The function
8871
9618
  * clones its markup when it can, and gives its HTML otherwise.
8872
9619
  */
8873
- bodyFunction(params, content) {
9620
+ bodyFunction(params, content, scope) {
8874
9621
  const name = this.unique("body");
8875
9622
  this.line(`const ${name} = (${params}) => {`);
8876
9623
  const fn = this.currentFn;
8877
9624
  this.line(`let $$html = '';`);
8878
- content();
8879
- this.flush();
8880
- const cloned = cloneLines(this, this.options.hoist, fn);
8881
- this.line(this.returnLine(fn, cloned));
9625
+ this.splitBody(scope, content, () => {
9626
+ this.flush();
9627
+ const cloned = this.options.hoist !== void 0 && cloneLines(this, this.options.hoist, fn);
9628
+ this.line(this.returnLine(fn, cloned));
9629
+ });
8882
9630
  this.close("};");
8883
9631
  return name;
8884
9632
  }
@@ -8894,9 +9642,9 @@ var Emitter = class {
8894
9642
  if (block.kind === "if" || block.kind === "switch") {
8895
9643
  const branches = block.kind === "if" ? block.branches : block.cases;
8896
9644
  const bodies = [];
8897
- for (const branch of branches) bodies.push(this.bodyFunction("", () => this.emitBody(branch.body)));
9645
+ for (const branch of branches) bodies.push(this.bodyFunction("", () => this.emitBody(branch.body), this.plan.bodyScopes.get(branch.body)));
8898
9646
  const fallback = block.fallback;
8899
- const other = fallback && this.bodyFunction("", () => this.emitBody(fallback));
9647
+ const other = fallback && this.bodyFunction("", () => this.emitBody(fallback), this.plan.bodyScopes.get(fallback));
8900
9648
  let index = other ? String(branches.length) : "-1";
8901
9649
  for (let at = branches.length - 1; at >= 0; at--) index = `${this.expression(branches[at].condition)} ? ${at} : ${index}`;
8902
9650
  const names = `[${[...bodies, ...other ? [other] : []].join(", ")}]`;
@@ -8908,9 +9656,9 @@ var Emitter = class {
8908
9656
  if (block.kind === "for" || block.kind === "repeat") {
8909
9657
  const item = this.unique("item");
8910
9658
  const index = this.unique("index");
8911
- const body = this.bodyFunction(`${item}, ${index}`, () => this.emitItem(block, item, index));
9659
+ const body = this.bodyFunction(`${item}, ${index}`, () => this.emitItem(block, item, index), this.plan.bodyScopes.get(block.body));
8912
9660
  const fallback = block.fallback;
8913
- const other = fallback && this.bodyFunction("", () => this.emitBody(fallback));
9661
+ const other = fallback && this.bodyFunction("", () => this.emitBody(fallback), this.plan.bodyScopes.get(fallback));
8914
9662
  const items = block.kind === "for" ? `$$b.toList(${this.expression(block.list)})` : `Array.from({ length: ${this.expression(block.count)} }, (_, index) => index)`;
8915
9663
  this.code(`$$b.nodes($$b.listNodes(${marks}, ${items}, ${body}, ${other ?? "undefined"}))`, this.settledMemos([block.kind === "for" ? block.list : block.count], scope));
8916
9664
  return true;
@@ -9027,7 +9775,10 @@ var Emitter = class {
9027
9775
  if (mark) this.line(`const ${mark} = $$ctx.mark();`);
9028
9776
  const end = server ? this.emitCatcher(block, scope) : void 0;
9029
9777
  this.line("try {");
9030
- this.emitBody(block.body);
9778
+ if (!server && this.options.hoist && this.plan.anchors.has(block) && tryCatchesClient(this.plan.graph.model, block)) {
9779
+ const fn = this.bodyFunction("", () => this.emitBody(block.body), this.plan.bodyScopes.get(block.body));
9780
+ this.code(`$$b.nodes($$b.attempt(${fn}))`);
9781
+ } else this.emitInlineBody(block.body);
9031
9782
  this.close(`} catch (${error}) {`);
9032
9783
  this.line(`$$html = ${before};`);
9033
9784
  if (mark) this.line(`$$ctx.restore(${mark});`);
@@ -9073,11 +9824,7 @@ var Emitter = class {
9073
9824
  this.emitLoading(block, scope);
9074
9825
  return;
9075
9826
  }
9076
- this.open(scope, block);
9077
- this.line("{");
9078
- this.emitBody(block.body);
9079
- this.close();
9080
- this.end(block);
9827
+ this.emitClientLoading(block, scope);
9081
9828
  return;
9082
9829
  case "portal":
9083
9830
  case "head":
@@ -9096,7 +9843,7 @@ var Emitter = class {
9096
9843
  default:
9097
9844
  this.open(scope, block);
9098
9845
  this.line("{");
9099
- this.emitBody(block.body);
9846
+ this.emitInlineBody(block.body);
9100
9847
  this.close();
9101
9848
  this.end(block);
9102
9849
  }
@@ -9325,32 +10072,37 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
9325
10072
  componentNames(node.children, names);
9326
10073
  break;
9327
10074
  case "if":
9328
- for (const branch of node.branches) componentNames(branch.body.children, names);
9329
- componentNames(node.fallback?.children ?? [], names);
10075
+ for (const branch of node.branches) bodyNames(branch.body, names);
10076
+ if (node.fallback) bodyNames(node.fallback, names);
9330
10077
  break;
9331
10078
  case "switch":
9332
- for (const branch of node.cases) componentNames(branch.body.children, names);
9333
- componentNames(node.fallback?.children ?? [], names);
10079
+ for (const branch of node.cases) bodyNames(branch.body, names);
10080
+ if (node.fallback) bodyNames(node.fallback, names);
9334
10081
  break;
9335
10082
  case "for":
9336
10083
  case "repeat":
9337
10084
  case "loading":
9338
10085
  case "client":
9339
10086
  case "defer":
9340
- componentNames(node.body.children, names);
9341
- componentNames(node.fallback?.children ?? [], names);
10087
+ bodyNames(node.body, names);
10088
+ if (node.fallback) bodyNames(node.fallback, names);
9342
10089
  break;
9343
10090
  case "try":
9344
- componentNames(node.body.children, names);
9345
- componentNames(node.fallback.children, names);
10091
+ bodyNames(node.body, names);
10092
+ bodyNames(node.fallback, names);
9346
10093
  break;
9347
10094
  case "key":
9348
10095
  case "portal":
9349
10096
  case "head":
9350
- case "offscreen": componentNames(node.body.children, names);
10097
+ case "offscreen": bodyNames(node.body, names);
9351
10098
  }
9352
10099
  return names;
9353
10100
  }
10101
+ /** Adds the components that a block body renders, in its markup and its templates. */
10102
+ function bodyNames(body, names) {
10103
+ componentNames(body.children, names);
10104
+ for (const template of body.templates) bodyNames(template.body, names);
10105
+ }
9354
10106
  /** Returns the source of an import, with `.brm` imports pointing to render modules. */
9355
10107
  function renderImport(file, statement, names) {
9356
10108
  const specifiers = [];
@@ -9406,7 +10158,7 @@ function generateRender(file, plan, getFill) {
9406
10158
  const patch = new Patch(file.source);
9407
10159
  addValueEdits(patch, file, model.sites, "client", void 0, void 0, model.component.id);
9408
10160
  const names = componentNames(file.children);
9409
- for (const template of file.templates) componentNames(template.body.children, names);
10161
+ for (const template of file.templates) bodyNames(template.body, names);
9410
10162
  for (const site of model.sites) if (!SKIPPED_SITES.has(site.kind)) for (const read of site.reads) names.add(read.declaration.name);
9411
10163
  let usesModule = false;
9412
10164
  for (const name of names) if (model.module.declarations.get(name)?.kind === "module") {
@@ -9499,7 +10251,8 @@ function generateRender(file, plan, getFill) {
9499
10251
  mode: "client",
9500
10252
  functions: true,
9501
10253
  fills: fill ? fills : void 0,
9502
- hoist
10254
+ hoist,
10255
+ waits: true
9503
10256
  });
9504
10257
  emitter.line(signature);
9505
10258
  emitter.line(`let $$html = '';`);
@@ -9508,6 +10261,7 @@ function generateRender(file, plan, getFill) {
9508
10261
  emitter.flush();
9509
10262
  const cloned = cloneLines(emitter, hoist);
9510
10263
  emitter.line(emitter.returnLine(0, cloned));
10264
+ for (let wait = 0; wait < emitter.waits; wait++) emitter.close("});");
9511
10265
  emitter.close();
9512
10266
  return {
9513
10267
  emitter,
@@ -9896,19 +10650,6 @@ const BROWSER_ONLY_SITES = /* @__PURE__ */ new Set([
9896
10650
  "effect",
9897
10651
  "client"
9898
10652
  ]);
9899
- /** Declarations that a handler reads or writes that can reach other components. */
9900
- const OUTER = /* @__PURE__ */ new Set([
9901
- "import",
9902
- "module",
9903
- "prop",
9904
- "props-rest",
9905
- "context",
9906
- "template",
9907
- "template-param",
9908
- "action",
9909
- "error",
9910
- "reset"
9911
- ]);
9912
10653
  const DEFERRED_SITES = /* @__PURE__ */ new Set([
9913
10654
  "function",
9914
10655
  "server-function",
@@ -9951,8 +10692,6 @@ var ClientGenerator = class {
9951
10692
  live = /* @__PURE__ */ new Map();
9952
10693
  /** The export that updates each live node. */
9953
10694
  updates = /* @__PURE__ */ new Map();
9954
- /** The handlers that can write a slot of another component. */
9955
- wide = [];
9956
10695
  /** Bodies that the client renders, by scope. */
9957
10696
  renders = /* @__PURE__ */ new Map();
9958
10697
  merge;
@@ -10046,7 +10785,6 @@ var ClientGenerator = class {
10046
10785
  `export const id = ${JSON.stringify(this.plan.id)};`,
10047
10786
  `export const props = ${this.propsMap()};`,
10048
10787
  `export const g = ${this.table()};`,
10049
- ...this.wide.length > 0 ? [`export const w = ${JSON.stringify(this.wide)};`] : [],
10050
10788
  ...refresh ? [`export const refresh = ${refresh};`] : [],
10051
10789
  ...tries ? [`export const t = ${tries};`] : []
10052
10790
  ];
@@ -10062,8 +10800,6 @@ var ClientGenerator = class {
10062
10800
  if (merged || names.length === 0) {
10063
10801
  const code = parts.all ?? "";
10064
10802
  delete parts.all;
10065
- const empty = {};
10066
- for (const name of names) empty[name] = [];
10067
10803
  return {
10068
10804
  code: [
10069
10805
  code,
@@ -10073,14 +10809,11 @@ var ClientGenerator = class {
10073
10809
  ].join("\n"),
10074
10810
  table: table.join("\n"),
10075
10811
  parts,
10076
- loaders: empty,
10077
10812
  clientCode,
10078
10813
  fillOf: (block) => this.createFill(block),
10079
10814
  diagnostics: this.diagnostics
10080
10815
  };
10081
10816
  }
10082
- const loaders = {};
10083
- for (const name of names) loaders[name] = [name];
10084
10817
  const reexports = [];
10085
10818
  for (const name of names) reexports.push(`export * from ${JSON.stringify(this.partPath(name))};`);
10086
10819
  return {
@@ -10092,7 +10825,6 @@ var ClientGenerator = class {
10092
10825
  ].join("\n"),
10093
10826
  table: table.join("\n"),
10094
10827
  parts,
10095
- loaders,
10096
10828
  clientCode,
10097
10829
  fillOf: (block) => this.createFill(block),
10098
10830
  diagnostics: this.diagnostics
@@ -10430,26 +11162,12 @@ var ClientGenerator = class {
10430
11162
  let code = this.withTemplates(site, this.rewriter.rewrite(site, "$$s", base));
10431
11163
  if (site.node.type === "FunctionExpression" && unmarked(code).trimStart().startsWith("(")) code = `function ${code}`;
10432
11164
  this.part = symbol;
10433
- if (site.kind !== "client" && !symbol.startsWith("t") && !this.writesOwn(site)) this.wide.push(symbol);
10434
11165
  if (symbol.startsWith("t")) this.emitTemplateArgs(site, symbol);
10435
11166
  if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.effect($$s, ${JSON.stringify(symbol)}, ${code}, 1);\n}`);
10436
11167
  else this.emit(this.handlerExport(site, symbol, code, base));
10437
11168
  }
10438
11169
  }
10439
11170
  /**
10440
- * True when a handler can write only the slots of its own component, so it waits for the
10441
- * update code of that component and not for the code of the components above it. The others
10442
- * are listed in `w`. A prop, a context, an import or a template can reach another component.
10443
- */
10444
- writesOwn(site, seen = /* @__PURE__ */ new Set()) {
10445
- if (seen.has(site)) return true;
10446
- seen.add(site);
10447
- for (let scope = site.scope; scope; scope = scope.parent) if (scope.kind === "template") return false;
10448
- for (const { declaration } of [...site.reads, ...site.writes]) if (OUTER.has(declaration.kind) && declaration.imported?.source !== "brumate/events") return false;
10449
- for (const callee of site.calls) if (!callee.site || !this.writesOwn(callee.site, seen)) return false;
10450
- return true;
10451
- }
10452
- /**
10453
11171
  * The export of a handler, which the core calls with the scope and the
10454
11172
  * arguments. A local function already takes them, so it is exported as it
10455
11173
  * is. An arrow function gets the scope as its first parameter.
@@ -10537,7 +11255,8 @@ var ClientGenerator = class {
10537
11255
  let fn = "text";
10538
11256
  if (this.plan.textContents.has(insert)) fn = "writeText";
10539
11257
  else if (this.plan.contents.has(insert)) fn = "content";
10540
- this.emit(`export function ${name("u")}($$s) {\n $$b.${fn}($$s, ${anchor}, ${expression()});\n}`);
11258
+ const write = fn !== "writeText" && mayBePromise(site.node, site) ? `$$b.fillValue($$s, ${anchor}, ${expression()}, ($$v) => $$b.${fn}($$s, ${anchor}, $$v))` : `$$b.${fn}($$s, ${anchor}, ${expression()})`;
11259
+ this.emit(`export function ${name("u")}($$s) {\n ${write};\n}`);
10541
11260
  }
10542
11261
  return;
10543
11262
  }
@@ -10604,7 +11323,8 @@ var ClientGenerator = class {
10604
11323
  const events = owner.kind === "dynamic" ? this.ownEvents(owner) : [];
10605
11324
  if (events.length > 0) parts.push(`{ "b-on": $$b.internal(${events.join(" + \" \" + ")}) }`);
10606
11325
  const value = parts.length > 1 ? `$$b.mergeAttributes([${parts.join(", ")}])` : parts[0] ?? "{}";
10607
- this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${value}, ${JSON.stringify(own)});\n}`);
11326
+ const helper = mayBePromise(site.node, site) ? "fillAttrs" : "attrs";
11327
+ this.emit(`export function ${name("u")}($$s) {\n $$b.${helper}($$s, ${anchor}, ${value}, ${JSON.stringify(own)});\n}`);
10608
11328
  } else if (attribute.kind === "value") {
10609
11329
  let value = (attribute.name === "class" ? classes(attribute.value.ast) : void 0) ?? expression();
10610
11330
  if (attribute.name === "class") {
@@ -10615,7 +11335,8 @@ var ClientGenerator = class {
10615
11335
  value = `[${classed.join(", ")}]`;
10616
11336
  }
10617
11337
  }
10618
- this.emit(`export function ${name("u")}($$s) {\n $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value});\n}`);
11338
+ const write = mayBePromise(attribute.value.ast, site) ? `$$b.fillValue($$s, ${JSON.stringify(`${anchor} ${attribute.name}`)}, ${value}, ($$v) => $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, $$v))` : `$$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value})`;
11339
+ this.emit(`export function ${name("u")}($$s) {\n ${write};\n}`);
10619
11340
  }
10620
11341
  }
10621
11342
  /** The `b-on` entries of the handlers of a dynamic tag, each as code that adds the scope ID. */
@@ -10778,6 +11499,23 @@ var ClientGenerator = class {
10778
11499
  case "offscreen":
10779
11500
  this.emit(`export function ${fn}($$s) {\n $$b.offscreen($$s, ${anchor}, ${header(0)}, ${this.renderName(block.body)}, ${this.plan.bodyScopes.get(block.body).id}${held});\n}`);
10780
11501
  return;
11502
+ case "loading": {
11503
+ const checks = [];
11504
+ const seen = /* @__PURE__ */ new Set();
11505
+ for (const read of headers[0]?.reads ?? []) {
11506
+ const slot = slotIndex(this.plan, read.declaration);
11507
+ if (slot !== -1 && !seen.has(read.declaration)) {
11508
+ seen.add(read.declaration);
11509
+ checks.push(`$$b.pending(${scopePath(this.plan, "$$s", base, read.declaration.scope)}, ${slot})`);
11510
+ }
11511
+ }
11512
+ if (checks.length === 0) return;
11513
+ const fallback = block.fallback;
11514
+ const render = fallback ? this.renderName(fallback) : "undefined";
11515
+ const kinds = this.hoist(`[${fallback ? this.kinds([fallback]).join(", ") : ""}]`);
11516
+ this.emit(`export function ${fn}($$s) {\n $$b.held($$s, ${anchor}, ${checks.join(" || ")}, ${this.plan.bodyScopes.get(block.body).id}, ${render}, ${kinds}${held});\n}`);
11517
+ return;
11518
+ }
10781
11519
  case "key": {
10782
11520
  const [inner] = block.body.children;
10783
11521
  const helper = inner?.kind === "dynamic" && inner.keyed ? "retag" : "rekey";
@@ -10821,6 +11559,14 @@ var ClientGenerator = class {
10821
11559
  collectRenders() {
10822
11560
  for (const node of this.plan.graph.nodes) {
10823
11561
  if (node.kind !== "block" || !this.plan.graph.live.has(node) || node.site.label === "for key") continue;
11562
+ if (node.block.kind === "loading") {
11563
+ const fallback = node.block.fallback;
11564
+ if (fallback) this.renders.set(this.plan.bodyScopes.get(fallback), {
11565
+ body: fallback,
11566
+ block: node.block
11567
+ });
11568
+ continue;
11569
+ }
10824
11570
  if (![
10825
11571
  "if",
10826
11572
  "switch",
@@ -10880,12 +11626,16 @@ var ClientGenerator = class {
10880
11626
  }
10881
11627
  for (const line of this.prologue(inside, base)) emitter.line(line);
10882
11628
  for (const template of this.declared(inside).slice(1)) emitter.emitTemplate(template.template);
10883
- if (isItem) emitter.emitItem(block, "$$item", "$$index");
10884
- else emitter.emitBody(body);
10885
- emitter.flush();
10886
- const cloned = block.kind === "if" || block.kind === "for" ? this.cloneRender(emitter) : false;
11629
+ let cloned = false;
11630
+ emitter.splitBody(scope, () => {
11631
+ if (isItem) emitter.emitItem(block, "$$item", "$$index");
11632
+ else emitter.emitBody(body);
11633
+ }, () => {
11634
+ emitter.flush();
11635
+ cloned = block.kind === "if" || block.kind === "for" || block.kind === "loading" ? this.cloneRender(emitter) : false;
11636
+ emitter.line(emitter.returnLine(0, cloned));
11637
+ });
10887
11638
  if (fill && !cloned) return;
10888
- emitter.line(emitter.returnLine(0, cloned));
10889
11639
  emitter.close();
10890
11640
  return emitter.lines.join("\n");
10891
11641
  }
@@ -11426,7 +12176,6 @@ function compile(source, options = {}) {
11426
12176
  server: server.code,
11427
12177
  client: entry.code,
11428
12178
  parts: partCodes,
11429
- loaders: client.loaders,
11430
12179
  table: client.table,
11431
12180
  clientCode: client.clientCode,
11432
12181
  render: render.code,
@@ -11643,4 +12392,4 @@ function inspect(source, options = {}) {
11643
12392
  //#endregion
11644
12393
  export { analyzeProject as A, getLocation as B, isReactiveModule as C, unmarked as D, originalPosition as E, summarize as F, isWithin as G, findError as H, parse$1 as I, walk as J, lookup as K, buildGraph as L, importSource as M, importedComponents as N, entryClasses as O, resolveRelative as P, forEachNode as R, sharedSites as S, builtin as T, analyze$1 as U, errorLink as V, getPatternNames as W, functionId as _, scopeLabel as a, SHARED_QUERY as b, DEFAULT_MERGE as c, generateServer as d, instanceScope as f, createPlan as g, clientState as h, report as i, analyzeProjectProps as j, refreshedNames as k, generateClient as l, blockBodies as m, formatReport as n, CompileError as o, slotIndex as p, resolveMacros as q, inspect as r, compile as s, anchorLabel as t, generateRender as u, getComponentName as v, resolveFromDisk as w, generateShared as x, hash as y, BrumateError as z };
11645
12394
 
11646
- //# sourceMappingURL=inspect-BLOdfj7o.js.map
12395
+ //# sourceMappingURL=inspect-BLPt-dZZ.js.map