@torpor/view 1.2.6 → 1.3.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 (38) hide show
  1. package/dist/{Effect-DazmAdyC.d.mts → Effect-99HYQdzZ.d.mts} +50 -33
  2. package/dist/Effect-99HYQdzZ.d.mts.map +1 -0
  3. package/dist/{Effect-Dewn7MLc.d.cts → Effect-Bf8fz_zC.d.cts} +50 -33
  4. package/dist/Effect-Bf8fz_zC.d.cts.map +1 -0
  5. package/dist/compile.cjs +1498 -101
  6. package/dist/compile.d.cts +268 -1
  7. package/dist/compile.d.cts.map +1 -1
  8. package/dist/compile.d.mts +268 -1
  9. package/dist/compile.d.mts.map +1 -1
  10. package/dist/compile.mjs +1495 -102
  11. package/dist/compile.mjs.map +1 -1
  12. package/dist/dev.d.cts +1 -1
  13. package/dist/dev.d.mts +1 -1
  14. package/dist/{fromWebSocket-DrN-IduP.cjs → fromWebSocket-Cdoghvmh.cjs} +15 -0
  15. package/dist/{fromWebSocket-CFGoMkV2.mjs → fromWebSocket-ERhd9KZR.mjs} +11 -2
  16. package/dist/fromWebSocket-ERhd9KZR.mjs.map +1 -0
  17. package/dist/index.cjs +121 -75
  18. package/dist/index.d.cts +12 -6
  19. package/dist/index.d.cts.map +1 -1
  20. package/dist/index.d.mts +12 -6
  21. package/dist/index.d.mts.map +1 -1
  22. package/dist/index.mjs +121 -75
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/runtime.iife.js +1 -0
  25. package/dist/slotAutoClose-BbKfzpkz.cjs +177 -0
  26. package/dist/slotAutoClose-CgDkf8fM.mjs +156 -0
  27. package/dist/slotAutoClose-CgDkf8fM.mjs.map +1 -0
  28. package/dist/ssr.cjs +29 -1
  29. package/dist/ssr.d.cts +32 -1
  30. package/dist/ssr.d.cts.map +1 -1
  31. package/dist/ssr.d.mts +32 -1
  32. package/dist/ssr.d.mts.map +1 -1
  33. package/dist/ssr.mjs +25 -2
  34. package/dist/ssr.mjs.map +1 -1
  35. package/package.json +8 -5
  36. package/dist/Effect-DazmAdyC.d.mts.map +0 -1
  37. package/dist/Effect-Dewn7MLc.d.cts.map +0 -1
  38. package/dist/fromWebSocket-CFGoMkV2.mjs.map +0 -1
package/dist/compile.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { n as autoCloseMessage, r as closesAncestor, t as AUTO_CLOSEABLE } from "./slotAutoClose-CgDkf8fM.mjs";
1
2
  //#region src/compile/utils/endOfString.ts
2
3
  function endOfString(char, content, start) {
3
4
  for (let j = start + 1; j < content.length; j++) if (content[j] === char && content[j - 1] !== "\\") return j;
@@ -348,6 +349,114 @@ function nodeRendersComponent(node) {
348
349
  return false;
349
350
  }
350
351
  //#endregion
352
+ //#region src/compile/utils/stalePropLets.ts
353
+ /**
354
+ * Detects the "plain `let` initialized from `$props`, read from markup"
355
+ * stale-capture trap. A component instantiated from a keyed `@for` stays
356
+ * alive across list mutations while its props are updated in place — reads
357
+ * of `$props.x` in template expressions track correctly, but a plain `let x =
358
+ * ...$props.y...` is evaluated once at setup, so template effects reading
359
+ * `x` never re-run and silently keep the previous row's values.
360
+ *
361
+ * Detection is best-effort and syntactic: top-level `let` declarations in the
362
+ * component script whose initializer (up to the first `;` or newline) mentions
363
+ * `$props`, and whose name then appears in a markup expression. Deliberately a
364
+ * warning, not an error — capturing a prop value once is sometimes intended,
365
+ * and destructured/renamed forms (`let { x } = $props`) aren't detected.
366
+ */
367
+ function stalePropLets(segments, markup, source) {
368
+ let script = "";
369
+ const deltas = [];
370
+ for (const segment of segments) {
371
+ deltas.push({
372
+ localStart: script.length,
373
+ delta: segment.fileStart
374
+ });
375
+ script += segment.text;
376
+ }
377
+ const toFileOffset = (local) => {
378
+ let delta = deltas[0].delta;
379
+ for (const entry of deltas) if (entry.localStart <= local) delta = entry.delta - entry.localStart;
380
+ else break;
381
+ return local + delta;
382
+ };
383
+ const names = [];
384
+ const LET = /^let[\s\n]/;
385
+ for (let i = 0; i < script.length; i++) {
386
+ const char = script[i];
387
+ if (char === "'" || char === "\"" || char === "`" || char === "/") {
388
+ const skipped = skipStringOrComment(script, i);
389
+ if (skipped !== -1) {
390
+ i = skipped - 1;
391
+ continue;
392
+ }
393
+ }
394
+ if (!LET.test(script.slice(i, i + 4))) continue;
395
+ if (i > 0 && /[\w$]/.test(script[i - 1])) continue;
396
+ let j = i + 3;
397
+ while (/\s/.test(script[j] ?? "")) j++;
398
+ let name = "";
399
+ while (/[\w$]/.test(script[j] ?? "")) {
400
+ name += script[j];
401
+ j++;
402
+ }
403
+ if (!name) continue;
404
+ while (/\s/.test(script[j] ?? "")) j++;
405
+ if (script[j] === ":") {
406
+ j++;
407
+ while (script[j] !== void 0 && script[j] !== "=" && script[j] !== "\n") j++;
408
+ }
409
+ while (/\s/.test(script[j] ?? "")) j++;
410
+ if (script[j] !== "=" || script[j + 1] === "=") continue;
411
+ j++;
412
+ let init = "";
413
+ while (j < script.length && script[j] !== ";" && script[j] !== "\n") {
414
+ if (script[j] === "'" || script[j] === "\"" || script[j] === "`") {
415
+ const skipped = skipStringOrComment(script, j);
416
+ if (skipped !== -1) {
417
+ init += script.slice(j, skipped);
418
+ j = skipped;
419
+ continue;
420
+ }
421
+ }
422
+ init += script[j];
423
+ j++;
424
+ }
425
+ if (/\$props\b/.test(init)) names.push({
426
+ name,
427
+ local: i
428
+ });
429
+ i = j;
430
+ }
431
+ if (names.length === 0 || !markup) return [];
432
+ const expressions = collectMarkupExpressions(markup);
433
+ if (!expressions) return [];
434
+ const warnings = [];
435
+ for (const { name, local } of names) {
436
+ const escaped = name.replace(/\$/g, "\\$");
437
+ if (!new RegExp(`(^|[^\\w$])${escaped}([^\\w$]|$)`).test(expressions)) continue;
438
+ const absolute = toFileOffset(local);
439
+ let startLine = 0;
440
+ let lastLineStart = 0;
441
+ if (source !== void 0) {
442
+ for (let i = 0; i < absolute && i < source.length; i++) if (source[i] === "\n") {
443
+ startLine += 1;
444
+ lastLineStart = i + 1;
445
+ }
446
+ }
447
+ warnings.push({
448
+ message: `'${name}' is a plain let initialized from $props. Its value is captured once at setup, so template expressions reading it won't update when the component's props change (keyed lists keep components alive and update props in place). Use a getter or $cache if it should stay live.`,
449
+ startIndex: absolute,
450
+ startLine,
451
+ startChar: absolute - lastLineStart,
452
+ endIndex: absolute,
453
+ endLine: startLine,
454
+ endChar: absolute - lastLineStart
455
+ });
456
+ }
457
+ return warnings;
458
+ }
459
+ //#endregion
351
460
  //#region src/compile/build/client/addMappedText.ts
352
461
  function addMappedText(preText, text, postText, span, status, b) {
353
462
  if (status.options.mapped === true) {
@@ -717,6 +826,59 @@ function bindingTarget(value, right, name, imports) {
717
826
  return `const t_bind_${varSuffix} = ${right};\nconst t_target_${varSuffix} = $peek(() => ${guard});\nif (t_target_${varSuffix} != null) t_target_${varSuffix}${suffix} = t_bind_${varSuffix};`;
718
827
  }
719
828
  //#endregion
829
+ //#region src/compile/utils/getContextUsage.ts
830
+ /**
831
+ * Gets the `$context` names that the compiled output references. The input is
832
+ * code-only text (a component's script plus markup expressions, or a slot
833
+ * fill's collected expressions), with `ranges` marking the positions that are
834
+ * code — matches that start inside a string, comment or regex literal are
835
+ * ignored, so mentions inside sample-code strings don't count.
836
+ */
837
+ function getContextUsage(source, ranges) {
838
+ const contextsMatches = source.matchAll(/\$context\??\s*(?:\.([\d\w]+)|\[([^\]]+)\])/g);
839
+ const contexts = [];
840
+ for (let match of contextsMatches) {
841
+ if (!isInCode(ranges, match.index)) continue;
842
+ const name = trimQuotes(match[1] || match[2]);
843
+ if (!contexts.includes(name)) contexts.push(name);
844
+ }
845
+ if (!contexts.length) for (let match of source.matchAll(/(?<![\w$])\$context(?![\w])(?!\s*:)(?!<)/g)) {
846
+ if (!isInCode(ranges, match.index)) continue;
847
+ contexts.push("$context");
848
+ break;
849
+ }
850
+ return contexts.length ? contexts : void 0;
851
+ }
852
+ /**
853
+ * Returns true if `index` falls inside one of the (sorted, non-overlapping)
854
+ * code ranges — i.e. not inside a string, comment or regex literal.
855
+ */
856
+ function isInCode(ranges, index) {
857
+ for (const [start, end] of ranges) {
858
+ if (index >= start && index < end) return true;
859
+ if (index < start) return false;
860
+ }
861
+ return false;
862
+ }
863
+ //#endregion
864
+ //#region src/compile/utils/fillUsesContext.ts
865
+ /**
866
+ * Returns true if a slot fill's content uses the `$context` parameter that
867
+ * the generated fill function declares: rendering a child component or slot
868
+ * forwards `$context` positionally (see buildComponentNode / buildSlotNode
869
+ * and their server counterparts), and a direct `$context` read in one of the
870
+ * fill's own expressions (interpolation, reactive attribute, event handler,
871
+ * control statement) reads it.
872
+ *
873
+ * Bias is towards `true`: when uncertain we keep `$context` named, which is
874
+ * always safe at the cost of a missed unused-parameter cleanup.
875
+ */
876
+ function fillUsesContext(fill) {
877
+ if (markupRendersComponent({ children: fill.children ?? [] })) return true;
878
+ const expressions = collectMarkupExpressions(fill);
879
+ return getContextUsage(expressions, codeRanges(expressions)) !== void 0;
880
+ }
881
+ //#endregion
720
882
  //#region src/compile/utils/isSpecialNode.ts
721
883
  function isSpecialNode(node) {
722
884
  return node.type === "special";
@@ -1282,23 +1444,52 @@ function getFragmentVarPath(fragment, status, name, path, varPaths) {
1282
1444
  varPaths.set(varPath, name);
1283
1445
  varPaths.set(name, name);
1284
1446
  }
1285
- while (varPath.includes("t_next(t_next(")) {
1447
+ while (/(?:t_next_text\(|t_next\(){2,}/.test(varPath)) {
1286
1448
  status.imports.add("t_skip");
1287
- const match = varPath.match(/(t_next\(){2,}/)[0];
1288
- const count = match.length / 7;
1289
- const pos = varPath.indexOf("t_next(t_next(");
1290
- const head = varPath.substring(0, pos);
1291
- let level = 0;
1292
- let end = 0;
1293
- for (let i = pos + match.length; i < varPath.length; i++) if (varPath[i] === "(") level++;
1294
- else if (varPath[i] === ")") {
1295
- if (level === 0) {
1296
- end = i;
1449
+ const runStart = /(?:t_next_text\(|t_next\(){2,}/.exec(varPath).index;
1450
+ const openings = [];
1451
+ let j = runStart;
1452
+ for (;;) {
1453
+ const open = /^(t_next_text|t_next)\(/.exec(varPath.slice(j));
1454
+ if (!open) break;
1455
+ openings.push({
1456
+ text: open[1] === "t_next_text",
1457
+ openEnd: j + open[0].length
1458
+ });
1459
+ j += open[0].length;
1460
+ }
1461
+ if (openings.length < 2) break;
1462
+ const count = openings.length;
1463
+ const innermostOpenEnd = openings[openings.length - 1].openEnd;
1464
+ let innerDepth = 0;
1465
+ let innermostClose = -1;
1466
+ for (let k = innermostOpenEnd; k < varPath.length; k++) if (varPath[k] === "(") innerDepth++;
1467
+ else if (varPath[k] === ")") {
1468
+ if (innerDepth === 0) {
1469
+ innermostClose = k;
1470
+ break;
1471
+ }
1472
+ innerDepth--;
1473
+ }
1474
+ if (innermostClose === -1) break;
1475
+ let outerDepth = 1;
1476
+ let outerClose = -1;
1477
+ for (let k = openings[0].openEnd; k < varPath.length; k++) if (varPath[k] === "(") outerDepth++;
1478
+ else if (varPath[k] === ")") {
1479
+ outerDepth--;
1480
+ if (outerDepth === 0) {
1481
+ outerClose = k;
1297
1482
  break;
1298
- } else level--;
1483
+ }
1299
1484
  }
1300
- const tail = varPath.substring(end + count);
1301
- varPath = `${head}t_skip(${varPath.substring(pos + match.length, end)}, ${count})${tail}`;
1485
+ if (outerClose === -1) break;
1486
+ let mask = 0;
1487
+ for (let k = 0; k < count; k++) if (openings[k].text) mask |= 1 << count - 1 - k;
1488
+ let param = varPath.substring(innermostOpenEnd, innermostClose);
1489
+ if (openings[openings.length - 1].text && param.endsWith(", true")) param = param.slice(0, -6);
1490
+ const head = varPath.substring(0, runStart);
1491
+ const tail = varPath.substring(outerClose + 1);
1492
+ varPath = `${head}t_skip(${param}, ${count}${mask ? `, ${mask}` : ""})${tail}`;
1302
1493
  }
1303
1494
  varPath = varPath.replaceAll("t_next_text", "t_next");
1304
1495
  return varPath;
@@ -1544,7 +1735,7 @@ function buildComponentNode(node, status, b, root = false) {
1544
1735
  "$sparent: ParentNode",
1545
1736
  "$sanchor: Node | null",
1546
1737
  slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>",
1547
- "$context?: Record<PropertyKey, any>"
1738
+ fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"
1548
1739
  ];
1549
1740
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = (\n${slotParams.join(",\n")}\n) => {`);
1550
1741
  buildFragment(slot, status, b, "$sparent", "$sanchor");
@@ -1674,6 +1865,44 @@ function isForBodyLeafSafe(forBodyChildren) {
1674
1865
  return !hasNestedControl(forBodyChildren);
1675
1866
  }
1676
1867
  //#endregion
1868
+ //#region src/compile/utils/forLoopVarNames.ts
1869
+ /**
1870
+ * Extracts the declared loop variable names from a `@for` statement — the
1871
+ * heuristic header parse shared by `buildForNode` (codegen) and the write
1872
+ * scanners (`forVarsWrittenIn`/`forVarsReassignedIn`, which use it to detect
1873
+ * nested loops that shadow an outer loop's variables).
1874
+ *
1875
+ * Handles the C-style (`for (let i = 0; i < n; i++)`), for-of and for-in
1876
+ * forms, with destructuring flattened to the bare names. TODO: Handle
1877
+ * destructuring, quotes, comments etc (same as buildForNode's note — this is
1878
+ * deliberately the same heuristic).
1879
+ */
1880
+ function forLoopVarNames(statement) {
1881
+ const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1882
+ const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
1883
+ const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
1884
+ const trimMatched = (value, start, end) => {
1885
+ const startIndex = value.indexOf(start);
1886
+ const endIndex = value.lastIndexOf(end);
1887
+ if (startIndex === -1 || endIndex === -1) return value;
1888
+ return value.slice(startIndex + 1, endIndex);
1889
+ };
1890
+ const names = [];
1891
+ const forLoopMatch = statement.match(forLoopRegex);
1892
+ if (forLoopMatch) {
1893
+ const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1894
+ for (const match of forVarMatches) names.push(match[1]);
1895
+ return names;
1896
+ }
1897
+ const forOfMatch = statement.match(forOfRegex);
1898
+ if (forOfMatch) {
1899
+ const match = forOfMatch[1];
1900
+ if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) names.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1901
+ else names.push(match);
1902
+ }
1903
+ return names;
1904
+ }
1905
+ //#endregion
1677
1906
  //#region src/compile/utils/forVarsWrittenIn.ts
1678
1907
  /**
1679
1908
  * Returns the set of `forVars` that are written anywhere in `children`,
@@ -1705,13 +1934,16 @@ function scan(children, forVars, bareWritePattern) {
1705
1934
  const found = /* @__PURE__ */ new Set();
1706
1935
  if (forVars.length === 0) return found;
1707
1936
  const collected = [];
1708
- for (const child of children) collectExpressionStrings(child, collected);
1937
+ for (const child of children) collectExpressionStrings(child, collected, /* @__PURE__ */ new Set());
1709
1938
  for (const varName of forVars) {
1710
1939
  const escaped = varName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1711
1940
  const writePattern = new RegExp(`(?<![\\w$.\\])\\)])\\[\\s*${escaped}\\s*\\]\\s*=(?![=>])|(?<![\\w$.\\])\\)])\\{\\s*${escaped}\\s*(:[^}]+)?\\}\\s*=(?![=>])|` + bareWritePattern(escaped) + `|(?<![\\w$.])(?:\\+\\+|--)\\s*${escaped}(?![\\w$])`);
1712
- for (const text of collected) if (writePattern.test(text)) {
1713
- found.add(varName);
1714
- break;
1941
+ for (const entry of collected) {
1942
+ if (entry.shadows.has(varName)) continue;
1943
+ if (writePattern.test(entry.text)) {
1944
+ found.add(varName);
1945
+ break;
1946
+ }
1715
1947
  }
1716
1948
  }
1717
1949
  return found;
@@ -1723,26 +1955,53 @@ function isElementLike(node) {
1723
1955
  * Collects every expression-like string from the body, including attribute
1724
1956
  * values (with `&`-binding targets marked by a trailing `=`), text
1725
1957
  * interpolations, and control statements (recursing into nested controls).
1958
+ *
1959
+ * Nested `@for` loops are special: their own statement is skipped entirely
1960
+ * (its declarations and init/update expressions belong to the inner loop's
1961
+ * variables — a C-style header's `i++` is the inner loop's own bookkeeping,
1962
+ * not a write of an outer loop's variable), and every string beneath it is
1963
+ * recorded with the inner loop's variable names as shadowing it.
1726
1964
  */
1727
- function collectExpressionStrings(node, out) {
1965
+ function collectExpressionStrings(node, out, shadows) {
1728
1966
  if (isTextNode(node)) {
1729
- out.push(node.content);
1967
+ out.push({
1968
+ text: node.content,
1969
+ shadows
1970
+ });
1730
1971
  return;
1731
1972
  }
1732
1973
  if (isElementLike(node)) {
1733
1974
  for (const attr of node.attributes) {
1734
1975
  if (attr.value !== void 0) {
1735
- if (attr.name.startsWith("&")) out.push(`${attr.value} =`);
1736
- else out.push(attr.value);
1976
+ if (attr.name.startsWith("&")) out.push({
1977
+ text: `${attr.value} =`,
1978
+ shadows
1979
+ });
1980
+ else out.push({
1981
+ text: attr.value,
1982
+ shadows
1983
+ });
1737
1984
  }
1738
- if (attr.fullyReactive && attr.name !== attr.value) out.push(attr.name);
1985
+ if (attr.fullyReactive && attr.name !== attr.value) out.push({
1986
+ text: attr.name,
1987
+ shadows
1988
+ });
1739
1989
  }
1740
- for (const child of node.children) collectExpressionStrings(child, out);
1990
+ for (const child of node.children) collectExpressionStrings(child, out, shadows);
1741
1991
  return;
1742
1992
  }
1743
1993
  if (isControlNode(node)) {
1744
- out.push(node.statement);
1745
- for (const child of node.children) collectExpressionStrings(child, out);
1994
+ if (node.operation === "@for") {
1995
+ const nested = new Set(shadows);
1996
+ for (const name of forLoopVarNames(node.statement)) nested.add(name);
1997
+ for (const child of node.children) collectExpressionStrings(child, out, nested);
1998
+ return;
1999
+ }
2000
+ out.push({
2001
+ text: node.statement,
2002
+ shadows
2003
+ });
2004
+ for (const child of node.children) collectExpressionStrings(child, out, shadows);
1746
2005
  }
1747
2006
  }
1748
2007
  //#endregion
@@ -1833,24 +2092,6 @@ function collectDirect(nodes, out) {
1833
2092
  }
1834
2093
  }
1835
2094
  //#endregion
1836
- //#region src/compile/utils/trimMatched.ts
1837
- /**
1838
- * Trims chars from the start and end of the supplied text when both the start and end match
1839
- *
1840
- * @param text The text to trim
1841
- *
1842
- * @returns The text without the chars at the start or the end
1843
- */
1844
- function trimMatched(text, startChar, endChar) {
1845
- let start = 0;
1846
- let end = text.length;
1847
- while (text[start] === startChar && text[end - 1] === endChar) {
1848
- start += 1;
1849
- end -= 1;
1850
- }
1851
- return text.substring(start, end);
1852
- }
1853
- //#endregion
1854
2095
  //#region src/compile/build/client/addBuildError.ts
1855
2096
  /**
1856
2097
  * Adds an error to the build status. Mirrors `parse/utils/addError`, but is
@@ -1889,26 +2130,11 @@ function addBuildError(status, message, start, end = start) {
1889
2130
  }
1890
2131
  //#endregion
1891
2132
  //#region src/compile/build/client/buildForNode.ts
1892
- const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1893
- const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
1894
- const forOfRegex = /for\s*\(\s*(?:let\s*|var\s*){0,1}(.+?)\s+(?:of|in).*?\)/;
1895
2133
  function buildForNode(node, status, b) {
1896
2134
  const parentName = node.parentName;
1897
2135
  const anchorName = node.varName ?? "null";
1898
2136
  node = node.children[0];
1899
- const forVarNames = [];
1900
- const forLoopMatch = node.statement.match(forLoopRegex);
1901
- if (forLoopMatch) {
1902
- const forVarMatches = forLoopMatch[1].matchAll(forLoopVarsRegex);
1903
- for (let match of forVarMatches) forVarNames.push(match[1]);
1904
- } else {
1905
- const forOfMatch = node.statement.match(forOfRegex);
1906
- if (forOfMatch) {
1907
- const match = forOfMatch[1];
1908
- if (match.startsWith("{") && match.endsWith("}") || match.startsWith("[") && match.endsWith("]")) forVarNames.push(...trimMatched(trimMatched(match, "{", "}"), "[", "]").split(",").map((m) => m.trim()));
1909
- else forVarNames.push(match);
1910
- }
1911
- }
2137
+ const forVarNames = forLoopVarNames(node.statement);
1912
2138
  const regionName = nextVarName("for_region", status);
1913
2139
  const listItemsName = nextVarName("new_items", status);
1914
2140
  const itemName = nextVarName("item", status);
@@ -2238,6 +2464,24 @@ function buildSwitchBranch(node, status, b, parentName, regionName, indexName, i
2238
2464
  }`);
2239
2465
  }
2240
2466
  //#endregion
2467
+ //#region src/compile/utils/trimMatched.ts
2468
+ /**
2469
+ * Trims chars from the start and end of the supplied text when both the start and end match
2470
+ *
2471
+ * @param text The text to trim
2472
+ *
2473
+ * @returns The text without the chars at the start or the end
2474
+ */
2475
+ function trimMatched(text, startChar, endChar) {
2476
+ let start = 0;
2477
+ let end = text.length;
2478
+ while (text[start] === startChar && text[end - 1] === endChar) {
2479
+ start += 1;
2480
+ end -= 1;
2481
+ }
2482
+ return text.substring(start, end);
2483
+ }
2484
+ //#endregion
2241
2485
  //#region src/compile/build/client/buildTryNode.ts
2242
2486
  function buildTryNode(node, status, b) {
2243
2487
  const anchorName = node.varName ?? "null";
@@ -2903,11 +3147,11 @@ const importsMap$1 = {
2903
3147
  t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
2904
3148
  t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
2905
3149
  };
2906
- function buildCode(template, map, options, errors = []) {
3150
+ function buildCode(template, map, options, errors = [], warnings = []) {
2907
3151
  let b = new Builder(options?.mapped);
2908
3152
  let imports = /* @__PURE__ */ new Set();
2909
3153
  imports.add("SlotRender");
2910
- buildTemplate(template, map, imports, b, options, errors);
3154
+ buildTemplate(template, map, imports, b, options, errors, warnings);
2911
3155
  let startSize = b.toString().length;
2912
3156
  if (imports.size) {
2913
3157
  const folder = options?.renderFolder ?? "@torpor/view";
@@ -2924,7 +3168,7 @@ function buildCode(template, map, options, errors = []) {
2924
3168
  }
2925
3169
  return b.toString();
2926
3170
  }
2927
- function buildTemplate(template, map, imports, b, options, errors = []) {
3171
+ function buildTemplate(template, map, imports, b, options, errors = [], warnings = []) {
2928
3172
  let script = template.script.map((s) => s.script).join("\n");
2929
3173
  for (const component of template.components) {
2930
3174
  if (component.markup) script += "\n" + collectMarkupExpressions(component.markup);
@@ -2951,9 +3195,11 @@ function buildTemplate(template, map, imports, b, options, errors = []) {
2951
3195
  let current = template.components[0];
2952
3196
  let status = makeStatus(imports, map, current, options, errors);
2953
3197
  let first = true;
3198
+ let componentScript = [];
2954
3199
  for (let chunk of template.script) if (chunk.script === "/* @params */") {
2955
3200
  if (!first) status = makeStatus(imports, map, current, options, errors);
2956
3201
  first = false;
3202
+ componentScript = [];
2957
3203
  b.append(`
2958
3204
  ${current.markup ? "$parent" : "_$parent"}: ParentNode,
2959
3205
  ${current.markup ? "$anchor" : "_$anchor"}: Node | null,`);
@@ -2999,10 +3245,17 @@ function buildTemplate(template, map, imports, b, options, errors = []) {
2999
3245
  status.inHead = false;
3000
3246
  }
3001
3247
  } else if (chunk.script === "/* @style */") {} else if (chunk.script === "/* @end */") {
3248
+ if (current.markup && warnings !== void 0) warnings.push(...stalePropLets(componentScript, current.markup, options?.source));
3002
3249
  addPopDevBoundary(status, b);
3003
3250
  currentIndex += 1;
3004
3251
  current = template.components[currentIndex];
3005
- } else addMappedText("", chunk.script, "", chunk.span, status, b);
3252
+ } else {
3253
+ addMappedText("", chunk.script, "", chunk.span, status, b);
3254
+ componentScript.push({
3255
+ text: chunk.script,
3256
+ fileStart: chunk.span.start
3257
+ });
3258
+ }
3006
3259
  }
3007
3260
  function makeStatus(imports, map, current, options, errors = []) {
3008
3261
  return {
@@ -3142,7 +3395,7 @@ function buildServerComponentNode(node, status, b) {
3142
3395
  for (let slot of node.children) if (isSpecialNode(slot) && (slot.tagName === "fill" || slot.tagName === "filldef")) {
3143
3396
  const nameAttribute = slot.attributes.find((a) => a.name === "name");
3144
3397
  const slotName = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
3145
- const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", "$context?: Record<PropertyKey, any>"];
3398
+ const slotParams = [slot.hasSlotProps ? "$slot: Record<PropertyKey, any>" : "_$slot?: Record<PropertyKey, any>", fillUsesContext(slot) ? "$context?: Record<PropertyKey, any>" : "_$context?: Record<PropertyKey, any>"];
3146
3399
  b.append(`${slot.hasSlotProps ? "// @ts-ignore\n" : ""}${slotsName}["${slotName}"] = async (\n${slotParams.join(",\n")}\n) => {`);
3147
3400
  b.append(`let t_body = "";`);
3148
3401
  for (let child of slot.children) buildServerNode(child, status, b);
@@ -3381,7 +3634,9 @@ function buildServerElementNode(node, status, b) {
3381
3634
  if (!voidTags.includes(tagName)) {
3382
3635
  const oldPreserveWhitespace = status.preserveWhitespace;
3383
3636
  status.preserveWhitespace = ["pre", "code"].includes(tagName);
3637
+ if (!tagName.startsWith("@")) status.elementStack.push(tagName);
3384
3638
  for (let child of node.children) buildServerNode(child, status, b);
3639
+ if (!tagName.startsWith("@")) status.elementStack.pop();
3385
3640
  status.preserveWhitespace = oldPreserveWhitespace;
3386
3641
  status.output += `</${tagName}>`;
3387
3642
  }
@@ -3455,8 +3710,12 @@ function buildServerSlotNode(node, status, b) {
3455
3710
  for (let { name, value } of slotAttributes) if (value != null) b.append(`${propsName}["${name}"] = ${value};`);
3456
3711
  else b.append(`${propsName}["${name}"] = true;`);
3457
3712
  }
3713
+ const closeTags = status.elementStack.filter((tag) => AUTO_CLOSEABLE.has(tag));
3458
3714
  b.append(`if ($slots && $slots["${slotName}"]) {`);
3459
- b.append(`${status.inHead ? "t_head" : "t_body"} += await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context);`);
3715
+ if (closeTags.length > 0) {
3716
+ status.imports.add("t_slot_guard");
3717
+ b.append(`${status.inHead ? "t_head" : "t_body"} += t_slot_guard([${closeTags.map((tag) => `"${tag}"`).join(", ")}], await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context), "${slotName}");`);
3718
+ } else b.append(`${status.inHead ? "t_head" : "t_body"} += await $slots["${slotName}"](${slotHasProps ? propsName : "undefined"}, $context);`);
3460
3719
  const fill = node.children.find((c) => isSpecialNode(c) && (c.tagName === "fill" || c.tagName === "filldef"));
3461
3720
  if (fill && isSpecialNode(fill) && fill.children.length) {
3462
3721
  b.append(`} else {`);
@@ -3565,6 +3824,7 @@ const importsMap = {
3565
3824
  t_attr: "import { t_attr } from \"${folder}\";",
3566
3825
  t_class: "import { t_class } from \"${folder}\";",
3567
3826
  t_style: "import { t_style } from \"${folder}\";",
3827
+ t_slot_guard: "import { t_slot_guard } from \"${folder}\";",
3568
3828
  ServerSlotRender: "import { type ServerSlotRender } from \"${folder}\";"
3569
3829
  };
3570
3830
  function buildServerCode(template, options) {
@@ -3632,6 +3892,7 @@ function buildServerTemplate(template, imports, b, options) {
3632
3892
  varNames: {},
3633
3893
  preserveWhitespace: false,
3634
3894
  awaitCount: 0,
3895
+ elementStack: [],
3635
3896
  options
3636
3897
  };
3637
3898
  b.append("");
@@ -3656,6 +3917,7 @@ function buildServerTemplate(template, imports, b, options) {
3656
3917
  varNames: {},
3657
3918
  preserveWhitespace: false,
3658
3919
  awaitCount: 0,
3920
+ elementStack: [],
3659
3921
  options
3660
3922
  };
3661
3923
  b.append(`} catch (${current.errorVar}) {`);
@@ -3679,6 +3941,7 @@ function buildServerTemplate(template, imports, b, options) {
3679
3941
  preserveWhitespace: false,
3680
3942
  inHead: true,
3681
3943
  awaitCount: 0,
3944
+ elementStack: [],
3682
3945
  options
3683
3946
  };
3684
3947
  b.append("");
@@ -3833,16 +4096,1156 @@ function build(template, options) {
3833
4096
  }
3834
4097
  let map = [];
3835
4098
  let errors = [];
4099
+ let warnings = [];
3836
4100
  return {
3837
- code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options, errors),
4101
+ code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options, errors, warnings),
3838
4102
  styles: template.components.map((c) => c.style ? {
3839
4103
  style: buildStyles(c.style, c.style.hash),
3840
4104
  hash: c.style.hash
3841
4105
  } : void 0).filter((c) => c !== void 0),
3842
4106
  map,
4107
+ errors,
4108
+ warnings
4109
+ };
4110
+ }
4111
+ //#endregion
4112
+ //#region src/compile/build/restricted/scanState.ts
4113
+ /**
4114
+ * Matches `let|const|var <name> [type] = $watch(` at exactly the scan
4115
+ * position (sticky), tolerating a type annotation.
4116
+ */
4117
+ const DECLARATION = /(?:let|const|var)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?\s*=\s*\$watch\s*(?:<[^>(]*>)?\s*\(/y;
4118
+ /**
4119
+ * Finds `let <name> = $watch(<initializer>)` declarations in a component's
4120
+ * script chunks (restricted mode's client state). Scans the code with
4121
+ * strings, comments and regex literals skipped — so a `$watch` inside a
4122
+ * string never matches — and returns each initializer source with its
4123
+ * absolute offset, so it can be parsed into a restricted expression with
4124
+ * correct error positions.
4125
+ */
4126
+ function scanStateInitializers(chunks) {
4127
+ let text = "";
4128
+ const offsets = [];
4129
+ for (const chunk of chunks) {
4130
+ for (let i = 0; i < chunk.script.length; i++) offsets.push(chunk.span.start + i);
4131
+ text += chunk.script;
4132
+ }
4133
+ const results = [];
4134
+ let i = 0;
4135
+ while (i < text.length) {
4136
+ const skipped = skipStringOrComment(text, i);
4137
+ if (skipped !== -1) {
4138
+ i = skipped;
4139
+ continue;
4140
+ }
4141
+ DECLARATION.lastIndex = i;
4142
+ const match = DECLARATION.exec(text);
4143
+ if (match === null || match.index !== i) {
4144
+ i += 1;
4145
+ continue;
4146
+ }
4147
+ const name = match[1];
4148
+ const open = i + match[0].length - 1;
4149
+ let level = 0;
4150
+ let close = -1;
4151
+ let j = open;
4152
+ while (j < text.length) {
4153
+ const skipped = skipStringOrComment(text, j);
4154
+ if (skipped !== -1) {
4155
+ j = skipped;
4156
+ continue;
4157
+ }
4158
+ if (text[j] === "(") level += 1;
4159
+ else if (text[j] === ")") {
4160
+ level -= 1;
4161
+ if (level === 0) {
4162
+ close = j;
4163
+ break;
4164
+ }
4165
+ }
4166
+ j += 1;
4167
+ }
4168
+ if (close === -1) break;
4169
+ const initStart = open + 1;
4170
+ results.push({
4171
+ name,
4172
+ initSource: text.substring(initStart, close),
4173
+ start: offsets[initStart] ?? i
4174
+ });
4175
+ i = close;
4176
+ }
4177
+ return results;
4178
+ }
4179
+ //#endregion
4180
+ //#region src/compile/build/restricted/parseExpression.ts
4181
+ /**
4182
+ * Parses a restricted template expression into the serialized op set.
4183
+ *
4184
+ * This is intentionally a small, hand-written parser rather than a general
4185
+ * JS parser: the grammar *is* the restricted op set (the permanent format
4186
+ * API), so anything outside it is rejected with a positioned error instead
4187
+ * of being parsed and then policed. Regex-based tokenizing was rejected --
4188
+ * operators inside string literals and operator precedence make it
4189
+ * unsound.
4190
+ *
4191
+ * Supported: literals, identifiers (props/data/loop variables), property
4192
+ * and index access, unary `! - + typeof`, arithmetic/comparison/logic
4193
+ * (`* / %`, `+ -`, `< <= > >=`, `== != === !==`, `&&`, `||`, `??`),
4194
+ * ternaries, and array/object literals.
4195
+ *
4196
+ * Deliberately not supported (each gets a targeted error): calls (format
4197
+ * in `derive` instead), authored functions/arrows, `new`, `await`,
4198
+ * assignments and updates, optional chaining, template literals, spread.
4199
+ */
4200
+ var RestrictedSyntaxError = class extends Error {
4201
+ /** Absolute index (including the parser's offset) where the error starts. */
4202
+ start;
4203
+ /** Absolute index where the error ends. */
4204
+ end;
4205
+ constructor(message, start, end) {
4206
+ super(message);
4207
+ this.name = "RestrictedSyntaxError";
4208
+ this.start = start;
4209
+ this.end = end;
4210
+ }
4211
+ };
4212
+ const MULTI_PUNCT = [
4213
+ "===",
4214
+ "!==",
4215
+ "&&=",
4216
+ "||=",
4217
+ "??=",
4218
+ "...",
4219
+ "=>",
4220
+ "?.",
4221
+ "==",
4222
+ "!=",
4223
+ "<=",
4224
+ ">=",
4225
+ "&&",
4226
+ "||",
4227
+ "??",
4228
+ "++",
4229
+ "--",
4230
+ "+=",
4231
+ "-=",
4232
+ "*=",
4233
+ "/=",
4234
+ "%="
4235
+ ];
4236
+ const SINGLE_PUNCT = new Set("+-*/%!<>=?:.,()[]{}".split(""));
4237
+ const ASSIGNMENT = /* @__PURE__ */ new Set([
4238
+ "=",
4239
+ "+=",
4240
+ "-=",
4241
+ "*=",
4242
+ "/=",
4243
+ "%=",
4244
+ "&&=",
4245
+ "||=",
4246
+ "??="
4247
+ ]);
4248
+ /** Binary operators from lowest to highest precedence. */
4249
+ const BINARY_LEVELS = [
4250
+ ["??"],
4251
+ ["||"],
4252
+ ["&&"],
4253
+ [
4254
+ "==",
4255
+ "!=",
4256
+ "===",
4257
+ "!=="
4258
+ ],
4259
+ [
4260
+ "<",
4261
+ "<=",
4262
+ ">",
4263
+ ">="
4264
+ ],
4265
+ ["+", "-"],
4266
+ [
4267
+ "*",
4268
+ "/",
4269
+ "%"
4270
+ ]
4271
+ ];
4272
+ const UNARY_PUNCT = /* @__PURE__ */ new Set([
4273
+ "!",
4274
+ "-",
4275
+ "+"
4276
+ ]);
4277
+ const DANGEROUS_KEYS = /* @__PURE__ */ new Set([
4278
+ "__proto__",
4279
+ "prototype",
4280
+ "constructor"
4281
+ ]);
4282
+ const RESERVED = {
4283
+ new: "`new` isn't supported in restricted expressions.",
4284
+ await: "`await` isn't supported in restricted expressions; SSR data comes from `data` requirements.",
4285
+ this: "`this` isn't supported in restricted expressions.",
4286
+ super: "`super` isn't supported in restricted expressions.",
4287
+ function: "Function expressions aren't supported in restricted expressions.",
4288
+ class: "Classes aren't supported in restricted expressions.",
4289
+ yield: "`yield` isn't supported in restricted expressions.",
4290
+ delete: "`delete` isn't supported in restricted expressions.",
4291
+ void: "`void` isn't supported in restricted expressions.",
4292
+ in: "`in` isn't supported in restricted expressions.",
4293
+ instanceof: "`instanceof` isn't supported in restricted expressions.",
4294
+ const: "Declarations aren't supported in restricted expressions.",
4295
+ let: "Declarations aren't supported in restricted expressions.",
4296
+ var: "Declarations aren't supported in restricted expressions.",
4297
+ return: "`return` isn't supported in restricted expressions."
4298
+ };
4299
+ const CALLS_UNSUPPORTED = "Function calls aren't supported in restricted template expressions. Compute formatted/derived values in the data layer instead, e.g. `data view from derive { of: …, map: { formattedX: format($item.x) } }`, or have the host shape the requirement's result.";
4300
+ const ARROWS_UNSUPPORTED = "Arrow functions aren't supported in restricted expressions. Move the logic into a `derive` requirement, a host formatter, or the client build.";
4301
+ function tokenize(source, offset) {
4302
+ const tokens = [];
4303
+ let i = 0;
4304
+ const error = (message, start, end) => {
4305
+ throw new RestrictedSyntaxError(message, offset + start, offset + end);
4306
+ };
4307
+ while (i < source.length) {
4308
+ const char = source[i];
4309
+ if (char === " " || char === " " || char === "\n" || char === "\r") {
4310
+ i += 1;
4311
+ continue;
4312
+ }
4313
+ const start = i;
4314
+ if (char >= "0" && char <= "9") {
4315
+ i += 1;
4316
+ while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
4317
+ if (source[i] === "." && source[i + 1] >= "0" && source[i + 1] <= "9") {
4318
+ i += 1;
4319
+ while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
4320
+ }
4321
+ if (source[i] === "e" || source[i] === "E") {
4322
+ const exponentStart = i;
4323
+ i += 1;
4324
+ if (source[i] === "+" || source[i] === "-") i += 1;
4325
+ if (source[i] >= "0" && source[i] <= "9") while (i < source.length && source[i] >= "0" && source[i] <= "9") i += 1;
4326
+ else i = exponentStart;
4327
+ }
4328
+ tokens.push({
4329
+ type: "num",
4330
+ value: source.substring(start, i),
4331
+ start: offset + start,
4332
+ end: offset + i
4333
+ });
4334
+ continue;
4335
+ }
4336
+ if (char === "\"" || char === "'") {
4337
+ const quote = char;
4338
+ i += 1;
4339
+ let value = "";
4340
+ let closed = false;
4341
+ while (i < source.length) {
4342
+ const current = source[i];
4343
+ if (current === quote) {
4344
+ i += 1;
4345
+ closed = true;
4346
+ break;
4347
+ }
4348
+ if (current === "\n") break;
4349
+ if (current === "\\") {
4350
+ i += 1;
4351
+ const escape = source[i];
4352
+ if (escape === void 0) break;
4353
+ switch (escape) {
4354
+ case "n":
4355
+ value += "\n";
4356
+ break;
4357
+ case "r":
4358
+ value += "\r";
4359
+ break;
4360
+ case "t":
4361
+ value += " ";
4362
+ break;
4363
+ case "b":
4364
+ value += "\b";
4365
+ break;
4366
+ case "f":
4367
+ value += "\f";
4368
+ break;
4369
+ case "v":
4370
+ value += "\v";
4371
+ break;
4372
+ case "0":
4373
+ value += "\0";
4374
+ break;
4375
+ case "\\":
4376
+ value += "\\";
4377
+ break;
4378
+ case "'":
4379
+ value += "'";
4380
+ break;
4381
+ case "\"":
4382
+ value += "\"";
4383
+ break;
4384
+ case "u": {
4385
+ const hex = source.substring(i + 1, i + 5);
4386
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) error("Invalid unicode escape sequence", i - 1, i + 2);
4387
+ value += String.fromCharCode(parseInt(hex, 16));
4388
+ i += 4;
4389
+ break;
4390
+ }
4391
+ default: error(`Invalid escape sequence "\\${escape}"`, i - 1, i + 1);
4392
+ }
4393
+ i += 1;
4394
+ continue;
4395
+ }
4396
+ value += current;
4397
+ i += 1;
4398
+ }
4399
+ if (!closed) error("Unterminated string literal", start, i);
4400
+ tokens.push({
4401
+ type: "str",
4402
+ value,
4403
+ start: offset + start,
4404
+ end: offset + i
4405
+ });
4406
+ continue;
4407
+ }
4408
+ if (char === "`") error("Template literals aren't supported in restricted expressions; use string concatenation with `+`.", start, start + 1);
4409
+ if (char === "$" || char === "_" || /[A-Za-z]/.test(char)) {
4410
+ i += 1;
4411
+ while (i < source.length && /[A-Za-z0-9_$]/.test(source[i])) i += 1;
4412
+ tokens.push({
4413
+ type: "ident",
4414
+ value: source.substring(start, i),
4415
+ start: offset + start,
4416
+ end: offset + i
4417
+ });
4418
+ continue;
4419
+ }
4420
+ let matched;
4421
+ for (const punct of MULTI_PUNCT) if (source.startsWith(punct, i)) {
4422
+ matched = punct;
4423
+ break;
4424
+ }
4425
+ if (matched === void 0 && SINGLE_PUNCT.has(char)) matched = char;
4426
+ if (matched !== void 0) {
4427
+ i += matched.length;
4428
+ tokens.push({
4429
+ type: "punct",
4430
+ value: matched,
4431
+ start: offset + start,
4432
+ end: offset + i
4433
+ });
4434
+ continue;
4435
+ }
4436
+ error(`Unexpected character "${char}"`, start, start + 1);
4437
+ }
4438
+ tokens.push({
4439
+ type: "eof",
4440
+ value: "",
4441
+ start: offset + source.length,
4442
+ end: offset + source.length
4443
+ });
4444
+ return tokens;
4445
+ }
4446
+ /**
4447
+ * Parses one restricted expression.
4448
+ *
4449
+ * @param source The expression source text
4450
+ * @param offset The source index the expression starts at, so errors point
4451
+ * into the original file
4452
+ */
4453
+ function parseExpression(source, offset = 0, options) {
4454
+ return parseCore(source, offset, false, options).expression;
4455
+ }
4456
+ /**
4457
+ * Parses an expression that is followed by more text (e.g. a requirement
4458
+ * spec's `,` or the end of the spec). Returns where the expression ended so
4459
+ * callers can continue scanning.
4460
+ */
4461
+ function parseExpressionPrefix(source, offset = 0, options) {
4462
+ return parseCore(source, offset, true, options);
4463
+ }
4464
+ function parseCore(source, offset, allowTrailing, options) {
4465
+ const allowCalls = options?.allowCalls === true;
4466
+ const tokens = tokenize(source, offset);
4467
+ let index = 0;
4468
+ const peek = () => tokens[index];
4469
+ const next = () => tokens[index++];
4470
+ const error = (message, token = peek()) => {
4471
+ throw new RestrictedSyntaxError(message, token.start, token.end);
4472
+ };
4473
+ const expect = (value) => {
4474
+ const token = next();
4475
+ if (token.type === "eof" || token.value !== value) error(`Expected "${value}"${token.type === "eof" ? " but reached the end of the expression" : ` but found "${token.value}"`}`, token);
4476
+ return token;
4477
+ };
4478
+ const isPunct = (value) => peek().type === "punct" && peek().value === value;
4479
+ function parseTernary() {
4480
+ const test = parseBinary(0);
4481
+ if (!isPunct("?")) return test;
4482
+ next();
4483
+ const consequent = parseTernary();
4484
+ expect(":");
4485
+ return {
4486
+ op: "ternary",
4487
+ test,
4488
+ consequent,
4489
+ alternate: parseTernary()
4490
+ };
4491
+ }
4492
+ function parseBinary(level) {
4493
+ if (level >= BINARY_LEVELS.length) return parseUnary();
4494
+ const operators = BINARY_LEVELS[level];
4495
+ let left = parseBinary(level + 1);
4496
+ while (peek().type === "punct" && operators.includes(peek().value)) {
4497
+ const operator = next().value;
4498
+ const right = parseBinary(level + 1);
4499
+ left = {
4500
+ op: "binary",
4501
+ operator,
4502
+ left,
4503
+ right
4504
+ };
4505
+ }
4506
+ return left;
4507
+ }
4508
+ function parseUnary() {
4509
+ const token = peek();
4510
+ if (token.type === "punct" && UNARY_PUNCT.has(token.value) || token.type === "ident" && token.value === "typeof") {
4511
+ next();
4512
+ const operand = parseUnary();
4513
+ return {
4514
+ op: "unary",
4515
+ operator: token.value,
4516
+ operand
4517
+ };
4518
+ }
4519
+ return parsePostfix();
4520
+ }
4521
+ function parsePostfix() {
4522
+ let expression = parsePrimary();
4523
+ while (true) {
4524
+ const token = peek();
4525
+ if (token.type !== "punct") return expression;
4526
+ if (token.value === "." || token.value === "?.") {
4527
+ const optional = token.value === "?.";
4528
+ next();
4529
+ if (optional && peek().type === "punct" && peek().value === "[") {
4530
+ next();
4531
+ const indexExpr = parseTernary();
4532
+ expect("]");
4533
+ expression = {
4534
+ op: "index",
4535
+ object: expression,
4536
+ index: indexExpr,
4537
+ optional: true
4538
+ };
4539
+ continue;
4540
+ }
4541
+ const key = next();
4542
+ if (key.type !== "ident") error(`Expected a property name after "${token.value}"`, key);
4543
+ if (DANGEROUS_KEYS.has(key.value)) error(`Dangerous property name "${key.value}" isn't allowed in restricted expressions`, key);
4544
+ expression = optional ? {
4545
+ op: "get",
4546
+ object: expression,
4547
+ key: key.value,
4548
+ optional: true
4549
+ } : {
4550
+ op: "get",
4551
+ object: expression,
4552
+ key: key.value
4553
+ };
4554
+ continue;
4555
+ }
4556
+ if (token.value === "[") {
4557
+ next();
4558
+ const indexExpr = parseTernary();
4559
+ expect("]");
4560
+ expression = {
4561
+ op: "index",
4562
+ object: expression,
4563
+ index: indexExpr
4564
+ };
4565
+ continue;
4566
+ }
4567
+ if (token.value === "(") {
4568
+ if (!allowCalls) error(CALLS_UNSUPPORTED, token);
4569
+ if (expression.op !== "ref") error("Only named host functions can be called; method calls (a.b()) aren't supported in restricted expressions.", token);
4570
+ next();
4571
+ const args = [];
4572
+ while (!isPunct(")")) {
4573
+ if (peek().type === "eof") expect(")");
4574
+ args.push(parseTernary());
4575
+ if (isPunct(",")) next();
4576
+ }
4577
+ expect(")");
4578
+ expression = {
4579
+ op: "call",
4580
+ name: expression.name,
4581
+ args
4582
+ };
4583
+ continue;
4584
+ }
4585
+ if (token.value === "++" || token.value === "--") error("Updates (`++`/`--`) aren't supported in restricted expressions.", token);
4586
+ return expression;
4587
+ }
4588
+ }
4589
+ function parsePrimary() {
4590
+ const token = next();
4591
+ switch (token.type) {
4592
+ case "num": return {
4593
+ op: "lit",
4594
+ value: Number(token.value)
4595
+ };
4596
+ case "str": return {
4597
+ op: "lit",
4598
+ value: token.value
4599
+ };
4600
+ case "ident": {
4601
+ const name = token.value;
4602
+ if (name === "true") return {
4603
+ op: "lit",
4604
+ value: true
4605
+ };
4606
+ if (name === "false") return {
4607
+ op: "lit",
4608
+ value: false
4609
+ };
4610
+ if (name === "null" || name === "undefined") return {
4611
+ op: "lit",
4612
+ value: null
4613
+ };
4614
+ const reserved = RESERVED[name];
4615
+ if (reserved !== void 0) error(reserved, token);
4616
+ return {
4617
+ op: "ref",
4618
+ name
4619
+ };
4620
+ }
4621
+ case "punct":
4622
+ if (token.value === "(") {
4623
+ const expression = parseTernary();
4624
+ expect(")");
4625
+ return expression;
4626
+ }
4627
+ if (token.value === "[") {
4628
+ const items = [];
4629
+ while (!isPunct("]")) {
4630
+ if (peek().type === "eof") expect("]");
4631
+ if (isPunct(",")) {
4632
+ next();
4633
+ continue;
4634
+ }
4635
+ items.push(parseTernary());
4636
+ if (isPunct(",")) next();
4637
+ }
4638
+ expect("]");
4639
+ return {
4640
+ op: "array",
4641
+ items
4642
+ };
4643
+ }
4644
+ if (token.value === "{") {
4645
+ const entries = {};
4646
+ while (!isPunct("}")) {
4647
+ if (peek().type === "eof") expect("}");
4648
+ if (isPunct(",")) {
4649
+ next();
4650
+ continue;
4651
+ }
4652
+ const key = next();
4653
+ if (key.type !== "ident" && key.type !== "str" && key.type !== "num") error("Expected an object key (identifier, string or number)", key);
4654
+ if (DANGEROUS_KEYS.has(key.value)) error(`Dangerous property name "${key.value}" isn't allowed in restricted expressions`, key);
4655
+ expect(":");
4656
+ entries[key.value] = parseTernary();
4657
+ if (isPunct(",")) next();
4658
+ }
4659
+ expect("}");
4660
+ return {
4661
+ op: "object",
4662
+ entries
4663
+ };
4664
+ }
4665
+ if (token.value === "...") error("Spread isn't supported in restricted expressions.", token);
4666
+ if (token.value === "=>") error(ARROWS_UNSUPPORTED, token);
4667
+ if (ASSIGNMENT.has(token.value)) error("Assignments aren't supported in restricted expressions.", token);
4668
+ error(`Unexpected "${token.value}"`, token);
4669
+ }
4670
+ error("Unexpected end of expression", token);
4671
+ }
4672
+ const expression = parseTernary();
4673
+ const trailing = peek();
4674
+ if (trailing.type !== "eof" && !allowTrailing) {
4675
+ if (trailing.type === "punct" && trailing.value === "=>") error(ARROWS_UNSUPPORTED, trailing);
4676
+ if (trailing.type === "punct" && ASSIGNMENT.has(trailing.value)) error("Assignments aren't supported in restricted expressions.", trailing);
4677
+ if (trailing.type === "ident" && RESERVED[trailing.value] !== void 0) error(RESERVED[trailing.value], trailing);
4678
+ error(`Unexpected "${trailing.value}" after expression`, trailing);
4679
+ }
4680
+ return {
4681
+ expression,
4682
+ end: trailing.type === "eof" ? offset + source.length : trailing.start
4683
+ };
4684
+ }
4685
+ //#endregion
4686
+ //#region src/compile/build/restricted/buildRestricted.ts
4687
+ /**
4688
+ * Builds a template into a serialized restricted program: the server-side
4689
+ * instruction tree interpreted by `renderRestricted` (no `eval`, so it is
4690
+ * legal on workerd).
4691
+ *
4692
+ * Must be called on a **freshly parsed** template: it maps text
4693
+ * interpolations through the parse-time source spans. Trimming whitespace
4694
+ * nodes here is safe (only whitespace-only nodes change), and matches the
4695
+ * JS build; `build()` calling `trimWhitespace` again is idempotent.
4696
+ */
4697
+ function buildRestricted(template, options) {
4698
+ const source = options?.source ?? "";
4699
+ const errors = [];
4700
+ const report = (message, start, end = start) => {
4701
+ errors.push(compileError(message, start, end, source));
4702
+ };
4703
+ const components = [];
4704
+ const styles = [];
4705
+ for (let componentIndex = 0; componentIndex < template.components.length; componentIndex++) {
4706
+ const component = template.components[componentIndex];
4707
+ const styleHash = component.style?.hash ?? "";
4708
+ if (component.style) styles.push({
4709
+ style: buildStyles(component.style, styleHash),
4710
+ hash: styleHash
4711
+ });
4712
+ if (component.head) report("@head content isn't supported in restricted mode yet.", component.start ?? 0);
4713
+ if (component.error) report("@error blocks aren't supported in restricted mode yet.", component.start ?? 0);
4714
+ const state = [];
4715
+ const stateNames = [];
4716
+ const allowedRefs = /* @__PURE__ */ new Set(["$props", "$data"]);
4717
+ const context = {
4718
+ source,
4719
+ styleHash,
4720
+ preserveWhitespace: options?.preserveWhitespace === true,
4721
+ errors,
4722
+ report,
4723
+ allowedRefs,
4724
+ stateNames,
4725
+ loopVars: [],
4726
+ elementStack: []
4727
+ };
4728
+ if (component.markup && options?.preserveWhitespace !== true) trimWhitespace(component.markup);
4729
+ const nextStart = template.components[componentIndex + 1]?.scriptStart ?? template.script.length;
4730
+ const componentChunks = template.script.slice(component.scriptStart ?? 0, nextStart);
4731
+ for (const scanned of scanStateInitializers(componentChunks)) try {
4732
+ const init = parseExprAt(scanned.initSource, scanned.start, context);
4733
+ validateRefs(init, /* @__PURE__ */ new Set(["$props"]), context, scanned.start, `state initializer "${scanned.name}"`, []);
4734
+ state.push({
4735
+ name: scanned.name,
4736
+ init
4737
+ });
4738
+ stateNames.push(scanned.name);
4739
+ allowedRefs.add(scanned.name);
4740
+ } catch (error) {
4741
+ if (error instanceof RestrictedSyntaxError) report(error.message, error.start, error.end);
4742
+ else throw error;
4743
+ }
4744
+ const markup = component.markup ? serializeChildren(component.markup.children, context) : [];
4745
+ components.push({
4746
+ name: component.name,
4747
+ default: component.default,
4748
+ markup,
4749
+ state: state.length > 0 ? state : void 0
4750
+ });
4751
+ }
4752
+ errors.sort((a, b) => a.startIndex - b.startIndex);
4753
+ return {
4754
+ program: {
4755
+ requirements: [],
4756
+ components
4757
+ },
4758
+ styles,
3843
4759
  errors
3844
4760
  };
3845
4761
  }
4762
+ function compileError(message, start, end, source) {
4763
+ let startLine = 0;
4764
+ let lastLineStart = 0;
4765
+ let i = 0;
4766
+ for (; i < start && i < source.length; i++) if (source[i] === "\n") {
4767
+ startLine += 1;
4768
+ lastLineStart = i + 1;
4769
+ }
4770
+ const startChar = start - lastLineStart;
4771
+ let endLine = startLine;
4772
+ for (; i < end && i < source.length; i++) if (source[i] === "\n") {
4773
+ endLine += 1;
4774
+ lastLineStart = i + 1;
4775
+ }
4776
+ return {
4777
+ message,
4778
+ startIndex: start,
4779
+ startLine,
4780
+ startChar,
4781
+ endIndex: end,
4782
+ endLine,
4783
+ endChar: end - lastLineStart
4784
+ };
4785
+ }
4786
+ function serializeChildren(nodes, context) {
4787
+ const result = [];
4788
+ for (const node of nodes) {
4789
+ const serialized = serializeNode(node, context);
4790
+ if (serialized !== void 0) result.push(serialized);
4791
+ }
4792
+ return result;
4793
+ }
4794
+ function serializeNode(node, context) {
4795
+ if (isTextNode(node)) return serializeText(node, context);
4796
+ if (isControlNode(node)) return serializeControl(node, context);
4797
+ if (node.type === "comment") return;
4798
+ if (isComponentNode(node)) return serializeComponent(node, context);
4799
+ if (isSpecialNode(node)) {
4800
+ if (node.tagName === "slot") return serializeSlotElement(node, context);
4801
+ context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4802
+ return;
4803
+ }
4804
+ return serializeElement(node, context);
4805
+ }
4806
+ /** Component attributes: static values and fully-reactive expressions only. */
4807
+ function serializeComponentProps(node, context) {
4808
+ const attributes = [];
4809
+ let needsClass = node.scopeStyles === true && context.styleHash !== "";
4810
+ for (const attribute of node.attributes) {
4811
+ const { name, value, fullyReactive, reactive } = attribute;
4812
+ if (name.startsWith("on") || name.startsWith(":on")) continue;
4813
+ if (name.startsWith("&")) {
4814
+ context.report(`Bindings ("${name}") aren't supported on components in restricted mode.`, attribute.span.start, attribute.span.end);
4815
+ continue;
4816
+ }
4817
+ if (name.startsWith(":")) {
4818
+ context.report(`Directives ("${name}") aren't supported on components in restricted mode.`, attribute.span.start, attribute.span.end);
4819
+ continue;
4820
+ }
4821
+ if (value === void 0) {
4822
+ attributes.push({ name });
4823
+ continue;
4824
+ }
4825
+ if (fullyReactive) {
4826
+ const expr = parseExprAt(value, attribute.span.start, context);
4827
+ if (name === "class" && needsClass) {
4828
+ attributes.push({
4829
+ name,
4830
+ expr,
4831
+ scoped: `torp-${context.styleHash}`
4832
+ });
4833
+ needsClass = false;
4834
+ } else attributes.push({
4835
+ name,
4836
+ expr
4837
+ });
4838
+ } else if (reactive) context.report(`Mixed static/dynamic prop values aren't supported in restricted mode; compute the whole "${name}" value with an expression.`, attribute.span.start, attribute.span.end);
4839
+ else {
4840
+ const literal = trimQuotes(value);
4841
+ if (name === "class" && needsClass) {
4842
+ attributes.push({
4843
+ name,
4844
+ value: literal,
4845
+ scoped: `torp-${context.styleHash}`
4846
+ });
4847
+ needsClass = false;
4848
+ } else attributes.push({
4849
+ name,
4850
+ value: literal
4851
+ });
4852
+ }
4853
+ }
4854
+ return attributes;
4855
+ }
4856
+ /**
4857
+ * Component children are slot fills: loose children become the default fill
4858
+ * (`_`) and `<fill name="x">` children become named fills. Fill children may
4859
+ * read `$slot.<name>` for the slot props the host component passes; other
4860
+ * attributes on fills aren't supported.
4861
+ */
4862
+ function serializeComponent(node, context) {
4863
+ const fills = [];
4864
+ const defaultFill = [];
4865
+ const fillContext = {
4866
+ ...context,
4867
+ allowedRefs: /* @__PURE__ */ new Set([...context.allowedRefs, "$slot"]),
4868
+ elementStack: []
4869
+ };
4870
+ for (const child of node.children) if (isFill(child)) {
4871
+ if (child.attributes.filter((attribute) => attribute.name !== "name").length > 0) {
4872
+ context.report(`Unexpected attributes on <fill>. Slot props are read as $slot.<name> inside the fill; only "name" is allowed here.`, child.span.start, child.span.end);
4873
+ continue;
4874
+ }
4875
+ const nameAttribute = child.attributes.find((attribute) => attribute.name === "name");
4876
+ const name = nameAttribute ? trimQuotes(nameAttribute.value ?? "") || "_" : "_";
4877
+ fills.push({
4878
+ name,
4879
+ children: serializeChildren(child.children, fillContext)
4880
+ });
4881
+ } else if (isTextNode(child) && child.content.trim() === "") continue;
4882
+ else {
4883
+ const serialized = serializeNode(child, fillContext);
4884
+ if (serialized !== void 0) defaultFill.push(serialized);
4885
+ }
4886
+ if (defaultFill.length > 0) fills.unshift({
4887
+ name: "_",
4888
+ children: defaultFill
4889
+ });
4890
+ return {
4891
+ t: "component",
4892
+ name: node.tagName,
4893
+ props: serializeComponentProps(node, context),
4894
+ fills
4895
+ };
4896
+ }
4897
+ function isFill(node) {
4898
+ return isSpecialNode(node) && (node.tagName === "fill" || node.tagName === "filldef");
4899
+ }
4900
+ /** `<slot name="…">fallback</slot>` in a restricted template. Slot props
4901
+ * (`<slot item={row}/>` — anything but `name`) are evaluated in the
4902
+ * artifact's scope and passed to the incoming slot render, matching the JS
4903
+ * server build. */
4904
+ function serializeSlotElement(node, context) {
4905
+ const nameAttribute = node.attributes.find((attribute) => attribute.name === "name");
4906
+ const name = nameAttribute?.value ? trimQuotes(nameAttribute.value) : "_";
4907
+ const props = [];
4908
+ for (const attribute of node.attributes) {
4909
+ const { name: propName, value, fullyReactive, reactive } = attribute;
4910
+ if (propName === "name") continue;
4911
+ if (propName.startsWith("on") || propName.startsWith(":on")) continue;
4912
+ if (propName.startsWith("&")) {
4913
+ context.report(`Bindings ("${propName}") aren't supported on slot elements in restricted mode.`, attribute.span.start, attribute.span.end);
4914
+ continue;
4915
+ }
4916
+ if (propName.startsWith(":")) {
4917
+ context.report(`Directives ("${propName}") aren't supported on slot elements in restricted mode.`, attribute.span.start, attribute.span.end);
4918
+ continue;
4919
+ }
4920
+ if (value === void 0) {
4921
+ props.push({ name: propName });
4922
+ continue;
4923
+ }
4924
+ if (fullyReactive) props.push({
4925
+ name: propName,
4926
+ expr: parseExprAt(value, attribute.span.start, context)
4927
+ });
4928
+ else if (reactive) context.report(`Mixed static/dynamic slot prop values aren't supported in restricted mode; compute the whole "${propName}" value with an expression.`, attribute.span.start, attribute.span.end);
4929
+ else props.push({
4930
+ name: propName,
4931
+ value: trimQuotes(value)
4932
+ });
4933
+ }
4934
+ const autoClose = context.elementStack.filter((tag) => AUTO_CLOSEABLE.has(tag));
4935
+ const fallbackTag = firstFallbackTag(node.children);
4936
+ if (fallbackTag !== void 0 && closesAncestor(fallbackTag, context.elementStack)) {
4937
+ const ancestor = [...context.elementStack].reverse().find((ancestor) => closesAncestor(fallbackTag, [ancestor]));
4938
+ context.report(`Slot fallback starts with <${fallbackTag}>, which auto-closes the enclosing <${ancestor}>: ` + autoCloseMessage(fallbackTag, ancestor), node.span.start, node.span.end);
4939
+ }
4940
+ const children = [];
4941
+ for (const child of node.children) if (isFill(child)) children.push(...serializeChildren(child.children, context));
4942
+ else {
4943
+ const serialized = serializeNode(child, context);
4944
+ if (serialized !== void 0) children.push(serialized);
4945
+ }
4946
+ const slot = {
4947
+ t: "slot",
4948
+ name,
4949
+ props,
4950
+ children
4951
+ };
4952
+ if (autoClose.length > 0) slot.autoClose = autoClose;
4953
+ return slot;
4954
+ }
4955
+ /** The tag of the first meaningful child (skipping whitespace text). */
4956
+ function firstFallbackTag(children) {
4957
+ for (const child of children) {
4958
+ if (isFill(child)) return firstFallbackTag(child.children);
4959
+ if (isTextNode(child)) {
4960
+ if (child.content.trim() === "") continue;
4961
+ return;
4962
+ }
4963
+ if (child.type === "element") return child.tagName;
4964
+ return;
4965
+ }
4966
+ }
4967
+ function serializeElement(node, context) {
4968
+ if (node.type === "component") {
4969
+ context.report(`Nested components ("<${node.tagName}>") aren't supported in restricted mode yet. Inline the markup, or render it client-side.`, node.span.start, node.span.end);
4970
+ return;
4971
+ }
4972
+ if (node.type === "special") {
4973
+ context.report(`Special elements ("<${node.tagName}>") aren't supported in restricted mode yet.`, node.span.start, node.span.end);
4974
+ return;
4975
+ }
4976
+ const childContext = node.tagName === "pre" || node.tagName === "code" ? {
4977
+ ...context,
4978
+ preserveWhitespace: true
4979
+ } : context;
4980
+ if (!voidTags.includes(node.tagName)) childContext.elementStack.push(node.tagName);
4981
+ const children = voidTags.includes(node.tagName) ? [] : serializeChildren(node.children, childContext);
4982
+ if (!voidTags.includes(node.tagName)) childContext.elementStack.pop();
4983
+ return {
4984
+ t: "el",
4985
+ tag: node.tagName,
4986
+ attrs: serializeAttributes(node, context),
4987
+ children
4988
+ };
4989
+ }
4990
+ function serializeAttributes(node, context) {
4991
+ const attributes = [];
4992
+ let needsClass = node.scopeStyles === true && context.styleHash !== "";
4993
+ for (const attribute of node.attributes) {
4994
+ const { name, value, fullyReactive, reactive } = attribute;
4995
+ if (name === "self" && node.tagName === "@element") continue;
4996
+ if (name === "&ref") continue;
4997
+ if (name.startsWith("on") || name.startsWith(":on")) continue;
4998
+ if (name.startsWith("transition")) continue;
4999
+ if (name.startsWith("&")) {
5000
+ context.report(`Form bindings ("${name}") aren't supported in restricted mode yet; use ${name.substring(1)}={…} instead.`, attribute.span.start, attribute.span.end);
5001
+ continue;
5002
+ }
5003
+ if (name.startsWith(":")) {
5004
+ context.report(`Directives ("${name}") aren't supported in restricted mode yet.`, attribute.span.start, attribute.span.end);
5005
+ continue;
5006
+ }
5007
+ if (value === void 0) {
5008
+ if (name === "class" && needsClass) {
5009
+ attributes.push({
5010
+ name: "class",
5011
+ value: `torp-${context.styleHash}`
5012
+ });
5013
+ needsClass = false;
5014
+ } else attributes.push({ name });
5015
+ continue;
5016
+ }
5017
+ if (fullyReactive) {
5018
+ const expr = parseExprAt(value, attribute.span.start, context);
5019
+ if (name === "class") {
5020
+ attributes.push({
5021
+ name,
5022
+ expr,
5023
+ format: "class",
5024
+ scoped: needsClass ? `torp-${context.styleHash}` : void 0
5025
+ });
5026
+ needsClass = false;
5027
+ } else if (name === "style") attributes.push({
5028
+ name,
5029
+ expr,
5030
+ format: "style"
5031
+ });
5032
+ else attributes.push({
5033
+ name,
5034
+ expr,
5035
+ format: "attr"
5036
+ });
5037
+ } else if (reactive) context.report(`Mixed static/dynamic attribute values aren't supported in restricted mode; compute the whole "${name}" value with an expression.`, attribute.span.start, attribute.span.end);
5038
+ else {
5039
+ let literal = trimQuotes(value);
5040
+ if (name === "class" && needsClass) {
5041
+ literal = literal ? `${literal} torp-${context.styleHash}` : `torp-${context.styleHash}`;
5042
+ needsClass = false;
5043
+ }
5044
+ attributes.push({
5045
+ name,
5046
+ value: literal
5047
+ });
5048
+ }
5049
+ }
5050
+ if (needsClass) attributes.push({
5051
+ name: "class",
5052
+ value: `torp-${context.styleHash}`
5053
+ });
5054
+ return attributes;
5055
+ }
5056
+ function serializeText(node, context) {
5057
+ const parts = [];
5058
+ const pushLiteral = (literal) => {
5059
+ const collapsed = context.preserveWhitespace ? literal : literal.replace(/\s+/g, " ");
5060
+ if (collapsed.length === 0) return;
5061
+ const last = parts[parts.length - 1];
5062
+ if (typeof last === "string") parts[parts.length - 1] = last + collapsed;
5063
+ else parts.push(collapsed);
5064
+ };
5065
+ if (node.spans.length === 0 || node.start === void 0) pushLiteral(node.content);
5066
+ else {
5067
+ const start = node.start;
5068
+ let cursor = 0;
5069
+ for (const span of node.spans) {
5070
+ const literalEnd = span.start - start - 1;
5071
+ pushLiteral(node.content.substring(cursor, literalEnd));
5072
+ parts.push(parseExprAt(context.source.substring(span.start, span.end), span.start, context));
5073
+ cursor = span.end - start + 1;
5074
+ }
5075
+ pushLiteral(node.content.substring(cursor));
5076
+ }
5077
+ if (parts.length === 0) return void 0;
5078
+ return {
5079
+ t: "text",
5080
+ parts
5081
+ };
5082
+ }
5083
+ function serializeControl(node, context) {
5084
+ if (node.operation === "@if group") return {
5085
+ t: "if",
5086
+ branches: node.children.filter(isControlNode).map((branch) => {
5087
+ if (branch.operation === "@else") return { children: serializeChildren(branch.children, context) };
5088
+ const statement = branch.statement;
5089
+ const open = statement.indexOf("(");
5090
+ if (open === -1) {
5091
+ context.report(`Malformed ${branch.operation} statement.`, branch.span.start, branch.span.end);
5092
+ return {
5093
+ test: {
5094
+ op: "lit",
5095
+ value: null
5096
+ },
5097
+ children: []
5098
+ };
5099
+ }
5100
+ const { inner, innerStart } = extractBalanced(statement, open, branch, context);
5101
+ return {
5102
+ test: parseExprAt(inner, branch.span.start + innerStart, context),
5103
+ children: serializeChildren(branch.children, context)
5104
+ };
5105
+ })
5106
+ };
5107
+ if (node.operation === "@for group") {
5108
+ const forNode = node.children.find((child) => isControlNode(child) && child.operation === "@for");
5109
+ if (!forNode) {
5110
+ context.report("Malformed @for block.", node.span.start, node.span.end);
5111
+ return;
5112
+ }
5113
+ const open = forNode.statement.indexOf("(");
5114
+ if (open === -1) {
5115
+ context.report("Malformed @for statement.", forNode.span.start, forNode.span.end);
5116
+ return;
5117
+ }
5118
+ const { inner, innerStart } = extractBalanced(forNode.statement, open, forNode, context);
5119
+ const match = /^\s*(?:(?:let|const|var)\s+)?([A-Za-z_$][\w$]*)\s+(of|in)\s+([\s\S]+)$/.exec(inner);
5120
+ if (!match) {
5121
+ context.report("Only `@for (item of list)` is supported in restricted mode yet (no destructuring, index variables, or C-style loops).", forNode.span.start, forNode.span.end);
5122
+ return;
5123
+ }
5124
+ if (match[2] === "in") {
5125
+ context.report("`in` loops aren't supported in restricted mode; use `of`.", forNode.span.start, forNode.span.end);
5126
+ return;
5127
+ }
5128
+ const item = match[1];
5129
+ const listSource = match[3].trim();
5130
+ const listIndex = inner.lastIndexOf(listSource);
5131
+ const list = parseExprAt(listSource, forNode.span.start + innerStart + listIndex, context);
5132
+ const keyNode = forNode.children.find((child) => isControlNode(child) && child.operation === "@key");
5133
+ let key;
5134
+ if (keyNode) {
5135
+ const keyContext = {
5136
+ ...context,
5137
+ loopVars: [...context.loopVars, item]
5138
+ };
5139
+ const equal = keyNode.statement.indexOf("=");
5140
+ const keySource = keyNode.statement.substring(equal + 1).replace(/;\s*$/, "").trim();
5141
+ key = parseExprAt(keySource, keyNode.span.start + keyNode.statement.indexOf(keySource), keyContext);
5142
+ }
5143
+ const childContext = {
5144
+ ...context,
5145
+ loopVars: [...context.loopVars, item]
5146
+ };
5147
+ return {
5148
+ t: "for",
5149
+ item,
5150
+ list,
5151
+ key,
5152
+ children: serializeChildren(forNode.children.filter((child) => !(isControlNode(child) && child.operation === "@key")), childContext)
5153
+ };
5154
+ }
5155
+ context.report(`"${node.operation}" isn't supported in restricted mode yet.`, controlSpan(node).start, controlSpan(node).end);
5156
+ }
5157
+ /** Group nodes (`@if group`, `@html group`…) carry zero spans; their first
5158
+ * control child has the real source span. */
5159
+ function controlSpan(node) {
5160
+ if (node.span.start === 0 && node.span.end === 0) {
5161
+ const child = node.children.find(isControlNode);
5162
+ if (child) return child.span;
5163
+ }
5164
+ return node.span;
5165
+ }
5166
+ /**
5167
+ * Extracts the text between `source[open]` and its matching `)`, skipping
5168
+ * strings and comments. `innerStart` is the index just after the `(`.
5169
+ */
5170
+ function extractBalanced(source, open, node, context) {
5171
+ let level = 0;
5172
+ for (let i = open; i < source.length; i++) {
5173
+ const skipped = skipStringOrComment(source, i);
5174
+ if (skipped !== -1) {
5175
+ i = skipped - 1;
5176
+ continue;
5177
+ }
5178
+ if (source[i] === "(") level += 1;
5179
+ else if (source[i] === ")") {
5180
+ level -= 1;
5181
+ if (level === 0) return {
5182
+ inner: source.substring(open + 1, i),
5183
+ innerStart: open + 1
5184
+ };
5185
+ }
5186
+ }
5187
+ context.report("Unbalanced parentheses in a control statement.", node.span.start, node.span.end);
5188
+ return {
5189
+ inner: source.substring(open + 1),
5190
+ innerStart: open + 1
5191
+ };
5192
+ }
5193
+ function parseExprAt(source, offset, context) {
5194
+ try {
5195
+ const expr = parseExpression(source, offset);
5196
+ validateRefs(expr, context.allowedRefs, context, offset, "template");
5197
+ return expr;
5198
+ } catch (error) {
5199
+ if (error instanceof RestrictedSyntaxError) {
5200
+ context.report(error.message, error.start, error.end);
5201
+ return {
5202
+ op: "lit",
5203
+ value: null
5204
+ };
5205
+ }
5206
+ throw error;
5207
+ }
5208
+ }
5209
+ /**
5210
+ * Validates that every identifier reference in a serialized expression is
5211
+ * available in the scope the interpreter will run it with -- so typos and
5212
+ * unknown roots are compile errors instead of render errors.
5213
+ */
5214
+ function validateRefs(expr, allowed, context, start, where, loopVars = context.loopVars) {
5215
+ switch (expr.op) {
5216
+ case "ref":
5217
+ if (!allowed.has(expr.name) && !loopVars.includes(expr.name)) {
5218
+ const available = [...allowed, ...loopVars].join(", ");
5219
+ context.report(`Unknown identifier "${expr.name}" in ${where}. Available: ${available || "(none)"}.`, start, start + expr.name.length + 2);
5220
+ }
5221
+ return;
5222
+ case "get":
5223
+ validateRefs(expr.object, allowed, context, start, where, loopVars);
5224
+ return;
5225
+ case "index":
5226
+ validateRefs(expr.object, allowed, context, start, where, loopVars);
5227
+ validateRefs(expr.index, allowed, context, start, where, loopVars);
5228
+ return;
5229
+ case "unary":
5230
+ validateRefs(expr.operand, allowed, context, start, where, loopVars);
5231
+ return;
5232
+ case "binary":
5233
+ validateRefs(expr.left, allowed, context, start, where, loopVars);
5234
+ validateRefs(expr.right, allowed, context, start, where, loopVars);
5235
+ return;
5236
+ case "ternary":
5237
+ validateRefs(expr.test, allowed, context, start, where, loopVars);
5238
+ validateRefs(expr.consequent, allowed, context, start, where, loopVars);
5239
+ validateRefs(expr.alternate, allowed, context, start, where, loopVars);
5240
+ return;
5241
+ case "array":
5242
+ for (const item of expr.items) validateRefs(item, allowed, context, start, where, loopVars);
5243
+ return;
5244
+ case "object":
5245
+ for (const value of Object.values(expr.entries)) validateRefs(value, allowed, context, start, where, loopVars);
5246
+ return;
5247
+ }
5248
+ }
3846
5249
  //#endregion
3847
5250
  //#region src/compile/buildType.ts
3848
5251
  /**
@@ -4236,12 +5639,14 @@ function parseText(status, element) {
4236
5639
  if (content || spaceContent) {
4237
5640
  const previousNode = element.children[element.children.length - 1];
4238
5641
  if (previousNode && isTextNode(previousNode)) {
5642
+ if (previousNode.start === void 0) previousNode.start = start - previousNode.content.length;
4239
5643
  previousNode.content += content + spaceContent;
4240
5644
  previousNode.spans.push(...spans);
4241
5645
  } else {
4242
5646
  const text = {
4243
5647
  type: "text",
4244
5648
  content: content + spaceContent,
5649
+ start,
4245
5650
  spans
4246
5651
  };
4247
5652
  element.children.push(text);
@@ -5318,39 +6723,6 @@ function getPropsUsage(source, ranges) {
5318
6723
  }
5319
6724
  return props.length ? props : void 0;
5320
6725
  }
5321
- /**
5322
- * Gets the `$context` names that the compiled output references. The input is
5323
- * the component's code-only text (script plus markup expressions), with
5324
- * `ranges` marking the positions that are code — matches that start inside a
5325
- * string, comment or regex literal are ignored, so mentions inside
5326
- * sample-code strings or prose don't count.
5327
- */
5328
- function getContextUsage(source, ranges) {
5329
- const contextsMatches = source.matchAll(/\$context\??\s*(?:\.([\d\w]+)|\[([^\]]+)\])/g);
5330
- const contexts = [];
5331
- for (let match of contextsMatches) {
5332
- if (!isInCode(ranges, match.index)) continue;
5333
- const name = trimQuotes(match[1] || match[2]);
5334
- if (!contexts.includes(name)) contexts.push(name);
5335
- }
5336
- if (!contexts.length) for (let match of source.matchAll(/(?<![\w$])\$context(?![\w])(?!\s*:)(?!<)/g)) {
5337
- if (!isInCode(ranges, match.index)) continue;
5338
- contexts.push("$context");
5339
- break;
5340
- }
5341
- return contexts.length ? contexts : void 0;
5342
- }
5343
- /**
5344
- * Returns true if `index` falls inside one of the (sorted, non-overlapping)
5345
- * code ranges — i.e. not inside a string, comment or regex literal.
5346
- */
5347
- function isInCode(ranges, index) {
5348
- for (const [start, end] of ranges) {
5349
- if (index >= start && index < end) return true;
5350
- if (index < start) return false;
5351
- }
5352
- return false;
5353
- }
5354
6726
  function consumeScriptComments(status) {
5355
6727
  const skipped = skipStringOrComment(status.source, status.i);
5356
6728
  if (skipped !== -1) {
@@ -5373,6 +6745,27 @@ function parse(source) {
5373
6745
  return parseCode(source);
5374
6746
  }
5375
6747
  //#endregion
5376
- export { build, buildType, parse };
6748
+ //#region src/compile/parse/bindDataTemplate.ts
6749
+ /**
6750
+ * Binds `$data` in a parsed template whose requirements come from an app
6751
+ * manifest (see `@torpor/embed/app`): inserts the `let $data = …` chunk
6752
+ * after the start-marker chunk and keeps `$props` from being renamed as an
6753
+ * unused param. Without it, builds reference an undeclared `$data`.
6754
+ */
6755
+ function bindDataTemplate(template) {
6756
+ for (let i = 0; i < template.script.length; i++) if (template.script[i].script === "/* @start */") {
6757
+ template.script.splice(i + 1, 0, {
6758
+ script: " let $data = $props?.$data ?? {};",
6759
+ span: {
6760
+ start: 0,
6761
+ end: 0
6762
+ }
6763
+ });
6764
+ i += 1;
6765
+ }
6766
+ for (const component of template.components) if (!component.props?.length) component.props = ["$data"];
6767
+ }
6768
+ //#endregion
6769
+ export { RestrictedSyntaxError, bindDataTemplate, build, buildRestricted, buildType, parse, parseExpressionPrefix };
5377
6770
 
5378
6771
  //# sourceMappingURL=compile.mjs.map