@yannosay/sinth 1.8.1 → 1.8.3

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,1706 +1,1706 @@
1
- import * as path from "path";
2
- import * as fs from "fs";
3
- 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
- import { Parser } from "./parser.ts";
5
- import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal, interpolateAttr, renderText } from "../utils.ts";
6
- import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
7
- import { FunctionDef } from "./types.ts";
8
- import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
9
- import { compileFunctionDef } from "./runtime/functions.ts";
10
- import { generateHelpers } from "./runtime/helpers.ts";
11
- import { buildRenderBody } from "./runtime/render.ts";
12
- import { BUILTIN_MAP, VOID_TAGS, BuiltinInfo } from "./builtins.ts";
13
- import { processStyleBlock } from "./style-processor.ts";
14
- import { buildHeadData, renderHead, HeadData } from "./head-builder.ts";
15
- import { compileCustomElement } from "./runtime/custom-element.ts";
16
-
17
- const EVENT_RE = /^on[A-Z]/;
18
- function eventAttrName(name: string): string | null {
19
- return EVENT_RE.test(name) ? name.toLowerCase() : null;
20
- }
21
-
22
- /**
23
- * CSS property names that are allowed as inline style shorthand attributes on
24
- * any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
25
- */
26
- export const INLINE_STYLE_PROPS = new Set([
27
- "color","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
28
- "fontSize","fontWeight","fontFamily","fontStyle","fontVariant","lineHeight","letterSpacing","textAlign",
29
- "textDecoration","textTransform","whiteSpace","wordBreak","wordWrap","textOverflow",
30
- "margin","marginTop","marginBottom","marginLeft","marginRight",
31
- "padding","paddingTop","paddingBottom","paddingLeft","paddingRight",
32
- "width","height","minWidth","maxWidth","minHeight","maxHeight",
33
- "display","flexDirection","flexWrap","flex","flexGrow","flexShrink","flexBasis",
34
- "justifyContent","alignItems","alignContent","alignSelf","gap","rowGap","columnGap",
35
- "gridTemplateColumns","gridTemplateRows","gridColumn","gridRow","gridArea",
36
- "position","top","right","bottom","left","zIndex",
37
- "border","borderTop","borderBottom","borderLeft","borderRight",
38
- "borderWidth","borderStyle","borderColor","borderRadius",
39
- "outline","outlineWidth","outlineStyle","outlineColor","outlineOffset",
40
- "boxShadow","textShadow","opacity","visibility",
41
- "overflow","overflowX","overflowY","objectFit","objectPosition",
42
- "cursor","userSelect","pointerEvents","resize",
43
- "transform","transition","animation","animationDuration","animationDelay",
44
- "listStyle","listStyleType","listStylePosition",
45
- "verticalAlign","float","clear",
46
- "content","quotes",
47
- ]);
48
-
49
- function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: CompileCtx): string | null {
50
- const paramMap = new Map<string, string>();
51
- for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
52
- paramMap.set(fnDef.params[i].name, compileExprToJS(args[i], ctx.loopVars));
53
- }
54
- const subExpr = (expr: Expression): Expression => {
55
- if (expr.kind === "variable" && expr.name && paramMap.has(expr.name)) {
56
- return { kind: "variable", name: paramMap.get(expr.name)! };
57
- }
58
- if (expr.kind === "binary") {
59
- return { ...expr, left: expr.left ? subExpr(expr.left) : undefined, right: expr.right ? subExpr(expr.right) : undefined };
60
- }
61
- if (expr.kind === "unary") {
62
- return { ...expr, operand: expr.operand ? subExpr(expr.operand) : undefined };
63
- }
64
- if (expr.kind === "assign") {
65
- if (expr.target && paramMap.has(expr.target)) {
66
- return { ...expr, target: paramMap.get(expr.target)!, right: expr.right ? subExpr(expr.right) : undefined };
67
- }
68
- return { ...expr, right: expr.right ? subExpr(expr.right) : undefined };
69
- }
70
- if (expr.kind === "postfix" && expr.target && paramMap.has(expr.target)) {
71
- return { ...expr, target: paramMap.get(expr.target)!, op: expr.op };
72
- }
73
- if (expr.kind === "index") {
74
- return { ...expr, object: expr.object ? subExpr(expr.object) : undefined, key: expr.key ? subExpr(expr.key) : undefined };
75
- }
76
- if (expr.kind === "call") {
77
- return { ...expr, callee: expr.callee ? subExpr(expr.callee) : undefined, args: expr.args?.map(a => subExpr(a)) };
78
- }
79
- return expr;
80
- };
81
- const subChild = (child: Child): Child => {
82
- switch (child.kind) {
83
- case "assign_stmt":
84
- return { ...child, expression: subExpr(child.expression) as Expression };
85
- case "if": {
86
- const ib = child as IfBlock;
87
- return {
88
- ...ib,
89
- condition: subExpr(ib.condition),
90
- body: ib.body.map(subChild),
91
- elseBody: ib.elseBody?.map(subChild),
92
- };
93
- }
94
- case "return":
95
- return { ...child, expression: child.expression ? subExpr(child.expression) : undefined };
96
- default:
97
- return child;
98
- }
99
- };
100
- const statements: string[] = [];
101
-
102
- for (const c of fnDef.body) {
103
- const substituted = subChild(c);
104
- if (substituted.kind === "assign_stmt") {
105
- statements.push(compileExprToJS(substituted.expression) + ";");
106
- } else if (substituted.kind === "expr") {
107
- statements.push(compileExprToJS((substituted as any).expression) + ";");
108
- } else if (substituted.kind === "if") {
109
- statements.push(compileIfToJS(substituted as IfBlock));
110
- } else if (substituted.kind === "return") {
111
- } else if (substituted.kind === "for") {
112
- const fl = substituted as any;
113
- const bodyStmts = fl.body.map((bc: any) => {
114
- 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) + ";";
118
- return "";
119
- }).filter(Boolean).join(" ");
120
- statements.push(`for (let ${fl.itemVar} of ${fl.arrayVar}) { ${bodyStmts} }`);
121
- }
122
- }
123
- if (statements.length === 0) return null;
124
- return statements.join(" ");
125
- }
126
-
127
- export function resolveBuiltinTag(
128
- name: string,
129
- attrs: Attr[],
130
- ): { tag: string; defaultClass?: string; voidEl: boolean } {
131
- if (name === "Heading") {
132
- const la = attrs.find(a => a.name === "level");
133
- const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
134
- if (!la) SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
135
- return { tag: `h${lv}`, voidEl: false };
136
- }
137
- const info = BUILTIN_MAP[name];
138
- if (info) return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
139
- SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
140
- return { tag: name.toLowerCase(), voidEl: false };
141
- }
142
-
143
- export function registerExpr(ctx: CompileCtx, expr: Expression): number {
144
- let jsExpr = compileExprToJS(expr, ctx.loopVars);
145
- if (ctx.scopePrefix && ctx.scopeVar && expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
146
- jsExpr = `_ctx.${ctx.scopePrefix}${expr.name}`;
147
- }
148
- const existing = ctx.exprMap.get(jsExpr);
149
- if (existing !== undefined) return existing;
150
- const id = ctx.exprRegistry.length;
151
- ctx.exprRegistry.push(jsExpr);
152
- ctx.exprMap.set(jsExpr, id);
153
- return id;
154
- }
155
-
156
- function emitCEAction(ctx: CompileCtx, eventName: string, handlerBody: string): string {
157
- if (!ctx.ceActionHandlers) ctx.ceActionHandlers = [];
158
- const idx = ctx.ceActionHandlers.length;
159
- ctx.ceActionHandlers.push(`function(e, host) { ${handlerBody} }`);
160
- return `data-sinth-ce-${eventName}="${idx}"`;
161
- }
162
-
163
-
164
- export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: CompileCtx): string {
165
- const { name, value } = attr;
166
- if (value === null) return name;
167
- if (value.kind === "null") return "";
168
- if (value.kind === "bool") return value.value ? name : "";
169
-
170
- if (name === "model" && value?.kind === "str") {
171
- let vName = interpolateAttr(value.value, paramMap);
172
- if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
173
- vName = `${ctx.scopePrefix}${vName}`;
174
- }
175
- const varDecl = ctx?.varDecls?.find(v => v.name === vName);
176
- const rhs = (varDecl && varDecl.varType === "int")
177
- ? `Number(e.target.value) || 0`
178
- : `e.target.value`;
179
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
180
- const handlerBody = `${vName} = ${rhs}; ${renderCall}`;
181
- if (ctx.scopePrefix) {
182
- const oninputAttr = emitCEAction(ctx, 'input', handlerBody);
183
- return `${oninputAttr} value="${escAttr(vName)}"`;
184
- }
185
- return `oninput="(function(e){ ${handlerBody} })(event)" value="${escAttr(vName)}"`;
186
- }
187
-
188
- if (name === "step" && value?.kind === "str") {
189
- const raw = value.value;
190
- if (raw.startsWith("__EXPR__")) {
191
- try {
192
- const expr: Expression = JSON.parse(raw.substring(8));
193
- if (expr.kind === "variable" && expr.name) {
194
- const stepExprId = registerExpr(ctx, expr);
195
- return `data-sinth-step="${stepExprId}"`;
196
- }
197
- } catch {}
198
- }
199
- }
200
-
201
-
202
-
203
- if (name === "delay") {
204
- if (value.kind === "num") {
205
- return `data-sinth-delay="${value.value}"`;
206
- }
207
- const v = litToString(value);
208
- if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}"`;
209
- if (v.startsWith("__EXPR__")) {
210
- try {
211
- const expr: Expression = JSON.parse(v.substring(8));
212
- const id = registerExpr(ctx, expr);
213
- return `data-sinth-delay-expr-id="${id}"`;
214
- } catch {}
215
- }
216
- const id = registerExpr(ctx, { kind: "variable", name: v });
217
- return `data-sinth-delay-expr-id="${id}"`;
218
- }
219
-
220
- if (name === "hide") {
221
- if (value === null) return `data-sinth-hide=""`;
222
- if (value && (value as any).kind === "bool") {
223
- return (value as any).value ? `data-sinth-hide=""` : "";
224
- }
225
- if (value?.kind === "str") {
226
- const v = value.value;
227
- if (v === "true") return `data-sinth-hide=""`;
228
- if (v === "false") return "";
229
- if (v.startsWith("__EXPR__")) {
230
- try {
231
- const expr: Expression = JSON.parse(v.substring(8));
232
- const id = registerExpr(ctx, expr);
233
- return `data-sinth-hide="${id}"`;
234
- } catch { return ""; }
235
- }
236
- }
237
- return "";
238
- }
239
-
240
- if (name === "fullscreen") {
241
- if (value?.kind === "str") {
242
- const v = value.value;
243
- if (v.startsWith("__EXPR__")) {
244
- try {
245
- const expr: Expression = JSON.parse(v.substring(8));
246
- const id = registerExpr(ctx, expr);
247
- return `data-sinth-fullscreen="${id}"`;
248
- } catch { return ""; }
249
- }
250
- }
251
- return "";
252
- }
253
-
254
- if (name === "fullscreenSync") {
255
- if (value?.kind === "str") {
256
- const raw = value.value;
257
- if (raw.startsWith("__EXPR__")) {
258
- try {
259
- const expr: Expression = JSON.parse(raw.substring(8));
260
- if (expr.kind === "variable" && expr.name) {
261
- return `data-sinth-fullscreen-sync="${escAttr(expr.name)}"`;
262
- }
263
- } catch {}
264
- }
265
- return `data-sinth-fullscreen-sync="${escAttr(raw)}"`;
266
- }
267
- return "";
268
- }
269
-
270
- if (name === "checked") {
271
- return (value as any)?.kind === "bool" && (value as any).value ? "checked" : "";
272
- }
273
-
274
- if (value.kind === "num") return `${name}="${value.value}"`;
275
-
276
- let raw = value.value;
277
-
278
- if (raw.startsWith("__ACTION_JS__")) {
279
- const js = raw.substring("__ACTION_JS__".length);
280
- const ev = eventAttrName(name);
281
- if (ev) return `${ev}="(function(){ ${js.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
282
- return `${name}="${escAttr(js)}"`;
283
- }
284
- if (raw.startsWith("__MULTI_EXPR__")) {
285
- const exprJson = raw.substring("__MULTI_EXPR__".length);
286
- try {
287
- const exprs: Expression[] = JSON.parse(exprJson);
288
- const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
289
- const ev = eventAttrName(name);
290
- let bumps = "";
291
- if (ctx.diffingEnabled) {
292
- const targets: string[] = [];
293
- for (const e of exprs) {
294
- if (e.kind === "assign" && e.target) targets.push(e.target);
295
- }
296
- if (targets.length) bumps = ";" + targets.map(t => `window._bump&&window._bump('${t.replace(/'/g, "\\'")}')`).join(";");
297
- }
298
- if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}${bumps}; sinthRender(); })()"`;
299
- return `${name}="${escAttr(jsExprs)}"`;
300
- } catch { }
301
- }
302
- if (raw.startsWith("__EXPR__")) {
303
- const exprJson = raw.substring("__EXPR__".length);
304
- try {
305
- const expr: Expression = JSON.parse(exprJson);
306
- const ev = eventAttrName(name);
307
- if (ev && expr.kind === "call" && expr.callee?.kind === "variable") {
308
- const fnName = expr.callee.name;
309
- const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
310
- if (fnDef) {
311
- const inlinedJS = inlineFunctionBody(fnDef, expr.args ?? [], ctx);
312
- if (inlinedJS) {
313
- return `${ev}="(function(){ ${inlinedJS.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
314
- }
315
- }
316
- }
317
- let jsExpr = compileExprToJS(expr, ctx?.loopVars);
318
- if (ctx.scopePrefix && ctx.scopeVar) {
319
- if (expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
320
- jsExpr = `${ctx.scopePrefix}${expr.name}`;
321
- } else if (expr.kind === "assign" && expr.target && ctx.varDecls?.some(v => v.name === expr.target)) {
322
- jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
323
- }
324
- }
325
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
326
- let bump = "";
327
- if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
328
- bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
329
- }
330
- if (ev) {
331
- const handlerBody = `${jsExpr}${bump}; ${renderCall}`;
332
- if (ctx.scopePrefix) {
333
- return emitCEAction(ctx, ev, handlerBody);
334
- }
335
- return `${ev}="(function(){ ${handlerBody.replace(/"/g, "&quot;")} })()"`;
336
- }
337
- return `${name}="${escAttr(jsExpr)}"`;
338
- } catch { }
339
- }
340
-
341
- raw = interpolateAttr(raw, paramMap);
342
-
343
- const ev = eventAttrName(name);
344
- if (ev) {
345
- const call = raw.includes("(") ? raw : raw + "()";
346
- return `${ev}="${escAttr(call)};sinthRender()"`;
347
- }
348
- return `${name}="${escAttr(raw)}"`;
349
- }
350
-
351
-
352
-
353
-
354
-
355
-
356
- function substituteParamsInExpr(expr: Expression, params: Map<string, string>): Expression {
357
- if (expr.kind === "variable" && expr.name && params.has(expr.name)) {
358
- const val = params.get(expr.name)!;
359
- if (val.startsWith("__LIT__")) {
360
- return { kind: "literal", value: { kind: "str", value: val.slice(7) } };
361
- }
362
- if (val.startsWith("__EXPR__")) {
363
- try {
364
- return JSON.parse(val.substring(8));
365
- } catch { return expr; }
366
- }
367
- return { kind: "literal", value: { kind: "str", value: val } };
368
- }
369
- if (expr.kind === "binary") {
370
- return {
371
- ...expr,
372
- left: expr.left ? substituteParamsInExpr(expr.left, params) : undefined,
373
- right: expr.right ? substituteParamsInExpr(expr.right, params) : undefined,
374
- };
375
- }
376
- if (expr.kind === "unary" && expr.operand) {
377
- return { ...expr, operand: substituteParamsInExpr(expr.operand, params) };
378
- }
379
- return expr;
380
- }
381
-
382
- function exprDeps(expr: Expression, declaredVars: Set<string>): string {
383
- const deps = new Set<string>();
384
- function walk(e: Expression | undefined): void {
385
- if (!e) return;
386
- if (e.kind === "variable" && e.name && declaredVars.has(e.name)) deps.add(e.name);
387
- if (e.kind === "binary") { walk(e.left); walk(e.right); }
388
- if (e.kind === "unary") walk(e.operand);
389
- if (e.kind === "call") { e.args?.forEach(walk); }
390
- if (e.kind === "index") { walk(e.object); walk(e.key); }
391
- if (e.kind === "assign") { if (e.target && declaredVars.has(e.target)) deps.add(e.target); walk(e.right); }
392
- }
393
- walk(expr);
394
- return [...deps].join(",");
395
- }
396
-
397
- export function renderChild(
398
- child: Child,
399
- ctx: CompileCtx,
400
- params: Map<string, string>,
401
- depth: number,
402
- ): string {
403
- if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
404
-
405
- switch (child.kind) {
406
- case "text":
407
- return renderText(child.value, params);
408
-
409
- case "expr": {
410
- if (!child.expression) return "";
411
-
412
- if (child.expression.kind === "variable" && child.expression.name && params.has(child.expression.name)) {
413
- const val = params.get(child.expression.name)!;
414
- if (val.startsWith("__LIT__")) {
415
- return esc(val.slice(7));
416
- }
417
- if (val.startsWith("__RAW__")) {
418
- return val.slice(7);
419
- }
420
- if (val.startsWith("__VAR__")) {
421
- const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
422
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
423
- }
424
- if (val.startsWith("__EXPR__")) {
425
- try {
426
- const expr: Expression = JSON.parse(val.substring(8));
427
- const exprId = registerExpr(ctx, expr);
428
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
429
- } catch { return esc(val); }
430
- }
431
- return esc(val);
432
- }
433
- if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
434
- const fnName = child.expression.callee.name;
435
- const isMemo = child.expression.memo === true;
436
- if (isMemo) {
437
- if (fnName && fnName.includes(".")) {
438
- SinthWarning.emit(`'$' on '${fnName}()' has no effect — dotted calls cannot be memoized.`);
439
- ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
440
- return "";
441
- }
442
- const js = compileExprToJS(child.expression);
443
- ctx.logicBlocks.push(`if(!_memo_${fnName}_done){_memo_${fnName}=${js};_memo_${fnName}_done=true;}`);
444
- const exprId = registerExpr(ctx, { kind: "variable", name: `_memo_${fnName}` });
445
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
446
- }
447
- if (fnName && fnName.includes(".")) {
448
- ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
449
- return "";
450
- }
451
- if (fnName === "remove" && child.expression.args && child.expression.args.length === 1) {
452
- const arg = child.expression.args[0];
453
- if (arg.kind === "literal" && arg.value?.kind === "str") {
454
- return `<span data-sinth-remove="${esc(arg.value.value)}"></span>`;
455
- }
456
- }
457
- const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
458
- if (fnDef && fnDef.returnType === "ui") {
459
- const callArgs = child.expression.args ?? [];
460
- const localParams = new Map<string, string>();
461
- for (let i = 0; i < fnDef.params.length && i < callArgs.length; i++) {
462
- const arg = callArgs[i];
463
- if (arg.kind === "literal" && arg.value?.kind === "str") {
464
- localParams.set(fnDef.params[i].name, "__LIT__" + arg.value.value);
465
- } else if (arg.kind === "variable" && arg.name) {
466
- localParams.set(fnDef.params[i].name, "__VAR__" + arg.name);
467
- } else {
468
- const exprId = registerExpr(ctx, arg);
469
- localParams.set(fnDef.params[i].name, "__EXPRID__" + exprId);
470
- }
471
- }
472
- const substituteExpr = (expr: Expression, pm: Map<string, string>): Expression => {
473
- if (expr.kind === "variable" && pm.has(expr.name!)) {
474
- const pv = pm.get(expr.name!)!;
475
- if (pv.startsWith("__LIT__")) return { kind: "literal", value: { kind: "str", value: pv.slice(7) } };
476
- if (pv.startsWith("__EXPRID__")) {
477
- const id = parseInt(pv.slice(10), 10);
478
- return { kind: "expr_ref", exprId: id };
479
- }
480
- return { kind: "variable", name: pv.slice(7) };
481
- }
482
- if (expr.kind === "binary") return { ...expr, left: substituteExpr(expr.left!, pm), right: substituteExpr(expr.right!, pm) };
483
- if (expr.kind === "unary") return { ...expr, operand: substituteExpr(expr.operand!, pm) };
484
- if (expr.kind === "call") return { ...expr, callee: substituteExpr(expr.callee!, pm), args: expr.args?.map(a => substituteExpr(a, pm)) };
485
- if (expr.kind === "index") return { ...expr, object: substituteExpr(expr.object!, pm), key: substituteExpr(expr.key!, pm) };
486
- if (expr.kind === "assign") {
487
- const target = expr.target;
488
- if (target && pm.has(target)) {
489
- const pv = pm.get(target)!;
490
- if (pv.startsWith("__VAR__")) {
491
- return { ...expr, target: pv.slice(7), right: expr.right ? substituteExpr(expr.right, pm) : undefined };
492
- }
493
- }
494
- return { ...expr, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
495
- }
496
- return expr;
497
- };
498
- const substituteChild = (c: Child, pm: Map<string, string>): Child => {
499
- if (c.kind === "expr") return { ...c, expression: substituteExpr(c.expression, pm) };
500
- if (c.kind === "assign_stmt") return { ...c, expression: substituteExpr(c.expression, pm) as Expression };
501
- if (c.kind === "return" && (c as ReturnStmt).expression) return { ...c, expression: substituteExpr((c as ReturnStmt).expression!, pm) } as Child;
502
- if (c.kind === "if") {
503
- const ib = c as IfBlock;
504
- return { ...ib, condition: substituteExpr(ib.condition, pm), body: ib.body.map(bc => substituteChild(bc, pm)), elseBody: ib.elseBody?.map(bc => substituteChild(bc, pm)) };
505
- }
506
- if (c.kind === "for") {
507
- const fl = c as ForLoop;
508
- return { ...fl, body: fl.body.map(bc => substituteChild(bc, pm)) };
509
- }
510
- if (c.kind === "use") {
511
- const u = c as CompUse;
512
- const sa: Attr[] = u.attrs.map(a => {
513
- if (a.value?.kind === "str") {
514
- let raw = a.value.value;
515
- if (raw.startsWith("__EXPR__")) {
516
- try {
517
- const expr: Expression = JSON.parse(raw.substring(8));
518
- const substituted = substituteExpr(expr, pm);
519
- return { ...a, value: { kind: "str" as const, value: "__EXPR__" + JSON.stringify(substituted) } };
520
- } catch {}
521
- }
522
- if (raw.startsWith("__ACTION_JS__")) {
523
- return { ...a, value: { kind: "str" as const, value: raw } };
524
- }
525
- if (raw.startsWith("__MULTI_EXPR__")) {
526
- try {
527
- const exprs: Expression[] = JSON.parse(raw.substring("__MULTI_EXPR__".length));
528
- const substituted = exprs.map(e => substituteExpr(e, pm));
529
- return { ...a, value: { kind: "str" as const, value: "__MULTI_EXPR__" + JSON.stringify(substituted) } };
530
- } catch {}
531
- }
532
- for (const [pn, pv] of pm) {
533
- if (pv.startsWith("__LIT__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
534
- if (pv.startsWith("__VAR__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
535
- }
536
- return { ...a, value: { kind: "str" as const, value: raw } };
537
- }
538
- return a;
539
- });
540
- return { ...u, attrs: sa, children: u.children.map(cc => substituteChild(cc, pm)) };
541
- }
542
- return c;
543
- };
544
- return fnDef.body.map(c => renderChild(substituteChild(c, localParams), ctx, localParams, depth + 1)).join("");
545
- }
546
- }
547
- if (child.expression.kind === "expr_ref" && child.expression.exprId !== undefined) {
548
- return `<span class="sinth-expr" data-expr-id="${child.expression.exprId}"></span>`;
549
- }
550
- if (child.expression.kind === "literal" && child.expression.value) {
551
- return esc(litToString(child.expression.value));
552
- }
553
- if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
554
- const exprId = registerExpr(ctx, child.expression);
555
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
556
- }
557
- let expr = child.expression;
558
- if (params.size > 0) {
559
- expr = substituteParamsInExpr(expr, params);
560
- }
561
- const exprId = registerExpr(ctx, expr);
562
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
563
- }
564
-
565
- case "assign_stmt": {
566
- ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
567
- return "";
568
- }
569
-
570
- case "remove": {
571
- return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
572
- }
573
-
574
- case "return":
575
- return "";
576
-
577
-
578
-
579
- case "if":
580
- return renderIfBlock(child, ctx, params, depth);
581
-
582
- case "for": {
583
- const loopVars = new Set<string>();
584
- loopVars.add(child.itemVar);
585
- if (child.keyVar) loopVars.add(child.keyVar);
586
- if (child.indexVar) loopVars.add(child.indexVar);
587
- const prev = ctx.loopVars;
588
- ctx.loopVars = loopVars;
589
- const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
590
- ctx.loopVars = prev;
591
- const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
592
- const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
593
- return (
594
- `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`
595
- );
596
- }
597
-
598
- case "use":
599
- return renderCompUse(child, ctx, params, depth);
600
-
601
- case "component_expr":
602
- return child.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
603
- }
604
- }
605
-
606
- export function renderIfBlock(
607
- ifBlock: IfBlock,
608
- ctx: CompileCtx,
609
- params: Map<string, string>,
610
- depth: number,
611
- ): string {
612
- if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
613
-
614
- const condJS = compileExprToJS(ifBlock.condition);
615
- const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
616
- const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
617
- const hasComp = allChildren.some(c => c.kind === "use");
618
-
619
- // pure logic
620
- if (hasAssign && !hasComp) {
621
- ctx.logicBlocks.push(compileIfToJS(ifBlock));
622
- return "";
623
- }
624
-
625
- // pure DOM
626
- if (!hasAssign && hasComp) {
627
- const tplId = ctx.ifIdCounter++;
628
- const condId = registerExpr(ctx, ifBlock.condition);
629
- const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
630
- const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
631
- let replaceAttr = "";
632
- let persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
633
- const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
634
- if (firstComp) {
635
- const idAttr = firstComp.attrs.find(a => a.name === "id");
636
- const replAttr = firstComp.attrs.find(a => a.name === "replace");
637
- const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
638
- if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
639
- replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
640
- }
641
- }
642
- let delayAttr = "";
643
- let delayHideAttr = "";
644
- if (firstComp) {
645
- const delayA = firstComp.attrs.find(a => a.name === "delay");
646
- const hideA = firstComp.attrs.find(a => a.name === "hide");
647
- if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
648
- if (delayA.value?.kind === "num") {
649
- delayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
650
- } else if (delayA.value?.kind === "str") {
651
- const v = litToString(delayA.value);
652
- if (/^\d+$/.test(v)) delayAttr = ` data-sinth-if-delay="${v}"`;
653
- }
654
- delayHideAttr = ` data-sinth-if-delay-hide="false"`;
655
- }
656
- }
657
- let elseDelayAttr = "";
658
- let elseDelayHideAttr = "";
659
- const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
660
- if (elseFirstComp) {
661
- const delayA = elseFirstComp.attrs.find(a => a.name === "delay");
662
- const hideA = elseFirstComp.attrs.find(a => a.name === "hide");
663
- if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
664
- if (delayA.value?.kind === "num") {
665
- elseDelayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
666
- } else if (delayA.value?.kind === "str") {
667
- const v = litToString(delayA.value);
668
- if (/^\d+$/.test(v)) elseDelayAttr = ` data-sinth-if-delay="${v}"`;
669
- }
670
- elseDelayHideAttr = ` data-sinth-if-delay-hide="false"`;
671
- }
672
- }
673
- return (
674
- `<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}${delayAttr}${delayHideAttr}${persistAttr}>${bodyHTML}</template>` +
675
- (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}"${elseDelayAttr}${elseDelayHideAttr}>${elseHTML}</template>` : "")
676
- );
677
- }
678
-
679
- // mixed
680
- const id = `__sm${ctx.mixedCounter++}__`;
681
-
682
- const ifAssignJS = ifBlock.body
683
- .filter(c => c.kind === "assign_stmt")
684
- .map(c => {
685
- const e = (c as AssignStmt).expression;
686
- const js = compileExprToJS(e);
687
- let bump = "";
688
- if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
689
- bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
690
- }
691
- return ` ${js};${bump}`;
692
- })
693
- .join("\n");
694
-
695
- const ifHTML = ifBlock.body
696
- .filter(c => c.kind !== "assign_stmt")
697
- .map(c => renderChild(c, ctx, params, depth + 1))
698
- .join("");
699
-
700
- const elseAssignJS = (ifBlock.elseBody ?? [])
701
- .filter(c => c.kind === "assign_stmt")
702
- .map(c => {
703
- const e = (c as AssignStmt).expression;
704
- const js = compileExprToJS(e);
705
- let bump = "";
706
- if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
707
- bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
708
- }
709
- return ` ${js};${bump}`;
710
- })
711
- .join("\n");
712
-
713
- const elseHTML = (ifBlock.elseBody ?? [])
714
- .filter(c => c.kind !== "assign_stmt")
715
- .map(c => renderChild(c, ctx, params, depth + 1))
716
- .join("");
717
-
718
- let replaceId: string | undefined;
719
- const ifFirstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
720
- const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
721
- if (ifFirstComp) {
722
- const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
723
- const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
724
- const ifReplaceVal = ifReplace?.value;
725
- const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
726
-
727
- if (ifId && ifId.kind === "str" && ifWantsReplace) {
728
- if (elseFirstComp) {
729
- const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
730
- const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
731
- const elseReplaceVal = elseReplace?.value;
732
- const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
733
-
734
- if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
735
- replaceId = ifId.value;
736
- }
737
- }
738
- }
739
- }
740
-
741
- const condId = registerExpr(ctx, ifBlock.condition);
742
- ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
743
-
744
- return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
745
- }
746
-
747
- export function renderCompUse(
748
- use: CompUse,
749
- ctx: CompileCtx,
750
- params: Map<string, string>,
751
- depth: number,
752
- ): string {
753
- if (use.name === "__IF_ROOT__") {
754
- return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
755
- }
756
-
757
- // RawHTML
758
- if (use.name === "RawHTML") {
759
- const ca = use.attrs.find(a => a.name === "content");
760
- if (!ca || !ca.value) return "";
761
- return interpolateAttr(litToString(ca.value), params);
762
- }
763
-
764
- // user-defined component
765
- const userDef = ctx.allDefs.get(use.name);
766
- if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
767
-
768
- // 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
- }
780
-
781
- // built-in component
782
- const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
783
- const isVoid = voidEl || VOID_TAGS.has(tag);
784
-
785
- const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
786
- let userClass: string | undefined;
787
- const inlineStyleParts: string[] = [];
788
-
789
- for (const attr of use.attrs) {
790
- if (attr.name === "level" && use.name === "Heading") continue;
791
-
792
- 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}`);
797
- continue;
798
- }
799
-
800
- if (attr.name === "class") {
801
- if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
802
- continue;
803
- }
804
- if (use.name === "Checkbox" && (attr.name === "checked" || attr.name === "onChange" || attr.name === "label")) continue;
805
- if (attr.name === "hide") {
806
- const rendered = renderAttr(attr, params, ctx);
807
- if (rendered) attrParts.push(rendered);
808
- continue;
809
- }
810
- const rendered = renderAttr(attr, params, ctx);
811
- if (rendered) attrParts.push(rendered);
812
- }
813
-
814
- const classes = [defaultClass, userClass].filter(Boolean).join(" ");
815
- if (classes) attrParts.push(`class="${escAttr(classes)}"`);
816
- if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
817
- if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
818
-
819
- const delayAttrVal = use.attrs.find(a => a.name === "delay");
820
- if (delayAttrVal) {
821
- const delayMs = delayAttrVal.value?.kind === "num" ? delayAttrVal.value.value : 1000;
822
- const eventNames = ["onClick", "onChange", "onInput", "onSubmit"];
823
- let hasEvent = false;
824
- for (const en of eventNames) {
825
- const evName = en.toLowerCase();
826
- const idx = attrParts.findIndex(p => p.startsWith(evName + "="));
827
- if (idx >= 0) {
828
- hasEvent = true;
829
- const current = attrParts[idx];
830
- const match = current.match(/\(function\(\)\{\s*(.+?);\s*sinthRender\(\)/);
831
- if (match) {
832
- const action = match[1];
833
- const qid = `__sq${ctx.ifIdCounter++}`;
834
- const hideAttr = use.attrs.find(a => a.name === "hide");
835
- const hideVal = hideAttr
836
- ? (hideAttr.value === null
837
- ? true
838
- : (hideAttr.value.kind === "bool"
839
- ? hideAttr.value.value
840
- : (hideAttr.value.kind === "str" && hideAttr.value.value !== "false")))
841
- : true;
842
- ctx.actionButtons.push({ qid, delayMs, hide: hideVal });
843
- const delayIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay"));
844
- if (delayIdx >= 0) attrParts.splice(delayIdx, 1);
845
- const hideIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-hide"));
846
- if (hideIdx >= 0) attrParts.splice(hideIdx, 1);
847
- const doneIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-done"));
848
- if (doneIdx >= 0) attrParts.splice(doneIdx, 1);
849
- attrParts.push(`data-sinth-queue-id="${qid}"`);
850
- if (hideVal) {
851
- attrParts.push(`style="display:none"`);
852
- }
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); } })()`)}"`;
854
- }
855
- }
856
- }
857
- if (!hasEvent) {
858
- if (use.attrs.some(a => a.name === "hide")) {
859
- const hideAttr = use.attrs.find(a => a.name === "hide")!;
860
- const hideVal = hideAttr.value;
861
- const isHidden = (hideVal === null) ||
862
- (hideVal?.kind === "bool" && hideVal.value) ||
863
- (hideVal?.kind === "str" && hideVal.value !== "false");
864
- attrParts.push(`data-sinth-delay-hide="${isHidden ? "true" : "false"}"`);
865
- if (!isHidden) {
866
- attrParts.push(`data-sinth-delay-done="1"`);
867
- }
868
- } else {
869
- attrParts.push(`data-sinth-delay-hide="true"`);
870
- }
871
- }
872
- }
873
- if (use.name === "Input") {
874
- const bindAttr = use.attrs.find(a => a.name === "bind");
875
- const modelAttr = use.attrs.find(a => a.name === "model");
876
- const bindOrModel = bindAttr || modelAttr;
877
- if (bindOrModel?.value?.kind === "str") {
878
- let vName = bindOrModel.value.value;
879
- if (vName.startsWith("__EXPR__")) {
880
- try {
881
- const expr: Expression = JSON.parse(vName.substring(8));
882
- if (expr.kind === "variable" && expr.name) vName = expr.name;
883
- } catch {}
884
- }
885
- const varDecl = ctx.varDecls?.find(v => v.name === vName);
886
- if (!use.attrs.some(a => a.name === "type")) {
887
- if (varDecl && varDecl.varType === "int") {
888
- attrParts.push(`type="number"`);
889
- } else {
890
- attrParts.push(`type="text"`);
891
- }
892
- }
893
- if (varDecl && varDecl.varType === "int" && !use.attrs.some(a => a.name === "step")) {
894
- attrParts.push(`step="1"`);
895
- }
896
- const rhs = (varDecl && varDecl.varType === "int")
897
- ? `Number(e.target.value) || 0`
898
- : `e.target.value`;
899
- const initialVal = varDecl?.value ? litToString(varDecl.value).replace(/"/g, '&quot;') : "";
900
- let resolvedName = vName;
901
- if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
902
- resolvedName = `${ctx.scopePrefix}${vName}`;
903
- }
904
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
905
- const handlerBody = `${resolvedName} = ${rhs}; ${renderCall}`;
906
- if (ctx.scopePrefix) {
907
- attrParts.push(emitCEAction(ctx, 'input', handlerBody));
908
- } else {
909
- attrParts.push(`oninput="(function(e){ ${handlerBody} })(event)"`);
910
- }
911
- attrParts.push(`value="${escAttr(initialVal)}"`);
912
- const valueExprId = registerExpr(ctx, { kind: "variable", name: vName });
913
- attrParts.push(`data-sinth-value="${valueExprId}"`);
914
- }
915
- }
916
- if (use.name === "Checkbox") {
917
- if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
918
-
919
- const checkedAttr = use.attrs.find(a => a.name === "checked");
920
- if (checkedAttr && checkedAttr.value) {
921
- if (checkedAttr.value.kind === "bool") {
922
- 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
- }
940
- }
941
- }
942
-
943
- const onChangeAttr = use.attrs.find(a => a.name === "onChange");
944
- if (onChangeAttr && onChangeAttr.value?.kind === "str") {
945
- let raw = onChangeAttr.value.value;
946
- if (raw.startsWith("__EXPR__")) {
947
- try {
948
- const expr: Expression = JSON.parse(raw.substring(8));
949
- const jsExpr = compileExprToJS(expr);
950
- attrParts.push(`onchange="(function(){ ${jsExpr}; sinthRender(); })(event)"`);
951
- } catch {}
952
- } 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)"`);
966
- }
967
- }
968
-
969
- const labelAttr = use.attrs.find(a => a.name === "label");
970
- const labelText = labelAttr?.value?.kind === "str" ? esc(interpolateAttr(labelAttr.value.value, params)) : "";
971
-
972
- if (labelText) {
973
- const checkAttrStr = attrParts.length ? " " + attrParts.join(" ") : "";
974
- return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
975
- }
976
- }
977
-
978
- const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
979
-
980
- if (isVoid) {
981
- if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
982
- return `<${tag}${attrStr}>`;
983
- }
984
-
985
- const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
986
- return `<${tag}${attrStr}>${inner}</${tag}>`;
987
- }
988
-
989
- export function expandUserComp(
990
- use: CompUse,
991
- def: CompDef,
992
- ctx: CompileCtx,
993
- params: Map<string, string>,
994
- depth: number,
995
- ): string {
996
- if (use.name === def.name && depth > 4) {
997
- throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
998
- }
999
-
1000
- const local = new Map<string, string>();
1001
-
1002
- for (const p of def.params) {
1003
- if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
1004
- }
1005
-
1006
- for (const attr of use.attrs) {
1007
- if (attr.value === null) {
1008
- local.set(attr.name, "true");
1009
- } else if (attr.value.kind !== "null") {
1010
- const raw = litToString(attr.value);
1011
- if (raw.startsWith("__EXPR__")) {
1012
- local.set(attr.name, raw);
1013
- } else {
1014
- local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
1015
- }
1016
- }
1017
- }
1018
-
1019
- for (const p of def.params) {
1020
- if (!local.has(p.name)) {
1021
- throw new SinthError(
1022
- `Component '${def.name}' requires parameter '${p.name}' but it was not provided.`,
1023
- use.loc,
1024
- );
1025
- }
1026
- }
1027
-
1028
- const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
1029
- local.set("slot", "__RAW__" + slotHTML);
1030
-
1031
- for (const block of def.styles) {
1032
- ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
1033
- }
1034
-
1035
- return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
1036
- }
1037
-
1038
-
1039
-
1040
- export function collectScripts(
1041
- file: SinthFile,
1042
- allDefs: Map<string, CompDef>,
1043
- ): { componentScripts: string[]; pageScripts: { raw: string; attrs: Record<string, string> }[] } {
1044
- const componentScripts: string[] = [];
1045
- const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
1046
- const seenFunctions = new Set<string>();
1047
-
1048
- for (const [, def] of allDefs) {
1049
- for (const block of def.scripts) {
1050
- for (const fn of extractFunctionNames(block.raw)) {
1051
- if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
1052
- seenFunctions.add(fn);
1053
- }
1054
- componentScripts.push(`(function(){\n${block.raw}\n})();`);
1055
- }
1056
- }
1057
-
1058
- for (const block of file.scripts) {
1059
- for (const fn of extractFunctionNames(block.raw)) {
1060
- if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
1061
- seenFunctions.add(fn);
1062
- }
1063
- pageScripts.push({ raw: block.raw, attrs: block.attrs });
1064
- }
1065
-
1066
- return { componentScripts, pageScripts };
1067
- }
1068
-
1069
- export function extractFunctionNames(js: string): string[] {
1070
- const names: string[] = [];
1071
- const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
1072
- let m: RegExpExecArray | null;
1073
- while ((m = re.exec(js)) !== null) names.push(m[1]);
1074
- return names;
1075
- }
1076
-
1077
-
1078
-
1079
-
1080
- // sinth runtime
1081
-
1082
-
1083
- export function buildRuntime(opts: {
1084
- varDecls: VarDeclaration[];
1085
- bodyHTML: string;
1086
- logicBlocks: string[];
1087
- mixedBlocks: MixedBlockEntry[];
1088
- assignedVars: Set<string>;
1089
- exprRegistry: string[];
1090
- sharedRuntime: boolean;
1091
- functionsJS: string;
1092
- }): string | { page: string; shared: string } {
1093
-
1094
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
1095
- const needsMixed = mixedBlocks.length > 0;
1096
- const needsExpr = bodyHTML.includes("sinth-expr") || needsMixed;
1097
- const needsIf = bodyHTML.includes("data-sinth-if") || needsMixed;
1098
- const needsFor = bodyHTML.includes("data-sinth-for") || bodyHTML.includes("data-sinth-for-expr"); const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
1099
- const needsLogic = logicBlocks.length > 0;
1100
- const needsFullscreen = bodyHTML.includes("data-sinth-fullscreen");
1101
- const needsFullscreenSync = bodyHTML.includes("data-sinth-fullscreen-sync");
1102
- const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync || needsDelay;
1103
-
1104
- const varLines = varDecls.map(v => {
1105
- if (!v.value) {
1106
- if (!assignedVars.has(v.name)) {
1107
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
1108
- SinthWarning.emit(
1109
- `Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
1110
- v.loc,
1111
- );
1112
- }
1113
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
1114
- return `let ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
1115
- }
1116
- 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)};`;
1119
- if (val.startsWith("__EXPR__")) {
1120
- try {
1121
- const expr: Expression = JSON.parse(val.substring(8));
1122
- const js = compileExprToJS(expr);
1123
- const id = exprRegistry.length;
1124
- exprRegistry.push(js);
1125
- return `let ${v.name} = __X[${id}]({});`;
1126
- } catch { return `let ${v.name} = ${val};`; }
1127
- }
1128
- if (v.varType === "obj") return `let ${v.name} = ${val};`;
1129
- if (v.varType === "str") return `let ${v.name} = ${JSON.stringify(val)};`;
1130
- if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
1131
- try {
1132
- const arr = JSON.parse(val.slice(7));
1133
- return `let ${v.name} = ${JSON.stringify(arr)};`;
1134
- } catch { return `let ${v.name} = ${val.slice(7)};`; }
1135
- }
1136
- return `let ${v.name} = ${val};`;
1137
- }).join("\n");
1138
-
1139
- const memoVars = new Set<string>();
1140
- for (const lb of logicBlocks) {
1141
- let matches = lb.match(/_memo_(\w+)/g);
1142
- if (matches) matches.forEach(m => memoVars.add(m));
1143
- matches = lb.match(/_memo_(\w+)_done/g);
1144
- if (matches) matches.forEach(m => memoVars.add(m));
1145
- }
1146
- for (const e of exprRegistry) {
1147
- let matches = e.match(/_memo_(\w+)/g);
1148
- if (matches) matches.forEach(m => memoVars.add(m));
1149
- }
1150
- const memoVarDecls = [...memoVars].map(m => `var ${m};`).join("\n");
1151
-
1152
- if (!needsRender) {
1153
- const out = [varLines, memoVarDecls].filter(Boolean).join("\n");
1154
- return out ? `// Sinth compiled runtime\n${out}` : "";
1155
- }
1156
-
1157
-
1158
- const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed });
1159
-
1160
- const exprVarUpdates = varDecls
1161
- .filter(v => v.value && litToString(v.value).startsWith("__EXPR__"))
1162
- .map(v => {
1163
- try {
1164
- const expr: Expression = JSON.parse(litToString(v.value!).substring(8));
1165
- const js = compileExprToJS(expr);
1166
- const idx = exprRegistry.indexOf(js);
1167
- return `${v.name} = __X[${idx}]({});`;
1168
- } catch { return ""; }
1169
- })
1170
- .filter(Boolean)
1171
- .join("\n ");
1172
-
1173
- const renderBody = buildRenderBody({
1174
- bodyHTML, logicBlocks, mixedBlocks,
1175
- needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
1176
- exprVarUpdates: exprVarUpdates || undefined
1177
- });
1178
-
1179
- let forDataJS = "";
1180
- let forSyncBlock = "";
1181
- if (needsFor) {
1182
- const forArrays = new Set<string>();
1183
- const forRegex = /data-sinth-for="([^"]+)"/g;
1184
- let m;
1185
- while ((m = forRegex.exec(bodyHTML)) !== null) {
1186
- forArrays.add(m[1]);
1187
- }
1188
- if (forArrays.size > 0) {
1189
- forDataJS = `var _sinthForData = {};\n`;
1190
- forSyncBlock = [...forArrays].map(v => `_sinthForData['${v.replace(/&quot;/g, '"')}'] = ${v.replace(/&quot;/g, '"')};`).join("\n ") + "\n ";
1191
- }
1192
- }
1193
-
1194
- const exprArrayJS = exprRegistry.length > 0
1195
- ? `let __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1196
- : "";
1197
-
1198
- let renderFunc = '';
1199
- if (needsRender) {
1200
- renderFunc = `function sinthRender() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\nsinthRender();`;
1201
- }
1202
-
1203
- if (needsFullscreenSync) {
1204
- renderFunc += `
1205
- (function() {
1206
- let syncedEls = document.querySelectorAll('[data-sinth-fullscreen-sync]');
1207
- if (syncedEls.length > 0) {
1208
- let vars = [];
1209
- syncedEls.forEach(function(el) { vars.push(el.dataset.sinthFullscreenSync); });
1210
- document.addEventListener('fullscreenchange', function() {
1211
- let state = !!document.fullscreenElement;
1212
- vars.forEach(function(varName) {
1213
- switch(varName) {
1214
- ${[...new Set(varDecls.filter(v => v.name).map(v => `case '${v.name}': ${v.name} = state; break;`))].join('\n ')}
1215
- }
1216
- });
1217
- sinthRender();
1218
- });
1219
- }
1220
- })();`;
1221
- }
1222
-
1223
- const pageCode = `// Sinth Page Runtime
1224
- ${forDataJS}
1225
- ${exprArrayJS}
1226
- ${memoVarDecls}
1227
- ${varLines}
1228
- ${renderFunc}`;
1229
- if (opts.sharedRuntime && helpers.trim()) {
1230
- const sharedCode = `// Sinth shared runtime
1231
- ${helpers}`;
1232
- return { page: pageCode, shared: sharedCode };
1233
- }
1234
-
1235
- return `// Sinth compiled runtime
1236
- ${forDataJS}
1237
- ${functionsJS ? functionsJS + "\n" : ""}${helpers}
1238
- ${exprArrayJS}
1239
- ${memoVarDecls}
1240
- ${varLines}
1241
- ${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
-
1
+ import * as path from "path";
2
+ import * as fs from "fs";
3
+ 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
+ import { Parser } from "./parser.ts";
5
+ import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal, interpolateAttr, renderText } from "../utils.ts";
6
+ import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
7
+ import { FunctionDef } from "./types.ts";
8
+ import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
9
+ import { compileFunctionDef } from "./runtime/functions.ts";
10
+ import { generateHelpers } from "./runtime/helpers.ts";
11
+ import { buildRenderBody } from "./runtime/render.ts";
12
+ import { BUILTIN_MAP, VOID_TAGS, BuiltinInfo } from "./builtins.ts";
13
+ import { processStyleBlock } from "./style-processor.ts";
14
+ import { buildHeadData, renderHead, HeadData } from "./head-builder.ts";
15
+ import { compileCustomElement } from "./runtime/custom-element.ts";
16
+
17
+ const EVENT_RE = /^on[A-Z]/;
18
+ function eventAttrName(name: string): string | null {
19
+ return EVENT_RE.test(name) ? name.toLowerCase() : null;
20
+ }
21
+
22
+ /**
23
+ * CSS property names that are allowed as inline style shorthand attributes on
24
+ * any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
25
+ */
26
+ export const INLINE_STYLE_PROPS = new Set([
27
+ "color","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
28
+ "fontSize","fontWeight","fontFamily","fontStyle","fontVariant","lineHeight","letterSpacing","textAlign",
29
+ "textDecoration","textTransform","whiteSpace","wordBreak","wordWrap","textOverflow",
30
+ "margin","marginTop","marginBottom","marginLeft","marginRight",
31
+ "padding","paddingTop","paddingBottom","paddingLeft","paddingRight",
32
+ "width","height","minWidth","maxWidth","minHeight","maxHeight",
33
+ "display","flexDirection","flexWrap","flex","flexGrow","flexShrink","flexBasis",
34
+ "justifyContent","alignItems","alignContent","alignSelf","gap","rowGap","columnGap",
35
+ "gridTemplateColumns","gridTemplateRows","gridColumn","gridRow","gridArea",
36
+ "position","top","right","bottom","left","zIndex",
37
+ "border","borderTop","borderBottom","borderLeft","borderRight",
38
+ "borderWidth","borderStyle","borderColor","borderRadius",
39
+ "outline","outlineWidth","outlineStyle","outlineColor","outlineOffset",
40
+ "boxShadow","textShadow","opacity","visibility",
41
+ "overflow","overflowX","overflowY","objectFit","objectPosition",
42
+ "cursor","userSelect","pointerEvents","resize",
43
+ "transform","transition","animation","animationDuration","animationDelay",
44
+ "listStyle","listStyleType","listStylePosition",
45
+ "verticalAlign","float","clear",
46
+ "content","quotes",
47
+ ]);
48
+
49
+ function inlineFunctionBody(fnDef: FunctionDef, args: Expression[], ctx: CompileCtx): string | null {
50
+ const paramMap = new Map<string, string>();
51
+ for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
52
+ paramMap.set(fnDef.params[i].name, compileExprToJS(args[i], ctx.loopVars));
53
+ }
54
+ const subExpr = (expr: Expression): Expression => {
55
+ if (expr.kind === "variable" && expr.name && paramMap.has(expr.name)) {
56
+ return { kind: "variable", name: paramMap.get(expr.name)! };
57
+ }
58
+ if (expr.kind === "binary") {
59
+ return { ...expr, left: expr.left ? subExpr(expr.left) : undefined, right: expr.right ? subExpr(expr.right) : undefined };
60
+ }
61
+ if (expr.kind === "unary") {
62
+ return { ...expr, operand: expr.operand ? subExpr(expr.operand) : undefined };
63
+ }
64
+ if (expr.kind === "assign") {
65
+ if (expr.target && paramMap.has(expr.target)) {
66
+ return { ...expr, target: paramMap.get(expr.target)!, right: expr.right ? subExpr(expr.right) : undefined };
67
+ }
68
+ return { ...expr, right: expr.right ? subExpr(expr.right) : undefined };
69
+ }
70
+ if (expr.kind === "postfix" && expr.target && paramMap.has(expr.target)) {
71
+ return { ...expr, target: paramMap.get(expr.target)!, op: expr.op };
72
+ }
73
+ if (expr.kind === "index") {
74
+ return { ...expr, object: expr.object ? subExpr(expr.object) : undefined, key: expr.key ? subExpr(expr.key) : undefined };
75
+ }
76
+ if (expr.kind === "call") {
77
+ return { ...expr, callee: expr.callee ? subExpr(expr.callee) : undefined, args: expr.args?.map(a => subExpr(a)) };
78
+ }
79
+ return expr;
80
+ };
81
+ const subChild = (child: Child): Child => {
82
+ switch (child.kind) {
83
+ case "assign_stmt":
84
+ return { ...child, expression: subExpr(child.expression) as Expression };
85
+ case "if": {
86
+ const ib = child as IfBlock;
87
+ return {
88
+ ...ib,
89
+ condition: subExpr(ib.condition),
90
+ body: ib.body.map(subChild),
91
+ elseBody: ib.elseBody?.map(subChild),
92
+ };
93
+ }
94
+ case "return":
95
+ return { ...child, expression: child.expression ? subExpr(child.expression) : undefined };
96
+ default:
97
+ return child;
98
+ }
99
+ };
100
+ const statements: string[] = [];
101
+
102
+ for (const c of fnDef.body) {
103
+ const substituted = subChild(c);
104
+ if (substituted.kind === "assign_stmt") {
105
+ statements.push(compileExprToJS(substituted.expression) + ";");
106
+ } else if (substituted.kind === "expr") {
107
+ statements.push(compileExprToJS((substituted as any).expression) + ";");
108
+ } else if (substituted.kind === "if") {
109
+ statements.push(compileIfToJS(substituted as IfBlock));
110
+ } else if (substituted.kind === "return") {
111
+ } else if (substituted.kind === "for") {
112
+ const fl = substituted as any;
113
+ const bodyStmts = fl.body.map((bc: any) => {
114
+ 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) + ";";
118
+ return "";
119
+ }).filter(Boolean).join(" ");
120
+ statements.push(`for (let ${fl.itemVar} of ${fl.arrayVar}) { ${bodyStmts} }`);
121
+ }
122
+ }
123
+ if (statements.length === 0) return null;
124
+ return statements.join(" ");
125
+ }
126
+
127
+ export function resolveBuiltinTag(
128
+ name: string,
129
+ attrs: Attr[],
130
+ ): { tag: string; defaultClass?: string; voidEl: boolean } {
131
+ if (name === "Heading") {
132
+ const la = attrs.find(a => a.name === "level");
133
+ const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
134
+ if (!la) SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
135
+ return { tag: `h${lv}`, voidEl: false };
136
+ }
137
+ const info = BUILTIN_MAP[name];
138
+ if (info) return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
139
+ SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
140
+ return { tag: name.toLowerCase(), voidEl: false };
141
+ }
142
+
143
+ export function registerExpr(ctx: CompileCtx, expr: Expression): number {
144
+ let jsExpr = compileExprToJS(expr, ctx.loopVars);
145
+ if (ctx.scopePrefix && ctx.scopeVar && expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
146
+ jsExpr = `_ctx.${ctx.scopePrefix}${expr.name}`;
147
+ }
148
+ const existing = ctx.exprMap.get(jsExpr);
149
+ if (existing !== undefined) return existing;
150
+ const id = ctx.exprRegistry.length;
151
+ ctx.exprRegistry.push(jsExpr);
152
+ ctx.exprMap.set(jsExpr, id);
153
+ return id;
154
+ }
155
+
156
+ function emitCEAction(ctx: CompileCtx, eventName: string, handlerBody: string): string {
157
+ if (!ctx.ceActionHandlers) ctx.ceActionHandlers = [];
158
+ const idx = ctx.ceActionHandlers.length;
159
+ ctx.ceActionHandlers.push(`function(e, host) { ${handlerBody} }`);
160
+ return `data-sinth-ce-${eventName}="${idx}"`;
161
+ }
162
+
163
+
164
+ export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx: CompileCtx): string {
165
+ const { name, value } = attr;
166
+ if (value === null) return name;
167
+ if (value.kind === "null") return "";
168
+ if (value.kind === "bool") return value.value ? name : "";
169
+
170
+ if (name === "model" && value?.kind === "str") {
171
+ let vName = interpolateAttr(value.value, paramMap);
172
+ if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
173
+ vName = `${ctx.scopePrefix}${vName}`;
174
+ }
175
+ const varDecl = ctx?.varDecls?.find(v => v.name === vName);
176
+ const rhs = (varDecl && varDecl.varType === "int")
177
+ ? `Number(e.target.value) || 0`
178
+ : `e.target.value`;
179
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
180
+ const handlerBody = `${vName} = ${rhs}; ${renderCall}`;
181
+ if (ctx.scopePrefix) {
182
+ const oninputAttr = emitCEAction(ctx, 'input', handlerBody);
183
+ return `${oninputAttr} value="${escAttr(vName)}"`;
184
+ }
185
+ return `oninput="(function(e){ ${handlerBody} })(event)" value="${escAttr(vName)}"`;
186
+ }
187
+
188
+ if (name === "step" && value?.kind === "str") {
189
+ const raw = value.value;
190
+ if (raw.startsWith("__EXPR__")) {
191
+ try {
192
+ const expr: Expression = JSON.parse(raw.substring(8));
193
+ if (expr.kind === "variable" && expr.name) {
194
+ const stepExprId = registerExpr(ctx, expr);
195
+ return `data-sinth-step="${stepExprId}"`;
196
+ }
197
+ } catch {}
198
+ }
199
+ }
200
+
201
+
202
+
203
+ if (name === "delay") {
204
+ if (value.kind === "num") {
205
+ return `data-sinth-delay="${value.value}"`;
206
+ }
207
+ const v = litToString(value);
208
+ if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}"`;
209
+ if (v.startsWith("__EXPR__")) {
210
+ try {
211
+ const expr: Expression = JSON.parse(v.substring(8));
212
+ const id = registerExpr(ctx, expr);
213
+ return `data-sinth-delay-expr-id="${id}"`;
214
+ } catch {}
215
+ }
216
+ const id = registerExpr(ctx, { kind: "variable", name: v });
217
+ return `data-sinth-delay-expr-id="${id}"`;
218
+ }
219
+
220
+ if (name === "hide") {
221
+ if (value === null) return `data-sinth-hide=""`;
222
+ if (value && (value as any).kind === "bool") {
223
+ return (value as any).value ? `data-sinth-hide=""` : "";
224
+ }
225
+ if (value?.kind === "str") {
226
+ const v = value.value;
227
+ if (v === "true") return `data-sinth-hide=""`;
228
+ if (v === "false") return "";
229
+ if (v.startsWith("__EXPR__")) {
230
+ try {
231
+ const expr: Expression = JSON.parse(v.substring(8));
232
+ const id = registerExpr(ctx, expr);
233
+ return `data-sinth-hide="${id}"`;
234
+ } catch { return ""; }
235
+ }
236
+ }
237
+ return "";
238
+ }
239
+
240
+ if (name === "fullscreen") {
241
+ if (value?.kind === "str") {
242
+ const v = value.value;
243
+ if (v.startsWith("__EXPR__")) {
244
+ try {
245
+ const expr: Expression = JSON.parse(v.substring(8));
246
+ const id = registerExpr(ctx, expr);
247
+ return `data-sinth-fullscreen="${id}"`;
248
+ } catch { return ""; }
249
+ }
250
+ }
251
+ return "";
252
+ }
253
+
254
+ if (name === "fullscreenSync") {
255
+ if (value?.kind === "str") {
256
+ const raw = value.value;
257
+ if (raw.startsWith("__EXPR__")) {
258
+ try {
259
+ const expr: Expression = JSON.parse(raw.substring(8));
260
+ if (expr.kind === "variable" && expr.name) {
261
+ return `data-sinth-fullscreen-sync="${escAttr(expr.name)}"`;
262
+ }
263
+ } catch {}
264
+ }
265
+ return `data-sinth-fullscreen-sync="${escAttr(raw)}"`;
266
+ }
267
+ return "";
268
+ }
269
+
270
+ if (name === "checked") {
271
+ return (value as any)?.kind === "bool" && (value as any).value ? "checked" : "";
272
+ }
273
+
274
+ if (value.kind === "num") return `${name}="${value.value}"`;
275
+
276
+ let raw = value.value;
277
+
278
+ if (raw.startsWith("__ACTION_JS__")) {
279
+ const js = raw.substring("__ACTION_JS__".length);
280
+ const ev = eventAttrName(name);
281
+ if (ev) return `${ev}="(function(){ ${js.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
282
+ return `${name}="${escAttr(js)}"`;
283
+ }
284
+ if (raw.startsWith("__MULTI_EXPR__")) {
285
+ const exprJson = raw.substring("__MULTI_EXPR__".length);
286
+ try {
287
+ const exprs: Expression[] = JSON.parse(exprJson);
288
+ const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
289
+ const ev = eventAttrName(name);
290
+ let bumps = "";
291
+ if (ctx.diffingEnabled) {
292
+ const targets: string[] = [];
293
+ for (const e of exprs) {
294
+ if (e.kind === "assign" && e.target) targets.push(e.target);
295
+ }
296
+ if (targets.length) bumps = ";" + targets.map(t => `window._bump&&window._bump('${t.replace(/'/g, "\\'")}')`).join(";");
297
+ }
298
+ if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}${bumps}; sinthRender(); })()"`;
299
+ return `${name}="${escAttr(jsExprs)}"`;
300
+ } catch { }
301
+ }
302
+ if (raw.startsWith("__EXPR__")) {
303
+ const exprJson = raw.substring("__EXPR__".length);
304
+ try {
305
+ const expr: Expression = JSON.parse(exprJson);
306
+ const ev = eventAttrName(name);
307
+ if (ev && expr.kind === "call" && expr.callee?.kind === "variable") {
308
+ const fnName = expr.callee.name;
309
+ const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
310
+ if (fnDef) {
311
+ const inlinedJS = inlineFunctionBody(fnDef, expr.args ?? [], ctx);
312
+ if (inlinedJS) {
313
+ return `${ev}="(function(){ ${inlinedJS.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
314
+ }
315
+ }
316
+ }
317
+ let jsExpr = compileExprToJS(expr, ctx?.loopVars);
318
+ if (ctx.scopePrefix && ctx.scopeVar) {
319
+ if (expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
320
+ jsExpr = `${ctx.scopePrefix}${expr.name}`;
321
+ } else if (expr.kind === "assign" && expr.target && ctx.varDecls?.some(v => v.name === expr.target)) {
322
+ jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
323
+ }
324
+ }
325
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
326
+ let bump = "";
327
+ if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
328
+ bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
329
+ }
330
+ if (ev) {
331
+ const handlerBody = `${jsExpr}${bump}; ${renderCall}`;
332
+ if (ctx.scopePrefix) {
333
+ return emitCEAction(ctx, ev, handlerBody);
334
+ }
335
+ return `${ev}="(function(){ ${handlerBody.replace(/"/g, "&quot;")} })()"`;
336
+ }
337
+ return `${name}="${escAttr(jsExpr)}"`;
338
+ } catch { }
339
+ }
340
+
341
+ raw = interpolateAttr(raw, paramMap);
342
+
343
+ const ev = eventAttrName(name);
344
+ if (ev) {
345
+ const call = raw.includes("(") ? raw : raw + "()";
346
+ return `${ev}="${escAttr(call)};sinthRender()"`;
347
+ }
348
+ return `${name}="${escAttr(raw)}"`;
349
+ }
350
+
351
+
352
+
353
+
354
+
355
+
356
+ function substituteParamsInExpr(expr: Expression, params: Map<string, string>): Expression {
357
+ if (expr.kind === "variable" && expr.name && params.has(expr.name)) {
358
+ const val = params.get(expr.name)!;
359
+ if (val.startsWith("__LIT__")) {
360
+ return { kind: "literal", value: { kind: "str", value: val.slice(7) } };
361
+ }
362
+ if (val.startsWith("__EXPR__")) {
363
+ try {
364
+ return JSON.parse(val.substring(8));
365
+ } catch { return expr; }
366
+ }
367
+ return { kind: "literal", value: { kind: "str", value: val } };
368
+ }
369
+ if (expr.kind === "binary") {
370
+ return {
371
+ ...expr,
372
+ left: expr.left ? substituteParamsInExpr(expr.left, params) : undefined,
373
+ right: expr.right ? substituteParamsInExpr(expr.right, params) : undefined,
374
+ };
375
+ }
376
+ if (expr.kind === "unary" && expr.operand) {
377
+ return { ...expr, operand: substituteParamsInExpr(expr.operand, params) };
378
+ }
379
+ return expr;
380
+ }
381
+
382
+ function exprDeps(expr: Expression, declaredVars: Set<string>): string {
383
+ const deps = new Set<string>();
384
+ function walk(e: Expression | undefined): void {
385
+ if (!e) return;
386
+ if (e.kind === "variable" && e.name && declaredVars.has(e.name)) deps.add(e.name);
387
+ if (e.kind === "binary") { walk(e.left); walk(e.right); }
388
+ if (e.kind === "unary") walk(e.operand);
389
+ if (e.kind === "call") { e.args?.forEach(walk); }
390
+ if (e.kind === "index") { walk(e.object); walk(e.key); }
391
+ if (e.kind === "assign") { if (e.target && declaredVars.has(e.target)) deps.add(e.target); walk(e.right); }
392
+ }
393
+ walk(expr);
394
+ return [...deps].join(",");
395
+ }
396
+
397
+ export function renderChild(
398
+ child: Child,
399
+ ctx: CompileCtx,
400
+ params: Map<string, string>,
401
+ depth: number,
402
+ ): string {
403
+ if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
404
+
405
+ switch (child.kind) {
406
+ case "text":
407
+ return renderText(child.value, params);
408
+
409
+ case "expr": {
410
+ if (!child.expression) return "";
411
+
412
+ if (child.expression.kind === "variable" && child.expression.name && params.has(child.expression.name)) {
413
+ const val = params.get(child.expression.name)!;
414
+ if (val.startsWith("__LIT__")) {
415
+ return esc(val.slice(7));
416
+ }
417
+ if (val.startsWith("__RAW__")) {
418
+ return val.slice(7);
419
+ }
420
+ if (val.startsWith("__VAR__")) {
421
+ const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
422
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
423
+ }
424
+ if (val.startsWith("__EXPR__")) {
425
+ try {
426
+ const expr: Expression = JSON.parse(val.substring(8));
427
+ const exprId = registerExpr(ctx, expr);
428
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
429
+ } catch { return esc(val); }
430
+ }
431
+ return esc(val);
432
+ }
433
+ if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
434
+ const fnName = child.expression.callee.name;
435
+ const isMemo = child.expression.memo === true;
436
+ if (isMemo) {
437
+ if (fnName && fnName.includes(".")) {
438
+ SinthWarning.emit(`'$' on '${fnName}()' has no effect — dotted calls cannot be memoized.`);
439
+ ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
440
+ return "";
441
+ }
442
+ const js = compileExprToJS(child.expression);
443
+ ctx.logicBlocks.push(`if(!_memo_${fnName}_done){_memo_${fnName}=${js};_memo_${fnName}_done=true;}`);
444
+ const exprId = registerExpr(ctx, { kind: "variable", name: `_memo_${fnName}` });
445
+ return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
446
+ }
447
+ if (fnName && fnName.includes(".")) {
448
+ ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
449
+ return "";
450
+ }
451
+ if (fnName === "remove" && child.expression.args && child.expression.args.length === 1) {
452
+ const arg = child.expression.args[0];
453
+ if (arg.kind === "literal" && arg.value?.kind === "str") {
454
+ return `<span data-sinth-remove="${esc(arg.value.value)}"></span>`;
455
+ }
456
+ }
457
+ const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
458
+ if (fnDef && fnDef.returnType === "ui") {
459
+ const callArgs = child.expression.args ?? [];
460
+ const localParams = new Map<string, string>();
461
+ for (let i = 0; i < fnDef.params.length && i < callArgs.length; i++) {
462
+ const arg = callArgs[i];
463
+ if (arg.kind === "literal" && arg.value?.kind === "str") {
464
+ localParams.set(fnDef.params[i].name, "__LIT__" + arg.value.value);
465
+ } else if (arg.kind === "variable" && arg.name) {
466
+ localParams.set(fnDef.params[i].name, "__VAR__" + arg.name);
467
+ } else {
468
+ const exprId = registerExpr(ctx, arg);
469
+ localParams.set(fnDef.params[i].name, "__EXPRID__" + exprId);
470
+ }
471
+ }
472
+ const substituteExpr = (expr: Expression, pm: Map<string, string>): Expression => {
473
+ if (expr.kind === "variable" && pm.has(expr.name!)) {
474
+ const pv = pm.get(expr.name!)!;
475
+ if (pv.startsWith("__LIT__")) return { kind: "literal", value: { kind: "str", value: pv.slice(7) } };
476
+ if (pv.startsWith("__EXPRID__")) {
477
+ const id = parseInt(pv.slice(10), 10);
478
+ return { kind: "expr_ref", exprId: id };
479
+ }
480
+ return { kind: "variable", name: pv.slice(7) };
481
+ }
482
+ if (expr.kind === "binary") return { ...expr, left: substituteExpr(expr.left!, pm), right: substituteExpr(expr.right!, pm) };
483
+ if (expr.kind === "unary") return { ...expr, operand: substituteExpr(expr.operand!, pm) };
484
+ if (expr.kind === "call") return { ...expr, callee: substituteExpr(expr.callee!, pm), args: expr.args?.map(a => substituteExpr(a, pm)) };
485
+ if (expr.kind === "index") return { ...expr, object: substituteExpr(expr.object!, pm), key: substituteExpr(expr.key!, pm) };
486
+ if (expr.kind === "assign") {
487
+ const target = expr.target;
488
+ if (target && pm.has(target)) {
489
+ const pv = pm.get(target)!;
490
+ if (pv.startsWith("__VAR__")) {
491
+ return { ...expr, target: pv.slice(7), right: expr.right ? substituteExpr(expr.right, pm) : undefined };
492
+ }
493
+ }
494
+ return { ...expr, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
495
+ }
496
+ return expr;
497
+ };
498
+ const substituteChild = (c: Child, pm: Map<string, string>): Child => {
499
+ if (c.kind === "expr") return { ...c, expression: substituteExpr(c.expression, pm) };
500
+ if (c.kind === "assign_stmt") return { ...c, expression: substituteExpr(c.expression, pm) as Expression };
501
+ if (c.kind === "return" && (c as ReturnStmt).expression) return { ...c, expression: substituteExpr((c as ReturnStmt).expression!, pm) } as Child;
502
+ if (c.kind === "if") {
503
+ const ib = c as IfBlock;
504
+ return { ...ib, condition: substituteExpr(ib.condition, pm), body: ib.body.map(bc => substituteChild(bc, pm)), elseBody: ib.elseBody?.map(bc => substituteChild(bc, pm)) };
505
+ }
506
+ if (c.kind === "for") {
507
+ const fl = c as ForLoop;
508
+ return { ...fl, body: fl.body.map(bc => substituteChild(bc, pm)) };
509
+ }
510
+ if (c.kind === "use") {
511
+ const u = c as CompUse;
512
+ const sa: Attr[] = u.attrs.map(a => {
513
+ if (a.value?.kind === "str") {
514
+ let raw = a.value.value;
515
+ if (raw.startsWith("__EXPR__")) {
516
+ try {
517
+ const expr: Expression = JSON.parse(raw.substring(8));
518
+ const substituted = substituteExpr(expr, pm);
519
+ return { ...a, value: { kind: "str" as const, value: "__EXPR__" + JSON.stringify(substituted) } };
520
+ } catch {}
521
+ }
522
+ if (raw.startsWith("__ACTION_JS__")) {
523
+ return { ...a, value: { kind: "str" as const, value: raw } };
524
+ }
525
+ if (raw.startsWith("__MULTI_EXPR__")) {
526
+ try {
527
+ const exprs: Expression[] = JSON.parse(raw.substring("__MULTI_EXPR__".length));
528
+ const substituted = exprs.map(e => substituteExpr(e, pm));
529
+ return { ...a, value: { kind: "str" as const, value: "__MULTI_EXPR__" + JSON.stringify(substituted) } };
530
+ } catch {}
531
+ }
532
+ for (const [pn, pv] of pm) {
533
+ if (pv.startsWith("__LIT__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
534
+ if (pv.startsWith("__VAR__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
535
+ }
536
+ return { ...a, value: { kind: "str" as const, value: raw } };
537
+ }
538
+ return a;
539
+ });
540
+ return { ...u, attrs: sa, children: u.children.map(cc => substituteChild(cc, pm)) };
541
+ }
542
+ return c;
543
+ };
544
+ return fnDef.body.map(c => renderChild(substituteChild(c, localParams), ctx, localParams, depth + 1)).join("");
545
+ }
546
+ }
547
+ if (child.expression.kind === "expr_ref" && child.expression.exprId !== undefined) {
548
+ return `<span class="sinth-expr" data-expr-id="${child.expression.exprId}"></span>`;
549
+ }
550
+ if (child.expression.kind === "literal" && child.expression.value) {
551
+ return esc(litToString(child.expression.value));
552
+ }
553
+ if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
554
+ const exprId = registerExpr(ctx, child.expression);
555
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
556
+ }
557
+ let expr = child.expression;
558
+ if (params.size > 0) {
559
+ expr = substituteParamsInExpr(expr, params);
560
+ }
561
+ const exprId = registerExpr(ctx, expr);
562
+ return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
563
+ }
564
+
565
+ case "assign_stmt": {
566
+ ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
567
+ return "";
568
+ }
569
+
570
+ case "remove": {
571
+ return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
572
+ }
573
+
574
+ case "return":
575
+ return "";
576
+
577
+
578
+
579
+ case "if":
580
+ return renderIfBlock(child, ctx, params, depth);
581
+
582
+ case "for": {
583
+ const loopVars = new Set<string>();
584
+ loopVars.add(child.itemVar);
585
+ if (child.keyVar) loopVars.add(child.keyVar);
586
+ if (child.indexVar) loopVars.add(child.indexVar);
587
+ const prev = ctx.loopVars;
588
+ ctx.loopVars = loopVars;
589
+ const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
590
+ ctx.loopVars = prev;
591
+ const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
592
+ const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
593
+ return (
594
+ `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`
595
+ );
596
+ }
597
+
598
+ case "use":
599
+ return renderCompUse(child, ctx, params, depth);
600
+
601
+ case "component_expr":
602
+ return child.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
603
+ }
604
+ }
605
+
606
+ export function renderIfBlock(
607
+ ifBlock: IfBlock,
608
+ ctx: CompileCtx,
609
+ params: Map<string, string>,
610
+ depth: number,
611
+ ): string {
612
+ if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
613
+
614
+ const condJS = compileExprToJS(ifBlock.condition);
615
+ const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
616
+ const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
617
+ const hasComp = allChildren.some(c => c.kind === "use");
618
+
619
+ // pure logic
620
+ if (hasAssign && !hasComp) {
621
+ ctx.logicBlocks.push(compileIfToJS(ifBlock));
622
+ return "";
623
+ }
624
+
625
+ // pure DOM
626
+ if (!hasAssign && hasComp) {
627
+ const tplId = ctx.ifIdCounter++;
628
+ const condId = registerExpr(ctx, ifBlock.condition);
629
+ const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
630
+ const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
631
+ let replaceAttr = "";
632
+ let persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
633
+ const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
634
+ if (firstComp) {
635
+ const idAttr = firstComp.attrs.find(a => a.name === "id");
636
+ const replAttr = firstComp.attrs.find(a => a.name === "replace");
637
+ const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
638
+ if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
639
+ replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
640
+ }
641
+ }
642
+ let delayAttr = "";
643
+ let delayHideAttr = "";
644
+ if (firstComp) {
645
+ const delayA = firstComp.attrs.find(a => a.name === "delay");
646
+ const hideA = firstComp.attrs.find(a => a.name === "hide");
647
+ if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
648
+ if (delayA.value?.kind === "num") {
649
+ delayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
650
+ } else if (delayA.value?.kind === "str") {
651
+ const v = litToString(delayA.value);
652
+ if (/^\d+$/.test(v)) delayAttr = ` data-sinth-if-delay="${v}"`;
653
+ }
654
+ delayHideAttr = ` data-sinth-if-delay-hide="false"`;
655
+ }
656
+ }
657
+ let elseDelayAttr = "";
658
+ let elseDelayHideAttr = "";
659
+ const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
660
+ if (elseFirstComp) {
661
+ const delayA = elseFirstComp.attrs.find(a => a.name === "delay");
662
+ const hideA = elseFirstComp.attrs.find(a => a.name === "hide");
663
+ if (delayA && hideA && hideA.value && (hideA.value as any).kind === "bool" && !(hideA.value as any).value) {
664
+ if (delayA.value?.kind === "num") {
665
+ elseDelayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
666
+ } else if (delayA.value?.kind === "str") {
667
+ const v = litToString(delayA.value);
668
+ if (/^\d+$/.test(v)) elseDelayAttr = ` data-sinth-if-delay="${v}"`;
669
+ }
670
+ elseDelayHideAttr = ` data-sinth-if-delay-hide="false"`;
671
+ }
672
+ }
673
+ return (
674
+ `<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}${delayAttr}${delayHideAttr}${persistAttr}>${bodyHTML}</template>` +
675
+ (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}"${elseDelayAttr}${elseDelayHideAttr}>${elseHTML}</template>` : "")
676
+ );
677
+ }
678
+
679
+ // mixed
680
+ const id = `__sm${ctx.mixedCounter++}__`;
681
+
682
+ const ifAssignJS = ifBlock.body
683
+ .filter(c => c.kind === "assign_stmt")
684
+ .map(c => {
685
+ const e = (c as AssignStmt).expression;
686
+ const js = compileExprToJS(e);
687
+ let bump = "";
688
+ if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
689
+ bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
690
+ }
691
+ return ` ${js};${bump}`;
692
+ })
693
+ .join("\n");
694
+
695
+ const ifHTML = ifBlock.body
696
+ .filter(c => c.kind !== "assign_stmt")
697
+ .map(c => renderChild(c, ctx, params, depth + 1))
698
+ .join("");
699
+
700
+ const elseAssignJS = (ifBlock.elseBody ?? [])
701
+ .filter(c => c.kind === "assign_stmt")
702
+ .map(c => {
703
+ const e = (c as AssignStmt).expression;
704
+ const js = compileExprToJS(e);
705
+ let bump = "";
706
+ if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
707
+ bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
708
+ }
709
+ return ` ${js};${bump}`;
710
+ })
711
+ .join("\n");
712
+
713
+ const elseHTML = (ifBlock.elseBody ?? [])
714
+ .filter(c => c.kind !== "assign_stmt")
715
+ .map(c => renderChild(c, ctx, params, depth + 1))
716
+ .join("");
717
+
718
+ let replaceId: string | undefined;
719
+ const ifFirstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
720
+ const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
721
+ if (ifFirstComp) {
722
+ const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
723
+ const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
724
+ const ifReplaceVal = ifReplace?.value;
725
+ const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
726
+
727
+ if (ifId && ifId.kind === "str" && ifWantsReplace) {
728
+ if (elseFirstComp) {
729
+ const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
730
+ const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
731
+ const elseReplaceVal = elseReplace?.value;
732
+ const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
733
+
734
+ if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
735
+ replaceId = ifId.value;
736
+ }
737
+ }
738
+ }
739
+ }
740
+
741
+ const condId = registerExpr(ctx, ifBlock.condition);
742
+ ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
743
+
744
+ return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
745
+ }
746
+
747
+ export function renderCompUse(
748
+ use: CompUse,
749
+ ctx: CompileCtx,
750
+ params: Map<string, string>,
751
+ depth: number,
752
+ ): string {
753
+ if (use.name === "__IF_ROOT__") {
754
+ return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
755
+ }
756
+
757
+ // RawHTML
758
+ if (use.name === "RawHTML") {
759
+ const ca = use.attrs.find(a => a.name === "content");
760
+ if (!ca || !ca.value) return "";
761
+ return interpolateAttr(litToString(ca.value), params);
762
+ }
763
+
764
+ // user-defined component
765
+ const userDef = ctx.allDefs.get(use.name);
766
+ if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
767
+
768
+ // 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
+ }
780
+
781
+ // built-in component
782
+ const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
783
+ const isVoid = voidEl || VOID_TAGS.has(tag);
784
+
785
+ const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
786
+ let userClass: string | undefined;
787
+ const inlineStyleParts: string[] = [];
788
+
789
+ for (const attr of use.attrs) {
790
+ if (attr.name === "level" && use.name === "Heading") continue;
791
+
792
+ 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}`);
797
+ continue;
798
+ }
799
+
800
+ if (attr.name === "class") {
801
+ if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
802
+ continue;
803
+ }
804
+ if (use.name === "Checkbox" && (attr.name === "checked" || attr.name === "onChange" || attr.name === "label")) continue;
805
+ if (attr.name === "hide") {
806
+ const rendered = renderAttr(attr, params, ctx);
807
+ if (rendered) attrParts.push(rendered);
808
+ continue;
809
+ }
810
+ const rendered = renderAttr(attr, params, ctx);
811
+ if (rendered) attrParts.push(rendered);
812
+ }
813
+
814
+ const classes = [defaultClass, userClass].filter(Boolean).join(" ");
815
+ if (classes) attrParts.push(`class="${escAttr(classes)}"`);
816
+ if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
817
+ if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
818
+
819
+ const delayAttrVal = use.attrs.find(a => a.name === "delay");
820
+ if (delayAttrVal) {
821
+ const delayMs = delayAttrVal.value?.kind === "num" ? delayAttrVal.value.value : 1000;
822
+ const eventNames = ["onClick", "onChange", "onInput", "onSubmit"];
823
+ let hasEvent = false;
824
+ for (const en of eventNames) {
825
+ const evName = en.toLowerCase();
826
+ const idx = attrParts.findIndex(p => p.startsWith(evName + "="));
827
+ if (idx >= 0) {
828
+ hasEvent = true;
829
+ const current = attrParts[idx];
830
+ const match = current.match(/\(function\(\)\{\s*(.+?);\s*sinthRender\(\)/);
831
+ if (match) {
832
+ const action = match[1];
833
+ const qid = `__sq${ctx.ifIdCounter++}`;
834
+ const hideAttr = use.attrs.find(a => a.name === "hide");
835
+ const hideVal = hideAttr
836
+ ? (hideAttr.value === null
837
+ ? true
838
+ : (hideAttr.value.kind === "bool"
839
+ ? hideAttr.value.value
840
+ : (hideAttr.value.kind === "str" && hideAttr.value.value !== "false")))
841
+ : true;
842
+ ctx.actionButtons.push({ qid, delayMs, hide: hideVal });
843
+ const delayIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay"));
844
+ if (delayIdx >= 0) attrParts.splice(delayIdx, 1);
845
+ const hideIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-hide"));
846
+ if (hideIdx >= 0) attrParts.splice(hideIdx, 1);
847
+ const doneIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-done"));
848
+ if (doneIdx >= 0) attrParts.splice(doneIdx, 1);
849
+ attrParts.push(`data-sinth-queue-id="${qid}"`);
850
+ if (hideVal) {
851
+ attrParts.push(`style="display:none"`);
852
+ }
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); } })()`)}"`;
854
+ }
855
+ }
856
+ }
857
+ if (!hasEvent) {
858
+ if (use.attrs.some(a => a.name === "hide")) {
859
+ const hideAttr = use.attrs.find(a => a.name === "hide")!;
860
+ const hideVal = hideAttr.value;
861
+ const isHidden = (hideVal === null) ||
862
+ (hideVal?.kind === "bool" && hideVal.value) ||
863
+ (hideVal?.kind === "str" && hideVal.value !== "false");
864
+ attrParts.push(`data-sinth-delay-hide="${isHidden ? "true" : "false"}"`);
865
+ if (!isHidden) {
866
+ attrParts.push(`data-sinth-delay-done="1"`);
867
+ }
868
+ } else {
869
+ attrParts.push(`data-sinth-delay-hide="true"`);
870
+ }
871
+ }
872
+ }
873
+ if (use.name === "Input") {
874
+ const bindAttr = use.attrs.find(a => a.name === "bind");
875
+ const modelAttr = use.attrs.find(a => a.name === "model");
876
+ const bindOrModel = bindAttr || modelAttr;
877
+ if (bindOrModel?.value?.kind === "str") {
878
+ let vName = bindOrModel.value.value;
879
+ if (vName.startsWith("__EXPR__")) {
880
+ try {
881
+ const expr: Expression = JSON.parse(vName.substring(8));
882
+ if (expr.kind === "variable" && expr.name) vName = expr.name;
883
+ } catch {}
884
+ }
885
+ const varDecl = ctx.varDecls?.find(v => v.name === vName);
886
+ if (!use.attrs.some(a => a.name === "type")) {
887
+ if (varDecl && varDecl.varType === "int") {
888
+ attrParts.push(`type="number"`);
889
+ } else {
890
+ attrParts.push(`type="text"`);
891
+ }
892
+ }
893
+ if (varDecl && varDecl.varType === "int" && !use.attrs.some(a => a.name === "step")) {
894
+ attrParts.push(`step="1"`);
895
+ }
896
+ const rhs = (varDecl && varDecl.varType === "int")
897
+ ? `Number(e.target.value) || 0`
898
+ : `e.target.value`;
899
+ const initialVal = varDecl?.value ? litToString(varDecl.value).replace(/"/g, '&quot;') : "";
900
+ let resolvedName = vName;
901
+ if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
902
+ resolvedName = `${ctx.scopePrefix}${vName}`;
903
+ }
904
+ const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : 'sinthRender()';
905
+ const handlerBody = `${resolvedName} = ${rhs}; ${renderCall}`;
906
+ if (ctx.scopePrefix) {
907
+ attrParts.push(emitCEAction(ctx, 'input', handlerBody));
908
+ } else {
909
+ attrParts.push(`oninput="(function(e){ ${handlerBody} })(event)"`);
910
+ }
911
+ attrParts.push(`value="${escAttr(initialVal)}"`);
912
+ const valueExprId = registerExpr(ctx, { kind: "variable", name: vName });
913
+ attrParts.push(`data-sinth-value="${valueExprId}"`);
914
+ }
915
+ }
916
+ if (use.name === "Checkbox") {
917
+ if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
918
+
919
+ const checkedAttr = use.attrs.find(a => a.name === "checked");
920
+ if (checkedAttr && checkedAttr.value) {
921
+ if (checkedAttr.value.kind === "bool") {
922
+ 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
+ }
940
+ }
941
+ }
942
+
943
+ const onChangeAttr = use.attrs.find(a => a.name === "onChange");
944
+ if (onChangeAttr && onChangeAttr.value?.kind === "str") {
945
+ let raw = onChangeAttr.value.value;
946
+ if (raw.startsWith("__EXPR__")) {
947
+ try {
948
+ const expr: Expression = JSON.parse(raw.substring(8));
949
+ const jsExpr = compileExprToJS(expr);
950
+ attrParts.push(`onchange="(function(){ ${jsExpr}; sinthRender(); })(event)"`);
951
+ } catch {}
952
+ } 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)"`);
966
+ }
967
+ }
968
+
969
+ const labelAttr = use.attrs.find(a => a.name === "label");
970
+ const labelText = labelAttr?.value?.kind === "str" ? esc(interpolateAttr(labelAttr.value.value, params)) : "";
971
+
972
+ if (labelText) {
973
+ const checkAttrStr = attrParts.length ? " " + attrParts.join(" ") : "";
974
+ return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
975
+ }
976
+ }
977
+
978
+ const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
979
+
980
+ if (isVoid) {
981
+ if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
982
+ return `<${tag}${attrStr}>`;
983
+ }
984
+
985
+ const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
986
+ return `<${tag}${attrStr}>${inner}</${tag}>`;
987
+ }
988
+
989
+ export function expandUserComp(
990
+ use: CompUse,
991
+ def: CompDef,
992
+ ctx: CompileCtx,
993
+ params: Map<string, string>,
994
+ depth: number,
995
+ ): string {
996
+ if (use.name === def.name && depth > 4) {
997
+ throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
998
+ }
999
+
1000
+ const local = new Map<string, string>();
1001
+
1002
+ for (const p of def.params) {
1003
+ if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
1004
+ }
1005
+
1006
+ for (const attr of use.attrs) {
1007
+ if (attr.value === null) {
1008
+ local.set(attr.name, "true");
1009
+ } else if (attr.value.kind !== "null") {
1010
+ const raw = litToString(attr.value);
1011
+ if (raw.startsWith("__EXPR__")) {
1012
+ local.set(attr.name, raw);
1013
+ } else {
1014
+ local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
1015
+ }
1016
+ }
1017
+ }
1018
+
1019
+ for (const p of def.params) {
1020
+ if (!local.has(p.name)) {
1021
+ throw new SinthError(
1022
+ `Component '${def.name}' requires parameter '${p.name}' but it was not provided.`,
1023
+ use.loc,
1024
+ );
1025
+ }
1026
+ }
1027
+
1028
+ const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
1029
+ local.set("slot", "__RAW__" + slotHTML);
1030
+
1031
+ for (const block of def.styles) {
1032
+ ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
1033
+ }
1034
+
1035
+ return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
1036
+ }
1037
+
1038
+
1039
+
1040
+ export function collectScripts(
1041
+ file: SinthFile,
1042
+ allDefs: Map<string, CompDef>,
1043
+ ): { componentScripts: string[]; pageScripts: { raw: string; attrs: Record<string, string> }[] } {
1044
+ const componentScripts: string[] = [];
1045
+ const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
1046
+ const seenFunctions = new Set<string>();
1047
+
1048
+ for (const [, def] of allDefs) {
1049
+ for (const block of def.scripts) {
1050
+ for (const fn of extractFunctionNames(block.raw)) {
1051
+ if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
1052
+ seenFunctions.add(fn);
1053
+ }
1054
+ componentScripts.push(`(function(){\n${block.raw}\n})();`);
1055
+ }
1056
+ }
1057
+
1058
+ for (const block of file.scripts) {
1059
+ for (const fn of extractFunctionNames(block.raw)) {
1060
+ if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
1061
+ seenFunctions.add(fn);
1062
+ }
1063
+ pageScripts.push({ raw: block.raw, attrs: block.attrs });
1064
+ }
1065
+
1066
+ return { componentScripts, pageScripts };
1067
+ }
1068
+
1069
+ export function extractFunctionNames(js: string): string[] {
1070
+ const names: string[] = [];
1071
+ const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
1072
+ let m: RegExpExecArray | null;
1073
+ while ((m = re.exec(js)) !== null) names.push(m[1]);
1074
+ return names;
1075
+ }
1076
+
1077
+
1078
+
1079
+
1080
+ // sinth runtime
1081
+
1082
+
1083
+ export function buildRuntime(opts: {
1084
+ varDecls: VarDeclaration[];
1085
+ bodyHTML: string;
1086
+ logicBlocks: string[];
1087
+ mixedBlocks: MixedBlockEntry[];
1088
+ assignedVars: Set<string>;
1089
+ exprRegistry: string[];
1090
+ sharedRuntime: boolean;
1091
+ functionsJS: string;
1092
+ }): string | { page: string; shared: string } {
1093
+
1094
+ const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
1095
+ const needsMixed = mixedBlocks.length > 0;
1096
+ const needsExpr = bodyHTML.includes("sinth-expr") || needsMixed;
1097
+ const needsIf = bodyHTML.includes("data-sinth-if") || needsMixed;
1098
+ const needsFor = bodyHTML.includes("data-sinth-for") || bodyHTML.includes("data-sinth-for-expr"); const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
1099
+ const needsLogic = logicBlocks.length > 0;
1100
+ const needsFullscreen = bodyHTML.includes("data-sinth-fullscreen");
1101
+ const needsFullscreenSync = bodyHTML.includes("data-sinth-fullscreen-sync");
1102
+ const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync || needsDelay;
1103
+
1104
+ const varLines = varDecls.map(v => {
1105
+ if (!v.value) {
1106
+ if (!assignedVars.has(v.name)) {
1107
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
1108
+ SinthWarning.emit(
1109
+ `Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
1110
+ v.loc,
1111
+ );
1112
+ }
1113
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
1114
+ return `let ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
1115
+ }
1116
+ 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)};`;
1119
+ if (val.startsWith("__EXPR__")) {
1120
+ try {
1121
+ const expr: Expression = JSON.parse(val.substring(8));
1122
+ const js = compileExprToJS(expr);
1123
+ const id = exprRegistry.length;
1124
+ exprRegistry.push(js);
1125
+ return `let ${v.name} = __X[${id}]({});`;
1126
+ } catch { return `let ${v.name} = ${val};`; }
1127
+ }
1128
+ if (v.varType === "obj") return `let ${v.name} = ${val};`;
1129
+ if (v.varType === "str") return `let ${v.name} = ${JSON.stringify(val)};`;
1130
+ if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
1131
+ try {
1132
+ const arr = JSON.parse(val.slice(7));
1133
+ return `let ${v.name} = ${JSON.stringify(arr)};`;
1134
+ } catch { return `let ${v.name} = ${val.slice(7)};`; }
1135
+ }
1136
+ return `let ${v.name} = ${val};`;
1137
+ }).join("\n");
1138
+
1139
+ const memoVars = new Set<string>();
1140
+ for (const lb of logicBlocks) {
1141
+ let matches = lb.match(/_memo_(\w+)/g);
1142
+ if (matches) matches.forEach(m => memoVars.add(m));
1143
+ matches = lb.match(/_memo_(\w+)_done/g);
1144
+ if (matches) matches.forEach(m => memoVars.add(m));
1145
+ }
1146
+ for (const e of exprRegistry) {
1147
+ let matches = e.match(/_memo_(\w+)/g);
1148
+ if (matches) matches.forEach(m => memoVars.add(m));
1149
+ }
1150
+ const memoVarDecls = [...memoVars].map(m => `var ${m};`).join("\n");
1151
+
1152
+ if (!needsRender) {
1153
+ const out = [varLines, memoVarDecls].filter(Boolean).join("\n");
1154
+ return out ? `// Sinth compiled runtime\n${out}` : "";
1155
+ }
1156
+
1157
+
1158
+ const helpers = generateHelpers({ needsExpr, needsIf, needsFor, needsDelay, needsMixed });
1159
+
1160
+ const exprVarUpdates = varDecls
1161
+ .filter(v => v.value && litToString(v.value).startsWith("__EXPR__"))
1162
+ .map(v => {
1163
+ try {
1164
+ const expr: Expression = JSON.parse(litToString(v.value!).substring(8));
1165
+ const js = compileExprToJS(expr);
1166
+ const idx = exprRegistry.indexOf(js);
1167
+ return `${v.name} = __X[${idx}]({});`;
1168
+ } catch { return ""; }
1169
+ })
1170
+ .filter(Boolean)
1171
+ .join("\n ");
1172
+
1173
+ const renderBody = buildRenderBody({
1174
+ bodyHTML, logicBlocks, mixedBlocks,
1175
+ needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
1176
+ exprVarUpdates: exprVarUpdates || undefined
1177
+ });
1178
+
1179
+ let forDataJS = "";
1180
+ let forSyncBlock = "";
1181
+ if (needsFor) {
1182
+ const forArrays = new Set<string>();
1183
+ const forRegex = /data-sinth-for="([^"]+)"/g;
1184
+ let m;
1185
+ while ((m = forRegex.exec(bodyHTML)) !== null) {
1186
+ forArrays.add(m[1]);
1187
+ }
1188
+ if (forArrays.size > 0) {
1189
+ forDataJS = `var _sinthForData = {};\n`;
1190
+ forSyncBlock = [...forArrays].map(v => `_sinthForData['${v.replace(/&quot;/g, '"')}'] = ${v.replace(/&quot;/g, '"')};`).join("\n ") + "\n ";
1191
+ }
1192
+ }
1193
+
1194
+ const exprArrayJS = exprRegistry.length > 0
1195
+ ? `let __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1196
+ : "";
1197
+
1198
+ let renderFunc = '';
1199
+ if (needsRender) {
1200
+ renderFunc = `function sinthRender() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\nsinthRender();`;
1201
+ }
1202
+
1203
+ if (needsFullscreenSync) {
1204
+ renderFunc += `
1205
+ (function() {
1206
+ let syncedEls = document.querySelectorAll('[data-sinth-fullscreen-sync]');
1207
+ if (syncedEls.length > 0) {
1208
+ let vars = [];
1209
+ syncedEls.forEach(function(el) { vars.push(el.dataset.sinthFullscreenSync); });
1210
+ document.addEventListener('fullscreenchange', function() {
1211
+ let state = !!document.fullscreenElement;
1212
+ vars.forEach(function(varName) {
1213
+ switch(varName) {
1214
+ ${[...new Set(varDecls.filter(v => v.name).map(v => `case '${v.name}': ${v.name} = state; break;`))].join('\n ')}
1215
+ }
1216
+ });
1217
+ sinthRender();
1218
+ });
1219
+ }
1220
+ })();`;
1221
+ }
1222
+
1223
+ const pageCode = `// Sinth Page Runtime
1224
+ ${forDataJS}
1225
+ ${exprArrayJS}
1226
+ ${memoVarDecls}
1227
+ ${varLines}
1228
+ ${renderFunc}`;
1229
+ if (opts.sharedRuntime && helpers.trim()) {
1230
+ const sharedCode = `// Sinth shared runtime
1231
+ ${helpers}`;
1232
+ return { page: pageCode, shared: sharedCode };
1233
+ }
1234
+
1235
+ return `// Sinth compiled runtime
1236
+ ${forDataJS}
1237
+ ${functionsJS ? functionsJS + "\n" : ""}${helpers}
1238
+ ${exprArrayJS}
1239
+ ${memoVarDecls}
1240
+ ${varLines}
1241
+ ${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
+