@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
|
@@ -0,0 +1,1585 @@
|
|
|
1
|
+
import * as path from "path";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, RemoveStmt, StyleBlock, CompDef, ParamDecl, VarDeclaration, SinthFile, CompileCtx, MixedBlockEntry, SinthError, SinthWarning, TT, AssignStmt, MetaEntry } from "./types.ts";import { Lexer } from "./lexer.ts";
|
|
4
|
+
import { Parser } from "./parser.ts";
|
|
5
|
+
import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal } from "../utils.ts";
|
|
6
|
+
import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
|
|
7
|
+
import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
export interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
|
|
13
|
+
|
|
14
|
+
export const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
15
|
+
// structural
|
|
16
|
+
Main: { tag: "main" },
|
|
17
|
+
Header: { tag: "header" },
|
|
18
|
+
Footer: { tag: "footer" },
|
|
19
|
+
Nav: { tag: "nav" },
|
|
20
|
+
Section: { tag: "section" },
|
|
21
|
+
Article: { tag: "article" },
|
|
22
|
+
Aside: { tag: "aside" },
|
|
23
|
+
Div: { tag: "div" },
|
|
24
|
+
Span: { tag: "span" },
|
|
25
|
+
Hero: { tag: "section", defaultClass: "hero" },
|
|
26
|
+
Container: { tag: "div", defaultClass: "container" },
|
|
27
|
+
Grid: { tag: "div", defaultClass: "grid" },
|
|
28
|
+
Flex: { tag: "div", defaultClass: "flex" },
|
|
29
|
+
Stack: { tag: "div", defaultClass: "stack" },
|
|
30
|
+
Row: { tag: "div", defaultClass: "row" },
|
|
31
|
+
Column: { tag: "div", defaultClass: "col" },
|
|
32
|
+
CardGrid: { tag: "div", defaultClass: "card-grid" },
|
|
33
|
+
// typography
|
|
34
|
+
Heading: { tag: "h1" },
|
|
35
|
+
SubHeading: { tag: "p", defaultClass: "subheading" },
|
|
36
|
+
Paragraph: { tag: "p" },
|
|
37
|
+
Lead: { tag: "p", defaultClass: "lead" },
|
|
38
|
+
Small: { tag: "small" },
|
|
39
|
+
Strong: { tag: "strong" },
|
|
40
|
+
Em: { tag: "em" },
|
|
41
|
+
Code: { tag: "code" },
|
|
42
|
+
Pre: { tag: "pre" },
|
|
43
|
+
Blockquote: { tag: "blockquote" },
|
|
44
|
+
Mark: { tag: "mark" },
|
|
45
|
+
Label: { tag: "label" },
|
|
46
|
+
Abbr: { tag: "abbr" },
|
|
47
|
+
Del: { tag: "del" },
|
|
48
|
+
Ins: { tag: "ins" },
|
|
49
|
+
Sub: { tag: "sub" },
|
|
50
|
+
Sup: { tag: "sup" },
|
|
51
|
+
Data: { tag: "data" },
|
|
52
|
+
Time: { tag: "time" },
|
|
53
|
+
Bdi: { tag: "bdi" },
|
|
54
|
+
Bdo: { tag: "bdo" },
|
|
55
|
+
Cite: { tag: "cite" },
|
|
56
|
+
Dfn: { tag: "dfn" },
|
|
57
|
+
Kbd: { tag: "kbd" },
|
|
58
|
+
Samp: { tag: "samp" },
|
|
59
|
+
Var: { tag: "var" },
|
|
60
|
+
Address: { tag: "address" },
|
|
61
|
+
Ruby: { tag: "ruby" },
|
|
62
|
+
Rt: { tag: "rt" },
|
|
63
|
+
Rp: { tag: "rp" },
|
|
64
|
+
// interactive
|
|
65
|
+
Button: { tag: "button" },
|
|
66
|
+
Link: { tag: "a" },
|
|
67
|
+
NavLink: { tag: "a" },
|
|
68
|
+
Select: { tag: "select" },
|
|
69
|
+
Form: { tag: "form" },
|
|
70
|
+
Fieldset: { tag: "fieldset" },
|
|
71
|
+
Legend: { tag: "legend" },
|
|
72
|
+
Details: { tag: "details" },
|
|
73
|
+
Summary: { tag: "summary" },
|
|
74
|
+
Dialog: { tag: "dialog" },
|
|
75
|
+
Textarea: { tag: "textarea" },
|
|
76
|
+
Datalist: { tag: "datalist" },
|
|
77
|
+
Optgroup: { tag: "optgroup" },
|
|
78
|
+
Option: { tag: "option" },
|
|
79
|
+
Progress: { tag: "progress" },
|
|
80
|
+
Meter: { tag: "meter" },
|
|
81
|
+
Output: { tag: "output" },
|
|
82
|
+
Map: { tag: "map" },
|
|
83
|
+
// media
|
|
84
|
+
Picture: { tag: "picture" },
|
|
85
|
+
Video: { tag: "video" },
|
|
86
|
+
Audio: { tag: "audio" },
|
|
87
|
+
Figure: { tag: "figure" },
|
|
88
|
+
Figcaption: { tag: "figcaption" },
|
|
89
|
+
Canvas: { tag: "canvas" },
|
|
90
|
+
Svg: { tag: "svg" },
|
|
91
|
+
IFrame: { tag: "iframe" },
|
|
92
|
+
Object: { tag: "object" },
|
|
93
|
+
// void elements
|
|
94
|
+
Img: { tag: "img", voidEl: true },
|
|
95
|
+
Logo: { tag: "img", voidEl: true },
|
|
96
|
+
Input: { tag: "input", voidEl: true },
|
|
97
|
+
Checkbox: { tag: "input", voidEl: true },
|
|
98
|
+
Hr: { tag: "hr", voidEl: true },
|
|
99
|
+
Br: { tag: "br", voidEl: true },
|
|
100
|
+
Wbr: { tag: "wbr", voidEl: true },
|
|
101
|
+
Source: { tag: "source", voidEl: true },
|
|
102
|
+
Embed: { tag: "embed", voidEl: true },
|
|
103
|
+
Col: { tag: "col", voidEl: true },
|
|
104
|
+
Area: { tag: "area", voidEl: true },
|
|
105
|
+
// lists
|
|
106
|
+
Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
|
|
107
|
+
Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
|
|
108
|
+
// tables
|
|
109
|
+
Table: { tag: "table" },
|
|
110
|
+
Caption: { tag: "caption" },
|
|
111
|
+
Thead: { tag: "thead" },
|
|
112
|
+
Tbody: { tag: "tbody" },
|
|
113
|
+
Tfoot: { tag: "tfoot" },
|
|
114
|
+
Tr: { tag: "tr" },
|
|
115
|
+
Th: { tag: "th" },
|
|
116
|
+
Td: { tag: "td" },
|
|
117
|
+
Colgroup: { tag: "colgroup" },
|
|
118
|
+
// utility
|
|
119
|
+
Template: { tag: "template" },
|
|
120
|
+
Slot: { tag: "slot" },
|
|
121
|
+
NoScript: { tag: "noscript" },
|
|
122
|
+
RawHTML: { tag: "__RAW__" },
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
export const VOID_TAGS = new Set([
|
|
126
|
+
"area","base","br","col","embed","hr","img","input",
|
|
127
|
+
"link","meta","param","source","track","wbr",
|
|
128
|
+
]);
|
|
129
|
+
|
|
130
|
+
const EVENT_RE = /^on[A-Z]/;
|
|
131
|
+
function eventAttrName(name: string): string | null {
|
|
132
|
+
return EVENT_RE.test(name) ? name.toLowerCase() : null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// preprocessor
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* for who's reading this: This maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
|
|
139
|
+
* these are used inside component style blocks, for example: onHover { color: "blue" }
|
|
140
|
+
*/
|
|
141
|
+
export const SINTH_PSEUDO_CLASS: Record<string, string> = {
|
|
142
|
+
onHover: ":hover",
|
|
143
|
+
onFocus: ":focus",
|
|
144
|
+
onActive: ":active",
|
|
145
|
+
onVisited: ":visited",
|
|
146
|
+
onChecked: ":checked",
|
|
147
|
+
onDisabled: ":disabled",
|
|
148
|
+
onEnabled: ":enabled",
|
|
149
|
+
onRequired: ":required",
|
|
150
|
+
onOptional: ":optional",
|
|
151
|
+
onValid: ":valid",
|
|
152
|
+
onInvalid: ":invalid",
|
|
153
|
+
onPlaceholderShown:":placeholder-shown",
|
|
154
|
+
onFocusWithin: ":focus-within",
|
|
155
|
+
onFocusVisible: ":focus-visible",
|
|
156
|
+
onFirst: ":first-child",
|
|
157
|
+
onLast: ":last-child",
|
|
158
|
+
onFirstOfType: ":first-of-type",
|
|
159
|
+
onLastOfType: ":last-of-type",
|
|
160
|
+
onEmpty: ":empty",
|
|
161
|
+
onTarget: ":target",
|
|
162
|
+
onLink: ":link",
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
export const SINTH_PSEUDO_ELEMENT: Record<string, string> = {
|
|
166
|
+
before: "::before",
|
|
167
|
+
after: "::after",
|
|
168
|
+
placeholder: "::placeholder",
|
|
169
|
+
selection: "::selection",
|
|
170
|
+
firstLine: "::first-line",
|
|
171
|
+
firstLetter: "::first-letter",
|
|
172
|
+
marker: "::marker",
|
|
173
|
+
backdrop: "::backdrop",
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
export function sinthCompToSelector(name: string): string {
|
|
177
|
+
const info = BUILTIN_MAP[name];
|
|
178
|
+
if (!info) return name.toLowerCase();
|
|
179
|
+
if (info.defaultClass) {
|
|
180
|
+
const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
|
|
181
|
+
return `${info.tag}${classes}`;
|
|
182
|
+
}
|
|
183
|
+
return info.tag;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* supported conversions:
|
|
188
|
+
* - component names as selectors: `Paragraph { ... }` → `p { ... }`
|
|
189
|
+
* - pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
|
|
190
|
+
* - pseudo-element shorthands: `before { ... }` → `&::before { ... }`
|
|
191
|
+
* - media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
|
|
192
|
+
* - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
|
|
193
|
+
*/
|
|
194
|
+
export function preprocessSinthStyle(raw: string): string {
|
|
195
|
+
const lines = raw.split("\n");
|
|
196
|
+
const result: string[] = [];
|
|
197
|
+
|
|
198
|
+
for (const line of lines) {
|
|
199
|
+
const trimmed = line.trim();
|
|
200
|
+
const indent = line.match(/^(\s*)/)?.[1] ?? "";
|
|
201
|
+
|
|
202
|
+
if (!trimmed) { result.push(line); continue; }
|
|
203
|
+
|
|
204
|
+
if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) { continue; }
|
|
205
|
+
// Standard comments pass through
|
|
206
|
+
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
|
207
|
+
result.push(line); continue;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
|
|
211
|
+
if (mediaMatch) {
|
|
212
|
+
const params = parseSinthMediaParams(mediaMatch[1]);
|
|
213
|
+
result.push(`${indent}@media (${params}) {`);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
|
|
218
|
+
if (blockMatch) {
|
|
219
|
+
const keyword = blockMatch[1];
|
|
220
|
+
|
|
221
|
+
const pseudoCls = SINTH_PSEUDO_CLASS[keyword];
|
|
222
|
+
if (pseudoCls) {
|
|
223
|
+
result.push(`${indent}&${pseudoCls} {`);
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const pseudoEl = SINTH_PSEUDO_ELEMENT[keyword];
|
|
228
|
+
if (pseudoEl) {
|
|
229
|
+
result.push(`${indent}&${pseudoEl} {`);
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if (/^[A-Z]/.test(keyword) && BUILTIN_MAP[keyword]) {
|
|
234
|
+
result.push(`${indent}${sinthCompToSelector(keyword)} {`);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
|
|
240
|
+
if (varPropMatch) {
|
|
241
|
+
result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
result.push(line);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return result.join("\n");
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export function parseSinthMediaParams(params: string): string {
|
|
252
|
+
const parts = params.split(",").map(p => {
|
|
253
|
+
const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
|
|
254
|
+
if (!m) return p.trim();
|
|
255
|
+
return `${camelToKebab(m[1])}: ${m[2].trim()}`;
|
|
256
|
+
});
|
|
257
|
+
return parts.join(") and (");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// style processor
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
export function convertCSSProps(css: string): string {
|
|
264
|
+
return css.split("\n").map(line => {
|
|
265
|
+
const trimmed = line.trim();
|
|
266
|
+
if (!trimmed) return line;
|
|
267
|
+
if (trimmed === "}" || trimmed.startsWith("}")) return line;
|
|
268
|
+
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
|
|
269
|
+
if (trimmed.startsWith("@")) return line;
|
|
270
|
+
if (trimmed.includes("{")) return line;
|
|
271
|
+
|
|
272
|
+
const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
|
|
273
|
+
if (!m) return line;
|
|
274
|
+
|
|
275
|
+
const [, indent, rawProp, , rawVal] = m;
|
|
276
|
+
|
|
277
|
+
const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
|
|
278
|
+
const hasQuotedVal = /^["']/.test(rawVal.trim());
|
|
279
|
+
if (!hasCamelCase && !hasQuotedVal) return line;
|
|
280
|
+
|
|
281
|
+
let val = rawVal.trim();
|
|
282
|
+
if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
|
|
283
|
+
if ((val.startsWith('"') && val.endsWith('"')) ||
|
|
284
|
+
(val.startsWith("'") && val.endsWith("'"))) {
|
|
285
|
+
val = val.slice(1, -1);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return `${indent}${camelToKebab(rawProp)}: ${val};`;
|
|
289
|
+
}).join("\n");
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function processStyleBlock(
|
|
293
|
+
block: StyleBlock,
|
|
294
|
+
hash: string,
|
|
295
|
+
params: Map<string, string> = new Map(),
|
|
296
|
+
): string {
|
|
297
|
+
let raw = block.raw;
|
|
298
|
+
|
|
299
|
+
// 1. interpolate {param} placeholders
|
|
300
|
+
if (params.size > 0) raw = interpolateAttr(raw, params);
|
|
301
|
+
|
|
302
|
+
// 2. sinth style preprocessing
|
|
303
|
+
raw = preprocessSinthStyle(raw);
|
|
304
|
+
|
|
305
|
+
// 3. warn if & in plain CSS
|
|
306
|
+
if (block.lang === "css" && raw.includes("&")) {
|
|
307
|
+
SinthWarning.emit(
|
|
308
|
+
`'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
|
|
309
|
+
block.loc,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// 4. camelCase → kebab-case
|
|
314
|
+
let css = convertCSSProps(raw);
|
|
315
|
+
|
|
316
|
+
// 5. SCSS compilation
|
|
317
|
+
if (block.lang === "scss") {
|
|
318
|
+
try {
|
|
319
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
320
|
+
const sass: { compileString: (src: string) => { css: string } } = require("sass");
|
|
321
|
+
css = sass.compileString(css).css;
|
|
322
|
+
} catch (e: unknown) {
|
|
323
|
+
const err = e as { code?: string; message?: string };
|
|
324
|
+
if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
|
|
325
|
+
throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
|
|
326
|
+
}
|
|
327
|
+
throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 6. if target component given, wrap content in its CSS selector
|
|
332
|
+
if (block.target) {
|
|
333
|
+
const selector = sinthCompToSelector(block.target);
|
|
334
|
+
css = `${selector} {\n${css}\n}`;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// 7. scope (except it's global)
|
|
338
|
+
if (!block.global) css = scopeCSS(css, hash);
|
|
339
|
+
|
|
340
|
+
return css;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export function scopeCSS(css: string, hash: string): string {
|
|
344
|
+
return processRules(css, `[data-s="${hash}"]`);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function processRules(css: string, attr: string): string {
|
|
348
|
+
let out = "", i = 0;
|
|
349
|
+
|
|
350
|
+
while (i < css.length) {
|
|
351
|
+
if (/\s/.test(css[i])) { out += css[i++]; continue; }
|
|
352
|
+
|
|
353
|
+
if (css[i] === "/" && css[i + 1] === "*") {
|
|
354
|
+
const end = css.indexOf("*/", i + 2);
|
|
355
|
+
if (end === -1) { out += css.substring(i); break; }
|
|
356
|
+
out += css.substring(i, end + 2);
|
|
357
|
+
i = end + 2;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const braceIdx = findCSSBrace(css, i);
|
|
362
|
+
if (braceIdx === -1) { out += css.substring(i); break; }
|
|
363
|
+
|
|
364
|
+
const selector = css.substring(i, braceIdx).trim();
|
|
365
|
+
const { content, end } = extractCSSBlock(css, braceIdx);
|
|
366
|
+
|
|
367
|
+
if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
|
|
368
|
+
out += `${selector} {${content}}\n`;
|
|
369
|
+
} else if (/^@(media|supports|layer|container)/.test(selector)) {
|
|
370
|
+
out += `${selector} {\n${processRules(content, attr)}\n}\n`;
|
|
371
|
+
} else if (selector.startsWith("@")) {
|
|
372
|
+
out += `${selector} {${content}}\n`;
|
|
373
|
+
} else if (selector.length > 0) {
|
|
374
|
+
out += `${scopeSelectors(selector, attr)} {${content}}\n`;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
i = end;
|
|
378
|
+
}
|
|
379
|
+
return out;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export function scopeSelectors(selList: string, attr: string): string {
|
|
383
|
+
return selList
|
|
384
|
+
.split(",")
|
|
385
|
+
.map(s => {
|
|
386
|
+
s = s.trim();
|
|
387
|
+
if (!s) return "";
|
|
388
|
+
if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
|
|
389
|
+
const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
|
|
390
|
+
if (m && m[1].trim()) {
|
|
391
|
+
return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
|
|
392
|
+
}
|
|
393
|
+
return `${attr} ${s}, ${s}${attr}`;
|
|
394
|
+
})
|
|
395
|
+
.filter(Boolean)
|
|
396
|
+
.join(",\n");
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function findCSSBrace(css: string, from: number): number {
|
|
400
|
+
let i = from;
|
|
401
|
+
while (i < css.length) {
|
|
402
|
+
if (css[i] === '"' || css[i] === "'") {
|
|
403
|
+
const q = css[i++];
|
|
404
|
+
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
405
|
+
i++;
|
|
406
|
+
} else if (css[i] === "{") {
|
|
407
|
+
return i;
|
|
408
|
+
} else { i++; }
|
|
409
|
+
}
|
|
410
|
+
return -1;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export function extractCSSBlock(css: string, openBrace: number): { content: string; end: number } {
|
|
414
|
+
let i = openBrace + 1, depth = 1;
|
|
415
|
+
while (i < css.length && depth > 0) {
|
|
416
|
+
if (css[i] === '"' || css[i] === "'") {
|
|
417
|
+
const q = css[i++];
|
|
418
|
+
while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
|
|
419
|
+
i++;
|
|
420
|
+
} else if (css[i] === "/" && css[i + 1] === "*") {
|
|
421
|
+
i += 2;
|
|
422
|
+
while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/")) i++;
|
|
423
|
+
i += 2;
|
|
424
|
+
} else if (css[i] === "{") { depth++; i++; }
|
|
425
|
+
else if (css[i] === "}") { depth--; if (depth > 0) i++; else break; }
|
|
426
|
+
else { i++; }
|
|
427
|
+
}
|
|
428
|
+
return { content: css.substring(openBrace + 1, i), end: i + 1 };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
// the HTML generator
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* CSS property names that are allowed as inline style shorthand attributes on
|
|
440
|
+
* any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
|
|
441
|
+
*/
|
|
442
|
+
export const INLINE_STYLE_PROPS = new Set([
|
|
443
|
+
"color","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
|
|
444
|
+
"fontSize","fontWeight","fontFamily","fontStyle","fontVariant","lineHeight","letterSpacing","textAlign",
|
|
445
|
+
"textDecoration","textTransform","whiteSpace","wordBreak","wordWrap","textOverflow",
|
|
446
|
+
"margin","marginTop","marginBottom","marginLeft","marginRight",
|
|
447
|
+
"padding","paddingTop","paddingBottom","paddingLeft","paddingRight",
|
|
448
|
+
"width","height","minWidth","maxWidth","minHeight","maxHeight",
|
|
449
|
+
"display","flexDirection","flexWrap","flex","flexGrow","flexShrink","flexBasis",
|
|
450
|
+
"justifyContent","alignItems","alignContent","alignSelf","gap","rowGap","columnGap",
|
|
451
|
+
"gridTemplateColumns","gridTemplateRows","gridColumn","gridRow","gridArea",
|
|
452
|
+
"position","top","right","bottom","left","zIndex",
|
|
453
|
+
"border","borderTop","borderBottom","borderLeft","borderRight",
|
|
454
|
+
"borderWidth","borderStyle","borderColor","borderRadius",
|
|
455
|
+
"outline","outlineWidth","outlineStyle","outlineColor","outlineOffset",
|
|
456
|
+
"boxShadow","textShadow","opacity","visibility",
|
|
457
|
+
"overflow","overflowX","overflowY","objectFit","objectPosition",
|
|
458
|
+
"cursor","userSelect","pointerEvents","resize",
|
|
459
|
+
"transform","transition","animation","animationDuration","animationDelay",
|
|
460
|
+
"listStyle","listStyleType","listStylePosition",
|
|
461
|
+
"verticalAlign","float","clear",
|
|
462
|
+
"content","quotes",
|
|
463
|
+
]);
|
|
464
|
+
|
|
465
|
+
export function resolveBuiltinTag(
|
|
466
|
+
name: string,
|
|
467
|
+
attrs: Attr[],
|
|
468
|
+
): { tag: string; defaultClass?: string; voidEl: boolean } {
|
|
469
|
+
if (name === "Heading") {
|
|
470
|
+
const la = attrs.find(a => a.name === "level");
|
|
471
|
+
const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
|
|
472
|
+
if (!la) SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
|
|
473
|
+
return { tag: `h${lv}`, voidEl: false };
|
|
474
|
+
}
|
|
475
|
+
const info = BUILTIN_MAP[name];
|
|
476
|
+
if (info) return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
|
|
477
|
+
SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
|
|
478
|
+
return { tag: name.toLowerCase(), voidEl: false };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export function registerExpr(ctx: CompileCtx, expr: Expression): number {
|
|
482
|
+
const jsExpr = compileExprToJS(expr, ctx.loopVars);
|
|
483
|
+
const existing = ctx.exprMap.get(jsExpr);
|
|
484
|
+
if (existing !== undefined) return existing;
|
|
485
|
+
const id = ctx.exprRegistry.length;
|
|
486
|
+
ctx.exprRegistry.push(jsExpr);
|
|
487
|
+
ctx.exprMap.set(jsExpr, id);
|
|
488
|
+
return id;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
export function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx?: CompileCtx): string {
|
|
493
|
+
const { name, value } = attr;
|
|
494
|
+
if (value === null) return name;
|
|
495
|
+
if (value.kind === "null") return "";
|
|
496
|
+
if (value.kind === "bool") return value.value ? name : "";
|
|
497
|
+
|
|
498
|
+
if (name === "model" && value?.kind === "str") {
|
|
499
|
+
const vName = interpolateAttr(value.value, paramMap);
|
|
500
|
+
return `oninput="(function(e){ ${vName} = e.target.value; sinthRender(); })(event)" value="${escAttr(vName)}"`;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
if (name === "delay") {
|
|
506
|
+
if (value.kind === "num") {
|
|
507
|
+
return `data-sinth-delay="${value.value}" style="display:none"`;
|
|
508
|
+
}
|
|
509
|
+
const v = litToString(value);
|
|
510
|
+
if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}" style="display:none"`;
|
|
511
|
+
if (v.startsWith("__EXPR__")) {
|
|
512
|
+
try {
|
|
513
|
+
const expr: Expression = JSON.parse(v.substring(8));
|
|
514
|
+
const id = registerExpr(ctx, expr);
|
|
515
|
+
return `data-sinth-delay-expr-id="${id}" style="display:none"`;
|
|
516
|
+
} catch {}
|
|
517
|
+
}
|
|
518
|
+
// plain variable name – register as expression
|
|
519
|
+
const id = registerExpr(ctx, { kind: "variable", name: v });
|
|
520
|
+
return `data-sinth-delay-expr-id="${id}" style="display:none"`;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
if (name === "checked") {
|
|
524
|
+
return (value as any)?.kind === "bool" && (value as any).value ? "checked" : "";
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
if (value.kind === "num") return `${name}="${value.value}"`;
|
|
528
|
+
|
|
529
|
+
let raw = value.value;
|
|
530
|
+
|
|
531
|
+
if (raw.startsWith("__MULTI_EXPR__")) {
|
|
532
|
+
const exprJson = raw.substring("__MULTI_EXPR__".length);
|
|
533
|
+
try {
|
|
534
|
+
const exprs: Expression[] = JSON.parse(exprJson);
|
|
535
|
+
const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
|
|
536
|
+
const ev = eventAttrName(name);
|
|
537
|
+
if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, """)}; sinthRender(); })()"`;
|
|
538
|
+
return `${name}="${escAttr(jsExprs)}"`;
|
|
539
|
+
} catch { }
|
|
540
|
+
}
|
|
541
|
+
if (raw.startsWith("__EXPR__")) {
|
|
542
|
+
const exprJson = raw.substring("__EXPR__".length);
|
|
543
|
+
try {
|
|
544
|
+
const expr: Expression = JSON.parse(exprJson);
|
|
545
|
+
const jsExpr = compileExprToJS(expr);
|
|
546
|
+
const ev = eventAttrName(name);
|
|
547
|
+
if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, """)}; sinthRender(); })()"`;
|
|
548
|
+
return `${name}="${escAttr(jsExpr)}"`;
|
|
549
|
+
} catch { }
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
raw = interpolateAttr(raw, paramMap);
|
|
553
|
+
|
|
554
|
+
const ev = eventAttrName(name);
|
|
555
|
+
if (ev) {
|
|
556
|
+
const call = raw.includes("(") ? raw : raw + "()";
|
|
557
|
+
return `${ev}="${escAttr(call)};sinthRender()"`;
|
|
558
|
+
}
|
|
559
|
+
return `${name}="${escAttr(raw)}"`;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export function renderText(text: string, params: Map<string, string>): string {
|
|
563
|
+
const rawSlots = new Map<string, string>();
|
|
564
|
+
let counter = 0;
|
|
565
|
+
|
|
566
|
+
let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
|
|
567
|
+
|
|
568
|
+
s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
|
|
569
|
+
const val = params.get(n);
|
|
570
|
+
if (val === undefined) return `$${n}`;
|
|
571
|
+
if (n === "slot") {
|
|
572
|
+
const ph = `\x00RAW${counter++}\x00`;
|
|
573
|
+
rawSlots.set(ph, val);
|
|
574
|
+
return ph;
|
|
575
|
+
}
|
|
576
|
+
return val;
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
s = esc(s);
|
|
580
|
+
|
|
581
|
+
for (const [ph, val] of rawSlots) s = s.replace(ph, val);
|
|
582
|
+
s = s.replace(/\x00DOLLAR\x00/g, "$");
|
|
583
|
+
|
|
584
|
+
const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
|
|
585
|
+
let m: RegExpExecArray | null;
|
|
586
|
+
while ((m = braceRe.exec(s)) !== null) {
|
|
587
|
+
SinthWarning.emit(
|
|
588
|
+
`Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
return s;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
export function interpolateAttr(text: string, params: Map<string, string>): string {
|
|
596
|
+
let s = text.replace(/\\\{/g, "\x00LB\x00");
|
|
597
|
+
s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
|
|
598
|
+
return s.replace(/\x00LB\x00/g, "{");
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
export function renderChild(
|
|
603
|
+
child: Child,
|
|
604
|
+
ctx: CompileCtx,
|
|
605
|
+
params: Map<string, string>,
|
|
606
|
+
depth: number,
|
|
607
|
+
): string {
|
|
608
|
+
if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
|
|
609
|
+
|
|
610
|
+
switch (child.kind) {
|
|
611
|
+
case "text":
|
|
612
|
+
return renderText(child.value, params);
|
|
613
|
+
|
|
614
|
+
case "expr": {
|
|
615
|
+
if (child.expression.kind === "literal" && child.expression.value) {
|
|
616
|
+
return esc(litToString(child.expression.value));
|
|
617
|
+
}
|
|
618
|
+
if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
|
|
619
|
+
const exprId = registerExpr(ctx, child.expression);
|
|
620
|
+
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
621
|
+
}
|
|
622
|
+
const exprId = registerExpr(ctx, child.expression);
|
|
623
|
+
return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
case "assign_stmt": {
|
|
627
|
+
ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
|
|
628
|
+
return "";
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
case "remove": {
|
|
632
|
+
return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
case "if":
|
|
636
|
+
return renderIfBlock(child, ctx, params, depth);
|
|
637
|
+
|
|
638
|
+
case "for": {
|
|
639
|
+
// collect loop‑variable names
|
|
640
|
+
const loopVars = new Set<string>();
|
|
641
|
+
loopVars.add(child.itemVar);
|
|
642
|
+
if (child.keyVar) loopVars.add(child.keyVar);
|
|
643
|
+
if (child.indexVar) loopVars.add(child.indexVar);
|
|
644
|
+
// set them on ctx for compilation of the body
|
|
645
|
+
const prev = ctx.loopVars;
|
|
646
|
+
ctx.loopVars = loopVars;
|
|
647
|
+
const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
648
|
+
ctx.loopVars = prev; // restore
|
|
649
|
+
const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
|
|
650
|
+
const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
|
|
651
|
+
return (
|
|
652
|
+
`<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`
|
|
653
|
+
);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
case "use":
|
|
657
|
+
return renderCompUse(child, ctx, params, depth);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
export function renderIfBlock(
|
|
662
|
+
ifBlock: IfBlock,
|
|
663
|
+
ctx: CompileCtx,
|
|
664
|
+
params: Map<string, string>,
|
|
665
|
+
depth: number,
|
|
666
|
+
): string {
|
|
667
|
+
if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
|
|
668
|
+
|
|
669
|
+
const condJS = compileExprToJS(ifBlock.condition);
|
|
670
|
+
const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
|
|
671
|
+
const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
|
|
672
|
+
const hasComp = allChildren.some(c => c.kind === "use");
|
|
673
|
+
|
|
674
|
+
// pure logic
|
|
675
|
+
if (hasAssign && !hasComp) {
|
|
676
|
+
ctx.logicBlocks.push(compileIfToJS(ifBlock));
|
|
677
|
+
return "";
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// pure DOM
|
|
681
|
+
if (!hasAssign && hasComp) {
|
|
682
|
+
const tplId = ctx.ifIdCounter++;
|
|
683
|
+
const condId = registerExpr(ctx, ifBlock.condition);
|
|
684
|
+
const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
685
|
+
const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
686
|
+
let replaceAttr = "";
|
|
687
|
+
const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
|
|
688
|
+
if (firstComp) {
|
|
689
|
+
const idAttr = firstComp.attrs.find(a => a.name === "id");
|
|
690
|
+
const replAttr = firstComp.attrs.find(a => a.name === "replace");
|
|
691
|
+
const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
|
|
692
|
+
if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
|
|
693
|
+
replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
return (
|
|
697
|
+
`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}>${bodyHTML}</template>` +
|
|
698
|
+
(elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// mixed
|
|
703
|
+
const id = `__sm${ctx.mixedCounter++}__`;
|
|
704
|
+
|
|
705
|
+
const ifAssignJS = ifBlock.body
|
|
706
|
+
.filter(c => c.kind === "assign_stmt")
|
|
707
|
+
.map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
|
|
708
|
+
.join("\n");
|
|
709
|
+
|
|
710
|
+
const ifHTML = ifBlock.body
|
|
711
|
+
.filter(c => c.kind !== "assign_stmt")
|
|
712
|
+
.map(c => renderChild(c, ctx, params, depth + 1))
|
|
713
|
+
.join("");
|
|
714
|
+
|
|
715
|
+
const elseAssignJS = (ifBlock.elseBody ?? [])
|
|
716
|
+
.filter(c => c.kind === "assign_stmt")
|
|
717
|
+
.map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
|
|
718
|
+
.join("\n");
|
|
719
|
+
|
|
720
|
+
const elseHTML = (ifBlock.elseBody ?? [])
|
|
721
|
+
.filter(c => c.kind !== "assign_stmt")
|
|
722
|
+
.map(c => renderChild(c, ctx, params, depth + 1))
|
|
723
|
+
.join("");
|
|
724
|
+
|
|
725
|
+
let replaceId: string | undefined;
|
|
726
|
+
const ifFirstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
|
|
727
|
+
const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
|
|
728
|
+
if (ifFirstComp) {
|
|
729
|
+
const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
|
|
730
|
+
const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
|
|
731
|
+
const ifReplaceVal = ifReplace?.value;
|
|
732
|
+
const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
|
|
733
|
+
|
|
734
|
+
if (ifId && ifId.kind === "str" && ifWantsReplace) {
|
|
735
|
+
if (elseFirstComp) {
|
|
736
|
+
const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
|
|
737
|
+
const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
|
|
738
|
+
const elseReplaceVal = elseReplace?.value;
|
|
739
|
+
const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
|
|
740
|
+
|
|
741
|
+
if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
|
|
742
|
+
replaceId = ifId.value;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
const condId = registerExpr(ctx, ifBlock.condition);
|
|
749
|
+
ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
|
|
750
|
+
|
|
751
|
+
return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
export function renderCompUse(
|
|
755
|
+
use: CompUse,
|
|
756
|
+
ctx: CompileCtx,
|
|
757
|
+
params: Map<string, string>,
|
|
758
|
+
depth: number,
|
|
759
|
+
): string {
|
|
760
|
+
// transparent wrapper inserted by flattenIfToUses()
|
|
761
|
+
if (use.name === "__IF_ROOT__") {
|
|
762
|
+
return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// RawHTML
|
|
766
|
+
if (use.name === "RawHTML") {
|
|
767
|
+
const ca = use.attrs.find(a => a.name === "content");
|
|
768
|
+
if (!ca || !ca.value) return "";
|
|
769
|
+
return interpolateAttr(litToString(ca.value), params);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// user-defined component
|
|
773
|
+
const userDef = ctx.allDefs.get(use.name);
|
|
774
|
+
if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
|
|
775
|
+
|
|
776
|
+
// custom element
|
|
777
|
+
const customEl = ctx.customEls.get(use.name);
|
|
778
|
+
if (customEl) {
|
|
779
|
+
const attrParts = [`data-s="${ctx.scopeHash}"`];
|
|
780
|
+
for (const attr of use.attrs) {
|
|
781
|
+
const r = renderAttr(attr, params, ctx);
|
|
782
|
+
if (r) attrParts.push(r);
|
|
783
|
+
}
|
|
784
|
+
const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
785
|
+
return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// built-in component
|
|
789
|
+
const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
|
|
790
|
+
const isVoid = voidEl || VOID_TAGS.has(tag);
|
|
791
|
+
|
|
792
|
+
const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
|
|
793
|
+
let userClass: string | undefined;
|
|
794
|
+
const inlineStyleParts: string[] = [];
|
|
795
|
+
|
|
796
|
+
for (const attr of use.attrs) {
|
|
797
|
+
if (attr.name === "level" && use.name === "Heading") continue;
|
|
798
|
+
|
|
799
|
+
if (INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
|
|
800
|
+
const val = attr.value.kind === "str"
|
|
801
|
+
? interpolateAttr(attr.value.value, params)
|
|
802
|
+
: litToString(attr.value);
|
|
803
|
+
inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
if (attr.name === "class") {
|
|
808
|
+
if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
const rendered = renderAttr(attr, params, ctx);
|
|
812
|
+
if (rendered) attrParts.push(rendered);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const classes = [defaultClass, userClass].filter(Boolean).join(" ");
|
|
816
|
+
if (classes) attrParts.push(`class="${escAttr(classes)}"`);
|
|
817
|
+
if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
|
|
818
|
+
if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
|
|
819
|
+
if (use.name === "Input") {
|
|
820
|
+
const bindAttr = use.attrs.find(a => a.name === "bind");
|
|
821
|
+
const modelAttr = use.attrs.find(a => a.name === "model");
|
|
822
|
+
const bindOrModel = bindAttr || modelAttr;
|
|
823
|
+
if (bindOrModel?.value?.kind === "str") {
|
|
824
|
+
let vName = bindOrModel.value.value;
|
|
825
|
+
if (vName.startsWith("__EXPR__")) {
|
|
826
|
+
try {
|
|
827
|
+
const expr: Expression = JSON.parse(vName.substring(8));
|
|
828
|
+
if (expr.kind === "variable" && expr.name) vName = expr.name;
|
|
829
|
+
} catch {}
|
|
830
|
+
}
|
|
831
|
+
if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="text"`);
|
|
832
|
+
attrParts.push(`oninput="(function(e){ ${vName} = e.target.value; sinthRender(); })(event)"`);
|
|
833
|
+
attrParts.push(`data-sinth-value="${escAttr(vName)}"`);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (use.name === "Checkbox") {
|
|
837
|
+
if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
|
|
838
|
+
const bindAttr = use.attrs.find(a => a.name === "bind");
|
|
839
|
+
if (bindAttr?.value?.kind === "str") {
|
|
840
|
+
let vName = bindAttr.value.value;
|
|
841
|
+
if (vName.startsWith("__EXPR__")) {
|
|
842
|
+
try {
|
|
843
|
+
const expr: Expression = JSON.parse(vName.substring(8));
|
|
844
|
+
if (expr.kind === "variable" && expr.name) vName = expr.name;
|
|
845
|
+
} catch {}
|
|
846
|
+
}
|
|
847
|
+
attrParts.push(`onchange="(function(e){ ${vName} = e.target.checked; sinthRender(); })(event)"`);
|
|
848
|
+
attrParts.push(`data-sinth-checked="${escAttr(vName)}"`);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
|
|
853
|
+
|
|
854
|
+
if (isVoid) {
|
|
855
|
+
if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
|
|
856
|
+
return `<${tag}${attrStr}>`;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
860
|
+
return `<${tag}${attrStr}>${inner}</${tag}>`;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
export function expandUserComp(
|
|
864
|
+
use: CompUse,
|
|
865
|
+
def: CompDef,
|
|
866
|
+
ctx: CompileCtx,
|
|
867
|
+
params: Map<string, string>,
|
|
868
|
+
depth: number,
|
|
869
|
+
): string {
|
|
870
|
+
if (use.name === def.name && depth > 1) {
|
|
871
|
+
throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
const local = new Map<string, string>();
|
|
875
|
+
|
|
876
|
+
for (const p of def.params) {
|
|
877
|
+
if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
for (const attr of use.attrs) {
|
|
881
|
+
if (attr.value === null) {
|
|
882
|
+
local.set(attr.name, "true");
|
|
883
|
+
} else if (attr.value.kind !== "null") {
|
|
884
|
+
const raw = litToString(attr.value);
|
|
885
|
+
local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
for (const p of def.params) {
|
|
890
|
+
if (!local.has(p.name)) {
|
|
891
|
+
throw new SinthError(
|
|
892
|
+
`Component '${def.name}' requires parameter '${p.name}' but it was not provided.`,
|
|
893
|
+
use.loc,
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
899
|
+
local.set("slot", slotHTML);
|
|
900
|
+
|
|
901
|
+
for (const block of def.styles) {
|
|
902
|
+
ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// script collector
|
|
909
|
+
|
|
910
|
+
export function collectScripts(
|
|
911
|
+
file: SinthFile,
|
|
912
|
+
allDefs: Map<string, CompDef>,
|
|
913
|
+
): { componentScripts: string[]; pageScripts: { raw: string; attrs: Record<string, string> }[] } {
|
|
914
|
+
const componentScripts: string[] = [];
|
|
915
|
+
const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
|
|
916
|
+
const seenFunctions = new Set<string>();
|
|
917
|
+
|
|
918
|
+
for (const [, def] of allDefs) {
|
|
919
|
+
for (const block of def.scripts) {
|
|
920
|
+
for (const fn of extractFunctionNames(block.raw)) {
|
|
921
|
+
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
|
|
922
|
+
seenFunctions.add(fn);
|
|
923
|
+
}
|
|
924
|
+
componentScripts.push(`(function(){\n${block.raw}\n})();`);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
for (const block of file.scripts) {
|
|
929
|
+
for (const fn of extractFunctionNames(block.raw)) {
|
|
930
|
+
if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
|
|
931
|
+
seenFunctions.add(fn);
|
|
932
|
+
}
|
|
933
|
+
pageScripts.push({ raw: block.raw, attrs: block.attrs });
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
return { componentScripts, pageScripts };
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
export function extractFunctionNames(js: string): string[] {
|
|
940
|
+
const names: string[] = [];
|
|
941
|
+
const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
|
|
942
|
+
let m: RegExpExecArray | null;
|
|
943
|
+
while ((m = re.exec(js)) !== null) names.push(m[1]);
|
|
944
|
+
return names;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
// head gen
|
|
949
|
+
|
|
950
|
+
export interface HeadData {
|
|
951
|
+
title?: string; fav?: string;
|
|
952
|
+
lang: string; charset: string; viewport: string;
|
|
953
|
+
metaTags: { name: string; content: string }[];
|
|
954
|
+
metaProps: { property: string; content: string }[];
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
export function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
958
|
+
let title: string | undefined, fav: string | undefined;
|
|
959
|
+
let lang = "en", charset = "UTF-8", viewport = "width=device-width, initial-scale=1.0";
|
|
960
|
+
const metaTags: { name: string; content: string }[] = [];
|
|
961
|
+
const metaProps: { property: string; content: string }[] = [];
|
|
962
|
+
|
|
963
|
+
for (const m of meta) {
|
|
964
|
+
const val = litToString(m.value);
|
|
965
|
+
switch (m.key) {
|
|
966
|
+
case "title": title = val; break;
|
|
967
|
+
case "fav": fav = val; break;
|
|
968
|
+
case "lang": lang = val; break;
|
|
969
|
+
case "charset": charset = val; break;
|
|
970
|
+
case "viewport": viewport = val; break;
|
|
971
|
+
case "descr": metaTags.push({ name: "description", content: val }); break;
|
|
972
|
+
case "author": metaTags.push({ name: "author", content: val }); break;
|
|
973
|
+
case "keywords": metaTags.push({ name: "keywords", content: val }); break;
|
|
974
|
+
case "robots": metaTags.push({ name: "robots", content: val }); break;
|
|
975
|
+
default:
|
|
976
|
+
if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
|
|
977
|
+
const prop = m.key
|
|
978
|
+
.replace(/^og([A-Z])/, (_: string, c: string) => `og:${c.toLowerCase()}`)
|
|
979
|
+
.replace(/^twitter([A-Z])/, (_: string, c: string) => `twitter:${c.toLowerCase()}`);
|
|
980
|
+
metaProps.push({ property: prop, content: val });
|
|
981
|
+
} else {
|
|
982
|
+
metaTags.push({ name: camelToKebab(m.key), content: val });
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
return { title, fav, lang, charset, viewport, metaTags, metaProps };
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
export function faviconType(p: string): string {
|
|
991
|
+
switch (path.extname(p).toLowerCase()) {
|
|
992
|
+
case ".ico": return "image/x-icon";
|
|
993
|
+
case ".png": return "image/png";
|
|
994
|
+
case ".svg": return "image/svg+xml";
|
|
995
|
+
case ".gif": return "image/gif";
|
|
996
|
+
case ".webp": return "image/webp";
|
|
997
|
+
case ".jpg":
|
|
998
|
+
case ".jpeg": return "image/jpeg";
|
|
999
|
+
default:
|
|
1000
|
+
SinthWarning.emit(`Unknown favicon extension '${path.extname(p)}', defaulting to image/x-icon`);
|
|
1001
|
+
return "image/x-icon";
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
export function renderHead(
|
|
1006
|
+
hd: HeadData,
|
|
1007
|
+
cssLinks: string[],
|
|
1008
|
+
jsLinks: { src: string; attrs: Record<string, string> }[],
|
|
1009
|
+
scopedCSS: string,
|
|
1010
|
+
companionJS: string | undefined,
|
|
1011
|
+
): string {
|
|
1012
|
+
const lines: string[] = [];
|
|
1013
|
+
lines.push(` <meta charset="${escAttr(hd.charset)}">`);
|
|
1014
|
+
lines.push(` <meta name="viewport" content="${escAttr(hd.viewport)}">`);
|
|
1015
|
+
if (hd.title) lines.push(` <title>${esc(hd.title)}</title>`);
|
|
1016
|
+
if (hd.fav) lines.push(` <link rel="icon" href="${escAttr(hd.fav)}" type="${faviconType(hd.fav)}">`);
|
|
1017
|
+
for (const m of hd.metaTags) lines.push(` <meta name="${escAttr(m.name)}" content="${escAttr(m.content)}">`);
|
|
1018
|
+
for (const m of hd.metaProps) lines.push(` <meta property="${escAttr(m.property)}" content="${escAttr(m.content)}">`);
|
|
1019
|
+
for (const css of cssLinks) lines.push(` <link rel="stylesheet" href="${escAttr(css)}">`);
|
|
1020
|
+
if (scopedCSS.trim()) lines.push(` <style>\n${scopedCSS}\n </style>`);
|
|
1021
|
+
for (const js of jsLinks) {
|
|
1022
|
+
const extra = Object.entries(js.attrs)
|
|
1023
|
+
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
1024
|
+
.join(" ");
|
|
1025
|
+
lines.push(` <script src="${escAttr(js.src)}"${extra ? " " + extra : ""}></script>`);
|
|
1026
|
+
}
|
|
1027
|
+
if (companionJS) lines.push(` <script src="${escAttr(companionJS)}"></script>`);
|
|
1028
|
+
return `<head>\n${lines.join("\n")}\n</head>`;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
// sinth runtime
|
|
1033
|
+
|
|
1034
|
+
export function buildRuntime(opts: {
|
|
1035
|
+
varDecls: VarDeclaration[];
|
|
1036
|
+
bodyHTML: string;
|
|
1037
|
+
logicBlocks: string[];
|
|
1038
|
+
mixedBlocks: MixedBlockEntry[];
|
|
1039
|
+
assignedVars: Set<string>;
|
|
1040
|
+
exprRegistry: string[];
|
|
1041
|
+
sharedRuntime: boolean;
|
|
1042
|
+
}): string | { page: string; shared: string } {
|
|
1043
|
+
const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
|
|
1044
|
+
|
|
1045
|
+
const needsExpr = bodyHTML.includes("sinth-expr");
|
|
1046
|
+
const needsIf = bodyHTML.includes("data-sinth-if");
|
|
1047
|
+
const needsFor = bodyHTML.includes("data-sinth-for");
|
|
1048
|
+
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"));
|
|
1049
|
+
const needsMixed = mixedBlocks.length > 0;
|
|
1050
|
+
const needsLogic = logicBlocks.length > 0;
|
|
1051
|
+
const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
|
|
1052
|
+
|
|
1053
|
+
const varLines = varDecls.map(v => {
|
|
1054
|
+
if (!v.value) {
|
|
1055
|
+
if (!assignedVars.has(v.name)) {
|
|
1056
|
+
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
1057
|
+
SinthWarning.emit(
|
|
1058
|
+
`Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
|
|
1059
|
+
v.loc,
|
|
1060
|
+
);
|
|
1061
|
+
}
|
|
1062
|
+
const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
|
|
1063
|
+
return `var ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
|
|
1064
|
+
}
|
|
1065
|
+
const val = litToString(v.value);
|
|
1066
|
+
if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
1067
|
+
if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
|
|
1068
|
+
if (v.varType === "obj") return `var ${v.name} = ${val};`;
|
|
1069
|
+
if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
|
|
1070
|
+
if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
|
|
1071
|
+
try {
|
|
1072
|
+
const arr = JSON.parse(val.slice(7));
|
|
1073
|
+
return `var ${v.name} = ${JSON.stringify(arr)};`;
|
|
1074
|
+
} catch { return `var ${v.name} = ${val.slice(7)};`; }
|
|
1075
|
+
}
|
|
1076
|
+
return `var ${v.name} = ${val};`;
|
|
1077
|
+
}).join("\n");
|
|
1078
|
+
|
|
1079
|
+
if (!needsRender && !needsDelay) {
|
|
1080
|
+
return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
let helpers = "";
|
|
1084
|
+
|
|
1085
|
+
if (needsExpr || needsIf || needsFor) {
|
|
1086
|
+
helpers += `
|
|
1087
|
+
function sinthExpr(el) {
|
|
1088
|
+
try {
|
|
1089
|
+
var exprFn = __X[el.dataset.exprId];
|
|
1090
|
+
if (exprFn) el.textContent = exprFn({});
|
|
1091
|
+
} catch(e) {}
|
|
1092
|
+
}
|
|
1093
|
+
`;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
if (needsIf || needsMixed) {
|
|
1097
|
+
helpers += `
|
|
1098
|
+
function sinthReplaceInsert(t, anchor, ifId, replaceId) {
|
|
1099
|
+
if (anchor) {
|
|
1100
|
+
var cur = anchor.nextSibling;
|
|
1101
|
+
while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
|
|
1102
|
+
} else {
|
|
1103
|
+
anchor = document.createElement('span');
|
|
1104
|
+
anchor.style.display = 'none';
|
|
1105
|
+
anchor.dataset.sinthIfAnchor = ifId;
|
|
1106
|
+
t.parentNode.insertBefore(anchor, t);
|
|
1107
|
+
}
|
|
1108
|
+
var _rp = null, _rpParent = null, _rpNext = null;
|
|
1109
|
+
if (replaceId) {
|
|
1110
|
+
_rp = document.getElementById(replaceId);
|
|
1111
|
+
if (_rp) {
|
|
1112
|
+
_rpParent = _rp.parentNode;
|
|
1113
|
+
_rpNext = _rp.nextSibling;
|
|
1114
|
+
_rp.parentNode.removeChild(_rp);
|
|
1115
|
+
anchor._sinthReplaced = _rp;
|
|
1116
|
+
anchor._sinthReplacedParent = _rpParent;
|
|
1117
|
+
anchor._sinthReplacedNext = _rpNext;
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
1121
|
+
frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1122
|
+
if (${needsDelay}) {
|
|
1123
|
+
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1124
|
+
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
1125
|
+
}
|
|
1126
|
+
var fragFirst = frag.firstChild;
|
|
1127
|
+
var fragLast = frag.lastChild;
|
|
1128
|
+
if (_rpParent && _rpNext) {
|
|
1129
|
+
_rpParent.insertBefore(frag, _rpNext);
|
|
1130
|
+
} else if (_rpParent) {
|
|
1131
|
+
_rpParent.appendChild(frag);
|
|
1132
|
+
} else {
|
|
1133
|
+
t.parentNode.insertBefore(frag, t);
|
|
1134
|
+
}
|
|
1135
|
+
if (replaceId && anchor) {
|
|
1136
|
+
anchor._sinthInsertedFirst = fragFirst;
|
|
1137
|
+
anchor._sinthInsertedLast = fragLast;
|
|
1138
|
+
}
|
|
1139
|
+
return anchor;
|
|
1140
|
+
}
|
|
1141
|
+
`;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
if (needsDelay) {
|
|
1145
|
+
helpers += `
|
|
1146
|
+
function sinthDelay(el) {
|
|
1147
|
+
if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
|
|
1148
|
+
el.dataset.sinthDelayDone = '1';
|
|
1149
|
+
var ms = parseInt(el.dataset.sinthDelay) || 0;
|
|
1150
|
+
el.style.display = 'none';
|
|
1151
|
+
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
1152
|
+
else el.style.display = '';
|
|
1153
|
+
}
|
|
1154
|
+
function sinthDelayExpr(el) {
|
|
1155
|
+
try {
|
|
1156
|
+
var fn = __X[el.dataset.sinthDelayExprId];
|
|
1157
|
+
var ms = fn ? parseInt(fn()) || 0 : 0;
|
|
1158
|
+
el.style.display = '';
|
|
1159
|
+
if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
|
|
1160
|
+
} catch(e) {}
|
|
1161
|
+
}
|
|
1162
|
+
`;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
if (needsIf) {
|
|
1166
|
+
helpers += `
|
|
1167
|
+
function sinthIfBlock(t) {
|
|
1168
|
+
var ifId = t.dataset.sinthIfId;
|
|
1169
|
+
var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
|
|
1170
|
+
var condFn = __X[t.dataset.sinthIfExpr];
|
|
1171
|
+
var cond = condFn ? condFn() : false;
|
|
1172
|
+
if (cond) {
|
|
1173
|
+
anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
|
|
1174
|
+
} else {
|
|
1175
|
+
if (anchor) {
|
|
1176
|
+
if (anchor._sinthReplaced) {
|
|
1177
|
+
var insFirst = anchor._sinthInsertedFirst;
|
|
1178
|
+
var insLast = anchor._sinthInsertedLast;
|
|
1179
|
+
var rpParent = anchor._sinthReplacedParent;
|
|
1180
|
+
var rpNext = anchor._sinthReplacedNext;
|
|
1181
|
+
if (insFirst && insLast) {
|
|
1182
|
+
var cur = insFirst;
|
|
1183
|
+
while (cur && cur !== insLast) {
|
|
1184
|
+
var next = cur.nextSibling;
|
|
1185
|
+
cur.remove();
|
|
1186
|
+
cur = next;
|
|
1187
|
+
}
|
|
1188
|
+
if (insLast) insLast.remove();
|
|
1189
|
+
}
|
|
1190
|
+
if (rpParent && rpNext) {
|
|
1191
|
+
rpParent.insertBefore(anchor._sinthReplaced, rpNext);
|
|
1192
|
+
} else if (rpParent) {
|
|
1193
|
+
rpParent.appendChild(anchor._sinthReplaced);
|
|
1194
|
+
}
|
|
1195
|
+
} else {
|
|
1196
|
+
var cur2 = anchor.nextSibling;
|
|
1197
|
+
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
1198
|
+
}
|
|
1199
|
+
anchor.remove();
|
|
1200
|
+
}
|
|
1201
|
+
var elseT = t.nextElementSibling;
|
|
1202
|
+
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
1203
|
+
var elseIfId = elseT.dataset.sinthIfId;
|
|
1204
|
+
var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
|
|
1205
|
+
if (ea) {
|
|
1206
|
+
var cur3 = ea.nextSibling;
|
|
1207
|
+
while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
|
|
1208
|
+
} else {
|
|
1209
|
+
ea = document.createElement('span');
|
|
1210
|
+
ea.style.display = 'none';
|
|
1211
|
+
ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
|
|
1212
|
+
t.parentNode.insertBefore(ea, t);
|
|
1213
|
+
}
|
|
1214
|
+
var ef = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
1215
|
+
ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1216
|
+
if (${needsDelay}) {
|
|
1217
|
+
ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1218
|
+
ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
1219
|
+
}
|
|
1220
|
+
t.parentNode.insertBefore(ef, t);
|
|
1221
|
+
} else {
|
|
1222
|
+
var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
|
|
1223
|
+
if (ea2) {
|
|
1224
|
+
var ec = ea2.nextSibling;
|
|
1225
|
+
while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
|
|
1226
|
+
ea2.remove();
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
`;
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
if (needsFor) {
|
|
1235
|
+
helpers += `
|
|
1236
|
+
function hashString(str) {
|
|
1237
|
+
var hash = 0, i, chr;
|
|
1238
|
+
for (i = 0; i < str.length; i++) {
|
|
1239
|
+
chr = str.charCodeAt(i);
|
|
1240
|
+
hash = ((hash << 5) - hash) + chr;
|
|
1241
|
+
hash |= 0;
|
|
1242
|
+
}
|
|
1243
|
+
return String(hash);
|
|
1244
|
+
}
|
|
1245
|
+
function sinthForBlock(t) {
|
|
1246
|
+
var source = window[t.dataset.sinthFor];
|
|
1247
|
+
if (source === undefined) source = [];
|
|
1248
|
+
var newHash = '';
|
|
1249
|
+
try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
|
|
1250
|
+
if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
t.dataset.sinthForHash = newHash;
|
|
1254
|
+
var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
|
|
1255
|
+
var entries;
|
|
1256
|
+
if (isObj) {
|
|
1257
|
+
entries = Object.entries(source);
|
|
1258
|
+
} else {
|
|
1259
|
+
if (!Array.isArray(source)) source = [];
|
|
1260
|
+
entries = source.map(function(item, index) { return [index, item]; });
|
|
1261
|
+
}
|
|
1262
|
+
var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
|
|
1263
|
+
if (anchor) {
|
|
1264
|
+
var cur2 = anchor.nextSibling;
|
|
1265
|
+
while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
|
|
1266
|
+
anchor.remove();
|
|
1267
|
+
}
|
|
1268
|
+
var fa = document.createElement('span');
|
|
1269
|
+
fa.style.display = 'none';
|
|
1270
|
+
fa.dataset.sinthForAnchor = t.dataset.sinthFor;
|
|
1271
|
+
t.parentNode && t.parentNode.insertBefore(fa, t);
|
|
1272
|
+
var _loopIdx = 0;
|
|
1273
|
+
entries.forEach(function(entry) {
|
|
1274
|
+
var _k = entry[0];
|
|
1275
|
+
var _v = entry[1];
|
|
1276
|
+
var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
|
|
1277
|
+
var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
|
|
1278
|
+
var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
|
|
1279
|
+
_loopIdx++;
|
|
1280
|
+
if (t.dataset.sinthIfReplace) {
|
|
1281
|
+
var _rp = document.getElementById(t.dataset.sinthIfReplace);
|
|
1282
|
+
if (_rp) _rp.parentNode.removeChild(_rp);
|
|
1283
|
+
}
|
|
1284
|
+
var frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
1285
|
+
frag.querySelectorAll('.sinth-expr').forEach(function(el) {
|
|
1286
|
+
try {
|
|
1287
|
+
var exprFn = __X[el.dataset.exprId];
|
|
1288
|
+
if (!exprFn) return;
|
|
1289
|
+
var _ctx = {};
|
|
1290
|
+
if (_item) _ctx[_item] = _v;
|
|
1291
|
+
if (_key) _ctx[_key] = _k;
|
|
1292
|
+
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
1293
|
+
el.textContent = exprFn(_ctx);
|
|
1294
|
+
el.classList.remove('sinth-expr');
|
|
1295
|
+
} catch(e) {}
|
|
1296
|
+
});
|
|
1297
|
+
frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
|
|
1298
|
+
var condFn = __X[ifT.dataset.sinthIfExpr];
|
|
1299
|
+
var _ctx = {};
|
|
1300
|
+
if (_item) _ctx[_item] = _v;
|
|
1301
|
+
if (_key) _ctx[_key] = _k;
|
|
1302
|
+
if (_idx) _ctx[_idx] = _loopIdx - 1;
|
|
1303
|
+
var cond = false;
|
|
1304
|
+
try { if (condFn) cond = condFn(_ctx); } catch(e) {}
|
|
1305
|
+
if (cond) {
|
|
1306
|
+
var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
|
|
1307
|
+
ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
1308
|
+
try {
|
|
1309
|
+
var exprFn2 = __X[el2.dataset.exprId];
|
|
1310
|
+
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
1311
|
+
} catch(e) {}
|
|
1312
|
+
});
|
|
1313
|
+
ifT.parentNode.insertBefore(ifContent, ifT);
|
|
1314
|
+
} else {
|
|
1315
|
+
var elseT = ifT.nextElementSibling;
|
|
1316
|
+
if (elseT && elseT.hasAttribute('data-sinth-else')) {
|
|
1317
|
+
var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
1318
|
+
elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
|
|
1319
|
+
try {
|
|
1320
|
+
var exprFn2 = __X[el2.dataset.exprId];
|
|
1321
|
+
if (exprFn2) el2.textContent = exprFn2(_ctx);
|
|
1322
|
+
} catch(e) {}
|
|
1323
|
+
});
|
|
1324
|
+
ifT.parentNode.insertBefore(elseContent, ifT);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
});
|
|
1328
|
+
if (${needsDelay}) {
|
|
1329
|
+
frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1330
|
+
frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
1331
|
+
}
|
|
1332
|
+
t.parentNode && t.parentNode.insertBefore(frag, t);
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
`;
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
if (needsMixed) {
|
|
1339
|
+
helpers += `
|
|
1340
|
+
function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
|
|
1341
|
+
var condFn = __X[condId];
|
|
1342
|
+
var cond = condFn ? condFn() : false;
|
|
1343
|
+
if (cond) {
|
|
1344
|
+
if (ifJS) eval(ifJS);
|
|
1345
|
+
el.innerHTML = ifHTML;
|
|
1346
|
+
} else {
|
|
1347
|
+
if (elseJS) eval(elseJS);
|
|
1348
|
+
el.innerHTML = elseHTML;
|
|
1349
|
+
}
|
|
1350
|
+
el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
|
|
1351
|
+
el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
|
|
1352
|
+
if (${needsDelay}) {
|
|
1353
|
+
el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1354
|
+
el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
`;
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
const exprArrayJS = exprRegistry.length > 0
|
|
1361
|
+
? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
|
|
1362
|
+
: "";
|
|
1363
|
+
|
|
1364
|
+
let renderBody = "";
|
|
1365
|
+
renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
|
|
1366
|
+
|
|
1367
|
+
if (needsLogic) {
|
|
1368
|
+
renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
if (needsMixed) {
|
|
1372
|
+
for (const mb of mixedBlocks) {
|
|
1373
|
+
renderBody += ` (function() {
|
|
1374
|
+
var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
|
|
1375
|
+
if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
|
|
1376
|
+
})();\n`;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
|
|
1381
|
+
var target = document.getElementById(el.dataset.sinthRemove);
|
|
1382
|
+
if (target) target.remove();
|
|
1383
|
+
});\n`;
|
|
1384
|
+
|
|
1385
|
+
if (needsIf) {
|
|
1386
|
+
renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
|
|
1387
|
+
}
|
|
1388
|
+
if (needsFor) {
|
|
1389
|
+
renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
|
|
1390
|
+
}
|
|
1391
|
+
renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
|
|
1392
|
+
try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
|
|
1393
|
+
});\n`;
|
|
1394
|
+
renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
|
|
1395
|
+
try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
|
|
1396
|
+
});\n`;
|
|
1397
|
+
if (needsExpr) {
|
|
1398
|
+
renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
|
|
1399
|
+
}
|
|
1400
|
+
if (needsDelay) {
|
|
1401
|
+
renderBody += ` setTimeout(function() {
|
|
1402
|
+
document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
|
|
1403
|
+
document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
|
|
1404
|
+
}, 0);\n`;
|
|
1405
|
+
}
|
|
1406
|
+
renderBody += ` window.scrollTo(_sx, _sy);\n`;
|
|
1407
|
+
|
|
1408
|
+
const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
|
|
1409
|
+
|
|
1410
|
+
const pageCode = `// Sinth page runtime
|
|
1411
|
+
${varLines}
|
|
1412
|
+
${exprArrayJS}
|
|
1413
|
+
${renderFunc}`;
|
|
1414
|
+
|
|
1415
|
+
if (opts.sharedRuntime && helpers.trim()) {
|
|
1416
|
+
const sharedCode = `// Sinth shared runtime
|
|
1417
|
+
${helpers}`;
|
|
1418
|
+
return { page: pageCode, shared: sharedCode };
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
return `// Sinth compiled runtime
|
|
1422
|
+
${varLines}
|
|
1423
|
+
${helpers}
|
|
1424
|
+
${exprArrayJS}
|
|
1425
|
+
${renderFunc}`;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
// main compilation pipeline
|
|
1429
|
+
|
|
1430
|
+
export interface CompileOptions {
|
|
1431
|
+
projectRoot: string;
|
|
1432
|
+
outDir: string;
|
|
1433
|
+
libraryPaths: string[];
|
|
1434
|
+
minify: boolean;
|
|
1435
|
+
checkOnly: boolean;
|
|
1436
|
+
sharedRuntime: boolean;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
export function compileFile(filePath: string, opts: CompileOptions): { html: string; shared?: string } | null {
|
|
1440
|
+
const absPath = path.resolve(filePath);
|
|
1441
|
+
const file = parseFile(absPath);
|
|
1442
|
+
|
|
1443
|
+
const cfg: ResolverConfig = { projectRoot: opts.projectRoot, libraryPaths: opts.libraryPaths };
|
|
1444
|
+
const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
|
|
1445
|
+
const hash = fnv1a(absPath);
|
|
1446
|
+
|
|
1447
|
+
const allVarDecls: VarDeclaration[] = file.varDecls;
|
|
1448
|
+
|
|
1449
|
+
const ctx: CompileCtx = {
|
|
1450
|
+
allDefs, customEls, cssLinks, jsLinks,
|
|
1451
|
+
scopeHash: hash,
|
|
1452
|
+
pageFile: absPath,
|
|
1453
|
+
extraCSS: [],
|
|
1454
|
+
mixedBlocks: [],
|
|
1455
|
+
mixedCounter: 0,
|
|
1456
|
+
logicBlocks: [],
|
|
1457
|
+
ifIdCounter: 0,
|
|
1458
|
+
exprRegistry: [],
|
|
1459
|
+
exprMap: new Map(),
|
|
1460
|
+
};
|
|
1461
|
+
|
|
1462
|
+
if (!file.isPage) {
|
|
1463
|
+
const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
1464
|
+
const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
|
|
1465
|
+
const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
|
|
1466
|
+
const h = `${body}\n<style>\n${allCSS}\n</style>`;
|
|
1467
|
+
return { html: h };
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
const headData = buildHeadData(file.meta);
|
|
1471
|
+
const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
|
|
1472
|
+
const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
|
|
1473
|
+
const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
|
|
1474
|
+
const { componentScripts, pageScripts } = collectScripts(file, allDefs);
|
|
1475
|
+
|
|
1476
|
+
// collect all assigned variables for default-value warnings
|
|
1477
|
+
const assignedVars = new Set<string>();
|
|
1478
|
+
for (const s of file.scripts) {
|
|
1479
|
+
for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+\-]?=)/g)) assignedVars.add(m[1]);
|
|
1480
|
+
}
|
|
1481
|
+
for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
|
|
1482
|
+
|
|
1483
|
+
// companion JS file (needs same name as .sinth, adds support for JS libraries)
|
|
1484
|
+
const companionJS = (() => {
|
|
1485
|
+
const base = absPath.replace(/\.sinth$/, ".js");
|
|
1486
|
+
return fs.existsSync(base) ? path.basename(base) : undefined;
|
|
1487
|
+
})();
|
|
1488
|
+
|
|
1489
|
+
const relativeCssLinks = cssLinks.map(css => {
|
|
1490
|
+
const rel = path.relative(path.dirname(absPath), css).replace(/\\/g, "/");
|
|
1491
|
+
return rel.startsWith(".") ? rel : "./" + rel;
|
|
1492
|
+
});
|
|
1493
|
+
const relativeJsLinks = jsLinks.map(js => ({
|
|
1494
|
+
...js,
|
|
1495
|
+
src: (() => {
|
|
1496
|
+
const rel = path.relative(path.dirname(absPath), js.src).replace(/\\/g, "/");
|
|
1497
|
+
return rel.startsWith(".") ? rel : "./" + rel;
|
|
1498
|
+
})(),
|
|
1499
|
+
}));
|
|
1500
|
+
|
|
1501
|
+
const runtimeResult = buildRuntime({
|
|
1502
|
+
varDecls: allVarDecls,
|
|
1503
|
+
bodyHTML,
|
|
1504
|
+
logicBlocks: ctx.logicBlocks,
|
|
1505
|
+
mixedBlocks: ctx.mixedBlocks,
|
|
1506
|
+
assignedVars,
|
|
1507
|
+
exprRegistry: ctx.exprRegistry,
|
|
1508
|
+
sharedRuntime: opts.sharedRuntime,
|
|
1509
|
+
});
|
|
1510
|
+
const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
|
|
1511
|
+
const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
|
|
1512
|
+
|
|
1513
|
+
|
|
1514
|
+
const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
|
|
1515
|
+
const scriptTags: string[] = [];
|
|
1516
|
+
if (componentScripts.length > 0) {
|
|
1517
|
+
scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
for (const s of pageScripts) {
|
|
1521
|
+
const extra = Object.entries(s.attrs)
|
|
1522
|
+
.map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
|
|
1523
|
+
.join(" ");
|
|
1524
|
+
const globalised = s.raw.replace(/\b(let|const)\b/g, "var");
|
|
1525
|
+
scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalised}\n</script>`);
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
|
|
1529
|
+
const sharedRuntimeTag = (() => {
|
|
1530
|
+
if (!opts.sharedRuntime || !sharedJS) return "";
|
|
1531
|
+
|
|
1532
|
+
const relPath = path.relative(opts.projectRoot, absPath);
|
|
1533
|
+
const htmlOutputDir = path.dirname(relPath.replace(/\.sinth$/, '.html'));
|
|
1534
|
+
const relativeRuntimePath = path.relative(htmlOutputDir, '.').replace(/\\/g, '/');
|
|
1535
|
+
const runtimeSrc = relativeRuntimePath ? `${relativeRuntimePath}/sinth-runtime.js` : './sinth-runtime.js';
|
|
1536
|
+
|
|
1537
|
+
return `<script src="${runtimeSrc}"></script>`;
|
|
1538
|
+
})();
|
|
1539
|
+
|
|
1540
|
+
const html = [
|
|
1541
|
+
"<!DOCTYPE html>",
|
|
1542
|
+
`<html lang="${escAttr(headData.lang)}">`,
|
|
1543
|
+
head,
|
|
1544
|
+
`<body data-s="${hash}">`,
|
|
1545
|
+
bodyHTML,
|
|
1546
|
+
sharedRuntimeTag,
|
|
1547
|
+
runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
|
|
1548
|
+
scriptTags.join("\n"),
|
|
1549
|
+
"</body>",
|
|
1550
|
+
"</html>",
|
|
1551
|
+
].filter(Boolean).join("\n");
|
|
1552
|
+
|
|
1553
|
+
const finalHTML = opts.minify ? minifyHTML(html) : html;
|
|
1554
|
+
return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
export function minifyHTML(html: string): string {
|
|
1558
|
+
return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
// file discovery & asset copy
|
|
1562
|
+
|
|
1563
|
+
export function findSinthPages(dir: string, outDir?: string): string[] {
|
|
1564
|
+
const results: string[] = [];
|
|
1565
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
1566
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
1567
|
+
const full = path.join(dir, entry.name);
|
|
1568
|
+
if (outDir && path.resolve(full) === path.resolve(outDir)) continue;
|
|
1569
|
+
if (entry.isDirectory()) results.push(...findSinthPages(full, outDir));
|
|
1570
|
+
else if (entry.name.endsWith(".sinth")) results.push(full);
|
|
1571
|
+
}
|
|
1572
|
+
return results;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
export function copyDir(src: string, dest: string): void {
|
|
1576
|
+
if (!fs.existsSync(src)) return;
|
|
1577
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
1578
|
+
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
|
1579
|
+
const sp = path.join(src, entry.name);
|
|
1580
|
+
const dp = path.join(dest, entry.name);
|
|
1581
|
+
if (entry.isDirectory()) copyDir(sp, dp);
|
|
1582
|
+
else fs.copyFileSync(sp, dp);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
|