@torpor/view 1.3.3 → 1.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 (60) hide show
  1. package/dist/{Effect-Bp-BIDDm.d.cts → Effect-Bi_nt6cx.d.cts} +16 -3
  2. package/dist/Effect-Bi_nt6cx.d.cts.map +1 -0
  3. package/dist/{Effect-VsIY2vPx.d.mts → Effect-Bi_nt6cx.d.mts} +16 -3
  4. package/dist/Effect-Bi_nt6cx.d.mts.map +1 -0
  5. package/dist/ListItemSpec-DFkYr2TE.d.cts +28 -0
  6. package/dist/ListItemSpec-DFkYr2TE.d.cts.map +1 -0
  7. package/dist/ListItemSpec-DFkYr2TE.d.mts +28 -0
  8. package/dist/ListItemSpec-DFkYr2TE.d.mts.map +1 -0
  9. package/dist/{AsyncOptions-BDtArmeL.d.mts → WatchOptions--xq-Gn4e.d.cts} +77 -4
  10. package/dist/WatchOptions--xq-Gn4e.d.cts.map +1 -0
  11. package/dist/{AsyncOptions-C_7mWR6F.d.cts → WatchOptions-DWF4EqB6.d.mts} +77 -4
  12. package/dist/WatchOptions-DWF4EqB6.d.mts.map +1 -0
  13. package/dist/compile.cjs +1399 -406
  14. package/dist/compile.d.cts +26 -12
  15. package/dist/compile.d.cts.map +1 -1
  16. package/dist/compile.d.mts +26 -12
  17. package/dist/compile.d.mts.map +1 -1
  18. package/dist/compile.mjs +1399 -406
  19. package/dist/compile.mjs.map +1 -1
  20. package/dist/dev.cjs +101 -51
  21. package/dist/dev.d.cts +33 -2
  22. package/dist/dev.d.cts.map +1 -1
  23. package/dist/dev.d.mts +33 -2
  24. package/dist/dev.d.mts.map +1 -1
  25. package/dist/dev.mjs +51 -2
  26. package/dist/dev.mjs.map +1 -1
  27. package/dist/{fromWebSocket-ERhd9KZR.mjs → fromWebSocket-B22DIys7.mjs} +11 -2
  28. package/dist/fromWebSocket-B22DIys7.mjs.map +1 -0
  29. package/dist/{fromWebSocket-Cdoghvmh.cjs → fromWebSocket-C56rkQpZ.cjs} +15 -0
  30. package/dist/index.cjs +605 -266
  31. package/dist/index.d.cts +36 -129
  32. package/dist/index.d.cts.map +1 -1
  33. package/dist/index.d.mts +36 -129
  34. package/dist/index.d.mts.map +1 -1
  35. package/dist/index.mjs +593 -255
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/runtime.iife.js +1 -1
  38. package/dist/ssr.cjs +122 -22
  39. package/dist/ssr.d.cts +46 -12
  40. package/dist/ssr.d.cts.map +1 -1
  41. package/dist/ssr.d.mts +46 -12
  42. package/dist/ssr.d.mts.map +1 -1
  43. package/dist/ssr.mjs +121 -23
  44. package/dist/ssr.mjs.map +1 -1
  45. package/dist/titleWarning-BMjLAXpn.mjs +72 -0
  46. package/dist/titleWarning-BMjLAXpn.mjs.map +1 -0
  47. package/dist/titleWarning-DXp4fK7q.cjs +87 -0
  48. package/package.json +2 -1
  49. package/dist/AsyncOptions-BDtArmeL.d.mts.map +0 -1
  50. package/dist/AsyncOptions-C_7mWR6F.d.cts.map +0 -1
  51. package/dist/Cleanup-D0wvGW5d.d.cts +0 -9
  52. package/dist/Cleanup-D0wvGW5d.d.cts.map +0 -1
  53. package/dist/Cleanup-D0wvGW5d.d.mts +0 -9
  54. package/dist/Cleanup-D0wvGW5d.d.mts.map +0 -1
  55. package/dist/Effect-Bp-BIDDm.d.cts.map +0 -1
  56. package/dist/Effect-VsIY2vPx.d.mts.map +0 -1
  57. package/dist/devContext-BulTn3U5.cjs +0 -27
  58. package/dist/devContext-ZNsPyOgB.mjs +0 -24
  59. package/dist/devContext-ZNsPyOgB.mjs.map +0 -1
  60. package/dist/fromWebSocket-ERhd9KZR.mjs.map +0 -1
package/dist/compile.mjs CHANGED
@@ -512,6 +512,65 @@ function hydrationBranchComment(index) {
512
512
  return `<!^${index}>`;
513
513
  }
514
514
  //#endregion
515
+ //#region src/compile/utils/escapeRawText.ts
516
+ /**
517
+ * Escapes raw-text content for inclusion in a generated template literal.
518
+ *
519
+ * Whitespace that would be altered by fragment-text whitespace collapsing is
520
+ * escaped (`\n`, `\t`, `\x20` for runs of spaces), so raw content round-trips
521
+ * exactly -- including line breaks and indentation inside scripts. Backticks
522
+ * and `${` are escaped so the literal doesn't terminate or interpolate, and
523
+ * backslashes are escaped so JavaScript escapes in the source text (e.g.
524
+ * `"\n"` inside an inline script) aren't consumed by the template literal.
525
+ */
526
+ function escapeRawText(text) {
527
+ let result = "";
528
+ for (let i = 0; i < text.length; i++) {
529
+ const char = text[i];
530
+ if (char === "\\") result += "\\\\";
531
+ else if (char === "`") result += "\\x60";
532
+ else if (char === " ") {
533
+ let end = i + 1;
534
+ while (text[end] === " ") end++;
535
+ if (end - i > 1) {
536
+ result += "\\x20".repeat(end - i);
537
+ i = end - 1;
538
+ } else result += " ";
539
+ } else if (/\s/.test(char)) result += whitespaceEscape(char);
540
+ else if (char === "$" && text[i + 1] === "{") result += "\\x24";
541
+ else result += char;
542
+ }
543
+ return result;
544
+ }
545
+ function whitespaceEscape(char) {
546
+ switch (char) {
547
+ case "\n": return "\\n";
548
+ case "\r": return "\\r";
549
+ case " ": return "\\t";
550
+ case "\f": return "\\f";
551
+ case "\v": return "\\v";
552
+ default: return `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`;
553
+ }
554
+ }
555
+ //#endregion
556
+ //#region src/compile/utils/escapeTemplateText.ts
557
+ /**
558
+ * Escapes text for inclusion in a generated template literal: backslashes,
559
+ * backticks and `${` are all written as escapes so the text round-trips
560
+ * literally instead of ending the literal or starting an interpolation.
561
+ */
562
+ function escapeTemplateText(text) {
563
+ let result = "";
564
+ for (let i = 0; i < text.length; i++) {
565
+ const char = text[i];
566
+ if (char === "\\") result += "\\\\";
567
+ else if (char === "`") result += "\\x60";
568
+ else if (char === "$" && text[i + 1] === "{") result += "\\x24";
569
+ else result += char;
570
+ }
571
+ return result;
572
+ }
573
+ //#endregion
515
574
  //#region src/compile/utils/isControlNode.ts
516
575
  function isControlNode(node) {
517
576
  return node.type === "control";
@@ -574,16 +633,60 @@ function getSingleElementRoot(children) {
574
633
  return renderingRoot;
575
634
  }
576
635
  //#endregion
636
+ //#region src/compile/utils/interpolation.ts
637
+ /**
638
+ * Finds the `}` that closes the interpolation starting at the `{` at `start`,
639
+ * skipping braces inside strings, template strings, comments and regex
640
+ * literals. Returns -1 when the interpolation is not closed.
641
+ */
642
+ function findMatchingBrace(text, start) {
643
+ let level = 0;
644
+ for (let i = start; i < text.length; i++) {
645
+ const char = text[i];
646
+ if (char === "{") level += 1;
647
+ else if (char === "}") {
648
+ level -= 1;
649
+ if (level === 0) return i;
650
+ } else {
651
+ const skipped = skipStringOrComment(text, i);
652
+ if (skipped !== -1) i = skipped - 1;
653
+ }
654
+ }
655
+ return -1;
656
+ }
657
+ /**
658
+ * Whether template text contains a complete `{...}` interpolation. Braces
659
+ * inside the expression's strings, comments and regex literals aren't counted
660
+ * as delimiters.
661
+ */
662
+ function hasInterpolation(text) {
663
+ for (let i = 0; i < text.length; i++) {
664
+ if (text[i] !== "{") continue;
665
+ return findMatchingBrace(text, i) !== -1;
666
+ }
667
+ return false;
668
+ }
669
+ /**
670
+ * Whether the supplied text is exactly one `{...}` interpolation (ignoring
671
+ * surrounding whitespace).
672
+ */
673
+ function isSingleInterpolation(text) {
674
+ const trimmed = text.trim();
675
+ if (!trimmed.startsWith("{")) return false;
676
+ return findMatchingBrace(trimmed, 0) === trimmed.length - 1;
677
+ }
678
+ //#endregion
577
679
  //#region src/compile/utils/isReactive.ts
578
680
  /**
579
- * Checks whether the supplied string is fully or partially reactive (i.e. contains braces)
681
+ * Checks whether the supplied text contains a `{...}` interpolation. Braces
682
+ * inside the expression's strings and comments don't count as delimiters.
580
683
  *
581
- * @param text The string to check
684
+ * @param text The text to check
582
685
  *
583
- * @returns True if the supplied string is fully or partially reactive
686
+ * @returns True if the supplied text is fully or partially reactive
584
687
  */
585
688
  function isReactive(text) {
586
- return text.includes("{") && text.includes("}");
689
+ return hasInterpolation(text);
587
690
  }
588
691
  //#endregion
589
692
  //#region src/compile/utils/trimQuotes.ts
@@ -653,8 +756,11 @@ function buildNodeFragmentText(node, status, fragments, currentFragment) {
653
756
  break;
654
757
  }
655
758
  case "text": {
656
- const content = node.content;
657
- if (currentFragment) currentFragment.text += isReactive(content) ? "#" : content;
759
+ const textNode = node;
760
+ if (currentFragment) {
761
+ if (textNode.raw) currentFragment.text += escapeRawText(textNode.content);
762
+ else currentFragment.text += isReactive(textNode.content) ? "#" : textNode.content;
763
+ }
658
764
  break;
659
765
  }
660
766
  case "special": buildSpecialFragmentText(node, status, fragments, currentFragment);
@@ -729,9 +835,9 @@ function buildElementFragmentText(node, status, fragments, currentFragment) {
729
835
  if (a.name.startsWith("data-")) return `${a.name}=""`;
730
836
  } else if (a.name === "class" && node.scopeStyles) {
731
837
  needsClass = false;
732
- let value = a.value ? `"${trimQuotes(a.value)} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
838
+ let value = a.value ? `"${escapeTemplateText(trimQuotes(a.value))} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
733
839
  return `${a.name}=${value}`;
734
- } else return `${a.name}${a.value != null ? `=${a.value}` : ""}`;
840
+ } else return `${a.name}${a.value != null ? `=${escapeTemplateText(a.value)}` : ""}`;
735
841
  }).filter(Boolean).join(" ");
736
842
  if (attributesText) currentFragment.text += " " + attributesText;
737
843
  if (needsClass) currentFragment.text += ` class="torp-${status.styleHash}"`;
@@ -967,7 +1073,7 @@ function containsIdentifier(value, name) {
967
1073
  * effect to the loop variable's signal).
968
1074
  */
969
1075
  function forVarBindings(status, source) {
970
- return collectBindings(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
1076
+ return collectBindings$1(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
971
1077
  }
972
1078
  /**
973
1079
  * Like `forVarBindings`, but binds only the loop variables named in `names`.
@@ -975,9 +1081,10 @@ function forVarBindings(status, source) {
975
1081
  * the scope's directly-evaluated code reads.
976
1082
  */
977
1083
  function forVarBindingsFor(status, names) {
978
- return collectBindings(status, (forVar) => names.has(forVar.name));
1084
+ return collectBindings$1(status, (forVar) => names.has(forVar.name));
979
1085
  }
980
- function collectBindings(status, include) {
1086
+ function collectBindings$1(status, include) {
1087
+ if (status.options.check === true) return "";
981
1088
  const bound = /* @__PURE__ */ new Set();
982
1089
  let result = "";
983
1090
  for (let i = status.forVars.length - 1; i >= 0; i--) {
@@ -1095,7 +1202,8 @@ function buildAddFragment(node, status, b, parentName, anchorName) {
1095
1202
  const fragment = node.fragment;
1096
1203
  const fragmentName = `t_fragment_${fragment.number}`;
1097
1204
  if (fragment.effects.length > 0) {
1098
- status.imports.add("$run");
1205
+ const check = status.options.check === true;
1206
+ if (!check) status.imports.add("$run");
1099
1207
  let forVarMask;
1100
1208
  for (let effect of fragment.effects) if (effect.forVarMask !== void 0) {
1101
1209
  if (forVarMask === void 0) forVarMask = 0;
@@ -1103,11 +1211,11 @@ function buildAddFragment(node, status, b, parentName, anchorName) {
1103
1211
  }
1104
1212
  let trailing = "";
1105
1213
  if (forVarMask !== void 0) trailing = `, undefined, { forVarMask: ${forVarMask} }`;
1106
- b.append("$run(() => {");
1214
+ b.append(check ? "(() => {" : "$run(() => {");
1107
1215
  appendForVarBindings(b, status, fragment.effects.map((e) => e.functionBody).join("\n"));
1108
1216
  if (status.options.mapped === true) for (let effect of fragment.effects) addMappedTextWithOffsets("", effect.functionBody, "", effect.spans, effect.offsets, effect.lengths, status, b);
1109
1217
  else b.append(fragment.effects.map((e) => e.functionBody).join("\n"));
1110
- b.append(`}${status.options.dev === true ? `, "setAttributes"${trailing}` : trailing});`);
1218
+ b.append(check ? "})();" : `}${status.options.dev === true ? `, "setAttributes"${trailing}` : trailing});`);
1111
1219
  }
1112
1220
  if (fragment.singleRootElement) {
1113
1221
  status.imports.add("t_add_element");
@@ -1360,7 +1468,7 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1360
1468
  if (lastType === "text" || lastType === "space") return;
1361
1469
  let textPath = {
1362
1470
  parent: path,
1363
- type: isSpace(node.content) ? "space" : "text",
1471
+ type: !node.raw && isSpace(node.content) ? "space" : "text",
1364
1472
  children: []
1365
1473
  };
1366
1474
  path.children.push(textPath);
@@ -1380,11 +1488,12 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1380
1488
  } else {
1381
1489
  status.imports.add("t_txt");
1382
1490
  if (declareVariable) b.append(`(${node.varName} = t_txt(" ")),`);
1491
+ else if (node.raw) b.append(`t_txt(${JSON.stringify(node.content)}),`);
1383
1492
  else b.append(`t_txt("${node.content}"),`);
1384
1493
  }
1385
1494
  }
1386
1495
  function textNodeNeedsDeclaration(node, topLevel, lastChild) {
1387
- return isReactive(node.content) || topLevel && lastChild;
1496
+ return !node.raw && isReactive(node.content) || topLevel && lastChild;
1388
1497
  }
1389
1498
  function declareSpecialFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, lastChild, declare) {
1390
1499
  if (node.tagName === "slot") declareParentAndAnchorFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, "slot", declare);
@@ -1569,10 +1678,16 @@ function buildRun(functionName, functionBody, status, b) {
1569
1678
  trailing = `, "${functionName}"`;
1570
1679
  if (forVarMask !== void 0) trailing += `, { forVarMask: ${forVarMask} }`;
1571
1680
  } else if (forVarMask !== void 0) trailing = `, undefined, { forVarMask: ${forVarMask} }`;
1572
- status.imports.add("$run");
1573
- b.append("$run(() => {");
1574
- b.append(functionBody);
1575
- b.append(`}${trailing});`);
1681
+ if (status.options.check === true) {
1682
+ b.append("(() => {");
1683
+ b.append(functionBody);
1684
+ b.append("})();");
1685
+ } else {
1686
+ status.imports.add("$run");
1687
+ b.append("$run(() => {");
1688
+ b.append(functionBody);
1689
+ b.append(`}${trailing});`);
1690
+ }
1576
1691
  addPopDevBoundary(status, b);
1577
1692
  }
1578
1693
  //#endregion
@@ -1754,7 +1869,8 @@ function buildComponentNode(node, status, b, root = false) {
1754
1869
  slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>",
1755
1870
  fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"
1756
1871
  ];
1757
- b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = (\n${slotParams.join(",\n")}\n) => {`);
1872
+ const check = status.options.check === true;
1873
+ b.append(check ? `((\n${slotParams.join(",\n")}\n) => {` : `${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = (\n${slotParams.join(",\n")}\n) => {`);
1758
1874
  buildFragment(slot, status, b, "$sparent", "$sanchor");
1759
1875
  status.fragmentStack.push({
1760
1876
  fragment: slot.fragment,
@@ -1763,7 +1879,7 @@ function buildComponentNode(node, status, b, root = false) {
1763
1879
  for (let child of slot.children) buildNode(child, status, b, "$sparent", "$sanchor");
1764
1880
  status.fragmentStack.pop();
1765
1881
  buildAddFragment(slot, status, b, "$sparent", "$sanchor");
1766
- b.append(`}`);
1882
+ b.append(check ? "})(null!, null, {}, undefined);" : `}`);
1767
1883
  }
1768
1884
  }
1769
1885
  let renderParams = `${node.parentName}, ${node.varName}, ${propsName}, $context`;
@@ -1777,6 +1893,49 @@ function buildComponentNode(node, status, b, root = false) {
1777
1893
  b.append("");
1778
1894
  }
1779
1895
  //#endregion
1896
+ //#region src/compile/build/client/checkCallbacks.ts
1897
+ /**
1898
+ * Helpers for the callbacks that control blocks (`@if`, `@switch`, `@await`,
1899
+ * …) pass to their runtime functions. A check build (`BuildOptions.check`)
1900
+ * calls each callback in place instead, as an immediately-invoked function,
1901
+ * because TypeScript carries narrowing into those but not into callbacks
1902
+ * passed elsewhere: `@if ($props.user) { {$props.user.name} }` then type
1903
+ * checks as it reads.
1904
+ */
1905
+ /** The callback's parameters: the insertion point, except in the head. */
1906
+ function controlParams(status) {
1907
+ return status.inHead ? "" : "t_before";
1908
+ }
1909
+ /** The arguments a check build calls a callback with, matching its parameters. */
1910
+ function controlArgs(params) {
1911
+ return params.split(",").map((p) => p.trim()).filter((p) => p !== "").map((p) => p === "t_before" ? "null as Node | null" : "undefined as any").join(", ");
1912
+ }
1913
+ /**
1914
+ * Opens a control block's callback.
1915
+ *
1916
+ * @param call The runtime call up to the callback, e.g. `t_run_control(region, anchor, `
1917
+ * @param params The callback's parameters, by default `t_before` (or none in the head)
1918
+ */
1919
+ function openControl(call, status, params = controlParams(status)) {
1920
+ return status.options.check === true ? `((${params}) => {` : `${call}(${params}) => {`;
1921
+ }
1922
+ /**
1923
+ * Closes a control block's callback and opens the next one, for runtime
1924
+ * calls that take several (e.g. `@await`'s content and `@with` branches).
1925
+ */
1926
+ function nextControl(status, params = controlParams(status), previousParams = controlParams(status)) {
1927
+ return status.options.check === true ? `})(${controlArgs(previousParams)});\n((${params}) => {` : `}, (${params}) => {`;
1928
+ }
1929
+ /**
1930
+ * Closes a control block's last callback, and the runtime call.
1931
+ *
1932
+ * @param trailing The runtime call's remaining arguments, e.g. `, "runIf"`
1933
+ * @param params The callback's parameters, to call it with in a check build
1934
+ */
1935
+ function closeControl(trailing, status, params = controlParams(status)) {
1936
+ return status.options.check === true ? `})(${controlArgs(params)});` : `}${trailing});`;
1937
+ }
1938
+ //#endregion
1780
1939
  //#region src/compile/build/client/buildAwaitNode.ts
1781
1940
  function buildAwaitNode(node, status, b) {
1782
1941
  const anchorName = node.varName ?? "null";
@@ -1792,7 +1951,7 @@ function buildAwaitNode(node, status, b) {
1792
1951
  addPushDevBoundary("control", "@await", status, b);
1793
1952
  b.append(`
1794
1953
  const ${regionName} = t_region(${status.options.dev === true ? `"await"` : ""});
1795
- t_run_await(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
1954
+ ${openControl(`t_run_await(${regionName}, ${anchorName}, `, status)}`);
1796
1955
  appendForVarBindings(b, status);
1797
1956
  if (awaitBranch !== void 0 && awaitBranch.children.length > 0) {
1798
1957
  buildFragment(awaitBranch, status, b, parentName, "t_before");
@@ -1805,7 +1964,7 @@ function buildAwaitNode(node, status, b) {
1805
1964
  buildAddFragment(awaitBranch, status, b, parentName, "t_before");
1806
1965
  }
1807
1966
  if (withBranch !== void 0) {
1808
- b.append(`}, (${status.inHead ? "" : "t_before"}) => {`);
1967
+ b.append(nextControl(status));
1809
1968
  appendForVarBindings(b, status);
1810
1969
  if (withBranch.children.length > 0) {
1811
1970
  buildFragment(withBranch, status, b, parentName, "t_before");
@@ -1817,8 +1976,8 @@ function buildAwaitNode(node, status, b) {
1817
1976
  status.fragmentStack.pop();
1818
1977
  buildAddFragment(withBranch, status, b, parentName, "t_before");
1819
1978
  }
1820
- b.append(`}${status.options.dev === true ? `, "runAwait"` : ""});`);
1821
- } else b.append(`}, null${status.options.dev === true ? `, "runAwait"` : ""});`);
1979
+ b.append(closeControl(status.options.dev === true ? `, "runAwait"` : "", status));
1980
+ } else b.append(closeControl(`, null${status.options.dev === true ? `, "runAwait"` : ""}`, status));
1822
1981
  addPopDevBoundary(status, b);
1823
1982
  b.append("");
1824
1983
  }
@@ -1883,41 +2042,185 @@ function isForBodyLeafSafe(forBodyChildren) {
1883
2042
  }
1884
2043
  //#endregion
1885
2044
  //#region src/compile/utils/forLoopVarNames.ts
2045
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1886
2046
  /**
1887
2047
  * Extracts the declared loop variable names from a `@for` statement — the
1888
- * heuristic header parse shared by `buildForNode` (codegen) and the write
1889
- * scanners (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect
1890
- * nested loops that shadow an outer loop's variables).
2048
+ * header parse shared by `buildForNode` (codegen) and the write scanners
2049
+ * (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect nested
2050
+ * loops that shadow an outer loop's variables).
1891
2051
  *
1892
2052
  * Handles the C-style (`for (let i = 0; i < n; i++)`), for-of and for-in
1893
- * forms, with destructuring flattened to the bare names. TODO: Handle
1894
- * destructuring, quotes, comments etc (same as buildForNode's note — this is
1895
- * deliberately the same heuristic).
2053
+ * forms, including comments, strings, nested destructuring and defaults.
1896
2054
  */
1897
2055
  function forLoopVarNames(statement) {
1898
- const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1899
- const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
1900
- const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
1901
- const trimMatched = (value, start, end) => {
1902
- const startIndex = value.indexOf(start);
1903
- const endIndex = value.lastIndexOf(end);
1904
- if (startIndex === -1 || endIndex === -1) return value;
1905
- return value.slice(startIndex + 1, endIndex);
1906
- };
2056
+ const source = maskComments(statement);
2057
+ const forIndex = source.indexOf("for");
2058
+ if (forIndex === -1) return [];
2059
+ const open = source.indexOf("(", forIndex + 3);
2060
+ if (open === -1) return [];
2061
+ const close = findMatching(source, open, "(", ")");
2062
+ if (close === -1) return [];
2063
+ const header = source.slice(open + 1, close);
1907
2064
  const names = [];
1908
- const forLoopMatch = statement.match(forLoopRegex);
1909
- if (forLoopMatch) {
1910
- const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1911
- for (const match of forVarMatches) names.push(match[1]);
1912
- return names;
1913
- }
1914
- const forOfMatch = statement.match(forOfRegex);
1915
- if (forOfMatch) {
1916
- const match = forOfMatch[1];
1917
- if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) names.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1918
- else names.push(match);
2065
+ const firstSemi = findTopLevel(header, (char) => char === ";");
2066
+ if (firstSemi !== -1) {
2067
+ const declaration = stripDeclarationKeyword(header.slice(0, firstSemi));
2068
+ for (const declarator of splitTopLevel(declaration, ",")) {
2069
+ const eq = findTopLevel(declarator, (char) => char === "=");
2070
+ collectBindings(eq === -1 ? declarator : declarator.slice(0, eq), names);
2071
+ }
2072
+ return [...new Set(names)];
2073
+ }
2074
+ const keyword = findLoopKeyword(header);
2075
+ if (keyword !== -1) collectBindings(stripDeclarationKeyword(header.slice(0, keyword)), names);
2076
+ return [...new Set(names)];
2077
+ }
2078
+ /** Replaces comments with spaces, preserving length and string contents. */
2079
+ function maskComments(source) {
2080
+ let masked = "";
2081
+ for (let i = 0; i < source.length; i++) {
2082
+ const skipped = skipStringOrComment(source, i);
2083
+ if (skipped === -1) {
2084
+ masked += source[i];
2085
+ continue;
2086
+ }
2087
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) masked += source.substring(i, skipped).replaceAll(/[^\r\n]/g, " ");
2088
+ else masked += source.substring(i, skipped);
2089
+ i = skipped - 1;
1919
2090
  }
1920
- return names;
2091
+ return masked;
2092
+ }
2093
+ /** Finds the close delimiter matching the opener at `start`. */
2094
+ function findMatching(source, start, open, close) {
2095
+ let depth = 0;
2096
+ for (let i = start; i < source.length; i++) {
2097
+ const skipped = skipStringOrComment(source, i);
2098
+ if (skipped !== -1) {
2099
+ i = skipped - 1;
2100
+ continue;
2101
+ }
2102
+ const char = source[i];
2103
+ if (char === open) depth += 1;
2104
+ else if (char === close) {
2105
+ depth -= 1;
2106
+ if (depth === 0) return i;
2107
+ }
2108
+ }
2109
+ return -1;
2110
+ }
2111
+ /** Finds the first match of `predicate` outside nested delimiters and strings. */
2112
+ function findTopLevel(source, predicate) {
2113
+ let depth = 0;
2114
+ for (let i = 0; i < source.length; i++) {
2115
+ const skipped = skipStringOrComment(source, i);
2116
+ if (skipped !== -1) {
2117
+ i = skipped - 1;
2118
+ continue;
2119
+ }
2120
+ const char = source[i];
2121
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2122
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2123
+ else if (depth === 0 && predicate(char, i)) return i;
2124
+ }
2125
+ return -1;
2126
+ }
2127
+ /** Finds a top-level `of` or `in` keyword. */
2128
+ function findLoopKeyword(source) {
2129
+ let depth = 0;
2130
+ for (let i = 0; i < source.length; i++) {
2131
+ const skipped = skipStringOrComment(source, i);
2132
+ if (skipped !== -1) {
2133
+ i = skipped - 1;
2134
+ continue;
2135
+ }
2136
+ const char = source[i];
2137
+ if (char === "(" || char === "[" || char === "{") {
2138
+ depth += 1;
2139
+ continue;
2140
+ }
2141
+ if (char === ")" || char === "]" || char === "}") {
2142
+ depth -= 1;
2143
+ continue;
2144
+ }
2145
+ if (depth !== 0) continue;
2146
+ for (const keyword of ["of", "in"]) {
2147
+ if (!source.startsWith(keyword, i)) continue;
2148
+ const previous = source[i - 1];
2149
+ const next = source[i + keyword.length];
2150
+ if ((previous === void 0 || !isIdentifierChar(previous)) && (next === void 0 || !isIdentifierChar(next))) return i;
2151
+ }
2152
+ }
2153
+ return -1;
2154
+ }
2155
+ /** Splits at a separator that isn't inside strings or nested delimiters. */
2156
+ function splitTopLevel(source, separator) {
2157
+ const parts = [];
2158
+ let start = 0;
2159
+ let depth = 0;
2160
+ for (let i = 0; i < source.length; i++) {
2161
+ const skipped = skipStringOrComment(source, i);
2162
+ if (skipped !== -1) {
2163
+ i = skipped - 1;
2164
+ continue;
2165
+ }
2166
+ const char = source[i];
2167
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2168
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2169
+ else if (depth === 0 && char === separator) {
2170
+ parts.push(source.slice(start, i));
2171
+ start = i + 1;
2172
+ }
2173
+ }
2174
+ parts.push(source.slice(start));
2175
+ return parts;
2176
+ }
2177
+ function stripDeclarationKeyword(declaration) {
2178
+ return declaration.trim().replace(/^(?:let|var|const)\b\s*/, "");
2179
+ }
2180
+ function collectBindings(pattern, names) {
2181
+ pattern = pattern.trim();
2182
+ if (!pattern) return;
2183
+ const open = pattern[0];
2184
+ if (open === "{") {
2185
+ const close = findMatching(pattern, 0, "{", "}");
2186
+ if (close === -1) return;
2187
+ for (const property of splitTopLevel(pattern.slice(1, close), ",")) collectObjectBinding(property.trim(), names);
2188
+ return;
2189
+ }
2190
+ if (open === "[") {
2191
+ const close = findMatching(pattern, 0, "[", "]");
2192
+ if (close === -1) return;
2193
+ for (let element of splitTopLevel(pattern.slice(1, close), ",")) {
2194
+ element = element.trim();
2195
+ if (!element) continue;
2196
+ if (element.startsWith("...")) element = element.slice(3).trim();
2197
+ const eq = findTopLevel(element, (char) => char === "=");
2198
+ collectBindings(eq === -1 ? element : element.slice(0, eq), names);
2199
+ }
2200
+ return;
2201
+ }
2202
+ const eq = findTopLevel(pattern, (char) => char === "=");
2203
+ const name = (eq === -1 ? pattern : pattern.slice(0, eq)).trim();
2204
+ if (IDENTIFIER.test(name)) names.push(name);
2205
+ }
2206
+ function collectObjectBinding(property, names) {
2207
+ property = property.trim();
2208
+ if (!property) return;
2209
+ if (property.startsWith("...")) {
2210
+ collectBindings(property.slice(3).trim(), names);
2211
+ return;
2212
+ }
2213
+ const colon = findTopLevel(property, (char) => char === ":");
2214
+ const eq = findTopLevel(property, (char) => char === "=");
2215
+ if (colon !== -1 && (eq === -1 || colon < eq)) {
2216
+ collectBindings(property.slice(colon + 1).trim(), names);
2217
+ return;
2218
+ }
2219
+ const name = (eq === -1 ? property : property.slice(0, eq)).trim();
2220
+ if (IDENTIFIER.test(name)) names.push(name);
2221
+ }
2222
+ function isIdentifierChar(char) {
2223
+ return /[A-Za-z0-9_$]/.test(char);
1921
2224
  }
1922
2225
  //#endregion
1923
2226
  //#region src/compile/utils/forVarsWrittenIn.ts
@@ -2171,6 +2474,10 @@ function buildForNode(node, status, b) {
2171
2474
  for (const name of reassignedForVars) addBuildError(status, `Cannot assign to loop variable "${name}": a @for loop variable is read-only. Assign to a property of the item (\`${name}.foo = …\`) instead, or mutate the source collection directly.`, node.span.start, node.span.end);
2172
2475
  const singleVar = noWatch && forVarNames.length === 1;
2173
2476
  const leafRow = isForBodyLeafSafe(node.children);
2477
+ if (status.options.check === true) {
2478
+ buildCheckForNode(node, status, b, parentName, forVarNames, keyStatement, key, itemName, beforeName, leafRow);
2479
+ return;
2480
+ }
2174
2481
  status.imports.add("t_region");
2175
2482
  status.imports.add("t_run_list");
2176
2483
  status.imports.add("ListItemSpec");
@@ -2230,6 +2537,32 @@ ${status.options.dev === true ? "function updateListItem(t_old_item, t_new_item)
2230
2537
  addPopDevBoundary(status, b);
2231
2538
  b.append("");
2232
2539
  }
2540
+ /**
2541
+ * Builds a `@for` for type checking only (see `BuildOptions.check`): the loop
2542
+ * runs in place, with each row's body called inside it, so loop variables
2543
+ * keep the types of the iterable's items and narrowing from around the loop
2544
+ * carries into it.
2545
+ */
2546
+ function buildCheckForNode(node, status, b, parentName, forVarNames, keyStatement, key, itemName, beforeName, leafRow) {
2547
+ b.append("");
2548
+ b.append("/* @for */");
2549
+ b.append("(() => {");
2550
+ addMappedText("", `${node.statement}`, " {", node.span, status, b);
2551
+ if (key !== void 0 && keyStatement) addMappedText("void (", keyStatement, ");", key.span, status, b);
2552
+ b.append(`((${itemName}: any, ${beforeName}: Node | null) => {`);
2553
+ const oldForVars = status.forVars;
2554
+ status.forVars = [...oldForVars, ...forVarNames.map((v) => ({
2555
+ name: v,
2556
+ path: `${itemName}.data.${v}`,
2557
+ shadow: true
2558
+ }))];
2559
+ buildForItem(node, status, b, parentName, beforeName, itemName, leafRow);
2560
+ status.forVars = oldForVars;
2561
+ b.append("})(undefined, null);");
2562
+ b.append("}");
2563
+ b.append("})();");
2564
+ b.append("");
2565
+ }
2233
2566
  function buildForItem(node, status, b, parentName, beforeName, itemName, leafRow) {
2234
2567
  const oldRegionName = nextVarName("old_region", status);
2235
2568
  if (!leafRow) {
@@ -2258,6 +2591,13 @@ function buildHtmlNode(node, status, b) {
2258
2591
  const htmlAnchorName = node.varName;
2259
2592
  const htmlParentName = node.parentName || htmlAnchorName + ".parentNode";
2260
2593
  node = node.children[0];
2594
+ if (status.options.check === true) {
2595
+ b.append("");
2596
+ b.append(`/* @html */`);
2597
+ addMappedText("", node.statement, ";", node.span, status, b);
2598
+ b.append("");
2599
+ return;
2600
+ }
2261
2601
  status.imports.add("t_region");
2262
2602
  status.imports.add("t_run_control");
2263
2603
  const firstNodeVar = nextVarName("html_first", status);
@@ -2337,11 +2677,11 @@ function buildIfNode(node, status, b) {
2337
2677
  b.append(`
2338
2678
  const ${regionName} = t_region(${status.options.dev === true ? `"if"` : ""});
2339
2679
  let ${indexName} = -1;
2340
- t_run_control(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2680
+ ${openControl(`t_run_control(${regionName}, ${anchorName}, `, status)}`);
2341
2681
  appendForVarBindings(b, status);
2342
2682
  let index = 0;
2343
2683
  for (let branch of branches) buildIfBranch(branch, status, b, parentName, regionName, indexName, index++);
2344
- b.append(`}${status.options.dev === true ? `, "runIf"` : ""});`);
2684
+ b.append(closeControl(status.options.dev === true ? `, "runIf"` : "", status));
2345
2685
  addPopDevBoundary(status, b);
2346
2686
  b.append("");
2347
2687
  }
@@ -2378,10 +2718,10 @@ function buildReplaceNode(node, status, b) {
2378
2718
  b.append(`
2379
2719
  /* @replace */
2380
2720
  const ${replaceRegionName} = t_region(${status.options.dev === true ? `"replace"` : ""});
2381
- t_run_control(${replaceRegionName}, ${replaceAnchorName}, (t_before) => {`);
2721
+ ${openControl(`t_run_control(${replaceRegionName}, ${replaceAnchorName}, `, status, "t_before")}`);
2382
2722
  appendForVarBindings(b, status);
2383
2723
  buildReplaceBranch(node, status, b, replaceParentName, replaceRegionName);
2384
- b.append(`}${status.options.dev === true ? ", \"replace\"" : ""});`);
2724
+ b.append(closeControl(status.options.dev === true ? ", \"replace\"" : "", status, "t_before"));
2385
2725
  b.append("");
2386
2726
  }
2387
2727
  function buildReplaceBranch(node, status, b, parentName, regionName) {
@@ -2438,14 +2778,13 @@ function buildSwitchNode(node, status, b) {
2438
2778
  b.append(`
2439
2779
  const ${regionName} = t_region(${status.options.dev === true ? `"switch"` : ""});
2440
2780
  let ${indexName} = -1;
2441
- t_run_control(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2781
+ ${openControl(`t_run_control(${regionName}, ${anchorName}, `, status)}`);
2442
2782
  appendForVarBindings(b, status);
2443
2783
  addMappedText("", `${node.statement}`, " {", node.span, status, b);
2444
2784
  let index = 0;
2445
2785
  for (let branch of branches) buildSwitchBranch(branch, status, b, parentName, regionName, indexName, index++);
2446
- b.append(`
2447
- }
2448
- }${status.options.dev === true ? `, "runSwitch"` : ""});`);
2786
+ b.append("}");
2787
+ b.append(closeControl(status.options.dev === true ? `, "runSwitch"` : "", status));
2449
2788
  addPopDevBoundary(status, b);
2450
2789
  b.append("");
2451
2790
  }
@@ -2503,16 +2842,20 @@ function buildTryNode(node, status, b) {
2503
2842
  addPushDevBoundary("control", "@try", status, b);
2504
2843
  b.append(`
2505
2844
  const ${regionName} = t_region(${status.options.dev === true ? `"try"` : ""});
2506
- t_run_try(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2845
+ ${openControl(`t_run_try(${regionName}, ${anchorName}, `, status)}`);
2507
2846
  appendForVarBindings(b, status);
2508
2847
  buildTryBranchBody(tryBranch, status, b, parentName);
2509
2848
  const catchVar = catchBranch ? trimMatched(catchBranch.statement.substring(5).trim(), "(", ")") || "err" : null;
2510
2849
  if (catchBranch && catchVar) {
2511
- addMappedText("},", `(${status.inHead ? "" : "t_before"}, ${catchVar}) => {`, "", catchBranch.span, status, b);
2850
+ const catchParams = `${status.inHead ? "" : "t_before"}, ${catchVar}`;
2851
+ if (status.options.check === true) {
2852
+ b.append(closeControl("", status));
2853
+ addMappedText("", `((${catchParams}) => {`, "", catchBranch.span, status, b);
2854
+ } else addMappedText("},", `(${catchParams}) => {`, "", catchBranch.span, status, b);
2512
2855
  appendForVarBindings(b, status);
2513
2856
  buildTryBranchBody(catchBranch, status, b, parentName);
2514
- b.append(`}${status.options.dev === true ? `, "runTry"` : ""});`);
2515
- } else b.append(`}, null${status.options.dev === true ? `, "runTry"` : ""});`);
2857
+ b.append(closeControl(status.options.dev === true ? `, "runTry"` : "", status, catchParams));
2858
+ } else b.append(closeControl(`, null${status.options.dev === true ? `, "runTry"` : ""}`, status));
2516
2859
  addPopDevBoundary(status, b);
2517
2860
  b.append("");
2518
2861
  }
@@ -2581,6 +2924,25 @@ function buildControlNode(node, status, b) {
2581
2924
  }
2582
2925
  }
2583
2926
  //#endregion
2927
+ //#region src/compile/utils/rawTextTags.ts
2928
+ /**
2929
+ * HTML raw-text elements. Their contents aren't parsed as markup (or as a
2930
+ * torpor template): braces, `@` and `<` are all literal, and the browser
2931
+ * doesn't decode character references inside them either. Rendered `<script>`
2932
+ * / `<style>` content is therefore emitted exactly as written.
2933
+ */
2934
+ const RAW_TEXT_TAGS = /* @__PURE__ */ new Set([
2935
+ "script",
2936
+ "style",
2937
+ "xmp",
2938
+ "iframe",
2939
+ "noembed",
2940
+ "noframes"
2941
+ ]);
2942
+ function isRawTextTag(tagName) {
2943
+ return RAW_TEXT_TAGS.has(tagName.toLowerCase());
2944
+ }
2945
+ //#endregion
2584
2946
  //#region src/compile/utils/trimEnd.ts
2585
2947
  /**
2586
2948
  * Trims a char from the end of the supplied text
@@ -2650,7 +3012,7 @@ function buildElementNode(node, status, b, parentName) {
2650
3012
  buildElementAttributes$1(node, varName, status, b);
2651
3013
  }
2652
3014
  const oldPreserveWhitespace = status.preserveWhitespace;
2653
- status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre";
3015
+ status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre" || isRawTextTag(node.tagName);
2654
3016
  for (let child of node.children) buildNode(child, status, b, parentName, "null");
2655
3017
  status.preserveWhitespace = oldPreserveWhitespace;
2656
3018
  if (svgElement) status.ns = oldns;
@@ -2661,10 +3023,13 @@ function buildDynamicElementNode(node, status, b) {
2661
3023
  status.imports.add("t_dynamic");
2662
3024
  let selfValue = selfAttribute.value;
2663
3025
  if (selfAttribute.fullyReactive) {
2664
- status.imports.add("$run");
2665
- b.append("$run(() => {");
2666
- b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
2667
- b.append(`}${status.options.dev === true ? `, "setDynamic"` : ""});`);
3026
+ if (status.options.check === true) b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
3027
+ else {
3028
+ status.imports.add("$run");
3029
+ b.append("$run(() => {");
3030
+ b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
3031
+ b.append(`}${status.options.dev === true ? `, "setDynamic"` : ""});`);
3032
+ }
2668
3033
  } else b.append(`${node.varName} = t_dynamic(${node.varName}, ${selfValue});`);
2669
3034
  }
2670
3035
  buildElementAttributes$1(node, node.varName, status, b);
@@ -2688,12 +3053,28 @@ function buildTitleNode(node, status, b) {
2688
3053
  else content = `\`${content.replaceAll("{", "${t_fmt(").replaceAll("}", ")}")}\``;
2689
3054
  } else content = `"${content}"`;
2690
3055
  status.imports.add("$run");
2691
- b.append("$run(() => {");
2692
- b.append(`
3056
+ if (status.options.dev === true) {
3057
+ status.imports.add("t_dev_title");
3058
+ b.append(`{
3059
+ const t_title_dev = t_dev_title();
3060
+ $run(() => {
3061
+ const t_old_title = document.title;
3062
+ document.title = ${content};
3063
+ t_title_dev.set(document.title);
3064
+ return () => {
3065
+ t_title_dev.unset();
3066
+ document.title = t_old_title;
3067
+ };
3068
+ }, "runTitle");
3069
+ }`);
3070
+ } else {
3071
+ b.append("$run(() => {");
3072
+ b.append(`
2693
3073
  const t_old_title = document.title;
2694
3074
  document.title = ${content};
2695
3075
  return () => document.title = t_old_title;
2696
- }${status.options.dev === true ? `, "runTitle"` : ""});`);
3076
+ });`);
3077
+ }
2697
3078
  }
2698
3079
  function buildHeadNode(node, status, b) {
2699
3080
  status.imports.add("$run");
@@ -2794,12 +3175,14 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2794
3175
  let eventName = bindEventName(node, name);
2795
3176
  let defaultValue = "\"\"";
2796
3177
  let inputValue = "e.target.value";
3178
+ let setJoin = "||";
2797
3179
  if (node.tagName === "input") {
2798
3180
  let typeAttribute = node.attributes.find((a) => a.name === "type");
2799
3181
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
2800
3182
  case "number":
2801
- defaultValue = "0";
2802
- inputValue = "Number(e.target.value)";
3183
+ defaultValue = "\"\"";
3184
+ inputValue = "e.target.value === \"\" ? undefined : Number(e.target.value)";
3185
+ setJoin = "??";
2803
3186
  break;
2804
3187
  case "checkbox":
2805
3188
  defaultValue = "false";
@@ -2812,7 +3195,7 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2812
3195
  return;
2813
3196
  }
2814
3197
  }
2815
- let set = `${value} || ${defaultValue}`;
3198
+ let set = `${value} ${setJoin} ${defaultValue}`;
2816
3199
  const propName = name.substring(1);
2817
3200
  buildRun("setBinding", `${propName === "value" ? `${varName}.${propName} = String(${set})` : `${varName}.${propName} = ${set}`};`, status, b);
2818
3201
  emitBindEvent(varName, eventName, `(e) => ${value} = ${inputValue}`, `${value} = ${inputValue};`, combined, status, b);
@@ -3007,6 +3390,7 @@ function buildSpecialNode(node, status, b, parentName, root = false) {
3007
3390
  //#endregion
3008
3391
  //#region src/compile/build/client/buildTextNode.ts
3009
3392
  function buildTextNode(node, status) {
3393
+ if (node.raw) return;
3010
3394
  let fragment = status.fragmentStack.at(-1)?.fragment;
3011
3395
  if (!fragment) return;
3012
3396
  let content = node.content || "";
@@ -3151,7 +3535,8 @@ const importsMap$1 = {
3151
3535
  SlotRender: "import { type SlotRender } from \"${folder}\";",
3152
3536
  devContext: "import { devContext } from \"${folder}/dev\";",
3153
3537
  t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
3154
- t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
3538
+ t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";",
3539
+ t_dev_title: "import { t_dev_title } from \"${folder}/dev\";"
3155
3540
  };
3156
3541
  function buildCode(template, map, options, errors = [], warnings = []) {
3157
3542
  let b = new Builder(options?.mapped);
@@ -3227,7 +3612,7 @@ function buildTemplate(template, map, imports, b, options, errors = [], warnings
3227
3612
  status.imports.add("t_region");
3228
3613
  status.imports.add("t_run_try");
3229
3614
  b.append(`const t_error_region = t_region();`);
3230
- b.append(`t_run_try(t_error_region, $anchor, () => {`);
3615
+ b.append(status.options.check === true ? "(() => {" : `t_run_try(t_error_region, $anchor, () => {`);
3231
3616
  }
3232
3617
  buildFragmentText(current.markup, status, b);
3233
3618
  b.append("");
@@ -3235,13 +3620,13 @@ function buildTemplate(template, map, imports, b, options, errors = [], warnings
3235
3620
  }
3236
3621
  } else if (chunk.script === "/* @error */") {
3237
3622
  if (current.markup && current.error) {
3238
- b.append(`}, (_, ${current.errorVar ?? "err"}) => {`);
3623
+ b.append(status.options.check === true ? `})();\n((_: Node | null, ${current.errorVar ?? "err"}: any) => {` : `}, (_, ${current.errorVar ?? "err"}) => {`);
3239
3624
  b.append("");
3240
3625
  b.append("/* User interface error */");
3241
3626
  buildFragmentText(current.error, status, b);
3242
3627
  b.append("");
3243
3628
  buildNode(current.error, status, b, "$parent", "$anchor", true);
3244
- b.append(`}${status.options.dev === true ? ", \"runError\"" : ""});`);
3629
+ b.append(status.options.check === true ? "})(null, undefined);" : `}${status.options.dev === true ? ", \"runError\"" : ""});`);
3245
3630
  }
3246
3631
  } else if (chunk.script === "/* @head */") {
3247
3632
  if (current.head) {
@@ -3289,10 +3674,10 @@ function buildStyles(style, styleHash) {
3289
3674
  for (let block of style.children) buildStyleNode(block, b, styleHash);
3290
3675
  return b.toString();
3291
3676
  }
3292
- function buildStyleNode(node, b, styleHash) {
3677
+ function buildStyleNode(node, b, styleHash, scoped = true) {
3293
3678
  switch (node.type) {
3294
3679
  case "block":
3295
- buildBlockNode(node, b, styleHash);
3680
+ buildBlockNode(node, b, styleHash, scoped);
3296
3681
  break;
3297
3682
  case "attribute":
3298
3683
  buildAttributeNode(node, b);
@@ -3301,55 +3686,164 @@ function buildStyleNode(node, b, styleHash) {
3301
3686
  default: throw new Error(`Invalid style node type: ${node.type}`);
3302
3687
  }
3303
3688
  }
3304
- function buildBlockNode(block, b, styleHash) {
3689
+ function buildBlockNode(block, b, styleHash, scoped) {
3690
+ const isKeyframes = block.selector.startsWith("@keyframes") || block.selector.startsWith("@-webkit-keyframes");
3305
3691
  if (block.selector.startsWith("@")) b.append(`${block.selector} {`);
3306
3692
  else {
3307
- block.selector = block.selector.replaceAll(/\s+/g, " ");
3308
- let selectors = [];
3309
- let global = false;
3310
- let start = 0;
3311
- for (let i = 0; i <= block.selector.length; i++) if (block.selector.substring(i).startsWith(":global(")) {
3312
- i += 7;
3313
- start = i + 1;
3314
- global = true;
3315
- } else if (global && block.selector[i] === ")") {
3316
- addSelector(selectors, block.selector, styleHash, start, i, global);
3317
- start = i + 1;
3318
- global = false;
3319
- } else if ("*,>+~".includes(block.selector[i])) {
3320
- addSelector(selectors, block.selector, styleHash, start, i, global);
3321
- selectors.push(block.selector[i]);
3322
- start = i + 1;
3323
- } else if (i === block.selector.length) addSelector(selectors, block.selector, styleHash, start, i, global);
3324
- else if (block.selector[i] === " ") {
3325
- addSelector(selectors, block.selector, styleHash, start, i, global);
3326
- start = i + 1;
3327
- }
3328
- b.append(`${selectors.join(" ").replaceAll(" ,", ",")} {`);
3693
+ block.selector = block.selector.replaceAll(/\s+/g, " ").trim();
3694
+ b.append(`${scoped ? scopeSelector(block.selector, styleHash) : block.selector} {`);
3329
3695
  }
3330
- for (let child of block.children) buildStyleNode(child, b, styleHash);
3696
+ for (let child of block.children) buildStyleNode(child, b, styleHash, scoped && !isKeyframes);
3331
3697
  b.append(`}`);
3332
3698
  }
3333
- function addSelector(selectors, selector, styleHash, start, end, global) {
3334
- if (end > start) {
3335
- let s = selector.substring(start, end);
3336
- if (!global) {
3337
- let pre = s;
3338
- let post = "";
3339
- let colonPosition = s.indexOf(":");
3340
- if (colonPosition !== -1) {
3341
- pre = s.substring(0, colonPosition);
3342
- post = s.substring(colonPosition);
3699
+ /**
3700
+ * Appends the component scope class to each compound selector. Both brackets
3701
+ * (`[data-x="a b"]`) and parentheses (`:is(.a, .b)`, `:global(...)`) are
3702
+ * treated as opaque, so spaces/commas inside them aren't mistaken for
3703
+ * combinators. `:global(...)` wrappers are removed without adding the scope.
3704
+ */
3705
+ function scopeSelector(selector, styleHash) {
3706
+ let result = "";
3707
+ let compound = "";
3708
+ let bracketDepth = 0;
3709
+ let parenDepth = 0;
3710
+ let quote = null;
3711
+ const flush = () => {
3712
+ if (!compound) return;
3713
+ result += scopeCompound(compound, styleHash);
3714
+ compound = "";
3715
+ };
3716
+ for (let i = 0; i < selector.length; i++) {
3717
+ const char = selector[i];
3718
+ if (quote !== null) {
3719
+ compound += char;
3720
+ if (char === "\\") compound += selector[++i] ?? "";
3721
+ else if (char === quote) quote = null;
3722
+ continue;
3723
+ }
3724
+ if (char === "\\") compound += char + (selector[++i] ?? "");
3725
+ else if (char === "\"" || char === "'") {
3726
+ quote = char;
3727
+ compound += char;
3728
+ } else if (char === "[") {
3729
+ bracketDepth += 1;
3730
+ compound += char;
3731
+ } else if (char === "]") {
3732
+ bracketDepth -= 1;
3733
+ compound += char;
3734
+ } else if (char === "(") {
3735
+ parenDepth += 1;
3736
+ compound += char;
3737
+ } else if (char === ")") {
3738
+ parenDepth -= 1;
3739
+ compound += char;
3740
+ } else if (bracketDepth === 0 && parenDepth === 0 && (char === " " || char === "," || char === ">" || char === "+" || char === "~")) {
3741
+ flush();
3742
+ result += char;
3743
+ } else compound += char;
3744
+ }
3745
+ flush();
3746
+ return result.trim();
3747
+ }
3748
+ function scopeCompound(compound, styleHash) {
3749
+ if (!compound.includes(":global(")) return addScope(compound, styleHash);
3750
+ const { text, onlyGlobal } = stripGlobal(compound);
3751
+ return onlyGlobal ? text : addScope(text, styleHash);
3752
+ }
3753
+ /** Removes `:global(...)` wrappers, reporting whether anything local remained. */
3754
+ function stripGlobal(compound) {
3755
+ let text = "";
3756
+ let hadLocal = false;
3757
+ let i = 0;
3758
+ while (i < compound.length) {
3759
+ if (compound.startsWith(":global(", i)) {
3760
+ const close = findClosingParen(compound, i + 7);
3761
+ if (close === -1) {
3762
+ text += compound.substring(i);
3763
+ break;
3343
3764
  }
3344
- s = `${pre}.torp-${styleHash}${post}`;
3765
+ text += compound.substring(i + 8, close);
3766
+ i = close + 1;
3767
+ continue;
3768
+ }
3769
+ const char = compound[i];
3770
+ if (char.trim()) hadLocal = true;
3771
+ text += char;
3772
+ i += 1;
3773
+ }
3774
+ return {
3775
+ text,
3776
+ onlyGlobal: !hadLocal
3777
+ };
3778
+ }
3779
+ function addScope(compound, styleHash) {
3780
+ const colon = findFirstPseudo(compound);
3781
+ const scope = `.torp-${styleHash}`;
3782
+ return colon === -1 ? `${compound}${scope}` : `${compound.substring(0, colon)}${scope}${compound.substring(colon)}`;
3783
+ }
3784
+ /** Finds the first top-level `:` (pseudo-class/element), skipping brackets/strings. */
3785
+ function findFirstPseudo(compound) {
3786
+ let bracketDepth = 0;
3787
+ let parenDepth = 0;
3788
+ let quote = null;
3789
+ for (let i = 0; i < compound.length; i++) {
3790
+ const char = compound[i];
3791
+ if (quote !== null) {
3792
+ if (char === "\\") i += 1;
3793
+ else if (char === quote) quote = null;
3794
+ continue;
3795
+ }
3796
+ if (char === "\\") i += 1;
3797
+ else if (char === "\"" || char === "'") quote = char;
3798
+ else if (char === "[") bracketDepth += 1;
3799
+ else if (char === "]") bracketDepth -= 1;
3800
+ else if (char === "(") parenDepth += 1;
3801
+ else if (char === ")") parenDepth -= 1;
3802
+ else if (bracketDepth === 0 && parenDepth === 0 && char === ":") return i;
3803
+ }
3804
+ return -1;
3805
+ }
3806
+ function findClosingParen(source, open) {
3807
+ let depth = 0;
3808
+ let bracketDepth = 0;
3809
+ let quote = null;
3810
+ for (let i = open; i < source.length; i++) {
3811
+ const char = source[i];
3812
+ if (quote !== null) {
3813
+ if (char === "\\") i += 1;
3814
+ else if (char === quote) quote = null;
3815
+ continue;
3816
+ }
3817
+ if (char === "\\") i += 1;
3818
+ else if (char === "\"" || char === "'") quote = char;
3819
+ else if (char === "[") bracketDepth += 1;
3820
+ else if (char === "]") bracketDepth -= 1;
3821
+ else if (bracketDepth === 0 && char === "(") depth += 1;
3822
+ else if (bracketDepth === 0 && char === ")") {
3823
+ depth -= 1;
3824
+ if (depth === 0) return i;
3345
3825
  }
3346
- selectors.push(s);
3347
3826
  }
3827
+ return -1;
3348
3828
  }
3349
3829
  function buildAttributeNode(attribute, b) {
3350
3830
  b.append(`${attribute.name}: ${attribute.value};`);
3351
3831
  }
3352
3832
  //#endregion
3833
+ //#region src/compile/utils/containsAwaitGroup.ts
3834
+ /**
3835
+ * Whether a markup tree contains an `@await` boundary, so the component's
3836
+ * render must be wrapped in a flush.
3837
+ */
3838
+ function containsAwaitGroup(node) {
3839
+ if (node === void 0 || node === null) return false;
3840
+ if (isControlNode(node) && node.operation === "@await group") return true;
3841
+ if (node.type !== "text" && node.type !== "comment") {
3842
+ for (let child of node.children) if (containsAwaitGroup(child)) return true;
3843
+ }
3844
+ return false;
3845
+ }
3846
+ //#endregion
3353
3847
  //#region src/compile/build/server/flushOutput.ts
3354
3848
  /**
3355
3849
  * Appends any pending output to the generated code, targeting the body
@@ -3402,7 +3896,7 @@ function buildServerComponentNode(node, status, b) {
3402
3896
  for (let slot of node.children) if (isSpecialNode(slot) && (slot.tagName === "fill" || slot.tagName === "filldef")) {
3403
3897
  const nameAttribute = slot.attributes.find((a) => a.name === "name");
3404
3898
  const slotName = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
3405
- const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3899
+ const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) || containsAwaitGroup(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3406
3900
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = async (\n${slotParams.join(",\n")}\n) => {`);
3407
3901
  b.append(`let t_body = "";`);
3408
3902
  for (let child of slot.children) buildServerNode(child, status, b);
@@ -3458,7 +3952,7 @@ function buildServerAwaitNode(node, status, b) {
3458
3952
  for (let branch of node.children) if (isControlNode(branch) && branch.operation === "@with") for (let child of branch.children) buildServerNode(child, status, b);
3459
3953
  flushOutput(status, b);
3460
3954
  b.append(`return { body: t_body, head: t_head };`);
3461
- b.append(`});`);
3955
+ b.append(`}, $context);`);
3462
3956
  b.append(`${status.inHead ? "t_head" : "t_body"} += ${resultName}.body;`);
3463
3957
  b.append(`t_head += ${resultName}.head;`);
3464
3958
  }
@@ -3640,7 +4134,7 @@ function buildServerElementNode(node, status, b) {
3640
4134
  status.output += `<${tagName}${attributes}>`;
3641
4135
  if (!voidTags.includes(tagName)) {
3642
4136
  const oldPreserveWhitespace = status.preserveWhitespace;
3643
- status.preserveWhitespace = ["pre", "code"].includes(tagName);
4137
+ status.preserveWhitespace = ["pre", "code"].includes(tagName) || isRawTextTag(tagName);
3644
4138
  if (!tagName.startsWith("@")) status.elementStack.push(tagName);
3645
4139
  for (let child of node.children) buildServerNode(child, status, b);
3646
4140
  if (!tagName.startsWith("@")) status.elementStack.pop();
@@ -3658,16 +4152,13 @@ function buildElementAttributes(node, status) {
3658
4152
  let typeAttribute = node.attributes.find((a) => a.name === "type");
3659
4153
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
3660
4154
  case "number":
3661
- defaultValue = "0";
4155
+ defaultValue = "\"\"";
3662
4156
  break;
3663
4157
  case "checkbox": defaultValue = "false";
3664
4158
  }
3665
- if (!defaultValue) {
3666
- status.imports.add("t_attr");
3667
- value = `t_attr(${value})`;
3668
- defaultValue = "\"\"";
3669
- }
3670
- let valueOrDefault = `(${value}) || ${defaultValue}`;
4159
+ if (!defaultValue) defaultValue = "\"\"";
4160
+ status.imports.add("t_attr");
4161
+ let valueOrDefault = `t_attr(${value}) || ${defaultValue}`;
3671
4162
  const propName = name.substring(1);
3672
4163
  attributes.push(`${propName}="\${${valueOrDefault}}"`);
3673
4164
  } else if (name === "class") {
@@ -3690,9 +4181,9 @@ function buildElementAttributes(node, status) {
3690
4181
  attributes.push(`${name}="${trimQuotes(value).replaceAll("{", "${t_attr(").replaceAll("}", ")}")}"`);
3691
4182
  } else if (name === "class" && node.scopeStyles && !status.inHead) {
3692
4183
  value = value ? `"${trimQuotes(value)} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
3693
- attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4184
+ attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3694
4185
  needsClass = false;
3695
- } else if (value != null) attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4186
+ } else if (value != null) attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3696
4187
  else attributes.push(`${name}`);
3697
4188
  if (needsClass) attributes.push(`class="torp-${status.styleHash}"`);
3698
4189
  return attributes.join(" ");
@@ -3755,15 +4246,21 @@ function buildServerSpecialNode(node, status, b) {
3755
4246
  //#region src/compile/build/server/buildServerTextNode.ts
3756
4247
  function buildServerTextNode(node, status) {
3757
4248
  let content = node.content || "";
4249
+ if (node.raw) {
4250
+ status.output += escapeRawText(content);
4251
+ return;
4252
+ }
3758
4253
  if (!status.preserveWhitespace) content = content.replaceAll(/\s+/g, " ");
4254
+ const parentTag = status.elementStack[status.elementStack.length - 1];
4255
+ const formatter = parentTag !== void 0 && isRawTextTag(parentTag) ? "t_fmt_raw" : "t_fmt";
3759
4256
  let level = 0;
3760
4257
  for (let i = 0; i < content.length; i++) {
3761
4258
  const char = content[i];
3762
4259
  if (char === "{") {
3763
4260
  level++;
3764
4261
  if (level === 1) {
3765
- status.imports.add("t_fmt");
3766
- status.output += "${t_fmt(";
4262
+ status.imports.add(formatter);
4263
+ status.output += "${" + formatter + "(";
3767
4264
  continue;
3768
4265
  }
3769
4266
  } else if (char === "}") {
@@ -3826,8 +4323,10 @@ const importsMap = {
3826
4323
  $peek: "import { $peek } from \"${folder}\";",
3827
4324
  $batch: "import { $batch } from \"${folder}\";",
3828
4325
  t_server_flush: "import { t_server_flush } from \"${folder}\";",
4326
+ t_render_context: "import { t_render_context } from \"${folder}\";",
3829
4327
  t_await_server: "import { t_await_server } from \"${folder}\";",
3830
4328
  t_fmt: "import { t_fmt } from \"${folder}\";",
4329
+ t_fmt_raw: "import { t_fmt_raw } from \"${folder}\";",
3831
4330
  t_attr: "import { t_attr } from \"${folder}\";",
3832
4331
  t_attr_if: "import { t_attr_if } from \"${folder}\";",
3833
4332
  t_class: "import { t_class } from \"${folder}\";",
@@ -3875,121 +4374,118 @@ function buildServerTemplate(template, imports, b, options) {
3875
4374
  for (let [i, chunk] of template.script.entries()) if (chunk.script === "/* @params */" && i > 0) asyncChunks.add(i - 1);
3876
4375
  let currentIndex = 0;
3877
4376
  let current = template.components[0];
3878
- for (let [chunkIndex, chunk] of template.script.entries()) if (chunk.script === "/* @params */") {
3879
- let params = [
3880
- current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
3881
- `${current.contextProps?.length || current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error) ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
3882
- `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
3883
- ];
3884
- b.append(params.join(",\n") + ",");
3885
- } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
3886
- else if (chunk.script === "/* @start */") {
3887
- if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
3888
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) {
3889
- imports.add("t_server_flush");
3890
- b.append(`return t_server_flush(async () => {`);
3891
- }
3892
- b.append(`let t_body = "";`);
3893
- b.append(`let t_head = "";`);
3894
- } else if (chunk.script === "/* @render */") {
3895
- if (current.markup) {
3896
- const status = {
3897
- imports,
3898
- output: "",
3899
- styleHash: current.style?.hash || "",
3900
- varNames: {},
3901
- preserveWhitespace: false,
3902
- awaitCount: 0,
3903
- elementStack: [],
3904
- options
3905
- };
3906
- b.append("");
3907
- b.append("/* User interface */");
3908
- if (current.error) {
3909
- b.append(`const t_try_body = t_body;`);
3910
- b.append(`const t_try_head = t_head;`);
3911
- b.append("try {");
4377
+ for (let [chunkIndex, chunk] of template.script.entries()) {
4378
+ const hasAwait = current !== void 0 && (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head));
4379
+ const rendersComponent = current !== void 0 && (current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error));
4380
+ if (chunk.script === "/* @params */") {
4381
+ let params = [
4382
+ current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
4383
+ `${current.contextProps?.length || rendersComponent || hasAwait ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
4384
+ `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
4385
+ ];
4386
+ b.append(params.join(",\n") + ",");
4387
+ } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
4388
+ else if (chunk.script === "/* @start */") {
4389
+ if (rendersComponent || hasAwait) {
4390
+ imports.add("t_render_context");
4391
+ b.append(`$context = t_render_context($context);`);
3912
4392
  }
3913
- buildServerNode(current.markup, status, b);
3914
- if (status.output) {
3915
- b.append(`t_body += \`${status.output}\`;`);
3916
- status.output = "";
4393
+ if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
4394
+ if (hasAwait) {
4395
+ imports.add("t_server_flush");
4396
+ b.append(`return t_server_flush(async () => {`);
3917
4397
  }
3918
- }
3919
- } else if (chunk.script === "/* @error */") {
3920
- if (current.markup && current.error) {
3921
- const status = {
3922
- imports,
3923
- output: "",
3924
- styleHash: current.style?.hash || "",
3925
- varNames: {},
3926
- preserveWhitespace: false,
3927
- awaitCount: 0,
3928
- elementStack: [],
3929
- options
3930
- };
3931
- b.append(`} catch (${current.errorVar}) {`);
3932
- b.append("t_body = t_try_body;");
3933
- b.append("t_head = t_try_head;");
3934
- b.append("/* User interface error */");
3935
- buildServerNode(current.error, status, b);
3936
- if (status.output) {
3937
- b.append(`t_body += \`${status.output}\`;`);
3938
- status.output = "";
4398
+ b.append(`let t_body = "";`);
4399
+ b.append(`let t_head = "";`);
4400
+ } else if (chunk.script === "/* @render */") {
4401
+ if (current.markup) {
4402
+ const status = {
4403
+ imports,
4404
+ output: "",
4405
+ styleHash: current.style?.hash || "",
4406
+ varNames: {},
4407
+ preserveWhitespace: false,
4408
+ awaitCount: 0,
4409
+ elementStack: [],
4410
+ options
4411
+ };
4412
+ b.append("");
4413
+ b.append("/* User interface */");
4414
+ if (current.error) {
4415
+ b.append(`const t_try_body = t_body;`);
4416
+ b.append(`const t_try_head = t_head;`);
4417
+ b.append("try {");
4418
+ }
4419
+ buildServerNode(current.markup, status, b);
4420
+ if (status.output) {
4421
+ b.append(`t_body += \`${status.output}\`;`);
4422
+ status.output = "";
4423
+ }
3939
4424
  }
3940
- b.append("}");
3941
- }
3942
- } else if (chunk.script === "/* @head */") {
3943
- if (current.head) {
3944
- const status = {
3945
- imports,
3946
- output: "",
3947
- styleHash: current.style?.hash || "",
3948
- varNames: {},
3949
- preserveWhitespace: false,
3950
- inHead: true,
3951
- awaitCount: 0,
3952
- elementStack: [],
3953
- options
3954
- };
3955
- b.append("");
3956
- b.append("/* Head */");
3957
- buildServerNode(current.head, status, b);
3958
- flushOutput(status, b);
3959
- }
3960
- } else if (chunk.script === "/* @style */") {
3961
- if (current.style) {
3962
- b.append("");
3963
- b.append("/* Style */");
3964
- const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
3965
- b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
3966
- }
3967
- } else if (chunk.script === "/* @end */") {
3968
- b.append(`return { body: t_body, head: t_head };`);
3969
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) b.append(`});`);
3970
- currentIndex += 1;
3971
- current = template.components[currentIndex];
3972
- } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
3973
- else b.append(chunk.script);
3974
- }
3975
- /**
3976
- * Whether a markup tree contains an `@await` boundary, so the component's
3977
- * render must be wrapped in a flush.
3978
- */
3979
- function containsAwaitGroup(node) {
3980
- if (node === void 0 || node === null) return false;
3981
- if (isControlNode(node) && node.operation === "@await group") return true;
3982
- if (node.type !== "text" && node.type !== "comment") {
3983
- for (let child of node.children) if (containsAwaitGroup(child)) return true;
4425
+ } else if (chunk.script === "/* @error */") {
4426
+ if (current.markup && current.error) {
4427
+ const status = {
4428
+ imports,
4429
+ output: "",
4430
+ styleHash: current.style?.hash || "",
4431
+ varNames: {},
4432
+ preserveWhitespace: false,
4433
+ awaitCount: 0,
4434
+ elementStack: [],
4435
+ options
4436
+ };
4437
+ b.append(`} catch (${current.errorVar}) {`);
4438
+ b.append("t_body = t_try_body;");
4439
+ b.append("t_head = t_try_head;");
4440
+ b.append("/* User interface error */");
4441
+ buildServerNode(current.error, status, b);
4442
+ if (status.output) {
4443
+ b.append(`t_body += \`${status.output}\`;`);
4444
+ status.output = "";
4445
+ }
4446
+ b.append("}");
4447
+ }
4448
+ } else if (chunk.script === "/* @head */") {
4449
+ if (current.head) {
4450
+ const status = {
4451
+ imports,
4452
+ output: "",
4453
+ styleHash: current.style?.hash || "",
4454
+ varNames: {},
4455
+ preserveWhitespace: false,
4456
+ inHead: true,
4457
+ awaitCount: 0,
4458
+ elementStack: [],
4459
+ options
4460
+ };
4461
+ b.append("");
4462
+ b.append("/* Head */");
4463
+ buildServerNode(current.head, status, b);
4464
+ flushOutput(status, b);
4465
+ }
4466
+ } else if (chunk.script === "/* @style */") {
4467
+ if (current.style) {
4468
+ b.append("");
4469
+ b.append("/* Style */");
4470
+ const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
4471
+ b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
4472
+ }
4473
+ } else if (chunk.script === "/* @end */") {
4474
+ b.append(`return { body: t_body, head: t_head };`);
4475
+ if (hasAwait) b.append(`});`);
4476
+ currentIndex += 1;
4477
+ current = template.components[currentIndex];
4478
+ } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
4479
+ else b.append(chunk.script);
3984
4480
  }
3985
- return false;
3986
4481
  }
3987
4482
  //#endregion
3988
4483
  //#region src/compile/utils/trimWhitespace.ts
3989
4484
  /**
3990
4485
  * Tag names whose contents should keep all whitespace untouched, matching
3991
4486
  * native HTML rendering of `pre`/`textarea` and the existing build-time
3992
- * `preserveWhitespace` behavior for `code`.
4487
+ * `preserveWhitespace` behavior for `code`. Raw-text elements (including
4488
+ * inline `<script>` / `<style>`) keep their contents exactly as written.
3993
4489
  */
3994
4490
  const PRESERVE_TAGS = /* @__PURE__ */ new Set([
3995
4491
  "pre",
@@ -4042,7 +4538,7 @@ function trimChildren(children, preserveAll, parentTag) {
4042
4538
  const grandChildren = getChildren(child);
4043
4539
  if (grandChildren) {
4044
4540
  const childTag = getTagName(child);
4045
- trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? ""), childTag);
4541
+ trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? "") || isRawTextTag(childTag ?? ""), childTag);
4046
4542
  }
4047
4543
  }
4048
4544
  if (preserveAll) return;
@@ -4981,7 +5477,7 @@ function serializeElement(node, context) {
4981
5477
  context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4982
5478
  return;
4983
5479
  }
4984
- const childContext = node.tagName === "pre" || node.tagName === "code" ? {
5480
+ const childContext = node.tagName === "pre" || node.tagName === "code" || isRawTextTag(node.tagName) ? {
4985
5481
  ...context,
4986
5482
  preserveWhitespace: true
4987
5483
  } : context;
@@ -5311,6 +5807,544 @@ function isSpaceNode(node) {
5311
5807
  return isTextNode(node) && isSpace(node.content);
5312
5808
  }
5313
5809
  //#endregion
5810
+ //#region src/compile/utils/nativeTags.ts
5811
+ /**
5812
+ * Native HTML and SVG tag names, used to tell elements apart from components.
5813
+ * A tag that is neither imported nor a component declared in the same file is
5814
+ * an element when it appears here, or when it contains a dash (an HTML custom
5815
+ * element). Anything else capitalized is reported as an unknown component.
5816
+ */
5817
+ const htmlTags = [
5818
+ "a",
5819
+ "abbr",
5820
+ "address",
5821
+ "area",
5822
+ "article",
5823
+ "aside",
5824
+ "audio",
5825
+ "b",
5826
+ "base",
5827
+ "bdi",
5828
+ "bdo",
5829
+ "blockquote",
5830
+ "body",
5831
+ "br",
5832
+ "button",
5833
+ "canvas",
5834
+ "caption",
5835
+ "cite",
5836
+ "code",
5837
+ "col",
5838
+ "colgroup",
5839
+ "data",
5840
+ "datalist",
5841
+ "dd",
5842
+ "del",
5843
+ "details",
5844
+ "dfn",
5845
+ "dialog",
5846
+ "div",
5847
+ "dl",
5848
+ "dt",
5849
+ "em",
5850
+ "embed",
5851
+ "fieldset",
5852
+ "figcaption",
5853
+ "figure",
5854
+ "footer",
5855
+ "form",
5856
+ "h1",
5857
+ "h2",
5858
+ "h3",
5859
+ "h4",
5860
+ "h5",
5861
+ "h6",
5862
+ "head",
5863
+ "header",
5864
+ "hgroup",
5865
+ "hr",
5866
+ "html",
5867
+ "i",
5868
+ "iframe",
5869
+ "img",
5870
+ "input",
5871
+ "ins",
5872
+ "kbd",
5873
+ "label",
5874
+ "legend",
5875
+ "li",
5876
+ "link",
5877
+ "main",
5878
+ "map",
5879
+ "mark",
5880
+ "menu",
5881
+ "meta",
5882
+ "meter",
5883
+ "nav",
5884
+ "noscript",
5885
+ "object",
5886
+ "ol",
5887
+ "optgroup",
5888
+ "option",
5889
+ "output",
5890
+ "p",
5891
+ "picture",
5892
+ "pre",
5893
+ "progress",
5894
+ "q",
5895
+ "rp",
5896
+ "rt",
5897
+ "ruby",
5898
+ "s",
5899
+ "samp",
5900
+ "script",
5901
+ "search",
5902
+ "section",
5903
+ "select",
5904
+ "slot",
5905
+ "small",
5906
+ "source",
5907
+ "span",
5908
+ "strong",
5909
+ "style",
5910
+ "sub",
5911
+ "summary",
5912
+ "sup",
5913
+ "table",
5914
+ "tbody",
5915
+ "td",
5916
+ "template",
5917
+ "textarea",
5918
+ "tfoot",
5919
+ "th",
5920
+ "thead",
5921
+ "time",
5922
+ "title",
5923
+ "tr",
5924
+ "track",
5925
+ "u",
5926
+ "ul",
5927
+ "var",
5928
+ "video",
5929
+ "wbr"
5930
+ ];
5931
+ const svgTags = [
5932
+ "a",
5933
+ "animate",
5934
+ "animateMotion",
5935
+ "animateTransform",
5936
+ "circle",
5937
+ "clipPath",
5938
+ "defs",
5939
+ "desc",
5940
+ "discard",
5941
+ "ellipse",
5942
+ "feBlend",
5943
+ "feColorMatrix",
5944
+ "feComponentTransfer",
5945
+ "feComposite",
5946
+ "feConvolveMatrix",
5947
+ "feDiffuseLighting",
5948
+ "feDisplacementMap",
5949
+ "feDistantLight",
5950
+ "feDropShadow",
5951
+ "feFlood",
5952
+ "feFuncA",
5953
+ "feFuncB",
5954
+ "feFuncG",
5955
+ "feFuncR",
5956
+ "feGaussianBlur",
5957
+ "feImage",
5958
+ "feMerge",
5959
+ "feMergeNode",
5960
+ "feMorphology",
5961
+ "feOffset",
5962
+ "fePointLight",
5963
+ "feSpecularLighting",
5964
+ "feSpotLight",
5965
+ "feTile",
5966
+ "feTurbulence",
5967
+ "filter",
5968
+ "foreignObject",
5969
+ "g",
5970
+ "image",
5971
+ "line",
5972
+ "linearGradient",
5973
+ "marker",
5974
+ "mask",
5975
+ "metadata",
5976
+ "mpath",
5977
+ "path",
5978
+ "pattern",
5979
+ "polygon",
5980
+ "polyline",
5981
+ "radialGradient",
5982
+ "rect",
5983
+ "script",
5984
+ "set",
5985
+ "stop",
5986
+ "style",
5987
+ "svg",
5988
+ "switch",
5989
+ "symbol",
5990
+ "text",
5991
+ "textPath",
5992
+ "title",
5993
+ "tspan",
5994
+ "use",
5995
+ "view"
5996
+ ];
5997
+ const nativeTags = /* @__PURE__ */ new Set([...htmlTags, ...svgTags]);
5998
+ //#endregion
5999
+ //#region src/compile/parse/utils/usesSlot.ts
6000
+ const slotRegex = /\$slot\b/;
6001
+ /**
6002
+ * Checks whether the $slot variable is read in the nodes' own scope
6003
+ *
6004
+ * Note that the children of a component node are excluded, because they are
6005
+ * passed to the component as fills, which get their own $slot parameter.
6006
+ * The component's attributes do belong to this scope.
6007
+ *
6008
+ * @param nodes The nodes to check
6009
+ *
6010
+ * @returns True if a $slot variable is read in the nodes' own scope
6011
+ */
6012
+ function usesSlot(nodes) {
6013
+ for (let node of nodes) if (node.type === "text") {
6014
+ const text = node;
6015
+ if (slotRegex.test(text.content)) return true;
6016
+ } else if (node.type === "control") {
6017
+ const control = node;
6018
+ if (slotRegex.test(control.statement)) return true;
6019
+ if (usesSlot(control.children)) return true;
6020
+ } else if (node.type === "element" || node.type === "special" || node.type === "component") {
6021
+ const element = node;
6022
+ for (let attribute of element.attributes) {
6023
+ if (slotRegex.test(attribute.name)) return true;
6024
+ if (attribute.value && slotRegex.test(attribute.value)) return true;
6025
+ }
6026
+ if (element.type !== "component" && usesSlot(element.children)) return true;
6027
+ }
6028
+ return false;
6029
+ }
6030
+ //#endregion
6031
+ //#region src/compile/parse/slottifyChildNodes.ts
6032
+ /**
6033
+ * Moves any child nodes that aren't already in a <fill> node into a default
6034
+ * <fill> node
6035
+ */
6036
+ function slottifyChildNodes(node) {
6037
+ let nonFillNodes = [];
6038
+ for (let child of node.children) if (isFillNode(child)) {
6039
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
6040
+ else break;
6041
+ } else nonFillNodes.push(child);
6042
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
6043
+ if (nonFillNodes.length) {
6044
+ let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
6045
+ if (!defaultFillNode) {
6046
+ defaultFillNode = {
6047
+ type: "special",
6048
+ tagName: "filldef",
6049
+ attributes: [],
6050
+ children: nonFillNodes,
6051
+ span: {
6052
+ start: 0,
6053
+ end: 0
6054
+ },
6055
+ hasSlotProps: usesSlot(nonFillNodes)
6056
+ };
6057
+ node.children.unshift(defaultFillNode);
6058
+ }
6059
+ node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
6060
+ }
6061
+ }
6062
+ function isFillNode(n) {
6063
+ return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
6064
+ }
6065
+ //#endregion
6066
+ //#region src/compile/parse/utils/addError.ts
6067
+ /**
6068
+ * Adds an error to the parse status
6069
+ *
6070
+ * @param status The parse status
6071
+ * @param message The error message to add
6072
+ * @param start (Optional) The start position of the error (defaults to the
6073
+ * current parse position)
6074
+ */
6075
+ function addError(status, message, start = status.i, end = status.i) {
6076
+ let startLine = 0;
6077
+ let lastLineStart = 0;
6078
+ let i = 0;
6079
+ for (; i < start; i++) if (status.source[i] === "\n") {
6080
+ startLine += 1;
6081
+ lastLineStart = i + 1;
6082
+ }
6083
+ let startChar = start - lastLineStart;
6084
+ let endLine = startLine;
6085
+ for (; i < end; i++) if (status.source[i] === "\n") {
6086
+ endLine += 1;
6087
+ lastLineStart = i + 1;
6088
+ }
6089
+ let endChar = end - lastLineStart;
6090
+ status.errors.push({
6091
+ message,
6092
+ startIndex: start,
6093
+ startLine,
6094
+ startChar,
6095
+ endIndex: end,
6096
+ endLine,
6097
+ endChar
6098
+ });
6099
+ }
6100
+ //#endregion
6101
+ //#region src/compile/parse/classifyComponents.ts
6102
+ /**
6103
+ * Classifies parsed tags as components or native elements once the whole file
6104
+ * has been parsed (so forward-declared local components are known).
6105
+ *
6106
+ * A tag is a component when its name is imported or is a component declared in
6107
+ * this file. Native and custom elements (`<div>`, `<my-widget>`,
6108
+ * `<linearGradient>`) stay elements. Any other capitalized tag is reported as
6109
+ * unknown instead of silently becoming a component call, unless the caller
6110
+ * opts into assuming external components (`allowUnknownComponents`).
6111
+ */
6112
+ function classifyComponents(status, importedNames, options) {
6113
+ const localNames = new Set(status.components.map((component) => component.name).filter((name) => !!name));
6114
+ for (const component of status.components) {
6115
+ if (component.markup) classifyNode(component.markup, status, importedNames, localNames, options);
6116
+ if (component.error) classifyNode(component.error, status, importedNames, localNames, options);
6117
+ if (component.head) classifyNode(component.head, status, importedNames, localNames, options);
6118
+ }
6119
+ }
6120
+ function classifyNode(node, status, importedNames, localNames, options) {
6121
+ if (isParentNode(node)) for (const child of node.children) classifyNode(child, status, importedNames, localNames, options);
6122
+ if (!isElementNode(node)) return;
6123
+ const tagName = node.tagName;
6124
+ if (importedNames.has(tagName) || localNames.has(tagName)) {
6125
+ node.type = "component";
6126
+ slottifyChildNodes(node);
6127
+ } else if (!nativeTags.has(tagName) && !tagName.includes("-") && /^[A-Z]/.test(tagName)) {
6128
+ if (options?.allowUnknownComponents) {
6129
+ node.type = "component";
6130
+ slottifyChildNodes(node);
6131
+ } else addError(status, `Unknown component or element: ${tagName}. Import it or define it in this file.`, node.span.start, node.span.end);
6132
+ }
6133
+ }
6134
+ //#endregion
6135
+ //#region src/compile/parse/collectImportNames.ts
6136
+ /**
6137
+ * Collects the local binding names introduced by top-level import statements.
6138
+ * Used to tell component tags apart from native elements without touching the
6139
+ * filesystem or relying on a tag-name convention.
6140
+ *
6141
+ * This is a focused import scanner, not a general JS parser: it handles the
6142
+ * import forms (`default`, `* as`, named/aliased, side-effect), comments and
6143
+ * multiline clauses. Type-only imports are ignored (they don't introduce a
6144
+ * value that can be rendered as a tag).
6145
+ */
6146
+ function collectImportNames(source) {
6147
+ const names = /* @__PURE__ */ new Set();
6148
+ let depth = 0;
6149
+ let i = 0;
6150
+ while (i < source.length) {
6151
+ const skipped = skipStringOrComment(source, i);
6152
+ if (skipped !== -1) {
6153
+ i = skipped;
6154
+ continue;
6155
+ }
6156
+ const char = source[i];
6157
+ if (char === "{") {
6158
+ depth += 1;
6159
+ i += 1;
6160
+ continue;
6161
+ }
6162
+ if (char === "}") {
6163
+ depth -= 1;
6164
+ i += 1;
6165
+ continue;
6166
+ }
6167
+ if (depth === 0 && char === "i" && startsWordAt(source, i, "import") && source[i - 1] !== ".") {
6168
+ const end = parseImport(source, i + 6, names);
6169
+ if (end !== -1) {
6170
+ i = end;
6171
+ continue;
6172
+ }
6173
+ }
6174
+ i += 1;
6175
+ }
6176
+ return names;
6177
+ }
6178
+ /** Parses one import statement, adding its value bindings. Returns the end index. */
6179
+ function parseImport(source, start, names) {
6180
+ let i = skipSpaceAndComments(source, start);
6181
+ if (i >= source.length) return -1;
6182
+ if (source[i] === "." || source[i] === "(") return -1;
6183
+ if (source[i] === "\"" || source[i] === "'") return skipStringAndStatementEnd(source, i);
6184
+ let typeOnly = false;
6185
+ if (startsWordAt(source, i, "type")) {
6186
+ const afterType = skipSpaceAndComments(source, i + 4);
6187
+ const next = source[afterType];
6188
+ if (next === "{" || next === "*" || isIdentifierStart(next)) {
6189
+ if (next === "{" || next === "*" || isTypeOnlyDefault(source, afterType)) {
6190
+ typeOnly = true;
6191
+ i = afterType;
6192
+ }
6193
+ }
6194
+ }
6195
+ while (i < source.length) {
6196
+ i = skipSpaceAndComments(source, i);
6197
+ if (i >= source.length) return -1;
6198
+ if (startsWordAt(source, i, "from")) {
6199
+ i = skipStringAndStatementEnd(source, skipSpaceAndComments(source, i + 4));
6200
+ return i;
6201
+ }
6202
+ const char = source[i];
6203
+ if (char === "{") {
6204
+ i += 1;
6205
+ while (i < source.length) {
6206
+ i = skipSpaceAndComments(source, i);
6207
+ if (source[i] === "}") {
6208
+ i += 1;
6209
+ break;
6210
+ }
6211
+ const specifier = parseSpecifier(source, i);
6212
+ if (!specifier) {
6213
+ i += 1;
6214
+ continue;
6215
+ }
6216
+ i = specifier.end;
6217
+ if (!typeOnly && specifier.name) names.add(specifier.name);
6218
+ }
6219
+ continue;
6220
+ }
6221
+ if (char === "*") {
6222
+ i = skipSpaceAndComments(source, i + 1);
6223
+ if (startsWordAt(source, i, "as")) {
6224
+ i = skipSpaceAndComments(source, i + 2);
6225
+ const identifier = readIdentifier(source, i);
6226
+ if (identifier) {
6227
+ if (!typeOnly) names.add(identifier.name);
6228
+ i = identifier.end;
6229
+ }
6230
+ }
6231
+ continue;
6232
+ }
6233
+ if (char === ",") {
6234
+ i += 1;
6235
+ continue;
6236
+ }
6237
+ if (isIdentifierStart(char)) {
6238
+ const identifier = readIdentifier(source, i);
6239
+ if (identifier) {
6240
+ if (!typeOnly) names.add(identifier.name);
6241
+ i = identifier.end;
6242
+ continue;
6243
+ }
6244
+ }
6245
+ i += 1;
6246
+ }
6247
+ return -1;
6248
+ }
6249
+ function parseSpecifier(source, start) {
6250
+ let i = skipSpaceAndComments(source, start);
6251
+ if (i >= source.length) return void 0;
6252
+ let typeOnly = false;
6253
+ if (startsWordAt(source, i, "type")) {
6254
+ const afterType = skipSpaceAndComments(source, i + 4);
6255
+ const next = source[afterType];
6256
+ if (next && next !== "," && next !== "}" && !startsWordAt(source, afterType, "as")) {
6257
+ typeOnly = true;
6258
+ i = afterType;
6259
+ }
6260
+ }
6261
+ let name;
6262
+ if (source[i] === "\"" || source[i] === "'") {
6263
+ const end = skipStringOrComment(source, i);
6264
+ i = end === -1 ? i + 1 : end;
6265
+ } else {
6266
+ const identifier = readIdentifier(source, i);
6267
+ if (!identifier) return void 0;
6268
+ name = identifier.name;
6269
+ i = identifier.end;
6270
+ }
6271
+ i = skipSpaceAndComments(source, i);
6272
+ if (startsWordAt(source, i, "as")) {
6273
+ i = skipSpaceAndComments(source, i + 2);
6274
+ if (source[i] === "\"" || source[i] === "'") {
6275
+ const end = skipStringOrComment(source, i);
6276
+ i = end === -1 ? i + 1 : end;
6277
+ name = void 0;
6278
+ } else {
6279
+ const alias = readIdentifier(source, i);
6280
+ if (alias) {
6281
+ name = alias.name;
6282
+ i = alias.end;
6283
+ }
6284
+ }
6285
+ }
6286
+ i = skipSpaceAndComments(source, i);
6287
+ if (source[i] === ",") i += 1;
6288
+ return {
6289
+ name: typeOnly ? void 0 : name,
6290
+ end: i
6291
+ };
6292
+ }
6293
+ function isTypeOnlyDefault(source, start) {
6294
+ const identifier = readIdentifier(source, start);
6295
+ if (!identifier) return false;
6296
+ return startsWordAt(source, skipSpaceAndComments(source, identifier.end), "from");
6297
+ }
6298
+ function skipStringAndStatementEnd(source, start) {
6299
+ let i = start;
6300
+ if (source[i] === "\"" || source[i] === "'") {
6301
+ const end = skipStringOrComment(source, i);
6302
+ i = end === -1 ? i + 1 : end;
6303
+ }
6304
+ i = skipSpaceAndComments(source, i);
6305
+ if (source[i] === ";") i += 1;
6306
+ return i;
6307
+ }
6308
+ function skipSpaceAndComments(source, start) {
6309
+ let i = start;
6310
+ while (i < source.length) {
6311
+ if (/\s/.test(source[i])) {
6312
+ i += 1;
6313
+ continue;
6314
+ }
6315
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) {
6316
+ const skipped = skipStringOrComment(source, i);
6317
+ if (skipped !== -1) {
6318
+ i = skipped;
6319
+ continue;
6320
+ }
6321
+ }
6322
+ break;
6323
+ }
6324
+ return i;
6325
+ }
6326
+ function readIdentifier(source, start) {
6327
+ if (!isIdentifierStart(source[start])) return void 0;
6328
+ let end = start + 1;
6329
+ while (end < source.length && isIdentifierPart(source[end])) end += 1;
6330
+ return {
6331
+ name: source.substring(start, end),
6332
+ end
6333
+ };
6334
+ }
6335
+ function isIdentifierStart(char) {
6336
+ return char !== void 0 && /[A-Za-z_$]/.test(char);
6337
+ }
6338
+ function isIdentifierPart(char) {
6339
+ return /[A-Za-z0-9_$]/.test(char);
6340
+ }
6341
+ function startsWordAt(source, start, word) {
6342
+ if (!source.startsWith(word, start)) return false;
6343
+ const previous = source[start - 1];
6344
+ const next = source[start + word.length];
6345
+ return (previous === void 0 || !isIdentifierPart(previous)) && (next === void 0 || !isIdentifierPart(next));
6346
+ }
6347
+ //#endregion
5314
6348
  //#region src/compile/parse/utils/accept.ts
5315
6349
  /**
5316
6350
  * Checks whether the source at the current parse position matches the supplied
@@ -5400,79 +6434,36 @@ function addSpaceElement(parent, status) {
5400
6434
  //#endregion
5401
6435
  //#region src/compile/utils/isFullyReactive.ts
5402
6436
  /**
5403
- * Checks whether the supplied string is fully reactive (i.e. starts and ends with braces)
6437
+ * Checks whether the supplied text is exactly one `{...}` interpolation,
6438
+ * ignoring surrounding whitespace. Braces inside the expression's strings and
6439
+ * comments don't count as delimiters.
5404
6440
  *
5405
- * @param text The string to check
6441
+ * @param text The text to check
5406
6442
  *
5407
- * @returns True if the supplied string is fully reactive
6443
+ * @returns True if the supplied text is fully reactive
5408
6444
  */
5409
6445
  function isFullyReactive(text) {
5410
- return text.trim().startsWith("{") && text.trim().endsWith("}");
6446
+ return isSingleInterpolation(text);
5411
6447
  }
5412
6448
  //#endregion
5413
- //#region src/compile/parse/utils/addError.ts
6449
+ //#region src/compile/parse/utils/consumeTagName.ts
5414
6450
  /**
5415
- * Adds an error to the parse status
6451
+ * Consumes a tag name, allowing letters, digits and dashes (custom elements
6452
+ * such as `<my-widget>`), and advances the current parse position to before
6453
+ * the next non-name character.
5416
6454
  *
5417
6455
  * @param status The parse status
5418
- * @param message The error message to add
5419
- * @param start (Optional) The start position of the error (defaults to the
5420
- * current parse position)
5421
- */
5422
- function addError(status, message, start = status.i, end = status.i) {
5423
- let startLine = 0;
5424
- let lastLineStart = 0;
5425
- let i = 0;
5426
- for (; i < start; i++) if (status.source[i] === "\n") {
5427
- startLine += 1;
5428
- lastLineStart = i + 1;
5429
- }
5430
- let startChar = start - lastLineStart;
5431
- let endLine = startLine;
5432
- for (; i < end; i++) if (status.source[i] === "\n") {
5433
- endLine += 1;
5434
- lastLineStart = i + 1;
5435
- }
5436
- let endChar = end - lastLineStart;
5437
- status.errors.push({
5438
- message,
5439
- startIndex: start,
5440
- startLine,
5441
- startChar,
5442
- endIndex: end,
5443
- endLine,
5444
- endChar
5445
- });
5446
- }
5447
- //#endregion
5448
- //#region src/compile/parse/utils/isAlphaNumericChar.ts
5449
- /**
5450
- * Checks whether the supplied character is a alpha-numeric
5451
6456
  *
5452
- * @param text The string to check
5453
- * @param index The index of the character in the string
5454
- *
5455
- * @returns True if the supplied character is alpha-numeric
6457
+ * @returns The tag name from the current parse position to the next non-name
6458
+ * character
5456
6459
  */
5457
- function isAlphaNumericChar(text, index) {
5458
- let code = text.charCodeAt(index);
5459
- return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
5460
- }
5461
- //#endregion
5462
- //#region src/compile/parse/utils/consumeAlphaNumeric.ts
5463
- /**
5464
- * Consumes alpha-numeric characters and advances the current parse position to
5465
- * before the next non-alpha character
5466
- *
5467
- * @param status The parse status
5468
- *
5469
- * @returns The string of alpha-numeric characters from the current parse position
5470
- * to the next non-alpha character
5471
- */
5472
- function consumeAlphaNumeric(status) {
6460
+ function consumeTagName(status) {
5473
6461
  const start = status.i;
5474
- for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
5475
- return "";
6462
+ for (status.i; status.i < status.source.length; status.i++) {
6463
+ const char = status.source[status.i];
6464
+ if (!/[A-Za-z0-9-]/.test(char)) return status.source.substring(start, status.i);
6465
+ }
6466
+ return status.source.substring(start, status.i);
5476
6467
  }
5477
6468
  //#endregion
5478
6469
  //#region src/compile/parse/utils/consumeUntil.ts
@@ -5499,7 +6490,7 @@ function parseTag(status) {
5499
6490
  consumeSpace(status);
5500
6491
  let tagStart = status.i + 1;
5501
6492
  let snailed = accept("@", status);
5502
- let tagName = consumeAlphaNumeric(status);
6493
+ let tagName = consumeTagName(status);
5503
6494
  let tagEnd = status.i;
5504
6495
  if (snailed) tagName = "@" + tagName;
5505
6496
  if (closeTag) tagName = "/" + tagName;
@@ -5554,14 +6545,20 @@ function parseAttribute(status) {
5554
6545
  if (accept("=", status)) {
5555
6546
  consumeSpace(status);
5556
6547
  valueStart = status.i;
5557
- value = parseAttributeValue(status);
5558
- valueEnd = status.i;
5559
- reactive = isReactive(value);
5560
- fullyReactive = isFullyReactive(value);
5561
- if (fullyReactive) {
5562
- value = value.substring(1, value.length - 1);
5563
- valueStart++;
5564
- valueEnd--;
6548
+ if (status.source[valueStart] === "`") {
6549
+ value = parseTemplateLiteral(status);
6550
+ valueEnd = status.i;
6551
+ reactive = fullyReactive = true;
6552
+ } else {
6553
+ value = parseAttributeValue(status);
6554
+ valueEnd = status.i;
6555
+ fullyReactive = isFullyReactive(value);
6556
+ reactive = fullyReactive;
6557
+ if (fullyReactive) {
6558
+ value = value.substring(1, value.length - 1);
6559
+ valueStart++;
6560
+ valueEnd--;
6561
+ }
5565
6562
  }
5566
6563
  } else if (name.startsWith("{") && name.endsWith("}")) {
5567
6564
  value = name.substring(1, name.length - 1);
@@ -5584,6 +6581,18 @@ function parseAttribute(status) {
5584
6581
  }
5585
6582
  };
5586
6583
  }
6584
+ /**
6585
+ * Consumes a backtick-delimited JavaScript template literal, reusing the
6586
+ * script scanner so `${...}` interpolations and nested strings/templates are
6587
+ * skipped correctly.
6588
+ */
6589
+ function parseTemplateLiteral(status) {
6590
+ const start = status.i;
6591
+ const end = skipStringOrComment(status.source, start);
6592
+ status.i = end === -1 ? start + 1 : end;
6593
+ if (status.source[status.i - 1] !== "`") addError(status, "Unclosed template literal in attribute", start, status.i);
6594
+ return status.source.substring(start, status.i);
6595
+ }
5587
6596
  function parseAttributeValue(status) {
5588
6597
  if (accept("\"", status)) {
5589
6598
  const value = consumeUntil("\"", status);
@@ -5664,73 +6673,6 @@ function parseText(status, element) {
5664
6673
  } else status.i += 1;
5665
6674
  }
5666
6675
  //#endregion
5667
- //#region src/compile/parse/utils/usesSlot.ts
5668
- const slotRegex = /\$slot\b/;
5669
- /**
5670
- * Checks whether the $slot variable is read in the nodes' own scope
5671
- *
5672
- * Note that the children of a component node are excluded, because they are
5673
- * passed to the component as fills, which get their own $slot parameter.
5674
- * The component's attributes do belong to this scope.
5675
- *
5676
- * @param nodes The nodes to check
5677
- *
5678
- * @returns True if a $slot variable is read in the nodes' own scope
5679
- */
5680
- function usesSlot(nodes) {
5681
- for (let node of nodes) if (node.type === "text") {
5682
- const text = node;
5683
- if (slotRegex.test(text.content)) return true;
5684
- } else if (node.type === "control") {
5685
- const control = node;
5686
- if (slotRegex.test(control.statement)) return true;
5687
- if (usesSlot(control.children)) return true;
5688
- } else if (node.type === "element" || node.type === "special" || node.type === "component") {
5689
- const element = node;
5690
- for (let attribute of element.attributes) {
5691
- if (slotRegex.test(attribute.name)) return true;
5692
- if (attribute.value && slotRegex.test(attribute.value)) return true;
5693
- }
5694
- if (element.type !== "component" && usesSlot(element.children)) return true;
5695
- }
5696
- return false;
5697
- }
5698
- //#endregion
5699
- //#region src/compile/parse/slottifyChildNodes.ts
5700
- /**
5701
- * Moves any child nodes that aren't already in a <fill> node into a default
5702
- * <fill> node
5703
- */
5704
- function slottifyChildNodes(node) {
5705
- let nonFillNodes = [];
5706
- for (let child of node.children) if (isFillNode(child)) {
5707
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5708
- else break;
5709
- } else nonFillNodes.push(child);
5710
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5711
- if (nonFillNodes.length) {
5712
- let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
5713
- if (!defaultFillNode) {
5714
- defaultFillNode = {
5715
- type: "special",
5716
- tagName: "filldef",
5717
- attributes: [],
5718
- children: nonFillNodes,
5719
- span: {
5720
- start: 0,
5721
- end: 0
5722
- },
5723
- hasSlotProps: usesSlot(nonFillNodes)
5724
- };
5725
- node.children.unshift(defaultFillNode);
5726
- }
5727
- node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
5728
- }
5729
- }
5730
- function isFillNode(n) {
5731
- return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
5732
- }
5733
- //#endregion
5734
6676
  //#region src/compile/parse/parseElement.ts
5735
6677
  function parseElement(status) {
5736
6678
  const current = status.components.at(-1);
@@ -5744,6 +6686,7 @@ function parseElement(status) {
5744
6686
  if (voidTags.includes(element.tagName)) checkVoidElement(status, element);
5745
6687
  if (!element.selfClosed && !voidTags.includes(element.tagName)) {
5746
6688
  status.stack.push(element);
6689
+ if (isRawTextTag(element.tagName)) parseRawText(status, element);
5747
6690
  while (status.i < status.source.length) {
5748
6691
  addSpaceElement(element, status);
5749
6692
  if (accept("}", status, false)) break;
@@ -5784,10 +6727,6 @@ function parseElement(status) {
5784
6727
  }
5785
6728
  status.stack.pop();
5786
6729
  }
5787
- if (/[A-Z]/.test(element.tagName[0])) {
5788
- element.type = "component";
5789
- slottifyChildNodes(element);
5790
- }
5791
6730
  if (isSpecialNode(element)) {
5792
6731
  if (element.tagName === "slot") {
5793
6732
  slottifyChildNodes(element);
@@ -5825,6 +6764,32 @@ function parseElement(status) {
5825
6764
  if (!element.closed && !voidTags.includes(element.tagName)) addError(status, `Unclosed non-void element: ${element.tagName}`, start, start + element.tagName.length + 1);
5826
6765
  return element;
5827
6766
  }
6767
+ /**
6768
+ * Consumes a raw-text element's content as a single literal text node. The
6769
+ * content ends at the first matching close tag (which the caller's child loop
6770
+ * then handles), or at the end of the source when the element is unclosed.
6771
+ */
6772
+ function parseRawText(status, element) {
6773
+ const start = status.i;
6774
+ const end = findRawTextEnd(status.source, element.tagName, start);
6775
+ if (end > start) {
6776
+ const text = {
6777
+ type: "text",
6778
+ content: status.source.substring(start, end),
6779
+ start,
6780
+ spans: [],
6781
+ raw: true
6782
+ };
6783
+ element.children.push(text);
6784
+ }
6785
+ status.i = end;
6786
+ }
6787
+ function findRawTextEnd(source, tagName, start) {
6788
+ const pattern = new RegExp(`</${tagName}(?=[\\s/>])`, "gi");
6789
+ pattern.lastIndex = start;
6790
+ const match = pattern.exec(source);
6791
+ return match ? match.index : source.length;
6792
+ }
5828
6793
  function checkVoidElement(status, element) {
5829
6794
  let i = status.i;
5830
6795
  consumeSpace(status);
@@ -5844,7 +6809,7 @@ function checkCloseTag(status, element) {
5844
6809
  accept("</", status);
5845
6810
  consumeSpace(status);
5846
6811
  let snailed = accept("@", status);
5847
- let closingTagName = consumeAlphaNumeric(status);
6812
+ let closingTagName = consumeTagName(status);
5848
6813
  if (snailed) closingTagName = "@" + closingTagName;
5849
6814
  consumeSpace(status);
5850
6815
  accept(">", status);
@@ -5954,6 +6919,8 @@ function parseControlOpen(status) {
5954
6919
  };
5955
6920
  }
5956
6921
  function parseControlStatement(start, operation, status) {
6922
+ const standalone = standaloneOperations.includes(operation);
6923
+ const braceStartsBody = !standalone || operation === "@function" || operation === "@async function";
5957
6924
  let parenCount = 0;
5958
6925
  while (status.i < status.source.length) {
5959
6926
  const skipped = skipStringOrComment(status.source, status.i);
@@ -5963,11 +6930,11 @@ function parseControlStatement(start, operation, status) {
5963
6930
  }
5964
6931
  if (accept("(", status)) parenCount += 1;
5965
6932
  else if (accept(")", status)) parenCount -= 1;
5966
- else if (accept("{", status) || accept("\n", status) && standaloneOperations.includes(operation)) {
6933
+ else if (accept("{", status) && braceStartsBody || accept("\n", status) && standalone) {
5967
6934
  if (parenCount === 0) return trimStart(status.source.substring(start, status.i - 1).trim(), "@");
5968
6935
  } else status.i += 1;
5969
6936
  }
5970
- return "";
6937
+ return trimStart(status.source.substring(start, status.i).trim(), "@");
5971
6938
  }
5972
6939
  /**
5973
6940
  * Groups the control node into the correct parent e.g. if/else into an if group
@@ -6220,7 +7187,6 @@ function parseStyles(source, status) {
6220
7187
  marker: 0,
6221
7188
  level: 0,
6222
7189
  braces: [],
6223
- imports: [],
6224
7190
  script: [],
6225
7191
  components: [],
6226
7192
  stack: [],
@@ -6299,37 +7265,64 @@ function parseStyleAttribute(status) {
6299
7265
  }
6300
7266
  //#endregion
6301
7267
  //#region src/compile/parse/scopeStyles.ts
7268
+ /**
7269
+ * Marks every element in a component that has scoped styles with the
7270
+ * component's scope class. This is intentionally not selector-based: deciding
7271
+ * which elements a CSS selector can match requires parsing selectors, and
7272
+ * pseudo-classes, attribute selectors and `@media` rules make compile-time
7273
+ * matching unreliable. Marking every element lets `buildStyles` append the
7274
+ * scope class to selectors without needing to understand their shape.
7275
+ */
6302
7276
  function scopeStyles(status) {
6303
- let selectors = [];
6304
- for (let component of status.components) if (component.style && component.markup) {
6305
- for (let block of component.style.children) if (block.type === "block") collectStyleSelectors(block, selectors);
6306
- scopeStylesOnNode(component.markup, selectors);
7277
+ for (let component of status.components) {
7278
+ if (!component.style) continue;
7279
+ if (component.markup) scopeStylesOnNode(component.markup);
7280
+ if (component.error) scopeStylesOnNode(component.error);
6307
7281
  }
6308
7282
  }
6309
- function scopeStylesOnNode(node, selectors) {
6310
- if (isElementNode(node) || isComponentNode(node)) node.scopeStyles = selectors.includes(node.tagName) || node.attributes.find((a) => {
6311
- if (a.name === "class" && a.reactive) return true;
6312
- else if (a.name === "id" && a.value) {
6313
- if (selectors.includes(`#${trimQuotes(a.value)}`)) return true;
6314
- } else if (a.name === "class" && a.value) {
6315
- for (let classname of trimQuotes(a.value).split(/\s+/)) if (selectors.includes(`.${classname}`)) return true;
6316
- }
6317
- }) !== void 0;
6318
- if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child, selectors);
7283
+ function scopeStylesOnNode(node) {
7284
+ if (isElementNode(node) || isComponentNode(node) || isSpecialNode(node) && (node.tagName === "@element" || node.tagName === "@component")) node.scopeStyles = true;
7285
+ if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child);
6319
7286
  }
6320
- function collectStyleSelectors(block, selectors) {
6321
- for (let s of block.selector.split(/[\s*,>+~[\]]/)) selectors.push(s);
7287
+ //#endregion
7288
+ //#region src/compile/parse/utils/isAlphaNumericChar.ts
7289
+ /**
7290
+ * Checks whether the supplied character is a alpha-numeric
7291
+ *
7292
+ * @param text The string to check
7293
+ * @param index The index of the character in the string
7294
+ *
7295
+ * @returns True if the supplied character is alpha-numeric
7296
+ */
7297
+ function isAlphaNumericChar(text, index) {
7298
+ let code = text.charCodeAt(index);
7299
+ return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
7300
+ }
7301
+ //#endregion
7302
+ //#region src/compile/parse/utils/consumeAlphaNumeric.ts
7303
+ /**
7304
+ * Consumes alpha-numeric characters and advances the current parse position to
7305
+ * before the next non-alpha character
7306
+ *
7307
+ * @param status The parse status
7308
+ *
7309
+ * @returns The string of alpha-numeric characters from the current parse position
7310
+ * to the next non-alpha character
7311
+ */
7312
+ function consumeAlphaNumeric(status) {
7313
+ const start = status.i;
7314
+ for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
7315
+ return "";
6322
7316
  }
6323
7317
  //#endregion
6324
7318
  //#region src/compile/parse/parseCode.ts
6325
- function parseCode(source) {
7319
+ function parseCode(source, options) {
6326
7320
  const status = {
6327
7321
  source,
6328
7322
  i: 0,
6329
7323
  marker: 0,
6330
7324
  level: 0,
6331
7325
  braces: [],
6332
- imports: [],
6333
7326
  script: [],
6334
7327
  components: [],
6335
7328
  stack: [],
@@ -6385,6 +7378,7 @@ function parseCode(source) {
6385
7378
  end: source.length
6386
7379
  }
6387
7380
  });
7381
+ classifyComponents(status, collectImportNames(source), options);
6388
7382
  scopeStyles(status);
6389
7383
  const ok = !status.errors.length;
6390
7384
  if (!ok) status.errors = status.errors.sort((a, b) => a.startIndex - b.startIndex);
@@ -6392,7 +7386,6 @@ function parseCode(source) {
6392
7386
  ok,
6393
7387
  errors: status.errors,
6394
7388
  template: ok ? {
6395
- imports: status.imports,
6396
7389
  script: status.script,
6397
7390
  components: status.components
6398
7391
  } : void 0
@@ -6488,7 +7481,6 @@ function parseComponentStart(status) {
6488
7481
  marker: 0,
6489
7482
  level: 0,
6490
7483
  braces: [],
6491
- imports: [],
6492
7484
  script: [],
6493
7485
  components: [],
6494
7486
  stack: [],
@@ -6749,12 +7741,13 @@ function consumeScriptComments(status) {
6749
7741
  * Parses source code into a component template
6750
7742
  *
6751
7743
  * @param source The source code
7744
+ * @param options Optional parse behaviour
6752
7745
  *
6753
7746
  * @returns A result indicating whether parsing was ok, and if so, containing
6754
7747
  * the component template's parts such as script, markup and styles
6755
7748
  */
6756
- function parse(source) {
6757
- return parseCode(source);
7749
+ function parse(source, options) {
7750
+ return parseCode(source, options);
6758
7751
  }
6759
7752
  //#endregion
6760
7753
  //#region src/compile/parse/bindDataTemplate.ts