@yannosay/sinth 0.4.1 → 0.5.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/sinth.ts +1598 -1230
package/src/sinth.ts CHANGED
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- // Sinth Compiler v0.1.0 — enum fix, raw-block detection, import resolution, CSS conversion, slot escaping, custom-elements, HTML5 map
2
+ // Sinth Compiler v1.0.0 — Unified if/else, Sinth Style language, tree-shaken runtime
3
+ // Single-file TypeScript compiler for the Sinth declarative web language.
4
+ // Run with: npx ts-node sinth.ts build | sinth build | sinth dev
3
5
 
4
6
  import * as fs from "fs";
5
7
  import * as path from "path";
6
8
  import * as http from "http";
7
9
 
8
- // ═══════════════════════════════════════════════════════════
9
- // SECTION 1: TYPES & AST DEFINITIONS
10
- // ═══════════════════════════════════════════════════════════
10
+ // ═══════════════════════════════════════════════════════════════════════════
11
+ // §1 TYPES & AST DEFINITIONS
12
+ // ═══════════════════════════════════════════════════════════════════════════
11
13
 
12
14
  interface Loc { file: string; line: number; col: number }
13
15
 
14
- // === v0.1.0: Must be plain `enum TT`, NOT `const enum TT` — const enum breaks TT[t] string indexing ===
16
+ // Plain `enum TT` (NOT const enum) — so TT[t] string-indexing works at runtime.
15
17
  enum TT {
16
- LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT, LBRACKET, RBRACKET,
18
+ LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT,
19
+ LBRACKET, RBRACKET,
17
20
  STRING, NUMBER, BOOL_TRUE, BOOL_FALSE, NULL_LIT,
18
21
  RAW_BLOCK,
19
22
  IDENT,
20
23
  KW_IMPORT, KW_AS, KW_CSS,
21
24
  KW_COMPONENT, KW_STYLE, KW_SCRIPT,
22
25
  KW_GLOBAL, KW_PAGE, KW_LANG,
23
- KW_CUSTOM_EL,
24
- KW_CUSTOM,
25
- // v0.2.0: Control flow keywords
26
+ KW_CUSTOM_EL, KW_CUSTOM,
26
27
  KW_IF, KW_ELSE, KW_FOR, KW_IN,
27
- // v0.1.0: Logic operators
28
28
  OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH,
29
29
  OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
30
30
  EOF,
@@ -32,28 +32,62 @@ enum TT {
32
32
 
33
33
  interface Token { type: TT; value: string; loc: Loc }
34
34
 
35
+ // ── Literal types ────────────────────────────────────────────────────────────
35
36
  type LitStr = { kind: "str"; value: string };
36
37
  type LitNum = { kind: "num"; value: number };
37
38
  type LitBool = { kind: "bool"; value: boolean };
38
39
  type LitNull = { kind: "null" };
39
40
  type Literal = LitStr | LitNum | LitBool | LitNull;
40
41
 
41
- interface Attr { name: string; value: Literal | null; loc: Loc }
42
- interface TextNode { kind: "text"; value: string; loc: Loc }
43
- interface CompUse { kind: "use"; name: string; attrs: Attr[]; children: Child[]; loc: Loc }
44
- interface ExprNode { kind: "expr"; expression: Expression; loc: Loc }
45
- interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
46
- interface ForLoop { kind: "for"; itemVar: string; arrayVar: string; body: Child[]; loc: Loc }
47
- type Child = TextNode | CompUse | ExprNode | IfBlock | ForLoop;
42
+ // ── Expression AST ───────────────────────────────────────────────────────────
43
+ type UnaryOp = "not" | "-";
44
+ type BinaryOp = "+" | "-" | "*" | "/" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "and" | "or";
45
+ type AssignOp = "=" | "+=" | "-=";
46
+ type PostfixOp = "++" | "--";
48
47
 
48
+ interface Expression {
49
+ kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix";
50
+ value?: Literal;
51
+ name?: string;
52
+ op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
53
+ operand?: Expression;
54
+ left?: Expression;
55
+ right?: Expression;
56
+ target?: string;
57
+ }
58
+
59
+ // ── AST node types ───────────────────────────────────────────────────────────
60
+ interface Attr { name: string; value: Literal | null; loc: Loc }
61
+ interface TextNode { kind: "text"; value: string; loc: Loc }
62
+ interface CompUse { kind: "use"; name: string; attrs: Attr[]; children: Child[]; loc: Loc }
63
+ interface ExprNode { kind: "expr"; expression: Expression; loc: Loc }
64
+ interface AssignStmt { kind: "assign_stmt"; expression: Expression; loc: Loc }
65
+ interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
66
+ interface ForLoop { kind: "for"; itemVar: string; arrayVar: string; body: Child[]; loc: Loc }
67
+
68
+ // v1.0.0: AssignStmt is a first-class Child so if bodies can be mixed.
69
+ type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop;
70
+
71
+ // ── Component / file structure ───────────────────────────────────────────────
49
72
  interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
50
- interface StyleBlock { global: boolean; lang: "css" | "scss"; raw: string; extraAttrs: Record<string, string>; loc: Loc }
51
- interface ScriptBlock { raw: string; attrs: Record<string, string>; loc: Loc }
52
- interface CompDef { name: string; params: ParamDecl[]; body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[]; loc: Loc }
53
73
 
74
+ interface StyleBlock {
75
+ global: boolean;
76
+ lang: "css" | "scss";
77
+ raw: string;
78
+ target?: string; // v1.0.0: component name for Sinth Style targeting
79
+ extraAttrs: Record<string, string>;
80
+ loc: Loc;
81
+ }
82
+
83
+ interface ScriptBlock { raw: string; attrs: Record<string, string>; loc: Loc }
84
+ interface CompDef { name: string; params: ParamDecl[]; body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[]; loc: Loc }
54
85
  interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
55
86
  interface CustomElInfo { tagName: string; params: ParamDecl[] }
56
87
 
88
+ type VarType = "int" | "str" | "bool" | "str[]";
89
+ interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
90
+
57
91
  type ImportNode =
58
92
  | { kind: "sinth"; path: string; loc: Loc }
59
93
  | { kind: "css"; path: string; loc: Loc }
@@ -61,34 +95,6 @@ type ImportNode =
61
95
 
62
96
  interface MetaEntry { key: string; value: Literal; loc: Loc }
63
97
 
64
- // === v0.1.0: Logic types ===
65
- type VarType = "int" | "str" | "bool" | "str[]";
66
-
67
- interface VarDeclaration {
68
- kind: "var";
69
- name: string;
70
- varType: VarType;
71
- value: Literal;
72
- loc: Loc;
73
- }
74
-
75
- // === v0.1.0: Expression AST ===
76
- type UnaryOp = "not" | "-";
77
- type BinaryOp = "+" | "-" | "*" | "/" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "and" | "or";
78
- type AssignOp = "=" | "+=" | "-=";
79
- type PostfixOp = "++" | "--";
80
-
81
- interface Expression {
82
- kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix";
83
- value?: Literal;
84
- name?: string;
85
- op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
86
- operand?: Expression;
87
- left?: Expression;
88
- right?: Expression;
89
- target?: string;
90
- }
91
-
92
98
  interface SinthFile {
93
99
  filePath: string;
94
100
  isPage: boolean;
@@ -102,19 +108,32 @@ interface SinthFile {
102
108
  varDecls: VarDeclaration[];
103
109
  }
104
110
 
111
+ // ── Mixed if/else block tracking ─────────────────────────────────────────────
112
+ interface MixedBlockEntry {
113
+ id: string;
114
+ conditionJS: string;
115
+ ifJS: string; // assignment JS in if-branch
116
+ ifHTML: string; // pre-rendered component HTML in if-branch
117
+ elseJS: string;
118
+ elseHTML: string;
119
+ }
120
+
105
121
  interface CompileCtx {
106
- allDefs: Map<string, CompDef>;
107
- customEls: Map<string, CustomElInfo>;
108
- cssLinks: string[];
109
- jsLinks: { src: string; attrs: Record<string, string> }[];
110
- scopeHash: string;
111
- pageFile: string;
112
- extraCSS: string[];
122
+ allDefs: Map<string, CompDef>;
123
+ customEls: Map<string, CustomElInfo>;
124
+ cssLinks: string[];
125
+ jsLinks: { src: string; attrs: Record<string, string> }[];
126
+ scopeHash: string;
127
+ pageFile: string;
128
+ extraCSS: string[];
129
+ mixedBlocks: MixedBlockEntry[]; // v1.0.0: mixed if/else anchors
130
+ mixedCounter: number;
131
+ logicBlocks: string[]; // v1.0.0: pure-logic if JS fragments
113
132
  }
114
133
 
115
- // ═══════════════════════════════════════════════════════════
116
- // SECTION 2: UTILITIES
117
- // ═══════════════════════════════════════════════════════════
134
+ // ═══════════════════════════════════════════════════════════════════════════
135
+ // §2 UTILITIES
136
+ // ═══════════════════════════════════════════════════════════════════════════
118
137
 
119
138
  class SinthError extends Error {
120
139
  constructor(
@@ -123,6 +142,7 @@ class SinthError extends Error {
123
142
  public readonly sourceLine?: string,
124
143
  ) {
125
144
  super(SinthError.buildMessage(rawMsg, loc, sourceLine));
145
+ Object.setPrototypeOf(this, SinthError.prototype);
126
146
  }
127
147
 
128
148
  static buildMessage(msg: string, loc?: Loc, sourceLine?: string): string {
@@ -138,7 +158,6 @@ class SinthError extends Error {
138
158
  return s;
139
159
  }
140
160
 
141
- // === v0.1.0: Attach source line to produce error preview ===
142
161
  withSource(lines: string[]): SinthError {
143
162
  if (!this.loc || this.sourceLine !== undefined) return this;
144
163
  const line = lines[this.loc.line - 1] ?? "";
@@ -153,7 +172,7 @@ class SinthWarning {
153
172
  }
154
173
  }
155
174
 
156
- /** FNV-1a 32-bit hash → deterministic 8-char hex scope id */
175
+ /** FNV-1a 32-bit hash → 8-char hex scope id */
157
176
  function fnv1a(s: string): string {
158
177
  let h = 0x811c9dc5;
159
178
  for (let i = 0; i < s.length; i++) {
@@ -192,9 +211,9 @@ function litToString(lit: Literal): string {
192
211
  }
193
212
  }
194
213
 
195
- // ═══════════════════════════════════════════════════════════
196
- // SECTION 3: LEXER
197
- // ═══════════════════════════════════════════════════════════
214
+ // ═══════════════════════════════════════════════════════════════════════════
215
+ // §3 LEXER
216
+ // ═══════════════════════════════════════════════════════════════════════════
198
217
 
199
218
  const KEYWORDS: Record<string, TT> = {
200
219
  "import": TT.KW_IMPORT,
@@ -209,7 +228,6 @@ const KEYWORDS: Record<string, TT> = {
209
228
  "true": TT.BOOL_TRUE,
210
229
  "false": TT.BOOL_FALSE,
211
230
  "null": TT.NULL_LIT,
212
- // === v0.1.0: custom-element and custom lexed as hyphenated identifier ===
213
231
  "custom-element": TT.KW_CUSTOM_EL,
214
232
  "custom": TT.KW_CUSTOM,
215
233
  "if": TT.KW_IF,
@@ -241,26 +259,25 @@ export class Lexer {
241
259
  if (ch === ",") { tokens.push(this.single(TT.COMMA, loc)); continue; }
242
260
  if (ch === ".") { tokens.push(this.single(TT.DOT, loc)); continue; }
243
261
  if (ch === ":") { tokens.push(this.single(TT.COLON, loc)); continue; }
262
+ if (ch === "[") { tokens.push(this.single(TT.LBRACKET, loc)); continue; }
263
+ if (ch === "]") { tokens.push(this.single(TT.RBRACKET, loc)); continue; }
264
+
265
+ // Two-character operators
244
266
  if (ch === "=" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_EQEQ, value: "==", loc }); continue; }
267
+ if (ch === "!" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_NEQ, value: "!=", loc }); continue; }
245
268
  if (ch === ">" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_GTEQ, value: ">=", loc }); continue; }
246
269
  if (ch === "<" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_LTEQ, value: "<=", loc }); continue; }
247
- if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
248
- if (ch === "[") { tokens.push(this.single(TT.LBRACKET, loc)); continue; }
249
- if (ch === "]") { tokens.push(this.single(TT.RBRACKET, loc)); continue; }
250
270
 
251
- // v0.1.0: Logic operators
271
+ if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
252
272
  if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
253
- if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) { tokens.push(this.single(TT.OP_MINUS, loc)); continue; }
254
273
  if (ch === "*") { tokens.push(this.single(TT.OP_STAR, loc)); continue; }
255
274
  if (ch === "/") { tokens.push(this.single(TT.OP_SLASH, loc)); continue; }
256
275
  if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
257
276
  if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
258
- if (ch === "!" && this.src[this.pos + 1] === "=") {
259
- this.adv(); // consume '!'
260
- this.adv(); // consume '='
261
- tokens.push({ type: TT.OP_NEQ, value: "!=", loc });
262
- continue;
263
- }
277
+ if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
278
+ tokens.push(this.single(TT.OP_MINUS, loc)); continue;
279
+ }
280
+
264
281
  if (ch === "{") {
265
282
  if (this.rawBlockPending) {
266
283
  this.rawBlockPending = false;
@@ -279,12 +296,11 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
279
296
 
280
297
  if (this.isIdentStart(ch)) {
281
298
  const tok = this.readIdent(loc);
282
- // === v0.1.0: Also set rawBlockPending for component, custom-element, custom ===
283
299
  if (
284
- tok.type === TT.KW_STYLE ||
285
- tok.type === TT.KW_SCRIPT ||
286
- tok.type === TT.KW_COMPONENT ||
287
- tok.type === TT.KW_CUSTOM_EL ||
300
+ tok.type === TT.KW_STYLE ||
301
+ tok.type === TT.KW_SCRIPT ||
302
+ tok.type === TT.KW_COMPONENT ||
303
+ tok.type === TT.KW_CUSTOM_EL ||
288
304
  tok.type === TT.KW_CUSTOM
289
305
  ) {
290
306
  this.rawBlockPending = true;
@@ -307,7 +323,7 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
307
323
  // Sinth comments: -- line or --[ nestable block ]--
308
324
  if (ch === "-" && this.src[this.pos + 1] === "-") {
309
325
  if (this.src[this.pos + 2] === "[") {
310
- this.adv(); this.adv(); this.adv(); // consume --[
326
+ this.adv(); this.adv(); this.adv();
311
327
  let depth = 1;
312
328
  while (this.pos < this.src.length && depth > 0) {
313
329
  if (this.src[this.pos] === "-" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "[") {
@@ -328,7 +344,6 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
328
344
  }
329
345
  }
330
346
 
331
- /** Consume a raw { ... } block tracking nested braces and skipping strings/comments. */
332
347
  private readRawBlock(loc: Loc): Token {
333
348
  this.adv(); // consume '{'
334
349
  const start = this.pos;
@@ -336,7 +351,6 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
336
351
 
337
352
  while (this.pos < this.src.length && depth > 0) {
338
353
  const ch = this.src[this.pos];
339
-
340
354
  if (ch === '"' || ch === "'" || ch === "`") { this.skipRawString(ch); continue; }
341
355
  if (ch === "/" && this.src[this.pos + 1] === "/") {
342
356
  while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
@@ -345,18 +359,14 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
345
359
  if (ch === "/" && this.src[this.pos + 1] === "*") {
346
360
  this.adv(); this.adv();
347
361
  while (this.pos < this.src.length - 1 &&
348
- !(this.src[this.pos] === "*" && this.src[this.pos + 1] === "/")) {
349
- this.adv();
350
- }
362
+ !(this.src[this.pos] === "*" && this.src[this.pos + 1] === "/")) { this.adv(); }
351
363
  this.adv(); this.adv();
352
364
  continue;
353
365
  }
354
-
355
366
  if (ch === "{") { depth++; this.adv(); }
356
367
  else if (ch === "}") {
357
368
  depth--;
358
369
  if (depth > 0) this.adv();
359
- // else: stop, leaving pos AT the closing }
360
370
  } else {
361
371
  this.adv();
362
372
  }
@@ -374,7 +384,7 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
374
384
  if (c === "\\") { this.adv(); this.adv(); continue; }
375
385
  if (c === quote) { this.adv(); return; }
376
386
  if (quote === "`" && c === "$" && this.src[this.pos + 1] === "{") {
377
- this.adv(); this.adv(); // ${
387
+ this.adv(); this.adv();
378
388
  let d = 1;
379
389
  while (this.pos < this.src.length && d > 0) {
380
390
  if (this.src[this.pos] === "{") d++;
@@ -427,7 +437,7 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
427
437
  }
428
438
  }
429
439
  if (this.pos >= this.src.length) throw new SinthError("Unterminated string literal", loc);
430
- this.adv(); // closing quote
440
+ this.adv();
431
441
  return { type: TT.STRING, value: result, loc };
432
442
  }
433
443
 
@@ -444,7 +454,6 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
444
454
 
445
455
  private readIdent(loc: Loc): Token {
446
456
  let s = "";
447
- // === v0.1.0: isIdentCont includes '-' so "custom-element" is read as one token ===
448
457
  while (this.pos < this.src.length && this.isIdentCont(this.src[this.pos])) {
449
458
  s += this.src[this.pos]; this.adv();
450
459
  }
@@ -465,157 +474,190 @@ if (ch === "!" && this.src[this.pos + 1] === "=") {
465
474
  private loc(): Loc { return { file: this.file, line: this.line, col: this.col }; }
466
475
  private isDigit(c: string) { return c >= "0" && c <= "9"; }
467
476
  private isIdentStart(c: string) { return /[a-zA-Z_\u00C0-\uFFFF]/.test(c); }
468
- // === v0.1.0: '-' allowed in identifiers so "custom-element" is a single token ===
469
477
  private isIdentCont(c: string) { return /[a-zA-Z0-9_\-\u00C0-\uFFFF]/.test(c); }
470
478
  }
471
479
 
472
- // ═══════════════════════════════════════════════════════════
473
- // SECTION 4: PARSER
474
- // ═══════════════════════════════════════════════════════════
480
+ // ═══════════════════════════════════════════════════════════════════════════
481
+ // §4 PARSER
482
+ // ═══════════════════════════════════════════════════════════════════════════
475
483
 
476
484
  export class Parser {
477
- private pos = 0;
485
+ private pos = 0;
478
486
  private loopVar: string | null = null;
487
+ /** Accumulated var declarations for type-checking in bodies. */
488
+ private _varDecls: VarDeclaration[] = [];
479
489
 
480
490
  constructor(private tokens: Token[], private file: string) {}
481
491
 
492
+ // ── Top-level file parse ────────────────────────────────────────────────
493
+
482
494
  parse(): SinthFile {
483
- const loc = this.peek().loc;
484
495
  let isPage = false;
485
- const imports: ImportNode[] = [];
486
- const meta: MetaEntry[] = [];
487
- const defs: CompDef[] = [];
488
- const uses: CompUse[] = [];
489
- const styles: StyleBlock[] = [];
490
- const scripts: ScriptBlock[] = [];
491
- const customEls: CustomElDecl[] = [];
492
- const varDecls: VarDeclaration[] = [];
493
-
494
- // 1. Optional page keyword
496
+ const imports: ImportNode[] = [];
497
+ const meta: MetaEntry[] = [];
498
+ const defs: CompDef[] = [];
499
+ const uses: CompUse[] = [];
500
+ const styles: StyleBlock[] = [];
501
+ const scripts: ScriptBlock[] = [];
502
+ const customEls: CustomElDecl[] = [];
503
+ const varDecls: VarDeclaration[] = [];
504
+ this._varDecls = varDecls;
505
+
495
506
  if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
496
507
 
497
- // 2. Imports — must come before metadata
498
508
  while (this.check(TT.KW_IMPORT)) imports.push(this.parseImport());
499
509
 
500
- // 3. Metadata — key = value pairs (lexer has already stripped comments/whitespace)
501
510
  while (this.isMetaStart()) {
502
- const keyName = this.tokens[this.pos].value;
503
- if (varDecls.some(v => v.name === keyName)) {
504
- break;
505
- }
506
511
  const entry = this.parseMeta();
507
512
  meta.push(entry);
508
513
  if (entry.key === "title") isPage = true;
509
514
  }
510
515
 
511
- // 4. Body: component definitions, usages, style, script, custom-element
512
- // 4a. Variable declarations (v0.1.0 logic)
516
+ // Variable declarations
513
517
  while (this.check(TT.IDENT) && this.peek().value === "var") {
514
518
  const vd = this.parseVarDeclaration();
515
- if (vd) varDecls.push(vd);
519
+ if (vd) { varDecls.push(vd); this._varDecls.push(vd); }
516
520
  }
517
- // Store var declarations for type checking in inline logic
518
- (this as any)._varDecls = varDecls;
519
521
 
520
- // 4b. Body: component definitions, usages, style, script, custom-element
522
+ // Body
521
523
  while (!this.check(TT.EOF)) {
522
- if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
523
- else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
524
- else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
524
+ if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
525
+ else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
526
+ else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
525
527
  else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
526
- else if (this.check(TT.IDENT)) {
527
- // Check if it's a variable assignment (ident = expression)
528
- const savedPos = this.pos;
529
- const identName = this.consume(TT.IDENT).value;
530
- if (this.check(TT.EQUALS)) {
531
- // It's an assignment: variableName = value
532
- this.consume(TT.EQUALS);
533
- const expr = this.parseExpression();
534
- if (expr) {
535
- // Wrap as inline script assignment
536
- const jsExpr = compileExprToJS(expr);
537
- const scriptBlock: ScriptBlock = {
538
- raw: `${identName} = ${jsExpr};\nsinthRender();`,
539
- attrs: {},
540
- loc: this.peek().loc,
541
- };
542
- scripts.push(scriptBlock);
543
- continue;
544
- }
545
- }
546
- // Not an assignment, revert and parse as component usage
547
- this.pos = savedPos;
548
- uses.push(this.parseCompUse());
528
+ else if (this.check(TT.IDENT) && this.peek().value === "var") {
529
+ const vd = this.parseVarDeclaration();
530
+ if (vd) varDecls.push(vd);
549
531
  }
550
- else throw new SinthError(`Unexpected token '${this.peek().value}'`, this.peek().loc);
532
+ else if (this.check(TT.KW_IF)) {
533
+ // v1.0.0: Top-level if blocks in a page are parsed via unified body
534
+ const ifNode = this.parseIfBlock();
535
+ uses.push(...this.flattenIfToUses(ifNode, scripts));
536
+ }
537
+ else if (this.check(TT.IDENT)) {
538
+ const savedPos = this.pos;
539
+ const identName = this.peek().value;
540
+ const nextType = this.tokens[this.pos + 1]?.type;
541
+
542
+ // Guard: Detect accidental top-level expressions (e.g. "guess == target" instead of "if guess == target")
543
+ // This prevents the parser from treating "guess" as a component and failing later on "=="
544
+ const isComparison = [TT.OP_EQEQ, TT.OP_NEQ, TT.OP_LT, TT.OP_GT, TT.OP_LTEQ, TT.OP_GTEQ].includes(nextType);
545
+ const isLogicAndOr = nextType === TT.IDENT && (this.tokens[this.pos + 1]?.value === "and" || this.tokens[this.pos + 1]?.value === "or");
546
+
547
+ if (isComparison || isLogicAndOr) {
548
+ throw new SinthError(
549
+ `Unexpected expression '${identName} ...' at top level. Did you mean to wrap this in an 'if' block?`,
550
+ this.peek().loc,
551
+ );
552
+ }
553
+
554
+ // Top-level assignment: ident = expr
555
+ if (nextType === TT.EQUALS ||
556
+ (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) ||
557
+ (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
558
+ this.consume(TT.IDENT); // consume name
559
+ let op: AssignOp = "=";
560
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
561
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
562
+ this.consume(TT.EQUALS);
563
+ const expr = this.parseExpression();
564
+ if (expr) {
565
+ const js = `${identName} ${op} ${compileExprToJS(expr)};
566
+ sinthRender();`;
567
+ scripts.push({ raw: js, attrs: {}, loc: this.peek().loc });
551
568
  }
569
+ continue;
570
+ }
552
571
 
553
- if ((this as any)._logicScripts) {
554
- scripts.push(...(this as any)._logicScripts);
572
+ // Component usage
573
+ this.pos = savedPos;
574
+ uses.push(this.parseCompUse());
575
+ }
576
+ else throw new SinthError(
577
+ `Unexpected token '${this.peek().value}' (${TT[this.peek().type]}) at top level`,
578
+ this.peek().loc,
579
+ );
555
580
  }
581
+
556
582
  return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
557
583
  }
558
584
 
559
- // ── Imports ──────────────────────────────────────────────
585
+ /** Flatten a top-level IfBlock into uses/scripts arrays so rendering works. */
586
+ private flattenIfToUses(ifNode: IfBlock, scripts: ScriptBlock[]): CompUse[] {
587
+ // Pure logic (only AssignStmt children): emit as script block
588
+ const bodyHasComp = ifNode.body.some(c => c.kind === "use");
589
+ const elseHasComp = (ifNode.elseBody ?? []).some(c => c.kind === "use");
590
+ if (!bodyHasComp && !elseHasComp) {
591
+ scripts.push({ raw: compileIfToJS(ifNode), attrs: {}, loc: ifNode.loc });
592
+ return [];
593
+ }
594
+ // Otherwise keep it embedded — it will be rendered as a child
595
+ // We wrap it in a synthetic CompUse placeholder so it flows through renderCompUse
596
+ // Actually: embed the IfBlock in a fake wrapper use
597
+ // We'll handle it by emitting a special "sinth-if-root" use
598
+ const syntheticUse: CompUse = {
599
+ kind: "use",
600
+ name: "__IF_ROOT__",
601
+ attrs: [],
602
+ children: [ifNode],
603
+ loc: ifNode.loc,
604
+ };
605
+ return [syntheticUse];
606
+ }
607
+
608
+ // ── Imports ──────────────────────────────────────────────────────────────
560
609
 
561
610
  private parseImport(): ImportNode {
562
611
  const loc = this.consume(TT.KW_IMPORT).loc;
563
-
564
612
  if (this.check(TT.KW_CSS)) {
565
613
  this.consume(TT.KW_CSS);
566
614
  return { kind: "css", path: this.consume(TT.STRING).value, loc };
567
615
  }
568
-
569
616
  if (this.check(TT.STRING)) {
570
617
  return { kind: "sinth", path: this.consume(TT.STRING).value, loc };
571
618
  }
572
-
573
619
  if (this.check(TT.IDENT)) {
574
620
  const name = this.consume(TT.IDENT).value;
575
621
  let alias: string | undefined;
576
622
  if (this.check(TT.KW_AS)) { this.consume(TT.KW_AS); alias = this.consume(TT.IDENT).value; }
577
623
  return { kind: "js", name, alias, loc };
578
624
  }
579
-
580
625
  throw new SinthError(`Expected import path, library name, or 'css'`, loc);
581
626
  }
582
627
 
583
- // ── Metadata ─────────────────────────────────────────────
628
+ // ── Metadata ─────────────────────────────────────────────────────────────
584
629
 
585
630
  private isMetaStart(): boolean {
586
- // Metadata: IDENT followed by EQUALS (e.g. title = "My Site")
587
- // Component usage: IDENT followed by LPAREN or LBRACE
588
631
  if (!this.check(TT.IDENT)) return false;
589
632
  return this.tokens[this.pos + 1]?.type === TT.EQUALS;
590
633
  }
591
634
 
592
- private parseMeta(): MetaEntry {
635
+ private parseMeta(): MetaEntry {
593
636
  const loc = this.peek().loc;
594
637
  const key = this.consume(TT.IDENT).value;
595
638
  this.consume(TT.EQUALS);
596
639
  return { key, value: this.parseLiteral(), loc };
597
640
  }
598
641
 
599
- // === v0.1.0: Parse variable declaration ===
642
+ // ── Variable declarations ────────────────────────────────────────────────
643
+
600
644
  private parseVarDeclaration(): VarDeclaration | null {
601
645
  const loc = this.peek().loc;
602
- this.consume(TT.IDENT); // 'var'
646
+ this.consume(TT.IDENT); // consume 'var'
603
647
 
604
648
  const typeTok = this.consume(TT.IDENT);
605
649
  let typeStr = typeTok.value;
606
650
  if (this.check(TT.LBRACKET) && this.tokens[this.pos + 1]?.type === TT.RBRACKET) {
607
- this.consume(TT.LBRACKET);
608
- this.consume(TT.RBRACKET);
651
+ this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
609
652
  typeStr = "str[]";
610
653
  }
611
-
612
654
  if (!["int", "str", "bool", "str[]"].includes(typeStr)) {
613
- throw new SinthError(`Unknown type '${typeStr}'. Expected int, str, bool, or str[]`, typeTok.loc);
655
+ throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[]`, typeTok.loc);
614
656
  }
615
657
 
616
658
  const nameTok = this.consume(TT.IDENT);
617
659
  let val: Literal | null = null;
618
-
660
+
619
661
  if (this.check(TT.EQUALS)) {
620
662
  this.consume(TT.EQUALS);
621
663
  if (this.check(TT.LBRACKET)) {
@@ -628,187 +670,204 @@ export class Parser {
628
670
  }
629
671
  }
630
672
 
631
- return {
632
- kind: "var",
633
- name: nameTok.value,
634
- varType: typeStr as VarType,
635
- value: val,
636
- loc,
637
- };
673
+ return { kind: "var", name: nameTok.value, varType: typeStr as VarType, value: val, loc };
638
674
  }
639
675
 
640
- private parseArrayLiteral(): Literal {
641
- const loc = this.consume(TT.LBRACKET).loc;
642
- const items: string[] = [];
643
-
676
+ private parseArrayLiteral(): Literal {
677
+ this.consume(TT.LBRACKET);
678
+ const items: any[] = [];
644
679
  while (!this.check(TT.RBRACKET) && !this.check(TT.EOF)) {
645
- if (this.check(TT.STRING)) {
680
+ if (this.check(TT.LBRACE)) {
681
+ items.push(this.parseObjectLiteral());
682
+ } else if (this.check(TT.STRING)) {
646
683
  items.push(this.consume(TT.STRING).value);
647
684
  } else if (this.check(TT.NUMBER)) {
648
- items.push(this.consume(TT.NUMBER).value);
685
+ items.push(parseFloat(this.consume(TT.NUMBER).value));
649
686
  } else if (this.check(TT.BOOL_TRUE)) {
650
687
  this.consume(TT.BOOL_TRUE);
651
- items.push("true");
688
+ items.push(true);
652
689
  } else if (this.check(TT.BOOL_FALSE)) {
653
690
  this.consume(TT.BOOL_FALSE);
654
- items.push("false");
655
- }
656
-
657
- if (this.check(TT.COMMA)) {
658
- this.consume(TT.COMMA);
659
- } else {
660
- break;
691
+ items.push(false);
692
+ } else if (this.check(TT.NULL_LIT)) {
693
+ this.consume(TT.NULL_LIT);
694
+ items.push(null);
661
695
  }
696
+ if (this.check(TT.COMMA)) this.consume(TT.COMMA); else break;
662
697
  }
663
-
664
698
  this.consume(TT.RBRACKET);
665
699
  return { kind: "str", value: `__ARR__${JSON.stringify(items)}` };
666
700
  }
667
701
 
702
+ private parseObjectLiteral(): Record<string, any> {
703
+ this.consume(TT.LBRACE);
704
+ const obj: Record<string, any> = {};
705
+ while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
706
+ const key = this.consume(TT.IDENT).value;
707
+ this.consume(TT.COLON);
708
+ if (this.check(TT.STRING)) {
709
+ obj[key] = this.consume(TT.STRING).value;
710
+ } else if (this.check(TT.NUMBER)) {
711
+ obj[key] = parseFloat(this.consume(TT.NUMBER).value);
712
+ } else if (this.check(TT.BOOL_TRUE)) {
713
+ this.consume(TT.BOOL_TRUE);
714
+ obj[key] = true;
715
+ } else if (this.check(TT.BOOL_FALSE)) {
716
+ this.consume(TT.BOOL_FALSE);
717
+ obj[key] = false;
718
+ } else if (this.check(TT.NULL_LIT)) {
719
+ this.consume(TT.NULL_LIT);
720
+ obj[key] = null;
721
+ } else {
722
+ throw new SinthError(`Expected literal value for key '${key}'`, this.peek().loc);
723
+ }
724
+ if (this.check(TT.COMMA)) this.consume(TT.COMMA);
725
+ }
726
+ this.consume(TT.RBRACE);
727
+ return obj;
728
+ }
729
+
730
+ // ── Expression parsing ───────────────────────────────────────────────────
668
731
 
669
- // ── Expression parsing (v0.1.0) ────────────────────────
670
- private parseExpression(): Expression | null {
732
+ /**
733
+ * Parses an expression. Handles:
734
+ * - Literals (string, number, bool, null)
735
+ * - Variable references
736
+ * - Parenthesised sub-expressions
737
+ * - Unary "not" / "-"
738
+ * - Binary comparisons (==, !=, <, >, <=, >=, +, -, *, /)
739
+ * - Assignments (=, +=, -=)
740
+ */
741
+ parseExpression(): Expression | null {
671
742
  const tok = this.peek();
672
-
743
+
673
744
  // Unary 'not'
674
745
  if (tok.type === TT.IDENT && tok.value === "not") {
675
- this.consume(TT.IDENT); // consume 'not'
746
+ this.consume(TT.IDENT);
676
747
  const operand = this.parseExpression();
677
748
  if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
678
749
  return { kind: "unary", op: "not", operand };
679
750
  }
680
751
 
681
- // Parenthesized expression
752
+ // Parenthesised expression
682
753
  if (this.check(TT.LPAREN)) {
683
754
  this.consume(TT.LPAREN);
684
- const expr = this.parseExpression();
685
- if (!expr) throw new SinthError("Expected expression after '('", this.peek().loc);
686
- if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", this.peek().loc);
755
+ const inner = this.parseExpression();
756
+ if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
757
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
687
758
  this.consume(TT.RPAREN);
688
- return expr;
759
+ // Check for trailing binary operator
760
+ return this.parseBinaryRHS(inner);
689
761
  }
690
762
 
691
763
  // Literal
692
- if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
764
+ if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
765
+ this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
693
766
  const lit = this.parseLiteral();
694
- if (lit) return { kind: "literal", value: lit };
767
+ const base: Expression = { kind: "literal", value: lit };
768
+ return this.parseBinaryRHS(base);
695
769
  }
696
-
697
- // Variable — check for assignment operators after it
770
+
771
+ // Variable or assignment
698
772
  if (tok.type === TT.IDENT) {
699
773
  const name = this.consume(TT.IDENT).value;
700
774
 
701
- // Check for !=
702
- if (this.check(TT.OP_NEQ)) {
703
- this.consume(TT.OP_NEQ);
704
- console.log("DEBUG != right side token:", this.peek().value, "type:", TT[this.peek().type]);
705
- const right = this.parseExpression();
706
- if (!right) throw new SinthError("Expected expression after !=", this.peek().loc);
707
- return { kind: "binary", left: { kind: "variable", name }, op: "!=", right };
708
- }
709
-
710
-
711
- // Check for == (comparison)
712
- if (this.check(TT.OP_EQEQ)) {
713
- this.consume(TT.OP_EQEQ);
714
- const right = this.parseExpression();
715
- if (!right) throw new SinthError("Expected expression after ==", this.peek().loc);
716
- return { kind: "binary", left: { kind: "variable", name }, op: "==", right };
717
- }
718
-
719
-
720
-
721
- // Check for <
722
- if (this.check(TT.OP_LT)) {
723
- this.consume(TT.OP_LT);
724
- const right = this.parseExpression();
725
- if (!right) throw new SinthError("Expected expression after <", this.peek().loc);
726
- return { kind: "binary", left: { kind: "variable", name }, op: "<", right };
727
- }
728
- // Check for >
729
- if (this.check(TT.OP_GT)) {
730
- this.consume(TT.OP_GT);
731
- const right = this.parseExpression();
732
- if (!right) throw new SinthError("Expected expression after >", this.peek().loc);
733
- return { kind: "binary", left: { kind: "variable", name }, op: ">", right };
734
- }
735
-
736
- // Check for >=
737
- if (this.check(TT.OP_GTEQ)) {
738
- this.consume(TT.OP_GTEQ);
739
- const right = this.parseExpression();
740
- if (!right) throw new SinthError("Expected expression after >= ", this.peek().loc);
741
- return { kind: "binary", left: { kind: "variable", name }, op: ">=", right };
742
- }
743
- // Check for <=
744
- if (this.check(TT.OP_LTEQ)) {
745
- this.consume(TT.OP_LTEQ);
746
- const right = this.parseExpression();
747
- if (!right) throw new SinthError("Expected expression after <=", this.peek().loc);
748
- return { kind: "binary", left: { kind: "variable", name }, op: "<=", right };
749
- }
750
-
751
- // Check for +=, -=, =
752
- if (this.check(TT.OP_PLUS) || this.check(TT.OP_MINUS) || this.check(TT.EQUALS)) {
753
- const opTok = this.peek();
775
+ // Handle dot notation: user.age
776
+ if (this.check(TT.DOT)) {
777
+ this.consume(TT.DOT);
778
+ const propName = this.consume(TT.IDENT).value;
779
+ const fullName = `${name}.${propName}`;
754
780
 
755
- // += (only if next-next token is =)
756
- const nextTok = this.tokens[this.pos + 1];
757
- if (opTok.type === TT.OP_PLUS && nextTok && nextTok.type === TT.EQUALS) {
758
- this.consume(TT.OP_PLUS); // consume '+'
759
- this.consume(TT.EQUALS); // consume '='
760
- const right = this.parseExpression();
761
- if (!right) throw new SinthError("Expected expression after +=", this.peek().loc);
762
- return { kind: "assign", target: name, op: "+=", right };
781
+ // Compound-assignment operators: +=, -=
782
+ const nextType = this.tokens[this.pos]?.type;
783
+ if (nextType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
784
+ this.consume(TT.OP_PLUS); this.consume(TT.EQUALS);
785
+ const rhs = this.parseExpression();
786
+ if (!rhs) throw new SinthError("Expected expression after +=", this.peek().loc);
787
+ return { kind: "assign", target: fullName, op: "+=", right: rhs };
763
788
  }
764
-
765
- // -=
766
- if (opTok.type === TT.OP_MINUS && nextTok && nextTok.type === TT.EQUALS) {
767
- this.consume(TT.OP_MINUS);
768
- this.consume(TT.EQUALS);
769
- const right = this.parseExpression();
770
- if (!right) throw new SinthError("Expected expression after -=", this.peek().loc);
771
- return { kind: "assign", target: name, op: "-=", right };
789
+ if (nextType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
790
+ this.consume(TT.OP_MINUS); this.consume(TT.EQUALS);
791
+ const rhs = this.parseExpression();
792
+ if (!rhs) throw new SinthError("Expected expression after -=", this.peek().loc);
793
+ return { kind: "assign", target: fullName, op: "-=", right: rhs };
772
794
  }
773
-
774
- // =
775
- if (opTok.type === TT.EQUALS) {
795
+ if (nextType === TT.EQUALS) {
776
796
  this.consume(TT.EQUALS);
777
- const right = this.parseExpression();
778
- if (!right) throw new SinthError("Expected expression after =", this.peek().loc);
779
- return { kind: "assign", target: name, op: "=", right };
797
+ const rhs = this.parseExpression();
798
+ if (!rhs) throw new SinthError("Expected expression after =", this.peek().loc);
799
+ return { kind: "assign", target: fullName, op: "=", right: rhs };
780
800
  }
781
801
 
782
- // Plain + or - (binary operator)
783
- if (opTok.type === TT.OP_PLUS || opTok.type === TT.OP_MINUS) {
784
- const op = this.consume(opTok.type).value as "+" | "-";
785
- const right = this.parseExpression();
786
- if (!right) throw new SinthError("Expected expression after " + op, this.peek().loc);
787
- return { kind: "binary", left: { kind: "variable", name }, op, right };
788
- }
802
+ const varExpr: Expression = { kind: "variable", name: fullName };
803
+ return this.parseBinaryRHS(varExpr);
789
804
  }
790
-
791
- // Just a variable reference
792
- return { kind: "variable", name };
805
+
806
+ // Compound-assignment operators: +=, -=
807
+ const nextType = this.tokens[this.pos]?.type;
808
+ if (nextType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
809
+ this.consume(TT.OP_PLUS); this.consume(TT.EQUALS);
810
+ const rhs = this.parseExpression();
811
+ if (!rhs) throw new SinthError("Expected expression after +=", this.peek().loc);
812
+ return { kind: "assign", target: name, op: "+=", right: rhs };
813
+ }
814
+ if (nextType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
815
+ this.consume(TT.OP_MINUS); this.consume(TT.EQUALS);
816
+ const rhs = this.parseExpression();
817
+ if (!rhs) throw new SinthError("Expected expression after -=", this.peek().loc);
818
+ return { kind: "assign", target: name, op: "-=", right: rhs };
819
+ }
820
+ // Simple assignment
821
+ if (nextType === TT.EQUALS) {
822
+ this.consume(TT.EQUALS);
823
+ const rhs = this.parseExpression();
824
+ if (!rhs) throw new SinthError("Expected expression after =", this.peek().loc);
825
+ return { kind: "assign", target: name, op: "=", right: rhs };
826
+ }
827
+
828
+ const varExpr: Expression = { kind: "variable", name };
829
+ return this.parseBinaryRHS(varExpr);
793
830
  }
794
-
831
+
795
832
  return null;
796
833
  }
797
834
 
798
- // ── Component definitions ─────────────────────────────────
835
+ /** After parsing a left-hand operand, check for a binary operator and parse RHS. */
836
+ private parseBinaryRHS(left: Expression): Expression {
837
+ const t = this.peek().type;
838
+ let op: BinaryOp | null = null;
839
+ if (t === TT.OP_EQEQ) op = "==";
840
+ else if (t === TT.OP_NEQ) op = "!=";
841
+ else if (t === TT.OP_LT) op = "<";
842
+ else if (t === TT.OP_GT) op = ">";
843
+ else if (t === TT.OP_LTEQ) op = "<=";
844
+ else if (t === TT.OP_GTEQ) op = ">=";
845
+ else if (t === TT.OP_PLUS) op = "+";
846
+ else if (t === TT.OP_MINUS) op = "-";
847
+ else if (t === TT.OP_STAR) op = "*";
848
+ else if (t === TT.OP_SLASH) op = "/";
849
+ else if (t === TT.IDENT && this.peek().value === "and") op = "and";
850
+ else if (t === TT.IDENT && this.peek().value === "or") op = "or";
851
+
852
+ if (!op) return left;
853
+ this.pos++;
854
+
855
+ const right = this.parseExpression();
856
+ if (!right) throw new SinthError(`Expected expression after '${op}'`, this.peek().loc);
857
+ return { kind: "binary", left, op, right };
858
+ }
859
+
860
+ // ── Component definitions ────────────────────────────────────────────────
799
861
 
800
862
  private parseCompDef(): CompDef {
801
- const loc = this.consume(TT.KW_COMPONENT).loc;
802
- const name = this.consume(TT.IDENT).value;
863
+ const loc = this.consume(TT.KW_COMPONENT).loc;
864
+ const name = this.consume(TT.IDENT).value;
803
865
  const params = this.parseParamDecls();
804
- // === v0.1.0: rawBlockPending was set by the lexer when KW_COMPONENT was read;
805
- // the next token is therefore RAW_BLOCK, not LBRACE ===
806
866
  const rawTok = this.consume(TT.RAW_BLOCK);
807
867
  const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
808
868
  return { name, params, body, styles, scripts, loc };
809
869
  }
810
870
 
811
- // === v0.1.0: Parse custom-element / custom declarations ===
812
871
  private parseCustomEl(): CustomElDecl {
813
872
  const loc = this.peek().loc;
814
873
  if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
@@ -816,7 +875,6 @@ export class Parser {
816
875
  const tagName = this.consume(TT.IDENT).value;
817
876
  const sinthName = tagNameToPascal(tagName);
818
877
  const params = this.parseParamDecls();
819
- // custom-element / custom declarations have no body block
820
878
  return { sinthName, tagName, params, loc };
821
879
  }
822
880
 
@@ -825,10 +883,9 @@ export class Parser {
825
883
  if (!this.check(TT.LPAREN)) return params;
826
884
  this.consume(TT.LPAREN);
827
885
  while (!this.check(TT.RPAREN)) {
828
- const ploc = this.peek().loc;
829
- // allow keywords as parameter names (e.g., "for" in custom-element declarations)
886
+ const ploc = this.peek().loc;
830
887
  const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
831
- const pname = nameTok.value;
888
+ const pname = nameTok.value;
832
889
  let defaultVal: Literal | undefined;
833
890
  if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
834
891
  params.push({ name: pname, defaultVal, loc: ploc });
@@ -838,9 +895,14 @@ export class Parser {
838
895
  return params;
839
896
  }
840
897
 
841
- private parseCompBody(raw: string, loc: Loc): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
898
+ private parseCompBody(
899
+ raw: string,
900
+ loc: Loc,
901
+ ): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
842
902
  const tokens = new Lexer(raw, loc.file).tokenize();
843
- return new Parser(tokens, loc.file).parseBodyContents();
903
+ const sub = new Parser(tokens, loc.file);
904
+ sub._varDecls = this._varDecls;
905
+ return sub.parseBodyContents();
844
906
  }
845
907
 
846
908
  private parseBodyContents(): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
@@ -852,15 +914,174 @@ export class Parser {
852
914
  const loc = this.peek().loc;
853
915
  body.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
854
916
  }
855
- else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
856
- else throw new SinthError(`Unexpected token '${this.peek().value}' in component body`, this.peek().loc);
917
+ else if (this.check(TT.IDENT) && this.peek().value === "var") {
918
+ const vd = this.parseVarDeclaration();
919
+ if (vd) this._varDecls.push(vd);
920
+ continue;
921
+ }
922
+ else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
923
+ else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
924
+ else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
925
+ else throw new SinthError(
926
+ `Unexpected token '${this.peek().value}' in component body`,
927
+ this.peek().loc,
928
+ );
857
929
  }
858
930
  return { body, styles, scripts };
859
931
  }
860
932
 
861
- // ── Component usages ──────────────────────────────────────
933
+ // ── If / else blocks (v1.0.0: unified mixed body) ────────────────────────
862
934
 
863
- private parseCompUse(): CompUse {
935
+ private parseIfBlock(): IfBlock {
936
+ const loc = this.consume(TT.KW_IF).loc;
937
+ const condition = this.parseExpression();
938
+ if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
939
+
940
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after if condition", this.peek().loc);
941
+ this.consume(TT.LBRACE);
942
+ const body = this.parseUnifiedBody();
943
+ this.consume(TT.RBRACE);
944
+
945
+ let elseBody: Child[] | undefined;
946
+ if (this.check(TT.KW_ELSE)) {
947
+ this.consume(TT.KW_ELSE);
948
+ if (this.check(TT.KW_IF)) {
949
+ // else if → treat as nested IfBlock
950
+ elseBody = [this.parseIfBlock()];
951
+ } else {
952
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after else", this.peek().loc);
953
+ this.consume(TT.LBRACE);
954
+ elseBody = this.parseUnifiedBody();
955
+ this.consume(TT.RBRACE);
956
+ }
957
+ }
958
+
959
+ return { kind: "if", condition, body, elseBody, loc };
960
+ }
961
+
962
+ /**
963
+ * v1.0.0: Parses a body that may contain ANY mix of assignment statements and
964
+ * component usages. This replaces the old split between "inline logic" and "DOM if".
965
+ */
966
+ private parseUnifiedBody(): Child[] {
967
+ const children: Child[] = [];
968
+
969
+ while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
970
+ if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
971
+ if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
972
+ if (this.check(TT.STRING)) {
973
+ const loc = this.peek().loc;
974
+ children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
975
+ continue;
976
+ }
977
+
978
+ // Variable declarations inside unified bodies
979
+ if (this.check(TT.IDENT) && this.peek().value === "var") {
980
+ const vd = this.parseVarDeclaration();
981
+ if (vd) this._varDecls.push(vd);
982
+ continue;
983
+ }
984
+
985
+ if (this.check(TT.IDENT)) {
986
+ const loc = this.peek().loc;
987
+ const name = this.peek().value;
988
+ const nextType = this.tokens[this.pos + 1]?.type;
989
+ const nextNextType = this.tokens[this.pos + 2]?.type;
990
+
991
+ // Handle dot notation for assignments: user.age = value
992
+ if (nextType === TT.DOT && (nextNextType === TT.EQUALS ||
993
+ (nextNextType === TT.OP_PLUS && this.tokens[this.pos + 3]?.type === TT.EQUALS) ||
994
+ (nextNextType === TT.OP_MINUS && this.tokens[this.pos + 3]?.type === TT.EQUALS))) {
995
+ let fullName = this.consume(TT.IDENT).value;
996
+ this.consume(TT.DOT);
997
+ fullName = fullName + "." + this.consume(TT.IDENT).value;
998
+
999
+ let op: AssignOp = "=";
1000
+ const afterDotType = this.tokens[this.pos]?.type;
1001
+ if (afterDotType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
1002
+ this.consume(TT.OP_PLUS); op = "+=";
1003
+ } else if (afterDotType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
1004
+ this.consume(TT.OP_MINUS); op = "-=";
1005
+ }
1006
+ this.consume(TT.EQUALS);
1007
+ const rhs = this.parseExpression();
1008
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
1009
+ const assignExpr: Expression = { kind: "assign", target: fullName, op, right: rhs };
1010
+ children.push({ kind: "assign_stmt", expression: assignExpr, loc });
1011
+ continue;
1012
+ }
1013
+
1014
+ // Assignment: ident = expr | ident += expr | ident -= expr
1015
+ const isSimpleAssign = nextType === TT.EQUALS;
1016
+ const isPlusAssign = nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
1017
+ const isMinusAssign = nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
1018
+
1019
+ if (isSimpleAssign || isPlusAssign || isMinusAssign) {
1020
+ this.consume(TT.IDENT); // consume name
1021
+ let op: AssignOp = "=";
1022
+ if (isPlusAssign) { this.consume(TT.OP_PLUS); op = "+="; }
1023
+ else if (isMinusAssign) { this.consume(TT.OP_MINUS); op = "-="; }
1024
+ this.consume(TT.EQUALS);
1025
+ const rhs = this.parseExpression();
1026
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
1027
+ const assignExpr: Expression = { kind: "assign", target: name, op, right: rhs };
1028
+ children.push({ kind: "assign_stmt", expression: assignExpr, loc });
1029
+ continue;
1030
+ }
1031
+
1032
+ // Component usage: ident( or ident{ or ident RAW_BLOCK
1033
+ if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1034
+ children.push(this.parseCompUse());
1035
+ continue;
1036
+ }
1037
+
1038
+ // Variable expression (e.g. just referencing a variable for display)
1039
+ // Check for dot notation variable reference (user.age without assignment)
1040
+ if (nextType === TT.DOT) {
1041
+ let fullName = this.consume(TT.IDENT).value;
1042
+ this.consume(TT.DOT);
1043
+ fullName = fullName + "." + this.consume(TT.IDENT).value;
1044
+ children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1045
+ continue;
1046
+ }
1047
+
1048
+ // Simple variable reference
1049
+ this.consume(TT.IDENT);
1050
+ children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1051
+ continue;
1052
+ }
1053
+
1054
+ throw new SinthError(
1055
+ `Unexpected token '${this.peek().value}' in if/else body`,
1056
+ this.peek().loc,
1057
+ );
1058
+ }
1059
+
1060
+ return children;
1061
+ }
1062
+
1063
+ // ── For loops ────────────────────────────────────────────────────────────
1064
+
1065
+ private parseForLoop(): ForLoop {
1066
+ const loc = this.consume(TT.KW_FOR).loc;
1067
+ const itemVar = this.consume(TT.IDENT).value;
1068
+ if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
1069
+ this.consume(TT.KW_IN);
1070
+ const arrayVar = this.consume(TT.IDENT).value;
1071
+
1072
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after for..in expression", this.peek().loc);
1073
+ this.consume(TT.LBRACE);
1074
+ this.loopVar = itemVar;
1075
+ const body = this.parseChildList();
1076
+ this.loopVar = null;
1077
+ this.consume(TT.RBRACE);
1078
+
1079
+ return { kind: "for", itemVar, arrayVar, body, loc };
1080
+ }
1081
+
1082
+ // ── Component usages ─────────────────────────────────────────────────────
1083
+
1084
+ private parseCompUse(): CompUse {
864
1085
  const loc = this.peek().loc;
865
1086
  const name = this.consume(TT.IDENT).value;
866
1087
  const attrs: Attr[] = [];
@@ -873,42 +1094,41 @@ private parseCompUse(): CompUse {
873
1094
  let value: Literal | null = null;
874
1095
  if (this.check(TT.COLON)) {
875
1096
  this.consume(TT.COLON);
876
- // For event attributes, try parsing the rest as an expression
877
- if (this.isEventAttribute(aname)) {
878
- // If the value is a quoted string, use it directly as handler code
1097
+ if (this.isEventAttr(aname)) {
879
1098
  if (this.check(TT.STRING)) {
880
1099
  value = this.parseLiteral();
881
1100
  } else {
882
- const startTokens = this.pos;
883
- let expr = this.parseExpression();
884
- if (expr && !this.check(TT.COMMA) && !this.check(TT.RPAREN) && !this.check(TT.EOF)) {
885
- // If there are more tokens, it's probably not a simple expression
886
- this.pos = startTokens;
887
- expr = null;
888
- }
889
- if (expr) {
1101
+ const savedPos = this.pos;
1102
+ const expr = this.parseExpression();
1103
+ if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
890
1104
  value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
891
1105
  } else {
892
- this.pos = startTokens;
893
- value = this.parseLiteral();
1106
+ this.pos = savedPos;
1107
+ value = this.parseLiteral();
894
1108
  }
895
1109
  }
896
1110
  } else {
897
- // Try literal first, then variable reference
898
- if (this.check(TT.STRING) || this.check(TT.NUMBER) ||
899
- this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
900
- this.check(TT.NULL_LIT) || this.check(TT.LBRACKET)) {
1111
+ if (this.check(TT.STRING) || this.check(TT.NUMBER) ||
1112
+ this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
1113
+ this.check(TT.NULL_LIT) || this.check(TT.LBRACKET) || this.check(TT.LBRACE)) {
901
1114
  value = this.parseLiteral();
902
1115
  } else if (this.check(TT.IDENT)) {
903
- const varName = this.consume(TT.IDENT).value;
904
- value = { kind: "str", value: varName };
1116
+ // Try to parse as expression (handles user.age, user.age * 20, etc.)
1117
+ const savedPos = this.pos;
1118
+ const expr = this.parseExpression();
1119
+ if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
1120
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
1121
+ } else {
1122
+ // Not a full expression, treat as simple variable reference
1123
+ this.pos = savedPos;
1124
+ value = { kind: "str", value: this.consume(TT.IDENT).value };
1125
+ }
905
1126
  } else {
906
1127
  value = this.parseLiteral();
907
1128
  }
908
1129
  }
909
1130
  }
910
1131
  attrs.push({ name: aname, value, loc: aloc });
911
-
912
1132
  if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
913
1133
  }
914
1134
  this.consume(TT.RPAREN);
@@ -918,7 +1138,9 @@ private parseCompUse(): CompUse {
918
1138
  if (this.check(TT.RAW_BLOCK)) {
919
1139
  const rawTok = this.consume(TT.RAW_BLOCK);
920
1140
  const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
921
- children.push(...new Parser(tokens, rawTok.loc.file).parseChildList());
1141
+ const sub = new Parser(tokens, rawTok.loc.file);
1142
+ sub._varDecls = this._varDecls;
1143
+ children.push(...sub.parseChildList());
922
1144
  } else if (this.check(TT.LBRACE)) {
923
1145
  this.consume(TT.LBRACE);
924
1146
  children.push(...this.parseChildList());
@@ -928,425 +1150,203 @@ private parseCompUse(): CompUse {
928
1150
  return { kind: "use", name, attrs, children, loc };
929
1151
  }
930
1152
 
931
- private parseIfBlock(): IfBlock {
932
- const loc = this.consume(TT.KW_IF).loc;
933
- const condition = this.parseExpression();
934
- if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
935
-
936
- let body: Child[];
937
- if (this.check(TT.LBRACE)) {
938
- this.consume(TT.LBRACE);
939
- body = this.parseChildList();
940
- this.consume(TT.RBRACE);
941
- } else {
942
- body = [];
943
- }
944
-
945
- let elseBody: Child[] | undefined;
946
- if (this.check(TT.KW_ELSE)) {
947
- this.consume(TT.KW_ELSE);
948
- if (this.check(TT.LBRACE)) {
949
- this.consume(TT.LBRACE);
950
- elseBody = this.parseChildList();
951
- this.consume(TT.RBRACE);
952
- }
953
- }
954
-
955
- return { kind: "if", condition, body, elseBody, loc };
1153
+ private isEventAttr(name: string): boolean {
1154
+ return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
956
1155
  }
957
1156
 
958
- private parseLogicBody(condition: Expression): string {
959
- let js = "if (" + compileExprToJS(condition) + ") {\n";
960
- while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
961
- if (this.check(TT.IDENT)) {
962
- const name = this.consume(TT.IDENT).value;
963
-
964
- // Assignment: name = value
965
- if (this.check(TT.EQUALS)) {
966
- this.consume(TT.EQUALS);
967
- const expr = this.parseExpression();
968
- if (expr) {
969
- // Type check: look up the variable's declared type
970
- const varDecl = (this as any)._varDecls?.find((v: any) => v.name === name);
971
- if (varDecl) {
972
- const exprJS = compileExprToJS(expr);
973
- // Check type compatibility
974
- const valueKind = expr.kind;
975
- const valueLiteralKind = expr.kind === "literal" ? expr.value?.kind : null;
976
-
977
- if (varDecl.varType === "int" && valueLiteralKind === "str") {
978
- SinthWarning.emit(`Type mismatch: '${name}' is declared as int but assigned a string value`);
979
- } else if (varDecl.varType === "str" && valueLiteralKind === "num") {
980
- SinthWarning.emit(`Type mismatch: '${name}' is declared as str but assigned a number value`);
981
- } else if (varDecl.varType === "bool" && valueLiteralKind !== "bool" && valueLiteralKind !== null) {
982
- SinthWarning.emit(`Type mismatch: '${name}' is declared as bool but assigned a non-boolean value`);
983
- }
984
- }
985
- js += " " + compileExprToJS({ kind: "assign", target: name, op: "=", right: expr }) + ";\n";
986
- }
987
- }
988
- // Addition assignment: name += value
989
- else if (this.check(TT.OP_PLUS) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
1157
+ private parseChildList(): Child[] {
1158
+ const children: Child[] = [];
1159
+ while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1160
+ if (this.check(TT.STRING)) {
1161
+ const loc = this.peek().loc;
1162
+ let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1163
+ while (this.check(TT.OP_PLUS)) {
990
1164
  this.consume(TT.OP_PLUS);
991
- this.consume(TT.EQUALS);
992
- const expr = this.parseExpression();
993
- if (expr) {
994
- js += " " + compileExprToJS({ kind: "assign", target: name, op: "+=", right: expr }) + ";\n";
995
- }
996
- }
997
- // Subtraction assignment: name -= value
998
- else if (this.check(TT.OP_MINUS) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
999
- this.consume(TT.OP_MINUS);
1000
- this.consume(TT.EQUALS);
1001
- const expr = this.parseExpression();
1002
- if (expr) {
1003
- js += " " + compileExprToJS({ kind: "assign", target: name, op: "-=", right: expr }) + ";\n";
1004
- }
1005
- }
1006
- // Function call: name()
1007
- else if (this.check(TT.LPAREN)) {
1008
- this.consume(TT.LPAREN);
1009
- let args = "";
1010
- while (!this.check(TT.RPAREN) && !this.check(TT.EOF)) {
1011
- const arg = this.parseExpression();
1012
- if (arg) {
1013
- args += (args ? ", " : "") + compileExprToJS(arg);
1165
+ let rhs: Expression | null = null;
1166
+ if (this.check(TT.STRING)) {
1167
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1168
+ } else if (this.check(TT.IDENT)) {
1169
+ const rhsName = this.consume(TT.IDENT).value;
1170
+ if (this.check(TT.DOT)) {
1171
+ this.consume(TT.DOT);
1172
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1173
+ } else {
1174
+ rhs = { kind: "variable", name: rhsName };
1014
1175
  }
1015
- if (this.check(TT.COMMA)) this.consume(TT.COMMA);
1176
+ } else {
1177
+ rhs = this.parseExpression();
1016
1178
  }
1017
- this.consume(TT.RPAREN);
1018
- js += " " + name + "(" + args + ");\n";
1019
- }
1020
- }
1021
- // Nested if
1022
- else if (this.check(TT.KW_IF)) {
1023
- this.consume(TT.KW_IF);
1024
- const innerCond = this.parseExpression();
1025
- if (innerCond && this.check(TT.LBRACE)) {
1026
- this.consume(TT.LBRACE);
1027
- js += " " + this.parseLogicBody(innerCond);
1179
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1180
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1028
1181
  }
1182
+ children.push({ kind: "expr", expression: leftExpr, loc });
1029
1183
  }
1030
- // var declaration (skip in logic body)
1031
1184
  else if (this.check(TT.IDENT) && this.peek().value === "var") {
1032
- this.consume(TT.IDENT); // var
1033
- this.consume(TT.IDENT); // type
1034
- this.consume(TT.IDENT); // name
1035
- if (this.check(TT.EQUALS)) {
1036
- this.consume(TT.EQUALS);
1037
- this.parseExpression();
1038
- }
1039
- }
1040
- else {
1041
- break;
1185
+ const vd = this.parseVarDeclaration();
1186
+ if (vd) this._varDecls.push(vd);
1187
+ continue;
1042
1188
  }
1043
- }
1044
- this.consume(TT.RBRACE);
1045
- js += "}\n";
1046
-
1047
- // Check for else
1048
- if (this.check(TT.KW_ELSE)) {
1049
- this.consume(TT.KW_ELSE);
1050
- if (this.check(TT.LBRACE)) {
1051
- this.consume(TT.LBRACE);
1052
- js += "else {\n";
1053
- while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
1054
- if (this.check(TT.IDENT)) {
1055
- const name = this.consume(TT.IDENT).value;
1056
- if (this.check(TT.EQUALS)) {
1057
- this.consume(TT.EQUALS);
1058
- const expr = this.parseExpression();
1059
- if (expr) {
1060
- js += " " + compileExprToJS({ kind: "assign", target: name, op: "=", right: expr }) + ";\n";
1061
- }
1062
- } else if (this.check(TT.OP_PLUS) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
1189
+ else if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); }
1190
+ else if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); }
1191
+ else if (this.check(TT.IDENT)) {
1192
+ const loc = this.peek().loc;
1193
+ const rawName = this.peek().value;
1194
+ const nextType = this.tokens[this.pos + 1]?.type;
1195
+
1196
+ // Handle dot notation: user.age
1197
+ if (nextType === TT.DOT) {
1198
+ let fullName = this.consume(TT.IDENT).value;
1199
+ this.consume(TT.DOT);
1200
+ fullName = fullName + "." + this.consume(TT.IDENT).value;
1201
+ const afterDotType = this.tokens[this.pos]?.type;
1202
+
1203
+ if (afterDotType === TT.OP_PLUS) {
1204
+ // user.name + "string" + user.age
1205
+ let leftExpr: Expression = { kind: "variable", name: fullName };
1206
+ while (this.check(TT.OP_PLUS)) {
1063
1207
  this.consume(TT.OP_PLUS);
1064
- this.consume(TT.EQUALS);
1065
- const expr = this.parseExpression();
1066
- if (expr) {
1067
- js += " " + compileExprToJS({ kind: "assign", target: name, op: "+=", right: expr }) + ";\n";
1068
- }
1069
- } else if (this.check(TT.OP_MINUS) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
1070
- this.consume(TT.OP_MINUS);
1071
- this.consume(TT.EQUALS);
1072
- const expr = this.parseExpression();
1073
- if (expr) {
1074
- js += " " + compileExprToJS({ kind: "assign", target: name, op: "-=", right: expr }) + ";\n";
1208
+ let rhs: Expression | null = null;
1209
+ if (this.check(TT.STRING)) {
1210
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1211
+ } else if (this.check(TT.IDENT)) {
1212
+ const rhsName = this.consume(TT.IDENT).value;
1213
+ if (this.check(TT.DOT)) {
1214
+ this.consume(TT.DOT);
1215
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1216
+ } else {
1217
+ rhs = { kind: "variable", name: rhsName };
1218
+ }
1219
+ } else {
1220
+ rhs = this.parseExpression();
1075
1221
  }
1222
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1223
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1076
1224
  }
1225
+ children.push({ kind: "expr", expression: leftExpr, loc });
1226
+ } else if (this.loopVar && fullName.split('.')[0] === this.loopVar) {
1227
+ children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1228
+ } else if (afterDotType === TT.LPAREN || afterDotType === TT.LBRACE || afterDotType === TT.RAW_BLOCK) {
1229
+ throw new SinthError(`Unexpected dot notation before component usage`, loc);
1077
1230
  } else {
1078
- break;
1079
- }
1080
- }
1081
- this.consume(TT.RBRACE);
1082
- js += "}\n";
1083
- }
1084
- }
1085
-
1086
- return js;
1087
- }
1088
-
1089
- private parseForLoop(): ForLoop {
1090
- const loc = this.consume(TT.KW_FOR).loc;
1091
- const itemVar = this.consume(TT.IDENT).value;
1092
- if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
1093
- this.consume(TT.KW_IN);
1094
- const arrayVar = this.consume(TT.IDENT).value;
1095
-
1096
- let body: Child[];
1097
- if (this.check(TT.LBRACE)) {
1098
- this.consume(TT.LBRACE);
1099
- this.loopVar = itemVar;
1100
- body = this.parseChildList();
1101
- this.loopVar = null;
1102
- this.consume(TT.RBRACE);
1103
- } else {
1104
- body = [];
1105
- }
1106
-
1107
- return { kind: "for", itemVar, arrayVar, body, loc };
1108
- }
1109
-
1110
- private isEventAttribute(name: string): boolean {
1111
- return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
1112
- }
1113
-
1114
- private parseChildList(): Child[] {
1115
- const children: Child[] = [];
1116
- while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1117
- if (this.check(TT.STRING)) {
1118
- const loc = this.peek().loc;
1119
- let leftExpr: Expression = {
1120
- kind: "literal",
1121
- value: { kind: "str", value: this.consume(TT.STRING).value }
1122
- };
1123
- // Keep chaining while there's a + operator
1124
- while (this.check(TT.OP_PLUS)) {
1125
- this.consume(TT.OP_PLUS);
1126
- let rightExpr: Expression | null = null;
1127
- if (this.check(TT.STRING)) {
1128
- rightExpr = {
1129
- kind: "literal",
1130
- value: { kind: "str", value: this.consume(TT.STRING).value }
1131
- };
1132
- } else if (this.check(TT.IDENT)) {
1133
- const varName = this.consume(TT.IDENT).value;
1134
- rightExpr = { kind: "variable", name: varName };
1135
- } else {
1136
- rightExpr = this.parseExpression();
1137
- }
1138
- if (!rightExpr) throw new SinthError("Expected expression after +", this.peek().loc);
1139
- leftExpr = {
1140
- kind: "binary",
1141
- left: leftExpr,
1142
- op: "+",
1143
- right: rightExpr,
1144
- };
1145
- }
1146
- children.push({ kind: "expr", expression: leftExpr, loc });
1147
- } else if (this.check(TT.KW_IF)) {
1148
- const ifStart = this.pos;
1149
- this.consume(TT.KW_IF);
1150
- const condition = this.parseExpression();
1151
- if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
1152
-
1153
- if (!this.check(TT.LBRACE)) {
1154
- throw new SinthError("Expected '{' after if condition", this.peek().loc);
1155
- }
1156
-
1157
- this.consume(TT.LBRACE);
1158
-
1159
-
1160
- // Determine if this is inline logic or DOM rendering
1161
- let isInlineLogic = false;
1162
-
1163
- // Check first token inside the body
1164
- if (this.check(TT.IDENT)) {
1165
- const identName = this.peek().value;
1166
- const nextType = this.tokens[this.pos + 1]?.type;
1167
-
1168
-
1169
-
1170
- // Assignment operators: =, +=, -=
1171
- if (nextType === TT.EQUALS) {
1172
- isInlineLogic = true;
1173
- } else if (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) {
1174
- isInlineLogic = true;
1175
- } else if (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) {
1176
- isInlineLogic = true;
1177
- }
1178
- // Not a built-in component or keyword
1179
- else if (identName === "if" || identName === "for" || identName === "var" ||
1180
- BUILTIN_MAP[identName]) {
1181
- isInlineLogic = false;
1182
- }
1183
- // If next token is not (, it might still be logic (like standalone variable for sinthRender)
1184
- // But if it's a component usage (IDENT followed by LPAREN or LBRACE), it's DOM
1185
- else if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1186
- isInlineLogic = false;
1187
- }
1188
- }
1189
- // Also check for nested if (could be inline or DOM)
1190
- else if (this.check(TT.KW_IF)) {
1191
- // Peek ahead to see if nested if contains assignment
1192
- const nestedStart = this.pos;
1193
- this.consume(TT.KW_IF);
1194
- const nestedCond = this.parseExpression();
1195
- if (nestedCond && this.check(TT.LBRACE)) {
1196
- this.consume(TT.LBRACE);
1197
- if (this.check(TT.IDENT) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
1198
- isInlineLogic = true;
1199
- }
1200
- }
1201
- // Reset position
1202
- while (this.pos > nestedStart) {
1203
- this.pos--;
1231
+ children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1204
1232
  }
1205
- this.pos = nestedStart;
1206
- }
1207
- // Keywords that indicate DOM rendering
1208
- else if (this.check(TT.KW_STYLE) || this.check(TT.KW_SCRIPT) ||
1209
- this.check(TT.STRING) || this.check(TT.KW_FOR)) {
1210
- isInlineLogic = false;
1211
- }
1212
-
1213
- if (isInlineLogic) {
1214
- // Parse as inline logic
1215
- const jsCode = this.parseLogicBody(condition);
1216
- const scriptBlock: ScriptBlock = {
1217
- raw: jsCode,
1218
- attrs: {},
1219
- loc: this.peek().loc
1220
- };
1221
- children.push({ kind: "text", value: "", loc: this.peek().loc });
1222
- (this as any)._logicScripts = (this as any)._logicScripts || [];
1223
- (this as any)._logicScripts.push(scriptBlock);
1224
- } else {
1225
- // Parse as DOM if — reset and use existing parser
1226
- this.pos = ifStart;
1227
- children.push(this.parseIfBlock());
1228
- }
1229
-
1230
- } else if (this.check(TT.KW_FOR)) {
1231
- children.push(this.parseForLoop());
1232
- } else if (this.check(TT.IDENT)) {
1233
- // Check if next token is + (variable + something)
1234
- if (this.tokens[this.pos + 1]?.type === TT.OP_PLUS) {
1235
- const loc = this.peek().loc;
1236
- const varName = this.consume(TT.IDENT).value;
1237
- this.consume(TT.OP_PLUS); // consume +
1238
- // Check if what follows is a string
1239
- if (this.check(TT.STRING)) {
1240
- const rightStr = this.consume(TT.STRING).value;
1241
- children.push({ kind: "expr", expression: {
1242
- kind: "binary",
1243
- left: { kind: "variable", name: varName },
1244
- op: "+",
1245
- right: { kind: "literal", value: { kind: "str", value: rightStr } },
1246
- }, loc });
1247
- } else {
1248
- // variable + expression
1249
- const rightExpr = this.parseExpression();
1250
- if (rightExpr) {
1251
- children.push({ kind: "expr", expression: {
1252
- kind: "binary",
1253
- left: { kind: "variable", name: varName },
1254
- op: "+",
1255
- right: rightExpr,
1256
- }, loc });
1233
+ } else if (nextType === TT.OP_PLUS) {
1234
+ const name = this.consume(TT.IDENT).value;
1235
+ let leftExpr: Expression = { kind: "variable", name };
1236
+ while (this.check(TT.OP_PLUS)) {
1237
+ this.consume(TT.OP_PLUS);
1238
+ let rhs: Expression | null = null;
1239
+ if (this.check(TT.STRING)) {
1240
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1241
+ } else if (this.check(TT.IDENT)) {
1242
+ const rhsName = this.consume(TT.IDENT).value;
1243
+ if (this.check(TT.DOT)) {
1244
+ this.consume(TT.DOT);
1245
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1246
+ } else {
1247
+ rhs = { kind: "variable", name: rhsName };
1248
+ }
1249
+ } else {
1250
+ rhs = this.parseExpression();
1257
1251
  }
1252
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1253
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1258
1254
  }
1259
- } else if (this.loopVar && this.peek().value === this.loopVar) {
1260
- const loc = this.peek().loc;
1261
- const name = this.consume(TT.IDENT).value;
1262
- children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1263
- } else if (this.tokens[this.pos + 1]?.type === TT.LPAREN ||
1264
- this.tokens[this.pos + 1]?.type === TT.LBRACE ||
1265
- this.tokens[this.pos + 1]?.type === TT.RAW_BLOCK) {
1255
+ children.push({ kind: "expr", expression: leftExpr, loc });
1256
+ } else if (this.loopVar && rawName === this.loopVar) {
1257
+ this.consume(TT.IDENT);
1258
+ children.push({ kind: "expr", expression: { kind: "variable", name: rawName }, loc });
1259
+ } else if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1266
1260
  children.push(this.parseCompUse());
1267
1261
  } else {
1268
- const loc = this.peek().loc;
1269
1262
  const name = this.consume(TT.IDENT).value;
1270
1263
  children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1271
1264
  }
1272
- } else {
1273
- throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1274
1265
  }
1266
+ else throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1275
1267
  }
1276
1268
  return children;
1277
1269
  }
1278
1270
 
1279
- // ── Style blocks ──────────────────────────────────────────
1271
+ // ── Style / Script blocks ────────────────────────────────────────────────
1280
1272
 
1281
1273
  private parseStyleBlock(): StyleBlock {
1282
1274
  const loc = this.consume(TT.KW_STYLE).loc;
1283
- let global = false, lang: "css" | "scss" = "css";
1275
+ let global = false, lang: "css" | "scss" = "css", target: string | undefined;
1284
1276
  const extraAttrs: Record<string, string> = {};
1285
1277
 
1286
1278
  while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1287
- if (this.check(TT.KW_GLOBAL)) { global = true; this.consume(TT.KW_GLOBAL); }
1288
- else if (this.check(TT.KW_LANG)) {
1279
+ if (this.check(TT.KW_GLOBAL)) { global = true; this.consume(TT.KW_GLOBAL); }
1280
+ else if (this.check(TT.KW_LANG)) {
1289
1281
  this.consume(TT.KW_LANG); this.consume(TT.EQUALS);
1290
1282
  const lv = this.consume(TT.STRING).value;
1291
1283
  if (lv !== "css" && lv !== "scss") throw new SinthError(`Unsupported style lang '${lv}'`, loc);
1292
1284
  lang = lv as "css" | "scss";
1293
1285
  }
1294
1286
  else if (this.check(TT.IDENT)) {
1295
- const k = this.consume(TT.IDENT).value;
1296
- this.consume(TT.EQUALS);
1297
- extraAttrs[k] = this.consume(TT.STRING).value;
1287
+ // v1.0.0: If IDENT is NOT followed by EQUALS, it's a component target name.
1288
+ if (this.tokens[this.pos + 1]?.type !== TT.EQUALS) {
1289
+ target = this.consume(TT.IDENT).value;
1290
+ } else {
1291
+ const k = this.consume(TT.IDENT).value;
1292
+ this.consume(TT.EQUALS);
1293
+ extraAttrs[k] = this.consume(TT.STRING).value;
1294
+ }
1298
1295
  }
1299
1296
  else throw new SinthError(`Unexpected token '${this.peek().value}' in style modifiers`, this.peek().loc);
1300
1297
  }
1301
1298
 
1302
- return { global, lang, raw: this.consume(TT.RAW_BLOCK).value, extraAttrs, loc };
1299
+ return { global, lang, raw: this.consume(TT.RAW_BLOCK).value, target, extraAttrs, loc };
1303
1300
  }
1304
1301
 
1305
- // ── Script blocks ─────────────────────────────────────────
1306
-
1307
1302
  private parseScriptBlock(): ScriptBlock {
1308
1303
  const loc = this.consume(TT.KW_SCRIPT).loc;
1309
1304
  const attrs: Record<string, string> = {};
1310
-
1311
1305
  while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1312
1306
  const key = this.consume(TT.IDENT).value;
1313
1307
  if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); attrs[key] = this.consume(TT.STRING).value; }
1314
1308
  else { attrs[key] = "true"; }
1315
1309
  }
1316
-
1317
1310
  return { raw: this.consume(TT.RAW_BLOCK).value, attrs, loc };
1318
1311
  }
1319
1312
 
1320
- // ── Literals ──────────────────────────────────────────────
1313
+ // ── Literals ─────────────────────────────────────────────────────────────
1321
1314
 
1322
- private parseLiteral(): Literal {
1315
+ private parseLiteral(): Literal {
1323
1316
  const tok = this.peek();
1324
- if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
1317
+ if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
1318
+ if (this.check(TT.LBRACE)) {
1319
+ const obj = this.parseObjectLiteral();
1320
+ return { kind: "str", value: JSON.stringify(obj) };
1321
+ }
1325
1322
  if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
1326
1323
  if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
1327
1324
  if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
1328
1325
  if (this.check(TT.BOOL_FALSE)){ this.consume(TT.BOOL_FALSE);return { kind: "bool", value: false }; }
1329
1326
  if (this.check(TT.NULL_LIT)) { this.consume(TT.NULL_LIT); return { kind: "null" }; }
1330
- throw new SinthError(`Expected literal value, got '${tok.value}'`, tok.loc);
1327
+ throw new SinthError(`Expected literal value, got '${tok.value}' (${TT[tok.type]})`, tok.loc);
1331
1328
  }
1332
1329
 
1333
- // ── Token helpers ─────────────────────────────────────────
1330
+ // ── Token helpers ─────────────────────────────────────────────────────────
1334
1331
 
1335
1332
  private peek(): Token { return this.tokens[this.pos]; }
1336
1333
  private check(t: TT): boolean { return this.tokens[this.pos]?.type === t; }
1337
1334
  private consume(t: TT): Token {
1338
1335
  const tok = this.tokens[this.pos];
1339
1336
  if (tok.type !== t) {
1340
- throw new SinthError(`Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`, tok.loc);
1337
+ throw new SinthError(
1338
+ `Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`,
1339
+ tok.loc,
1340
+ );
1341
1341
  }
1342
1342
  this.pos++;
1343
1343
  return tok;
1344
1344
  }
1345
1345
  }
1346
1346
 
1347
- // ═══════════════════════════════════════════════════════════
1348
- // SECTION 5: IMPORT RESOLVER
1349
- // ═══════════════════════════════════════════════════════════
1347
+ // ═══════════════════════════════════════════════════════════════════════════
1348
+ // §5 IMPORT RESOLVER
1349
+ // ═══════════════════════════════════════════════════════════════════════════
1350
1350
 
1351
1351
  interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
1352
1352
 
@@ -1357,13 +1357,11 @@ interface ResolvedImports {
1357
1357
  jsLinks: { src: string; attrs: Record<string, string> }[];
1358
1358
  }
1359
1359
 
1360
- // Module-level import stack for circular detection
1361
1360
  const IMPORT_STACK: string[] = [];
1362
1361
 
1363
- // === v0.1.0: parseFile catches errors and attaches source line preview ===
1364
1362
  function parseFile(filePath: string): SinthFile {
1365
1363
  if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
1366
- const src = fs.readFileSync(filePath, "utf-8");
1364
+ const src = fs.readFileSync(filePath, "utf-8");
1367
1365
  const srcLines = src.split("\n");
1368
1366
  try {
1369
1367
  const tokens = new Lexer(src, filePath).tokenize();
@@ -1384,24 +1382,21 @@ function resolveImports(
1384
1382
  const cssLinks: string[] = [];
1385
1383
  const jsLinks: { src: string; attrs: Record<string, string> }[] = [];
1386
1384
 
1387
- // Register this file's own component definitions
1388
1385
  for (const def of file.defs) {
1389
1386
  if (BUILTIN_MAP[def.name]) {
1390
- throw new SinthError(`'${def.name}' is a built-in SinthUI component and cannot be redefined.`, def.loc);
1387
+ throw new SinthError(`'${def.name}' is a built-in Sinth component and cannot be redefined.`, def.loc);
1391
1388
  }
1392
1389
  if (allDefs.has(def.name)) throw new SinthError(`Duplicate component definition '${def.name}'`, def.loc);
1393
1390
  allDefs.set(def.name, def);
1394
1391
  }
1395
1392
 
1396
- // Register custom element declarations
1397
1393
  for (const el of file.customEls) {
1398
1394
  customEls.set(el.sinthName, { tagName: el.tagName, params: el.params });
1399
1395
  }
1400
1396
 
1401
- // Warn about metadata in component files
1402
1397
  if (!file.isPage && file.meta.length > 0) {
1403
1398
  for (const m of file.meta) {
1404
- SinthWarning.emit(`Metadata key '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
1399
+ SinthWarning.emit(`Metadata '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
1405
1400
  }
1406
1401
  }
1407
1402
 
@@ -1414,7 +1409,6 @@ function resolveImports(
1414
1409
  const src = resolveLibrary(imp.name, cfg);
1415
1410
  jsLinks.push({ src, attrs: {} });
1416
1411
 
1417
- // === v0.1.0: Auto-import companion .sinth for JS libraries (e.g. sinthui.sinth) ===
1418
1412
  for (const libDir of cfg.libraryPaths) {
1419
1413
  const companion = path.join(libDir, imp.name + ".sinth");
1420
1414
  if (fs.existsSync(companion) && !visited.has(companion)) {
@@ -1432,7 +1426,7 @@ function resolveImports(
1432
1426
 
1433
1427
  if (IMPORT_STACK.includes(resolved)) {
1434
1428
  throw new SinthError(
1435
- `Circular import detected.\n Chain: ${[...IMPORT_STACK, resolved].join(" → ")}`
1429
+ `Circular import: ${[...IMPORT_STACK, resolved].join(" → ")}`
1436
1430
  );
1437
1431
  }
1438
1432
  if (visited.has(resolved)) continue;
@@ -1444,14 +1438,12 @@ function resolveImports(
1444
1438
 
1445
1439
  const sub = resolveImports(imported, cfg, visited);
1446
1440
  for (const [name, def] of sub.allDefs) {
1447
- if (allDefs.has(name)) {
1448
- throw new SinthError(`Component '${name}' defined in multiple imported files.`);
1449
- }
1441
+ if (allDefs.has(name)) throw new SinthError(`Component '${name}' defined in multiple imported files.`);
1450
1442
  allDefs.set(name, def);
1451
1443
  }
1452
1444
  for (const [n, e] of sub.customEls) customEls.set(n, e);
1453
- for (const l of sub.cssLinks) if (!cssLinks.includes(l)) cssLinks.push(l);
1454
- for (const j of sub.jsLinks) jsLinks.push(j);
1445
+ for (const l of sub.cssLinks) if (!cssLinks.includes(l)) cssLinks.push(l);
1446
+ for (const j of sub.jsLinks) jsLinks.push(j);
1455
1447
  }
1456
1448
  }
1457
1449
 
@@ -1472,25 +1464,20 @@ function resolveLibrary(name: string, cfg: ResolverConfig): string {
1472
1464
  return `/libraries/${base}`;
1473
1465
  }
1474
1466
 
1475
- // === v0.1.0: resolveSinthPath — first try relative to importing file, then library paths ===
1476
1467
  function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
1477
- // Explicit relative path
1478
1468
  if (p.startsWith("./") || p.startsWith("../")) {
1479
- const r = path.resolve(path.dirname(fromFile), p);
1469
+ const r = path.resolve(path.dirname(fromFile), p);
1480
1470
  if (fs.existsSync(r)) return r;
1481
1471
  const w = r.endsWith(".sinth") ? "" : r + ".sinth";
1482
1472
  if (w && fs.existsSync(w)) return w;
1483
1473
  throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
1484
1474
  }
1485
1475
 
1486
- // === v0.1.0: Non-relative paths (e.g. "components/Card.sinth"): try relative to importing
1487
- // file's directory FIRST, then fall back to library paths ===
1488
- const relToFile = path.resolve(path.dirname(fromFile), p);
1476
+ const relToFile = path.resolve(path.dirname(fromFile), p);
1489
1477
  if (fs.existsSync(relToFile)) return relToFile;
1490
1478
  const relToFileExt = relToFile.endsWith(".sinth") ? relToFile : relToFile + ".sinth";
1491
1479
  if (fs.existsSync(relToFileExt)) return relToFileExt;
1492
1480
 
1493
- // Library path fallback
1494
1481
  for (const libDir of cfg.libraryPaths) {
1495
1482
  const c1 = path.join(libDir, p);
1496
1483
  if (fs.existsSync(c1)) return c1;
@@ -1499,19 +1486,18 @@ function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): str
1499
1486
  }
1500
1487
 
1501
1488
  throw new SinthError(
1502
- `Cannot resolve import '${p}'\n Tried relative: ${relToFileExt}\n Tried library paths: ${cfg.libraryPaths.join(", ")}`
1489
+ `Cannot resolve import '${p}'\n Tried: ${relToFileExt}\n Library paths: ${cfg.libraryPaths.join(", ")}`
1503
1490
  );
1504
1491
  }
1505
1492
 
1506
- // ═══════════════════════════════════════════════════════════
1507
- // SECTION 6: BUILT-IN COMPONENT MAP
1508
- // ═══════════════════════════════════════════════════════════
1493
+ // ═══════════════════════════════════════════════════════════════════════════
1494
+ // §6 BUILT-IN COMPONENT MAP
1495
+ // ═══════════════════════════════════════════════════════════════════════════
1509
1496
 
1510
1497
  interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
1511
1498
 
1512
- // === v0.1.0: Complete HTML5 map; Col = void <col>; Column = grid div; added SubHeading, CardGrid ===
1513
1499
  const BUILTIN_MAP: Record<string, BuiltinInfo> = {
1514
- // ── Structural ──────────────────────────────────────────
1500
+ // Structural
1515
1501
  Main: { tag: "main" },
1516
1502
  Header: { tag: "header" },
1517
1503
  Footer: { tag: "footer" },
@@ -1527,14 +1513,13 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
1527
1513
  Flex: { tag: "div", defaultClass: "flex" },
1528
1514
  Stack: { tag: "div", defaultClass: "stack" },
1529
1515
  Row: { tag: "div", defaultClass: "row" },
1530
- // === v0.1.0: Column = grid helper div; Col = HTML void table col ===
1531
1516
  Column: { tag: "div", defaultClass: "col" },
1532
- // ── Typography ────────────────────────────────────────────
1533
- Heading: { tag: "h1" }, // resolved dynamically by level attr
1517
+ CardGrid: { tag: "div", defaultClass: "card-grid" },
1518
+ // Typography
1519
+ Heading: { tag: "h1" },
1520
+ SubHeading: { tag: "p", defaultClass: "subheading" },
1534
1521
  Paragraph: { tag: "p" },
1535
- // === v0.1.0: SubHeading convenience component ===
1536
- SubHeading: { tag: "p", defaultClass: "subheading" },
1537
- Lead: { tag: "p", defaultClass: "lead" },
1522
+ Lead: { tag: "p", defaultClass: "lead" },
1538
1523
  Small: { tag: "small" },
1539
1524
  Strong: { tag: "strong" },
1540
1525
  Em: { tag: "em" },
@@ -1561,7 +1546,7 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
1561
1546
  Ruby: { tag: "ruby" },
1562
1547
  Rt: { tag: "rt" },
1563
1548
  Rp: { tag: "rp" },
1564
- // ── Interactive ────────────────────────────────────────────
1549
+ // Interactive
1565
1550
  Button: { tag: "button" },
1566
1551
  Link: { tag: "a" },
1567
1552
  NavLink: { tag: "a" },
@@ -1580,7 +1565,7 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
1580
1565
  Meter: { tag: "meter" },
1581
1566
  Output: { tag: "output" },
1582
1567
  Map: { tag: "map" },
1583
- // ── Media ──────────────────────────────────────────────────
1568
+ // Media
1584
1569
  Picture: { tag: "picture" },
1585
1570
  Video: { tag: "video" },
1586
1571
  Audio: { tag: "audio" },
@@ -1590,22 +1575,21 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
1590
1575
  Svg: { tag: "svg" },
1591
1576
  IFrame: { tag: "iframe" },
1592
1577
  Object: { tag: "object" },
1593
- // ── Void elements ──────────────────────────────────────────
1578
+ // Void elements
1594
1579
  Img: { tag: "img", voidEl: true },
1595
1580
  Logo: { tag: "img", voidEl: true },
1596
1581
  Input: { tag: "input", voidEl: true },
1597
1582
  Hr: { tag: "hr", voidEl: true },
1598
1583
  Br: { tag: "br", voidEl: true },
1599
- Wbr: { tag: "wbr", voidEl: true },
1584
+ Wbr: { tag: "wbr", voidEl: true },
1600
1585
  Source: { tag: "source", voidEl: true },
1601
1586
  Embed: { tag: "embed", voidEl: true },
1602
- // === v0.1.0: Col = HTML void table column (NOT the grid div) ===
1603
1587
  Col: { tag: "col", voidEl: true },
1604
1588
  Area: { tag: "area", voidEl: true },
1605
- // ── Lists ─────────────────────────────────────────────────
1606
- Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
1607
- Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
1608
- // ── Tables ─────────────────────────────────────────────────
1589
+ // Lists
1590
+ Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
1591
+ Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
1592
+ // Tables
1609
1593
  Table: { tag: "table" },
1610
1594
  Caption: { tag: "caption" },
1611
1595
  Thead: { tag: "thead" },
@@ -1615,86 +1599,212 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
1615
1599
  Th: { tag: "th" },
1616
1600
  Td: { tag: "td" },
1617
1601
  Colgroup: { tag: "colgroup" },
1618
- // ── Utility ────────────────────────────────────────────────
1602
+ // Utility
1619
1603
  Template: { tag: "template" },
1620
1604
  Slot: { tag: "slot" },
1621
1605
  NoScript: { tag: "noscript" },
1622
- // === v0.1.0: CardGrid convenience layout wrapper ===
1623
- CardGrid: { tag: "div", defaultClass: "card-grid" },
1624
- // === v0.1.0: RawHTML marker — handled specially in renderCompUse ===
1625
1606
  RawHTML: { tag: "__RAW__" },
1626
1607
  };
1627
1608
 
1628
- // All HTML void elements (never receive closing tags)
1629
- const VOID_TAGS = new Set([
1630
- "area", "base", "br", "col", "embed", "hr", "img", "input",
1631
- "link", "meta", "param", "source", "track", "wbr",
1632
- ]);
1609
+ const VOID_TAGS = new Set([
1610
+ "area","base","br","col","embed","hr","img","input",
1611
+ "link","meta","param","source","track","wbr",
1612
+ ]);
1613
+
1614
+ const EVENT_RE = /^on[A-Z]/;
1615
+ function eventAttrName(name: string): string | null {
1616
+ return EVENT_RE.test(name) ? name.toLowerCase() : null;
1617
+ }
1618
+
1619
+ // ═══════════════════════════════════════════════════════════════════════════
1620
+ // §7 SINTH STYLE LANGUAGE — PREPROCESSOR
1621
+ // ═══════════════════════════════════════════════════════════════════════════
1622
+
1623
+ /**
1624
+ * Maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
1625
+ * These are used inside component style blocks: onHover { color: "blue" }
1626
+ */
1627
+ const SINTH_PSEUDO_CLASS: Record<string, string> = {
1628
+ onHover: ":hover",
1629
+ onFocus: ":focus",
1630
+ onActive: ":active",
1631
+ onVisited: ":visited",
1632
+ onChecked: ":checked",
1633
+ onDisabled: ":disabled",
1634
+ onEnabled: ":enabled",
1635
+ onRequired: ":required",
1636
+ onOptional: ":optional",
1637
+ onValid: ":valid",
1638
+ onInvalid: ":invalid",
1639
+ onPlaceholderShown:":placeholder-shown",
1640
+ onFocusWithin: ":focus-within",
1641
+ onFocusVisible: ":focus-visible",
1642
+ onFirst: ":first-child",
1643
+ onLast: ":last-child",
1644
+ onFirstOfType: ":first-of-type",
1645
+ onLastOfType: ":last-of-type",
1646
+ onEmpty: ":empty",
1647
+ onTarget: ":target",
1648
+ onLink: ":link",
1649
+ };
1650
+
1651
+ /**
1652
+ * Maps Sinth Style pseudo-element shorthand keywords to real CSS pseudo-elements.
1653
+ */
1654
+ const SINTH_PSEUDO_ELEMENT: Record<string, string> = {
1655
+ before: "::before",
1656
+ after: "::after",
1657
+ placeholder: "::placeholder",
1658
+ selection: "::selection",
1659
+ firstLine: "::first-line",
1660
+ firstLetter: "::first-letter",
1661
+ marker: "::marker",
1662
+ backdrop: "::backdrop",
1663
+ };
1664
+
1665
+ /** Resolves a Sinth component name to its CSS selector string. */
1666
+ function sinthCompToSelector(name: string): string {
1667
+ const info = BUILTIN_MAP[name];
1668
+ if (!info) return name.toLowerCase();
1669
+ if (info.defaultClass) {
1670
+ const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
1671
+ return `${info.tag}${classes}`;
1672
+ }
1673
+ return info.tag;
1674
+ }
1675
+
1676
+ /**
1677
+ * v1.0.0: Preprocesses a raw style block body, transforming Sinth Style syntax into
1678
+ * standard CSS. All transformations are backward-compatible: raw CSS is never broken.
1679
+ *
1680
+ * Supported conversions:
1681
+ * - Component names as selectors: `Paragraph { ... }` → `p { ... }`
1682
+ * - Pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
1683
+ * - Pseudo-element shorthands: `before { ... }` → `&::before { ... }`
1684
+ * - Media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
1685
+ * - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
1686
+ */
1687
+ function preprocessSinthStyle(raw: string): string {
1688
+ const lines = raw.split("\n");
1689
+ const result: string[] = [];
1690
+
1691
+ for (const line of lines) {
1692
+ const trimmed = line.trim();
1693
+ const indent = line.match(/^(\s*)/)?.[1] ?? "";
1633
1694
 
1634
- const EVENT_RE = /^on[A-Z]/;
1635
- function eventAttrName(name: string): string | null {
1636
- return EVENT_RE.test(name) ? name.toLowerCase() : null;
1695
+ // Empty lines pass through
1696
+ if (!trimmed) { result.push(line); continue; }
1697
+
1698
+ // Strip Sinth comments from style blocks
1699
+ if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) { continue; }
1700
+ // Standard comments pass through
1701
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
1702
+ result.push(line); continue;
1703
+ }
1704
+
1705
+ // media(maxWidth: "600px") { → @media (max-width: 600px) {
1706
+ const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
1707
+ if (mediaMatch) {
1708
+ const params = parseSinthMediaParams(mediaMatch[1]);
1709
+ result.push(`${indent}@media (${params}) {`);
1710
+ continue;
1711
+ }
1712
+
1713
+ // Block opener: check if it's a keyword that maps to a pseudo-class/element
1714
+ const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
1715
+ if (blockMatch) {
1716
+ const keyword = blockMatch[1];
1717
+
1718
+ const pseudoCls = SINTH_PSEUDO_CLASS[keyword];
1719
+ if (pseudoCls) {
1720
+ result.push(`${indent}&${pseudoCls} {`);
1721
+ continue;
1722
+ }
1723
+
1724
+ const pseudoEl = SINTH_PSEUDO_ELEMENT[keyword];
1725
+ if (pseudoEl) {
1726
+ result.push(`${indent}&${pseudoEl} {`);
1727
+ continue;
1728
+ }
1729
+
1730
+ // Capital-letter IDENT = component name
1731
+ if (/^[A-Z]/.test(keyword) && BUILTIN_MAP[keyword]) {
1732
+ result.push(`${indent}${sinthCompToSelector(keyword)} {`);
1733
+ continue;
1734
+ }
1735
+ }
1736
+
1737
+ // CSS custom property shorthand: `var --primary: "value"` → `--primary: value;`
1738
+ const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
1739
+ if (varPropMatch) {
1740
+ result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
1741
+ continue;
1742
+ }
1743
+
1744
+ result.push(line);
1745
+ }
1746
+
1747
+ return result.join("\n");
1748
+ }
1749
+
1750
+ /** Converts Sinth media-query params to CSS @media condition string. */
1751
+ function parseSinthMediaParams(params: string): string {
1752
+ const parts = params.split(",").map(p => {
1753
+ const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
1754
+ if (!m) return p.trim();
1755
+ return `${camelToKebab(m[1])}: ${m[2].trim()}`;
1756
+ });
1757
+ return parts.join(") and (");
1637
1758
  }
1638
1759
 
1639
- // ═══════════════════════════════════════════════════════════
1640
- // SECTION 7: STYLE PROCESSOR
1641
- // ═══════════════════════════════════════════════════════════
1760
+ // ═══════════════════════════════════════════════════════════════════════════
1761
+ // §8 STYLE PROCESSOR
1762
+ // ═══════════════════════════════════════════════════════════════════════════
1642
1763
 
1643
- // === v0.1.0: Completely rewritten convertCSSProps — bulletproof line-by-line approach ===
1644
- // Rules:
1645
- // - Match lines of the form: [whitespace] camelCaseProp : "value" [;]
1646
- // - Convert property name camelCase → kebab-case
1647
- // - Strip surrounding single or double quotes from value
1648
- // - Ensure trailing semicolon
1649
- // - Leave selectors (contain { or :pseudo), @rules, comments, braces untouched
1764
+ /**
1765
+ * Converts camelCase CSS property names to kebab-case, strips surrounding
1766
+ * quotes from values, and ensures each declaration ends with a semicolon.
1767
+ * Selectors, @rules, comments, and braces are left untouched.
1768
+ */
1650
1769
  function convertCSSProps(css: string): string {
1651
1770
  return css.split("\n").map(line => {
1652
1771
  const trimmed = line.trim();
1653
-
1654
- // Leave empty lines, braces, @rules, comments untouched
1655
- if (!trimmed) return line;
1772
+ if (!trimmed) return line;
1656
1773
  if (trimmed === "}" || trimmed.startsWith("}")) return line;
1657
1774
  if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
1658
- // Strip Sinth comments (-- ...) from style blocks
1659
- if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) return "";
1660
- if (trimmed.startsWith("@")) return line;
1661
- // Lines containing { are selector/block openers — leave untouched
1662
- if (trimmed.includes("{")) return line;
1663
-
1664
- // Match a CSS declaration: identifier (colon) value [semicolon]
1665
- // The colon must NOT be preceded by another colon (avoid matching ::before, &:hover etc.)
1666
- // Property names are identifiers: letters, digits, hyphens — but we only camelCase-convert
1667
- // identifiers that are purely alphabetic (camelCase or vendor-prefixed).
1775
+ if (trimmed.startsWith("@")) return line;
1776
+ if (trimmed.includes("{")) return line;
1777
+
1668
1778
  const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
1669
1779
  if (!m) return line;
1670
1780
 
1671
- const [, indent, rawProp, sep, rawVal] = m;
1781
+ const [, indent, rawProp, , rawVal] = m;
1672
1782
 
1673
- // Decide if this looks like a declaration vs a pseudo-selector line
1674
- // A declaration ends without { and the value is either quoted or a plain CSS value
1675
- // We require either camelCase OR a quoted value to convert
1783
+ // Only convert if there's a camelCase hint or a quoted value
1676
1784
  const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
1677
1785
  const hasQuotedVal = /^["']/.test(rawVal.trim());
1678
1786
  if (!hasCamelCase && !hasQuotedVal) return line;
1679
1787
 
1680
- // Strip trailing semicolon from value if present before stripping quotes
1681
1788
  let val = rawVal.trim();
1682
1789
  if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
1683
-
1684
- // Strip surrounding quotes
1685
- if (
1686
- (val.startsWith('"') && val.endsWith('"')) ||
1687
- (val.startsWith("'") && val.endsWith("'"))
1688
- ) {
1790
+ if ((val.startsWith('"') && val.endsWith('"')) ||
1791
+ (val.startsWith("'") && val.endsWith("'"))) {
1689
1792
  val = val.slice(1, -1);
1690
1793
  }
1691
1794
 
1692
- const kebab = camelToKebab(rawProp);
1693
- return `${indent}${kebab}: ${val};`;
1795
+ return `${indent}${camelToKebab(rawProp)}: ${val};`;
1694
1796
  }).join("\n");
1695
1797
  }
1696
1798
 
1697
- // === v0.1.0: processStyleBlock — correct order: interpolate {param} → camelCase convert → SCSS → scope ===
1799
+ /**
1800
+ * Processes a StyleBlock:
1801
+ * 1. Interpolate {param} placeholders
1802
+ * 2. Sinth Style preprocessing (pseudo-class shorthands, media, component selectors)
1803
+ * 3. camelCase → kebab-case conversion
1804
+ * 4. SCSS compilation (if lang="scss")
1805
+ * 5. Scoping (unless global)
1806
+ * 6. If block has a `target` component, wrap in the appropriate CSS selector
1807
+ */
1698
1808
  function processStyleBlock(
1699
1809
  block: StyleBlock,
1700
1810
  hash: string,
@@ -1702,23 +1812,24 @@ function processStyleBlock(
1702
1812
  ): string {
1703
1813
  let raw = block.raw;
1704
1814
 
1705
- // Step 1: Interpolate {param} placeholders (before anything else)
1706
- if (params.size > 0) {
1707
- raw = interpolateAttr(raw, params);
1708
- }
1815
+ // 1. Interpolate {param} placeholders
1816
+ if (params.size > 0) raw = interpolateAttr(raw, params);
1709
1817
 
1710
- // Step 2: Warn if & appears in a plain CSS block
1818
+ // 2. Sinth Style preprocessing
1819
+ raw = preprocessSinthStyle(raw);
1820
+
1821
+ // 3. Warn if & in plain CSS
1711
1822
  if (block.lang === "css" && raw.includes("&")) {
1712
1823
  SinthWarning.emit(
1713
- `'&' found in a plain CSS block. Use style lang="scss" for SCSS features.`,
1824
+ `'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
1714
1825
  block.loc,
1715
1826
  );
1716
1827
  }
1717
1828
 
1718
- // Step 3: Convert camelCase property names BEFORE SCSS compilation
1829
+ // 4. camelCase → kebab-case
1719
1830
  let css = convertCSSProps(raw);
1720
1831
 
1721
- // Step 4: SCSS compilation (if requested)
1832
+ // 5. SCSS compilation
1722
1833
  if (block.lang === "scss") {
1723
1834
  try {
1724
1835
  // eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -1727,15 +1838,19 @@ function processStyleBlock(
1727
1838
  } catch (e: unknown) {
1728
1839
  const err = e as { code?: string; message?: string };
1729
1840
  if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
1730
- throw new SinthError(
1731
- "SCSS support requires the 'sass' package.\n Install with: npm install sass"
1732
- );
1841
+ throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
1733
1842
  }
1734
1843
  throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
1735
1844
  }
1736
1845
  }
1737
1846
 
1738
- // Step 5: Scope selectors (unless global)
1847
+ // 6. If a target component is given, wrap content in its CSS selector
1848
+ if (block.target) {
1849
+ const selector = sinthCompToSelector(block.target);
1850
+ css = `${selector} {\n${css}\n}`;
1851
+ }
1852
+
1853
+ // 7. Scope (unless global)
1739
1854
  if (!block.global) css = scopeCSS(css, hash);
1740
1855
 
1741
1856
  return css;
@@ -1746,14 +1861,11 @@ function scopeCSS(css: string, hash: string): string {
1746
1861
  }
1747
1862
 
1748
1863
  function processRules(css: string, attr: string): string {
1749
- let out = "";
1750
- let i = 0;
1864
+ let out = "", i = 0;
1751
1865
 
1752
1866
  while (i < css.length) {
1753
- // Skip top-level whitespace
1754
1867
  if (/\s/.test(css[i])) { out += css[i++]; continue; }
1755
1868
 
1756
- // Skip CSS block comments
1757
1869
  if (css[i] === "/" && css[i + 1] === "*") {
1758
1870
  const end = css.indexOf("*/", i + 2);
1759
1871
  if (end === -1) { out += css.substring(i); break; }
@@ -1769,13 +1881,10 @@ function processRules(css: string, attr: string): string {
1769
1881
  const { content, end } = extractCSSBlock(css, braceIdx);
1770
1882
 
1771
1883
  if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
1772
- // @keyframes: never scope — they're global by name
1773
1884
  out += `${selector} {${content}}\n`;
1774
1885
  } else if (/^@(media|supports|layer|container)/.test(selector)) {
1775
- // Descend into conditional @rules
1776
1886
  out += `${selector} {\n${processRules(content, attr)}\n}\n`;
1777
1887
  } else if (selector.startsWith("@")) {
1778
- // Other @rules: pass through
1779
1888
  out += `${selector} {${content}}\n`;
1780
1889
  } else if (selector.length > 0) {
1781
1890
  out += `${scopeSelectors(selector, attr)} {${content}}\n`;
@@ -1783,7 +1892,6 @@ function processRules(css: string, attr: string): string {
1783
1892
 
1784
1893
  i = end;
1785
1894
  }
1786
-
1787
1895
  return out;
1788
1896
  }
1789
1897
 
@@ -1793,9 +1901,7 @@ function scopeSelectors(selList: string, attr: string): string {
1793
1901
  .map(s => {
1794
1902
  s = s.trim();
1795
1903
  if (!s) return "";
1796
- // Don't scope root elements
1797
1904
  if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
1798
- // Handle pseudo-classes/elements: insert scope before pseudo suffix
1799
1905
  const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
1800
1906
  if (m && m[1].trim()) {
1801
1907
  return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
@@ -1815,9 +1921,7 @@ function findCSSBrace(css: string, from: number): number {
1815
1921
  i++;
1816
1922
  } else if (css[i] === "{") {
1817
1923
  return i;
1818
- } else {
1819
- i++;
1820
- }
1924
+ } else { i++; }
1821
1925
  }
1822
1926
  return -1;
1823
1927
  }
@@ -1840,9 +1944,92 @@ function extractCSSBlock(css: string, openBrace: number): { content: string; end
1840
1944
  return { content: css.substring(openBrace + 1, i), end: i + 1 };
1841
1945
  }
1842
1946
 
1843
- // ═══════════════════════════════════════════════════════════
1844
- // SECTION 8: HTML GENERATOR
1845
- // ═══════════════════════════════════════════════════════════
1947
+ // ═══════════════════════════════════════════════════════════════════════════
1948
+ // §9 EXPRESSION → JS COMPILER
1949
+ // ═══════════════════════════════════════════════════════════════════════════
1950
+
1951
+ function compileExprToJS(expr: Expression): string {
1952
+ switch (expr.kind) {
1953
+ case "literal":
1954
+ if (!expr.value) return "null";
1955
+ if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
1956
+ if (expr.value.kind === "num") return String((expr.value as LitNum).value);
1957
+ if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
1958
+ return "null";
1959
+ case "variable":
1960
+ return expr.name ?? "undefined";
1961
+ case "binary": {
1962
+ const l = compileExprToJS(expr.left!);
1963
+ const r = compileExprToJS(expr.right!);
1964
+ const o = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op!;
1965
+ return `(${l} ${o} ${r})`;
1966
+ }
1967
+ case "unary": {
1968
+ const o = expr.op === "not" ? "!" : expr.op!;
1969
+ return `${o}(${compileExprToJS(expr.operand!)})`;
1970
+ }
1971
+ case "assign": {
1972
+ const v = expr.right ? compileExprToJS(expr.right) : "null";
1973
+ return `${expr.target} ${expr.op} ${v}`;
1974
+ }
1975
+ case "postfix":
1976
+ return `${expr.target}${expr.op}`;
1977
+ default:
1978
+ return "";
1979
+ }
1980
+ }
1981
+
1982
+ /** Compiles a pure-logic IfBlock (containing only AssignStmt children) to JS. */
1983
+ function compileIfToJS(ifBlock: IfBlock): string {
1984
+ const cond = compileExprToJS(ifBlock.condition);
1985
+ const ifJS = bodyToJS(ifBlock.body);
1986
+ const elseJS = ifBlock.elseBody ? bodyToJS(ifBlock.elseBody) : "";
1987
+ let js = `if (${cond}) {\n${ifJS}}\n`;
1988
+ if (elseJS) js += `else {\n${elseJS}}\n`;
1989
+ return js;
1990
+ }
1991
+
1992
+ function bodyToJS(children: Child[]): string {
1993
+ return children
1994
+ .filter(c => c.kind === "assign_stmt" || c.kind === "if")
1995
+ .map(c => {
1996
+ if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
1997
+ if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
1998
+ return "";
1999
+ })
2000
+ .join("");
2001
+ }
2002
+
2003
+ // ═══════════════════════════════════════════════════════════════════════════
2004
+ // §10 HTML GENERATOR
2005
+ // ═══════════════════════════════════════════════════════════════════════════
2006
+
2007
+ /**
2008
+ * CSS property names that are allowed as inline style shorthand attributes on
2009
+ * any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
2010
+ */
2011
+ const INLINE_STYLE_PROPS = new Set([
2012
+ "color","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
2013
+ "fontSize","fontWeight","fontFamily","fontStyle","fontVariant","lineHeight","letterSpacing","textAlign",
2014
+ "textDecoration","textTransform","whiteSpace","wordBreak","wordWrap","textOverflow",
2015
+ "margin","marginTop","marginBottom","marginLeft","marginRight",
2016
+ "padding","paddingTop","paddingBottom","paddingLeft","paddingRight",
2017
+ "width","height","minWidth","maxWidth","minHeight","maxHeight",
2018
+ "display","flexDirection","flexWrap","flex","flexGrow","flexShrink","flexBasis",
2019
+ "justifyContent","alignItems","alignContent","alignSelf","gap","rowGap","columnGap",
2020
+ "gridTemplateColumns","gridTemplateRows","gridColumn","gridRow","gridArea",
2021
+ "position","top","right","bottom","left","zIndex",
2022
+ "border","borderTop","borderBottom","borderLeft","borderRight",
2023
+ "borderWidth","borderStyle","borderColor","borderRadius",
2024
+ "outline","outlineWidth","outlineStyle","outlineColor","outlineOffset",
2025
+ "boxShadow","textShadow","opacity","visibility",
2026
+ "overflow","overflowX","overflowY","objectFit","objectPosition",
2027
+ "cursor","userSelect","pointerEvents","resize",
2028
+ "transform","transition","animation","animationDuration","animationDelay",
2029
+ "listStyle","listStyleType","listStylePosition",
2030
+ "verticalAlign","float","clear",
2031
+ "content","quotes",
2032
+ ]);
1846
2033
 
1847
2034
  function resolveBuiltinTag(
1848
2035
  name: string,
@@ -1862,101 +2049,81 @@ function resolveBuiltinTag(
1862
2049
 
1863
2050
  function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
1864
2051
  const { name, value } = attr;
1865
-
1866
2052
  if (value === null) return name;
1867
2053
  if (value.kind === "null") return "";
1868
2054
  if (value.kind === "bool") return value.value ? name : "";
1869
2055
 
2056
+ if (name === "model" && value?.kind === "str") {
2057
+ const vName = interpolateAttr(value.value, paramMap);
2058
+ return `oninput="(function(e){ ${vName} = e.target.value; sinthRender(); })(event)" value="${escAttr(vName)}"`;
2059
+ }
2060
+
1870
2061
  if (name === "delay") {
1871
- // Support both numbers and variable references
1872
- let delayVal: string;
1873
2062
  if (value.kind === "num") {
1874
- delayVal = String(value.value);
1875
- } else {
1876
- delayVal = litToString(value);
1877
- // If it looks like a variable name (not a number), treat it as a JS expression
1878
- if (!/^\d+$/.test(delayVal)) {
1879
- return `data-sinth-delay-expr="${escAttr(delayVal)}" style="display:none"`;
1880
- }
2063
+ return `data-sinth-delay="${value.value}" style="display:none"`;
1881
2064
  }
1882
- return `data-sinth-delay="${escAttr(delayVal)}" style="display:none"`;
1883
- }
2065
+ const v = litToString(value);
2066
+ if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}" style="display:none"`;
2067
+ if (v.startsWith("__EXPR__")) {
2068
+ try {
2069
+ const expr: Expression = JSON.parse(v.substring(8));
2070
+ const jsExpr = compileExprToJS(expr);
2071
+ return `data-sinth-delay-expr="${escAttr(jsExpr)}" style="display:none"`;
2072
+ } catch {}
2073
+ }
2074
+ return `data-sinth-delay-expr="${escAttr(v)}" style="display:none"`;
2075
+ }
1884
2076
 
1885
- if (value.kind === "num") return `${name}="${value.value}"`;
2077
+ if (value.kind === "num") return `${name}="${value.value}"`;
1886
2078
 
1887
2079
  let raw = value.value;
1888
-
1889
- // Check for inline expression
2080
+
2081
+ // Inline expression reference
1890
2082
  if (raw.startsWith("__EXPR__")) {
1891
2083
  const exprJson = raw.substring("__EXPR__".length);
1892
2084
  try {
1893
2085
  const expr: Expression = JSON.parse(exprJson);
1894
2086
  const jsExpr = compileExprToJS(expr);
1895
2087
  const ev = eventAttrName(name);
1896
- if (ev) {
1897
- return `${ev}="(function(){ ${jsExpr.replace(/"/g, '&quot;')}; })()"`;
1898
- }
2088
+ if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; })()"`;
1899
2089
  return `${name}="${escAttr(jsExpr)}"`;
1900
- } catch {
1901
- // Fall through to normal handling
1902
- }
1903
- }
2090
+ } catch { /* fall through */ }
2091
+ }
1904
2092
 
1905
2093
  raw = interpolateAttr(raw, paramMap);
1906
2094
 
1907
2095
  const ev = eventAttrName(name);
1908
- if (ev) {
1909
- // Always append sinthRender() to event handlers
1910
- const handler = raw.includes("(") ? raw : raw;
1911
- return `${ev}="${escAttr(handler)};sinthRender()"`;
1912
- }
2096
+ if (ev) return `${ev}="${escAttr(raw)};sinthRender()"`;
1913
2097
  return `${name}="${escAttr(raw)}"`;
1914
2098
  }
1915
2099
 
1916
- // === v0.1.0: renderText — "$slot" protected from double-escaping via placeholder approach ===
1917
2100
  function renderText(text: string, params: Map<string, string>): string {
1918
- // Map of placeholder → raw HTML for slot-like params
1919
2101
  const rawSlots = new Map<string, string>();
1920
- let counter = 0;
1921
-
1922
- let s = text;
2102
+ let counter = 0;
1923
2103
 
1924
- // Step 1: Replace \$ with a placeholder so it survives param substitution
1925
- s = s.replace(/\\\$/g, "\x00DOLLAR\x00");
2104
+ let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
1926
2105
 
1927
- // Step 2: Substitute $param references
1928
2106
  s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
1929
2107
  const val = params.get(n);
1930
- if (val === undefined) return `$${n}`; // unknown param — keep as literal
1931
-
1932
- // "$slot" (and any raw-HTML param) must NOT be HTML-escaped — use a placeholder
2108
+ if (val === undefined) return `$${n}`;
1933
2109
  if (n === "slot") {
1934
2110
  const ph = `\x00RAW${counter++}\x00`;
1935
2111
  rawSlots.set(ph, val);
1936
2112
  return ph;
1937
2113
  }
1938
-
1939
- return val; // will be HTML-escaped in step 3
2114
+ return val;
1940
2115
  });
1941
2116
 
1942
- // Step 3: HTML-escape the entire string
1943
- // Placeholders contain \x00 which esc() does not touch
1944
2117
  s = esc(s);
1945
2118
 
1946
- // Step 4: Restore raw HTML slot placeholders (must NOT be escaped)
1947
- for (const [ph, val] of rawSlots) {
1948
- s = s.replace(ph, val);
1949
- }
1950
-
1951
- // Step 5: Restore \$ → $
2119
+ for (const [ph, val] of rawSlots) s = s.replace(ph, val);
1952
2120
  s = s.replace(/\x00DOLLAR\x00/g, "$");
1953
2121
 
1954
- // === v0.1.0: Warn about {identifier} patterns remaining after substitution ===
1955
2122
  const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
1956
- let m: RegExpExecArray | null;
2123
+ let m: RegExpExecArray | null;
1957
2124
  while ((m = braceRe.exec(s)) !== null) {
1958
2125
  SinthWarning.emit(
1959
- `Use $param for text interpolation. {param} is for attributes only. Found '${m[0]}' in text content.`
2126
+ `Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
1960
2127
  );
1961
2128
  }
1962
2129
 
@@ -1964,8 +2131,7 @@ function renderText(text: string, params: Map<string, string>): string {
1964
2131
  }
1965
2132
 
1966
2133
  function interpolateAttr(text: string, params: Map<string, string>): string {
1967
- let s = text;
1968
- s = s.replace(/\\\{/g, "\x00LB\x00");
2134
+ let s = text.replace(/\\\{/g, "\x00LB\x00");
1969
2135
  s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
1970
2136
  return s.replace(/\x00LB\x00/g, "{");
1971
2137
  }
@@ -1977,34 +2143,103 @@ function renderChild(
1977
2143
  depth: number,
1978
2144
  ): string {
1979
2145
  if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
1980
- if (child.kind === "text") return renderText(child.value, params);
1981
- if (child.kind === "expr") {
1982
- const jsExpr = compileExprToJS(child.expression);
1983
- return `<span class="sinth-expr" data-expr="${escAttr(jsExpr)}"></span>`;
1984
- }
1985
- if (child.kind === "if") {
1986
- const condJS = compileExprToJS(child.condition);
1987
- const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
1988
- const elseHTML = child.elseBody ? child.elseBody.map(c => renderChild(c, ctx, params, depth + 1)).join("") : "";
1989
- return `<template data-sinth-if="${escAttr(condJS)}">${bodyHTML}</template>` +
1990
- (elseHTML ? `<template data-sinth-else>${elseHTML}</template>` : "");
1991
- }
1992
- if (child.kind === "for") {
1993
- let bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
1994
- // Replace component tags for the loop variable with expression spans
1995
- const itemVar = child.itemVar;
1996
- bodyHTML = bodyHTML.replace(
1997
- new RegExp(`<${itemVar}[^>]*>(.*?)</${itemVar}>`, 'g'),
1998
- (_, content) => {
1999
- if (!content || content.trim() === '') {
2000
- return `<span class="sinth-expr" data-expr="${itemVar}"></span>`;
2001
- }
2002
- return `<span class="sinth-expr" data-expr="${itemVar}">${content}</span>`;
2003
- }
2004
- );
2005
- return `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(itemVar)}">${bodyHTML}</template>`;
2146
+
2147
+ switch (child.kind) {
2148
+ case "text":
2149
+ return renderText(child.value, params);
2150
+
2151
+ case "expr": {
2152
+ const jsExpr = compileExprToJS(child.expression);
2153
+ return `<span class="sinth-expr" data-expr="${escAttr(jsExpr)}"></span>`;
2154
+ }
2155
+
2156
+ case "assign_stmt": {
2157
+ // An AssignStmt appearing in a child list (outside an if-block) is emitted as
2158
+ // a logic block that runs in sinthRender().
2159
+ ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
2160
+ return "";
2161
+ }
2162
+
2163
+ case "if":
2164
+ return renderIfBlock(child, ctx, params, depth);
2165
+
2166
+ case "for": {
2167
+ const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2168
+ return (
2169
+ `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}">${bodyHTML}</template>`
2170
+ );
2171
+ }
2172
+
2173
+ case "use":
2174
+ return renderCompUse(child, ctx, params, depth);
2175
+ }
2176
+ }
2177
+
2178
+ /**
2179
+ * v1.0.0: Unified if/else block renderer.
2180
+ *
2181
+ * Classifies each branch as containing assignments, components, or both, then
2182
+ * chooses the appropriate rendering strategy:
2183
+ * • Pure-logic → JS fragment in sinthRender(); no HTML output.
2184
+ * • Pure-DOM → <template data-sinth-if> for runtime DOM diffing.
2185
+ * • Mixed → <span id="__smN__"> placeholder; sinthRender() sets innerHTML.
2186
+ */
2187
+ function renderIfBlock(
2188
+ ifBlock: IfBlock,
2189
+ ctx: CompileCtx,
2190
+ params: Map<string, string>,
2191
+ depth: number,
2192
+ ): string {
2193
+ if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
2194
+
2195
+ const condJS = compileExprToJS(ifBlock.condition);
2196
+ const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
2197
+ const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
2198
+ const hasComp = allChildren.some(c => c.kind === "use");
2199
+
2200
+ // ── Pure-logic ──────────────────────────────────────────────────────────
2201
+ if (hasAssign && !hasComp) {
2202
+ ctx.logicBlocks.push(compileIfToJS(ifBlock));
2203
+ return "";
2204
+ }
2205
+
2206
+ // ── Pure-DOM ────────────────────────────────────────────────────────────
2207
+ if (!hasAssign && hasComp) {
2208
+ const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2209
+ const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
2210
+ return (
2211
+ `<template data-sinth-if="${escAttr(condJS)}">${bodyHTML}</template>` +
2212
+ (elseHTML ? `<template data-sinth-else>${elseHTML}</template>` : "")
2213
+ );
2006
2214
  }
2007
- return renderCompUse(child, ctx, params, depth);
2215
+
2216
+ // ── Mixed ───────────────────────────────────────────────────────────────
2217
+ // Both assignments and component children appear in at least one branch.
2218
+ const id = `__sm${ctx.mixedCounter++}__`;
2219
+
2220
+ const ifAssignJS = ifBlock.body
2221
+ .filter(c => c.kind === "assign_stmt")
2222
+ .map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
2223
+ .join("\n");
2224
+
2225
+ const ifHTML = ifBlock.body
2226
+ .filter(c => c.kind !== "assign_stmt")
2227
+ .map(c => renderChild(c, ctx, params, depth + 1))
2228
+ .join("");
2229
+
2230
+ const elseAssignJS = (ifBlock.elseBody ?? [])
2231
+ .filter(c => c.kind === "assign_stmt")
2232
+ .map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
2233
+ .join("\n");
2234
+
2235
+ const elseHTML = (ifBlock.elseBody ?? [])
2236
+ .filter(c => c.kind !== "assign_stmt")
2237
+ .map(c => renderChild(c, ctx, params, depth + 1))
2238
+ .join("");
2239
+
2240
+ ctx.mixedBlocks.push({ id, conditionJS: condJS, ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML });
2241
+
2242
+ return `<span id="${id}" data-sinth-mixed></span>`;
2008
2243
  }
2009
2244
 
2010
2245
  function renderCompUse(
@@ -2013,7 +2248,12 @@ function renderCompUse(
2013
2248
  params: Map<string, string>,
2014
2249
  depth: number,
2015
2250
  ): string {
2016
- // === v0.1.0: RawHTML — output content attribute verbatim, no wrapping tag, no scoping ===
2251
+ // Transparent wrapper inserted by flattenIfToUses()
2252
+ if (use.name === "__IF_ROOT__") {
2253
+ return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
2254
+ }
2255
+
2256
+ // RawHTML
2017
2257
  if (use.name === "RawHTML") {
2018
2258
  const ca = use.attrs.find(a => a.name === "content");
2019
2259
  if (!ca || !ca.value) return "";
@@ -2027,14 +2267,13 @@ function renderCompUse(
2027
2267
  // Custom element
2028
2268
  const customEl = ctx.customEls.get(use.name);
2029
2269
  if (customEl) {
2030
- const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
2270
+ const attrParts = [`data-s="${ctx.scopeHash}"`];
2031
2271
  for (const attr of use.attrs) {
2032
2272
  const r = renderAttr(attr, params);
2033
2273
  if (r) attrParts.push(r);
2034
2274
  }
2035
- const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
2036
- const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2037
- return `<${customEl.tagName}${attrStr}>${inner}</${customEl.tagName}>`;
2275
+ const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2276
+ return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
2038
2277
  }
2039
2278
 
2040
2279
  // Built-in component
@@ -2043,9 +2282,20 @@ function renderCompUse(
2043
2282
 
2044
2283
  const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
2045
2284
  let userClass: string | undefined;
2285
+ const inlineStyleParts: string[] = [];
2046
2286
 
2047
2287
  for (const attr of use.attrs) {
2048
- if (attr.name === "level" && use.name === "Heading") continue; // consumed by tag resolution
2288
+ if (attr.name === "level" && use.name === "Heading") continue;
2289
+
2290
+ // v1.0.0: Inline CSS shorthand Paragraph(color: "red") { ... }
2291
+ if (INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
2292
+ const val = attr.value.kind === "str"
2293
+ ? interpolateAttr(attr.value.value, params)
2294
+ : litToString(attr.value);
2295
+ inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
2296
+ continue;
2297
+ }
2298
+
2049
2299
  if (attr.name === "class") {
2050
2300
  if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
2051
2301
  continue;
@@ -2054,21 +2304,15 @@ function renderCompUse(
2054
2304
  if (rendered) attrParts.push(rendered);
2055
2305
  }
2056
2306
 
2057
- // Merge default class with user-supplied class
2058
2307
  const classes = [defaultClass, userClass].filter(Boolean).join(" ");
2059
2308
  if (classes) attrParts.push(`class="${escAttr(classes)}"`);
2060
-
2061
- // === v0.1.0: Default type="button" for <button> elements ===
2062
- if (tag === "button" && !use.attrs.some(a => a.name === "type")) {
2063
- attrParts.push(`type="button"`);
2064
- }
2309
+ if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
2310
+ if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
2065
2311
 
2066
2312
  const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
2067
2313
 
2068
2314
  if (isVoid) {
2069
- if (use.children.length > 0) {
2070
- SinthWarning.emit(`<${tag}> is a void element and cannot have children.`, use.loc);
2071
- }
2315
+ if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
2072
2316
  return `<${tag}${attrStr}>`;
2073
2317
  }
2074
2318
 
@@ -2083,20 +2327,16 @@ function expandUserComp(
2083
2327
  params: Map<string, string>,
2084
2328
  depth: number,
2085
2329
  ): string {
2086
- // Recursion check
2087
2330
  if (use.name === def.name && depth > 1) {
2088
2331
  throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
2089
2332
  }
2090
2333
 
2091
- // Build local parameter map
2092
2334
  const local = new Map<string, string>();
2093
2335
 
2094
- // Apply defaults first
2095
2336
  for (const p of def.params) {
2096
2337
  if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
2097
2338
  }
2098
2339
 
2099
- // Apply caller-supplied attributes
2100
2340
  for (const attr of use.attrs) {
2101
2341
  if (attr.value === null) {
2102
2342
  local.set(attr.name, "true");
@@ -2106,7 +2346,6 @@ function expandUserComp(
2106
2346
  }
2107
2347
  }
2108
2348
 
2109
- // Validate required parameters
2110
2349
  for (const p of def.params) {
2111
2350
  if (!local.has(p.name)) {
2112
2351
  throw new SinthError(
@@ -2116,11 +2355,9 @@ function expandUserComp(
2116
2355
  }
2117
2356
  }
2118
2357
 
2119
- // Render slot: children at the call site
2120
2358
  const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
2121
2359
  local.set("slot", slotHTML);
2122
2360
 
2123
- // === v0.1.0: Process component style blocks with instance params and push to extraCSS ===
2124
2361
  for (const block of def.styles) {
2125
2362
  ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
2126
2363
  }
@@ -2128,41 +2365,9 @@ function expandUserComp(
2128
2365
  return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
2129
2366
  }
2130
2367
 
2131
- // === v0.1.0: Expression to JS helper ===
2132
- function compileExprToJS(expr: Expression): string {
2133
- switch (expr.kind) {
2134
- case "literal":
2135
- if (!expr.value) return "null";
2136
- if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
2137
- if (expr.value.kind === "num") return String((expr.value as LitNum).value);
2138
- if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
2139
- return "null";
2140
- case "variable":
2141
- return expr.name || "undefined";
2142
- case "binary": {
2143
- const left = compileExprToJS(expr.left!);
2144
- const right = compileExprToJS(expr.right!);
2145
- const op = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op;
2146
- return `(${left} ${op} ${right})`;
2147
- }
2148
- case "unary": {
2149
- const op = expr.op === "not" ? "!" : expr.op;
2150
- return `${op}(${compileExprToJS(expr.operand!)})`;
2151
- }
2152
- case "assign": {
2153
- const val = expr.right ? compileExprToJS(expr.right) : "null";
2154
- return `${expr.target} ${expr.op} ${val}`;
2155
- }
2156
- case "postfix":
2157
- return `${expr.target}${expr.op}`;
2158
- default:
2159
- return "";
2160
- }
2161
- }
2162
-
2163
- // ═══════════════════════════════════════════════════════════
2164
- // SECTION 9: SCRIPT COLLECTOR
2165
- // ═══════════════════════════════════════════════════════════
2368
+ // ═══════════════════════════════════════════════════════════════════════════
2369
+ // §11 SCRIPT COLLECTOR
2370
+ // ═══════════════════════════════════════════════════════════════════════════
2166
2371
 
2167
2372
  function collectScripts(
2168
2373
  file: SinthFile,
@@ -2172,25 +2377,19 @@ function collectScripts(
2172
2377
  const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
2173
2378
  const seenFunctions = new Set<string>();
2174
2379
 
2175
- // Component script blocks → hoisted as IIFEs
2176
2380
  for (const [, def] of allDefs) {
2177
2381
  for (const block of def.scripts) {
2178
2382
  for (const fn of extractFunctionNames(block.raw)) {
2179
- if (seenFunctions.has(fn)) {
2180
- throw new SinthError(`Function '${fn}' defined in multiple component script blocks.`);
2181
- }
2383
+ if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
2182
2384
  seenFunctions.add(fn);
2183
2385
  }
2184
2386
  componentScripts.push(`(function(){\n${block.raw}\n})();`);
2185
2387
  }
2186
2388
  }
2187
2389
 
2188
- // Page-level script blocks
2189
2390
  for (const block of file.scripts) {
2190
2391
  for (const fn of extractFunctionNames(block.raw)) {
2191
- if (seenFunctions.has(fn)) {
2192
- throw new SinthError(`Function '${fn}' conflicts with a component script.`);
2193
- }
2392
+ if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
2194
2393
  seenFunctions.add(fn);
2195
2394
  }
2196
2395
  pageScripts.push({ raw: block.raw, attrs: block.attrs });
@@ -2202,14 +2401,14 @@ function collectScripts(
2202
2401
  function extractFunctionNames(js: string): string[] {
2203
2402
  const names: string[] = [];
2204
2403
  const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
2205
- let m: RegExpExecArray | null;
2404
+ let m: RegExpExecArray | null;
2206
2405
  while ((m = re.exec(js)) !== null) names.push(m[1]);
2207
2406
  return names;
2208
2407
  }
2209
2408
 
2210
- // ═══════════════════════════════════════════════════════════
2211
- // SECTION 10: HEAD GENERATOR
2212
- // ═══════════════════════════════════════════════════════════
2409
+ // ═══════════════════════════════════════════════════════════════════════════
2410
+ // §12 HEAD GENERATOR
2411
+ // ═══════════════════════════════════════════════════════════════════════════
2213
2412
 
2214
2413
  interface HeadData {
2215
2414
  title?: string; fav?: string;
@@ -2220,9 +2419,7 @@ interface HeadData {
2220
2419
 
2221
2420
  function buildHeadData(meta: MetaEntry[]): HeadData {
2222
2421
  let title: string | undefined, fav: string | undefined;
2223
- let lang = "en";
2224
- let charset = "UTF-8";
2225
- let viewport = "width=device-width, initial-scale=1.0";
2422
+ let lang = "en", charset = "UTF-8", viewport = "width=device-width, initial-scale=1.0";
2226
2423
  const metaTags: { name: string; content: string }[] = [];
2227
2424
  const metaProps: { property: string; content: string }[] = [];
2228
2425
 
@@ -2241,8 +2438,8 @@ function buildHeadData(meta: MetaEntry[]): HeadData {
2241
2438
  default:
2242
2439
  if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
2243
2440
  const prop = m.key
2244
- .replace(/^og([A-Z])/, (_, c: string) => `og:${c.toLowerCase()}`)
2245
- .replace(/^twitter([A-Z])/, (_, c: string) => `twitter:${c.toLowerCase()}`);
2441
+ .replace(/^og([A-Z])/, (_: string, c: string) => `og:${c.toLowerCase()}`)
2442
+ .replace(/^twitter([A-Z])/, (_: string, c: string) => `twitter:${c.toLowerCase()}`);
2246
2443
  metaProps.push({ property: prop, content: val });
2247
2444
  } else {
2248
2445
  metaTags.push({ name: camelToKebab(m.key), content: val });
@@ -2253,10 +2450,8 @@ function buildHeadData(meta: MetaEntry[]): HeadData {
2253
2450
  return { title, fav, lang, charset, viewport, metaTags, metaProps };
2254
2451
  }
2255
2452
 
2256
- // === v0.1.0: .jpg and .jpeg return "image/jpeg" ===
2257
2453
  function faviconType(p: string): string {
2258
- const ext = path.extname(p).toLowerCase();
2259
- switch (ext) {
2454
+ switch (path.extname(p).toLowerCase()) {
2260
2455
  case ".ico": return "image/x-icon";
2261
2456
  case ".png": return "image/png";
2262
2457
  case ".svg": return "image/svg+xml";
@@ -2265,7 +2460,7 @@ function faviconType(p: string): string {
2265
2460
  case ".jpg":
2266
2461
  case ".jpeg": return "image/jpeg";
2267
2462
  default:
2268
- SinthWarning.emit(`Unknown favicon extension '${ext}', defaulting to image/x-icon`);
2463
+ SinthWarning.emit(`Unknown favicon extension '${path.extname(p)}', defaulting to image/x-icon`);
2269
2464
  return "image/x-icon";
2270
2465
  }
2271
2466
  }
@@ -2296,9 +2491,317 @@ function renderHead(
2296
2491
  return `<head>\n${lines.join("\n")}\n</head>`;
2297
2492
  }
2298
2493
 
2299
- // ═══════════════════════════════════════════════════════════
2300
- // SECTION 11: MAIN COMPILATION PIPELINE
2301
- // ═══════════════════════════════════════════════════════════
2494
+ // ═══════════════════════════════════════════════════════════════════════════
2495
+ // §13 SINTH RUNTIME — TREE-SHAKEN BUILDER
2496
+ // ═══════════════════════════════════════════════════════════════════════════
2497
+
2498
+ /**
2499
+ * Builds the sinthRender() function body, including only the runtime
2500
+ * features that are actually used by this page. This keeps output lean.
2501
+ */
2502
+ function buildRuntime(opts: {
2503
+ varDecls: VarDeclaration[];
2504
+ bodyHTML: string;
2505
+ logicBlocks: string[];
2506
+ mixedBlocks: MixedBlockEntry[];
2507
+ assignedVars: Set<string>;
2508
+ }): string {
2509
+ const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars } = opts;
2510
+
2511
+ // Feature flags
2512
+ // Feature flags
2513
+ const needsExpr = bodyHTML.includes("sinth-expr");
2514
+ const needsIf = bodyHTML.includes("data-sinth-if");
2515
+ const needsFor = bodyHTML.includes("data-sinth-for");
2516
+ const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr"));
2517
+ const needsMixed = mixedBlocks.length > 0;
2518
+ const needsLogic = logicBlocks.length > 0;
2519
+ const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
2520
+
2521
+ // Variable declarations with type defaults
2522
+ const varLines = varDecls.map(v => {
2523
+ if (!v.value) {
2524
+ if (!assignedVars.has(v.name)) {
2525
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
2526
+ SinthWarning.emit(
2527
+ `Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
2528
+ v.loc,
2529
+ );
2530
+ }
2531
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
2532
+ return `var ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
2533
+ }
2534
+ const val = litToString(v.value);
2535
+ if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
2536
+ if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
2537
+ if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2538
+ if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
2539
+ try {
2540
+ const arr = JSON.parse(val.slice(7));
2541
+ return `var ${v.name} = ${JSON.stringify(arr)};`;
2542
+ } catch { return `var ${v.name} = ${val.slice(7)};`; }
2543
+ }
2544
+ return `var ${v.name} = ${val};`;
2545
+ }).join("\n");
2546
+
2547
+ if (!needsRender && !needsDelay) {
2548
+ return varLines ? `// Sinth v1.0.0\n${varLines}` : "";
2549
+ }
2550
+
2551
+ let renderBody = "";
2552
+
2553
+ // Scroll position preservation
2554
+ renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
2555
+
2556
+ // Pure-logic if blocks
2557
+ if (needsLogic) {
2558
+ renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
2559
+ }
2560
+
2561
+ // data-sinth-for templates (MUST run before if-templates)
2562
+ if (needsFor) {
2563
+ renderBody += `
2564
+ document.querySelectorAll('template[data-sinth-for]').forEach(function(t) {
2565
+ var arr;
2566
+ try { arr = eval(t.dataset.sinthFor); } catch(e) { arr = []; }
2567
+ if (!Array.isArray(arr)) arr = [];
2568
+ var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
2569
+ if (anchor) {
2570
+ var cur2 = anchor.nextSibling;
2571
+ while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2572
+ anchor.remove();
2573
+ }
2574
+ var fa = document.createElement('span');
2575
+ fa.style.display = 'none';
2576
+ fa.dataset.sinthForAnchor = t.dataset.sinthFor;
2577
+ t.parentNode && t.parentNode.insertBefore(fa, t);
2578
+ arr.forEach(function(item) {
2579
+ var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
2580
+ var _user = item; // Capture in closure
2581
+ window['_sinth_item_'] = _user;
2582
+ var frag = document.createRange().createContextualFragment(t.innerHTML);
2583
+ // Replace expressions with actual values BEFORE inserting into DOM
2584
+ frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2585
+ try {
2586
+ if (el.dataset.expr === _item) {
2587
+ el.textContent = _user;
2588
+ } else if (el.dataset.expr && el.dataset.expr.indexOf(_item) !== -1) {
2589
+ var expr = el.dataset.expr;
2590
+ // Replace variable name with the captured closure variable
2591
+ eval('var ' + _item + ' = _user;');
2592
+ el.textContent = eval(expr);
2593
+ }
2594
+ } catch(e) {}
2595
+ });
2596
+ // Process if-templates
2597
+ frag.querySelectorAll('template[data-sinth-if]').forEach(function(ifT) {
2598
+ var cond = false;
2599
+ try { eval('var ' + _item + ' = _user;'); cond = eval(ifT.dataset.sinthIf); } catch(e) {}
2600
+ if (cond) {
2601
+ var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
2602
+ ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2603
+ try { eval('var ' + _item + ' = _user;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2604
+ });
2605
+ ifT.parentNode.insertBefore(ifContent, ifT);
2606
+ } else {
2607
+ var elseT = ifT.nextElementSibling;
2608
+ if (elseT && elseT.hasAttribute('data-sinth-else')) {
2609
+ var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
2610
+ elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2611
+ try { eval('var ' + _item + ' = _user;'); el2.textContent = eval(el2.dataset.expr); } catch(e) {}
2612
+ });
2613
+ ifT.parentNode.insertBefore(elseContent, ifT);
2614
+ }
2615
+ }
2616
+ });
2617
+ // Handle delays
2618
+ frag.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2619
+ var ms = parseInt(el.dataset.sinthDelay) || 0;
2620
+ el.style.display = 'none';
2621
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2622
+ else el.style.display = '';
2623
+ });
2624
+ frag.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2625
+ try {
2626
+ eval('var ' + _item + ' = _user;');
2627
+ var ms = eval(el.dataset.sinthDelayExpr) || 0;
2628
+ el.style.display = '';
2629
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2630
+ } catch(e) {}
2631
+ });
2632
+ t.parentNode && t.parentNode.insertBefore(frag, t);
2633
+ });
2634
+ });
2635
+ `;
2636
+ }
2637
+
2638
+ // data-sinth-if / data-sinth-else templates (run AFTER for-loops)
2639
+ if (needsIf) {
2640
+ renderBody += `
2641
+ document.querySelectorAll('template[data-sinth-if]').forEach(function(t) {
2642
+ var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + t.dataset.sinthIf + '"]');
2643
+ var cond;
2644
+ try { cond = eval(t.dataset.sinthIf); } catch(e) { cond = false; }
2645
+ if (cond) {
2646
+ if (anchor) {
2647
+ var cur = anchor.nextSibling;
2648
+ while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
2649
+ } else {
2650
+ anchor = document.createElement('span');
2651
+ anchor.style.display = 'none';
2652
+ anchor.dataset.sinthIfAnchor = t.dataset.sinthIf;
2653
+ t.parentNode.insertBefore(anchor, t);
2654
+ }
2655
+ var frag = document.createRange().createContextualFragment(t.innerHTML);
2656
+ frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2657
+ try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2658
+ });
2659
+ frag.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2660
+ var ms = parseInt(el.dataset.sinthDelay) || 0;
2661
+ el.style.display = 'none';
2662
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2663
+ else el.style.display = '';
2664
+ });
2665
+ frag.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2666
+ try {
2667
+ var ms = eval(el.dataset.sinthDelayExpr) || 0;
2668
+ el.style.display = '';
2669
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2670
+ } catch(e) {}
2671
+ });
2672
+ t.parentNode.insertBefore(frag, t);
2673
+ } else {
2674
+ if (anchor) {
2675
+ var cur2 = anchor.nextSibling;
2676
+ while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2677
+ anchor.remove();
2678
+ }
2679
+ var elseT = t.nextElementSibling;
2680
+ if (elseT && elseT.dataset && elseT.hasAttribute('data-sinth-else')) {
2681
+ var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + t.dataset.sinthIf + '"]');
2682
+ if (ea) {
2683
+ var cur3 = ea.nextSibling;
2684
+ while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
2685
+ } else {
2686
+ ea = document.createElement('span');
2687
+ ea.style.display = 'none';
2688
+ ea.dataset.sinthIfAnchor = '__else__' + t.dataset.sinthIf;
2689
+ t.parentNode.insertBefore(ea, t);
2690
+ }
2691
+ var ef = document.createRange().createContextualFragment(elseT.innerHTML);
2692
+ ef.querySelectorAll('.sinth-expr').forEach(function(el) {
2693
+ try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2694
+ });
2695
+ ef.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2696
+ var ms = parseInt(el.dataset.sinthDelay) || 0;
2697
+ el.style.display = 'none';
2698
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2699
+ else el.style.display = '';
2700
+ });
2701
+ ef.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2702
+ try {
2703
+ var ms = eval(el.dataset.sinthDelayExpr) || 0;
2704
+ el.style.display = '';
2705
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2706
+ } catch(e) {}
2707
+ });
2708
+ t.parentNode.insertBefore(ef, t);
2709
+ } else {
2710
+ var ea2 = t.parentNode ? t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + t.dataset.sinthIf + '"]') : null;
2711
+ if (ea2) {
2712
+ var ec = ea2.nextSibling;
2713
+ while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
2714
+ ea2.remove();
2715
+ }
2716
+ }
2717
+ }
2718
+ });
2719
+ `;
2720
+ }
2721
+
2722
+
2723
+ // Mixed if/else blocks
2724
+ if (needsMixed) {
2725
+ for (const mb of mixedBlocks) {
2726
+ const ifHTMLJS = JSON.stringify(mb.ifHTML);
2727
+ const elseHTMLJS = JSON.stringify(mb.elseHTML);
2728
+ const hasDelay = mb.ifHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay");
2729
+ renderBody += `
2730
+ (function() {
2731
+ var __el = document.getElementById(${JSON.stringify(mb.id)});
2732
+ if (__el) {
2733
+ var __cond;
2734
+ try { __cond = (${mb.conditionJS}); } catch(e) { __cond = false; }
2735
+ if (__cond) {
2736
+ ${mb.ifJS ? mb.ifJS + "\n" : ""} __el.innerHTML = ${ifHTMLJS};
2737
+ } else {
2738
+ ${mb.elseJS ? mb.elseJS + "\n" : ""} __el.innerHTML = ${elseHTMLJS};
2739
+ }
2740
+ __el.querySelectorAll('.sinth-expr').forEach(function(e) {
2741
+ try { e.textContent = eval(e.dataset.expr); } catch(ex) {}
2742
+ });
2743
+ ${hasDelay ? `
2744
+ // Handle delays for this mixed block
2745
+ __el.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2746
+ var ms = parseInt(el.dataset.sinthDelay) || 0;
2747
+ el.style.display = 'none'; // Ensure hidden before timeout
2748
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2749
+ else el.style.display = '';
2750
+ });
2751
+ __el.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2752
+ try {
2753
+ var ms = parseInt(eval(el.dataset.sinthDelayExpr)) || 0;
2754
+ el.style.display = 'none';
2755
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2756
+ else el.style.display = '';
2757
+ } catch(e) {}
2758
+ });
2759
+ ` : ""}
2760
+ }
2761
+ })();
2762
+ `;
2763
+ }
2764
+ }
2765
+
2766
+ // Expression spans
2767
+ if (needsExpr) {
2768
+ renderBody += `
2769
+ document.querySelectorAll('.sinth-expr').forEach(function(el) {
2770
+ try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2771
+ });
2772
+ `;
2773
+ }
2774
+
2775
+ // Restore scroll
2776
+ renderBody += ` window.scrollTo(_sx, _sy);\n`;
2777
+
2778
+ // Delay reveals (one-shot, only on first render)
2779
+ const delayBlock = needsDelay ? `
2780
+ setTimeout(function() {
2781
+ document.querySelectorAll('[data-sinth-delay]').forEach(function(el) {
2782
+ var ms = parseInt(el.dataset.sinthDelay) || 0;
2783
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2784
+ else el.style.display = '';
2785
+ });
2786
+ document.querySelectorAll('[data-sinth-delay-expr]').forEach(function(el) {
2787
+ try {
2788
+ var ms = parseInt(eval(el.dataset.sinthDelayExpr)) || 0;
2789
+ if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2790
+ else el.style.display = '';
2791
+ } catch(e) {}
2792
+ });
2793
+ }, 0);
2794
+ ` : "";
2795
+
2796
+ return `// Sinth v1.0.0 — compiled runtime
2797
+ ${varLines}
2798
+ ${needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : ""}
2799
+ ${delayBlock}`;
2800
+ }
2801
+
2802
+ // ═══════════════════════════════════════════════════════════════════════════
2803
+ // §14 MAIN COMPILATION PIPELINE
2804
+ // ═══════════════════════════════════════════════════════════════════════════
2302
2805
 
2303
2806
  interface CompileOptions {
2304
2807
  projectRoot: string;
@@ -2316,14 +2819,20 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2316
2819
  const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
2317
2820
  const hash = fnv1a(absPath);
2318
2821
 
2319
- // === v0.1.0: extraCSS collected during rendering (per-instance component styles) ===
2822
+ // All var declarations are already collected via shared _varDecls reference
2823
+ const allVarDecls: VarDeclaration[] = file.varDecls;
2824
+
2320
2825
  const ctx: CompileCtx = {
2321
2826
  allDefs, customEls, cssLinks, jsLinks,
2322
- scopeHash: hash, pageFile: absPath, extraCSS: [],
2827
+ scopeHash: hash,
2828
+ pageFile: absPath,
2829
+ extraCSS: [],
2830
+ mixedBlocks: [],
2831
+ mixedCounter: 0,
2832
+ logicBlocks: [],
2323
2833
  };
2324
2834
 
2325
2835
  if (!file.isPage) {
2326
- // Component file → fragment only
2327
2836
  const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
2328
2837
  const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
2329
2838
  const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
@@ -2332,36 +2841,32 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2332
2841
 
2333
2842
  const headData = buildHeadData(file.meta);
2334
2843
 
2335
- // Render body HTML first (populates ctx.extraCSS from expandUserComp)
2844
+ // Render body HTML (populates ctx.extraCSS, ctx.mixedBlocks, ctx.logicBlocks)
2336
2845
  const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
2337
2846
 
2338
- // Page-level style blocks (no component params)
2339
- const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
2847
+ const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
2340
2848
  const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
2341
2849
 
2342
2850
  const { componentScripts, pageScripts } = collectScripts(file, allDefs);
2343
2851
 
2852
+ // Collect all assigned variables for default-value warnings
2344
2853
  const assignedVars = new Set<string>();
2345
2854
  for (const s of file.scripts) {
2346
- const matches = s.raw.matchAll(/(\w+)\s*=/g);
2347
- for (const m of matches) assignedVars.add(m[1]);
2348
- }
2349
- for (const v of file.varDecls) {
2350
- if (v.value) assignedVars.add(v.name);
2855
+ for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+\-]?=)/g)) assignedVars.add(m[1]);
2351
2856
  }
2857
+ for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
2352
2858
 
2859
+ // Companion JS file (same name as .sinth)
2353
2860
  const companionJS = (() => {
2354
2861
  const base = absPath.replace(/\.sinth$/, ".js");
2355
2862
  return fs.existsSync(base) ? path.basename(base) : undefined;
2356
2863
  })();
2357
2864
 
2358
- // Convert CSS absolute paths to relative paths from the HTML output
2865
+ // Make CSS / JS links relative to the HTML output directory
2359
2866
  const relativeCssLinks = cssLinks.map(css => {
2360
2867
  const rel = path.relative(path.dirname(absPath), css).replace(/\\/g, "/");
2361
2868
  return rel.startsWith(".") ? rel : "./" + rel;
2362
2869
  });
2363
-
2364
- // Convert JS absolute paths to relative paths from the HTML output
2365
2870
  const relativeJsLinks = jsLinks.map(js => ({
2366
2871
  ...js,
2367
2872
  src: (() => {
@@ -2370,26 +2875,31 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2370
2875
  })(),
2371
2876
  }));
2372
2877
 
2373
- const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
2374
- const scriptTags: string[] = [];
2878
+ const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
2879
+
2880
+ // Build tree-shaken runtime
2881
+ const runtimeJS = buildRuntime({
2882
+ varDecls: allVarDecls,
2883
+ bodyHTML,
2884
+ logicBlocks: ctx.logicBlocks,
2885
+ mixedBlocks: ctx.mixedBlocks,
2886
+ assignedVars,
2887
+ });
2375
2888
 
2889
+ // Component-level script IIFEs
2890
+ const scriptTags: string[] = [];
2376
2891
  if (componentScripts.length > 0) {
2377
2892
  scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
2378
2893
  }
2379
- let logicScriptsRaw = "";
2380
- for (const s of pageScripts) {
2894
+
2895
+ // Page-level script blocks
2896
+ for (const s of pageScripts) {
2381
2897
  const extra = Object.entries(s.attrs)
2382
2898
  .map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
2383
2899
  .join(" ");
2384
- // Convert let/const to var for global accessibility
2385
- const globalRaw = s.raw.replace(/\b(let|const)\b/g, 'var');
2386
- // Check if this is an inline logic script (starts with "if (")
2387
- if (globalRaw.trim().startsWith("if (")) {
2388
- logicScriptsRaw += globalRaw + "\n";
2389
- } else {
2390
- scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalRaw}\n</script>`);
2391
- }
2392
- }
2900
+ const globalised = s.raw.replace(/\b(let|const)\b/g, "var");
2901
+ scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalised}\n</script>`);
2902
+ }
2393
2903
 
2394
2904
  const html = [
2395
2905
  "<!DOCTYPE html>",
@@ -2397,129 +2907,11 @@ for (const s of pageScripts) {
2397
2907
  head,
2398
2908
  `<body data-s="${hash}">`,
2399
2909
  bodyHTML,
2400
- `<script>
2401
- //Compiled using Sinth Logic
2402
- ${file.varDecls.map(v => {
2403
- if (!v.value) {
2404
- if (!assignedVars.has(v.name)) {
2405
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
2406
- const defaultVal = defaults[v.varType] || "undefined";
2407
- SinthWarning.emit(`Variable '${v.name}' is declared but never assigned. Using default value ${defaultVal}.`, v.loc);
2408
- }
2409
- if (v.varType === "str") return `var ${v.name} = "";`;
2410
- if (v.varType === "int") return `var ${v.name} = 0;`;
2411
- if (v.varType === "bool") return `var ${v.name} = false;`;
2412
- if (v.varType === "str[]") return `var ${v.name} = [];`;
2413
- return `var ${v.name};`;
2414
- }
2415
- const val = litToString(v.value);
2416
-
2417
- if (v.varType !== "str[]" && val.startsWith("__VAR__")) {
2418
- const refName = val.slice(7);
2419
- return `var ${v.name} = ${refName};`;
2420
- }
2421
-
2422
- if (val.startsWith("__ARR__")) {
2423
- return `var ${v.name} = ${val.slice(7)};`;
2424
- }
2425
-
2426
- if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2427
- return `var ${v.name} = ${val};`;
2428
- }).join("\n")}
2429
- ${(bodyHTML.includes('data-sinth-if') || bodyHTML.includes('data-sinth-for') || bodyHTML.includes('data-sinth-delay') || bodyHTML.includes('sinth-expr')) ? `
2430
- function sinthRender() {
2431
- const scrollX = window.scrollX;
2432
- const scrollY = window.scrollY;
2433
- ${(bodyHTML.includes('data-sinth-if') || bodyHTML.includes('data-sinth-for')) ? `
2434
- function processTemplates(root) {${bodyHTML.includes('data-sinth-if') ? `
2435
- root.querySelectorAll('template[data-sinth-if]').forEach(t => {
2436
- // Store original HTML on first pass
2437
- if (!t.dataset.sinthOriginal) {
2438
- t.dataset.sinthOriginal = t.innerHTML;
2439
- }
2440
- const cond = eval(t.dataset.sinthIf);
2441
- // Find any previously inserted content
2442
- const existing = t.parentNode.querySelector('[data-sinth-if-anchor="' + CSS.escape(t.dataset.sinthIf) + '"]');
2443
- if (cond) {
2444
- if (!existing) {
2445
- // Insert new content with anchor marker
2446
- const anchor = document.createElement('span');
2447
- anchor.style.display = 'none';
2448
- anchor.dataset.sinthIfAnchor = t.dataset.sinthIf;
2449
- const frag = document.createRange().createContextualFragment(t.innerHTML);
2450
- t.parentNode.insertBefore(anchor, t);
2451
- t.parentNode.insertBefore(frag, t);${bodyHTML.includes('sinth-expr') ? `
2452
- root.querySelectorAll('.sinth-expr').forEach(el => {
2453
- try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2454
- });` : ''}
2455
- }
2456
- } else {
2457
- // Remove inserted content if condition is false
2458
- if (existing) {
2459
- let next = existing.nextSibling;
2460
- while (next && next !== t && !(next.dataset && next.dataset.sinthIfAnchor)) {
2461
- const toRemove = next;
2462
- next = next.nextSibling;
2463
- toRemove.remove();
2464
- }
2465
- existing.remove();
2466
- }
2467
- // Also handle else
2468
- const elseT = t.nextElementSibling;
2469
- if (elseT && elseT.matches && elseT.matches('template[data-sinth-else]')) {
2470
- if (!elseT.dataset.sinthOriginal) {
2471
- elseT.dataset.sinthOriginal = elseT.innerHTML;
2472
- }
2473
- const elseAnchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + CSS.escape('else-' + t.dataset.sinthIf) + '"]');
2474
- const elseExisting = elseAnchor ? elseAnchor.nextSibling : null;
2475
- if (!elseExisting || elseExisting === t) {
2476
- const anchor = document.createElement('span');
2477
- anchor.style.display = 'none';
2478
- anchor.dataset.sinthIfAnchor = 'else-' + t.dataset.sinthIf;
2479
- const frag = document.createRange().createContextualFragment(elseT.innerHTML);
2480
- t.parentNode.insertBefore(anchor, t);
2481
- t.parentNode.insertBefore(frag, t);${bodyHTML.includes('sinth-expr') ? `
2482
- root.querySelectorAll('.sinth-expr').forEach(el => {
2483
- try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2484
- });` : ''}
2485
- }
2486
- }
2487
- }
2488
- });` : ''}
2489
- }
2490
- processTemplates(document.body);` : ''}${bodyHTML.includes('data-sinth-delay') ? `
2491
- setTimeout(() => {
2492
- document.querySelectorAll('[data-sinth-delay]').forEach(el => {
2493
- const delayMs = parseInt(el.dataset.sinthDelay) || 0;
2494
- if (delayMs > 0) {
2495
- setTimeout(() => { el.style.display = ''; }, delayMs);
2496
- }
2497
- });
2498
- document.querySelectorAll('[data-sinth-delay-expr]').forEach(el => {
2499
- try {
2500
- const delayMs = parseInt(eval(el.dataset.sinthDelayExpr)) || 0;
2501
- if (delayMs > 0) {
2502
- setTimeout(() => { el.style.display = ''; }, delayMs);
2503
- }
2504
- } catch(e) {}
2505
- });
2506
- }, 0);` : ''}
2507
-
2508
- ${logicScriptsRaw}
2509
- ${bodyHTML.includes('sinth-expr') ? `
2510
- document.querySelectorAll('.sinth-expr').forEach(el => {
2511
- try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2512
- });` : ''}
2513
- window.scrollTo(scrollX, scrollY);
2514
- }
2515
-
2516
- sinthRender();` : ''}
2517
-
2518
- </script>`,
2910
+ runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
2519
2911
  scriptTags.join("\n"),
2520
2912
  "</body>",
2521
2913
  "</html>",
2522
- ].join("\n");
2914
+ ].filter(Boolean).join("\n");
2523
2915
 
2524
2916
  return opts.minify ? minifyHTML(html) : html;
2525
2917
  }
@@ -2528,27 +2920,22 @@ function minifyHTML(html: string): string {
2528
2920
  return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
2529
2921
  }
2530
2922
 
2531
- // ═══════════════════════════════════════════════════════════
2532
- // SECTION 12: FILE DISCOVERY & ASSET COPY
2533
- // ═══════════════════════════════════════════════════════════
2923
+ // ═══════════════════════════════════════════════════════════════════════════
2924
+ // §15 FILE DISCOVERY & ASSET COPY
2925
+ // ═══════════════════════════════════════════════════════════════════════════
2534
2926
 
2535
- // === v0.1.0: findSinthPages skips outDir to prevent infinite watcher loops ===
2536
2927
  function findSinthPages(dir: string, outDir?: string): string[] {
2537
2928
  const results: string[] = [];
2538
2929
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
2539
2930
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
2540
2931
  const full = path.join(dir, entry.name);
2541
2932
  if (outDir && path.resolve(full) === path.resolve(outDir)) continue;
2542
- if (entry.isDirectory()) {
2543
- results.push(...findSinthPages(full, outDir));
2544
- } else if (entry.name.endsWith(".sinth")) {
2545
- results.push(full);
2546
- }
2933
+ if (entry.isDirectory()) results.push(...findSinthPages(full, outDir));
2934
+ else if (entry.name.endsWith(".sinth")) results.push(full);
2547
2935
  }
2548
2936
  return results;
2549
2937
  }
2550
2938
 
2551
- // === v0.1.0: Recursive directory copy for assets/ ===
2552
2939
  function copyDir(src: string, dest: string): void {
2553
2940
  if (!fs.existsSync(src)) return;
2554
2941
  fs.mkdirSync(dest, { recursive: true });
@@ -2560,21 +2947,20 @@ function copyDir(src: string, dest: string): void {
2560
2947
  }
2561
2948
  }
2562
2949
 
2563
- // ═══════════════════════════════════════════════════════════
2564
- // SECTION 13: DEV SERVER
2565
- // ═══════════════════════════════════════════════════════════
2950
+ // ═══════════════════════════════════════════════════════════════════════════
2951
+ // §16 DEV SERVER
2952
+ // ═══════════════════════════════════════════════════════════════════════════
2566
2953
 
2567
2954
  const LIVE_RELOAD_SCRIPT = `<script>
2568
2955
  (function(){
2569
- const es = new EventSource('/__sinth_sse__');
2570
- es.onmessage = () => location.reload();
2571
- es.onerror = () => setTimeout(() => location.reload(), 1000);
2956
+ var es = new EventSource('/__sinth_sse__');
2957
+ es.onmessage = function() { location.reload(); };
2958
+ es.onerror = function() { setTimeout(function() { location.reload(); }, 1000); };
2572
2959
  })();
2573
2960
  </script>`;
2574
2961
 
2575
- async function startDevServer(opts: CompileOptions & { port: number, files?: string[] }) {
2962
+ async function startDevServer(opts: CompileOptions & { port: number; files?: string[] }): Promise<void> {
2576
2963
  const clients: http.ServerResponse[] = [];
2577
- let debounce: ReturnType<typeof setTimeout> | null = null;
2578
2964
  const cache = new Map<string, string>();
2579
2965
 
2580
2966
  function notify(): void {
@@ -2590,12 +2976,9 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
2590
2976
  try {
2591
2977
  const html = compileFile(p, { ...opts, checkOnly: false });
2592
2978
  if (!html) continue;
2593
- const rel = path.relative(opts.projectRoot, p)
2594
- .replace(/\.sinth$/, ".html")
2595
- .replace(/\\/g, "/");
2979
+ const rel = path.relative(opts.projectRoot, p).replace(/\.sinth$/, ".html").replace(/\\/g, "/");
2596
2980
  const url = "/" + rel;
2597
2981
  cache.set(url, html + LIVE_RELOAD_SCRIPT);
2598
- // Also map root URL to index.html
2599
2982
  if (rel === "index.html" || rel.endsWith("/index.html")) {
2600
2983
  cache.set("/", html + LIVE_RELOAD_SCRIPT);
2601
2984
  }
@@ -2607,38 +2990,33 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
2607
2990
 
2608
2991
  compileAll();
2609
2992
 
2610
- // === v0.1.0: Watch ignores changes whose absolute path is inside outDir ===
2611
2993
  const resolvedOut = path.resolve(opts.outDir);
2612
- // Use fs.watch with fs.watchFile fallback for Windows reliability
2613
- let watchReady = false;
2994
+ let watchReady = false;
2614
2995
  try {
2615
2996
  fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
2616
2997
  if (!filename) return;
2617
2998
  const abs = path.resolve(opts.projectRoot, filename);
2618
2999
  if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut) return;
2619
3000
  process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
2620
- compileAll();
2621
- notify();
3001
+ compileAll(); notify();
2622
3002
  });
2623
3003
  watchReady = true;
2624
3004
  } catch {}
2625
3005
 
2626
3006
  if (!watchReady) {
2627
- // Fallback: poll for changes every 500ms
3007
+ const mtimes = new Map<string, number>();
2628
3008
  const poller = setInterval(() => {
2629
3009
  const pages = (opts.files && opts.files.length > 0)
2630
- ? opts.files
2631
- : findSinthPages(opts.projectRoot, opts.outDir);
3010
+ ? opts.files : findSinthPages(opts.projectRoot, opts.outDir);
2632
3011
  for (const p of pages) {
2633
- const stat = fs.statSync(p);
2634
- const key = p + ":" + stat.mtimeMs;
2635
- if (cache.get("__mtime__" + p) !== key) {
2636
- cache.set("__mtime__" + p, key);
2637
- process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${path.relative(opts.projectRoot, p)}\n`);
2638
- compileAll();
2639
- notify();
2640
- break;
2641
- }
3012
+ try {
3013
+ const mtime = fs.statSync(p).mtimeMs;
3014
+ if (mtimes.get(p) !== mtime) {
3015
+ mtimes.set(p, mtime);
3016
+ process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${path.relative(opts.projectRoot, p)}\n`);
3017
+ compileAll(); notify(); break;
3018
+ }
3019
+ } catch {}
2642
3020
  }
2643
3021
  }, 500);
2644
3022
  process.on("exit", () => clearInterval(poller));
@@ -2646,8 +3024,7 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
2646
3024
 
2647
3025
  const EXT_TYPES: Record<string, string> = {
2648
3026
  ".css": "text/css", ".js": "application/javascript",
2649
- ".png": "image/png", ".svg": "image/svg+xml",
2650
- ".ico": "image/x-icon",
3027
+ ".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon",
2651
3028
  ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
2652
3029
  ".gif": "image/gif", ".webp": "image/webp",
2653
3030
  ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf",
@@ -2657,31 +3034,17 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
2657
3034
  const server = http.createServer((req, res) => {
2658
3035
  const reqUrl = (req.url ?? "/").split("?")[0];
2659
3036
 
2660
- // SSE endpoint for live reload
2661
3037
  if (reqUrl === "/__sinth_sse__") {
2662
- res.writeHead(200, {
2663
- "Content-Type": "text/event-stream",
2664
- "Cache-Control": "no-cache",
2665
- "Connection": "keep-alive",
2666
- });
3038
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
2667
3039
  clients.push(res);
2668
- req.on("close", () => {
2669
- const i = clients.indexOf(res);
2670
- if (i !== -1) clients.splice(i, 1);
2671
- });
3040
+ req.on("close", () => { const i = clients.indexOf(res); if (i !== -1) clients.splice(i, 1); });
2672
3041
  return;
2673
3042
  }
2674
3043
 
2675
- // Serve cached compiled HTML
2676
3044
  const cached = cache.get(reqUrl) ??
2677
3045
  cache.get(reqUrl.endsWith("/") ? reqUrl + "index.html" : reqUrl + ".html");
2678
- if (cached) {
2679
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2680
- res.end(cached);
2681
- return;
2682
- }
3046
+ if (cached) { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(cached); return; }
2683
3047
 
2684
- // Serve static files (assets, CSS, fonts, etc.)
2685
3048
  let filePath = path.join(opts.projectRoot, reqUrl);
2686
3049
  if (reqUrl.endsWith("/")) filePath = path.join(filePath, "index.html");
2687
3050
  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
@@ -2691,8 +3054,7 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
2691
3054
  return;
2692
3055
  }
2693
3056
 
2694
- res.writeHead(404, { "Content-Type": "text/plain" });
2695
- res.end("404 Not Found");
3057
+ res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 Not Found");
2696
3058
  });
2697
3059
 
2698
3060
  server.listen(opts.port, () => {
@@ -2702,9 +3064,9 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
2702
3064
  });
2703
3065
  }
2704
3066
 
2705
- // ═══════════════════════════════════════════════════════════
2706
- // SECTION 14: CLI ENTRY POINT
2707
- // ═══════════════════════════════════════════════════════════
3067
+ // ═══════════════════════════════════════════════════════════════════════════
3068
+ // §17 CLI ENTRY POINT
3069
+ // ═══════════════════════════════════════════════════════════════════════════
2708
3070
 
2709
3071
  function loadConfig(root: string): Record<string, unknown> {
2710
3072
  const cfgPath = path.join(root, "sinth.config.json");
@@ -2717,8 +3079,8 @@ function loadConfig(root: string): Record<string, unknown> {
2717
3079
 
2718
3080
  async function main(): Promise<void> {
2719
3081
  const [,, command, ...args] = process.argv;
2720
- const cwd = process.cwd();
2721
- const cfg = loadConfig(cwd);
3082
+ const cwd = process.cwd();
3083
+ const cfg = loadConfig(cwd);
2722
3084
 
2723
3085
  const outDirIdx = args.indexOf("--out");
2724
3086
  const outDir = outDirIdx !== -1 ? args[outDirIdx + 1] : (cfg.outDir as string | undefined) ?? path.join(cwd, "dist");
@@ -2727,7 +3089,6 @@ async function main(): Promise<void> {
2727
3089
  const minify = args.includes("--prod") || Boolean(cfg.minify);
2728
3090
  const libraryPaths = (cfg.libraryPaths as string[] | undefined) ?? [path.join(cwd, "libraries")];
2729
3091
 
2730
- // Remove flag values from args so they don't get treated as .sinth files
2731
3092
  const flagValues = new Set<string>();
2732
3093
  if (outDirIdx !== -1) flagValues.add(args[outDirIdx + 1]);
2733
3094
  if (portIdx !== -1) flagValues.add(args[portIdx + 1]);
@@ -2738,18 +3099,14 @@ async function main(): Promise<void> {
2738
3099
  switch (command) {
2739
3100
  case "build": {
2740
3101
  const nonSinth = cleanArgs.filter(a => !a.endsWith(".sinth"));
2741
- if (nonSinth.length > 0) {
2742
- process.stdout.write(`\x1b[33mSkipping non-.sinth files:\x1b[0m ${nonSinth.join(", ")}\n`);
2743
- }
3102
+ if (nonSinth.length > 0) process.stdout.write(`\x1b[33mSkipping non-.sinth files:\x1b[0m ${nonSinth.join(", ")}\n`);
3103
+
2744
3104
  const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
2745
- const pages = fileArgs.length > 0
3105
+ const pages = fileArgs.length > 0
2746
3106
  ? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
2747
3107
  : findSinthPages(cwd, outDir);
2748
3108
 
2749
- if (pages.length === 0) {
2750
- process.stdout.write("No .sinth files found.\n");
2751
- process.exit(0);
2752
- }
3109
+ if (pages.length === 0) { process.stdout.write("No .sinth files found.\n"); process.exit(0); }
2753
3110
 
2754
3111
  let hadError = false, built = 0;
2755
3112
 
@@ -2769,22 +3126,21 @@ async function main(): Promise<void> {
2769
3126
  }
2770
3127
  }
2771
3128
 
2772
- // === v0.1.0: Copy assets/ to outDir/assets/ ===
2773
- const assetsIn = path.join(cwd, "assets");
2774
- const assetsOut = path.join(outDir, "assets");
3129
+ // Copy assets/
3130
+ const assetsIn = path.join(cwd, "assets"), assetsOut = path.join(outDir, "assets");
2775
3131
  if (fs.existsSync(assetsIn)) {
2776
3132
  copyDir(assetsIn, assetsOut);
2777
3133
  process.stdout.write(` \x1b[32m✓\x1b[0m assets/ → ${path.relative(cwd, assetsOut)}/\n`);
2778
3134
  }
2779
3135
 
2780
- const libIn = path.join(cwd, "libraries");
2781
- const libOut = path.join(outDir, "libraries");
3136
+ // Copy libraries/ (without .sinth / .html files)
3137
+ const libIn = path.join(cwd, "libraries"), libOut = path.join(outDir, "libraries");
2782
3138
  if (fs.existsSync(libIn)) {
2783
3139
  copyDir(libIn, libOut);
2784
- const cleanFiles = fs.readdirSync(libOut, { recursive: true }) as string[];
2785
- for (const f of cleanFiles) {
3140
+ const libFiles = fs.readdirSync(libOut, { recursive: true }) as string[];
3141
+ for (const f of libFiles) {
2786
3142
  if (f.endsWith(".sinth") || f.endsWith(".html")) {
2787
- fs.unlinkSync(path.join(libOut, f));
3143
+ try { fs.unlinkSync(path.join(libOut, f)); } catch {}
2788
3144
  }
2789
3145
  }
2790
3146
  process.stdout.write(` \x1b[32m✓\x1b[0m libraries/ → ${path.relative(cwd, libOut)}/\n`);
@@ -2797,7 +3153,7 @@ async function main(): Promise<void> {
2797
3153
 
2798
3154
  case "dev": {
2799
3155
  const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
2800
- const files = fileArgs.length > 0
3156
+ const files = fileArgs.length > 0
2801
3157
  ? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
2802
3158
  : undefined;
2803
3159
  await startDevServer({ ...opts, port, files });
@@ -2806,8 +3162,8 @@ async function main(): Promise<void> {
2806
3162
 
2807
3163
  case "check": {
2808
3164
  opts.checkOnly = true;
2809
- const pages = findSinthPages(cwd, outDir);
2810
- let hadError = false;
3165
+ const pages = findSinthPages(cwd, outDir);
3166
+ let hadError = false;
2811
3167
  for (const p of pages) {
2812
3168
  try {
2813
3169
  compileFile(p, opts);
@@ -2821,51 +3177,68 @@ async function main(): Promise<void> {
2821
3177
  break;
2822
3178
  }
2823
3179
 
2824
- // === v0.1.0: sinth version command ===
2825
3180
  case "version":
2826
3181
  case "--version":
2827
3182
  case "-v": {
2828
- const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf-8"));
2829
- process.stdout.write(`Sinth Compiler v${pkg.version}\n`);
3183
+ const pkgPath = path.join(__dirname, "..", "package.json");
3184
+ if (fs.existsSync(pkgPath)) {
3185
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
3186
+ process.stdout.write(`Sinth Compiler v${pkg.version}\n`);
3187
+ } else {
3188
+ process.stdout.write("Sinth Compiler v1.0.0\n");
3189
+ }
2830
3190
  break;
2831
3191
  }
2832
3192
 
2833
3193
  case "init": {
2834
- const projectName = args[0] || "my-sinth-project";
2835
- const projectDir = path.resolve(cwd, projectName);
2836
- scaffoldProject(projectDir);
3194
+ const projectName = cleanArgs[0] || "my-sinth-project";
3195
+ scaffoldProject(path.resolve(cwd, projectName));
2837
3196
  break;
2838
3197
  }
2839
3198
 
2840
3199
  default: {
2841
3200
  process.stdout.write(`
2842
- \x1b[1mSinth Compiler v0.1.0\x1b[0m
3201
+ \x1b[1mSinth Compiler v1.0.0\x1b[0m
2843
3202
 
2844
3203
  \x1b[1mCommands:\x1b[0m
2845
- sinth build [--out ./dist] [--prod] Compile all .sinth pages + copy assets/
2846
- sinth dev [--port 3000] Start dev server with live reload
2847
- sinth check Lint without emitting files
2848
- sinth init Scaffold a new project
2849
- sinth version Print version
3204
+ sinth build [files] [--out ./dist] [--prod] Compile .sinth pages
3205
+ sinth dev [files] [--port 3000] Live-reload dev server
3206
+ sinth check Lint without emitting
3207
+ sinth init [name] Scaffold a new project
3208
+ sinth version Print version
2850
3209
 
2851
3210
  \x1b[1mConfig:\x1b[0m sinth.config.json
2852
3211
  { "outDir": "./dist", "libraryPaths": ["./libraries"], "minify": false }
3212
+
3213
+ \x1b[1mSinth Style v1.0.0:\x1b[0m
3214
+ style Paragraph { color: "red"; onHover { color: "blue" } }
3215
+ style { Hero { padding: "4rem"; media(maxWidth: "600px") { padding: "1rem" } } }
3216
+ Paragraph(color: "red", fontSize: "1.2rem") { "Inline shorthand" }
3217
+
3218
+ \x1b[1mMixed if/else:\x1b[0m
3219
+ if guess == target {
3220
+ result = "Correct!"
3221
+ Paragraph(id: "msg") { result }
3222
+ } else {
3223
+ result = "Wrong!"
3224
+ Paragraph(id: "msg") { "Nope!" }
3225
+ }
2853
3226
  `);
2854
3227
  break;
2855
3228
  }
2856
3229
  }
2857
3230
  }
2858
3231
 
2859
- // ── Project scaffolding ───────────────────────────────────────────────────────
3232
+ // ═══════════════════════════════════════════════════════════════════════════
3233
+ // §18 PROJECT SCAFFOLDING
3234
+ // ═══════════════════════════════════════════════════════════════════════════
2860
3235
 
2861
3236
  function scaffoldProject(root: string): void {
2862
3237
  for (const d of ["pages", "components", "styles", "libraries", "assets"]) {
2863
3238
  fs.mkdirSync(path.join(root, d), { recursive: true });
2864
3239
  }
2865
3240
 
2866
- // Main page
2867
3241
  fs.writeFileSync(path.join(root, "pages", "index.sinth"), `-- My Sinth Site
2868
-
2869
3242
  page
2870
3243
 
2871
3244
  import "../components/Navbar.sinth"
@@ -2873,32 +3246,36 @@ import css "../styles/reset.css"
2873
3246
 
2874
3247
  title = "My Site"
2875
3248
  fav = "assets/favicon.ico"
2876
- descr = "Built with Sinth."
3249
+ descr = "Built with Sinth v1.0.0."
3250
+
3251
+ var int score = 0
3252
+ var str message = "Click to begin"
2877
3253
 
2878
3254
  Navbar
2879
3255
 
2880
3256
  Hero {
2881
3257
  Heading(level: 1) { "Welcome to Sinth" }
2882
3258
  Paragraph { "A declarative, component-based web UI language." }
2883
- Button(onClick: "handleCTA") { "Get Started" }
3259
+ Button(onClick: "handleClick") { "Get Started" }
3260
+ Paragraph(id: "score-display") { message }
2884
3261
  }
2885
3262
 
2886
3263
  Main {
2887
3264
  Section {
2888
3265
  Heading(level: 2) { "Features" }
2889
3266
  CardGrid {
2890
- -- Add cards here
3267
+ -- Add Card components here
2891
3268
  }
2892
3269
  }
2893
3270
  }
2894
3271
 
2895
3272
  style {
2896
- Hero {
3273
+ section.hero {
2897
3274
  padding: "4rem 2rem"
2898
3275
  textAlign: "center"
2899
3276
  backgroundColor: "#f0f4ff"
2900
3277
  }
2901
- Main {
3278
+ main {
2902
3279
  maxWidth: "1100px"
2903
3280
  margin: "0 auto"
2904
3281
  padding: "2rem"
@@ -2906,13 +3283,14 @@ style {
2906
3283
  }
2907
3284
 
2908
3285
  script {
2909
- function handleCTA() {
2910
- alert("Hello from Sinth!")
3286
+ function handleClick() {
3287
+ score += 1
3288
+ message = "Score: " + score
3289
+ sinthRender()
2911
3290
  }
2912
3291
  }
2913
3292
  `);
2914
3293
 
2915
- // Navbar component
2916
3294
  fs.writeFileSync(path.join(root, "components", "Navbar.sinth"), `-- Navbar component
2917
3295
 
2918
3296
  component Navbar {
@@ -2927,7 +3305,7 @@ component Navbar {
2927
3305
  }
2928
3306
 
2929
3307
  style {
2930
- Header {
3308
+ header {
2931
3309
  display: "flex"
2932
3310
  alignItems: "center"
2933
3311
  padding: "1rem 2rem"
@@ -2953,12 +3331,11 @@ component Navbar {
2953
3331
  }
2954
3332
  `);
2955
3333
 
2956
- // Card component
2957
3334
  fs.writeFileSync(path.join(root, "components", "Card.sinth"), `-- Card component
2958
3335
 
2959
3336
  component Card(title, color = "blue") {
2960
3337
  Div(class: "card") {
2961
- Heading(level: 2) { "$title" }
3338
+ Heading(level: 3) { "$title" }
2962
3339
  Div(class: "card-body") { "$slot" }
2963
3340
  }
2964
3341
 
@@ -2967,9 +3344,11 @@ component Card(title, color = "blue") {
2967
3344
  backgroundColor: "#f7f7f7"
2968
3345
  borderRadius: "1rem"
2969
3346
  padding: "1.5rem"
2970
- textAlign: "center"
2971
3347
  marginBottom: "1rem"
2972
3348
  }
3349
+ .card:hover {
3350
+ boxShadow: "0 4px 16px rgba(0,0,0,0.1)"
3351
+ }
2973
3352
  .card-body {
2974
3353
  marginTop: "0.75rem"
2975
3354
  }
@@ -2977,41 +3356,30 @@ component Card(title, color = "blue") {
2977
3356
  }
2978
3357
  `);
2979
3358
 
2980
- // Reset CSS
2981
- fs.writeFileSync(
2982
- path.join(root, "styles", "reset.css"),
2983
- `*, *::before, *::after { box-sizing: border-box; }\nbody { margin: 0; font-family: system-ui, sans-serif; line-height: 1.6; }\nimg { max-width: 100%; display: block; }\n`,
3359
+ fs.writeFileSync(path.join(root, "styles", "reset.css"),
3360
+ `*, *::before, *::after { box-sizing: border-box; }\nbody { margin: 0; font-family: system-ui, sans-serif; line-height: 1.6; }\nimg { max-width: 100%; display: block; }\n`
2984
3361
  );
2985
3362
 
2986
- // sinth.config.json
2987
- fs.writeFileSync(
2988
- path.join(root, "sinth.config.json"),
2989
- JSON.stringify({ outDir: "./dist", libraryPaths: ["./libraries"], minify: false }, null, 2),
3363
+ fs.writeFileSync(path.join(root, "sinth.config.json"),
3364
+ JSON.stringify({ outDir: "./dist", libraryPaths: ["./libraries"], minify: false }, null, 2)
2990
3365
  );
2991
3366
 
2992
- // .gitignore
2993
3367
  fs.writeFileSync(path.join(root, ".gitignore"), "dist/\nnode_modules/\n");
2994
3368
 
2995
- // package.json
2996
- fs.writeFileSync(
2997
- path.join(root, "package.json"),
2998
- JSON.stringify({
2999
- name: "my-sinth-site",
3000
- version: "1.0.0",
3001
- scripts: {
3002
- build: "sinth build",
3003
- dev: "sinth dev",
3004
- },
3005
- devDependencies: { "ts-node": "^10.0.0", typescript: "^5.0.0", sass: "^1.70.0" },
3006
- }, null, 2),
3007
- );
3369
+ fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({
3370
+ name: path.basename(root).toLowerCase().replace(/\s+/g, "-"),
3371
+ version: "1.0.0",
3372
+ scripts: { build: "sinth build", dev: "sinth dev" },
3373
+ devDependencies: { "ts-node": "^10.0.0", typescript: "^5.0.0", sass: "^1.70.0" },
3374
+ }, null, 2));
3008
3375
 
3009
3376
  process.stdout.write(`
3010
- \x1b[32m✓ Sinth project scaffolded!\x1b[0m
3377
+ \x1b[32m✓ Sinth project scaffolded at ${path.basename(root)}/\x1b[0m
3011
3378
 
3012
3379
  \x1b[1mNext steps:\x1b[0m
3013
- sinth dev ./pages/index.sinth
3014
- sinth build or sinth build ./index.sinth
3380
+ cd ${path.basename(root)}
3381
+ sinth dev
3382
+ sinth build
3015
3383
  `);
3016
3384
  }
3017
3385