@torpor/view 1.1.3 → 1.2.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.
package/dist/compile.cjs CHANGED
@@ -751,6 +751,157 @@ function addMappedTextWithOffsets(preText, text, postText, spans, offsets, lengt
751
751
  } else b.append(preText + text + postText);
752
752
  }
753
753
  //#endregion
754
+ //#region src/compile/utils/containsIdentifier.ts
755
+ /**
756
+ * Whether `name` appears in `value` as a standalone identifier (not as part
757
+ * of a longer identifier or a property access). Used to decide which loop
758
+ * variables a chunk of generated code actually references.
759
+ */
760
+ function containsIdentifier(value, name) {
761
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
762
+ return new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`).test(value);
763
+ }
764
+ //#endregion
765
+ //#region src/compile/build/client/forVars.ts
766
+ /**
767
+ * Returns the per-scope shadow bindings for every read-only loop variable in
768
+ * scope (`const <name> = <dataPath>;`), one per line, or `""` when there are
769
+ * none.
770
+ *
771
+ * The hook is that a `@for` body's user code is emitted inside a number of
772
+ * compiler-generated scopes (`$run` effects, event handlers, control-node
773
+ * callbacks, the row-create callback, …). Emitting the bindings at the top of
774
+ * each scope makes the loop variable resolve lexically, so shadowing
775
+ * (`arr.filter(child => child.ok)`) and no-space operator styles just work —
776
+ * unlike the old textual substitution, which had no notion of scope.
777
+ *
778
+ * The binding is re-created on every invocation of the scope, so reads stay
779
+ * live and tracked (in the proxy path, reading `<dataPath>` subscribes the
780
+ * effect to the loop variable's signal).
781
+ */
782
+ function forVarBindings(status, source) {
783
+ return collectBindings(status, (forVar) => source === void 0 || containsIdentifier(source, forVar.name));
784
+ }
785
+ /**
786
+ * Like `forVarBindings`, but binds only the loop variables named in `names`.
787
+ * Used for the row-create scope, where a separate scan decides which variables
788
+ * the scope's directly-evaluated code reads.
789
+ */
790
+ function forVarBindingsFor(status, names) {
791
+ return collectBindings(status, (forVar) => names.has(forVar.name));
792
+ }
793
+ function collectBindings(status, include) {
794
+ const bound = /* @__PURE__ */ new Set();
795
+ let result = "";
796
+ for (let i = status.forVars.length - 1; i >= 0; i--) {
797
+ const forVar = status.forVars[i];
798
+ if (!forVar.shadow || bound.has(forVar.name) || !include(forVar)) continue;
799
+ bound.add(forVar.name);
800
+ result = `const ${forVar.name} = ${forVar.path};\n` + result;
801
+ }
802
+ return result;
803
+ }
804
+ /**
805
+ * Appends the shadow bindings for `status` to the builder, if there are any.
806
+ * (A bare `b.append("")` would still emit a blank line.)
807
+ */
808
+ function appendForVarBindings(b, status, source) {
809
+ const bindings = forVarBindings(status, source);
810
+ if (bindings !== "") b.append(bindings);
811
+ }
812
+ /** Appends the shadow bindings for the named loop variables, if there are any. */
813
+ function appendForVarBindingsFor(b, status, names) {
814
+ const bindings = forVarBindingsFor(status, names);
815
+ if (bindings !== "") b.append(bindings);
816
+ }
817
+ /**
818
+ * Adds the shadow bindings *inside* a user-supplied function expression (an
819
+ * event handler, transition factory, …), at invocation time, rather than
820
+ * letting them be captured from the enclosing row scope.
821
+ *
822
+ * This matters because these callbacks are created once (when the row is
823
+ * created) but invoked later — a binding captured from the row scope would
824
+ * snapshot the loop variable and go stale after keyed reconciliation
825
+ * replaces the row's data.
826
+ *
827
+ * When the expression is a plain arrow / function (the common case) the
828
+ * bindings are injected into its body, so no extra closure is allocated. Any
829
+ * other expression (a call returning a handler, a conditional, …) is wrapped
830
+ * in a passthrough closure instead.
831
+ */
832
+ function injectForVarHandler(value, status) {
833
+ const bindings = forVarBindings(status, value);
834
+ if (bindings === "") return value;
835
+ const arrow = findTopLevelArrow(value);
836
+ if (arrow !== -1) {
837
+ let body = arrow + 2;
838
+ while (body < value.length && /\s/.test(value[body])) body += 1;
839
+ if (value[body] === "{") return `${value.substring(0, body + 1)}\n${bindings}${value.substring(body + 1)}`;
840
+ return `${value.substring(0, body)}{\n${bindings}return ${value.substring(body)}\n}`;
841
+ }
842
+ if (/\bfunction\b/.test(value)) {
843
+ const brace = findBodyBrace(value);
844
+ if (brace !== -1) return `${value.substring(0, brace + 1)}\n${bindings}${value.substring(brace + 1)}`;
845
+ }
846
+ return `function (...t_args) {\n${bindings}return (${value}).apply(this, t_args);\n}`;
847
+ }
848
+ /**
849
+ * Returns the index of the first `=>` at the top level of `value` (not inside
850
+ * a string/comment or nested parens/brackets/braces), or -1. Used to find the
851
+ * outer arrow of a handler expression.
852
+ */
853
+ function findTopLevelArrow(value) {
854
+ let depth = 0;
855
+ let i = 0;
856
+ while (i < value.length) {
857
+ const skipped = skipStringOrComment(value, i);
858
+ if (skipped !== -1) {
859
+ i = skipped;
860
+ continue;
861
+ }
862
+ const char = value[i];
863
+ if (char === "(" || char === "[" || char === "{") depth += 1;
864
+ else if (char === ")" || char === "]" || char === "}") depth -= 1;
865
+ else if (char === "=" && value[i + 1] === ">" && depth === 0) return i;
866
+ i += 1;
867
+ }
868
+ return -1;
869
+ }
870
+ /**
871
+ * Injects the shadow bindings at the top of a `@function` declaration's body,
872
+ * so a named function can reference enclosing loop variables and still see
873
+ * their current values when it is called later.
874
+ */
875
+ function injectIntoFunctionBody(statement, status) {
876
+ const bindings = forVarBindings(status, statement);
877
+ if (bindings === "") return statement;
878
+ const brace = findBodyBrace(statement);
879
+ if (brace === -1) return statement;
880
+ return `${statement.substring(0, brace + 1)}\n${bindings}${statement.substring(brace + 1)}`;
881
+ }
882
+ /**
883
+ * Returns the index of the `{` that opens an expression's function body (the
884
+ * first top-level brace, skipping parameter parens/brackets and
885
+ * strings/comments), or -1 if there isn't one.
886
+ */
887
+ function findBodyBrace(value) {
888
+ let depth = 0;
889
+ let i = 0;
890
+ while (i < value.length) {
891
+ const skipped = skipStringOrComment(value, i);
892
+ if (skipped !== -1) {
893
+ i = skipped;
894
+ continue;
895
+ }
896
+ const char = value[i];
897
+ if (char === "(" || char === "[") depth += 1;
898
+ else if (char === ")" || char === "]") depth -= 1;
899
+ else if (char === "{" && depth === 0) return i;
900
+ i += 1;
901
+ }
902
+ return -1;
903
+ }
904
+ //#endregion
754
905
  //#region src/compile/build/client/buildAddFragment.ts
755
906
  function buildAddFragment(node, status, b, parentName, anchorName) {
756
907
  if (node.fragment) {
@@ -766,6 +917,7 @@ function buildAddFragment(node, status, b, parentName, anchorName) {
766
917
  let trailing = "";
767
918
  if (forVarMask !== void 0) trailing = `, undefined, { forVarMask: ${forVarMask} }`;
768
919
  b.append("$run(() => {");
920
+ appendForVarBindings(b, status, fragment.effects.map((e) => e.functionBody).join("\n"));
769
921
  if (status.options.mapped === true) for (let effect of fragment.effects) addMappedTextWithOffsets("", effect.functionBody, "", effect.spans, effect.offsets, effect.lengths, status, b);
770
922
  else b.append(fragment.effects.map((e) => e.functionBody).join("\n"));
771
923
  b.append(`}${status.options.dev === true ? `, "setAttributes"${trailing}` : trailing});`);
@@ -1160,58 +1312,35 @@ function getFragmentVarPathPart(path, varPath, status, root = false, rootFn = "t
1160
1312
  //#endregion
1161
1313
  //#region src/compile/utils/forVarsReadIn.ts
1162
1314
  /**
1163
- * Returns a bitmask of the for-loop variables whose substituted paths appear
1164
- * in `expr`. Bit N is set when the Nth for-var (by position in `forVarNames`)
1165
- * is read.
1315
+ * Returns a bitmask of the for-loop variables whose names appear in `expr`.
1316
+ * Bit N is set when the Nth for-var (by position in `forVars`) is read.
1166
1317
  *
1167
- * After `replaceForVarNames` has run, every reference to a for-var in the
1168
- * body has been rewritten to its data-bag path (e.g. `row` →
1169
- * `t_item_42.data.row`, or `t_item_42.data` for single-var loops). This
1170
- * helper scans the POST-substitution `expr` for those paths and returns a
1171
- * bitmask — used to annotate each effect with `forVarMask` so the keyed-list
1318
+ * Used to annotate each effect with `forVarMask` so the keyed-list
1172
1319
  * reconciler's no-proxy force-rerun path (`rerunRegionEffects`) can skip
1173
1320
  * effects that don't depend on the changed for-vars via a single bitwise AND.
1174
1321
  *
1322
+ * Read-only loop vars are referenced by their bare name (they resolve to a
1323
+ * per-scope shadow binding); written vars are substituted to their data path,
1324
+ * whose trailing property is the variable name. Matching on an
1325
+ * identifier-boundary regex catches both (`t_item.data.row` contains a
1326
+ * standalone `row`), without matching substrings of the compiler's generated
1327
+ * names (e.g. the `i` inside `t_item_1`).
1328
+ *
1175
1329
  * Conservative by design: a false positive (claiming a dependency that
1176
1330
  * doesn't really exist) just causes an unnecessary re-run, while a false
1177
- * negative would drop a needed update. String literals that happen to
1178
- * contain the substituted path are extremely unlikely and harmless.
1331
+ * negative would drop a needed update.
1179
1332
  */
1180
- function forVarsReadIn(expr, forVarNames) {
1333
+ function forVarsReadIn(expr, forVars) {
1181
1334
  let mask = 0;
1182
- for (let i = 0; i < forVarNames.length; i++) {
1183
- const subPath = forVarNames[i][1];
1184
- if (subPath && expr.includes(subPath)) mask |= 1 << i;
1185
- }
1335
+ for (let i = 0; i < forVars.length; i++) if (containsIdentifier(expr, forVars[i].name)) mask |= 1 << i;
1186
1336
  return mask;
1187
1337
  }
1188
1338
  //#endregion
1189
- //#region src/compile/build/client/replaceForVarNames.ts
1190
- /**
1191
- * Variables used within a for loop need to be retrieved from the loop data.
1192
- */
1193
- function replaceForVarNames(value, status) {
1194
- if (status.forVarNames.length === 0) return value;
1195
- let result = "";
1196
- let index = 0;
1197
- for (let [start, end] of codeRanges(value)) {
1198
- result += value.substring(index, start);
1199
- result += replaceVarNames(value.substring(start, end), status);
1200
- index = end;
1201
- }
1202
- result += value.substring(index);
1203
- return result;
1204
- }
1205
- function replaceVarNames(code, status) {
1206
- for (let varName of status.forVarNames) code = code.replaceAll(new RegExp(`(^|\\s|\\(|\\[|\\{|!|\\?|\\.\\.\\.)${varName[0]}($|\\s|\\.|,|\\(|\\)|\\[|\\]|\\}|;|\\?)`, "g"), `$1${varName[1]}$2`);
1207
- return code;
1208
- }
1209
- //#endregion
1210
1339
  //#region src/compile/build/client/buildRun.ts
1211
1340
  function buildRun(functionName, functionBody, status, b) {
1212
- functionBody = replaceForVarNames(functionBody, status);
1213
1341
  addPushDevBoundary("run", functionName, status, b);
1214
- let forVarMask = status.forVarNames.length > 0 ? forVarsReadIn(functionBody, status.forVarNames) : void 0;
1342
+ let forVarMask = status.forVars.length > 0 ? forVarsReadIn(functionBody, status.forVars) : void 0;
1343
+ functionBody = forVarBindings(status, functionBody) + functionBody;
1215
1344
  let trailing = "";
1216
1345
  if (status.options.dev === true) {
1217
1346
  trailing = `, "${functionName}"`;
@@ -1366,15 +1495,15 @@ function buildComponentNode(node, status, b, root = false) {
1366
1495
  });
1367
1496
  b.append(`let ${propsName} = $watch({`);
1368
1497
  for (let p of props) {
1369
- let value = replaceForVarNames(p.value, status);
1498
+ let value = p.value;
1370
1499
  p.preText ??= "";
1371
1500
  p.postText ??= "";
1372
1501
  if (p.spans.length === 1) addMappedText(p.name ? `${p.name}: ` + p.preText : p.preText, value, p.postText + ",", p.spans[0], status, b);
1373
1502
  else addMappedTextWithOffsets(p.name ? `${p.name}: ` + p.preText : p.preText, value, p.postText + ",", p.spans, p.offsets, p.lengths, status, b);
1374
1503
  }
1375
1504
  b.append("});");
1376
- if (runs.length) buildRun("setProps", replaceForVarNames(runs.join("\n"), status), status, b);
1377
- if (bindingRuns.length) buildRun("setBindings", replaceForVarNames(bindingRuns.join("\n"), status), status, b);
1505
+ if (runs.length) buildRun("setProps", runs.join("\n"), status, b);
1506
+ if (bindingRuns.length) buildRun("setBindings", bindingRuns.join("\n"), status, b);
1378
1507
  if (root) {
1379
1508
  status.imports.add("$run");
1380
1509
  b.append(`
@@ -1440,6 +1569,7 @@ function buildAwaitNode(node, status, b) {
1440
1569
  b.append(`
1441
1570
  const ${regionName} = t_region(${status.options.dev === true ? `"await"` : ""});
1442
1571
  t_run_await(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
1572
+ appendForVarBindings(b, status);
1443
1573
  if (awaitBranch !== void 0 && awaitBranch.children.length > 0) {
1444
1574
  buildFragment(awaitBranch, status, b, parentName, "t_before");
1445
1575
  status.fragmentStack.push({
@@ -1452,6 +1582,7 @@ function buildAwaitNode(node, status, b) {
1452
1582
  }
1453
1583
  if (withBranch !== void 0) {
1454
1584
  b.append(`}, (${status.inHead ? "" : "t_before"}) => {`);
1585
+ appendForVarBindings(b, status);
1455
1586
  if (withBranch.children.length > 0) {
1456
1587
  buildFragment(withBranch, status, b, parentName, "t_before");
1457
1588
  status.fragmentStack.push({
@@ -1527,6 +1658,78 @@ function isForBodyLeafSafe(forBodyChildren) {
1527
1658
  return !hasNestedControl(forBodyChildren);
1528
1659
  }
1529
1660
  //#endregion
1661
+ //#region src/compile/utils/forVarsWrittenIn.ts
1662
+ /**
1663
+ * Returns the set of `forVars` that are written anywhere in `children`,
1664
+ * treating any write-target mention (direct assignment, property/index
1665
+ * assignment, `&`-binding) as a write.
1666
+ *
1667
+ * This is the conservative scan behind `isForBodyNoProxySafe`: anything
1668
+ * ambiguous must disable the no-proxy specialization, so a *property* write
1669
+ * (`row.name = …`) counts even though it doesn't replace the loop variable.
1670
+ */
1671
+ function forVarsWrittenIn(children, forVars) {
1672
+ return scan(children, forVars, (escaped) => `\\b${escaped}(?:\\.[a-zA-Z_$][\\w$]*|\\[[^\\]]+\\])?\\s*(?:=(?![=>])|[+\\-*/%&|^]=|\\+\\+|--)`);
1673
+ }
1674
+ /**
1675
+ * Returns the set of `forVars` whose *binding* is written in `children` — i.e.
1676
+ * the loop variable itself is assigned (`row = …`, `row += …`, `row++`), bound
1677
+ * as a two-way target (`&value={row}`), or destructured into (`[row] = …`,
1678
+ * `{row} = …`).
1679
+ *
1680
+ * Loop variables are read-only (a `@for` extracts a copy of each element), so
1681
+ * `buildForNode` reports each name in this set as a compile error. A write to
1682
+ * a *property* (`row.name = …`) or *index* (`row[i] = …`) mutates the row
1683
+ * object through the shadowed reference and is not included.
1684
+ */
1685
+ function forVarsReassignedIn(children, forVars) {
1686
+ return scan(children, forVars, (escaped) => `(?<![\\w$.])${escaped}\\s*(?:=(?![=>])|[+\\-*/%&|^]=|\\+\\+|--)`);
1687
+ }
1688
+ function scan(children, forVars, bareWritePattern) {
1689
+ const found = /* @__PURE__ */ new Set();
1690
+ if (forVars.length === 0) return found;
1691
+ const collected = [];
1692
+ for (const child of children) collectExpressionStrings(child, collected);
1693
+ for (const varName of forVars) {
1694
+ const escaped = varName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1695
+ const writePattern = new RegExp(`(?<![\\w$.\\])\\)])\\[\\s*${escaped}\\s*\\]\\s*=(?![=>])|(?<![\\w$.\\])\\)])\\{\\s*${escaped}\\s*(:[^}]+)?\\}\\s*=(?![=>])|` + bareWritePattern(escaped) + `|(?<![\\w$.])(?:\\+\\+|--)\\s*${escaped}(?![\\w$])`);
1696
+ for (const text of collected) if (writePattern.test(text)) {
1697
+ found.add(varName);
1698
+ break;
1699
+ }
1700
+ }
1701
+ return found;
1702
+ }
1703
+ function isElementLike(node) {
1704
+ return node.type === "element" || node.type === "component" || node.type === "special";
1705
+ }
1706
+ /**
1707
+ * Collects every expression-like string from the body, including attribute
1708
+ * values (with `&`-binding targets marked by a trailing `=`), text
1709
+ * interpolations, and control statements (recursing into nested controls).
1710
+ */
1711
+ function collectExpressionStrings(node, out) {
1712
+ if (isTextNode(node)) {
1713
+ out.push(node.content);
1714
+ return;
1715
+ }
1716
+ if (isElementLike(node)) {
1717
+ for (const attr of node.attributes) {
1718
+ if (attr.value !== void 0) {
1719
+ if (attr.name.startsWith("&")) out.push(`${attr.value} =`);
1720
+ else out.push(attr.value);
1721
+ }
1722
+ if (attr.fullyReactive && attr.name !== attr.value) out.push(attr.name);
1723
+ }
1724
+ for (const child of node.children) collectExpressionStrings(child, out);
1725
+ return;
1726
+ }
1727
+ if (isControlNode(node)) {
1728
+ out.push(node.statement);
1729
+ for (const child of node.children) collectExpressionStrings(child, out);
1730
+ }
1731
+ }
1732
+ //#endregion
1530
1733
  //#region src/compile/utils/isForBodyNoProxySafe.ts
1531
1734
  /**
1532
1735
  * Returns true if the body of a `@for` loop never writes to any of its loop
@@ -1558,37 +1761,59 @@ function isForBodyLeafSafe(forBodyChildren) {
1558
1761
  function isForBodyNoProxySafe(forBodyChildren, forVars) {
1559
1762
  if (forVars.length === 0) return false;
1560
1763
  if (hasNestedControl(forBodyChildren)) return false;
1561
- const collected = [];
1562
- for (const child of forBodyChildren) collectExpressionStrings(child, collected);
1563
- for (const varName of forVars) {
1564
- const escaped = varName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1565
- const writePattern = new RegExp(`\\[\\s*${escaped}\\s*\\]\\s*=(?![=>])|\\{\\s*${escaped}\\s*(:[^}]+)?\\}\\s*=(?![=>])|\\b${escaped}(?:\\.[a-zA-Z_$][\\w$]*|\\[[^\\]]+\\])?\\s*(?:=(?![=>])|[+\\-*/%&|^]=|\\+\\+|--)|(?:\\+\\+|--)\\s*${escaped}\\b`);
1566
- for (const text of collected) if (writePattern.test(text)) return false;
1567
- }
1568
- return true;
1764
+ return forVarsWrittenIn(forBodyChildren, forVars).size === 0;
1569
1765
  }
1570
- function isElementLike(node) {
1571
- return node.type === "element" || node.type === "component" || node.type === "special";
1766
+ //#endregion
1767
+ //#region src/compile/utils/isComponentNode.ts
1768
+ function isComponentNode(node) {
1769
+ return node.type === "component";
1572
1770
  }
1573
- function collectExpressionStrings(node, out) {
1574
- if (isTextNode(node)) {
1575
- out.push(node.content);
1576
- return;
1771
+ //#endregion
1772
+ //#region src/compile/utils/forVarsReadDirectlyIn.ts
1773
+ /**
1774
+ * Returns the subset of `forVars` that are referenced by code evaluated
1775
+ * *synchronously in the enclosing row-create scope*, rather than inside a
1776
+ * nested function scope the compiler emits.
1777
+ *
1778
+ * Every compiler-generated scope (effects, handlers, control callbacks,
1779
+ * `$onmount`, `@function` bodies) emits its own shadow binding for the loop
1780
+ * vars it reads. The remaining "direct" positions are evaluated in the
1781
+ * row-create scope itself and rely on the binding emitted at the top of the
1782
+ * row callback:
1783
+ *
1784
+ * - a component's initial props object (`<Child label={item.name} />`),
1785
+ * including fill/slot content that closes over the row scope,
1786
+ * - `@const` / `@console` / `@debugger` statements,
1787
+ * - a `&ref` write target, and an interpolated `@element` tag.
1788
+ *
1789
+ * Emitting the row-scope binding only when one of these needs it avoids an
1790
+ * unused `const <var> = <data>;` line in the common case.
1791
+ */
1792
+ function forVarsReadDirectlyIn(children, forVars) {
1793
+ const sources = [];
1794
+ collectDirect(children, sources);
1795
+ const found = /* @__PURE__ */ new Set();
1796
+ for (const forVar of forVars) {
1797
+ if (!forVar.shadow) continue;
1798
+ if (sources.some((source) => containsIdentifier(source, forVar.name))) found.add(forVar.name);
1577
1799
  }
1578
- if (isElementLike(node)) {
1800
+ return found;
1801
+ }
1802
+ function collectDirect(nodes, out) {
1803
+ for (const node of nodes) if (isComponentNode(node)) {
1804
+ for (const attr of node.attributes) if (attr.value != null) out.push(attr.value);
1805
+ collectDirect(node.children, out);
1806
+ } else if (isElementNode(node) || isSpecialNode(node)) {
1807
+ const slotProps = isSpecialNode(node) && (node.tagName === "slot" || node.tagName === "fill" || node.tagName === "filldef");
1579
1808
  for (const attr of node.attributes) {
1580
- if (attr.value !== void 0) {
1581
- if (attr.name.startsWith("&")) out.push(`${attr.value} =`);
1582
- else out.push(attr.value);
1583
- }
1584
- if (attr.fullyReactive && attr.name !== attr.value) out.push(attr.name);
1809
+ if (attr.value == null) continue;
1810
+ if (slotProps) out.push(attr.value);
1811
+ else if (attr.name === "&ref") out.push(attr.value);
1812
+ else if (attr.name === "self" && !attr.fullyReactive) out.push(attr.value);
1585
1813
  }
1586
- for (const child of node.children) collectExpressionStrings(child, out);
1587
- return;
1588
- }
1589
- if (isControlNode(node)) {
1590
- out.push(node.statement);
1591
- for (const child of node.children) collectExpressionStrings(child, out);
1814
+ collectDirect(node.children, out);
1815
+ } else if (isControlNode(node)) {
1816
+ if (node.operation === "@const" || node.operation === "@console" || node.operation === "@debugger") out.push(node.statement);
1592
1817
  }
1593
1818
  }
1594
1819
  //#endregion
@@ -1610,6 +1835,43 @@ function trimMatched(text, startChar, endChar) {
1610
1835
  return text.substring(start, end);
1611
1836
  }
1612
1837
  //#endregion
1838
+ //#region src/compile/build/client/addBuildError.ts
1839
+ /**
1840
+ * Adds an error to the build status. Mirrors `parse/utils/addError`, but is
1841
+ * used during building (where loop-variable write rules, etc. are enforced).
1842
+ *
1843
+ * Line/char are derived from `status.options.source` when it is available;
1844
+ * when it isn't, they default to 0 and consumers should rely on `startIndex`.
1845
+ */
1846
+ function addBuildError(status, message, start, end = start) {
1847
+ const source = status.options.source;
1848
+ let startLine = 0;
1849
+ let lastLineStart = 0;
1850
+ let i = 0;
1851
+ if (source !== void 0) {
1852
+ for (; i < start && i < source.length; i++) if (source[i] === "\n") {
1853
+ startLine += 1;
1854
+ lastLineStart = i + 1;
1855
+ }
1856
+ }
1857
+ const startChar = start - lastLineStart;
1858
+ let endLine = startLine;
1859
+ for (; i < end && source !== void 0 && i < source.length; i++) if (source[i] === "\n") {
1860
+ endLine += 1;
1861
+ lastLineStart = i + 1;
1862
+ }
1863
+ const error = {
1864
+ message,
1865
+ startIndex: start,
1866
+ startLine,
1867
+ startChar,
1868
+ endIndex: end,
1869
+ endLine,
1870
+ endChar: end - lastLineStart
1871
+ };
1872
+ status.errors.push(error);
1873
+ }
1874
+ //#endregion
1613
1875
  //#region src/compile/build/client/buildForNode.ts
1614
1876
  const forLoopRegex = /for\s*\((.+?);.*?;.*?\)/;
1615
1877
  const forLoopVarsRegex = /(?:let\s+|var\s+){0,1}([^\s,;+=]+)(?:\s*=\s*[^,;]+){0,1}/g;
@@ -1646,6 +1908,8 @@ function buildForNode(node, status, b) {
1646
1908
  }
1647
1909
  const noWatch = isForBodyNoProxySafe(node.children, forVarNames);
1648
1910
  if (noWatch) status.imports.add("t_rerun_region_effects");
1911
+ const reassignedForVars = forVarsReassignedIn(node.children, forVarNames);
1912
+ for (const name of reassignedForVars) addBuildError(status, `Cannot assign to loop variable "${name}": a @for loop variable is read-only. Assign to a property of the item (\`${name}.foo = …\`) instead, or mutate the source collection directly.`, node.span.start, node.span.end);
1649
1913
  const singleVar = noWatch && forVarNames.length === 1;
1650
1914
  const leafRow = isForBodyLeafSafe(node.children);
1651
1915
  status.imports.add("t_region");
@@ -1662,7 +1926,8 @@ function buildForNode(node, status, b) {
1662
1926
  ${anchorName},
1663
1927
  ${status.options.dev === true ? "function createNewItems() {" : "() => {"}
1664
1928
  let ${listItemsName}: ListItemSpec[] = [];`);
1665
- addMappedText("", `${replaceForVarNames(node.statement, status)}`, " {", node.span, status, b);
1929
+ appendForVarBindings(b, status, `${node.statement}\n${keyStatement}`);
1930
+ addMappedText("", `${node.statement}`, " {", node.span, status, b);
1666
1931
  if (singleVar) b.append(`${listItemsName}.push({ data: ${forVarNames[0]}, key: `);
1667
1932
  else b.append(`${listItemsName}.push({ data: { ${forVarNames.join(", ")} }, key: `);
1668
1933
  if (key !== void 0) addMappedText("", `${keyStatement || "undefined"}`, " });", key.span, status, b);
@@ -1671,11 +1936,16 @@ function buildForNode(node, status, b) {
1671
1936
  b.append(`return ${listItemsName};`);
1672
1937
  b.append(`},
1673
1938
  ${status.options.dev === true ? `function createListItem(${itemName}, ${beforeName}) {` : `(${itemName}, ${beforeName}) => {`}`);
1674
- let oldForVarNames = status.forVarNames;
1675
- const forVarBitBase = oldForVarNames.length;
1676
- status.forVarNames = [...status.forVarNames, ...singleVar ? forVarNames.map((v) => [v, `${itemName}.data`]) : forVarNames.map((v) => [v, `${itemName}.data.${v}`])];
1939
+ let oldForVars = status.forVars;
1940
+ const forVarBitBase = oldForVars.length;
1941
+ status.forVars = [...oldForVars, ...forVarNames.map((v) => ({
1942
+ name: v,
1943
+ path: singleVar ? `${itemName}.data` : `${itemName}.data.${v}`,
1944
+ shadow: true
1945
+ }))];
1946
+ appendForVarBindingsFor(b, status, forVarsReadDirectlyIn(node.children, status.forVars));
1677
1947
  buildForItem(node, status, b, parentName, beforeName, itemName, leafRow);
1678
- status.forVarNames = oldForVarNames;
1948
+ status.forVars = oldForVars;
1679
1949
  b.append(`},
1680
1950
  ${status.options.dev === true ? "function updateListItem(t_old_item, t_new_item) {" : "(t_old_item, t_new_item) => {"}`);
1681
1951
  if (noWatch) {
@@ -1737,7 +2007,8 @@ function buildHtmlNode(node, status, b) {
1737
2007
  b.append(`let ${firstNodeVar}: ChildNode | null = null;`);
1738
2008
  b.append(`let ${lastNodeVar}: ChildNode | null = null;`);
1739
2009
  b.append(`t_run_control(t_region(), ${htmlAnchorName}, (t_before) => {`);
1740
- b.append(`${replaceForVarNames(node.statement, status)};`);
2010
+ appendForVarBindings(b, status);
2011
+ b.append(`${node.statement};`);
1741
2012
  b.append(`if (${firstNodeVar} !== null && ${lastNodeVar} !== null) {`);
1742
2013
  b.append(`let t_node: ChildNode | null = ${lastNodeVar};`);
1743
2014
  b.append(`while (t_node !== null && t_node !== ${firstNodeVar}) {`);
@@ -1753,7 +2024,7 @@ function buildHtmlNode(node, status, b) {
1753
2024
  b.append(`let ${templateName} = document.createElement("template");`);
1754
2025
  node.span.start += 5;
1755
2026
  node.span.end -= 2;
1756
- addMappedText("", `${templateName}.innerHTML = ${replaceForVarNames(node.statement, status)};`, "", node.span, status, b);
2027
+ addMappedText("", `${templateName}.innerHTML = ${node.statement};`, "", node.span, status, b);
1757
2028
  b.append(`let ${fragmentName} = ${templateName}.content.cloneNode(true) as DocumentFragment;`);
1758
2029
  b.append(`${firstNodeVar} = ${fragmentName}.firstChild;`);
1759
2030
  b.append(`${lastNodeVar} = ${fragmentName}.lastChild;`);
@@ -1808,6 +2079,7 @@ function buildIfNode(node, status, b) {
1808
2079
  const ${regionName} = t_region(${status.options.dev === true ? `"if"` : ""});
1809
2080
  let ${indexName} = -1;
1810
2081
  t_run_control(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2082
+ appendForVarBindings(b, status);
1811
2083
  let index = 0;
1812
2084
  for (let branch of branches) buildIfBranch(branch, status, b, parentName, regionName, indexName, index++);
1813
2085
  b.append(`}${status.options.dev === true ? `, "runIf"` : ""});`);
@@ -1815,7 +2087,7 @@ function buildIfNode(node, status, b) {
1815
2087
  b.append("");
1816
2088
  }
1817
2089
  function buildIfBranch(node, status, b, parentName, regionName, indexName, index) {
1818
- addMappedText("", `${replaceForVarNames(node.statement, status)}`, " {", node.span, status, b);
2090
+ addMappedText("", `${node.statement}`, " {", node.span, status, b);
1819
2091
  b.append(`if (!t_run_branch(${regionName}, ${indexName}, ${index})) return;`);
1820
2092
  if (node.children.length > 0) {
1821
2093
  b.append(`
@@ -1852,13 +2124,14 @@ function buildReplaceNode(node, status, b) {
1852
2124
  /* @replace */
1853
2125
  const ${replaceRegionName} = t_region(${status.options.dev === true ? `"replace"` : ""});
1854
2126
  t_run_control(${replaceRegionName}, ${replaceAnchorName}, (t_before) => {`);
2127
+ appendForVarBindings(b, status);
1855
2128
  buildReplaceBranch(node, status, b, replaceParentName, replaceRegionName);
1856
2129
  b.append(`}${status.options.dev === true ? ", \"replace\"" : ""});`);
1857
2130
  b.append("");
1858
2131
  }
1859
2132
  function buildReplaceBranch(node, status, b, parentName, regionName) {
1860
2133
  status.imports.add("t_run_branch");
1861
- b.append(`${replaceForVarNames(node.statement, status)};`);
2134
+ b.append(`${node.statement};`);
1862
2135
  b.append(`if (!t_run_branch(${regionName}, 0, -1)) return;`);
1863
2136
  b.append(`
1864
2137
  const t_new_region = t_region(${status.options.dev === true ? `"replace_branch"` : ""});
@@ -1878,7 +2151,9 @@ function buildReplaceBranch(node, status, b, parentName, regionName) {
1878
2151
  //#region src/compile/build/client/buildScriptNode.ts
1879
2152
  function buildScriptNode(node, status, b) {
1880
2153
  b.append(`/* ${node.operation} */`);
1881
- addMappedText("", `${maybeAppend$1(node.statement, ";")}`, "", node.span, status, b);
2154
+ let text = maybeAppend$1(node.statement, ";");
2155
+ if (node.operation === "@function" || node.operation === "@async function") text = injectIntoFunctionBody(text, status);
2156
+ addMappedText("", text, "", node.span, status, b);
1882
2157
  }
1883
2158
  function maybeAppend$1(text, end) {
1884
2159
  if (!text.endsWith(end)) text += end;
@@ -1914,7 +2189,8 @@ function buildSwitchNode(node, status, b) {
1914
2189
  const ${regionName} = t_region(${status.options.dev === true ? `"switch"` : ""});
1915
2190
  let ${indexName} = -1;
1916
2191
  t_run_control(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
1917
- addMappedText("", `${replaceForVarNames(node.statement, status)}`, " {", node.span, status, b);
2192
+ appendForVarBindings(b, status);
2193
+ addMappedText("", `${node.statement}`, " {", node.span, status, b);
1918
2194
  let index = 0;
1919
2195
  for (let branch of branches) buildSwitchBranch(branch, status, b, parentName, regionName, indexName, index++);
1920
2196
  b.append(`
@@ -1924,7 +2200,7 @@ function buildSwitchNode(node, status, b) {
1924
2200
  b.append("");
1925
2201
  }
1926
2202
  function buildSwitchBranch(node, status, b, parentName, regionName, indexName, index) {
1927
- addMappedText("", `${replaceForVarNames(node.statement, status)}`, " {", node.span, status, b);
2203
+ addMappedText("", `${node.statement}`, " {", node.span, status, b);
1928
2204
  b.append(`if (!t_run_branch(${regionName}, ${indexName}, ${index})) return;`);
1929
2205
  if (node.children.length > 0) {
1930
2206
  b.append(`
@@ -1963,10 +2239,12 @@ function buildTryNode(node, status, b) {
1963
2239
  b.append(`
1964
2240
  const ${regionName} = t_region(${status.options.dev === true ? `"try"` : ""});
1965
2241
  t_run_try(${regionName}, ${anchorName}, (${status.inHead ? "" : "t_before"}) => {`);
2242
+ appendForVarBindings(b, status);
1966
2243
  buildTryBranchBody(tryBranch, status, b, parentName);
1967
2244
  const catchVar = catchBranch ? trimMatched(catchBranch.statement.substring(5).trim(), "(", ")") || "err" : null;
1968
2245
  if (catchBranch && catchVar) {
1969
- addMappedText("},", `(${status.inHead ? "" : "t_before"}, ${replaceForVarNames(catchVar, status)}) => {`, "", catchBranch.span, status, b);
2246
+ addMappedText("},", `(${status.inHead ? "" : "t_before"}, ${catchVar}) => {`, "", catchBranch.span, status, b);
2247
+ appendForVarBindings(b, status);
1970
2248
  buildTryBranchBody(catchBranch, status, b, parentName);
1971
2249
  b.append(`}${status.options.dev === true ? `, "runTry"` : ""});`);
1972
2250
  } else b.append(`}, null${status.options.dev === true ? `, "runTry"` : ""});`);
@@ -2055,18 +2333,16 @@ function trimEnd(text, char) {
2055
2333
  //#endregion
2056
2334
  //#region src/compile/build/client/buildMount.ts
2057
2335
  function buildMount(_functionName, functionBody, status, b) {
2058
- functionBody = replaceForVarNames(functionBody, status);
2059
2336
  status.imports.add("$onmount");
2060
2337
  b.append("// @ts-ignore\n$onmount(() => {");
2061
- b.append(functionBody);
2338
+ b.append(forVarBindings(status, functionBody) + functionBody);
2062
2339
  b.append("});");
2063
2340
  }
2064
2341
  //#endregion
2065
2342
  //#region src/compile/build/client/stashRun.ts
2066
2343
  function stashRun(fragment, functionStart, value, functionEnd, span, status) {
2067
- value = replaceForVarNames(value, status);
2068
2344
  let functionBody = functionStart + value + functionEnd;
2069
- let forVarMask = status.forVarNames.length > 0 ? forVarsReadIn(value, status.forVarNames) : void 0;
2345
+ let forVarMask = status.forVars.length > 0 ? forVarsReadIn(value, status.forVars) : void 0;
2070
2346
  fragment.effects.push({
2071
2347
  functionBody,
2072
2348
  spans: [span],
@@ -2079,15 +2355,8 @@ function stashRun(fragment, functionStart, value, functionEnd, span, status) {
2079
2355
  //#region src/compile/build/client/stashRunWithOffsets.ts
2080
2356
  function stashRunWithOffsets(fragment, functionStart, value, functionEnd, spans, offsets, lengths, status) {
2081
2357
  let functionBody = functionStart + value + functionEnd;
2082
- for (let i = 0; i < offsets.length; i++) {
2083
- offsets[i] += functionStart.length;
2084
- const oldLength = functionBody.length;
2085
- functionBody = functionBody.substring(0, offsets[i]) + replaceForVarNames(functionBody.substring(offsets[i], offsets[i] + lengths[i]), status) + functionBody.substring(offsets[i] + lengths[i]);
2086
- const changedLength = functionBody.length - oldLength;
2087
- lengths[i] += changedLength;
2088
- for (let j = i + 1; j < offsets.length; j++) offsets[j] += changedLength;
2089
- }
2090
- let forVarMask = status.forVarNames.length > 0 ? forVarsReadIn(functionBody, status.forVarNames) : void 0;
2358
+ for (let i = 0; i < offsets.length; i++) offsets[i] += functionStart.length;
2359
+ let forVarMask = status.forVars.length > 0 ? forVarsReadIn(functionBody, status.forVars) : void 0;
2091
2360
  fragment.effects.push({
2092
2361
  functionBody,
2093
2362
  spans,
@@ -2170,7 +2439,6 @@ function buildHeadNode(node, status, b) {
2170
2439
  const t_head_el = t_head_element("${node.tagName}", ${JSON.stringify(selector)});`);
2171
2440
  for (let { name, value, span } of node.attributes) if (value != null) {
2172
2441
  status.imports.add("t_attribute");
2173
- value = replaceForVarNames(value, status);
2174
2442
  addMappedText(`t_attribute(t_head_el, "${name}", `, value, ");", span, status, b);
2175
2443
  }
2176
2444
  b.append(`}${status.options.dev === true ? `, "runHead"` : ""});`);
@@ -2201,7 +2469,7 @@ function headElementSelector(node) {
2201
2469
  function buildElementAttributes$1(node, varName, status, b) {
2202
2470
  let fragment = status.fragmentStack.at(-1)?.fragment;
2203
2471
  if (!fragment) throw new Error("No fragment on stack");
2204
- const combinedHandlers = combinedEventHandlers(node, status);
2472
+ const combinedHandlers = combinedEventHandlers(node);
2205
2473
  const consumedHandlers = new Set(Array.from(combinedHandlers.values(), (c) => c.index));
2206
2474
  for (let [index, { name, value, reactive, fullyReactive, span }] of node.attributes.entries()) if (name === "self" && node.tagName === "@element") {} else if (name === "&ref") {} else if (value != null && fullyReactive) {
2207
2475
  if (name === "&group") buildBindGroupAttribute(node, varName, value, status, b, combinedHandlers.get(index));
@@ -2218,7 +2486,7 @@ function buildElementAttributes$1(node, varName, status, b) {
2218
2486
  stashRun(fragment, `${status.ns ? "// @ts-ignore\n" : ""}${varName}.${propName} = t_class(`, params.join(", "), ");", span, status);
2219
2487
  } else if (name === "style") {
2220
2488
  status.imports.add("t_style");
2221
- stashRun(fragment, `${varName}.style.cssText += t_style(`, value, ");", span, status);
2489
+ stashRun(fragment, `${varName}.style.cssText = t_style(`, value, ");", span, status);
2222
2490
  } else if (name.includes("-")) {
2223
2491
  status.imports.add("t_attribute");
2224
2492
  stashRun(fragment, `t_attribute(${varName}, "${name}", `, value, ");", span, status);
@@ -2237,7 +2505,7 @@ function buildElementAttributes$1(node, varName, status, b) {
2237
2505
  stashRunWithOffsets(fragment, `${status.ns ? "// @ts-ignore\n" : ""}${varName}.${propName} = t_class(`, params.join(", "), ");", spans, offsets, lengths, status);
2238
2506
  } else if (name === "style") {
2239
2507
  status.imports.add("t_style");
2240
- stashRunWithOffsets(fragment, `${varName}.style.cssText += t_style(`, value, ");", spans, offsets, lengths, status);
2508
+ stashRunWithOffsets(fragment, `${varName}.style.cssText = t_style(`, value, ");", spans, offsets, lengths, status);
2241
2509
  } else if (name.includes("-")) {
2242
2510
  status.imports.add("t_attribute");
2243
2511
  stashRunWithOffsets(fragment, `t_attribute(${varName}, "${name}", `, value, ");", spans, offsets, lengths, status);
@@ -2248,7 +2516,6 @@ function buildElementAttributes$1(node, varName, status, b) {
2248
2516
  }
2249
2517
  }
2250
2518
  function buildBindGroupAttribute(node, varName, value, status, b, combined) {
2251
- value = replaceForVarNames(value, status);
2252
2519
  let eventName = "change";
2253
2520
  let inputValue = node.attributes.find((a) => a.name === "value")?.value;
2254
2521
  let set = `${value} == ${inputValue}`;
@@ -2259,7 +2526,6 @@ function buildBindGroupAttribute(node, varName, value, status, b, combined) {
2259
2526
  }`, `if (e.target.${propName}) ${value} = ${inputValue};`, combined, status, b);
2260
2527
  }
2261
2528
  function buildBindAttribute(node, varName, name, value, status, b, combined) {
2262
- value = replaceForVarNames(value, status);
2263
2529
  let eventName = bindEventName(node, name);
2264
2530
  let defaultValue = "\"\"";
2265
2531
  let inputValue = "e.target.value";
@@ -2307,7 +2573,7 @@ function bindEventName(node, name) {
2307
2573
  * as one t_event that calls the binding write and the user handler in source
2308
2574
  * order. Returns a map from binding attribute index to the combined handler.
2309
2575
  */
2310
- function combinedEventHandlers(node, status) {
2576
+ function combinedEventHandlers(node) {
2311
2577
  const bindings = /* @__PURE__ */ new Map();
2312
2578
  const handlers = /* @__PURE__ */ new Map();
2313
2579
  for (let [index, { name, value, fullyReactive }] of node.attributes.entries()) {
@@ -2322,7 +2588,7 @@ function combinedEventHandlers(node, status) {
2322
2588
  const handler = node.attributes[handlerIndex];
2323
2589
  combined.set(bindingIndex, {
2324
2590
  index: handlerIndex,
2325
- value: replaceForVarNames(handler.value, status),
2591
+ value: handler.value,
2326
2592
  span: handler.span,
2327
2593
  first: handlerIndex < bindingIndex
2328
2594
  });
@@ -2337,10 +2603,11 @@ function combinedEventHandlers(node, status) {
2337
2603
  function emitBindEvent(varName, eventName, listener, body, combined, status, b) {
2338
2604
  status.imports.add("t_event");
2339
2605
  if (!combined) {
2340
- b.append(`t_event(${varName}, "${eventName}", ${listener});`);
2606
+ b.append(`t_event(${varName}, "${eventName}", ${injectForVarHandler(listener, status)});`);
2341
2607
  return;
2342
2608
  }
2343
2609
  b.append(`t_event(${varName}, "${eventName}", (e) => {`);
2610
+ appendForVarBindings(b, status, combined.value);
2344
2611
  const handlerCall = `((${combined.value}) as ((e: any) => any) | undefined)?.(e);`;
2345
2612
  if (combined.first) {
2346
2613
  addMappedText("", handlerCall, "", combined.span, status, b);
@@ -2352,13 +2619,13 @@ function emitBindEvent(varName, eventName, listener, body, combined, status, b)
2352
2619
  b.append("});");
2353
2620
  }
2354
2621
  function buildEventAttribute(varName, name, value, span, status, b) {
2355
- value = replaceForVarNames(value, status);
2622
+ value = injectForVarHandler(value, status);
2356
2623
  const eventName = name.substring(2);
2357
2624
  status.imports.add("t_event");
2358
2625
  addMappedText(`t_event(${varName}, "${eventName}", `, value, `);`, span, status, b);
2359
2626
  }
2360
2627
  function buildTransitionAttribute(node, varName, name, value, status, b) {
2361
- value = replaceForVarNames(value, status);
2628
+ value = injectForVarHandler(value, status);
2362
2629
  status.imports.add("t_animate");
2363
2630
  let entryVarName = nextVarName("trans_in", status);
2364
2631
  let exitVarName = nextVarName("trans_out", status);
@@ -2369,7 +2636,7 @@ function buildTransitionAttribute(node, varName, name, value, status, b) {
2369
2636
  } else if (name === "transition-in") {
2370
2637
  let outAttribute = node.attributes.find((a) => a.name === "transition-out");
2371
2638
  if (outAttribute && outAttribute.value && outAttribute.fullyReactive) {
2372
- let outValue = outAttribute.value;
2639
+ let outValue = injectForVarHandler(outAttribute.value, status);
2373
2640
  b.append(`const ${entryVarName} = (${value})(${varName});`);
2374
2641
  b.append(`const ${exitVarName} = (${outValue})(${varName});`);
2375
2642
  b.append(`t_animate(${varName}, ${entryVarName}, ${exitVarName});`);
@@ -2423,11 +2690,11 @@ function buildSlotNode(node, status, b) {
2423
2690
  });
2424
2691
  b.append(`const ${propsName} = $watch({`);
2425
2692
  for (let p of props) {
2426
- let value = replaceForVarNames(p.value, status);
2693
+ let value = p.value;
2427
2694
  addMappedText(`${p.name}: `, value, ",", p.span, status, b);
2428
2695
  }
2429
2696
  b.append("});");
2430
- if (runs.length) buildRun("setProps", replaceForVarNames(runs.join("\n"), status), status, b);
2697
+ if (runs.length) buildRun("setProps", runs.join("\n"), status, b);
2431
2698
  }
2432
2699
  const slotParentName = node.parentName;
2433
2700
  const slotAnchorName = node.varName;
@@ -2621,11 +2888,11 @@ const importsMap$1 = {
2621
2888
  t_push_dev_bound: "import { t_push_dev_bound } from \"${folder}/dev\";",
2622
2889
  t_pop_dev_bound: "import { t_pop_dev_bound } from \"${folder}/dev\";"
2623
2890
  };
2624
- function buildCode(template, map, options) {
2891
+ function buildCode(template, map, options, errors = []) {
2625
2892
  let b = new Builder(options?.mapped);
2626
2893
  let imports = /* @__PURE__ */ new Set();
2627
2894
  imports.add("SlotRender");
2628
- buildTemplate(template, map, imports, b, options);
2895
+ buildTemplate(template, map, imports, b, options, errors);
2629
2896
  let startSize = b.toString().length;
2630
2897
  if (imports.size) {
2631
2898
  const folder = options?.renderFolder ?? "@torpor/view";
@@ -2642,7 +2909,7 @@ function buildCode(template, map, options) {
2642
2909
  }
2643
2910
  return b.toString();
2644
2911
  }
2645
- function buildTemplate(template, map, imports, b, options) {
2912
+ function buildTemplate(template, map, imports, b, options, errors = []) {
2646
2913
  let script = template.script.map((s) => s.script).join("\n");
2647
2914
  for (const component of template.components) {
2648
2915
  if (component.markup) script += "\n" + collectMarkupExpressions(component.markup);
@@ -2667,10 +2934,10 @@ function buildTemplate(template, map, imports, b, options) {
2667
2934
  if (/\$batch\b/.test(scriptCode)) imports.add("$batch");
2668
2935
  let currentIndex = 0;
2669
2936
  let current = template.components[0];
2670
- let status = makeStatus(imports, map, current, options);
2937
+ let status = makeStatus(imports, map, current, options, errors);
2671
2938
  let first = true;
2672
2939
  for (let chunk of template.script) if (chunk.script === "/* @params */") {
2673
- if (!first) status = makeStatus(imports, map, current, options);
2940
+ if (!first) status = makeStatus(imports, map, current, options, errors);
2674
2941
  first = false;
2675
2942
  b.append(`
2676
2943
  ${current.markup ? "$parent" : "_$parent"}: ParentNode,
@@ -2722,7 +2989,7 @@ function buildTemplate(template, map, imports, b, options) {
2722
2989
  current = template.components[currentIndex];
2723
2990
  } else addMappedText("", chunk.script, "", chunk.span, status, b);
2724
2991
  }
2725
- function makeStatus(imports, map, current, options) {
2992
+ function makeStatus(imports, map, current, options, errors = []) {
2726
2993
  return {
2727
2994
  imports,
2728
2995
  props: current?.props ?? [],
@@ -2732,11 +2999,12 @@ function makeStatus(imports, map, current, options) {
2732
2999
  map,
2733
3000
  varNames: {},
2734
3001
  fragmentStack: [],
2735
- forVarNames: [],
3002
+ forVars: [],
2736
3003
  ns: false,
2737
3004
  preserveWhitespace: false,
2738
3005
  inHead: false,
2739
- options: options ?? {}
3006
+ options: options ?? {},
3007
+ errors
2740
3008
  };
2741
3009
  }
2742
3010
  //#endregion
@@ -3120,7 +3388,7 @@ function buildElementAttributes(node, status) {
3120
3388
  value = `t_attr(${value})`;
3121
3389
  defaultValue = "\"\"";
3122
3390
  }
3123
- let valueOrDefault = `${value} || ${defaultValue}`;
3391
+ let valueOrDefault = `(${value}) || ${defaultValue}`;
3124
3392
  const propName = name.substring(1);
3125
3393
  attributes.push(`${propName}="\${${valueOrDefault}}"`);
3126
3394
  } else if (name === "class") {
@@ -3137,7 +3405,7 @@ function buildElementAttributes(node, status) {
3137
3405
  attributes.push(`\${t_style(${value}) !== "" ? \`style="\${t_style(${value})}"\` : ""}`);
3138
3406
  } else {
3139
3407
  status.imports.add("t_attr");
3140
- attributes.push(`\${${value} ? \`${name}="\${t_attr(${value})}"\` : ""}`);
3408
+ attributes.push(`\${(${value}) ? \`${name}="\${t_attr(${value})}"\` : ""}`);
3141
3409
  }
3142
3410
  } else if (value != null && reactive) {
3143
3411
  status.imports.add("t_attr");
@@ -3548,13 +3816,15 @@ function build(template, options) {
3548
3816
  if (component.head) trimWhitespace(component.head);
3549
3817
  }
3550
3818
  let map = [];
3819
+ let errors = [];
3551
3820
  return {
3552
- code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options),
3821
+ code: options?.server ? buildServerCode(template, options) : buildCode(template, map, options, errors),
3553
3822
  styles: template.components.map((c) => c.style ? {
3554
3823
  style: buildStyles(c.style, c.style.hash),
3555
3824
  hash: c.style.hash
3556
3825
  } : void 0).filter((c) => c !== void 0),
3557
- map
3826
+ map,
3827
+ errors
3558
3828
  };
3559
3829
  }
3560
3830
  //#endregion
@@ -4595,11 +4865,6 @@ function parseStyleAttribute(status) {
4595
4865
  };
4596
4866
  }
4597
4867
  //#endregion
4598
- //#region src/compile/utils/isComponentNode.ts
4599
- function isComponentNode(node) {
4600
- return node.type === "component";
4601
- }
4602
- //#endregion
4603
4868
  //#region src/compile/parse/scopeStyles.ts
4604
4869
  function scopeStyles(status) {
4605
4870
  let selectors = [];