brumate 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +2 -2
  2. package/check.d.ts +49 -0
  3. package/dist/{boot-C25Sa6vq.d.ts → boot-SCWYwuUd.d.ts} +8 -10
  4. package/dist/cli.js +275 -15
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client-BBtVTOIt.js +3506 -0
  7. package/dist/client-BBtVTOIt.js.map +1 -0
  8. package/dist/{client-D0CqSxoO.d.ts → client-Cs3o4key.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-BLJjxqVc.js} +4 -4
  14. package/dist/defer-BLJjxqVc.js.map +1 -0
  15. package/dist/{devtools-CQgD7NPB.js → devtools-DTpsVFbn.js} +56 -82
  16. package/dist/devtools-DTpsVFbn.js.map +1 -0
  17. package/dist/{devtools-panel-BVB-W5q4.js → devtools-panel-C1Dfv6nq.js} +397 -333
  18. package/dist/devtools-panel-C1Dfv6nq.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-DZIiMDnS.js +506 -0
  24. package/dist/files-DZIiMDnS.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-DS9B1H-M.js} +92 -22
  31. package/dist/html-DS9B1H-M.js.map +1 -0
  32. package/dist/{html-Bq1rFxX_.d.ts → html-Gggepsf-.d.ts} +22 -5
  33. package/dist/index.d.ts +98 -10
  34. package/dist/index.js +639 -104
  35. package/dist/index.js.map +1 -1
  36. package/dist/{inspect-BHpOw1LF.js → inspect-DomFHy5O.js} +3832 -695
  37. package/dist/inspect-DomFHy5O.js.map +1 -0
  38. package/dist/{loader-Dos_3NP0.js → loader-D62komKu.js} +20 -14
  39. package/dist/loader-D62komKu.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-BNIpmZq2.js} +138 -9
  47. package/dist/produce-BNIpmZq2.js.map +1 -0
  48. package/dist/{produce-D0V0ICkz.d.ts → produce-CRfouraC.d.ts} +44 -5
  49. package/dist/{rpc-ygMRPmN4.js → rpc-BTMb8jap.js} +11 -6
  50. package/dist/rpc-BTMb8jap.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-CxVDYE_V.js → server-BTtsQFFw.js} +633 -163
  83. package/dist/server-BTtsQFFw.js.map +1 -0
  84. package/dist/{server-DuFYRXrd.d.ts → server-CYw15Dsg.d.ts} +103 -22
  85. package/dist/{static-loader-nZssh66R.js → static-loader-C_GYIFtt.js} +79 -99
  86. package/dist/static-loader-C_GYIFtt.js.map +1 -0
  87. package/dist/{static-loader-Drpr0AzI.d.ts → static-loader-DVuLmXeu.d.ts} +2 -2
  88. package/dist/{stream-DCYZO4IF.js → stream-r4V5zBKm.js} +102 -16
  89. package/dist/stream-r4V5zBKm.js.map +1 -0
  90. package/dist/vite.d.ts +13 -20
  91. package/dist/vite.js +1956 -554
  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 spread$1, S as rawHTML, b as ownValue, d as escapeAttribute, f as handlerEntry, g as isRaw, n as VOID_ELEMENTS, p as insertValue, r as actionAttributes, s as bindEntry, u as escape, v as onAttribute, w as styleElement } from "./html-DS9B1H-M.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-r4V5zBKm.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-BNIpmZq2.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}.`);
@@ -1262,6 +1322,8 @@ var Context = class Context {
1262
1322
  /** The scope that the render used last, since it uses one a few times in a row. */
1263
1323
  last;
1264
1324
  root;
1325
+ /** The keys of the signals that a visible `$client` waits for. See `near`. */
1326
+ waited;
1265
1327
  /** The ID spaces of the blocks that the render is in, from the outside in. */
1266
1328
  spaces;
1267
1329
  baseId;
@@ -1282,6 +1344,10 @@ var Context = class Context {
1282
1344
  markup: true
1283
1345
  };
1284
1346
  onBoundary;
1347
+ /** The `#try` blocks of the parents of this context, from the outside in. */
1348
+ outer = [];
1349
+ /** The `#try` blocks of this context that are rendering their bodies now. */
1350
+ catchers = [];
1285
1351
  /** The scope that renders the next component, which becomes its owner. */
1286
1352
  owner;
1287
1353
  /**
@@ -1295,6 +1361,8 @@ var Context = class Context {
1295
1361
  rpcPrefix = "/_brumate";
1296
1362
  /** The ID of the build, for forms that post to server functions. See `RenderOptions`. */
1297
1363
  build;
1364
+ /** True in development, where a memo that failed or a `#catch` sends its error to the browser. */
1365
+ development = false;
1298
1366
  /** Results of server functions that a form posted to this page, for `$action`. */
1299
1367
  actions = /* @__PURE__ */ new Map();
1300
1368
  /** The params of the route of the page, for `$route`. */
@@ -1386,6 +1454,10 @@ var Context = class Context {
1386
1454
  rpc() {
1387
1455
  return this.root.rpcPrefix;
1388
1456
  }
1457
+ /** True when the render is in development. */
1458
+ isDev() {
1459
+ return this.root.development;
1460
+ }
1389
1461
  /** Returns the ID of the build, when the render has one. */
1390
1462
  buildId() {
1391
1463
  return this.root.build;
@@ -1412,7 +1484,7 @@ var Context = class Context {
1412
1484
  root.owner = void 0;
1413
1485
  }
1414
1486
  }
1415
- const inserted = root.inserted.findLast((entry) => entry.from === up);
1487
+ const inserted = findLastInserted(root.inserted, up);
1416
1488
  if (inserted) {
1417
1489
  up = inserted.at;
1418
1490
  record.t = inserted.at;
@@ -1458,12 +1530,18 @@ var Context = class Context {
1458
1530
  * keep `from`, the scope of the markup that wrote them, for their values,
1459
1531
  * and find their contexts from `at`.
1460
1532
  */
1461
- async children(from, at, renderBody) {
1533
+ async children(from, at, renderBody, tag) {
1534
+ const { inserted } = this.root;
1535
+ const outer = findLastInserted(inserted, at);
1462
1536
  const entry = {
1463
1537
  from,
1464
- at
1538
+ at: outer ? outer.at : at,
1539
+ tag: tag ?? outer?.tag
1465
1540
  };
1466
- const { inserted } = this.root;
1541
+ if (outer) {
1542
+ const passing = this.find(at);
1543
+ if (passing) passing.record.f = outer.at;
1544
+ }
1467
1545
  inserted.push(entry);
1468
1546
  try {
1469
1547
  return await renderBody();
@@ -1471,6 +1549,10 @@ var Context = class Context {
1471
1549
  inserted.splice(inserted.indexOf(entry), 1);
1472
1550
  }
1473
1551
  }
1552
+ /** The tag of the element where the children that render now are inserted, for spacers. */
1553
+ spacerTag() {
1554
+ return this.root.inserted.at(-1)?.tag ?? "div";
1555
+ }
1474
1556
  /**
1475
1557
  * The ID that `$id()` makes: the scope's ID and the position of the call.
1476
1558
  * A dot in a scope ID inside a `#loading` body becomes `_`, so the ID also
@@ -1493,9 +1575,9 @@ var Context = class Context {
1493
1575
  record.v[context.key] = value;
1494
1576
  }
1495
1577
  /**
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.
1578
+ * Reads a context from the nearest scope above `scope` that provides it.
1579
+ * With `slot`, records which slot holds it, so the client can update it
1580
+ * when the provided value changes.
1499
1581
  */
1500
1582
  consume(context, scope, slot) {
1501
1583
  if (slot !== void 0) {
@@ -1503,7 +1585,7 @@ var Context = class Context {
1503
1585
  record.x ??= {};
1504
1586
  record.x[context.key] = slot;
1505
1587
  }
1506
- for (let id = scope; id !== void 0;) {
1588
+ for (let id = this.find(scope)?.parent; id !== void 0;) {
1507
1589
  const node = this.find(id);
1508
1590
  if (node?.values?.has(context.key)) return node.values.get(context.key);
1509
1591
  id = node?.parent;
@@ -1601,19 +1683,65 @@ var Context = class Context {
1601
1683
  }
1602
1684
  /** The records of the scopes of this render, by ID, in the order the render made them. */
1603
1685
  get state() {
1604
- return new Map(this.scopes.map((entry) => [entry.id, entry.record]));
1686
+ const state = /* @__PURE__ */ new Map();
1687
+ for (const entry of this.scopes) state.set(entry.id, entry.record);
1688
+ return state;
1605
1689
  }
1606
1690
  /**
1607
1691
  * The list of each list item scope whose list is a slot of an enclosing
1608
1692
  * scope, as `[scope, slot]`. The items of a list share one array.
1609
1693
  */
1610
1694
  get sources() {
1611
- return new Map(this.scopes.flatMap((entry) => entry.source ? [[entry.id, entry.source]] : []));
1695
+ const sources = /* @__PURE__ */ new Map();
1696
+ for (const entry of this.scopes) if (entry.source) sources.set(entry.id, entry.source);
1697
+ return sources;
1698
+ }
1699
+ /** The scope that `unbind` collects the promise props of its component in. */
1700
+ sink(scope) {
1701
+ return this.entry(scope);
1612
1702
  }
1613
1703
  slots(scope, values, names) {
1614
1704
  const entry = this.entry(scope);
1615
1705
  entry.record.s = values;
1616
1706
  if (names) entry.names = names;
1707
+ const forwarded = this.forwards?.get(scope);
1708
+ if (forwarded) {
1709
+ this.forwards.delete(scope);
1710
+ for (const [slot, value] of forwarded) values[slot] = value;
1711
+ }
1712
+ let wrapped;
1713
+ for (let slot = 0; slot < values.length; slot++) {
1714
+ const value = values[slot];
1715
+ if (value instanceof Promise && entry.props?.includes(value) && values.indexOf(value) === slot) {
1716
+ wrapped ??= [...values];
1717
+ wrapped[slot] = new PropPromise(this.isDev() ? value : value.catch((error) => {
1718
+ const safe = new Error(error instanceof ServerError ? error.message : "The page could not compute a value");
1719
+ safe.stack = "";
1720
+ throw safe;
1721
+ }));
1722
+ }
1723
+ }
1724
+ entry.props = void 0;
1725
+ if (wrapped) entry.record.s = wrapped;
1726
+ }
1727
+ /** Elements that bound props of components forwarded to the slots of scopes that have no slots yet. */
1728
+ forwards;
1729
+ /**
1730
+ * Writes the element that a component forwards to a slot of a scope above it, and on through
1731
+ * the props that scope binds in turn. The parent records its slots after its children render,
1732
+ * so a write for a scope that has none waits for them.
1733
+ */
1734
+ forward(target, value) {
1735
+ const record = this.ownRecord(target.scope);
1736
+ if (!record?.s) {
1737
+ const waiting = (this.forwards ??= /* @__PURE__ */ new Map()).get(target.scope) ?? /* @__PURE__ */ new Map();
1738
+ waiting.set(target.slot, value);
1739
+ this.forwards.set(target.scope, waiting);
1740
+ return;
1741
+ }
1742
+ record.s[target.slot] = value;
1743
+ const next = record.b?.[target.slot];
1744
+ if (isSlotReference(next)) this.forward(next, value);
1617
1745
  }
1618
1746
  /**
1619
1747
  * Records the props that a parent bound with `$bind`, among the props that
@@ -1621,6 +1749,18 @@ var Context = class Context {
1621
1749
  * writes in the browser go to the parent's slots.
1622
1750
  */
1623
1751
  bindings(scope, props, slots) {
1752
+ this.bound(scope, props, slots);
1753
+ for (const [name, slot] of Object.entries(slots)) {
1754
+ const value = props[name];
1755
+ const written = this.entry(scope).record.s?.[slot];
1756
+ if (isBinding(value) && written instanceof ElementReference && isSlotReference(value.target)) this.forward(value.target, written);
1757
+ }
1758
+ }
1759
+ /**
1760
+ * Records where the bound props write, before the component renders its markup, so an element
1761
+ * that it forwards can name the signal at the end of the bindings. See `refKey`.
1762
+ */
1763
+ bound(scope, props, slots) {
1624
1764
  for (const [name, slot] of Object.entries(slots)) {
1625
1765
  const value = props[name];
1626
1766
  if (isBinding(value)) (this.entry(scope).record.b ??= {})[slot] = value.target;
@@ -1645,6 +1785,42 @@ var Context = class Context {
1645
1785
  if (links[anchor] === child) delete links[anchor];
1646
1786
  });
1647
1787
  }
1788
+ /**
1789
+ * A `ref` that the rest props of a component hold is a binding of a signal above. The element
1790
+ * that spreads them goes to that signal, as when the component names `ref` itself.
1791
+ */
1792
+ restRef(attributes, scope, anchor, tag) {
1793
+ const value = attributes.ref;
1794
+ if (typeof tag !== "function" && isBinding(value)) {
1795
+ if (isSlotReference(value.target)) this.forward(value.target, new ElementReference(scope, anchor));
1796
+ else (this.record(scope).r ??= {})[anchor] = value.target;
1797
+ }
1798
+ return attributes;
1799
+ }
1800
+ /**
1801
+ * The `b-near` attribute of a visible `$client` that reads the signal at `slot` of `scope`,
1802
+ * which a component may get with `ref=$bind(...)`. It records the key, so `refKey` marks only
1803
+ * the elements that a callback waits for.
1804
+ */
1805
+ near(scope, slot) {
1806
+ const key = `${scope}.${slot}`;
1807
+ (this.root.waited ??= /* @__PURE__ */ new Set()).add(key);
1808
+ return ` b-near="${key}"`;
1809
+ }
1810
+ /**
1811
+ * The `b-r` attribute of an element that a component forwards for its caller: the scope and slot
1812
+ * of the signal at the end of the bindings, `S.slot`, when a visible `$client` waits for it.
1813
+ * The loader finds the element by it. Empty otherwise.
1814
+ */
1815
+ refKey(scope, slot) {
1816
+ let target = this.ownRecord(scope)?.b?.[slot];
1817
+ let key = "";
1818
+ while (isSlotReference(target)) {
1819
+ key = `${target.scope}.${target.slot}`;
1820
+ target = this.find(target.scope)?.record.b?.[target.slot];
1821
+ }
1822
+ return this.root.waited?.has(key) ? ` b-r="${key}"` : "";
1823
+ }
1648
1824
  /** Returns the reference that a `ref` signal holds on the server. */
1649
1825
  element(scope, anchor) {
1650
1826
  return new ElementReference(scope, anchor);
@@ -1657,6 +1833,17 @@ var Context = class Context {
1657
1833
  */
1658
1834
  fn(value, ref, scope, args) {
1659
1835
  if (typeof value !== "function") return value;
1836
+ if (args === void 0 && /#t\d/.test(ref)) {
1837
+ const render = value;
1838
+ function template(...rest) {
1839
+ return new Children(scope, async () => {
1840
+ const html = await render(...rest);
1841
+ return isRaw(html) ? rawHTML(html) : insertValue(html);
1842
+ });
1843
+ }
1844
+ functionReferences.set(template, new FunctionReference(ref, scope));
1845
+ return template;
1846
+ }
1660
1847
  if (args === void 0) {
1661
1848
  functionReferences.set(value, new FunctionReference(ref, scope));
1662
1849
  return value;
@@ -1764,6 +1951,18 @@ var Context = class Context {
1764
1951
  fallbackEnd(id) {
1765
1952
  return this.reveal?.hidden.has(id) ? "</template>" : "";
1766
1953
  }
1954
+ /**
1955
+ * Starts a `#try` body. A `#loading` body inside it that fails renders the `#catch` body with
1956
+ * `draw`, after the page is sent. The returned function ends the `#try` body.
1957
+ */
1958
+ catcher(key, draw) {
1959
+ const entry = {
1960
+ key,
1961
+ render: draw
1962
+ };
1963
+ this.catchers.push(entry);
1964
+ return () => removeLast(this.catchers, entry);
1965
+ }
1767
1966
  /** Returns the ID of a new `#loading` boundary. */
1768
1967
  boundary() {
1769
1968
  return spaceId(this.space, this.space.boundary++);
@@ -1801,6 +2000,8 @@ var Context = class Context {
1801
2000
  register(id, renderBody, inTarget, around = false) {
1802
2001
  const child = new Context(this.root, void 0, 0, `${id}.`);
1803
2002
  child.inTarget = inTarget;
2003
+ const catchers = [...this.outer, ...this.catchers];
2004
+ child.outer = catchers;
1804
2005
  const group = this.reveal;
1805
2006
  group?.add(id);
1806
2007
  const end = around ? void 0 : this.traced("body", `#loading ${id}`);
@@ -1817,7 +2018,8 @@ var Context = class Context {
1817
2018
  throw error;
1818
2019
  }),
1819
2020
  around,
1820
- group
2021
+ group,
2022
+ catchers
1821
2023
  };
1822
2024
  boundary.render.catch(() => {});
1823
2025
  const root = this.root;
@@ -1927,18 +2129,32 @@ function ready(node) {
1927
2129
  }
1928
2130
  /**
1929
2131
  * 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.
2132
+ * a promise of it while it loads. A memo that fails gives a `MemoError`
2133
+ * either way, so the page renders, the stream goes on, and a read in the
2134
+ * browser throws the error as a memo that failed there.
1933
2135
  */
1934
2136
  function stateValue(node) {
1935
2137
  try {
1936
2138
  return read(node);
1937
2139
  } catch (error) {
1938
- return error instanceof NotReady ? wait(node) : Promise.reject(error);
2140
+ if (error instanceof NotReady) return wait(node).catch((failure) => heldError(failure, node.ctx));
2141
+ return heldError(error, node.ctx);
1939
2142
  }
1940
2143
  }
1941
2144
  /**
2145
+ * The error of a memo for the page state. In development it is the error as seroval
2146
+ * writes it: its name, message, own properties, `cause` and the `errors` of an `AggregateError`,
2147
+ * and no stack (the serial options leave stacks out). In production it is the message of
2148
+ * a `ServerError`, which the app chose to show, or else a generic message, and the error is
2149
+ * logged, as for a server function that fails.
2150
+ */
2151
+ function heldError(error, ctx) {
2152
+ let sent;
2153
+ if (ctx?.isDev()) sent = error instanceof Error ? error : new Error(String(error));
2154
+ else sent = safeError(error, "The page could not compute a value");
2155
+ return Object.assign(new MemoError(sent), { [Symbol.for("brumate.held")]: true });
2156
+ }
2157
+ /**
1942
2158
  * Starts every memo of a run of declarations that the render waits for,
1943
2159
  * so they load at the same time. Returns a promise that settles when all
1944
2160
  * of them have, or undefined when none is loading. A memo that fails
@@ -1974,8 +2190,8 @@ const LAZY = Symbol.for("brumate.lazy");
1974
2190
  * them, so they read the contexts that the component provides. `from` is the
1975
2191
  * scope of the markup that wrote them.
1976
2192
  */
1977
- function children(from, renderBody) {
1978
- return new Children(from, renderBody);
2193
+ function children(from, renderBody, ref) {
2194
+ return new Children(from, renderBody, ref);
1979
2195
  }
1980
2196
  /** The symbol of raw HTML. See `html.ts`. */
1981
2197
  const RAW = Symbol.for("brumate.raw");
@@ -1989,14 +2205,32 @@ var Children = class {
1989
2205
  [LAZY];
1990
2206
  /** The HTML of the first render, under the symbol of raw HTML. */
1991
2207
  [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;
2208
+ /**
2209
+ * The export that renders the children in the browser, which the page state sends in place of
2210
+ * their HTML. Each insert in the browser then renders them with new scopes.
2211
+ */
2212
+ [CHILDREN_REF];
2213
+ constructor(from, renderBody, ref) {
2214
+ if (ref !== void 0) this[CHILDREN_REF] = new ChildrenReference(ref, from);
2215
+ this[LAZY] = async (ctx, at, tag, anchor) => {
2216
+ const reference = this[CHILDREN_REF];
2217
+ if (reference && reference.at === void 0 && anchor !== void 0) {
2218
+ reference.at = at;
2219
+ reference.anchor = anchor;
2220
+ }
2221
+ const html = await (at === void 0 ? renderBody(ctx) : ctx.children(from, at, () => renderBody(ctx), tag));
2222
+ if (ref === void 0) this[RAW] ??= html;
1996
2223
  return html;
1997
2224
  };
1998
2225
  }
1999
2226
  };
2227
+ /**
2228
+ * The tag of the spacers of a windowed list in children: a row in a table body, an item in a
2229
+ * list, as the element where the children are inserted says, or else a `div`.
2230
+ */
2231
+ function spacerTag(ctx) {
2232
+ return ctx.spacerTag();
2233
+ }
2000
2234
  /** Makes markup that renders where it is inserted, such as the children of a layout. */
2001
2235
  function lazy(renderAt) {
2002
2236
  return { [LAZY]: renderAt };
@@ -2021,15 +2255,21 @@ function actionResult(ctx, fn) {
2021
2255
  return ctx.actionResult(fn);
2022
2256
  }
2023
2257
  /**
2024
- * Renders a value inserted in markup. `ctx` and `scope` are where it is
2025
- * inserted, for markup that renders there.
2258
+ * Renders a value inserted in markup. `ctx`, `scope` and `anchor` are where it
2259
+ * is inserted, for markup that renders there.
2026
2260
  */
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);
2261
+ function insert(value, ctx, scope, tag, anchor) {
2262
+ 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));
2263
+ if (isLazy(value) && ctx) return value[LAZY](ctx, scope, tag, anchor);
2030
2264
  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(""));
2265
+ const parts = [];
2266
+ let allStrings = true;
2267
+ for (const item of value) {
2268
+ const part = insert(item, ctx, scope, tag);
2269
+ if (typeof part !== "string") allStrings = false;
2270
+ parts.push(part);
2271
+ }
2272
+ return allStrings ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
2033
2273
  }
2034
2274
  return insertValue(value);
2035
2275
  }
@@ -2037,30 +2277,48 @@ function insert(value, ctx, scope) {
2037
2277
  * Renders a child component. With `scope` and `anchor`, records the child's
2038
2278
  * scope so the parent can update its props on the client.
2039
2279
  */
2040
- function component(Child, props, ctx, scope, anchor) {
2280
+ function component(Child, props, ctx, scope, anchor, paragraph) {
2041
2281
  if (ctx.past()) return Promise.resolve("");
2042
2282
  if (scope !== void 0 && anchor !== void 0) ctx.link(scope, anchor, ctx.peek());
2043
2283
  if (scope !== void 0) ctx.own(scope);
2044
2284
  const given = props?.children;
2045
- if (!(given instanceof Children)) return Child(props, ctx);
2285
+ if (!(given instanceof Children) || given[CHILDREN_REF]) return checkParagraph(Child(props, ctx), ctx, paragraph);
2046
2286
  const root = ctx.peek();
2047
- return Child(props, ctx).then(async (html) => {
2287
+ return checkParagraph(Child(props, ctx).then(async (html) => {
2048
2288
  if (given[RAW] === void 0) await given[LAZY](ctx, root);
2049
2289
  return html;
2290
+ }), ctx, paragraph);
2291
+ }
2292
+ /**
2293
+ * In development, throws when a component inside a `<p>` starts with an element that closes the
2294
+ * `<p>`. `paragraph` names the component and where it is, and only the compiler sets it. The
2295
+ * browser splits the markers of the blocks of the page there, so it is an error before that.
2296
+ */
2297
+ function checkParagraph(rendered, ctx, paragraph) {
2298
+ if (paragraph === void 0 || !ctx.isDev()) return rendered;
2299
+ return rendered.then((html) => {
2300
+ const tag = typeof html === "string" ? firstTag(html) : void 0;
2301
+ 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"`);
2302
+ return html;
2050
2303
  });
2051
2304
  }
2052
2305
  /** Renders a dynamic tag, which can be an element name or a component. */
2053
- function dynamic(tag, attributes, content, ctx, scope) {
2306
+ function dynamic(tag, attributes, content, ctx, scope, ref) {
2054
2307
  if (typeof tag === "function") {
2055
- const entries = attributes["b-on"];
2056
- const props = typeof entries === "string" && scope !== void 0 ? {
2308
+ if (ref !== void 0) attributes = {
2057
2309
  ...attributes,
2058
- "b-on": entries.split(" ").map((entry) => entry.includes("@") ? entry : `${entry}@${scope}`).join(" ")
2059
- } : attributes;
2310
+ ref
2311
+ };
2312
+ const { "b-b": bound, "b-on": entries, ...passed } = attributes;
2313
+ addEntryHandlers(passed, entries, scope, (reference) => {
2314
+ const handler = Object.assign(() => {}, reference.modifiers ? { [MODIFIERS]: reference.modifiers } : {});
2315
+ functionReferences.set(handler, reference);
2316
+ return handler;
2317
+ });
2060
2318
  return component(tag, content ? {
2061
- ...props,
2319
+ ...passed,
2062
2320
  children: content
2063
- } : props, ctx, scope);
2321
+ } : passed, ctx, scope, bound === void 0 ? void 0 : Number(ownValue("b-b", bound).split(":")[1]));
2064
2322
  }
2065
2323
  const on = [];
2066
2324
  const open = `<${tag}${spread(attributes, on)}${onAttribute(on, "")}>`;
@@ -2077,7 +2335,8 @@ function holds(value, target, seen = /* @__PURE__ */ new Set()) {
2077
2335
  if (value instanceof Map) items = [...value.keys(), ...value.values()];
2078
2336
  else if (value instanceof Set) items = [...value];
2079
2337
  else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype) items = Object.values(value);
2080
- return items.some((item) => holds(item, target, seen));
2338
+ for (const item of items) if (holds(item, target, seen)) return true;
2339
+ return false;
2081
2340
  }
2082
2341
  /**
2083
2342
  * The error of a value in the state of a page that cannot be sent to the
@@ -2088,7 +2347,11 @@ function unsendable(error, ctx) {
2088
2347
  const target = secret ?? error.value;
2089
2348
  if (target === void 0) return error instanceof Error ? error : new Error(String(error));
2090
2349
  for (const { record, names } of ctx.scopes) {
2091
- const index = (record.s ?? []).findIndex((value) => holds(value, target));
2350
+ let index = -1;
2351
+ for (const [slot, value] of (record.s ?? []).entries()) if (holds(value, target)) {
2352
+ index = slot;
2353
+ break;
2354
+ }
2092
2355
  if (index === -1) continue;
2093
2356
  let owner = record;
2094
2357
  while (owner && owner.m === void 0 && owner.p !== void 0) owner = ctx.ownRecord(owner.p);
@@ -2136,6 +2399,11 @@ const PACKED_FIELDS = /* @__PURE__ */ new Set([
2136
2399
  "i",
2137
2400
  "c"
2138
2401
  ]);
2402
+ /** True when a record has a field that `PackedState` has no place for. */
2403
+ function hasUnpackedField(record) {
2404
+ for (const field of Object.keys(record)) if (!PACKED_FIELDS.has(field)) return true;
2405
+ return false;
2406
+ }
2139
2407
  /** A group of `PackedState` while `packState` collects it. */
2140
2408
  /** How many of the last groups `packState` compares a record with, before it looks up its name. */
2141
2409
  const RECENT_GROUPS = 4;
@@ -2148,7 +2416,9 @@ function splitId(id) {
2148
2416
  /** The records of a state as a map, for a state written as an object, such as in tests. */
2149
2417
  function toStateMap(state) {
2150
2418
  if (state instanceof Map) return state;
2151
- return new Map(Object.entries(state).map(([key, record]) => [parseId(key), record]));
2419
+ const map = /* @__PURE__ */ new Map();
2420
+ for (const [key, record] of Object.entries(state)) map.set(parseId(key), record);
2421
+ return map;
2152
2422
  }
2153
2423
  /**
2154
2424
  * Visits the scopes of a state in the order of the keys of an object: number
@@ -2161,7 +2431,9 @@ function visitOrdered(entries, visit) {
2161
2431
  let last = -Infinity;
2162
2432
  for (const entry of entries) if (typeof entry.id === "number") {
2163
2433
  if (entry.id < last) {
2164
- numbers = entries.filter((item) => typeof item.id === "number").toSorted((a, b) => a.id - b.id);
2434
+ const numeric = [];
2435
+ for (const item of entries) if (typeof item.id === "number") numeric.push(item);
2436
+ numbers = numeric.toSorted((a, b) => a.id - b.id);
2165
2437
  break;
2166
2438
  }
2167
2439
  last = entry.id;
@@ -2197,17 +2469,19 @@ function groupSource(record, group) {
2197
2469
  */
2198
2470
  function packState(input, sources) {
2199
2471
  const state = toStateMap(input);
2200
- return packEntries(Array.from(state, ([id, record]) => {
2472
+ const entries = [];
2473
+ for (const [id, record] of state) {
2201
2474
  const [prefix, n] = splitId(id);
2202
- return {
2475
+ entries.push({
2203
2476
  id,
2204
2477
  prefix,
2205
2478
  n,
2206
2479
  record,
2207
2480
  ctx: void 0,
2208
2481
  source: sources?.get(id)
2209
- };
2210
- }), (id) => state.get(id));
2482
+ });
2483
+ }
2484
+ return packEntries(entries, (id) => state.get(id));
2211
2485
  }
2212
2486
  /** Packs the scopes of a render. `lookup` finds the record of a scope in the same state. */
2213
2487
  function packEntries(scopes, lookup) {
@@ -2221,7 +2495,7 @@ function packEntries(scopes, lookup) {
2221
2495
  const [ownerPrefix, owner] = splitId(record.o);
2222
2496
  base = ownerPrefix === prefix ? n - owner : void 0;
2223
2497
  }
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))) {
2498
+ if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 || hasUnpackedField(record)) {
2225
2499
  result[id] = record;
2226
2500
  return;
2227
2501
  }
@@ -2230,7 +2504,11 @@ function packEntries(scopes, lookup) {
2230
2504
  if ("i" in record) flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? 1 : 2;
2231
2505
  if (record.c) flags |= 4;
2232
2506
  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);
2507
+ let group;
2508
+ 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) {
2509
+ group = item;
2510
+ break;
2511
+ }
2234
2512
  if (!group) {
2235
2513
  const name = `${prefix}:${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ""}`;
2236
2514
  group = groups.get(name);
@@ -2299,13 +2577,13 @@ function packEntries(scopes, lookup) {
2299
2577
  function serializeState(state, refs, onRecord, onError, onDone, sources, last = false) {
2300
2578
  const packed = state instanceof Context ? packEntries(state.scopes, (id) => state.ownRecord(id)) : packState(state, sources);
2301
2579
  let leaked = false;
2302
- const send = (code, initial) => {
2580
+ function send(code, initial) {
2303
2581
  const error = leaked ? void 0 : secretError(code);
2304
2582
  if (error) {
2305
2583
  leaked = true;
2306
2584
  onError(error);
2307
2585
  } else if (!leaked) onRecord(code, initial);
2308
- };
2586
+ }
2309
2587
  if (last) {
2310
2588
  let code;
2311
2589
  try {
@@ -2366,12 +2644,39 @@ function stateScript(code, scopes = false, attributes = {}) {
2366
2644
  if (attributes.route !== void 0) extra += ` b-route="${escapeAttribute(attributes.route)}"`;
2367
2645
  if (attributes.params !== void 0) extra += ` b-params="${escapeAttribute(JSON.stringify(attributes.params))}"`;
2368
2646
  if (attributes.build !== void 0) extra += ` b-build="${escapeAttribute(attributes.build)}"`;
2647
+ if (attributes.fail !== void 0) extra += ` b-fail="${attributes.fail}"`;
2648
+ if (attributes.catches !== void 0) extra += ` b-catch="${attributes.catches}"`;
2369
2649
  return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
2370
2650
  }
2371
2651
  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
2652
  const SHOW_FALLBACK = `function $bF(i){var t=document.querySelector('template[b-f="'+i+'"]');t&&t.replaceWith(t.content)}`;
2373
2653
  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
2654
  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()}`;
2655
+ /**
2656
+ * The record that tells the browser a `#loading` body failed. Its code is the error, and the
2657
+ * browser hands it to the nearest `#try` around the boundary.
2658
+ */
2659
+ function failScript(error, refs, boundary, root, nonce) {
2660
+ let code;
2661
+ try {
2662
+ code = crossSerialize(error, {
2663
+ plugins: syncPlugins,
2664
+ ...serialOptions(),
2665
+ refs
2666
+ });
2667
+ } catch {
2668
+ code = crossSerialize(new Error(String(error)), {
2669
+ plugins: syncPlugins,
2670
+ ...serialOptions(),
2671
+ refs
2672
+ });
2673
+ }
2674
+ return stateScript(code, false, {
2675
+ root,
2676
+ nonce,
2677
+ fail: boundary
2678
+ });
2679
+ }
2375
2680
  /** The `pending` of a render that has nothing left to send. */
2376
2681
  const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
2377
2682
  done: true,
@@ -2383,10 +2688,10 @@ function createQueue() {
2383
2688
  let wake;
2384
2689
  let closed = false;
2385
2690
  let failure;
2386
- const notify = () => {
2691
+ function notify() {
2387
2692
  wake?.();
2388
2693
  wake = void 0;
2389
- };
2694
+ }
2390
2695
  return {
2391
2696
  push(item) {
2392
2697
  items.push(item);
@@ -2423,6 +2728,7 @@ async function render(Root, props, options = {}) {
2423
2728
  if (options.actions) ctx.actions = options.actions;
2424
2729
  if (options.params) ctx.params = options.params;
2425
2730
  ctx.build = options.build;
2731
+ ctx.development = options.dev === true;
2426
2732
  if (options.defer) ctx.target = { ...options.defer };
2427
2733
  ctx.inOrder = !options.defer && rendersInOrder(options.inOrder ?? "bots", options.request ?? options.event?.request);
2428
2734
  const event = options.event ?? (options.request ? new RequestEvent(options.request, {
@@ -2436,7 +2742,9 @@ async function render(Root, props, options = {}) {
2436
2742
  ctx.send();
2437
2743
  const html = beforeBodyEnd(rendered, ctx.portals.join(""));
2438
2744
  let queue;
2439
- const pending = () => queue ??= createQueue();
2745
+ function pending() {
2746
+ return queue ??= createQueue();
2747
+ }
2440
2748
  const refs = /* @__PURE__ */ new Map();
2441
2749
  const { nonce } = options;
2442
2750
  const root = options.defer ? `d${options.defer.boundary}` : options.base;
@@ -2444,19 +2752,19 @@ async function render(Root, props, options = {}) {
2444
2752
  let open = 0;
2445
2753
  let swap = false;
2446
2754
  let headSwap = false;
2447
- const finish = () => {
2755
+ function finish() {
2448
2756
  open--;
2449
2757
  if (open === 0) queue?.close();
2450
- };
2758
+ }
2451
2759
  let boundaries = 0;
2452
2760
  const swapScript = options.dev ? SWAP_DEV : SWAP;
2453
2761
  let fallbackDefined = false;
2454
- const showFallback = () => {
2762
+ function showFallback() {
2455
2763
  if (fallbackDefined) return "";
2456
2764
  fallbackDefined = true;
2457
2765
  return `${SHOW_FALLBACK};`;
2458
- };
2459
- const serialize = (target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) => {
2766
+ }
2767
+ function serialize(target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) {
2460
2768
  open++;
2461
2769
  serializeState(target, refs, (code, initial) => {
2462
2770
  if (initial) {
@@ -2475,9 +2783,27 @@ async function render(Root, props, options = {}) {
2475
2783
  nonce
2476
2784
  }));
2477
2785
  }, onError, finish, void 0, last);
2478
- };
2786
+ }
2787
+ async function renderCatch(boundary, error) {
2788
+ const entry = boundary.catchers.at(-1);
2789
+ if (!entry) return;
2790
+ const child = new Context(ctx, void 0, 0, `${boundary.id}c.`);
2791
+ child.outer = boundary.catchers.slice(0, -1);
2792
+ try {
2793
+ return {
2794
+ html: await entry.render(child, error),
2795
+ ctx: child,
2796
+ key: entry.key
2797
+ };
2798
+ } catch (failure) {
2799
+ console.error(failure);
2800
+ return;
2801
+ }
2802
+ }
2479
2803
  const inOrder = ctx.inOrder ? [] : void 0;
2480
- const stopped = () => event?.signal.aborted === true;
2804
+ function stopped() {
2805
+ return event?.signal.aborted === true;
2806
+ }
2481
2807
  event?.signal.addEventListener("abort", () => queue?.close(), { once: true });
2482
2808
  ctx.watch((boundary) => {
2483
2809
  if (inOrder) {
@@ -2486,14 +2812,14 @@ async function render(Root, props, options = {}) {
2486
2812
  }
2487
2813
  boundaries++;
2488
2814
  open++;
2489
- const skip = (after) => {
2815
+ function skip(after) {
2490
2816
  if (after) pending().push(`${scriptTag}${showFallback()}${after}<\/script>`);
2491
2817
  finish();
2492
- };
2493
- const turn = (send) => {
2818
+ }
2819
+ function turn(send) {
2494
2820
  if (boundary.group) boundary.group.ready(boundary.id, send);
2495
2821
  else send("");
2496
- };
2822
+ }
2497
2823
  boundary.render.then((result) => {
2498
2824
  if (boundary.cancelled || boundary.around || stopped()) {
2499
2825
  turn(skip);
@@ -2518,8 +2844,29 @@ async function render(Root, props, options = {}) {
2518
2844
  finish();
2519
2845
  });
2520
2846
  }, (error) => {
2521
- console.error(error);
2522
- turn(skip);
2847
+ if (boundary.cancelled || boundary.around || stopped()) {
2848
+ console.error(error);
2849
+ turn(skip);
2850
+ return;
2851
+ }
2852
+ turn((after) => {
2853
+ if (ctx.isDev()) console.error(error);
2854
+ renderCatch(boundary, error).then((result) => {
2855
+ if (!result) {
2856
+ pending().push(failScript(caught(error, ctx), refs, boundary.id, root, nonce));
2857
+ skip(after);
2858
+ return;
2859
+ }
2860
+ serialize(result.ctx, (script) => {
2861
+ pending().push(`<template b-c="${result.key}">${result.html}</template>${result.ctx.portals.join("")}${stateScript("0", false, {
2862
+ root,
2863
+ nonce,
2864
+ catches: result.key
2865
+ })}${script}`);
2866
+ });
2867
+ skip(after);
2868
+ });
2869
+ });
2523
2870
  });
2524
2871
  });
2525
2872
  if (options.defer) return {
@@ -2544,13 +2891,28 @@ async function render(Root, props, options = {}) {
2544
2891
  if (inOrder) {
2545
2892
  const bodies = /* @__PURE__ */ new Map();
2546
2893
  const portals = [];
2894
+ const catches = [];
2547
2895
  for (let index = 0; index < inOrder.length; index++) {
2548
2896
  const boundary = inOrder[index];
2549
2897
  let result;
2550
2898
  try {
2551
2899
  result = await boundary.render;
2552
2900
  } catch (error) {
2553
- console.error(error);
2901
+ if (boundary.cancelled || boundary.around) continue;
2902
+ if (ctx.isDev()) console.error(error);
2903
+ const replacement = await renderCatch(boundary, error);
2904
+ if (!replacement) {
2905
+ console.error(error);
2906
+ continue;
2907
+ }
2908
+ catches.push([replacement.key, replacement.html]);
2909
+ portals.push(...replacement.ctx.portals);
2910
+ serialize(replacement.ctx, (script) => {
2911
+ state += script;
2912
+ }, void 0, (failed) => {
2913
+ failure = failed;
2914
+ });
2915
+ if (failure !== void 0) throw unsendable(failure, replacement.ctx);
2554
2916
  continue;
2555
2917
  }
2556
2918
  if (boundary.cancelled || boundary.around) continue;
@@ -2564,7 +2926,9 @@ async function render(Root, props, options = {}) {
2564
2926
  }, index === inOrder.length - 1);
2565
2927
  if (failure !== void 0) throw unsendable(failure, result.ctx);
2566
2928
  }
2567
- page = beforeBodyEnd(inlineBodies(rendered, bodies), [...ctx.portals, ...portals].join(""));
2929
+ let shell = rendered;
2930
+ for (const [key, catchHTML] of catches) shell = replaceBlock(shell, key, catchHTML);
2931
+ page = beforeBodyEnd(inlineBodies(shell, bodies), [...ctx.portals, ...portals].join(""));
2568
2932
  }
2569
2933
  return {
2570
2934
  html: page,
@@ -2586,6 +2950,26 @@ function rendersInOrder(option, request) {
2586
2950
  if (typeof option === "function") return option(request);
2587
2951
  return BOTS.test(request.headers.get("user-agent") ?? "");
2588
2952
  }
2953
+ /**
2954
+ * Replaces what a block holds, between its markers, with other markup. `key` is the scope and
2955
+ * the anchor in the start marker. A page without the block stays as it is.
2956
+ */
2957
+ function replaceBlock(html, key, inner) {
2958
+ const open = `<!--b${key}-->`;
2959
+ const start = html.indexOf(open);
2960
+ if (start === -1) return html;
2961
+ const comments = /<!--([^>]*?)-->/g;
2962
+ comments.lastIndex = start + open.length;
2963
+ let depth = 0;
2964
+ for (let found = comments.exec(html); found; found = comments.exec(html)) {
2965
+ const data = found[1];
2966
+ if (data[0] === "/") {
2967
+ if (depth === 0) return html.slice(0, start + open.length) + inner + html.slice(found.index);
2968
+ depth--;
2969
+ } else if (/^[btilP]-?\d/.test(data)) depth++;
2970
+ }
2971
+ return html;
2972
+ }
2589
2973
  const BOUNDARY_MARKER = /<!--(l[\d.]+|\/l)-->/g;
2590
2974
  /**
2591
2975
  * Puts the bodies of boundaries in place of their fallbacks, with the bodies
@@ -2619,6 +3003,25 @@ function inlineBodies(html, bodies) {
2619
3003
  return result + html.slice(position);
2620
3004
  }
2621
3005
  const HTML = /<html[\s>]/i;
3006
+ const HTML_TAG = /^<html((?:"[^"]*"|'[^']*'|[^>"'])*)>/i;
3007
+ const ATTRIBUTE_NAME = /([^\s"'<>/=]+)(?:=(?:"[^"]*"|'[^']*'|[^\s"'>]+))?/g;
3008
+ /**
3009
+ * Adds `b-html` to the `<html>` tag, with the names of the attributes that the page sent, so
3010
+ * client navigation can tell them from those that a script sets.
3011
+ */
3012
+ function nameHtmlAttributes(page) {
3013
+ const tag = HTML_TAG.exec(page);
3014
+ if (!tag) return page;
3015
+ const names = [];
3016
+ const attributes = tag[1].replace(ATTRIBUTE_NAME, (text, name) => {
3017
+ if (name.toLowerCase() === "b-html") return "";
3018
+ names.push(name);
3019
+ return text;
3020
+ });
3021
+ if (attributes === tag[1] && names.length === 0) return page;
3022
+ const list = names.length > 0 ? ` b-html="${escapeAttribute(names.join(" "))}"` : "";
3023
+ return `${page.slice(0, 5)}${attributes.trimEnd()}${list}>${page.slice(tag[0].length)}`;
3024
+ }
2622
3025
  /**
2623
3026
  * Inserts markup before `</body>`, or at the end if there is none. `index`
2624
3027
  * is where `</body>` is, when the caller found it already.
@@ -2639,7 +3042,7 @@ function firstRender(html, componentHead, state, options) {
2639
3042
  const match = HTML.exec(html);
2640
3043
  if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + html + tail + (options.end ?? "");
2641
3044
  const headContent = html.slice(0, match.index) + head;
2642
- let page = html.slice(match.index);
3045
+ let page = nameHtmlAttributes(html.slice(match.index));
2643
3046
  const lower = page.toLowerCase();
2644
3047
  const headEnd = lower.indexOf("</head>");
2645
3048
  let bodyEnd = lower.lastIndexOf("</body>");
@@ -2717,6 +3120,36 @@ function errorAnswer(error, fallback) {
2717
3120
  status: 500
2718
3121
  };
2719
3122
  }
3123
+ /** Errors that `safeError` logged, so a failure read in two places logs once. */
3124
+ const logged = /* @__PURE__ */ new WeakSet();
3125
+ /**
3126
+ * The error that the page state may carry in production: a plain `Error` with the message of a
3127
+ * `ServerError`, or `fallback`, and no stack, which holds paths of the server. Any other error is
3128
+ * logged once. A thrown value that is not an object is logged each time.
3129
+ */
3130
+ function safeError(error, fallback) {
3131
+ let message = fallback;
3132
+ if (error instanceof ServerError) message = error.message;
3133
+ else if (typeof error !== "object" || error === null) console.error(error);
3134
+ else if (!logged.has(error)) {
3135
+ logged.add(error);
3136
+ console.error(error);
3137
+ }
3138
+ const safe = new Error(message);
3139
+ safe.stack = "";
3140
+ return safe;
3141
+ }
3142
+ /**
3143
+ * The error that a `#catch` body gets on the server, which the page state carries to the
3144
+ * browser. In development it is the error itself, for debugging. In production it is a plain
3145
+ * `Error` with the message of a `ServerError`, or a generic message, and the real error is
3146
+ * logged, as for a server function that fails. The body renders with this value too, so the
3147
+ * HTML cannot print what the state does not carry.
3148
+ */
3149
+ function caught(error, ctx) {
3150
+ if (ctx.isDev()) return error;
3151
+ return safeError(error, "The page could not render this part");
3152
+ }
2720
3153
  /** True for a request that a `<form>` sent, without client code. */
2721
3154
  function isFormPost(request) {
2722
3155
  const type = request.headers.get("content-type") ?? "";
@@ -2908,7 +3341,9 @@ async function handleRequest(functions, request, prefix = "/_brumate", options =
2908
3341
  id,
2909
3342
  args
2910
3343
  };
2911
- const invoke = () => withEvent(event, () => fn(...args));
3344
+ function invoke() {
3345
+ return withEvent(event, () => fn(...args));
3346
+ }
2912
3347
  return runEntry(options.middleware, event, () => runEntry(options.fileMiddleware?.[id], event, () => posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke())));
2913
3348
  }
2914
3349
  /**
@@ -2923,7 +3358,8 @@ async function answerCall(functions, event, run) {
2923
3358
  const result = await run();
2924
3359
  const { refreshed } = event;
2925
3360
  if (refreshed?.size) {
2926
- const ids = Object.keys(functions).filter((key) => refreshed.has(unwrap(functions[key])));
3361
+ const ids = [];
3362
+ for (const key of Object.keys(functions)) if (refreshed.has(unwrap(functions[key]))) ids.push(key);
2927
3363
  if (ids.length > 0) headers.set("x-brumate-refresh", ids.join(","));
2928
3364
  }
2929
3365
  headers.set("content-type", STREAM_TYPE);
@@ -2960,7 +3396,8 @@ async function keptPage(key) {
2960
3396
  const page = JSON.parse(text);
2961
3397
  const tags = Object.keys(page.tags);
2962
3398
  const versions = await tagVersions(tags);
2963
- if (page.expires <= Date.now() || tags.some((tag) => versions[tag] !== page.tags[tag])) return;
3399
+ if (page.expires <= Date.now()) return;
3400
+ for (const tag of tags) if (versions[tag] !== page.tags[tag]) return;
2964
3401
  const headers = new Headers(page.headers);
2965
3402
  const maxAge = Number(/max-age=(\d+)/.exec(headers.get("cache-control") ?? "")?.[1] ?? 0);
2966
3403
  headers.set("age", String(Math.max(0, Math.floor(maxAge - (page.expires - Date.now()) / 1e3))));
@@ -2974,13 +3411,20 @@ async function keptPage(key) {
2974
3411
  async function keepPage(key, response, event) {
2975
3412
  const maxAge = Number(/max-age=(\d+)/.exec(response.headers.get("cache-control") ?? "")?.[1] ?? 0);
2976
3413
  if (maxAge <= 0) return;
2977
- const versions = await tagVersions([...event.cacheTags].filter(([, version]) => version === void 0).map(([tag]) => tag));
3414
+ const missing = [];
3415
+ for (const [tag, version] of event.cacheTags) if (version === void 0) missing.push(tag);
3416
+ const versions = await tagVersions(missing);
3417
+ const kept = [];
3418
+ for (const [name, value] of response.headers) if (name !== "set-cookie") kept.push([name, value]);
3419
+ const body = await response.clone().text();
3420
+ const tags = {};
3421
+ for (const [tag, version] of event.cacheTags) tags[tag] = version ?? versions[tag];
2978
3422
  const page = {
2979
3423
  status: response.status,
2980
- headers: [...response.headers].filter(([name]) => name !== "set-cookie"),
2981
- body: await response.clone().text(),
3424
+ headers: kept,
3425
+ body,
2982
3426
  expires: Date.now() + maxAge * 1e3,
2983
- tags: Object.fromEntries([...event.cacheTags].map(([tag, version]) => [tag, version ?? versions[tag]]))
3427
+ tags
2984
3428
  };
2985
3429
  await cacheStore().set(key, JSON.stringify(page), maxAge);
2986
3430
  }
@@ -3003,18 +3447,22 @@ function cacheControl(cache, event, response) {
3003
3447
  const warnedPrivate = /* @__PURE__ */ new Set();
3004
3448
  /** Imports every module of a matched route before it renders. */
3005
3449
  async function resolveView(view) {
3450
+ const names = Object.keys(view.slots);
3451
+ const pending = [];
3452
+ for (const slot of Object.values(view.slots)) pending.push(resolveView(slot));
3006
3453
  const [module, loading, ...slots] = await Promise.all([
3007
3454
  view.load(),
3008
3455
  view.loading?.(),
3009
- ...Object.values(view.slots).map(resolveView)
3456
+ ...pending
3010
3457
  ]);
3011
- const names = Object.keys(view.slots);
3458
+ const resolved = {};
3459
+ for (const [index, name] of names.entries()) resolved[name] = slots[index];
3012
3460
  return {
3013
3461
  key: view.key,
3014
3462
  component: module.default,
3015
3463
  loading: loading?.default,
3016
3464
  cache: module.cache,
3017
- slots: Object.fromEntries(names.map((name, index) => [name, slots[index]]))
3465
+ slots: resolved
3018
3466
  };
3019
3467
  }
3020
3468
  /**
@@ -3032,6 +3480,13 @@ async function renderView(view, props, ctx, scope) {
3032
3480
  * A component that renders a route, with its slots rendering where the
3033
3481
  * layout inserts them. `props` go to every view, such as `params`.
3034
3482
  */
3483
+ /** The component IDs of a view and of the views in its slots. */
3484
+ function viewIds(view) {
3485
+ const id = view.component.brumateId;
3486
+ const ids = id === void 0 ? [] : [id];
3487
+ for (const slot of Object.values(view.slots)) ids.push(...viewIds(slot));
3488
+ return ids;
3489
+ }
3035
3490
  function viewComponent(view, props) {
3036
3491
  return (_props, ctx) => {
3037
3492
  const own = { ...props };
@@ -3089,11 +3544,18 @@ async function renderPage(view, props, request, options, extra) {
3089
3544
  }
3090
3545
  const path = new URL(request.url).pathname;
3091
3546
  const endRender = event?.traced("render", path) ?? (() => {});
3092
- const hints = request.headers.has("x-brumate-base") ? [] : options.hints ?? [];
3547
+ let hints = [];
3548
+ if (!request.headers.has("x-brumate-base")) {
3549
+ const wanted = [...options.hints ?? []];
3550
+ for (const id of viewIds(view)) wanted.push(...options.bundleHints?.[id] ?? []);
3551
+ hints = [...new Set(wanted)];
3552
+ }
3093
3553
  const nonce = options.nonce === void 0 ? "" : ` nonce="${escapeAttribute(options.nonce)}"`;
3094
- const links = nonce ? [] : hints.map((url) => `<${url}>; rel=modulepreload`);
3554
+ const links = [];
3555
+ if (!nonce) for (const url of hints) links.push(`<${url}>; rel=modulepreload`);
3095
3556
  if (links.length > 0) options.earlyHints?.(links);
3096
- const preload = hints.map((url) => `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`).join("");
3557
+ let preload = "";
3558
+ for (const url of hints) preload += `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`;
3097
3559
  const parts = await render(viewComponent(view, props), {}, {
3098
3560
  ...options,
3099
3561
  request,
@@ -3278,7 +3740,7 @@ function fillHoles(tree, request, shell, options) {
3278
3740
  headers.append("vary", "x-brumate-defer");
3279
3741
  headers.append("vary", "x-brumate-base");
3280
3742
  const marked = shell.replace(HOLE, (template) => `${template} b-hole`);
3281
- const bodies = holes.map(async ([, at, boundary, base]) => {
3743
+ async function loadBody([, at, boundary, base]) {
3282
3744
  const asked = new Headers(request.headers);
3283
3745
  asked.set("x-brumate-defer", `${boundary} ${at}`);
3284
3746
  asked.set("x-brumate-base", base);
@@ -3293,13 +3755,16 @@ function fillHoles(tree, request, shell, options) {
3293
3755
  console.error(error);
3294
3756
  return "";
3295
3757
  }
3296
- });
3758
+ }
3759
+ const bodies = [];
3760
+ for (const hole of holes) bodies.push(loadBody(hole));
3297
3761
  const body = new ReadableStream({ async start(controller) {
3298
3762
  controller.enqueue(marked);
3299
- const pending = new Map(bodies.map((body, index) => [index, body.then((html) => ({
3763
+ const pending = /* @__PURE__ */ new Map();
3764
+ for (const [index, promise] of bodies.entries()) pending.set(index, promise.then((html) => ({
3300
3765
  html,
3301
3766
  index
3302
- }))]));
3767
+ })));
3303
3768
  while (pending.size > 0) {
3304
3769
  const { html, index } = await Promise.race(pending.values());
3305
3770
  pending.delete(index);
@@ -3312,7 +3777,8 @@ function fillHoles(tree, request, shell, options) {
3312
3777
  /** A response with more headers, such as cookies that middleware set. */
3313
3778
  function withHeaders(answer, headers) {
3314
3779
  const sent = new Set(answer.headers.getSetCookie());
3315
- const cookies = headers.getSetCookie().filter((cookie) => !sent.has(cookie));
3780
+ const cookies = [];
3781
+ for (const cookie of headers.getSetCookie()) if (!sent.has(cookie)) cookies.push(cookie);
3316
3782
  if (cookies.length === 0) return answer;
3317
3783
  const result = respond(answer.body, answer);
3318
3784
  for (const cookie of cookies) result.headers.append("set-cookie", cookie);
@@ -3344,7 +3810,8 @@ async function answerRoute(match, request, url, options) {
3344
3810
  const handler = endpoint[request.method] ?? (request.method === "HEAD" ? endpoint.GET : void 0);
3345
3811
  if (handler) return withEvent(options.event, () => handler(request, match.params));
3346
3812
  if (match.view.load === missingPage || request.method !== "GET") {
3347
- const allow = Object.keys(endpoint).filter((name) => /^[A-Z]+$/.test(name));
3813
+ const allow = [];
3814
+ for (const name of Object.keys(endpoint)) if (/^[A-Z]+$/.test(name)) allow.push(name);
3348
3815
  return new Response("Method not allowed", {
3349
3816
  status: 405,
3350
3817
  headers: { allow: allow.join(", ") }
@@ -3391,27 +3858,30 @@ async function renderRoute(match, request, url, options) {
3391
3858
  * function belongs to and the modifiers of its wrappers. A function that
3392
3859
  * refers to nothing in the browser is left out.
3393
3860
  */
3394
- function spread(attributes, on) {
3395
- const entries = on && attributes["b-on"];
3861
+ function spread(attributes, on, names) {
3862
+ const entries = on && ownValue("b-on", attributes["b-on"]);
3396
3863
  if (typeof entries === "string") {
3397
3864
  on.unshift(entries);
3398
3865
  const { "b-on": _, ...rest } = attributes;
3399
- return spread(rest, on);
3866
+ return spread(rest, on, names);
3400
3867
  }
3401
3868
  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));
3869
+ const parts = on && /^on[A-Z]/.test(name) && typeof value === "function" ? value[PARTS] ?? [value] : [];
3870
+ for (const part of parts) {
3871
+ const reference = functionReferences.get(part);
3872
+ if (reference) {
3873
+ const modifiers = part[MODIFIERS];
3874
+ on.push(handlerEntry(name, reference.ref, reference.scope, modifiers, reference.args));
3875
+ }
3406
3876
  }
3407
3877
  if (on && (name === "value" || name === "checked") && isBinding(value)) {
3408
3878
  const setter = typeof value.set === "function" ? functionReferences.get(value.set) : void 0;
3409
3879
  on.push(bindEntry(name, value.ref, setter));
3410
3880
  }
3411
3881
  }
3412
- return spread$1(attributes);
3882
+ return spread$1(attributes, names);
3413
3883
  }
3414
3884
  //#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 };
3885
+ 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
3886
 
3417
- //# sourceMappingURL=server-CxVDYE_V.js.map
3887
+ //# sourceMappingURL=server-BTtsQFFw.js.map