@yannosay/sinth 0.6.0 → 0.7.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/src/sinth.ts CHANGED
@@ -127,6 +127,10 @@ interface CompileCtx {
127
127
  mixedBlocks: MixedBlockEntry[];
128
128
  mixedCounter: number;
129
129
  logicBlocks: string[];
130
+ ifIdCounter: number;
131
+ exprRegistry: string[];
132
+ exprMap: Map<string, number>;
133
+ loopVars?: Set<string>;
130
134
  }
131
135
 
132
136
  class SinthError extends Error {
@@ -166,7 +170,7 @@ class SinthWarning {
166
170
  }
167
171
  }
168
172
 
169
- /** FNV-1a 32-bit hash → 8-char hex scope id */
173
+ // FNV-1a 32-bit hash → 8-char hex scope id
170
174
  function fnv1a(s: string): string {
171
175
  let h = 0x811c9dc5;
172
176
  for (let i = 0; i < s.length; i++) {
@@ -182,7 +186,7 @@ function camelToKebab(s: string): string {
182
186
  return s.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`);
183
187
  }
184
188
 
185
- /** "w-counter" → "WCounter" */
189
+ // "w-counter" → "WCounter"
186
190
  function tagNameToPascal(tag: string): string {
187
191
  return tag.split("-").map(p => p.charAt(0).toUpperCase() + p.slice(1)).join("");
188
192
  }
@@ -936,6 +940,14 @@ private parseArrayLiteral(): Literal {
936
940
  while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
937
941
  if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
938
942
  if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
943
+ if (this.check(TT.LPAREN)) {
944
+ const loc = this.peek().loc;
945
+ const expr = this.parseExpression();
946
+ if (expr) {
947
+ children.push({ kind: "expr", expression: expr, loc });
948
+ }
949
+ continue;
950
+ }
939
951
  if (this.check(TT.STRING)) {
940
952
  const loc = this.peek().loc;
941
953
  children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
@@ -1030,6 +1042,30 @@ private parseArrayLiteral(): Literal {
1030
1042
  `Unexpected token '${this.peek().value}' in if/else body`,
1031
1043
  this.peek().loc,
1032
1044
  );
1045
+
1046
+ // reject implicit concatenation only after expression children
1047
+ if (children.length > 0) {
1048
+ const lastChild = children[children.length - 1];
1049
+ if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
1050
+ const nextTT = this.tokens[this.pos]?.type;
1051
+ if (
1052
+ nextTT === TT.STRING || nextTT === TT.NUMBER ||
1053
+ nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
1054
+ (nextTT === TT.IDENT &&
1055
+ this.tokens[this.pos]?.value !== "var" &&
1056
+ this.tokens[this.pos]?.value !== "if" &&
1057
+ this.tokens[this.pos]?.value !== "for" &&
1058
+ this.tokens[this.pos]?.value !== "else" &&
1059
+ this.tokens[this.pos]?.value !== "and" &&
1060
+ this.tokens[this.pos]?.value !== "or")
1061
+ ) {
1062
+ throw new SinthError(
1063
+ `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
1064
+ this.peek().loc,
1065
+ );
1066
+ }
1067
+ }
1068
+ }
1033
1069
  }
1034
1070
 
1035
1071
  return children;
@@ -1045,23 +1081,36 @@ private parseArrayLiteral(): Literal {
1045
1081
  let indexVar: string | undefined;
1046
1082
  if (this.check(TT.COMMA)) {
1047
1083
  this.consume(TT.COMMA);
1048
- keyVar = firstVar;
1049
- itemVar = this.consume(TT.IDENT).value;
1084
+ const secondVar = this.consume(TT.IDENT).value;
1050
1085
  if (this.check(TT.COMMA)) {
1086
+ // three variables: key, value, index
1051
1087
  this.consume(TT.COMMA);
1088
+ keyVar = firstVar;
1089
+ itemVar = secondVar;
1052
1090
  indexVar = this.consume(TT.IDENT).value;
1091
+ } else {
1092
+ // two variables – tentatively value, index; fix after seeing source type
1093
+ itemVar = firstVar;
1094
+ indexVar = secondVar;
1053
1095
  }
1054
1096
  } else {
1097
+ // one variable: item only
1055
1098
  itemVar = firstVar;
1056
- if (this.check(TT.COMMA)) {
1057
- this.consume(TT.COMMA);
1058
- indexVar = this.consume(TT.IDENT).value;
1059
- }
1060
1099
  }
1061
1100
  if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
1062
1101
  this.consume(TT.KW_IN);
1063
1102
  const arrayVar = this.consume(TT.IDENT).value;
1064
1103
 
1104
+ // If two variables and the source is an object, swap to key, value
1105
+ if (keyVar === undefined && indexVar !== undefined) {
1106
+ const srcDecl = this._varDecls.find(d => d.name === arrayVar);
1107
+ if (srcDecl && srcDecl.varType === "obj") {
1108
+ keyVar = itemVar; // first → key
1109
+ itemVar = indexVar; // second → value
1110
+ indexVar = undefined;
1111
+ }
1112
+ }
1113
+
1065
1114
  if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after for..in expression", this.peek().loc);
1066
1115
  this.consume(TT.LBRACE);
1067
1116
  this.loopVar = itemVar;
@@ -1152,6 +1201,14 @@ private parseArrayLiteral(): Literal {
1152
1201
  private parseChildList(): Child[] {
1153
1202
  const children: Child[] = [];
1154
1203
  while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1204
+ if (this.check(TT.LPAREN)) {
1205
+ const loc = this.peek().loc;
1206
+ const expr = this.parseExpression();
1207
+ if (expr) {
1208
+ children.push({ kind: "expr", expression: expr, loc });
1209
+ }
1210
+ continue;
1211
+ }
1155
1212
  if (this.check(TT.STRING)) {
1156
1213
  const loc = this.peek().loc;
1157
1214
  let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
@@ -1299,6 +1356,29 @@ private parseArrayLiteral(): Literal {
1299
1356
  }
1300
1357
  }
1301
1358
  else throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1359
+ // reject implicit concatenation only after expression children
1360
+ if (children.length > 0) {
1361
+ const lastChild = children[children.length - 1];
1362
+ if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
1363
+ const nextTT = this.tokens[this.pos]?.type;
1364
+ if (
1365
+ nextTT === TT.STRING || nextTT === TT.NUMBER ||
1366
+ nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
1367
+ (nextTT === TT.IDENT &&
1368
+ this.tokens[this.pos]?.value !== "var" &&
1369
+ this.tokens[this.pos]?.value !== "if" &&
1370
+ this.tokens[this.pos]?.value !== "for" &&
1371
+ this.tokens[this.pos]?.value !== "else" &&
1372
+ this.tokens[this.pos]?.value !== "and" &&
1373
+ this.tokens[this.pos]?.value !== "or")
1374
+ ) {
1375
+ throw new SinthError(
1376
+ `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
1377
+ this.peek().loc,
1378
+ );
1379
+ }
1380
+ }
1381
+ }
1302
1382
  }
1303
1383
  return children;
1304
1384
  }
@@ -1942,7 +2022,7 @@ function extractCSSBlock(css: string, openBrace: number): { content: string; end
1942
2022
 
1943
2023
  // expression -> js compiler
1944
2024
 
1945
- function compileExprToJS(expr: Expression): string {
2025
+ function compileExprToJS(expr: Expression, loopVars?: Set<string>): string {
1946
2026
  switch (expr.kind) {
1947
2027
  case "literal":
1948
2028
  if (!expr.value) return "null";
@@ -1951,23 +2031,26 @@ function compileExprToJS(expr: Expression): string {
1951
2031
  if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
1952
2032
  return "null";
1953
2033
  case "variable":
2034
+ if (loopVars && expr.name && loopVars.has(expr.name)) {
2035
+ return `_ctx.${expr.name}`;
2036
+ }
1954
2037
  return expr.name ?? "undefined";
1955
2038
  case "binary": {
1956
- const l = compileExprToJS(expr.left!);
1957
- const r = compileExprToJS(expr.right!);
2039
+ const l = compileExprToJS(expr.left!, loopVars);
2040
+ const r = compileExprToJS(expr.right!, loopVars);
1958
2041
  const o = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op!;
1959
2042
  return `(${l} ${o} ${r})`;
1960
2043
  }
1961
2044
  case "unary": {
1962
2045
  const o = expr.op === "not" ? "!" : expr.op!;
1963
- return `${o}(${compileExprToJS(expr.operand!)})`;
2046
+ return `${o}(${compileExprToJS(expr.operand!, loopVars)})`;
1964
2047
  }
1965
2048
  case "assign": {
1966
- const v = expr.right ? compileExprToJS(expr.right) : "null";
2049
+ const v = expr.right ? compileExprToJS(expr.right, loopVars) : "null";
1967
2050
  return `${expr.target} ${expr.op} ${v}`;
1968
2051
  }
1969
2052
  case "index":
1970
- return `${compileExprToJS(expr.object!)}[${compileExprToJS(expr.key!)}]`;
2053
+ return `${compileExprToJS(expr.object!, loopVars)}[${compileExprToJS(expr.key!, loopVars)}]`;
1971
2054
  case "postfix":
1972
2055
  return `${expr.target}${expr.op}`;
1973
2056
  default:
@@ -2040,7 +2123,18 @@ function resolveBuiltinTag(
2040
2123
  return { tag: name.toLowerCase(), voidEl: false };
2041
2124
  }
2042
2125
 
2043
- function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
2126
+ function registerExpr(ctx: CompileCtx, expr: Expression): number {
2127
+ const jsExpr = compileExprToJS(expr, ctx.loopVars);
2128
+ const existing = ctx.exprMap.get(jsExpr);
2129
+ if (existing !== undefined) return existing;
2130
+ const id = ctx.exprRegistry.length;
2131
+ ctx.exprRegistry.push(jsExpr);
2132
+ ctx.exprMap.set(jsExpr, id);
2133
+ return id;
2134
+ }
2135
+
2136
+
2137
+ function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx?: CompileCtx): string {
2044
2138
  const { name, value } = attr;
2045
2139
  if (value === null) return name;
2046
2140
  if (value.kind === "null") return "";
@@ -2062,11 +2156,13 @@ if (name === "delay") {
2062
2156
  if (v.startsWith("__EXPR__")) {
2063
2157
  try {
2064
2158
  const expr: Expression = JSON.parse(v.substring(8));
2065
- const jsExpr = compileExprToJS(expr);
2066
- return `data-sinth-delay-expr="${escAttr(jsExpr)}" style="display:none"`;
2159
+ const id = registerExpr(ctx, expr);
2160
+ return `data-sinth-delay-expr-id="${id}" style="display:none"`;
2067
2161
  } catch {}
2068
2162
  }
2069
- return `data-sinth-delay-expr="${escAttr(v)}" style="display:none"`;
2163
+ // plain variable name – register as expression
2164
+ const id = registerExpr(ctx, { kind: "variable", name: v });
2165
+ return `data-sinth-delay-expr-id="${id}" style="display:none"`;
2070
2166
  }
2071
2167
 
2072
2168
  if (name === "checked") {
@@ -2134,6 +2230,7 @@ function interpolateAttr(text: string, params: Map<string, string>): string {
2134
2230
  return s.replace(/\x00LB\x00/g, "{");
2135
2231
  }
2136
2232
 
2233
+
2137
2234
  function renderChild(
2138
2235
  child: Child,
2139
2236
  ctx: CompileCtx,
@@ -2147,8 +2244,15 @@ function renderChild(
2147
2244
  return renderText(child.value, params);
2148
2245
 
2149
2246
  case "expr": {
2150
- const jsExpr = compileExprToJS(child.expression);
2151
- return `<span class="sinth-expr" data-expr="${escAttr(jsExpr)}"></span>`;
2247
+ if (child.expression.kind === "literal" && child.expression.value) {
2248
+ return esc(litToString(child.expression.value));
2249
+ }
2250
+ if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
2251
+ const exprId = registerExpr(ctx, child.expression);
2252
+ return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
2253
+ }
2254
+ const exprId = registerExpr(ctx, child.expression);
2255
+ return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
2152
2256
  }
2153
2257
 
2154
2258
  case "assign_stmt": {
@@ -2160,7 +2264,16 @@ function renderChild(
2160
2264
  return renderIfBlock(child, ctx, params, depth);
2161
2265
 
2162
2266
  case "for": {
2267
+ // collect loop‑variable names
2268
+ const loopVars = new Set<string>();
2269
+ loopVars.add(child.itemVar);
2270
+ if (child.keyVar) loopVars.add(child.keyVar);
2271
+ if (child.indexVar) loopVars.add(child.indexVar);
2272
+ // set them on ctx for compilation of the body
2273
+ const prev = ctx.loopVars;
2274
+ ctx.loopVars = loopVars;
2163
2275
  const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2276
+ ctx.loopVars = prev; // restore
2164
2277
  const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
2165
2278
  const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
2166
2279
  return (
@@ -2194,11 +2307,13 @@ depth: number,
2194
2307
 
2195
2308
  // pure DOM
2196
2309
  if (!hasAssign && hasComp) {
2310
+ const tplId = ctx.ifIdCounter++;
2311
+ const condId = registerExpr(ctx, ifBlock.condition);
2197
2312
  const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2198
2313
  const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
2199
2314
  return (
2200
- `<template data-sinth-if="${escAttr(condJS)}">${bodyHTML}</template>` +
2201
- (elseHTML ? `<template data-sinth-else>${elseHTML}</template>` : "")
2315
+ `<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}">${bodyHTML}</template>` +
2316
+ (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
2202
2317
  );
2203
2318
  }
2204
2319
 
@@ -2248,7 +2363,8 @@ depth: number,
2248
2363
  }
2249
2364
  }
2250
2365
 
2251
- ctx.mixedBlocks.push({ id, conditionJS: condJS, ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
2366
+ const condId = registerExpr(ctx, ifBlock.condition);
2367
+ ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
2252
2368
 
2253
2369
  return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
2254
2370
  }
@@ -2280,7 +2396,7 @@ function renderCompUse(
2280
2396
  if (customEl) {
2281
2397
  const attrParts = [`data-s="${ctx.scopeHash}"`];
2282
2398
  for (const attr of use.attrs) {
2283
- const r = renderAttr(attr, params);
2399
+ const r = renderAttr(attr, params, ctx);
2284
2400
  if (r) attrParts.push(r);
2285
2401
  }
2286
2402
  const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
@@ -2310,7 +2426,7 @@ function renderCompUse(
2310
2426
  if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
2311
2427
  continue;
2312
2428
  }
2313
- const rendered = renderAttr(attr, params);
2429
+ const rendered = renderAttr(attr, params, ctx);
2314
2430
  if (rendered) attrParts.push(rendered);
2315
2431
  }
2316
2432
 
@@ -2539,14 +2655,15 @@ function buildRuntime(opts: {
2539
2655
  logicBlocks: string[];
2540
2656
  mixedBlocks: MixedBlockEntry[];
2541
2657
  assignedVars: Set<string>;
2658
+ exprRegistry: string[];
2542
2659
  }): string {
2543
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars } = opts;
2660
+ const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
2544
2661
 
2545
2662
 
2546
2663
  const needsExpr = bodyHTML.includes("sinth-expr");
2547
2664
  const needsIf = bodyHTML.includes("data-sinth-if");
2548
2665
  const needsFor = bodyHTML.includes("data-sinth-for");
2549
- const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr"));
2666
+ const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
2550
2667
  const needsMixed = mixedBlocks.length > 0;
2551
2668
  const needsLogic = logicBlocks.length > 0;
2552
2669
  const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
@@ -2593,8 +2710,8 @@ return `var ${v.name} = ${val};`;
2593
2710
  if (needsFor) {
2594
2711
  renderBody += `
2595
2712
  document.querySelectorAll('template[data-sinth-for]').forEach(function(t) {
2596
- var source;
2597
- try { source = eval(t.dataset.sinthFor); } catch(e) { source = []; }
2713
+ var source = window[t.dataset.sinthFor];
2714
+ if (source === undefined) source = [];
2598
2715
  var newHash = '';
2599
2716
  try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
2600
2717
  if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
@@ -2631,27 +2748,32 @@ return `var ${v.name} = ${val};`;
2631
2748
  var _user = _v;
2632
2749
  var frag = document.createRange().createContextualFragment(t.innerHTML);
2633
2750
  frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2634
- try {
2635
- if (el.dataset.expr === _item) {
2636
- el.textContent = _v;
2637
- } else if (_key && el.dataset.expr === _key) {
2638
- el.textContent = _k;
2639
- } else if (el.dataset.expr && (el.dataset.expr.indexOf(_item) !== -1 || (_key && el.dataset.expr.indexOf(_key) !== -1) || (_idx && el.dataset.expr.indexOf(_idx) !== -1))) {
2640
- eval('var ' + _item + ' = _user;');
2641
- if (_key) eval('var ' + _key + ' = _k;');
2642
- if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;');
2643
- el.textContent = eval(el.dataset.expr);
2644
- el.classList.remove('sinth-expr'); // Mark as processed
2645
- }
2751
+ try {
2752
+ var exprFn = __X[el.dataset.exprId];
2753
+ if (!exprFn) return;
2754
+ var _ctx = {};
2755
+ if (_item) _ctx[_item] = _v;
2756
+ if (_key) _ctx[_key] = _k;
2757
+ if (_idx) _ctx[_idx] = _loopIdx - 1;
2758
+ el.textContent = exprFn(_ctx);
2759
+ el.classList.remove('sinth-expr');
2646
2760
  } catch(e) {}
2647
2761
  });
2648
- frag.querySelectorAll('template[data-sinth-if]').forEach(function(ifT) {
2762
+ frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
2763
+ var condFn = __X[ifT.dataset.sinthIfExpr];
2764
+ var _ctx = {};
2765
+ if (_item) _ctx[_item] = _v;
2766
+ if (_key) _ctx[_key] = _k;
2767
+ if (_idx) _ctx[_idx] = _loopIdx - 1;
2649
2768
  var cond = false;
2650
- try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;'); if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;'); cond = eval(ifT.dataset.sinthIf); } catch(e) {}
2769
+ try { if (condFn) cond = condFn(_ctx); } catch(e) {}
2651
2770
  if (cond) {
2652
2771
  var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
2653
2772
  ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2654
- try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;'); if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2773
+ try {
2774
+ var exprFn2 = __X[el2.dataset.exprId];
2775
+ if (exprFn2) el2.textContent = exprFn2(_ctx);
2776
+ } catch(e) {}
2655
2777
  });
2656
2778
  ifT.parentNode.insertBefore(ifContent, ifT);
2657
2779
  } else {
@@ -2659,7 +2781,10 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2659
2781
  if (elseT && elseT.hasAttribute('data-sinth-else')) {
2660
2782
  var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
2661
2783
  elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2662
- try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;'); if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2784
+ try {
2785
+ var exprFn2 = __X[el2.dataset.exprId];
2786
+ if (exprFn2) el2.textContent = exprFn2(_ctx);
2787
+ } catch(e) {}
2663
2788
  });
2664
2789
  ifT.parentNode.insertBefore(elseContent, ifT);
2665
2790
  }
@@ -2673,14 +2798,16 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2673
2798
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2674
2799
  else el.style.display = '';
2675
2800
  });
2676
- frag.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2801
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2677
2802
  if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
2678
2803
  el.dataset.sinthDelayDone = '1';
2679
2804
  try {
2680
- eval('var ' + _item + ' = _user;');
2681
- if (_key) eval('var ' + _key + ' = _k;');
2682
- if (_idx) eval('var ' + _idx + ' = _loopIdx - 1;');
2683
- var ms = eval(el.dataset.sinthDelayExpr) || 0;
2805
+ var fn = __X[el.dataset.sinthDelayExprId];
2806
+ var _ctx = {};
2807
+ if (_item) _ctx[_item] = _v;
2808
+ if (_key) _ctx[_key] = _k;
2809
+ if (_idx) _ctx[_idx] = _loopIdx - 1;
2810
+ var ms = fn ? parseInt(fn(_ctx)) || 0 : 0;
2684
2811
  el.style.display = 'none';
2685
2812
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2686
2813
  else el.style.display = '';
@@ -2693,10 +2820,11 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2693
2820
  }
2694
2821
  if (needsIf) {
2695
2822
  renderBody += `
2696
- document.querySelectorAll('template[data-sinth-if]').forEach(function(t) {
2697
- var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + t.dataset.sinthIf + '"]');
2698
- var cond;
2699
- try { cond = eval(t.dataset.sinthIf); } catch(e) { cond = false; }
2823
+ document.querySelectorAll('template[data-sinth-if-expr]').forEach(function(t) {
2824
+ var ifId = t.dataset.sinthIfId;
2825
+ var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
2826
+ var condFn = __X[t.dataset.sinthIfExpr];
2827
+ var cond = condFn ? condFn() : false;
2700
2828
  if (cond) {
2701
2829
  if (anchor) {
2702
2830
  var cur = anchor.nextSibling;
@@ -2704,12 +2832,15 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2704
2832
  } else {
2705
2833
  anchor = document.createElement('span');
2706
2834
  anchor.style.display = 'none';
2707
- anchor.dataset.sinthIfAnchor = t.dataset.sinthIf;
2835
+ anchor.dataset.sinthIfAnchor = ifId;
2708
2836
  t.parentNode.insertBefore(anchor, t);
2709
2837
  }
2710
2838
  var frag = document.createRange().createContextualFragment(t.innerHTML);
2711
2839
  frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2712
- try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2840
+ try {
2841
+ var exprFn = __X[el.dataset.exprId];
2842
+ if (exprFn) el.textContent = exprFn();
2843
+ } catch(e) {}
2713
2844
  });
2714
2845
  frag.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2715
2846
  if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
@@ -2719,9 +2850,10 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2719
2850
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2720
2851
  else el.style.display = '';
2721
2852
  });
2722
- frag.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2853
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2723
2854
  try {
2724
- var ms = eval(el.dataset.sinthDelayExpr) || 0;
2855
+ var fn = __X[el.dataset.sinthDelayExprId];
2856
+ var ms = fn ? parseInt(fn()) || 0 : 0;
2725
2857
  el.style.display = '';
2726
2858
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2727
2859
  } catch(e) {}
@@ -2735,19 +2867,22 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2735
2867
  }
2736
2868
  var elseT = t.nextElementSibling;
2737
2869
  if (elseT && elseT.dataset && elseT.hasAttribute('data-sinth-else')) {
2738
- var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + t.dataset.sinthIf + '"]');
2870
+ var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
2739
2871
  if (ea) {
2740
2872
  var cur3 = ea.nextSibling;
2741
2873
  while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
2742
2874
  } else {
2743
2875
  ea = document.createElement('span');
2744
2876
  ea.style.display = 'none';
2745
- ea.dataset.sinthIfAnchor = '__else__' + t.dataset.sinthIf;
2877
+ ea.dataset.sinthIfAnchor = '__else__' + ifId;
2746
2878
  t.parentNode.insertBefore(ea, t);
2747
2879
  }
2748
2880
  var ef = document.createRange().createContextualFragment(elseT.innerHTML);
2749
2881
  ef.querySelectorAll('.sinth-expr').forEach(function(el) {
2750
- try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2882
+ try {
2883
+ var exprFn = __X[el.dataset.exprId];
2884
+ if (exprFn) el.textContent = exprFn();
2885
+ } catch(e) {}
2751
2886
  });
2752
2887
  ef.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2753
2888
  var ms = parseInt(el.dataset.sinthDelay) || 0;
@@ -2755,16 +2890,17 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2755
2890
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2756
2891
  else el.style.display = '';
2757
2892
  });
2758
- ef.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2893
+ ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2759
2894
  try {
2760
- var ms = eval(el.dataset.sinthDelayExpr) || 0;
2895
+ var fn = __X[el.dataset.sinthDelayExprId];
2896
+ var ms = fn ? parseInt(fn()) || 0 : 0;
2761
2897
  el.style.display = '';
2762
2898
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2763
2899
  } catch(e) {}
2764
2900
  });
2765
2901
  t.parentNode.insertBefore(ef, t);
2766
2902
  } else {
2767
- var ea2 = t.parentNode ? t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + t.dataset.sinthIf + '"]') : null;
2903
+ var ea2 = t.parentNode ? t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]') : null;
2768
2904
  if (ea2) {
2769
2905
  var ec = ea2.nextSibling;
2770
2906
  while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
@@ -2776,34 +2912,39 @@ try { eval('var ' + _item + ' = _user;'); if (_key) eval('var ' + _key + ' = _k;
2776
2912
  `;
2777
2913
  }
2778
2914
 
2779
-
2780
2915
  // mixed if/else blocks
2781
2916
  if (needsMixed) {
2782
2917
  for (const mb of mixedBlocks) {
2783
2918
  const ifHTMLJS = JSON.stringify(mb.ifHTML);
2784
2919
  const elseHTMLJS = JSON.stringify(mb.elseHTML);
2785
- const hasDelay = mb.ifHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay");
2920
+ const hasDelay = mb.ifHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay-expr-id");
2786
2921
  renderBody += `
2787
2922
  (function() {
2788
2923
  var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
2789
2924
  if (__el) {
2790
- var __cond;
2791
- try { __cond = (${mb.conditionJS}); } catch(e) { __cond = false; }
2925
+ var condFn = __X[${mb.conditionJS}];
2926
+ var __cond = condFn ? condFn() : false;
2792
2927
  if (__cond) {
2793
2928
  ${mb.ifJS ? mb.ifJS : ""} __el.innerHTML = ${ifHTMLJS};
2794
2929
  } else {
2795
2930
  ${mb.elseJS ? mb.elseJS : ""} __el.innerHTML = ${elseHTMLJS};
2796
2931
  }
2797
2932
  __el.querySelectorAll('.sinth-expr').forEach(function(e) {
2798
- try { e.textContent = eval(e.dataset.expr); } catch(ex) {}
2933
+ try {
2934
+ var exprFn = __X[e.dataset.exprId];
2935
+ if (exprFn) e.textContent = exprFn();
2936
+ } catch(ex) {}
2799
2937
  });
2800
- __el.querySelectorAll('template[data-sinth-if]').forEach(function(innerT) {
2801
- var innerCond;
2802
- try { innerCond = eval(innerT.dataset.sinthIf); } catch(e) { innerCond = false; }
2938
+ __el.querySelectorAll('template[data-sinth-if-expr]').forEach(function(innerT) {
2939
+ var innerCondFn = __X[innerT.dataset.sinthIfExpr];
2940
+ var innerCond = innerCondFn ? innerCondFn() : false;
2803
2941
  if (innerCond) {
2804
2942
  var innerFrag = document.createRange().createContextualFragment(innerT.innerHTML);
2805
2943
  innerFrag.querySelectorAll('.sinth-expr').forEach(function(e2) {
2806
- try { e2.textContent = eval(e2.dataset.expr); } catch(ex) {}
2944
+ try {
2945
+ var exprFn2 = __X[e2.dataset.exprId];
2946
+ if (exprFn2) e2.textContent = exprFn2();
2947
+ } catch(ex) {}
2807
2948
  });
2808
2949
  innerT.parentNode.insertBefore(innerFrag, innerT);
2809
2950
  } else {
@@ -2811,23 +2952,26 @@ __el.querySelectorAll('template[data-sinth-if]').forEach(function(innerT) {
2811
2952
  if (innerElse && innerElse.hasAttribute('data-sinth-else')) {
2812
2953
  var innerElseFrag = document.createRange().createContextualFragment(innerElse.innerHTML);
2813
2954
  innerElseFrag.querySelectorAll('.sinth-expr').forEach(function(e2) {
2814
- try { e2.textContent = eval(e2.dataset.expr); } catch(ex) {}
2955
+ try {
2956
+ var exprFn2 = __X[e2.dataset.exprId];
2957
+ if (exprFn2) e2.textContent = exprFn2();
2958
+ } catch(ex) {}
2815
2959
  });
2816
2960
  innerT.parentNode.insertBefore(innerElseFrag, innerT);
2817
2961
  }
2818
2962
  }
2819
2963
  });
2820
2964
  ${hasDelay ? `
2821
- // Handle delays for this mixed block
2822
2965
  __el.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2823
2966
  var ms = parseInt(el.dataset.sinthDelay) || 0;
2824
- el.style.display = 'none'; // Ensure hidden before timeout
2967
+ el.style.display = 'none';
2825
2968
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2826
2969
  else el.style.display = '';
2827
2970
  });
2828
- __el.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2971
+ __el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2829
2972
  try {
2830
- var ms = parseInt(eval(el.dataset.sinthDelayExpr)) || 0;
2973
+ var fn = __X[el.dataset.sinthDelayExprId];
2974
+ var ms = fn ? parseInt(fn()) || 0 : 0;
2831
2975
  el.style.display = 'none';
2832
2976
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2833
2977
  else el.style.display = '';
@@ -2843,10 +2987,10 @@ else el.style.display = '';
2843
2987
  // set input vals from bound vars
2844
2988
  renderBody += `
2845
2989
  document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
2846
- try { el.value = eval(el.dataset.sinthValue) || ''; } catch(e) {}
2990
+ try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
2847
2991
  });
2848
2992
  document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
2849
- try { el.checked = !!eval(el.dataset.sinthChecked); } catch(e) {}
2993
+ try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
2850
2994
  });
2851
2995
  `;
2852
2996
 
@@ -2854,7 +2998,10 @@ else el.style.display = '';
2854
2998
  if (needsExpr) {
2855
2999
  renderBody += `
2856
3000
  document.querySelectorAll('.sinth-expr').forEach(function(el) {
2857
- try { el.textContent = eval(el.dataset.expr); } catch(e) {}
3001
+ try {
3002
+ var exprFn = __X[el.dataset.exprId];
3003
+ if (exprFn) el.textContent = exprFn({});
3004
+ } catch(e) {}
2858
3005
  });
2859
3006
  `;
2860
3007
  }
@@ -2870,9 +3017,10 @@ setTimeout(function() {
2870
3017
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2871
3018
  else el.style.display = '';
2872
3019
  });
2873
- document.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
3020
+ document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) {
2874
3021
  try {
2875
- var ms = parseInt(eval(el.dataset.sinthDelayExpr)) || 0;
3022
+ var fn = __X[el.dataset.sinthDelayExprId];
3023
+ var ms = fn ? parseInt(fn()) || 0 : 0;
2876
3024
  if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2877
3025
  else el.style.display = '';
2878
3026
  } catch(e) {}
@@ -2880,6 +3028,13 @@ setTimeout(function() {
2880
3028
  }, 0);
2881
3029
  ` : "";
2882
3030
 
3031
+ // Build the expression registry as a JS array
3032
+ const exprArrayJS = opts.exprRegistry && opts.exprRegistry.length > 0
3033
+ ? `var __X = [${opts.exprRegistry.map((js) => {
3034
+ return `function(_ctx){ return ${js}; }`;
3035
+ }).join(",")}];\n`
3036
+ : "";
3037
+
2883
3038
  return `// Sinth compiled runtime
2884
3039
  ${varLines}
2885
3040
  ${needsFor ? `function hashString(str) {
@@ -2892,6 +3047,7 @@ ${needsFor ? `function hashString(str) {
2892
3047
  return String(hash);
2893
3048
  }
2894
3049
  ` : ""}
3050
+ ${exprArrayJS}
2895
3051
  ${needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : ""}
2896
3052
  ${delayBlock}`;
2897
3053
  }
@@ -2924,6 +3080,9 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2924
3080
  mixedBlocks: [],
2925
3081
  mixedCounter: 0,
2926
3082
  logicBlocks: [],
3083
+ ifIdCounter: 0,
3084
+ exprRegistry: [],
3085
+ exprMap: new Map(),
2927
3086
  };
2928
3087
 
2929
3088
  if (!file.isPage) {
@@ -2973,6 +3132,7 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2973
3132
  logicBlocks: ctx.logicBlocks,
2974
3133
  mixedBlocks: ctx.mixedBlocks,
2975
3134
  assignedVars,
3135
+ exprRegistry: ctx.exprRegistry,
2976
3136
  });
2977
3137
 
2978
3138
  const scriptTags: string[] = [];