@yannosay/sinth 0.0.4
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/LICENSE +660 -0
- package/README.md +30 -0
- package/bin/sinth.js +5 -0
- package/components/Card.sinth +21 -0
- package/components/Navbar.sinth +38 -0
- package/package.json +13 -0
- package/pages/index.sinth +46 -0
- package/sinth.config.json +7 -0
- package/src/sinth.ts +2046 -0
- package/styles/reset.css +3 -0
- package/test-project/components/Card.sinth +21 -0
- package/test-project/components/Navbar.sinth +38 -0
- package/test-project/package.json +13 -0
- package/test-project/pages/index.sinth +46 -0
- package/test-project/sinth.config.json +7 -0
- package/test-project/styles/reset.css +3 -0
- package/tsconfig.json +23 -0
package/src/sinth.ts
ADDED
|
@@ -0,0 +1,2046 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Sinth Compiler v0.0.4 — enum fix, raw-block detection, import resolution, CSS conversion, slot escaping, custom-elements, HTML5 map
|
|
3
|
+
|
|
4
|
+
import * as fs from "fs";
|
|
5
|
+
import * as path from "path";
|
|
6
|
+
import * as http from "http";
|
|
7
|
+
|
|
8
|
+
// ═══════════════════════════════════════════════════════════
|
|
9
|
+
// SECTION 1: TYPES & AST DEFINITIONS
|
|
10
|
+
// ═══════════════════════════════════════════════════════════
|
|
11
|
+
|
|
12
|
+
interface Loc { file: string; line: number; col: number }
|
|
13
|
+
|
|
14
|
+
// === v0.0.4: Must be plain `enum TT`, NOT `const enum TT` — const enum breaks TT[t] string indexing ===
|
|
15
|
+
enum TT {
|
|
16
|
+
LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT,
|
|
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
|
+
// === v0.0.4: KW_CUSTOM_EL and KW_CUSTOM ensured present ===
|
|
24
|
+
KW_CUSTOM_EL,
|
|
25
|
+
KW_CUSTOM,
|
|
26
|
+
EOF,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface Token { type: TT; value: string; loc: Loc }
|
|
30
|
+
|
|
31
|
+
type LitStr = { kind: "str"; value: string };
|
|
32
|
+
type LitNum = { kind: "num"; value: number };
|
|
33
|
+
type LitBool = { kind: "bool"; value: boolean };
|
|
34
|
+
type LitNull = { kind: "null" };
|
|
35
|
+
type Literal = LitStr | LitNum | LitBool | LitNull;
|
|
36
|
+
|
|
37
|
+
interface Attr { name: string; value: Literal | null; loc: Loc }
|
|
38
|
+
interface TextNode { kind: "text"; value: string; loc: Loc }
|
|
39
|
+
interface CompUse { kind: "use"; name: string; attrs: Attr[]; children: Child[]; loc: Loc }
|
|
40
|
+
type Child = TextNode | CompUse;
|
|
41
|
+
|
|
42
|
+
interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
|
|
43
|
+
interface StyleBlock { global: boolean; lang: "css" | "scss"; raw: string; extraAttrs: Record<string, string>; loc: Loc }
|
|
44
|
+
interface ScriptBlock { raw: string; attrs: Record<string, string>; loc: Loc }
|
|
45
|
+
interface CompDef { name: string; params: ParamDecl[]; body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[]; loc: Loc }
|
|
46
|
+
|
|
47
|
+
interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
|
|
48
|
+
interface CustomElInfo { tagName: string; params: ParamDecl[] }
|
|
49
|
+
|
|
50
|
+
type ImportNode =
|
|
51
|
+
| { kind: "sinth"; path: string; loc: Loc }
|
|
52
|
+
| { kind: "css"; path: string; loc: Loc }
|
|
53
|
+
| { kind: "js"; name: string; alias?: string; loc: Loc };
|
|
54
|
+
|
|
55
|
+
interface MetaEntry { key: string; value: Literal; loc: Loc }
|
|
56
|
+
|
|
57
|
+
interface SinthFile {
|
|
58
|
+
filePath: string;
|
|
59
|
+
isPage: boolean;
|
|
60
|
+
imports: ImportNode[];
|
|
61
|
+
meta: MetaEntry[];
|
|
62
|
+
defs: CompDef[];
|
|
63
|
+
uses: CompUse[];
|
|
64
|
+
styles: StyleBlock[];
|
|
65
|
+
scripts: ScriptBlock[];
|
|
66
|
+
customEls: CustomElDecl[];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface CompileCtx {
|
|
70
|
+
allDefs: Map<string, CompDef>;
|
|
71
|
+
customEls: Map<string, CustomElInfo>;
|
|
72
|
+
cssLinks: string[];
|
|
73
|
+
jsLinks: { src: string; attrs: Record<string, string> }[];
|
|
74
|
+
scopeHash: string;
|
|
75
|
+
pageFile: string;
|
|
76
|
+
extraCSS: string[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ═══════════════════════════════════════════════════════════
|
|
80
|
+
// SECTION 2: UTILITIES
|
|
81
|
+
// ═══════════════════════════════════════════════════════════
|
|
82
|
+
|
|
83
|
+
class SinthError extends Error {
|
|
84
|
+
constructor(
|
|
85
|
+
public readonly rawMsg: string,
|
|
86
|
+
public readonly loc?: Loc,
|
|
87
|
+
public readonly sourceLine?: string,
|
|
88
|
+
) {
|
|
89
|
+
super(SinthError.buildMessage(rawMsg, loc, sourceLine));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
static buildMessage(msg: string, loc?: Loc, sourceLine?: string): string {
|
|
93
|
+
let s = `Error: ${msg}`;
|
|
94
|
+
if (loc) {
|
|
95
|
+
s += `\n at: ${loc.file} (line ${loc.line}, col ${loc.col})`;
|
|
96
|
+
if (sourceLine !== undefined) {
|
|
97
|
+
const lineNum = String(loc.line).padStart(4);
|
|
98
|
+
const pointer = " ".repeat(Math.max(0, loc.col - 1)) + "^";
|
|
99
|
+
s += `\n${lineNum} | ${sourceLine}\n | ${pointer}`;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return s;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// === v0.0.4: Attach source line to produce error preview ===
|
|
106
|
+
withSource(lines: string[]): SinthError {
|
|
107
|
+
if (!this.loc || this.sourceLine !== undefined) return this;
|
|
108
|
+
const line = lines[this.loc.line - 1] ?? "";
|
|
109
|
+
return new SinthError(this.rawMsg, this.loc, line);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
class SinthWarning {
|
|
114
|
+
static emit(msg: string, loc?: Loc): void {
|
|
115
|
+
const where = loc ? `\n at: ${loc.file}:${loc.line}` : "";
|
|
116
|
+
process.stderr.write(`\x1b[33mWarning:\x1b[0m ${msg}${where}\n`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** FNV-1a 32-bit hash → deterministic 8-char hex scope id */
|
|
121
|
+
function fnv1a(s: string): string {
|
|
122
|
+
let h = 0x811c9dc5;
|
|
123
|
+
for (let i = 0; i < s.length; i++) {
|
|
124
|
+
h ^= s.charCodeAt(i);
|
|
125
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
126
|
+
}
|
|
127
|
+
return h.toString(16).padStart(8, "0").slice(0, 8);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** camelCase → kebab-case with vendor prefix support */
|
|
131
|
+
function camelToKebab(s: string): string {
|
|
132
|
+
const vp = s.match(/^(Webkit|Moz|Ms)(.+)$/);
|
|
133
|
+
if (vp) return `-${vp[1].toLowerCase()}-${camelToKebab(vp[2])}`;
|
|
134
|
+
return s.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** "w-counter" → "WCounter" */
|
|
138
|
+
function tagNameToPascal(tag: string): string {
|
|
139
|
+
return tag.split("-").map(p => p.charAt(0).toUpperCase() + p.slice(1)).join("");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function esc(s: string): string {
|
|
143
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function escAttr(s: string): string {
|
|
147
|
+
return esc(s).replace(/"/g, """);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function litToString(lit: Literal): string {
|
|
151
|
+
switch (lit.kind) {
|
|
152
|
+
case "str": return lit.value;
|
|
153
|
+
case "num": return String(lit.value);
|
|
154
|
+
case "bool": return String(lit.value);
|
|
155
|
+
case "null": return "";
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ═══════════════════════════════════════════════════════════
|
|
160
|
+
// SECTION 3: LEXER
|
|
161
|
+
// ═══════════════════════════════════════════════════════════
|
|
162
|
+
|
|
163
|
+
const KEYWORDS: Record<string, TT> = {
|
|
164
|
+
"import": TT.KW_IMPORT,
|
|
165
|
+
"as": TT.KW_AS,
|
|
166
|
+
"css": TT.KW_CSS,
|
|
167
|
+
"component": TT.KW_COMPONENT,
|
|
168
|
+
"style": TT.KW_STYLE,
|
|
169
|
+
"script": TT.KW_SCRIPT,
|
|
170
|
+
"global": TT.KW_GLOBAL,
|
|
171
|
+
"page": TT.KW_PAGE,
|
|
172
|
+
"lang": TT.KW_LANG,
|
|
173
|
+
"true": TT.BOOL_TRUE,
|
|
174
|
+
"false": TT.BOOL_FALSE,
|
|
175
|
+
"null": TT.NULL_LIT,
|
|
176
|
+
// === v0.0.4: custom-element and custom lexed as hyphenated identifier ===
|
|
177
|
+
"custom-element": TT.KW_CUSTOM_EL,
|
|
178
|
+
"custom": TT.KW_CUSTOM,
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export class Lexer {
|
|
182
|
+
private pos = 0;
|
|
183
|
+
private line = 1;
|
|
184
|
+
private col = 1;
|
|
185
|
+
private rawBlockPending = false;
|
|
186
|
+
|
|
187
|
+
constructor(public readonly src: string, private readonly file: string) {}
|
|
188
|
+
|
|
189
|
+
tokenize(): Token[] {
|
|
190
|
+
const tokens: Token[] = [];
|
|
191
|
+
while (true) {
|
|
192
|
+
this.skipWS();
|
|
193
|
+
if (this.pos >= this.src.length) break;
|
|
194
|
+
|
|
195
|
+
const loc = this.loc();
|
|
196
|
+
const ch = this.src[this.pos];
|
|
197
|
+
|
|
198
|
+
if (ch === "(") { tokens.push(this.single(TT.LPAREN, loc)); continue; }
|
|
199
|
+
if (ch === ")") { tokens.push(this.single(TT.RPAREN, loc)); continue; }
|
|
200
|
+
if (ch === "}") { tokens.push(this.single(TT.RBRACE, loc)); continue; }
|
|
201
|
+
if (ch === ",") { tokens.push(this.single(TT.COMMA, loc)); continue; }
|
|
202
|
+
if (ch === ".") { tokens.push(this.single(TT.DOT, loc)); continue; }
|
|
203
|
+
if (ch === ":") { tokens.push(this.single(TT.COLON, loc)); continue; }
|
|
204
|
+
if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
|
|
205
|
+
|
|
206
|
+
if (ch === "{") {
|
|
207
|
+
if (this.rawBlockPending) {
|
|
208
|
+
this.rawBlockPending = false;
|
|
209
|
+
tokens.push(this.readRawBlock(loc));
|
|
210
|
+
} else {
|
|
211
|
+
tokens.push(this.single(TT.LBRACE, loc));
|
|
212
|
+
}
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (ch === '"' || ch === "'") { tokens.push(this.readString(loc)); continue; }
|
|
217
|
+
|
|
218
|
+
if (this.isDigit(ch) || (ch === "-" && this.isDigit(this.src[this.pos + 1] ?? ""))) {
|
|
219
|
+
tokens.push(this.readNumber(loc)); continue;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (this.isIdentStart(ch)) {
|
|
223
|
+
const tok = this.readIdent(loc);
|
|
224
|
+
// === v0.0.4: Also set rawBlockPending for component, custom-element, custom ===
|
|
225
|
+
if (
|
|
226
|
+
tok.type === TT.KW_STYLE ||
|
|
227
|
+
tok.type === TT.KW_SCRIPT ||
|
|
228
|
+
tok.type === TT.KW_COMPONENT ||
|
|
229
|
+
tok.type === TT.KW_CUSTOM_EL ||
|
|
230
|
+
tok.type === TT.KW_CUSTOM
|
|
231
|
+
) {
|
|
232
|
+
this.rawBlockPending = true;
|
|
233
|
+
}
|
|
234
|
+
tokens.push(tok);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
throw new SinthError(`Unexpected character '${ch}'`, loc);
|
|
239
|
+
}
|
|
240
|
+
tokens.push({ type: TT.EOF, value: "", loc: this.loc() });
|
|
241
|
+
return tokens;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
private skipWS(): void {
|
|
245
|
+
while (this.pos < this.src.length) {
|
|
246
|
+
const ch = this.src[this.pos];
|
|
247
|
+
if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") { this.adv(); continue; }
|
|
248
|
+
|
|
249
|
+
// Sinth comments: -- line or --[ nestable block ]--
|
|
250
|
+
if (ch === "-" && this.src[this.pos + 1] === "-") {
|
|
251
|
+
if (this.src[this.pos + 2] === "[") {
|
|
252
|
+
this.adv(); this.adv(); this.adv(); // consume --[
|
|
253
|
+
let depth = 1;
|
|
254
|
+
while (this.pos < this.src.length && depth > 0) {
|
|
255
|
+
if (this.src[this.pos] === "-" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "[") {
|
|
256
|
+
depth++; this.adv(); this.adv(); this.adv();
|
|
257
|
+
} else if (this.src[this.pos] === "]" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "-") {
|
|
258
|
+
depth--; this.adv(); this.adv(); this.adv();
|
|
259
|
+
} else {
|
|
260
|
+
this.adv();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (depth > 0) throw new SinthError("Unterminated block comment --[ ... ]--", this.loc());
|
|
264
|
+
} else {
|
|
265
|
+
while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
|
|
266
|
+
}
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Consume a raw { ... } block tracking nested braces and skipping strings/comments. */
|
|
274
|
+
private readRawBlock(loc: Loc): Token {
|
|
275
|
+
this.adv(); // consume '{'
|
|
276
|
+
const start = this.pos;
|
|
277
|
+
let depth = 1;
|
|
278
|
+
|
|
279
|
+
while (this.pos < this.src.length && depth > 0) {
|
|
280
|
+
const ch = this.src[this.pos];
|
|
281
|
+
|
|
282
|
+
if (ch === '"' || ch === "'" || ch === "`") { this.skipRawString(ch); continue; }
|
|
283
|
+
if (ch === "/" && this.src[this.pos + 1] === "/") {
|
|
284
|
+
while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
if (ch === "/" && this.src[this.pos + 1] === "*") {
|
|
288
|
+
this.adv(); this.adv();
|
|
289
|
+
while (this.pos < this.src.length - 1 &&
|
|
290
|
+
!(this.src[this.pos] === "*" && this.src[this.pos + 1] === "/")) {
|
|
291
|
+
this.adv();
|
|
292
|
+
}
|
|
293
|
+
this.adv(); this.adv();
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (ch === "{") { depth++; this.adv(); }
|
|
298
|
+
else if (ch === "}") {
|
|
299
|
+
depth--;
|
|
300
|
+
if (depth > 0) this.adv();
|
|
301
|
+
// else: stop, leaving pos AT the closing }
|
|
302
|
+
} else {
|
|
303
|
+
this.adv();
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const content = this.src.substring(start, this.pos);
|
|
308
|
+
this.adv(); // consume closing '}'
|
|
309
|
+
return { type: TT.RAW_BLOCK, value: content, loc };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
private skipRawString(quote: string): void {
|
|
313
|
+
this.adv();
|
|
314
|
+
while (this.pos < this.src.length) {
|
|
315
|
+
const c = this.src[this.pos];
|
|
316
|
+
if (c === "\\") { this.adv(); this.adv(); continue; }
|
|
317
|
+
if (c === quote) { this.adv(); return; }
|
|
318
|
+
if (quote === "`" && c === "$" && this.src[this.pos + 1] === "{") {
|
|
319
|
+
this.adv(); this.adv(); // ${
|
|
320
|
+
let d = 1;
|
|
321
|
+
while (this.pos < this.src.length && d > 0) {
|
|
322
|
+
if (this.src[this.pos] === "{") d++;
|
|
323
|
+
else if (this.src[this.pos] === "}") d--;
|
|
324
|
+
this.adv();
|
|
325
|
+
}
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
this.adv();
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
private readString(loc: Loc): Token {
|
|
333
|
+
const quote = this.src[this.pos];
|
|
334
|
+
this.adv();
|
|
335
|
+
let result = "";
|
|
336
|
+
while (this.pos < this.src.length && this.src[this.pos] !== quote) {
|
|
337
|
+
if (this.src[this.pos] === "\\") {
|
|
338
|
+
this.adv();
|
|
339
|
+
const e = this.src[this.pos];
|
|
340
|
+
switch (e) {
|
|
341
|
+
case "\\": result += "\\"; break;
|
|
342
|
+
case '"': result += '"'; break;
|
|
343
|
+
case "'": result += "'"; break;
|
|
344
|
+
case "n": result += "\n"; break;
|
|
345
|
+
case "r": result += "\r"; break;
|
|
346
|
+
case "t": result += "\t"; break;
|
|
347
|
+
case "$": result += "$"; break;
|
|
348
|
+
case "{": result += "{"; break;
|
|
349
|
+
case "u": {
|
|
350
|
+
this.adv();
|
|
351
|
+
if (this.src[this.pos] === "{") {
|
|
352
|
+
this.adv();
|
|
353
|
+
let hex = "";
|
|
354
|
+
while (this.src[this.pos] !== "}") { hex += this.src[this.pos]; this.adv(); }
|
|
355
|
+
result += String.fromCodePoint(parseInt(hex, 16));
|
|
356
|
+
} else {
|
|
357
|
+
const hex = this.src.substring(this.pos, this.pos + 4);
|
|
358
|
+
result += String.fromCharCode(parseInt(hex, 16));
|
|
359
|
+
this.pos += 3; this.col += 3;
|
|
360
|
+
}
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
default: throw new SinthError(`Unknown escape sequence \\${e}`, loc);
|
|
364
|
+
}
|
|
365
|
+
this.adv();
|
|
366
|
+
} else {
|
|
367
|
+
result += this.src[this.pos];
|
|
368
|
+
this.adv();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (this.pos >= this.src.length) throw new SinthError("Unterminated string literal", loc);
|
|
372
|
+
this.adv(); // closing quote
|
|
373
|
+
return { type: TT.STRING, value: result, loc };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
private readNumber(loc: Loc): Token {
|
|
377
|
+
let s = "";
|
|
378
|
+
if (this.src[this.pos] === "-") { s += "-"; this.adv(); }
|
|
379
|
+
while (this.isDigit(this.src[this.pos] ?? "")) { s += this.src[this.pos]; this.adv(); }
|
|
380
|
+
if (this.src[this.pos] === "." && this.isDigit(this.src[this.pos + 1] ?? "")) {
|
|
381
|
+
s += "."; this.adv();
|
|
382
|
+
while (this.isDigit(this.src[this.pos] ?? "")) { s += this.src[this.pos]; this.adv(); }
|
|
383
|
+
}
|
|
384
|
+
return { type: TT.NUMBER, value: s, loc };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
private readIdent(loc: Loc): Token {
|
|
388
|
+
let s = "";
|
|
389
|
+
// === v0.0.4: isIdentCont includes '-' so "custom-element" is read as one token ===
|
|
390
|
+
while (this.pos < this.src.length && this.isIdentCont(this.src[this.pos])) {
|
|
391
|
+
s += this.src[this.pos]; this.adv();
|
|
392
|
+
}
|
|
393
|
+
const kw = KEYWORDS[s];
|
|
394
|
+
return { type: kw !== undefined ? kw : TT.IDENT, value: s, loc };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
private adv(): void {
|
|
398
|
+
const ch = this.src[this.pos++];
|
|
399
|
+
if (ch === "\n") { this.line++; this.col = 1; } else { this.col++; }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private single(type: TT, loc: Loc): Token {
|
|
403
|
+
this.adv();
|
|
404
|
+
return { type, value: this.src[this.pos - 1], loc };
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
private loc(): Loc { return { file: this.file, line: this.line, col: this.col }; }
|
|
408
|
+
private isDigit(c: string) { return c >= "0" && c <= "9"; }
|
|
409
|
+
private isIdentStart(c: string) { return /[a-zA-Z_\u00C0-\uFFFF]/.test(c); }
|
|
410
|
+
// === v0.0.4: '-' allowed in identifiers so "custom-element" is a single token ===
|
|
411
|
+
private isIdentCont(c: string) { return /[a-zA-Z0-9_\-\u00C0-\uFFFF]/.test(c); }
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// ═══════════════════════════════════════════════════════════
|
|
415
|
+
// SECTION 4: PARSER
|
|
416
|
+
// ═══════════════════════════════════════════════════════════
|
|
417
|
+
|
|
418
|
+
export class Parser {
|
|
419
|
+
private pos = 0;
|
|
420
|
+
|
|
421
|
+
constructor(private tokens: Token[], private file: string) {}
|
|
422
|
+
|
|
423
|
+
parse(): SinthFile {
|
|
424
|
+
const loc = this.peek().loc;
|
|
425
|
+
let isPage = false;
|
|
426
|
+
const imports: ImportNode[] = [];
|
|
427
|
+
const meta: MetaEntry[] = [];
|
|
428
|
+
const defs: CompDef[] = [];
|
|
429
|
+
const uses: CompUse[] = [];
|
|
430
|
+
const styles: StyleBlock[] = [];
|
|
431
|
+
const scripts: ScriptBlock[] = [];
|
|
432
|
+
const customEls: CustomElDecl[] = [];
|
|
433
|
+
|
|
434
|
+
// 1. Optional page keyword
|
|
435
|
+
if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
|
|
436
|
+
|
|
437
|
+
// 2. Imports — must come before metadata
|
|
438
|
+
while (this.check(TT.KW_IMPORT)) imports.push(this.parseImport());
|
|
439
|
+
|
|
440
|
+
// 3. Metadata — key = value pairs (lexer has already stripped comments/whitespace)
|
|
441
|
+
while (this.isMetaStart()) {
|
|
442
|
+
const entry = this.parseMeta();
|
|
443
|
+
meta.push(entry);
|
|
444
|
+
if (entry.key === "title") isPage = true;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// 4. Body: component definitions, usages, style, script, custom-element
|
|
448
|
+
while (!this.check(TT.EOF)) {
|
|
449
|
+
if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
|
|
450
|
+
else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
|
|
451
|
+
else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
|
|
452
|
+
else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
|
|
453
|
+
else if (this.check(TT.IDENT)) { uses.push(this.parseCompUse()); }
|
|
454
|
+
else throw new SinthError(`Unexpected token '${this.peek().value}'`, this.peek().loc);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ── Imports ──────────────────────────────────────────────
|
|
461
|
+
|
|
462
|
+
private parseImport(): ImportNode {
|
|
463
|
+
const loc = this.consume(TT.KW_IMPORT).loc;
|
|
464
|
+
|
|
465
|
+
if (this.check(TT.KW_CSS)) {
|
|
466
|
+
this.consume(TT.KW_CSS);
|
|
467
|
+
return { kind: "css", path: this.consume(TT.STRING).value, loc };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
if (this.check(TT.STRING)) {
|
|
471
|
+
return { kind: "sinth", path: this.consume(TT.STRING).value, loc };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
if (this.check(TT.IDENT)) {
|
|
475
|
+
const name = this.consume(TT.IDENT).value;
|
|
476
|
+
let alias: string | undefined;
|
|
477
|
+
if (this.check(TT.KW_AS)) { this.consume(TT.KW_AS); alias = this.consume(TT.IDENT).value; }
|
|
478
|
+
return { kind: "js", name, alias, loc };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
throw new SinthError(`Expected import path, library name, or 'css'`, loc);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// ── Metadata ─────────────────────────────────────────────
|
|
485
|
+
|
|
486
|
+
private isMetaStart(): boolean {
|
|
487
|
+
// Metadata: IDENT followed by EQUALS (e.g. title = "My Site")
|
|
488
|
+
// Component usage: IDENT followed by LPAREN or LBRACE
|
|
489
|
+
if (!this.check(TT.IDENT)) return false;
|
|
490
|
+
return this.tokens[this.pos + 1]?.type === TT.EQUALS;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
private parseMeta(): MetaEntry {
|
|
494
|
+
const loc = this.peek().loc;
|
|
495
|
+
const key = this.consume(TT.IDENT).value;
|
|
496
|
+
this.consume(TT.EQUALS);
|
|
497
|
+
return { key, value: this.parseLiteral(), loc };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// ── Component definitions ─────────────────────────────────
|
|
501
|
+
|
|
502
|
+
private parseCompDef(): CompDef {
|
|
503
|
+
const loc = this.consume(TT.KW_COMPONENT).loc;
|
|
504
|
+
const name = this.consume(TT.IDENT).value;
|
|
505
|
+
const params = this.parseParamDecls();
|
|
506
|
+
// === v0.0.4: rawBlockPending was set by the lexer when KW_COMPONENT was read;
|
|
507
|
+
// the next token is therefore RAW_BLOCK, not LBRACE ===
|
|
508
|
+
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
509
|
+
const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
|
|
510
|
+
return { name, params, body, styles, scripts, loc };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// === v0.0.4: Parse custom-element / custom declarations ===
|
|
514
|
+
private parseCustomEl(): CustomElDecl {
|
|
515
|
+
const loc = this.peek().loc;
|
|
516
|
+
if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
|
|
517
|
+
else if (this.check(TT.KW_CUSTOM)) this.consume(TT.KW_CUSTOM);
|
|
518
|
+
const tagName = this.consume(TT.IDENT).value;
|
|
519
|
+
const sinthName = tagNameToPascal(tagName);
|
|
520
|
+
const params = this.parseParamDecls();
|
|
521
|
+
// custom-element / custom declarations have no body block
|
|
522
|
+
return { sinthName, tagName, params, loc };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
private parseParamDecls(): ParamDecl[] {
|
|
526
|
+
const params: ParamDecl[] = [];
|
|
527
|
+
if (!this.check(TT.LPAREN)) return params;
|
|
528
|
+
this.consume(TT.LPAREN);
|
|
529
|
+
while (!this.check(TT.RPAREN)) {
|
|
530
|
+
const ploc = this.peek().loc;
|
|
531
|
+
const pname = this.consume(TT.IDENT).value;
|
|
532
|
+
let defaultVal: Literal | undefined;
|
|
533
|
+
if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
|
|
534
|
+
params.push({ name: pname, defaultVal, loc: ploc });
|
|
535
|
+
if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
|
|
536
|
+
}
|
|
537
|
+
this.consume(TT.RPAREN);
|
|
538
|
+
return params;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
private parseCompBody(raw: string, loc: Loc): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
|
|
542
|
+
const tokens = new Lexer(raw, loc.file).tokenize();
|
|
543
|
+
return new Parser(tokens, loc.file).parseBodyContents();
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
private parseBodyContents(): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
|
|
547
|
+
const body: Child[] = [], styles: StyleBlock[] = [], scripts: ScriptBlock[] = [];
|
|
548
|
+
while (!this.check(TT.EOF)) {
|
|
549
|
+
if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
|
|
550
|
+
else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
|
|
551
|
+
else if (this.check(TT.STRING)) {
|
|
552
|
+
const loc = this.peek().loc;
|
|
553
|
+
body.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
|
|
554
|
+
}
|
|
555
|
+
else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
|
|
556
|
+
else throw new SinthError(`Unexpected token '${this.peek().value}' in component body`, this.peek().loc);
|
|
557
|
+
}
|
|
558
|
+
return { body, styles, scripts };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// ── Component usages ──────────────────────────────────────
|
|
562
|
+
|
|
563
|
+
private parseCompUse(): CompUse {
|
|
564
|
+
const loc = this.peek().loc;
|
|
565
|
+
const name = this.consume(TT.IDENT).value;
|
|
566
|
+
const attrs: Attr[] = [];
|
|
567
|
+
|
|
568
|
+
if (this.check(TT.LPAREN)) {
|
|
569
|
+
this.consume(TT.LPAREN);
|
|
570
|
+
while (!this.check(TT.RPAREN)) {
|
|
571
|
+
const aloc = this.peek().loc;
|
|
572
|
+
const aname = this.consume(TT.IDENT).value;
|
|
573
|
+
let value: Literal | null = null;
|
|
574
|
+
if (this.check(TT.COLON)) { this.consume(TT.COLON); value = this.parseLiteral(); }
|
|
575
|
+
attrs.push({ name: aname, value, loc: aloc });
|
|
576
|
+
if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
|
|
577
|
+
}
|
|
578
|
+
this.consume(TT.RPAREN);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const children: Child[] = [];
|
|
582
|
+
if (this.check(TT.RAW_BLOCK)) {
|
|
583
|
+
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
584
|
+
const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
|
|
585
|
+
children.push(...new Parser(tokens, rawTok.loc.file).parseChildList());
|
|
586
|
+
} else if (this.check(TT.LBRACE)) {
|
|
587
|
+
this.consume(TT.LBRACE);
|
|
588
|
+
children.push(...this.parseChildList());
|
|
589
|
+
this.consume(TT.RBRACE);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
return { kind: "use", name, attrs, children, loc };
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
private parseChildList(): Child[] {
|
|
596
|
+
const children: Child[] = [];
|
|
597
|
+
while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
|
|
598
|
+
if (this.check(TT.STRING)) {
|
|
599
|
+
const loc = this.peek().loc;
|
|
600
|
+
children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
|
|
601
|
+
} else if (this.check(TT.IDENT)) {
|
|
602
|
+
children.push(this.parseCompUse());
|
|
603
|
+
} else {
|
|
604
|
+
throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return children;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// ── Style blocks ──────────────────────────────────────────
|
|
611
|
+
|
|
612
|
+
private parseStyleBlock(): StyleBlock {
|
|
613
|
+
const loc = this.consume(TT.KW_STYLE).loc;
|
|
614
|
+
let global = false, lang: "css" | "scss" = "css";
|
|
615
|
+
const extraAttrs: Record<string, string> = {};
|
|
616
|
+
|
|
617
|
+
while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
|
|
618
|
+
if (this.check(TT.KW_GLOBAL)) { global = true; this.consume(TT.KW_GLOBAL); }
|
|
619
|
+
else if (this.check(TT.KW_LANG)) {
|
|
620
|
+
this.consume(TT.KW_LANG); this.consume(TT.EQUALS);
|
|
621
|
+
const lv = this.consume(TT.STRING).value;
|
|
622
|
+
if (lv !== "css" && lv !== "scss") throw new SinthError(`Unsupported style lang '${lv}'`, loc);
|
|
623
|
+
lang = lv as "css" | "scss";
|
|
624
|
+
}
|
|
625
|
+
else if (this.check(TT.IDENT)) {
|
|
626
|
+
const k = this.consume(TT.IDENT).value;
|
|
627
|
+
this.consume(TT.EQUALS);
|
|
628
|
+
extraAttrs[k] = this.consume(TT.STRING).value;
|
|
629
|
+
}
|
|
630
|
+
else throw new SinthError(`Unexpected token '${this.peek().value}' in style modifiers`, this.peek().loc);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
return { global, lang, raw: this.consume(TT.RAW_BLOCK).value, extraAttrs, loc };
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// ── Script blocks ─────────────────────────────────────────
|
|
637
|
+
|
|
638
|
+
private parseScriptBlock(): ScriptBlock {
|
|
639
|
+
const loc = this.consume(TT.KW_SCRIPT).loc;
|
|
640
|
+
const attrs: Record<string, string> = {};
|
|
641
|
+
|
|
642
|
+
while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
|
|
643
|
+
const key = this.consume(TT.IDENT).value;
|
|
644
|
+
if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); attrs[key] = this.consume(TT.STRING).value; }
|
|
645
|
+
else { attrs[key] = "true"; }
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
return { raw: this.consume(TT.RAW_BLOCK).value, attrs, loc };
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ── Literals ──────────────────────────────────────────────
|
|
652
|
+
|
|
653
|
+
private parseLiteral(): Literal {
|
|
654
|
+
const tok = this.peek();
|
|
655
|
+
if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
|
|
656
|
+
if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
|
|
657
|
+
if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
|
|
658
|
+
if (this.check(TT.BOOL_FALSE)){ this.consume(TT.BOOL_FALSE);return { kind: "bool", value: false }; }
|
|
659
|
+
if (this.check(TT.NULL_LIT)) { this.consume(TT.NULL_LIT); return { kind: "null" }; }
|
|
660
|
+
throw new SinthError(`Expected literal value, got '${tok.value}'`, tok.loc);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// ── Token helpers ─────────────────────────────────────────
|
|
664
|
+
|
|
665
|
+
private peek(): Token { return this.tokens[this.pos]; }
|
|
666
|
+
private check(t: TT): boolean { return this.tokens[this.pos]?.type === t; }
|
|
667
|
+
private consume(t: TT): Token {
|
|
668
|
+
const tok = this.tokens[this.pos];
|
|
669
|
+
if (tok.type !== t) {
|
|
670
|
+
throw new SinthError(`Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`, tok.loc);
|
|
671
|
+
}
|
|
672
|
+
this.pos++;
|
|
673
|
+
return tok;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// ═══════════════════════════════════════════════════════════
|
|
678
|
+
// SECTION 5: IMPORT RESOLVER
|
|
679
|
+
// ═══════════════════════════════════════════════════════════
|
|
680
|
+
|
|
681
|
+
interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
|
|
682
|
+
|
|
683
|
+
interface ResolvedImports {
|
|
684
|
+
allDefs: Map<string, CompDef>;
|
|
685
|
+
customEls: Map<string, CustomElInfo>;
|
|
686
|
+
cssLinks: string[];
|
|
687
|
+
jsLinks: { src: string; attrs: Record<string, string> }[];
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// Module-level import stack for circular detection
|
|
691
|
+
const IMPORT_STACK: string[] = [];
|
|
692
|
+
|
|
693
|
+
// === v0.0.4: parseFile catches errors and attaches source line preview ===
|
|
694
|
+
function parseFile(filePath: string): SinthFile {
|
|
695
|
+
if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
|
|
696
|
+
const src = fs.readFileSync(filePath, "utf-8");
|
|
697
|
+
const srcLines = src.split("\n");
|
|
698
|
+
try {
|
|
699
|
+
const tokens = new Lexer(src, filePath).tokenize();
|
|
700
|
+
return new Parser(tokens, filePath).parse();
|
|
701
|
+
} catch (e) {
|
|
702
|
+
if (e instanceof SinthError) throw e.withSource(srcLines);
|
|
703
|
+
throw e;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function resolveImports(
|
|
708
|
+
file: SinthFile,
|
|
709
|
+
cfg: ResolverConfig,
|
|
710
|
+
visited: Set<string> = new Set(),
|
|
711
|
+
): ResolvedImports {
|
|
712
|
+
const allDefs = new Map<string, CompDef>();
|
|
713
|
+
const customEls = new Map<string, CustomElInfo>();
|
|
714
|
+
const cssLinks: string[] = [];
|
|
715
|
+
const jsLinks: { src: string; attrs: Record<string, string> }[] = [];
|
|
716
|
+
|
|
717
|
+
// Register this file's own component definitions
|
|
718
|
+
for (const def of file.defs) {
|
|
719
|
+
if (BUILTIN_MAP[def.name]) {
|
|
720
|
+
throw new SinthError(`'${def.name}' is a built-in SinthUI component and cannot be redefined.`, def.loc);
|
|
721
|
+
}
|
|
722
|
+
if (allDefs.has(def.name)) throw new SinthError(`Duplicate component definition '${def.name}'`, def.loc);
|
|
723
|
+
allDefs.set(def.name, def);
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// Register custom element declarations
|
|
727
|
+
for (const el of file.customEls) {
|
|
728
|
+
customEls.set(el.sinthName, { tagName: el.tagName, params: el.params });
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// Warn about metadata in component files
|
|
732
|
+
if (!file.isPage && file.meta.length > 0) {
|
|
733
|
+
for (const m of file.meta) {
|
|
734
|
+
SinthWarning.emit(`Metadata key '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
for (const imp of file.imports) {
|
|
739
|
+
if (imp.kind === "css") {
|
|
740
|
+
const r = resolveRelative(imp.path, file.filePath);
|
|
741
|
+
if (!cssLinks.includes(r)) cssLinks.push(r);
|
|
742
|
+
|
|
743
|
+
} else if (imp.kind === "js") {
|
|
744
|
+
const src = resolveLibrary(imp.name, cfg);
|
|
745
|
+
jsLinks.push({ src, attrs: {} });
|
|
746
|
+
|
|
747
|
+
// === v0.0.4: Auto-import companion .sinth for JS libraries (e.g. sinthui.sinth) ===
|
|
748
|
+
for (const libDir of cfg.libraryPaths) {
|
|
749
|
+
const companion = path.join(libDir, imp.name + ".sinth");
|
|
750
|
+
if (fs.existsSync(companion) && !visited.has(companion)) {
|
|
751
|
+
visited.add(companion);
|
|
752
|
+
IMPORT_STACK.push(companion);
|
|
753
|
+
const sub = resolveImports(parseFile(companion), cfg, visited);
|
|
754
|
+
IMPORT_STACK.pop();
|
|
755
|
+
for (const [n, d] of sub.allDefs) allDefs.set(n, d);
|
|
756
|
+
for (const [n, e] of sub.customEls) customEls.set(n, e);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
} else if (imp.kind === "sinth") {
|
|
761
|
+
const resolved = resolveSinthPath(imp.path, file.filePath, cfg);
|
|
762
|
+
|
|
763
|
+
if (IMPORT_STACK.includes(resolved)) {
|
|
764
|
+
throw new SinthError(
|
|
765
|
+
`Circular import detected.\n Chain: ${[...IMPORT_STACK, resolved].join(" → ")}`
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
if (visited.has(resolved)) continue;
|
|
769
|
+
visited.add(resolved);
|
|
770
|
+
|
|
771
|
+
IMPORT_STACK.push(resolved);
|
|
772
|
+
const imported = parseFile(resolved);
|
|
773
|
+
IMPORT_STACK.pop();
|
|
774
|
+
|
|
775
|
+
const sub = resolveImports(imported, cfg, visited);
|
|
776
|
+
for (const [name, def] of sub.allDefs) {
|
|
777
|
+
if (allDefs.has(name)) {
|
|
778
|
+
throw new SinthError(`Component '${name}' defined in multiple imported files.`);
|
|
779
|
+
}
|
|
780
|
+
allDefs.set(name, def);
|
|
781
|
+
}
|
|
782
|
+
for (const [n, e] of sub.customEls) customEls.set(n, e);
|
|
783
|
+
for (const l of sub.cssLinks) if (!cssLinks.includes(l)) cssLinks.push(l);
|
|
784
|
+
for (const j of sub.jsLinks) jsLinks.push(j);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
return { allDefs, customEls, cssLinks, jsLinks };
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function resolveRelative(p: string, fromFile: string): string {
|
|
792
|
+
if (p.startsWith("./") || p.startsWith("../")) return path.resolve(path.dirname(fromFile), p);
|
|
793
|
+
return p;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function resolveLibrary(name: string, cfg: ResolverConfig): string {
|
|
797
|
+
const base = name.endsWith(".js") ? name : name + ".js";
|
|
798
|
+
for (const libDir of cfg.libraryPaths) {
|
|
799
|
+
const c = path.join(libDir, base);
|
|
800
|
+
if (fs.existsSync(c)) return c;
|
|
801
|
+
}
|
|
802
|
+
return `/libraries/${base}`;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// === v0.0.4: resolveSinthPath — first try relative to importing file, then library paths ===
|
|
806
|
+
function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
|
|
807
|
+
// Explicit relative path
|
|
808
|
+
if (p.startsWith("./") || p.startsWith("../")) {
|
|
809
|
+
const r = path.resolve(path.dirname(fromFile), p);
|
|
810
|
+
if (fs.existsSync(r)) return r;
|
|
811
|
+
const w = r.endsWith(".sinth") ? "" : r + ".sinth";
|
|
812
|
+
if (w && fs.existsSync(w)) return w;
|
|
813
|
+
throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// === v0.0.4: Non-relative paths (e.g. "components/Card.sinth"): try relative to importing
|
|
817
|
+
// file's directory FIRST, then fall back to library paths ===
|
|
818
|
+
const relToFile = path.resolve(path.dirname(fromFile), p);
|
|
819
|
+
if (fs.existsSync(relToFile)) return relToFile;
|
|
820
|
+
const relToFileExt = relToFile.endsWith(".sinth") ? relToFile : relToFile + ".sinth";
|
|
821
|
+
if (fs.existsSync(relToFileExt)) return relToFileExt;
|
|
822
|
+
|
|
823
|
+
// Library path fallback
|
|
824
|
+
for (const libDir of cfg.libraryPaths) {
|
|
825
|
+
const c1 = path.join(libDir, p);
|
|
826
|
+
if (fs.existsSync(c1)) return c1;
|
|
827
|
+
const c2 = c1.endsWith(".sinth") ? c1 : c1 + ".sinth";
|
|
828
|
+
if (fs.existsSync(c2)) return c2;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
throw new SinthError(
|
|
832
|
+
`Cannot resolve import '${p}'\n Tried relative: ${relToFileExt}\n Tried library paths: ${cfg.libraryPaths.join(", ")}`
|
|
833
|
+
);
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
// ═══════════════════════════════════════════════════════════
|
|
837
|
+
// SECTION 6: BUILT-IN COMPONENT MAP
|
|
838
|
+
// ═══════════════════════════════════════════════════════════
|
|
839
|
+
|
|
840
|
+
interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
|
|
841
|
+
|
|
842
|
+
// === v0.0.4: Complete HTML5 map; Col = void <col>; Column = grid div; added SubHeading, CardGrid ===
|
|
843
|
+
const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
844
|
+
// ── Structural ──────────────────────────────────────────
|
|
845
|
+
Main: { tag: "main" },
|
|
846
|
+
Header: { tag: "header" },
|
|
847
|
+
Footer: { tag: "footer" },
|
|
848
|
+
Nav: { tag: "nav" },
|
|
849
|
+
Section: { tag: "section" },
|
|
850
|
+
Article: { tag: "article" },
|
|
851
|
+
Aside: { tag: "aside" },
|
|
852
|
+
Div: { tag: "div" },
|
|
853
|
+
Span: { tag: "span" },
|
|
854
|
+
Hero: { tag: "section", defaultClass: "hero" },
|
|
855
|
+
Container: { tag: "div", defaultClass: "container" },
|
|
856
|
+
Grid: { tag: "div", defaultClass: "grid" },
|
|
857
|
+
Flex: { tag: "div", defaultClass: "flex" },
|
|
858
|
+
Stack: { tag: "div", defaultClass: "stack" },
|
|
859
|
+
Row: { tag: "div", defaultClass: "row" },
|
|
860
|
+
// === v0.0.4: Column = grid helper div; Col = HTML void table col ===
|
|
861
|
+
Column: { tag: "div", defaultClass: "col" },
|
|
862
|
+
// ── Typography ────────────────────────────────────────────
|
|
863
|
+
Heading: { tag: "h1" }, // resolved dynamically by level attr
|
|
864
|
+
Paragraph: { tag: "p" },
|
|
865
|
+
// === v0.0.4: SubHeading convenience component ===
|
|
866
|
+
SubHeading: { tag: "p", defaultClass: "subheading" },
|
|
867
|
+
Lead: { tag: "p", defaultClass: "lead" },
|
|
868
|
+
Small: { tag: "small" },
|
|
869
|
+
Strong: { tag: "strong" },
|
|
870
|
+
Em: { tag: "em" },
|
|
871
|
+
Code: { tag: "code" },
|
|
872
|
+
Pre: { tag: "pre" },
|
|
873
|
+
Blockquote: { tag: "blockquote" },
|
|
874
|
+
Mark: { tag: "mark" },
|
|
875
|
+
Label: { tag: "label" },
|
|
876
|
+
Abbr: { tag: "abbr" },
|
|
877
|
+
Del: { tag: "del" },
|
|
878
|
+
Ins: { tag: "ins" },
|
|
879
|
+
Sub: { tag: "sub" },
|
|
880
|
+
Sup: { tag: "sup" },
|
|
881
|
+
Data: { tag: "data" },
|
|
882
|
+
Time: { tag: "time" },
|
|
883
|
+
Bdi: { tag: "bdi" },
|
|
884
|
+
Bdo: { tag: "bdo" },
|
|
885
|
+
Cite: { tag: "cite" },
|
|
886
|
+
Dfn: { tag: "dfn" },
|
|
887
|
+
Kbd: { tag: "kbd" },
|
|
888
|
+
Samp: { tag: "samp" },
|
|
889
|
+
Var: { tag: "var" },
|
|
890
|
+
Address: { tag: "address" },
|
|
891
|
+
Ruby: { tag: "ruby" },
|
|
892
|
+
Rt: { tag: "rt" },
|
|
893
|
+
Rp: { tag: "rp" },
|
|
894
|
+
// ── Interactive ────────────────────────────────────────────
|
|
895
|
+
Button: { tag: "button" },
|
|
896
|
+
Link: { tag: "a" },
|
|
897
|
+
NavLink: { tag: "a" },
|
|
898
|
+
Select: { tag: "select" },
|
|
899
|
+
Form: { tag: "form" },
|
|
900
|
+
Fieldset: { tag: "fieldset" },
|
|
901
|
+
Legend: { tag: "legend" },
|
|
902
|
+
Details: { tag: "details" },
|
|
903
|
+
Summary: { tag: "summary" },
|
|
904
|
+
Dialog: { tag: "dialog" },
|
|
905
|
+
Textarea: { tag: "textarea" },
|
|
906
|
+
Datalist: { tag: "datalist" },
|
|
907
|
+
Optgroup: { tag: "optgroup" },
|
|
908
|
+
Option: { tag: "option" },
|
|
909
|
+
Progress: { tag: "progress" },
|
|
910
|
+
Meter: { tag: "meter" },
|
|
911
|
+
Output: { tag: "output" },
|
|
912
|
+
Map: { tag: "map" },
|
|
913
|
+
// ── Media ──────────────────────────────────────────────────
|
|
914
|
+
Picture: { tag: "picture" },
|
|
915
|
+
Video: { tag: "video" },
|
|
916
|
+
Audio: { tag: "audio" },
|
|
917
|
+
Figure: { tag: "figure" },
|
|
918
|
+
Figcaption: { tag: "figcaption" },
|
|
919
|
+
Canvas: { tag: "canvas" },
|
|
920
|
+
Svg: { tag: "svg" },
|
|
921
|
+
IFrame: { tag: "iframe" },
|
|
922
|
+
Object: { tag: "object" },
|
|
923
|
+
// ── Void elements ──────────────────────────────────────────
|
|
924
|
+
Img: { tag: "img", voidEl: true },
|
|
925
|
+
Logo: { tag: "img", voidEl: true },
|
|
926
|
+
Input: { tag: "input", voidEl: true },
|
|
927
|
+
Hr: { tag: "hr", voidEl: true },
|
|
928
|
+
Br: { tag: "br", voidEl: true },
|
|
929
|
+
Wbr: { tag: "wbr", voidEl: true },
|
|
930
|
+
Source: { tag: "source", voidEl: true },
|
|
931
|
+
Embed: { tag: "embed", voidEl: true },
|
|
932
|
+
// === v0.0.4: Col = HTML void table column (NOT the grid div) ===
|
|
933
|
+
Col: { tag: "col", voidEl: true },
|
|
934
|
+
Area: { tag: "area", voidEl: true },
|
|
935
|
+
// ── Lists ─────────────────────────────────────────────────
|
|
936
|
+
Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
|
|
937
|
+
Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
|
|
938
|
+
// ── Tables ─────────────────────────────────────────────────
|
|
939
|
+
Table: { tag: "table" },
|
|
940
|
+
Caption: { tag: "caption" },
|
|
941
|
+
Thead: { tag: "thead" },
|
|
942
|
+
Tbody: { tag: "tbody" },
|
|
943
|
+
Tfoot: { tag: "tfoot" },
|
|
944
|
+
Tr: { tag: "tr" },
|
|
945
|
+
Th: { tag: "th" },
|
|
946
|
+
Td: { tag: "td" },
|
|
947
|
+
Colgroup: { tag: "colgroup" },
|
|
948
|
+
// ── Utility ────────────────────────────────────────────────
|
|
949
|
+
Template: { tag: "template" },
|
|
950
|
+
Slot: { tag: "slot" },
|
|
951
|
+
NoScript: { tag: "noscript" },
|
|
952
|
+
// === v0.0.4: CardGrid convenience layout wrapper ===
|
|
953
|
+
CardGrid: { tag: "div", defaultClass: "card-grid" },
|
|
954
|
+
// === v0.0.4: RawHTML marker — handled specially in renderCompUse ===
|
|
955
|
+
RawHTML: { tag: "__RAW__" },
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
// All HTML void elements (never receive closing tags)
|
|
959
|
+
const VOID_TAGS = new Set([
|
|
960
|
+
"area", "base", "br", "col", "embed", "hr", "img", "input",
|
|
961
|
+
"link", "meta", "param", "source", "track", "wbr",
|
|
962
|
+
]);
|
|
963
|
+
|
|
964
|
+
const EVENT_RE = /^on[A-Z]/;
|
|
965
|
+
function eventAttrName(name: string): string | null {
|
|
966
|
+
return EVENT_RE.test(name) ? name.toLowerCase() : null;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
// ═══════════════════════════════════════════════════════════
|
|
970
|
+
// SECTION 7: STYLE PROCESSOR
|
|
971
|
+
// ═══════════════════════════════════════════════════════════
|
|
972
|
+
|
|
973
|
+
// === v0.0.4: Completely rewritten convertCSSProps — bulletproof line-by-line approach ===
|
|
974
|
+
// Rules:
|
|
975
|
+
// - Match lines of the form: [whitespace] camelCaseProp : "value" [;]
|
|
976
|
+
// - Convert property name camelCase → kebab-case
|
|
977
|
+
// - Strip surrounding single or double quotes from value
|
|
978
|
+
// - Ensure trailing semicolon
|
|
979
|
+
// - Leave selectors (contain { or :pseudo), @rules, comments, braces untouched
|
|
980
|
+
function convertCSSProps(css: string): string {
|
|
981
|
+
return css.split("\n").map(line => {
|
|
982
|
+
const trimmed = line.trim();
|
|
983
|
+
|
|
984
|
+
// Leave empty lines, braces, @rules, comments untouched
|
|
985
|
+
if (!trimmed) return line;
|
|
986
|
+
if (trimmed === "}" || trimmed.startsWith("}")) return line;
|
|
987
|
+
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
|
|
988
|
+
if (trimmed.startsWith("@")) return line;
|
|
989
|
+
// Lines containing { are selector/block openers — leave untouched
|
|
990
|
+
if (trimmed.includes("{")) return line;
|
|
991
|
+
|
|
992
|
+
// Match a CSS declaration: identifier (colon) value [semicolon]
|
|
993
|
+
// The colon must NOT be preceded by another colon (avoid matching ::before, &:hover etc.)
|
|
994
|
+
// Property names are identifiers: letters, digits, hyphens — but we only camelCase-convert
|
|
995
|
+
// identifiers that are purely alphabetic (camelCase or vendor-prefixed).
|
|
996
|
+
const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
|
|
997
|
+
if (!m) return line;
|
|
998
|
+
|
|
999
|
+
const [, indent, rawProp, sep, rawVal] = m;
|
|
1000
|
+
|
|
1001
|
+
// Decide if this looks like a declaration vs a pseudo-selector line
|
|
1002
|
+
// A declaration ends without { and the value is either quoted or a plain CSS value
|
|
1003
|
+
// We require either camelCase OR a quoted value to convert
|
|
1004
|
+
const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
|
|
1005
|
+
const hasQuotedVal = /^["']/.test(rawVal.trim());
|
|
1006
|
+
if (!hasCamelCase && !hasQuotedVal) return line;
|
|
1007
|
+
|
|
1008
|
+
// Strip trailing semicolon from value if present before stripping quotes
|
|
1009
|
+
let val = rawVal.trim();
|
|
1010
|
+
if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
|
|
1011
|
+
|
|
1012
|
+
// Strip surrounding quotes
|
|
1013
|
+
if (
|
|
1014
|
+
(val.startsWith('"') && val.endsWith('"')) ||
|
|
1015
|
+
(val.startsWith("'") && val.endsWith("'"))
|
|
1016
|
+
) {
|
|
1017
|
+
val = val.slice(1, -1);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
const kebab = camelToKebab(rawProp);
|
|
1021
|
+
return `${indent}${kebab}: ${val};`;
|
|
1022
|
+
}).join("\n");
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// === v0.0.4: processStyleBlock — correct order: interpolate {param} → camelCase convert → SCSS → scope ===
|
|
1026
|
+
function processStyleBlock(
|
|
1027
|
+
block: StyleBlock,
|
|
1028
|
+
hash: string,
|
|
1029
|
+
params: Map<string, string> = new Map(),
|
|
1030
|
+
): string {
|
|
1031
|
+
let raw = block.raw;
|
|
1032
|
+
|
|
1033
|
+
// Step 1: Interpolate {param} placeholders (before anything else)
|
|
1034
|
+
if (params.size > 0) {
|
|
1035
|
+
raw = interpolateAttr(raw, params);
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// Step 2: Warn if & appears in a plain CSS block
|
|
1039
|
+
if (block.lang === "css" && raw.includes("&")) {
|
|
1040
|
+
SinthWarning.emit(
|
|
1041
|
+
`'&' found in a plain CSS block. Use style lang="scss" for SCSS features.`,
|
|
1042
|
+
block.loc,
|
|
1043
|
+
);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// Step 3: Convert camelCase property names BEFORE SCSS compilation
|
|
1047
|
+
let css = convertCSSProps(raw);
|
|
1048
|
+
|
|
1049
|
+
// Step 4: SCSS compilation (if requested)
|
|
1050
|
+
if (block.lang === "scss") {
|
|
1051
|
+
try {
|
|
1052
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
1053
|
+
const sass: { compileString: (src: string) => { css: string } } = require("sass");
|
|
1054
|
+
css = sass.compileString(css).css;
|
|
1055
|
+
} catch (e: unknown) {
|
|
1056
|
+
const err = e as { code?: string; message?: string };
|
|
1057
|
+
if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
|
|
1058
|
+
throw new SinthError(
|
|
1059
|
+
"SCSS support requires the 'sass' package.\n Install with: npm install sass"
|
|
1060
|
+
);
|
|
1061
|
+
}
|
|
1062
|
+
throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// Step 5: Scope selectors (unless global)
|
|
1067
|
+
if (!block.global) css = scopeCSS(css, hash);
|
|
1068
|
+
|
|
1069
|
+
return css;
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
function scopeCSS(css: string, hash: string): string {
|
|
1073
|
+
return processRules(css, `[data-s="${hash}"]`);
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
function processRules(css: string, attr: string): string {
|
|
1077
|
+
let out = "";
|
|
1078
|
+
let i = 0;
|
|
1079
|
+
|
|
1080
|
+
while (i < css.length) {
|
|
1081
|
+
// Skip top-level whitespace
|
|
1082
|
+
if (/\s/.test(css[i])) { out += css[i++]; continue; }
|
|
1083
|
+
|
|
1084
|
+
// Skip CSS block comments
|
|
1085
|
+
if (css[i] === "/" && css[i + 1] === "*") {
|
|
1086
|
+
const end = css.indexOf("*/", i + 2);
|
|
1087
|
+
if (end === -1) { out += css.substring(i); break; }
|
|
1088
|
+
out += css.substring(i, end + 2);
|
|
1089
|
+
i = end + 2;
|
|
1090
|
+
continue;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
const braceIdx = findCSSBrace(css, i);
|
|
1094
|
+
if (braceIdx === -1) { out += css.substring(i); break; }
|
|
1095
|
+
|
|
1096
|
+
const selector = css.substring(i, braceIdx).trim();
|
|
1097
|
+
const { content, end } = extractCSSBlock(css, braceIdx);
|
|
1098
|
+
|
|
1099
|
+
if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
|
|
1100
|
+
// @keyframes: never scope — they're global by name
|
|
1101
|
+
out += `${selector} {${content}}\n`;
|
|
1102
|
+
} else if (/^@(media|supports|layer|container)/.test(selector)) {
|
|
1103
|
+
// Descend into conditional @rules
|
|
1104
|
+
out += `${selector} {\n${processRules(content, attr)}\n}\n`;
|
|
1105
|
+
} else if (selector.startsWith("@")) {
|
|
1106
|
+
// Other @rules: pass through
|
|
1107
|
+
out += `${selector} {${content}}\n`;
|
|
1108
|
+
} else if (selector.length > 0) {
|
|
1109
|
+
out += `${scopeSelectors(selector, attr)} {${content}}\n`;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
i = end;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
return out;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
function scopeSelectors(selList: string, attr: string): string {
|
|
1119
|
+
return selList
|
|
1120
|
+
.split(",")
|
|
1121
|
+
.map(s => {
|
|
1122
|
+
s = s.trim();
|
|
1123
|
+
if (!s) return "";
|
|
1124
|
+
// Don't scope root elements
|
|
1125
|
+
if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
|
|
1126
|
+
// Handle pseudo-classes/elements: insert scope before pseudo suffix
|
|
1127
|
+
const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
|
|
1128
|
+
if (m && m[1].trim()) {
|
|
1129
|
+
return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
|
|
1130
|
+
}
|
|
1131
|
+
return `${attr} ${s}, ${s}${attr}`;
|
|
1132
|
+
})
|
|
1133
|
+
.filter(Boolean)
|
|
1134
|
+
.join(",\n");
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
function findCSSBrace(css: string, from: number): number {
|
|
1138
|
+
let i = from;
|
|
1139
|
+
while (i < css.length) {
|
|
1140
|
+
if (css[i] === '"' || css[i] === "'") {
|
|
1141
|
+
const q = css[i++];
|
|
1142
|
+
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
1143
|
+
i++;
|
|
1144
|
+
} else if (css[i] === "{") {
|
|
1145
|
+
return i;
|
|
1146
|
+
} else {
|
|
1147
|
+
i++;
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
return -1;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
function extractCSSBlock(css: string, openBrace: number): { content: string; end: number } {
|
|
1154
|
+
let i = openBrace + 1, depth = 1;
|
|
1155
|
+
while (i < css.length && depth > 0) {
|
|
1156
|
+
if (css[i] === '"' || css[i] === "'") {
|
|
1157
|
+
const q = css[i++];
|
|
1158
|
+
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
1159
|
+
i++;
|
|
1160
|
+
} else if (css[i] === "/" && css[i + 1] === "*") {
|
|
1161
|
+
i += 2;
|
|
1162
|
+
while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/")) i++;
|
|
1163
|
+
i += 2;
|
|
1164
|
+
} else if (css[i] === "{") { depth++; i++; }
|
|
1165
|
+
else if (css[i] === "}") { depth--; if (depth > 0) i++; else break; }
|
|
1166
|
+
else { i++; }
|
|
1167
|
+
}
|
|
1168
|
+
return { content: css.substring(openBrace + 1, i), end: i + 1 };
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
// ═══════════════════════════════════════════════════════════
|
|
1172
|
+
// SECTION 8: HTML GENERATOR
|
|
1173
|
+
// ═══════════════════════════════════════════════════════════
|
|
1174
|
+
|
|
1175
|
+
function resolveBuiltinTag(
|
|
1176
|
+
name: string,
|
|
1177
|
+
attrs: Attr[],
|
|
1178
|
+
): { tag: string; defaultClass?: string; voidEl: boolean } {
|
|
1179
|
+
if (name === "Heading") {
|
|
1180
|
+
const la = attrs.find(a => a.name === "level");
|
|
1181
|
+
const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
|
|
1182
|
+
if (!la) SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
|
|
1183
|
+
return { tag: `h${lv}`, voidEl: false };
|
|
1184
|
+
}
|
|
1185
|
+
const info = BUILTIN_MAP[name];
|
|
1186
|
+
if (info) return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
|
|
1187
|
+
SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
|
|
1188
|
+
return { tag: name.toLowerCase(), voidEl: false };
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
|
|
1192
|
+
const { name, value } = attr;
|
|
1193
|
+
|
|
1194
|
+
if (value === null) return name; // shorthand boolean true
|
|
1195
|
+
if (value.kind === "null") return ""; // omit attribute entirely
|
|
1196
|
+
if (value.kind === "bool") return value.value ? name : ""; // true → name, false → omit
|
|
1197
|
+
if (value.kind === "num") return `${name}="${value.value}"`;
|
|
1198
|
+
|
|
1199
|
+
// String value — interpolate {param}, then emit
|
|
1200
|
+
let raw = value.value;
|
|
1201
|
+
raw = interpolateAttr(raw, paramMap);
|
|
1202
|
+
|
|
1203
|
+
const ev = eventAttrName(name);
|
|
1204
|
+
if (ev) {
|
|
1205
|
+
const call = raw.includes("(") ? raw : `${raw}(event)`;
|
|
1206
|
+
return `${ev}="${escAttr(call)}"`;
|
|
1207
|
+
}
|
|
1208
|
+
return `${name}="${escAttr(raw)}"`;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// === v0.0.4: renderText — "$slot" protected from double-escaping via placeholder approach ===
|
|
1212
|
+
function renderText(text: string, params: Map<string, string>): string {
|
|
1213
|
+
// Map of placeholder → raw HTML for slot-like params
|
|
1214
|
+
const rawSlots = new Map<string, string>();
|
|
1215
|
+
let counter = 0;
|
|
1216
|
+
|
|
1217
|
+
let s = text;
|
|
1218
|
+
|
|
1219
|
+
// Step 1: Replace \$ with a placeholder so it survives param substitution
|
|
1220
|
+
s = s.replace(/\\\$/g, "\x00DOLLAR\x00");
|
|
1221
|
+
|
|
1222
|
+
// Step 2: Substitute $param references
|
|
1223
|
+
s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
|
|
1224
|
+
const val = params.get(n);
|
|
1225
|
+
if (val === undefined) return `$${n}`; // unknown param — keep as literal
|
|
1226
|
+
|
|
1227
|
+
// "$slot" (and any raw-HTML param) must NOT be HTML-escaped — use a placeholder
|
|
1228
|
+
if (n === "slot") {
|
|
1229
|
+
const ph = `\x00RAW${counter++}\x00`;
|
|
1230
|
+
rawSlots.set(ph, val);
|
|
1231
|
+
return ph;
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
return val; // will be HTML-escaped in step 3
|
|
1235
|
+
});
|
|
1236
|
+
|
|
1237
|
+
// Step 3: HTML-escape the entire string
|
|
1238
|
+
// Placeholders contain \x00 which esc() does not touch
|
|
1239
|
+
s = esc(s);
|
|
1240
|
+
|
|
1241
|
+
// Step 4: Restore raw HTML slot placeholders (must NOT be escaped)
|
|
1242
|
+
for (const [ph, val] of rawSlots) {
|
|
1243
|
+
s = s.replace(ph, val);
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
// Step 5: Restore \$ → $
|
|
1247
|
+
s = s.replace(/\x00DOLLAR\x00/g, "$");
|
|
1248
|
+
|
|
1249
|
+
// === v0.0.4: Warn about {identifier} patterns remaining after substitution ===
|
|
1250
|
+
const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
|
|
1251
|
+
let m: RegExpExecArray | null;
|
|
1252
|
+
while ((m = braceRe.exec(s)) !== null) {
|
|
1253
|
+
SinthWarning.emit(
|
|
1254
|
+
`Use $param for text interpolation. {param} is for attributes only. Found '${m[0]}' in text content.`
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
return s;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
function interpolateAttr(text: string, params: Map<string, string>): string {
|
|
1262
|
+
let s = text;
|
|
1263
|
+
s = s.replace(/\\\{/g, "\x00LB\x00");
|
|
1264
|
+
s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
|
|
1265
|
+
return s.replace(/\x00LB\x00/g, "{");
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
function renderChild(
|
|
1269
|
+
child: Child,
|
|
1270
|
+
ctx: CompileCtx,
|
|
1271
|
+
params: Map<string, string>,
|
|
1272
|
+
depth: number,
|
|
1273
|
+
): string {
|
|
1274
|
+
if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
|
|
1275
|
+
if (child.kind === "text") return renderText(child.value, params);
|
|
1276
|
+
return renderCompUse(child, ctx, params, depth);
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
function renderCompUse(
|
|
1280
|
+
use: CompUse,
|
|
1281
|
+
ctx: CompileCtx,
|
|
1282
|
+
params: Map<string, string>,
|
|
1283
|
+
depth: number,
|
|
1284
|
+
): string {
|
|
1285
|
+
// === v0.0.4: RawHTML — output content attribute verbatim, no wrapping tag, no scoping ===
|
|
1286
|
+
if (use.name === "RawHTML") {
|
|
1287
|
+
const ca = use.attrs.find(a => a.name === "content");
|
|
1288
|
+
if (!ca || !ca.value) return "";
|
|
1289
|
+
return interpolateAttr(litToString(ca.value), params);
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
// User-defined component
|
|
1293
|
+
const userDef = ctx.allDefs.get(use.name);
|
|
1294
|
+
if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
|
|
1295
|
+
|
|
1296
|
+
// Custom element
|
|
1297
|
+
const customEl = ctx.customEls.get(use.name);
|
|
1298
|
+
if (customEl) {
|
|
1299
|
+
const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
|
|
1300
|
+
for (const attr of use.attrs) {
|
|
1301
|
+
const r = renderAttr(attr, params);
|
|
1302
|
+
if (r) attrParts.push(r);
|
|
1303
|
+
}
|
|
1304
|
+
const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
1305
|
+
const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
1306
|
+
return `<${customEl.tagName}${attrStr}>${inner}</${customEl.tagName}>`;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// Built-in component
|
|
1310
|
+
const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
|
|
1311
|
+
const isVoid = voidEl || VOID_TAGS.has(tag);
|
|
1312
|
+
|
|
1313
|
+
const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
|
|
1314
|
+
let userClass: string | undefined;
|
|
1315
|
+
|
|
1316
|
+
for (const attr of use.attrs) {
|
|
1317
|
+
if (attr.name === "level" && use.name === "Heading") continue; // consumed by tag resolution
|
|
1318
|
+
if (attr.name === "class") {
|
|
1319
|
+
if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
|
|
1320
|
+
continue;
|
|
1321
|
+
}
|
|
1322
|
+
const rendered = renderAttr(attr, params);
|
|
1323
|
+
if (rendered) attrParts.push(rendered);
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
// Merge default class with user-supplied class
|
|
1327
|
+
const classes = [defaultClass, userClass].filter(Boolean).join(" ");
|
|
1328
|
+
if (classes) attrParts.push(`class="${escAttr(classes)}"`);
|
|
1329
|
+
|
|
1330
|
+
// === v0.0.4: Default type="button" for <button> elements ===
|
|
1331
|
+
if (tag === "button" && !use.attrs.some(a => a.name === "type")) {
|
|
1332
|
+
attrParts.push(`type="button"`);
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
1336
|
+
|
|
1337
|
+
if (isVoid) {
|
|
1338
|
+
if (use.children.length > 0) {
|
|
1339
|
+
SinthWarning.emit(`<${tag}> is a void element and cannot have children.`, use.loc);
|
|
1340
|
+
}
|
|
1341
|
+
return `<${tag}${attrStr}>`;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
1345
|
+
return `<${tag}${attrStr}>${inner}</${tag}>`;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
function expandUserComp(
|
|
1349
|
+
use: CompUse,
|
|
1350
|
+
def: CompDef,
|
|
1351
|
+
ctx: CompileCtx,
|
|
1352
|
+
params: Map<string, string>,
|
|
1353
|
+
depth: number,
|
|
1354
|
+
): string {
|
|
1355
|
+
// Recursion check
|
|
1356
|
+
if (use.name === def.name && depth > 1) {
|
|
1357
|
+
throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// Build local parameter map
|
|
1361
|
+
const local = new Map<string, string>();
|
|
1362
|
+
|
|
1363
|
+
// Apply defaults first
|
|
1364
|
+
for (const p of def.params) {
|
|
1365
|
+
if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
// Apply caller-supplied attributes
|
|
1369
|
+
for (const attr of use.attrs) {
|
|
1370
|
+
if (attr.value === null) {
|
|
1371
|
+
local.set(attr.name, "true");
|
|
1372
|
+
} else if (attr.value.kind !== "null") {
|
|
1373
|
+
const raw = litToString(attr.value);
|
|
1374
|
+
local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// Validate required parameters
|
|
1379
|
+
for (const p of def.params) {
|
|
1380
|
+
if (!local.has(p.name)) {
|
|
1381
|
+
throw new SinthError(
|
|
1382
|
+
`Component '${def.name}' requires parameter '${p.name}' but it was not provided.`,
|
|
1383
|
+
use.loc,
|
|
1384
|
+
);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// Render slot: children at the call site
|
|
1389
|
+
const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
1390
|
+
local.set("slot", slotHTML);
|
|
1391
|
+
|
|
1392
|
+
// === v0.0.4: Process component style blocks with instance params and push to extraCSS ===
|
|
1393
|
+
for (const block of def.styles) {
|
|
1394
|
+
ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// ═══════════════════════════════════════════════════════════
|
|
1401
|
+
// SECTION 9: SCRIPT COLLECTOR
|
|
1402
|
+
// ═══════════════════════════════════════════════════════════
|
|
1403
|
+
|
|
1404
|
+
function collectScripts(
|
|
1405
|
+
file: SinthFile,
|
|
1406
|
+
allDefs: Map<string, CompDef>,
|
|
1407
|
+
): { componentScripts: string[]; pageScripts: { raw: string; attrs: Record<string, string> }[] } {
|
|
1408
|
+
const componentScripts: string[] = [];
|
|
1409
|
+
const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
|
|
1410
|
+
const seenFunctions = new Set<string>();
|
|
1411
|
+
|
|
1412
|
+
// Component script blocks → hoisted as IIFEs
|
|
1413
|
+
for (const [, def] of allDefs) {
|
|
1414
|
+
for (const block of def.scripts) {
|
|
1415
|
+
for (const fn of extractFunctionNames(block.raw)) {
|
|
1416
|
+
if (seenFunctions.has(fn)) {
|
|
1417
|
+
throw new SinthError(`Function '${fn}' defined in multiple component script blocks.`);
|
|
1418
|
+
}
|
|
1419
|
+
seenFunctions.add(fn);
|
|
1420
|
+
}
|
|
1421
|
+
componentScripts.push(`(function(){\n${block.raw}\n})();`);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
// Page-level script blocks
|
|
1426
|
+
for (const block of file.scripts) {
|
|
1427
|
+
for (const fn of extractFunctionNames(block.raw)) {
|
|
1428
|
+
if (seenFunctions.has(fn)) {
|
|
1429
|
+
throw new SinthError(`Function '${fn}' conflicts with a component script.`);
|
|
1430
|
+
}
|
|
1431
|
+
seenFunctions.add(fn);
|
|
1432
|
+
}
|
|
1433
|
+
pageScripts.push({ raw: block.raw, attrs: block.attrs });
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
return { componentScripts, pageScripts };
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
function extractFunctionNames(js: string): string[] {
|
|
1440
|
+
const names: string[] = [];
|
|
1441
|
+
const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
|
|
1442
|
+
let m: RegExpExecArray | null;
|
|
1443
|
+
while ((m = re.exec(js)) !== null) names.push(m[1]);
|
|
1444
|
+
return names;
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
// ═══════════════════════════════════════════════════════════
|
|
1448
|
+
// SECTION 10: HEAD GENERATOR
|
|
1449
|
+
// ═══════════════════════════════════════════════════════════
|
|
1450
|
+
|
|
1451
|
+
interface HeadData {
|
|
1452
|
+
title?: string; fav?: string;
|
|
1453
|
+
lang: string; charset: string; viewport: string;
|
|
1454
|
+
metaTags: { name: string; content: string }[];
|
|
1455
|
+
metaProps: { property: string; content: string }[];
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
1459
|
+
let title: string | undefined, fav: string | undefined;
|
|
1460
|
+
let lang = "en";
|
|
1461
|
+
let charset = "UTF-8";
|
|
1462
|
+
let viewport = "width=device-width, initial-scale=1.0";
|
|
1463
|
+
const metaTags: { name: string; content: string }[] = [];
|
|
1464
|
+
const metaProps: { property: string; content: string }[] = [];
|
|
1465
|
+
|
|
1466
|
+
for (const m of meta) {
|
|
1467
|
+
const val = litToString(m.value);
|
|
1468
|
+
switch (m.key) {
|
|
1469
|
+
case "title": title = val; break;
|
|
1470
|
+
case "fav": fav = val; break;
|
|
1471
|
+
case "lang": lang = val; break;
|
|
1472
|
+
case "charset": charset = val; break;
|
|
1473
|
+
case "viewport": viewport = val; break;
|
|
1474
|
+
case "descr": metaTags.push({ name: "description", content: val }); break;
|
|
1475
|
+
case "author": metaTags.push({ name: "author", content: val }); break;
|
|
1476
|
+
case "keywords": metaTags.push({ name: "keywords", content: val }); break;
|
|
1477
|
+
case "robots": metaTags.push({ name: "robots", content: val }); break;
|
|
1478
|
+
default:
|
|
1479
|
+
if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
|
|
1480
|
+
const prop = m.key
|
|
1481
|
+
.replace(/^og([A-Z])/, (_, c: string) => `og:${c.toLowerCase()}`)
|
|
1482
|
+
.replace(/^twitter([A-Z])/, (_, c: string) => `twitter:${c.toLowerCase()}`);
|
|
1483
|
+
metaProps.push({ property: prop, content: val });
|
|
1484
|
+
} else {
|
|
1485
|
+
metaTags.push({ name: camelToKebab(m.key), content: val });
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
return { title, fav, lang, charset, viewport, metaTags, metaProps };
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
// === v0.0.4: .jpg and .jpeg return "image/jpeg" ===
|
|
1494
|
+
function faviconType(p: string): string {
|
|
1495
|
+
const ext = path.extname(p).toLowerCase();
|
|
1496
|
+
switch (ext) {
|
|
1497
|
+
case ".ico": return "image/x-icon";
|
|
1498
|
+
case ".png": return "image/png";
|
|
1499
|
+
case ".svg": return "image/svg+xml";
|
|
1500
|
+
case ".gif": return "image/gif";
|
|
1501
|
+
case ".webp": return "image/webp";
|
|
1502
|
+
case ".jpg":
|
|
1503
|
+
case ".jpeg": return "image/jpeg";
|
|
1504
|
+
default:
|
|
1505
|
+
SinthWarning.emit(`Unknown favicon extension '${ext}', defaulting to image/x-icon`);
|
|
1506
|
+
return "image/x-icon";
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
function renderHead(
|
|
1511
|
+
hd: HeadData,
|
|
1512
|
+
cssLinks: string[],
|
|
1513
|
+
jsLinks: { src: string; attrs: Record<string, string> }[],
|
|
1514
|
+
scopedCSS: string,
|
|
1515
|
+
companionJS: string | undefined,
|
|
1516
|
+
): string {
|
|
1517
|
+
const lines: string[] = [];
|
|
1518
|
+
lines.push(` <meta charset="${escAttr(hd.charset)}">`);
|
|
1519
|
+
lines.push(` <meta name="viewport" content="${escAttr(hd.viewport)}">`);
|
|
1520
|
+
if (hd.title) lines.push(` <title>${esc(hd.title)}</title>`);
|
|
1521
|
+
if (hd.fav) lines.push(` <link rel="icon" href="${escAttr(hd.fav)}" type="${faviconType(hd.fav)}">`);
|
|
1522
|
+
for (const m of hd.metaTags) lines.push(` <meta name="${escAttr(m.name)}" content="${escAttr(m.content)}">`);
|
|
1523
|
+
for (const m of hd.metaProps) lines.push(` <meta property="${escAttr(m.property)}" content="${escAttr(m.content)}">`);
|
|
1524
|
+
for (const css of cssLinks) lines.push(` <link rel="stylesheet" href="${escAttr(css)}">`);
|
|
1525
|
+
if (scopedCSS.trim()) lines.push(` <style>\n${scopedCSS}\n </style>`);
|
|
1526
|
+
for (const js of jsLinks) {
|
|
1527
|
+
const extra = Object.entries(js.attrs)
|
|
1528
|
+
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
1529
|
+
.join(" ");
|
|
1530
|
+
lines.push(` <script src="${escAttr(js.src)}"${extra ? " " + extra : ""}></script>`);
|
|
1531
|
+
}
|
|
1532
|
+
if (companionJS) lines.push(` <script src="${escAttr(companionJS)}"></script>`);
|
|
1533
|
+
return `<head>\n${lines.join("\n")}\n</head>`;
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
// ═══════════════════════════════════════════════════════════
|
|
1537
|
+
// SECTION 11: MAIN COMPILATION PIPELINE
|
|
1538
|
+
// ═══════════════════════════════════════════════════════════
|
|
1539
|
+
|
|
1540
|
+
interface CompileOptions {
|
|
1541
|
+
projectRoot: string;
|
|
1542
|
+
outDir: string;
|
|
1543
|
+
libraryPaths: string[];
|
|
1544
|
+
minify: boolean;
|
|
1545
|
+
checkOnly: boolean;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
function compileFile(filePath: string, opts: CompileOptions): string | null {
|
|
1549
|
+
const absPath = path.resolve(filePath);
|
|
1550
|
+
const file = parseFile(absPath);
|
|
1551
|
+
|
|
1552
|
+
const cfg: ResolverConfig = { projectRoot: opts.projectRoot, libraryPaths: opts.libraryPaths };
|
|
1553
|
+
const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
|
|
1554
|
+
const hash = fnv1a(absPath);
|
|
1555
|
+
|
|
1556
|
+
// === v0.0.4: extraCSS collected during rendering (per-instance component styles) ===
|
|
1557
|
+
const ctx: CompileCtx = {
|
|
1558
|
+
allDefs, customEls, cssLinks, jsLinks,
|
|
1559
|
+
scopeHash: hash, pageFile: absPath, extraCSS: [],
|
|
1560
|
+
};
|
|
1561
|
+
|
|
1562
|
+
if (!file.isPage) {
|
|
1563
|
+
// Component file → fragment only
|
|
1564
|
+
const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
1565
|
+
const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
|
|
1566
|
+
const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
|
|
1567
|
+
return `${body}\n<style>\n${allCSS}\n</style>`;
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
const headData = buildHeadData(file.meta);
|
|
1571
|
+
|
|
1572
|
+
// Render body HTML first (populates ctx.extraCSS from expandUserComp)
|
|
1573
|
+
const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
1574
|
+
|
|
1575
|
+
// Page-level style blocks (no component params)
|
|
1576
|
+
const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
|
|
1577
|
+
const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
|
|
1578
|
+
|
|
1579
|
+
const { componentScripts, pageScripts } = collectScripts(file, allDefs);
|
|
1580
|
+
|
|
1581
|
+
const companionJS = (() => {
|
|
1582
|
+
const base = absPath.replace(/\.sinth$/, ".js");
|
|
1583
|
+
return fs.existsSync(base) ? path.basename(base) : undefined;
|
|
1584
|
+
})();
|
|
1585
|
+
|
|
1586
|
+
const head = renderHead(headData, cssLinks, jsLinks, scopedCSS, companionJS);
|
|
1587
|
+
const scriptTags: string[] = [];
|
|
1588
|
+
|
|
1589
|
+
if (componentScripts.length > 0) {
|
|
1590
|
+
scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
|
|
1591
|
+
}
|
|
1592
|
+
for (const s of pageScripts) {
|
|
1593
|
+
const extra = Object.entries(s.attrs)
|
|
1594
|
+
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
1595
|
+
.join(" ");
|
|
1596
|
+
scriptTags.push(`<script${extra ? " " + extra : ""}>\n${s.raw}\n</script>`);
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
const html = [
|
|
1600
|
+
"<!DOCTYPE html>",
|
|
1601
|
+
`<html lang="${escAttr(headData.lang)}">`,
|
|
1602
|
+
head,
|
|
1603
|
+
`<body data-s="${hash}">`,
|
|
1604
|
+
bodyHTML,
|
|
1605
|
+
scriptTags.join("\n"),
|
|
1606
|
+
"</body>",
|
|
1607
|
+
"</html>",
|
|
1608
|
+
].join("\n");
|
|
1609
|
+
|
|
1610
|
+
return opts.minify ? minifyHTML(html) : html;
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
function minifyHTML(html: string): string {
|
|
1614
|
+
return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
// ═══════════════════════════════════════════════════════════
|
|
1618
|
+
// SECTION 12: FILE DISCOVERY & ASSET COPY
|
|
1619
|
+
// ═══════════════════════════════════════════════════════════
|
|
1620
|
+
|
|
1621
|
+
// === v0.0.4: findSinthPages skips outDir to prevent infinite watcher loops ===
|
|
1622
|
+
function findSinthPages(dir: string, outDir?: string): string[] {
|
|
1623
|
+
const results: string[] = [];
|
|
1624
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
1625
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
1626
|
+
const full = path.join(dir, entry.name);
|
|
1627
|
+
if (outDir && path.resolve(full) === path.resolve(outDir)) continue;
|
|
1628
|
+
if (entry.isDirectory()) {
|
|
1629
|
+
results.push(...findSinthPages(full, outDir));
|
|
1630
|
+
} else if (entry.name.endsWith(".sinth")) {
|
|
1631
|
+
results.push(full);
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
return results;
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
// === v0.0.4: Recursive directory copy for assets/ ===
|
|
1638
|
+
function copyDir(src: string, dest: string): void {
|
|
1639
|
+
if (!fs.existsSync(src)) return;
|
|
1640
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
1641
|
+
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
|
1642
|
+
const sp = path.join(src, entry.name);
|
|
1643
|
+
const dp = path.join(dest, entry.name);
|
|
1644
|
+
if (entry.isDirectory()) copyDir(sp, dp);
|
|
1645
|
+
else fs.copyFileSync(sp, dp);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
// ═══════════════════════════════════════════════════════════
|
|
1650
|
+
// SECTION 13: DEV SERVER
|
|
1651
|
+
// ═══════════════════════════════════════════════════════════
|
|
1652
|
+
|
|
1653
|
+
const LIVE_RELOAD_SCRIPT = `<script>
|
|
1654
|
+
(function(){
|
|
1655
|
+
const es = new EventSource('/__sinth_sse__');
|
|
1656
|
+
es.onmessage = () => location.reload();
|
|
1657
|
+
es.onerror = () => setTimeout(() => location.reload(), 1000);
|
|
1658
|
+
})();
|
|
1659
|
+
</script>`;
|
|
1660
|
+
|
|
1661
|
+
async function startDevServer(opts: CompileOptions & { port: number }) {
|
|
1662
|
+
const clients: http.ServerResponse[] = [];
|
|
1663
|
+
let debounce: ReturnType<typeof setTimeout> | null = null;
|
|
1664
|
+
const cache = new Map<string, string>();
|
|
1665
|
+
|
|
1666
|
+
function notify(): void {
|
|
1667
|
+
for (const c of clients) { try { c.write("data: reload\n\n"); } catch {} }
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
function compileAll(): void {
|
|
1671
|
+
cache.clear();
|
|
1672
|
+
const pages = findSinthPages(opts.projectRoot, opts.outDir);
|
|
1673
|
+
for (const p of pages) {
|
|
1674
|
+
try {
|
|
1675
|
+
const html = compileFile(p, { ...opts, checkOnly: false });
|
|
1676
|
+
if (!html) continue;
|
|
1677
|
+
const rel = path.relative(opts.projectRoot, p)
|
|
1678
|
+
.replace(/\.sinth$/, ".html")
|
|
1679
|
+
.replace(/\\/g, "/");
|
|
1680
|
+
const url = "/" + rel;
|
|
1681
|
+
cache.set(url, html + LIVE_RELOAD_SCRIPT);
|
|
1682
|
+
// Also map root URL to index.html
|
|
1683
|
+
if (rel === "index.html" || rel.endsWith("/index.html")) {
|
|
1684
|
+
cache.set("/", html + LIVE_RELOAD_SCRIPT);
|
|
1685
|
+
}
|
|
1686
|
+
} catch (e: unknown) {
|
|
1687
|
+
process.stderr.write(`\x1b[31m${(e as Error).message}\x1b[0m\n`);
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
compileAll();
|
|
1693
|
+
|
|
1694
|
+
// === v0.0.4: Watch ignores changes whose absolute path is inside outDir ===
|
|
1695
|
+
const resolvedOut = path.resolve(opts.outDir);
|
|
1696
|
+
try {
|
|
1697
|
+
fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
|
|
1698
|
+
if (!filename) return;
|
|
1699
|
+
const abs = path.resolve(opts.projectRoot, filename);
|
|
1700
|
+
// Skip events from inside the output directory to prevent infinite loops
|
|
1701
|
+
if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut) return;
|
|
1702
|
+
if (debounce) clearTimeout(debounce);
|
|
1703
|
+
debounce = setTimeout(() => { compileAll(); notify(); }, 80);
|
|
1704
|
+
});
|
|
1705
|
+
} catch {}
|
|
1706
|
+
|
|
1707
|
+
const EXT_TYPES: Record<string, string> = {
|
|
1708
|
+
".css": "text/css", ".js": "application/javascript",
|
|
1709
|
+
".png": "image/png", ".svg": "image/svg+xml",
|
|
1710
|
+
".ico": "image/x-icon",
|
|
1711
|
+
".jpg": "image/jpeg", ".jpeg": "image/jpeg",
|
|
1712
|
+
".gif": "image/gif", ".webp": "image/webp",
|
|
1713
|
+
".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf",
|
|
1714
|
+
".json": "application/json", ".xml": "application/xml",
|
|
1715
|
+
};
|
|
1716
|
+
|
|
1717
|
+
const server = http.createServer((req, res) => {
|
|
1718
|
+
const reqUrl = (req.url ?? "/").split("?")[0];
|
|
1719
|
+
|
|
1720
|
+
// SSE endpoint for live reload
|
|
1721
|
+
if (reqUrl === "/__sinth_sse__") {
|
|
1722
|
+
res.writeHead(200, {
|
|
1723
|
+
"Content-Type": "text/event-stream",
|
|
1724
|
+
"Cache-Control": "no-cache",
|
|
1725
|
+
"Connection": "keep-alive",
|
|
1726
|
+
});
|
|
1727
|
+
clients.push(res);
|
|
1728
|
+
req.on("close", () => {
|
|
1729
|
+
const i = clients.indexOf(res);
|
|
1730
|
+
if (i !== -1) clients.splice(i, 1);
|
|
1731
|
+
});
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
// Serve cached compiled HTML
|
|
1736
|
+
const cached = cache.get(reqUrl) ??
|
|
1737
|
+
cache.get(reqUrl.endsWith("/") ? reqUrl + "index.html" : reqUrl + ".html");
|
|
1738
|
+
if (cached) {
|
|
1739
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
1740
|
+
res.end(cached);
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
|
|
1744
|
+
// Serve static files (assets, CSS, fonts, etc.)
|
|
1745
|
+
let filePath = path.join(opts.projectRoot, reqUrl);
|
|
1746
|
+
if (reqUrl.endsWith("/")) filePath = path.join(filePath, "index.html");
|
|
1747
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
|
|
1748
|
+
const ctype = EXT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
|
|
1749
|
+
res.writeHead(200, { "Content-Type": ctype });
|
|
1750
|
+
res.end(fs.readFileSync(filePath));
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
1755
|
+
res.end("404 Not Found");
|
|
1756
|
+
});
|
|
1757
|
+
|
|
1758
|
+
server.listen(opts.port, () => {
|
|
1759
|
+
process.stdout.write(
|
|
1760
|
+
`\x1b[32m[sinth dev]\x1b[0m Serving at \x1b[4mhttp://localhost:${opts.port}\x1b[0m\n`
|
|
1761
|
+
);
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
// ═══════════════════════════════════════════════════════════
|
|
1766
|
+
// SECTION 14: CLI ENTRY POINT
|
|
1767
|
+
// ═══════════════════════════════════════════════════════════
|
|
1768
|
+
|
|
1769
|
+
function loadConfig(root: string): Record<string, unknown> {
|
|
1770
|
+
const cfgPath = path.join(root, "sinth.config.json");
|
|
1771
|
+
if (fs.existsSync(cfgPath)) {
|
|
1772
|
+
try { return JSON.parse(fs.readFileSync(cfgPath, "utf-8")) as Record<string, unknown>; }
|
|
1773
|
+
catch { SinthWarning.emit("Could not parse sinth.config.json"); }
|
|
1774
|
+
}
|
|
1775
|
+
return {};
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
async function main(): Promise<void> {
|
|
1779
|
+
const [,, command, ...args] = process.argv;
|
|
1780
|
+
const cwd = process.cwd();
|
|
1781
|
+
const cfg = loadConfig(cwd);
|
|
1782
|
+
|
|
1783
|
+
const outDirIdx = args.indexOf("--out");
|
|
1784
|
+
const outDir = outDirIdx !== -1 ? args[outDirIdx + 1] : (cfg.outDir as string | undefined) ?? path.join(cwd, "dist");
|
|
1785
|
+
const portIdx = args.indexOf("--port");
|
|
1786
|
+
const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : (cfg.port as number | undefined) ?? 3000;
|
|
1787
|
+
const minify = args.includes("--prod") || Boolean(cfg.minify);
|
|
1788
|
+
const libraryPaths = (cfg.libraryPaths as string[] | undefined) ?? [path.join(cwd, "libraries")];
|
|
1789
|
+
|
|
1790
|
+
const opts: CompileOptions = { projectRoot: cwd, outDir, libraryPaths, minify, checkOnly: false };
|
|
1791
|
+
|
|
1792
|
+
switch (command) {
|
|
1793
|
+
case "build": {
|
|
1794
|
+
const pages = findSinthPages(cwd, outDir);
|
|
1795
|
+
let hadError = false, built = 0;
|
|
1796
|
+
|
|
1797
|
+
for (const p of pages) {
|
|
1798
|
+
try {
|
|
1799
|
+
const html = compileFile(p, opts);
|
|
1800
|
+
if (!html) continue;
|
|
1801
|
+
const rel = path.relative(cwd, p).replace(/\.sinth$/, ".html");
|
|
1802
|
+
const out = path.join(outDir, rel);
|
|
1803
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
1804
|
+
fs.writeFileSync(out, html);
|
|
1805
|
+
process.stdout.write(` \x1b[32m✓\x1b[0m ${rel}\n`);
|
|
1806
|
+
built++;
|
|
1807
|
+
} catch (e: unknown) {
|
|
1808
|
+
process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${(e as Error).message}\n`);
|
|
1809
|
+
hadError = true;
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
// === v0.0.4: Copy assets/ to outDir/assets/ ===
|
|
1814
|
+
const assetsIn = path.join(cwd, "assets");
|
|
1815
|
+
const assetsOut = path.join(outDir, "assets");
|
|
1816
|
+
if (fs.existsSync(assetsIn)) {
|
|
1817
|
+
copyDir(assetsIn, assetsOut);
|
|
1818
|
+
process.stdout.write(` \x1b[32m✓\x1b[0m assets/ → ${path.relative(cwd, assetsOut)}/\n`);
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
process.stdout.write(`\n\x1b[1mBuilt ${built} page(s)\x1b[0m${hadError ? " with errors" : ""}\n`);
|
|
1822
|
+
process.exit(hadError ? 1 : 0);
|
|
1823
|
+
break;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
case "dev": {
|
|
1827
|
+
await startDevServer({ ...opts, port });
|
|
1828
|
+
break;
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
case "check": {
|
|
1832
|
+
opts.checkOnly = true;
|
|
1833
|
+
const pages = findSinthPages(cwd, outDir);
|
|
1834
|
+
let hadError = false;
|
|
1835
|
+
for (const p of pages) {
|
|
1836
|
+
try {
|
|
1837
|
+
compileFile(p, opts);
|
|
1838
|
+
process.stdout.write(` \x1b[32m✓\x1b[0m ${path.relative(cwd, p)}\n`);
|
|
1839
|
+
} catch (e: unknown) {
|
|
1840
|
+
process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${(e as Error).message}\n`);
|
|
1841
|
+
hadError = true;
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
process.exit(hadError ? 1 : 0);
|
|
1845
|
+
break;
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
// === v0.0.4: sinth version command ===
|
|
1849
|
+
case "version":
|
|
1850
|
+
case "--version":
|
|
1851
|
+
case "-v": {
|
|
1852
|
+
process.stdout.write("Sinth Compiler v0.0.4\n");
|
|
1853
|
+
break;
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
case "init": {
|
|
1857
|
+
const projectName = args[0] || "my-sinth-project";
|
|
1858
|
+
const projectDir = path.resolve(cwd, projectName);
|
|
1859
|
+
scaffoldProject(projectDir);
|
|
1860
|
+
break;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
default: {
|
|
1864
|
+
process.stdout.write(`
|
|
1865
|
+
\x1b[1mSinth Compiler v0.0.4\x1b[0m
|
|
1866
|
+
|
|
1867
|
+
\x1b[1mCommands:\x1b[0m
|
|
1868
|
+
sinth build [--out ./dist] [--prod] Compile all .sinth pages + copy assets/
|
|
1869
|
+
sinth dev [--port 3000] Start dev server with live reload
|
|
1870
|
+
sinth check Lint without emitting files
|
|
1871
|
+
sinth init Scaffold a new project
|
|
1872
|
+
sinth version Print version
|
|
1873
|
+
|
|
1874
|
+
\x1b[1mConfig:\x1b[0m sinth.config.json
|
|
1875
|
+
{ "outDir": "./dist", "libraryPaths": ["./libraries"], "minify": false }
|
|
1876
|
+
`);
|
|
1877
|
+
break;
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// ── Project scaffolding ───────────────────────────────────────────────────────
|
|
1883
|
+
|
|
1884
|
+
function scaffoldProject(root: string): void {
|
|
1885
|
+
for (const d of ["pages", "components", "styles", "libraries", "assets"]) {
|
|
1886
|
+
fs.mkdirSync(path.join(root, d), { recursive: true });
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
// Main page
|
|
1890
|
+
fs.writeFileSync(path.join(root, "pages", "index.sinth"), `-- My Sinth Site
|
|
1891
|
+
|
|
1892
|
+
page
|
|
1893
|
+
|
|
1894
|
+
import "../components/Navbar.sinth"
|
|
1895
|
+
import css "../styles/reset.css"
|
|
1896
|
+
|
|
1897
|
+
title = "My Site"
|
|
1898
|
+
fav = "assets/favicon.ico"
|
|
1899
|
+
descr = "Built with Sinth."
|
|
1900
|
+
|
|
1901
|
+
Navbar
|
|
1902
|
+
|
|
1903
|
+
Hero {
|
|
1904
|
+
Heading(level: 1) { "Welcome to Sinth" }
|
|
1905
|
+
Paragraph { "A declarative, component-based web UI language." }
|
|
1906
|
+
Button(onClick: "handleCTA") { "Get Started" }
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
Main {
|
|
1910
|
+
Section {
|
|
1911
|
+
Heading(level: 2) { "Features" }
|
|
1912
|
+
CardGrid {
|
|
1913
|
+
-- Add cards here
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
style {
|
|
1919
|
+
Hero {
|
|
1920
|
+
padding: "4rem 2rem"
|
|
1921
|
+
textAlign: "center"
|
|
1922
|
+
backgroundColor: "#f0f4ff"
|
|
1923
|
+
}
|
|
1924
|
+
Main {
|
|
1925
|
+
maxWidth: "1100px"
|
|
1926
|
+
margin: "0 auto"
|
|
1927
|
+
padding: "2rem"
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
script {
|
|
1932
|
+
function handleCTA() {
|
|
1933
|
+
alert("Hello from Sinth!")
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
`);
|
|
1937
|
+
|
|
1938
|
+
// Navbar component
|
|
1939
|
+
fs.writeFileSync(path.join(root, "components", "Navbar.sinth"), `-- Navbar component
|
|
1940
|
+
|
|
1941
|
+
component Navbar {
|
|
1942
|
+
Header {
|
|
1943
|
+
Nav {
|
|
1944
|
+
Link(href: "/", class: "logo") { "MySite" }
|
|
1945
|
+
Div(class: "nav-links") {
|
|
1946
|
+
NavLink(href: "/") { "Home" }
|
|
1947
|
+
NavLink(href: "/about") { "About" }
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
style {
|
|
1953
|
+
Header {
|
|
1954
|
+
display: "flex"
|
|
1955
|
+
alignItems: "center"
|
|
1956
|
+
padding: "1rem 2rem"
|
|
1957
|
+
backgroundColor: "#1a1a2e"
|
|
1958
|
+
color: "white"
|
|
1959
|
+
}
|
|
1960
|
+
.logo {
|
|
1961
|
+
fontSize: "1.5rem"
|
|
1962
|
+
fontWeight: "700"
|
|
1963
|
+
color: "white"
|
|
1964
|
+
textDecoration: "none"
|
|
1965
|
+
}
|
|
1966
|
+
.nav-links {
|
|
1967
|
+
marginLeft: "auto"
|
|
1968
|
+
display: "flex"
|
|
1969
|
+
gap: "1.5rem"
|
|
1970
|
+
}
|
|
1971
|
+
.nav-links a {
|
|
1972
|
+
color: "rgba(255,255,255,0.8)"
|
|
1973
|
+
textDecoration: "none"
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
`);
|
|
1978
|
+
|
|
1979
|
+
// Card component
|
|
1980
|
+
fs.writeFileSync(path.join(root, "components", "Card.sinth"), `-- Card component
|
|
1981
|
+
|
|
1982
|
+
component Card(title, color = "blue") {
|
|
1983
|
+
Div(class: "card") {
|
|
1984
|
+
Heading(level: 2) { "$title" }
|
|
1985
|
+
Div(class: "card-body") { "$slot" }
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
style {
|
|
1989
|
+
.card {
|
|
1990
|
+
backgroundColor: "#f7f7f7"
|
|
1991
|
+
borderRadius: "1rem"
|
|
1992
|
+
padding: "1.5rem"
|
|
1993
|
+
textAlign: "center"
|
|
1994
|
+
marginBottom: "1rem"
|
|
1995
|
+
}
|
|
1996
|
+
.card-body {
|
|
1997
|
+
marginTop: "0.75rem"
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
`);
|
|
2002
|
+
|
|
2003
|
+
// Reset CSS
|
|
2004
|
+
fs.writeFileSync(
|
|
2005
|
+
path.join(root, "styles", "reset.css"),
|
|
2006
|
+
`*, *::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`,
|
|
2007
|
+
);
|
|
2008
|
+
|
|
2009
|
+
// sinth.config.json
|
|
2010
|
+
fs.writeFileSync(
|
|
2011
|
+
path.join(root, "sinth.config.json"),
|
|
2012
|
+
JSON.stringify({ outDir: "./dist", libraryPaths: ["./libraries"], minify: false }, null, 2),
|
|
2013
|
+
);
|
|
2014
|
+
|
|
2015
|
+
// .gitignore
|
|
2016
|
+
fs.writeFileSync(path.join(root, ".gitignore"), "dist/\nnode_modules/\n");
|
|
2017
|
+
|
|
2018
|
+
// package.json
|
|
2019
|
+
fs.writeFileSync(
|
|
2020
|
+
path.join(root, "package.json"),
|
|
2021
|
+
JSON.stringify({
|
|
2022
|
+
name: "my-sinth-site",
|
|
2023
|
+
version: "1.0.0",
|
|
2024
|
+
scripts: {
|
|
2025
|
+
build: "npx ts-node sinth.ts build",
|
|
2026
|
+
dev: "npx ts-node sinth.ts dev",
|
|
2027
|
+
},
|
|
2028
|
+
devDependencies: { "ts-node": "^10.0.0", typescript: "^5.0.0", sass: "^1.70.0" },
|
|
2029
|
+
}, null, 2),
|
|
2030
|
+
);
|
|
2031
|
+
|
|
2032
|
+
process.stdout.write(`
|
|
2033
|
+
\x1b[32m✓ Sinth project scaffolded!\x1b[0m
|
|
2034
|
+
|
|
2035
|
+
\x1b[1mNext steps:\x1b[0m
|
|
2036
|
+
npm install
|
|
2037
|
+
npx ts-node sinth.ts dev -- start dev server at http://localhost:3000
|
|
2038
|
+
npx ts-node sinth.ts build -- build to ./dist
|
|
2039
|
+
`);
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
// ── Entry point ──────────────────────────────────────────────────────────────
|
|
2043
|
+
main().catch(e => {
|
|
2044
|
+
process.stderr.write(`\x1b[31m${(e as Error).message}\x1b[0m\n`);
|
|
2045
|
+
process.exit(1);
|
|
2046
|
+
});
|