@torpor/view 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/{Effect-99HYQdzZ.d.mts → Effect-Bi_nt6cx.d.cts} +31 -3
  2. package/dist/Effect-Bi_nt6cx.d.cts.map +1 -0
  3. package/dist/{Effect-Bf8fz_zC.d.cts → Effect-Bi_nt6cx.d.mts} +31 -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 +1316 -400
  14. package/dist/compile.d.cts +16 -12
  15. package/dist/compile.d.cts.map +1 -1
  16. package/dist/compile.d.mts +16 -12
  17. package/dist/compile.d.mts.map +1 -1
  18. package/dist/compile.mjs +1316 -400
  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 +621 -269
  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 +609 -258
  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-99HYQdzZ.d.mts.map +0 -1
  56. package/dist/Effect-Bf8fz_zC.d.cts.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}"`;
@@ -885,6 +991,21 @@ function isSpecialNode(node) {
885
991
  return node.type === "special";
886
992
  }
887
993
  //#endregion
994
+ //#region src/compile/utils/propKey.ts
995
+ const IDENTIFIER_REGEX = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
996
+ /**
997
+ * Formats a prop name for use as an object key in generated code. Valid
998
+ * identifiers are left unquoted; anything else (e.g. dashed props like
999
+ * `aria-hidden`) is quoted so that the generated code stays valid.
1000
+ *
1001
+ * @param name The prop name as written on the component or slot
1002
+ *
1003
+ * @returns The name as an object key text
1004
+ */
1005
+ function propKey(name) {
1006
+ return IDENTIFIER_REGEX.test(name) ? name : JSON.stringify(name);
1007
+ }
1008
+ //#endregion
888
1009
  //#region src/compile/build/utils/nextVarName.ts
889
1010
  /**
890
1011
  * Makes a supplied variable name (hopefully!) unique by prepending `t_` and
@@ -952,7 +1073,7 @@ function containsIdentifier(value, name) {
952
1073
  * effect to the loop variable's signal).
953
1074
  */
954
1075
  function forVarBindings(status, source) {
955
- return collectBindings(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
1076
+ return collectBindings$1(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
956
1077
  }
957
1078
  /**
958
1079
  * Like `forVarBindings`, but binds only the loop variables named in `names`.
@@ -960,9 +1081,9 @@ function forVarBindings(status, source) {
960
1081
  * the scope's directly-evaluated code reads.
961
1082
  */
962
1083
  function forVarBindingsFor(status, names) {
963
- return collectBindings(status, (forVar) => names.has(forVar.name));
1084
+ return collectBindings$1(status, (forVar) => names.has(forVar.name));
964
1085
  }
965
- function collectBindings(status, include) {
1086
+ function collectBindings$1(status, include) {
966
1087
  const bound = /* @__PURE__ */ new Set();
967
1088
  let result = "";
968
1089
  for (let i = status.forVars.length - 1; i >= 0; i--) {
@@ -1345,7 +1466,7 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1345
1466
  if (lastType === "text" || lastType === "space") return;
1346
1467
  let textPath = {
1347
1468
  parent: path,
1348
- type: isSpace(node.content) ? "space" : "text",
1469
+ type: !node.raw && isSpace(node.content) ? "space" : "text",
1349
1470
  children: []
1350
1471
  };
1351
1472
  path.children.push(textPath);
@@ -1365,11 +1486,12 @@ function declareTextFragmentVars(fragment, node, path, status, b, varPaths, last
1365
1486
  } else {
1366
1487
  status.imports.add("t_txt");
1367
1488
  if (declareVariable) b.append(`(${node.varName} = t_txt(" ")),`);
1489
+ else if (node.raw) b.append(`t_txt(${JSON.stringify(node.content)}),`);
1368
1490
  else b.append(`t_txt("${node.content}"),`);
1369
1491
  }
1370
1492
  }
1371
1493
  function textNodeNeedsDeclaration(node, topLevel, lastChild) {
1372
- return isReactive(node.content) || topLevel && lastChild;
1494
+ return !node.raw && isReactive(node.content) || topLevel && lastChild;
1373
1495
  }
1374
1496
  function declareSpecialFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, lastChild, declare) {
1375
1497
  if (node.tagName === "slot") declareParentAndAnchorFragmentVars(fragment, node, path, status, b, parentName, anchorName, varPaths, "slot", declare);
@@ -1706,8 +1828,9 @@ function buildComponentNode(node, status, b, root = false) {
1706
1828
  let value = p.value;
1707
1829
  p.preText ??= "";
1708
1830
  p.postText ??= "";
1709
- if (p.spans.length === 1) addMappedText(p.name ? `${p.name}: ` + p.preText : p.preText, value, p.postText + ",", p.spans[0], status, b);
1710
- else addMappedTextWithOffsets(p.name ? `${p.name}: ` + p.preText : p.preText, value, p.postText + ",", p.spans, p.offsets, p.lengths, status, b);
1831
+ const key = p.name ? `${propKey(p.name)}: ` : "";
1832
+ if (p.spans.length === 1) addMappedText(key + p.preText, value, p.postText + ",", p.spans[0], status, b);
1833
+ else addMappedTextWithOffsets(key + p.preText, value, p.postText + ",", p.spans, p.offsets, p.lengths, status, b);
1711
1834
  }
1712
1835
  b.append("});");
1713
1836
  if (runs.length) buildRun("setProps", runs.join("\n"), status, b);
@@ -1867,41 +1990,185 @@ function isForBodyLeafSafe(forBodyChildren) {
1867
1990
  }
1868
1991
  //#endregion
1869
1992
  //#region src/compile/utils/forLoopVarNames.ts
1993
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1870
1994
  /**
1871
1995
  * Extracts the declared loop variable names from a `@for` statement — the
1872
- * heuristic header parse shared by `buildForNode` (codegen) and the write
1873
- * scanners (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect
1874
- * nested loops that shadow an outer loop's variables).
1996
+ * header parse shared by `buildForNode` (codegen) and the write scanners
1997
+ * (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect nested
1998
+ * loops that shadow an outer loop's variables).
1875
1999
  *
1876
2000
  * Handles the C-style (`for (let i = 0; i < n; i++)`), for-of and for-in
1877
- * forms, with destructuring flattened to the bare names. TODO: Handle
1878
- * destructuring, quotes, comments etc (same as buildForNode's note — this is
1879
- * deliberately the same heuristic).
2001
+ * forms, including comments, strings, nested destructuring and defaults.
1880
2002
  */
1881
2003
  function forLoopVarNames(statement) {
1882
- const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1883
- const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
1884
- const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
1885
- const trimMatched = (value, start, end) => {
1886
- const startIndex = value.indexOf(start);
1887
- const endIndex = value.lastIndexOf(end);
1888
- if (startIndex === -1 || endIndex === -1) return value;
1889
- return value.slice(startIndex + 1, endIndex);
1890
- };
2004
+ const source = maskComments(statement);
2005
+ const forIndex = source.indexOf("for");
2006
+ if (forIndex === -1) return [];
2007
+ const open = source.indexOf("(", forIndex + 3);
2008
+ if (open === -1) return [];
2009
+ const close = findMatching(source, open, "(", ")");
2010
+ if (close === -1) return [];
2011
+ const header = source.slice(open + 1, close);
1891
2012
  const names = [];
1892
- const forLoopMatch = statement.match(forLoopRegex);
1893
- if (forLoopMatch) {
1894
- const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1895
- for (const match of forVarMatches) names.push(match[1]);
1896
- return names;
1897
- }
1898
- const forOfMatch = statement.match(forOfRegex);
1899
- if (forOfMatch) {
1900
- const match = forOfMatch[1];
1901
- if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) names.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1902
- else names.push(match);
2013
+ const firstSemi = findTopLevel(header, (char) => char === ";");
2014
+ if (firstSemi !== -1) {
2015
+ const declaration = stripDeclarationKeyword(header.slice(0, firstSemi));
2016
+ for (const declarator of splitTopLevel(declaration, ",")) {
2017
+ const eq = findTopLevel(declarator, (char) => char === "=");
2018
+ collectBindings(eq === -1 ? declarator : declarator.slice(0, eq), names);
2019
+ }
2020
+ return [...new Set(names)];
2021
+ }
2022
+ const keyword = findLoopKeyword(header);
2023
+ if (keyword !== -1) collectBindings(stripDeclarationKeyword(header.slice(0, keyword)), names);
2024
+ return [...new Set(names)];
2025
+ }
2026
+ /** Replaces comments with spaces, preserving length and string contents. */
2027
+ function maskComments(source) {
2028
+ let masked = "";
2029
+ for (let i = 0; i < source.length; i++) {
2030
+ const skipped = skipStringOrComment(source, i);
2031
+ if (skipped === -1) {
2032
+ masked += source[i];
2033
+ continue;
2034
+ }
2035
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) masked += source.substring(i, skipped).replaceAll(/[^\r\n]/g, " ");
2036
+ else masked += source.substring(i, skipped);
2037
+ i = skipped - 1;
1903
2038
  }
1904
- return names;
2039
+ return masked;
2040
+ }
2041
+ /** Finds the close delimiter matching the opener at `start`. */
2042
+ function findMatching(source, start, open, close) {
2043
+ let depth = 0;
2044
+ for (let i = start; i < source.length; i++) {
2045
+ const skipped = skipStringOrComment(source, i);
2046
+ if (skipped !== -1) {
2047
+ i = skipped - 1;
2048
+ continue;
2049
+ }
2050
+ const char = source[i];
2051
+ if (char === open) depth += 1;
2052
+ else if (char === close) {
2053
+ depth -= 1;
2054
+ if (depth === 0) return i;
2055
+ }
2056
+ }
2057
+ return -1;
2058
+ }
2059
+ /** Finds the first match of `predicate` outside nested delimiters and strings. */
2060
+ function findTopLevel(source, predicate) {
2061
+ let depth = 0;
2062
+ for (let i = 0; i < source.length; i++) {
2063
+ const skipped = skipStringOrComment(source, i);
2064
+ if (skipped !== -1) {
2065
+ i = skipped - 1;
2066
+ continue;
2067
+ }
2068
+ const char = source[i];
2069
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2070
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2071
+ else if (depth === 0 && predicate(char, i)) return i;
2072
+ }
2073
+ return -1;
2074
+ }
2075
+ /** Finds a top-level `of` or `in` keyword. */
2076
+ function findLoopKeyword(source) {
2077
+ let depth = 0;
2078
+ for (let i = 0; i < source.length; i++) {
2079
+ const skipped = skipStringOrComment(source, i);
2080
+ if (skipped !== -1) {
2081
+ i = skipped - 1;
2082
+ continue;
2083
+ }
2084
+ const char = source[i];
2085
+ if (char === "(" || char === "[" || char === "{") {
2086
+ depth += 1;
2087
+ continue;
2088
+ }
2089
+ if (char === ")" || char === "]" || char === "}") {
2090
+ depth -= 1;
2091
+ continue;
2092
+ }
2093
+ if (depth !== 0) continue;
2094
+ for (const keyword of ["of", "in"]) {
2095
+ if (!source.startsWith(keyword, i)) continue;
2096
+ const previous = source[i - 1];
2097
+ const next = source[i + keyword.length];
2098
+ if ((previous === void 0 || !isIdentifierChar(previous)) && (next === void 0 || !isIdentifierChar(next))) return i;
2099
+ }
2100
+ }
2101
+ return -1;
2102
+ }
2103
+ /** Splits at a separator that isn't inside strings or nested delimiters. */
2104
+ function splitTopLevel(source, separator) {
2105
+ const parts = [];
2106
+ let start = 0;
2107
+ let depth = 0;
2108
+ for (let i = 0; i < source.length; i++) {
2109
+ const skipped = skipStringOrComment(source, i);
2110
+ if (skipped !== -1) {
2111
+ i = skipped - 1;
2112
+ continue;
2113
+ }
2114
+ const char = source[i];
2115
+ if (char === "(" || char === "[" || char === "{") depth += 1;
2116
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
2117
+ else if (depth === 0 && char === separator) {
2118
+ parts.push(source.slice(start, i));
2119
+ start = i + 1;
2120
+ }
2121
+ }
2122
+ parts.push(source.slice(start));
2123
+ return parts;
2124
+ }
2125
+ function stripDeclarationKeyword(declaration) {
2126
+ return declaration.trim().replace(/^(?:let|var|const)\b\s*/, "");
2127
+ }
2128
+ function collectBindings(pattern, names) {
2129
+ pattern = pattern.trim();
2130
+ if (!pattern) return;
2131
+ const open = pattern[0];
2132
+ if (open === "{") {
2133
+ const close = findMatching(pattern, 0, "{", "}");
2134
+ if (close === -1) return;
2135
+ for (const property of splitTopLevel(pattern.slice(1, close), ",")) collectObjectBinding(property.trim(), names);
2136
+ return;
2137
+ }
2138
+ if (open === "[") {
2139
+ const close = findMatching(pattern, 0, "[", "]");
2140
+ if (close === -1) return;
2141
+ for (let element of splitTopLevel(pattern.slice(1, close), ",")) {
2142
+ element = element.trim();
2143
+ if (!element) continue;
2144
+ if (element.startsWith("...")) element = element.slice(3).trim();
2145
+ const eq = findTopLevel(element, (char) => char === "=");
2146
+ collectBindings(eq === -1 ? element : element.slice(0, eq), names);
2147
+ }
2148
+ return;
2149
+ }
2150
+ const eq = findTopLevel(pattern, (char) => char === "=");
2151
+ const name = (eq === -1 ? pattern : pattern.slice(0, eq)).trim();
2152
+ if (IDENTIFIER.test(name)) names.push(name);
2153
+ }
2154
+ function collectObjectBinding(property, names) {
2155
+ property = property.trim();
2156
+ if (!property) return;
2157
+ if (property.startsWith("...")) {
2158
+ collectBindings(property.slice(3).trim(), names);
2159
+ return;
2160
+ }
2161
+ const colon = findTopLevel(property, (char) => char === ":");
2162
+ const eq = findTopLevel(property, (char) => char === "=");
2163
+ if (colon !== -1 && (eq === -1 || colon < eq)) {
2164
+ collectBindings(property.slice(colon + 1).trim(), names);
2165
+ return;
2166
+ }
2167
+ const name = (eq === -1 ? property : property.slice(0, eq)).trim();
2168
+ if (IDENTIFIER.test(name)) names.push(name);
2169
+ }
2170
+ function isIdentifierChar(char) {
2171
+ return /[A-Za-z0-9_$]/.test(char);
1905
2172
  }
1906
2173
  //#endregion
1907
2174
  //#region src/compile/utils/forVarsWrittenIn.ts
@@ -2172,8 +2439,10 @@ function buildForNode(node, status, b) {
2172
2439
  appendForVarBindings(b, status, `${node.statement}\n${keyStatement}`);
2173
2440
  addMappedText("", `${node.statement}`, " {", node.span, status, b);
2174
2441
  const dataExpr = singleVar ? forVarNames[0] : `{ ${forVarNames.join(", ")} }`;
2175
- if (key !== void 0) addMappedText(`${listItemsName}.push({ data: ${dataExpr}, key: `, `${keyStatement || "undefined"}`, " });", key.span, status, b);
2176
- else b.append(`${listItemsName}.push({ data: ${dataExpr} });`);
2442
+ if (key !== void 0) {
2443
+ status.imports.add("$peek");
2444
+ addMappedText(`${listItemsName}.push({ data: ${dataExpr}, key: $peek(() => `, `${keyStatement || "undefined"}`, ") });", key.span, status, b);
2445
+ } else b.append(`${listItemsName}.push({ data: ${dataExpr} });`);
2177
2446
  b.append(`}`);
2178
2447
  b.append(`return ${listItemsName};`);
2179
2448
  b.append(`},
@@ -2563,6 +2832,25 @@ function buildControlNode(node, status, b) {
2563
2832
  }
2564
2833
  }
2565
2834
  //#endregion
2835
+ //#region src/compile/utils/rawTextTags.ts
2836
+ /**
2837
+ * HTML raw-text elements. Their contents aren't parsed as markup (or as a
2838
+ * torpor template): braces, `@` and `<` are all literal, and the browser
2839
+ * doesn't decode character references inside them either. Rendered `<script>`
2840
+ * / `<style>` content is therefore emitted exactly as written.
2841
+ */
2842
+ const RAW_TEXT_TAGS = /* @__PURE__ */ new Set([
2843
+ "script",
2844
+ "style",
2845
+ "xmp",
2846
+ "iframe",
2847
+ "noembed",
2848
+ "noframes"
2849
+ ]);
2850
+ function isRawTextTag(tagName) {
2851
+ return RAW_TEXT_TAGS.has(tagName.toLowerCase());
2852
+ }
2853
+ //#endregion
2566
2854
  //#region src/compile/utils/trimEnd.ts
2567
2855
  /**
2568
2856
  * Trims a char from the end of the supplied text
@@ -2632,7 +2920,7 @@ function buildElementNode(node, status, b, parentName) {
2632
2920
  buildElementAttributes$1(node, varName, status, b);
2633
2921
  }
2634
2922
  const oldPreserveWhitespace = status.preserveWhitespace;
2635
- status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre";
2923
+ status.preserveWhitespace = node.tagName === "code" || node.tagName === "pre" || isRawTextTag(node.tagName);
2636
2924
  for (let child of node.children) buildNode(child, status, b, parentName, "null");
2637
2925
  status.preserveWhitespace = oldPreserveWhitespace;
2638
2926
  if (svgElement) status.ns = oldns;
@@ -2670,12 +2958,28 @@ function buildTitleNode(node, status, b) {
2670
2958
  else content = `\`${content.replaceAll("{", "${t_fmt(").replaceAll("}", ")}")}\``;
2671
2959
  } else content = `"${content}"`;
2672
2960
  status.imports.add("$run");
2673
- b.append("$run(() => {");
2674
- b.append(`
2961
+ if (status.options.dev === true) {
2962
+ status.imports.add("t_dev_title");
2963
+ b.append(`{
2964
+ const t_title_dev = t_dev_title();
2965
+ $run(() => {
2966
+ const t_old_title = document.title;
2967
+ document.title = ${content};
2968
+ t_title_dev.set(document.title);
2969
+ return () => {
2970
+ t_title_dev.unset();
2971
+ document.title = t_old_title;
2972
+ };
2973
+ }, "runTitle");
2974
+ }`);
2975
+ } else {
2976
+ b.append("$run(() => {");
2977
+ b.append(`
2675
2978
  const t_old_title = document.title;
2676
2979
  document.title = ${content};
2677
2980
  return () => document.title = t_old_title;
2678
- }${status.options.dev === true ? `, "runTitle"` : ""});`);
2981
+ });`);
2982
+ }
2679
2983
  }
2680
2984
  function buildHeadNode(node, status, b) {
2681
2985
  status.imports.add("$run");
@@ -2776,12 +3080,14 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2776
3080
  let eventName = bindEventName(node, name);
2777
3081
  let defaultValue = "\"\"";
2778
3082
  let inputValue = "e.target.value";
3083
+ let setJoin = "||";
2779
3084
  if (node.tagName === "input") {
2780
3085
  let typeAttribute = node.attributes.find((a) => a.name === "type");
2781
3086
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
2782
3087
  case "number":
2783
- defaultValue = "0";
2784
- inputValue = "Number(e.target.value)";
3088
+ defaultValue = "\"\"";
3089
+ inputValue = "e.target.value === \"\" ? undefined : Number(e.target.value)";
3090
+ setJoin = "??";
2785
3091
  break;
2786
3092
  case "checkbox":
2787
3093
  defaultValue = "false";
@@ -2794,7 +3100,7 @@ function buildBindAttribute(node, varName, name, value, status, b, combined) {
2794
3100
  return;
2795
3101
  }
2796
3102
  }
2797
- let set = `${value} || ${defaultValue}`;
3103
+ let set = `${value} ${setJoin} ${defaultValue}`;
2798
3104
  const propName = name.substring(1);
2799
3105
  buildRun("setBinding", `${propName === "value" ? `${varName}.${propName} = String(${set})` : `${varName}.${propName} = ${set}`};`, status, b);
2800
3106
  emitBindEvent(varName, eventName, `(e) => ${value} = ${inputValue}`, `${value} = ${inputValue};`, combined, status, b);
@@ -2938,7 +3244,7 @@ function buildSlotNode(node, status, b) {
2938
3244
  b.append(`const ${propsName} = $watch({`);
2939
3245
  for (let p of props) {
2940
3246
  let value = p.value;
2941
- addMappedText(`${p.name}: `, value, ",", p.span, status, b);
3247
+ addMappedText(`${propKey(p.name)}: `, value, ",", p.span, status, b);
2942
3248
  }
2943
3249
  b.append("});");
2944
3250
  if (runs.length) buildRun("setProps", runs.join("\n"), status, b);
@@ -2989,6 +3295,7 @@ function buildSpecialNode(node, status, b, parentName, root = false) {
2989
3295
  //#endregion
2990
3296
  //#region src/compile/build/client/buildTextNode.ts
2991
3297
  function buildTextNode(node, status) {
3298
+ if (node.raw) return;
2992
3299
  let fragment = status.fragmentStack.at(-1)?.fragment;
2993
3300
  if (!fragment) return;
2994
3301
  let content = node.content || "";
@@ -3133,7 +3440,8 @@ const importsMap$1 = {
3133
3440
  SlotRender: "import { type SlotRender } from \"${folder}\";",
3134
3441
  devContext: "import { devContext } from \"${folder}/dev\";",
3135
3442
  t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
3136
- t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
3443
+ t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";",
3444
+ t_dev_title: "import { t_dev_title } from \"${folder}/dev\";"
3137
3445
  };
3138
3446
  function buildCode(template, map, options, errors = [], warnings = []) {
3139
3447
  let b = new Builder(options?.mapped);
@@ -3271,10 +3579,10 @@ function buildStyles(style, styleHash) {
3271
3579
  for (let block of style.children) buildStyleNode(block, b, styleHash);
3272
3580
  return b.toString();
3273
3581
  }
3274
- function buildStyleNode(node, b, styleHash) {
3582
+ function buildStyleNode(node, b, styleHash, scoped = true) {
3275
3583
  switch (node.type) {
3276
3584
  case "block":
3277
- buildBlockNode(node, b, styleHash);
3585
+ buildBlockNode(node, b, styleHash, scoped);
3278
3586
  break;
3279
3587
  case "attribute":
3280
3588
  buildAttributeNode(node, b);
@@ -3283,55 +3591,164 @@ function buildStyleNode(node, b, styleHash) {
3283
3591
  default: throw new Error(`Invalid style node type: ${node.type}`);
3284
3592
  }
3285
3593
  }
3286
- function buildBlockNode(block, b, styleHash) {
3594
+ function buildBlockNode(block, b, styleHash, scoped) {
3595
+ const isKeyframes = block.selector.startsWith("@keyframes") || block.selector.startsWith("@-webkit-keyframes");
3287
3596
  if (block.selector.startsWith("@")) b.append(`${block.selector} {`);
3288
3597
  else {
3289
- block.selector = block.selector.replaceAll(/\s+/g, " ");
3290
- let selectors = [];
3291
- let global = false;
3292
- let start = 0;
3293
- for (let i = 0; i <= block.selector.length; i++) if (block.selector.substring(i).startsWith(":global(")) {
3294
- i += 7;
3295
- start = i + 1;
3296
- global = true;
3297
- } else if (global && block.selector[i] === ")") {
3298
- addSelector(selectors, block.selector, styleHash, start, i, global);
3299
- start = i + 1;
3300
- global = false;
3301
- } else if ("*,>+~".includes(block.selector[i])) {
3302
- addSelector(selectors, block.selector, styleHash, start, i, global);
3303
- selectors.push(block.selector[i]);
3304
- start = i + 1;
3305
- } else if (i === block.selector.length) addSelector(selectors, block.selector, styleHash, start, i, global);
3306
- else if (block.selector[i] === " ") {
3307
- addSelector(selectors, block.selector, styleHash, start, i, global);
3308
- start = i + 1;
3309
- }
3310
- b.append(`${selectors.join(" ").replaceAll(" ,", ",")} {`);
3598
+ block.selector = block.selector.replaceAll(/\s+/g, " ").trim();
3599
+ b.append(`${scoped ? scopeSelector(block.selector, styleHash) : block.selector} {`);
3311
3600
  }
3312
- for (let child of block.children) buildStyleNode(child, b, styleHash);
3601
+ for (let child of block.children) buildStyleNode(child, b, styleHash, scoped && !isKeyframes);
3313
3602
  b.append(`}`);
3314
3603
  }
3315
- function addSelector(selectors, selector, styleHash, start, end, global) {
3316
- if (end > start) {
3317
- let s = selector.substring(start, end);
3318
- if (!global) {
3319
- let pre = s;
3320
- let post = "";
3321
- let colonPosition = s.indexOf(":");
3322
- if (colonPosition !== -1) {
3323
- pre = s.substring(0, colonPosition);
3324
- post = s.substring(colonPosition);
3604
+ /**
3605
+ * Appends the component scope class to each compound selector. Both brackets
3606
+ * (`[data-x="a b"]`) and parentheses (`:is(.a, .b)`, `:global(...)`) are
3607
+ * treated as opaque, so spaces/commas inside them aren't mistaken for
3608
+ * combinators. `:global(...)` wrappers are removed without adding the scope.
3609
+ */
3610
+ function scopeSelector(selector, styleHash) {
3611
+ let result = "";
3612
+ let compound = "";
3613
+ let bracketDepth = 0;
3614
+ let parenDepth = 0;
3615
+ let quote = null;
3616
+ const flush = () => {
3617
+ if (!compound) return;
3618
+ result += scopeCompound(compound, styleHash);
3619
+ compound = "";
3620
+ };
3621
+ for (let i = 0; i < selector.length; i++) {
3622
+ const char = selector[i];
3623
+ if (quote !== null) {
3624
+ compound += char;
3625
+ if (char === "\\") compound += selector[++i] ?? "";
3626
+ else if (char === quote) quote = null;
3627
+ continue;
3628
+ }
3629
+ if (char === "\\") compound += char + (selector[++i] ?? "");
3630
+ else if (char === "\"" || char === "'") {
3631
+ quote = char;
3632
+ compound += char;
3633
+ } else if (char === "[") {
3634
+ bracketDepth += 1;
3635
+ compound += char;
3636
+ } else if (char === "]") {
3637
+ bracketDepth -= 1;
3638
+ compound += char;
3639
+ } else if (char === "(") {
3640
+ parenDepth += 1;
3641
+ compound += char;
3642
+ } else if (char === ")") {
3643
+ parenDepth -= 1;
3644
+ compound += char;
3645
+ } else if (bracketDepth === 0 && parenDepth === 0 && (char === " " || char === "," || char === ">" || char === "+" || char === "~")) {
3646
+ flush();
3647
+ result += char;
3648
+ } else compound += char;
3649
+ }
3650
+ flush();
3651
+ return result.trim();
3652
+ }
3653
+ function scopeCompound(compound, styleHash) {
3654
+ if (!compound.includes(":global(")) return addScope(compound, styleHash);
3655
+ const { text, onlyGlobal } = stripGlobal(compound);
3656
+ return onlyGlobal ? text : addScope(text, styleHash);
3657
+ }
3658
+ /** Removes `:global(...)` wrappers, reporting whether anything local remained. */
3659
+ function stripGlobal(compound) {
3660
+ let text = "";
3661
+ let hadLocal = false;
3662
+ let i = 0;
3663
+ while (i < compound.length) {
3664
+ if (compound.startsWith(":global(", i)) {
3665
+ const close = findClosingParen(compound, i + 7);
3666
+ if (close === -1) {
3667
+ text += compound.substring(i);
3668
+ break;
3325
3669
  }
3326
- s = `${pre}.torp-${styleHash}${post}`;
3670
+ text += compound.substring(i + 8, close);
3671
+ i = close + 1;
3672
+ continue;
3673
+ }
3674
+ const char = compound[i];
3675
+ if (char.trim()) hadLocal = true;
3676
+ text += char;
3677
+ i += 1;
3678
+ }
3679
+ return {
3680
+ text,
3681
+ onlyGlobal: !hadLocal
3682
+ };
3683
+ }
3684
+ function addScope(compound, styleHash) {
3685
+ const colon = findFirstPseudo(compound);
3686
+ const scope = `.torp-${styleHash}`;
3687
+ return colon === -1 ? `${compound}${scope}` : `${compound.substring(0, colon)}${scope}${compound.substring(colon)}`;
3688
+ }
3689
+ /** Finds the first top-level `:` (pseudo-class/element), skipping brackets/strings. */
3690
+ function findFirstPseudo(compound) {
3691
+ let bracketDepth = 0;
3692
+ let parenDepth = 0;
3693
+ let quote = null;
3694
+ for (let i = 0; i < compound.length; i++) {
3695
+ const char = compound[i];
3696
+ if (quote !== null) {
3697
+ if (char === "\\") i += 1;
3698
+ else if (char === quote) quote = null;
3699
+ continue;
3700
+ }
3701
+ if (char === "\\") i += 1;
3702
+ else if (char === "\"" || char === "'") quote = char;
3703
+ else if (char === "[") bracketDepth += 1;
3704
+ else if (char === "]") bracketDepth -= 1;
3705
+ else if (char === "(") parenDepth += 1;
3706
+ else if (char === ")") parenDepth -= 1;
3707
+ else if (bracketDepth === 0 && parenDepth === 0 && char === ":") return i;
3708
+ }
3709
+ return -1;
3710
+ }
3711
+ function findClosingParen(source, open) {
3712
+ let depth = 0;
3713
+ let bracketDepth = 0;
3714
+ let quote = null;
3715
+ for (let i = open; i < source.length; i++) {
3716
+ const char = source[i];
3717
+ if (quote !== null) {
3718
+ if (char === "\\") i += 1;
3719
+ else if (char === quote) quote = null;
3720
+ continue;
3721
+ }
3722
+ if (char === "\\") i += 1;
3723
+ else if (char === "\"" || char === "'") quote = char;
3724
+ else if (char === "[") bracketDepth += 1;
3725
+ else if (char === "]") bracketDepth -= 1;
3726
+ else if (bracketDepth === 0 && char === "(") depth += 1;
3727
+ else if (bracketDepth === 0 && char === ")") {
3728
+ depth -= 1;
3729
+ if (depth === 0) return i;
3327
3730
  }
3328
- selectors.push(s);
3329
3731
  }
3732
+ return -1;
3330
3733
  }
3331
3734
  function buildAttributeNode(attribute, b) {
3332
3735
  b.append(`${attribute.name}: ${attribute.value};`);
3333
3736
  }
3334
3737
  //#endregion
3738
+ //#region src/compile/utils/containsAwaitGroup.ts
3739
+ /**
3740
+ * Whether a markup tree contains an `@await` boundary, so the component's
3741
+ * render must be wrapped in a flush.
3742
+ */
3743
+ function containsAwaitGroup(node) {
3744
+ if (node === void 0 || node === null) return false;
3745
+ if (isControlNode(node) && node.operation === "@await group") return true;
3746
+ if (node.type !== "text" && node.type !== "comment") {
3747
+ for (let child of node.children) if (containsAwaitGroup(child)) return true;
3748
+ }
3749
+ return false;
3750
+ }
3751
+ //#endregion
3335
3752
  //#region src/compile/build/server/flushOutput.ts
3336
3753
  /**
3337
3754
  * Appends any pending output to the generated code, targeting the body
@@ -3374,7 +3791,7 @@ function buildServerComponentNode(node, status, b) {
3374
3791
  });
3375
3792
  }
3376
3793
  b.append(`const ${propsName} = {`);
3377
- for (let p of props) b.append(p.name ? `${p.name}: ${p.value},` : `${p.value},`);
3794
+ for (let p of props) b.append(p.name ? `${propKey(p.name)}: ${p.value},` : `${p.value},`);
3378
3795
  b.append("};");
3379
3796
  }
3380
3797
  const componentHasSlots = node.children.length;
@@ -3384,7 +3801,7 @@ function buildServerComponentNode(node, status, b) {
3384
3801
  for (let slot of node.children) if (isSpecialNode(slot) && (slot.tagName === "fill" || slot.tagName === "filldef")) {
3385
3802
  const nameAttribute = slot.attributes.find((a) => a.name === "name");
3386
3803
  const slotName = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
3387
- const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3804
+ const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) || containsAwaitGroup(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3388
3805
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = async (\n${slotParams.join(",\n")}\n) => {`);
3389
3806
  b.append(`let t_body = "";`);
3390
3807
  for (let child of slot.children) buildServerNode(child, status, b);
@@ -3440,7 +3857,7 @@ function buildServerAwaitNode(node, status, b) {
3440
3857
  for (let branch of node.children) if (isControlNode(branch) && branch.operation === "@with") for (let child of branch.children) buildServerNode(child, status, b);
3441
3858
  flushOutput(status, b);
3442
3859
  b.append(`return { body: t_body, head: t_head };`);
3443
- b.append(`});`);
3860
+ b.append(`}, $context);`);
3444
3861
  b.append(`${status.inHead ? "t_head" : "t_body"} += ${resultName}.body;`);
3445
3862
  b.append(`t_head += ${resultName}.head;`);
3446
3863
  }
@@ -3622,7 +4039,7 @@ function buildServerElementNode(node, status, b) {
3622
4039
  status.output += `<${tagName}${attributes}>`;
3623
4040
  if (!voidTags.includes(tagName)) {
3624
4041
  const oldPreserveWhitespace = status.preserveWhitespace;
3625
- status.preserveWhitespace = ["pre", "code"].includes(tagName);
4042
+ status.preserveWhitespace = ["pre", "code"].includes(tagName) || isRawTextTag(tagName);
3626
4043
  if (!tagName.startsWith("@")) status.elementStack.push(tagName);
3627
4044
  for (let child of node.children) buildServerNode(child, status, b);
3628
4045
  if (!tagName.startsWith("@")) status.elementStack.pop();
@@ -3640,16 +4057,13 @@ function buildElementAttributes(node, status) {
3640
4057
  let typeAttribute = node.attributes.find((a) => a.name === "type");
3641
4058
  if (typeAttribute && typeAttribute.value) switch (trimQuotes(typeAttribute.value)) {
3642
4059
  case "number":
3643
- defaultValue = "0";
4060
+ defaultValue = "\"\"";
3644
4061
  break;
3645
4062
  case "checkbox": defaultValue = "false";
3646
4063
  }
3647
- if (!defaultValue) {
3648
- status.imports.add("t_attr");
3649
- value = `t_attr(${value})`;
3650
- defaultValue = "\"\"";
3651
- }
3652
- let valueOrDefault = `(${value}) || ${defaultValue}`;
4064
+ if (!defaultValue) defaultValue = "\"\"";
4065
+ status.imports.add("t_attr");
4066
+ let valueOrDefault = `t_attr(${value}) || ${defaultValue}`;
3653
4067
  const propName = name.substring(1);
3654
4068
  attributes.push(`${propName}="\${${valueOrDefault}}"`);
3655
4069
  } else if (name === "class") {
@@ -3672,9 +4086,9 @@ function buildElementAttributes(node, status) {
3672
4086
  attributes.push(`${name}="${trimQuotes(value).replaceAll("{", "${t_attr(").replaceAll("}", ")}")}"`);
3673
4087
  } else if (name === "class" && node.scopeStyles && !status.inHead) {
3674
4088
  value = value ? `"${trimQuotes(value)} torp-${status.styleHash}"` : `"torp-${status.styleHash}"`;
3675
- attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4089
+ attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3676
4090
  needsClass = false;
3677
- } else if (value != null) attributes.push(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`);
4091
+ } else if (value != null) attributes.push(escapeTemplateText(`${name}="${trimQuotes(value).replaceAll("\"", "&quot;")}"`));
3678
4092
  else attributes.push(`${name}`);
3679
4093
  if (needsClass) attributes.push(`class="torp-${status.styleHash}"`);
3680
4094
  return attributes.join(" ");
@@ -3737,15 +4151,21 @@ function buildServerSpecialNode(node, status, b) {
3737
4151
  //#region src/compile/build/server/buildServerTextNode.ts
3738
4152
  function buildServerTextNode(node, status) {
3739
4153
  let content = node.content || "";
4154
+ if (node.raw) {
4155
+ status.output += escapeRawText(content);
4156
+ return;
4157
+ }
3740
4158
  if (!status.preserveWhitespace) content = content.replaceAll(/\s+/g, " ");
4159
+ const parentTag = status.elementStack[status.elementStack.length - 1];
4160
+ const formatter = parentTag !== void 0 && isRawTextTag(parentTag) ? "t_fmt_raw" : "t_fmt";
3741
4161
  let level = 0;
3742
4162
  for (let i = 0; i < content.length; i++) {
3743
4163
  const char = content[i];
3744
4164
  if (char === "{") {
3745
4165
  level++;
3746
4166
  if (level === 1) {
3747
- status.imports.add("t_fmt");
3748
- status.output += "${t_fmt(";
4167
+ status.imports.add(formatter);
4168
+ status.output += "${" + formatter + "(";
3749
4169
  continue;
3750
4170
  }
3751
4171
  } else if (char === "}") {
@@ -3808,8 +4228,10 @@ const importsMap = {
3808
4228
  $peek: "import { $peek } from \"${folder}\";",
3809
4229
  $batch: "import { $batch } from \"${folder}\";",
3810
4230
  t_server_flush: "import { t_server_flush } from \"${folder}\";",
4231
+ t_render_context: "import { t_render_context } from \"${folder}\";",
3811
4232
  t_await_server: "import { t_await_server } from \"${folder}\";",
3812
4233
  t_fmt: "import { t_fmt } from \"${folder}\";",
4234
+ t_fmt_raw: "import { t_fmt_raw } from \"${folder}\";",
3813
4235
  t_attr: "import { t_attr } from \"${folder}\";",
3814
4236
  t_attr_if: "import { t_attr_if } from \"${folder}\";",
3815
4237
  t_class: "import { t_class } from \"${folder}\";",
@@ -3857,121 +4279,118 @@ function buildServerTemplate(template, imports, b, options) {
3857
4279
  for (let [i, chunk] of template.script.entries()) if (chunk.script === "/* @params */" && i > 0) asyncChunks.add(i - 1);
3858
4280
  let currentIndex = 0;
3859
4281
  let current = template.components[0];
3860
- for (let [chunkIndex, chunk] of template.script.entries()) if (chunk.script === "/* @params */") {
3861
- let params = [
3862
- current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
3863
- `${current.contextProps?.length || current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error) ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
3864
- `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
3865
- ];
3866
- b.append(params.join(",\n") + ",");
3867
- } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
3868
- else if (chunk.script === "/* @start */") {
3869
- if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
3870
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) {
3871
- imports.add("t_server_flush");
3872
- b.append(`return t_server_flush(async () => {`);
3873
- }
3874
- b.append(`let t_body = "";`);
3875
- b.append(`let t_head = "";`);
3876
- } else if (chunk.script === "/* @render */") {
3877
- if (current.markup) {
3878
- const status = {
3879
- imports,
3880
- output: "",
3881
- styleHash: current.style?.hash || "",
3882
- varNames: {},
3883
- preserveWhitespace: false,
3884
- awaitCount: 0,
3885
- elementStack: [],
3886
- options
3887
- };
3888
- b.append("");
3889
- b.append("/* User interface */");
3890
- if (current.error) {
3891
- b.append(`const t_try_body = t_body;`);
3892
- b.append(`const t_try_head = t_head;`);
3893
- b.append("try {");
4282
+ for (let [chunkIndex, chunk] of template.script.entries()) {
4283
+ const hasAwait = current !== void 0 && (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head));
4284
+ const rendersComponent = current !== void 0 && (current.markup && markupRendersComponent(current.markup) || current.error && markupRendersComponent(current.error));
4285
+ if (chunk.script === "/* @params */") {
4286
+ let params = [
4287
+ current.params ?? `${current.props?.length ? "$props: Record<PropertyKey, any>" : "_$props?: Record<PropertyKey, any>"}`,
4288
+ `${current.contextProps?.length || rendersComponent || hasAwait ? "$context" : "_$context"}?: Record<PropertyKey, any>`,
4289
+ `${current.slotProps?.length ? "$slots" : "_$slots"}?: Record<string, ServerSlotRender>`
4290
+ ];
4291
+ b.append(params.join(",\n") + ",");
4292
+ } else if (chunk.script === ") /* @return_type */ {") b.append("): Promise<{ body: string; head: string }> {");
4293
+ else if (chunk.script === "/* @start */") {
4294
+ if (rendersComponent || hasAwait) {
4295
+ imports.add("t_render_context");
4296
+ b.append(`$context = t_render_context($context);`);
3894
4297
  }
3895
- buildServerNode(current.markup, status, b);
3896
- if (status.output) {
3897
- b.append(`t_body += \`${status.output}\`;`);
3898
- status.output = "";
4298
+ if (current.contextProps?.length) b.append(`$context = Object.assign({}, $context);`);
4299
+ if (hasAwait) {
4300
+ imports.add("t_server_flush");
4301
+ b.append(`return t_server_flush(async () => {`);
3899
4302
  }
3900
- }
3901
- } else if (chunk.script === "/* @error */") {
3902
- if (current.markup && current.error) {
3903
- const status = {
3904
- imports,
3905
- output: "",
3906
- styleHash: current.style?.hash || "",
3907
- varNames: {},
3908
- preserveWhitespace: false,
3909
- awaitCount: 0,
3910
- elementStack: [],
3911
- options
3912
- };
3913
- b.append(`} catch (${current.errorVar}) {`);
3914
- b.append("t_body = t_try_body;");
3915
- b.append("t_head = t_try_head;");
3916
- b.append("/* User interface error */");
3917
- buildServerNode(current.error, status, b);
3918
- if (status.output) {
3919
- b.append(`t_body += \`${status.output}\`;`);
3920
- status.output = "";
4303
+ b.append(`let t_body = "";`);
4304
+ b.append(`let t_head = "";`);
4305
+ } else if (chunk.script === "/* @render */") {
4306
+ if (current.markup) {
4307
+ const status = {
4308
+ imports,
4309
+ output: "",
4310
+ styleHash: current.style?.hash || "",
4311
+ varNames: {},
4312
+ preserveWhitespace: false,
4313
+ awaitCount: 0,
4314
+ elementStack: [],
4315
+ options
4316
+ };
4317
+ b.append("");
4318
+ b.append("/* User interface */");
4319
+ if (current.error) {
4320
+ b.append(`const t_try_body = t_body;`);
4321
+ b.append(`const t_try_head = t_head;`);
4322
+ b.append("try {");
4323
+ }
4324
+ buildServerNode(current.markup, status, b);
4325
+ if (status.output) {
4326
+ b.append(`t_body += \`${status.output}\`;`);
4327
+ status.output = "";
4328
+ }
3921
4329
  }
3922
- b.append("}");
3923
- }
3924
- } else if (chunk.script === "/* @head */") {
3925
- if (current.head) {
3926
- const status = {
3927
- imports,
3928
- output: "",
3929
- styleHash: current.style?.hash || "",
3930
- varNames: {},
3931
- preserveWhitespace: false,
3932
- inHead: true,
3933
- awaitCount: 0,
3934
- elementStack: [],
3935
- options
3936
- };
3937
- b.append("");
3938
- b.append("/* Head */");
3939
- buildServerNode(current.head, status, b);
3940
- flushOutput(status, b);
3941
- }
3942
- } else if (chunk.script === "/* @style */") {
3943
- if (current.style) {
3944
- b.append("");
3945
- b.append("/* Style */");
3946
- const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
3947
- b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
3948
- }
3949
- } else if (chunk.script === "/* @end */") {
3950
- b.append(`return { body: t_body, head: t_head };`);
3951
- if (containsAwaitGroup(current.markup) || containsAwaitGroup(current.error) || containsAwaitGroup(current.head)) b.append(`});`);
3952
- currentIndex += 1;
3953
- current = template.components[currentIndex];
3954
- } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
3955
- else b.append(chunk.script);
3956
- }
3957
- /**
3958
- * Whether a markup tree contains an `@await` boundary, so the component's
3959
- * render must be wrapped in a flush.
3960
- */
3961
- function containsAwaitGroup(node) {
3962
- if (node === void 0 || node === null) return false;
3963
- if (isControlNode(node) && node.operation === "@await group") return true;
3964
- if (node.type !== "text" && node.type !== "comment") {
3965
- for (let child of node.children) if (containsAwaitGroup(child)) return true;
4330
+ } else if (chunk.script === "/* @error */") {
4331
+ if (current.markup && current.error) {
4332
+ const status = {
4333
+ imports,
4334
+ output: "",
4335
+ styleHash: current.style?.hash || "",
4336
+ varNames: {},
4337
+ preserveWhitespace: false,
4338
+ awaitCount: 0,
4339
+ elementStack: [],
4340
+ options
4341
+ };
4342
+ b.append(`} catch (${current.errorVar}) {`);
4343
+ b.append("t_body = t_try_body;");
4344
+ b.append("t_head = t_try_head;");
4345
+ b.append("/* User interface error */");
4346
+ buildServerNode(current.error, status, b);
4347
+ if (status.output) {
4348
+ b.append(`t_body += \`${status.output}\`;`);
4349
+ status.output = "";
4350
+ }
4351
+ b.append("}");
4352
+ }
4353
+ } else if (chunk.script === "/* @head */") {
4354
+ if (current.head) {
4355
+ const status = {
4356
+ imports,
4357
+ output: "",
4358
+ styleHash: current.style?.hash || "",
4359
+ varNames: {},
4360
+ preserveWhitespace: false,
4361
+ inHead: true,
4362
+ awaitCount: 0,
4363
+ elementStack: [],
4364
+ options
4365
+ };
4366
+ b.append("");
4367
+ b.append("/* Head */");
4368
+ buildServerNode(current.head, status, b);
4369
+ flushOutput(status, b);
4370
+ }
4371
+ } else if (chunk.script === "/* @style */") {
4372
+ if (current.style) {
4373
+ b.append("");
4374
+ b.append("/* Style */");
4375
+ const styles = buildStyles(current.style, current.style.hash).replaceAll("\"", "\\\"").replaceAll(/\s+/g, " ");
4376
+ b.append(`t_head += "<style id='${current.style.hash}'>${styles}</style>";\n`);
4377
+ }
4378
+ } else if (chunk.script === "/* @end */") {
4379
+ b.append(`return { body: t_body, head: t_head };`);
4380
+ if (hasAwait) b.append(`});`);
4381
+ currentIndex += 1;
4382
+ current = template.components[currentIndex];
4383
+ } else if (asyncChunks.has(chunkIndex)) b.append(chunk.script.replace(/(?<!async\s)function\s+([A-Za-z_$][\w$]*)((?:<(?:[^<>]|<[^<>]*>)*>)?)\s*\($/, "async function $1$2("));
4384
+ else b.append(chunk.script);
3966
4385
  }
3967
- return false;
3968
4386
  }
3969
4387
  //#endregion
3970
4388
  //#region src/compile/utils/trimWhitespace.ts
3971
4389
  /**
3972
4390
  * Tag names whose contents should keep all whitespace untouched, matching
3973
4391
  * native HTML rendering of `pre`/`textarea` and the existing build-time
3974
- * `preserveWhitespace` behavior for `code`.
4392
+ * `preserveWhitespace` behavior for `code`. Raw-text elements (including
4393
+ * inline `<script>` / `<style>`) keep their contents exactly as written.
3975
4394
  */
3976
4395
  const PRESERVE_TAGS = /* @__PURE__ */ new Set([
3977
4396
  "pre",
@@ -4024,7 +4443,7 @@ function trimChildren(children, preserveAll, parentTag) {
4024
4443
  const grandChildren = getChildren(child);
4025
4444
  if (grandChildren) {
4026
4445
  const childTag = getTagName(child);
4027
- trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? ""), childTag);
4446
+ trimChildren(grandChildren, preserveAll || PRESERVE_TAGS.has(childTag ?? "") || isRawTextTag(childTag ?? ""), childTag);
4028
4447
  }
4029
4448
  }
4030
4449
  if (preserveAll) return;
@@ -4963,7 +5382,7 @@ function serializeElement(node, context) {
4963
5382
  context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4964
5383
  return;
4965
5384
  }
4966
- const childContext = node.tagName === "pre" || node.tagName === "code" ? {
5385
+ const childContext = node.tagName === "pre" || node.tagName === "code" || isRawTextTag(node.tagName) ? {
4967
5386
  ...context,
4968
5387
  preserveWhitespace: true
4969
5388
  } : context;
@@ -5293,28 +5712,566 @@ function isSpaceNode(node) {
5293
5712
  return isTextNode(node) && isSpace(node.content);
5294
5713
  }
5295
5714
  //#endregion
5296
- //#region src/compile/parse/utils/accept.ts
5715
+ //#region src/compile/utils/nativeTags.ts
5297
5716
  /**
5298
- * Checks whether the source at the current parse position matches the supplied
5299
- * string
5300
- *
5301
- * @param value The string to check
5302
- * @param status The parse status
5303
- * @param advance (Optional) If true, advances the parse position past the
5304
- * checked string (defaults to true)
5305
- *
5306
- * @returns True if the supplied string was found at the current parse position
5717
+ * Native HTML and SVG tag names, used to tell elements apart from components.
5718
+ * A tag that is neither imported nor a component declared in the same file is
5719
+ * an element when it appears here, or when it contains a dash (an HTML custom
5720
+ * element). Anything else capitalized is reported as an unknown component.
5307
5721
  */
5308
- function accept(value, status, advance = true) {
5309
- if (status.source.substring(status.i, status.i + value.length) == value) {
5310
- status.i += advance ? value.length : 0;
5311
- return true;
5312
- }
5313
- return false;
5314
- }
5315
- //#endregion
5316
- //#region src/compile/parse/parseInlineScript.ts
5317
- function parseInlineScript(status) {
5722
+ const htmlTags = [
5723
+ "a",
5724
+ "abbr",
5725
+ "address",
5726
+ "area",
5727
+ "article",
5728
+ "aside",
5729
+ "audio",
5730
+ "b",
5731
+ "base",
5732
+ "bdi",
5733
+ "bdo",
5734
+ "blockquote",
5735
+ "body",
5736
+ "br",
5737
+ "button",
5738
+ "canvas",
5739
+ "caption",
5740
+ "cite",
5741
+ "code",
5742
+ "col",
5743
+ "colgroup",
5744
+ "data",
5745
+ "datalist",
5746
+ "dd",
5747
+ "del",
5748
+ "details",
5749
+ "dfn",
5750
+ "dialog",
5751
+ "div",
5752
+ "dl",
5753
+ "dt",
5754
+ "em",
5755
+ "embed",
5756
+ "fieldset",
5757
+ "figcaption",
5758
+ "figure",
5759
+ "footer",
5760
+ "form",
5761
+ "h1",
5762
+ "h2",
5763
+ "h3",
5764
+ "h4",
5765
+ "h5",
5766
+ "h6",
5767
+ "head",
5768
+ "header",
5769
+ "hgroup",
5770
+ "hr",
5771
+ "html",
5772
+ "i",
5773
+ "iframe",
5774
+ "img",
5775
+ "input",
5776
+ "ins",
5777
+ "kbd",
5778
+ "label",
5779
+ "legend",
5780
+ "li",
5781
+ "link",
5782
+ "main",
5783
+ "map",
5784
+ "mark",
5785
+ "menu",
5786
+ "meta",
5787
+ "meter",
5788
+ "nav",
5789
+ "noscript",
5790
+ "object",
5791
+ "ol",
5792
+ "optgroup",
5793
+ "option",
5794
+ "output",
5795
+ "p",
5796
+ "picture",
5797
+ "pre",
5798
+ "progress",
5799
+ "q",
5800
+ "rp",
5801
+ "rt",
5802
+ "ruby",
5803
+ "s",
5804
+ "samp",
5805
+ "script",
5806
+ "search",
5807
+ "section",
5808
+ "select",
5809
+ "slot",
5810
+ "small",
5811
+ "source",
5812
+ "span",
5813
+ "strong",
5814
+ "style",
5815
+ "sub",
5816
+ "summary",
5817
+ "sup",
5818
+ "table",
5819
+ "tbody",
5820
+ "td",
5821
+ "template",
5822
+ "textarea",
5823
+ "tfoot",
5824
+ "th",
5825
+ "thead",
5826
+ "time",
5827
+ "title",
5828
+ "tr",
5829
+ "track",
5830
+ "u",
5831
+ "ul",
5832
+ "var",
5833
+ "video",
5834
+ "wbr"
5835
+ ];
5836
+ const svgTags = [
5837
+ "a",
5838
+ "animate",
5839
+ "animateMotion",
5840
+ "animateTransform",
5841
+ "circle",
5842
+ "clipPath",
5843
+ "defs",
5844
+ "desc",
5845
+ "discard",
5846
+ "ellipse",
5847
+ "feBlend",
5848
+ "feColorMatrix",
5849
+ "feComponentTransfer",
5850
+ "feComposite",
5851
+ "feConvolveMatrix",
5852
+ "feDiffuseLighting",
5853
+ "feDisplacementMap",
5854
+ "feDistantLight",
5855
+ "feDropShadow",
5856
+ "feFlood",
5857
+ "feFuncA",
5858
+ "feFuncB",
5859
+ "feFuncG",
5860
+ "feFuncR",
5861
+ "feGaussianBlur",
5862
+ "feImage",
5863
+ "feMerge",
5864
+ "feMergeNode",
5865
+ "feMorphology",
5866
+ "feOffset",
5867
+ "fePointLight",
5868
+ "feSpecularLighting",
5869
+ "feSpotLight",
5870
+ "feTile",
5871
+ "feTurbulence",
5872
+ "filter",
5873
+ "foreignObject",
5874
+ "g",
5875
+ "image",
5876
+ "line",
5877
+ "linearGradient",
5878
+ "marker",
5879
+ "mask",
5880
+ "metadata",
5881
+ "mpath",
5882
+ "path",
5883
+ "pattern",
5884
+ "polygon",
5885
+ "polyline",
5886
+ "radialGradient",
5887
+ "rect",
5888
+ "script",
5889
+ "set",
5890
+ "stop",
5891
+ "style",
5892
+ "svg",
5893
+ "switch",
5894
+ "symbol",
5895
+ "text",
5896
+ "textPath",
5897
+ "title",
5898
+ "tspan",
5899
+ "use",
5900
+ "view"
5901
+ ];
5902
+ const nativeTags = /* @__PURE__ */ new Set([...htmlTags, ...svgTags]);
5903
+ //#endregion
5904
+ //#region src/compile/parse/utils/usesSlot.ts
5905
+ const slotRegex = /\$slot\b/;
5906
+ /**
5907
+ * Checks whether the $slot variable is read in the nodes' own scope
5908
+ *
5909
+ * Note that the children of a component node are excluded, because they are
5910
+ * passed to the component as fills, which get their own $slot parameter.
5911
+ * The component's attributes do belong to this scope.
5912
+ *
5913
+ * @param nodes The nodes to check
5914
+ *
5915
+ * @returns True if a $slot variable is read in the nodes' own scope
5916
+ */
5917
+ function usesSlot(nodes) {
5918
+ for (let node of nodes) if (node.type === "text") {
5919
+ const text = node;
5920
+ if (slotRegex.test(text.content)) return true;
5921
+ } else if (node.type === "control") {
5922
+ const control = node;
5923
+ if (slotRegex.test(control.statement)) return true;
5924
+ if (usesSlot(control.children)) return true;
5925
+ } else if (node.type === "element" || node.type === "special" || node.type === "component") {
5926
+ const element = node;
5927
+ for (let attribute of element.attributes) {
5928
+ if (slotRegex.test(attribute.name)) return true;
5929
+ if (attribute.value && slotRegex.test(attribute.value)) return true;
5930
+ }
5931
+ if (element.type !== "component" && usesSlot(element.children)) return true;
5932
+ }
5933
+ return false;
5934
+ }
5935
+ //#endregion
5936
+ //#region src/compile/parse/slottifyChildNodes.ts
5937
+ /**
5938
+ * Moves any child nodes that aren't already in a <fill> node into a default
5939
+ * <fill> node
5940
+ */
5941
+ function slottifyChildNodes(node) {
5942
+ let nonFillNodes = [];
5943
+ for (let child of node.children) if (isFillNode(child)) {
5944
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5945
+ else break;
5946
+ } else nonFillNodes.push(child);
5947
+ if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5948
+ if (nonFillNodes.length) {
5949
+ let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
5950
+ if (!defaultFillNode) {
5951
+ defaultFillNode = {
5952
+ type: "special",
5953
+ tagName: "filldef",
5954
+ attributes: [],
5955
+ children: nonFillNodes,
5956
+ span: {
5957
+ start: 0,
5958
+ end: 0
5959
+ },
5960
+ hasSlotProps: usesSlot(nonFillNodes)
5961
+ };
5962
+ node.children.unshift(defaultFillNode);
5963
+ }
5964
+ node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
5965
+ }
5966
+ }
5967
+ function isFillNode(n) {
5968
+ return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
5969
+ }
5970
+ //#endregion
5971
+ //#region src/compile/parse/utils/addError.ts
5972
+ /**
5973
+ * Adds an error to the parse status
5974
+ *
5975
+ * @param status The parse status
5976
+ * @param message The error message to add
5977
+ * @param start (Optional) The start position of the error (defaults to the
5978
+ * current parse position)
5979
+ */
5980
+ function addError(status, message, start = status.i, end = status.i) {
5981
+ let startLine = 0;
5982
+ let lastLineStart = 0;
5983
+ let i = 0;
5984
+ for (; i < start; i++) if (status.source[i] === "\n") {
5985
+ startLine += 1;
5986
+ lastLineStart = i + 1;
5987
+ }
5988
+ let startChar = start - lastLineStart;
5989
+ let endLine = startLine;
5990
+ for (; i < end; i++) if (status.source[i] === "\n") {
5991
+ endLine += 1;
5992
+ lastLineStart = i + 1;
5993
+ }
5994
+ let endChar = end - lastLineStart;
5995
+ status.errors.push({
5996
+ message,
5997
+ startIndex: start,
5998
+ startLine,
5999
+ startChar,
6000
+ endIndex: end,
6001
+ endLine,
6002
+ endChar
6003
+ });
6004
+ }
6005
+ //#endregion
6006
+ //#region src/compile/parse/classifyComponents.ts
6007
+ /**
6008
+ * Classifies parsed tags as components or native elements once the whole file
6009
+ * has been parsed (so forward-declared local components are known).
6010
+ *
6011
+ * A tag is a component when its name is imported or is a component declared in
6012
+ * this file. Native and custom elements (`<div>`, `<my-widget>`,
6013
+ * `<linearGradient>`) stay elements. Any other capitalized tag is reported as
6014
+ * unknown instead of silently becoming a component call, unless the caller
6015
+ * opts into assuming external components (`allowUnknownComponents`).
6016
+ */
6017
+ function classifyComponents(status, importedNames, options) {
6018
+ const localNames = new Set(status.components.map((component) => component.name).filter((name) => !!name));
6019
+ for (const component of status.components) {
6020
+ if (component.markup) classifyNode(component.markup, status, importedNames, localNames, options);
6021
+ if (component.error) classifyNode(component.error, status, importedNames, localNames, options);
6022
+ if (component.head) classifyNode(component.head, status, importedNames, localNames, options);
6023
+ }
6024
+ }
6025
+ function classifyNode(node, status, importedNames, localNames, options) {
6026
+ if (isParentNode(node)) for (const child of node.children) classifyNode(child, status, importedNames, localNames, options);
6027
+ if (!isElementNode(node)) return;
6028
+ const tagName = node.tagName;
6029
+ if (importedNames.has(tagName) || localNames.has(tagName)) {
6030
+ node.type = "component";
6031
+ slottifyChildNodes(node);
6032
+ } else if (!nativeTags.has(tagName) && !tagName.includes("-") && /^[A-Z]/.test(tagName)) {
6033
+ if (options?.allowUnknownComponents) {
6034
+ node.type = "component";
6035
+ slottifyChildNodes(node);
6036
+ } else addError(status, `Unknown component or element: ${tagName}. Import it or define it in this file.`, node.span.start, node.span.end);
6037
+ }
6038
+ }
6039
+ //#endregion
6040
+ //#region src/compile/parse/collectImportNames.ts
6041
+ /**
6042
+ * Collects the local binding names introduced by top-level import statements.
6043
+ * Used to tell component tags apart from native elements without touching the
6044
+ * filesystem or relying on a tag-name convention.
6045
+ *
6046
+ * This is a focused import scanner, not a general JS parser: it handles the
6047
+ * import forms (`default`, `* as`, named/aliased, side-effect), comments and
6048
+ * multiline clauses. Type-only imports are ignored (they don't introduce a
6049
+ * value that can be rendered as a tag).
6050
+ */
6051
+ function collectImportNames(source) {
6052
+ const names = /* @__PURE__ */ new Set();
6053
+ let depth = 0;
6054
+ let i = 0;
6055
+ while (i < source.length) {
6056
+ const skipped = skipStringOrComment(source, i);
6057
+ if (skipped !== -1) {
6058
+ i = skipped;
6059
+ continue;
6060
+ }
6061
+ const char = source[i];
6062
+ if (char === "{") {
6063
+ depth += 1;
6064
+ i += 1;
6065
+ continue;
6066
+ }
6067
+ if (char === "}") {
6068
+ depth -= 1;
6069
+ i += 1;
6070
+ continue;
6071
+ }
6072
+ if (depth === 0 && char === "i" && startsWordAt(source, i, "import") && source[i - 1] !== ".") {
6073
+ const end = parseImport(source, i + 6, names);
6074
+ if (end !== -1) {
6075
+ i = end;
6076
+ continue;
6077
+ }
6078
+ }
6079
+ i += 1;
6080
+ }
6081
+ return names;
6082
+ }
6083
+ /** Parses one import statement, adding its value bindings. Returns the end index. */
6084
+ function parseImport(source, start, names) {
6085
+ let i = skipSpaceAndComments(source, start);
6086
+ if (i >= source.length) return -1;
6087
+ if (source[i] === "." || source[i] === "(") return -1;
6088
+ if (source[i] === "\"" || source[i] === "'") return skipStringAndStatementEnd(source, i);
6089
+ let typeOnly = false;
6090
+ if (startsWordAt(source, i, "type")) {
6091
+ const afterType = skipSpaceAndComments(source, i + 4);
6092
+ const next = source[afterType];
6093
+ if (next === "{" || next === "*" || isIdentifierStart(next)) {
6094
+ if (next === "{" || next === "*" || isTypeOnlyDefault(source, afterType)) {
6095
+ typeOnly = true;
6096
+ i = afterType;
6097
+ }
6098
+ }
6099
+ }
6100
+ while (i < source.length) {
6101
+ i = skipSpaceAndComments(source, i);
6102
+ if (i >= source.length) return -1;
6103
+ if (startsWordAt(source, i, "from")) {
6104
+ i = skipStringAndStatementEnd(source, skipSpaceAndComments(source, i + 4));
6105
+ return i;
6106
+ }
6107
+ const char = source[i];
6108
+ if (char === "{") {
6109
+ i += 1;
6110
+ while (i < source.length) {
6111
+ i = skipSpaceAndComments(source, i);
6112
+ if (source[i] === "}") {
6113
+ i += 1;
6114
+ break;
6115
+ }
6116
+ const specifier = parseSpecifier(source, i);
6117
+ if (!specifier) {
6118
+ i += 1;
6119
+ continue;
6120
+ }
6121
+ i = specifier.end;
6122
+ if (!typeOnly && specifier.name) names.add(specifier.name);
6123
+ }
6124
+ continue;
6125
+ }
6126
+ if (char === "*") {
6127
+ i = skipSpaceAndComments(source, i + 1);
6128
+ if (startsWordAt(source, i, "as")) {
6129
+ i = skipSpaceAndComments(source, i + 2);
6130
+ const identifier = readIdentifier(source, i);
6131
+ if (identifier) {
6132
+ if (!typeOnly) names.add(identifier.name);
6133
+ i = identifier.end;
6134
+ }
6135
+ }
6136
+ continue;
6137
+ }
6138
+ if (char === ",") {
6139
+ i += 1;
6140
+ continue;
6141
+ }
6142
+ if (isIdentifierStart(char)) {
6143
+ const identifier = readIdentifier(source, i);
6144
+ if (identifier) {
6145
+ if (!typeOnly) names.add(identifier.name);
6146
+ i = identifier.end;
6147
+ continue;
6148
+ }
6149
+ }
6150
+ i += 1;
6151
+ }
6152
+ return -1;
6153
+ }
6154
+ function parseSpecifier(source, start) {
6155
+ let i = skipSpaceAndComments(source, start);
6156
+ if (i >= source.length) return void 0;
6157
+ let typeOnly = false;
6158
+ if (startsWordAt(source, i, "type")) {
6159
+ const afterType = skipSpaceAndComments(source, i + 4);
6160
+ const next = source[afterType];
6161
+ if (next && next !== "," && next !== "}" && !startsWordAt(source, afterType, "as")) {
6162
+ typeOnly = true;
6163
+ i = afterType;
6164
+ }
6165
+ }
6166
+ let name;
6167
+ if (source[i] === "\"" || source[i] === "'") {
6168
+ const end = skipStringOrComment(source, i);
6169
+ i = end === -1 ? i + 1 : end;
6170
+ } else {
6171
+ const identifier = readIdentifier(source, i);
6172
+ if (!identifier) return void 0;
6173
+ name = identifier.name;
6174
+ i = identifier.end;
6175
+ }
6176
+ i = skipSpaceAndComments(source, i);
6177
+ if (startsWordAt(source, i, "as")) {
6178
+ i = skipSpaceAndComments(source, i + 2);
6179
+ if (source[i] === "\"" || source[i] === "'") {
6180
+ const end = skipStringOrComment(source, i);
6181
+ i = end === -1 ? i + 1 : end;
6182
+ name = void 0;
6183
+ } else {
6184
+ const alias = readIdentifier(source, i);
6185
+ if (alias) {
6186
+ name = alias.name;
6187
+ i = alias.end;
6188
+ }
6189
+ }
6190
+ }
6191
+ i = skipSpaceAndComments(source, i);
6192
+ if (source[i] === ",") i += 1;
6193
+ return {
6194
+ name: typeOnly ? void 0 : name,
6195
+ end: i
6196
+ };
6197
+ }
6198
+ function isTypeOnlyDefault(source, start) {
6199
+ const identifier = readIdentifier(source, start);
6200
+ if (!identifier) return false;
6201
+ return startsWordAt(source, skipSpaceAndComments(source, identifier.end), "from");
6202
+ }
6203
+ function skipStringAndStatementEnd(source, start) {
6204
+ let i = start;
6205
+ if (source[i] === "\"" || source[i] === "'") {
6206
+ const end = skipStringOrComment(source, i);
6207
+ i = end === -1 ? i + 1 : end;
6208
+ }
6209
+ i = skipSpaceAndComments(source, i);
6210
+ if (source[i] === ";") i += 1;
6211
+ return i;
6212
+ }
6213
+ function skipSpaceAndComments(source, start) {
6214
+ let i = start;
6215
+ while (i < source.length) {
6216
+ if (/\s/.test(source[i])) {
6217
+ i += 1;
6218
+ continue;
6219
+ }
6220
+ if (source[i] === "/" && (source[i + 1] === "/" || source[i + 1] === "*")) {
6221
+ const skipped = skipStringOrComment(source, i);
6222
+ if (skipped !== -1) {
6223
+ i = skipped;
6224
+ continue;
6225
+ }
6226
+ }
6227
+ break;
6228
+ }
6229
+ return i;
6230
+ }
6231
+ function readIdentifier(source, start) {
6232
+ if (!isIdentifierStart(source[start])) return void 0;
6233
+ let end = start + 1;
6234
+ while (end < source.length && isIdentifierPart(source[end])) end += 1;
6235
+ return {
6236
+ name: source.substring(start, end),
6237
+ end
6238
+ };
6239
+ }
6240
+ function isIdentifierStart(char) {
6241
+ return char !== void 0 && /[A-Za-z_$]/.test(char);
6242
+ }
6243
+ function isIdentifierPart(char) {
6244
+ return /[A-Za-z0-9_$]/.test(char);
6245
+ }
6246
+ function startsWordAt(source, start, word) {
6247
+ if (!source.startsWith(word, start)) return false;
6248
+ const previous = source[start - 1];
6249
+ const next = source[start + word.length];
6250
+ return (previous === void 0 || !isIdentifierPart(previous)) && (next === void 0 || !isIdentifierPart(next));
6251
+ }
6252
+ //#endregion
6253
+ //#region src/compile/parse/utils/accept.ts
6254
+ /**
6255
+ * Checks whether the source at the current parse position matches the supplied
6256
+ * string
6257
+ *
6258
+ * @param value The string to check
6259
+ * @param status The parse status
6260
+ * @param advance (Optional) If true, advances the parse position past the
6261
+ * checked string (defaults to true)
6262
+ *
6263
+ * @returns True if the supplied string was found at the current parse position
6264
+ */
6265
+ function accept(value, status, advance = true) {
6266
+ if (status.source.substring(status.i, status.i + value.length) == value) {
6267
+ status.i += advance ? value.length : 0;
6268
+ return true;
6269
+ }
6270
+ return false;
6271
+ }
6272
+ //#endregion
6273
+ //#region src/compile/parse/parseInlineScript.ts
6274
+ function parseInlineScript(status) {
5318
6275
  const start = status.i;
5319
6276
  let braceCount = 0;
5320
6277
  while (status.i < status.source.length) {
@@ -5382,79 +6339,36 @@ function addSpaceElement(parent, status) {
5382
6339
  //#endregion
5383
6340
  //#region src/compile/utils/isFullyReactive.ts
5384
6341
  /**
5385
- * Checks whether the supplied string is fully reactive (i.e. starts and ends with braces)
6342
+ * Checks whether the supplied text is exactly one `{...}` interpolation,
6343
+ * ignoring surrounding whitespace. Braces inside the expression's strings and
6344
+ * comments don't count as delimiters.
5386
6345
  *
5387
- * @param text The string to check
6346
+ * @param text The text to check
5388
6347
  *
5389
- * @returns True if the supplied string is fully reactive
6348
+ * @returns True if the supplied text is fully reactive
5390
6349
  */
5391
6350
  function isFullyReactive(text) {
5392
- return text.trim().startsWith("{") && text.trim().endsWith("}");
6351
+ return isSingleInterpolation(text);
5393
6352
  }
5394
6353
  //#endregion
5395
- //#region src/compile/parse/utils/addError.ts
6354
+ //#region src/compile/parse/utils/consumeTagName.ts
5396
6355
  /**
5397
- * Adds an error to the parse status
6356
+ * Consumes a tag name, allowing letters, digits and dashes (custom elements
6357
+ * such as `<my-widget>`), and advances the current parse position to before
6358
+ * the next non-name character.
5398
6359
  *
5399
6360
  * @param status The parse status
5400
- * @param message The error message to add
5401
- * @param start (Optional) The start position of the error (defaults to the
5402
- * current parse position)
5403
- */
5404
- function addError(status, message, start = status.i, end = status.i) {
5405
- let startLine = 0;
5406
- let lastLineStart = 0;
5407
- let i = 0;
5408
- for (; i < start; i++) if (status.source[i] === "\n") {
5409
- startLine += 1;
5410
- lastLineStart = i + 1;
5411
- }
5412
- let startChar = start - lastLineStart;
5413
- let endLine = startLine;
5414
- for (; i < end; i++) if (status.source[i] === "\n") {
5415
- endLine += 1;
5416
- lastLineStart = i + 1;
5417
- }
5418
- let endChar = end - lastLineStart;
5419
- status.errors.push({
5420
- message,
5421
- startIndex: start,
5422
- startLine,
5423
- startChar,
5424
- endIndex: end,
5425
- endLine,
5426
- endChar
5427
- });
5428
- }
5429
- //#endregion
5430
- //#region src/compile/parse/utils/isAlphaNumericChar.ts
5431
- /**
5432
- * Checks whether the supplied character is a alpha-numeric
5433
- *
5434
- * @param text The string to check
5435
- * @param index The index of the character in the string
5436
6361
  *
5437
- * @returns True if the supplied character is alpha-numeric
6362
+ * @returns The tag name from the current parse position to the next non-name
6363
+ * character
5438
6364
  */
5439
- function isAlphaNumericChar(text, index) {
5440
- let code = text.charCodeAt(index);
5441
- return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
5442
- }
5443
- //#endregion
5444
- //#region src/compile/parse/utils/consumeAlphaNumeric.ts
5445
- /**
5446
- * Consumes alpha-numeric characters and advances the current parse position to
5447
- * before the next non-alpha character
5448
- *
5449
- * @param status The parse status
5450
- *
5451
- * @returns The string of alpha-numeric characters from the current parse position
5452
- * to the next non-alpha character
5453
- */
5454
- function consumeAlphaNumeric(status) {
6365
+ function consumeTagName(status) {
5455
6366
  const start = status.i;
5456
- for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
5457
- return "";
6367
+ for (status.i; status.i < status.source.length; status.i++) {
6368
+ const char = status.source[status.i];
6369
+ if (!/[A-Za-z0-9-]/.test(char)) return status.source.substring(start, status.i);
6370
+ }
6371
+ return status.source.substring(start, status.i);
5458
6372
  }
5459
6373
  //#endregion
5460
6374
  //#region src/compile/parse/utils/consumeUntil.ts
@@ -5481,7 +6395,7 @@ function parseTag(status) {
5481
6395
  consumeSpace(status);
5482
6396
  let tagStart = status.i + 1;
5483
6397
  let snailed = accept("@", status);
5484
- let tagName = consumeAlphaNumeric(status);
6398
+ let tagName = consumeTagName(status);
5485
6399
  let tagEnd = status.i;
5486
6400
  if (snailed) tagName = "@" + tagName;
5487
6401
  if (closeTag) tagName = "/" + tagName;
@@ -5536,14 +6450,20 @@ function parseAttribute(status) {
5536
6450
  if (accept("=", status)) {
5537
6451
  consumeSpace(status);
5538
6452
  valueStart = status.i;
5539
- value = parseAttributeValue(status);
5540
- valueEnd = status.i;
5541
- reactive = isReactive(value);
5542
- fullyReactive = isFullyReactive(value);
5543
- if (fullyReactive) {
5544
- value = value.substring(1, value.length - 1);
5545
- valueStart++;
5546
- valueEnd--;
6453
+ if (status.source[valueStart] === "`") {
6454
+ value = parseTemplateLiteral(status);
6455
+ valueEnd = status.i;
6456
+ reactive = fullyReactive = true;
6457
+ } else {
6458
+ value = parseAttributeValue(status);
6459
+ valueEnd = status.i;
6460
+ fullyReactive = isFullyReactive(value);
6461
+ reactive = fullyReactive;
6462
+ if (fullyReactive) {
6463
+ value = value.substring(1, value.length - 1);
6464
+ valueStart++;
6465
+ valueEnd--;
6466
+ }
5547
6467
  }
5548
6468
  } else if (name.startsWith("{") && name.endsWith("}")) {
5549
6469
  value = name.substring(1, name.length - 1);
@@ -5566,6 +6486,18 @@ function parseAttribute(status) {
5566
6486
  }
5567
6487
  };
5568
6488
  }
6489
+ /**
6490
+ * Consumes a backtick-delimited JavaScript template literal, reusing the
6491
+ * script scanner so `${...}` interpolations and nested strings/templates are
6492
+ * skipped correctly.
6493
+ */
6494
+ function parseTemplateLiteral(status) {
6495
+ const start = status.i;
6496
+ const end = skipStringOrComment(status.source, start);
6497
+ status.i = end === -1 ? start + 1 : end;
6498
+ if (status.source[status.i - 1] !== "`") addError(status, "Unclosed template literal in attribute", start, status.i);
6499
+ return status.source.substring(start, status.i);
6500
+ }
5569
6501
  function parseAttributeValue(status) {
5570
6502
  if (accept("\"", status)) {
5571
6503
  const value = consumeUntil("\"", status);
@@ -5646,73 +6578,6 @@ function parseText(status, element) {
5646
6578
  } else status.i += 1;
5647
6579
  }
5648
6580
  //#endregion
5649
- //#region src/compile/parse/utils/usesSlot.ts
5650
- const slotRegex = /\$slot\b/;
5651
- /**
5652
- * Checks whether the $slot variable is read in the nodes' own scope
5653
- *
5654
- * Note that the children of a component node are excluded, because they are
5655
- * passed to the component as fills, which get their own $slot parameter.
5656
- * The component's attributes do belong to this scope.
5657
- *
5658
- * @param nodes The nodes to check
5659
- *
5660
- * @returns True if a $slot variable is read in the nodes' own scope
5661
- */
5662
- function usesSlot(nodes) {
5663
- for (let node of nodes) if (node.type === "text") {
5664
- const text = node;
5665
- if (slotRegex.test(text.content)) return true;
5666
- } else if (node.type === "control") {
5667
- const control = node;
5668
- if (slotRegex.test(control.statement)) return true;
5669
- if (usesSlot(control.children)) return true;
5670
- } else if (node.type === "element" || node.type === "special" || node.type === "component") {
5671
- const element = node;
5672
- for (let attribute of element.attributes) {
5673
- if (slotRegex.test(attribute.name)) return true;
5674
- if (attribute.value && slotRegex.test(attribute.value)) return true;
5675
- }
5676
- if (element.type !== "component" && usesSlot(element.children)) return true;
5677
- }
5678
- return false;
5679
- }
5680
- //#endregion
5681
- //#region src/compile/parse/slottifyChildNodes.ts
5682
- /**
5683
- * Moves any child nodes that aren't already in a <fill> node into a default
5684
- * <fill> node
5685
- */
5686
- function slottifyChildNodes(node) {
5687
- let nonFillNodes = [];
5688
- for (let child of node.children) if (isFillNode(child)) {
5689
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5690
- else break;
5691
- } else nonFillNodes.push(child);
5692
- if (nonFillNodes.find((n) => !isSpaceNode(n)) === void 0) nonFillNodes = [];
5693
- if (nonFillNodes.length) {
5694
- let defaultFillNode = node.children.find((n) => isFillNode(n) && !n.attributes.find((a) => a.name === "name"));
5695
- if (!defaultFillNode) {
5696
- defaultFillNode = {
5697
- type: "special",
5698
- tagName: "filldef",
5699
- attributes: [],
5700
- children: nonFillNodes,
5701
- span: {
5702
- start: 0,
5703
- end: 0
5704
- },
5705
- hasSlotProps: usesSlot(nonFillNodes)
5706
- };
5707
- node.children.unshift(defaultFillNode);
5708
- }
5709
- node.children = node.children.filter((c) => isFillNode(c) || !nonFillNodes.includes(c));
5710
- }
5711
- }
5712
- function isFillNode(n) {
5713
- return isSpecialNode(n) && (n.tagName === "fill" || n.tagName === "filldef");
5714
- }
5715
- //#endregion
5716
6581
  //#region src/compile/parse/parseElement.ts
5717
6582
  function parseElement(status) {
5718
6583
  const current = status.components.at(-1);
@@ -5726,6 +6591,7 @@ function parseElement(status) {
5726
6591
  if (voidTags.includes(element.tagName)) checkVoidElement(status, element);
5727
6592
  if (!element.selfClosed && !voidTags.includes(element.tagName)) {
5728
6593
  status.stack.push(element);
6594
+ if (isRawTextTag(element.tagName)) parseRawText(status, element);
5729
6595
  while (status.i < status.source.length) {
5730
6596
  addSpaceElement(element, status);
5731
6597
  if (accept("}", status, false)) break;
@@ -5766,10 +6632,6 @@ function parseElement(status) {
5766
6632
  }
5767
6633
  status.stack.pop();
5768
6634
  }
5769
- if (/[A-Z]/.test(element.tagName[0])) {
5770
- element.type = "component";
5771
- slottifyChildNodes(element);
5772
- }
5773
6635
  if (isSpecialNode(element)) {
5774
6636
  if (element.tagName === "slot") {
5775
6637
  slottifyChildNodes(element);
@@ -5807,6 +6669,32 @@ function parseElement(status) {
5807
6669
  if (!element.closed && !voidTags.includes(element.tagName)) addError(status, `Unclosed non-void element: ${element.tagName}`, start, start + element.tagName.length + 1);
5808
6670
  return element;
5809
6671
  }
6672
+ /**
6673
+ * Consumes a raw-text element's content as a single literal text node. The
6674
+ * content ends at the first matching close tag (which the caller's child loop
6675
+ * then handles), or at the end of the source when the element is unclosed.
6676
+ */
6677
+ function parseRawText(status, element) {
6678
+ const start = status.i;
6679
+ const end = findRawTextEnd(status.source, element.tagName, start);
6680
+ if (end > start) {
6681
+ const text = {
6682
+ type: "text",
6683
+ content: status.source.substring(start, end),
6684
+ start,
6685
+ spans: [],
6686
+ raw: true
6687
+ };
6688
+ element.children.push(text);
6689
+ }
6690
+ status.i = end;
6691
+ }
6692
+ function findRawTextEnd(source, tagName, start) {
6693
+ const pattern = new RegExp(`</${tagName}(?=[\\s/>])`, "gi");
6694
+ pattern.lastIndex = start;
6695
+ const match = pattern.exec(source);
6696
+ return match ? match.index : source.length;
6697
+ }
5810
6698
  function checkVoidElement(status, element) {
5811
6699
  let i = status.i;
5812
6700
  consumeSpace(status);
@@ -5826,7 +6714,7 @@ function checkCloseTag(status, element) {
5826
6714
  accept("</", status);
5827
6715
  consumeSpace(status);
5828
6716
  let snailed = accept("@", status);
5829
- let closingTagName = consumeAlphaNumeric(status);
6717
+ let closingTagName = consumeTagName(status);
5830
6718
  if (snailed) closingTagName = "@" + closingTagName;
5831
6719
  consumeSpace(status);
5832
6720
  accept(">", status);
@@ -5936,6 +6824,8 @@ function parseControlOpen(status) {
5936
6824
  };
5937
6825
  }
5938
6826
  function parseControlStatement(start, operation, status) {
6827
+ const standalone = standaloneOperations.includes(operation);
6828
+ const braceStartsBody = !standalone || operation === "@function" || operation === "@async function";
5939
6829
  let parenCount = 0;
5940
6830
  while (status.i < status.source.length) {
5941
6831
  const skipped = skipStringOrComment(status.source, status.i);
@@ -5945,11 +6835,11 @@ function parseControlStatement(start, operation, status) {
5945
6835
  }
5946
6836
  if (accept("(", status)) parenCount += 1;
5947
6837
  else if (accept(")", status)) parenCount -= 1;
5948
- else if (accept("{", status) || accept("\n", status) && standaloneOperations.includes(operation)) {
6838
+ else if (accept("{", status) && braceStartsBody || accept("\n", status) && standalone) {
5949
6839
  if (parenCount === 0) return trimStart(status.source.substring(start, status.i - 1).trim(), "@");
5950
6840
  } else status.i += 1;
5951
6841
  }
5952
- return "";
6842
+ return trimStart(status.source.substring(start, status.i).trim(), "@");
5953
6843
  }
5954
6844
  /**
5955
6845
  * Groups the control node into the correct parent e.g. if/else into an if group
@@ -6202,7 +7092,6 @@ function parseStyles(source, status) {
6202
7092
  marker: 0,
6203
7093
  level: 0,
6204
7094
  braces: [],
6205
- imports: [],
6206
7095
  script: [],
6207
7096
  components: [],
6208
7097
  stack: [],
@@ -6281,37 +7170,64 @@ function parseStyleAttribute(status) {
6281
7170
  }
6282
7171
  //#endregion
6283
7172
  //#region src/compile/parse/scopeStyles.ts
7173
+ /**
7174
+ * Marks every element in a component that has scoped styles with the
7175
+ * component's scope class. This is intentionally not selector-based: deciding
7176
+ * which elements a CSS selector can match requires parsing selectors, and
7177
+ * pseudo-classes, attribute selectors and `@media` rules make compile-time
7178
+ * matching unreliable. Marking every element lets `buildStyles` append the
7179
+ * scope class to selectors without needing to understand their shape.
7180
+ */
6284
7181
  function scopeStyles(status) {
6285
- let selectors = [];
6286
- for (let component of status.components) if (component.style && component.markup) {
6287
- for (let block of component.style.children) if (block.type === "block") collectStyleSelectors(block, selectors);
6288
- scopeStylesOnNode(component.markup, selectors);
7182
+ for (let component of status.components) {
7183
+ if (!component.style) continue;
7184
+ if (component.markup) scopeStylesOnNode(component.markup);
7185
+ if (component.error) scopeStylesOnNode(component.error);
6289
7186
  }
6290
7187
  }
6291
- function scopeStylesOnNode(node, selectors) {
6292
- if (isElementNode(node) || isComponentNode(node)) node.scopeStyles = selectors.includes(node.tagName) || node.attributes.find((a) => {
6293
- if (a.name === "class" && a.reactive) return true;
6294
- else if (a.name === "id" && a.value) {
6295
- if (selectors.includes(`#${trimQuotes(a.value)}`)) return true;
6296
- } else if (a.name === "class" && a.value) {
6297
- for (let classname of trimQuotes(a.value).split(/\s+/)) if (selectors.includes(`.${classname}`)) return true;
6298
- }
6299
- }) !== void 0;
6300
- if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child, selectors);
7188
+ function scopeStylesOnNode(node) {
7189
+ if (isElementNode(node) || isComponentNode(node) || isSpecialNode(node) && (node.tagName === "@element" || node.tagName === "@component")) node.scopeStyles = true;
7190
+ if (isParentNode(node)) for (let child of node.children) scopeStylesOnNode(child);
6301
7191
  }
6302
- function collectStyleSelectors(block, selectors) {
6303
- for (let s of block.selector.split(/[\s*,>+~[\]]/)) selectors.push(s);
7192
+ //#endregion
7193
+ //#region src/compile/parse/utils/isAlphaNumericChar.ts
7194
+ /**
7195
+ * Checks whether the supplied character is a alpha-numeric
7196
+ *
7197
+ * @param text The string to check
7198
+ * @param index The index of the character in the string
7199
+ *
7200
+ * @returns True if the supplied character is alpha-numeric
7201
+ */
7202
+ function isAlphaNumericChar(text, index) {
7203
+ let code = text.charCodeAt(index);
7204
+ return code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123;
7205
+ }
7206
+ //#endregion
7207
+ //#region src/compile/parse/utils/consumeAlphaNumeric.ts
7208
+ /**
7209
+ * Consumes alpha-numeric characters and advances the current parse position to
7210
+ * before the next non-alpha character
7211
+ *
7212
+ * @param status The parse status
7213
+ *
7214
+ * @returns The string of alpha-numeric characters from the current parse position
7215
+ * to the next non-alpha character
7216
+ */
7217
+ function consumeAlphaNumeric(status) {
7218
+ const start = status.i;
7219
+ for (status.i; status.i < status.source.length; status.i++) if (!isAlphaNumericChar(status.source, status.i)) return status.source.substring(start, status.i);
7220
+ return "";
6304
7221
  }
6305
7222
  //#endregion
6306
7223
  //#region src/compile/parse/parseCode.ts
6307
- function parseCode(source) {
7224
+ function parseCode(source, options) {
6308
7225
  const status = {
6309
7226
  source,
6310
7227
  i: 0,
6311
7228
  marker: 0,
6312
7229
  level: 0,
6313
7230
  braces: [],
6314
- imports: [],
6315
7231
  script: [],
6316
7232
  components: [],
6317
7233
  stack: [],
@@ -6367,6 +7283,7 @@ function parseCode(source) {
6367
7283
  end: source.length
6368
7284
  }
6369
7285
  });
7286
+ classifyComponents(status, collectImportNames(source), options);
6370
7287
  scopeStyles(status);
6371
7288
  const ok = !status.errors.length;
6372
7289
  if (!ok) status.errors = status.errors.sort((a, b) => a.startIndex - b.startIndex);
@@ -6374,7 +7291,6 @@ function parseCode(source) {
6374
7291
  ok,
6375
7292
  errors: status.errors,
6376
7293
  template: ok ? {
6377
- imports: status.imports,
6378
7294
  script: status.script,
6379
7295
  components: status.components
6380
7296
  } : void 0
@@ -6470,7 +7386,6 @@ function parseComponentStart(status) {
6470
7386
  marker: 0,
6471
7387
  level: 0,
6472
7388
  braces: [],
6473
- imports: [],
6474
7389
  script: [],
6475
7390
  components: [],
6476
7391
  stack: [],
@@ -6731,12 +7646,13 @@ function consumeScriptComments(status) {
6731
7646
  * Parses source code into a component template
6732
7647
  *
6733
7648
  * @param source The source code
7649
+ * @param options Optional parse behaviour
6734
7650
  *
6735
7651
  * @returns A result indicating whether parsing was ok, and if so, containing
6736
7652
  * the component template's parts such as script, markup and styles
6737
7653
  */
6738
- function parse(source) {
6739
- return parseCode(source);
7654
+ function parse(source, options) {
7655
+ return parseCode(source, options);
6740
7656
  }
6741
7657
  //#endregion
6742
7658
  //#region src/compile/parse/bindDataTemplate.ts