@yannosay/sinth 1.8.4 → 1.11.4
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/README.md +56 -509
- package/bin/sinth.js +1 -1
- package/package.json +1 -1
- package/src/browser/compile.ts +72 -0
- package/src/cli.ts +1 -1
- package/src/core/cli-compiler.ts +481 -0
- package/src/core/compiler.ts +134 -547
- package/src/core/expr.ts +16 -11
- package/src/core/runtime/helpers.ts +9 -8
- package/src/core/runtime/render.ts +23 -9
- package/src/core/types.ts +4 -0
- package/src/server.ts +1 -1
package/src/core/compiler.ts
CHANGED
|
@@ -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,9 +100,9 @@ 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) + ";");
|
|
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) + ";");
|
|
108
106
|
} else if (substituted.kind === "if") {
|
|
109
107
|
statements.push(compileIfToJS(substituted as IfBlock));
|
|
110
108
|
} else if (substituted.kind === "return") {
|
|
@@ -141,7 +139,7 @@ export function resolveBuiltinTag(
|
|
|
141
139
|
}
|
|
142
140
|
|
|
143
141
|
export function registerExpr(ctx: CompileCtx, expr: Expression): number {
|
|
144
|
-
let jsExpr = compileExprToJS(expr, ctx.loopVars);
|
|
142
|
+
let jsExpr = compileExprToJS(expr, ctx.loopVars, ctx.namespace, ctx.declaredVars);
|
|
145
143
|
if (ctx.scopePrefix && ctx.scopeVar && expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
|
|
146
144
|
jsExpr = `_ctx.${ctx.scopePrefix}${expr.name}`;
|
|
147
145
|
}
|
|
@@ -163,6 +161,7 @@ function emitCEAction(ctx: CompileCtx, eventName: string, handlerBody: string):
|
|
|
163
161
|
|
|
164
162
|
export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: CompileCtx): string {
|
|
165
163
|
const { name, value } = attr;
|
|
164
|
+
const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
|
|
166
165
|
if (value === null) return name;
|
|
167
166
|
if (value.kind === "null") return "";
|
|
168
167
|
if (value.kind === "bool") return value.value ? name : "";
|
|
@@ -172,11 +171,12 @@ if (name === "model" && value?.kind === "str") {
|
|
|
172
171
|
if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
|
|
173
172
|
vName = `${ctx.scopePrefix}${vName}`;
|
|
174
173
|
}
|
|
174
|
+
if (ctx.namespace) vName = ctx.namespace + "_" + vName;
|
|
175
175
|
const varDecl = ctx?.varDecls?.find(v => v.name === vName);
|
|
176
176
|
const rhs = (varDecl && varDecl.varType === "int")
|
|
177
177
|
? `Number(e.target.value) || 0`
|
|
178
178
|
: `e.target.value`;
|
|
179
|
-
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` :
|
|
179
|
+
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
|
|
180
180
|
const handlerBody = `${vName} = ${rhs}; ${renderCall}`;
|
|
181
181
|
if (ctx.scopePrefix) {
|
|
182
182
|
const oninputAttr = emitCEAction(ctx, 'input', handlerBody);
|
|
@@ -278,14 +278,14 @@ if (name === "delay") {
|
|
|
278
278
|
if (raw.startsWith("__ACTION_JS__")) {
|
|
279
279
|
const js = raw.substring("__ACTION_JS__".length);
|
|
280
280
|
const ev = eventAttrName(name);
|
|
281
|
-
if (ev) return `${ev}="(function(){ ${js.replace(/"/g, """)};
|
|
281
|
+
if (ev) return `${ev}="(function(){ ${js.replace(/"/g, """)}; ${renderFn}(); })()"`;
|
|
282
282
|
return `${name}="${escAttr(js)}"`;
|
|
283
283
|
}
|
|
284
284
|
if (raw.startsWith("__MULTI_EXPR__")) {
|
|
285
285
|
const exprJson = raw.substring("__MULTI_EXPR__".length);
|
|
286
286
|
try {
|
|
287
287
|
const exprs: Expression[] = JSON.parse(exprJson);
|
|
288
|
-
const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
|
|
288
|
+
const jsExprs = exprs.map(e => compileExprToJS(e, undefined, ctx.namespace)).join("; ");
|
|
289
289
|
const ev = eventAttrName(name);
|
|
290
290
|
let bumps = "";
|
|
291
291
|
if (ctx.diffingEnabled) {
|
|
@@ -295,7 +295,7 @@ if (name === "delay") {
|
|
|
295
295
|
}
|
|
296
296
|
if (targets.length) bumps = ";" + targets.map(t => `window._bump&&window._bump('${t.replace(/'/g, "\\'")}')`).join(";");
|
|
297
297
|
}
|
|
298
|
-
if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, """)}${bumps};
|
|
298
|
+
if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, """)}${bumps}; ${renderFn}(); })()"`;
|
|
299
299
|
return `${name}="${escAttr(jsExprs)}"`;
|
|
300
300
|
} catch { }
|
|
301
301
|
}
|
|
@@ -310,11 +310,11 @@ if (name === "delay") {
|
|
|
310
310
|
if (fnDef) {
|
|
311
311
|
const inlinedJS = inlineFunctionBody(fnDef, expr.args ?? [], ctx);
|
|
312
312
|
if (inlinedJS) {
|
|
313
|
-
return `${ev}="(function(){ ${inlinedJS.replace(/"/g, """)};
|
|
313
|
+
return `${ev}="(function(){ ${inlinedJS.replace(/"/g, """)}; ${renderFn}(); })()"`;
|
|
314
314
|
}
|
|
315
315
|
}
|
|
316
316
|
}
|
|
317
|
-
let jsExpr = compileExprToJS(expr, ctx?.loopVars);
|
|
317
|
+
let jsExpr = compileExprToJS(expr, ctx?.loopVars, ctx.namespace);
|
|
318
318
|
if (ctx.scopePrefix && ctx.scopeVar) {
|
|
319
319
|
if (expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
|
|
320
320
|
jsExpr = `${ctx.scopePrefix}${expr.name}`;
|
|
@@ -322,7 +322,7 @@ if (name === "delay") {
|
|
|
322
322
|
jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
|
|
323
323
|
}
|
|
324
324
|
}
|
|
325
|
-
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` :
|
|
325
|
+
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
|
|
326
326
|
let bump = "";
|
|
327
327
|
if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
|
|
328
328
|
bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
|
|
@@ -343,7 +343,7 @@ if (name === "delay") {
|
|
|
343
343
|
const ev = eventAttrName(name);
|
|
344
344
|
if (ev) {
|
|
345
345
|
const call = raw.includes("(") ? raw : raw + "()";
|
|
346
|
-
return `${ev}="${escAttr(call)}
|
|
346
|
+
return `${ev}="${escAttr(call)};${renderFn}()"`;
|
|
347
347
|
}
|
|
348
348
|
return `${name}="${escAttr(raw)}"`;
|
|
349
349
|
}
|
|
@@ -436,7 +436,7 @@ export function renderChild(
|
|
|
436
436
|
if (isMemo) {
|
|
437
437
|
if (fnName && fnName.includes(".")) {
|
|
438
438
|
SinthWarning.emit(`'$' on '${fnName}()' has no effect — dotted calls cannot be memoized.`);
|
|
439
|
-
ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
|
|
439
|
+
ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
|
|
440
440
|
return "";
|
|
441
441
|
}
|
|
442
442
|
const js = compileExprToJS(child.expression);
|
|
@@ -445,7 +445,7 @@ export function renderChild(
|
|
|
445
445
|
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
446
446
|
}
|
|
447
447
|
if (fnName && fnName.includes(".")) {
|
|
448
|
-
ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
|
|
448
|
+
ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
|
|
449
449
|
return "";
|
|
450
450
|
}
|
|
451
451
|
if (fnName === "remove" && child.expression.args && child.expression.args.length === 1) {
|
|
@@ -563,7 +563,7 @@ export function renderChild(
|
|
|
563
563
|
}
|
|
564
564
|
|
|
565
565
|
case "assign_stmt": {
|
|
566
|
-
ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
|
|
566
|
+
ctx.logicBlocks.push(compileExprToJS(child.expression, undefined, ctx.namespace) + ";");
|
|
567
567
|
return "";
|
|
568
568
|
}
|
|
569
569
|
|
|
@@ -611,10 +611,22 @@ depth: number,
|
|
|
611
611
|
): string {
|
|
612
612
|
if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
|
|
613
613
|
|
|
614
|
-
const condJS = compileExprToJS(ifBlock.condition);
|
|
614
|
+
const condJS = compileExprToJS(ifBlock.condition, undefined, ctx.namespace, ctx.declaredVars);
|
|
615
615
|
const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
|
|
616
616
|
const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
|
|
617
|
-
const hasComp
|
|
617
|
+
const hasComp = allChildren.some(c => c.kind === "use");
|
|
618
|
+
|
|
619
|
+
if (!hasAssign && !hasComp) {
|
|
620
|
+
const tplId = ctx.ifIdCounter++;
|
|
621
|
+
const condId = registerExpr(ctx, ifBlock.condition);
|
|
622
|
+
const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
623
|
+
const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
624
|
+
const persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
|
|
625
|
+
return (
|
|
626
|
+
`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${persistAttr}>${bodyHTML}</template>` +
|
|
627
|
+
(elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
|
|
628
|
+
);
|
|
629
|
+
}
|
|
618
630
|
|
|
619
631
|
// pure logic
|
|
620
632
|
if (hasAssign && !hasComp) {
|
|
@@ -622,7 +634,7 @@ depth: number,
|
|
|
622
634
|
return "";
|
|
623
635
|
}
|
|
624
636
|
|
|
625
|
-
// pure DOM
|
|
637
|
+
// pure DOM (components need replace/persist/delay handling)
|
|
626
638
|
if (!hasAssign && hasComp) {
|
|
627
639
|
const tplId = ctx.ifIdCounter++;
|
|
628
640
|
const condId = registerExpr(ctx, ifBlock.condition);
|
|
@@ -683,7 +695,7 @@ depth: number,
|
|
|
683
695
|
.filter(c => c.kind === "assign_stmt")
|
|
684
696
|
.map(c => {
|
|
685
697
|
const e = (c as AssignStmt).expression;
|
|
686
|
-
const js = compileExprToJS(e);
|
|
698
|
+
const js = compileExprToJS(e, undefined, ctx.namespace);
|
|
687
699
|
let bump = "";
|
|
688
700
|
if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
|
|
689
701
|
bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
|
|
@@ -701,7 +713,7 @@ depth: number,
|
|
|
701
713
|
.filter(c => c.kind === "assign_stmt")
|
|
702
714
|
.map(c => {
|
|
703
715
|
const e = (c as AssignStmt).expression;
|
|
704
|
-
const js = compileExprToJS(e);
|
|
716
|
+
const js = compileExprToJS(e, undefined, ctx.namespace);
|
|
705
717
|
let bump = "";
|
|
706
718
|
if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
|
|
707
719
|
bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
|
|
@@ -739,8 +751,14 @@ depth: number,
|
|
|
739
751
|
}
|
|
740
752
|
|
|
741
753
|
const condId = registerExpr(ctx, ifBlock.condition);
|
|
754
|
+
|
|
755
|
+
const hasFullscreen = ifHTML.includes("data-sinth-fullscreen") || elseHTML.includes("data-sinth-fullscreen");
|
|
756
|
+
|
|
742
757
|
ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
|
|
743
758
|
|
|
759
|
+
if (hasFullscreen) {
|
|
760
|
+
return `<span id="${replaceId || id}" data-sinth-mixed data-sinth-mixed-fullscreen="${condId}"></span>`;
|
|
761
|
+
}
|
|
744
762
|
return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
|
|
745
763
|
}
|
|
746
764
|
|
|
@@ -750,6 +768,7 @@ export function renderCompUse(
|
|
|
750
768
|
params: Map<string, string>,
|
|
751
769
|
depth: number,
|
|
752
770
|
): string {
|
|
771
|
+
const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
|
|
753
772
|
if (use.name === "__IF_ROOT__") {
|
|
754
773
|
return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
755
774
|
}
|
|
@@ -782,7 +801,7 @@ export function renderCompUse(
|
|
|
782
801
|
const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
|
|
783
802
|
const isVoid = voidEl || VOID_TAGS.has(tag);
|
|
784
803
|
|
|
785
|
-
|
|
804
|
+
let attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
|
|
786
805
|
let userClass: string | undefined;
|
|
787
806
|
const inlineStyleParts: string[] = [];
|
|
788
807
|
|
|
@@ -790,10 +809,20 @@ export function renderCompUse(
|
|
|
790
809
|
if (attr.name === "level" && use.name === "Heading") continue;
|
|
791
810
|
|
|
792
811
|
if (INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
812
|
+
if (attr.value.kind === "str" && attr.value.value.startsWith("__EXPR__")) {
|
|
813
|
+
try {
|
|
814
|
+
const expr: Expression = JSON.parse(attr.value.value.substring(8));
|
|
815
|
+
const exprId = registerExpr(ctx, expr);
|
|
816
|
+
inlineStyleParts.push(`${camelToKebab(attr.name)}:__EXPR__${exprId}`);
|
|
817
|
+
} catch {
|
|
818
|
+
inlineStyleParts.push(`${camelToKebab(attr.name)}: ${interpolateAttr(attr.value.value, params)}`);
|
|
819
|
+
}
|
|
820
|
+
} else {
|
|
821
|
+
const val = attr.value.kind === "str"
|
|
822
|
+
? interpolateAttr(attr.value.value, params)
|
|
823
|
+
: litToString(attr.value);
|
|
824
|
+
inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
|
|
825
|
+
}
|
|
797
826
|
continue;
|
|
798
827
|
}
|
|
799
828
|
|
|
@@ -813,7 +842,19 @@ export function renderCompUse(
|
|
|
813
842
|
|
|
814
843
|
const classes = [defaultClass, userClass].filter(Boolean).join(" ");
|
|
815
844
|
if (classes) attrParts.push(`class="${escAttr(classes)}"`);
|
|
816
|
-
if (inlineStyleParts.length > 0)
|
|
845
|
+
if (inlineStyleParts.length > 0) {
|
|
846
|
+
const staticParts: string[] = [];
|
|
847
|
+
const exprParts: string[] = [];
|
|
848
|
+
for (const p of inlineStyleParts) {
|
|
849
|
+
if (p.includes(':__EXPR__')) {
|
|
850
|
+
exprParts.push(p.replace('__EXPR__', ''));
|
|
851
|
+
} else {
|
|
852
|
+
staticParts.push(p);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
if (staticParts.length > 0) attrParts.push(`style="${escAttr(staticParts.join("; "))}"`);
|
|
856
|
+
if (exprParts.length > 0) attrParts.push(`data-sinth-style="${escAttr(exprParts.join(";"))}"`);
|
|
857
|
+
}
|
|
817
858
|
if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
|
|
818
859
|
|
|
819
860
|
const delayAttrVal = use.attrs.find(a => a.name === "delay");
|
|
@@ -850,7 +891,7 @@ export function renderCompUse(
|
|
|
850
891
|
if (hideVal) {
|
|
851
892
|
attrParts.push(`style="display:none"`);
|
|
852
893
|
}
|
|
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};
|
|
894
|
+
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
895
|
}
|
|
855
896
|
}
|
|
856
897
|
}
|
|
@@ -901,7 +942,8 @@ export function renderCompUse(
|
|
|
901
942
|
if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
|
|
902
943
|
resolvedName = `${ctx.scopePrefix}${vName}`;
|
|
903
944
|
}
|
|
904
|
-
|
|
945
|
+
if (ctx.namespace) resolvedName = ctx.namespace + "_" + resolvedName;
|
|
946
|
+
const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
|
|
905
947
|
const handlerBody = `${resolvedName} = ${rhs}; ${renderCall}`;
|
|
906
948
|
if (ctx.scopePrefix) {
|
|
907
949
|
attrParts.push(emitCEAction(ctx, 'input', handlerBody));
|
|
@@ -917,53 +959,52 @@ export function renderCompUse(
|
|
|
917
959
|
if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
|
|
918
960
|
|
|
919
961
|
const checkedAttr = use.attrs.find(a => a.name === "checked");
|
|
962
|
+
const onChangeAttr = use.attrs.find(a => a.name === "onChange");
|
|
963
|
+
|
|
964
|
+
// Resolve bound variable name (same pattern as Input's bind/model)
|
|
965
|
+
let boundVarName: string | null = null;
|
|
966
|
+
if (checkedAttr && checkedAttr.value?.kind === "str") {
|
|
967
|
+
let raw = checkedAttr.value.value;
|
|
968
|
+
if (raw.startsWith("__EXPR__")) {
|
|
969
|
+
try {
|
|
970
|
+
const expr: Expression = JSON.parse(raw.substring(8));
|
|
971
|
+
if (expr.kind === "variable" && expr.name) {
|
|
972
|
+
boundVarName = expr.name;
|
|
973
|
+
}
|
|
974
|
+
} catch {}
|
|
975
|
+
} else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
|
|
976
|
+
boundVarName = raw;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
let resolvedName = boundVarName;
|
|
981
|
+
if (resolvedName && ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === resolvedName)) {
|
|
982
|
+
resolvedName = `${ctx.scopePrefix}${resolvedName}`;
|
|
983
|
+
}
|
|
984
|
+
if (resolvedName && ctx.namespace) resolvedName = ctx.namespace + "_" + resolvedName;
|
|
985
|
+
|
|
920
986
|
if (checkedAttr && checkedAttr.value) {
|
|
921
987
|
if (checkedAttr.value.kind === "bool") {
|
|
922
988
|
if (checkedAttr.value.value) attrParts.push(`checked`);
|
|
923
|
-
} else if (checkedAttr.value.kind === "str") {
|
|
924
|
-
|
|
925
|
-
|
|
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
|
-
}
|
|
989
|
+
} else if (checkedAttr.value.kind === "str" && boundVarName) {
|
|
990
|
+
const checkedExprId = registerExpr(ctx, { kind: "variable", name: boundVarName });
|
|
991
|
+
attrParts.push(`data-sinth-checked="${checkedExprId}"`);
|
|
940
992
|
}
|
|
941
993
|
}
|
|
942
994
|
|
|
943
|
-
const onChangeAttr = use.attrs.find(a => a.name === "onChange");
|
|
944
995
|
if (onChangeAttr && onChangeAttr.value?.kind === "str") {
|
|
945
996
|
let raw = onChangeAttr.value.value;
|
|
946
997
|
if (raw.startsWith("__EXPR__")) {
|
|
947
998
|
try {
|
|
948
999
|
const expr: Expression = JSON.parse(raw.substring(8));
|
|
949
|
-
const jsExpr = compileExprToJS(expr);
|
|
950
|
-
attrParts.push(`onchange="(function(){ ${jsExpr};
|
|
1000
|
+
const jsExpr = compileExprToJS(expr, undefined, ctx.namespace);
|
|
1001
|
+
attrParts.push(`onchange="(function(){ ${jsExpr}; ${renderFn}(); })(event)"`);
|
|
951
1002
|
} catch {}
|
|
952
1003
|
} else {
|
|
953
|
-
attrParts.push(`onchange="${escAttr(raw)}
|
|
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)"`);
|
|
1004
|
+
attrParts.push(`onchange="${escAttr(raw)};${renderFn}()"`);
|
|
966
1005
|
}
|
|
1006
|
+
} else if (!onChangeAttr && resolvedName) {
|
|
1007
|
+
attrParts.push(`onchange="(function(e){ ${resolvedName} = e.target.checked; ${renderFn}(); })(event)"`);
|
|
967
1008
|
}
|
|
968
1009
|
|
|
969
1010
|
const labelAttr = use.attrs.find(a => a.name === "label");
|
|
@@ -974,7 +1015,8 @@ export function renderCompUse(
|
|
|
974
1015
|
return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
|
|
975
1016
|
}
|
|
976
1017
|
}
|
|
977
|
-
|
|
1018
|
+
|
|
1019
|
+
attrParts = attrParts.filter(p => !p.startsWith("bind="));
|
|
978
1020
|
const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
979
1021
|
|
|
980
1022
|
if (isVoid) {
|
|
@@ -1089,9 +1131,12 @@ export function buildRuntime(opts: {
|
|
|
1089
1131
|
exprRegistry: string[];
|
|
1090
1132
|
sharedRuntime: boolean;
|
|
1091
1133
|
functionsJS: string;
|
|
1134
|
+
namespace?: string;
|
|
1092
1135
|
}): string | { page: string; shared: string } {
|
|
1093
1136
|
|
|
1094
1137
|
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
|
|
1138
|
+
const ns = opts.namespace ? "_" + opts.namespace : "";
|
|
1139
|
+
const renderFn = "sinthRender" + ns;
|
|
1095
1140
|
const needsMixed = mixedBlocks.length > 0;
|
|
1096
1141
|
const needsExpr = bodyHTML.includes("sinth-expr") || needsMixed;
|
|
1097
1142
|
const needsIf = bodyHTML.includes("data-sinth-if") || needsMixed;
|
|
@@ -1102,6 +1147,7 @@ export function buildRuntime(opts: {
|
|
|
1102
1147
|
const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync || needsDelay;
|
|
1103
1148
|
|
|
1104
1149
|
const varLines = varDecls.map(v => {
|
|
1150
|
+
const vn = ns ? ns.slice(1) + "_" + v.name : v.name;
|
|
1105
1151
|
if (!v.value) {
|
|
1106
1152
|
if (!assignedVars.has(v.name)) {
|
|
1107
1153
|
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
@@ -1111,29 +1157,29 @@ export function buildRuntime(opts: {
|
|
|
1111
1157
|
);
|
|
1112
1158
|
}
|
|
1113
1159
|
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
1114
|
-
return `
|
|
1160
|
+
return `var ${vn} = ${defaults[v.varType] ?? "undefined"};`;
|
|
1115
1161
|
}
|
|
1116
1162
|
const val = litToString(v.value);
|
|
1117
|
-
if (val.startsWith("__VAR__")) return `
|
|
1118
|
-
if (val.startsWith("__ARR__")) return `
|
|
1163
|
+
if (val.startsWith("__VAR__")) return `var ${vn} = ${val.slice(7)};`;
|
|
1164
|
+
if (val.startsWith("__ARR__")) return `var ${vn} = ${val.slice(7)};`;
|
|
1119
1165
|
if (val.startsWith("__EXPR__")) {
|
|
1120
1166
|
try {
|
|
1121
1167
|
const expr: Expression = JSON.parse(val.substring(8));
|
|
1122
1168
|
const js = compileExprToJS(expr);
|
|
1123
1169
|
const id = exprRegistry.length;
|
|
1124
1170
|
exprRegistry.push(js);
|
|
1125
|
-
return `
|
|
1126
|
-
} catch { return `
|
|
1171
|
+
return `var ${vn} = __X${ns}[${id}]({});`;
|
|
1172
|
+
} catch { return `var ${vn} = ${val};`; }
|
|
1127
1173
|
}
|
|
1128
|
-
if (v.varType === "obj") return `
|
|
1129
|
-
if (v.varType === "str") return `
|
|
1174
|
+
if (v.varType === "obj") return `var ${vn} = ${val};`;
|
|
1175
|
+
if (v.varType === "str") return `var ${vn} = ${JSON.stringify(val)};`;
|
|
1130
1176
|
if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
|
|
1131
1177
|
try {
|
|
1132
1178
|
const arr = JSON.parse(val.slice(7));
|
|
1133
|
-
return `
|
|
1134
|
-
} catch { return `
|
|
1179
|
+
return `var ${vn} = ${JSON.stringify(arr)};`;
|
|
1180
|
+
} catch { return `var ${vn} = ${val.slice(7)};`; }
|
|
1135
1181
|
}
|
|
1136
|
-
return `
|
|
1182
|
+
return `var ${vn} = ${val};`;
|
|
1137
1183
|
}).join("\n");
|
|
1138
1184
|
|
|
1139
1185
|
const memoVars = new Set<string>();
|
|
@@ -1155,7 +1201,7 @@ export function buildRuntime(opts: {
|
|
|
1155
1201
|
}
|
|
1156
1202
|
|
|
1157
1203
|
|
|
1158
|
-
const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed });
|
|
1204
|
+
const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed, ns });
|
|
1159
1205
|
|
|
1160
1206
|
const exprVarUpdates = varDecls
|
|
1161
1207
|
.filter(v => v.value && litToString(v.value).startsWith("__EXPR__"))
|
|
@@ -1164,7 +1210,8 @@ export function buildRuntime(opts: {
|
|
|
1164
1210
|
const expr: Expression = JSON.parse(litToString(v.value!).substring(8));
|
|
1165
1211
|
const js = compileExprToJS(expr);
|
|
1166
1212
|
const idx = exprRegistry.indexOf(js);
|
|
1167
|
-
|
|
1213
|
+
const vn2 = ns ? ns.slice(1) + "_" + v.name : v.name;
|
|
1214
|
+
return `${vn2} = __X${ns}[${idx}]({});`;
|
|
1168
1215
|
} catch { return ""; }
|
|
1169
1216
|
})
|
|
1170
1217
|
.filter(Boolean)
|
|
@@ -1173,7 +1220,8 @@ export function buildRuntime(opts: {
|
|
|
1173
1220
|
const renderBody = buildRenderBody({
|
|
1174
1221
|
bodyHTML, logicBlocks, mixedBlocks,
|
|
1175
1222
|
needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
|
|
1176
|
-
exprVarUpdates: exprVarUpdates || undefined
|
|
1223
|
+
exprVarUpdates: exprVarUpdates || undefined,
|
|
1224
|
+
ns
|
|
1177
1225
|
});
|
|
1178
1226
|
|
|
1179
1227
|
let forDataJS = "";
|
|
@@ -1192,12 +1240,12 @@ export function buildRuntime(opts: {
|
|
|
1192
1240
|
}
|
|
1193
1241
|
|
|
1194
1242
|
const exprArrayJS = exprRegistry.length > 0
|
|
1195
|
-
? `let __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
1243
|
+
? `let __X${ns} = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
1196
1244
|
: "";
|
|
1197
1245
|
|
|
1198
1246
|
let renderFunc = '';
|
|
1199
1247
|
if (needsRender) {
|
|
1200
|
-
renderFunc = `function
|
|
1248
|
+
renderFunc = `function ${renderFn}() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\n${renderFn}();`;
|
|
1201
1249
|
}
|
|
1202
1250
|
|
|
1203
1251
|
if (needsFullscreenSync) {
|
|
@@ -1211,10 +1259,13 @@ export function buildRuntime(opts: {
|
|
|
1211
1259
|
let state = !!document.fullscreenElement;
|
|
1212
1260
|
vars.forEach(function(varName) {
|
|
1213
1261
|
switch(varName) {
|
|
1214
|
-
${[...new Set(varDecls.filter(v => v.name).map(v =>
|
|
1262
|
+
${[...new Set(varDecls.filter(v => v.name).map(v => {
|
|
1263
|
+
const vn3 = ns ? ns.slice(1) + "_" + v.name : v.name;
|
|
1264
|
+
return `case '${v.name}': ${vn3} = state; break;`;
|
|
1265
|
+
}))].join('\n ')}
|
|
1215
1266
|
}
|
|
1216
1267
|
});
|
|
1217
|
-
|
|
1268
|
+
${renderFn}();
|
|
1218
1269
|
});
|
|
1219
1270
|
}
|
|
1220
1271
|
})();`;
|
|
@@ -1239,468 +1290,4 @@ ${exprArrayJS}
|
|
|
1239
1290
|
${memoVarDecls}
|
|
1240
1291
|
${varLines}
|
|
1241
1292
|
${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
|
-
|
|
1293
|
+
}
|