brumate 0.3.0 → 0.4.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 (122) hide show
  1. package/README.md +2 -2
  2. package/check.d.ts +49 -0
  3. package/dist/{boot-C25Sa6vq.d.ts → boot-DLlRmD9z.d.ts} +8 -10
  4. package/dist/cli.js +275 -15
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-BvDsC6Qr.js +3463 -0
  7. package/dist/client-BvDsC6Qr.js.map +1 -0
  8. package/dist/{client-D0CqSxoO.d.ts → client-DBwL2wKQ.d.ts} +390 -181
  9. package/dist/{client-routes-JTbGtukf.js → client-routes-BtGpYCef.js} +60 -30
  10. package/dist/client-routes-BtGpYCef.js.map +1 -0
  11. package/dist/{cookies-BzllthiF.js → cookies-Cnbf4w-S.js} +14 -7
  12. package/dist/cookies-Cnbf4w-S.js.map +1 -0
  13. package/dist/{defer-BbD7JQhj.js → defer-CKWZLv2K.js} +4 -4
  14. package/dist/defer-CKWZLv2K.js.map +1 -0
  15. package/dist/{devtools-CQgD7NPB.js → devtools-4uTPwR_v.js} +56 -82
  16. package/dist/devtools-4uTPwR_v.js.map +1 -0
  17. package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-Be9pxYgv.js} +397 -333
  18. package/dist/devtools-panel-Be9pxYgv.js.map +1 -0
  19. package/dist/{events-CSs7OwIC.js → events-LgLdp1R7.js} +34 -5
  20. package/dist/events-LgLdp1R7.js.map +1 -0
  21. package/dist/features-CHY5Ekku.js +30 -0
  22. package/dist/features-CHY5Ekku.js.map +1 -0
  23. package/dist/files-WW4RlajL.js +506 -0
  24. package/dist/files-WW4RlajL.js.map +1 -0
  25. package/dist/{forms-Cl21hkHt.d.ts → forms-j1xPAR14.d.ts} +3 -3
  26. package/dist/{forms-Bg-CwGqX.js → forms-nXK7-Lv_.js} +78 -44
  27. package/dist/forms-nXK7-Lv_.js.map +1 -0
  28. package/dist/highlight.js +31 -22
  29. package/dist/highlight.js.map +1 -1
  30. package/dist/{html-mNTKzaDD.js → html-BtKRyi7g.js} +86 -22
  31. package/dist/html-BtKRyi7g.js.map +1 -0
  32. package/dist/{html-Bq1rFxX_.d.ts → html-Bw9Qwu6F.d.ts} +20 -5
  33. package/dist/index.d.ts +96 -10
  34. package/dist/index.js +639 -104
  35. package/dist/index.js.map +1 -1
  36. package/dist/{inspect-BHpOw1LF.js → inspect-Y6y4uNZp.js} +3751 -676
  37. package/dist/inspect-Y6y4uNZp.js.map +1 -0
  38. package/dist/{loader-Dos_3NP0.js → loader-BjKGJzLN.js} +20 -14
  39. package/dist/loader-BjKGJzLN.js.map +1 -0
  40. package/dist/logo-DQ_OYhBi.js +10 -0
  41. package/dist/logo-DQ_OYhBi.js.map +1 -0
  42. package/dist/{navigate-O78d_zGN.js → navigate-CfOr-TRF.js} +94 -31
  43. package/dist/navigate-CfOr-TRF.js.map +1 -0
  44. package/dist/nesting-DA5vJw9X.js +265 -0
  45. package/dist/nesting-DA5vJw9X.js.map +1 -0
  46. package/dist/{produce-Doc91GkX.js → produce-B7X9ori9.js} +137 -9
  47. package/dist/produce-B7X9ori9.js.map +1 -0
  48. package/dist/{produce-D0V0ICkz.d.ts → produce-DIgHBVwL.d.ts} +39 -5
  49. package/dist/{rpc-ygMRPmN4.js → rpc-Q-XkLwFh.js} +11 -6
  50. package/dist/rpc-Q-XkLwFh.js.map +1 -0
  51. package/dist/runtime/batch.js +9 -7
  52. package/dist/runtime/batch.js.map +1 -1
  53. package/dist/runtime/client.d.ts +4 -4
  54. package/dist/runtime/client.js +4 -4
  55. package/dist/runtime/devtools.d.ts +11 -29
  56. package/dist/runtime/devtools.js +3 -1
  57. package/dist/runtime/env.js +14 -2
  58. package/dist/runtime/env.js.map +1 -1
  59. package/dist/runtime/events.d.ts +23 -1
  60. package/dist/runtime/events.js +1 -1
  61. package/dist/runtime/forms.d.ts +2 -2
  62. package/dist/runtime/forms.js +1 -1
  63. package/dist/runtime/hot.d.ts +1 -1
  64. package/dist/runtime/hot.js +5 -2
  65. package/dist/runtime/hot.js.map +1 -1
  66. package/dist/runtime/html.d.ts +2 -2
  67. package/dist/runtime/html.js +1 -1
  68. package/dist/runtime/loader.d.ts +2 -2
  69. package/dist/runtime/loader.js +2 -2
  70. package/dist/runtime/routes.js +4 -1
  71. package/dist/runtime/routes.js.map +1 -1
  72. package/dist/runtime/server.d.ts +5 -5
  73. package/dist/runtime/server.js +5 -5
  74. package/dist/runtime/signals.d.ts +38 -1
  75. package/dist/runtime/signals.js +33 -1
  76. package/dist/runtime/signals.js.map +1 -1
  77. package/dist/runtime/static-loader.d.ts +2 -2
  78. package/dist/runtime/static-loader.js +1 -1
  79. package/dist/runtime/testing.d.ts +18 -3
  80. package/dist/runtime/testing.js +150 -33
  81. package/dist/runtime/testing.js.map +1 -1
  82. package/dist/{server-DuFYRXrd.d.ts → server-BvPIg9pT.d.ts} +84 -22
  83. package/dist/{server-CxVDYE_V.js → server-DjyOVJtJ.js} +598 -164
  84. package/dist/server-DjyOVJtJ.js.map +1 -0
  85. package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-BGgdp_Y5.d.ts} +2 -2
  86. package/dist/{static-loader-nZssh66R.js → static-loader-BZR17hSw.js} +78 -99
  87. package/dist/static-loader-BZR17hSw.js.map +1 -0
  88. package/dist/{stream-DCYZO4IF.js → stream-BP5AVmg5.js} +102 -16
  89. package/dist/stream-BP5AVmg5.js.map +1 -0
  90. package/dist/vite.d.ts +13 -20
  91. package/dist/vite.js +1890 -548
  92. package/dist/vite.js.map +1 -1
  93. package/elements.d.ts +951 -0
  94. package/forms/forms.brm.ts +3 -3
  95. package/package.json +12 -3
  96. package/skills/brumate/SKILL.md +58 -0
  97. package/skills/brumate/references/errors.md +2078 -0
  98. package/skills/brumate/references/events.md +117 -0
  99. package/skills/brumate/references/signals.md +61 -0
  100. package/skills/brumate/references/state.md +235 -0
  101. package/skills/brumate/references/syntax.md +250 -0
  102. package/types.d.ts +4 -4
  103. package/dist/client-BD6XT-s5.js +0 -1968
  104. package/dist/client-BD6XT-s5.js.map +0 -1
  105. package/dist/client-routes-JTbGtukf.js.map +0 -1
  106. package/dist/cookies-BzllthiF.js.map +0 -1
  107. package/dist/defer-BbD7JQhj.js.map +0 -1
  108. package/dist/devtools-CQgD7NPB.js.map +0 -1
  109. package/dist/devtools-panel-BVB-W5q4.js.map +0 -1
  110. package/dist/events-CSs7OwIC.js.map +0 -1
  111. package/dist/files-BXSSrQgc.js +0 -205
  112. package/dist/files-BXSSrQgc.js.map +0 -1
  113. package/dist/forms-Bg-CwGqX.js.map +0 -1
  114. package/dist/html-mNTKzaDD.js.map +0 -1
  115. package/dist/inspect-BHpOw1LF.js.map +0 -1
  116. package/dist/loader-Dos_3NP0.js.map +0 -1
  117. package/dist/navigate-O78d_zGN.js.map +0 -1
  118. package/dist/produce-Doc91GkX.js.map +0 -1
  119. package/dist/rpc-ygMRPmN4.js.map +0 -1
  120. package/dist/server-CxVDYE_V.js.map +0 -1
  121. package/dist/static-loader-nZssh66R.js.map +0 -1
  122. package/dist/stream-DCYZO4IF.js.map +0 -1
@@ -1,11 +1,12 @@
1
- import { n as MODIFIERS } from "./events-CSs7OwIC.js";
2
- import { _ as rawHTML, d as handlerEntry, f as insertValue, h as onAttribute, l as escape, n as actionAttributes, o as bindEntry, p as isRaw, t as VOID_ELEMENTS, u as escapeAttribute, v as spread$1, y as styleElement } from "./html-mNTKzaDD.js";
3
- import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-BzllthiF.js";
4
- import { a as plugins, c as functionReferences, i as callPlugins, o as serialOptions, r as toChunkStream, s as syncPlugins, t as STREAM_TYPE } from "./stream-DCYZO4IF.js";
5
- import { a as SlotReference, d as parseId, i as FunctionReference, n as Binding, o as isAsyncIterable, r as ElementReference, s as isBinding } from "./produce-Doc91GkX.js";
1
+ import { n as closesParagraph, r as firstTag } from "./nesting-DA5vJw9X.js";
2
+ import { n as MODIFIERS } from "./events-LgLdp1R7.js";
3
+ import { C as styleElement, S as spread$1, _ as onAttribute, d as escapeAttribute, f as handlerEntry, h as isRaw, n as VOID_ELEMENTS, p as insertValue, r as actionAttributes, s as bindEntry, u as escape, x as rawHTML, y as ownValue } from "./html-BtKRyi7g.js";
4
+ import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Cnbf4w-S.js";
5
+ import { a as plugins, c as functionReferences, i as callPlugins, o as serialOptions, r as toChunkStream, s as syncPlugins, t as STREAM_TYPE } from "./stream-BP5AVmg5.js";
6
+ import { a as ElementReference, b as parseId, c as PARTS, d as SlotReference, f as addEntryHandlers, g as isSlotReference, i as ChildrenReference, l as PropPromise, m as isBinding, n as Binding, o as FunctionReference, p as isAsyncIterable, r as CHILDREN_REF, s as MemoError } from "./produce-B7X9ori9.js";
6
7
  import { n as serverSecrets } from "./secrets-BxagsJxJ.js";
7
8
  import "./context-CTiSzQRc.js";
8
- import { a as applyIntent, d as formValues, f as formatPath, m as groupIssues, p as getAt, r as INTENT, v as parseIntent, y as parsePath } from "./forms-Bg-CwGqX.js";
9
+ import { a as applyIntent, d as formatPath, f as getAt, m as groupIssues, r as INTENT, u as formValues, v as parseIntent, y as parsePath } from "./forms-nXK7-Lv_.js";
9
10
  import { crossSerialize, crossSerializeStream, fromJSON, toJSON } from "seroval";
10
11
  //#region src/runtime/request.ts
11
12
  function noTrace() {}
@@ -434,7 +435,14 @@ function cached(fn, options) {
434
435
  const kept = await store.get(key);
435
436
  if (kept) {
436
437
  const entry = JSON.parse(kept);
437
- if (entry.expires > Date.now() && tags.every((tag) => entry.tags[tag] === versions[tag])) return fromJSON(entry.value, { plugins: syncPlugins });
438
+ let fresh = entry.expires > Date.now();
439
+ if (fresh) {
440
+ for (const tag of tags) if (entry.tags[tag] !== versions[tag]) {
441
+ fresh = false;
442
+ break;
443
+ }
444
+ }
445
+ if (fresh) return fromJSON(entry.value, { plugins: syncPlugins });
438
446
  }
439
447
  let run = running$1.get(key);
440
448
  if (!run) {
@@ -462,9 +470,11 @@ function cacheStore() {
462
470
  /** The versions of tags. A tag that was never revalidated has version `0`. */
463
471
  async function tagVersions(tags) {
464
472
  const versions = {};
465
- await Promise.all([...tags].map(async (tag) => {
473
+ const reads = [];
474
+ for (const tag of tags) reads.push((async () => {
466
475
  versions[tag] = await store.get(`brumate:tag:${tag}`) ?? "0";
467
- }));
476
+ })());
477
+ await Promise.all(reads);
468
478
  return versions;
469
479
  }
470
480
  let revalidations = 0;
@@ -475,7 +485,9 @@ let revalidations = 0;
475
485
  */
476
486
  async function revalidate(...tags) {
477
487
  const version = `${Date.now()}.${revalidations++}`;
478
- await Promise.all(tags.map((tag) => store.set(`brumate:tag:${tag}`, version, TAG_AGE)));
488
+ const writes = [];
489
+ for (const tag of tags) writes.push(store.set(`brumate:tag:${tag}`, version, TAG_AGE));
490
+ await Promise.all(writes);
479
491
  }
480
492
  //#endregion
481
493
  //#region src/runtime/router.ts
@@ -494,7 +506,7 @@ function wrap(view, wrapper) {
494
506
  } : view;
495
507
  }
496
508
  /** The layout of a folder, or undefined when it has none. */
497
- function wrapperOf(node, segments, index, params, path) {
509
+ function findWrapper(node, segments, index, params, path) {
498
510
  return node.layout ? {
499
511
  layout: node.layout,
500
512
  key: key(path, "_layout", params),
@@ -568,8 +580,12 @@ function matchNode(node, segments, index, params, path = "") {
568
580
  ...inner.view,
569
581
  loading: node.loading
570
582
  } : inner.view;
571
- const wrapper = wrapperOf(node, segments, index, params, path);
572
- const errors = wrapper ? inner.errors.map((view) => wrap(view, wrapper)) : inner.errors;
583
+ const wrapper = findWrapper(node, segments, index, params, path);
584
+ let errors = inner.errors;
585
+ if (wrapper) {
586
+ errors = [];
587
+ for (const view of inner.errors) errors.push(wrap(view, wrapper));
588
+ }
573
589
  if (node.error) errors.push(errorIn(node.error, wrapper, params, path));
574
590
  return {
575
591
  view: wrap(content, wrapper),
@@ -588,7 +604,8 @@ const missingPage = () => {
588
604
  function matchRoute(tree, pathname) {
589
605
  let segments;
590
606
  try {
591
- segments = pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment));
607
+ segments = [];
608
+ for (const segment of pathname.split("/")) if (segment) segments.push(decodeURIComponent(segment));
592
609
  } catch {
593
610
  return;
594
611
  }
@@ -600,7 +617,7 @@ function matchRoute(tree, pathname) {
600
617
  */
601
618
  function notFound(tree) {
602
619
  return {
603
- errors: tree.error ? [errorIn(tree.error, wrapperOf(tree, [], 0, {}, ""), {}, "")] : [],
620
+ errors: tree.error ? [errorIn(tree.error, findWrapper(tree, [], 0, {}, ""), {}, "")] : [],
604
621
  middleware: tree.middleware ? [tree.middleware] : []
605
622
  };
606
623
  }
@@ -638,10 +655,13 @@ function summary(issues) {
638
655
  */
639
656
  function plainIssue(issue) {
640
657
  const plain = { message: String(issue.message) };
641
- if (issue.path && issue.path.length > 0) plain.path = issue.path.map((segment) => {
642
- const key = typeof segment === "object" && segment !== null ? segment.key : segment;
643
- return typeof key === "number" ? key : String(key);
644
- });
658
+ if (issue.path && issue.path.length > 0) {
659
+ plain.path = [];
660
+ for (const segment of issue.path) {
661
+ const key = typeof segment === "object" && segment !== null ? segment.key : segment;
662
+ plain.path.push(typeof key === "number" ? key : String(key));
663
+ }
664
+ }
645
665
  return plain;
646
666
  }
647
667
  /**
@@ -653,7 +673,11 @@ async function safeParse(schema, value) {
653
673
  const props = schema["~standard"];
654
674
  if (props?.version !== 1 || typeof props.validate !== "function") throw new TypeError("The schema is not a Standard Schema of version 1");
655
675
  const result = await props.validate(value);
656
- if (result.issues) return { issues: result.issues.map(plainIssue) };
676
+ if (result.issues) {
677
+ const issues = [];
678
+ for (const issue of result.issues) issues.push(plainIssue(issue));
679
+ return { issues };
680
+ }
657
681
  return { value: result.value };
658
682
  }
659
683
  /**
@@ -713,12 +737,18 @@ function fieldErrors(issues) {
713
737
  //#endregion
714
738
  //#region src/runtime/submission.ts
715
739
  /** True for a file, so it is not sent back. */
716
- const isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
740
+ function isBlob(value) {
741
+ return typeof Blob !== "undefined" && value instanceof Blob;
742
+ }
717
743
  /** The values to send back: without files and hidden fields. */
718
744
  function echo(value, hidden, path = []) {
719
745
  if (path.length > 0 && hidden.has(formatPath(path))) return;
720
746
  if (isBlob(value)) return;
721
- if (Array.isArray(value)) return value.map((item, index) => echo(item, hidden, [...path, index]));
747
+ if (Array.isArray(value)) {
748
+ const copy = new Array(value.length);
749
+ for (const [index, item] of value.entries()) if (index in value) copy[index] = echo(item, hidden, [...path, index]);
750
+ return copy;
751
+ }
722
752
  if (typeof value === "object" && value !== null) {
723
753
  const copy = {};
724
754
  for (const [key, item] of Object.entries(value)) {
@@ -755,27 +785,33 @@ function replyId() {
755
785
  async function parseSubmission(schema, form, options = {}) {
756
786
  const hidden = new Set(options.hide);
757
787
  const id = replyId();
758
- const make = (status, payload, issues, list) => ({
759
- payload,
760
- reply(reply = {}) {
761
- const grouped = groupIssues(issues);
762
- const errors = { ...grouped.errors };
763
- for (const [name, messages] of Object.entries(reply.fieldErrors ?? {})) errors[name] = [...Object.hasOwn(errors, name) ? errors[name] : [], ...messages];
764
- const keys = {};
765
- const items = list === void 0 ? void 0 : getAt(payload, parsePath(list));
766
- if (list !== void 0 && Array.isArray(items)) keys[list] = items.map((_, index) => `${id}-${index}`);
767
- const result = {
768
- status,
769
- value: reply.reset ? void 0 : echo(payload, hidden),
770
- errors: reply.reset ? {} : errors,
771
- formErrors: [...grouped.formErrors, ...reply.formErrors ?? []],
772
- keys: reply.reset ? {} : keys,
773
- id
774
- };
775
- if (reply.reset) result.reset = true;
776
- return result;
777
- }
778
- });
788
+ function make(status, payload, issues, list) {
789
+ return {
790
+ payload,
791
+ reply(reply = {}) {
792
+ const grouped = groupIssues(issues);
793
+ const errors = { ...grouped.errors };
794
+ for (const [name, messages] of Object.entries(reply.fieldErrors ?? {})) errors[name] = [...Object.hasOwn(errors, name) ? errors[name] : [], ...messages];
795
+ const keys = {};
796
+ const items = list === void 0 ? void 0 : getAt(payload, parsePath(list));
797
+ if (list !== void 0 && Array.isArray(items)) {
798
+ const itemKeys = new Array(items.length);
799
+ for (let index = 0; index < items.length; index++) if (index in items) itemKeys[index] = `${id}-${index}`;
800
+ keys[list] = itemKeys;
801
+ }
802
+ const result = {
803
+ status,
804
+ value: reply.reset ? void 0 : echo(payload, hidden),
805
+ errors: reply.reset ? {} : errors,
806
+ formErrors: [...grouped.formErrors, ...reply.formErrors ?? []],
807
+ keys: reply.reset ? {} : keys,
808
+ id
809
+ };
810
+ if (reply.reset) result.reset = true;
811
+ return result;
812
+ }
813
+ };
814
+ }
779
815
  const raw = form.get(INTENT);
780
816
  const values = formValues(form, (name) => name === INTENT);
781
817
  if (values.issues) return {
@@ -812,10 +848,11 @@ async function parseSubmission(schema, form, options = {}) {
812
848
  if (intent.type === "validate") {
813
849
  const result = await safeParse(schema, payload);
814
850
  const name = intent.name;
815
- const issues = (result.issues ?? []).filter((issue) => {
851
+ const issues = [];
852
+ for (const issue of result.issues ?? []) {
816
853
  const path = issue.path ? formatPath(issue.path) : "";
817
- return path === name || path.startsWith(`${name}.`) || path.startsWith(`${name}[`);
818
- });
854
+ if (path === name || path.startsWith(`${name}.`) || path.startsWith(`${name}[`)) issues.push(issue);
855
+ }
819
856
  return {
820
857
  status: "intent",
821
858
  intent,
@@ -861,11 +898,11 @@ function windowMs(window) {
861
898
  function createMemoryStore(now = Date.now) {
862
899
  const counts = /* @__PURE__ */ new Map();
863
900
  let sweeps = 0;
864
- const sweep = () => {
901
+ function sweep() {
865
902
  if (++sweeps % 1e3 !== 0) return;
866
903
  const time = now();
867
904
  for (const [key, entry] of counts) if (entry.expires <= time) counts.delete(key);
868
- };
905
+ }
869
906
  return {
870
907
  increment(key, ttl) {
871
908
  sweep();
@@ -906,7 +943,7 @@ function isDevelopment() {
906
943
  * What a limit counts per: the server function, the pattern of the route,
907
944
  * such as `/api/[id]`, or one count for every path that no route matches.
908
945
  */
909
- function targetOf(event) {
946
+ function getTarget(event) {
910
947
  return event.call?.id ?? event.route ?? "(no route)";
911
948
  }
912
949
  /**
@@ -915,10 +952,10 @@ function targetOf(event) {
915
952
  * up the limit of all. So it throws in production. In development it warns
916
953
  * once and returns undefined, and the limit does not count.
917
954
  */
918
- async function keyOf(event, options) {
955
+ async function readKey(event, options) {
919
956
  const key = await options.key?.(event, event.call?.args ?? []) ?? clientAddress(event);
920
957
  if (key !== void 0) return key;
921
- const message = `rateLimit: the request to "${targetOf(event)}" has no key, because the server did not pass the address of the client. Pass \`address\` to the handler of the server, or set \`key\` on the limit.`;
958
+ const message = `rateLimit: the request to "${getTarget(event)}" has no key, because the server did not pass the address of the client. Pass \`address\` to the handler of the server, or set \`key\` on the limit.`;
922
959
  if (!isDevelopment()) throw new Error(message);
923
960
  if (!warned) {
924
961
  warned = true;
@@ -931,9 +968,9 @@ async function keyOf(event, options) {
931
968
  */
932
969
  async function check(event, options) {
933
970
  if (event.prerender || !(options.enabled ?? config.enabled ?? true)) return;
934
- const key = await keyOf(event, options);
971
+ const key = await readKey(event, options);
935
972
  if (key === void 0) return;
936
- const name = `${key} ${targetOf(event)}`;
973
+ const name = `${key} ${getTarget(event)}`;
937
974
  const store = options.store ?? config.store ?? (memory ??= createMemoryStore(clock));
938
975
  const window = windowMs(options.window);
939
976
  const now = clock();
@@ -997,13 +1034,12 @@ function parseAddress(text) {
997
1034
  const value = text.trim().replace(/^\[|\]$/g, "");
998
1035
  if (value.includes(":")) return parseIPv6(value);
999
1036
  const parts = value.split(".");
1000
- if (parts.length !== 4 || !parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) < 256)) return;
1037
+ if (parts.length !== 4) return;
1038
+ for (const part of parts) if (!/^\d{1,3}$/.test(part) || Number(part) >= 256) return;
1001
1039
  const bytes = /* @__PURE__ */ new Uint8Array(16);
1002
1040
  bytes[10] = 255;
1003
1041
  bytes[11] = 255;
1004
- parts.forEach((part, index) => {
1005
- bytes[12 + index] = Number(part);
1006
- });
1042
+ for (const [index, part] of parts.entries()) bytes[12 + index] = Number(part);
1007
1043
  return bytes;
1008
1044
  }
1009
1045
  function parseIPv6(value) {
@@ -1035,7 +1071,8 @@ function parseIPv6(value) {
1035
1071
  return bytes;
1036
1072
  }
1037
1073
  function isIPv4(bytes) {
1038
- return bytes.slice(0, 10).every((byte) => byte === 0) && bytes[10] === 255 && bytes[11] === 255;
1074
+ for (const byte of bytes.slice(0, 10)) if (byte !== 0) return false;
1075
+ return bytes[10] === 255 && bytes[11] === 255;
1039
1076
  }
1040
1077
  /**
1041
1078
  * Reads a range: an address, or a CIDR such as `10.0.0.0/8` or `fd00::/8`.
@@ -1082,10 +1119,15 @@ function formatAddress(bytes) {
1082
1119
  function clientAddress(event, proxies = config.proxies ?? []) {
1083
1120
  const seen = event.address === void 0 ? void 0 : parseAddress(event.address);
1084
1121
  if (!seen) return;
1085
- const ranges = proxies.map(parseRange);
1086
- const trusted = (address) => ranges.some((range) => inParsedRange(address, range));
1122
+ const ranges = [];
1123
+ for (const proxy of proxies) ranges.push(parseRange(proxy));
1124
+ function trusted(address) {
1125
+ for (const range of ranges) if (inParsedRange(address, range)) return true;
1126
+ return false;
1127
+ }
1087
1128
  if (!trusted(seen)) return formatAddress(seen);
1088
- const hops = (event.request.headers.get("x-forwarded-for") ?? "").split(",").filter((hop) => hop.trim() !== "");
1129
+ const hops = [];
1130
+ for (const hop of (event.request.headers.get("x-forwarded-for") ?? "").split(",")) if (hop.trim() !== "") hops.push(hop);
1089
1131
  let client = seen;
1090
1132
  for (let index = hops.length - 1; index >= 0; index--) {
1091
1133
  const address = parseAddress(hops[index]);
@@ -1190,7 +1232,11 @@ var RevealGroup = class {
1190
1232
  }
1191
1233
  /** The body is ready, or failed with nothing to send. `send` writes it, and runs `after` with it. */
1192
1234
  ready(id, send) {
1193
- const member = this.members.find((item) => item.id === id);
1235
+ let member;
1236
+ for (const item of this.members) if (item.id === id) {
1237
+ member = item;
1238
+ break;
1239
+ }
1194
1240
  if (member) {
1195
1241
  member.send = send;
1196
1242
  this.flush();
@@ -1209,14 +1255,28 @@ var RevealGroup = class {
1209
1255
  const next = members[index + 1];
1210
1256
  member.send(next && this.hidden.has(next.id) ? `$bF(${scriptJSON(next.id)})` : "");
1211
1257
  };
1212
- if (this.order === "natural") members.forEach((member, index) => member.send && !member.sent && sendAt(index));
1213
- else if (this.order === "sequential") {
1258
+ if (this.order === "natural") {
1259
+ for (const [index, member] of members.entries()) if (member.send && !member.sent) sendAt(index);
1260
+ } else if (this.order === "sequential") {
1214
1261
  for (let index = 0; index < members.length && members[index].send; index++) if (!members[index].sent) sendAt(index);
1215
1262
  } else if (this.closed && this.order === "backwards") {
1216
1263
  for (let index = members.length - 1; index >= 0 && members[index].send; index--) if (!members[index].sent) sendAt(index);
1217
- } else if (this.closed && members.every((member) => member.send)) members.forEach((member, index) => !member.sent && sendAt(index));
1264
+ } else if (this.closed) {
1265
+ let allReady = true;
1266
+ for (const member of members) if (!member.send) {
1267
+ allReady = false;
1268
+ break;
1269
+ }
1270
+ if (allReady) {
1271
+ for (const [index, member] of members.entries()) if (!member.sent) sendAt(index);
1272
+ }
1273
+ }
1218
1274
  }
1219
1275
  };
1276
+ /** The last entry of the inserted children that comes from `from`. */
1277
+ function findLastInserted(inserted, from) {
1278
+ for (let index = inserted.length - 1; index >= 0; index--) if (inserted[index].from === from) return inserted[index];
1279
+ }
1220
1280
  /** True if a boundary holds `target`, whose ID starts with the boundary's ID and a dot. */
1221
1281
  function holdsBoundary(id, target) {
1222
1282
  return typeof target === "string" && target.startsWith(`${id}.`);
@@ -1282,6 +1342,10 @@ var Context = class Context {
1282
1342
  markup: true
1283
1343
  };
1284
1344
  onBoundary;
1345
+ /** The `#try` blocks of the parents of this context, from the outside in. */
1346
+ outer = [];
1347
+ /** The `#try` blocks of this context that are rendering their bodies now. */
1348
+ catchers = [];
1285
1349
  /** The scope that renders the next component, which becomes its owner. */
1286
1350
  owner;
1287
1351
  /**
@@ -1295,6 +1359,8 @@ var Context = class Context {
1295
1359
  rpcPrefix = "/_brumate";
1296
1360
  /** The ID of the build, for forms that post to server functions. See `RenderOptions`. */
1297
1361
  build;
1362
+ /** True in development, where a memo that failed or a `#catch` sends its error to the browser. */
1363
+ development = false;
1298
1364
  /** Results of server functions that a form posted to this page, for `$action`. */
1299
1365
  actions = /* @__PURE__ */ new Map();
1300
1366
  /** The params of the route of the page, for `$route`. */
@@ -1386,6 +1452,10 @@ var Context = class Context {
1386
1452
  rpc() {
1387
1453
  return this.root.rpcPrefix;
1388
1454
  }
1455
+ /** True when the render is in development. */
1456
+ isDev() {
1457
+ return this.root.development;
1458
+ }
1389
1459
  /** Returns the ID of the build, when the render has one. */
1390
1460
  buildId() {
1391
1461
  return this.root.build;
@@ -1412,7 +1482,7 @@ var Context = class Context {
1412
1482
  root.owner = void 0;
1413
1483
  }
1414
1484
  }
1415
- const inserted = root.inserted.findLast((entry) => entry.from === up);
1485
+ const inserted = findLastInserted(root.inserted, up);
1416
1486
  if (inserted) {
1417
1487
  up = inserted.at;
1418
1488
  record.t = inserted.at;
@@ -1458,12 +1528,18 @@ var Context = class Context {
1458
1528
  * keep `from`, the scope of the markup that wrote them, for their values,
1459
1529
  * and find their contexts from `at`.
1460
1530
  */
1461
- async children(from, at, renderBody) {
1531
+ async children(from, at, renderBody, tag) {
1532
+ const { inserted } = this.root;
1533
+ const outer = findLastInserted(inserted, at);
1462
1534
  const entry = {
1463
1535
  from,
1464
- at
1536
+ at: outer ? outer.at : at,
1537
+ tag: tag ?? outer?.tag
1465
1538
  };
1466
- const { inserted } = this.root;
1539
+ if (outer) {
1540
+ const passing = this.find(at);
1541
+ if (passing) passing.record.f = outer.at;
1542
+ }
1467
1543
  inserted.push(entry);
1468
1544
  try {
1469
1545
  return await renderBody();
@@ -1471,6 +1547,10 @@ var Context = class Context {
1471
1547
  inserted.splice(inserted.indexOf(entry), 1);
1472
1548
  }
1473
1549
  }
1550
+ /** The tag of the element where the children that render now are inserted, for spacers. */
1551
+ spacerTag() {
1552
+ return this.root.inserted.at(-1)?.tag ?? "div";
1553
+ }
1474
1554
  /**
1475
1555
  * The ID that `$id()` makes: the scope's ID and the position of the call.
1476
1556
  * A dot in a scope ID inside a `#loading` body becomes `_`, so the ID also
@@ -1493,9 +1573,9 @@ var Context = class Context {
1493
1573
  record.v[context.key] = value;
1494
1574
  }
1495
1575
  /**
1496
- * Reads a context from the nearest scope that provides it, starting at
1497
- * `scope`. With `slot`, records which slot holds it, so the client can
1498
- * update it when the provided value changes.
1576
+ * Reads a context from the nearest scope above `scope` that provides it.
1577
+ * With `slot`, records which slot holds it, so the client can update it
1578
+ * when the provided value changes.
1499
1579
  */
1500
1580
  consume(context, scope, slot) {
1501
1581
  if (slot !== void 0) {
@@ -1503,7 +1583,7 @@ var Context = class Context {
1503
1583
  record.x ??= {};
1504
1584
  record.x[context.key] = slot;
1505
1585
  }
1506
- for (let id = scope; id !== void 0;) {
1586
+ for (let id = this.find(scope)?.parent; id !== void 0;) {
1507
1587
  const node = this.find(id);
1508
1588
  if (node?.values?.has(context.key)) return node.values.get(context.key);
1509
1589
  id = node?.parent;
@@ -1601,19 +1681,65 @@ var Context = class Context {
1601
1681
  }
1602
1682
  /** The records of the scopes of this render, by ID, in the order the render made them. */
1603
1683
  get state() {
1604
- return new Map(this.scopes.map((entry) => [entry.id, entry.record]));
1684
+ const state = /* @__PURE__ */ new Map();
1685
+ for (const entry of this.scopes) state.set(entry.id, entry.record);
1686
+ return state;
1605
1687
  }
1606
1688
  /**
1607
1689
  * The list of each list item scope whose list is a slot of an enclosing
1608
1690
  * scope, as `[scope, slot]`. The items of a list share one array.
1609
1691
  */
1610
1692
  get sources() {
1611
- return new Map(this.scopes.flatMap((entry) => entry.source ? [[entry.id, entry.source]] : []));
1693
+ const sources = /* @__PURE__ */ new Map();
1694
+ for (const entry of this.scopes) if (entry.source) sources.set(entry.id, entry.source);
1695
+ return sources;
1696
+ }
1697
+ /** The scope that `unbind` collects the promise props of its component in. */
1698
+ sink(scope) {
1699
+ return this.entry(scope);
1612
1700
  }
1613
1701
  slots(scope, values, names) {
1614
1702
  const entry = this.entry(scope);
1615
1703
  entry.record.s = values;
1616
1704
  if (names) entry.names = names;
1705
+ const forwarded = this.forwards?.get(scope);
1706
+ if (forwarded) {
1707
+ this.forwards.delete(scope);
1708
+ for (const [slot, value] of forwarded) values[slot] = value;
1709
+ }
1710
+ let wrapped;
1711
+ for (let slot = 0; slot < values.length; slot++) {
1712
+ const value = values[slot];
1713
+ if (value instanceof Promise && entry.props?.includes(value) && values.indexOf(value) === slot) {
1714
+ wrapped ??= [...values];
1715
+ wrapped[slot] = new PropPromise(this.isDev() ? value : value.catch((error) => {
1716
+ const safe = new Error(error instanceof ServerError ? error.message : "The page could not compute a value");
1717
+ safe.stack = "";
1718
+ throw safe;
1719
+ }));
1720
+ }
1721
+ }
1722
+ entry.props = void 0;
1723
+ if (wrapped) entry.record.s = wrapped;
1724
+ }
1725
+ /** Elements that bound props of components forwarded to the slots of scopes that have no slots yet. */
1726
+ forwards;
1727
+ /**
1728
+ * Writes the element that a component forwards to a slot of a scope above it, and on through
1729
+ * the props that scope binds in turn. The parent records its slots after its children render,
1730
+ * so a write for a scope that has none waits for them.
1731
+ */
1732
+ forward(target, value) {
1733
+ const record = this.ownRecord(target.scope);
1734
+ if (!record?.s) {
1735
+ const waiting = (this.forwards ??= /* @__PURE__ */ new Map()).get(target.scope) ?? /* @__PURE__ */ new Map();
1736
+ waiting.set(target.slot, value);
1737
+ this.forwards.set(target.scope, waiting);
1738
+ return;
1739
+ }
1740
+ record.s[target.slot] = value;
1741
+ const next = record.b?.[target.slot];
1742
+ if (isSlotReference(next)) this.forward(next, value);
1617
1743
  }
1618
1744
  /**
1619
1745
  * Records the props that a parent bound with `$bind`, among the props that
@@ -1623,7 +1749,12 @@ var Context = class Context {
1623
1749
  bindings(scope, props, slots) {
1624
1750
  for (const [name, slot] of Object.entries(slots)) {
1625
1751
  const value = props[name];
1626
- if (isBinding(value)) (this.entry(scope).record.b ??= {})[slot] = value.target;
1752
+ if (isBinding(value)) {
1753
+ const record = this.entry(scope).record;
1754
+ (record.b ??= {})[slot] = value.target;
1755
+ const written = record.s?.[slot];
1756
+ if (written instanceof ElementReference && isSlotReference(value.target)) this.forward(value.target, written);
1757
+ }
1627
1758
  }
1628
1759
  }
1629
1760
  /**
@@ -1645,6 +1776,15 @@ var Context = class Context {
1645
1776
  if (links[anchor] === child) delete links[anchor];
1646
1777
  });
1647
1778
  }
1779
+ /**
1780
+ * A `ref` that the rest props of a component hold is a binding of a signal above. The element
1781
+ * that spreads them goes to that signal, as when the component names `ref` itself.
1782
+ */
1783
+ restRef(attributes, scope, anchor, tag) {
1784
+ const value = attributes.ref;
1785
+ if (typeof tag !== "function" && isBinding(value) && isSlotReference(value.target)) this.forward(value.target, new ElementReference(scope, anchor));
1786
+ return attributes;
1787
+ }
1648
1788
  /** Returns the reference that a `ref` signal holds on the server. */
1649
1789
  element(scope, anchor) {
1650
1790
  return new ElementReference(scope, anchor);
@@ -1657,6 +1797,17 @@ var Context = class Context {
1657
1797
  */
1658
1798
  fn(value, ref, scope, args) {
1659
1799
  if (typeof value !== "function") return value;
1800
+ if (args === void 0 && /#t\d/.test(ref)) {
1801
+ const render = value;
1802
+ function template(...rest) {
1803
+ return new Children(scope, async () => {
1804
+ const html = await render(...rest);
1805
+ return isRaw(html) ? rawHTML(html) : insertValue(html);
1806
+ });
1807
+ }
1808
+ functionReferences.set(template, new FunctionReference(ref, scope));
1809
+ return template;
1810
+ }
1660
1811
  if (args === void 0) {
1661
1812
  functionReferences.set(value, new FunctionReference(ref, scope));
1662
1813
  return value;
@@ -1764,6 +1915,18 @@ var Context = class Context {
1764
1915
  fallbackEnd(id) {
1765
1916
  return this.reveal?.hidden.has(id) ? "</template>" : "";
1766
1917
  }
1918
+ /**
1919
+ * Starts a `#try` body. A `#loading` body inside it that fails renders the `#catch` body with
1920
+ * `draw`, after the page is sent. The returned function ends the `#try` body.
1921
+ */
1922
+ catcher(key, draw) {
1923
+ const entry = {
1924
+ key,
1925
+ render: draw
1926
+ };
1927
+ this.catchers.push(entry);
1928
+ return () => removeLast(this.catchers, entry);
1929
+ }
1767
1930
  /** Returns the ID of a new `#loading` boundary. */
1768
1931
  boundary() {
1769
1932
  return spaceId(this.space, this.space.boundary++);
@@ -1801,6 +1964,8 @@ var Context = class Context {
1801
1964
  register(id, renderBody, inTarget, around = false) {
1802
1965
  const child = new Context(this.root, void 0, 0, `${id}.`);
1803
1966
  child.inTarget = inTarget;
1967
+ const catchers = [...this.outer, ...this.catchers];
1968
+ child.outer = catchers;
1804
1969
  const group = this.reveal;
1805
1970
  group?.add(id);
1806
1971
  const end = around ? void 0 : this.traced("body", `#loading ${id}`);
@@ -1817,7 +1982,8 @@ var Context = class Context {
1817
1982
  throw error;
1818
1983
  }),
1819
1984
  around,
1820
- group
1985
+ group,
1986
+ catchers
1821
1987
  };
1822
1988
  boundary.render.catch(() => {});
1823
1989
  const root = this.root;
@@ -1927,18 +2093,32 @@ function ready(node) {
1927
2093
  }
1928
2094
  /**
1929
2095
  * The value of a memo for the page state: its value when it is ready, or
1930
- * a promise of it while it loads. A memo that fails gives a rejected
1931
- * promise either way, so the page renders and the failure reaches the
1932
- * browser as the load that failed.
2096
+ * a promise of it while it loads. A memo that fails gives a `MemoError`
2097
+ * either way, so the page renders, the stream goes on, and a read in the
2098
+ * browser throws the error as a memo that failed there.
1933
2099
  */
1934
2100
  function stateValue(node) {
1935
2101
  try {
1936
2102
  return read(node);
1937
2103
  } catch (error) {
1938
- return error instanceof NotReady ? wait(node) : Promise.reject(error);
2104
+ if (error instanceof NotReady) return wait(node).catch((failure) => heldError(failure, node.ctx));
2105
+ return heldError(error, node.ctx);
1939
2106
  }
1940
2107
  }
1941
2108
  /**
2109
+ * The error of a memo for the page state. In development it is the error as seroval
2110
+ * writes it: its name, message, own properties, `cause` and the `errors` of an `AggregateError`,
2111
+ * and no stack (the serial options leave stacks out). In production it is the message of
2112
+ * a `ServerError`, which the app chose to show, or else a generic message, and the error is
2113
+ * logged, as for a server function that fails.
2114
+ */
2115
+ function heldError(error, ctx) {
2116
+ let sent;
2117
+ if (ctx?.isDev()) sent = error instanceof Error ? error : new Error(String(error));
2118
+ else sent = safeError(error, "The page could not compute a value");
2119
+ return Object.assign(new MemoError(sent), { [Symbol.for("brumate.held")]: true });
2120
+ }
2121
+ /**
1942
2122
  * Starts every memo of a run of declarations that the render waits for,
1943
2123
  * so they load at the same time. Returns a promise that settles when all
1944
2124
  * of them have, or undefined when none is loading. A memo that fails
@@ -1974,8 +2154,8 @@ const LAZY = Symbol.for("brumate.lazy");
1974
2154
  * them, so they read the contexts that the component provides. `from` is the
1975
2155
  * scope of the markup that wrote them.
1976
2156
  */
1977
- function children(from, renderBody) {
1978
- return new Children(from, renderBody);
2157
+ function children(from, renderBody, ref) {
2158
+ return new Children(from, renderBody, ref);
1979
2159
  }
1980
2160
  /** The symbol of raw HTML. See `html.ts`. */
1981
2161
  const RAW = Symbol.for("brumate.raw");
@@ -1989,14 +2169,32 @@ var Children = class {
1989
2169
  [LAZY];
1990
2170
  /** The HTML of the first render, under the symbol of raw HTML. */
1991
2171
  [RAW];
1992
- constructor(from, renderBody) {
1993
- this[LAZY] = async (ctx, at) => {
1994
- const html = await (at === void 0 ? renderBody(ctx) : ctx.children(from, at, () => renderBody(ctx)));
1995
- this[RAW] ??= html;
2172
+ /**
2173
+ * The export that renders the children in the browser, which the page state sends in place of
2174
+ * their HTML. Each insert in the browser then renders them with new scopes.
2175
+ */
2176
+ [CHILDREN_REF];
2177
+ constructor(from, renderBody, ref) {
2178
+ if (ref !== void 0) this[CHILDREN_REF] = new ChildrenReference(ref, from);
2179
+ this[LAZY] = async (ctx, at, tag, anchor) => {
2180
+ const reference = this[CHILDREN_REF];
2181
+ if (reference && reference.at === void 0 && anchor !== void 0) {
2182
+ reference.at = at;
2183
+ reference.anchor = anchor;
2184
+ }
2185
+ const html = await (at === void 0 ? renderBody(ctx) : ctx.children(from, at, () => renderBody(ctx), tag));
2186
+ if (ref === void 0) this[RAW] ??= html;
1996
2187
  return html;
1997
2188
  };
1998
2189
  }
1999
2190
  };
2191
+ /**
2192
+ * The tag of the spacers of a windowed list in children: a row in a table body, an item in a
2193
+ * list, as the element where the children are inserted says, or else a `div`.
2194
+ */
2195
+ function spacerTag(ctx) {
2196
+ return ctx.spacerTag();
2197
+ }
2000
2198
  /** Makes markup that renders where it is inserted, such as the children of a layout. */
2001
2199
  function lazy(renderAt) {
2002
2200
  return { [LAZY]: renderAt };
@@ -2021,15 +2219,21 @@ function actionResult(ctx, fn) {
2021
2219
  return ctx.actionResult(fn);
2022
2220
  }
2023
2221
  /**
2024
- * Renders a value inserted in markup. `ctx` and `scope` are where it is
2025
- * inserted, for markup that renders there.
2222
+ * Renders a value inserted in markup. `ctx`, `scope` and `anchor` are where it
2223
+ * is inserted, for markup that renders there.
2026
2224
  */
2027
- function insert(value, ctx, scope) {
2028
- if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope));
2029
- if (isLazy(value) && ctx) return value[LAZY](ctx, scope);
2225
+ function insert(value, ctx, scope, tag, anchor) {
2226
+ if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope, tag, anchor));
2227
+ if (isLazy(value) && ctx) return value[LAZY](ctx, scope, tag, anchor);
2030
2228
  if (Array.isArray(value)) {
2031
- const parts = value.map((item) => insert(item, ctx, scope));
2032
- return parts.every((part) => typeof part === "string") ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
2229
+ const parts = [];
2230
+ let allStrings = true;
2231
+ for (const item of value) {
2232
+ const part = insert(item, ctx, scope, tag);
2233
+ if (typeof part !== "string") allStrings = false;
2234
+ parts.push(part);
2235
+ }
2236
+ return allStrings ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
2033
2237
  }
2034
2238
  return insertValue(value);
2035
2239
  }
@@ -2037,30 +2241,48 @@ function insert(value, ctx, scope) {
2037
2241
  * Renders a child component. With `scope` and `anchor`, records the child's
2038
2242
  * scope so the parent can update its props on the client.
2039
2243
  */
2040
- function component(Child, props, ctx, scope, anchor) {
2244
+ function component(Child, props, ctx, scope, anchor, paragraph) {
2041
2245
  if (ctx.past()) return Promise.resolve("");
2042
2246
  if (scope !== void 0 && anchor !== void 0) ctx.link(scope, anchor, ctx.peek());
2043
2247
  if (scope !== void 0) ctx.own(scope);
2044
2248
  const given = props?.children;
2045
- if (!(given instanceof Children)) return Child(props, ctx);
2249
+ if (!(given instanceof Children) || given[CHILDREN_REF]) return checkParagraph(Child(props, ctx), ctx, paragraph);
2046
2250
  const root = ctx.peek();
2047
- return Child(props, ctx).then(async (html) => {
2251
+ return checkParagraph(Child(props, ctx).then(async (html) => {
2048
2252
  if (given[RAW] === void 0) await given[LAZY](ctx, root);
2049
2253
  return html;
2254
+ }), ctx, paragraph);
2255
+ }
2256
+ /**
2257
+ * In development, throws when a component inside a `<p>` starts with an element that closes the
2258
+ * `<p>`. `paragraph` names the component and where it is, and only the compiler sets it. The
2259
+ * browser splits the markers of the blocks of the page there, so it is an error before that.
2260
+ */
2261
+ function checkParagraph(rendered, ctx, paragraph) {
2262
+ if (paragraph === void 0 || !ctx.isDev()) return rendered;
2263
+ return rendered.then((html) => {
2264
+ const tag = typeof html === "string" ? firstTag(html) : void 0;
2265
+ if (tag !== void 0 && closesParagraph(tag)) throw new Error(`${paragraph} renders <${tag}>, which the HTML parser does not keep inside a <p>: it closes the <p> and splits the markers of the page [BRM185]. Move the component out of the <p>, or make it render a <span>, as with as="span"`);
2266
+ return html;
2050
2267
  });
2051
2268
  }
2052
2269
  /** Renders a dynamic tag, which can be an element name or a component. */
2053
- function dynamic(tag, attributes, content, ctx, scope) {
2270
+ function dynamic(tag, attributes, content, ctx, scope, ref) {
2054
2271
  if (typeof tag === "function") {
2055
- const entries = attributes["b-on"];
2056
- const props = typeof entries === "string" && scope !== void 0 ? {
2272
+ if (ref !== void 0) attributes = {
2057
2273
  ...attributes,
2058
- "b-on": entries.split(" ").map((entry) => entry.includes("@") ? entry : `${entry}@${scope}`).join(" ")
2059
- } : attributes;
2274
+ ref
2275
+ };
2276
+ const { "b-b": bound, "b-on": entries, ...passed } = attributes;
2277
+ addEntryHandlers(passed, entries, scope, (reference) => {
2278
+ const handler = Object.assign(() => {}, reference.modifiers ? { [MODIFIERS]: reference.modifiers } : {});
2279
+ functionReferences.set(handler, reference);
2280
+ return handler;
2281
+ });
2060
2282
  return component(tag, content ? {
2061
- ...props,
2283
+ ...passed,
2062
2284
  children: content
2063
- } : props, ctx, scope);
2285
+ } : passed, ctx, scope, bound === void 0 ? void 0 : Number(ownValue("b-b", bound).split(":")[1]));
2064
2286
  }
2065
2287
  const on = [];
2066
2288
  const open = `<${tag}${spread(attributes, on)}${onAttribute(on, "")}>`;
@@ -2077,7 +2299,8 @@ function holds(value, target, seen = /* @__PURE__ */ new Set()) {
2077
2299
  if (value instanceof Map) items = [...value.keys(), ...value.values()];
2078
2300
  else if (value instanceof Set) items = [...value];
2079
2301
  else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype) items = Object.values(value);
2080
- return items.some((item) => holds(item, target, seen));
2302
+ for (const item of items) if (holds(item, target, seen)) return true;
2303
+ return false;
2081
2304
  }
2082
2305
  /**
2083
2306
  * The error of a value in the state of a page that cannot be sent to the
@@ -2088,7 +2311,11 @@ function unsendable(error, ctx) {
2088
2311
  const target = secret ?? error.value;
2089
2312
  if (target === void 0) return error instanceof Error ? error : new Error(String(error));
2090
2313
  for (const { record, names } of ctx.scopes) {
2091
- const index = (record.s ?? []).findIndex((value) => holds(value, target));
2314
+ let index = -1;
2315
+ for (const [slot, value] of (record.s ?? []).entries()) if (holds(value, target)) {
2316
+ index = slot;
2317
+ break;
2318
+ }
2092
2319
  if (index === -1) continue;
2093
2320
  let owner = record;
2094
2321
  while (owner && owner.m === void 0 && owner.p !== void 0) owner = ctx.ownRecord(owner.p);
@@ -2136,6 +2363,11 @@ const PACKED_FIELDS = /* @__PURE__ */ new Set([
2136
2363
  "i",
2137
2364
  "c"
2138
2365
  ]);
2366
+ /** True when a record has a field that `PackedState` has no place for. */
2367
+ function hasUnpackedField(record) {
2368
+ for (const field of Object.keys(record)) if (!PACKED_FIELDS.has(field)) return true;
2369
+ return false;
2370
+ }
2139
2371
  /** A group of `PackedState` while `packState` collects it. */
2140
2372
  /** How many of the last groups `packState` compares a record with, before it looks up its name. */
2141
2373
  const RECENT_GROUPS = 4;
@@ -2148,7 +2380,9 @@ function splitId(id) {
2148
2380
  /** The records of a state as a map, for a state written as an object, such as in tests. */
2149
2381
  function toStateMap(state) {
2150
2382
  if (state instanceof Map) return state;
2151
- return new Map(Object.entries(state).map(([key, record]) => [parseId(key), record]));
2383
+ const map = /* @__PURE__ */ new Map();
2384
+ for (const [key, record] of Object.entries(state)) map.set(parseId(key), record);
2385
+ return map;
2152
2386
  }
2153
2387
  /**
2154
2388
  * Visits the scopes of a state in the order of the keys of an object: number
@@ -2161,7 +2395,9 @@ function visitOrdered(entries, visit) {
2161
2395
  let last = -Infinity;
2162
2396
  for (const entry of entries) if (typeof entry.id === "number") {
2163
2397
  if (entry.id < last) {
2164
- numbers = entries.filter((item) => typeof item.id === "number").toSorted((a, b) => a.id - b.id);
2398
+ const numeric = [];
2399
+ for (const item of entries) if (typeof item.id === "number") numeric.push(item);
2400
+ numbers = numeric.toSorted((a, b) => a.id - b.id);
2165
2401
  break;
2166
2402
  }
2167
2403
  last = entry.id;
@@ -2197,17 +2433,19 @@ function groupSource(record, group) {
2197
2433
  */
2198
2434
  function packState(input, sources) {
2199
2435
  const state = toStateMap(input);
2200
- return packEntries(Array.from(state, ([id, record]) => {
2436
+ const entries = [];
2437
+ for (const [id, record] of state) {
2201
2438
  const [prefix, n] = splitId(id);
2202
- return {
2439
+ entries.push({
2203
2440
  id,
2204
2441
  prefix,
2205
2442
  n,
2206
2443
  record,
2207
2444
  ctx: void 0,
2208
2445
  source: sources?.get(id)
2209
- };
2210
- }), (id) => state.get(id));
2446
+ });
2447
+ }
2448
+ return packEntries(entries, (id) => state.get(id));
2211
2449
  }
2212
2450
  /** Packs the scopes of a render. `lookup` finds the record of a scope in the same state. */
2213
2451
  function packEntries(scopes, lookup) {
@@ -2221,7 +2459,7 @@ function packEntries(scopes, lookup) {
2221
2459
  const [ownerPrefix, owner] = splitId(record.o);
2222
2460
  base = ownerPrefix === prefix ? n - owner : void 0;
2223
2461
  }
2224
- if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 || !Object.keys(record).every((field) => PACKED_FIELDS.has(field))) {
2462
+ if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 || hasUnpackedField(record)) {
2225
2463
  result[id] = record;
2226
2464
  return;
2227
2465
  }
@@ -2230,7 +2468,11 @@ function packEntries(scopes, lookup) {
2230
2468
  if ("i" in record) flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? 1 : 2;
2231
2469
  if (record.c) flags |= 4;
2232
2470
  if (record.m !== void 0) flags |= 16;
2233
- let group = recent.find((item) => item.k === record.k && item.base === base && item.flags === flags && item.count === slots.length && item.m === record.m && item.prefix === prefix);
2471
+ let group;
2472
+ for (const item of recent) if (item.k === record.k && item.base === base && item.flags === flags && item.count === slots.length && item.m === record.m && item.prefix === prefix) {
2473
+ group = item;
2474
+ break;
2475
+ }
2234
2476
  if (!group) {
2235
2477
  const name = `${prefix}:${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ""}`;
2236
2478
  group = groups.get(name);
@@ -2299,13 +2541,13 @@ function packEntries(scopes, lookup) {
2299
2541
  function serializeState(state, refs, onRecord, onError, onDone, sources, last = false) {
2300
2542
  const packed = state instanceof Context ? packEntries(state.scopes, (id) => state.ownRecord(id)) : packState(state, sources);
2301
2543
  let leaked = false;
2302
- const send = (code, initial) => {
2544
+ function send(code, initial) {
2303
2545
  const error = leaked ? void 0 : secretError(code);
2304
2546
  if (error) {
2305
2547
  leaked = true;
2306
2548
  onError(error);
2307
2549
  } else if (!leaked) onRecord(code, initial);
2308
- };
2550
+ }
2309
2551
  if (last) {
2310
2552
  let code;
2311
2553
  try {
@@ -2366,12 +2608,39 @@ function stateScript(code, scopes = false, attributes = {}) {
2366
2608
  if (attributes.route !== void 0) extra += ` b-route="${escapeAttribute(attributes.route)}"`;
2367
2609
  if (attributes.params !== void 0) extra += ` b-params="${escapeAttribute(JSON.stringify(attributes.params))}"`;
2368
2610
  if (attributes.build !== void 0) extra += ` b-build="${escapeAttribute(attributes.build)}"`;
2611
+ if (attributes.fail !== void 0) extra += ` b-fail="${attributes.fail}"`;
2612
+ if (attributes.catches !== void 0) extra += ` b-catch="${attributes.catches}"`;
2369
2613
  return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
2370
2614
  }
2371
2615
  const HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h="'+i+'"]'),h=document.head;e&&(h.append(e.content),e.remove());t!=null&&(h.querySelector('title:not([b-t])')||h.prepend(document.createElement('title')),document.title=t)}`;
2372
2616
  const SHOW_FALLBACK = `function $bF(i){var t=document.querySelector('template[b-f="'+i+'"]');t&&t.replaceWith(t.content)}`;
2373
2617
  const SWAP = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode;for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;p.removeChild(n);n=x}p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
2374
2618
  const SWAP_DEV = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode,f=[];for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;f.push(p.removeChild(n));n=x}(self.$bD||(self.$bD={}))[i]={f:f,b:[].slice.call(t.content.childNodes)};p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
2619
+ /**
2620
+ * The record that tells the browser a `#loading` body failed. Its code is the error, and the
2621
+ * browser hands it to the nearest `#try` around the boundary.
2622
+ */
2623
+ function failScript(error, refs, boundary, root, nonce) {
2624
+ let code;
2625
+ try {
2626
+ code = crossSerialize(error, {
2627
+ plugins: syncPlugins,
2628
+ ...serialOptions(),
2629
+ refs
2630
+ });
2631
+ } catch {
2632
+ code = crossSerialize(new Error(String(error)), {
2633
+ plugins: syncPlugins,
2634
+ ...serialOptions(),
2635
+ refs
2636
+ });
2637
+ }
2638
+ return stateScript(code, false, {
2639
+ root,
2640
+ nonce,
2641
+ fail: boundary
2642
+ });
2643
+ }
2375
2644
  /** The `pending` of a render that has nothing left to send. */
2376
2645
  const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
2377
2646
  done: true,
@@ -2383,10 +2652,10 @@ function createQueue() {
2383
2652
  let wake;
2384
2653
  let closed = false;
2385
2654
  let failure;
2386
- const notify = () => {
2655
+ function notify() {
2387
2656
  wake?.();
2388
2657
  wake = void 0;
2389
- };
2658
+ }
2390
2659
  return {
2391
2660
  push(item) {
2392
2661
  items.push(item);
@@ -2423,6 +2692,7 @@ async function render(Root, props, options = {}) {
2423
2692
  if (options.actions) ctx.actions = options.actions;
2424
2693
  if (options.params) ctx.params = options.params;
2425
2694
  ctx.build = options.build;
2695
+ ctx.development = options.dev === true;
2426
2696
  if (options.defer) ctx.target = { ...options.defer };
2427
2697
  ctx.inOrder = !options.defer && rendersInOrder(options.inOrder ?? "bots", options.request ?? options.event?.request);
2428
2698
  const event = options.event ?? (options.request ? new RequestEvent(options.request, {
@@ -2436,7 +2706,9 @@ async function render(Root, props, options = {}) {
2436
2706
  ctx.send();
2437
2707
  const html = beforeBodyEnd(rendered, ctx.portals.join(""));
2438
2708
  let queue;
2439
- const pending = () => queue ??= createQueue();
2709
+ function pending() {
2710
+ return queue ??= createQueue();
2711
+ }
2440
2712
  const refs = /* @__PURE__ */ new Map();
2441
2713
  const { nonce } = options;
2442
2714
  const root = options.defer ? `d${options.defer.boundary}` : options.base;
@@ -2444,19 +2716,19 @@ async function render(Root, props, options = {}) {
2444
2716
  let open = 0;
2445
2717
  let swap = false;
2446
2718
  let headSwap = false;
2447
- const finish = () => {
2719
+ function finish() {
2448
2720
  open--;
2449
2721
  if (open === 0) queue?.close();
2450
- };
2722
+ }
2451
2723
  let boundaries = 0;
2452
2724
  const swapScript = options.dev ? SWAP_DEV : SWAP;
2453
2725
  let fallbackDefined = false;
2454
- const showFallback = () => {
2726
+ function showFallback() {
2455
2727
  if (fallbackDefined) return "";
2456
2728
  fallbackDefined = true;
2457
2729
  return `${SHOW_FALLBACK};`;
2458
- };
2459
- const serialize = (target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) => {
2730
+ }
2731
+ function serialize(target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) {
2460
2732
  open++;
2461
2733
  serializeState(target, refs, (code, initial) => {
2462
2734
  if (initial) {
@@ -2475,9 +2747,27 @@ async function render(Root, props, options = {}) {
2475
2747
  nonce
2476
2748
  }));
2477
2749
  }, onError, finish, void 0, last);
2478
- };
2750
+ }
2751
+ async function renderCatch(boundary, error) {
2752
+ const entry = boundary.catchers.at(-1);
2753
+ if (!entry) return;
2754
+ const child = new Context(ctx, void 0, 0, `${boundary.id}c.`);
2755
+ child.outer = boundary.catchers.slice(0, -1);
2756
+ try {
2757
+ return {
2758
+ html: await entry.render(child, error),
2759
+ ctx: child,
2760
+ key: entry.key
2761
+ };
2762
+ } catch (failure) {
2763
+ console.error(failure);
2764
+ return;
2765
+ }
2766
+ }
2479
2767
  const inOrder = ctx.inOrder ? [] : void 0;
2480
- const stopped = () => event?.signal.aborted === true;
2768
+ function stopped() {
2769
+ return event?.signal.aborted === true;
2770
+ }
2481
2771
  event?.signal.addEventListener("abort", () => queue?.close(), { once: true });
2482
2772
  ctx.watch((boundary) => {
2483
2773
  if (inOrder) {
@@ -2486,14 +2776,14 @@ async function render(Root, props, options = {}) {
2486
2776
  }
2487
2777
  boundaries++;
2488
2778
  open++;
2489
- const skip = (after) => {
2779
+ function skip(after) {
2490
2780
  if (after) pending().push(`${scriptTag}${showFallback()}${after}<\/script>`);
2491
2781
  finish();
2492
- };
2493
- const turn = (send) => {
2782
+ }
2783
+ function turn(send) {
2494
2784
  if (boundary.group) boundary.group.ready(boundary.id, send);
2495
2785
  else send("");
2496
- };
2786
+ }
2497
2787
  boundary.render.then((result) => {
2498
2788
  if (boundary.cancelled || boundary.around || stopped()) {
2499
2789
  turn(skip);
@@ -2518,8 +2808,29 @@ async function render(Root, props, options = {}) {
2518
2808
  finish();
2519
2809
  });
2520
2810
  }, (error) => {
2521
- console.error(error);
2522
- turn(skip);
2811
+ if (boundary.cancelled || boundary.around || stopped()) {
2812
+ console.error(error);
2813
+ turn(skip);
2814
+ return;
2815
+ }
2816
+ turn((after) => {
2817
+ if (ctx.isDev()) console.error(error);
2818
+ renderCatch(boundary, error).then((result) => {
2819
+ if (!result) {
2820
+ pending().push(failScript(caught(error, ctx), refs, boundary.id, root, nonce));
2821
+ skip(after);
2822
+ return;
2823
+ }
2824
+ serialize(result.ctx, (script) => {
2825
+ pending().push(`<template b-c="${result.key}">${result.html}</template>${result.ctx.portals.join("")}${stateScript("0", false, {
2826
+ root,
2827
+ nonce,
2828
+ catches: result.key
2829
+ })}${script}`);
2830
+ });
2831
+ skip(after);
2832
+ });
2833
+ });
2523
2834
  });
2524
2835
  });
2525
2836
  if (options.defer) return {
@@ -2544,13 +2855,28 @@ async function render(Root, props, options = {}) {
2544
2855
  if (inOrder) {
2545
2856
  const bodies = /* @__PURE__ */ new Map();
2546
2857
  const portals = [];
2858
+ const catches = [];
2547
2859
  for (let index = 0; index < inOrder.length; index++) {
2548
2860
  const boundary = inOrder[index];
2549
2861
  let result;
2550
2862
  try {
2551
2863
  result = await boundary.render;
2552
2864
  } catch (error) {
2553
- console.error(error);
2865
+ if (boundary.cancelled || boundary.around) continue;
2866
+ if (ctx.isDev()) console.error(error);
2867
+ const replacement = await renderCatch(boundary, error);
2868
+ if (!replacement) {
2869
+ console.error(error);
2870
+ continue;
2871
+ }
2872
+ catches.push([replacement.key, replacement.html]);
2873
+ portals.push(...replacement.ctx.portals);
2874
+ serialize(replacement.ctx, (script) => {
2875
+ state += script;
2876
+ }, void 0, (failed) => {
2877
+ failure = failed;
2878
+ });
2879
+ if (failure !== void 0) throw unsendable(failure, replacement.ctx);
2554
2880
  continue;
2555
2881
  }
2556
2882
  if (boundary.cancelled || boundary.around) continue;
@@ -2564,7 +2890,9 @@ async function render(Root, props, options = {}) {
2564
2890
  }, index === inOrder.length - 1);
2565
2891
  if (failure !== void 0) throw unsendable(failure, result.ctx);
2566
2892
  }
2567
- page = beforeBodyEnd(inlineBodies(rendered, bodies), [...ctx.portals, ...portals].join(""));
2893
+ let shell = rendered;
2894
+ for (const [key, catchHTML] of catches) shell = replaceBlock(shell, key, catchHTML);
2895
+ page = beforeBodyEnd(inlineBodies(shell, bodies), [...ctx.portals, ...portals].join(""));
2568
2896
  }
2569
2897
  return {
2570
2898
  html: page,
@@ -2586,6 +2914,26 @@ function rendersInOrder(option, request) {
2586
2914
  if (typeof option === "function") return option(request);
2587
2915
  return BOTS.test(request.headers.get("user-agent") ?? "");
2588
2916
  }
2917
+ /**
2918
+ * Replaces what a block holds, between its markers, with other markup. `key` is the scope and
2919
+ * the anchor in the start marker. A page without the block stays as it is.
2920
+ */
2921
+ function replaceBlock(html, key, inner) {
2922
+ const open = `<!--b${key}-->`;
2923
+ const start = html.indexOf(open);
2924
+ if (start === -1) return html;
2925
+ const comments = /<!--([^>]*?)-->/g;
2926
+ comments.lastIndex = start + open.length;
2927
+ let depth = 0;
2928
+ for (let found = comments.exec(html); found; found = comments.exec(html)) {
2929
+ const data = found[1];
2930
+ if (data[0] === "/") {
2931
+ if (depth === 0) return html.slice(0, start + open.length) + inner + html.slice(found.index);
2932
+ depth--;
2933
+ } else if (/^[btilP]-?\d/.test(data)) depth++;
2934
+ }
2935
+ return html;
2936
+ }
2589
2937
  const BOUNDARY_MARKER = /<!--(l[\d.]+|\/l)-->/g;
2590
2938
  /**
2591
2939
  * Puts the bodies of boundaries in place of their fallbacks, with the bodies
@@ -2619,6 +2967,25 @@ function inlineBodies(html, bodies) {
2619
2967
  return result + html.slice(position);
2620
2968
  }
2621
2969
  const HTML = /<html[\s>]/i;
2970
+ const HTML_TAG = /^<html((?:"[^"]*"|'[^']*'|[^>"'])*)>/i;
2971
+ const ATTRIBUTE_NAME = /([^\s"'<>/=]+)(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?/g;
2972
+ /**
2973
+ * Adds `b-html` to the `<html>` tag, with the names of the attributes that the page sent, so
2974
+ * client navigation can tell them from those that a script sets.
2975
+ */
2976
+ function nameHtmlAttributes(page) {
2977
+ const tag = HTML_TAG.exec(page);
2978
+ if (!tag) return page;
2979
+ const names = [];
2980
+ const attributes = tag[1].replace(ATTRIBUTE_NAME, (text, name) => {
2981
+ if (name.toLowerCase() === "b-html") return "";
2982
+ names.push(name);
2983
+ return text;
2984
+ });
2985
+ if (attributes === tag[1] && names.length === 0) return page;
2986
+ const list = names.length > 0 ? ` b-html="${escapeAttribute(names.join(" "))}"` : "";
2987
+ return `${page.slice(0, 5)}${attributes.trimEnd()}${list}>${page.slice(tag[0].length)}`;
2988
+ }
2622
2989
  /**
2623
2990
  * Inserts markup before `</body>`, or at the end if there is none. `index`
2624
2991
  * is where `</body>` is, when the caller found it already.
@@ -2639,7 +3006,7 @@ function firstRender(html, componentHead, state, options) {
2639
3006
  const match = HTML.exec(html);
2640
3007
  if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + html + tail + (options.end ?? "");
2641
3008
  const headContent = html.slice(0, match.index) + head;
2642
- let page = html.slice(match.index);
3009
+ let page = nameHtmlAttributes(html.slice(match.index));
2643
3010
  const lower = page.toLowerCase();
2644
3011
  const headEnd = lower.indexOf("</head>");
2645
3012
  let bodyEnd = lower.lastIndexOf("</body>");
@@ -2717,6 +3084,36 @@ function errorAnswer(error, fallback) {
2717
3084
  status: 500
2718
3085
  };
2719
3086
  }
3087
+ /** Errors that `safeError` logged, so a failure read in two places logs once. */
3088
+ const logged = /* @__PURE__ */ new WeakSet();
3089
+ /**
3090
+ * The error that the page state may carry in production: a plain `Error` with the message of a
3091
+ * `ServerError`, or `fallback`, and no stack, which holds paths of the server. Any other error is
3092
+ * logged once. A thrown value that is not an object is logged each time.
3093
+ */
3094
+ function safeError(error, fallback) {
3095
+ let message = fallback;
3096
+ if (error instanceof ServerError) message = error.message;
3097
+ else if (typeof error !== "object" || error === null) console.error(error);
3098
+ else if (!logged.has(error)) {
3099
+ logged.add(error);
3100
+ console.error(error);
3101
+ }
3102
+ const safe = new Error(message);
3103
+ safe.stack = "";
3104
+ return safe;
3105
+ }
3106
+ /**
3107
+ * The error that a `#catch` body gets on the server, which the page state carries to the
3108
+ * browser. In development it is the error itself, for debugging. In production it is a plain
3109
+ * `Error` with the message of a `ServerError`, or a generic message, and the real error is
3110
+ * logged, as for a server function that fails. The body renders with this value too, so the
3111
+ * HTML cannot print what the state does not carry.
3112
+ */
3113
+ function caught(error, ctx) {
3114
+ if (ctx.isDev()) return error;
3115
+ return safeError(error, "The page could not render this part");
3116
+ }
2720
3117
  /** True for a request that a `<form>` sent, without client code. */
2721
3118
  function isFormPost(request) {
2722
3119
  const type = request.headers.get("content-type") ?? "";
@@ -2908,7 +3305,9 @@ async function handleRequest(functions, request, prefix = "/_brumate", options =
2908
3305
  id,
2909
3306
  args
2910
3307
  };
2911
- const invoke = () => withEvent(event, () => fn(...args));
3308
+ function invoke() {
3309
+ return withEvent(event, () => fn(...args));
3310
+ }
2912
3311
  return runEntry(options.middleware, event, () => runEntry(options.fileMiddleware?.[id], event, () => posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke())));
2913
3312
  }
2914
3313
  /**
@@ -2923,7 +3322,8 @@ async function answerCall(functions, event, run) {
2923
3322
  const result = await run();
2924
3323
  const { refreshed } = event;
2925
3324
  if (refreshed?.size) {
2926
- const ids = Object.keys(functions).filter((key) => refreshed.has(unwrap(functions[key])));
3325
+ const ids = [];
3326
+ for (const key of Object.keys(functions)) if (refreshed.has(unwrap(functions[key]))) ids.push(key);
2927
3327
  if (ids.length > 0) headers.set("x-brumate-refresh", ids.join(","));
2928
3328
  }
2929
3329
  headers.set("content-type", STREAM_TYPE);
@@ -2960,7 +3360,8 @@ async function keptPage(key) {
2960
3360
  const page = JSON.parse(text);
2961
3361
  const tags = Object.keys(page.tags);
2962
3362
  const versions = await tagVersions(tags);
2963
- if (page.expires <= Date.now() || tags.some((tag) => versions[tag] !== page.tags[tag])) return;
3363
+ if (page.expires <= Date.now()) return;
3364
+ for (const tag of tags) if (versions[tag] !== page.tags[tag]) return;
2964
3365
  const headers = new Headers(page.headers);
2965
3366
  const maxAge = Number(/max-age=(\d+)/.exec(headers.get("cache-control") ?? "")?.[1] ?? 0);
2966
3367
  headers.set("age", String(Math.max(0, Math.floor(maxAge - (page.expires - Date.now()) / 1e3))));
@@ -2974,13 +3375,20 @@ async function keptPage(key) {
2974
3375
  async function keepPage(key, response, event) {
2975
3376
  const maxAge = Number(/max-age=(\d+)/.exec(response.headers.get("cache-control") ?? "")?.[1] ?? 0);
2976
3377
  if (maxAge <= 0) return;
2977
- const versions = await tagVersions([...event.cacheTags].filter(([, version]) => version === void 0).map(([tag]) => tag));
3378
+ const missing = [];
3379
+ for (const [tag, version] of event.cacheTags) if (version === void 0) missing.push(tag);
3380
+ const versions = await tagVersions(missing);
3381
+ const kept = [];
3382
+ for (const [name, value] of response.headers) if (name !== "set-cookie") kept.push([name, value]);
3383
+ const body = await response.clone().text();
3384
+ const tags = {};
3385
+ for (const [tag, version] of event.cacheTags) tags[tag] = version ?? versions[tag];
2978
3386
  const page = {
2979
3387
  status: response.status,
2980
- headers: [...response.headers].filter(([name]) => name !== "set-cookie"),
2981
- body: await response.clone().text(),
3388
+ headers: kept,
3389
+ body,
2982
3390
  expires: Date.now() + maxAge * 1e3,
2983
- tags: Object.fromEntries([...event.cacheTags].map(([tag, version]) => [tag, version ?? versions[tag]]))
3391
+ tags
2984
3392
  };
2985
3393
  await cacheStore().set(key, JSON.stringify(page), maxAge);
2986
3394
  }
@@ -3003,18 +3411,22 @@ function cacheControl(cache, event, response) {
3003
3411
  const warnedPrivate = /* @__PURE__ */ new Set();
3004
3412
  /** Imports every module of a matched route before it renders. */
3005
3413
  async function resolveView(view) {
3414
+ const names = Object.keys(view.slots);
3415
+ const pending = [];
3416
+ for (const slot of Object.values(view.slots)) pending.push(resolveView(slot));
3006
3417
  const [module, loading, ...slots] = await Promise.all([
3007
3418
  view.load(),
3008
3419
  view.loading?.(),
3009
- ...Object.values(view.slots).map(resolveView)
3420
+ ...pending
3010
3421
  ]);
3011
- const names = Object.keys(view.slots);
3422
+ const resolved = {};
3423
+ for (const [index, name] of names.entries()) resolved[name] = slots[index];
3012
3424
  return {
3013
3425
  key: view.key,
3014
3426
  component: module.default,
3015
3427
  loading: loading?.default,
3016
3428
  cache: module.cache,
3017
- slots: Object.fromEntries(names.map((name, index) => [name, slots[index]]))
3429
+ slots: resolved
3018
3430
  };
3019
3431
  }
3020
3432
  /**
@@ -3032,6 +3444,13 @@ async function renderView(view, props, ctx, scope) {
3032
3444
  * A component that renders a route, with its slots rendering where the
3033
3445
  * layout inserts them. `props` go to every view, such as `params`.
3034
3446
  */
3447
+ /** The component IDs of a view and of the views in its slots. */
3448
+ function viewIds(view) {
3449
+ const id = view.component.brumateId;
3450
+ const ids = id === void 0 ? [] : [id];
3451
+ for (const slot of Object.values(view.slots)) ids.push(...viewIds(slot));
3452
+ return ids;
3453
+ }
3035
3454
  function viewComponent(view, props) {
3036
3455
  return (_props, ctx) => {
3037
3456
  const own = { ...props };
@@ -3089,11 +3508,18 @@ async function renderPage(view, props, request, options, extra) {
3089
3508
  }
3090
3509
  const path = new URL(request.url).pathname;
3091
3510
  const endRender = event?.traced("render", path) ?? (() => {});
3092
- const hints = request.headers.has("x-brumate-base") ? [] : options.hints ?? [];
3511
+ let hints = [];
3512
+ if (!request.headers.has("x-brumate-base")) {
3513
+ const wanted = [...options.hints ?? []];
3514
+ for (const id of viewIds(view)) wanted.push(...options.bundleHints?.[id] ?? []);
3515
+ hints = [...new Set(wanted)];
3516
+ }
3093
3517
  const nonce = options.nonce === void 0 ? "" : ` nonce="${escapeAttribute(options.nonce)}"`;
3094
- const links = nonce ? [] : hints.map((url) => `<${url}>; rel=modulepreload`);
3518
+ const links = [];
3519
+ if (!nonce) for (const url of hints) links.push(`<${url}>; rel=modulepreload`);
3095
3520
  if (links.length > 0) options.earlyHints?.(links);
3096
- const preload = hints.map((url) => `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`).join("");
3521
+ let preload = "";
3522
+ for (const url of hints) preload += `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`;
3097
3523
  const parts = await render(viewComponent(view, props), {}, {
3098
3524
  ...options,
3099
3525
  request,
@@ -3278,7 +3704,7 @@ function fillHoles(tree, request, shell, options) {
3278
3704
  headers.append("vary", "x-brumate-defer");
3279
3705
  headers.append("vary", "x-brumate-base");
3280
3706
  const marked = shell.replace(HOLE, (template) => `${template} b-hole`);
3281
- const bodies = holes.map(async ([, at, boundary, base]) => {
3707
+ async function loadBody([, at, boundary, base]) {
3282
3708
  const asked = new Headers(request.headers);
3283
3709
  asked.set("x-brumate-defer", `${boundary} ${at}`);
3284
3710
  asked.set("x-brumate-base", base);
@@ -3293,13 +3719,16 @@ function fillHoles(tree, request, shell, options) {
3293
3719
  console.error(error);
3294
3720
  return "";
3295
3721
  }
3296
- });
3722
+ }
3723
+ const bodies = [];
3724
+ for (const hole of holes) bodies.push(loadBody(hole));
3297
3725
  const body = new ReadableStream({ async start(controller) {
3298
3726
  controller.enqueue(marked);
3299
- const pending = new Map(bodies.map((body, index) => [index, body.then((html) => ({
3727
+ const pending = /* @__PURE__ */ new Map();
3728
+ for (const [index, promise] of bodies.entries()) pending.set(index, promise.then((html) => ({
3300
3729
  html,
3301
3730
  index
3302
- }))]));
3731
+ })));
3303
3732
  while (pending.size > 0) {
3304
3733
  const { html, index } = await Promise.race(pending.values());
3305
3734
  pending.delete(index);
@@ -3312,7 +3741,8 @@ function fillHoles(tree, request, shell, options) {
3312
3741
  /** A response with more headers, such as cookies that middleware set. */
3313
3742
  function withHeaders(answer, headers) {
3314
3743
  const sent = new Set(answer.headers.getSetCookie());
3315
- const cookies = headers.getSetCookie().filter((cookie) => !sent.has(cookie));
3744
+ const cookies = [];
3745
+ for (const cookie of headers.getSetCookie()) if (!sent.has(cookie)) cookies.push(cookie);
3316
3746
  if (cookies.length === 0) return answer;
3317
3747
  const result = respond(answer.body, answer);
3318
3748
  for (const cookie of cookies) result.headers.append("set-cookie", cookie);
@@ -3344,7 +3774,8 @@ async function answerRoute(match, request, url, options) {
3344
3774
  const handler = endpoint[request.method] ?? (request.method === "HEAD" ? endpoint.GET : void 0);
3345
3775
  if (handler) return withEvent(options.event, () => handler(request, match.params));
3346
3776
  if (match.view.load === missingPage || request.method !== "GET") {
3347
- const allow = Object.keys(endpoint).filter((name) => /^[A-Z]+$/.test(name));
3777
+ const allow = [];
3778
+ for (const name of Object.keys(endpoint)) if (/^[A-Z]+$/.test(name)) allow.push(name);
3348
3779
  return new Response("Method not allowed", {
3349
3780
  status: 405,
3350
3781
  headers: { allow: allow.join(", ") }
@@ -3391,27 +3822,30 @@ async function renderRoute(match, request, url, options) {
3391
3822
  * function belongs to and the modifiers of its wrappers. A function that
3392
3823
  * refers to nothing in the browser is left out.
3393
3824
  */
3394
- function spread(attributes, on) {
3395
- const entries = on && attributes["b-on"];
3825
+ function spread(attributes, on, names) {
3826
+ const entries = on && ownValue("b-on", attributes["b-on"]);
3396
3827
  if (typeof entries === "string") {
3397
3828
  on.unshift(entries);
3398
3829
  const { "b-on": _, ...rest } = attributes;
3399
- return spread(rest, on);
3830
+ return spread(rest, on, names);
3400
3831
  }
3401
3832
  for (const [name, value] of Object.entries(attributes)) {
3402
- const reference = on && /^on[A-Z]/.test(name) && typeof value === "function" ? functionReferences.get(value) : void 0;
3403
- if (reference) {
3404
- const modifiers = value[MODIFIERS];
3405
- on.push(handlerEntry(name, reference.ref, reference.scope, modifiers, reference.args));
3833
+ const parts = on && /^on[A-Z]/.test(name) && typeof value === "function" ? value[PARTS] ?? [value] : [];
3834
+ for (const part of parts) {
3835
+ const reference = functionReferences.get(part);
3836
+ if (reference) {
3837
+ const modifiers = part[MODIFIERS];
3838
+ on.push(handlerEntry(name, reference.ref, reference.scope, modifiers, reference.args));
3839
+ }
3406
3840
  }
3407
3841
  if (on && (name === "value" || name === "checked") && isBinding(value)) {
3408
3842
  const setter = typeof value.set === "function" ? functionReferences.get(value.set) : void 0;
3409
3843
  on.push(bindEntry(name, value.ref, setter));
3410
3844
  }
3411
3845
  }
3412
- return spread$1(attributes);
3846
+ return spread$1(attributes, names);
3413
3847
  }
3414
3848
  //#endregion
3415
- export { withEvent as $, RateLimitError as A, matchRoute as B, stateScript as C, wait as D, streamState as E, ValidationError as F, storageStore as G, memoryStore as H, fieldErrors as I, dedupe as J, RequestEvent as K, parse as L, configureRateLimit as M, rateLimit as N, waitAll as O, parseSubmission as P, redirect as Q, parseForm as R, spread as S, streamParts as T, revalidate as U, cached as V, setCacheStore as W, getEvent as X, defineMiddleware as Y, isRedirect as Z, read as _, binding as a, renderToStream as b, dynamic as c, inlineBodies as d, insert as f, packState as g, memo as h, actionResult as i, clientAddress as j, idempotent as k, handleRequest as l, lazy as m, NotReady as n, children as o, isCrossSite as p, ServerError as q, action as r, component as s, Context as t, handleRoute as u, ready as v, stateValue as w, settled as x, render as y, safeParse as z };
3849
+ export { isRedirect as $, waitAll as A, parseForm as B, spacerTag as C, streamParts as D, stateValue as E, rateLimit as F, revalidate as G, matchRoute as H, parseSubmission as I, RequestEvent as J, setCacheStore as K, ValidationError as L, RateLimitError as M, clientAddress as N, streamState as O, configureRateLimit as P, getEvent as Q, fieldErrors as R, settled as S, stateScript as T, cached as U, safeParse as V, memoryStore as W, dedupe as X, ServerError as Y, defineMiddleware as Z, packState as _, binding as a, render as b, component as c, handleRoute as d, redirect as et, inlineBodies as f, memo as g, lazy as h, actionResult as i, idempotent as j, wait as k, dynamic as l, isCrossSite as m, NotReady as n, caught as o, insert as p, storageStore as q, action as r, children as s, Context as t, withEvent as tt, handleRequest as u, read as v, spread as w, renderToStream as x, ready as y, parse as z };
3416
3850
 
3417
- //# sourceMappingURL=server-CxVDYE_V.js.map
3851
+ //# sourceMappingURL=server-DjyOVJtJ.js.map