@yannosay/sinth 0.13.1 → 0.13.2

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.
@@ -0,0 +1,299 @@
1
+ import { BUILTIN_MAP } from "./builtins.ts";
2
+ import { SinthError, SinthWarning, StyleBlock } from "./types.ts";
3
+ import { camelToKebab, interpolateAttr } from "../utils.ts";
4
+
5
+
6
+
7
+ /**
8
+ * for who's reading this: this maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
9
+ * these are used inside component style blocks, for example: onHover { color: "blue" }
10
+ */
11
+ export const SINTH_PSEUDO_CLASS: Record<string, string> = {
12
+ onHover: ":hover",
13
+ onFocus: ":focus",
14
+ onActive: ":active",
15
+ onVisited: ":visited",
16
+ onChecked: ":checked",
17
+ onDisabled: ":disabled",
18
+ onEnabled: ":enabled",
19
+ onRequired: ":required",
20
+ onOptional: ":optional",
21
+ onValid: ":valid",
22
+ onInvalid: ":invalid",
23
+ onPlaceholderShown:":placeholder-shown",
24
+ onFocusWithin: ":focus-within",
25
+ onFocusVisible: ":focus-visible",
26
+ onFirst: ":first-child",
27
+ onLast: ":last-child",
28
+ onFirstOfType: ":first-of-type",
29
+ onLastOfType: ":last-of-type",
30
+ onEmpty: ":empty",
31
+ onTarget: ":target",
32
+ onLink: ":link",
33
+ };
34
+
35
+ export const SINTH_PSEUDO_ELEMENT: Record<string, string> = {
36
+ before: "::before",
37
+ after: "::after",
38
+ placeholder: "::placeholder",
39
+ selection: "::selection",
40
+ firstLine: "::first-line",
41
+ firstLetter: "::first-letter",
42
+ marker: "::marker",
43
+ backdrop: "::backdrop",
44
+ };
45
+
46
+ export function sinthCompToSelector(name: string): string {
47
+ const info = BUILTIN_MAP[name];
48
+ if (!info) return name.toLowerCase();
49
+ if (info.defaultClass) {
50
+ const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
51
+ return `${info.tag}${classes}`;
52
+ }
53
+ return info.tag;
54
+ }
55
+
56
+ /**
57
+ * supported conversions:
58
+ * - component names as selectors: `Paragraph { ... }` → `p { ... }`
59
+ * - pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
60
+ * - pseudo-element shorthands: `before { ... }` → `&::before { ... }`
61
+ * - media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
62
+ * - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
63
+ */
64
+ export function preprocessSinthStyle(raw: string): string {
65
+ const lines = raw.split("\n");
66
+ const result: string[] = [];
67
+
68
+ for (const line of lines) {
69
+ const trimmed = line.trim();
70
+ const indent = line.match(/^(\s*)/)?.[1] ?? "";
71
+
72
+ if (!trimmed) { result.push(line); continue; }
73
+
74
+ if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) { continue; }
75
+ // Standard comments pass through
76
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
77
+ result.push(line); continue;
78
+ }
79
+
80
+ const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
81
+ if (mediaMatch) {
82
+ const params = parseSinthMediaParams(mediaMatch[1]);
83
+ result.push(`${indent}@media (${params}) {`);
84
+ continue;
85
+ }
86
+
87
+ const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
88
+ if (blockMatch) {
89
+ const keyword = blockMatch[1];
90
+
91
+ const pseudoCls = SINTH_PSEUDO_CLASS[keyword];
92
+ if (pseudoCls) {
93
+ result.push(`${indent}&${pseudoCls} {`);
94
+ continue;
95
+ }
96
+
97
+ const pseudoEl = SINTH_PSEUDO_ELEMENT[keyword];
98
+ if (pseudoEl) {
99
+ result.push(`${indent}&${pseudoEl} {`);
100
+ continue;
101
+ }
102
+
103
+ if (/^[A-Z]/.test(keyword) && BUILTIN_MAP[keyword]) {
104
+ result.push(`${indent}${sinthCompToSelector(keyword)} {`);
105
+ continue;
106
+ }
107
+ }
108
+
109
+ const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
110
+ if (varPropMatch) {
111
+ result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
112
+ continue;
113
+ }
114
+
115
+ result.push(line);
116
+ }
117
+
118
+ return result.join("\n");
119
+ }
120
+
121
+ export function parseSinthMediaParams(params: string): string {
122
+ const parts = params.split(",").map(p => {
123
+ const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
124
+ if (!m) return p.trim();
125
+ return `${camelToKebab(m[1])}: ${m[2].trim()}`;
126
+ });
127
+ return parts.join(") and (");
128
+ }
129
+
130
+ // style processor
131
+
132
+
133
+ export function convertCSSProps(css: string): string {
134
+ return css.split("\n").map(line => {
135
+ const trimmed = line.trim();
136
+ if (!trimmed) return line;
137
+ if (trimmed === "}" || trimmed.startsWith("}")) return line;
138
+ if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
139
+ if (trimmed.startsWith("@")) return line;
140
+ if (trimmed.includes("{")) return line;
141
+
142
+ const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
143
+ if (!m) return line;
144
+
145
+ const [, indent, rawProp, , rawVal] = m;
146
+
147
+ const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
148
+ const hasQuotedVal = /^["']/.test(rawVal.trim());
149
+ if (!hasCamelCase && !hasQuotedVal) return line;
150
+
151
+ let val = rawVal.trim();
152
+ if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
153
+ if ((val.startsWith('"') && val.endsWith('"')) ||
154
+ (val.startsWith("'") && val.endsWith("'"))) {
155
+ val = val.slice(1, -1);
156
+ }
157
+
158
+ return `${indent}${camelToKebab(rawProp)}: ${val};`;
159
+ }).join("\n");
160
+ }
161
+
162
+ export function processStyleBlock(
163
+ block: StyleBlock,
164
+ hash: string,
165
+ params: Map<string, string> = new Map(),
166
+ ): string {
167
+ let raw = block.raw;
168
+
169
+ // 1. interpolate {param} placeholders
170
+ if (params.size > 0) raw = interpolateAttr(raw, params);
171
+
172
+ // 2. sinth style preprocessing
173
+ raw = preprocessSinthStyle(raw);
174
+
175
+ // 3. warn if & in plain CSS
176
+ if (block.lang === "css" && raw.includes("&")) {
177
+ SinthWarning.emit(
178
+ `'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
179
+ block.loc,
180
+ );
181
+ }
182
+
183
+ // 4. camelCase → kebab-case
184
+ let css = convertCSSProps(raw);
185
+
186
+ // 5. SCSS compilation
187
+ if (block.lang === "scss") {
188
+ try {
189
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
190
+ const sass: { compileString: (src: string) => { css: string } } = require("sass");
191
+ css = sass.compileString(css).css;
192
+ } catch (e: unknown) {
193
+ const err = e as { code?: string; message?: string };
194
+ if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
195
+ throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
196
+ }
197
+ throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
198
+ }
199
+ }
200
+
201
+ // 6. if target component given, wrap content in its CSS selector
202
+ if (block.target) {
203
+ const selector = sinthCompToSelector(block.target);
204
+ css = `${selector} {\n${css}\n}`;
205
+ }
206
+
207
+ // 7. scope (except it's global)
208
+ if (!block.global) css = scopeCSS(css, hash);
209
+
210
+ return css;
211
+ }
212
+
213
+ export function scopeCSS(css: string, hash: string): string {
214
+ return processRules(css, `[data-s="${hash}"]`);
215
+ }
216
+
217
+ export function processRules(css: string, attr: string): string {
218
+ let out = "", i = 0;
219
+
220
+ while (i < css.length) {
221
+ if (/\s/.test(css[i])) { out += css[i++]; continue; }
222
+
223
+ if (css[i] === "/" && css[i + 1] === "*") {
224
+ const end = css.indexOf("*/", i + 2);
225
+ if (end === -1) { out += css.substring(i); break; }
226
+ out += css.substring(i, end + 2);
227
+ i = end + 2;
228
+ continue;
229
+ }
230
+
231
+ const braceIdx = findCSSBrace(css, i);
232
+ if (braceIdx === -1) { out += css.substring(i); break; }
233
+
234
+ const selector = css.substring(i, braceIdx).trim();
235
+ const { content, end } = extractCSSBlock(css, braceIdx);
236
+
237
+ if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
238
+ out += `${selector} {${content}}\n`;
239
+ } else if (/^@(media|supports|layer|container)/.test(selector)) {
240
+ out += `${selector} {\n${processRules(content, attr)}\n}\n`;
241
+ } else if (selector.startsWith("@")) {
242
+ out += `${selector} {${content}}\n`;
243
+ } else if (selector.length > 0) {
244
+ out += `${scopeSelectors(selector, attr)} {${content}}\n`;
245
+ }
246
+
247
+ i = end;
248
+ }
249
+ return out;
250
+ }
251
+
252
+ export function scopeSelectors(selList: string, attr: string): string {
253
+ return selList
254
+ .split(",")
255
+ .map(s => {
256
+ s = s.trim();
257
+ if (!s) return "";
258
+ if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
259
+ const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
260
+ if (m && m[1].trim()) {
261
+ return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
262
+ }
263
+ return `${attr} ${s}, ${s}${attr}`;
264
+ })
265
+ .filter(Boolean)
266
+ .join(",\n");
267
+ }
268
+
269
+ export function findCSSBrace(css: string, from: number): number {
270
+ let i = from;
271
+ while (i < css.length) {
272
+ if (css[i] === '"' || css[i] === "'") {
273
+ const q = css[i++];
274
+ while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
275
+ i++;
276
+ } else if (css[i] === "{") {
277
+ return i;
278
+ } else { i++; }
279
+ }
280
+ return -1;
281
+ }
282
+
283
+ export function extractCSSBlock(css: string, openBrace: number): { content: string; end: number } {
284
+ let i = openBrace + 1, depth = 1;
285
+ while (i < css.length && depth > 0) {
286
+ if (css[i] === '"' || css[i] === "'") {
287
+ const q = css[i++];
288
+ while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
289
+ i++;
290
+ } else if (css[i] === "/" && css[i + 1] === "*") {
291
+ i += 2;
292
+ while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/")) i++;
293
+ i += 2;
294
+ } else if (css[i] === "{") { depth++; i++; }
295
+ else if (css[i] === "}") { depth--; if (depth > 0) i++; else break; }
296
+ else { i++; }
297
+ }
298
+ return { content: css.substring(openBrace + 1, i), end: i + 1 };
299
+ }
package/src/resolver.ts CHANGED
@@ -3,7 +3,7 @@ import * as path from "path";
3
3
  import { SinthFile, CompDef, CustomElInfo, SinthError, SinthWarning } from "./core/types.ts";
4
4
  import { Lexer } from "./core/lexer.ts";
5
5
  import { Parser } from "./core/parser.ts";
6
- import { BUILTIN_MAP } from "./core/compiler.ts";
6
+ import { BUILTIN_MAP } from "./core/builtins.ts";
7
7
 
8
8
 
9
9
 
package/src/utils.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Literal } from "./core/types.ts";
1
+ import { Literal, SinthWarning } from "./core/types.ts";
2
2
 
3
3
 
4
4
  export function fnv1a(s: string): string {
@@ -35,4 +35,43 @@ export function litToString(lit: Literal): string {
35
35
  case "bool": return String(lit.value);
36
36
  case "null": return "";
37
37
  }
38
+ }
39
+
40
+ export function interpolateAttr(text: string, params: Map<string, string>): string {
41
+ let s = text.replace(/\\\{/g, "\x00LB\x00");
42
+ s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
43
+ return s.replace(/\x00LB\x00/g, "{");
44
+ }
45
+
46
+ export function renderText(text: string, params: Map<string, string>): string {
47
+ const rawSlots = new Map<string, string>();
48
+ let counter = 0;
49
+
50
+ let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
51
+
52
+ s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
53
+ const val = params.get(n);
54
+ if (val === undefined) return `$${n}`;
55
+ if (n === "slot") {
56
+ const ph = `\x00RAW${counter++}\x00`;
57
+ rawSlots.set(ph, val);
58
+ return ph;
59
+ }
60
+ return val;
61
+ });
62
+
63
+ s = esc(s);
64
+
65
+ for (const [ph, val] of rawSlots) s = s.replace(ph, val);
66
+ s = s.replace(/\x00DOLLAR\x00/g, "$");
67
+
68
+ const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
69
+ let m: RegExpExecArray | null;
70
+ while ((m = braceRe.exec(s)) !== null) {
71
+ SinthWarning.emit(
72
+ `Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
73
+ );
74
+ }
75
+
76
+ return s;
38
77
  }