@yannosay/sinth 1.11.6 → 1.12.1

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