@yannosay/sinth 1.8.5 → 1.11.6

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.
@@ -1,5 +1,3 @@
1
- import * as path from "path";
2
- import * as fs from "fs";
3
1
  import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, StyleBlock, CompDef, ParamDecl, VarDeclaration, SinthFile, CompileCtx, MixedBlockEntry, SinthError, SinthWarning, TT, AssignStmt, MetaEntry } from "./types.ts";
4
2
  import { Parser } from "./parser.ts";
5
3
  import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal, interpolateAttr, renderText } from "../utils.ts";
@@ -15,7 +13,7 @@ import { buildHeadData, renderHead, HeadData } from "./head-builder.ts";
15
13
  import { compileCustomElement } from "./runtime/custom-element.ts";
16
14
 
17
15
  const EVENT_RE = /^on[A-Z]/;
18
- function eventAttrName(name: string): string | null {
16
+ export function eventAttrName(name: string): string | null {
19
17
  return EVENT_RE.test(name) ? name.toLowerCase() : null;
20
18
  }
21
19
 
@@ -49,7 +47,7 @@ export const INLINE_STYLE_PROPS = new Set([
49
47
  function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: CompileCtx): string | null {
50
48
  const paramMap = new Map<string, string>();
51
49
  for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
52
- paramMap.set(fnDef.params[i].name, compileExprToJS(args[i], ctx.loopVars));
50
+ paramMap.set(fnDef.params[i].name, compileExprToJS(args[i], ctx.loopVars, ctx.namespace));
53
51
  }
54
52
  const subExpr = (expr: Expression): Expression => {
55
53
  if (expr.kind === "variable" && expr.name && paramMap.has(expr.name)) {
@@ -102,22 +100,72 @@ function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: Compile
102
100
  for (const c of fnDef.body) {
103
101
  const substituted = subChild(c);
104
102
  if (substituted.kind === "assign_stmt") {
105
- statements.push(compileExprToJS(substituted.expression) + ";");
103
+ statements.push(compileExprToJS(substituted.expression, ctx.loopVars, ctx.namespace, ctx.declaredVars) + ";");
106
104
  } else if (substituted.kind === "expr") {
107
- statements.push(compileExprToJS((substituted as any).expression) + ";");
105
+ statements.push(compileExprToJS((substituted as any).expression, ctx.loopVars, ctx.namespace, ctx.declaredVars) + ";");
108
106
  } else if (substituted.kind === "if") {
109
- statements.push(compileIfToJS(substituted as IfBlock));
107
+ statements.push(compileIfToJS(substituted as IfBlock, ctx.loopVars, ctx.namespace, ctx.declaredVars));
110
108
  } else if (substituted.kind === "return") {
111
109
  } else if (substituted.kind === "for") {
112
110
  const fl = substituted as any;
111
+ const innerLoopVars = new Set<string>();
112
+ if (ctx.loopVars) {
113
+ for (const v of ctx.loopVars) {
114
+ if (v !== fl.itemVar && v !== fl.indexVar && v !== fl.keyVar) {
115
+ innerLoopVars.add(v);
116
+ }
117
+ }
118
+ }
113
119
  const bodyStmts = fl.body.map((bc: any) => {
114
120
  const s = subChild(bc);
115
- if (s.kind === "assign_stmt") return compileExprToJS(s.expression) + ";";
116
- if (s.kind === "if") return compileIfToJS(s);
117
- if (s.kind === "expr") return compileExprToJS(s.expression) + ";";
121
+ if (s.kind === "assign_stmt") return compileExprToJS(s.expression, innerLoopVars, ctx.namespace, ctx.declaredVars) + ";";
122
+ if (s.kind === "if") return compileIfToJS(s, innerLoopVars, ctx.namespace, ctx.declaredVars);
123
+ if (s.kind === "expr") return compileExprToJS(s.expression, innerLoopVars, ctx.namespace, ctx.declaredVars) + ";";
118
124
  return "";
119
125
  }).filter(Boolean).join(" ");
120
- statements.push(`for (let ${fl.itemVar} of ${fl.arrayVar}) { ${bodyStmts} }`);
126
+ const nsArrayVar = (ctx.namespace && ctx.declaredVars && ctx.declaredVars.has(fl.arrayVar)) ? ctx.namespace + "_" + fl.arrayVar : fl.arrayVar;
127
+ if (fl.indexVar) {
128
+ const alreadyDeclared = fnDef.body.some((bc: any) => bc.kind === "var" && bc.name === fl.indexVar);
129
+ if (!alreadyDeclared) {
130
+ statements.push(`let ${fl.indexVar} = 0;`);
131
+ }
132
+ statements.push(`for (let ${fl.itemVar} of ${nsArrayVar}) { ${bodyStmts} ${fl.indexVar} = ${fl.indexVar} + 1; }`);
133
+ } else {
134
+ statements.push(`for (let ${fl.itemVar} of ${nsArrayVar}) { ${bodyStmts} }`);
135
+ }
136
+ } else if (substituted.kind === "var") {
137
+ const vd = substituted as VarDeclaration;
138
+ let initJS: string;
139
+ if (vd.value) {
140
+ const lit = vd.value;
141
+ if (lit.kind === "str") {
142
+ if (lit.value.startsWith("__VAR__")) {
143
+ const varName = lit.value.slice(7);
144
+ initJS = paramMap.has(varName) ? paramMap.get(varName)! : varName;
145
+ } else if (lit.value.startsWith("__ARR__")) {
146
+ initJS = lit.value.slice(7);
147
+ } else if (lit.value.startsWith("__EXPR__")) {
148
+ try {
149
+ const innerExpr: Expression = JSON.parse(lit.value.substring(8));
150
+ initJS = compileExprToJS(subExpr(innerExpr), ctx.loopVars, ctx.namespace);
151
+ } catch { initJS = JSON.stringify(lit.value); }
152
+ } else {
153
+ initJS = JSON.stringify(lit.value);
154
+ }
155
+ } else if (lit.kind === "num") {
156
+ initJS = String(lit.value);
157
+ } else if (lit.kind === "bool") {
158
+ initJS = String(lit.value);
159
+ } else if (lit.kind === "null") {
160
+ initJS = "null";
161
+ } else {
162
+ initJS = "null";
163
+ }
164
+ } else {
165
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]", obj: "{}" };
166
+ initJS = defaults[vd.varType] ?? "undefined";
167
+ }
168
+ statements.push(`let ${vd.name} = ${initJS};`);
121
169
  }
122
170
  }
123
171
  if (statements.length === 0) return null;
@@ -141,7 +189,7 @@ export function resolveBuiltinTag(
141
189
  }
142
190
 
143
191
  export function registerExpr(ctx: CompileCtx, expr: Expression): number {
144
- let jsExpr = compileExprToJS(expr, ctx.loopVars);
192
+ let jsExpr = compileExprToJS(expr, ctx.loopVars, ctx.namespace, ctx.declaredVars);
145
193
  if (ctx.scopePrefix && ctx.scopeVar && expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
146
194
  jsExpr = `_ctx.${ctx.scopePrefix}${expr.name}`;
147
195
  }
@@ -163,6 +211,7 @@ function emitCEAction(ctx: CompileCtx, eventName: string, handlerBody: string):
163
211
 
164
212
  export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: CompileCtx): string {
165
213
  const { name, value } = attr;
214
+ const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
166
215
  if (value === null) return name;
167
216
  if (value.kind === "null") return "";
168
217
  if (value.kind === "bool") return value.value ? name : "";
@@ -172,11 +221,12 @@ if (name === "model" && value?.kind === "str") {
172
221
  if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
173
222
  vName = `${ctx.scopePrefix}${vName}`;
174
223
  }
224
+ if (ctx.namespace) vName = ctx.namespace + "_" + vName;
175
225
  const varDecl = ctx?.varDecls?.find(v => v.name === vName);
176
226
  const rhs = (varDecl && varDecl.varType === "int")
177
227
  ? `Number(e.target.value) || 0`
178
228
  : `e.target.value`;
179
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
229
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
180
230
  const handlerBody = `${vName} = ${rhs}; ${renderCall}`;
181
231
  if (ctx.scopePrefix) {
182
232
  const oninputAttr = emitCEAction(ctx, 'input', handlerBody);
@@ -278,14 +328,14 @@ if (name === "delay") {
278
328
  if (raw.startsWith("__ACTION_JS__")) {
279
329
  const js = raw.substring("__ACTION_JS__".length);
280
330
  const ev = eventAttrName(name);
281
- if (ev) return `${ev}="(function(){ ${js.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
331
+ if (ev) return `${ev}="(function(){ ${js.replace(/"/g, "&quot;")}; ${renderFn}(); })()"`;
282
332
  return `${name}="${escAttr(js)}"`;
283
333
  }
284
334
  if (raw.startsWith("__MULTI_EXPR__")) {
285
335
  const exprJson = raw.substring("__MULTI_EXPR__".length);
286
336
  try {
287
337
  const exprs: Expression[] = JSON.parse(exprJson);
288
- const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
338
+ const jsExprs = exprs.map(e => compileExprToJS(e, undefined, ctx.namespace)).join("; ");
289
339
  const ev = eventAttrName(name);
290
340
  let bumps = "";
291
341
  if (ctx.diffingEnabled) {
@@ -295,7 +345,7 @@ if (name === "delay") {
295
345
  }
296
346
  if (targets.length) bumps = ";" + targets.map(t => `window._bump&&window._bump('${t.replace(/'/g, "\\'")}')`).join(";");
297
347
  }
298
- if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}${bumps}; sinthRender(); })()"`;
348
+ if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}${bumps}; ${renderFn}(); })()"`;
299
349
  return `${name}="${escAttr(jsExprs)}"`;
300
350
  } catch { }
301
351
  }
@@ -310,11 +360,11 @@ if (name === "delay") {
310
360
  if (fnDef) {
311
361
  const inlinedJS = inlineFunctionBody(fnDef, expr.args ?? [], ctx);
312
362
  if (inlinedJS) {
313
- return `${ev}="(function(){ ${inlinedJS.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
363
+ return `${ev}="(function(){ ${inlinedJS.replace(/"/g, "&quot;")}; ${renderFn}(); })()"`;
314
364
  }
315
365
  }
316
366
  }
317
- let jsExpr = compileExprToJS(expr, ctx?.loopVars);
367
+ let jsExpr = compileExprToJS(expr, ctx?.loopVars, ctx.namespace);
318
368
  if (ctx.scopePrefix && ctx.scopeVar) {
319
369
  if (expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
320
370
  jsExpr = `${ctx.scopePrefix}${expr.name}`;
@@ -322,7 +372,10 @@ if (name === "delay") {
322
372
  jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
323
373
  }
324
374
  }
325
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
375
+ if (ev && expr.kind === "variable" && expr.name && ctx.functionDefs.some(f => f.name === expr.name)) {
376
+ jsExpr = jsExpr + "()";
377
+ }
378
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
326
379
  let bump = "";
327
380
  if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
328
381
  bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
@@ -343,7 +396,7 @@ if (name === "delay") {
343
396
  const ev = eventAttrName(name);
344
397
  if (ev) {
345
398
  const call = raw.includes("(") ? raw : raw + "()";
346
- return `${ev}="${escAttr(call)};sinthRender()"`;
399
+ return `${ev}="${escAttr(call)};${renderFn}()"`;
347
400
  }
348
401
  return `${name}="${escAttr(raw)}"`;
349
402
  }
@@ -436,7 +489,7 @@ export function renderChild(
436
489
  if (isMemo) {
437
490
  if (fnName && fnName.includes(".")) {
438
491
  SinthWarning.emit(`'$' on '${fnName}()' has no effect — dotted calls cannot be memoized.`);
439
- ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
492
+ ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
440
493
  return "";
441
494
  }
442
495
  const js = compileExprToJS(child.expression);
@@ -445,7 +498,7 @@ export function renderChild(
445
498
  return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
446
499
  }
447
500
  if (fnName && fnName.includes(".")) {
448
- ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
501
+ ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
449
502
  return "";
450
503
  }
451
504
  if (fnName === "remove" && child.expression.args && child.expression.args.length === 1) {
@@ -563,7 +616,7 @@ export function renderChild(
563
616
  }
564
617
 
565
618
  case "assign_stmt": {
566
- ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
619
+ ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
567
620
  return "";
568
621
  }
569
622
 
@@ -574,7 +627,8 @@ export function renderChild(
574
627
  case "return":
575
628
  return "";
576
629
 
577
-
630
+ case "var":
631
+ return "";
578
632
 
579
633
  case "if":
580
634
  return renderIfBlock(child, ctx, params, depth);
@@ -611,10 +665,22 @@ depth: number,
611
665
  ): string {
612
666
  if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
613
667
 
614
- const condJS = compileExprToJS(ifBlock.condition);
668
+ const condJS = compileExprToJS(ifBlock.condition, undefined, ctx.namespace, ctx.declaredVars);
615
669
  const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
616
670
  const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
617
- const hasComp = allChildren.some(c => c.kind === "use");
671
+ const hasComp = allChildren.some(c => c.kind === "use");
672
+
673
+ if (!hasAssign && !hasComp) {
674
+ const tplId = ctx.ifIdCounter++;
675
+ const condId = registerExpr(ctx, ifBlock.condition);
676
+ const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
677
+ const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
678
+ const persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
679
+ return (
680
+ `<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${persistAttr}>${bodyHTML}</template>` +
681
+ (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
682
+ );
683
+ }
618
684
 
619
685
  // pure logic
620
686
  if (hasAssign && !hasComp) {
@@ -622,14 +688,14 @@ depth: number,
622
688
  return "";
623
689
  }
624
690
 
625
- // pure DOM
691
+ // pure DOM (components need replace/persist/delay handling)
626
692
  if (!hasAssign && hasComp) {
627
693
  const tplId = ctx.ifIdCounter++;
628
694
  const condId = registerExpr(ctx, ifBlock.condition);
629
695
  const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
630
696
  const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
631
697
  let replaceAttr = "";
632
- let persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
698
+ let persistAttr = (ifBlock.persist || hasComp) ? ` data-sinth-if-persist="true"` : "";
633
699
  const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
634
700
  if (firstComp) {
635
701
  const idAttr = firstComp.attrs.find(a => a.name === "id");
@@ -683,7 +749,7 @@ depth: number,
683
749
  .filter(c => c.kind === "assign_stmt")
684
750
  .map(c => {
685
751
  const e = (c as AssignStmt).expression;
686
- const js = compileExprToJS(e);
752
+ const js = compileExprToJS(e, undefined, ctx.namespace);
687
753
  let bump = "";
688
754
  if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
689
755
  bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
@@ -701,7 +767,7 @@ depth: number,
701
767
  .filter(c => c.kind === "assign_stmt")
702
768
  .map(c => {
703
769
  const e = (c as AssignStmt).expression;
704
- const js = compileExprToJS(e);
770
+ const js = compileExprToJS(e, undefined, ctx.namespace);
705
771
  let bump = "";
706
772
  if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
707
773
  bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
@@ -739,8 +805,14 @@ depth: number,
739
805
  }
740
806
 
741
807
  const condId = registerExpr(ctx, ifBlock.condition);
808
+
809
+ const hasFullscreen = ifHTML.includes("data-sinth-fullscreen") || elseHTML.includes("data-sinth-fullscreen");
810
+
742
811
  ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
743
812
 
813
+ if (hasFullscreen) {
814
+ return `<span id="${replaceId || id}" data-sinth-mixed data-sinth-mixed-fullscreen="${condId}"></span>`;
815
+ }
744
816
  return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
745
817
  }
746
818
 
@@ -750,11 +822,12 @@ export function renderCompUse(
750
822
  params: Map<string, string>,
751
823
  depth: number,
752
824
  ): string {
825
+ const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
753
826
  if (use.name === "__IF_ROOT__") {
754
827
  return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
755
828
  }
756
829
 
757
- // RawHTML
830
+
758
831
  if (use.name === "RawHTML") {
759
832
  const ca = use.attrs.find(a => a.name === "content");
760
833
  if (!ca || !ca.value) return "";
@@ -766,23 +839,23 @@ export function renderCompUse(
766
839
  if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
767
840
 
768
841
  // custom element
769
- const customEl = ctx.customEls.get(use.name);
770
- if (customEl) {
771
- const attrParts = [`data-s="${ctx.scopeHash}"`];
772
- for (const attr of use.attrs) {
773
- if (attr.name === "bind" || attr.name === "model") continue;
774
- const r = renderAttr(attr, params, ctx);
775
- if (r) attrParts.push(r);
776
- }
777
- const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
778
- return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
779
- }
842
+ // const customEl = ctx.customEls.get(use.name);
843
+ // if (customEl) {
844
+ // const attrParts = [`data-s="${ctx.scopeHash}"`];
845
+ // for (const attr of use.attrs) {
846
+ // if (attr.name === "bind" || attr.name === "model") continue;
847
+ // const r = renderAttr(attr, params, ctx);
848
+ // if (r) attrParts.push(r);
849
+ // }
850
+ // const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
851
+ // return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
852
+ // }
780
853
 
781
854
  // built-in component
782
855
  const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
783
856
  const isVoid = voidEl || VOID_TAGS.has(tag);
784
857
 
785
- const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
858
+ let attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
786
859
  let userClass: string | undefined;
787
860
  const inlineStyleParts: string[] = [];
788
861
 
@@ -790,10 +863,20 @@ export function renderCompUse(
790
863
  if (attr.name === "level" && use.name === "Heading") continue;
791
864
 
792
865
  if (INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
793
- const val = attr.value.kind === "str"
794
- ? interpolateAttr(attr.value.value, params)
795
- : litToString(attr.value);
796
- inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
866
+ if (attr.value.kind === "str" && attr.value.value.startsWith("__EXPR__")) {
867
+ try {
868
+ const expr: Expression = JSON.parse(attr.value.value.substring(8));
869
+ const exprId = registerExpr(ctx, expr);
870
+ inlineStyleParts.push(`${camelToKebab(attr.name)}:__EXPR__${exprId}`);
871
+ } catch {
872
+ inlineStyleParts.push(`${camelToKebab(attr.name)}: ${interpolateAttr(attr.value.value, params)}`);
873
+ }
874
+ } else {
875
+ const val = attr.value.kind === "str"
876
+ ? interpolateAttr(attr.value.value, params)
877
+ : litToString(attr.value);
878
+ inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
879
+ }
797
880
  continue;
798
881
  }
799
882
 
@@ -813,7 +896,19 @@ export function renderCompUse(
813
896
 
814
897
  const classes = [defaultClass, userClass].filter(Boolean).join(" ");
815
898
  if (classes) attrParts.push(`class="${escAttr(classes)}"`);
816
- if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
899
+ if (inlineStyleParts.length > 0) {
900
+ const staticParts: string[] = [];
901
+ const exprParts: string[] = [];
902
+ for (const p of inlineStyleParts) {
903
+ if (p.includes(':__EXPR__')) {
904
+ exprParts.push(p.replace('__EXPR__', ''));
905
+ } else {
906
+ staticParts.push(p);
907
+ }
908
+ }
909
+ if (staticParts.length > 0) attrParts.push(`style="${escAttr(staticParts.join("; "))}"`);
910
+ if (exprParts.length > 0) attrParts.push(`data-sinth-style="${escAttr(exprParts.join(";"))}"`);
911
+ }
817
912
  if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
818
913
 
819
914
  const delayAttrVal = use.attrs.find(a => a.name === "delay");
@@ -850,7 +945,7 @@ export function renderCompUse(
850
945
  if (hideVal) {
851
946
  attrParts.push(`style="display:none"`);
852
947
  }
853
- attrParts[idx] = `${evName}="${escAttr(`(function(e){ var el=document.querySelector('[data-sinth-queue-id=${qid}]'); if(!el)return; var hide=${hideVal}; if(hide)el.style.display='none'; var q=window._sinthQ=q||{}; var sq=q.${qid}=q.${qid}||[]; sq.push(function(){ if(hide)el.style.display=''; ${action}; sinthRender(); }); if(sq.length===1){ (function p(first){ if(!sq||sq.length===0){delete q.${qid};return;} var a=sq[0]; sq.shift(); var d=first?${delayMs}:0; setTimeout(function(){ a(); if(sq.length>0)setTimeout(function(){p(false)},${delayMs}); },d); })(true); } })()`)}"`;
948
+ attrParts[idx] = `${evName}="${escAttr(`(function(e){ var el=document.querySelector('[data-sinth-queue-id=${qid}]'); if(!el)return; var hide=${hideVal}; if(hide)el.style.display='none'; var q=window._sinthQ=q||{}; var sq=q.${qid}=q.${qid}||[]; sq.push(function(){ if(hide)el.style.display=''; ${action}; ${renderFn}(); }); if(sq.length===1){ (function p(first){ if(!sq||sq.length===0){delete q.${qid};return;} var a=sq[0]; sq.shift(); var d=first?${delayMs}:0; setTimeout(function(){ a(); if(sq.length>0)setTimeout(function(){p(false)},${delayMs}); },d); })(true); } })()`)}"`;
854
949
  }
855
950
  }
856
951
  }
@@ -901,7 +996,8 @@ export function renderCompUse(
901
996
  if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
902
997
  resolvedName = `${ctx.scopePrefix}${vName}`;
903
998
  }
904
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
999
+ if (ctx.namespace) resolvedName = ctx.namespace + "_" + resolvedName;
1000
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
905
1001
  const handlerBody = `${resolvedName} = ${rhs}; ${renderCall}`;
906
1002
  if (ctx.scopePrefix) {
907
1003
  attrParts.push(emitCEAction(ctx, 'input', handlerBody));
@@ -917,53 +1013,52 @@ export function renderCompUse(
917
1013
  if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
918
1014
 
919
1015
  const checkedAttr = use.attrs.find(a => a.name === "checked");
1016
+ const onChangeAttr = use.attrs.find(a => a.name === "onChange");
1017
+
1018
+ // Resolve bound variable name (same pattern as Input's bind/model)
1019
+ let boundVarName: string | null = null;
1020
+ if (checkedAttr && checkedAttr.value?.kind === "str") {
1021
+ let raw = checkedAttr.value.value;
1022
+ if (raw.startsWith("__EXPR__")) {
1023
+ try {
1024
+ const expr: Expression = JSON.parse(raw.substring(8));
1025
+ if (expr.kind === "variable" && expr.name) {
1026
+ boundVarName = expr.name;
1027
+ }
1028
+ } catch {}
1029
+ } else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
1030
+ boundVarName = raw;
1031
+ }
1032
+ }
1033
+
1034
+ let resolvedName = boundVarName;
1035
+ if (resolvedName && ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === resolvedName)) {
1036
+ resolvedName = `${ctx.scopePrefix}${resolvedName}`;
1037
+ }
1038
+ if (resolvedName && ctx.namespace) resolvedName = ctx.namespace + "_" + resolvedName;
1039
+
920
1040
  if (checkedAttr && checkedAttr.value) {
921
1041
  if (checkedAttr.value.kind === "bool") {
922
1042
  if (checkedAttr.value.value) attrParts.push(`checked`);
923
- } else if (checkedAttr.value.kind === "str") {
924
- let raw = checkedAttr.value.value;
925
- if (raw.startsWith("__EXPR__")) {
926
- try {
927
- const expr: Expression = JSON.parse(raw.substring(8));
928
- if (expr.kind === "variable" && expr.name) {
929
- const checkedExprId = registerExpr(ctx, { kind: "variable", name: expr.name });
930
- attrParts.push(`data-sinth-checked="${checkedExprId}"`);
931
- } else {
932
- const exprId = registerExpr(ctx, expr);
933
- attrParts.push(`data-sinth-checked-expr="${exprId}"`);
934
- }
935
- } catch {}
936
- } else {
937
- const checkedExprId = registerExpr(ctx, { kind: "variable", name: raw });
938
- attrParts.push(`data-sinth-checked="${checkedExprId}"`);
939
- }
1043
+ } else if (checkedAttr.value.kind === "str" && boundVarName) {
1044
+ const checkedExprId = registerExpr(ctx, { kind: "variable", name: boundVarName });
1045
+ attrParts.push(`data-sinth-checked="${checkedExprId}"`);
940
1046
  }
941
1047
  }
942
1048
 
943
- const onChangeAttr = use.attrs.find(a => a.name === "onChange");
944
1049
  if (onChangeAttr && onChangeAttr.value?.kind === "str") {
945
1050
  let raw = onChangeAttr.value.value;
946
1051
  if (raw.startsWith("__EXPR__")) {
947
1052
  try {
948
1053
  const expr: Expression = JSON.parse(raw.substring(8));
949
- const jsExpr = compileExprToJS(expr);
950
- attrParts.push(`onchange="(function(){ ${jsExpr}; sinthRender(); })(event)"`);
1054
+ const jsExpr = compileExprToJS(expr, undefined, ctx.namespace);
1055
+ attrParts.push(`onchange="(function(){ ${jsExpr}; ${renderFn}(); })(event)"`);
951
1056
  } catch {}
952
1057
  } else {
953
- attrParts.push(`onchange="${escAttr(raw)};sinthRender()"`);
954
- }
955
- } else if (!onChangeAttr && checkedAttr) {
956
- const raw = checkedAttr.value?.kind === "str" ? checkedAttr.value.value : "";
957
- if (raw.startsWith("__EXPR__")) {
958
- try {
959
- const expr: Expression = JSON.parse(raw.substring(8));
960
- if (expr.kind === "variable" && expr.name) {
961
- attrParts.push(`onchange="(function(e){ ${expr.name} = e.target.checked; sinthRender(); })(event)"`);
962
- }
963
- } catch {}
964
- } else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
965
- attrParts.push(`onchange="(function(e){ ${raw} = e.target.checked; sinthRender(); })(event)"`);
1058
+ attrParts.push(`onchange="${escAttr(raw)};${renderFn}()"`);
966
1059
  }
1060
+ } else if (!onChangeAttr && resolvedName) {
1061
+ attrParts.push(`onchange="(function(e){ ${resolvedName} = e.target.checked; ${renderFn}(); })(event)"`);
967
1062
  }
968
1063
 
969
1064
  const labelAttr = use.attrs.find(a => a.name === "label");
@@ -974,7 +1069,8 @@ export function renderCompUse(
974
1069
  return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
975
1070
  }
976
1071
  }
977
-
1072
+
1073
+ attrParts = attrParts.filter(p => !p.startsWith("bind="));
978
1074
  const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
979
1075
 
980
1076
  if (isVoid) {
@@ -1089,9 +1185,12 @@ export function buildRuntime(opts: {
1089
1185
  exprRegistry: string[];
1090
1186
  sharedRuntime: boolean;
1091
1187
  functionsJS: string;
1188
+ namespace?: string;
1092
1189
  }): string | { page: string; shared: string } {
1093
1190
 
1094
1191
  const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
1192
+ const ns = opts.namespace ? "_" + opts.namespace : "";
1193
+ const renderFn = "sinthRender" + ns;
1095
1194
  const needsMixed = mixedBlocks.length > 0;
1096
1195
  const needsExpr = bodyHTML.includes("sinth-expr") || needsMixed;
1097
1196
  const needsIf = bodyHTML.includes("data-sinth-if") || needsMixed;
@@ -1102,6 +1201,7 @@ export function buildRuntime(opts: {
1102
1201
  const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync || needsDelay;
1103
1202
 
1104
1203
  const varLines = varDecls.map(v => {
1204
+ const vn = ns ? ns.slice(1) + "_" + v.name : v.name;
1105
1205
  if (!v.value) {
1106
1206
  if (!assignedVars.has(v.name)) {
1107
1207
  const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
@@ -1111,29 +1211,29 @@ export function buildRuntime(opts: {
1111
1211
  );
1112
1212
  }
1113
1213
  const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
1114
- return `let ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
1214
+ return `var ${vn} = ${defaults[v.varType] ?? "undefined"};`;
1115
1215
  }
1116
1216
  const val = litToString(v.value);
1117
- if (val.startsWith("__VAR__")) return `let ${v.name} = ${val.slice(7)};`;
1118
- if (val.startsWith("__ARR__")) return `let ${v.name} = ${val.slice(7)};`;
1217
+ if (val.startsWith("__VAR__")) return `var ${vn} = ${val.slice(7)};`;
1218
+ if (val.startsWith("__ARR__")) return `var ${vn} = ${val.slice(7)};`;
1119
1219
  if (val.startsWith("__EXPR__")) {
1120
1220
  try {
1121
1221
  const expr: Expression = JSON.parse(val.substring(8));
1122
1222
  const js = compileExprToJS(expr);
1123
1223
  const id = exprRegistry.length;
1124
1224
  exprRegistry.push(js);
1125
- return `let ${v.name} = __X[${id}]({});`;
1126
- } catch { return `let ${v.name} = ${val};`; }
1225
+ return `var ${vn} = __X${ns}[${id}]({});`;
1226
+ } catch { return `var ${vn} = ${val};`; }
1127
1227
  }
1128
- if (v.varType === "obj") return `let ${v.name} = ${val};`;
1129
- if (v.varType === "str") return `let ${v.name} = ${JSON.stringify(val)};`;
1228
+ if (v.varType === "obj") return `var ${vn} = ${val};`;
1229
+ if (v.varType === "str") return `var ${vn} = ${JSON.stringify(val)};`;
1130
1230
  if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
1131
1231
  try {
1132
1232
  const arr = JSON.parse(val.slice(7));
1133
- return `let ${v.name} = ${JSON.stringify(arr)};`;
1134
- } catch { return `let ${v.name} = ${val.slice(7)};`; }
1233
+ return `var ${vn} = ${JSON.stringify(arr)};`;
1234
+ } catch { return `var ${vn} = ${val.slice(7)};`; }
1135
1235
  }
1136
- return `let ${v.name} = ${val};`;
1236
+ return `var ${vn} = ${val};`;
1137
1237
  }).join("\n");
1138
1238
 
1139
1239
  const memoVars = new Set<string>();
@@ -1155,7 +1255,7 @@ export function buildRuntime(opts: {
1155
1255
  }
1156
1256
 
1157
1257
 
1158
- const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed });
1258
+ const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed, ns });
1159
1259
 
1160
1260
  const exprVarUpdates = varDecls
1161
1261
  .filter(v => v.value && litToString(v.value).startsWith("__EXPR__"))
@@ -1164,7 +1264,8 @@ export function buildRuntime(opts: {
1164
1264
  const expr: Expression = JSON.parse(litToString(v.value!).substring(8));
1165
1265
  const js = compileExprToJS(expr);
1166
1266
  const idx = exprRegistry.indexOf(js);
1167
- return `${v.name} = __X[${idx}]({});`;
1267
+ const vn2 = ns ? ns.slice(1) + "_" + v.name : v.name;
1268
+ return `${vn2} = __X${ns}[${idx}]({});`;
1168
1269
  } catch { return ""; }
1169
1270
  })
1170
1271
  .filter(Boolean)
@@ -1173,7 +1274,8 @@ export function buildRuntime(opts: {
1173
1274
  const renderBody = buildRenderBody({
1174
1275
  bodyHTML, logicBlocks, mixedBlocks,
1175
1276
  needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
1176
- exprVarUpdates: exprVarUpdates || undefined
1277
+ exprVarUpdates: exprVarUpdates || undefined,
1278
+ ns
1177
1279
  });
1178
1280
 
1179
1281
  let forDataJS = "";
@@ -1187,17 +1289,21 @@ export function buildRuntime(opts: {
1187
1289
  }
1188
1290
  if (forArrays.size > 0) {
1189
1291
  forDataJS = `var _sinthForData = {};\n`;
1190
- forSyncBlock = [...forArrays].map(v => `_sinthForData['${v.replace(/&quot;/g, '"')}'] = ${v.replace(/&quot;/g, '"')};`).join("\n ") + "\n ";
1292
+ forSyncBlock = [...forArrays].map(v => {
1293
+ const bare = v.replace(/&quot;/g, '"');
1294
+ const namespaced = opts.namespace ? opts.namespace + "_" + bare : bare;
1295
+ return `_sinthForData['${bare}'] = ${namespaced};`;
1296
+ }).join("\n ") + "\n ";
1191
1297
  }
1192
1298
  }
1193
1299
 
1194
1300
  const exprArrayJS = exprRegistry.length > 0
1195
- ? `let __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1301
+ ? `let __X${ns} = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1196
1302
  : "";
1197
1303
 
1198
1304
  let renderFunc = '';
1199
1305
  if (needsRender) {
1200
- renderFunc = `function sinthRender() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\nsinthRender();`;
1306
+ renderFunc = `function ${renderFn}() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\n${renderFn}();`;
1201
1307
  }
1202
1308
 
1203
1309
  if (needsFullscreenSync) {
@@ -1211,10 +1317,13 @@ export function buildRuntime(opts: {
1211
1317
  let state = !!document.fullscreenElement;
1212
1318
  vars.forEach(function(varName) {
1213
1319
  switch(varName) {
1214
- ${[...new Set(varDecls.filter(v => v.name).map(v => `case '${v.name}': ${v.name} = state; break;`))].join('\n ')}
1320
+ ${[...new Set(varDecls.filter(v => v.name).map(v => {
1321
+ const vn3 = ns ? ns.slice(1) + "_" + v.name : v.name;
1322
+ return `case '${v.name}': ${vn3} = state; break;`;
1323
+ }))].join('\n ')}
1215
1324
  }
1216
1325
  });
1217
- sinthRender();
1326
+ ${renderFn}();
1218
1327
  });
1219
1328
  }
1220
1329
  })();`;
@@ -1239,468 +1348,4 @@ ${exprArrayJS}
1239
1348
  ${memoVarDecls}
1240
1349
  ${varLines}
1241
1350
  ${renderFunc}`;
1242
- }
1243
-
1244
-
1245
- export interface CompileOptions {
1246
- projectRoot: string;
1247
- outDir: string;
1248
- libraryPaths: string[];
1249
- minify: boolean;
1250
- checkOnly: boolean;
1251
- sharedRuntime: boolean;
1252
- }
1253
-
1254
- export function compileFile(filePath: string, opts: CompileOptions): { html: string; shared?: string } | null {
1255
- const absPath = path.resolve(filePath);
1256
- const file = parseFile(absPath);
1257
- const cfg: ResolverConfig = { projectRoot: opts.projectRoot, libraryPaths: opts.libraryPaths };
1258
- const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
1259
- const hash = fnv1a(absPath);
1260
- const allVarDecls: VarDeclaration[] = file.varDecls;
1261
- const functionDefs: FunctionDef[] = file.functions;
1262
-
1263
- const declaredVars = new Set(allVarDecls.map(v => v.name));
1264
- const declaredFuncs = new Set(file.functions.map(f => f.name));
1265
-
1266
- function collectExprVars(expr: Expression | undefined, vars: Set<string>): void {
1267
- if (!expr) return;
1268
- if (expr.kind === "variable" && expr.name && !declaredFuncs.has(expr.name)) vars.add(expr.name);
1269
- if (expr.kind === "assign" && expr.target) vars.add(expr.target);
1270
- if (expr.left) collectExprVars(expr.left, vars);
1271
- if (expr.right) collectExprVars(expr.right, vars);
1272
- if (expr.operand) collectExprVars(expr.operand, vars);
1273
- if (expr.object) collectExprVars(expr.object, vars);
1274
- if (expr.key) collectExprVars(expr.key, vars);
1275
- if (expr.args) expr.args.forEach(a => collectExprVars(a, vars));
1276
- }
1277
-
1278
- function collectChildVars(child: Child, vars: Set<string>): void {
1279
- if (child.kind === "expr" || child.kind === "assign_stmt" || child.kind === "return") {
1280
- collectExprVars(child.expression, vars);
1281
- }
1282
- if (child.kind === "if") {
1283
- collectExprVars((child as IfBlock).condition, vars);
1284
- (child as IfBlock).body.forEach(c => collectChildVars(c, vars));
1285
- (child as IfBlock).elseBody?.forEach(c => collectChildVars(c, vars));
1286
- }
1287
- if (child.kind === "for") {
1288
- (child as ForLoop).body.forEach(c => collectChildVars(c, vars));
1289
- }
1290
- if (child.kind === "use") {
1291
- (child as CompUse).attrs.forEach(a => {
1292
- if (a.name === "id") return;
1293
- if (a.value?.kind === "str") {
1294
- const v = a.value.value;
1295
- if (v.startsWith("__EXPR__") || v.startsWith("__MULTI_EXPR__")) {
1296
- try {
1297
- const exprs: Expression[] = v.startsWith("__MULTI_EXPR__")
1298
- ? JSON.parse(v.substring("__MULTI_EXPR__".length))
1299
- : [JSON.parse(v.substring(8))];
1300
- exprs.forEach(e => collectExprVars(e, vars));
1301
- } catch {}
1302
- }
1303
- }
1304
- });
1305
- (child as CompUse).children.forEach(c => collectChildVars(c, vars));
1306
- }
1307
- }
1308
- const pageVars = new Set<string>();
1309
- file.uses.forEach(u => collectChildVars(u, pageVars));
1310
-
1311
- const pageLoopVars = new Set<string>();
1312
- const gatherLoopVars = (child: Child): void => {
1313
- if (child.kind === "for") {
1314
- const fl = child as ForLoop;
1315
- if (fl.itemVar) pageLoopVars.add(fl.itemVar);
1316
- if (fl.keyVar) pageLoopVars.add(fl.keyVar);
1317
- if (fl.indexVar) pageLoopVars.add(fl.indexVar);
1318
- fl.body.forEach(gatherLoopVars);
1319
- } else if (child.kind === "if") {
1320
- (child as IfBlock).body.forEach(gatherLoopVars);
1321
- (child as IfBlock).elseBody?.forEach(gatherLoopVars);
1322
- } else if (child.kind === "use") {
1323
- (child as CompUse).children.forEach(gatherLoopVars);
1324
- }
1325
- };
1326
- file.uses.forEach(gatherLoopVars);
1327
-
1328
- for (const v of pageVars) {
1329
- if (pageLoopVars.has(v)) continue;
1330
- const rootVar = v.split('.')[0];
1331
- if (declaredVars.has(rootVar)) continue;
1332
- let foundInFn = false;
1333
- for (const fn of file.functions) {
1334
- if (fn.params.some(p => p.name === rootVar)) { foundInFn = true; break; }
1335
- const fnLoopVars = new Set<string>();
1336
- const gatherFnLoopVars = (child: Child): void => {
1337
- if (child.kind === "for") {
1338
- const fl = child as ForLoop;
1339
- if (fl.itemVar) fnLoopVars.add(fl.itemVar);
1340
- if (fl.keyVar) fnLoopVars.add(fl.keyVar);
1341
- if (fl.indexVar) fnLoopVars.add(fl.indexVar);
1342
- fl.body.forEach(gatherFnLoopVars);
1343
- } else if (child.kind === "if") {
1344
- (child as IfBlock).body.forEach(gatherFnLoopVars);
1345
- (child as IfBlock).elseBody?.forEach(gatherFnLoopVars);
1346
- } else if (child.kind === "use") {
1347
- (child as CompUse).children.forEach(gatherFnLoopVars);
1348
- }
1349
- };
1350
- fn.body.forEach(gatherFnLoopVars);
1351
- if (fnLoopVars.has(rootVar)) { foundInFn = true; break; }
1352
- }
1353
- if (!foundInFn) {
1354
- throw new SinthError(
1355
- `Variable '${rootVar}' is used but never declared. Add 'var str ${rootVar}' or 'var int ${rootVar}' before using it.`
1356
- );
1357
- }
1358
- }
1359
- for (const fn of file.functions) {
1360
- const fnParamNames = new Set(fn.params.map(p => p.name));
1361
- const fnBodyVars = new Set<string>();
1362
- fn.body.forEach(c => collectChildVars(c, fnBodyVars));
1363
-
1364
- const fnLoopVars = new Set<string>();
1365
- const gatherFnLoopVars = (child: Child): void => {
1366
- if (child.kind === "for") {
1367
- const fl = child as ForLoop;
1368
- if (fl.itemVar) fnLoopVars.add(fl.itemVar);
1369
- if (fl.keyVar) fnLoopVars.add(fl.keyVar);
1370
- if (fl.indexVar) fnLoopVars.add(fl.indexVar);
1371
- fl.body.forEach(gatherFnLoopVars);
1372
- } else if (child.kind === "if") {
1373
- (child as IfBlock).body.forEach(gatherFnLoopVars);
1374
- (child as IfBlock).elseBody?.forEach(gatherFnLoopVars);
1375
- } else if (child.kind === "use") {
1376
- (child as CompUse).children.forEach(gatherFnLoopVars);
1377
- }
1378
- };
1379
- fn.body.forEach(gatherFnLoopVars);
1380
-
1381
- for (const v of fnBodyVars) {
1382
- if (fnLoopVars.has(v)) continue;
1383
- const rootVar = v.split('.')[0];
1384
- if (!fnParamNames.has(rootVar) && !declaredVars.has(rootVar) && !declaredFuncs.has(rootVar)) {
1385
- throw new SinthError(
1386
- `Variable '${rootVar}' used in function '${fn.name}' is not declared. It must be a parameter or a page-level variable.`
1387
- );
1388
- }
1389
- }
1390
- for (const child of fn.body) {
1391
- checkTypeInChild(child, allVarDecls, functionDefs);
1392
- }
1393
- }
1394
- for (const use of file.uses) {
1395
- checkTypeInChild(use, allVarDecls, functionDefs);
1396
- }
1397
-
1398
- function inferType(expr: Expression, varDecls: VarDeclaration[], functionDefs: FunctionDef[]): string | null {
1399
- if (expr.kind === "literal" && expr.value) {
1400
- if (expr.value.kind === "str") return "str";
1401
- if (expr.value.kind === "num") return "int";
1402
- if (expr.value.kind === "bool") return "bool";
1403
- return null;
1404
- }
1405
- if (expr.kind === "variable" && expr.name) {
1406
- const vd = varDecls.find(v => v.name === expr.name);
1407
- if (vd) return vd.varType === "str[]" ? "str[]" : vd.varType;
1408
- return null;
1409
- }
1410
- if (expr.kind === "call" && expr.callee?.kind === "variable" && expr.callee.name) {
1411
- const fd = functionDefs.find(f => f.name === expr.callee!.name);
1412
- if (fd?.returnType) return fd.returnType;
1413
- return null;
1414
- }
1415
- if (expr.kind === "binary" && expr.op === "+") return "str";
1416
- if (expr.kind === "unary" && expr.op === "not") return "bool";
1417
- return null;
1418
- }
1419
-
1420
- function checkCallArgs(fnDef: FunctionDef, args: Expression[], loc: Loc, varDecls: VarDeclaration[], functionDefs: FunctionDef[]): void {
1421
- for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
1422
- const param = fnDef.params[i];
1423
- const arg = args[i];
1424
- if (!param.paramType) continue;
1425
- const argType = inferType(arg, varDecls, functionDefs);
1426
- if (argType && argType !== param.paramType) {
1427
- if (param.paramType === "int" && argType === "str" && arg.kind === "literal" && arg.value?.kind === "str") {
1428
- if (!isNaN(Number(arg.value.value))) continue;
1429
- }
1430
- throw new SinthError(
1431
- `Function '${fnDef.name}' parameter '${param.name}' expects '${param.paramType}' but got '${argType}'`,
1432
- loc
1433
- );
1434
- }
1435
- }
1436
- }
1437
-
1438
- function checkTypeInExpr(expr: Expression | undefined, varDecls: VarDeclaration[], functionDefs: FunctionDef[]): void {
1439
- if (!expr) return;
1440
- if (expr.kind === "call" && expr.callee?.kind === "variable" && expr.callee.name) {
1441
- const fnDef = functionDefs.find(f => f.name === expr.callee!.name);
1442
- if (fnDef) checkCallArgs(fnDef, expr.args ?? [], fnDef.loc, varDecls, functionDefs);
1443
- }
1444
- if (expr.left) checkTypeInExpr(expr.left, varDecls, functionDefs);
1445
- if (expr.right) checkTypeInExpr(expr.right, varDecls, functionDefs);
1446
- if (expr.operand) checkTypeInExpr(expr.operand, varDecls, functionDefs);
1447
- if (expr.args) expr.args.forEach(a => checkTypeInExpr(a, varDecls, functionDefs));
1448
- }
1449
-
1450
- function checkTypeInChild(child: Child, varDecls: VarDeclaration[], functionDefs: FunctionDef[]): void {
1451
- if (child.kind === "expr" && child.expression) {
1452
- checkTypeInExpr(child.expression, varDecls, functionDefs);
1453
- }
1454
- if (child.kind === "assign_stmt" && child.expression) {
1455
- checkTypeInExpr(child.expression, varDecls, functionDefs);
1456
- }
1457
- if (child.kind === "return" && (child as ReturnStmt).expression) {
1458
- checkTypeInExpr((child as ReturnStmt).expression, varDecls, functionDefs);
1459
- }
1460
- if (child.kind === "if") {
1461
- const ib = child as IfBlock;
1462
- checkTypeInExpr(ib.condition, varDecls, functionDefs);
1463
- ib.body.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
1464
- ib.elseBody?.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
1465
- }
1466
- if (child.kind === "for") {
1467
- (child as ForLoop).body.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
1468
- }
1469
- if (child.kind === "use") {
1470
- const u = child as CompUse;
1471
- u.attrs.forEach(a => {
1472
- if (a.value?.kind === "str" && a.value.value.startsWith("__EXPR__")) {
1473
- try {
1474
- const expr: Expression = JSON.parse(a.value.value.substring(8));
1475
- checkTypeInExpr(expr, varDecls, functionDefs);
1476
- } catch {}
1477
- }
1478
- });
1479
- u.children.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
1480
- }
1481
- }
1482
-
1483
- const enableDiffing = file.meta.some(m =>
1484
- m.key === "domdiffing" &&
1485
- (m.value.kind === "bool" ? m.value.value === true : (m.value.kind === "str" && m.value.value === "true"))
1486
- );
1487
- const topLevelLogicIfs: string[] = [];
1488
- file.scripts = file.scripts.filter(s => {
1489
- const trimmed = s.raw.trim();
1490
- if (/^if\s*\(/.test(trimmed) || /^\{/.test(trimmed)) {
1491
- topLevelLogicIfs.push(trimmed);
1492
- return false;
1493
- }
1494
- return true;
1495
- });
1496
-
1497
- const ctx: CompileCtx = {
1498
- allDefs, functionDefs, customEls, cssLinks, jsLinks,
1499
- scopeHash: hash,
1500
- pageFile: absPath,
1501
- extraCSS: [],
1502
- mixedBlocks: [],
1503
- mixedCounter: 0,
1504
- logicBlocks: [...topLevelLogicIfs],
1505
- ifIdCounter: 0,
1506
- exprRegistry: [],
1507
- exprMap: new Map(),
1508
- varDecls: allVarDecls,
1509
- actionButtons: [],
1510
- diffingEnabled: enableDiffing,
1511
- declaredVars: declaredVars,
1512
- };
1513
-
1514
- if (!file.isPage) {
1515
- const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
1516
- const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
1517
- const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
1518
- const h = `${body}\n<style>\n${allCSS}\n</style>`;
1519
- return { html: h };
1520
- }
1521
-
1522
- const headData = buildHeadData(file.meta);
1523
- const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
1524
- const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
1525
- const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
1526
- const { componentScripts, pageScripts } = collectScripts(file, allDefs);
1527
-
1528
- // collect all assigned variables for default-value warnings
1529
- const assignedVars = new Set<string>();
1530
- for (const s of file.scripts) {
1531
- for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+\-]?=)/g)) assignedVars.add(m[1]);
1532
- }
1533
- for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
1534
-
1535
- // warn about reserved browser globals
1536
- const RESERVED_GLOBALS = new Set(["name", "location", "history", "status", "closed", "length", "top", "self", "parent", "frames", "origin"]);
1537
- for (const v of file.varDecls) {
1538
- if (RESERVED_GLOBALS.has(v.name)) {
1539
- SinthWarning.emit(`Variable '${v.name}' shadows a reserved browser global. This may cause unexpected behavior. Consider renaming.`, v.loc);
1540
- }
1541
- }
1542
-
1543
- // compile function definitions to JS
1544
- const compiledFunctions = functionDefs.map(f => compileFunctionDef(f, ctx)).join("\n");
1545
-
1546
- // companion JS file (needs same name as .sinth, adds support for JS libraries)
1547
- const companionJS = (() => {
1548
- const base = absPath.replace(/\.sinth$/, ".js");
1549
- return fs.existsSync(base) ? path.basename(base) : undefined;
1550
- })();
1551
-
1552
- const relativeCssLinks = cssLinks.map(css => {
1553
- const rel = path.relative(path.dirname(absPath), css).replace(/\\/g, "/");
1554
- return rel.startsWith(".") ? rel : "./" + rel;
1555
- });
1556
- const relativeJsLinks = jsLinks.map(js => ({
1557
- ...js,
1558
- src: (() => {
1559
- const rel = path.relative(path.dirname(absPath), js.src).replace(/\\/g, "/");
1560
- return rel.startsWith(".") ? rel : "./" + rel;
1561
- })(),
1562
- }));
1563
-
1564
- const runtimeResult = buildRuntime({
1565
- varDecls: allVarDecls,
1566
- bodyHTML,
1567
- logicBlocks: ctx.logicBlocks,
1568
- mixedBlocks: ctx.mixedBlocks,
1569
- assignedVars,
1570
- exprRegistry: ctx.exprRegistry,
1571
- sharedRuntime: opts.sharedRuntime,
1572
- functionsJS: compiledFunctions,
1573
- });
1574
- const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
1575
- const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
1576
- let finalRuntimeJS = runtimeJS;
1577
- if (enableDiffing) {
1578
- finalRuntimeJS = runtimeJS.replace('sinthRender();',
1579
- 'var _bump=function(v){_bump._v[v]=(_bump._v[v]||0)+1;};' +
1580
- '_bump._v={};' +
1581
- 'window._bump=_bump;' +
1582
- 'var _exprCache=new WeakMap();' +
1583
- 'var _origSinthExpr=sinthExpr;' +
1584
- 'sinthExpr=function(el){' +
1585
- 'var deps=el.dataset.sinthDeps;' +
1586
- 'if(deps!=null){' +
1587
- 'var list=deps.split(",").filter(Boolean);' +
1588
- 'if(list.length){' +
1589
- 'var h="";' +
1590
- 'for(var i=0;i<list.length;i++){var v=list[i].trim();h+=v+":"+(_bump._v[v]||0)+";";}' +
1591
- 'var old=_exprCache.get(el);' +
1592
- 'if(old===h)return;' +
1593
- '_exprCache.set(el,h);' +
1594
- '}else{' +
1595
- 'if(_exprCache.has(el))return;' +
1596
- '_exprCache.set(el,1);' +
1597
- '}' +
1598
- '}' +
1599
- '_origSinthExpr(el);' +
1600
- '};' +
1601
- 'sinthRender();'
1602
- );
1603
- }
1604
-
1605
-
1606
- const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
1607
- const scriptTags: string[] = [];
1608
- if (componentScripts.length > 0) {
1609
- scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
1610
- }
1611
-
1612
- for (const s of pageScripts) {
1613
- const extra = Object.entries(s.attrs)
1614
- .map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
1615
- .join(" ");
1616
- const globalised = s.raw.replace(/\b(let|const)\b/g, "let");
1617
- scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalised}\n</script>`);
1618
- }
1619
-
1620
-
1621
- const sharedRuntimeTag = (() => {
1622
- if (!opts.sharedRuntime || !sharedJS) return "";
1623
-
1624
- const relPath = path.relative(opts.projectRoot, absPath);
1625
- const htmlOutputDir = path.dirname(relPath.replace(/\.sinth$/, '.html'));
1626
- const relativeRuntimePath = path.relative(htmlOutputDir, '.').replace(/\\/g, '/');
1627
- const runtimeSrc = relativeRuntimePath ? `${relativeRuntimePath}/sinth-runtime.js` : './sinth-runtime.js';
1628
-
1629
- return `<script src="${runtimeSrc}"></script>`;
1630
- })();
1631
-
1632
- let actionInitScript = '';
1633
- if (ctx.actionButtons.length > 0) {
1634
- actionInitScript = '<script>' +
1635
- ctx.actionButtons.map(b =>
1636
- `setTimeout(function(){ var el=document.querySelector('[data-sinth-queue-id="${b.qid}"]'); if(el)el.style.display=''; },${b.delayMs});`
1637
- ).join('') +
1638
- '</script>';
1639
- }
1640
-
1641
- const html = [
1642
- "<!DOCTYPE html>",
1643
- `<html lang="${escAttr(headData.lang)}">`,
1644
- head,
1645
- `<body data-s="${hash}">`,
1646
- bodyHTML,
1647
- actionInitScript,
1648
- sharedRuntimeTag,
1649
- finalRuntimeJS.trim() ? `<script>\n${finalRuntimeJS}\n</script>` : "",
1650
- scriptTags.join("\n"),
1651
- "</body>",
1652
- "</html>",
1653
- ].filter(Boolean).join("\n");
1654
-
1655
- for (const cel of file.customEls) {
1656
- if (cel.exportTag) {
1657
- try {
1658
- const compJs = compileCustomElement(cel, opts, hash, ctx);
1659
- const relPath = path.relative(opts.projectRoot, path.dirname(absPath));
1660
- const outPath = path.join(opts.outDir, relPath, cel.exportTag + ".js");
1661
- if (!opts.checkOnly) {
1662
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
1663
- fs.writeFileSync(outPath, compJs);
1664
- process.stdout.write(` \x1b[32m✓\x1b[0m ${cel.exportTag}.js (custom element)\n`);
1665
- }
1666
- } catch (e: unknown) {
1667
- SinthWarning.emit(`Failed to compile custom element '${cel.exportTag}': ${(e as Error).message}`, cel.loc);
1668
- }
1669
- }
1670
- }
1671
-
1672
- const finalHTML = opts.minify ? minifyHTML(html) : html;
1673
- return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
1674
- }
1675
-
1676
-
1677
-
1678
- export function minifyHTML(html: string): string {
1679
- return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
1680
- }
1681
-
1682
- // file discovery & asset copy
1683
-
1684
- export function findSinthPages(dir: string, outDir?: string): string[] {
1685
- const results: string[] = [];
1686
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1687
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
1688
- const full = path.join(dir, entry.name);
1689
- if (outDir && path.resolve(full) === path.resolve(outDir)) continue;
1690
- if (entry.isDirectory()) results.push(...findSinthPages(full, outDir));
1691
- else if (entry.name.endsWith(".sinth")) results.push(full);
1692
- }
1693
- return results;
1694
- }
1695
-
1696
- export function copyDir(src: string, dest: string): void {
1697
- if (!fs.existsSync(src)) return;
1698
- fs.mkdirSync(dest, { recursive: true });
1699
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
1700
- const sp = path.join(src, entry.name);
1701
- const dp = path.join(dest, entry.name);
1702
- if (entry.isDirectory()) copyDir(sp, dp);
1703
- else fs.copyFileSync(sp, dp);
1704
- }
1705
- }
1706
-
1351
+ }