@yannosay/sinth 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/bin/sinth.js +5 -5
- package/package.json +44 -45
- package/src/cli.ts +339 -0
- package/src/core/compiler.ts +1585 -0
- package/src/core/expr.ts +60 -0
- package/src/core/lexer.ts +266 -0
- package/src/core/parser.ts +1013 -0
- package/src/core/runtime.ts +398 -0
- package/src/core/types.ts +166 -0
- package/src/resolver.ts +150 -0
- package/src/server.ts +129 -0
- package/src/utils.ts +38 -0
- package/tsconfig.json +6 -2
- package/src/sinth.ts +0 -3693
package/src/sinth.ts
DELETED
|
@@ -1,3693 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Sinth Compiler 0.5.4 — 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
|
|
5
|
-
|
|
6
|
-
import * as fs from "fs";
|
|
7
|
-
import * as path from "path";
|
|
8
|
-
import * as http from "http";
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
interface Loc { file: string; line: number; col: number }
|
|
12
|
-
|
|
13
|
-
// plain `enum TT` so TT[t] string-indexing works at runtime.
|
|
14
|
-
enum TT {
|
|
15
|
-
LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT,
|
|
16
|
-
LBRACKET, RBRACKET,
|
|
17
|
-
STRING, NUMBER, BOOL_TRUE, BOOL_FALSE, NULL_LIT,
|
|
18
|
-
RAW_BLOCK,
|
|
19
|
-
IDENT,
|
|
20
|
-
KW_IMPORT, KW_AS, KW_CSS,
|
|
21
|
-
KW_COMPONENT, KW_STYLE, KW_SCRIPT,
|
|
22
|
-
KW_GLOBAL, KW_PAGE, KW_LANG,
|
|
23
|
-
KW_CUSTOM_EL, KW_CUSTOM,
|
|
24
|
-
KW_IF, KW_ELSE, KW_FOR, KW_IN, KW_REMOVE,
|
|
25
|
-
OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
|
|
26
|
-
OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
|
|
27
|
-
EOF,
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
interface Token { type: TT; value: string; loc: Loc }
|
|
31
|
-
|
|
32
|
-
type LitStr = { kind: "str"; value: string };
|
|
33
|
-
type LitNum = { kind: "num"; value: number };
|
|
34
|
-
type LitBool = { kind: "bool"; value: boolean };
|
|
35
|
-
type LitNull = { kind: "null" };
|
|
36
|
-
type Literal = LitStr | LitNum | LitBool | LitNull;
|
|
37
|
-
|
|
38
|
-
type UnaryOp = "not" | "-";
|
|
39
|
-
type BinaryOp = "+" | "-" | "*" | "/" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "and" | "or";
|
|
40
|
-
type AssignOp = "=" | "+=" | "-=";
|
|
41
|
-
type PostfixOp = "++" | "--";
|
|
42
|
-
|
|
43
|
-
interface Expression {
|
|
44
|
-
kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index";
|
|
45
|
-
value?: Literal;
|
|
46
|
-
name?: string;
|
|
47
|
-
op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
|
|
48
|
-
operand?: Expression;
|
|
49
|
-
left?: Expression;
|
|
50
|
-
right?: Expression;
|
|
51
|
-
target?: string;
|
|
52
|
-
object?: Expression;
|
|
53
|
-
key?: Expression;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
interface Attr { name: string; value: Literal | null; loc: Loc }
|
|
57
|
-
interface TextNode { kind: "text"; value: string; loc: Loc }
|
|
58
|
-
interface CompUse { kind: "use"; name: string; attrs: Attr[]; children: Child[]; loc: Loc }
|
|
59
|
-
interface ExprNode { kind: "expr"; expression: Expression; loc: Loc }
|
|
60
|
-
interface AssignStmt { kind: "assign_stmt"; expression: Expression; loc: Loc }
|
|
61
|
-
interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
|
|
62
|
-
interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
|
|
63
|
-
interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt;
|
|
67
|
-
|
|
68
|
-
interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
|
|
69
|
-
|
|
70
|
-
interface StyleBlock {
|
|
71
|
-
global: boolean;
|
|
72
|
-
lang: "css" | "scss";
|
|
73
|
-
raw: string;
|
|
74
|
-
target?: string;
|
|
75
|
-
extraAttrs: Record<string, string>;
|
|
76
|
-
loc: Loc;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
interface ScriptBlock { raw: string; attrs: Record<string, string>; loc: Loc }
|
|
80
|
-
interface CompDef { name: string; params: ParamDecl[]; body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[]; loc: Loc }
|
|
81
|
-
interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
|
|
82
|
-
interface CustomElInfo { tagName: string; params: ParamDecl[] }
|
|
83
|
-
|
|
84
|
-
type VarType = "int" | "str" | "bool" | "str[]" | "obj";
|
|
85
|
-
interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
|
|
86
|
-
|
|
87
|
-
type ImportNode =
|
|
88
|
-
| { kind: "sinth"; path: string; loc: Loc }
|
|
89
|
-
| { kind: "css"; path: string; loc: Loc }
|
|
90
|
-
| { kind: "js"; name: string; alias?: string; loc: Loc };
|
|
91
|
-
|
|
92
|
-
interface MetaEntry { key: string; value: Literal; loc: Loc }
|
|
93
|
-
|
|
94
|
-
interface SinthFile {
|
|
95
|
-
filePath: string;
|
|
96
|
-
isPage: boolean;
|
|
97
|
-
imports: ImportNode[];
|
|
98
|
-
meta: MetaEntry[];
|
|
99
|
-
defs: CompDef[];
|
|
100
|
-
uses: CompUse[];
|
|
101
|
-
styles: StyleBlock[];
|
|
102
|
-
scripts: ScriptBlock[];
|
|
103
|
-
customEls: CustomElDecl[];
|
|
104
|
-
varDecls: VarDeclaration[];
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
interface MixedBlockEntry {
|
|
108
|
-
id: string;
|
|
109
|
-
conditionJS: string;
|
|
110
|
-
ifJS: string;
|
|
111
|
-
ifHTML: string;
|
|
112
|
-
elseJS: string;
|
|
113
|
-
elseHTML: string;
|
|
114
|
-
replaceId?: string;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
interface CompileCtx {
|
|
118
|
-
allDefs: Map<string, CompDef>;
|
|
119
|
-
customEls: Map<string, CustomElInfo>;
|
|
120
|
-
cssLinks: string[];
|
|
121
|
-
jsLinks: { src: string; attrs: Record<string, string> }[];
|
|
122
|
-
scopeHash: string;
|
|
123
|
-
pageFile: string;
|
|
124
|
-
extraCSS: string[];
|
|
125
|
-
mixedBlocks: MixedBlockEntry[];
|
|
126
|
-
mixedCounter: number;
|
|
127
|
-
logicBlocks: string[];
|
|
128
|
-
ifIdCounter: number;
|
|
129
|
-
exprRegistry: string[];
|
|
130
|
-
exprMap: Map<string, number>;
|
|
131
|
-
loopVars?: Set<string>;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
class SinthError extends Error {
|
|
135
|
-
constructor(
|
|
136
|
-
public readonly rawMsg: string,
|
|
137
|
-
public readonly loc?: Loc,
|
|
138
|
-
public readonly sourceLine?: string,
|
|
139
|
-
) {
|
|
140
|
-
super(SinthError.buildMessage(rawMsg, loc, sourceLine));
|
|
141
|
-
Object.setPrototypeOf(this, SinthError.prototype);
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
static buildMessage(msg: string, loc?: Loc, sourceLine?: string): string {
|
|
145
|
-
let s = `Error: ${msg}`;
|
|
146
|
-
if (loc) {
|
|
147
|
-
s += `\n at: ${loc.file} (line ${loc.line}, col ${loc.col})`;
|
|
148
|
-
if (sourceLine !== undefined) {
|
|
149
|
-
const lineNum = String(loc.line).padStart(4);
|
|
150
|
-
const pointer = " ".repeat(Math.max(0, loc.col - 1)) + "^";
|
|
151
|
-
s += `\n${lineNum} | ${sourceLine}\n | ${pointer}`;
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
return s;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
withSource(lines: string[]): SinthError {
|
|
158
|
-
if (!this.loc || this.sourceLine !== undefined) return this;
|
|
159
|
-
const line = lines[this.loc.line - 1] ?? "";
|
|
160
|
-
return new SinthError(this.rawMsg, this.loc, line);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
class SinthWarning {
|
|
165
|
-
static emit(msg: string, loc?: Loc): void {
|
|
166
|
-
const where = loc ? `\n at: ${loc.file}:${loc.line}` : "";
|
|
167
|
-
process.stderr.write(`\x1b[33mWarning:\x1b[0m ${msg}${where}\n`);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// FNV-1a 32-bit hash → 8-char hex scope id
|
|
172
|
-
function fnv1a(s: string): string {
|
|
173
|
-
let h = 0x811c9dc5;
|
|
174
|
-
for (let i = 0; i < s.length; i++) {
|
|
175
|
-
h ^= s.charCodeAt(i);
|
|
176
|
-
h = Math.imul(h, 0x01000193) >>> 0;
|
|
177
|
-
}
|
|
178
|
-
return h.toString(16).padStart(8, "0").slice(0, 8);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function camelToKebab(s: string): string {
|
|
182
|
-
const vp = s.match(/^(Webkit|Moz|Ms)(.+)$/);
|
|
183
|
-
if (vp) return `-${vp[1].toLowerCase()}-${camelToKebab(vp[2])}`;
|
|
184
|
-
return s.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`);
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
// "w-counter" → "WCounter"
|
|
188
|
-
function tagNameToPascal(tag: string): string {
|
|
189
|
-
return tag.split("-").map(p => p.charAt(0).toUpperCase() + p.slice(1)).join("");
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
function esc(s: string): string {
|
|
193
|
-
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
function escAttr(s: string): string {
|
|
197
|
-
return esc(s).replace(/"/g, """);
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function litToString(lit: Literal): string {
|
|
201
|
-
switch (lit.kind) {
|
|
202
|
-
case "str": return lit.value;
|
|
203
|
-
case "num": return String(lit.value);
|
|
204
|
-
case "bool": return String(lit.value);
|
|
205
|
-
case "null": return "";
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
// lexer
|
|
210
|
-
const KEYWORDS: Record<string, TT> = {
|
|
211
|
-
"import": TT.KW_IMPORT,
|
|
212
|
-
"as": TT.KW_AS,
|
|
213
|
-
"css": TT.KW_CSS,
|
|
214
|
-
"component": TT.KW_COMPONENT,
|
|
215
|
-
"style": TT.KW_STYLE,
|
|
216
|
-
"script": TT.KW_SCRIPT,
|
|
217
|
-
"global": TT.KW_GLOBAL,
|
|
218
|
-
"page": TT.KW_PAGE,
|
|
219
|
-
"lang": TT.KW_LANG,
|
|
220
|
-
"true": TT.BOOL_TRUE,
|
|
221
|
-
"false": TT.BOOL_FALSE,
|
|
222
|
-
"null": TT.NULL_LIT,
|
|
223
|
-
"custom-element": TT.KW_CUSTOM_EL,
|
|
224
|
-
"custom": TT.KW_CUSTOM,
|
|
225
|
-
"if": TT.KW_IF,
|
|
226
|
-
"else": TT.KW_ELSE,
|
|
227
|
-
"for": TT.KW_FOR,
|
|
228
|
-
"in": TT.KW_IN,
|
|
229
|
-
"remove": TT.KW_REMOVE,
|
|
230
|
-
};
|
|
231
|
-
|
|
232
|
-
export class Lexer {
|
|
233
|
-
private pos = 0;
|
|
234
|
-
private line = 1;
|
|
235
|
-
private col = 1;
|
|
236
|
-
private rawBlockPending = false;
|
|
237
|
-
|
|
238
|
-
constructor(public readonly src: string, private readonly file: string) {}
|
|
239
|
-
|
|
240
|
-
tokenize(): Token[] {
|
|
241
|
-
const tokens: Token[] = [];
|
|
242
|
-
while (true) {
|
|
243
|
-
this.skipWS();
|
|
244
|
-
if (this.pos >= this.src.length) break;
|
|
245
|
-
|
|
246
|
-
const loc = this.loc();
|
|
247
|
-
const ch = this.src[this.pos];
|
|
248
|
-
|
|
249
|
-
if (ch === "(") { tokens.push(this.single(TT.LPAREN, loc)); continue; }
|
|
250
|
-
if (ch === ")") { tokens.push(this.single(TT.RPAREN, loc)); continue; }
|
|
251
|
-
if (ch === "}") { tokens.push(this.single(TT.RBRACE, loc)); continue; }
|
|
252
|
-
if (ch === ",") { tokens.push(this.single(TT.COMMA, loc)); continue; }
|
|
253
|
-
if (ch === ".") { tokens.push(this.single(TT.DOT, loc)); continue; }
|
|
254
|
-
if (ch === ":") { tokens.push(this.single(TT.COLON, loc)); continue; }
|
|
255
|
-
if (ch === "[") { tokens.push(this.single(TT.LBRACKET, loc)); continue; }
|
|
256
|
-
if (ch === "]") { tokens.push(this.single(TT.RBRACKET, loc)); continue; }
|
|
257
|
-
|
|
258
|
-
// two-character operators ->
|
|
259
|
-
if (ch === "=" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_EQEQ, value: "==", loc }); continue; }
|
|
260
|
-
if (ch === "!" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_NEQ, value: "!=", loc }); continue; }
|
|
261
|
-
if (ch === ">" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_GTEQ, value: ">=", loc }); continue; }
|
|
262
|
-
if (ch === "<" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_LTEQ, value: "<=", loc }); continue; }
|
|
263
|
-
|
|
264
|
-
if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
|
|
265
|
-
if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
|
|
266
|
-
if (ch === "*") { tokens.push(this.single(TT.OP_STAR, loc)); continue; }
|
|
267
|
-
if (ch === "/") { tokens.push(this.single(TT.OP_SLASH, loc)); continue; }
|
|
268
|
-
if (ch === ";") { tokens.push(this.single(TT.OP_SEMI, loc)); continue; }
|
|
269
|
-
if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
|
|
270
|
-
if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
|
|
271
|
-
if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
|
|
272
|
-
tokens.push(this.single(TT.OP_MINUS, loc)); continue;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
if (ch === "{") {
|
|
276
|
-
if (this.rawBlockPending) {
|
|
277
|
-
this.rawBlockPending = false;
|
|
278
|
-
tokens.push(this.readRawBlock(loc));
|
|
279
|
-
} else {
|
|
280
|
-
tokens.push(this.single(TT.LBRACE, loc));
|
|
281
|
-
}
|
|
282
|
-
continue;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
if (ch === '"' || ch === "'") { tokens.push(this.readString(loc)); continue; }
|
|
286
|
-
|
|
287
|
-
if (this.isDigit(ch) || (ch === "-" && this.isDigit(this.src[this.pos + 1] ?? ""))) {
|
|
288
|
-
tokens.push(this.readNumber(loc)); continue;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
if (this.isIdentStart(ch)) {
|
|
292
|
-
const tok = this.readIdent(loc);
|
|
293
|
-
if (
|
|
294
|
-
tok.type === TT.KW_STYLE ||
|
|
295
|
-
tok.type === TT.KW_SCRIPT ||
|
|
296
|
-
tok.type === TT.KW_COMPONENT ||
|
|
297
|
-
tok.type === TT.KW_CUSTOM_EL ||
|
|
298
|
-
tok.type === TT.KW_CUSTOM
|
|
299
|
-
) {
|
|
300
|
-
this.rawBlockPending = true;
|
|
301
|
-
}
|
|
302
|
-
tokens.push(tok);
|
|
303
|
-
continue;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
throw new SinthError(`Unexpected character '${ch}'`, loc);
|
|
307
|
-
}
|
|
308
|
-
tokens.push({ type: TT.EOF, value: "", loc: this.loc() });
|
|
309
|
-
return tokens;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
private skipWS(): void {
|
|
313
|
-
while (this.pos < this.src.length) {
|
|
314
|
-
const ch = this.src[this.pos];
|
|
315
|
-
if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") { this.adv(); continue; }
|
|
316
|
-
|
|
317
|
-
// sinth comments: -- line or --[ nestable block ]--
|
|
318
|
-
if (ch === "-" && this.src[this.pos + 1] === "-") {
|
|
319
|
-
if (this.src[this.pos + 2] === "[") {
|
|
320
|
-
this.adv(); this.adv(); this.adv();
|
|
321
|
-
let depth = 1;
|
|
322
|
-
while (this.pos < this.src.length && depth > 0) {
|
|
323
|
-
if (this.src[this.pos] === "-" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "[") {
|
|
324
|
-
depth++; this.adv(); this.adv(); this.adv();
|
|
325
|
-
} else if (this.src[this.pos] === "]" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "-") {
|
|
326
|
-
depth--; this.adv(); this.adv(); this.adv();
|
|
327
|
-
} else {
|
|
328
|
-
this.adv();
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
if (depth > 0) throw new SinthError("Unterminated block comment --[ ... ]--", this.loc());
|
|
332
|
-
} else {
|
|
333
|
-
while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
|
|
334
|
-
}
|
|
335
|
-
continue;
|
|
336
|
-
}
|
|
337
|
-
break;
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
private readRawBlock(loc: Loc): Token {
|
|
342
|
-
this.adv(); // consume '{'
|
|
343
|
-
const start = this.pos;
|
|
344
|
-
let depth = 1;
|
|
345
|
-
|
|
346
|
-
while (this.pos < this.src.length && depth > 0) {
|
|
347
|
-
const ch = this.src[this.pos];
|
|
348
|
-
if (ch === '"' || ch === "'" || ch === "`") { this.skipRawString(ch); continue; }
|
|
349
|
-
if (ch === "/" && this.src[this.pos + 1] === "/") {
|
|
350
|
-
while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
|
|
351
|
-
continue;
|
|
352
|
-
}
|
|
353
|
-
if (ch === "/" && this.src[this.pos + 1] === "*") {
|
|
354
|
-
this.adv(); this.adv();
|
|
355
|
-
while (this.pos < this.src.length - 1 &&
|
|
356
|
-
!(this.src[this.pos] === "*" && this.src[this.pos + 1] === "/")) { this.adv(); }
|
|
357
|
-
this.adv(); this.adv();
|
|
358
|
-
continue;
|
|
359
|
-
}
|
|
360
|
-
if (ch === "{") { depth++; this.adv(); }
|
|
361
|
-
else if (ch === "}") {
|
|
362
|
-
depth--;
|
|
363
|
-
if (depth > 0) this.adv();
|
|
364
|
-
} else {
|
|
365
|
-
this.adv();
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
const content = this.src.substring(start, this.pos);
|
|
370
|
-
this.adv(); // consume closing '}'
|
|
371
|
-
return { type: TT.RAW_BLOCK, value: content, loc };
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
private skipRawString(quote: string): void {
|
|
375
|
-
this.adv();
|
|
376
|
-
while (this.pos < this.src.length) {
|
|
377
|
-
const c = this.src[this.pos];
|
|
378
|
-
if (c === "\\") { this.adv(); this.adv(); continue; }
|
|
379
|
-
if (c === quote) { this.adv(); return; }
|
|
380
|
-
if (quote === "`" && c === "$" && this.src[this.pos + 1] === "{") {
|
|
381
|
-
this.adv(); this.adv();
|
|
382
|
-
let d = 1;
|
|
383
|
-
while (this.pos < this.src.length && d > 0) {
|
|
384
|
-
if (this.src[this.pos] === "{") d++;
|
|
385
|
-
else if (this.src[this.pos] === "}") d--;
|
|
386
|
-
this.adv();
|
|
387
|
-
}
|
|
388
|
-
continue;
|
|
389
|
-
}
|
|
390
|
-
this.adv();
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
private readString(loc: Loc): Token {
|
|
395
|
-
const quote = this.src[this.pos];
|
|
396
|
-
this.adv();
|
|
397
|
-
let result = "";
|
|
398
|
-
while (this.pos < this.src.length && this.src[this.pos] !== quote) {
|
|
399
|
-
if (this.src[this.pos] === "\\") {
|
|
400
|
-
this.adv();
|
|
401
|
-
const e = this.src[this.pos];
|
|
402
|
-
switch (e) {
|
|
403
|
-
case "\\": result += "\\"; break;
|
|
404
|
-
case '"': result += '"'; break;
|
|
405
|
-
case "'": result += "'"; break;
|
|
406
|
-
case "n": result += "\n"; break;
|
|
407
|
-
case "r": result += "\r"; break;
|
|
408
|
-
case "t": result += "\t"; break;
|
|
409
|
-
case "$": result += "$"; break;
|
|
410
|
-
case "{": result += "{"; break;
|
|
411
|
-
case "u": {
|
|
412
|
-
this.adv();
|
|
413
|
-
if (this.src[this.pos] === "{") {
|
|
414
|
-
this.adv();
|
|
415
|
-
let hex = "";
|
|
416
|
-
while (this.src[this.pos] !== "}") { hex += this.src[this.pos]; this.adv(); }
|
|
417
|
-
result += String.fromCodePoint(parseInt(hex, 16));
|
|
418
|
-
} else {
|
|
419
|
-
const hex = this.src.substring(this.pos, this.pos + 4);
|
|
420
|
-
result += String.fromCharCode(parseInt(hex, 16));
|
|
421
|
-
this.pos += 3; this.col += 3;
|
|
422
|
-
}
|
|
423
|
-
break;
|
|
424
|
-
}
|
|
425
|
-
default: throw new SinthError(`Unknown escape sequence \\${e}`, loc);
|
|
426
|
-
}
|
|
427
|
-
this.adv();
|
|
428
|
-
} else {
|
|
429
|
-
result += this.src[this.pos];
|
|
430
|
-
this.adv();
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
if (this.pos >= this.src.length) throw new SinthError("Unterminated string literal", loc);
|
|
434
|
-
this.adv();
|
|
435
|
-
return { type: TT.STRING, value: result, loc };
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
private readNumber(loc: Loc): Token {
|
|
439
|
-
let s = "";
|
|
440
|
-
if (this.src[this.pos] === "-") { s += "-"; this.adv(); }
|
|
441
|
-
while (this.isDigit(this.src[this.pos] ?? "")) { s += this.src[this.pos]; this.adv(); }
|
|
442
|
-
if (this.src[this.pos] === "." && this.isDigit(this.src[this.pos + 1] ?? "")) {
|
|
443
|
-
s += "."; this.adv();
|
|
444
|
-
while (this.isDigit(this.src[this.pos] ?? "")) { s += this.src[this.pos]; this.adv(); }
|
|
445
|
-
}
|
|
446
|
-
return { type: TT.NUMBER, value: s, loc };
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
private readIdent(loc: Loc): Token {
|
|
450
|
-
let s = "";
|
|
451
|
-
while (this.pos < this.src.length && this.isIdentCont(this.src[this.pos])) {
|
|
452
|
-
s += this.src[this.pos]; this.adv();
|
|
453
|
-
}
|
|
454
|
-
const kw = KEYWORDS[s];
|
|
455
|
-
return { type: kw !== undefined ? kw : TT.IDENT, value: s, loc };
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
private adv(): void {
|
|
459
|
-
const ch = this.src[this.pos++];
|
|
460
|
-
if (ch === "\n") { this.line++; this.col = 1; } else { this.col++; }
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
private single(type: TT, loc: Loc): Token {
|
|
464
|
-
this.adv();
|
|
465
|
-
return { type, value: this.src[this.pos - 1], loc };
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
private loc(): Loc { return { file: this.file, line: this.line, col: this.col }; }
|
|
469
|
-
private isDigit(c: string) { return c >= "0" && c <= "9"; }
|
|
470
|
-
private isIdentStart(c: string) { return /[a-zA-Z_\u00C0-\uFFFF]/.test(c); }
|
|
471
|
-
private isIdentCont(c: string) { return /[a-zA-Z0-9_\-\u00C0-\uFFFF]/.test(c); }
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
// parser
|
|
475
|
-
|
|
476
|
-
export class Parser {
|
|
477
|
-
private pos = 0;
|
|
478
|
-
private loopVar: string | null = null;
|
|
479
|
-
/** Accumulated var declarations for type-checking in bodies. */
|
|
480
|
-
private _varDecls: VarDeclaration[] = [];
|
|
481
|
-
|
|
482
|
-
constructor(private tokens: Token[], private file: string) {}
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
// top-level file parse
|
|
486
|
-
parse(): SinthFile {
|
|
487
|
-
let isPage = false;
|
|
488
|
-
const imports: ImportNode[] = [];
|
|
489
|
-
const meta: MetaEntry[] = [];
|
|
490
|
-
const defs: CompDef[] = [];
|
|
491
|
-
const uses: CompUse[] = [];
|
|
492
|
-
const styles: StyleBlock[] = [];
|
|
493
|
-
const scripts: ScriptBlock[] = [];
|
|
494
|
-
const customEls: CustomElDecl[] = [];
|
|
495
|
-
const varDecls: VarDeclaration[] = [];
|
|
496
|
-
this._varDecls = varDecls;
|
|
497
|
-
|
|
498
|
-
if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
|
|
499
|
-
|
|
500
|
-
while (this.check(TT.KW_IMPORT)) imports.push(this.parseImport());
|
|
501
|
-
|
|
502
|
-
while (this.isMetaStart()) {
|
|
503
|
-
const entry = this.parseMeta();
|
|
504
|
-
meta.push(entry);
|
|
505
|
-
if (entry.key === "title") isPage = true;
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
while (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
510
|
-
const vd = this.parseVarDeclaration();
|
|
511
|
-
if (vd) { varDecls.push(vd); }
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
while (!this.check(TT.EOF)) {
|
|
516
|
-
if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
|
|
517
|
-
else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
|
|
518
|
-
else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
|
|
519
|
-
else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
|
|
520
|
-
else if (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
521
|
-
const vd = this.parseVarDeclaration();
|
|
522
|
-
if (vd) varDecls.push(vd);
|
|
523
|
-
}
|
|
524
|
-
else if (this.check(TT.KW_IF)) {
|
|
525
|
-
const ifNode = this.parseIfBlock();
|
|
526
|
-
uses.push(...this.flattenIfToUses(ifNode, scripts));
|
|
527
|
-
}
|
|
528
|
-
else if (this.check(TT.KW_FOR)) {
|
|
529
|
-
const forNode = this.parseForLoop();
|
|
530
|
-
uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
|
|
531
|
-
}
|
|
532
|
-
else if (this.check(TT.IDENT)) {
|
|
533
|
-
const savedPos = this.pos;
|
|
534
|
-
const identName = this.peek().value;
|
|
535
|
-
const nextType = this.tokens[this.pos + 1]?.type;
|
|
536
|
-
|
|
537
|
-
// detect accidental top-level expressions (guess == target" instead of "if guess == target")
|
|
538
|
-
const isComparison = [TT.OP_EQEQ, TT.OP_NEQ, TT.OP_LT, TT.OP_GT, TT.OP_LTEQ, TT.OP_GTEQ].includes(nextType);
|
|
539
|
-
const isLogicAndOr = nextType === TT.IDENT && (this.tokens[this.pos + 1]?.value === "and" || this.tokens[this.pos + 1]?.value === "or");
|
|
540
|
-
|
|
541
|
-
if (isComparison || isLogicAndOr) {
|
|
542
|
-
throw new SinthError(
|
|
543
|
-
`Unexpected expression '${identName} ...' at top level. Did you mean to wrap this in an 'if' block?`,
|
|
544
|
-
this.peek().loc,
|
|
545
|
-
);
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
// top-level assignment: ident = expr
|
|
549
|
-
if (nextType === TT.EQUALS ||
|
|
550
|
-
(nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) ||
|
|
551
|
-
(nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
|
|
552
|
-
this.consume(TT.IDENT); // consume name
|
|
553
|
-
let op: AssignOp = "=";
|
|
554
|
-
if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
|
|
555
|
-
else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
|
|
556
|
-
this.consume(TT.EQUALS);
|
|
557
|
-
const expr = this.parseExpression();
|
|
558
|
-
if (expr) {
|
|
559
|
-
const js = `${identName} ${op} ${compileExprToJS(expr)};
|
|
560
|
-
sinthRender();`;
|
|
561
|
-
scripts.push({ raw: js, attrs: {}, loc: this.peek().loc });
|
|
562
|
-
}
|
|
563
|
-
continue;
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// component usage
|
|
567
|
-
this.pos = savedPos;
|
|
568
|
-
uses.push(this.parseCompUse());
|
|
569
|
-
}
|
|
570
|
-
else throw new SinthError(
|
|
571
|
-
`Unexpected token '${this.peek().value}' (${TT[this.peek().type]}) at top level`,
|
|
572
|
-
this.peek().loc,
|
|
573
|
-
);
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
private flattenIfToUses(ifNode: IfBlock, scripts: ScriptBlock[]): CompUse[] {
|
|
580
|
-
const bodyHasComp = ifNode.body.some(c => c.kind === "use");
|
|
581
|
-
const elseHasComp = (ifNode.elseBody ?? []).some(c => c.kind === "use");
|
|
582
|
-
if (!bodyHasComp && !elseHasComp) {
|
|
583
|
-
scripts.push({ raw: compileIfToJS(ifNode), attrs: {}, loc: ifNode.loc });
|
|
584
|
-
return [];
|
|
585
|
-
}
|
|
586
|
-
const syntheticUse: CompUse = {
|
|
587
|
-
kind: "use",
|
|
588
|
-
name: "__IF_ROOT__",
|
|
589
|
-
attrs: [],
|
|
590
|
-
children: [ifNode],
|
|
591
|
-
loc: ifNode.loc,
|
|
592
|
-
};
|
|
593
|
-
return [syntheticUse];
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// imports
|
|
597
|
-
|
|
598
|
-
private parseImport(): ImportNode {
|
|
599
|
-
const loc = this.consume(TT.KW_IMPORT).loc;
|
|
600
|
-
if (this.check(TT.KW_CSS)) {
|
|
601
|
-
this.consume(TT.KW_CSS);
|
|
602
|
-
return { kind: "css", path: this.consume(TT.STRING).value, loc };
|
|
603
|
-
}
|
|
604
|
-
if (this.check(TT.STRING)) {
|
|
605
|
-
return { kind: "sinth", path: this.consume(TT.STRING).value, loc };
|
|
606
|
-
}
|
|
607
|
-
if (this.check(TT.IDENT)) {
|
|
608
|
-
const name = this.consume(TT.IDENT).value;
|
|
609
|
-
let alias: string | undefined;
|
|
610
|
-
if (this.check(TT.KW_AS)) { this.consume(TT.KW_AS); alias = this.consume(TT.IDENT).value; }
|
|
611
|
-
return { kind: "js", name, alias, loc };
|
|
612
|
-
}
|
|
613
|
-
throw new SinthError(`Expected import path, library name, or 'css'`, loc);
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// metadata
|
|
617
|
-
|
|
618
|
-
private isMetaStart(): boolean {
|
|
619
|
-
if (!this.check(TT.IDENT)) return false;
|
|
620
|
-
return this.tokens[this.pos + 1]?.type === TT.EQUALS;
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
private parseMeta(): MetaEntry {
|
|
624
|
-
const loc = this.peek().loc;
|
|
625
|
-
const key = this.consume(TT.IDENT).value;
|
|
626
|
-
this.consume(TT.EQUALS);
|
|
627
|
-
return { key, value: this.parseLiteral(), loc };
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
// var declarations
|
|
631
|
-
|
|
632
|
-
private parseVarDeclaration(): VarDeclaration | null {
|
|
633
|
-
const loc = this.peek().loc;
|
|
634
|
-
this.consume(TT.IDENT); // consume 'var'
|
|
635
|
-
|
|
636
|
-
const typeTok = this.consume(TT.IDENT);
|
|
637
|
-
let typeStr = typeTok.value;
|
|
638
|
-
if (this.check(TT.LBRACKET) && this.tokens[this.pos + 1]?.type === TT.RBRACKET) {
|
|
639
|
-
this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
|
|
640
|
-
typeStr = "str[]";
|
|
641
|
-
}
|
|
642
|
-
if (!["int", "str", "bool", "str[]", "obj"].includes(typeStr)) {
|
|
643
|
-
throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
const nameTok = this.consume(TT.IDENT);
|
|
647
|
-
let val: Literal | null = null;
|
|
648
|
-
|
|
649
|
-
if (this.check(TT.EQUALS)) {
|
|
650
|
-
this.consume(TT.EQUALS);
|
|
651
|
-
if (this.check(TT.LBRACKET)) {
|
|
652
|
-
val = this.parseArrayLiteral();
|
|
653
|
-
} else if (this.check(TT.IDENT)) {
|
|
654
|
-
const refName = this.consume(TT.IDENT).value;
|
|
655
|
-
val = { kind: "str", value: `__VAR__${refName}` };
|
|
656
|
-
} else {
|
|
657
|
-
val = this.parseLiteral();
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
return { kind: "var", name: nameTok.value, varType: typeStr as VarType, value: val, loc };
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
private parseArrayLiteral(): Literal {
|
|
665
|
-
this.consume(TT.LBRACKET);
|
|
666
|
-
const items: any[] = [];
|
|
667
|
-
while (!this.check(TT.RBRACKET) && !this.check(TT.EOF)) {
|
|
668
|
-
if (this.check(TT.LBRACE)) {
|
|
669
|
-
items.push(this.parseObjectLiteral());
|
|
670
|
-
} else if (this.check(TT.STRING)) {
|
|
671
|
-
items.push(this.consume(TT.STRING).value);
|
|
672
|
-
} else if (this.check(TT.NUMBER)) {
|
|
673
|
-
items.push(parseFloat(this.consume(TT.NUMBER).value));
|
|
674
|
-
} else if (this.check(TT.BOOL_TRUE)) {
|
|
675
|
-
this.consume(TT.BOOL_TRUE);
|
|
676
|
-
items.push(true);
|
|
677
|
-
} else if (this.check(TT.BOOL_FALSE)) {
|
|
678
|
-
this.consume(TT.BOOL_FALSE);
|
|
679
|
-
items.push(false);
|
|
680
|
-
} else if (this.check(TT.NULL_LIT)) {
|
|
681
|
-
this.consume(TT.NULL_LIT);
|
|
682
|
-
items.push(null);
|
|
683
|
-
}
|
|
684
|
-
if (this.check(TT.COMMA)) this.consume(TT.COMMA); else break;
|
|
685
|
-
}
|
|
686
|
-
this.consume(TT.RBRACKET);
|
|
687
|
-
return { kind: "str", value: `__ARR__${JSON.stringify(items)}` };
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
private parseObjectLiteral(): Record<string, any> {
|
|
691
|
-
this.consume(TT.LBRACE);
|
|
692
|
-
const obj: Record<string, any> = {};
|
|
693
|
-
while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
|
|
694
|
-
const key = this.consume(TT.IDENT).value;
|
|
695
|
-
this.consume(TT.COLON);
|
|
696
|
-
if (this.check(TT.STRING)) {
|
|
697
|
-
obj[key] = this.consume(TT.STRING).value;
|
|
698
|
-
} else if (this.check(TT.NUMBER)) {
|
|
699
|
-
obj[key] = parseFloat(this.consume(TT.NUMBER).value);
|
|
700
|
-
} else if (this.check(TT.BOOL_TRUE)) {
|
|
701
|
-
this.consume(TT.BOOL_TRUE);
|
|
702
|
-
obj[key] = true;
|
|
703
|
-
} else if (this.check(TT.BOOL_FALSE)) {
|
|
704
|
-
this.consume(TT.BOOL_FALSE);
|
|
705
|
-
obj[key] = false;
|
|
706
|
-
} else if (this.check(TT.NULL_LIT)) {
|
|
707
|
-
this.consume(TT.NULL_LIT);
|
|
708
|
-
obj[key] = null;
|
|
709
|
-
} else {
|
|
710
|
-
throw new SinthError(`Expected literal value for key '${key}'`, this.peek().loc);
|
|
711
|
-
}
|
|
712
|
-
if (this.check(TT.COMMA)) this.consume(TT.COMMA);
|
|
713
|
-
}
|
|
714
|
-
this.consume(TT.RBRACE);
|
|
715
|
-
return obj;
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
// expression parsing
|
|
719
|
-
|
|
720
|
-
parseExpression(): Expression | null {
|
|
721
|
-
const tok = this.peek();
|
|
722
|
-
|
|
723
|
-
// Unary 'not'
|
|
724
|
-
if (tok.type === TT.IDENT && tok.value === "not") {
|
|
725
|
-
this.consume(TT.IDENT);
|
|
726
|
-
const operand = this.parseExpression();
|
|
727
|
-
if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
|
|
728
|
-
const unaryExpr: Expression = { kind: "unary", op: "not", operand };
|
|
729
|
-
return this.parseBinaryRHS(this.parsePostfix(unaryExpr));
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
if (this.check(TT.LPAREN)) {
|
|
733
|
-
this.consume(TT.LPAREN);
|
|
734
|
-
const inner = this.parseExpression();
|
|
735
|
-
if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
|
|
736
|
-
if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
|
|
737
|
-
this.consume(TT.RPAREN);
|
|
738
|
-
return this.parseBinaryRHS(this.parsePostfix(inner));
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
// literal
|
|
742
|
-
if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
|
|
743
|
-
this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
|
|
744
|
-
const lit = this.parseLiteral();
|
|
745
|
-
const base: Expression = { kind: "literal", value: lit };
|
|
746
|
-
return this.parseBinaryRHS(this.parsePostfix(base));
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// var or assignment
|
|
750
|
-
if (tok.type === TT.IDENT) {
|
|
751
|
-
const name = this.consume(TT.IDENT).value;
|
|
752
|
-
let varExpr: Expression;
|
|
753
|
-
|
|
754
|
-
// dot notation -> user.age
|
|
755
|
-
if (this.check(TT.DOT)) {
|
|
756
|
-
this.consume(TT.DOT);
|
|
757
|
-
const propName = this.consume(TT.IDENT).value;
|
|
758
|
-
const fullName = `${name}.${propName}`;
|
|
759
|
-
varExpr = { kind: "variable", name: fullName };
|
|
760
|
-
} else {
|
|
761
|
-
varExpr = { kind: "variable", name };
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
// apply bracket postfixes (e.g. data[key], data["x"])
|
|
765
|
-
const indexedExpr = this.parsePostfix(varExpr);
|
|
766
|
-
|
|
767
|
-
// if indexing was applied, we don't allow assignment, just binary RHS
|
|
768
|
-
if (indexedExpr !== varExpr) {
|
|
769
|
-
return this.parseBinaryRHS(indexedExpr);
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
// no indexing – check for assignment operators
|
|
773
|
-
const nextType = this.tokens[this.pos]?.type;
|
|
774
|
-
if (nextType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
|
|
775
|
-
this.consume(TT.OP_PLUS); this.consume(TT.EQUALS);
|
|
776
|
-
const rhs = this.parseExpression();
|
|
777
|
-
if (!rhs) throw new SinthError("Expected expression after +=", this.peek().loc);
|
|
778
|
-
return { kind: "assign", target: varExpr.name!, op: "+=", right: rhs };
|
|
779
|
-
}
|
|
780
|
-
if (nextType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
|
|
781
|
-
this.consume(TT.OP_MINUS); this.consume(TT.EQUALS);
|
|
782
|
-
const rhs = this.parseExpression();
|
|
783
|
-
if (!rhs) throw new SinthError("Expected expression after -=", this.peek().loc);
|
|
784
|
-
return { kind: "assign", target: varExpr.name!, op: "-=", right: rhs };
|
|
785
|
-
}
|
|
786
|
-
if (nextType === TT.EQUALS) {
|
|
787
|
-
this.consume(TT.EQUALS);
|
|
788
|
-
const rhs = this.parseExpression();
|
|
789
|
-
if (!rhs) throw new SinthError("Expected expression after =", this.peek().loc);
|
|
790
|
-
return { kind: "assign", target: varExpr.name!, op: "=", right: rhs };
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
return this.parseBinaryRHS(varExpr);
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
return null;
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
private parseBinaryRHS(left: Expression): Expression {
|
|
800
|
-
const t = this.peek().type;
|
|
801
|
-
let op: BinaryOp | null = null;
|
|
802
|
-
if (t === TT.OP_EQEQ) op = "==";
|
|
803
|
-
else if (t === TT.OP_NEQ) op = "!=";
|
|
804
|
-
else if (t === TT.OP_LT) op = "<";
|
|
805
|
-
else if (t === TT.OP_GT) op = ">";
|
|
806
|
-
else if (t === TT.OP_LTEQ) op = "<=";
|
|
807
|
-
else if (t === TT.OP_GTEQ) op = ">=";
|
|
808
|
-
else if (t === TT.OP_PLUS) op = "+";
|
|
809
|
-
else if (t === TT.OP_MINUS) op = "-";
|
|
810
|
-
else if (t === TT.OP_STAR) op = "*";
|
|
811
|
-
else if (t === TT.OP_SLASH) op = "/";
|
|
812
|
-
else if (t === TT.IDENT && this.peek().value === "and") op = "and";
|
|
813
|
-
else if (t === TT.IDENT && this.peek().value === "or") op = "or";
|
|
814
|
-
|
|
815
|
-
if (!op) return left;
|
|
816
|
-
this.pos++;
|
|
817
|
-
|
|
818
|
-
const right = this.parseExpression();
|
|
819
|
-
if (!right) throw new SinthError(`Expected expression after '${op}'`, this.peek().loc);
|
|
820
|
-
return { kind: "binary", left, op, right };
|
|
821
|
-
}
|
|
822
|
-
|
|
823
|
-
private parsePostfix(base: Expression): Expression {
|
|
824
|
-
let expr = base;
|
|
825
|
-
while (this.check(TT.LBRACKET)) {
|
|
826
|
-
this.consume(TT.LBRACKET);
|
|
827
|
-
const key = this.parseExpression();
|
|
828
|
-
if (!key) throw new SinthError("Expected expression inside [...]", this.peek().loc);
|
|
829
|
-
this.consume(TT.RBRACKET);
|
|
830
|
-
expr = { kind: "index", object: expr, key };
|
|
831
|
-
}
|
|
832
|
-
return expr;
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
// component definitions
|
|
837
|
-
|
|
838
|
-
private parseCompDef(): CompDef {
|
|
839
|
-
const loc = this.consume(TT.KW_COMPONENT).loc;
|
|
840
|
-
const name = this.consume(TT.IDENT).value;
|
|
841
|
-
const params = this.parseParamDecls();
|
|
842
|
-
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
843
|
-
const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
|
|
844
|
-
return { name, params, body, styles, scripts, loc };
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
private parseCustomEl(): CustomElDecl {
|
|
848
|
-
const loc = this.peek().loc;
|
|
849
|
-
if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
|
|
850
|
-
else if (this.check(TT.KW_CUSTOM)) this.consume(TT.KW_CUSTOM);
|
|
851
|
-
const tagName = this.consume(TT.IDENT).value;
|
|
852
|
-
const sinthName = tagNameToPascal(tagName);
|
|
853
|
-
const params = this.parseParamDecls();
|
|
854
|
-
return { sinthName, tagName, params, loc };
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
private parseParamDecls(): ParamDecl[] {
|
|
858
|
-
const params: ParamDecl[] = [];
|
|
859
|
-
if (!this.check(TT.LPAREN)) return params;
|
|
860
|
-
this.consume(TT.LPAREN);
|
|
861
|
-
while (!this.check(TT.RPAREN)) {
|
|
862
|
-
const ploc = this.peek().loc;
|
|
863
|
-
const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
|
|
864
|
-
const pname = nameTok.value;
|
|
865
|
-
let defaultVal: Literal | undefined;
|
|
866
|
-
if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
|
|
867
|
-
params.push({ name: pname, defaultVal, loc: ploc });
|
|
868
|
-
if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
|
|
869
|
-
}
|
|
870
|
-
this.consume(TT.RPAREN);
|
|
871
|
-
return params;
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
private parseCompBody(
|
|
875
|
-
raw: string,
|
|
876
|
-
loc: Loc,
|
|
877
|
-
): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
|
|
878
|
-
const tokens = new Lexer(raw, loc.file).tokenize();
|
|
879
|
-
const sub = new Parser(tokens, loc.file);
|
|
880
|
-
sub._varDecls = this._varDecls;
|
|
881
|
-
return sub.parseBodyContents();
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
private parseBodyContents(): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
|
|
885
|
-
const body: Child[] = [], styles: StyleBlock[] = [], scripts: ScriptBlock[] = [];
|
|
886
|
-
while (!this.check(TT.EOF)) {
|
|
887
|
-
if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
|
|
888
|
-
else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
|
|
889
|
-
else if (this.check(TT.STRING)) {
|
|
890
|
-
const loc = this.peek().loc;
|
|
891
|
-
body.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
|
|
892
|
-
}
|
|
893
|
-
else if (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
894
|
-
const vd = this.parseVarDeclaration();
|
|
895
|
-
if (vd) this._varDecls.push(vd);
|
|
896
|
-
continue;
|
|
897
|
-
}
|
|
898
|
-
else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
|
|
899
|
-
else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
|
|
900
|
-
else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
|
|
901
|
-
else throw new SinthError(
|
|
902
|
-
`Unexpected token '${this.peek().value}' in component body`,
|
|
903
|
-
this.peek().loc,
|
|
904
|
-
);
|
|
905
|
-
}
|
|
906
|
-
return { body, styles, scripts };
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
// if / else blocks
|
|
910
|
-
|
|
911
|
-
private parseIfBlock(): IfBlock {
|
|
912
|
-
const loc = this.consume(TT.KW_IF).loc;
|
|
913
|
-
const condition = this.parseExpression();
|
|
914
|
-
if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
|
|
915
|
-
|
|
916
|
-
if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after if condition", this.peek().loc);
|
|
917
|
-
this.consume(TT.LBRACE);
|
|
918
|
-
const body = this.parseUnifiedBody();
|
|
919
|
-
this.consume(TT.RBRACE);
|
|
920
|
-
|
|
921
|
-
let elseBody: Child[] | undefined;
|
|
922
|
-
if (this.check(TT.KW_ELSE)) {
|
|
923
|
-
this.consume(TT.KW_ELSE);
|
|
924
|
-
if (this.check(TT.KW_IF)) {
|
|
925
|
-
elseBody = [this.parseIfBlock()];
|
|
926
|
-
} else {
|
|
927
|
-
if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after else", this.peek().loc);
|
|
928
|
-
this.consume(TT.LBRACE);
|
|
929
|
-
elseBody = this.parseUnifiedBody();
|
|
930
|
-
this.consume(TT.RBRACE);
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
return { kind: "if", condition, body, elseBody, loc };
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
private parseUnifiedBody(): Child[] {
|
|
938
|
-
const children: Child[] = [];
|
|
939
|
-
|
|
940
|
-
while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
|
|
941
|
-
if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
|
|
942
|
-
if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
|
|
943
|
-
if (this.check(TT.LPAREN)) {
|
|
944
|
-
const loc = this.peek().loc;
|
|
945
|
-
const expr = this.parseExpression();
|
|
946
|
-
if (expr) {
|
|
947
|
-
children.push({ kind: "expr", expression: expr, loc });
|
|
948
|
-
}
|
|
949
|
-
continue;
|
|
950
|
-
}
|
|
951
|
-
if (this.check(TT.STRING)) {
|
|
952
|
-
const loc = this.peek().loc;
|
|
953
|
-
children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
|
|
954
|
-
continue;
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
if (this.check(TT.KW_REMOVE)) {
|
|
958
|
-
const loc = this.consume(TT.KW_REMOVE).loc;
|
|
959
|
-
if (this.check(TT.STRING)) {
|
|
960
|
-
const target = this.consume(TT.STRING).value;
|
|
961
|
-
children.push({ kind: "remove", target, loc });
|
|
962
|
-
} else {
|
|
963
|
-
throw new SinthError(
|
|
964
|
-
`Expected a string after 'remove', got '${this.peek().value}'. Use remove "id".`,
|
|
965
|
-
this.peek().loc,
|
|
966
|
-
);
|
|
967
|
-
}
|
|
968
|
-
continue;
|
|
969
|
-
}
|
|
970
|
-
if (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
971
|
-
const vd = this.parseVarDeclaration();
|
|
972
|
-
if (vd) this._varDecls.push(vd);
|
|
973
|
-
continue;
|
|
974
|
-
}
|
|
975
|
-
|
|
976
|
-
if (this.check(TT.IDENT)) {
|
|
977
|
-
const loc = this.peek().loc;
|
|
978
|
-
const name = this.peek().value;
|
|
979
|
-
const nextType = this.tokens[this.pos + 1]?.type;
|
|
980
|
-
const nextNextType = this.tokens[this.pos + 2]?.type;
|
|
981
|
-
|
|
982
|
-
if (nextType === TT.DOT && (nextNextType === TT.EQUALS ||
|
|
983
|
-
(nextNextType === TT.OP_PLUS && this.tokens[this.pos + 3]?.type === TT.EQUALS) ||
|
|
984
|
-
(nextNextType === TT.OP_MINUS && this.tokens[this.pos + 3]?.type === TT.EQUALS))) {
|
|
985
|
-
let fullName = this.consume(TT.IDENT).value;
|
|
986
|
-
this.consume(TT.DOT);
|
|
987
|
-
fullName = fullName + "." + this.consume(TT.IDENT).value;
|
|
988
|
-
|
|
989
|
-
let op: AssignOp = "=";
|
|
990
|
-
const afterDotType = this.tokens[this.pos]?.type;
|
|
991
|
-
if (afterDotType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
|
|
992
|
-
this.consume(TT.OP_PLUS); op = "+=";
|
|
993
|
-
} else if (afterDotType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
|
|
994
|
-
this.consume(TT.OP_MINUS); op = "-=";
|
|
995
|
-
}
|
|
996
|
-
this.consume(TT.EQUALS);
|
|
997
|
-
const rhs = this.parseExpression();
|
|
998
|
-
if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
|
|
999
|
-
const assignExpr: Expression = { kind: "assign", target: fullName, op, right: rhs };
|
|
1000
|
-
children.push({ kind: "assign_stmt", expression: assignExpr, loc });
|
|
1001
|
-
continue;
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
// assignment: ident = expr | ident += expr | ident -= expr
|
|
1005
|
-
const isSimpleAssign = nextType === TT.EQUALS;
|
|
1006
|
-
const isPlusAssign = nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
|
|
1007
|
-
const isMinusAssign = nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
|
|
1008
|
-
|
|
1009
|
-
if (isSimpleAssign || isPlusAssign || isMinusAssign) {
|
|
1010
|
-
this.consume(TT.IDENT); // consume name
|
|
1011
|
-
let op: AssignOp = "=";
|
|
1012
|
-
if (isPlusAssign) { this.consume(TT.OP_PLUS); op = "+="; }
|
|
1013
|
-
else if (isMinusAssign) { this.consume(TT.OP_MINUS); op = "-="; }
|
|
1014
|
-
this.consume(TT.EQUALS);
|
|
1015
|
-
const rhs = this.parseExpression();
|
|
1016
|
-
if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
|
|
1017
|
-
const assignExpr: Expression = { kind: "assign", target: name, op, right: rhs };
|
|
1018
|
-
children.push({ kind: "assign_stmt", expression: assignExpr, loc });
|
|
1019
|
-
continue;
|
|
1020
|
-
}
|
|
1021
|
-
|
|
1022
|
-
// Component usage: ident( or ident{ or ident RAW_BLOCK
|
|
1023
|
-
if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
|
|
1024
|
-
children.push(this.parseCompUse());
|
|
1025
|
-
continue;
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
// var expression
|
|
1029
|
-
// check dot notation variable reference (user.age without assignment)
|
|
1030
|
-
if (nextType === TT.DOT) {
|
|
1031
|
-
let fullName = this.consume(TT.IDENT).value;
|
|
1032
|
-
this.consume(TT.DOT);
|
|
1033
|
-
fullName = fullName + "." + this.consume(TT.IDENT).value;
|
|
1034
|
-
children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
|
|
1035
|
-
continue;
|
|
1036
|
-
}
|
|
1037
|
-
|
|
1038
|
-
// bracket notation: ident[...]
|
|
1039
|
-
if (nextType === TT.LBRACKET) {
|
|
1040
|
-
this.consume(TT.IDENT);
|
|
1041
|
-
const varExpr: Expression = { kind: "variable", name };
|
|
1042
|
-
const indexedExpr = this.parsePostfix(varExpr);
|
|
1043
|
-
children.push({ kind: "expr", expression: indexedExpr, loc });
|
|
1044
|
-
continue;
|
|
1045
|
-
}
|
|
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
|
-
// reject implicit concatenation only after expression children
|
|
1060
|
-
if (children.length > 0) {
|
|
1061
|
-
const lastChild = children[children.length - 1];
|
|
1062
|
-
if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
|
|
1063
|
-
const nextTT = this.tokens[this.pos]?.type;
|
|
1064
|
-
if (
|
|
1065
|
-
nextTT === TT.STRING || nextTT === TT.NUMBER ||
|
|
1066
|
-
nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
|
|
1067
|
-
(nextTT === TT.IDENT &&
|
|
1068
|
-
this.tokens[this.pos]?.value !== "var" &&
|
|
1069
|
-
this.tokens[this.pos]?.value !== "if" &&
|
|
1070
|
-
this.tokens[this.pos]?.value !== "for" &&
|
|
1071
|
-
this.tokens[this.pos]?.value !== "else" &&
|
|
1072
|
-
this.tokens[this.pos]?.value !== "and" &&
|
|
1073
|
-
this.tokens[this.pos]?.value !== "or")
|
|
1074
|
-
) {
|
|
1075
|
-
throw new SinthError(
|
|
1076
|
-
`Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
|
|
1077
|
-
this.peek().loc,
|
|
1078
|
-
);
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
|
|
1084
|
-
return children;
|
|
1085
|
-
}
|
|
1086
|
-
|
|
1087
|
-
// for loops
|
|
1088
|
-
|
|
1089
|
-
private parseForLoop(): ForLoop {
|
|
1090
|
-
const loc = this.consume(TT.KW_FOR).loc;
|
|
1091
|
-
const firstVar = this.consume(TT.IDENT).value;
|
|
1092
|
-
let keyVar: string | undefined;
|
|
1093
|
-
let itemVar: string;
|
|
1094
|
-
let indexVar: string | undefined;
|
|
1095
|
-
if (this.check(TT.COMMA)) {
|
|
1096
|
-
this.consume(TT.COMMA);
|
|
1097
|
-
const secondVar = this.consume(TT.IDENT).value;
|
|
1098
|
-
if (this.check(TT.COMMA)) {
|
|
1099
|
-
// three variables: key, value, index
|
|
1100
|
-
this.consume(TT.COMMA);
|
|
1101
|
-
keyVar = firstVar;
|
|
1102
|
-
itemVar = secondVar;
|
|
1103
|
-
indexVar = this.consume(TT.IDENT).value;
|
|
1104
|
-
} else {
|
|
1105
|
-
// two variables – tentatively value, index; fix after seeing source type
|
|
1106
|
-
itemVar = firstVar;
|
|
1107
|
-
indexVar = secondVar;
|
|
1108
|
-
}
|
|
1109
|
-
} else {
|
|
1110
|
-
// one variable: item only
|
|
1111
|
-
itemVar = firstVar;
|
|
1112
|
-
}
|
|
1113
|
-
if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
|
|
1114
|
-
this.consume(TT.KW_IN);
|
|
1115
|
-
const arrayVar = this.consume(TT.IDENT).value;
|
|
1116
|
-
|
|
1117
|
-
// If two variables and the source is an object, swap to key, value
|
|
1118
|
-
if (keyVar === undefined && indexVar !== undefined) {
|
|
1119
|
-
const srcDecl = this._varDecls.find(d => d.name === arrayVar);
|
|
1120
|
-
if (srcDecl && srcDecl.varType === "obj") {
|
|
1121
|
-
keyVar = itemVar; // first → key
|
|
1122
|
-
itemVar = indexVar; // second → value
|
|
1123
|
-
indexVar = undefined;
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
|
|
1127
|
-
if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after for..in expression", this.peek().loc);
|
|
1128
|
-
this.consume(TT.LBRACE);
|
|
1129
|
-
this.loopVar = itemVar;
|
|
1130
|
-
const body = this.parseChildList();
|
|
1131
|
-
this.loopVar = null;
|
|
1132
|
-
this.consume(TT.RBRACE);
|
|
1133
|
-
|
|
1134
|
-
return { kind: "for", keyVar, itemVar, indexVar, arrayVar, body, loc };
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
// component usages
|
|
1138
|
-
|
|
1139
|
-
private parseCompUse(): CompUse {
|
|
1140
|
-
const loc = this.peek().loc;
|
|
1141
|
-
const name = this.consume(TT.IDENT).value;
|
|
1142
|
-
const attrs: Attr[] = [];
|
|
1143
|
-
|
|
1144
|
-
if (this.check(TT.LPAREN)) {
|
|
1145
|
-
this.consume(TT.LPAREN);
|
|
1146
|
-
while (!this.check(TT.RPAREN)) {
|
|
1147
|
-
const aloc = this.peek().loc;
|
|
1148
|
-
const aname = this.consume(TT.IDENT).value;
|
|
1149
|
-
let value: Literal | null = null;
|
|
1150
|
-
if (this.check(TT.COLON)) {
|
|
1151
|
-
this.consume(TT.COLON);
|
|
1152
|
-
if (this.isEventAttr(aname)) {
|
|
1153
|
-
if (this.check(TT.STRING)) {
|
|
1154
|
-
value = this.parseLiteral();
|
|
1155
|
-
} else {
|
|
1156
|
-
const savedPos = this.pos;
|
|
1157
|
-
const expr = this.parseExpression();
|
|
1158
|
-
if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI))) {
|
|
1159
|
-
const exprs: Expression[] = [expr];
|
|
1160
|
-
while (this.check(TT.OP_SEMI)) {
|
|
1161
|
-
this.consume(TT.OP_SEMI);
|
|
1162
|
-
const next = this.parseExpression();
|
|
1163
|
-
if (next) exprs.push(next);
|
|
1164
|
-
else break;
|
|
1165
|
-
}
|
|
1166
|
-
if (exprs.length === 1) {
|
|
1167
|
-
value = { kind: "str", value: "__EXPR__" + JSON.stringify(exprs[0]) };
|
|
1168
|
-
} else {
|
|
1169
|
-
value = { kind: "str", value: "__MULTI_EXPR__" + JSON.stringify(exprs) };
|
|
1170
|
-
}
|
|
1171
|
-
} else {
|
|
1172
|
-
this.pos = savedPos;
|
|
1173
|
-
value = this.parseLiteral();
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
} else {
|
|
1177
|
-
if (this.check(TT.STRING) || this.check(TT.NUMBER) ||
|
|
1178
|
-
this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
|
|
1179
|
-
this.check(TT.NULL_LIT) || this.check(TT.LBRACKET) || this.check(TT.LBRACE)) {
|
|
1180
|
-
value = this.parseLiteral();
|
|
1181
|
-
} else if (this.check(TT.IDENT) || this.check(TT.LPAREN)) {
|
|
1182
|
-
const savedPos = this.pos;
|
|
1183
|
-
const expr = this.parseExpression();
|
|
1184
|
-
if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
|
|
1185
|
-
value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
|
|
1186
|
-
} else {
|
|
1187
|
-
this.pos = savedPos;
|
|
1188
|
-
if (this.check(TT.IDENT)) {
|
|
1189
|
-
value = { kind: "str", value: this.consume(TT.IDENT).value };
|
|
1190
|
-
} else {
|
|
1191
|
-
value = this.parseLiteral();
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
} else {
|
|
1195
|
-
value = this.parseLiteral();
|
|
1196
|
-
}
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
attrs.push({ name: aname, value, loc: aloc });
|
|
1200
|
-
if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
|
|
1201
|
-
}
|
|
1202
|
-
this.consume(TT.RPAREN);
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
const children: Child[] = [];
|
|
1206
|
-
if (this.check(TT.RAW_BLOCK)) {
|
|
1207
|
-
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
1208
|
-
const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
|
|
1209
|
-
const sub = new Parser(tokens, rawTok.loc.file);
|
|
1210
|
-
sub._varDecls = this._varDecls;
|
|
1211
|
-
children.push(...sub.parseChildList());
|
|
1212
|
-
} else if (this.check(TT.LBRACE)) {
|
|
1213
|
-
this.consume(TT.LBRACE);
|
|
1214
|
-
children.push(...this.parseChildList());
|
|
1215
|
-
this.consume(TT.RBRACE);
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
return { kind: "use", name, attrs, children, loc };
|
|
1219
|
-
}
|
|
1220
|
-
|
|
1221
|
-
private isEventAttr(name: string): boolean {
|
|
1222
|
-
return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
|
|
1223
|
-
}
|
|
1224
|
-
|
|
1225
|
-
private parseChildList(): Child[] {
|
|
1226
|
-
const children: Child[] = [];
|
|
1227
|
-
while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
|
|
1228
|
-
if (this.check(TT.LPAREN)) {
|
|
1229
|
-
const loc = this.peek().loc;
|
|
1230
|
-
const expr = this.parseExpression();
|
|
1231
|
-
if (expr) {
|
|
1232
|
-
children.push({ kind: "expr", expression: expr, loc });
|
|
1233
|
-
}
|
|
1234
|
-
continue;
|
|
1235
|
-
}
|
|
1236
|
-
if (this.check(TT.STRING)) {
|
|
1237
|
-
const loc = this.peek().loc;
|
|
1238
|
-
let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
|
|
1239
|
-
while (this.check(TT.OP_PLUS)) {
|
|
1240
|
-
this.consume(TT.OP_PLUS);
|
|
1241
|
-
let rhs: Expression | null = null;
|
|
1242
|
-
if (this.check(TT.STRING)) {
|
|
1243
|
-
rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
|
|
1244
|
-
} else if (this.check(TT.IDENT)) {
|
|
1245
|
-
const rhsName = this.consume(TT.IDENT).value;
|
|
1246
|
-
if (this.check(TT.DOT)) {
|
|
1247
|
-
this.consume(TT.DOT);
|
|
1248
|
-
rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
|
|
1249
|
-
} else if (this.check(TT.LBRACKET)) {
|
|
1250
|
-
const rhsVar: Expression = { kind: "variable", name: rhsName };
|
|
1251
|
-
rhs = this.parsePostfix(rhsVar);
|
|
1252
|
-
} else {
|
|
1253
|
-
rhs = { kind: "variable", name: rhsName };
|
|
1254
|
-
}
|
|
1255
|
-
} else {
|
|
1256
|
-
rhs = this.parseExpression();
|
|
1257
|
-
}
|
|
1258
|
-
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
1259
|
-
leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
|
|
1260
|
-
}
|
|
1261
|
-
children.push({ kind: "expr", expression: leftExpr, loc });
|
|
1262
|
-
}
|
|
1263
|
-
else if (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
1264
|
-
const vd = this.parseVarDeclaration();
|
|
1265
|
-
if (vd) this._varDecls.push(vd);
|
|
1266
|
-
continue;
|
|
1267
|
-
}
|
|
1268
|
-
else if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); }
|
|
1269
|
-
else if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); }
|
|
1270
|
-
else if (this.check(TT.IDENT)) {
|
|
1271
|
-
const loc = this.peek().loc;
|
|
1272
|
-
const rawName = this.peek().value;
|
|
1273
|
-
const nextType = this.tokens[this.pos + 1]?.type;
|
|
1274
|
-
|
|
1275
|
-
if (nextType === TT.DOT) {
|
|
1276
|
-
let fullName = this.consume(TT.IDENT).value;
|
|
1277
|
-
this.consume(TT.DOT);
|
|
1278
|
-
fullName = fullName + "." + this.consume(TT.IDENT).value;
|
|
1279
|
-
const afterDotType = this.tokens[this.pos]?.type;
|
|
1280
|
-
|
|
1281
|
-
if (afterDotType === TT.OP_PLUS) {
|
|
1282
|
-
let leftExpr: Expression = { kind: "variable", name: fullName };
|
|
1283
|
-
while (this.check(TT.OP_PLUS)) {
|
|
1284
|
-
this.consume(TT.OP_PLUS);
|
|
1285
|
-
let rhs: Expression | null = null;
|
|
1286
|
-
if (this.check(TT.STRING)) {
|
|
1287
|
-
rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
|
|
1288
|
-
} else if (this.check(TT.IDENT)) {
|
|
1289
|
-
const rhsName = this.consume(TT.IDENT).value;
|
|
1290
|
-
if (this.check(TT.DOT)) {
|
|
1291
|
-
this.consume(TT.DOT);
|
|
1292
|
-
rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
|
|
1293
|
-
} else if (this.check(TT.LBRACKET)) {
|
|
1294
|
-
const rhsVar: Expression = { kind: "variable", name: rhsName };
|
|
1295
|
-
rhs = this.parsePostfix(rhsVar);
|
|
1296
|
-
} else {
|
|
1297
|
-
rhs = { kind: "variable", name: rhsName };
|
|
1298
|
-
}
|
|
1299
|
-
} else {
|
|
1300
|
-
rhs = this.parseExpression();
|
|
1301
|
-
}
|
|
1302
|
-
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
1303
|
-
leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
|
|
1304
|
-
}
|
|
1305
|
-
children.push({ kind: "expr", expression: leftExpr, loc });
|
|
1306
|
-
} else if (this.loopVar && fullName.split('.')[0] === this.loopVar) {
|
|
1307
|
-
children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
|
|
1308
|
-
} else if (afterDotType === TT.LPAREN || afterDotType === TT.LBRACE || afterDotType === TT.RAW_BLOCK) {
|
|
1309
|
-
throw new SinthError(`Unexpected dot notation before component usage`, loc);
|
|
1310
|
-
} else {
|
|
1311
|
-
children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
|
|
1312
|
-
}
|
|
1313
|
-
} else if (nextType === TT.OP_PLUS) {
|
|
1314
|
-
const name = this.consume(TT.IDENT).value;
|
|
1315
|
-
let leftExpr: Expression = { kind: "variable", name };
|
|
1316
|
-
while (this.check(TT.OP_PLUS)) {
|
|
1317
|
-
this.consume(TT.OP_PLUS);
|
|
1318
|
-
let rhs: Expression | null = null;
|
|
1319
|
-
if (this.check(TT.STRING)) {
|
|
1320
|
-
rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
|
|
1321
|
-
} else if (this.check(TT.IDENT)) {
|
|
1322
|
-
const rhsName = this.consume(TT.IDENT).value;
|
|
1323
|
-
if (this.check(TT.DOT)) {
|
|
1324
|
-
this.consume(TT.DOT);
|
|
1325
|
-
rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
|
|
1326
|
-
} else if (this.check(TT.LBRACKET)) {
|
|
1327
|
-
const rhsVar: Expression = { kind: "variable", name: rhsName };
|
|
1328
|
-
rhs = this.parsePostfix(rhsVar);
|
|
1329
|
-
} else {
|
|
1330
|
-
rhs = { kind: "variable", name: rhsName };
|
|
1331
|
-
}
|
|
1332
|
-
} else {
|
|
1333
|
-
rhs = this.parseExpression();
|
|
1334
|
-
}
|
|
1335
|
-
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
1336
|
-
leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
|
|
1337
|
-
}
|
|
1338
|
-
children.push({ kind: "expr", expression: leftExpr, loc });
|
|
1339
|
-
} else if (this.loopVar && rawName === this.loopVar) {
|
|
1340
|
-
this.consume(TT.IDENT);
|
|
1341
|
-
children.push({ kind: "expr", expression: { kind: "variable", name: rawName }, loc });
|
|
1342
|
-
} else if (nextType === TT.LBRACKET) {
|
|
1343
|
-
const name = this.consume(TT.IDENT).value;
|
|
1344
|
-
const varExpr: Expression = { kind: "variable", name };
|
|
1345
|
-
let indexedExpr = this.parsePostfix(varExpr);
|
|
1346
|
-
// support concatenation: data[prop] + "..."
|
|
1347
|
-
if (this.check(TT.OP_PLUS)) {
|
|
1348
|
-
let leftExpr: Expression = indexedExpr;
|
|
1349
|
-
while (this.check(TT.OP_PLUS)) {
|
|
1350
|
-
this.consume(TT.OP_PLUS);
|
|
1351
|
-
let rhs: Expression | null = null;
|
|
1352
|
-
if (this.check(TT.STRING)) {
|
|
1353
|
-
rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
|
|
1354
|
-
} else if (this.check(TT.IDENT)) {
|
|
1355
|
-
const rhsName = this.consume(TT.IDENT).value;
|
|
1356
|
-
if (this.check(TT.DOT)) {
|
|
1357
|
-
this.consume(TT.DOT);
|
|
1358
|
-
rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
|
|
1359
|
-
} else if (this.check(TT.LBRACKET)) {
|
|
1360
|
-
const rhsVar: Expression = { kind: "variable", name: rhsName };
|
|
1361
|
-
rhs = this.parsePostfix(rhsVar);
|
|
1362
|
-
} else {
|
|
1363
|
-
rhs = { kind: "variable", name: rhsName };
|
|
1364
|
-
}
|
|
1365
|
-
} else {
|
|
1366
|
-
rhs = this.parseExpression();
|
|
1367
|
-
}
|
|
1368
|
-
if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
1369
|
-
leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
|
|
1370
|
-
}
|
|
1371
|
-
children.push({ kind: "expr", expression: leftExpr, loc });
|
|
1372
|
-
} else {
|
|
1373
|
-
children.push({ kind: "expr", expression: indexedExpr, loc });
|
|
1374
|
-
}
|
|
1375
|
-
} else if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
|
|
1376
|
-
children.push(this.parseCompUse());
|
|
1377
|
-
} else {
|
|
1378
|
-
const name = this.consume(TT.IDENT).value;
|
|
1379
|
-
children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
else throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
|
|
1383
|
-
// reject implicit concatenation only after expression children
|
|
1384
|
-
if (children.length > 0) {
|
|
1385
|
-
const lastChild = children[children.length - 1];
|
|
1386
|
-
if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
|
|
1387
|
-
const nextTT = this.tokens[this.pos]?.type;
|
|
1388
|
-
if (
|
|
1389
|
-
nextTT === TT.STRING || nextTT === TT.NUMBER ||
|
|
1390
|
-
nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
|
|
1391
|
-
(nextTT === TT.IDENT &&
|
|
1392
|
-
this.tokens[this.pos]?.value !== "var" &&
|
|
1393
|
-
this.tokens[this.pos]?.value !== "if" &&
|
|
1394
|
-
this.tokens[this.pos]?.value !== "for" &&
|
|
1395
|
-
this.tokens[this.pos]?.value !== "else" &&
|
|
1396
|
-
this.tokens[this.pos]?.value !== "and" &&
|
|
1397
|
-
this.tokens[this.pos]?.value !== "or")
|
|
1398
|
-
) {
|
|
1399
|
-
throw new SinthError(
|
|
1400
|
-
`Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
|
|
1401
|
-
this.peek().loc,
|
|
1402
|
-
);
|
|
1403
|
-
}
|
|
1404
|
-
}
|
|
1405
|
-
}
|
|
1406
|
-
}
|
|
1407
|
-
return children;
|
|
1408
|
-
}
|
|
1409
|
-
|
|
1410
|
-
// style & script blocks
|
|
1411
|
-
|
|
1412
|
-
private parseStyleBlock(): StyleBlock {
|
|
1413
|
-
const loc = this.consume(TT.KW_STYLE).loc;
|
|
1414
|
-
let global = false, lang: "css" | "scss" = "css", target: string | undefined;
|
|
1415
|
-
const extraAttrs: Record<string, string> = {};
|
|
1416
|
-
|
|
1417
|
-
while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
|
|
1418
|
-
if (this.check(TT.KW_GLOBAL)) { global = true; this.consume(TT.KW_GLOBAL); }
|
|
1419
|
-
else if (this.check(TT.KW_LANG)) {
|
|
1420
|
-
this.consume(TT.KW_LANG); this.consume(TT.EQUALS);
|
|
1421
|
-
const lv = this.consume(TT.STRING).value;
|
|
1422
|
-
if (lv !== "css" && lv !== "scss") throw new SinthError(`Unsupported style lang '${lv}'`, loc);
|
|
1423
|
-
lang = lv as "css" | "scss";
|
|
1424
|
-
}
|
|
1425
|
-
else if (this.check(TT.IDENT)) {
|
|
1426
|
-
if (this.tokens[this.pos + 1]?.type !== TT.EQUALS) {
|
|
1427
|
-
target = this.consume(TT.IDENT).value;
|
|
1428
|
-
} else {
|
|
1429
|
-
const k = this.consume(TT.IDENT).value;
|
|
1430
|
-
this.consume(TT.EQUALS);
|
|
1431
|
-
extraAttrs[k] = this.consume(TT.STRING).value;
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
else throw new SinthError(`Unexpected token '${this.peek().value}' in style modifiers`, this.peek().loc);
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
return { global, lang, raw: this.consume(TT.RAW_BLOCK).value, target, extraAttrs, loc };
|
|
1438
|
-
}
|
|
1439
|
-
|
|
1440
|
-
private parseScriptBlock(): ScriptBlock {
|
|
1441
|
-
const loc = this.consume(TT.KW_SCRIPT).loc;
|
|
1442
|
-
const attrs: Record<string, string> = {};
|
|
1443
|
-
while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
|
|
1444
|
-
const key = this.consume(TT.IDENT).value;
|
|
1445
|
-
if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); attrs[key] = this.consume(TT.STRING).value; }
|
|
1446
|
-
else { attrs[key] = "true"; }
|
|
1447
|
-
}
|
|
1448
|
-
return { raw: this.consume(TT.RAW_BLOCK).value, attrs, loc };
|
|
1449
|
-
}
|
|
1450
|
-
|
|
1451
|
-
private parseLiteral(): Literal {
|
|
1452
|
-
const tok = this.peek();
|
|
1453
|
-
if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
|
|
1454
|
-
if (this.check(TT.LBRACE)) {
|
|
1455
|
-
const obj = this.parseObjectLiteral();
|
|
1456
|
-
return { kind: "str", value: JSON.stringify(obj) };
|
|
1457
|
-
}
|
|
1458
|
-
if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
|
|
1459
|
-
if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
|
|
1460
|
-
if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
|
|
1461
|
-
if (this.check(TT.BOOL_FALSE)){ this.consume(TT.BOOL_FALSE);return { kind: "bool", value: false }; }
|
|
1462
|
-
if (this.check(TT.NULL_LIT)) { this.consume(TT.NULL_LIT); return { kind: "null" }; }
|
|
1463
|
-
throw new SinthError(`Expected literal value, got '${tok.value}' (${TT[tok.type]})`, tok.loc);
|
|
1464
|
-
}
|
|
1465
|
-
|
|
1466
|
-
private peek(): Token { return this.tokens[this.pos]; }
|
|
1467
|
-
private check(t: TT): boolean { return this.tokens[this.pos]?.type === t; }
|
|
1468
|
-
private consume(t: TT): Token {
|
|
1469
|
-
const tok = this.tokens[this.pos];
|
|
1470
|
-
if (tok.type !== t) {
|
|
1471
|
-
throw new SinthError(
|
|
1472
|
-
`Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`,
|
|
1473
|
-
tok.loc,
|
|
1474
|
-
);
|
|
1475
|
-
}
|
|
1476
|
-
this.pos++;
|
|
1477
|
-
return tok;
|
|
1478
|
-
}
|
|
1479
|
-
}
|
|
1480
|
-
|
|
1481
|
-
// import resolver
|
|
1482
|
-
|
|
1483
|
-
interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
|
|
1484
|
-
|
|
1485
|
-
interface ResolvedImports {
|
|
1486
|
-
allDefs: Map<string, CompDef>;
|
|
1487
|
-
customEls: Map<string, CustomElInfo>;
|
|
1488
|
-
cssLinks: string[];
|
|
1489
|
-
jsLinks: { src: string; attrs: Record<string, string> }[];
|
|
1490
|
-
}
|
|
1491
|
-
|
|
1492
|
-
const IMPORT_STACK: string[] = [];
|
|
1493
|
-
|
|
1494
|
-
function parseFile(filePath: string): SinthFile {
|
|
1495
|
-
if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
|
|
1496
|
-
const src = fs.readFileSync(filePath, "utf-8");
|
|
1497
|
-
const srcLines = src.split("\n");
|
|
1498
|
-
try {
|
|
1499
|
-
const tokens = new Lexer(src, filePath).tokenize();
|
|
1500
|
-
return new Parser(tokens, filePath).parse();
|
|
1501
|
-
} catch (e) {
|
|
1502
|
-
if (e instanceof SinthError) throw e.withSource(srcLines);
|
|
1503
|
-
throw e;
|
|
1504
|
-
}
|
|
1505
|
-
}
|
|
1506
|
-
|
|
1507
|
-
function resolveImports(
|
|
1508
|
-
file: SinthFile,
|
|
1509
|
-
cfg: ResolverConfig,
|
|
1510
|
-
visited: Set<string> = new Set(),
|
|
1511
|
-
): ResolvedImports {
|
|
1512
|
-
const allDefs = new Map<string, CompDef>();
|
|
1513
|
-
const customEls = new Map<string, CustomElInfo>();
|
|
1514
|
-
const cssLinks: string[] = [];
|
|
1515
|
-
const jsLinks: { src: string; attrs: Record<string, string> }[] = [];
|
|
1516
|
-
|
|
1517
|
-
for (const def of file.defs) {
|
|
1518
|
-
if (BUILTIN_MAP[def.name]) {
|
|
1519
|
-
throw new SinthError(`'${def.name}' is a built-in Sinth component and cannot be redefined.`, def.loc);
|
|
1520
|
-
}
|
|
1521
|
-
if (allDefs.has(def.name)) throw new SinthError(`Duplicate component definition '${def.name}'`, def.loc);
|
|
1522
|
-
allDefs.set(def.name, def);
|
|
1523
|
-
}
|
|
1524
|
-
|
|
1525
|
-
for (const el of file.customEls) {
|
|
1526
|
-
customEls.set(el.sinthName, { tagName: el.tagName, params: el.params });
|
|
1527
|
-
}
|
|
1528
|
-
|
|
1529
|
-
if (!file.isPage && file.meta.length > 0) {
|
|
1530
|
-
for (const m of file.meta) {
|
|
1531
|
-
SinthWarning.emit(`Metadata '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
|
|
1532
|
-
}
|
|
1533
|
-
}
|
|
1534
|
-
|
|
1535
|
-
for (const imp of file.imports) {
|
|
1536
|
-
if (imp.kind === "css") {
|
|
1537
|
-
const r = resolveRelative(imp.path, file.filePath);
|
|
1538
|
-
if (!cssLinks.includes(r)) cssLinks.push(r);
|
|
1539
|
-
|
|
1540
|
-
} else if (imp.kind === "js") {
|
|
1541
|
-
const src = resolveLibrary(imp.name, cfg);
|
|
1542
|
-
jsLinks.push({ src, attrs: {} });
|
|
1543
|
-
|
|
1544
|
-
for (const libDir of cfg.libraryPaths) {
|
|
1545
|
-
const companion = path.join(libDir, imp.name + ".sinth");
|
|
1546
|
-
if (fs.existsSync(companion) && !visited.has(companion)) {
|
|
1547
|
-
visited.add(companion);
|
|
1548
|
-
IMPORT_STACK.push(companion);
|
|
1549
|
-
const sub = resolveImports(parseFile(companion), cfg, visited);
|
|
1550
|
-
IMPORT_STACK.pop();
|
|
1551
|
-
for (const [n, d] of sub.allDefs) allDefs.set(n, d);
|
|
1552
|
-
for (const [n, e] of sub.customEls) customEls.set(n, e);
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
} else if (imp.kind === "sinth") {
|
|
1557
|
-
const resolved = resolveSinthPath(imp.path, file.filePath, cfg);
|
|
1558
|
-
|
|
1559
|
-
if (IMPORT_STACK.includes(resolved)) {
|
|
1560
|
-
throw new SinthError(
|
|
1561
|
-
`Circular import: ${[...IMPORT_STACK, resolved].join(" → ")}`
|
|
1562
|
-
);
|
|
1563
|
-
}
|
|
1564
|
-
if (visited.has(resolved)) continue;
|
|
1565
|
-
visited.add(resolved);
|
|
1566
|
-
|
|
1567
|
-
IMPORT_STACK.push(resolved);
|
|
1568
|
-
const imported = parseFile(resolved);
|
|
1569
|
-
IMPORT_STACK.pop();
|
|
1570
|
-
|
|
1571
|
-
const sub = resolveImports(imported, cfg, visited);
|
|
1572
|
-
for (const [name, def] of sub.allDefs) {
|
|
1573
|
-
if (allDefs.has(name)) throw new SinthError(`Component '${name}' defined in multiple imported files.`);
|
|
1574
|
-
allDefs.set(name, def);
|
|
1575
|
-
}
|
|
1576
|
-
for (const [n, e] of sub.customEls) customEls.set(n, e);
|
|
1577
|
-
for (const l of sub.cssLinks) if (!cssLinks.includes(l)) cssLinks.push(l);
|
|
1578
|
-
for (const j of sub.jsLinks) jsLinks.push(j);
|
|
1579
|
-
}
|
|
1580
|
-
}
|
|
1581
|
-
|
|
1582
|
-
return { allDefs, customEls, cssLinks, jsLinks };
|
|
1583
|
-
}
|
|
1584
|
-
|
|
1585
|
-
function resolveRelative(p: string, fromFile: string): string {
|
|
1586
|
-
if (p.startsWith("./") || p.startsWith("../")) return path.resolve(path.dirname(fromFile), p);
|
|
1587
|
-
return p;
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
function resolveLibrary(name: string, cfg: ResolverConfig): string {
|
|
1591
|
-
const base = name.endsWith(".js") ? name : name + ".js";
|
|
1592
|
-
for (const libDir of cfg.libraryPaths) {
|
|
1593
|
-
const c = path.join(libDir, base);
|
|
1594
|
-
if (fs.existsSync(c)) return c;
|
|
1595
|
-
}
|
|
1596
|
-
return `/libraries/${base}`;
|
|
1597
|
-
}
|
|
1598
|
-
|
|
1599
|
-
function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
|
|
1600
|
-
if (p.startsWith("./") || p.startsWith("../")) {
|
|
1601
|
-
const r = path.resolve(path.dirname(fromFile), p);
|
|
1602
|
-
if (fs.existsSync(r)) return r;
|
|
1603
|
-
const w = r.endsWith(".sinth") ? "" : r + ".sinth";
|
|
1604
|
-
if (w && fs.existsSync(w)) return w;
|
|
1605
|
-
throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
|
|
1606
|
-
}
|
|
1607
|
-
|
|
1608
|
-
const relToFile = path.resolve(path.dirname(fromFile), p);
|
|
1609
|
-
if (fs.existsSync(relToFile)) return relToFile;
|
|
1610
|
-
const relToFileExt = relToFile.endsWith(".sinth") ? relToFile : relToFile + ".sinth";
|
|
1611
|
-
if (fs.existsSync(relToFileExt)) return relToFileExt;
|
|
1612
|
-
|
|
1613
|
-
for (const libDir of cfg.libraryPaths) {
|
|
1614
|
-
const c1 = path.join(libDir, p);
|
|
1615
|
-
if (fs.existsSync(c1)) return c1;
|
|
1616
|
-
const c2 = c1.endsWith(".sinth") ? c1 : c1 + ".sinth";
|
|
1617
|
-
if (fs.existsSync(c2)) return c2;
|
|
1618
|
-
}
|
|
1619
|
-
|
|
1620
|
-
throw new SinthError(
|
|
1621
|
-
`Cannot resolve import '${p}'\n Tried: ${relToFileExt}\n Library paths: ${cfg.libraryPaths.join(", ")}`
|
|
1622
|
-
);
|
|
1623
|
-
}
|
|
1624
|
-
|
|
1625
|
-
// built-in component map
|
|
1626
|
-
|
|
1627
|
-
interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
|
|
1628
|
-
|
|
1629
|
-
const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
1630
|
-
// structural
|
|
1631
|
-
Main: { tag: "main" },
|
|
1632
|
-
Header: { tag: "header" },
|
|
1633
|
-
Footer: { tag: "footer" },
|
|
1634
|
-
Nav: { tag: "nav" },
|
|
1635
|
-
Section: { tag: "section" },
|
|
1636
|
-
Article: { tag: "article" },
|
|
1637
|
-
Aside: { tag: "aside" },
|
|
1638
|
-
Div: { tag: "div" },
|
|
1639
|
-
Span: { tag: "span" },
|
|
1640
|
-
Hero: { tag: "section", defaultClass: "hero" },
|
|
1641
|
-
Container: { tag: "div", defaultClass: "container" },
|
|
1642
|
-
Grid: { tag: "div", defaultClass: "grid" },
|
|
1643
|
-
Flex: { tag: "div", defaultClass: "flex" },
|
|
1644
|
-
Stack: { tag: "div", defaultClass: "stack" },
|
|
1645
|
-
Row: { tag: "div", defaultClass: "row" },
|
|
1646
|
-
Column: { tag: "div", defaultClass: "col" },
|
|
1647
|
-
CardGrid: { tag: "div", defaultClass: "card-grid" },
|
|
1648
|
-
// typography
|
|
1649
|
-
Heading: { tag: "h1" },
|
|
1650
|
-
SubHeading: { tag: "p", defaultClass: "subheading" },
|
|
1651
|
-
Paragraph: { tag: "p" },
|
|
1652
|
-
Lead: { tag: "p", defaultClass: "lead" },
|
|
1653
|
-
Small: { tag: "small" },
|
|
1654
|
-
Strong: { tag: "strong" },
|
|
1655
|
-
Em: { tag: "em" },
|
|
1656
|
-
Code: { tag: "code" },
|
|
1657
|
-
Pre: { tag: "pre" },
|
|
1658
|
-
Blockquote: { tag: "blockquote" },
|
|
1659
|
-
Mark: { tag: "mark" },
|
|
1660
|
-
Label: { tag: "label" },
|
|
1661
|
-
Abbr: { tag: "abbr" },
|
|
1662
|
-
Del: { tag: "del" },
|
|
1663
|
-
Ins: { tag: "ins" },
|
|
1664
|
-
Sub: { tag: "sub" },
|
|
1665
|
-
Sup: { tag: "sup" },
|
|
1666
|
-
Data: { tag: "data" },
|
|
1667
|
-
Time: { tag: "time" },
|
|
1668
|
-
Bdi: { tag: "bdi" },
|
|
1669
|
-
Bdo: { tag: "bdo" },
|
|
1670
|
-
Cite: { tag: "cite" },
|
|
1671
|
-
Dfn: { tag: "dfn" },
|
|
1672
|
-
Kbd: { tag: "kbd" },
|
|
1673
|
-
Samp: { tag: "samp" },
|
|
1674
|
-
Var: { tag: "var" },
|
|
1675
|
-
Address: { tag: "address" },
|
|
1676
|
-
Ruby: { tag: "ruby" },
|
|
1677
|
-
Rt: { tag: "rt" },
|
|
1678
|
-
Rp: { tag: "rp" },
|
|
1679
|
-
// interactive
|
|
1680
|
-
Button: { tag: "button" },
|
|
1681
|
-
Link: { tag: "a" },
|
|
1682
|
-
NavLink: { tag: "a" },
|
|
1683
|
-
Select: { tag: "select" },
|
|
1684
|
-
Form: { tag: "form" },
|
|
1685
|
-
Fieldset: { tag: "fieldset" },
|
|
1686
|
-
Legend: { tag: "legend" },
|
|
1687
|
-
Details: { tag: "details" },
|
|
1688
|
-
Summary: { tag: "summary" },
|
|
1689
|
-
Dialog: { tag: "dialog" },
|
|
1690
|
-
Textarea: { tag: "textarea" },
|
|
1691
|
-
Datalist: { tag: "datalist" },
|
|
1692
|
-
Optgroup: { tag: "optgroup" },
|
|
1693
|
-
Option: { tag: "option" },
|
|
1694
|
-
Progress: { tag: "progress" },
|
|
1695
|
-
Meter: { tag: "meter" },
|
|
1696
|
-
Output: { tag: "output" },
|
|
1697
|
-
Map: { tag: "map" },
|
|
1698
|
-
// media
|
|
1699
|
-
Picture: { tag: "picture" },
|
|
1700
|
-
Video: { tag: "video" },
|
|
1701
|
-
Audio: { tag: "audio" },
|
|
1702
|
-
Figure: { tag: "figure" },
|
|
1703
|
-
Figcaption: { tag: "figcaption" },
|
|
1704
|
-
Canvas: { tag: "canvas" },
|
|
1705
|
-
Svg: { tag: "svg" },
|
|
1706
|
-
IFrame: { tag: "iframe" },
|
|
1707
|
-
Object: { tag: "object" },
|
|
1708
|
-
// void elements
|
|
1709
|
-
Img: { tag: "img", voidEl: true },
|
|
1710
|
-
Logo: { tag: "img", voidEl: true },
|
|
1711
|
-
Input: { tag: "input", voidEl: true },
|
|
1712
|
-
Checkbox: { tag: "input", voidEl: true },
|
|
1713
|
-
Hr: { tag: "hr", voidEl: true },
|
|
1714
|
-
Br: { tag: "br", voidEl: true },
|
|
1715
|
-
Wbr: { tag: "wbr", voidEl: true },
|
|
1716
|
-
Source: { tag: "source", voidEl: true },
|
|
1717
|
-
Embed: { tag: "embed", voidEl: true },
|
|
1718
|
-
Col: { tag: "col", voidEl: true },
|
|
1719
|
-
Area: { tag: "area", voidEl: true },
|
|
1720
|
-
// lists
|
|
1721
|
-
Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
|
|
1722
|
-
Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
|
|
1723
|
-
// tables
|
|
1724
|
-
Table: { tag: "table" },
|
|
1725
|
-
Caption: { tag: "caption" },
|
|
1726
|
-
Thead: { tag: "thead" },
|
|
1727
|
-
Tbody: { tag: "tbody" },
|
|
1728
|
-
Tfoot: { tag: "tfoot" },
|
|
1729
|
-
Tr: { tag: "tr" },
|
|
1730
|
-
Th: { tag: "th" },
|
|
1731
|
-
Td: { tag: "td" },
|
|
1732
|
-
Colgroup: { tag: "colgroup" },
|
|
1733
|
-
// utility
|
|
1734
|
-
Template: { tag: "template" },
|
|
1735
|
-
Slot: { tag: "slot" },
|
|
1736
|
-
NoScript: { tag: "noscript" },
|
|
1737
|
-
RawHTML: { tag: "__RAW__" },
|
|
1738
|
-
};
|
|
1739
|
-
|
|
1740
|
-
const VOID_TAGS = new Set([
|
|
1741
|
-
"area","base","br","col","embed","hr","img","input",
|
|
1742
|
-
"link","meta","param","source","track","wbr",
|
|
1743
|
-
]);
|
|
1744
|
-
|
|
1745
|
-
const EVENT_RE = /^on[A-Z]/;
|
|
1746
|
-
function eventAttrName(name: string): string | null {
|
|
1747
|
-
return EVENT_RE.test(name) ? name.toLowerCase() : null;
|
|
1748
|
-
}
|
|
1749
|
-
|
|
1750
|
-
// preprocessor
|
|
1751
|
-
|
|
1752
|
-
/**
|
|
1753
|
-
* for who's reading this: This maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
|
|
1754
|
-
* these are used inside component style blocks, for example: onHover { color: "blue" }
|
|
1755
|
-
*/
|
|
1756
|
-
const SINTH_PSEUDO_CLASS: Record<string, string> = {
|
|
1757
|
-
onHover: ":hover",
|
|
1758
|
-
onFocus: ":focus",
|
|
1759
|
-
onActive: ":active",
|
|
1760
|
-
onVisited: ":visited",
|
|
1761
|
-
onChecked: ":checked",
|
|
1762
|
-
onDisabled: ":disabled",
|
|
1763
|
-
onEnabled: ":enabled",
|
|
1764
|
-
onRequired: ":required",
|
|
1765
|
-
onOptional: ":optional",
|
|
1766
|
-
onValid: ":valid",
|
|
1767
|
-
onInvalid: ":invalid",
|
|
1768
|
-
onPlaceholderShown:":placeholder-shown",
|
|
1769
|
-
onFocusWithin: ":focus-within",
|
|
1770
|
-
onFocusVisible: ":focus-visible",
|
|
1771
|
-
onFirst: ":first-child",
|
|
1772
|
-
onLast: ":last-child",
|
|
1773
|
-
onFirstOfType: ":first-of-type",
|
|
1774
|
-
onLastOfType: ":last-of-type",
|
|
1775
|
-
onEmpty: ":empty",
|
|
1776
|
-
onTarget: ":target",
|
|
1777
|
-
onLink: ":link",
|
|
1778
|
-
};
|
|
1779
|
-
|
|
1780
|
-
const SINTH_PSEUDO_ELEMENT: Record<string, string> = {
|
|
1781
|
-
before: "::before",
|
|
1782
|
-
after: "::after",
|
|
1783
|
-
placeholder: "::placeholder",
|
|
1784
|
-
selection: "::selection",
|
|
1785
|
-
firstLine: "::first-line",
|
|
1786
|
-
firstLetter: "::first-letter",
|
|
1787
|
-
marker: "::marker",
|
|
1788
|
-
backdrop: "::backdrop",
|
|
1789
|
-
};
|
|
1790
|
-
|
|
1791
|
-
function sinthCompToSelector(name: string): string {
|
|
1792
|
-
const info = BUILTIN_MAP[name];
|
|
1793
|
-
if (!info) return name.toLowerCase();
|
|
1794
|
-
if (info.defaultClass) {
|
|
1795
|
-
const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
|
|
1796
|
-
return `${info.tag}${classes}`;
|
|
1797
|
-
}
|
|
1798
|
-
return info.tag;
|
|
1799
|
-
}
|
|
1800
|
-
|
|
1801
|
-
/**
|
|
1802
|
-
* supported conversions:
|
|
1803
|
-
* - component names as selectors: `Paragraph { ... }` → `p { ... }`
|
|
1804
|
-
* - pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
|
|
1805
|
-
* - pseudo-element shorthands: `before { ... }` → `&::before { ... }`
|
|
1806
|
-
* - media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
|
|
1807
|
-
* - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
|
|
1808
|
-
*/
|
|
1809
|
-
function preprocessSinthStyle(raw: string): string {
|
|
1810
|
-
const lines = raw.split("\n");
|
|
1811
|
-
const result: string[] = [];
|
|
1812
|
-
|
|
1813
|
-
for (const line of lines) {
|
|
1814
|
-
const trimmed = line.trim();
|
|
1815
|
-
const indent = line.match(/^(\s*)/)?.[1] ?? "";
|
|
1816
|
-
|
|
1817
|
-
if (!trimmed) { result.push(line); continue; }
|
|
1818
|
-
|
|
1819
|
-
if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) { continue; }
|
|
1820
|
-
// Standard comments pass through
|
|
1821
|
-
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
|
1822
|
-
result.push(line); continue;
|
|
1823
|
-
}
|
|
1824
|
-
|
|
1825
|
-
const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
|
|
1826
|
-
if (mediaMatch) {
|
|
1827
|
-
const params = parseSinthMediaParams(mediaMatch[1]);
|
|
1828
|
-
result.push(`${indent}@media (${params}) {`);
|
|
1829
|
-
continue;
|
|
1830
|
-
}
|
|
1831
|
-
|
|
1832
|
-
const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
|
|
1833
|
-
if (blockMatch) {
|
|
1834
|
-
const keyword = blockMatch[1];
|
|
1835
|
-
|
|
1836
|
-
const pseudoCls = SINTH_PSEUDO_CLASS[keyword];
|
|
1837
|
-
if (pseudoCls) {
|
|
1838
|
-
result.push(`${indent}&${pseudoCls} {`);
|
|
1839
|
-
continue;
|
|
1840
|
-
}
|
|
1841
|
-
|
|
1842
|
-
const pseudoEl = SINTH_PSEUDO_ELEMENT[keyword];
|
|
1843
|
-
if (pseudoEl) {
|
|
1844
|
-
result.push(`${indent}&${pseudoEl} {`);
|
|
1845
|
-
continue;
|
|
1846
|
-
}
|
|
1847
|
-
|
|
1848
|
-
if (/^[A-Z]/.test(keyword) && BUILTIN_MAP[keyword]) {
|
|
1849
|
-
result.push(`${indent}${sinthCompToSelector(keyword)} {`);
|
|
1850
|
-
continue;
|
|
1851
|
-
}
|
|
1852
|
-
}
|
|
1853
|
-
|
|
1854
|
-
const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
|
|
1855
|
-
if (varPropMatch) {
|
|
1856
|
-
result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
|
|
1857
|
-
continue;
|
|
1858
|
-
}
|
|
1859
|
-
|
|
1860
|
-
result.push(line);
|
|
1861
|
-
}
|
|
1862
|
-
|
|
1863
|
-
return result.join("\n");
|
|
1864
|
-
}
|
|
1865
|
-
|
|
1866
|
-
function parseSinthMediaParams(params: string): string {
|
|
1867
|
-
const parts = params.split(",").map(p => {
|
|
1868
|
-
const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
|
|
1869
|
-
if (!m) return p.trim();
|
|
1870
|
-
return `${camelToKebab(m[1])}: ${m[2].trim()}`;
|
|
1871
|
-
});
|
|
1872
|
-
return parts.join(") and (");
|
|
1873
|
-
}
|
|
1874
|
-
|
|
1875
|
-
// style processor
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
function convertCSSProps(css: string): string {
|
|
1879
|
-
return css.split("\n").map(line => {
|
|
1880
|
-
const trimmed = line.trim();
|
|
1881
|
-
if (!trimmed) return line;
|
|
1882
|
-
if (trimmed === "}" || trimmed.startsWith("}")) return line;
|
|
1883
|
-
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
|
|
1884
|
-
if (trimmed.startsWith("@")) return line;
|
|
1885
|
-
if (trimmed.includes("{")) return line;
|
|
1886
|
-
|
|
1887
|
-
const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
|
|
1888
|
-
if (!m) return line;
|
|
1889
|
-
|
|
1890
|
-
const [, indent, rawProp, , rawVal] = m;
|
|
1891
|
-
|
|
1892
|
-
const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
|
|
1893
|
-
const hasQuotedVal = /^["']/.test(rawVal.trim());
|
|
1894
|
-
if (!hasCamelCase && !hasQuotedVal) return line;
|
|
1895
|
-
|
|
1896
|
-
let val = rawVal.trim();
|
|
1897
|
-
if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
|
|
1898
|
-
if ((val.startsWith('"') && val.endsWith('"')) ||
|
|
1899
|
-
(val.startsWith("'") && val.endsWith("'"))) {
|
|
1900
|
-
val = val.slice(1, -1);
|
|
1901
|
-
}
|
|
1902
|
-
|
|
1903
|
-
return `${indent}${camelToKebab(rawProp)}: ${val};`;
|
|
1904
|
-
}).join("\n");
|
|
1905
|
-
}
|
|
1906
|
-
|
|
1907
|
-
function processStyleBlock(
|
|
1908
|
-
block: StyleBlock,
|
|
1909
|
-
hash: string,
|
|
1910
|
-
params: Map<string, string> = new Map(),
|
|
1911
|
-
): string {
|
|
1912
|
-
let raw = block.raw;
|
|
1913
|
-
|
|
1914
|
-
// 1. interpolate {param} placeholders
|
|
1915
|
-
if (params.size > 0) raw = interpolateAttr(raw, params);
|
|
1916
|
-
|
|
1917
|
-
// 2. sinth style preprocessing
|
|
1918
|
-
raw = preprocessSinthStyle(raw);
|
|
1919
|
-
|
|
1920
|
-
// 3. warn if & in plain CSS
|
|
1921
|
-
if (block.lang === "css" && raw.includes("&")) {
|
|
1922
|
-
SinthWarning.emit(
|
|
1923
|
-
`'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
|
|
1924
|
-
block.loc,
|
|
1925
|
-
);
|
|
1926
|
-
}
|
|
1927
|
-
|
|
1928
|
-
// 4. camelCase → kebab-case
|
|
1929
|
-
let css = convertCSSProps(raw);
|
|
1930
|
-
|
|
1931
|
-
// 5. SCSS compilation
|
|
1932
|
-
if (block.lang === "scss") {
|
|
1933
|
-
try {
|
|
1934
|
-
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
1935
|
-
const sass: { compileString: (src: string) => { css: string } } = require("sass");
|
|
1936
|
-
css = sass.compileString(css).css;
|
|
1937
|
-
} catch (e: unknown) {
|
|
1938
|
-
const err = e as { code?: string; message?: string };
|
|
1939
|
-
if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
|
|
1940
|
-
throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
|
|
1941
|
-
}
|
|
1942
|
-
throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
|
|
1943
|
-
}
|
|
1944
|
-
}
|
|
1945
|
-
|
|
1946
|
-
// 6. if target component given, wrap content in its CSS selector
|
|
1947
|
-
if (block.target) {
|
|
1948
|
-
const selector = sinthCompToSelector(block.target);
|
|
1949
|
-
css = `${selector} {\n${css}\n}`;
|
|
1950
|
-
}
|
|
1951
|
-
|
|
1952
|
-
// 7. scope (except it's global)
|
|
1953
|
-
if (!block.global) css = scopeCSS(css, hash);
|
|
1954
|
-
|
|
1955
|
-
return css;
|
|
1956
|
-
}
|
|
1957
|
-
|
|
1958
|
-
function scopeCSS(css: string, hash: string): string {
|
|
1959
|
-
return processRules(css, `[data-s="${hash}"]`);
|
|
1960
|
-
}
|
|
1961
|
-
|
|
1962
|
-
function processRules(css: string, attr: string): string {
|
|
1963
|
-
let out = "", i = 0;
|
|
1964
|
-
|
|
1965
|
-
while (i < css.length) {
|
|
1966
|
-
if (/\s/.test(css[i])) { out += css[i++]; continue; }
|
|
1967
|
-
|
|
1968
|
-
if (css[i] === "/" && css[i + 1] === "*") {
|
|
1969
|
-
const end = css.indexOf("*/", i + 2);
|
|
1970
|
-
if (end === -1) { out += css.substring(i); break; }
|
|
1971
|
-
out += css.substring(i, end + 2);
|
|
1972
|
-
i = end + 2;
|
|
1973
|
-
continue;
|
|
1974
|
-
}
|
|
1975
|
-
|
|
1976
|
-
const braceIdx = findCSSBrace(css, i);
|
|
1977
|
-
if (braceIdx === -1) { out += css.substring(i); break; }
|
|
1978
|
-
|
|
1979
|
-
const selector = css.substring(i, braceIdx).trim();
|
|
1980
|
-
const { content, end } = extractCSSBlock(css, braceIdx);
|
|
1981
|
-
|
|
1982
|
-
if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
|
|
1983
|
-
out += `${selector} {${content}}\n`;
|
|
1984
|
-
} else if (/^@(media|supports|layer|container)/.test(selector)) {
|
|
1985
|
-
out += `${selector} {\n${processRules(content, attr)}\n}\n`;
|
|
1986
|
-
} else if (selector.startsWith("@")) {
|
|
1987
|
-
out += `${selector} {${content}}\n`;
|
|
1988
|
-
} else if (selector.length > 0) {
|
|
1989
|
-
out += `${scopeSelectors(selector, attr)} {${content}}\n`;
|
|
1990
|
-
}
|
|
1991
|
-
|
|
1992
|
-
i = end;
|
|
1993
|
-
}
|
|
1994
|
-
return out;
|
|
1995
|
-
}
|
|
1996
|
-
|
|
1997
|
-
function scopeSelectors(selList: string, attr: string): string {
|
|
1998
|
-
return selList
|
|
1999
|
-
.split(",")
|
|
2000
|
-
.map(s => {
|
|
2001
|
-
s = s.trim();
|
|
2002
|
-
if (!s) return "";
|
|
2003
|
-
if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
|
|
2004
|
-
const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
|
|
2005
|
-
if (m && m[1].trim()) {
|
|
2006
|
-
return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
|
|
2007
|
-
}
|
|
2008
|
-
return `${attr} ${s}, ${s}${attr}`;
|
|
2009
|
-
})
|
|
2010
|
-
.filter(Boolean)
|
|
2011
|
-
.join(",\n");
|
|
2012
|
-
}
|
|
2013
|
-
|
|
2014
|
-
function findCSSBrace(css: string, from: number): number {
|
|
2015
|
-
let i = from;
|
|
2016
|
-
while (i < css.length) {
|
|
2017
|
-
if (css[i] === '"' || css[i] === "'") {
|
|
2018
|
-
const q = css[i++];
|
|
2019
|
-
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
2020
|
-
i++;
|
|
2021
|
-
} else if (css[i] === "{") {
|
|
2022
|
-
return i;
|
|
2023
|
-
} else { i++; }
|
|
2024
|
-
}
|
|
2025
|
-
return -1;
|
|
2026
|
-
}
|
|
2027
|
-
|
|
2028
|
-
function extractCSSBlock(css: string, openBrace: number): { content: string; end: number } {
|
|
2029
|
-
let i = openBrace + 1, depth = 1;
|
|
2030
|
-
while (i < css.length && depth > 0) {
|
|
2031
|
-
if (css[i] === '"' || css[i] === "'") {
|
|
2032
|
-
const q = css[i++];
|
|
2033
|
-
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
2034
|
-
i++;
|
|
2035
|
-
} else if (css[i] === "/" && css[i + 1] === "*") {
|
|
2036
|
-
i += 2;
|
|
2037
|
-
while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/")) i++;
|
|
2038
|
-
i += 2;
|
|
2039
|
-
} else if (css[i] === "{") { depth++; i++; }
|
|
2040
|
-
else if (css[i] === "}") { depth--; if (depth > 0) i++; else break; }
|
|
2041
|
-
else { i++; }
|
|
2042
|
-
}
|
|
2043
|
-
return { content: css.substring(openBrace + 1, i), end: i + 1 };
|
|
2044
|
-
}
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
// expression -> js compiler
|
|
2048
|
-
|
|
2049
|
-
function compileExprToJS(expr: Expression, loopVars?: Set<string>): string {
|
|
2050
|
-
switch (expr.kind) {
|
|
2051
|
-
case "literal":
|
|
2052
|
-
if (!expr.value) return "null";
|
|
2053
|
-
if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
|
|
2054
|
-
if (expr.value.kind === "num") return String((expr.value as LitNum).value);
|
|
2055
|
-
if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
|
|
2056
|
-
return "null";
|
|
2057
|
-
case "variable":
|
|
2058
|
-
if (loopVars && expr.name && loopVars.has(expr.name)) {
|
|
2059
|
-
return `_ctx.${expr.name}`;
|
|
2060
|
-
}
|
|
2061
|
-
return expr.name ?? "undefined";
|
|
2062
|
-
case "binary": {
|
|
2063
|
-
const l = compileExprToJS(expr.left!, loopVars);
|
|
2064
|
-
const r = compileExprToJS(expr.right!, loopVars);
|
|
2065
|
-
const o = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op!;
|
|
2066
|
-
return `(${l} ${o} ${r})`;
|
|
2067
|
-
}
|
|
2068
|
-
case "unary": {
|
|
2069
|
-
const o = expr.op === "not" ? "!" : expr.op!;
|
|
2070
|
-
return `${o}(${compileExprToJS(expr.operand!, loopVars)})`;
|
|
2071
|
-
}
|
|
2072
|
-
case "assign": {
|
|
2073
|
-
const v = expr.right ? compileExprToJS(expr.right, loopVars) : "null";
|
|
2074
|
-
return `${expr.target} ${expr.op} ${v}`;
|
|
2075
|
-
}
|
|
2076
|
-
case "index":
|
|
2077
|
-
return `${compileExprToJS(expr.object!, loopVars)}[${compileExprToJS(expr.key!, loopVars)}]`;
|
|
2078
|
-
case "postfix":
|
|
2079
|
-
return `${expr.target}${expr.op}`;
|
|
2080
|
-
default:
|
|
2081
|
-
return "";
|
|
2082
|
-
}
|
|
2083
|
-
}
|
|
2084
|
-
|
|
2085
|
-
function compileIfToJS(ifBlock: IfBlock): string {
|
|
2086
|
-
const cond = compileExprToJS(ifBlock.condition);
|
|
2087
|
-
const ifJS = bodyToJS(ifBlock.body);
|
|
2088
|
-
const elseJS = ifBlock.elseBody ? bodyToJS(ifBlock.elseBody) : "";
|
|
2089
|
-
let js = `if (${cond}) {\n${ifJS}}\n`;
|
|
2090
|
-
if (elseJS) js += `else {\n${elseJS}}\n`;
|
|
2091
|
-
return js;
|
|
2092
|
-
}
|
|
2093
|
-
|
|
2094
|
-
function bodyToJS(children: Child[]): string {
|
|
2095
|
-
return children
|
|
2096
|
-
.filter(c => c.kind === "assign_stmt" || c.kind === "if")
|
|
2097
|
-
.map(c => {
|
|
2098
|
-
if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
|
|
2099
|
-
if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
|
|
2100
|
-
return "";
|
|
2101
|
-
})
|
|
2102
|
-
.join("");
|
|
2103
|
-
}
|
|
2104
|
-
|
|
2105
|
-
// the HTML generator
|
|
2106
|
-
|
|
2107
|
-
/**
|
|
2108
|
-
* CSS property names that are allowed as inline style shorthand attributes on
|
|
2109
|
-
* any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
|
|
2110
|
-
*/
|
|
2111
|
-
const INLINE_STYLE_PROPS = new Set([
|
|
2112
|
-
"color","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
|
|
2113
|
-
"fontSize","fontWeight","fontFamily","fontStyle","fontVariant","lineHeight","letterSpacing","textAlign",
|
|
2114
|
-
"textDecoration","textTransform","whiteSpace","wordBreak","wordWrap","textOverflow",
|
|
2115
|
-
"margin","marginTop","marginBottom","marginLeft","marginRight",
|
|
2116
|
-
"padding","paddingTop","paddingBottom","paddingLeft","paddingRight",
|
|
2117
|
-
"width","height","minWidth","maxWidth","minHeight","maxHeight",
|
|
2118
|
-
"display","flexDirection","flexWrap","flex","flexGrow","flexShrink","flexBasis",
|
|
2119
|
-
"justifyContent","alignItems","alignContent","alignSelf","gap","rowGap","columnGap",
|
|
2120
|
-
"gridTemplateColumns","gridTemplateRows","gridColumn","gridRow","gridArea",
|
|
2121
|
-
"position","top","right","bottom","left","zIndex",
|
|
2122
|
-
"border","borderTop","borderBottom","borderLeft","borderRight",
|
|
2123
|
-
"borderWidth","borderStyle","borderColor","borderRadius",
|
|
2124
|
-
"outline","outlineWidth","outlineStyle","outlineColor","outlineOffset",
|
|
2125
|
-
"boxShadow","textShadow","opacity","visibility",
|
|
2126
|
-
"overflow","overflowX","overflowY","objectFit","objectPosition",
|
|
2127
|
-
"cursor","userSelect","pointerEvents","resize",
|
|
2128
|
-
"transform","transition","animation","animationDuration","animationDelay",
|
|
2129
|
-
"listStyle","listStyleType","listStylePosition",
|
|
2130
|
-
"verticalAlign","float","clear",
|
|
2131
|
-
"content","quotes",
|
|
2132
|
-
]);
|
|
2133
|
-
|
|
2134
|
-
function resolveBuiltinTag(
|
|
2135
|
-
name: string,
|
|
2136
|
-
attrs: Attr[],
|
|
2137
|
-
): { tag: string; defaultClass?: string; voidEl: boolean } {
|
|
2138
|
-
if (name === "Heading") {
|
|
2139
|
-
const la = attrs.find(a => a.name === "level");
|
|
2140
|
-
const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
|
|
2141
|
-
if (!la) SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
|
|
2142
|
-
return { tag: `h${lv}`, voidEl: false };
|
|
2143
|
-
}
|
|
2144
|
-
const info = BUILTIN_MAP[name];
|
|
2145
|
-
if (info) return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
|
|
2146
|
-
SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
|
|
2147
|
-
return { tag: name.toLowerCase(), voidEl: false };
|
|
2148
|
-
}
|
|
2149
|
-
|
|
2150
|
-
function registerExpr(ctx: CompileCtx, expr: Expression): number {
|
|
2151
|
-
const jsExpr = compileExprToJS(expr, ctx.loopVars);
|
|
2152
|
-
const existing = ctx.exprMap.get(jsExpr);
|
|
2153
|
-
if (existing !== undefined) return existing;
|
|
2154
|
-
const id = ctx.exprRegistry.length;
|
|
2155
|
-
ctx.exprRegistry.push(jsExpr);
|
|
2156
|
-
ctx.exprMap.set(jsExpr, id);
|
|
2157
|
-
return id;
|
|
2158
|
-
}
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx?: CompileCtx): string {
|
|
2162
|
-
const { name, value } = attr;
|
|
2163
|
-
if (value === null) return name;
|
|
2164
|
-
if (value.kind === "null") return "";
|
|
2165
|
-
if (value.kind === "bool") return value.value ? name : "";
|
|
2166
|
-
|
|
2167
|
-
if (name === "model" && value?.kind === "str") {
|
|
2168
|
-
const vName = interpolateAttr(value.value, paramMap);
|
|
2169
|
-
return `oninput="(function(e){ ${vName} = e.target.value; sinthRender(); })(event)" value="${escAttr(vName)}"`;
|
|
2170
|
-
}
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
if (name === "delay") {
|
|
2175
|
-
if (value.kind === "num") {
|
|
2176
|
-
return `data-sinth-delay="${value.value}" style="display:none"`;
|
|
2177
|
-
}
|
|
2178
|
-
const v = litToString(value);
|
|
2179
|
-
if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}" style="display:none"`;
|
|
2180
|
-
if (v.startsWith("__EXPR__")) {
|
|
2181
|
-
try {
|
|
2182
|
-
const expr: Expression = JSON.parse(v.substring(8));
|
|
2183
|
-
const id = registerExpr(ctx, expr);
|
|
2184
|
-
return `data-sinth-delay-expr-id="${id}" style="display:none"`;
|
|
2185
|
-
} catch {}
|
|
2186
|
-
}
|
|
2187
|
-
// plain variable name – register as expression
|
|
2188
|
-
const id = registerExpr(ctx, { kind: "variable", name: v });
|
|
2189
|
-
return `data-sinth-delay-expr-id="${id}" style="display:none"`;
|
|
2190
|
-
}
|
|
2191
|
-
|
|
2192
|
-
if (name === "checked") {
|
|
2193
|
-
return (value as any)?.kind === "bool" && (value as any).value ? "checked" : "";
|
|
2194
|
-
}
|
|
2195
|
-
|
|
2196
|
-
if (value.kind === "num") return `${name}="${value.value}"`;
|
|
2197
|
-
|
|
2198
|
-
let raw = value.value;
|
|
2199
|
-
|
|
2200
|
-
if (raw.startsWith("__MULTI_EXPR__")) {
|
|
2201
|
-
const exprJson = raw.substring("__MULTI_EXPR__".length);
|
|
2202
|
-
try {
|
|
2203
|
-
const exprs: Expression[] = JSON.parse(exprJson);
|
|
2204
|
-
const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
|
|
2205
|
-
const ev = eventAttrName(name);
|
|
2206
|
-
if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, """)}; sinthRender(); })()"`;
|
|
2207
|
-
return `${name}="${escAttr(jsExprs)}"`;
|
|
2208
|
-
} catch { }
|
|
2209
|
-
}
|
|
2210
|
-
if (raw.startsWith("__EXPR__")) {
|
|
2211
|
-
const exprJson = raw.substring("__EXPR__".length);
|
|
2212
|
-
try {
|
|
2213
|
-
const expr: Expression = JSON.parse(exprJson);
|
|
2214
|
-
const jsExpr = compileExprToJS(expr);
|
|
2215
|
-
const ev = eventAttrName(name);
|
|
2216
|
-
if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, """)}; sinthRender(); })()"`;
|
|
2217
|
-
return `${name}="${escAttr(jsExpr)}"`;
|
|
2218
|
-
} catch { }
|
|
2219
|
-
}
|
|
2220
|
-
|
|
2221
|
-
raw = interpolateAttr(raw, paramMap);
|
|
2222
|
-
|
|
2223
|
-
const ev = eventAttrName(name);
|
|
2224
|
-
if (ev) {
|
|
2225
|
-
const call = raw.includes("(") ? raw : raw + "()";
|
|
2226
|
-
return `${ev}="${escAttr(call)};sinthRender()"`;
|
|
2227
|
-
}
|
|
2228
|
-
return `${name}="${escAttr(raw)}"`;
|
|
2229
|
-
}
|
|
2230
|
-
|
|
2231
|
-
function renderText(text: string, params: Map<string, string>): string {
|
|
2232
|
-
const rawSlots = new Map<string, string>();
|
|
2233
|
-
let counter = 0;
|
|
2234
|
-
|
|
2235
|
-
let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
|
|
2236
|
-
|
|
2237
|
-
s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
|
|
2238
|
-
const val = params.get(n);
|
|
2239
|
-
if (val === undefined) return `$${n}`;
|
|
2240
|
-
if (n === "slot") {
|
|
2241
|
-
const ph = `\x00RAW${counter++}\x00`;
|
|
2242
|
-
rawSlots.set(ph, val);
|
|
2243
|
-
return ph;
|
|
2244
|
-
}
|
|
2245
|
-
return val;
|
|
2246
|
-
});
|
|
2247
|
-
|
|
2248
|
-
s = esc(s);
|
|
2249
|
-
|
|
2250
|
-
for (const [ph, val] of rawSlots) s = s.replace(ph, val);
|
|
2251
|
-
s = s.replace(/\x00DOLLAR\x00/g, "$");
|
|
2252
|
-
|
|
2253
|
-
const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
|
|
2254
|
-
let m: RegExpExecArray | null;
|
|
2255
|
-
while ((m = braceRe.exec(s)) !== null) {
|
|
2256
|
-
SinthWarning.emit(
|
|
2257
|
-
`Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
|
|
2258
|
-
);
|
|
2259
|
-
}
|
|
2260
|
-
|
|
2261
|
-
return s;
|
|
2262
|
-
}
|
|
2263
|
-
|
|
2264
|
-
function interpolateAttr(text: string, params: Map<string, string>): string {
|
|
2265
|
-
let s = text.replace(/\\\{/g, "\x00LB\x00");
|
|
2266
|
-
s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
|
|
2267
|
-
return s.replace(/\x00LB\x00/g, "{");
|
|
2268
|
-
}
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
function renderChild(
|
|
2272
|
-
child: Child,
|
|
2273
|
-
ctx: CompileCtx,
|
|
2274
|
-
params: Map<string, string>,
|
|
2275
|
-
depth: number,
|
|
2276
|
-
): string {
|
|
2277
|
-
if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
|
|
2278
|
-
|
|
2279
|
-
switch (child.kind) {
|
|
2280
|
-
case "text":
|
|
2281
|
-
return renderText(child.value, params);
|
|
2282
|
-
|
|
2283
|
-
case "expr": {
|
|
2284
|
-
if (child.expression.kind === "literal" && child.expression.value) {
|
|
2285
|
-
return esc(litToString(child.expression.value));
|
|
2286
|
-
}
|
|
2287
|
-
if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
|
|
2288
|
-
const exprId = registerExpr(ctx, child.expression);
|
|
2289
|
-
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
2290
|
-
}
|
|
2291
|
-
const exprId = registerExpr(ctx, child.expression);
|
|
2292
|
-
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
2293
|
-
}
|
|
2294
|
-
|
|
2295
|
-
case "assign_stmt": {
|
|
2296
|
-
ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
|
|
2297
|
-
return "";
|
|
2298
|
-
}
|
|
2299
|
-
|
|
2300
|
-
case "remove": {
|
|
2301
|
-
return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
|
|
2302
|
-
}
|
|
2303
|
-
|
|
2304
|
-
case "if":
|
|
2305
|
-
return renderIfBlock(child, ctx, params, depth);
|
|
2306
|
-
|
|
2307
|
-
case "for": {
|
|
2308
|
-
// collect loop‑variable names
|
|
2309
|
-
const loopVars = new Set<string>();
|
|
2310
|
-
loopVars.add(child.itemVar);
|
|
2311
|
-
if (child.keyVar) loopVars.add(child.keyVar);
|
|
2312
|
-
if (child.indexVar) loopVars.add(child.indexVar);
|
|
2313
|
-
// set them on ctx for compilation of the body
|
|
2314
|
-
const prev = ctx.loopVars;
|
|
2315
|
-
ctx.loopVars = loopVars;
|
|
2316
|
-
const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
2317
|
-
ctx.loopVars = prev; // restore
|
|
2318
|
-
const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
|
|
2319
|
-
const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
|
|
2320
|
-
return (
|
|
2321
|
-
`<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`
|
|
2322
|
-
);
|
|
2323
|
-
}
|
|
2324
|
-
|
|
2325
|
-
case "use":
|
|
2326
|
-
return renderCompUse(child, ctx, params, depth);
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
|
|
2330
|
-
function renderIfBlock(
|
|
2331
|
-
ifBlock: IfBlock,
|
|
2332
|
-
ctx: CompileCtx,
|
|
2333
|
-
params: Map<string, string>,
|
|
2334
|
-
depth: number,
|
|
2335
|
-
): string {
|
|
2336
|
-
if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
|
|
2337
|
-
|
|
2338
|
-
const condJS = compileExprToJS(ifBlock.condition);
|
|
2339
|
-
const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
|
|
2340
|
-
const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
|
|
2341
|
-
const hasComp = allChildren.some(c => c.kind === "use");
|
|
2342
|
-
|
|
2343
|
-
// pure logic
|
|
2344
|
-
if (hasAssign && !hasComp) {
|
|
2345
|
-
ctx.logicBlocks.push(compileIfToJS(ifBlock));
|
|
2346
|
-
return "";
|
|
2347
|
-
}
|
|
2348
|
-
|
|
2349
|
-
// pure DOM
|
|
2350
|
-
if (!hasAssign && hasComp) {
|
|
2351
|
-
const tplId = ctx.ifIdCounter++;
|
|
2352
|
-
const condId = registerExpr(ctx, ifBlock.condition);
|
|
2353
|
-
const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
2354
|
-
const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
2355
|
-
let replaceAttr = "";
|
|
2356
|
-
const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
|
|
2357
|
-
if (firstComp) {
|
|
2358
|
-
const idAttr = firstComp.attrs.find(a => a.name === "id");
|
|
2359
|
-
const replAttr = firstComp.attrs.find(a => a.name === "replace");
|
|
2360
|
-
const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
|
|
2361
|
-
if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
|
|
2362
|
-
replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
|
|
2363
|
-
}
|
|
2364
|
-
}
|
|
2365
|
-
return (
|
|
2366
|
-
`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}>${bodyHTML}</template>` +
|
|
2367
|
-
(elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
|
|
2368
|
-
);
|
|
2369
|
-
}
|
|
2370
|
-
|
|
2371
|
-
// mixed
|
|
2372
|
-
const id = `__sm${ctx.mixedCounter++}__`;
|
|
2373
|
-
|
|
2374
|
-
const ifAssignJS = ifBlock.body
|
|
2375
|
-
.filter(c => c.kind === "assign_stmt")
|
|
2376
|
-
.map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
|
|
2377
|
-
.join("\n");
|
|
2378
|
-
|
|
2379
|
-
const ifHTML = ifBlock.body
|
|
2380
|
-
.filter(c => c.kind !== "assign_stmt")
|
|
2381
|
-
.map(c => renderChild(c, ctx, params, depth + 1))
|
|
2382
|
-
.join("");
|
|
2383
|
-
|
|
2384
|
-
const elseAssignJS = (ifBlock.elseBody ?? [])
|
|
2385
|
-
.filter(c => c.kind === "assign_stmt")
|
|
2386
|
-
.map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
|
|
2387
|
-
.join("\n");
|
|
2388
|
-
|
|
2389
|
-
const elseHTML = (ifBlock.elseBody ?? [])
|
|
2390
|
-
.filter(c => c.kind !== "assign_stmt")
|
|
2391
|
-
.map(c => renderChild(c, ctx, params, depth + 1))
|
|
2392
|
-
.join("");
|
|
2393
|
-
|
|
2394
|
-
let replaceId: string | undefined;
|
|
2395
|
-
const ifFirstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
|
|
2396
|
-
const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
|
|
2397
|
-
if (ifFirstComp) {
|
|
2398
|
-
const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
|
|
2399
|
-
const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
|
|
2400
|
-
const ifReplaceVal = ifReplace?.value;
|
|
2401
|
-
const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
|
|
2402
|
-
|
|
2403
|
-
if (ifId && ifId.kind === "str" && ifWantsReplace) {
|
|
2404
|
-
if (elseFirstComp) {
|
|
2405
|
-
const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
|
|
2406
|
-
const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
|
|
2407
|
-
const elseReplaceVal = elseReplace?.value;
|
|
2408
|
-
const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
|
|
2409
|
-
|
|
2410
|
-
if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
|
|
2411
|
-
replaceId = ifId.value;
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2414
|
-
}
|
|
2415
|
-
}
|
|
2416
|
-
|
|
2417
|
-
const condId = registerExpr(ctx, ifBlock.condition);
|
|
2418
|
-
ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
|
|
2419
|
-
|
|
2420
|
-
return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
|
|
2421
|
-
}
|
|
2422
|
-
|
|
2423
|
-
function renderCompUse(
|
|
2424
|
-
use: CompUse,
|
|
2425
|
-
ctx: CompileCtx,
|
|
2426
|
-
params: Map<string, string>,
|
|
2427
|
-
depth: number,
|
|
2428
|
-
): string {
|
|
2429
|
-
// transparent wrapper inserted by flattenIfToUses()
|
|
2430
|
-
if (use.name === "__IF_ROOT__") {
|
|
2431
|
-
return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
2432
|
-
}
|
|
2433
|
-
|
|
2434
|
-
// RawHTML
|
|
2435
|
-
if (use.name === "RawHTML") {
|
|
2436
|
-
const ca = use.attrs.find(a => a.name === "content");
|
|
2437
|
-
if (!ca || !ca.value) return "";
|
|
2438
|
-
return interpolateAttr(litToString(ca.value), params);
|
|
2439
|
-
}
|
|
2440
|
-
|
|
2441
|
-
// user-defined component
|
|
2442
|
-
const userDef = ctx.allDefs.get(use.name);
|
|
2443
|
-
if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
|
|
2444
|
-
|
|
2445
|
-
// custom element
|
|
2446
|
-
const customEl = ctx.customEls.get(use.name);
|
|
2447
|
-
if (customEl) {
|
|
2448
|
-
const attrParts = [`data-s="${ctx.scopeHash}"`];
|
|
2449
|
-
for (const attr of use.attrs) {
|
|
2450
|
-
const r = renderAttr(attr, params, ctx);
|
|
2451
|
-
if (r) attrParts.push(r);
|
|
2452
|
-
}
|
|
2453
|
-
const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
2454
|
-
return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
|
|
2455
|
-
}
|
|
2456
|
-
|
|
2457
|
-
// built-in component
|
|
2458
|
-
const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
|
|
2459
|
-
const isVoid = voidEl || VOID_TAGS.has(tag);
|
|
2460
|
-
|
|
2461
|
-
const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
|
|
2462
|
-
let userClass: string | undefined;
|
|
2463
|
-
const inlineStyleParts: string[] = [];
|
|
2464
|
-
|
|
2465
|
-
for (const attr of use.attrs) {
|
|
2466
|
-
if (attr.name === "level" && use.name === "Heading") continue;
|
|
2467
|
-
|
|
2468
|
-
if (INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
|
|
2469
|
-
const val = attr.value.kind === "str"
|
|
2470
|
-
? interpolateAttr(attr.value.value, params)
|
|
2471
|
-
: litToString(attr.value);
|
|
2472
|
-
inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
|
|
2473
|
-
continue;
|
|
2474
|
-
}
|
|
2475
|
-
|
|
2476
|
-
if (attr.name === "class") {
|
|
2477
|
-
if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
|
|
2478
|
-
continue;
|
|
2479
|
-
}
|
|
2480
|
-
const rendered = renderAttr(attr, params, ctx);
|
|
2481
|
-
if (rendered) attrParts.push(rendered);
|
|
2482
|
-
}
|
|
2483
|
-
|
|
2484
|
-
const classes = [defaultClass, userClass].filter(Boolean).join(" ");
|
|
2485
|
-
if (classes) attrParts.push(`class="${escAttr(classes)}"`);
|
|
2486
|
-
if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
|
|
2487
|
-
if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
|
|
2488
|
-
if (use.name === "Input") {
|
|
2489
|
-
const bindAttr = use.attrs.find(a => a.name === "bind");
|
|
2490
|
-
const modelAttr = use.attrs.find(a => a.name === "model");
|
|
2491
|
-
const bindOrModel = bindAttr || modelAttr;
|
|
2492
|
-
if (bindOrModel?.value?.kind === "str") {
|
|
2493
|
-
let vName = bindOrModel.value.value;
|
|
2494
|
-
if (vName.startsWith("__EXPR__")) {
|
|
2495
|
-
try {
|
|
2496
|
-
const expr: Expression = JSON.parse(vName.substring(8));
|
|
2497
|
-
if (expr.kind === "variable" && expr.name) vName = expr.name;
|
|
2498
|
-
} catch {}
|
|
2499
|
-
}
|
|
2500
|
-
if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="text"`);
|
|
2501
|
-
attrParts.push(`oninput="(function(e){ ${vName} = e.target.value; sinthRender(); })(event)"`);
|
|
2502
|
-
attrParts.push(`data-sinth-value="${escAttr(vName)}"`);
|
|
2503
|
-
}
|
|
2504
|
-
}
|
|
2505
|
-
if (use.name === "Checkbox") {
|
|
2506
|
-
if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
|
|
2507
|
-
const bindAttr = use.attrs.find(a => a.name === "bind");
|
|
2508
|
-
if (bindAttr?.value?.kind === "str") {
|
|
2509
|
-
let vName = bindAttr.value.value;
|
|
2510
|
-
if (vName.startsWith("__EXPR__")) {
|
|
2511
|
-
try {
|
|
2512
|
-
const expr: Expression = JSON.parse(vName.substring(8));
|
|
2513
|
-
if (expr.kind === "variable" && expr.name) vName = expr.name;
|
|
2514
|
-
} catch {}
|
|
2515
|
-
}
|
|
2516
|
-
attrParts.push(`onchange="(function(e){ ${vName} = e.target.checked; sinthRender(); })(event)"`);
|
|
2517
|
-
attrParts.push(`data-sinth-checked="${escAttr(vName)}"`);
|
|
2518
|
-
}
|
|
2519
|
-
}
|
|
2520
|
-
|
|
2521
|
-
const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
2522
|
-
|
|
2523
|
-
if (isVoid) {
|
|
2524
|
-
if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
|
|
2525
|
-
return `<${tag}${attrStr}>`;
|
|
2526
|
-
}
|
|
2527
|
-
|
|
2528
|
-
const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
2529
|
-
return `<${tag}${attrStr}>${inner}</${tag}>`;
|
|
2530
|
-
}
|
|
2531
|
-
|
|
2532
|
-
function expandUserComp(
|
|
2533
|
-
use: CompUse,
|
|
2534
|
-
def: CompDef,
|
|
2535
|
-
ctx: CompileCtx,
|
|
2536
|
-
params: Map<string, string>,
|
|
2537
|
-
depth: number,
|
|
2538
|
-
): string {
|
|
2539
|
-
if (use.name === def.name && depth > 1) {
|
|
2540
|
-
throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
|
|
2541
|
-
}
|
|
2542
|
-
|
|
2543
|
-
const local = new Map<string, string>();
|
|
2544
|
-
|
|
2545
|
-
for (const p of def.params) {
|
|
2546
|
-
if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
|
|
2547
|
-
}
|
|
2548
|
-
|
|
2549
|
-
for (const attr of use.attrs) {
|
|
2550
|
-
if (attr.value === null) {
|
|
2551
|
-
local.set(attr.name, "true");
|
|
2552
|
-
} else if (attr.value.kind !== "null") {
|
|
2553
|
-
const raw = litToString(attr.value);
|
|
2554
|
-
local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
|
|
2555
|
-
}
|
|
2556
|
-
}
|
|
2557
|
-
|
|
2558
|
-
for (const p of def.params) {
|
|
2559
|
-
if (!local.has(p.name)) {
|
|
2560
|
-
throw new SinthError(
|
|
2561
|
-
`Component '${def.name}' requires parameter '${p.name}' but it was not provided.`,
|
|
2562
|
-
use.loc,
|
|
2563
|
-
);
|
|
2564
|
-
}
|
|
2565
|
-
}
|
|
2566
|
-
|
|
2567
|
-
const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
2568
|
-
local.set("slot", slotHTML);
|
|
2569
|
-
|
|
2570
|
-
for (const block of def.styles) {
|
|
2571
|
-
ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
|
|
2572
|
-
}
|
|
2573
|
-
|
|
2574
|
-
return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
|
|
2575
|
-
}
|
|
2576
|
-
|
|
2577
|
-
// script collector
|
|
2578
|
-
|
|
2579
|
-
function collectScripts(
|
|
2580
|
-
file: SinthFile,
|
|
2581
|
-
allDefs: Map<string, CompDef>,
|
|
2582
|
-
): { componentScripts: string[]; pageScripts: { raw: string; attrs: Record<string, string> }[] } {
|
|
2583
|
-
const componentScripts: string[] = [];
|
|
2584
|
-
const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
|
|
2585
|
-
const seenFunctions = new Set<string>();
|
|
2586
|
-
|
|
2587
|
-
for (const [, def] of allDefs) {
|
|
2588
|
-
for (const block of def.scripts) {
|
|
2589
|
-
for (const fn of extractFunctionNames(block.raw)) {
|
|
2590
|
-
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
|
|
2591
|
-
seenFunctions.add(fn);
|
|
2592
|
-
}
|
|
2593
|
-
componentScripts.push(`(function(){\n${block.raw}\n})();`);
|
|
2594
|
-
}
|
|
2595
|
-
}
|
|
2596
|
-
|
|
2597
|
-
for (const block of file.scripts) {
|
|
2598
|
-
for (const fn of extractFunctionNames(block.raw)) {
|
|
2599
|
-
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
|
|
2600
|
-
seenFunctions.add(fn);
|
|
2601
|
-
}
|
|
2602
|
-
pageScripts.push({ raw: block.raw, attrs: block.attrs });
|
|
2603
|
-
}
|
|
2604
|
-
|
|
2605
|
-
return { componentScripts, pageScripts };
|
|
2606
|
-
}
|
|
2607
|
-
|
|
2608
|
-
function extractFunctionNames(js: string): string[] {
|
|
2609
|
-
const names: string[] = [];
|
|
2610
|
-
const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
|
|
2611
|
-
let m: RegExpExecArray | null;
|
|
2612
|
-
while ((m = re.exec(js)) !== null) names.push(m[1]);
|
|
2613
|
-
return names;
|
|
2614
|
-
}
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
// head gen
|
|
2618
|
-
|
|
2619
|
-
interface HeadData {
|
|
2620
|
-
title?: string; fav?: string;
|
|
2621
|
-
lang: string; charset: string; viewport: string;
|
|
2622
|
-
metaTags: { name: string; content: string }[];
|
|
2623
|
-
metaProps: { property: string; content: string }[];
|
|
2624
|
-
}
|
|
2625
|
-
|
|
2626
|
-
function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
2627
|
-
let title: string | undefined, fav: string | undefined;
|
|
2628
|
-
let lang = "en", charset = "UTF-8", viewport = "width=device-width, initial-scale=1.0";
|
|
2629
|
-
const metaTags: { name: string; content: string }[] = [];
|
|
2630
|
-
const metaProps: { property: string; content: string }[] = [];
|
|
2631
|
-
|
|
2632
|
-
for (const m of meta) {
|
|
2633
|
-
const val = litToString(m.value);
|
|
2634
|
-
switch (m.key) {
|
|
2635
|
-
case "title": title = val; break;
|
|
2636
|
-
case "fav": fav = val; break;
|
|
2637
|
-
case "lang": lang = val; break;
|
|
2638
|
-
case "charset": charset = val; break;
|
|
2639
|
-
case "viewport": viewport = val; break;
|
|
2640
|
-
case "descr": metaTags.push({ name: "description", content: val }); break;
|
|
2641
|
-
case "author": metaTags.push({ name: "author", content: val }); break;
|
|
2642
|
-
case "keywords": metaTags.push({ name: "keywords", content: val }); break;
|
|
2643
|
-
case "robots": metaTags.push({ name: "robots", content: val }); break;
|
|
2644
|
-
default:
|
|
2645
|
-
if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
|
|
2646
|
-
const prop = m.key
|
|
2647
|
-
.replace(/^og([A-Z])/, (_: string, c: string) => `og:${c.toLowerCase()}`)
|
|
2648
|
-
.replace(/^twitter([A-Z])/, (_: string, c: string) => `twitter:${c.toLowerCase()}`);
|
|
2649
|
-
metaProps.push({ property: prop, content: val });
|
|
2650
|
-
} else {
|
|
2651
|
-
metaTags.push({ name: camelToKebab(m.key), content: val });
|
|
2652
|
-
}
|
|
2653
|
-
}
|
|
2654
|
-
}
|
|
2655
|
-
|
|
2656
|
-
return { title, fav, lang, charset, viewport, metaTags, metaProps };
|
|
2657
|
-
}
|
|
2658
|
-
|
|
2659
|
-
function faviconType(p: string): string {
|
|
2660
|
-
switch (path.extname(p).toLowerCase()) {
|
|
2661
|
-
case ".ico": return "image/x-icon";
|
|
2662
|
-
case ".png": return "image/png";
|
|
2663
|
-
case ".svg": return "image/svg+xml";
|
|
2664
|
-
case ".gif": return "image/gif";
|
|
2665
|
-
case ".webp": return "image/webp";
|
|
2666
|
-
case ".jpg":
|
|
2667
|
-
case ".jpeg": return "image/jpeg";
|
|
2668
|
-
default:
|
|
2669
|
-
SinthWarning.emit(`Unknown favicon extension '${path.extname(p)}', defaulting to image/x-icon`);
|
|
2670
|
-
return "image/x-icon";
|
|
2671
|
-
}
|
|
2672
|
-
}
|
|
2673
|
-
|
|
2674
|
-
function renderHead(
|
|
2675
|
-
hd: HeadData,
|
|
2676
|
-
cssLinks: string[],
|
|
2677
|
-
jsLinks: { src: string; attrs: Record<string, string> }[],
|
|
2678
|
-
scopedCSS: string,
|
|
2679
|
-
companionJS: string | undefined,
|
|
2680
|
-
): string {
|
|
2681
|
-
const lines: string[] = [];
|
|
2682
|
-
lines.push(` <meta charset="${escAttr(hd.charset)}">`);
|
|
2683
|
-
lines.push(` <meta name="viewport" content="${escAttr(hd.viewport)}">`);
|
|
2684
|
-
if (hd.title) lines.push(` <title>${esc(hd.title)}</title>`);
|
|
2685
|
-
if (hd.fav) lines.push(` <link rel="icon" href="${escAttr(hd.fav)}" type="${faviconType(hd.fav)}">`);
|
|
2686
|
-
for (const m of hd.metaTags) lines.push(` <meta name="${escAttr(m.name)}" content="${escAttr(m.content)}">`);
|
|
2687
|
-
for (const m of hd.metaProps) lines.push(` <meta property="${escAttr(m.property)}" content="${escAttr(m.content)}">`);
|
|
2688
|
-
for (const css of cssLinks) lines.push(` <link rel="stylesheet" href="${escAttr(css)}">`);
|
|
2689
|
-
if (scopedCSS.trim()) lines.push(` <style>\n${scopedCSS}\n </style>`);
|
|
2690
|
-
for (const js of jsLinks) {
|
|
2691
|
-
const extra = Object.entries(js.attrs)
|
|
2692
|
-
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
2693
|
-
.join(" ");
|
|
2694
|
-
lines.push(` <script src="${escAttr(js.src)}"${extra ? " " + extra : ""}></script>`);
|
|
2695
|
-
}
|
|
2696
|
-
if (companionJS) lines.push(` <script src="${escAttr(companionJS)}"></script>`);
|
|
2697
|
-
return `<head>\n${lines.join("\n")}\n</head>`;
|
|
2698
|
-
}
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
// sinth runtime
|
|
2702
|
-
|
|
2703
|
-
function buildRuntime(opts: {
|
|
2704
|
-
varDecls: VarDeclaration[];
|
|
2705
|
-
bodyHTML: string;
|
|
2706
|
-
logicBlocks: string[];
|
|
2707
|
-
mixedBlocks: MixedBlockEntry[];
|
|
2708
|
-
assignedVars: Set<string>;
|
|
2709
|
-
exprRegistry: string[];
|
|
2710
|
-
sharedRuntime: boolean;
|
|
2711
|
-
}): string | { page: string; shared: string } {
|
|
2712
|
-
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
|
|
2713
|
-
|
|
2714
|
-
const needsExpr = bodyHTML.includes("sinth-expr");
|
|
2715
|
-
const needsIf = bodyHTML.includes("data-sinth-if");
|
|
2716
|
-
const needsFor = bodyHTML.includes("data-sinth-for");
|
|
2717
|
-
const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
|
|
2718
|
-
const needsMixed = mixedBlocks.length > 0;
|
|
2719
|
-
const needsLogic = logicBlocks.length > 0;
|
|
2720
|
-
const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
|
|
2721
|
-
|
|
2722
|
-
const varLines = varDecls.map(v => {
|
|
2723
|
-
if (!v.value) {
|
|
2724
|
-
if (!assignedVars.has(v.name)) {
|
|
2725
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
2726
|
-
SinthWarning.emit(
|
|
2727
|
-
`Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
|
|
2728
|
-
v.loc,
|
|
2729
|
-
);
|
|
2730
|
-
}
|
|
2731
|
-
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
2732
|
-
return `var ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
|
|
2733
|
-
}
|
|
2734
|
-
const val = litToString(v.value);
|
|
2735
|
-
if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
2736
|
-
if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
2737
|
-
if (v.varType === "obj") return `var ${v.name} = ${val};`;
|
|
2738
|
-
if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
|
|
2739
|
-
if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
|
|
2740
|
-
try {
|
|
2741
|
-
const arr = JSON.parse(val.slice(7));
|
|
2742
|
-
return `var ${v.name} = ${JSON.stringify(arr)};`;
|
|
2743
|
-
} catch { return `var ${v.name} = ${val.slice(7)};`; }
|
|
2744
|
-
}
|
|
2745
|
-
return `var ${v.name} = ${val};`;
|
|
2746
|
-
}).join("\n");
|
|
2747
|
-
|
|
2748
|
-
if (!needsRender && !needsDelay) {
|
|
2749
|
-
return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
|
|
2750
|
-
}
|
|
2751
|
-
|
|
2752
|
-
let helpers = "";
|
|
2753
|
-
|
|
2754
|
-
if (needsExpr || needsIf || needsFor) {
|
|
2755
|
-
helpers += `
|
|
2756
|
-
function sinthExpr(el) {
|
|
2757
|
-
try {
|
|
2758
|
-
var exprFn = __X[el.dataset.exprId];
|
|
2759
|
-
if (exprFn) el.textContent = exprFn({});
|
|
2760
|
-
} catch(e) {}
|
|
2761
|
-
}
|
|
2762
|
-
`;
|
|
2763
|
-
}
|
|
2764
|
-
|
|
2765
|
-
if (needsIf || needsMixed) {
|
|
2766
|
-
helpers += `
|
|
2767
|
-
function sinthReplaceInsert(t, anchor, ifId, replaceId) {
|
|
2768
|
-
if (anchor) {
|
|
2769
|
-
var cur = anchor.nextSibling;
|
|
2770
|
-
while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
|
|
2771
|
-
} else {
|
|
2772
|
-
anchor = document.createElement('span');
|
|
2773
|
-
anchor.style.display = 'none';
|
|
2774
|
-
anchor.dataset.sinthIfAnchor = ifId;
|
|
2775
|
-
t.parentNode.insertBefore(anchor, t);
|
|
2776
|
-
}
|
|
2777
|
-
var _rp = null, _rpParent = null, _rpNext = null;
|
|
2778
|
-
if (replaceId) {
|
|
2779
|
-
_rp = document.getElementById(replaceId);
|
|
2780
|
-
if (_rp) {
|
|
2781
|
-
_rpParent = _rp.parentNode;
|
|
2782
|
-
_rpNext = _rp.nextSibling;
|
|
2783
|
-
_rp.parentNode.removeChild(_rp);
|
|
2784
|
-
anchor._sinthReplaced = _rp;
|
|
2785
|
-
anchor._sinthReplacedParent = _rpParent;
|
|
2786
|
-
anchor._sinthReplacedNext = _rpNext;
|
|
2787
|
-
}
|
|
2788
|
-
}
|
|
2789
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
2790
|
-
frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
2791
|
-
if (${needsDelay}) {
|
|
2792
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
2793
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
2794
|
-
}
|
|
2795
|
-
var fragFirst = frag.firstChild;
|
|
2796
|
-
var fragLast = frag.lastChild;
|
|
2797
|
-
if (_rpParent && _rpNext) {
|
|
2798
|
-
_rpParent.insertBefore(frag, _rpNext);
|
|
2799
|
-
} else if (_rpParent) {
|
|
2800
|
-
_rpParent.appendChild(frag);
|
|
2801
|
-
} else {
|
|
2802
|
-
t.parentNode.insertBefore(frag, t);
|
|
2803
|
-
}
|
|
2804
|
-
if (replaceId && anchor) {
|
|
2805
|
-
anchor._sinthInsertedFirst = fragFirst;
|
|
2806
|
-
anchor._sinthInsertedLast = fragLast;
|
|
2807
|
-
}
|
|
2808
|
-
return anchor;
|
|
2809
|
-
}
|
|
2810
|
-
`;
|
|
2811
|
-
}
|
|
2812
|
-
|
|
2813
|
-
if (needsDelay) {
|
|
2814
|
-
helpers += `
|
|
2815
|
-
function sinthDelay(el) {
|
|
2816
|
-
if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
|
|
2817
|
-
el.dataset.sinthDelayDone = '1';
|
|
2818
|
-
var ms = parseInt(el.dataset.sinthDelay) || 0;
|
|
2819
|
-
el.style.display = 'none';
|
|
2820
|
-
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
2821
|
-
else el.style.display = '';
|
|
2822
|
-
}
|
|
2823
|
-
function sinthDelayExpr(el) {
|
|
2824
|
-
try {
|
|
2825
|
-
var fn = __X[el.dataset.sinthDelayExprId];
|
|
2826
|
-
var ms = fn ? parseInt(fn()) || 0 : 0;
|
|
2827
|
-
el.style.display = '';
|
|
2828
|
-
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
2829
|
-
} catch(e) {}
|
|
2830
|
-
}
|
|
2831
|
-
`;
|
|
2832
|
-
}
|
|
2833
|
-
|
|
2834
|
-
if (needsIf) {
|
|
2835
|
-
helpers += `
|
|
2836
|
-
function sinthIfBlock(t) {
|
|
2837
|
-
var ifId = t.dataset.sinthIfId;
|
|
2838
|
-
var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
|
|
2839
|
-
var condFn = __X[t.dataset.sinthIfExpr];
|
|
2840
|
-
var cond = condFn ? condFn() : false;
|
|
2841
|
-
if (cond) {
|
|
2842
|
-
anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
|
|
2843
|
-
} else {
|
|
2844
|
-
if (anchor) {
|
|
2845
|
-
if (anchor._sinthReplaced) {
|
|
2846
|
-
var insFirst = anchor._sinthInsertedFirst;
|
|
2847
|
-
var insLast = anchor._sinthInsertedLast;
|
|
2848
|
-
var rpParent = anchor._sinthReplacedParent;
|
|
2849
|
-
var rpNext = anchor._sinthReplacedNext;
|
|
2850
|
-
if (insFirst && insLast) {
|
|
2851
|
-
var cur = insFirst;
|
|
2852
|
-
while (cur && cur !== insLast) {
|
|
2853
|
-
var next = cur.nextSibling;
|
|
2854
|
-
cur.remove();
|
|
2855
|
-
cur = next;
|
|
2856
|
-
}
|
|
2857
|
-
if (insLast) insLast.remove();
|
|
2858
|
-
}
|
|
2859
|
-
if (rpParent && rpNext) {
|
|
2860
|
-
rpParent.insertBefore(anchor._sinthReplaced, rpNext);
|
|
2861
|
-
} else if (rpParent) {
|
|
2862
|
-
rpParent.appendChild(anchor._sinthReplaced);
|
|
2863
|
-
}
|
|
2864
|
-
} else {
|
|
2865
|
-
var cur2 = anchor.nextSibling;
|
|
2866
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
2867
|
-
}
|
|
2868
|
-
anchor.remove();
|
|
2869
|
-
}
|
|
2870
|
-
var elseT = t.nextElementSibling;
|
|
2871
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
2872
|
-
var elseIfId = elseT.dataset.sinthIfId;
|
|
2873
|
-
var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
|
|
2874
|
-
if (ea) {
|
|
2875
|
-
var cur3 = ea.nextSibling;
|
|
2876
|
-
while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
|
|
2877
|
-
} else {
|
|
2878
|
-
ea = document.createElement('span');
|
|
2879
|
-
ea.style.display = 'none';
|
|
2880
|
-
ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
|
|
2881
|
-
t.parentNode.insertBefore(ea, t);
|
|
2882
|
-
}
|
|
2883
|
-
var ef = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
2884
|
-
ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
2885
|
-
if (${needsDelay}) {
|
|
2886
|
-
ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
2887
|
-
ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
2888
|
-
}
|
|
2889
|
-
t.parentNode.insertBefore(ef, t);
|
|
2890
|
-
} else {
|
|
2891
|
-
var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
|
|
2892
|
-
if (ea2) {
|
|
2893
|
-
var ec = ea2.nextSibling;
|
|
2894
|
-
while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
|
|
2895
|
-
ea2.remove();
|
|
2896
|
-
}
|
|
2897
|
-
}
|
|
2898
|
-
}
|
|
2899
|
-
}
|
|
2900
|
-
`;
|
|
2901
|
-
}
|
|
2902
|
-
|
|
2903
|
-
if (needsFor) {
|
|
2904
|
-
helpers += `
|
|
2905
|
-
function hashString(str) {
|
|
2906
|
-
var hash = 0, i, chr;
|
|
2907
|
-
for (i = 0; i < str.length; i++) {
|
|
2908
|
-
chr = str.charCodeAt(i);
|
|
2909
|
-
hash = ((hash << 5) - hash) + chr;
|
|
2910
|
-
hash |= 0;
|
|
2911
|
-
}
|
|
2912
|
-
return String(hash);
|
|
2913
|
-
}
|
|
2914
|
-
function sinthForBlock(t) {
|
|
2915
|
-
var source = window[t.dataset.sinthFor];
|
|
2916
|
-
if (source === undefined) source = [];
|
|
2917
|
-
var newHash = '';
|
|
2918
|
-
try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
|
|
2919
|
-
if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
|
|
2920
|
-
return;
|
|
2921
|
-
}
|
|
2922
|
-
t.dataset.sinthForHash = newHash;
|
|
2923
|
-
var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
|
|
2924
|
-
var entries;
|
|
2925
|
-
if (isObj) {
|
|
2926
|
-
entries = Object.entries(source);
|
|
2927
|
-
} else {
|
|
2928
|
-
if (!Array.isArray(source)) source = [];
|
|
2929
|
-
entries = source.map(function(item, index) { return [index, item]; });
|
|
2930
|
-
}
|
|
2931
|
-
var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
|
|
2932
|
-
if (anchor) {
|
|
2933
|
-
var cur2 = anchor.nextSibling;
|
|
2934
|
-
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
2935
|
-
anchor.remove();
|
|
2936
|
-
}
|
|
2937
|
-
var fa = document.createElement('span');
|
|
2938
|
-
fa.style.display = 'none';
|
|
2939
|
-
fa.dataset.sinthForAnchor = t.dataset.sinthFor;
|
|
2940
|
-
t.parentNode && t.parentNode.insertBefore(fa, t);
|
|
2941
|
-
var _loopIdx = 0;
|
|
2942
|
-
entries.forEach(function(entry) {
|
|
2943
|
-
var _k = entry[0];
|
|
2944
|
-
var _v = entry[1];
|
|
2945
|
-
var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
|
|
2946
|
-
var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
|
|
2947
|
-
var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
|
|
2948
|
-
_loopIdx++;
|
|
2949
|
-
if (t.dataset.sinthIfReplace) {
|
|
2950
|
-
var _rp = document.getElementById(t.dataset.sinthIfReplace);
|
|
2951
|
-
if (_rp) _rp.parentNode.removeChild(_rp);
|
|
2952
|
-
}
|
|
2953
|
-
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
2954
|
-
frag.querySelectorAll('.sinth-expr').forEach(function(el) {
|
|
2955
|
-
try {
|
|
2956
|
-
var exprFn = __X[el.dataset.exprId];
|
|
2957
|
-
if (!exprFn) return;
|
|
2958
|
-
var _ctx = {};
|
|
2959
|
-
if (_item) _ctx[_item] = _v;
|
|
2960
|
-
if (_key) _ctx[_key] = _k;
|
|
2961
|
-
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
2962
|
-
el.textContent = exprFn(_ctx);
|
|
2963
|
-
el.classList.remove('sinth-expr');
|
|
2964
|
-
} catch(e) {}
|
|
2965
|
-
});
|
|
2966
|
-
frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
|
|
2967
|
-
var condFn = __X[ifT.dataset.sinthIfExpr];
|
|
2968
|
-
var _ctx = {};
|
|
2969
|
-
if (_item) _ctx[_item] = _v;
|
|
2970
|
-
if (_key) _ctx[_key] = _k;
|
|
2971
|
-
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
2972
|
-
var cond = false;
|
|
2973
|
-
try { if (condFn) cond = condFn(_ctx); } catch(e) {}
|
|
2974
|
-
if (cond) {
|
|
2975
|
-
var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
|
|
2976
|
-
ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
2977
|
-
try {
|
|
2978
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
2979
|
-
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
2980
|
-
} catch(e) {}
|
|
2981
|
-
});
|
|
2982
|
-
ifT.parentNode.insertBefore(ifContent, ifT);
|
|
2983
|
-
} else {
|
|
2984
|
-
var elseT = ifT.nextElementSibling;
|
|
2985
|
-
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
2986
|
-
var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
2987
|
-
elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
2988
|
-
try {
|
|
2989
|
-
var exprFn2 = __X[el2.dataset.exprId];
|
|
2990
|
-
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
2991
|
-
} catch(e) {}
|
|
2992
|
-
});
|
|
2993
|
-
ifT.parentNode.insertBefore(elseContent, ifT);
|
|
2994
|
-
}
|
|
2995
|
-
}
|
|
2996
|
-
});
|
|
2997
|
-
if (${needsDelay}) {
|
|
2998
|
-
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
2999
|
-
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
3000
|
-
}
|
|
3001
|
-
t.parentNode && t.parentNode.insertBefore(frag, t);
|
|
3002
|
-
});
|
|
3003
|
-
}
|
|
3004
|
-
`;
|
|
3005
|
-
}
|
|
3006
|
-
|
|
3007
|
-
if (needsMixed) {
|
|
3008
|
-
helpers += `
|
|
3009
|
-
function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
3010
|
-
var condFn = __X[condId];
|
|
3011
|
-
var cond = condFn ? condFn() : false;
|
|
3012
|
-
if (cond) {
|
|
3013
|
-
if (ifJS) eval(ifJS);
|
|
3014
|
-
el.innerHTML = ifHTML;
|
|
3015
|
-
} else {
|
|
3016
|
-
if (elseJS) eval(elseJS);
|
|
3017
|
-
el.innerHTML = elseHTML;
|
|
3018
|
-
}
|
|
3019
|
-
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
3020
|
-
el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
3021
|
-
if (${needsDelay}) {
|
|
3022
|
-
el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
3023
|
-
el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
3024
|
-
}
|
|
3025
|
-
}
|
|
3026
|
-
`;
|
|
3027
|
-
}
|
|
3028
|
-
|
|
3029
|
-
const exprArrayJS = exprRegistry.length > 0
|
|
3030
|
-
? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
3031
|
-
: "";
|
|
3032
|
-
|
|
3033
|
-
let renderBody = "";
|
|
3034
|
-
renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
|
|
3035
|
-
|
|
3036
|
-
if (needsLogic) {
|
|
3037
|
-
renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
|
|
3038
|
-
}
|
|
3039
|
-
|
|
3040
|
-
if (needsMixed) {
|
|
3041
|
-
for (const mb of mixedBlocks) {
|
|
3042
|
-
renderBody += ` (function() {
|
|
3043
|
-
var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
|
|
3044
|
-
if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
|
|
3045
|
-
})();\n`;
|
|
3046
|
-
}
|
|
3047
|
-
}
|
|
3048
|
-
|
|
3049
|
-
renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
|
|
3050
|
-
var target = document.getElementById(el.dataset.sinthRemove);
|
|
3051
|
-
if (target) target.remove();
|
|
3052
|
-
});\n`;
|
|
3053
|
-
|
|
3054
|
-
if (needsIf) {
|
|
3055
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
|
|
3056
|
-
}
|
|
3057
|
-
if (needsFor) {
|
|
3058
|
-
renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
|
|
3059
|
-
}
|
|
3060
|
-
renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
|
|
3061
|
-
try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
|
|
3062
|
-
});\n`;
|
|
3063
|
-
renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
|
|
3064
|
-
try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
|
|
3065
|
-
});\n`;
|
|
3066
|
-
if (needsExpr) {
|
|
3067
|
-
renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
|
|
3068
|
-
}
|
|
3069
|
-
if (needsDelay) {
|
|
3070
|
-
renderBody += ` setTimeout(function() {
|
|
3071
|
-
document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
3072
|
-
document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
3073
|
-
}, 0);\n`;
|
|
3074
|
-
}
|
|
3075
|
-
renderBody += ` window.scrollTo(_sx, _sy);\n`;
|
|
3076
|
-
|
|
3077
|
-
const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
|
|
3078
|
-
|
|
3079
|
-
const pageCode = `// Sinth page runtime
|
|
3080
|
-
${varLines}
|
|
3081
|
-
${exprArrayJS}
|
|
3082
|
-
${renderFunc}`;
|
|
3083
|
-
|
|
3084
|
-
if (opts.sharedRuntime && helpers.trim()) {
|
|
3085
|
-
const sharedCode = `// Sinth shared runtime
|
|
3086
|
-
${helpers}`;
|
|
3087
|
-
return { page: pageCode, shared: sharedCode };
|
|
3088
|
-
}
|
|
3089
|
-
|
|
3090
|
-
return `// Sinth compiled runtime
|
|
3091
|
-
${varLines}
|
|
3092
|
-
${helpers}
|
|
3093
|
-
${exprArrayJS}
|
|
3094
|
-
${renderFunc}`;
|
|
3095
|
-
}
|
|
3096
|
-
|
|
3097
|
-
// main compilation pipeline
|
|
3098
|
-
|
|
3099
|
-
interface CompileOptions {
|
|
3100
|
-
projectRoot: string;
|
|
3101
|
-
outDir: string;
|
|
3102
|
-
libraryPaths: string[];
|
|
3103
|
-
minify: boolean;
|
|
3104
|
-
checkOnly: boolean;
|
|
3105
|
-
sharedRuntime: boolean;
|
|
3106
|
-
}
|
|
3107
|
-
|
|
3108
|
-
function compileFile(filePath: string, opts: CompileOptions): { html: string; shared?: string } | null {
|
|
3109
|
-
const absPath = path.resolve(filePath);
|
|
3110
|
-
const file = parseFile(absPath);
|
|
3111
|
-
|
|
3112
|
-
const cfg: ResolverConfig = { projectRoot: opts.projectRoot, libraryPaths: opts.libraryPaths };
|
|
3113
|
-
const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
|
|
3114
|
-
const hash = fnv1a(absPath);
|
|
3115
|
-
|
|
3116
|
-
const allVarDecls: VarDeclaration[] = file.varDecls;
|
|
3117
|
-
|
|
3118
|
-
const ctx: CompileCtx = {
|
|
3119
|
-
allDefs, customEls, cssLinks, jsLinks,
|
|
3120
|
-
scopeHash: hash,
|
|
3121
|
-
pageFile: absPath,
|
|
3122
|
-
extraCSS: [],
|
|
3123
|
-
mixedBlocks: [],
|
|
3124
|
-
mixedCounter: 0,
|
|
3125
|
-
logicBlocks: [],
|
|
3126
|
-
ifIdCounter: 0,
|
|
3127
|
-
exprRegistry: [],
|
|
3128
|
-
exprMap: new Map(),
|
|
3129
|
-
};
|
|
3130
|
-
|
|
3131
|
-
if (!file.isPage) {
|
|
3132
|
-
const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
3133
|
-
const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
|
|
3134
|
-
const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
|
|
3135
|
-
return { html: `${body}\n<style>\n${allCSS}\n</style>` };
|
|
3136
|
-
}
|
|
3137
|
-
|
|
3138
|
-
const headData = buildHeadData(file.meta);
|
|
3139
|
-
const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
3140
|
-
const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
|
|
3141
|
-
const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
|
|
3142
|
-
const { componentScripts, pageScripts } = collectScripts(file, allDefs);
|
|
3143
|
-
|
|
3144
|
-
// collect all assigned variables for default-value warnings
|
|
3145
|
-
const assignedVars = new Set<string>();
|
|
3146
|
-
for (const s of file.scripts) {
|
|
3147
|
-
for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+\-]?=)/g)) assignedVars.add(m[1]);
|
|
3148
|
-
}
|
|
3149
|
-
for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
|
|
3150
|
-
|
|
3151
|
-
// companion JS file (needs same name as .sinth, adds support for JS libraries)
|
|
3152
|
-
const companionJS = (() => {
|
|
3153
|
-
const base = absPath.replace(/\.sinth$/, ".js");
|
|
3154
|
-
return fs.existsSync(base) ? path.basename(base) : undefined;
|
|
3155
|
-
})();
|
|
3156
|
-
|
|
3157
|
-
const relativeCssLinks = cssLinks.map(css => {
|
|
3158
|
-
const rel = path.relative(path.dirname(absPath), css).replace(/\\/g, "/");
|
|
3159
|
-
return rel.startsWith(".") ? rel : "./" + rel;
|
|
3160
|
-
});
|
|
3161
|
-
const relativeJsLinks = jsLinks.map(js => ({
|
|
3162
|
-
...js,
|
|
3163
|
-
src: (() => {
|
|
3164
|
-
const rel = path.relative(path.dirname(absPath), js.src).replace(/\\/g, "/");
|
|
3165
|
-
return rel.startsWith(".") ? rel : "./" + rel;
|
|
3166
|
-
})(),
|
|
3167
|
-
}));
|
|
3168
|
-
|
|
3169
|
-
const runtimeResult = buildRuntime({
|
|
3170
|
-
varDecls: allVarDecls,
|
|
3171
|
-
bodyHTML,
|
|
3172
|
-
logicBlocks: ctx.logicBlocks,
|
|
3173
|
-
mixedBlocks: ctx.mixedBlocks,
|
|
3174
|
-
assignedVars,
|
|
3175
|
-
exprRegistry: ctx.exprRegistry,
|
|
3176
|
-
sharedRuntime: opts.sharedRuntime,
|
|
3177
|
-
});
|
|
3178
|
-
const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
|
|
3179
|
-
const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
|
|
3180
|
-
|
|
3181
|
-
const sharedRuntimeTag = opts.sharedRuntime && sharedJS
|
|
3182
|
-
? `<script src="./sinth-runtime.js"></script>`
|
|
3183
|
-
: "";
|
|
3184
|
-
|
|
3185
|
-
const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
|
|
3186
|
-
const scriptTags: string[] = [];
|
|
3187
|
-
if (componentScripts.length > 0) {
|
|
3188
|
-
scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
|
|
3189
|
-
}
|
|
3190
|
-
|
|
3191
|
-
for (const s of pageScripts) {
|
|
3192
|
-
const extra = Object.entries(s.attrs)
|
|
3193
|
-
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
3194
|
-
.join(" ");
|
|
3195
|
-
const globalised = s.raw.replace(/\b(let|const)\b/g, "var");
|
|
3196
|
-
scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalised}\n</script>`);
|
|
3197
|
-
}
|
|
3198
|
-
|
|
3199
|
-
const html = [
|
|
3200
|
-
"<!DOCTYPE html>",
|
|
3201
|
-
`<html lang="${escAttr(headData.lang)}">`,
|
|
3202
|
-
head,
|
|
3203
|
-
`<body data-s="${hash}">`,
|
|
3204
|
-
bodyHTML,
|
|
3205
|
-
sharedRuntimeTag,
|
|
3206
|
-
runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
|
|
3207
|
-
scriptTags.join("\n"),
|
|
3208
|
-
"</body>",
|
|
3209
|
-
"</html>",
|
|
3210
|
-
].filter(Boolean).join("\n");
|
|
3211
|
-
|
|
3212
|
-
const finalHTML = opts.minify ? minifyHTML(html) : html;
|
|
3213
|
-
return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
|
|
3214
|
-
}
|
|
3215
|
-
|
|
3216
|
-
function minifyHTML(html: string): string {
|
|
3217
|
-
return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
|
|
3218
|
-
}
|
|
3219
|
-
|
|
3220
|
-
// file discovery & asset copy
|
|
3221
|
-
|
|
3222
|
-
function findSinthPages(dir: string, outDir?: string): string[] {
|
|
3223
|
-
const results: string[] = [];
|
|
3224
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
3225
|
-
if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
3226
|
-
const full = path.join(dir, entry.name);
|
|
3227
|
-
if (outDir && path.resolve(full) === path.resolve(outDir)) continue;
|
|
3228
|
-
if (entry.isDirectory()) results.push(...findSinthPages(full, outDir));
|
|
3229
|
-
else if (entry.name.endsWith(".sinth")) results.push(full);
|
|
3230
|
-
}
|
|
3231
|
-
return results;
|
|
3232
|
-
}
|
|
3233
|
-
|
|
3234
|
-
function copyDir(src: string, dest: string): void {
|
|
3235
|
-
if (!fs.existsSync(src)) return;
|
|
3236
|
-
fs.mkdirSync(dest, { recursive: true });
|
|
3237
|
-
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
|
3238
|
-
const sp = path.join(src, entry.name);
|
|
3239
|
-
const dp = path.join(dest, entry.name);
|
|
3240
|
-
if (entry.isDirectory()) copyDir(sp, dp);
|
|
3241
|
-
else fs.copyFileSync(sp, dp);
|
|
3242
|
-
}
|
|
3243
|
-
}
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
// dev server
|
|
3247
|
-
|
|
3248
|
-
const LIVE_RELOAD_SCRIPT = `<script>
|
|
3249
|
-
(function(){
|
|
3250
|
-
var es = new EventSource('/__sinth_sse__');
|
|
3251
|
-
es.onmessage = function() { location.reload(); };
|
|
3252
|
-
es.onerror = function() { setTimeout(function() { location.reload(); }, 1000); };
|
|
3253
|
-
})();
|
|
3254
|
-
</script>`;
|
|
3255
|
-
|
|
3256
|
-
async function startDevServer(opts: CompileOptions & { port: number; files?: string[] }): Promise<void> {
|
|
3257
|
-
const clients: http.ServerResponse[] = [];
|
|
3258
|
-
const cache = new Map<string, string>();
|
|
3259
|
-
|
|
3260
|
-
function notify(): void {
|
|
3261
|
-
for (const c of clients) { try { c.write("data: reload\n\n"); } catch {} }
|
|
3262
|
-
}
|
|
3263
|
-
|
|
3264
|
-
function compileAll(): void {
|
|
3265
|
-
cache.clear();
|
|
3266
|
-
const pages = (opts.files && opts.files.length > 0)
|
|
3267
|
-
? opts.files.filter(f => fs.existsSync(f))
|
|
3268
|
-
: findSinthPages(opts.projectRoot, opts.outDir);
|
|
3269
|
-
for (const p of pages) {
|
|
3270
|
-
try {
|
|
3271
|
-
const html = compileFile(p, { ...opts, checkOnly: false });
|
|
3272
|
-
if (!html) continue;
|
|
3273
|
-
const rel = path.relative(opts.projectRoot, p).replace(/\.sinth$/, ".html").replace(/\\/g, "/");
|
|
3274
|
-
const url = "/" + rel;
|
|
3275
|
-
cache.set(url, html + LIVE_RELOAD_SCRIPT);
|
|
3276
|
-
if (rel === "index.html" || rel.endsWith("/index.html")) {
|
|
3277
|
-
cache.set("/", html + LIVE_RELOAD_SCRIPT);
|
|
3278
|
-
}
|
|
3279
|
-
} catch (e: unknown) {
|
|
3280
|
-
process.stderr.write(`\x1b[31m${(e as Error).message}\x1b[0m\n`);
|
|
3281
|
-
}
|
|
3282
|
-
}
|
|
3283
|
-
}
|
|
3284
|
-
|
|
3285
|
-
compileAll();
|
|
3286
|
-
|
|
3287
|
-
const resolvedOut = path.resolve(opts.outDir);
|
|
3288
|
-
let watchReady = false;
|
|
3289
|
-
try {
|
|
3290
|
-
fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
|
|
3291
|
-
if (!filename) return;
|
|
3292
|
-
const abs = path.resolve(opts.projectRoot, filename);
|
|
3293
|
-
if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut) return;
|
|
3294
|
-
process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
|
|
3295
|
-
compileAll(); notify();
|
|
3296
|
-
});
|
|
3297
|
-
watchReady = true;
|
|
3298
|
-
} catch {}
|
|
3299
|
-
|
|
3300
|
-
if (!watchReady) {
|
|
3301
|
-
const mtimes = new Map<string, number>();
|
|
3302
|
-
const poller = setInterval(() => {
|
|
3303
|
-
const pages = (opts.files && opts.files.length > 0)
|
|
3304
|
-
? opts.files : findSinthPages(opts.projectRoot, opts.outDir);
|
|
3305
|
-
for (const p of pages) {
|
|
3306
|
-
try {
|
|
3307
|
-
const mtime = fs.statSync(p).mtimeMs;
|
|
3308
|
-
if (mtimes.get(p) !== mtime) {
|
|
3309
|
-
mtimes.set(p, mtime);
|
|
3310
|
-
process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${path.relative(opts.projectRoot, p)}\n`);
|
|
3311
|
-
compileAll(); notify(); break;
|
|
3312
|
-
}
|
|
3313
|
-
} catch {}
|
|
3314
|
-
}
|
|
3315
|
-
}, 500);
|
|
3316
|
-
process.on("exit", () => clearInterval(poller));
|
|
3317
|
-
}
|
|
3318
|
-
|
|
3319
|
-
const EXT_TYPES: Record<string, string> = {
|
|
3320
|
-
".css": "text/css", ".js": "application/javascript",
|
|
3321
|
-
".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon",
|
|
3322
|
-
".jpg": "image/jpeg", ".jpeg": "image/jpeg",
|
|
3323
|
-
".gif": "image/gif", ".webp": "image/webp",
|
|
3324
|
-
".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf",
|
|
3325
|
-
".json": "application/json", ".xml": "application/xml",
|
|
3326
|
-
};
|
|
3327
|
-
|
|
3328
|
-
const server = http.createServer((req, res) => {
|
|
3329
|
-
const reqUrl = (req.url ?? "/").split("?")[0];
|
|
3330
|
-
|
|
3331
|
-
if (reqUrl === "/__sinth_sse__") {
|
|
3332
|
-
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
|
|
3333
|
-
clients.push(res);
|
|
3334
|
-
req.on("close", () => { const i = clients.indexOf(res); if (i !== -1) clients.splice(i, 1); });
|
|
3335
|
-
return;
|
|
3336
|
-
}
|
|
3337
|
-
|
|
3338
|
-
const cached = cache.get(reqUrl) ??
|
|
3339
|
-
cache.get(reqUrl.endsWith("/") ? reqUrl + "index.html" : reqUrl + ".html");
|
|
3340
|
-
if (cached) { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(cached); return; }
|
|
3341
|
-
|
|
3342
|
-
let filePath = path.join(opts.projectRoot, reqUrl);
|
|
3343
|
-
if (reqUrl.endsWith("/")) filePath = path.join(filePath, "index.html");
|
|
3344
|
-
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
3345
|
-
const ctype = EXT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
|
|
3346
|
-
res.writeHead(200, { "Content-Type": ctype });
|
|
3347
|
-
res.end(fs.readFileSync(filePath));
|
|
3348
|
-
return;
|
|
3349
|
-
}
|
|
3350
|
-
|
|
3351
|
-
res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 Not Found");
|
|
3352
|
-
});
|
|
3353
|
-
|
|
3354
|
-
server.listen(opts.port, () => {
|
|
3355
|
-
process.stdout.write(
|
|
3356
|
-
`\x1b[32m[sinth dev]\x1b[0m Serving at \x1b[4mhttp://localhost:${opts.port}\x1b[0m\n`
|
|
3357
|
-
);
|
|
3358
|
-
});
|
|
3359
|
-
}
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
// cli entry point
|
|
3363
|
-
|
|
3364
|
-
function loadConfig(root: string): Record<string, unknown> {
|
|
3365
|
-
const cfgPath = path.join(root, "sinth.config.json");
|
|
3366
|
-
if (fs.existsSync(cfgPath)) {
|
|
3367
|
-
try { return JSON.parse(fs.readFileSync(cfgPath, "utf-8")) as Record<string, unknown>; }
|
|
3368
|
-
catch { SinthWarning.emit("Could not parse sinth.config.json"); }
|
|
3369
|
-
}
|
|
3370
|
-
return {};
|
|
3371
|
-
}
|
|
3372
|
-
|
|
3373
|
-
async function main(): Promise<void> {
|
|
3374
|
-
const [,, command, ...args] = process.argv;
|
|
3375
|
-
const cwd = process.cwd();
|
|
3376
|
-
const cfg = loadConfig(cwd);
|
|
3377
|
-
|
|
3378
|
-
const outDirIdx = args.indexOf("--out");
|
|
3379
|
-
const outDir = outDirIdx !== -1 ? args[outDirIdx + 1] : (cfg.outDir as string | undefined) ?? path.join(cwd, "dist");
|
|
3380
|
-
const portIdx = args.indexOf("--port");
|
|
3381
|
-
const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : (cfg.port as number | undefined) ?? 3000;
|
|
3382
|
-
const minify = args.includes("--prod") || Boolean(cfg.minify);
|
|
3383
|
-
const sharedRuntime = args.includes("--shared-runtime") || Boolean(cfg.sharedRuntime);
|
|
3384
|
-
const libraryPaths = (cfg.libraryPaths as string[] | undefined) ?? [path.join(cwd, "libraries")];
|
|
3385
|
-
|
|
3386
|
-
const flagValues = new Set<string>();
|
|
3387
|
-
if (outDirIdx !== -1) flagValues.add(args[outDirIdx + 1]);
|
|
3388
|
-
if (portIdx !== -1) flagValues.add(args[portIdx + 1]);
|
|
3389
|
-
const cleanArgs = args.filter(a => !a.startsWith("--") && !flagValues.has(a));
|
|
3390
|
-
|
|
3391
|
-
const opts: CompileOptions = { projectRoot: cwd, outDir, libraryPaths, minify, checkOnly: false, sharedRuntime };
|
|
3392
|
-
|
|
3393
|
-
switch (command) {
|
|
3394
|
-
case "build": {
|
|
3395
|
-
const nonSinth = cleanArgs.filter(a => !a.endsWith(".sinth"));
|
|
3396
|
-
if (nonSinth.length > 0) process.stdout.write(`\x1b[33mSkipping non-.sinth files:\x1b[0m ${nonSinth.join(", ")}\n`);
|
|
3397
|
-
|
|
3398
|
-
const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
|
|
3399
|
-
const pages = fileArgs.length > 0
|
|
3400
|
-
? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
|
|
3401
|
-
: findSinthPages(cwd, outDir);
|
|
3402
|
-
|
|
3403
|
-
if (pages.length === 0) { process.stdout.write("No .sinth files found.\n"); process.exit(0); }
|
|
3404
|
-
|
|
3405
|
-
let hadError = false, built = 0;
|
|
3406
|
-
|
|
3407
|
-
const sharedRuntimes: string[] = [];
|
|
3408
|
-
for (const p of pages) {
|
|
3409
|
-
try {
|
|
3410
|
-
const result = compileFile(p, opts);
|
|
3411
|
-
if (!result) continue;
|
|
3412
|
-
const html = result.html;
|
|
3413
|
-
if (result.shared) {
|
|
3414
|
-
sharedRuntimes.push(result.shared);
|
|
3415
|
-
}
|
|
3416
|
-
const rel = path.relative(cwd, p).replace(/\.sinth$/, ".html");
|
|
3417
|
-
const out = path.join(outDir, rel);
|
|
3418
|
-
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
3419
|
-
fs.writeFileSync(out, html);
|
|
3420
|
-
process.stdout.write(` \x1b[32m✓\x1b[0m ${rel}\n`);
|
|
3421
|
-
built++;
|
|
3422
|
-
} catch (e: unknown) {
|
|
3423
|
-
process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${(e as Error).message}\n`);
|
|
3424
|
-
hadError = true;
|
|
3425
|
-
}
|
|
3426
|
-
}
|
|
3427
|
-
|
|
3428
|
-
if (sharedRuntimes.length > 0) {
|
|
3429
|
-
const combined = sharedRuntimes.join("\n");
|
|
3430
|
-
fs.writeFileSync(path.join(outDir, "sinth-runtime.js"), combined);
|
|
3431
|
-
process.stdout.write(` \x1b[32m✓\x1b[0m sinth-runtime.js (shared)\n`);
|
|
3432
|
-
}
|
|
3433
|
-
|
|
3434
|
-
// copies to output
|
|
3435
|
-
const assetsIn = path.join(cwd, "assets"), assetsOut = path.join(outDir, "assets");
|
|
3436
|
-
if (fs.existsSync(assetsIn)) {
|
|
3437
|
-
copyDir(assetsIn, assetsOut);
|
|
3438
|
-
process.stdout.write(` \x1b[32m✓\x1b[0m assets/ → ${path.relative(cwd, assetsOut)}/\n`);
|
|
3439
|
-
}
|
|
3440
|
-
|
|
3441
|
-
const libIn = path.join(cwd, "libraries"), libOut = path.join(outDir, "libraries");
|
|
3442
|
-
if (fs.existsSync(libIn)) {
|
|
3443
|
-
copyDir(libIn, libOut);
|
|
3444
|
-
const libFiles = fs.readdirSync(libOut, { recursive: true }) as string[];
|
|
3445
|
-
for (const f of libFiles) {
|
|
3446
|
-
if (f.endsWith(".sinth") || f.endsWith(".html")) {
|
|
3447
|
-
try { fs.unlinkSync(path.join(libOut, f)); } catch {}
|
|
3448
|
-
}
|
|
3449
|
-
}
|
|
3450
|
-
process.stdout.write(` \x1b[32m✓\x1b[0m libraries/ → ${path.relative(cwd, libOut)}/\n`);
|
|
3451
|
-
}
|
|
3452
|
-
|
|
3453
|
-
process.stdout.write(`\n\x1b[1mBuilt ${built} page(s)\x1b[0m${hadError ? " with errors" : ""}\n`);
|
|
3454
|
-
process.exit(hadError ? 1 : 0);
|
|
3455
|
-
break;
|
|
3456
|
-
}
|
|
3457
|
-
|
|
3458
|
-
case "dev": {
|
|
3459
|
-
const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
|
|
3460
|
-
const files = fileArgs.length > 0
|
|
3461
|
-
? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
|
|
3462
|
-
: undefined;
|
|
3463
|
-
await startDevServer({ ...opts, port, files });
|
|
3464
|
-
break;
|
|
3465
|
-
}
|
|
3466
|
-
|
|
3467
|
-
case "check": {
|
|
3468
|
-
opts.checkOnly = true;
|
|
3469
|
-
const pages = findSinthPages(cwd, outDir);
|
|
3470
|
-
let hadError = false;
|
|
3471
|
-
for (const p of pages) {
|
|
3472
|
-
try {
|
|
3473
|
-
compileFile(p, opts);
|
|
3474
|
-
process.stdout.write(` \x1b[32m✓\x1b[0m ${path.relative(cwd, p)}\n`);
|
|
3475
|
-
} catch (e: unknown) {
|
|
3476
|
-
process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${(e as Error).message}\n`);
|
|
3477
|
-
hadError = true;
|
|
3478
|
-
}
|
|
3479
|
-
}
|
|
3480
|
-
process.exit(hadError ? 1 : 0);
|
|
3481
|
-
break;
|
|
3482
|
-
}
|
|
3483
|
-
|
|
3484
|
-
case "version":
|
|
3485
|
-
case "--version":
|
|
3486
|
-
case "-v": {
|
|
3487
|
-
const pkgPath = path.join(__dirname, "..", "package.json");
|
|
3488
|
-
if (fs.existsSync(pkgPath)) {
|
|
3489
|
-
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
3490
|
-
process.stdout.write(`Sinth Compiler v${pkg.version}\n`);
|
|
3491
|
-
} else {
|
|
3492
|
-
process.stdout.write("Sinth Compiler v1.0.0\n");
|
|
3493
|
-
}
|
|
3494
|
-
break;
|
|
3495
|
-
}
|
|
3496
|
-
|
|
3497
|
-
case "init": {
|
|
3498
|
-
const projectName = cleanArgs[0] || "my-sinth-project";
|
|
3499
|
-
scaffoldProject(path.resolve(cwd, projectName));
|
|
3500
|
-
break;
|
|
3501
|
-
}
|
|
3502
|
-
|
|
3503
|
-
default: {
|
|
3504
|
-
let version = "1.0.0";
|
|
3505
|
-
const paths = [
|
|
3506
|
-
path.resolve(__dirname, "..", "package.json"),
|
|
3507
|
-
path.resolve(__dirname, "package.json"),
|
|
3508
|
-
path.resolve(process.cwd(), "package.json"),
|
|
3509
|
-
path.resolve(process.cwd(), "..", "package.json"),
|
|
3510
|
-
];
|
|
3511
|
-
for (const p of paths) {
|
|
3512
|
-
if (fs.existsSync(p)) {
|
|
3513
|
-
try {
|
|
3514
|
-
const pkg = JSON.parse(fs.readFileSync(p, "utf-8"));
|
|
3515
|
-
version = pkg.version;
|
|
3516
|
-
break;
|
|
3517
|
-
} catch {}
|
|
3518
|
-
}
|
|
3519
|
-
}
|
|
3520
|
-
process.stdout.write(`
|
|
3521
|
-
\x1b[1mSinth Compiler v${version}\x1b[0m
|
|
3522
|
-
|
|
3523
|
-
\x1b[1mCommands:\x1b[0m
|
|
3524
|
-
sinth build [files] [--out ./dist] [--prod] Compile .sinth pages
|
|
3525
|
-
sinth dev [files] [--port 3000] Live-reload dev server
|
|
3526
|
-
sinth check Lint without emitting
|
|
3527
|
-
sinth init [name] Scaffold a new project
|
|
3528
|
-
sinth version Print version
|
|
3529
|
-
`);
|
|
3530
|
-
break;
|
|
3531
|
-
}
|
|
3532
|
-
}
|
|
3533
|
-
}
|
|
3534
|
-
|
|
3535
|
-
// project scaffholding
|
|
3536
|
-
|
|
3537
|
-
function scaffoldProject(root: string): void {
|
|
3538
|
-
for (const d of ["pages", "components", "styles", "libraries", "assets"]) {
|
|
3539
|
-
fs.mkdirSync(path.join(root, d), { recursive: true });
|
|
3540
|
-
}
|
|
3541
|
-
|
|
3542
|
-
fs.writeFileSync(path.join(root, "pages", "index.sinth"), `-- My Sinth Site
|
|
3543
|
-
page
|
|
3544
|
-
|
|
3545
|
-
import "../components/Navbar.sinth"
|
|
3546
|
-
import css "../styles/reset.css"
|
|
3547
|
-
|
|
3548
|
-
title = "My Site"
|
|
3549
|
-
fav = "assets/favicon.ico"
|
|
3550
|
-
descr = "Built with Sinth v1.0.0."
|
|
3551
|
-
|
|
3552
|
-
var int score = 0
|
|
3553
|
-
var str message = "Click to begin"
|
|
3554
|
-
|
|
3555
|
-
Navbar
|
|
3556
|
-
|
|
3557
|
-
Hero {
|
|
3558
|
-
Heading(level: 1) { "Welcome to Sinth" }
|
|
3559
|
-
Paragraph { "A declarative, component-based web UI language." }
|
|
3560
|
-
Button(onClick: "handleClick") { "Get Started" }
|
|
3561
|
-
Paragraph(id: "score-display") { message }
|
|
3562
|
-
}
|
|
3563
|
-
|
|
3564
|
-
Main {
|
|
3565
|
-
Section {
|
|
3566
|
-
Heading(level: 2) { "Features" }
|
|
3567
|
-
CardGrid {
|
|
3568
|
-
-- Add Card components here
|
|
3569
|
-
}
|
|
3570
|
-
}
|
|
3571
|
-
}
|
|
3572
|
-
|
|
3573
|
-
style {
|
|
3574
|
-
section.hero {
|
|
3575
|
-
padding: "4rem 2rem"
|
|
3576
|
-
textAlign: "center"
|
|
3577
|
-
backgroundColor: "#f0f4ff"
|
|
3578
|
-
}
|
|
3579
|
-
main {
|
|
3580
|
-
maxWidth: "1100px"
|
|
3581
|
-
margin: "0 auto"
|
|
3582
|
-
padding: "2rem"
|
|
3583
|
-
}
|
|
3584
|
-
}
|
|
3585
|
-
|
|
3586
|
-
script {
|
|
3587
|
-
function handleClick() {
|
|
3588
|
-
score += 1
|
|
3589
|
-
message = "Score: " + score
|
|
3590
|
-
sinthRender()
|
|
3591
|
-
}
|
|
3592
|
-
}
|
|
3593
|
-
`);
|
|
3594
|
-
|
|
3595
|
-
fs.writeFileSync(path.join(root, "components", "Navbar.sinth"), `-- Navbar component
|
|
3596
|
-
|
|
3597
|
-
component Navbar {
|
|
3598
|
-
Header {
|
|
3599
|
-
Nav {
|
|
3600
|
-
Link(href: "/", class: "logo") { "MySite" }
|
|
3601
|
-
Div(class: "nav-links") {
|
|
3602
|
-
NavLink(href: "/") { "Home" }
|
|
3603
|
-
NavLink(href: "/about") { "About" }
|
|
3604
|
-
}
|
|
3605
|
-
}
|
|
3606
|
-
}
|
|
3607
|
-
|
|
3608
|
-
style {
|
|
3609
|
-
header {
|
|
3610
|
-
display: "flex"
|
|
3611
|
-
alignItems: "center"
|
|
3612
|
-
padding: "1rem 2rem"
|
|
3613
|
-
backgroundColor: "#1a1a2e"
|
|
3614
|
-
color: "white"
|
|
3615
|
-
}
|
|
3616
|
-
.logo {
|
|
3617
|
-
fontSize: "1.5rem"
|
|
3618
|
-
fontWeight: "700"
|
|
3619
|
-
color: "white"
|
|
3620
|
-
textDecoration: "none"
|
|
3621
|
-
}
|
|
3622
|
-
.nav-links {
|
|
3623
|
-
marginLeft: "auto"
|
|
3624
|
-
display: "flex"
|
|
3625
|
-
gap: "1.5rem"
|
|
3626
|
-
}
|
|
3627
|
-
.nav-links a {
|
|
3628
|
-
color: "rgba(255,255,255,0.8)"
|
|
3629
|
-
textDecoration: "none"
|
|
3630
|
-
}
|
|
3631
|
-
}
|
|
3632
|
-
}
|
|
3633
|
-
`);
|
|
3634
|
-
|
|
3635
|
-
fs.writeFileSync(path.join(root, "components", "Card.sinth"), `-- Card component
|
|
3636
|
-
|
|
3637
|
-
component Card(title, color = "blue") {
|
|
3638
|
-
Div(class: "card") {
|
|
3639
|
-
Heading(level: 3) { "$title" }
|
|
3640
|
-
Div(class: "card-body") { "$slot" }
|
|
3641
|
-
}
|
|
3642
|
-
|
|
3643
|
-
style {
|
|
3644
|
-
.card {
|
|
3645
|
-
backgroundColor: "#f7f7f7"
|
|
3646
|
-
borderRadius: "1rem"
|
|
3647
|
-
padding: "1.5rem"
|
|
3648
|
-
marginBottom: "1rem"
|
|
3649
|
-
}
|
|
3650
|
-
.card:hover {
|
|
3651
|
-
boxShadow: "0 4px 16px rgba(0,0,0,0.1)"
|
|
3652
|
-
}
|
|
3653
|
-
.card-body {
|
|
3654
|
-
marginTop: "0.75rem"
|
|
3655
|
-
}
|
|
3656
|
-
}
|
|
3657
|
-
}
|
|
3658
|
-
`);
|
|
3659
|
-
|
|
3660
|
-
fs.writeFileSync(path.join(root, "styles", "reset.css"),
|
|
3661
|
-
`*, *::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`
|
|
3662
|
-
);
|
|
3663
|
-
|
|
3664
|
-
fs.writeFileSync(path.join(root, "sinth.config.json"),
|
|
3665
|
-
JSON.stringify({ outDir: "./dist", libraryPaths: ["./libraries"], minify: false }, null, 2)
|
|
3666
|
-
);
|
|
3667
|
-
|
|
3668
|
-
fs.writeFileSync(path.join(root, ".gitignore"), "dist/\nnode_modules/\n");
|
|
3669
|
-
|
|
3670
|
-
fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({
|
|
3671
|
-
name: path.basename(root).toLowerCase().replace(/\s+/g, "-"),
|
|
3672
|
-
version: "1.0.0",
|
|
3673
|
-
scripts: { build: "sinth build", dev: "sinth dev" },
|
|
3674
|
-
devDependencies: { "ts-node": "^10.0.0", typescript: "^5.0.0", sass: "^1.70.0" },
|
|
3675
|
-
}, null, 2));
|
|
3676
|
-
|
|
3677
|
-
process.stdout.write(`
|
|
3678
|
-
\x1b[32m✓ Sinth project scaffolded at ${path.basename(root)}/\x1b[0m
|
|
3679
|
-
|
|
3680
|
-
\x1b[1mNext steps:\x1b[0m
|
|
3681
|
-
cd ${path.basename(root)}
|
|
3682
|
-
sinth dev
|
|
3683
|
-
sinth build
|
|
3684
|
-
`);
|
|
3685
|
-
}
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
main().catch(e => {
|
|
3691
|
-
process.stderr.write(`\x1b[31m${(e as Error).message}\x1b[0m\n`);
|
|
3692
|
-
process.exit(1);
|
|
3693
|
-
});
|