brumate 0.1.0 → 0.2.0

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 (108) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-C0UCNL3J.js +1643 -0
  4. package/dist/client-C0UCNL3J.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/defer-D0bo1Gqx.js +52 -0
  12. package/dist/defer-D0bo1Gqx.js.map +1 -0
  13. package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
  14. package/dist/devtools-C50VH8gZ.js.map +1 -0
  15. package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
  16. package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
  17. package/dist/events-BKWRqtMg.js +52 -0
  18. package/dist/events-BKWRqtMg.js.map +1 -0
  19. package/dist/{files-BBLPU9JR.js → files-Bnn1JqHx.js} +18 -3
  20. package/dist/files-Bnn1JqHx.js.map +1 -0
  21. package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
  22. package/dist/html-bHZbkK-h.js.map +1 -0
  23. package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
  24. package/dist/index.d.ts +79 -29
  25. package/dist/index.js +12 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspect-CRZlO11T.js → inspect-BJtACnQp.js} +928 -91
  28. package/dist/inspect-BJtACnQp.js.map +1 -0
  29. package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
  30. package/dist/loader-B18i3_-T.js.map +1 -0
  31. package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
  32. package/dist/navigate-BwuZveDF.js.map +1 -0
  33. package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
  34. package/dist/produce-CWfJ4byV.js.map +1 -0
  35. package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
  36. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  37. package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
  38. package/dist/rpc-B-Zkn6Ch.js.map +1 -0
  39. package/dist/runtime/batch.d.ts +23 -0
  40. package/dist/runtime/batch.js +69 -0
  41. package/dist/runtime/batch.js.map +1 -0
  42. package/dist/runtime/client.d.ts +5 -5
  43. package/dist/runtime/client.js +5 -1345
  44. package/dist/runtime/context.d.ts +2 -2
  45. package/dist/runtime/context.js +1 -1
  46. package/dist/runtime/devtools.d.ts +5 -4
  47. package/dist/runtime/devtools.js +1 -1
  48. package/dist/runtime/env.d.ts +44 -0
  49. package/dist/runtime/env.js +61 -0
  50. package/dist/runtime/env.js.map +1 -0
  51. package/dist/runtime/events.d.ts +27 -0
  52. package/dist/runtime/events.js +1 -0
  53. package/dist/runtime/hot.d.ts +1 -1
  54. package/dist/runtime/html.d.ts +2 -2
  55. package/dist/runtime/html.js +1 -1
  56. package/dist/runtime/loader.d.ts +2 -2
  57. package/dist/runtime/loader.js +2 -2
  58. package/dist/runtime/routes.d.ts +2 -21
  59. package/dist/runtime/routes.js +31 -1
  60. package/dist/runtime/routes.js.map +1 -1
  61. package/dist/runtime/server.d.ts +6 -5
  62. package/dist/runtime/server.js +5 -6
  63. package/dist/runtime/signals.d.ts +22 -1
  64. package/dist/runtime/signals.js +29 -1
  65. package/dist/runtime/signals.js.map +1 -1
  66. package/dist/runtime/static-loader.d.ts +2 -2
  67. package/dist/runtime/static-loader.js +1 -1
  68. package/dist/runtime/testing.d.ts +46 -5
  69. package/dist/runtime/testing.js +240 -33
  70. package/dist/runtime/testing.js.map +1 -1
  71. package/dist/secrets-BxagsJxJ.js +23 -0
  72. package/dist/secrets-BxagsJxJ.js.map +1 -0
  73. package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
  74. package/dist/server-BqfM95r1.js +2762 -0
  75. package/dist/server-BqfM95r1.js.map +1 -0
  76. package/dist/skew-FRmAy9iy.js +49 -0
  77. package/dist/skew-FRmAy9iy.js.map +1 -0
  78. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  79. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
  80. package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
  81. package/dist/static-loader-DOygOFj5.js.map +1 -0
  82. package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
  83. package/dist/stream-JaMHMdBD.js.map +1 -0
  84. package/dist/vite.d.ts +42 -1
  85. package/dist/vite.js +435 -55
  86. package/dist/vite.js.map +1 -1
  87. package/package.json +15 -2
  88. package/types.d.ts +9 -1
  89. package/dist/client-routes-DakuM32C.js.map +0 -1
  90. package/dist/context-BG8KCF3v.js +0 -15
  91. package/dist/context-BG8KCF3v.js.map +0 -1
  92. package/dist/context-aeo9esY9.d.ts +0 -16
  93. package/dist/devtools-BKjnHrnv.js.map +0 -1
  94. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  95. package/dist/files-BBLPU9JR.js.map +0 -1
  96. package/dist/html-DEeoepg3.js.map +0 -1
  97. package/dist/inspect-CRZlO11T.js.map +0 -1
  98. package/dist/loader-Dc9OwY5I.js.map +0 -1
  99. package/dist/navigate-CzLjnoPH.js.map +0 -1
  100. package/dist/produce-BRGHP7e0.js.map +0 -1
  101. package/dist/rpc-9fSqL_YK.js.map +0 -1
  102. package/dist/runtime/client.js.map +0 -1
  103. package/dist/server-DZsgnPKS.js +0 -1615
  104. package/dist/server-DZsgnPKS.js.map +0 -1
  105. package/dist/shared-CWYOd0H3.js +0 -40
  106. package/dist/shared-CWYOd0H3.js.map +0 -1
  107. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  108. package/dist/stream-bgNCMcaA.js.map +0 -1
@@ -1,3 +1,5 @@
1
+ import { t as KEY_NAMES } from "./events-BKWRqtMg.js";
2
+ import { u as insertValue } from "./html-bHZbkK-h.js";
1
3
  import { parseSync } from "oxc-parser";
2
4
  import { parse } from "postcss";
3
5
  import selectorParser from "postcss-selector-parser";
@@ -10,6 +12,8 @@ const MACROS = /* @__PURE__ */ new Set([
10
12
  "$signal",
11
13
  "$memo",
12
14
  "$optimistic",
15
+ "$debounced",
16
+ "$throttled",
13
17
  "$effect",
14
18
  "$client",
15
19
  "$untrack",
@@ -17,6 +21,8 @@ const MACROS = /* @__PURE__ */ new Set([
17
21
  "$isPending",
18
22
  "$setContext",
19
23
  "$getContext",
24
+ "$route",
25
+ "$navigation",
20
26
  "$id",
21
27
  "$title",
22
28
  "$action"
@@ -242,15 +248,34 @@ const REACTIVE = /* @__PURE__ */ new Set([
242
248
  "item",
243
249
  "action"
244
250
  ]);
251
+ /** The module of the wrappers of event handlers, which the compiler reads. */
252
+ const EVENTS_MODULE = "brumate/events";
253
+ /** The wrappers that `brumate/events` exports. */
254
+ const WRAPPERS$1 = /* @__PURE__ */ new Set([
255
+ "prevent",
256
+ "stop",
257
+ "once",
258
+ "capture"
259
+ ]);
260
+ /** The events whose `prevent` can name keys. */
261
+ const KEY_EVENTS = /* @__PURE__ */ new Set([
262
+ "keydown",
263
+ "keyup",
264
+ "keypress"
265
+ ]);
245
266
  const COMPILE_TIME_FUNCTIONS = MACROS;
246
267
  const MISPLACED = {
247
268
  $setContext: "Call $setContext at the top level of a script",
248
269
  $title: "Call $title at the top level of a script",
249
270
  $id: "Create an ID with \"const name = $id()\" at the top level of a script",
250
271
  $getContext: "Read a context with \"const name = $getContext(Context)\" at the top level of a script",
272
+ $route: "Read the route with \"const name = $route()\" at the top level of a script",
273
+ $navigation: "Read the navigation with \"const name = $navigation()\" at the top level of a script",
251
274
  $props: "Call $props() as the value of a const in the component script",
252
275
  $signal: "Declare a signal with \"let name = $signal(value)\" at the top level of a script",
253
276
  $memo: "Declare a memo with \"const name = $memo(value)\" at the top level of a script",
277
+ $debounced: "Declare a debounced value with \"const name = $debounced(value, ms)\" at the top level of a script",
278
+ $throttled: "Declare a throttled value with \"const name = $throttled(value, ms)\" at the top level of a script",
254
279
  $optimistic: "Declare an optimistic value with \"let name = $optimistic(source)\" at the top level of a script",
255
280
  $action: "Declare the result of a form with \"const name = $action(serverFunction)\" at the top level of a script",
256
281
  $effect: "Call $effect at the top level of a script",
@@ -310,7 +335,7 @@ function hasUseServer(fn) {
310
335
  return false;
311
336
  }
312
337
  /** Returns the name of a compile-time function that `node` calls, if any. */
313
- function calleeName(node) {
338
+ function calleeName$1(node) {
314
339
  if (node?.type === "CallExpression" && node.callee.type === "Identifier") return node.callee.name;
315
340
  }
316
341
  function range(node) {
@@ -438,6 +463,44 @@ var Analyzer = class {
438
463
  site.range = range(expression);
439
464
  return site;
440
465
  }
466
+ /**
467
+ * Reads the wrappers of `brumate/events` around a handler, such as
468
+ * `prevent(move, 'Enter')`, into the modifiers that `b-on` holds, so the
469
+ * loader applies them before the handler's code loads. A modifier in the
470
+ * attribute name, such as `onSubmit:prevent`, still works, with a warning.
471
+ */
472
+ readWrappers(site, attribute, scope) {
473
+ if (attribute.modifiers.length > 0) {
474
+ const [first] = attribute.modifiers;
475
+ this.report("warning", `${attribute.name}:${first} is replaced by ${attribute.name}=(${first === "passive" ? "handler" : `${first}(handler)`}) from brumate/events${first === "passive" ? ", since listeners are passive unless a handler prevents" : ""}`, attribute);
476
+ }
477
+ const modifiers = [];
478
+ let node = attribute.handler.ast;
479
+ for (;;) {
480
+ while (node.type === "ParenthesizedExpression") node = node.expression;
481
+ if (node.type !== "CallExpression" || node.callee.type !== "Identifier") break;
482
+ const imported = lookup(scope, node.callee.name)?.imported;
483
+ const name = imported?.source === EVENTS_MODULE ? imported.name : void 0;
484
+ if (name === void 0 || !WRAPPERS$1.has(name)) break;
485
+ const [handler, ...rest] = node.arguments;
486
+ if (!handler || name !== "prevent" && rest.length > 0) {
487
+ this.report("error", `${name} takes a handler`, node);
488
+ break;
489
+ }
490
+ if (rest.length > 0) {
491
+ const keys = rest.map((key) => key.type === "Literal" && typeof key.value === "string" ? key.value : void 0);
492
+ const wrong = rest.find((_, index) => {
493
+ const key = keys[index];
494
+ return key === void 0 || !(KEY_NAMES.includes(key) || /^[A-Za-z0-9]$/.test(key));
495
+ });
496
+ if (!KEY_EVENTS.has(attribute.event)) this.report("error", "Only prevent of a keyboard event takes keys, such as onKeyDown", node);
497
+ else if (wrong) this.report("error", "Name each key of prevent as a string of its event.key, such as 'ArrowDown', 'Space' or 'a'", wrong);
498
+ modifiers.push(`prevent(${keys.join(",")})`);
499
+ } else modifiers.push(name);
500
+ node = handler;
501
+ }
502
+ if (modifiers.length > 0) site.modifiers = modifiers;
503
+ }
441
504
  declareFunction(name, fn, scope, at) {
442
505
  const server = hasUseServer(fn);
443
506
  const kind = server ? "server-function" : "function";
@@ -516,11 +579,14 @@ var Analyzer = class {
516
579
  this.createSite("setup", scope, statement, "setup");
517
580
  break;
518
581
  case "ExpressionStatement": {
519
- const name = calleeName(statement.expression);
582
+ const name = calleeName$1(statement.expression);
520
583
  if (name === "$title") {
521
584
  const call = statement.expression;
522
585
  if (call.arguments.length !== 1) this.report("error", "$title takes one argument, the title", call);
523
- else this.createSite("title", scope, call.arguments[0], "title");
586
+ else {
587
+ this.report("warning", "$title is replaced by <title> in #head, such as #head { <title>{`${count} left`}</title> }, and goes in a later version", call);
588
+ this.createSite("title", scope, call.arguments[0], "title");
589
+ }
524
590
  } else if (name === "$setContext") this.declareProvide(statement.expression, scope);
525
591
  else if (name === "$effect" || name === "$client") this.declareEffect(statement.expression, name, scope);
526
592
  else this.createSite("setup", scope, statement, "setup");
@@ -535,9 +601,12 @@ var Analyzer = class {
535
601
  return type === "TSInterfaceDeclaration" || type === "TSTypeAliasDeclaration";
536
602
  }
537
603
  declareVariable(declarator, kind, scope, isComponent) {
538
- const init = declarator.init;
539
604
  const id = declarator.id;
540
- const name = calleeName(init);
605
+ const awaited = declarator.init?.type === "AwaitExpression" ? declarator.init : void 0;
606
+ const awaitedName = awaited && calleeName$1(awaited.argument);
607
+ if (awaited && awaitedName !== void 0 && MACROS.has(awaitedName) && awaitedName !== "$memo") this.report("error", `await works with $memo, not ${awaitedName}`, awaited);
608
+ const init = awaitedName === "$memo" ? awaited.argument : declarator.init;
609
+ const name = calleeName$1(init);
541
610
  const call = init;
542
611
  if (name === "$props") {
543
612
  if (!isComponent) this.report("error", "$props() can only be called in the component script", declarator);
@@ -567,6 +636,15 @@ var Analyzer = class {
567
636
  declaration.idIndex = [...scope.declarations.values()].filter((item) => item.idIndex !== void 0).length;
568
637
  return;
569
638
  }
639
+ if (name === "$route" || name === "$navigation") {
640
+ if (kind !== "const" || id.type !== "Identifier") {
641
+ this.report("error", MISPLACED[name], declarator);
642
+ return;
643
+ }
644
+ if (name === "$navigation" ? call.arguments.length > 0 : call.arguments.length > 1) this.report("error", name === "$navigation" ? "$navigation takes no arguments" : "$route takes at most one argument, the path of the route", call);
645
+ this.addDeclaration(scope, id.name, "context", id);
646
+ return;
647
+ }
570
648
  if (name === "$getContext") {
571
649
  if (kind !== "const" || id.type !== "Identifier") {
572
650
  this.report("error", "Read a context with \"const name = $getContext(Context)\"", declarator);
@@ -592,6 +670,27 @@ var Analyzer = class {
592
670
  declaration.action = argument.name;
593
671
  return;
594
672
  }
673
+ if (name === "$debounced" || name === "$throttled") {
674
+ if (kind !== "const") this.report("error", `Declare ${name} with const`, declarator);
675
+ if (id.type !== "Identifier") {
676
+ this.report("error", `${name} cannot be destructured`, id);
677
+ return;
678
+ }
679
+ const [argument, wait] = call.arguments;
680
+ const declaration = this.addDeclaration(scope, id.name, "memo", id);
681
+ if (!argument || call.arguments.length !== 2) {
682
+ this.report("error", `${name} takes a value and a wait in milliseconds`, call);
683
+ return;
684
+ }
685
+ const ms = wait?.type === "Literal" && typeof wait.value === "number" ? wait.value : NaN;
686
+ if (!(ms >= 0 && ms <= 2147483647)) this.report("error", `The wait of ${name} must be a number of milliseconds, such as 300`, wait);
687
+ declaration.timing = {
688
+ kind: name === "$debounced" ? "debounced" : "throttled",
689
+ ms
690
+ };
691
+ declaration.site = this.createSite("memo", scope, argument, `memo ${id.name}`, { declaration });
692
+ return;
693
+ }
595
694
  if (name === "$signal" || name === "$memo" || name === "$optimistic") {
596
695
  const expected = name === "$memo" ? "const" : "let";
597
696
  if (kind !== expected) this.report("error", `Declare ${name} with ${expected}`, declarator);
@@ -602,11 +701,15 @@ var Analyzer = class {
602
701
  if (call.arguments.length > 1) this.report("error", `${name} takes one argument`, call);
603
702
  const argument = call.arguments[0];
604
703
  if (name === "$signal") {
605
- this.addDeclaration(scope, id.name, "signal", id);
606
- if (argument) this.createSite("setup", scope, argument, `signal ${id.name}`);
704
+ const declaration = this.addDeclaration(scope, id.name, "signal", id);
705
+ if (argument) {
706
+ declaration.init = argument;
707
+ this.createSite("setup", scope, argument, `signal ${id.name}`);
708
+ }
607
709
  return;
608
710
  }
609
711
  const declaration = this.addDeclaration(scope, id.name, "memo", id);
712
+ if (awaited && name === "$memo") declaration.awaited = true;
610
713
  if (!argument) {
611
714
  this.report("error", `${name} needs a value`, call);
612
715
  return;
@@ -741,10 +844,13 @@ var Analyzer = class {
741
844
  this.visitNodes(node.children, scope);
742
845
  break;
743
846
  case "listener":
744
- for (const attribute of node.attributes) this.createExpressionSite("event", scope, attribute.handler, `event ${node.target}.${attribute.event}`, {
745
- owner: node,
746
- event: attribute
747
- });
847
+ for (const attribute of node.attributes) {
848
+ const site = this.createExpressionSite("event", scope, attribute.handler, `event ${node.target}.${attribute.event}`, {
849
+ owner: node,
850
+ event: attribute
851
+ });
852
+ this.readWrappers(site, attribute, scope);
853
+ }
748
854
  break;
749
855
  default: this.visitBlock(node, scope);
750
856
  }
@@ -760,12 +866,14 @@ var Analyzer = class {
760
866
  case "value":
761
867
  this.createExpressionSite(isComponent ? "prop" : "attribute", scope, attribute.value, `${isComponent ? "prop" : "attribute"} ${tag}.${attribute.name}`, { owner: node });
762
868
  break;
763
- case "event":
764
- this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
869
+ case "event": {
870
+ const site = this.createExpressionSite(isComponent ? "prop" : "event", scope, attribute.handler, isComponent ? `prop ${tag}.${attribute.name}` : `event ${tag}.${attribute.event}`, {
765
871
  owner: node,
766
872
  event: isComponent ? void 0 : attribute
767
873
  });
874
+ if (!isComponent) this.readWrappers(site, attribute, scope);
768
875
  break;
876
+ }
769
877
  case "ref":
770
878
  if (node.kind === "element") this.refs.push({
771
879
  attribute,
@@ -843,7 +951,9 @@ var Analyzer = class {
843
951
  this.visitBody(block.body, scope, block);
844
952
  break;
845
953
  case "client":
954
+ case "defer":
846
955
  this.visitBody(block.body, scope, block);
956
+ if (block.fallback) this.visitBody(block.fallback, scope, block);
847
957
  break;
848
958
  case "offscreen":
849
959
  this.header(block, scope, block.visible, "offscreen");
@@ -952,6 +1062,7 @@ var Resolver = class {
952
1062
  this.site.calls.add(declaration);
953
1063
  if (this.untracked === 0) this.site.trackedCalls.add(declaration);
954
1064
  }
1065
+ return reference;
955
1066
  }
956
1067
  visitChildren(node) {
957
1068
  for (const [key, child] of children(node)) if (!TYPE_KEYS.has(key)) this.visit(child);
@@ -1046,10 +1157,20 @@ var Resolver = class {
1046
1157
  case "BreakStatement":
1047
1158
  case "ContinueStatement":
1048
1159
  case "MetaProperty": return;
1049
- case "AwaitExpression":
1160
+ case "AwaitExpression": {
1161
+ const argument = node.argument;
1162
+ if (argument.type === "Identifier") {
1163
+ const declaration = this.isLocal(argument.name) ? void 0 : lookup(this.site.scope, argument.name);
1164
+ if (declaration?.kind === "memo" || declaration?.kind === "async-memo") {
1165
+ const reference = this.reference(argument, "read");
1166
+ if (reference) reference.await = range(node);
1167
+ return;
1168
+ }
1169
+ }
1050
1170
  if (this.functionDepth === 0) this.site.awaits = true;
1051
- this.visit(node.argument);
1171
+ this.visit(argument);
1052
1172
  return;
1173
+ }
1053
1174
  case "CallExpression": {
1054
1175
  if (this.site.kind === "server-function" && node.callee.type === "MemberExpression" && !node.callee.computed && node.callee.property.type === "Identifier" && node.callee.property.name === "refresh" && node.arguments[0]?.type === "Identifier") {
1055
1176
  const target = lookup(this.site.scope, node.arguments[0].name);
@@ -1273,13 +1394,37 @@ function isLiveProp(declaration, liveProps) {
1273
1394
  function resetUsed(model, block, reached) {
1274
1395
  return model.declarations.some((declaration) => declaration.kind === "reset" && declaration.block === block && declaration.reads.some((read) => reached.has(read.site)));
1275
1396
  }
1397
+ /** Sites whose code runs in the browser after the page renders, and can throw there. */
1398
+ const CLIENT_CODE = /* @__PURE__ */ new Set([
1399
+ "event",
1400
+ "effect",
1401
+ "client"
1402
+ ]);
1403
+ /**
1404
+ * True if the body of a `#try` holds code that runs in the browser: a
1405
+ * handler, an effect, a `$client` callback or a memo that loads. An error
1406
+ * in it renders the `#catch` body in the browser, so both bodies ship.
1407
+ */
1408
+ function tryCatchesClient(model, block) {
1409
+ const body = model.scopes.find((scope) => scope.block === block && scope.body === block.body);
1410
+ return body !== void 0 && model.sites.some((site) => (CLIENT_CODE.has(site.kind) || site.kind === "memo" && site.declaration?.kind === "async-memo") && isWithin(site.scope, body));
1411
+ }
1276
1412
  /** True if a site's expression is a function, such as a function passed as a prop. */
1413
+ /** True for a site whose value is a `#template`, such as the prop `item=option`. */
1414
+ function isTemplateValue(site) {
1415
+ return site.node.type === "Identifier" && lookup(site.scope, site.node.name)?.kind === "template";
1416
+ }
1277
1417
  function isFunctionValue(site) {
1278
- const node = site.node;
1418
+ let node = site.node;
1419
+ for (;;) {
1420
+ while (node.type === "ParenthesizedExpression") node = node.expression;
1421
+ if (node.type !== "CallExpression" || node.callee.type !== "Identifier" || lookup(site.scope, node.callee.name)?.imported?.source !== "brumate/events" || !node.arguments[0]) break;
1422
+ node = node.arguments[0];
1423
+ }
1279
1424
  if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") return true;
1280
1425
  if (node.type === "Identifier") {
1281
1426
  const kind = lookup(site.scope, node.name)?.kind;
1282
- return kind === "function" || kind === "server-function";
1427
+ return kind === "function" || kind === "server-function" || kind === "template";
1283
1428
  }
1284
1429
  return false;
1285
1430
  }
@@ -1385,7 +1530,7 @@ function buildGraph(model, options = {}) {
1385
1530
  if (created.has(scope)) continue;
1386
1531
  const block = scope.block;
1387
1532
  const parentCreated = scope.parent !== void 0 && created.has(scope.parent);
1388
- const blockLive = scope.kind === "body" && block !== void 0 && (block.kind === "client" || block.kind === "portal" && block.target !== void 0 || block.kind === "try" && resetUsed(model, block, reached) || (headers.get(block) ?? []).some((node) => live.has(node)) || block.kind === "try" && scope.body === block.fallback && tryChanges(block));
1533
+ const blockLive = scope.kind === "body" && block !== void 0 && (block.kind === "client" && scope.body === block.body || block.kind === "portal" && block.target !== void 0 || block.kind === "try" && (resetUsed(model, block, reached) || tryCatchesClient(model, block)) || (headers.get(block) ?? []).some((node) => live.has(node)) || block.kind === "try" && scope.body === block.fallback && tryChanges(block));
1389
1534
  const templateUsed = scope.kind === "template" && templateCallChanges(scope);
1390
1535
  if (parentCreated || blockLive || templateUsed) created.add(scope);
1391
1536
  }
@@ -1422,6 +1567,24 @@ function buildGraph(model, options = {}) {
1422
1567
  message: "This $effect reads no value that changes on the client, so it never runs",
1423
1568
  range: site.range
1424
1569
  });
1570
+ for (const scope of model.scopes) {
1571
+ const block = scope.block;
1572
+ if (block?.kind !== "defer" || scope.body !== block.body) continue;
1573
+ let message;
1574
+ for (let outer = scope.parent; outer && !message; outer = outer.parent) {
1575
+ const around = outer.block;
1576
+ if (around?.kind === "client" && outer.body === around.body) message = "#defer cannot be inside a #client body";
1577
+ else if (created.has(outer)) message = "#defer cannot be in markup that the browser renders";
1578
+ }
1579
+ if (message) diagnostics.push({
1580
+ severity: "error",
1581
+ message,
1582
+ range: {
1583
+ start: block.start,
1584
+ end: block.start + 6
1585
+ }
1586
+ });
1587
+ }
1425
1588
  return {
1426
1589
  model,
1427
1590
  nodes,
@@ -1981,6 +2144,7 @@ var Parser = class {
1981
2144
  const name = parts[0];
1982
2145
  const modifiers = parts.slice(1);
1983
2146
  for (const modifier of modifiers) if (!MODIFIERS.has(modifier)) this.fail(`Unknown event modifier ":${modifier}"`, start);
2147
+ if (owner === "component" && modifiers.length > 0) this.fail(`Modifiers apply to elements. Put ":${modifiers[0]}" on the element that the component renders`, start);
1984
2148
  if (this.peek() !== "=") this.fail("Expected an event handler", this.pos);
1985
2149
  this.pos++;
1986
2150
  const value = this.parseValue();
@@ -2347,21 +2511,25 @@ var Parser = class {
2347
2511
  body: this.parseBody("portal")
2348
2512
  };
2349
2513
  }
2350
- case "client": {
2351
- const header = this.parseHeader("client", false);
2514
+ case "client":
2515
+ case "defer": {
2516
+ const header = this.parseHeader(keyword, false);
2352
2517
  let trigger = "visible";
2353
2518
  if (header) {
2354
2519
  const code = this.source.slice(header.start, header.end).trim();
2355
2520
  const value = code.slice(1, -1);
2356
- if (!/^(['"]).*\1$/.test(code) || !CLIENT_TRIGGERS.has(value)) this.fail("The trigger of #client must be \"visible\", \"idle\" or \"load\"", header.start);
2521
+ if (!/^(['"]).*\1$/.test(code) || !CLIENT_TRIGGERS.has(value)) this.fail(`The trigger of #${keyword} must be "visible", "idle" or "load"`, header.start);
2357
2522
  trigger = value;
2358
2523
  }
2524
+ const body = this.parseBody(keyword);
2525
+ const fallback = this.parseBranch("else") ? this.parseBody("else") : void 0;
2359
2526
  return {
2360
- kind: "client",
2527
+ kind: keyword,
2361
2528
  start,
2362
2529
  end: this.pos,
2363
2530
  trigger,
2364
- body: this.parseBody("client")
2531
+ body,
2532
+ fallback
2365
2533
  };
2366
2534
  }
2367
2535
  case "offscreen": {
@@ -2376,7 +2544,6 @@ var Parser = class {
2376
2544
  body
2377
2545
  };
2378
2546
  }
2379
- case "defer": return this.fail("#defer is reserved for a future block", start);
2380
2547
  default: return this.fail(`Unknown block #${keyword}`, start);
2381
2548
  }
2382
2549
  }
@@ -2497,12 +2664,13 @@ function childrenOf(node) {
2497
2664
  case "switch": return [...node.cases.flatMap((branch) => branch.body.children), ...node.fallback?.children ?? []];
2498
2665
  case "for":
2499
2666
  case "repeat":
2500
- case "loading": return [...node.body.children, ...node.fallback?.children ?? []];
2667
+ case "loading":
2668
+ case "client":
2669
+ case "defer": return [...node.body.children, ...node.fallback?.children ?? []];
2501
2670
  case "try": return [...node.body.children, ...node.fallback.children];
2502
2671
  case "key":
2503
2672
  case "portal":
2504
2673
  case "head":
2505
- case "client":
2506
2674
  case "offscreen": return node.body.children;
2507
2675
  default: return [];
2508
2676
  }
@@ -2742,6 +2910,16 @@ const SENDABLE = /* @__PURE__ */ new Set([
2742
2910
  "Date",
2743
2911
  "URL",
2744
2912
  "URLSearchParams",
2913
+ "Headers",
2914
+ "FormData",
2915
+ "Request",
2916
+ "Response",
2917
+ "ReadableStream",
2918
+ "Event",
2919
+ "CustomEvent",
2920
+ "DOMException",
2921
+ "AbortSignal",
2922
+ "ImageData",
2745
2923
  "Map",
2746
2924
  "Set",
2747
2925
  "Promise",
@@ -2771,7 +2949,12 @@ const SENDABLE = /* @__PURE__ */ new Set([
2771
2949
  "Boolean"
2772
2950
  ]);
2773
2951
  /** Compile-time functions whose argument is the value, such as `$signal(new Foo())`. */
2774
- const WRAPPERS = /* @__PURE__ */ new Set(["$signal", "$memo"]);
2952
+ const WRAPPERS = /* @__PURE__ */ new Set([
2953
+ "$signal",
2954
+ "$memo",
2955
+ "$debounced",
2956
+ "$throttled"
2957
+ ]);
2775
2958
  /** The value that a declaration holds, by the offset of its name. */
2776
2959
  function initializers(file) {
2777
2960
  const result = /* @__PURE__ */ new Map();
@@ -2816,6 +2999,66 @@ function checkCaptures(file, plan) {
2816
2999
  return diagnostics;
2817
3000
  }
2818
3001
  //#endregion
3002
+ //#region src/env-check.ts
3003
+ /** The property that a read of `env` reads, such as `DATABASE_URL` for `env.DATABASE_URL`. */
3004
+ function propertyAt(node, at) {
3005
+ if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.start === at) {
3006
+ if (node.computed) return node.property.type === "Literal" ? String(node.property.value) : null;
3007
+ return node.property.type === "Identifier" ? node.property.name : null;
3008
+ }
3009
+ for (const [, child] of children(node)) {
3010
+ const found = propertyAt(child, at);
3011
+ if (found !== void 0) return found;
3012
+ }
3013
+ }
3014
+ /** The server variable that a read reads, or `*` for a read of the whole object. */
3015
+ function serverRead(read, server) {
3016
+ const nodes = [read.site.node, ...read.site.extra ?? []];
3017
+ for (const node of nodes) {
3018
+ const property = propertyAt(node, read.range.start);
3019
+ if (property === void 0) continue;
3020
+ if (property === null) return "*";
3021
+ return server.includes(property) ? property : void 0;
3022
+ }
3023
+ return "*";
3024
+ }
3025
+ /** Errors for server variables that code in the browser reads, or that the page state would send. */
3026
+ function checkEnv(file, plan, envImport) {
3027
+ const diagnostics = [];
3028
+ const values = initializers(file);
3029
+ const slots = /* @__PURE__ */ new Set();
3030
+ for (const layout of plan.scopes.values()) for (const declaration of layout.slots) slots.add(declaration);
3031
+ for (const declaration of plan.graph.model.declarations) {
3032
+ if (!declaration.imported) continue;
3033
+ const server = envImport(declaration.imported.source, declaration.imported.name);
3034
+ if (!server) continue;
3035
+ const name = declaration.name;
3036
+ for (const read of declaration.reads) {
3037
+ const variable = serverRead(read, server);
3038
+ if (variable === void 0) continue;
3039
+ const what = variable === "*" ? `${name}, with its server variables,` : `${name}.${variable}, a server variable,`;
3040
+ if (plan.graph.reached.has(read.site)) {
3041
+ diagnostics.push({
3042
+ severity: "error",
3043
+ message: `${what} is read by code that runs in the browser (${read.site.label}). Read it in a server function`,
3044
+ range: read.range
3045
+ });
3046
+ continue;
3047
+ }
3048
+ const holder = [...slots].find((slot) => {
3049
+ const init = values.get(slot.range.start);
3050
+ return init && read.range.start >= init.start && read.range.end <= init.end;
3051
+ });
3052
+ if (holder) diagnostics.push({
3053
+ severity: "error",
3054
+ message: `"${holder.name}" holds ${what} and code that runs in the browser reads it. Keep server variables out of values that the browser reads`,
3055
+ range: read.range
3056
+ });
3057
+ }
3058
+ }
3059
+ return diagnostics;
3060
+ }
3061
+ //#endregion
2819
3062
  //#region src/sourcemap.ts
2820
3063
  const OPEN = "";
2821
3064
  const CLOSE = "";
@@ -3533,7 +3776,18 @@ var Patch = class {
3533
3776
  return result + copy(this.source, position, end);
3534
3777
  }
3535
3778
  };
3779
+ /** The name of the function that a call expression calls, when it is a plain name. */
3780
+ function calleeName(node) {
3781
+ return node.callee.type === "Identifier" ? node.callee.name : void 0;
3782
+ }
3536
3783
  /** The variable that holds a memo on the server, which can be a promise. */
3784
+ /** The compile-time functions that declare a memo of their first argument. The others are options. */
3785
+ const MEMOS = /* @__PURE__ */ new Set([
3786
+ "$memo",
3787
+ "$optimistic",
3788
+ "$debounced",
3789
+ "$throttled"
3790
+ ]);
3537
3791
  function promiseName(name) {
3538
3792
  return `$$p_${name}`;
3539
3793
  }
@@ -3542,11 +3796,30 @@ function promiseName(name) {
3542
3796
  * `$signal(x)` and `$memo(x)` become `(x)`, `$props()` becomes `$$props`
3543
3797
  * and `$untrack(x)` becomes `(x)`. On the server, a memo is renamed to
3544
3798
  * `$$p_<name>`, because it can hold a promise that is awaited where it is read.
3799
+ * The memos in `inline` are plain values on the server too.
3545
3800
  */
3546
- function addValueEdits(patch, file, sites, mode = "server") {
3801
+ function addValueEdits(patch, file, sites, mode = "server", inline = /* @__PURE__ */ new Set()) {
3547
3802
  const sitesByNode = /* @__PURE__ */ new Map();
3548
- for (const site of sites) sitesByNode.set(site.node, site);
3803
+ const awaits = /* @__PURE__ */ new Map();
3804
+ const replaced = /* @__PURE__ */ new Set();
3805
+ for (const site of sites) {
3806
+ sitesByNode.set(site.node, site);
3807
+ for (const read of site.reads) if (read.await) awaits.set(read.await.start, read);
3808
+ }
3549
3809
  const visit = (node) => {
3810
+ if (node.type === "AwaitExpression") {
3811
+ const argument = node.argument;
3812
+ if (argument.type === "CallExpression" && calleeName(argument) === "$memo") {
3813
+ patch.replace(node.start, argument.start, "");
3814
+ visit(argument);
3815
+ return;
3816
+ }
3817
+ const read = awaits.get(node.start);
3818
+ if (read && !replaced.has(read)) {
3819
+ patch.replace(node.start, node.end, read.declaration.name);
3820
+ return;
3821
+ }
3822
+ }
3550
3823
  if (node.type === "CallExpression" && node.callee.type === "Identifier") {
3551
3824
  const name = node.callee.name;
3552
3825
  const argument = node.arguments[0];
@@ -3568,16 +3841,20 @@ function addValueEdits(patch, file, sites, mode = "server") {
3568
3841
  for (const rest of node.arguments.slice(1)) visit(rest);
3569
3842
  return;
3570
3843
  }
3571
- if (name === "$signal" || name === "$memo" || name === "$optimistic" || name === "$untrack") {
3844
+ if (MEMOS.has(name) || name === "$signal" || name === "$untrack") {
3572
3845
  if (!argument) {
3573
3846
  patch.replace(node.start, node.end, "undefined");
3574
3847
  return;
3575
3848
  }
3576
- const site = name === "$memo" || name === "$optimistic" ? sitesByNode.get(argument) : void 0;
3577
- const declaration = site?.declaration;
3849
+ const site = MEMOS.has(name) ? sitesByNode.get(argument) : void 0;
3850
+ const declaration = site?.declaration && !inline.has(site.declaration) ? site.declaration : void 0;
3578
3851
  if (declaration && mode === "server") patch.replace(declaration.range.start, declaration.range.end, promiseName(declaration.name));
3579
3852
  if (declaration && mode === "server") {
3580
- for (const read of site.reads) if (read.range.start !== read.range.end && read.declaration !== declaration && (read.declaration.kind === "memo" || read.declaration.kind === "async-memo")) patch.replace(read.range.start, read.range.end, `$$b.read(${promiseName(read.declaration.name)})`);
3853
+ for (const read of site.reads) if (read.range.start !== read.range.end && read.declaration !== declaration && !inline.has(read.declaration) && (read.declaration.kind === "memo" || read.declaration.kind === "async-memo")) {
3854
+ const range = read.await ?? read.range;
3855
+ patch.replace(range.start, range.end, `$$b.read(${promiseName(read.declaration.name)})`);
3856
+ replaced.add(read);
3857
+ }
3581
3858
  patch.replace(node.start, argument.start, site.awaits ? "$$b.memo(async () => (" : "$$b.memo(() => (");
3582
3859
  patch.replace(argument.end, node.end, "), $$ctx)");
3583
3860
  } else if (site?.awaits) {
@@ -4115,7 +4392,8 @@ function createPlan(file, graph, path, hideNames = false) {
4115
4392
  plan.needsId = true;
4116
4393
  };
4117
4394
  const symbols = /* @__PURE__ */ new Map();
4118
- for (const site of model.sites) if (site.kind === "event" || site.kind === "prop" && isFunctionValue(site)) symbols.set(site, `h${site.id}`);
4395
+ for (const site of model.sites) if (site.kind === "prop" && isTemplateValue(site)) symbols.set(site, `t${site.id}`);
4396
+ else if (site.kind === "event" || site.kind === "prop" && isFunctionValue(site)) symbols.set(site, `h${site.id}`);
4119
4397
  else if (site.kind === "client") {
4120
4398
  symbols.set(site, `c${site.id}`);
4121
4399
  anchor(site.scope, site);
@@ -4223,7 +4501,7 @@ function createPlan(file, graph, path, hideNames = false) {
4223
4501
  };
4224
4502
  const visitBlock = (block, scope, outer) => {
4225
4503
  const portalTarget = block.kind === "portal" && block.target !== void 0;
4226
- const live = block.kind === "client" || portalTarget || block.kind === "try" && resetUsed(model, block, graph.reached) || (headerSites.get(block) ?? []).some((site) => isLiveSite(site));
4504
+ const live = block.kind === "client" || block.kind === "defer" || portalTarget || block.kind === "try" && (resetUsed(model, block, graph.reached) || tryCatchesClient(model, block)) || (headerSites.get(block) ?? []).some((site) => isLiveSite(site));
4227
4505
  if (live) anchor(scope, block);
4228
4506
  if (live && block.kind === "offscreen") scopes.get(bodyScopes.get(block.body)).needsId = true;
4229
4507
  if (block.kind === "portal" || block.kind === "head") scopes.get(bodyScopes.get(block.body)).needsId = true;
@@ -4249,6 +4527,34 @@ function createPlan(file, graph, path, hideNames = false) {
4249
4527
  };
4250
4528
  for (const template of file.templates) visitBody(template.body);
4251
4529
  visitNodes(file.children, model.component);
4530
+ const checkTitles = (nodes, inHead) => {
4531
+ for (const node of nodes) switch (node.kind) {
4532
+ case "element": {
4533
+ const tag = node.tag.toLowerCase();
4534
+ if (tag === "title" && !inHead) diagnostics.push({
4535
+ severity: "error",
4536
+ message: "Put <title> in #head, as <meta> and <link>, such as #head { <title>{`${count} left`}</title> }",
4537
+ range: {
4538
+ start: node.start,
4539
+ end: node.end
4540
+ }
4541
+ });
4542
+ else if (tag !== "head" && tag !== "svg") checkTitles(node.children, inHead);
4543
+ break;
4544
+ }
4545
+ case "component":
4546
+ case "dynamic":
4547
+ case "fragment":
4548
+ checkTitles(node.children, inHead);
4549
+ break;
4550
+ case "text":
4551
+ case "insert":
4552
+ case "listener": break;
4553
+ default: for (const body of blockBodies(node)) checkTitles(body.children, inHead || node.kind === "head");
4554
+ }
4555
+ };
4556
+ for (const template of file.templates) checkTitles(template.body.children, false);
4557
+ checkTitles(file.children, false);
4252
4558
  for (const plan of scopes.values()) {
4253
4559
  if (plan.slots.length > 0) plan.needsId = true;
4254
4560
  if ([...plan.scope.declarations.values()].some((declaration) => declaration.idIndex !== void 0)) plan.needsId = true;
@@ -4300,7 +4606,9 @@ function blockBodies(block) {
4300
4606
  case "switch": return [...block.cases.map((branch) => branch.body), ...block.fallback ? [block.fallback] : []];
4301
4607
  case "for":
4302
4608
  case "repeat":
4303
- case "loading": return [block.body, ...block.fallback ? [block.fallback] : []];
4609
+ case "loading":
4610
+ case "client":
4611
+ case "defer": return [block.body, ...block.fallback ? [block.fallback] : []];
4304
4612
  case "try": return [block.body, block.fallback];
4305
4613
  default: return [block.body];
4306
4614
  }
@@ -4339,30 +4647,55 @@ const DEFERRED_SITES$1 = /* @__PURE__ */ new Set([
4339
4647
  "effect",
4340
4648
  "client"
4341
4649
  ]);
4342
- /** Returns the nearest `#loading` body scope that contains a scope, up to `limit`. */
4650
+ /**
4651
+ * Returns the nearest `#loading` or `#defer` body scope that contains a
4652
+ * scope, up to `limit`. Both render after the rest of the page, so the
4653
+ * page does not wait for the memos that only they read.
4654
+ */
4343
4655
  function loadingBody(scope, limit) {
4344
- for (let current = scope; current && current !== limit; current = current.parent) if (current.block?.kind === "loading" && current.body === current.block.body) return current;
4656
+ for (let current = scope; current && current !== limit; current = current.parent) {
4657
+ const block = current.block;
4658
+ if ((block?.kind === "loading" || block?.kind === "defer") && current.body === block.body) return current;
4659
+ }
4345
4660
  }
4346
4661
  /** Any memo can hold a promise, because its expression can call code that returns one. */
4347
4662
  function isMemo(declaration) {
4348
4663
  return declaration.kind === "memo" || declaration.kind === "async-memo";
4349
4664
  }
4350
4665
  /**
4351
- * Returns the memos that the server awaits where they are declared,
4352
- * because markup or code outside every `#loading` body reads them. The
4353
- * others are awaited by the `#loading` bodies that read them.
4666
+ * The scope whose render waits for a read. A read with `await` inside a
4667
+ * `#loading` body makes the render around the block wait, so it counts as
4668
+ * a read in the scope that holds the block. Inside a `#defer` body, the
4669
+ * request for the body waits, so the read stays where it is. `limit` is
4670
+ * the scope of the declaration, which a read inside it never leaves.
4671
+ */
4672
+ function readScope(read, limit) {
4673
+ const scope = read.site.scope;
4674
+ if (!read.await) return scope;
4675
+ const body = loadingBody(scope, limit);
4676
+ return body?.block?.kind === "loading" ? body.parent : scope;
4677
+ }
4678
+ /**
4679
+ * Returns the memos that the server awaits where they are declared: those
4680
+ * declared with `await $memo(…)`, and those that markup or code outside
4681
+ * every `#loading` body reads, with `await` or without. The others are
4682
+ * awaited by the `#loading` bodies that read them.
4354
4683
  */
4355
4684
  function blockingMemos(plan) {
4356
4685
  const result = /* @__PURE__ */ new Set();
4357
4686
  for (const declaration of plan.graph.model.declarations) {
4358
4687
  if (!isMemo(declaration)) continue;
4688
+ if (declaration.awaited) {
4689
+ result.add(declaration);
4690
+ continue;
4691
+ }
4359
4692
  for (const read of declaration.reads) {
4360
4693
  if (read.range.start === read.range.end) continue;
4361
4694
  const site = read.site;
4362
4695
  if (DEFERRED_SITES$1.has(site.kind) || site.kind === "memo") continue;
4363
4696
  let template = false;
4364
4697
  for (let scope = site.scope; scope; scope = scope.parent) template ||= scope.kind === "template";
4365
- if (template || !loadingBody(site.scope, declaration.scope)) {
4698
+ if (template || !loadingBody(readScope(read, declaration.scope), declaration.scope)) {
4366
4699
  result.add(declaration);
4367
4700
  break;
4368
4701
  }
@@ -4370,18 +4703,173 @@ function blockingMemos(plan) {
4370
4703
  }
4371
4704
  return result;
4372
4705
  }
4373
- /** Returns the memos that a `#loading` body awaits before it renders. */
4706
+ /**
4707
+ * Returns the memos that a `#loading` body waits for before it renders:
4708
+ * the memos that its markup reads, and the memos that a `#loading` body
4709
+ * inside it reads with `await`. Memos that the page or a body around it
4710
+ * waits for are left out.
4711
+ */
4374
4712
  function awaitedMemos(plan, body, blocking) {
4375
4713
  const result = /* @__PURE__ */ new Set();
4376
4714
  for (const site of plan.graph.model.sites) {
4377
- if (DEFERRED_SITES$1.has(site.kind) || loadingBody(site.scope) !== body) continue;
4715
+ if (DEFERRED_SITES$1.has(site.kind)) continue;
4378
4716
  for (const read of site.reads) {
4379
- if (read.range.start === read.range.end) continue;
4717
+ if (read.range.start === read.range.end || loadingBody(readScope(read)) !== body) continue;
4380
4718
  if (isMemo(read.declaration) && !blocking.has(read.declaration)) result.add(read.declaration);
4381
4719
  }
4382
4720
  }
4721
+ const outer = body.parent && loadingBody(body.parent);
4722
+ if (outer) for (const declaration of awaitedMemos(plan, outer, blocking)) result.delete(declaration);
4383
4723
  return [...result];
4384
4724
  }
4725
+ /**
4726
+ * True if the markup of a `#loading` body may wait for something other than
4727
+ * the memos it reads, so the body cannot render in place when those memos
4728
+ * are ready: a child component, a dynamic tag, a template, or an insert of
4729
+ * a prop, which can be a promise or the children of a parent. Bodies that
4730
+ * render later, such as those of a `#loading` or a `#defer` inside it, wait
4731
+ * on their own.
4732
+ */
4733
+ function mayWait(plan, nodes) {
4734
+ const insertWaits = (node) => {
4735
+ const site = plan.graph.model.sites.find((item) => item.node === node.expression.ast);
4736
+ if (!site) return false;
4737
+ for (const read of site.reads) {
4738
+ const kind = read.declaration.kind;
4739
+ if (kind === "prop" || kind === "props-rest" || kind === "template") return true;
4740
+ }
4741
+ return false;
4742
+ };
4743
+ for (const node of nodes) switch (node.kind) {
4744
+ case "component":
4745
+ case "dynamic": return true;
4746
+ case "insert":
4747
+ if (insertWaits(node)) return true;
4748
+ break;
4749
+ case "element":
4750
+ case "fragment":
4751
+ if (mayWait(plan, node.children)) return true;
4752
+ break;
4753
+ case "text":
4754
+ case "listener": break;
4755
+ default: {
4756
+ const bodies = node.kind === "loading" || node.kind === "defer" || node.kind === "client" ? node.fallback ? [node.fallback] : [] : blockBodies(node);
4757
+ for (const body of bodies) if (mayWait(plan, body.children)) return true;
4758
+ }
4759
+ }
4760
+ return false;
4761
+ }
4762
+ /** Expressions that run code the compiler cannot see, or that a memo should not hold. */
4763
+ const UNSAFE_NODES = /* @__PURE__ */ new Set([
4764
+ "CallExpression",
4765
+ "NewExpression",
4766
+ "TaggedTemplateExpression",
4767
+ "AwaitExpression",
4768
+ "YieldExpression",
4769
+ "ImportExpression",
4770
+ "AssignmentExpression",
4771
+ "UpdateExpression",
4772
+ "FunctionExpression",
4773
+ "ArrowFunctionExpression",
4774
+ "ClassExpression"
4775
+ ]);
4776
+ /**
4777
+ * True if an expression always gives a primitive, so it is never a promise
4778
+ * or an async iterable. A name is a primitive when `plain` says that it reads
4779
+ * a declaration that holds one.
4780
+ */
4781
+ function isPrimitive(node, plain = () => false) {
4782
+ switch (node.type) {
4783
+ case "Identifier": return plain(node);
4784
+ case "Literal": return !("regex" in node && node.regex);
4785
+ case "TemplateLiteral":
4786
+ case "BinaryExpression":
4787
+ case "UnaryExpression": return true;
4788
+ case "LogicalExpression": return isPrimitive(node.left, plain) && isPrimitive(node.right, plain);
4789
+ case "ConditionalExpression": return isPrimitive(node.consequent, plain) && isPrimitive(node.alternate, plain);
4790
+ case "TSAsExpression":
4791
+ case "TSSatisfiesExpression":
4792
+ case "TSNonNullExpression": return isPrimitive(node.expression, plain);
4793
+ default: return false;
4794
+ }
4795
+ }
4796
+ /** True if an expression calls no code and, unless `members`, reads no property. */
4797
+ function isSafe(node, members) {
4798
+ if (UNSAFE_NODES.has(node.type)) return false;
4799
+ if (!members && (node.type === "MemberExpression" || node.type === "ChainExpression")) return false;
4800
+ for (const [, child] of children(node)) if (!isSafe(child, members)) return false;
4801
+ return true;
4802
+ }
4803
+ /** True if a name in the code of a site reads a declaration that `plain` accepts. */
4804
+ function readsPlain(site, name, plain) {
4805
+ return site?.reads.some((read) => read.range.start === name.start && read.range.end === name.end && plain(read.declaration)) ?? false;
4806
+ }
4807
+ const ARITHMETIC_ASSIGNMENTS = /* @__PURE__ */ new Set([
4808
+ "+=",
4809
+ "-=",
4810
+ "*=",
4811
+ "/=",
4812
+ "%=",
4813
+ "**=",
4814
+ "<<=",
4815
+ ">>=",
4816
+ ">>>=",
4817
+ "&=",
4818
+ "|=",
4819
+ "^="
4820
+ ]);
4821
+ /** Returns the assignment or update of a site whose target is at `at`. */
4822
+ function writeAt(node, at) {
4823
+ if (node.type === "AssignmentExpression" && node.left.type === "Identifier" && node.left.start === at || node.type === "UpdateExpression" && node.argument.type === "Identifier" && node.argument.start === at) return node;
4824
+ for (const [, child] of children(node)) {
4825
+ const found = writeAt(child, at);
4826
+ if (found) return found;
4827
+ }
4828
+ }
4829
+ /**
4830
+ * Returns the memos and signals that always hold a primitive on the server,
4831
+ * so the server reads them as plain values.
4832
+ *
4833
+ * - A memo gives a primitive and calls nothing, so it is never a promise and
4834
+ * needs no render context. Each memo that it reads is one too, so no read
4835
+ * waits for a load. A memo that the server would not compute where it is
4836
+ * declared reads no property, because computing it early must not throw.
4837
+ * - A signal starts with a primitive, and each write gives a primitive, such
4838
+ * as `count++`. A signal that an element ref sets is left out.
4839
+ */
4840
+ function plainValues(plan, blocking) {
4841
+ const result = /* @__PURE__ */ new Set();
4842
+ const visiting = /* @__PURE__ */ new Set();
4843
+ const check = (declaration) => {
4844
+ if (result.has(declaration)) return true;
4845
+ if (visiting.has(declaration)) return false;
4846
+ visiting.add(declaration);
4847
+ const plain = declaration.kind === "signal" ? isPlainSignal(declaration) : isPlainMemo(declaration);
4848
+ visiting.delete(declaration);
4849
+ if (plain) result.add(declaration);
4850
+ return plain;
4851
+ };
4852
+ const isPlainMemo = (declaration) => {
4853
+ const site = declaration.site;
4854
+ return declaration.kind === "memo" && !declaration.writable && !declaration.optimistic && site !== void 0 && isPrimitive(site.node, (name) => readsPlain(site, name, check)) && isSafe(site.node, blocking.has(declaration)) && site.reads.every((read) => !isMemo(read.declaration) || check(read.declaration));
4855
+ };
4856
+ const isPlainSignal = (declaration) => {
4857
+ if (declaration.refs.length > 0) return false;
4858
+ const init = declaration.init;
4859
+ if (init) {
4860
+ const site = plan.graph.model.sites.find((item) => item.node === init);
4861
+ if (!isPrimitive(init, (name) => readsPlain(site, name, check))) return false;
4862
+ }
4863
+ return declaration.writes.every((write) => {
4864
+ const node = writeAt(write.site.node, write.range.start);
4865
+ if (node?.type === "UpdateExpression") return true;
4866
+ if (node?.type !== "AssignmentExpression") return false;
4867
+ return ARITHMETIC_ASSIGNMENTS.has(node.operator) || isPrimitive(node.right, (name) => readsPlain(write.site, name, check));
4868
+ });
4869
+ };
4870
+ for (const declaration of plan.graph.model.declarations) check(declaration);
4871
+ return result;
4872
+ }
4385
4873
  //#endregion
4386
4874
  //#region src/codegen/markup.ts
4387
4875
  const VOID_ELEMENTS = /* @__PURE__ */ new Set([
@@ -4410,8 +4898,13 @@ function specialCall(declarator) {
4410
4898
  const init = declarator.init;
4411
4899
  if (init?.type !== "CallExpression" || init.callee.type !== "Identifier") return;
4412
4900
  const name = init.callee.name;
4413
- return name === "$getContext" || name === "$id" ? name : void 0;
4901
+ return name === "$getContext" || name === "$id" || name === "$route" || name === "$navigation" ? name : void 0;
4414
4902
  }
4903
+ /** The contexts that the runtime provides, by the compile-time function that reads them. */
4904
+ const BUILT_IN_CONTEXTS = {
4905
+ $route: "$$b.routeContext",
4906
+ $navigation: "$$b.navigationContext"
4907
+ };
4415
4908
  /** Writes code that renders markup to an HTML string, on the server or on the client. */
4416
4909
  /** The exports of the core that do on the client what the server's render context does. */
4417
4910
  const CLIENT_HELPERS = {
@@ -4430,6 +4923,71 @@ const CLIENT_HELPERS = {
4430
4923
  after: "afterInsert",
4431
4924
  title: "title"
4432
4925
  };
4926
+ /** The named character references that markup reads. Others stay as they are written. */
4927
+ const NAMED = {
4928
+ amp: "&",
4929
+ lt: "<",
4930
+ gt: ">",
4931
+ quot: "\"",
4932
+ apos: "'",
4933
+ nbsp: "\xA0",
4934
+ copy: "©",
4935
+ reg: "®",
4936
+ trade: "™",
4937
+ hellip: "…",
4938
+ mdash: "—",
4939
+ ndash: "–",
4940
+ lsquo: "‘",
4941
+ rsquo: "’",
4942
+ ldquo: "“",
4943
+ rdquo: "”",
4944
+ laquo: "«",
4945
+ raquo: "»",
4946
+ middot: "·",
4947
+ bull: "•",
4948
+ times: "×",
4949
+ euro: "€"
4950
+ };
4951
+ /**
4952
+ * Markup text or a static attribute value, with its character references
4953
+ * read. A number that is no character, such as one past 0x10FFFF, reads as
4954
+ * U+FFFD, as the browser reads it.
4955
+ */
4956
+ function decodeReferences(html) {
4957
+ return html.replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, name) => {
4958
+ if (name[0] === "#") {
4959
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : Number(name.slice(1));
4960
+ return code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : "�";
4961
+ }
4962
+ return NAMED[name.toLowerCase()] ?? match;
4963
+ });
4964
+ }
4965
+ /** The value of a static attribute, with its character references read. */
4966
+ function decodeAttribute(text) {
4967
+ return decodeReferences(text);
4968
+ }
4969
+ /** The text that markup text shows, with its character references read. */
4970
+ function decodeText(html) {
4971
+ return decodeReferences(html);
4972
+ }
4973
+ /** The markup of an inserted literal, such as `{'<b>'}`, or undefined for other code. */
4974
+ function literalText(node) {
4975
+ if (node.type === "Literal") return "regex" in node && node.regex ? void 0 : insertValue(node.value);
4976
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) return insertValue(node.quasis[0].value.cooked);
4977
+ }
4978
+ /**
4979
+ * Blocks whose shape on the server depends on data: which branch renders,
4980
+ * how many items a list has, whether a body throws or shows. The server
4981
+ * numbers the scopes of their bodies after an ID of the block's own.
4982
+ */
4983
+ const DATA_SHAPED = /* @__PURE__ */ new Set([
4984
+ "if",
4985
+ "switch",
4986
+ "for",
4987
+ "repeat",
4988
+ "try",
4989
+ "offscreen"
4990
+ ]);
4433
4991
  var Emitter = class {
4434
4992
  lines = [];
4435
4993
  file;
@@ -4444,10 +5002,14 @@ var Emitter = class {
4444
5002
  ctxArgument;
4445
5003
  /** Async memos that the server awaits where they are declared. */
4446
5004
  blocking;
5005
+ /** Memos and signals that hold a primitive on the server, so it awaits none of them. */
5006
+ inline;
4447
5007
  parts = [];
4448
5008
  depth = 0;
4449
5009
  /** How many of this component's elements contain the current node. */
4450
5010
  nesting = 0;
5011
+ /** How many `#head` blocks contain the current node, where a `<title>` sets the title of the page. */
5012
+ headBlocks = 0;
4451
5013
  counter = 0;
4452
5014
  constructor(file, plan, patch, options) {
4453
5015
  this.file = file;
@@ -4458,6 +5020,7 @@ var Emitter = class {
4458
5020
  this.async = options.mode === "server" ? "async " : "";
4459
5021
  this.ctxArgument = options.mode === "server" ? "$$ctx" : "undefined";
4460
5022
  this.blocking = blockingMemos(plan);
5023
+ this.inline = options.mode === "server" ? plainValues(plan, this.blocking) : /* @__PURE__ */ new Set();
4461
5024
  for (const site of plan.graph.model.sites) this.sitesByNode.set(site.node, site);
4462
5025
  for (const declaration of plan.graph.model.declarations) for (const ref of declaration.refs) this.refTargets.set(ref.attribute, declaration);
4463
5026
  }
@@ -4542,27 +5105,83 @@ var Emitter = class {
4542
5105
  emitSlots(scope) {
4543
5106
  const slots = this.plan.scopes.get(scope)?.slots ?? [];
4544
5107
  if (slots.length > 0) {
4545
- const values = slots.map((slot) => this.isPromise(slot) ? `$$b.wait(${promiseName(slot.name)})` : slot.name);
5108
+ const values = slots.map((slot) => this.isPromise(slot) ? `$$b.stateValue(${promiseName(slot.name)})` : slot.name);
4546
5109
  const names = this.options.mode === "server" ? `, ${JSON.stringify(slots.map((slot) => slot.name))}` : "";
4547
5110
  this.line(`${this.helper("slots")}(${this.scopeVar(scope)}, [${values.join(", ")}]${names});`);
4548
5111
  }
4549
5112
  }
5113
+ /** True if the server inserts a primitive, such as a memo that it computes as a plain value. */
5114
+ isPrimitiveInsert(expression) {
5115
+ if (this.options.mode !== "server") return false;
5116
+ const site = this.sitesByNode.get(expression.ast);
5117
+ return isPrimitive(expression.ast, (name) => readsPlain(site, name, (declaration) => this.inline.has(declaration)));
5118
+ }
4550
5119
  /** True for an async memo that is a promise where its scope ends, on the server. */
4551
5120
  isPromise(declaration) {
4552
- return this.options.mode === "server" && isMemo(declaration) && !this.blocking.has(declaration);
5121
+ return this.options.mode === "server" && isMemo(declaration) && !this.blocking.has(declaration) && !this.inline.has(declaration);
4553
5122
  }
4554
- /** Awaits the async memos of a statement that markup outside `#loading` reads. */
4555
- awaitMemos(statement) {
5123
+ /**
5124
+ * The memos of a statement that the server waits for where they are
5125
+ * declared. `awaited` is true when every one of them is declared with
5126
+ * `await $memo(…)`. Such statements in a row form a run: every memo of
5127
+ * the run starts, and the render waits for all of them where the run
5128
+ * ends, so independent memos load at the same time. A memo that the
5129
+ * markup makes the page wait for, without the keyword, is awaited on its
5130
+ * own, as the code reads.
5131
+ */
5132
+ blockingDeclarations(statement) {
4556
5133
  if (this.options.mode !== "server" || statement.type !== "VariableDeclaration") return;
5134
+ const declarations = [];
5135
+ let awaited = true;
4557
5136
  for (const declarator of statement.declarations) {
4558
- const init = declarator.init;
5137
+ let init = declarator.init;
5138
+ if (init?.type === "AwaitExpression") init = init.argument;
4559
5139
  const argument = init?.type === "CallExpression" ? init.arguments[0] : void 0;
4560
5140
  const declaration = argument && this.sitesByNode.get(argument)?.declaration;
4561
- if (declaration && isMemo(declaration) && this.blocking.has(declaration)) this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5141
+ if (!declaration || !isMemo(declaration) || !this.blocking.has(declaration)) {
5142
+ awaited = false;
5143
+ continue;
5144
+ }
5145
+ awaited &&= declaration.awaited === true;
5146
+ if (!this.inline.has(declaration)) declarations.push(declaration);
5147
+ }
5148
+ return declarations.length === 0 ? void 0 : {
5149
+ declarations,
5150
+ awaited
5151
+ };
5152
+ }
5153
+ /** Waits for the memos of a run of declarations, and gives each its value. */
5154
+ awaitRun(run) {
5155
+ if (run.length === 1) {
5156
+ const [declaration] = run;
5157
+ this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5158
+ return;
4562
5159
  }
5160
+ const names = run.map((declaration) => promiseName(declaration.name));
5161
+ this.line(`if (($$t = $$b.waitAll([${names.join(", ")}])) !== undefined) await $$t;`);
5162
+ for (const declaration of run) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
4563
5163
  }
4564
5164
  emitStatements(statements, scope) {
5165
+ let run = [];
5166
+ const endRun = () => {
5167
+ if (run.length > 0) {
5168
+ this.awaitRun(run);
5169
+ run = [];
5170
+ }
5171
+ };
4565
5172
  for (const statement of statements) {
5173
+ const blocking = this.blockingDeclarations(statement);
5174
+ if (blocking?.awaited) {
5175
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
5176
+ run.push(...blocking.declarations);
5177
+ continue;
5178
+ }
5179
+ endRun();
5180
+ if (blocking) {
5181
+ this.raw(this.patch.slice(statement.start, statement.end), statement.start);
5182
+ for (const declaration of blocking.declarations) this.awaitRun([declaration]);
5183
+ continue;
5184
+ }
4566
5185
  if (statement.type === "ExpressionStatement") {
4567
5186
  const expression = statement.expression;
4568
5187
  const name = expression.type === "CallExpression" && expression.callee.type === "Identifier" ? expression.callee.name : void 0;
@@ -4587,8 +5206,8 @@ var Emitter = class {
4587
5206
  if (!this.options.functions && this.isFunctionStatement(statement)) continue;
4588
5207
  }
4589
5208
  this.raw(this.patch.slice(statement.start, statement.end), statement.start);
4590
- this.awaitMemos(statement);
4591
5209
  }
5210
+ endRun();
4592
5211
  }
4593
5212
  source(node) {
4594
5213
  return this.patch.slice(node.start, node.end);
@@ -4608,13 +5227,14 @@ var Emitter = class {
4608
5227
  this.line(`const ${declaration.name} = ${this.helper("id")}(${target}, ${declaration.idIndex});`);
4609
5228
  continue;
4610
5229
  }
4611
- if (call !== "$getContext" || declarator.id.type !== "Identifier" || !init.arguments[0]) {
5230
+ const context = call && BUILT_IN_CONTEXTS[call] ? BUILT_IN_CONTEXTS[call] : call === "$getContext" && init.arguments[0] ? this.source(init.arguments[0]) : void 0;
5231
+ if (!context || declarator.id.type !== "Identifier") {
4612
5232
  this.line(`${statement.kind} ${this.source(declarator)};`);
4613
5233
  continue;
4614
5234
  }
4615
5235
  const slot = declaration ? slotIndex(this.plan, declaration) : -1;
4616
5236
  const record = slot === -1 ? "" : `, ${slot}`;
4617
- this.line(`const ${declarator.id.name} = ${this.helper("consume")}(${this.source(init.arguments[0])}, ${target}${record});`);
5237
+ this.line(`const ${declarator.id.name} = ${this.helper("consume")}(${context}, ${target}${record});`);
4618
5238
  }
4619
5239
  return true;
4620
5240
  }
@@ -4636,7 +5256,21 @@ var Emitter = class {
4636
5256
  const anchor = this.anchor(scope, site);
4637
5257
  this.html("<template b-b=\"");
4638
5258
  this.code(anchor.scope);
4639
- this.html(`:${anchor.index}" b-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"></template>`);
5259
+ this.html(`:${anchor.index}" b-client="${site.trigger}=${this.plan.id}#${this.plan.symbols.get(site)}"`);
5260
+ const near = site.trigger === "visible" ? this.refElement(site, scope) : void 0;
5261
+ if (near !== void 0) {
5262
+ this.html(" b-near=\"");
5263
+ this.code(anchor.scope);
5264
+ this.html(`:${near}"`);
5265
+ }
5266
+ this.html("></template>");
5267
+ }
5268
+ }
5269
+ /** The anchor of the first element of `scope` that a site reads through `ref`. */
5270
+ refElement(site, scope) {
5271
+ for (const read of site.reads) for (const ref of read.declaration.refs) {
5272
+ const index = ref.scope === scope ? this.plan.anchors.get(ref.element) : void 0;
5273
+ if (index !== void 0) return index;
4640
5274
  }
4641
5275
  }
4642
5276
  /** Emits the content of the component, without creating its scope. */
@@ -4735,15 +5369,19 @@ var Emitter = class {
4735
5369
  return;
4736
5370
  case "insert": {
4737
5371
  const anchor = this.anchor(scope, node);
4738
- const at = this.options.mode === "server" ? `, $$ctx, ${this.scopeVar(instanceScope(this.plan, scope))}` : "";
4739
- const value = this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
5372
+ const ast = node.expression.ast;
5373
+ const kind = ast.type === "Identifier" ? lookup(scope, ast.name)?.kind : void 0;
5374
+ const at = this.options.mode === "server" || kind === "prop" || kind === "props-rest" ? `, ${this.ctxArgument}, ${this.scopeVar(instanceScope(this.plan, scope))}` : "";
5375
+ const value = this.isPrimitiveInsert(node.expression) ? `$$b.insert(${this.expression(node.expression)})` : this.ready(`$$b.insert(${this.expression(node.expression)}${at})`);
5376
+ const text = literalText(node.expression.ast);
5377
+ const emitValue = () => text === void 0 ? this.code(value) : this.html(text);
4740
5378
  if (anchor && !this.plan.contents.has(node)) {
4741
5379
  this.html("<!--t");
4742
5380
  this.code(anchor.scope);
4743
5381
  this.html(`:${anchor.index}-->`);
4744
- this.code(value);
5382
+ emitValue();
4745
5383
  this.html("<!--/t-->");
4746
- } else this.code(value);
5384
+ } else emitValue();
4747
5385
  return;
4748
5386
  }
4749
5387
  case "element":
@@ -4760,18 +5398,22 @@ var Emitter = class {
4760
5398
  return;
4761
5399
  case "listener": {
4762
5400
  const anchor = this.anchor(scope, node);
4763
- const events = node.attributes.map((attribute) => this.eventEntry(attribute.event, attribute.modifiers, attribute.handler));
5401
+ const events = node.attributes.map((attribute) => this.eventEntry(attribute));
4764
5402
  this.html("<template b-b=\"");
4765
5403
  this.code(anchor.scope);
4766
5404
  this.html(`:${anchor.index}" b-listen="${node.target}" b-on="${events.join(" ")}"></template>`);
4767
5405
  return;
4768
5406
  }
4769
- default: this.emitBlock(node, scope);
5407
+ default: if (this.options.mode === "server" && DATA_SHAPED.has(node.kind)) {
5408
+ this.line("$$ctx.enter();");
5409
+ this.emitBlock(node, scope);
5410
+ this.line("$$ctx.leave();");
5411
+ } else this.emitBlock(node, scope);
4770
5412
  }
4771
5413
  }
4772
- eventEntry(event, modifiers, handler) {
5414
+ eventEntry({ event, modifiers, handler }) {
4773
5415
  const site = this.sitesByNode.get(handler.ast);
4774
- return `${[event, ...modifiers].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
5416
+ return `${[event, ...[.../* @__PURE__ */ new Set([...modifiers, ...site.modifiers ?? []])]].join(":")}=${this.plan.id}#${this.plan.symbols.get(site)}`;
4775
5417
  }
4776
5418
  emitRef(target, attribute, anchor) {
4777
5419
  const declaration = this.refTargets.get(attribute);
@@ -4827,14 +5469,23 @@ var Emitter = class {
4827
5469
  return `\`\${${this.scopeVar(instanceScope(this.plan, declaration.scope))}}:${slot}\``;
4828
5470
  }
4829
5471
  emitElement(node, scope) {
5472
+ const pageTitle = node.tag === "title" && this.headBlocks > 0;
5473
+ if (pageTitle && this.options.mode === "server") this.line(`${this.helper("title")}(${this.titleText(node)}, true);`);
5474
+ let spreadHandlers;
5475
+ if (this.options.mode === "server" && node.attributes.some((attribute) => attribute.kind === "spread")) {
5476
+ spreadHandlers = this.unique("on");
5477
+ this.line(`const ${spreadHandlers}: string[] = [];`);
5478
+ }
4830
5479
  this.html(`<${node.tag}`);
4831
5480
  if (this.hasScope(node.tag, staticClasses(node.attributes))) this.html(` ${this.plan.styles.attribute}`);
4832
5481
  const ownStyle = this.emitVariables(node);
4833
5482
  const events = [];
4834
5483
  let prefetch;
4835
5484
  const anchor = this.anchor(scope, node);
5485
+ const merged = node.attributes.some((attribute) => attribute.kind === "spread") ? [] : void 0;
4836
5486
  for (const attribute of node.attributes) {
4837
5487
  if (ownStyle && (attribute.kind === "static" || attribute.kind === "value") && attribute.name === "style") continue;
5488
+ if (merged && this.mergedAttribute(node, attribute, scope, merged)) continue;
4838
5489
  switch (attribute.kind) {
4839
5490
  case "static":
4840
5491
  this.html(attribute.value === true ? ` ${attribute.name}` : ` ${attribute.name}="${attribute.value}"`);
@@ -4854,13 +5505,13 @@ var Emitter = class {
4854
5505
  break;
4855
5506
  }
4856
5507
  case "spread":
4857
- this.code(`$$b.spread(${this.expression(attribute.value)})`);
5508
+ this.code(`$$b.spread(${this.expression(attribute.value)}${spreadHandlers ? `, ${spreadHandlers}` : ""})`);
4858
5509
  break;
4859
5510
  case "computed":
4860
5511
  this.code(`$$b.attribute(${this.expression(attribute.name)}, ${attribute.value === true ? "true" : this.expression(attribute.value)})`);
4861
5512
  break;
4862
5513
  case "event":
4863
- events.push(this.eventEntry(attribute.event, attribute.modifiers, attribute.handler));
5514
+ events.push(this.eventEntry(attribute));
4864
5515
  break;
4865
5516
  case "ref":
4866
5517
  if (anchor) this.emitRef(attribute.target, attribute, anchor);
@@ -4868,15 +5519,16 @@ var Emitter = class {
4868
5519
  case "prefetch": prefetch = attribute.strategy;
4869
5520
  }
4870
5521
  }
5522
+ if (merged) this.code(`$$b.spread($$b.mergeAttributes([${merged.join(", ")}])${spreadHandlers ? `, ${spreadHandlers}` : ""})`);
4871
5523
  if (anchor) {
4872
5524
  this.html(" b-b=\"");
4873
5525
  this.code(anchor.scope);
4874
5526
  this.html(`:${anchor.index}"`);
4875
5527
  }
4876
- if (events.length > 0) {
4877
- this.html(` b-on="${events.join(" ")}"`);
4878
- if (prefetch) this.html(` data-prefetch="${prefetch}"`);
4879
- }
5528
+ if (pageTitle) this.html(" b-t");
5529
+ if (spreadHandlers) this.code(`$$b.onAttribute(${spreadHandlers}, ${JSON.stringify(events.join(" "))})`);
5530
+ else if (events.length > 0) this.html(` b-on="${events.join(" ")}"`);
5531
+ if (events.length > 0 && prefetch) this.html(` data-prefetch="${prefetch}"`);
4880
5532
  this.html(">");
4881
5533
  if (VOID_ELEMENTS.has(node.tag)) return;
4882
5534
  this.nesting++;
@@ -4885,6 +5537,42 @@ var Emitter = class {
4885
5537
  this.html(`</${node.tag}>`);
4886
5538
  }
4887
5539
  /**
5540
+ * Adds an attribute of an element with spreads to `parts`, the objects
5541
+ * that its spread merges. Returns false for an attribute that stays apart,
5542
+ * such as a handler or a `ref`.
5543
+ */
5544
+ mergedAttribute(node, attribute, scope, parts) {
5545
+ switch (attribute.kind) {
5546
+ case "static":
5547
+ parts.push(`{ ${JSON.stringify(attribute.name)}: ${attribute.value === true ? "true" : JSON.stringify(decodeAttribute(attribute.value))} }`);
5548
+ return true;
5549
+ case "value":
5550
+ if (this.formAction(node, attribute.name, attribute.value, scope)) return false;
5551
+ parts.push(`{ ${JSON.stringify(attribute.name)}: ${this.expression(attribute.value)} }`);
5552
+ return true;
5553
+ case "computed":
5554
+ parts.push(`{ [${this.expression(attribute.name)}]: ${attribute.value === true ? "true" : this.expression(attribute.value)} }`);
5555
+ return true;
5556
+ case "spread":
5557
+ parts.push(this.expression(attribute.value));
5558
+ return true;
5559
+ default: return false;
5560
+ }
5561
+ }
5562
+ /**
5563
+ * The text of a `<title>`, as code: its one insert, or its text and the
5564
+ * inserts in it joined, such as `Items ({count})`.
5565
+ */
5566
+ titleText(node) {
5567
+ const [only] = node.children;
5568
+ if (only?.kind === "insert" && node.children.length === 1) return this.expression(only.expression);
5569
+ const parts = node.children.flatMap((child) => {
5570
+ if (child.kind === "insert") return [`(${this.expression(child.expression)} ?? '')`];
5571
+ return child.kind === "text" ? [JSON.stringify(decodeText(cleanText(child.value)))] : [];
5572
+ });
5573
+ return parts.length === 0 ? "\"\"" : parts.join(" + ");
5574
+ }
5575
+ /**
4888
5576
  * Renders a literal `class` value as the runtime renders it, without
4889
5577
  * building the value. A class with a condition is added when the condition
4890
5578
  * is truthy. No class leaves the attribute out.
@@ -4928,12 +5616,21 @@ var Emitter = class {
4928
5616
  emitChildren(nodes, scope) {
4929
5617
  if (nodes.length === 0) return;
4930
5618
  const name = this.unique("children");
4931
- this.line(`const ${name} = ${this.wait}(${this.async}() => {`);
5619
+ if (this.options.mode === "server") {
5620
+ this.line(`const ${name} = $$b.children(${this.scopeVar(instanceScope(this.plan, scope))}, async ($$ctx) => {`);
5621
+ this.line(`let $$html = '';`);
5622
+ this.atTopLevel(() => this.emitNodes(nodes, scope));
5623
+ this.flush();
5624
+ this.line("return $$html;");
5625
+ this.close("});");
5626
+ return name;
5627
+ }
5628
+ this.line(`const ${name} = $$b.children(${this.scopeVar(instanceScope(this.plan, scope))}, () => {`);
4932
5629
  this.line(`let $$html = '';`);
4933
5630
  this.atTopLevel(() => this.emitNodes(nodes, scope));
4934
5631
  this.flush();
4935
- this.line("return $$b.raw($$html);");
4936
- this.close("})();");
5632
+ this.line("return $$html;");
5633
+ this.close("});");
4937
5634
  return name;
4938
5635
  }
4939
5636
  props(attributes, scope, extra = []) {
@@ -5006,7 +5703,7 @@ var Emitter = class {
5006
5703
  if (this.hasScope(void 0, staticClasses(node.attributes))) extra.push(`${JSON.stringify(this.plan.styles.attribute)}: true`);
5007
5704
  const anchor = this.anchor(scope, node);
5008
5705
  if (anchor) extra.push(`"b-b": \`\${${anchor.scope}}:${anchor.index}\``);
5009
- const events = node.attributes.flatMap((attribute) => attribute.kind === "event" ? [this.eventEntry(attribute.event, attribute.modifiers, attribute.handler)] : []);
5706
+ const events = node.attributes.flatMap((attribute) => attribute.kind === "event" ? [this.eventEntry(attribute)] : []);
5010
5707
  if (events.length > 0) extra.push(`"b-on": ${JSON.stringify(events.join(" "))}`);
5011
5708
  let attributes = node.attributes.filter((attribute) => attribute.kind !== "event");
5012
5709
  const { variables } = this.plan.styles;
@@ -5043,7 +5740,9 @@ var Emitter = class {
5043
5740
  this.html("<!--P");
5044
5741
  this.code(this.scopeVar(body));
5045
5742
  this.html("-->");
5743
+ this.headBlocks += block.kind === "head" ? 1 : 0;
5046
5744
  this.atTopLevel(() => this.emitBody(block.body, false));
5745
+ this.headBlocks -= block.kind === "head" ? 1 : 0;
5047
5746
  this.html("<!--/P-->");
5048
5747
  this.flush();
5049
5748
  this.line("return $$html;");
@@ -5051,13 +5750,35 @@ var Emitter = class {
5051
5750
  this.line(`${this.helper(block.kind === "head" ? "head" : "portal")}(${name});`);
5052
5751
  }
5053
5752
  /**
5054
- * Writes the fallback of `#loading` and renders its body after the rest of
5055
- * the page, so data that the body waits for does not hold up the page.
5753
+ * Renders a `#loading` block. When the memos that its body reads are
5754
+ * ready, and the body waits for nothing else, the body renders in place,
5755
+ * in the ID space of its boundary. Otherwise the fallback renders, and the
5756
+ * body renders after the rest of the page, so data that the body waits
5757
+ * for does not hold up the page. The memos that the body reads with
5758
+ * `await` are ready here, because the render around the block waited for
5759
+ * them.
5056
5760
  */
5057
5761
  emitLoading(block, scope) {
5058
5762
  const boundary = this.unique("boundary");
5059
5763
  const body = this.plan.bodyScopes.get(block.body);
5764
+ const memos = awaitedMemos(this.plan, body, this.blocking).filter((declaration) => !this.inline.has(declaration));
5765
+ const names = memos.map((declaration) => promiseName(declaration.name));
5766
+ const inPlace = !mayWait(this.plan, block.body.children);
5767
+ if (inPlace && memos.length === 0) {
5768
+ this.line("$$ctx.enter();");
5769
+ this.emitBody(block.body);
5770
+ this.line("$$ctx.leave();");
5771
+ return;
5772
+ }
5060
5773
  this.line(`const ${boundary} = $$ctx.boundary();`);
5774
+ if (inPlace) {
5775
+ this.line(`if ($$b.settled([${names.join(", ")}])) {`);
5776
+ this.line(`$$ctx.enter(${boundary});`);
5777
+ for (const declaration of memos) this.line(`const ${declaration.name} = $$b.read(${promiseName(declaration.name)});`);
5778
+ this.emitBody(block.body);
5779
+ this.line("$$ctx.leave();");
5780
+ this.close("} else {");
5781
+ }
5061
5782
  this.open(scope, block);
5062
5783
  this.html("<!--l");
5063
5784
  this.code(boundary);
@@ -5071,7 +5792,45 @@ var Emitter = class {
5071
5792
  this.end(block);
5072
5793
  this.line(`$$ctx.defer(${boundary}, async ($$ctx) => {`);
5073
5794
  this.line(`let $$html = '';`);
5074
- for (const declaration of awaitedMemos(this.plan, body, this.blocking)) this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5795
+ for (const declaration of memos) this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5796
+ this.emitBody(block.body);
5797
+ this.flush();
5798
+ this.line("return $$html;");
5799
+ this.close("});");
5800
+ if (inPlace) this.close();
5801
+ }
5802
+ /**
5803
+ * Renders the fallback of a `#defer` block between the markers of a
5804
+ * boundary, and a template that the loader starts when the trigger fires.
5805
+ * The body renders only in the request for it, and replaces the fallback
5806
+ * as a `#loading` body does.
5807
+ */
5808
+ emitDefer(block, scope) {
5809
+ const boundary = this.unique("boundary");
5810
+ const anchor = this.anchor(scope, block);
5811
+ const body = this.plan.bodyScopes.get(block.body);
5812
+ this.line(`const ${boundary} = $$ctx.boundary();`);
5813
+ this.html("<template b-b=\"");
5814
+ this.code(anchor.scope);
5815
+ this.html(`:${anchor.index}" b-defer="${block.trigger}:`);
5816
+ this.code(boundary);
5817
+ this.html(":");
5818
+ this.code("$$ctx.base()");
5819
+ this.html("\"></template><!--l");
5820
+ this.code(boundary);
5821
+ this.html("-->");
5822
+ if (block.fallback) {
5823
+ this.line("{");
5824
+ this.emitBody(block.fallback);
5825
+ this.close();
5826
+ }
5827
+ this.html("<!--/l-->");
5828
+ this.line(`$$ctx.deferBlock(${boundary}, ${anchor.scope} + ${JSON.stringify(`:${anchor.index}`)}, async ($$ctx) => {`);
5829
+ this.line(`let $$html = '';`);
5830
+ for (const declaration of awaitedMemos(this.plan, body, this.blocking)) {
5831
+ if (this.inline.has(declaration)) continue;
5832
+ this.line(`const ${declaration.name} = ${this.memoValue(declaration.name)};`);
5833
+ }
5075
5834
  this.emitBody(block.body);
5076
5835
  this.flush();
5077
5836
  this.line("return $$html;");
@@ -5163,9 +5922,25 @@ var Emitter = class {
5163
5922
  this.code(anchor.scope);
5164
5923
  this.html(`:${anchor.index}" b-client="${block.trigger}=${this.plan.id}#k${body.id}"></template>`);
5165
5924
  this.open(scope, block);
5925
+ if (block.fallback) {
5926
+ this.line("{");
5927
+ this.emitBody(block.fallback);
5928
+ this.close();
5929
+ }
5166
5930
  this.end(block);
5167
5931
  return;
5168
5932
  }
5933
+ case "defer":
5934
+ if (this.options.mode === "server") this.emitDefer(block, scope);
5935
+ else {
5936
+ this.line(`$$b.deferInBrowser(${JSON.stringify(this.plan.id)});`);
5937
+ if (block.fallback) {
5938
+ this.line("{");
5939
+ this.emitBody(block.fallback);
5940
+ this.close();
5941
+ }
5942
+ }
5943
+ return;
5169
5944
  case "loading":
5170
5945
  if (this.options.mode === "server") {
5171
5946
  this.emitLoading(block, scope);
@@ -5315,7 +6090,7 @@ function serverFunctions(plan) {
5315
6090
  function generateServer(file, plan) {
5316
6091
  const model = plan.graph.model;
5317
6092
  const patch = new Patch(file.source);
5318
- addValueEdits(patch, file, model.sites);
6093
+ addValueEdits(patch, file, model.sites, "server", plainValues(plan, blockingMemos(plan)));
5319
6094
  addEventEdits(patch, model);
5320
6095
  const source = (node) => patch.slice(node.start, node.end);
5321
6096
  const header = ["import * as $$b from 'brumate/server';"];
@@ -5395,6 +6170,8 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
5395
6170
  case "for":
5396
6171
  case "repeat":
5397
6172
  case "loading":
6173
+ case "client":
6174
+ case "defer":
5398
6175
  componentNames(node.body.children, names);
5399
6176
  componentNames(node.fallback?.children ?? [], names);
5400
6177
  break;
@@ -5405,7 +6182,6 @@ function componentNames(nodes, names = /* @__PURE__ */ new Set()) {
5405
6182
  case "key":
5406
6183
  case "portal":
5407
6184
  case "head":
5408
- case "client":
5409
6185
  case "offscreen": componentNames(node.body.children, names);
5410
6186
  }
5411
6187
  return names;
@@ -5450,6 +6226,10 @@ function clientModuleScript(file, plan) {
5450
6226
  }
5451
6227
  return result;
5452
6228
  }
6229
+ /** True if the render of the component awaits a promise, outside memos and the code of handlers. */
6230
+ function awaitsPromise(plan) {
6231
+ return plan.graph.model.sites.some((site) => site.awaits && site.kind !== "memo" && site.kind !== "function" && !SKIPPED_SITES.has(site.kind));
6232
+ }
5453
6233
  /**
5454
6234
  * Generates the render module: the component's render function for the
5455
6235
  * client, used when a parent renders it inside a block that changes.
@@ -5491,6 +6271,17 @@ function generateRender(file, plan) {
5491
6271
  });
5492
6272
  const generics = file.generics ? `<${file.generics}>` : "";
5493
6273
  emitter.line(`export default function ${plan.name}${generics}($$props: ${propsType(file)}): string {`);
6274
+ if (awaitsPromise(plan)) {
6275
+ emitter.line(`throw new Error(${JSON.stringify(`${plan.name} awaits a promise in its script or markup, so only the server can render it`)});`);
6276
+ emitter.close();
6277
+ return [
6278
+ ...header,
6279
+ ...moduleBody,
6280
+ "",
6281
+ ...emitter.lines,
6282
+ ""
6283
+ ].join("\n");
6284
+ }
5494
6285
  emitter.line(`let $$html = '';`);
5495
6286
  emitter.line(`const ${emitter.scopeVar(model.component)} = $$b.createScope(${model.component.id}, undefined, ${JSON.stringify(plan.id)});`);
5496
6287
  emitter.emitComponentContent(setup);
@@ -5654,6 +6445,15 @@ var Rewriter = class {
5654
6445
  if (value) patch.replace(node.start, node.end, value);
5655
6446
  return;
5656
6447
  }
6448
+ case "AwaitExpression": {
6449
+ const reference = target(node.argument);
6450
+ if (reference?.await) {
6451
+ const value = this.value(reference.declaration, scopeVar, base);
6452
+ patch.replace(node.start, node.end, value ?? reference.declaration.name);
6453
+ return;
6454
+ }
6455
+ break;
6456
+ }
5657
6457
  case "Property":
5658
6458
  if (node.shorthand && node.value.type === "Identifier") {
5659
6459
  const reference = target(node.value);
@@ -5849,8 +6649,8 @@ var ClientGenerator = class {
5849
6649
  lines.push(code);
5850
6650
  }
5851
6651
  generate() {
5852
- this.checkSupport();
5853
6652
  this.collectRenders();
6653
+ this.checkSupport();
5854
6654
  this.placeCode();
5855
6655
  this.emitFunctions();
5856
6656
  this.emitRoots();
@@ -5872,11 +6672,13 @@ var ClientGenerator = class {
5872
6672
  if (used.size > 0) parts[name] = `${[...used].map((index) => `import * as $$m${index} from ${JSON.stringify(this.shared.specifiers[index])};`).join("\n")}\n${code}`;
5873
6673
  }
5874
6674
  const refresh = this.refreshTable();
6675
+ const tries = this.triesTable();
5875
6676
  const table = [
5876
6677
  `export const id = ${JSON.stringify(this.plan.id)};`,
5877
6678
  `export const props = ${this.propsMap()};`,
5878
6679
  `export const g = ${this.table()};`,
5879
- ...refresh ? [`export const refresh = ${refresh};`] : []
6680
+ ...refresh ? [`export const refresh = ${refresh};`] : [],
6681
+ ...tries ? [`export const t = ${tries};`] : []
5880
6682
  ];
5881
6683
  const clientCode = names.length > 0;
5882
6684
  if (merged || !clientCode) {
@@ -6052,7 +6854,12 @@ var ClientGenerator = class {
6052
6854
  return lines.join("\n");
6053
6855
  }
6054
6856
  checkSupport() {
6055
- for (const site of this.model.sites) if (this.live.has(site) && site.kind === "tag" && !site.owner?.keyed) this.error("A dynamic tag that changes on the client is not supported yet", site.range);
6857
+ const rendered = this.renderedScopes();
6858
+ for (const site of this.model.sites) {
6859
+ const live = this.live.has(site);
6860
+ if (live && site.kind === "tag" && !site.owner?.keyed) this.error("A dynamic tag that changes on the client is not supported yet", site.range);
6861
+ if (site.awaits && site.kind !== "memo" && !DEFERRED_SITES.has(site.kind) && (live || rendered.some((scope) => isWithin(site.scope, scope)))) this.error(live ? "Code that the browser updates can await only a memo. Load the promise in a memo instead" : "Markup that the browser renders can await only a memo. Load the promise in a memo instead", site.range);
6862
+ }
6056
6863
  }
6057
6864
  clientReads() {
6058
6865
  const reads = /* @__PURE__ */ new Set();
@@ -6154,7 +6961,7 @@ var ClientGenerator = class {
6154
6961
  const symbol = this.plan.symbols.get(site);
6155
6962
  if (!symbol) continue;
6156
6963
  const base = instanceScope(this.plan, site.scope);
6157
- let code = this.rewriter.rewrite(site, "$$s", base);
6964
+ let code = this.withTemplates(site, this.rewriter.rewrite(site, "$$s", base));
6158
6965
  if (site.node.type === "FunctionExpression" && unmarked(code).trimStart().startsWith("(")) code = `function ${code}`;
6159
6966
  this.part = symbol;
6160
6967
  if (site.kind === "client") this.emit(`export function ${symbol}($$s) {\n $$b.effect($$s, ${JSON.stringify(symbol)}, ${code});\n}`);
@@ -6206,7 +7013,9 @@ var ClientGenerator = class {
6206
7013
  const slot = slotIndex(this.plan, node.declaration);
6207
7014
  if (slot !== -1) {
6208
7015
  const value = site.awaits ? `(async () => (${expression()}))()` : expression();
6209
- this.emit(`export function ${name("m")}($$s) {\n $$b.memo($$s, ${slot}, () => ${value});\n}`);
7016
+ const timing = node.declaration.timing;
7017
+ const call = timing ? `$$b.timed($$s, ${slot}, ${timing.ms}, ${timing.kind === "throttled"}, () => ${value})` : `$$b.memo($$s, ${slot}, () => ${value})`;
7018
+ this.emit(`export function ${name("m")}($$s) {\n ${call};\n}`);
6210
7019
  }
6211
7020
  break;
6212
7021
  }
@@ -6272,8 +7081,16 @@ var ClientGenerator = class {
6272
7081
  this.emit(`export function ${name("u")}($$s) {\n $$b.prop($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${expression()});\n}`);
6273
7082
  return;
6274
7083
  }
6275
- if (attribute.kind === "spread") this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${expression()});\n}`);
6276
- else if (attribute.kind === "value") {
7084
+ if (attribute.kind === "spread") {
7085
+ const own = owner.attributes.flatMap((item) => item.kind === "static" || item.kind === "value" ? [item.name] : []);
7086
+ if (this.plan.styles.css) own.push(this.plan.styles.attribute, "style");
7087
+ const parts = owner.attributes.flatMap((item) => {
7088
+ if (item === attribute) return [expression()];
7089
+ return item.kind === "static" ? [`{ ${JSON.stringify(item.name)}: ${item.value === true ? "true" : JSON.stringify(decodeAttribute(item.value))} }`] : [];
7090
+ });
7091
+ const value = parts.length > 1 ? `$$b.mergeAttributes([${parts.join(", ")}])` : expression();
7092
+ this.emit(`export function ${name("u")}($$s) {\n $$b.attrs($$s, ${anchor}, ${value}, ${JSON.stringify(own)});\n}`);
7093
+ } else if (attribute.kind === "value") {
6277
7094
  const value = (attribute.name === "class" ? classes(attribute.value.ast) : void 0) ?? expression();
6278
7095
  this.emit(`export function ${name("u")}($$s) {\n $$b.attr($$s, ${anchor}, ${JSON.stringify(attribute.name)}, ${value});\n}`);
6279
7096
  }
@@ -6384,7 +7201,7 @@ var ClientGenerator = class {
6384
7201
  }
6385
7202
  for (const scope of this.model.scopes) {
6386
7203
  const block = scope.block;
6387
- const clientOnly = block?.kind === "client" || block?.kind === "portal" && block.target !== void 0 || block?.kind === "try" && this.plan.anchors.has(block);
7204
+ const clientOnly = block?.kind === "client" && scope.body === block.body || block?.kind === "portal" && block.target !== void 0 || block?.kind === "try" && this.plan.anchors.has(block);
6388
7205
  if (scope.kind === "body" && block && clientOnly && scope.body) this.renders.set(scope, {
6389
7206
  body: scope.body,
6390
7207
  block
@@ -6427,7 +7244,8 @@ var ClientGenerator = class {
6427
7244
  }
6428
7245
  if (block.kind === "client") {
6429
7246
  const anchor = this.plan.anchors.get(block);
6430
- this.emit(`export function k${scope.id}($$s) {\n $$b.fill($$s, ${anchor}, r${scope.id});\n}`);
7247
+ const fallback = block.fallback ? `, [${this.kinds([block.fallback]).join(", ")}]` : "";
7248
+ this.emit(`export function k${scope.id}($$s) {\n $$b.fill($$s, ${anchor}, r${scope.id}${fallback});\n}`);
6431
7249
  }
6432
7250
  }
6433
7251
  }
@@ -6438,7 +7256,8 @@ var ClientGenerator = class {
6438
7256
  */
6439
7257
  withTemplates(site, code) {
6440
7258
  const templates = [];
6441
- for (const callee of site.calls) {
7259
+ const used = [...site.calls, ...site.reads.map((read) => read.declaration).filter((item) => item.kind === "template")];
7260
+ for (const callee of used) {
6442
7261
  if (callee.kind !== "template") continue;
6443
7262
  const template = this.model.scopes.find((item) => item.template?.name === callee.name && item.parent === callee.scope);
6444
7263
  for (const item of template ? this.inside(template) : []) if (!templates.includes(item)) templates.push(item);
@@ -6479,6 +7298,24 @@ var ClientGenerator = class {
6479
7298
  * The memos to load again when a server function calls `refresh(fn)`:
6480
7299
  * by the ID of `fn`, the scope kind and the update of each memo.
6481
7300
  */
7301
+ /**
7302
+ * The `#try` blocks that catch errors of client code, by the scope kinds
7303
+ * inside their bodies: the kind of the scope that holds the block, the
7304
+ * anchor of the block, the render functions of the body and the `#catch`
7305
+ * body, and the kinds of both bodies.
7306
+ */
7307
+ triesTable() {
7308
+ const entries = [];
7309
+ for (const scope of this.model.scopes) {
7310
+ const block = scope.block;
7311
+ if (block?.kind !== "try" || scope.body !== block.body || !this.plan.anchors.has(block) || !tryCatchesClient(this.model, block)) continue;
7312
+ const owner = instanceScope(this.plan, scope.parent);
7313
+ const fallback = this.plan.bodyScopes.get(block.fallback);
7314
+ const entry = `[${owner.id}, ${this.plan.anchors.get(block)}, ${JSON.stringify(`r${scope.id}`)}, ${JSON.stringify(`r${fallback.id}`)}, [${this.kinds(blockBodies(block)).join(", ")}]]`;
7315
+ for (const inside of this.model.scopes) if (isWithin(inside, scope)) entries.push(`${inside.id}: ${entry}`);
7316
+ }
7317
+ return entries.length > 0 ? `{ ${entries.join(", ")} }` : void 0;
7318
+ }
6482
7319
  refreshTable() {
6483
7320
  const table = /* @__PURE__ */ new Map();
6484
7321
  for (const node of this.plan.graph.nodes) {
@@ -6706,7 +7543,7 @@ function compile(source, options = {}) {
6706
7543
  const plan = createPlan(file, graph, options.path, options.hideNames);
6707
7544
  const styleErrors = [...plan.styles.diagnostics, ...plan.diagnostics].filter((diagnostic) => diagnostic.severity === "error");
6708
7545
  if (styleErrors.length > 0) fail(styleErrors);
6709
- const captures = checkCaptures(file, plan);
7546
+ const captures = [...checkCaptures(file, plan), ...options.envImport ? checkEnv(file, plan, options.envImport) : []];
6710
7547
  if (captures.length > 0) fail(captures);
6711
7548
  const shared = sharedContext(origin, modules, calls, options.path ?? filename);
6712
7549
  const client = generateClient(file, plan, options.merge, shared);
@@ -6923,4 +7760,4 @@ function inspect(source, options = {}) {
6923
7760
  //#endregion
6924
7761
  export { summarize as A, resolveFromDisk as C, analyzeProjectProps as D, analyzeProject as E, analyze$1 as F, isWithin as I, lookup as L, buildGraph as M, BrumateError as N, forEachNode as O, getLocation as P, isReactiveModule as S, unmarked as T, getComponentName as _, CompileError as a, generateShared as b, generateClient as c, instanceScope as d, slotIndex as f, functionId as g, createPlan as h, scopeLabel as i, parse$1 as j, resolveRelative as k, generateRender as l, clientState as m, inspect as n, compile as o, blockBodies as p, report as r, DEFAULT_MERGE as s, formatReport as t, generateServer as u, hash as v, builtin as w, sharedSites as x, SHARED_QUERY as y };
6925
7762
 
6926
- //# sourceMappingURL=inspect-CRZlO11T.js.map
7763
+ //# sourceMappingURL=inspect-BJtACnQp.js.map