@yannosay/sinth 0.4.0 → 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.
- package/package.json +1 -1
- package/src/sinth.ts +1603 -1178
package/src/sinth.ts
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Sinth Compiler
|
|
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
|
-
//
|
|
10
|
-
//
|
|
10
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
11
|
+
// §1 TYPES & AST DEFINITIONS
|
|
12
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
11
13
|
|
|
12
14
|
interface Loc { file: string; line: number; col: number }
|
|
13
15
|
|
|
14
|
-
//
|
|
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,
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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:
|
|
107
|
-
customEls:
|
|
108
|
-
cssLinks:
|
|
109
|
-
jsLinks:
|
|
110
|
-
scopeHash:
|
|
111
|
-
pageFile:
|
|
112
|
-
extraCSS:
|
|
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
|
-
//
|
|
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 →
|
|
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
|
-
//
|
|
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,21 +259,24 @@ 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
|
-
|
|
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 === "
|
|
277
|
+
if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
|
|
278
|
+
tokens.push(this.single(TT.OP_MINUS, loc)); continue;
|
|
279
|
+
}
|
|
259
280
|
|
|
260
281
|
if (ch === "{") {
|
|
261
282
|
if (this.rawBlockPending) {
|
|
@@ -275,12 +296,11 @@ export class Lexer {
|
|
|
275
296
|
|
|
276
297
|
if (this.isIdentStart(ch)) {
|
|
277
298
|
const tok = this.readIdent(loc);
|
|
278
|
-
// === v0.1.0: Also set rawBlockPending for component, custom-element, custom ===
|
|
279
299
|
if (
|
|
280
|
-
tok.type === TT.KW_STYLE
|
|
281
|
-
tok.type === TT.KW_SCRIPT
|
|
282
|
-
tok.type === TT.KW_COMPONENT
|
|
283
|
-
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 ||
|
|
284
304
|
tok.type === TT.KW_CUSTOM
|
|
285
305
|
) {
|
|
286
306
|
this.rawBlockPending = true;
|
|
@@ -303,7 +323,7 @@ export class Lexer {
|
|
|
303
323
|
// Sinth comments: -- line or --[ nestable block ]--
|
|
304
324
|
if (ch === "-" && this.src[this.pos + 1] === "-") {
|
|
305
325
|
if (this.src[this.pos + 2] === "[") {
|
|
306
|
-
this.adv(); this.adv(); this.adv();
|
|
326
|
+
this.adv(); this.adv(); this.adv();
|
|
307
327
|
let depth = 1;
|
|
308
328
|
while (this.pos < this.src.length && depth > 0) {
|
|
309
329
|
if (this.src[this.pos] === "-" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "[") {
|
|
@@ -324,7 +344,6 @@ export class Lexer {
|
|
|
324
344
|
}
|
|
325
345
|
}
|
|
326
346
|
|
|
327
|
-
/** Consume a raw { ... } block tracking nested braces and skipping strings/comments. */
|
|
328
347
|
private readRawBlock(loc: Loc): Token {
|
|
329
348
|
this.adv(); // consume '{'
|
|
330
349
|
const start = this.pos;
|
|
@@ -332,7 +351,6 @@ export class Lexer {
|
|
|
332
351
|
|
|
333
352
|
while (this.pos < this.src.length && depth > 0) {
|
|
334
353
|
const ch = this.src[this.pos];
|
|
335
|
-
|
|
336
354
|
if (ch === '"' || ch === "'" || ch === "`") { this.skipRawString(ch); continue; }
|
|
337
355
|
if (ch === "/" && this.src[this.pos + 1] === "/") {
|
|
338
356
|
while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
|
|
@@ -341,18 +359,14 @@ export class Lexer {
|
|
|
341
359
|
if (ch === "/" && this.src[this.pos + 1] === "*") {
|
|
342
360
|
this.adv(); this.adv();
|
|
343
361
|
while (this.pos < this.src.length - 1 &&
|
|
344
|
-
!(this.src[this.pos] === "*" && this.src[this.pos + 1] === "/")) {
|
|
345
|
-
this.adv();
|
|
346
|
-
}
|
|
362
|
+
!(this.src[this.pos] === "*" && this.src[this.pos + 1] === "/")) { this.adv(); }
|
|
347
363
|
this.adv(); this.adv();
|
|
348
364
|
continue;
|
|
349
365
|
}
|
|
350
|
-
|
|
351
366
|
if (ch === "{") { depth++; this.adv(); }
|
|
352
367
|
else if (ch === "}") {
|
|
353
368
|
depth--;
|
|
354
369
|
if (depth > 0) this.adv();
|
|
355
|
-
// else: stop, leaving pos AT the closing }
|
|
356
370
|
} else {
|
|
357
371
|
this.adv();
|
|
358
372
|
}
|
|
@@ -370,7 +384,7 @@ export class Lexer {
|
|
|
370
384
|
if (c === "\\") { this.adv(); this.adv(); continue; }
|
|
371
385
|
if (c === quote) { this.adv(); return; }
|
|
372
386
|
if (quote === "`" && c === "$" && this.src[this.pos + 1] === "{") {
|
|
373
|
-
this.adv(); this.adv();
|
|
387
|
+
this.adv(); this.adv();
|
|
374
388
|
let d = 1;
|
|
375
389
|
while (this.pos < this.src.length && d > 0) {
|
|
376
390
|
if (this.src[this.pos] === "{") d++;
|
|
@@ -423,7 +437,7 @@ export class Lexer {
|
|
|
423
437
|
}
|
|
424
438
|
}
|
|
425
439
|
if (this.pos >= this.src.length) throw new SinthError("Unterminated string literal", loc);
|
|
426
|
-
this.adv();
|
|
440
|
+
this.adv();
|
|
427
441
|
return { type: TT.STRING, value: result, loc };
|
|
428
442
|
}
|
|
429
443
|
|
|
@@ -440,7 +454,6 @@ export class Lexer {
|
|
|
440
454
|
|
|
441
455
|
private readIdent(loc: Loc): Token {
|
|
442
456
|
let s = "";
|
|
443
|
-
// === v0.1.0: isIdentCont includes '-' so "custom-element" is read as one token ===
|
|
444
457
|
while (this.pos < this.src.length && this.isIdentCont(this.src[this.pos])) {
|
|
445
458
|
s += this.src[this.pos]; this.adv();
|
|
446
459
|
}
|
|
@@ -461,157 +474,190 @@ export class Lexer {
|
|
|
461
474
|
private loc(): Loc { return { file: this.file, line: this.line, col: this.col }; }
|
|
462
475
|
private isDigit(c: string) { return c >= "0" && c <= "9"; }
|
|
463
476
|
private isIdentStart(c: string) { return /[a-zA-Z_\u00C0-\uFFFF]/.test(c); }
|
|
464
|
-
// === v0.1.0: '-' allowed in identifiers so "custom-element" is a single token ===
|
|
465
477
|
private isIdentCont(c: string) { return /[a-zA-Z0-9_\-\u00C0-\uFFFF]/.test(c); }
|
|
466
478
|
}
|
|
467
479
|
|
|
468
|
-
//
|
|
469
|
-
//
|
|
470
|
-
//
|
|
480
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
481
|
+
// §4 PARSER
|
|
482
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
471
483
|
|
|
472
484
|
export class Parser {
|
|
473
|
-
private pos
|
|
485
|
+
private pos = 0;
|
|
474
486
|
private loopVar: string | null = null;
|
|
487
|
+
/** Accumulated var declarations for type-checking in bodies. */
|
|
488
|
+
private _varDecls: VarDeclaration[] = [];
|
|
475
489
|
|
|
476
490
|
constructor(private tokens: Token[], private file: string) {}
|
|
477
491
|
|
|
492
|
+
// ── Top-level file parse ────────────────────────────────────────────────
|
|
493
|
+
|
|
478
494
|
parse(): SinthFile {
|
|
479
|
-
const loc = this.peek().loc;
|
|
480
495
|
let isPage = false;
|
|
481
|
-
const imports: ImportNode[]
|
|
482
|
-
const meta: MetaEntry[]
|
|
483
|
-
const defs: CompDef[]
|
|
484
|
-
const uses: CompUse[]
|
|
485
|
-
const styles: StyleBlock[]
|
|
486
|
-
const scripts: ScriptBlock[]
|
|
487
|
-
const customEls: CustomElDecl[]
|
|
488
|
-
const varDecls:
|
|
489
|
-
|
|
490
|
-
|
|
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
|
+
|
|
491
506
|
if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
|
|
492
507
|
|
|
493
|
-
// 2. Imports — must come before metadata
|
|
494
508
|
while (this.check(TT.KW_IMPORT)) imports.push(this.parseImport());
|
|
495
509
|
|
|
496
|
-
// 3. Metadata — key = value pairs (lexer has already stripped comments/whitespace)
|
|
497
510
|
while (this.isMetaStart()) {
|
|
498
|
-
const keyName = this.tokens[this.pos].value;
|
|
499
|
-
if (varDecls.some(v => v.name === keyName)) {
|
|
500
|
-
break;
|
|
501
|
-
}
|
|
502
511
|
const entry = this.parseMeta();
|
|
503
512
|
meta.push(entry);
|
|
504
513
|
if (entry.key === "title") isPage = true;
|
|
505
514
|
}
|
|
506
515
|
|
|
507
|
-
//
|
|
508
|
-
// 4a. Variable declarations (v0.1.0 logic)
|
|
516
|
+
// Variable declarations
|
|
509
517
|
while (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
510
518
|
const vd = this.parseVarDeclaration();
|
|
511
|
-
if (vd) varDecls.push(vd);
|
|
519
|
+
if (vd) { varDecls.push(vd); this._varDecls.push(vd); }
|
|
512
520
|
}
|
|
513
|
-
// Store var declarations for type checking in inline logic
|
|
514
|
-
(this as any)._varDecls = varDecls;
|
|
515
521
|
|
|
516
|
-
//
|
|
522
|
+
// Body
|
|
517
523
|
while (!this.check(TT.EOF)) {
|
|
518
|
-
if (this.check(TT.KW_COMPONENT))
|
|
519
|
-
else if (this.check(TT.KW_STYLE))
|
|
520
|
-
else if (this.check(TT.KW_SCRIPT))
|
|
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()); }
|
|
521
527
|
else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
|
|
522
|
-
else if (this.check(TT.IDENT)) {
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
const identName = this.consume(TT.IDENT).value;
|
|
526
|
-
if (this.check(TT.EQUALS)) {
|
|
527
|
-
// It's an assignment: variableName = value
|
|
528
|
-
this.consume(TT.EQUALS);
|
|
529
|
-
const expr = this.parseExpression();
|
|
530
|
-
if (expr) {
|
|
531
|
-
// Wrap as inline script assignment
|
|
532
|
-
const jsExpr = compileExprToJS(expr);
|
|
533
|
-
const scriptBlock: ScriptBlock = {
|
|
534
|
-
raw: `${identName} = ${jsExpr};\nsinthRender();`,
|
|
535
|
-
attrs: {},
|
|
536
|
-
loc: this.peek().loc,
|
|
537
|
-
};
|
|
538
|
-
scripts.push(scriptBlock);
|
|
539
|
-
continue;
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
// Not an assignment, revert and parse as component usage
|
|
543
|
-
this.pos = savedPos;
|
|
544
|
-
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);
|
|
545
531
|
}
|
|
546
|
-
else
|
|
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 });
|
|
547
568
|
}
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
548
571
|
|
|
549
|
-
|
|
550
|
-
|
|
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
|
+
);
|
|
551
580
|
}
|
|
581
|
+
|
|
552
582
|
return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
|
|
553
583
|
}
|
|
554
584
|
|
|
555
|
-
|
|
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 ──────────────────────────────────────────────────────────────
|
|
556
609
|
|
|
557
610
|
private parseImport(): ImportNode {
|
|
558
611
|
const loc = this.consume(TT.KW_IMPORT).loc;
|
|
559
|
-
|
|
560
612
|
if (this.check(TT.KW_CSS)) {
|
|
561
613
|
this.consume(TT.KW_CSS);
|
|
562
614
|
return { kind: "css", path: this.consume(TT.STRING).value, loc };
|
|
563
615
|
}
|
|
564
|
-
|
|
565
616
|
if (this.check(TT.STRING)) {
|
|
566
617
|
return { kind: "sinth", path: this.consume(TT.STRING).value, loc };
|
|
567
618
|
}
|
|
568
|
-
|
|
569
619
|
if (this.check(TT.IDENT)) {
|
|
570
620
|
const name = this.consume(TT.IDENT).value;
|
|
571
621
|
let alias: string | undefined;
|
|
572
622
|
if (this.check(TT.KW_AS)) { this.consume(TT.KW_AS); alias = this.consume(TT.IDENT).value; }
|
|
573
623
|
return { kind: "js", name, alias, loc };
|
|
574
624
|
}
|
|
575
|
-
|
|
576
625
|
throw new SinthError(`Expected import path, library name, or 'css'`, loc);
|
|
577
626
|
}
|
|
578
627
|
|
|
579
|
-
// ── Metadata
|
|
628
|
+
// ── Metadata ─────────────────────────────────────────────────────────────
|
|
580
629
|
|
|
581
630
|
private isMetaStart(): boolean {
|
|
582
|
-
// Metadata: IDENT followed by EQUALS (e.g. title = "My Site")
|
|
583
|
-
// Component usage: IDENT followed by LPAREN or LBRACE
|
|
584
631
|
if (!this.check(TT.IDENT)) return false;
|
|
585
632
|
return this.tokens[this.pos + 1]?.type === TT.EQUALS;
|
|
586
633
|
}
|
|
587
634
|
|
|
588
|
-
|
|
635
|
+
private parseMeta(): MetaEntry {
|
|
589
636
|
const loc = this.peek().loc;
|
|
590
637
|
const key = this.consume(TT.IDENT).value;
|
|
591
638
|
this.consume(TT.EQUALS);
|
|
592
639
|
return { key, value: this.parseLiteral(), loc };
|
|
593
640
|
}
|
|
594
641
|
|
|
595
|
-
//
|
|
642
|
+
// ── Variable declarations ────────────────────────────────────────────────
|
|
643
|
+
|
|
596
644
|
private parseVarDeclaration(): VarDeclaration | null {
|
|
597
645
|
const loc = this.peek().loc;
|
|
598
|
-
this.consume(TT.IDENT); // 'var'
|
|
646
|
+
this.consume(TT.IDENT); // consume 'var'
|
|
599
647
|
|
|
600
648
|
const typeTok = this.consume(TT.IDENT);
|
|
601
649
|
let typeStr = typeTok.value;
|
|
602
650
|
if (this.check(TT.LBRACKET) && this.tokens[this.pos + 1]?.type === TT.RBRACKET) {
|
|
603
|
-
this.consume(TT.LBRACKET);
|
|
604
|
-
this.consume(TT.RBRACKET);
|
|
651
|
+
this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
|
|
605
652
|
typeStr = "str[]";
|
|
606
653
|
}
|
|
607
|
-
|
|
608
654
|
if (!["int", "str", "bool", "str[]"].includes(typeStr)) {
|
|
609
|
-
throw new SinthError(`Unknown type '${typeStr}'. Expected int, str, bool,
|
|
655
|
+
throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[]`, typeTok.loc);
|
|
610
656
|
}
|
|
611
657
|
|
|
612
658
|
const nameTok = this.consume(TT.IDENT);
|
|
613
659
|
let val: Literal | null = null;
|
|
614
|
-
|
|
660
|
+
|
|
615
661
|
if (this.check(TT.EQUALS)) {
|
|
616
662
|
this.consume(TT.EQUALS);
|
|
617
663
|
if (this.check(TT.LBRACKET)) {
|
|
@@ -624,174 +670,204 @@ export class Parser {
|
|
|
624
670
|
}
|
|
625
671
|
}
|
|
626
672
|
|
|
627
|
-
return {
|
|
628
|
-
kind: "var",
|
|
629
|
-
name: nameTok.value,
|
|
630
|
-
varType: typeStr as VarType,
|
|
631
|
-
value: val,
|
|
632
|
-
loc,
|
|
633
|
-
};
|
|
673
|
+
return { kind: "var", name: nameTok.value, varType: typeStr as VarType, value: val, loc };
|
|
634
674
|
}
|
|
635
675
|
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
const items:
|
|
639
|
-
|
|
676
|
+
private parseArrayLiteral(): Literal {
|
|
677
|
+
this.consume(TT.LBRACKET);
|
|
678
|
+
const items: any[] = [];
|
|
640
679
|
while (!this.check(TT.RBRACKET) && !this.check(TT.EOF)) {
|
|
641
|
-
if (this.check(TT.
|
|
680
|
+
if (this.check(TT.LBRACE)) {
|
|
681
|
+
items.push(this.parseObjectLiteral());
|
|
682
|
+
} else if (this.check(TT.STRING)) {
|
|
642
683
|
items.push(this.consume(TT.STRING).value);
|
|
643
684
|
} else if (this.check(TT.NUMBER)) {
|
|
644
|
-
items.push(this.consume(TT.NUMBER).value);
|
|
685
|
+
items.push(parseFloat(this.consume(TT.NUMBER).value));
|
|
645
686
|
} else if (this.check(TT.BOOL_TRUE)) {
|
|
646
687
|
this.consume(TT.BOOL_TRUE);
|
|
647
|
-
items.push(
|
|
688
|
+
items.push(true);
|
|
648
689
|
} else if (this.check(TT.BOOL_FALSE)) {
|
|
649
690
|
this.consume(TT.BOOL_FALSE);
|
|
650
|
-
items.push(
|
|
651
|
-
}
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
this.consume(TT.COMMA);
|
|
655
|
-
} else {
|
|
656
|
-
break;
|
|
691
|
+
items.push(false);
|
|
692
|
+
} else if (this.check(TT.NULL_LIT)) {
|
|
693
|
+
this.consume(TT.NULL_LIT);
|
|
694
|
+
items.push(null);
|
|
657
695
|
}
|
|
696
|
+
if (this.check(TT.COMMA)) this.consume(TT.COMMA); else break;
|
|
658
697
|
}
|
|
659
|
-
|
|
660
698
|
this.consume(TT.RBRACKET);
|
|
661
699
|
return { kind: "str", value: `__ARR__${JSON.stringify(items)}` };
|
|
662
700
|
}
|
|
663
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
|
+
}
|
|
664
729
|
|
|
665
|
-
// ── Expression parsing
|
|
666
|
-
|
|
730
|
+
// ── Expression parsing ───────────────────────────────────────────────────
|
|
731
|
+
|
|
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 {
|
|
667
742
|
const tok = this.peek();
|
|
668
|
-
|
|
743
|
+
|
|
669
744
|
// Unary 'not'
|
|
670
745
|
if (tok.type === TT.IDENT && tok.value === "not") {
|
|
671
|
-
this.consume(TT.IDENT);
|
|
746
|
+
this.consume(TT.IDENT);
|
|
672
747
|
const operand = this.parseExpression();
|
|
673
748
|
if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
|
|
674
749
|
return { kind: "unary", op: "not", operand };
|
|
675
750
|
}
|
|
676
751
|
|
|
752
|
+
// Parenthesised expression
|
|
753
|
+
if (this.check(TT.LPAREN)) {
|
|
754
|
+
this.consume(TT.LPAREN);
|
|
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);
|
|
758
|
+
this.consume(TT.RPAREN);
|
|
759
|
+
// Check for trailing binary operator
|
|
760
|
+
return this.parseBinaryRHS(inner);
|
|
761
|
+
}
|
|
762
|
+
|
|
677
763
|
// Literal
|
|
678
|
-
if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
|
|
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)) {
|
|
679
766
|
const lit = this.parseLiteral();
|
|
680
|
-
|
|
767
|
+
const base: Expression = { kind: "literal", value: lit };
|
|
768
|
+
return this.parseBinaryRHS(base);
|
|
681
769
|
}
|
|
682
|
-
|
|
683
|
-
// Variable
|
|
770
|
+
|
|
771
|
+
// Variable or assignment
|
|
684
772
|
if (tok.type === TT.IDENT) {
|
|
685
773
|
const name = this.consume(TT.IDENT).value;
|
|
686
774
|
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
this.consume(TT.
|
|
691
|
-
const
|
|
692
|
-
if (!right) throw new SinthError("Expected expression after ==", this.peek().loc);
|
|
693
|
-
return { kind: "binary", left: { kind: "variable", name }, op: "==", right };
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
// Check for !=
|
|
697
|
-
if (this.check(TT.OP_NEQ)) {
|
|
698
|
-
this.consume(TT.OP_NEQ);
|
|
699
|
-
const right = this.parseExpression();
|
|
700
|
-
if (!right) throw new SinthError("Expected expression after !=", this.peek().loc);
|
|
701
|
-
return { kind: "binary", left: { kind: "variable", name }, op: "!=", right };
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
// Check for <
|
|
705
|
-
if (this.check(TT.OP_LT)) {
|
|
706
|
-
this.consume(TT.OP_LT);
|
|
707
|
-
const right = this.parseExpression();
|
|
708
|
-
if (!right) throw new SinthError("Expected expression after <", this.peek().loc);
|
|
709
|
-
return { kind: "binary", left: { kind: "variable", name }, op: "<", right };
|
|
710
|
-
}
|
|
711
|
-
// Check for >
|
|
712
|
-
if (this.check(TT.OP_GT)) {
|
|
713
|
-
this.consume(TT.OP_GT);
|
|
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
|
-
// Check for >=
|
|
720
|
-
if (this.check(TT.OP_GTEQ)) {
|
|
721
|
-
this.consume(TT.OP_GTEQ);
|
|
722
|
-
const right = this.parseExpression();
|
|
723
|
-
if (!right) throw new SinthError("Expected expression after >= ", this.peek().loc);
|
|
724
|
-
return { kind: "binary", left: { kind: "variable", name }, op: ">=", right };
|
|
725
|
-
}
|
|
726
|
-
// Check for <=
|
|
727
|
-
if (this.check(TT.OP_LTEQ)) {
|
|
728
|
-
this.consume(TT.OP_LTEQ);
|
|
729
|
-
const right = this.parseExpression();
|
|
730
|
-
if (!right) throw new SinthError("Expected expression after <=", this.peek().loc);
|
|
731
|
-
return { kind: "binary", left: { kind: "variable", name }, op: "<=", right };
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
// Check for +=, -=, =
|
|
735
|
-
if (this.check(TT.OP_PLUS) || this.check(TT.OP_MINUS) || this.check(TT.EQUALS)) {
|
|
736
|
-
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}`;
|
|
737
780
|
|
|
738
|
-
//
|
|
739
|
-
const
|
|
740
|
-
if (
|
|
741
|
-
this.consume(TT.OP_PLUS);
|
|
742
|
-
this.
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
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 };
|
|
746
788
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
const right = this.parseExpression();
|
|
753
|
-
if (!right) throw new SinthError("Expected expression after -=", this.peek().loc);
|
|
754
|
-
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 };
|
|
755
794
|
}
|
|
756
|
-
|
|
757
|
-
// =
|
|
758
|
-
if (opTok.type === TT.EQUALS) {
|
|
795
|
+
if (nextType === TT.EQUALS) {
|
|
759
796
|
this.consume(TT.EQUALS);
|
|
760
|
-
const
|
|
761
|
-
if (!
|
|
762
|
-
return { kind: "assign", target:
|
|
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 };
|
|
763
800
|
}
|
|
764
801
|
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
const op = this.consume(opTok.type).value as "+" | "-";
|
|
768
|
-
const right = this.parseExpression();
|
|
769
|
-
if (!right) throw new SinthError("Expected expression after " + op, this.peek().loc);
|
|
770
|
-
return { kind: "binary", left: { kind: "variable", name }, op, right };
|
|
771
|
-
}
|
|
802
|
+
const varExpr: Expression = { kind: "variable", name: fullName };
|
|
803
|
+
return this.parseBinaryRHS(varExpr);
|
|
772
804
|
}
|
|
773
|
-
|
|
774
|
-
//
|
|
775
|
-
|
|
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);
|
|
776
830
|
}
|
|
777
|
-
|
|
831
|
+
|
|
778
832
|
return null;
|
|
779
833
|
}
|
|
780
834
|
|
|
781
|
-
|
|
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 ────────────────────────────────────────────────
|
|
782
861
|
|
|
783
862
|
private parseCompDef(): CompDef {
|
|
784
|
-
const loc
|
|
785
|
-
const name
|
|
863
|
+
const loc = this.consume(TT.KW_COMPONENT).loc;
|
|
864
|
+
const name = this.consume(TT.IDENT).value;
|
|
786
865
|
const params = this.parseParamDecls();
|
|
787
|
-
// === v0.1.0: rawBlockPending was set by the lexer when KW_COMPONENT was read;
|
|
788
|
-
// the next token is therefore RAW_BLOCK, not LBRACE ===
|
|
789
866
|
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
790
867
|
const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
|
|
791
868
|
return { name, params, body, styles, scripts, loc };
|
|
792
869
|
}
|
|
793
870
|
|
|
794
|
-
// === v0.1.0: Parse custom-element / custom declarations ===
|
|
795
871
|
private parseCustomEl(): CustomElDecl {
|
|
796
872
|
const loc = this.peek().loc;
|
|
797
873
|
if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
|
|
@@ -799,7 +875,6 @@ export class Parser {
|
|
|
799
875
|
const tagName = this.consume(TT.IDENT).value;
|
|
800
876
|
const sinthName = tagNameToPascal(tagName);
|
|
801
877
|
const params = this.parseParamDecls();
|
|
802
|
-
// custom-element / custom declarations have no body block
|
|
803
878
|
return { sinthName, tagName, params, loc };
|
|
804
879
|
}
|
|
805
880
|
|
|
@@ -808,10 +883,9 @@ export class Parser {
|
|
|
808
883
|
if (!this.check(TT.LPAREN)) return params;
|
|
809
884
|
this.consume(TT.LPAREN);
|
|
810
885
|
while (!this.check(TT.RPAREN)) {
|
|
811
|
-
const ploc
|
|
812
|
-
// allow keywords as parameter names (e.g., "for" in custom-element declarations)
|
|
886
|
+
const ploc = this.peek().loc;
|
|
813
887
|
const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
|
|
814
|
-
const pname
|
|
888
|
+
const pname = nameTok.value;
|
|
815
889
|
let defaultVal: Literal | undefined;
|
|
816
890
|
if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
|
|
817
891
|
params.push({ name: pname, defaultVal, loc: ploc });
|
|
@@ -821,9 +895,14 @@ export class Parser {
|
|
|
821
895
|
return params;
|
|
822
896
|
}
|
|
823
897
|
|
|
824
|
-
private parseCompBody(
|
|
898
|
+
private parseCompBody(
|
|
899
|
+
raw: string,
|
|
900
|
+
loc: Loc,
|
|
901
|
+
): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
|
|
825
902
|
const tokens = new Lexer(raw, loc.file).tokenize();
|
|
826
|
-
|
|
903
|
+
const sub = new Parser(tokens, loc.file);
|
|
904
|
+
sub._varDecls = this._varDecls;
|
|
905
|
+
return sub.parseBodyContents();
|
|
827
906
|
}
|
|
828
907
|
|
|
829
908
|
private parseBodyContents(): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
|
|
@@ -835,15 +914,174 @@ export class Parser {
|
|
|
835
914
|
const loc = this.peek().loc;
|
|
836
915
|
body.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
|
|
837
916
|
}
|
|
838
|
-
else if (this.check(TT.IDENT)
|
|
839
|
-
|
|
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
|
+
);
|
|
840
929
|
}
|
|
841
930
|
return { body, styles, scripts };
|
|
842
931
|
}
|
|
843
932
|
|
|
844
|
-
// ──
|
|
933
|
+
// ── If / else blocks (v1.0.0: unified mixed body) ────────────────────────
|
|
934
|
+
|
|
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 ────────────────────────────────────────────────────────────
|
|
845
1064
|
|
|
846
|
-
private
|
|
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 {
|
|
847
1085
|
const loc = this.peek().loc;
|
|
848
1086
|
const name = this.consume(TT.IDENT).value;
|
|
849
1087
|
const attrs: Attr[] = [];
|
|
@@ -856,42 +1094,41 @@ private parseCompUse(): CompUse {
|
|
|
856
1094
|
let value: Literal | null = null;
|
|
857
1095
|
if (this.check(TT.COLON)) {
|
|
858
1096
|
this.consume(TT.COLON);
|
|
859
|
-
|
|
860
|
-
if (this.isEventAttribute(aname)) {
|
|
861
|
-
// If the value is a quoted string, use it directly as handler code
|
|
1097
|
+
if (this.isEventAttr(aname)) {
|
|
862
1098
|
if (this.check(TT.STRING)) {
|
|
863
1099
|
value = this.parseLiteral();
|
|
864
1100
|
} else {
|
|
865
|
-
const
|
|
866
|
-
|
|
867
|
-
if (expr &&
|
|
868
|
-
// If there are more tokens, it's probably not a simple expression
|
|
869
|
-
this.pos = startTokens;
|
|
870
|
-
expr = null;
|
|
871
|
-
}
|
|
872
|
-
if (expr) {
|
|
1101
|
+
const savedPos = this.pos;
|
|
1102
|
+
const expr = this.parseExpression();
|
|
1103
|
+
if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
|
|
873
1104
|
value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
|
|
874
1105
|
} else {
|
|
875
|
-
this.pos =
|
|
876
|
-
value
|
|
1106
|
+
this.pos = savedPos;
|
|
1107
|
+
value = this.parseLiteral();
|
|
877
1108
|
}
|
|
878
1109
|
}
|
|
879
1110
|
} else {
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
this.check(TT.
|
|
883
|
-
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)) {
|
|
884
1114
|
value = this.parseLiteral();
|
|
885
1115
|
} else if (this.check(TT.IDENT)) {
|
|
886
|
-
|
|
887
|
-
|
|
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
|
+
}
|
|
888
1126
|
} else {
|
|
889
1127
|
value = this.parseLiteral();
|
|
890
1128
|
}
|
|
891
1129
|
}
|
|
892
1130
|
}
|
|
893
1131
|
attrs.push({ name: aname, value, loc: aloc });
|
|
894
|
-
|
|
895
1132
|
if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
|
|
896
1133
|
}
|
|
897
1134
|
this.consume(TT.RPAREN);
|
|
@@ -901,7 +1138,9 @@ private parseCompUse(): CompUse {
|
|
|
901
1138
|
if (this.check(TT.RAW_BLOCK)) {
|
|
902
1139
|
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
903
1140
|
const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
|
|
904
|
-
|
|
1141
|
+
const sub = new Parser(tokens, rawTok.loc.file);
|
|
1142
|
+
sub._varDecls = this._varDecls;
|
|
1143
|
+
children.push(...sub.parseChildList());
|
|
905
1144
|
} else if (this.check(TT.LBRACE)) {
|
|
906
1145
|
this.consume(TT.LBRACE);
|
|
907
1146
|
children.push(...this.parseChildList());
|
|
@@ -911,385 +1150,203 @@ private parseCompUse(): CompUse {
|
|
|
911
1150
|
return { kind: "use", name, attrs, children, loc };
|
|
912
1151
|
}
|
|
913
1152
|
|
|
914
|
-
private
|
|
915
|
-
|
|
916
|
-
const condition = this.parseExpression();
|
|
917
|
-
if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
|
|
918
|
-
|
|
919
|
-
let body: Child[];
|
|
920
|
-
if (this.check(TT.LBRACE)) {
|
|
921
|
-
this.consume(TT.LBRACE);
|
|
922
|
-
body = this.parseChildList();
|
|
923
|
-
this.consume(TT.RBRACE);
|
|
924
|
-
} else {
|
|
925
|
-
body = [];
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
let elseBody: Child[] | undefined;
|
|
929
|
-
if (this.check(TT.KW_ELSE)) {
|
|
930
|
-
this.consume(TT.KW_ELSE);
|
|
931
|
-
if (this.check(TT.LBRACE)) {
|
|
932
|
-
this.consume(TT.LBRACE);
|
|
933
|
-
elseBody = this.parseChildList();
|
|
934
|
-
this.consume(TT.RBRACE);
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
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();
|
|
939
1155
|
}
|
|
940
1156
|
|
|
941
|
-
private
|
|
942
|
-
|
|
943
|
-
while (!this.check(TT.
|
|
944
|
-
if (this.check(TT.
|
|
945
|
-
const
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
if (this.check(TT.EQUALS)) {
|
|
949
|
-
this.consume(TT.EQUALS);
|
|
950
|
-
const expr = this.parseExpression();
|
|
951
|
-
if (expr) {
|
|
952
|
-
// Type check: look up the variable's declared type
|
|
953
|
-
const varDecl = (this as any)._varDecls?.find((v: any) => v.name === name);
|
|
954
|
-
if (varDecl) {
|
|
955
|
-
const exprJS = compileExprToJS(expr);
|
|
956
|
-
// Check type compatibility
|
|
957
|
-
const valueKind = expr.kind;
|
|
958
|
-
const valueLiteralKind = expr.kind === "literal" ? expr.value?.kind : null;
|
|
959
|
-
|
|
960
|
-
if (varDecl.varType === "int" && valueLiteralKind === "str") {
|
|
961
|
-
SinthWarning.emit(`Type mismatch: '${name}' is declared as int but assigned a string value`);
|
|
962
|
-
} else if (varDecl.varType === "str" && valueLiteralKind === "num") {
|
|
963
|
-
SinthWarning.emit(`Type mismatch: '${name}' is declared as str but assigned a number value`);
|
|
964
|
-
} else if (varDecl.varType === "bool" && valueLiteralKind !== "bool" && valueLiteralKind !== null) {
|
|
965
|
-
SinthWarning.emit(`Type mismatch: '${name}' is declared as bool but assigned a non-boolean value`);
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
js += " " + compileExprToJS({ kind: "assign", target: name, op: "=", right: expr }) + ";\n";
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
// Addition assignment: name += value
|
|
972
|
-
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)) {
|
|
973
1164
|
this.consume(TT.OP_PLUS);
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
const expr = this.parseExpression();
|
|
985
|
-
if (expr) {
|
|
986
|
-
js += " " + compileExprToJS({ kind: "assign", target: name, op: "-=", right: expr }) + ";\n";
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
// Function call: name()
|
|
990
|
-
else if (this.check(TT.LPAREN)) {
|
|
991
|
-
this.consume(TT.LPAREN);
|
|
992
|
-
let args = "";
|
|
993
|
-
while (!this.check(TT.RPAREN) && !this.check(TT.EOF)) {
|
|
994
|
-
const arg = this.parseExpression();
|
|
995
|
-
if (arg) {
|
|
996
|
-
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 };
|
|
997
1175
|
}
|
|
998
|
-
|
|
1176
|
+
} else {
|
|
1177
|
+
rhs = this.parseExpression();
|
|
999
1178
|
}
|
|
1000
|
-
this.
|
|
1001
|
-
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
// Nested if
|
|
1005
|
-
else if (this.check(TT.KW_IF)) {
|
|
1006
|
-
this.consume(TT.KW_IF);
|
|
1007
|
-
const innerCond = this.parseExpression();
|
|
1008
|
-
if (innerCond && this.check(TT.LBRACE)) {
|
|
1009
|
-
this.consume(TT.LBRACE);
|
|
1010
|
-
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 };
|
|
1011
1181
|
}
|
|
1182
|
+
children.push({ kind: "expr", expression: leftExpr, loc });
|
|
1012
1183
|
}
|
|
1013
|
-
// var declaration (skip in logic body)
|
|
1014
1184
|
else if (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
1015
|
-
this.
|
|
1016
|
-
this.
|
|
1017
|
-
|
|
1018
|
-
if (this.check(TT.EQUALS)) {
|
|
1019
|
-
this.consume(TT.EQUALS);
|
|
1020
|
-
this.parseExpression();
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
else {
|
|
1024
|
-
break;
|
|
1185
|
+
const vd = this.parseVarDeclaration();
|
|
1186
|
+
if (vd) this._varDecls.push(vd);
|
|
1187
|
+
continue;
|
|
1025
1188
|
}
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
private parseForLoop(): ForLoop {
|
|
1033
|
-
const loc = this.consume(TT.KW_FOR).loc;
|
|
1034
|
-
const itemVar = this.consume(TT.IDENT).value;
|
|
1035
|
-
if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
|
|
1036
|
-
this.consume(TT.KW_IN);
|
|
1037
|
-
const arrayVar = this.consume(TT.IDENT).value;
|
|
1038
|
-
|
|
1039
|
-
let body: Child[];
|
|
1040
|
-
if (this.check(TT.LBRACE)) {
|
|
1041
|
-
this.consume(TT.LBRACE);
|
|
1042
|
-
this.loopVar = itemVar;
|
|
1043
|
-
body = this.parseChildList();
|
|
1044
|
-
this.loopVar = null;
|
|
1045
|
-
this.consume(TT.RBRACE);
|
|
1046
|
-
} else {
|
|
1047
|
-
body = [];
|
|
1048
|
-
}
|
|
1049
|
-
|
|
1050
|
-
return { kind: "for", itemVar, arrayVar, body, loc };
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
private isEventAttribute(name: string): boolean {
|
|
1054
|
-
return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
|
|
1055
|
-
}
|
|
1056
|
-
|
|
1057
|
-
private parseChildList(): Child[] {
|
|
1058
|
-
const children: Child[] = [];
|
|
1059
|
-
while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
|
|
1060
|
-
if (this.check(TT.STRING)) {
|
|
1061
|
-
const loc = this.peek().loc;
|
|
1062
|
-
let leftExpr: Expression = {
|
|
1063
|
-
kind: "literal",
|
|
1064
|
-
value: { kind: "str", value: this.consume(TT.STRING).value }
|
|
1065
|
-
};
|
|
1066
|
-
// Keep chaining while there's a + operator
|
|
1067
|
-
while (this.check(TT.OP_PLUS)) {
|
|
1068
|
-
this.consume(TT.OP_PLUS);
|
|
1069
|
-
let rightExpr: Expression | null = null;
|
|
1070
|
-
if (this.check(TT.STRING)) {
|
|
1071
|
-
rightExpr = {
|
|
1072
|
-
kind: "literal",
|
|
1073
|
-
value: { kind: "str", value: this.consume(TT.STRING).value }
|
|
1074
|
-
};
|
|
1075
|
-
} else if (this.check(TT.IDENT)) {
|
|
1076
|
-
const varName = this.consume(TT.IDENT).value;
|
|
1077
|
-
rightExpr = { kind: "variable", name: varName };
|
|
1078
|
-
} else {
|
|
1079
|
-
rightExpr = this.parseExpression();
|
|
1080
|
-
}
|
|
1081
|
-
if (!rightExpr) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
1082
|
-
leftExpr = {
|
|
1083
|
-
kind: "binary",
|
|
1084
|
-
left: leftExpr,
|
|
1085
|
-
op: "+",
|
|
1086
|
-
right: rightExpr,
|
|
1087
|
-
};
|
|
1088
|
-
}
|
|
1089
|
-
children.push({ kind: "expr", expression: leftExpr, loc });
|
|
1090
|
-
} else if (this.check(TT.KW_IF)) {
|
|
1091
|
-
const ifStart = this.pos;
|
|
1092
|
-
this.consume(TT.KW_IF);
|
|
1093
|
-
const condition = this.parseExpression();
|
|
1094
|
-
if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
|
|
1095
|
-
|
|
1096
|
-
if (!this.check(TT.LBRACE)) {
|
|
1097
|
-
throw new SinthError("Expected '{' after if condition", this.peek().loc);
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
this.consume(TT.LBRACE);
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
// Determine if this is inline logic or DOM rendering
|
|
1104
|
-
let isInlineLogic = false;
|
|
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;
|
|
1105
1195
|
|
|
1106
|
-
//
|
|
1107
|
-
if (
|
|
1108
|
-
|
|
1109
|
-
|
|
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;
|
|
1110
1202
|
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
// Also check for nested if (could be inline or DOM)
|
|
1133
|
-
else if (this.check(TT.KW_IF)) {
|
|
1134
|
-
// Peek ahead to see if nested if contains assignment
|
|
1135
|
-
const nestedStart = this.pos;
|
|
1136
|
-
this.consume(TT.KW_IF);
|
|
1137
|
-
const nestedCond = this.parseExpression();
|
|
1138
|
-
if (nestedCond && this.check(TT.LBRACE)) {
|
|
1139
|
-
this.consume(TT.LBRACE);
|
|
1140
|
-
if (this.check(TT.IDENT) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
|
|
1141
|
-
isInlineLogic = true;
|
|
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)) {
|
|
1207
|
+
this.consume(TT.OP_PLUS);
|
|
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();
|
|
1221
|
+
}
|
|
1222
|
+
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
1223
|
+
leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
|
|
1142
1224
|
}
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
this.pos = nestedStart;
|
|
1149
|
-
}
|
|
1150
|
-
// Keywords that indicate DOM rendering
|
|
1151
|
-
else if (this.check(TT.KW_STYLE) || this.check(TT.KW_SCRIPT) ||
|
|
1152
|
-
this.check(TT.STRING) || this.check(TT.KW_FOR)) {
|
|
1153
|
-
isInlineLogic = false;
|
|
1154
|
-
}
|
|
1155
|
-
|
|
1156
|
-
if (isInlineLogic) {
|
|
1157
|
-
// Parse as inline logic
|
|
1158
|
-
const jsCode = this.parseLogicBody(condition);
|
|
1159
|
-
const scriptBlock: ScriptBlock = {
|
|
1160
|
-
raw: jsCode,
|
|
1161
|
-
attrs: {},
|
|
1162
|
-
loc: this.peek().loc
|
|
1163
|
-
};
|
|
1164
|
-
children.push({ kind: "text", value: "", loc: this.peek().loc });
|
|
1165
|
-
(this as any)._logicScripts = (this as any)._logicScripts || [];
|
|
1166
|
-
(this as any)._logicScripts.push(scriptBlock);
|
|
1167
|
-
} else {
|
|
1168
|
-
// Parse as DOM if — reset and use existing parser
|
|
1169
|
-
this.pos = ifStart;
|
|
1170
|
-
children.push(this.parseIfBlock());
|
|
1171
|
-
}
|
|
1172
|
-
|
|
1173
|
-
} else if (this.check(TT.KW_FOR)) {
|
|
1174
|
-
children.push(this.parseForLoop());
|
|
1175
|
-
} else if (this.check(TT.IDENT)) {
|
|
1176
|
-
// Check if next token is + (variable + something)
|
|
1177
|
-
if (this.tokens[this.pos + 1]?.type === TT.OP_PLUS) {
|
|
1178
|
-
const loc = this.peek().loc;
|
|
1179
|
-
const varName = this.consume(TT.IDENT).value;
|
|
1180
|
-
this.consume(TT.OP_PLUS); // consume +
|
|
1181
|
-
// Check if what follows is a string
|
|
1182
|
-
if (this.check(TT.STRING)) {
|
|
1183
|
-
const rightStr = this.consume(TT.STRING).value;
|
|
1184
|
-
children.push({ kind: "expr", expression: {
|
|
1185
|
-
kind: "binary",
|
|
1186
|
-
left: { kind: "variable", name: varName },
|
|
1187
|
-
op: "+",
|
|
1188
|
-
right: { kind: "literal", value: { kind: "str", value: rightStr } },
|
|
1189
|
-
}, loc });
|
|
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);
|
|
1190
1230
|
} else {
|
|
1191
|
-
|
|
1192
|
-
const rightExpr = this.parseExpression();
|
|
1193
|
-
if (rightExpr) {
|
|
1194
|
-
children.push({ kind: "expr", expression: {
|
|
1195
|
-
kind: "binary",
|
|
1196
|
-
left: { kind: "variable", name: varName },
|
|
1197
|
-
op: "+",
|
|
1198
|
-
right: rightExpr,
|
|
1199
|
-
}, loc });
|
|
1200
|
-
}
|
|
1231
|
+
children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
|
|
1201
1232
|
}
|
|
1202
|
-
} else if (
|
|
1203
|
-
const loc = this.peek().loc;
|
|
1233
|
+
} else if (nextType === TT.OP_PLUS) {
|
|
1204
1234
|
const name = this.consume(TT.IDENT).value;
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
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();
|
|
1251
|
+
}
|
|
1252
|
+
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
1253
|
+
leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
|
|
1254
|
+
}
|
|
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) {
|
|
1209
1260
|
children.push(this.parseCompUse());
|
|
1210
1261
|
} else {
|
|
1211
|
-
const loc = this.peek().loc;
|
|
1212
1262
|
const name = this.consume(TT.IDENT).value;
|
|
1213
1263
|
children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
|
|
1214
1264
|
}
|
|
1215
|
-
} else {
|
|
1216
|
-
throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
|
|
1217
1265
|
}
|
|
1266
|
+
else throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
|
|
1218
1267
|
}
|
|
1219
1268
|
return children;
|
|
1220
1269
|
}
|
|
1221
1270
|
|
|
1222
|
-
// ── Style blocks
|
|
1271
|
+
// ── Style / Script blocks ────────────────────────────────────────────────
|
|
1223
1272
|
|
|
1224
1273
|
private parseStyleBlock(): StyleBlock {
|
|
1225
1274
|
const loc = this.consume(TT.KW_STYLE).loc;
|
|
1226
|
-
let global = false, lang: "css" | "scss" = "css";
|
|
1275
|
+
let global = false, lang: "css" | "scss" = "css", target: string | undefined;
|
|
1227
1276
|
const extraAttrs: Record<string, string> = {};
|
|
1228
1277
|
|
|
1229
1278
|
while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
|
|
1230
|
-
if
|
|
1231
|
-
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)) {
|
|
1232
1281
|
this.consume(TT.KW_LANG); this.consume(TT.EQUALS);
|
|
1233
1282
|
const lv = this.consume(TT.STRING).value;
|
|
1234
1283
|
if (lv !== "css" && lv !== "scss") throw new SinthError(`Unsupported style lang '${lv}'`, loc);
|
|
1235
1284
|
lang = lv as "css" | "scss";
|
|
1236
1285
|
}
|
|
1237
1286
|
else if (this.check(TT.IDENT)) {
|
|
1238
|
-
|
|
1239
|
-
this.
|
|
1240
|
-
|
|
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
|
+
}
|
|
1241
1295
|
}
|
|
1242
1296
|
else throw new SinthError(`Unexpected token '${this.peek().value}' in style modifiers`, this.peek().loc);
|
|
1243
1297
|
}
|
|
1244
1298
|
|
|
1245
|
-
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 };
|
|
1246
1300
|
}
|
|
1247
1301
|
|
|
1248
|
-
// ── Script blocks ─────────────────────────────────────────
|
|
1249
|
-
|
|
1250
1302
|
private parseScriptBlock(): ScriptBlock {
|
|
1251
1303
|
const loc = this.consume(TT.KW_SCRIPT).loc;
|
|
1252
1304
|
const attrs: Record<string, string> = {};
|
|
1253
|
-
|
|
1254
1305
|
while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
|
|
1255
1306
|
const key = this.consume(TT.IDENT).value;
|
|
1256
1307
|
if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); attrs[key] = this.consume(TT.STRING).value; }
|
|
1257
1308
|
else { attrs[key] = "true"; }
|
|
1258
1309
|
}
|
|
1259
|
-
|
|
1260
1310
|
return { raw: this.consume(TT.RAW_BLOCK).value, attrs, loc };
|
|
1261
1311
|
}
|
|
1262
1312
|
|
|
1263
|
-
// ── Literals
|
|
1313
|
+
// ── Literals ─────────────────────────────────────────────────────────────
|
|
1264
1314
|
|
|
1265
|
-
|
|
1315
|
+
private parseLiteral(): Literal {
|
|
1266
1316
|
const tok = this.peek();
|
|
1267
|
-
if (this.check(TT.LBRACKET))
|
|
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
|
+
}
|
|
1268
1322
|
if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
|
|
1269
1323
|
if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
|
|
1270
1324
|
if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
|
|
1271
1325
|
if (this.check(TT.BOOL_FALSE)){ this.consume(TT.BOOL_FALSE);return { kind: "bool", value: false }; }
|
|
1272
1326
|
if (this.check(TT.NULL_LIT)) { this.consume(TT.NULL_LIT); return { kind: "null" }; }
|
|
1273
|
-
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);
|
|
1274
1328
|
}
|
|
1275
1329
|
|
|
1276
|
-
// ── Token helpers
|
|
1330
|
+
// ── Token helpers ─────────────────────────────────────────────────────────
|
|
1277
1331
|
|
|
1278
1332
|
private peek(): Token { return this.tokens[this.pos]; }
|
|
1279
1333
|
private check(t: TT): boolean { return this.tokens[this.pos]?.type === t; }
|
|
1280
1334
|
private consume(t: TT): Token {
|
|
1281
1335
|
const tok = this.tokens[this.pos];
|
|
1282
1336
|
if (tok.type !== t) {
|
|
1283
|
-
throw new SinthError(
|
|
1337
|
+
throw new SinthError(
|
|
1338
|
+
`Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`,
|
|
1339
|
+
tok.loc,
|
|
1340
|
+
);
|
|
1284
1341
|
}
|
|
1285
1342
|
this.pos++;
|
|
1286
1343
|
return tok;
|
|
1287
1344
|
}
|
|
1288
1345
|
}
|
|
1289
1346
|
|
|
1290
|
-
//
|
|
1291
|
-
//
|
|
1292
|
-
//
|
|
1347
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1348
|
+
// §5 IMPORT RESOLVER
|
|
1349
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1293
1350
|
|
|
1294
1351
|
interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
|
|
1295
1352
|
|
|
@@ -1300,13 +1357,11 @@ interface ResolvedImports {
|
|
|
1300
1357
|
jsLinks: { src: string; attrs: Record<string, string> }[];
|
|
1301
1358
|
}
|
|
1302
1359
|
|
|
1303
|
-
// Module-level import stack for circular detection
|
|
1304
1360
|
const IMPORT_STACK: string[] = [];
|
|
1305
1361
|
|
|
1306
|
-
// === v0.1.0: parseFile catches errors and attaches source line preview ===
|
|
1307
1362
|
function parseFile(filePath: string): SinthFile {
|
|
1308
1363
|
if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
|
|
1309
|
-
const src
|
|
1364
|
+
const src = fs.readFileSync(filePath, "utf-8");
|
|
1310
1365
|
const srcLines = src.split("\n");
|
|
1311
1366
|
try {
|
|
1312
1367
|
const tokens = new Lexer(src, filePath).tokenize();
|
|
@@ -1327,24 +1382,21 @@ function resolveImports(
|
|
|
1327
1382
|
const cssLinks: string[] = [];
|
|
1328
1383
|
const jsLinks: { src: string; attrs: Record<string, string> }[] = [];
|
|
1329
1384
|
|
|
1330
|
-
// Register this file's own component definitions
|
|
1331
1385
|
for (const def of file.defs) {
|
|
1332
1386
|
if (BUILTIN_MAP[def.name]) {
|
|
1333
|
-
throw new SinthError(`'${def.name}' is a built-in
|
|
1387
|
+
throw new SinthError(`'${def.name}' is a built-in Sinth component and cannot be redefined.`, def.loc);
|
|
1334
1388
|
}
|
|
1335
1389
|
if (allDefs.has(def.name)) throw new SinthError(`Duplicate component definition '${def.name}'`, def.loc);
|
|
1336
1390
|
allDefs.set(def.name, def);
|
|
1337
1391
|
}
|
|
1338
1392
|
|
|
1339
|
-
// Register custom element declarations
|
|
1340
1393
|
for (const el of file.customEls) {
|
|
1341
1394
|
customEls.set(el.sinthName, { tagName: el.tagName, params: el.params });
|
|
1342
1395
|
}
|
|
1343
1396
|
|
|
1344
|
-
// Warn about metadata in component files
|
|
1345
1397
|
if (!file.isPage && file.meta.length > 0) {
|
|
1346
1398
|
for (const m of file.meta) {
|
|
1347
|
-
SinthWarning.emit(`Metadata
|
|
1399
|
+
SinthWarning.emit(`Metadata '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
|
|
1348
1400
|
}
|
|
1349
1401
|
}
|
|
1350
1402
|
|
|
@@ -1357,7 +1409,6 @@ function resolveImports(
|
|
|
1357
1409
|
const src = resolveLibrary(imp.name, cfg);
|
|
1358
1410
|
jsLinks.push({ src, attrs: {} });
|
|
1359
1411
|
|
|
1360
|
-
// === v0.1.0: Auto-import companion .sinth for JS libraries (e.g. sinthui.sinth) ===
|
|
1361
1412
|
for (const libDir of cfg.libraryPaths) {
|
|
1362
1413
|
const companion = path.join(libDir, imp.name + ".sinth");
|
|
1363
1414
|
if (fs.existsSync(companion) && !visited.has(companion)) {
|
|
@@ -1375,7 +1426,7 @@ function resolveImports(
|
|
|
1375
1426
|
|
|
1376
1427
|
if (IMPORT_STACK.includes(resolved)) {
|
|
1377
1428
|
throw new SinthError(
|
|
1378
|
-
`Circular import
|
|
1429
|
+
`Circular import: ${[...IMPORT_STACK, resolved].join(" → ")}`
|
|
1379
1430
|
);
|
|
1380
1431
|
}
|
|
1381
1432
|
if (visited.has(resolved)) continue;
|
|
@@ -1387,14 +1438,12 @@ function resolveImports(
|
|
|
1387
1438
|
|
|
1388
1439
|
const sub = resolveImports(imported, cfg, visited);
|
|
1389
1440
|
for (const [name, def] of sub.allDefs) {
|
|
1390
|
-
if (allDefs.has(name)) {
|
|
1391
|
-
throw new SinthError(`Component '${name}' defined in multiple imported files.`);
|
|
1392
|
-
}
|
|
1441
|
+
if (allDefs.has(name)) throw new SinthError(`Component '${name}' defined in multiple imported files.`);
|
|
1393
1442
|
allDefs.set(name, def);
|
|
1394
1443
|
}
|
|
1395
1444
|
for (const [n, e] of sub.customEls) customEls.set(n, e);
|
|
1396
|
-
for (const l of sub.cssLinks)
|
|
1397
|
-
for (const j of sub.jsLinks)
|
|
1445
|
+
for (const l of sub.cssLinks) if (!cssLinks.includes(l)) cssLinks.push(l);
|
|
1446
|
+
for (const j of sub.jsLinks) jsLinks.push(j);
|
|
1398
1447
|
}
|
|
1399
1448
|
}
|
|
1400
1449
|
|
|
@@ -1415,25 +1464,20 @@ function resolveLibrary(name: string, cfg: ResolverConfig): string {
|
|
|
1415
1464
|
return `/libraries/${base}`;
|
|
1416
1465
|
}
|
|
1417
1466
|
|
|
1418
|
-
// === v0.1.0: resolveSinthPath — first try relative to importing file, then library paths ===
|
|
1419
1467
|
function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
|
|
1420
|
-
// Explicit relative path
|
|
1421
1468
|
if (p.startsWith("./") || p.startsWith("../")) {
|
|
1422
|
-
const r
|
|
1469
|
+
const r = path.resolve(path.dirname(fromFile), p);
|
|
1423
1470
|
if (fs.existsSync(r)) return r;
|
|
1424
1471
|
const w = r.endsWith(".sinth") ? "" : r + ".sinth";
|
|
1425
1472
|
if (w && fs.existsSync(w)) return w;
|
|
1426
1473
|
throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
|
|
1427
1474
|
}
|
|
1428
1475
|
|
|
1429
|
-
|
|
1430
|
-
// file's directory FIRST, then fall back to library paths ===
|
|
1431
|
-
const relToFile = path.resolve(path.dirname(fromFile), p);
|
|
1476
|
+
const relToFile = path.resolve(path.dirname(fromFile), p);
|
|
1432
1477
|
if (fs.existsSync(relToFile)) return relToFile;
|
|
1433
1478
|
const relToFileExt = relToFile.endsWith(".sinth") ? relToFile : relToFile + ".sinth";
|
|
1434
1479
|
if (fs.existsSync(relToFileExt)) return relToFileExt;
|
|
1435
1480
|
|
|
1436
|
-
// Library path fallback
|
|
1437
1481
|
for (const libDir of cfg.libraryPaths) {
|
|
1438
1482
|
const c1 = path.join(libDir, p);
|
|
1439
1483
|
if (fs.existsSync(c1)) return c1;
|
|
@@ -1442,19 +1486,18 @@ function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): str
|
|
|
1442
1486
|
}
|
|
1443
1487
|
|
|
1444
1488
|
throw new SinthError(
|
|
1445
|
-
`Cannot resolve import '${p}'\n Tried
|
|
1489
|
+
`Cannot resolve import '${p}'\n Tried: ${relToFileExt}\n Library paths: ${cfg.libraryPaths.join(", ")}`
|
|
1446
1490
|
);
|
|
1447
1491
|
}
|
|
1448
1492
|
|
|
1449
|
-
//
|
|
1450
|
-
//
|
|
1451
|
-
//
|
|
1493
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1494
|
+
// §6 BUILT-IN COMPONENT MAP
|
|
1495
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1452
1496
|
|
|
1453
1497
|
interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
|
|
1454
1498
|
|
|
1455
|
-
// === v0.1.0: Complete HTML5 map; Col = void <col>; Column = grid div; added SubHeading, CardGrid ===
|
|
1456
1499
|
const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
1457
|
-
//
|
|
1500
|
+
// Structural
|
|
1458
1501
|
Main: { tag: "main" },
|
|
1459
1502
|
Header: { tag: "header" },
|
|
1460
1503
|
Footer: { tag: "footer" },
|
|
@@ -1470,14 +1513,13 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
1470
1513
|
Flex: { tag: "div", defaultClass: "flex" },
|
|
1471
1514
|
Stack: { tag: "div", defaultClass: "stack" },
|
|
1472
1515
|
Row: { tag: "div", defaultClass: "row" },
|
|
1473
|
-
// === v0.1.0: Column = grid helper div; Col = HTML void table col ===
|
|
1474
1516
|
Column: { tag: "div", defaultClass: "col" },
|
|
1475
|
-
|
|
1476
|
-
|
|
1517
|
+
CardGrid: { tag: "div", defaultClass: "card-grid" },
|
|
1518
|
+
// Typography
|
|
1519
|
+
Heading: { tag: "h1" },
|
|
1520
|
+
SubHeading: { tag: "p", defaultClass: "subheading" },
|
|
1477
1521
|
Paragraph: { tag: "p" },
|
|
1478
|
-
|
|
1479
|
-
SubHeading: { tag: "p", defaultClass: "subheading" },
|
|
1480
|
-
Lead: { tag: "p", defaultClass: "lead" },
|
|
1522
|
+
Lead: { tag: "p", defaultClass: "lead" },
|
|
1481
1523
|
Small: { tag: "small" },
|
|
1482
1524
|
Strong: { tag: "strong" },
|
|
1483
1525
|
Em: { tag: "em" },
|
|
@@ -1504,7 +1546,7 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
1504
1546
|
Ruby: { tag: "ruby" },
|
|
1505
1547
|
Rt: { tag: "rt" },
|
|
1506
1548
|
Rp: { tag: "rp" },
|
|
1507
|
-
//
|
|
1549
|
+
// Interactive
|
|
1508
1550
|
Button: { tag: "button" },
|
|
1509
1551
|
Link: { tag: "a" },
|
|
1510
1552
|
NavLink: { tag: "a" },
|
|
@@ -1523,7 +1565,7 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
1523
1565
|
Meter: { tag: "meter" },
|
|
1524
1566
|
Output: { tag: "output" },
|
|
1525
1567
|
Map: { tag: "map" },
|
|
1526
|
-
//
|
|
1568
|
+
// Media
|
|
1527
1569
|
Picture: { tag: "picture" },
|
|
1528
1570
|
Video: { tag: "video" },
|
|
1529
1571
|
Audio: { tag: "audio" },
|
|
@@ -1533,22 +1575,21 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
1533
1575
|
Svg: { tag: "svg" },
|
|
1534
1576
|
IFrame: { tag: "iframe" },
|
|
1535
1577
|
Object: { tag: "object" },
|
|
1536
|
-
//
|
|
1578
|
+
// Void elements
|
|
1537
1579
|
Img: { tag: "img", voidEl: true },
|
|
1538
1580
|
Logo: { tag: "img", voidEl: true },
|
|
1539
1581
|
Input: { tag: "input", voidEl: true },
|
|
1540
1582
|
Hr: { tag: "hr", voidEl: true },
|
|
1541
1583
|
Br: { tag: "br", voidEl: true },
|
|
1542
|
-
Wbr: { tag: "wbr",
|
|
1584
|
+
Wbr: { tag: "wbr", voidEl: true },
|
|
1543
1585
|
Source: { tag: "source", voidEl: true },
|
|
1544
1586
|
Embed: { tag: "embed", voidEl: true },
|
|
1545
|
-
// === v0.1.0: Col = HTML void table column (NOT the grid div) ===
|
|
1546
1587
|
Col: { tag: "col", voidEl: true },
|
|
1547
1588
|
Area: { tag: "area", voidEl: true },
|
|
1548
|
-
//
|
|
1549
|
-
Ul:
|
|
1550
|
-
Dl:
|
|
1551
|
-
//
|
|
1589
|
+
// Lists
|
|
1590
|
+
Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
|
|
1591
|
+
Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
|
|
1592
|
+
// Tables
|
|
1552
1593
|
Table: { tag: "table" },
|
|
1553
1594
|
Caption: { tag: "caption" },
|
|
1554
1595
|
Thead: { tag: "thead" },
|
|
@@ -1558,86 +1599,212 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
1558
1599
|
Th: { tag: "th" },
|
|
1559
1600
|
Td: { tag: "td" },
|
|
1560
1601
|
Colgroup: { tag: "colgroup" },
|
|
1561
|
-
//
|
|
1602
|
+
// Utility
|
|
1562
1603
|
Template: { tag: "template" },
|
|
1563
1604
|
Slot: { tag: "slot" },
|
|
1564
1605
|
NoScript: { tag: "noscript" },
|
|
1565
|
-
// === v0.1.0: CardGrid convenience layout wrapper ===
|
|
1566
|
-
CardGrid: { tag: "div", defaultClass: "card-grid" },
|
|
1567
|
-
// === v0.1.0: RawHTML marker — handled specially in renderCompUse ===
|
|
1568
1606
|
RawHTML: { tag: "__RAW__" },
|
|
1569
1607
|
};
|
|
1570
1608
|
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
"
|
|
1574
|
-
|
|
1575
|
-
|
|
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] ?? "";
|
|
1576
1694
|
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
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 (");
|
|
1580
1758
|
}
|
|
1581
1759
|
|
|
1582
|
-
//
|
|
1583
|
-
//
|
|
1584
|
-
//
|
|
1760
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1761
|
+
// §8 STYLE PROCESSOR
|
|
1762
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1585
1763
|
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
// - Ensure trailing semicolon
|
|
1592
|
-
// - 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
|
+
*/
|
|
1593
1769
|
function convertCSSProps(css: string): string {
|
|
1594
1770
|
return css.split("\n").map(line => {
|
|
1595
1771
|
const trimmed = line.trim();
|
|
1596
|
-
|
|
1597
|
-
// Leave empty lines, braces, @rules, comments untouched
|
|
1598
|
-
if (!trimmed) return line;
|
|
1772
|
+
if (!trimmed) return line;
|
|
1599
1773
|
if (trimmed === "}" || trimmed.startsWith("}")) return line;
|
|
1600
1774
|
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
|
|
1601
|
-
|
|
1602
|
-
if (trimmed.
|
|
1603
|
-
|
|
1604
|
-
// Lines containing { are selector/block openers — leave untouched
|
|
1605
|
-
if (trimmed.includes("{")) return line;
|
|
1606
|
-
|
|
1607
|
-
// Match a CSS declaration: identifier (colon) value [semicolon]
|
|
1608
|
-
// The colon must NOT be preceded by another colon (avoid matching ::before, &:hover etc.)
|
|
1609
|
-
// Property names are identifiers: letters, digits, hyphens — but we only camelCase-convert
|
|
1610
|
-
// identifiers that are purely alphabetic (camelCase or vendor-prefixed).
|
|
1775
|
+
if (trimmed.startsWith("@")) return line;
|
|
1776
|
+
if (trimmed.includes("{")) return line;
|
|
1777
|
+
|
|
1611
1778
|
const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
|
|
1612
1779
|
if (!m) return line;
|
|
1613
1780
|
|
|
1614
|
-
const [, indent, rawProp,
|
|
1781
|
+
const [, indent, rawProp, , rawVal] = m;
|
|
1615
1782
|
|
|
1616
|
-
//
|
|
1617
|
-
// A declaration ends without { and the value is either quoted or a plain CSS value
|
|
1618
|
-
// We require either camelCase OR a quoted value to convert
|
|
1783
|
+
// Only convert if there's a camelCase hint or a quoted value
|
|
1619
1784
|
const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
|
|
1620
1785
|
const hasQuotedVal = /^["']/.test(rawVal.trim());
|
|
1621
1786
|
if (!hasCamelCase && !hasQuotedVal) return line;
|
|
1622
1787
|
|
|
1623
|
-
// Strip trailing semicolon from value if present before stripping quotes
|
|
1624
1788
|
let val = rawVal.trim();
|
|
1625
1789
|
if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
if (
|
|
1629
|
-
(val.startsWith('"') && val.endsWith('"')) ||
|
|
1630
|
-
(val.startsWith("'") && val.endsWith("'"))
|
|
1631
|
-
) {
|
|
1790
|
+
if ((val.startsWith('"') && val.endsWith('"')) ||
|
|
1791
|
+
(val.startsWith("'") && val.endsWith("'"))) {
|
|
1632
1792
|
val = val.slice(1, -1);
|
|
1633
1793
|
}
|
|
1634
1794
|
|
|
1635
|
-
|
|
1636
|
-
return `${indent}${kebab}: ${val};`;
|
|
1795
|
+
return `${indent}${camelToKebab(rawProp)}: ${val};`;
|
|
1637
1796
|
}).join("\n");
|
|
1638
1797
|
}
|
|
1639
1798
|
|
|
1640
|
-
|
|
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
|
+
*/
|
|
1641
1808
|
function processStyleBlock(
|
|
1642
1809
|
block: StyleBlock,
|
|
1643
1810
|
hash: string,
|
|
@@ -1645,23 +1812,24 @@ function processStyleBlock(
|
|
|
1645
1812
|
): string {
|
|
1646
1813
|
let raw = block.raw;
|
|
1647
1814
|
|
|
1648
|
-
//
|
|
1649
|
-
if (params.size > 0)
|
|
1650
|
-
raw = interpolateAttr(raw, params);
|
|
1651
|
-
}
|
|
1815
|
+
// 1. Interpolate {param} placeholders
|
|
1816
|
+
if (params.size > 0) raw = interpolateAttr(raw, params);
|
|
1652
1817
|
|
|
1653
|
-
//
|
|
1818
|
+
// 2. Sinth Style preprocessing
|
|
1819
|
+
raw = preprocessSinthStyle(raw);
|
|
1820
|
+
|
|
1821
|
+
// 3. Warn if & in plain CSS
|
|
1654
1822
|
if (block.lang === "css" && raw.includes("&")) {
|
|
1655
1823
|
SinthWarning.emit(
|
|
1656
|
-
`'&' found in
|
|
1824
|
+
`'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
|
|
1657
1825
|
block.loc,
|
|
1658
1826
|
);
|
|
1659
1827
|
}
|
|
1660
1828
|
|
|
1661
|
-
//
|
|
1829
|
+
// 4. camelCase → kebab-case
|
|
1662
1830
|
let css = convertCSSProps(raw);
|
|
1663
1831
|
|
|
1664
|
-
//
|
|
1832
|
+
// 5. SCSS compilation
|
|
1665
1833
|
if (block.lang === "scss") {
|
|
1666
1834
|
try {
|
|
1667
1835
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
@@ -1670,15 +1838,19 @@ function processStyleBlock(
|
|
|
1670
1838
|
} catch (e: unknown) {
|
|
1671
1839
|
const err = e as { code?: string; message?: string };
|
|
1672
1840
|
if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
|
|
1673
|
-
throw new SinthError(
|
|
1674
|
-
"SCSS support requires the 'sass' package.\n Install with: npm install sass"
|
|
1675
|
-
);
|
|
1841
|
+
throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
|
|
1676
1842
|
}
|
|
1677
1843
|
throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
|
|
1678
1844
|
}
|
|
1679
1845
|
}
|
|
1680
1846
|
|
|
1681
|
-
//
|
|
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)
|
|
1682
1854
|
if (!block.global) css = scopeCSS(css, hash);
|
|
1683
1855
|
|
|
1684
1856
|
return css;
|
|
@@ -1689,14 +1861,11 @@ function scopeCSS(css: string, hash: string): string {
|
|
|
1689
1861
|
}
|
|
1690
1862
|
|
|
1691
1863
|
function processRules(css: string, attr: string): string {
|
|
1692
|
-
let out = "";
|
|
1693
|
-
let i = 0;
|
|
1864
|
+
let out = "", i = 0;
|
|
1694
1865
|
|
|
1695
1866
|
while (i < css.length) {
|
|
1696
|
-
// Skip top-level whitespace
|
|
1697
1867
|
if (/\s/.test(css[i])) { out += css[i++]; continue; }
|
|
1698
1868
|
|
|
1699
|
-
// Skip CSS block comments
|
|
1700
1869
|
if (css[i] === "/" && css[i + 1] === "*") {
|
|
1701
1870
|
const end = css.indexOf("*/", i + 2);
|
|
1702
1871
|
if (end === -1) { out += css.substring(i); break; }
|
|
@@ -1712,13 +1881,10 @@ function processRules(css: string, attr: string): string {
|
|
|
1712
1881
|
const { content, end } = extractCSSBlock(css, braceIdx);
|
|
1713
1882
|
|
|
1714
1883
|
if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
|
|
1715
|
-
// @keyframes: never scope — they're global by name
|
|
1716
1884
|
out += `${selector} {${content}}\n`;
|
|
1717
1885
|
} else if (/^@(media|supports|layer|container)/.test(selector)) {
|
|
1718
|
-
// Descend into conditional @rules
|
|
1719
1886
|
out += `${selector} {\n${processRules(content, attr)}\n}\n`;
|
|
1720
1887
|
} else if (selector.startsWith("@")) {
|
|
1721
|
-
// Other @rules: pass through
|
|
1722
1888
|
out += `${selector} {${content}}\n`;
|
|
1723
1889
|
} else if (selector.length > 0) {
|
|
1724
1890
|
out += `${scopeSelectors(selector, attr)} {${content}}\n`;
|
|
@@ -1726,7 +1892,6 @@ function processRules(css: string, attr: string): string {
|
|
|
1726
1892
|
|
|
1727
1893
|
i = end;
|
|
1728
1894
|
}
|
|
1729
|
-
|
|
1730
1895
|
return out;
|
|
1731
1896
|
}
|
|
1732
1897
|
|
|
@@ -1736,9 +1901,7 @@ function scopeSelectors(selList: string, attr: string): string {
|
|
|
1736
1901
|
.map(s => {
|
|
1737
1902
|
s = s.trim();
|
|
1738
1903
|
if (!s) return "";
|
|
1739
|
-
// Don't scope root elements
|
|
1740
1904
|
if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
|
|
1741
|
-
// Handle pseudo-classes/elements: insert scope before pseudo suffix
|
|
1742
1905
|
const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
|
|
1743
1906
|
if (m && m[1].trim()) {
|
|
1744
1907
|
return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
|
|
@@ -1758,9 +1921,7 @@ function findCSSBrace(css: string, from: number): number {
|
|
|
1758
1921
|
i++;
|
|
1759
1922
|
} else if (css[i] === "{") {
|
|
1760
1923
|
return i;
|
|
1761
|
-
} else {
|
|
1762
|
-
i++;
|
|
1763
|
-
}
|
|
1924
|
+
} else { i++; }
|
|
1764
1925
|
}
|
|
1765
1926
|
return -1;
|
|
1766
1927
|
}
|
|
@@ -1783,9 +1944,92 @@ function extractCSSBlock(css: string, openBrace: number): { content: string; end
|
|
|
1783
1944
|
return { content: css.substring(openBrace + 1, i), end: i + 1 };
|
|
1784
1945
|
}
|
|
1785
1946
|
|
|
1786
|
-
//
|
|
1787
|
-
//
|
|
1788
|
-
//
|
|
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
|
+
]);
|
|
1789
2033
|
|
|
1790
2034
|
function resolveBuiltinTag(
|
|
1791
2035
|
name: string,
|
|
@@ -1805,101 +2049,81 @@ function resolveBuiltinTag(
|
|
|
1805
2049
|
|
|
1806
2050
|
function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
|
|
1807
2051
|
const { name, value } = attr;
|
|
1808
|
-
|
|
1809
2052
|
if (value === null) return name;
|
|
1810
2053
|
if (value.kind === "null") return "";
|
|
1811
2054
|
if (value.kind === "bool") return value.value ? name : "";
|
|
1812
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
|
+
|
|
1813
2061
|
if (name === "delay") {
|
|
1814
|
-
// Support both numbers and variable references
|
|
1815
|
-
let delayVal: string;
|
|
1816
2062
|
if (value.kind === "num") {
|
|
1817
|
-
|
|
1818
|
-
} else {
|
|
1819
|
-
delayVal = litToString(value);
|
|
1820
|
-
// If it looks like a variable name (not a number), treat it as a JS expression
|
|
1821
|
-
if (!/^\d+$/.test(delayVal)) {
|
|
1822
|
-
return `data-sinth-delay-expr="${escAttr(delayVal)}" style="display:none"`;
|
|
1823
|
-
}
|
|
2063
|
+
return `data-sinth-delay="${value.value}" style="display:none"`;
|
|
1824
2064
|
}
|
|
1825
|
-
|
|
1826
|
-
}
|
|
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
|
+
}
|
|
1827
2076
|
|
|
1828
|
-
if (value.kind === "num")
|
|
2077
|
+
if (value.kind === "num") return `${name}="${value.value}"`;
|
|
1829
2078
|
|
|
1830
2079
|
let raw = value.value;
|
|
1831
|
-
|
|
1832
|
-
//
|
|
2080
|
+
|
|
2081
|
+
// Inline expression reference
|
|
1833
2082
|
if (raw.startsWith("__EXPR__")) {
|
|
1834
2083
|
const exprJson = raw.substring("__EXPR__".length);
|
|
1835
2084
|
try {
|
|
1836
2085
|
const expr: Expression = JSON.parse(exprJson);
|
|
1837
2086
|
const jsExpr = compileExprToJS(expr);
|
|
1838
2087
|
const ev = eventAttrName(name);
|
|
1839
|
-
if (ev) {
|
|
1840
|
-
return `${ev}="(function(){ ${jsExpr.replace(/"/g, '"')}; })()"`;
|
|
1841
|
-
}
|
|
2088
|
+
if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, """)}; })()"`;
|
|
1842
2089
|
return `${name}="${escAttr(jsExpr)}"`;
|
|
1843
|
-
} catch {
|
|
1844
|
-
|
|
1845
|
-
}
|
|
1846
|
-
}
|
|
2090
|
+
} catch { /* fall through */ }
|
|
2091
|
+
}
|
|
1847
2092
|
|
|
1848
2093
|
raw = interpolateAttr(raw, paramMap);
|
|
1849
2094
|
|
|
1850
2095
|
const ev = eventAttrName(name);
|
|
1851
|
-
if (ev) {
|
|
1852
|
-
// Always append sinthRender() to event handlers
|
|
1853
|
-
const handler = raw.includes("(") ? raw : raw;
|
|
1854
|
-
return `${ev}="${escAttr(handler)};sinthRender()"`;
|
|
1855
|
-
}
|
|
2096
|
+
if (ev) return `${ev}="${escAttr(raw)};sinthRender()"`;
|
|
1856
2097
|
return `${name}="${escAttr(raw)}"`;
|
|
1857
2098
|
}
|
|
1858
2099
|
|
|
1859
|
-
// === v0.1.0: renderText — "$slot" protected from double-escaping via placeholder approach ===
|
|
1860
2100
|
function renderText(text: string, params: Map<string, string>): string {
|
|
1861
|
-
// Map of placeholder → raw HTML for slot-like params
|
|
1862
2101
|
const rawSlots = new Map<string, string>();
|
|
1863
|
-
let
|
|
1864
|
-
|
|
1865
|
-
let s = text;
|
|
2102
|
+
let counter = 0;
|
|
1866
2103
|
|
|
1867
|
-
|
|
1868
|
-
s = s.replace(/\\\$/g, "\x00DOLLAR\x00");
|
|
2104
|
+
let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
|
|
1869
2105
|
|
|
1870
|
-
// Step 2: Substitute $param references
|
|
1871
2106
|
s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
|
|
1872
2107
|
const val = params.get(n);
|
|
1873
|
-
if (val === undefined) return `$${n}`;
|
|
1874
|
-
|
|
1875
|
-
// "$slot" (and any raw-HTML param) must NOT be HTML-escaped — use a placeholder
|
|
2108
|
+
if (val === undefined) return `$${n}`;
|
|
1876
2109
|
if (n === "slot") {
|
|
1877
2110
|
const ph = `\x00RAW${counter++}\x00`;
|
|
1878
2111
|
rawSlots.set(ph, val);
|
|
1879
2112
|
return ph;
|
|
1880
2113
|
}
|
|
1881
|
-
|
|
1882
|
-
return val; // will be HTML-escaped in step 3
|
|
2114
|
+
return val;
|
|
1883
2115
|
});
|
|
1884
2116
|
|
|
1885
|
-
// Step 3: HTML-escape the entire string
|
|
1886
|
-
// Placeholders contain \x00 which esc() does not touch
|
|
1887
2117
|
s = esc(s);
|
|
1888
2118
|
|
|
1889
|
-
|
|
1890
|
-
for (const [ph, val] of rawSlots) {
|
|
1891
|
-
s = s.replace(ph, val);
|
|
1892
|
-
}
|
|
1893
|
-
|
|
1894
|
-
// Step 5: Restore \$ → $
|
|
2119
|
+
for (const [ph, val] of rawSlots) s = s.replace(ph, val);
|
|
1895
2120
|
s = s.replace(/\x00DOLLAR\x00/g, "$");
|
|
1896
2121
|
|
|
1897
|
-
// === v0.1.0: Warn about {identifier} patterns remaining after substitution ===
|
|
1898
2122
|
const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
|
|
1899
|
-
let
|
|
2123
|
+
let m: RegExpExecArray | null;
|
|
1900
2124
|
while ((m = braceRe.exec(s)) !== null) {
|
|
1901
2125
|
SinthWarning.emit(
|
|
1902
|
-
`Use $param for text interpolation
|
|
2126
|
+
`Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
|
|
1903
2127
|
);
|
|
1904
2128
|
}
|
|
1905
2129
|
|
|
@@ -1907,8 +2131,7 @@ function renderText(text: string, params: Map<string, string>): string {
|
|
|
1907
2131
|
}
|
|
1908
2132
|
|
|
1909
2133
|
function interpolateAttr(text: string, params: Map<string, string>): string {
|
|
1910
|
-
let s = text;
|
|
1911
|
-
s = s.replace(/\\\{/g, "\x00LB\x00");
|
|
2134
|
+
let s = text.replace(/\\\{/g, "\x00LB\x00");
|
|
1912
2135
|
s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
|
|
1913
2136
|
return s.replace(/\x00LB\x00/g, "{");
|
|
1914
2137
|
}
|
|
@@ -1920,34 +2143,103 @@ function renderChild(
|
|
|
1920
2143
|
depth: number,
|
|
1921
2144
|
): string {
|
|
1922
2145
|
if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
(
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
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
|
+
);
|
|
1949
2214
|
}
|
|
1950
|
-
|
|
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>`;
|
|
1951
2243
|
}
|
|
1952
2244
|
|
|
1953
2245
|
function renderCompUse(
|
|
@@ -1956,7 +2248,12 @@ function renderCompUse(
|
|
|
1956
2248
|
params: Map<string, string>,
|
|
1957
2249
|
depth: number,
|
|
1958
2250
|
): string {
|
|
1959
|
-
//
|
|
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
|
|
1960
2257
|
if (use.name === "RawHTML") {
|
|
1961
2258
|
const ca = use.attrs.find(a => a.name === "content");
|
|
1962
2259
|
if (!ca || !ca.value) return "";
|
|
@@ -1970,14 +2267,13 @@ function renderCompUse(
|
|
|
1970
2267
|
// Custom element
|
|
1971
2268
|
const customEl = ctx.customEls.get(use.name);
|
|
1972
2269
|
if (customEl) {
|
|
1973
|
-
const attrParts
|
|
2270
|
+
const attrParts = [`data-s="${ctx.scopeHash}"`];
|
|
1974
2271
|
for (const attr of use.attrs) {
|
|
1975
2272
|
const r = renderAttr(attr, params);
|
|
1976
2273
|
if (r) attrParts.push(r);
|
|
1977
2274
|
}
|
|
1978
|
-
const
|
|
1979
|
-
|
|
1980
|
-
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}>`;
|
|
1981
2277
|
}
|
|
1982
2278
|
|
|
1983
2279
|
// Built-in component
|
|
@@ -1986,9 +2282,20 @@ function renderCompUse(
|
|
|
1986
2282
|
|
|
1987
2283
|
const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
|
|
1988
2284
|
let userClass: string | undefined;
|
|
2285
|
+
const inlineStyleParts: string[] = [];
|
|
1989
2286
|
|
|
1990
2287
|
for (const attr of use.attrs) {
|
|
1991
|
-
if (attr.name === "level" && use.name === "Heading") continue;
|
|
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
|
+
|
|
1992
2299
|
if (attr.name === "class") {
|
|
1993
2300
|
if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
|
|
1994
2301
|
continue;
|
|
@@ -1997,21 +2304,15 @@ function renderCompUse(
|
|
|
1997
2304
|
if (rendered) attrParts.push(rendered);
|
|
1998
2305
|
}
|
|
1999
2306
|
|
|
2000
|
-
// Merge default class with user-supplied class
|
|
2001
2307
|
const classes = [defaultClass, userClass].filter(Boolean).join(" ");
|
|
2002
2308
|
if (classes) attrParts.push(`class="${escAttr(classes)}"`);
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
if (tag === "button" && !use.attrs.some(a => a.name === "type")) {
|
|
2006
|
-
attrParts.push(`type="button"`);
|
|
2007
|
-
}
|
|
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"`);
|
|
2008
2311
|
|
|
2009
2312
|
const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
2010
2313
|
|
|
2011
2314
|
if (isVoid) {
|
|
2012
|
-
if (use.children.length > 0) {
|
|
2013
|
-
SinthWarning.emit(`<${tag}> is a void element and cannot have children.`, use.loc);
|
|
2014
|
-
}
|
|
2315
|
+
if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
|
|
2015
2316
|
return `<${tag}${attrStr}>`;
|
|
2016
2317
|
}
|
|
2017
2318
|
|
|
@@ -2026,20 +2327,16 @@ function expandUserComp(
|
|
|
2026
2327
|
params: Map<string, string>,
|
|
2027
2328
|
depth: number,
|
|
2028
2329
|
): string {
|
|
2029
|
-
// Recursion check
|
|
2030
2330
|
if (use.name === def.name && depth > 1) {
|
|
2031
2331
|
throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
|
|
2032
2332
|
}
|
|
2033
2333
|
|
|
2034
|
-
// Build local parameter map
|
|
2035
2334
|
const local = new Map<string, string>();
|
|
2036
2335
|
|
|
2037
|
-
// Apply defaults first
|
|
2038
2336
|
for (const p of def.params) {
|
|
2039
2337
|
if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
|
|
2040
2338
|
}
|
|
2041
2339
|
|
|
2042
|
-
// Apply caller-supplied attributes
|
|
2043
2340
|
for (const attr of use.attrs) {
|
|
2044
2341
|
if (attr.value === null) {
|
|
2045
2342
|
local.set(attr.name, "true");
|
|
@@ -2049,7 +2346,6 @@ function expandUserComp(
|
|
|
2049
2346
|
}
|
|
2050
2347
|
}
|
|
2051
2348
|
|
|
2052
|
-
// Validate required parameters
|
|
2053
2349
|
for (const p of def.params) {
|
|
2054
2350
|
if (!local.has(p.name)) {
|
|
2055
2351
|
throw new SinthError(
|
|
@@ -2059,11 +2355,9 @@ function expandUserComp(
|
|
|
2059
2355
|
}
|
|
2060
2356
|
}
|
|
2061
2357
|
|
|
2062
|
-
// Render slot: children at the call site
|
|
2063
2358
|
const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
2064
2359
|
local.set("slot", slotHTML);
|
|
2065
2360
|
|
|
2066
|
-
// === v0.1.0: Process component style blocks with instance params and push to extraCSS ===
|
|
2067
2361
|
for (const block of def.styles) {
|
|
2068
2362
|
ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
|
|
2069
2363
|
}
|
|
@@ -2071,41 +2365,9 @@ function expandUserComp(
|
|
|
2071
2365
|
return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
|
|
2072
2366
|
}
|
|
2073
2367
|
|
|
2074
|
-
//
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
case "literal":
|
|
2078
|
-
if (!expr.value) return "null";
|
|
2079
|
-
if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
|
|
2080
|
-
if (expr.value.kind === "num") return String((expr.value as LitNum).value);
|
|
2081
|
-
if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
|
|
2082
|
-
return "null";
|
|
2083
|
-
case "variable":
|
|
2084
|
-
return expr.name || "undefined";
|
|
2085
|
-
case "binary": {
|
|
2086
|
-
const left = compileExprToJS(expr.left!);
|
|
2087
|
-
const right = compileExprToJS(expr.right!);
|
|
2088
|
-
const op = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op;
|
|
2089
|
-
return `(${left} ${op} ${right})`;
|
|
2090
|
-
}
|
|
2091
|
-
case "unary": {
|
|
2092
|
-
const op = expr.op === "not" ? "!" : expr.op;
|
|
2093
|
-
return `${op}(${compileExprToJS(expr.operand!)})`;
|
|
2094
|
-
}
|
|
2095
|
-
case "assign": {
|
|
2096
|
-
const val = expr.right ? compileExprToJS(expr.right) : "null";
|
|
2097
|
-
return `${expr.target} ${expr.op} ${val}`;
|
|
2098
|
-
}
|
|
2099
|
-
case "postfix":
|
|
2100
|
-
return `${expr.target}${expr.op}`;
|
|
2101
|
-
default:
|
|
2102
|
-
return "";
|
|
2103
|
-
}
|
|
2104
|
-
}
|
|
2105
|
-
|
|
2106
|
-
// ═══════════════════════════════════════════════════════════
|
|
2107
|
-
// SECTION 9: SCRIPT COLLECTOR
|
|
2108
|
-
// ═══════════════════════════════════════════════════════════
|
|
2368
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2369
|
+
// §11 SCRIPT COLLECTOR
|
|
2370
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2109
2371
|
|
|
2110
2372
|
function collectScripts(
|
|
2111
2373
|
file: SinthFile,
|
|
@@ -2115,25 +2377,19 @@ function collectScripts(
|
|
|
2115
2377
|
const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
|
|
2116
2378
|
const seenFunctions = new Set<string>();
|
|
2117
2379
|
|
|
2118
|
-
// Component script blocks → hoisted as IIFEs
|
|
2119
2380
|
for (const [, def] of allDefs) {
|
|
2120
2381
|
for (const block of def.scripts) {
|
|
2121
2382
|
for (const fn of extractFunctionNames(block.raw)) {
|
|
2122
|
-
if (seenFunctions.has(fn)) {
|
|
2123
|
-
throw new SinthError(`Function '${fn}' defined in multiple component script blocks.`);
|
|
2124
|
-
}
|
|
2383
|
+
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
|
|
2125
2384
|
seenFunctions.add(fn);
|
|
2126
2385
|
}
|
|
2127
2386
|
componentScripts.push(`(function(){\n${block.raw}\n})();`);
|
|
2128
2387
|
}
|
|
2129
2388
|
}
|
|
2130
2389
|
|
|
2131
|
-
// Page-level script blocks
|
|
2132
2390
|
for (const block of file.scripts) {
|
|
2133
2391
|
for (const fn of extractFunctionNames(block.raw)) {
|
|
2134
|
-
if (seenFunctions.has(fn)) {
|
|
2135
|
-
throw new SinthError(`Function '${fn}' conflicts with a component script.`);
|
|
2136
|
-
}
|
|
2392
|
+
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
|
|
2137
2393
|
seenFunctions.add(fn);
|
|
2138
2394
|
}
|
|
2139
2395
|
pageScripts.push({ raw: block.raw, attrs: block.attrs });
|
|
@@ -2145,14 +2401,14 @@ function collectScripts(
|
|
|
2145
2401
|
function extractFunctionNames(js: string): string[] {
|
|
2146
2402
|
const names: string[] = [];
|
|
2147
2403
|
const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
|
|
2148
|
-
let
|
|
2404
|
+
let m: RegExpExecArray | null;
|
|
2149
2405
|
while ((m = re.exec(js)) !== null) names.push(m[1]);
|
|
2150
2406
|
return names;
|
|
2151
2407
|
}
|
|
2152
2408
|
|
|
2153
|
-
//
|
|
2154
|
-
//
|
|
2155
|
-
//
|
|
2409
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2410
|
+
// §12 HEAD GENERATOR
|
|
2411
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2156
2412
|
|
|
2157
2413
|
interface HeadData {
|
|
2158
2414
|
title?: string; fav?: string;
|
|
@@ -2163,9 +2419,7 @@ interface HeadData {
|
|
|
2163
2419
|
|
|
2164
2420
|
function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
2165
2421
|
let title: string | undefined, fav: string | undefined;
|
|
2166
|
-
let lang
|
|
2167
|
-
let charset = "UTF-8";
|
|
2168
|
-
let viewport = "width=device-width, initial-scale=1.0";
|
|
2422
|
+
let lang = "en", charset = "UTF-8", viewport = "width=device-width, initial-scale=1.0";
|
|
2169
2423
|
const metaTags: { name: string; content: string }[] = [];
|
|
2170
2424
|
const metaProps: { property: string; content: string }[] = [];
|
|
2171
2425
|
|
|
@@ -2184,8 +2438,8 @@ function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
|
2184
2438
|
default:
|
|
2185
2439
|
if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
|
|
2186
2440
|
const prop = m.key
|
|
2187
|
-
.replace(/^og([A-Z])/, (_, c: string) => `og:${c.toLowerCase()}`)
|
|
2188
|
-
.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()}`);
|
|
2189
2443
|
metaProps.push({ property: prop, content: val });
|
|
2190
2444
|
} else {
|
|
2191
2445
|
metaTags.push({ name: camelToKebab(m.key), content: val });
|
|
@@ -2196,10 +2450,8 @@ function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
|
2196
2450
|
return { title, fav, lang, charset, viewport, metaTags, metaProps };
|
|
2197
2451
|
}
|
|
2198
2452
|
|
|
2199
|
-
// === v0.1.0: .jpg and .jpeg return "image/jpeg" ===
|
|
2200
2453
|
function faviconType(p: string): string {
|
|
2201
|
-
|
|
2202
|
-
switch (ext) {
|
|
2454
|
+
switch (path.extname(p).toLowerCase()) {
|
|
2203
2455
|
case ".ico": return "image/x-icon";
|
|
2204
2456
|
case ".png": return "image/png";
|
|
2205
2457
|
case ".svg": return "image/svg+xml";
|
|
@@ -2208,7 +2460,7 @@ function faviconType(p: string): string {
|
|
|
2208
2460
|
case ".jpg":
|
|
2209
2461
|
case ".jpeg": return "image/jpeg";
|
|
2210
2462
|
default:
|
|
2211
|
-
SinthWarning.emit(`Unknown favicon extension '${
|
|
2463
|
+
SinthWarning.emit(`Unknown favicon extension '${path.extname(p)}', defaulting to image/x-icon`);
|
|
2212
2464
|
return "image/x-icon";
|
|
2213
2465
|
}
|
|
2214
2466
|
}
|
|
@@ -2239,9 +2491,317 @@ function renderHead(
|
|
|
2239
2491
|
return `<head>\n${lines.join("\n")}\n</head>`;
|
|
2240
2492
|
}
|
|
2241
2493
|
|
|
2242
|
-
//
|
|
2243
|
-
//
|
|
2244
|
-
//
|
|
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
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2245
2805
|
|
|
2246
2806
|
interface CompileOptions {
|
|
2247
2807
|
projectRoot: string;
|
|
@@ -2259,14 +2819,20 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
|
|
|
2259
2819
|
const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
|
|
2260
2820
|
const hash = fnv1a(absPath);
|
|
2261
2821
|
|
|
2262
|
-
//
|
|
2822
|
+
// All var declarations are already collected via shared _varDecls reference
|
|
2823
|
+
const allVarDecls: VarDeclaration[] = file.varDecls;
|
|
2824
|
+
|
|
2263
2825
|
const ctx: CompileCtx = {
|
|
2264
2826
|
allDefs, customEls, cssLinks, jsLinks,
|
|
2265
|
-
scopeHash:
|
|
2827
|
+
scopeHash: hash,
|
|
2828
|
+
pageFile: absPath,
|
|
2829
|
+
extraCSS: [],
|
|
2830
|
+
mixedBlocks: [],
|
|
2831
|
+
mixedCounter: 0,
|
|
2832
|
+
logicBlocks: [],
|
|
2266
2833
|
};
|
|
2267
2834
|
|
|
2268
2835
|
if (!file.isPage) {
|
|
2269
|
-
// Component file → fragment only
|
|
2270
2836
|
const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
2271
2837
|
const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
|
|
2272
2838
|
const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
|
|
@@ -2275,36 +2841,32 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
|
|
|
2275
2841
|
|
|
2276
2842
|
const headData = buildHeadData(file.meta);
|
|
2277
2843
|
|
|
2278
|
-
// Render body HTML
|
|
2844
|
+
// Render body HTML (populates ctx.extraCSS, ctx.mixedBlocks, ctx.logicBlocks)
|
|
2279
2845
|
const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
2280
2846
|
|
|
2281
|
-
|
|
2282
|
-
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");
|
|
2283
2848
|
const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
|
|
2284
2849
|
|
|
2285
2850
|
const { componentScripts, pageScripts } = collectScripts(file, allDefs);
|
|
2286
2851
|
|
|
2852
|
+
// Collect all assigned variables for default-value warnings
|
|
2287
2853
|
const assignedVars = new Set<string>();
|
|
2288
2854
|
for (const s of file.scripts) {
|
|
2289
|
-
const
|
|
2290
|
-
for (const m of matches) assignedVars.add(m[1]);
|
|
2291
|
-
}
|
|
2292
|
-
for (const v of file.varDecls) {
|
|
2293
|
-
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]);
|
|
2294
2856
|
}
|
|
2857
|
+
for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
|
|
2295
2858
|
|
|
2859
|
+
// Companion JS file (same name as .sinth)
|
|
2296
2860
|
const companionJS = (() => {
|
|
2297
2861
|
const base = absPath.replace(/\.sinth$/, ".js");
|
|
2298
2862
|
return fs.existsSync(base) ? path.basename(base) : undefined;
|
|
2299
2863
|
})();
|
|
2300
2864
|
|
|
2301
|
-
|
|
2865
|
+
// Make CSS / JS links relative to the HTML output directory
|
|
2302
2866
|
const relativeCssLinks = cssLinks.map(css => {
|
|
2303
2867
|
const rel = path.relative(path.dirname(absPath), css).replace(/\\/g, "/");
|
|
2304
2868
|
return rel.startsWith(".") ? rel : "./" + rel;
|
|
2305
2869
|
});
|
|
2306
|
-
|
|
2307
|
-
// Convert JS absolute paths to relative paths from the HTML output
|
|
2308
2870
|
const relativeJsLinks = jsLinks.map(js => ({
|
|
2309
2871
|
...js,
|
|
2310
2872
|
src: (() => {
|
|
@@ -2313,26 +2875,31 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
|
|
|
2313
2875
|
})(),
|
|
2314
2876
|
}));
|
|
2315
2877
|
|
|
2316
|
-
const head
|
|
2317
|
-
|
|
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
|
+
});
|
|
2318
2888
|
|
|
2889
|
+
// Component-level script IIFEs
|
|
2890
|
+
const scriptTags: string[] = [];
|
|
2319
2891
|
if (componentScripts.length > 0) {
|
|
2320
2892
|
scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
|
|
2321
2893
|
}
|
|
2322
|
-
|
|
2323
|
-
|
|
2894
|
+
|
|
2895
|
+
// Page-level script blocks
|
|
2896
|
+
for (const s of pageScripts) {
|
|
2324
2897
|
const extra = Object.entries(s.attrs)
|
|
2325
2898
|
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
2326
2899
|
.join(" ");
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
if (globalRaw.trim().startsWith("if (")) {
|
|
2331
|
-
logicScriptsRaw += globalRaw + "\n";
|
|
2332
|
-
} else {
|
|
2333
|
-
scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalRaw}\n</script>`);
|
|
2334
|
-
}
|
|
2335
|
-
}
|
|
2900
|
+
const globalised = s.raw.replace(/\b(let|const)\b/g, "var");
|
|
2901
|
+
scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalised}\n</script>`);
|
|
2902
|
+
}
|
|
2336
2903
|
|
|
2337
2904
|
const html = [
|
|
2338
2905
|
"<!DOCTYPE html>",
|
|
@@ -2340,129 +2907,11 @@ for (const s of pageScripts) {
|
|
|
2340
2907
|
head,
|
|
2341
2908
|
`<body data-s="${hash}">`,
|
|
2342
2909
|
bodyHTML,
|
|
2343
|
-
`<script
|
|
2344
|
-
//Compiled using Sinth Logic
|
|
2345
|
-
${file.varDecls.map(v => {
|
|
2346
|
-
if (!v.value) {
|
|
2347
|
-
if (!assignedVars.has(v.name)) {
|
|
2348
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
2349
|
-
const defaultVal = defaults[v.varType] || "undefined";
|
|
2350
|
-
SinthWarning.emit(`Variable '${v.name}' is declared but never assigned. Using default value ${defaultVal}.`, v.loc);
|
|
2351
|
-
}
|
|
2352
|
-
if (v.varType === "str") return `var ${v.name} = "";`;
|
|
2353
|
-
if (v.varType === "int") return `var ${v.name} = 0;`;
|
|
2354
|
-
if (v.varType === "bool") return `var ${v.name} = false;`;
|
|
2355
|
-
if (v.varType === "str[]") return `var ${v.name} = [];`;
|
|
2356
|
-
return `var ${v.name};`;
|
|
2357
|
-
}
|
|
2358
|
-
const val = litToString(v.value);
|
|
2359
|
-
|
|
2360
|
-
if (v.varType !== "str[]" && val.startsWith("__VAR__")) {
|
|
2361
|
-
const refName = val.slice(7);
|
|
2362
|
-
return `var ${v.name} = ${refName};`;
|
|
2363
|
-
}
|
|
2364
|
-
|
|
2365
|
-
if (val.startsWith("__ARR__")) {
|
|
2366
|
-
return `var ${v.name} = ${val.slice(7)};`;
|
|
2367
|
-
}
|
|
2368
|
-
|
|
2369
|
-
if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
|
|
2370
|
-
return `var ${v.name} = ${val};`;
|
|
2371
|
-
}).join("\n")}
|
|
2372
|
-
${(bodyHTML.includes('data-sinth-if') || bodyHTML.includes('data-sinth-for') || bodyHTML.includes('data-sinth-delay') || bodyHTML.includes('sinth-expr')) ? `
|
|
2373
|
-
function sinthRender() {
|
|
2374
|
-
const scrollX = window.scrollX;
|
|
2375
|
-
const scrollY = window.scrollY;
|
|
2376
|
-
${(bodyHTML.includes('data-sinth-if') || bodyHTML.includes('data-sinth-for')) ? `
|
|
2377
|
-
function processTemplates(root) {${bodyHTML.includes('data-sinth-if') ? `
|
|
2378
|
-
root.querySelectorAll('template[data-sinth-if]').forEach(t => {
|
|
2379
|
-
// Store original HTML on first pass
|
|
2380
|
-
if (!t.dataset.sinthOriginal) {
|
|
2381
|
-
t.dataset.sinthOriginal = t.innerHTML;
|
|
2382
|
-
}
|
|
2383
|
-
const cond = eval(t.dataset.sinthIf);
|
|
2384
|
-
// Find any previously inserted content
|
|
2385
|
-
const existing = t.parentNode.querySelector('[data-sinth-if-anchor="' + t.dataset.sinthIf + '"]');
|
|
2386
|
-
if (cond) {
|
|
2387
|
-
if (!existing) {
|
|
2388
|
-
// Insert new content with anchor marker
|
|
2389
|
-
const anchor = document.createElement('span');
|
|
2390
|
-
anchor.style.display = 'none';
|
|
2391
|
-
anchor.dataset.sinthIfAnchor = t.dataset.sinthIf;
|
|
2392
|
-
const frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
2393
|
-
t.parentNode.insertBefore(anchor, t);
|
|
2394
|
-
t.parentNode.insertBefore(frag, t);${bodyHTML.includes('sinth-expr') ? `
|
|
2395
|
-
root.querySelectorAll('.sinth-expr').forEach(el => {
|
|
2396
|
-
try { el.textContent = eval(el.dataset.expr); } catch(e) {}
|
|
2397
|
-
});` : ''}
|
|
2398
|
-
}
|
|
2399
|
-
} else {
|
|
2400
|
-
// Remove inserted content if condition is false
|
|
2401
|
-
if (existing) {
|
|
2402
|
-
let next = existing.nextSibling;
|
|
2403
|
-
while (next && next !== t && !(next.dataset && next.dataset.sinthIfAnchor)) {
|
|
2404
|
-
const toRemove = next;
|
|
2405
|
-
next = next.nextSibling;
|
|
2406
|
-
toRemove.remove();
|
|
2407
|
-
}
|
|
2408
|
-
existing.remove();
|
|
2409
|
-
}
|
|
2410
|
-
// Also handle else
|
|
2411
|
-
const elseT = t.nextElementSibling;
|
|
2412
|
-
if (elseT && elseT.matches && elseT.matches('template[data-sinth-else]')) {
|
|
2413
|
-
if (!elseT.dataset.sinthOriginal) {
|
|
2414
|
-
elseT.dataset.sinthOriginal = elseT.innerHTML;
|
|
2415
|
-
}
|
|
2416
|
-
const elseAnchor = t.parentNode.querySelector('[data-sinth-if-anchor="else-' + t.dataset.sinthIf + '"]');
|
|
2417
|
-
const elseExisting = elseAnchor ? elseAnchor.nextSibling : null;
|
|
2418
|
-
if (!elseExisting || elseExisting === t) {
|
|
2419
|
-
const anchor = document.createElement('span');
|
|
2420
|
-
anchor.style.display = 'none';
|
|
2421
|
-
anchor.dataset.sinthIfAnchor = 'else-' + t.dataset.sinthIf;
|
|
2422
|
-
const frag = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
2423
|
-
t.parentNode.insertBefore(anchor, t);
|
|
2424
|
-
t.parentNode.insertBefore(frag, t);${bodyHTML.includes('sinth-expr') ? `
|
|
2425
|
-
root.querySelectorAll('.sinth-expr').forEach(el => {
|
|
2426
|
-
try { el.textContent = eval(el.dataset.expr); } catch(e) {}
|
|
2427
|
-
});` : ''}
|
|
2428
|
-
}
|
|
2429
|
-
}
|
|
2430
|
-
}
|
|
2431
|
-
});` : ''}
|
|
2432
|
-
}
|
|
2433
|
-
processTemplates(document.body);` : ''}${bodyHTML.includes('data-sinth-delay') ? `
|
|
2434
|
-
setTimeout(() => {
|
|
2435
|
-
document.querySelectorAll('[data-sinth-delay]').forEach(el => {
|
|
2436
|
-
const delayMs = parseInt(el.dataset.sinthDelay) || 0;
|
|
2437
|
-
if (delayMs > 0) {
|
|
2438
|
-
setTimeout(() => { el.style.display = ''; }, delayMs);
|
|
2439
|
-
}
|
|
2440
|
-
});
|
|
2441
|
-
document.querySelectorAll('[data-sinth-delay-expr]').forEach(el => {
|
|
2442
|
-
try {
|
|
2443
|
-
const delayMs = parseInt(eval(el.dataset.sinthDelayExpr)) || 0;
|
|
2444
|
-
if (delayMs > 0) {
|
|
2445
|
-
setTimeout(() => { el.style.display = ''; }, delayMs);
|
|
2446
|
-
}
|
|
2447
|
-
} catch(e) {}
|
|
2448
|
-
});
|
|
2449
|
-
}, 0);` : ''}
|
|
2450
|
-
|
|
2451
|
-
${logicScriptsRaw}
|
|
2452
|
-
${bodyHTML.includes('sinth-expr') ? `
|
|
2453
|
-
document.querySelectorAll('.sinth-expr').forEach(el => {
|
|
2454
|
-
try { el.textContent = eval(el.dataset.expr); } catch(e) {}
|
|
2455
|
-
});` : ''}
|
|
2456
|
-
window.scrollTo(scrollX, scrollY);
|
|
2457
|
-
}
|
|
2458
|
-
|
|
2459
|
-
sinthRender();` : ''}
|
|
2460
|
-
|
|
2461
|
-
</script>`,
|
|
2910
|
+
runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
|
|
2462
2911
|
scriptTags.join("\n"),
|
|
2463
2912
|
"</body>",
|
|
2464
2913
|
"</html>",
|
|
2465
|
-
].join("\n");
|
|
2914
|
+
].filter(Boolean).join("\n");
|
|
2466
2915
|
|
|
2467
2916
|
return opts.minify ? minifyHTML(html) : html;
|
|
2468
2917
|
}
|
|
@@ -2471,27 +2920,22 @@ function minifyHTML(html: string): string {
|
|
|
2471
2920
|
return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
|
|
2472
2921
|
}
|
|
2473
2922
|
|
|
2474
|
-
//
|
|
2475
|
-
//
|
|
2476
|
-
//
|
|
2923
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2924
|
+
// §15 FILE DISCOVERY & ASSET COPY
|
|
2925
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2477
2926
|
|
|
2478
|
-
// === v0.1.0: findSinthPages skips outDir to prevent infinite watcher loops ===
|
|
2479
2927
|
function findSinthPages(dir: string, outDir?: string): string[] {
|
|
2480
2928
|
const results: string[] = [];
|
|
2481
2929
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
2482
2930
|
if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
2483
2931
|
const full = path.join(dir, entry.name);
|
|
2484
2932
|
if (outDir && path.resolve(full) === path.resolve(outDir)) continue;
|
|
2485
|
-
if (entry.isDirectory())
|
|
2486
|
-
|
|
2487
|
-
} else if (entry.name.endsWith(".sinth")) {
|
|
2488
|
-
results.push(full);
|
|
2489
|
-
}
|
|
2933
|
+
if (entry.isDirectory()) results.push(...findSinthPages(full, outDir));
|
|
2934
|
+
else if (entry.name.endsWith(".sinth")) results.push(full);
|
|
2490
2935
|
}
|
|
2491
2936
|
return results;
|
|
2492
2937
|
}
|
|
2493
2938
|
|
|
2494
|
-
// === v0.1.0: Recursive directory copy for assets/ ===
|
|
2495
2939
|
function copyDir(src: string, dest: string): void {
|
|
2496
2940
|
if (!fs.existsSync(src)) return;
|
|
2497
2941
|
fs.mkdirSync(dest, { recursive: true });
|
|
@@ -2503,21 +2947,20 @@ function copyDir(src: string, dest: string): void {
|
|
|
2503
2947
|
}
|
|
2504
2948
|
}
|
|
2505
2949
|
|
|
2506
|
-
//
|
|
2507
|
-
//
|
|
2508
|
-
//
|
|
2950
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2951
|
+
// §16 DEV SERVER
|
|
2952
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2509
2953
|
|
|
2510
2954
|
const LIVE_RELOAD_SCRIPT = `<script>
|
|
2511
2955
|
(function(){
|
|
2512
|
-
|
|
2513
|
-
es.onmessage = ()
|
|
2514
|
-
es.onerror = ()
|
|
2956
|
+
var es = new EventSource('/__sinth_sse__');
|
|
2957
|
+
es.onmessage = function() { location.reload(); };
|
|
2958
|
+
es.onerror = function() { setTimeout(function() { location.reload(); }, 1000); };
|
|
2515
2959
|
})();
|
|
2516
2960
|
</script>`;
|
|
2517
2961
|
|
|
2518
|
-
async function startDevServer(opts: CompileOptions & { port: number
|
|
2962
|
+
async function startDevServer(opts: CompileOptions & { port: number; files?: string[] }): Promise<void> {
|
|
2519
2963
|
const clients: http.ServerResponse[] = [];
|
|
2520
|
-
let debounce: ReturnType<typeof setTimeout> | null = null;
|
|
2521
2964
|
const cache = new Map<string, string>();
|
|
2522
2965
|
|
|
2523
2966
|
function notify(): void {
|
|
@@ -2533,12 +2976,9 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
|
|
|
2533
2976
|
try {
|
|
2534
2977
|
const html = compileFile(p, { ...opts, checkOnly: false });
|
|
2535
2978
|
if (!html) continue;
|
|
2536
|
-
const rel = path.relative(opts.projectRoot, p)
|
|
2537
|
-
.replace(/\.sinth$/, ".html")
|
|
2538
|
-
.replace(/\\/g, "/");
|
|
2979
|
+
const rel = path.relative(opts.projectRoot, p).replace(/\.sinth$/, ".html").replace(/\\/g, "/");
|
|
2539
2980
|
const url = "/" + rel;
|
|
2540
2981
|
cache.set(url, html + LIVE_RELOAD_SCRIPT);
|
|
2541
|
-
// Also map root URL to index.html
|
|
2542
2982
|
if (rel === "index.html" || rel.endsWith("/index.html")) {
|
|
2543
2983
|
cache.set("/", html + LIVE_RELOAD_SCRIPT);
|
|
2544
2984
|
}
|
|
@@ -2550,38 +2990,33 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
|
|
|
2550
2990
|
|
|
2551
2991
|
compileAll();
|
|
2552
2992
|
|
|
2553
|
-
// === v0.1.0: Watch ignores changes whose absolute path is inside outDir ===
|
|
2554
2993
|
const resolvedOut = path.resolve(opts.outDir);
|
|
2555
|
-
|
|
2556
|
-
let watchReady = false;
|
|
2994
|
+
let watchReady = false;
|
|
2557
2995
|
try {
|
|
2558
2996
|
fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
|
|
2559
2997
|
if (!filename) return;
|
|
2560
2998
|
const abs = path.resolve(opts.projectRoot, filename);
|
|
2561
2999
|
if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut) return;
|
|
2562
3000
|
process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
|
|
2563
|
-
compileAll();
|
|
2564
|
-
notify();
|
|
3001
|
+
compileAll(); notify();
|
|
2565
3002
|
});
|
|
2566
3003
|
watchReady = true;
|
|
2567
3004
|
} catch {}
|
|
2568
3005
|
|
|
2569
3006
|
if (!watchReady) {
|
|
2570
|
-
|
|
3007
|
+
const mtimes = new Map<string, number>();
|
|
2571
3008
|
const poller = setInterval(() => {
|
|
2572
3009
|
const pages = (opts.files && opts.files.length > 0)
|
|
2573
|
-
? opts.files
|
|
2574
|
-
: findSinthPages(opts.projectRoot, opts.outDir);
|
|
3010
|
+
? opts.files : findSinthPages(opts.projectRoot, opts.outDir);
|
|
2575
3011
|
for (const p of pages) {
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
}
|
|
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 {}
|
|
2585
3020
|
}
|
|
2586
3021
|
}, 500);
|
|
2587
3022
|
process.on("exit", () => clearInterval(poller));
|
|
@@ -2589,8 +3024,7 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
|
|
|
2589
3024
|
|
|
2590
3025
|
const EXT_TYPES: Record<string, string> = {
|
|
2591
3026
|
".css": "text/css", ".js": "application/javascript",
|
|
2592
|
-
".png": "image/png", ".svg": "image/svg+xml",
|
|
2593
|
-
".ico": "image/x-icon",
|
|
3027
|
+
".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon",
|
|
2594
3028
|
".jpg": "image/jpeg", ".jpeg": "image/jpeg",
|
|
2595
3029
|
".gif": "image/gif", ".webp": "image/webp",
|
|
2596
3030
|
".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf",
|
|
@@ -2600,31 +3034,17 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
|
|
|
2600
3034
|
const server = http.createServer((req, res) => {
|
|
2601
3035
|
const reqUrl = (req.url ?? "/").split("?")[0];
|
|
2602
3036
|
|
|
2603
|
-
// SSE endpoint for live reload
|
|
2604
3037
|
if (reqUrl === "/__sinth_sse__") {
|
|
2605
|
-
res.writeHead(200, {
|
|
2606
|
-
"Content-Type": "text/event-stream",
|
|
2607
|
-
"Cache-Control": "no-cache",
|
|
2608
|
-
"Connection": "keep-alive",
|
|
2609
|
-
});
|
|
3038
|
+
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
|
|
2610
3039
|
clients.push(res);
|
|
2611
|
-
req.on("close", () => {
|
|
2612
|
-
const i = clients.indexOf(res);
|
|
2613
|
-
if (i !== -1) clients.splice(i, 1);
|
|
2614
|
-
});
|
|
3040
|
+
req.on("close", () => { const i = clients.indexOf(res); if (i !== -1) clients.splice(i, 1); });
|
|
2615
3041
|
return;
|
|
2616
3042
|
}
|
|
2617
3043
|
|
|
2618
|
-
// Serve cached compiled HTML
|
|
2619
3044
|
const cached = cache.get(reqUrl) ??
|
|
2620
3045
|
cache.get(reqUrl.endsWith("/") ? reqUrl + "index.html" : reqUrl + ".html");
|
|
2621
|
-
if (cached) {
|
|
2622
|
-
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
2623
|
-
res.end(cached);
|
|
2624
|
-
return;
|
|
2625
|
-
}
|
|
3046
|
+
if (cached) { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(cached); return; }
|
|
2626
3047
|
|
|
2627
|
-
// Serve static files (assets, CSS, fonts, etc.)
|
|
2628
3048
|
let filePath = path.join(opts.projectRoot, reqUrl);
|
|
2629
3049
|
if (reqUrl.endsWith("/")) filePath = path.join(filePath, "index.html");
|
|
2630
3050
|
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
@@ -2634,8 +3054,7 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
|
|
|
2634
3054
|
return;
|
|
2635
3055
|
}
|
|
2636
3056
|
|
|
2637
|
-
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2638
|
-
res.end("404 Not Found");
|
|
3057
|
+
res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 Not Found");
|
|
2639
3058
|
});
|
|
2640
3059
|
|
|
2641
3060
|
server.listen(opts.port, () => {
|
|
@@ -2645,9 +3064,9 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
|
|
|
2645
3064
|
});
|
|
2646
3065
|
}
|
|
2647
3066
|
|
|
2648
|
-
//
|
|
2649
|
-
//
|
|
2650
|
-
//
|
|
3067
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
3068
|
+
// §17 CLI ENTRY POINT
|
|
3069
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2651
3070
|
|
|
2652
3071
|
function loadConfig(root: string): Record<string, unknown> {
|
|
2653
3072
|
const cfgPath = path.join(root, "sinth.config.json");
|
|
@@ -2660,8 +3079,8 @@ function loadConfig(root: string): Record<string, unknown> {
|
|
|
2660
3079
|
|
|
2661
3080
|
async function main(): Promise<void> {
|
|
2662
3081
|
const [,, command, ...args] = process.argv;
|
|
2663
|
-
const cwd
|
|
2664
|
-
const cfg
|
|
3082
|
+
const cwd = process.cwd();
|
|
3083
|
+
const cfg = loadConfig(cwd);
|
|
2665
3084
|
|
|
2666
3085
|
const outDirIdx = args.indexOf("--out");
|
|
2667
3086
|
const outDir = outDirIdx !== -1 ? args[outDirIdx + 1] : (cfg.outDir as string | undefined) ?? path.join(cwd, "dist");
|
|
@@ -2670,7 +3089,6 @@ async function main(): Promise<void> {
|
|
|
2670
3089
|
const minify = args.includes("--prod") || Boolean(cfg.minify);
|
|
2671
3090
|
const libraryPaths = (cfg.libraryPaths as string[] | undefined) ?? [path.join(cwd, "libraries")];
|
|
2672
3091
|
|
|
2673
|
-
// Remove flag values from args so they don't get treated as .sinth files
|
|
2674
3092
|
const flagValues = new Set<string>();
|
|
2675
3093
|
if (outDirIdx !== -1) flagValues.add(args[outDirIdx + 1]);
|
|
2676
3094
|
if (portIdx !== -1) flagValues.add(args[portIdx + 1]);
|
|
@@ -2681,18 +3099,14 @@ async function main(): Promise<void> {
|
|
|
2681
3099
|
switch (command) {
|
|
2682
3100
|
case "build": {
|
|
2683
3101
|
const nonSinth = cleanArgs.filter(a => !a.endsWith(".sinth"));
|
|
2684
|
-
if (nonSinth.length > 0) {
|
|
2685
|
-
|
|
2686
|
-
}
|
|
3102
|
+
if (nonSinth.length > 0) process.stdout.write(`\x1b[33mSkipping non-.sinth files:\x1b[0m ${nonSinth.join(", ")}\n`);
|
|
3103
|
+
|
|
2687
3104
|
const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
|
|
2688
|
-
const pages
|
|
3105
|
+
const pages = fileArgs.length > 0
|
|
2689
3106
|
? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
|
|
2690
3107
|
: findSinthPages(cwd, outDir);
|
|
2691
3108
|
|
|
2692
|
-
if (pages.length === 0) {
|
|
2693
|
-
process.stdout.write("No .sinth files found.\n");
|
|
2694
|
-
process.exit(0);
|
|
2695
|
-
}
|
|
3109
|
+
if (pages.length === 0) { process.stdout.write("No .sinth files found.\n"); process.exit(0); }
|
|
2696
3110
|
|
|
2697
3111
|
let hadError = false, built = 0;
|
|
2698
3112
|
|
|
@@ -2712,22 +3126,21 @@ async function main(): Promise<void> {
|
|
|
2712
3126
|
}
|
|
2713
3127
|
}
|
|
2714
3128
|
|
|
2715
|
-
//
|
|
2716
|
-
const assetsIn
|
|
2717
|
-
const assetsOut = path.join(outDir, "assets");
|
|
3129
|
+
// Copy assets/
|
|
3130
|
+
const assetsIn = path.join(cwd, "assets"), assetsOut = path.join(outDir, "assets");
|
|
2718
3131
|
if (fs.existsSync(assetsIn)) {
|
|
2719
3132
|
copyDir(assetsIn, assetsOut);
|
|
2720
3133
|
process.stdout.write(` \x1b[32m✓\x1b[0m assets/ → ${path.relative(cwd, assetsOut)}/\n`);
|
|
2721
3134
|
}
|
|
2722
3135
|
|
|
2723
|
-
|
|
2724
|
-
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");
|
|
2725
3138
|
if (fs.existsSync(libIn)) {
|
|
2726
3139
|
copyDir(libIn, libOut);
|
|
2727
|
-
const
|
|
2728
|
-
for (const f of
|
|
3140
|
+
const libFiles = fs.readdirSync(libOut, { recursive: true }) as string[];
|
|
3141
|
+
for (const f of libFiles) {
|
|
2729
3142
|
if (f.endsWith(".sinth") || f.endsWith(".html")) {
|
|
2730
|
-
fs.unlinkSync(path.join(libOut, f));
|
|
3143
|
+
try { fs.unlinkSync(path.join(libOut, f)); } catch {}
|
|
2731
3144
|
}
|
|
2732
3145
|
}
|
|
2733
3146
|
process.stdout.write(` \x1b[32m✓\x1b[0m libraries/ → ${path.relative(cwd, libOut)}/\n`);
|
|
@@ -2740,7 +3153,7 @@ async function main(): Promise<void> {
|
|
|
2740
3153
|
|
|
2741
3154
|
case "dev": {
|
|
2742
3155
|
const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
|
|
2743
|
-
const files
|
|
3156
|
+
const files = fileArgs.length > 0
|
|
2744
3157
|
? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
|
|
2745
3158
|
: undefined;
|
|
2746
3159
|
await startDevServer({ ...opts, port, files });
|
|
@@ -2749,8 +3162,8 @@ async function main(): Promise<void> {
|
|
|
2749
3162
|
|
|
2750
3163
|
case "check": {
|
|
2751
3164
|
opts.checkOnly = true;
|
|
2752
|
-
const pages
|
|
2753
|
-
let hadError
|
|
3165
|
+
const pages = findSinthPages(cwd, outDir);
|
|
3166
|
+
let hadError = false;
|
|
2754
3167
|
for (const p of pages) {
|
|
2755
3168
|
try {
|
|
2756
3169
|
compileFile(p, opts);
|
|
@@ -2764,51 +3177,68 @@ async function main(): Promise<void> {
|
|
|
2764
3177
|
break;
|
|
2765
3178
|
}
|
|
2766
3179
|
|
|
2767
|
-
// === v0.1.0: sinth version command ===
|
|
2768
3180
|
case "version":
|
|
2769
3181
|
case "--version":
|
|
2770
3182
|
case "-v": {
|
|
2771
|
-
const
|
|
2772
|
-
|
|
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
|
+
}
|
|
2773
3190
|
break;
|
|
2774
3191
|
}
|
|
2775
3192
|
|
|
2776
3193
|
case "init": {
|
|
2777
|
-
const projectName =
|
|
2778
|
-
|
|
2779
|
-
scaffoldProject(projectDir);
|
|
3194
|
+
const projectName = cleanArgs[0] || "my-sinth-project";
|
|
3195
|
+
scaffoldProject(path.resolve(cwd, projectName));
|
|
2780
3196
|
break;
|
|
2781
3197
|
}
|
|
2782
3198
|
|
|
2783
3199
|
default: {
|
|
2784
3200
|
process.stdout.write(`
|
|
2785
|
-
\x1b[1mSinth Compiler
|
|
3201
|
+
\x1b[1mSinth Compiler v1.0.0\x1b[0m
|
|
2786
3202
|
|
|
2787
3203
|
\x1b[1mCommands:\x1b[0m
|
|
2788
|
-
sinth build [--out ./dist] [--prod] Compile
|
|
2789
|
-
sinth dev [--port 3000]
|
|
2790
|
-
sinth check
|
|
2791
|
-
sinth init
|
|
2792
|
-
sinth 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
|
|
2793
3209
|
|
|
2794
3210
|
\x1b[1mConfig:\x1b[0m sinth.config.json
|
|
2795
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
|
+
}
|
|
2796
3226
|
`);
|
|
2797
3227
|
break;
|
|
2798
3228
|
}
|
|
2799
3229
|
}
|
|
2800
3230
|
}
|
|
2801
3231
|
|
|
2802
|
-
//
|
|
3232
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
3233
|
+
// §18 PROJECT SCAFFOLDING
|
|
3234
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2803
3235
|
|
|
2804
3236
|
function scaffoldProject(root: string): void {
|
|
2805
3237
|
for (const d of ["pages", "components", "styles", "libraries", "assets"]) {
|
|
2806
3238
|
fs.mkdirSync(path.join(root, d), { recursive: true });
|
|
2807
3239
|
}
|
|
2808
3240
|
|
|
2809
|
-
// Main page
|
|
2810
3241
|
fs.writeFileSync(path.join(root, "pages", "index.sinth"), `-- My Sinth Site
|
|
2811
|
-
|
|
2812
3242
|
page
|
|
2813
3243
|
|
|
2814
3244
|
import "../components/Navbar.sinth"
|
|
@@ -2816,32 +3246,36 @@ import css "../styles/reset.css"
|
|
|
2816
3246
|
|
|
2817
3247
|
title = "My Site"
|
|
2818
3248
|
fav = "assets/favicon.ico"
|
|
2819
|
-
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"
|
|
2820
3253
|
|
|
2821
3254
|
Navbar
|
|
2822
3255
|
|
|
2823
3256
|
Hero {
|
|
2824
3257
|
Heading(level: 1) { "Welcome to Sinth" }
|
|
2825
3258
|
Paragraph { "A declarative, component-based web UI language." }
|
|
2826
|
-
Button(onClick: "
|
|
3259
|
+
Button(onClick: "handleClick") { "Get Started" }
|
|
3260
|
+
Paragraph(id: "score-display") { message }
|
|
2827
3261
|
}
|
|
2828
3262
|
|
|
2829
3263
|
Main {
|
|
2830
3264
|
Section {
|
|
2831
3265
|
Heading(level: 2) { "Features" }
|
|
2832
3266
|
CardGrid {
|
|
2833
|
-
-- Add
|
|
3267
|
+
-- Add Card components here
|
|
2834
3268
|
}
|
|
2835
3269
|
}
|
|
2836
3270
|
}
|
|
2837
3271
|
|
|
2838
3272
|
style {
|
|
2839
|
-
|
|
3273
|
+
section.hero {
|
|
2840
3274
|
padding: "4rem 2rem"
|
|
2841
3275
|
textAlign: "center"
|
|
2842
3276
|
backgroundColor: "#f0f4ff"
|
|
2843
3277
|
}
|
|
2844
|
-
|
|
3278
|
+
main {
|
|
2845
3279
|
maxWidth: "1100px"
|
|
2846
3280
|
margin: "0 auto"
|
|
2847
3281
|
padding: "2rem"
|
|
@@ -2849,13 +3283,14 @@ style {
|
|
|
2849
3283
|
}
|
|
2850
3284
|
|
|
2851
3285
|
script {
|
|
2852
|
-
function
|
|
2853
|
-
|
|
3286
|
+
function handleClick() {
|
|
3287
|
+
score += 1
|
|
3288
|
+
message = "Score: " + score
|
|
3289
|
+
sinthRender()
|
|
2854
3290
|
}
|
|
2855
3291
|
}
|
|
2856
3292
|
`);
|
|
2857
3293
|
|
|
2858
|
-
// Navbar component
|
|
2859
3294
|
fs.writeFileSync(path.join(root, "components", "Navbar.sinth"), `-- Navbar component
|
|
2860
3295
|
|
|
2861
3296
|
component Navbar {
|
|
@@ -2870,7 +3305,7 @@ component Navbar {
|
|
|
2870
3305
|
}
|
|
2871
3306
|
|
|
2872
3307
|
style {
|
|
2873
|
-
|
|
3308
|
+
header {
|
|
2874
3309
|
display: "flex"
|
|
2875
3310
|
alignItems: "center"
|
|
2876
3311
|
padding: "1rem 2rem"
|
|
@@ -2896,12 +3331,11 @@ component Navbar {
|
|
|
2896
3331
|
}
|
|
2897
3332
|
`);
|
|
2898
3333
|
|
|
2899
|
-
// Card component
|
|
2900
3334
|
fs.writeFileSync(path.join(root, "components", "Card.sinth"), `-- Card component
|
|
2901
3335
|
|
|
2902
3336
|
component Card(title, color = "blue") {
|
|
2903
3337
|
Div(class: "card") {
|
|
2904
|
-
Heading(level:
|
|
3338
|
+
Heading(level: 3) { "$title" }
|
|
2905
3339
|
Div(class: "card-body") { "$slot" }
|
|
2906
3340
|
}
|
|
2907
3341
|
|
|
@@ -2910,9 +3344,11 @@ component Card(title, color = "blue") {
|
|
|
2910
3344
|
backgroundColor: "#f7f7f7"
|
|
2911
3345
|
borderRadius: "1rem"
|
|
2912
3346
|
padding: "1.5rem"
|
|
2913
|
-
textAlign: "center"
|
|
2914
3347
|
marginBottom: "1rem"
|
|
2915
3348
|
}
|
|
3349
|
+
.card:hover {
|
|
3350
|
+
boxShadow: "0 4px 16px rgba(0,0,0,0.1)"
|
|
3351
|
+
}
|
|
2916
3352
|
.card-body {
|
|
2917
3353
|
marginTop: "0.75rem"
|
|
2918
3354
|
}
|
|
@@ -2920,41 +3356,30 @@ component Card(title, color = "blue") {
|
|
|
2920
3356
|
}
|
|
2921
3357
|
`);
|
|
2922
3358
|
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
path.join(root, "styles", "reset.css"),
|
|
2926
|
-
`*, *::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`
|
|
2927
3361
|
);
|
|
2928
3362
|
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
path.join(root, "sinth.config.json"),
|
|
2932
|
-
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)
|
|
2933
3365
|
);
|
|
2934
3366
|
|
|
2935
|
-
// .gitignore
|
|
2936
3367
|
fs.writeFileSync(path.join(root, ".gitignore"), "dist/\nnode_modules/\n");
|
|
2937
3368
|
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
scripts: {
|
|
2945
|
-
build: "sinth build",
|
|
2946
|
-
dev: "sinth dev",
|
|
2947
|
-
},
|
|
2948
|
-
devDependencies: { "ts-node": "^10.0.0", typescript: "^5.0.0", sass: "^1.70.0" },
|
|
2949
|
-
}, null, 2),
|
|
2950
|
-
);
|
|
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));
|
|
2951
3375
|
|
|
2952
3376
|
process.stdout.write(`
|
|
2953
|
-
\x1b[32m✓ Sinth project scaffolded
|
|
3377
|
+
\x1b[32m✓ Sinth project scaffolded at ${path.basename(root)}/\x1b[0m
|
|
2954
3378
|
|
|
2955
3379
|
\x1b[1mNext steps:\x1b[0m
|
|
2956
|
-
|
|
2957
|
-
sinth
|
|
3380
|
+
cd ${path.basename(root)}
|
|
3381
|
+
sinth dev
|
|
3382
|
+
sinth build
|
|
2958
3383
|
`);
|
|
2959
3384
|
}
|
|
2960
3385
|
|