@yannosay/sinth 1.11.6 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js ADDED
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.LIVE_RELOAD_SCRIPT = void 0;
37
+ exports.startDevServer = startDevServer;
38
+ const http = __importStar(require("http"));
39
+ const path = __importStar(require("path"));
40
+ const fs = __importStar(require("fs"));
41
+ const cli_compiler_1 = require("./core/cli-compiler");
42
+ exports.LIVE_RELOAD_SCRIPT = `<script>
43
+ (function(){
44
+ var es = new EventSource('/__sinth_sse__');
45
+ es.onmessage = function() { location.reload(); };
46
+ es.onerror = function() { setTimeout(function() { location.reload(); }, 1000); };
47
+ })();
48
+ </script>`;
49
+ async function startDevServer(opts) {
50
+ const clients = [];
51
+ const cache = new Map();
52
+ function notify() {
53
+ for (const c of clients) {
54
+ try {
55
+ c.write("data: reload\n\n");
56
+ }
57
+ catch { }
58
+ }
59
+ }
60
+ function compileAll() {
61
+ cache.clear();
62
+ const pages = (opts.files && opts.files.length > 0)
63
+ ? opts.files.filter(f => fs.existsSync(f))
64
+ : (0, cli_compiler_1.findSinthPages)(opts.projectRoot, opts.outDir);
65
+ for (const p of pages) {
66
+ try {
67
+ const result = (0, cli_compiler_1.compileFile)(p, { ...opts, checkOnly: false });
68
+ if (!result)
69
+ continue;
70
+ const html = result.html;
71
+ const rel = path.relative(opts.projectRoot, p).replace(/\.sinth$/, ".html").replace(/\\/g, "/");
72
+ const url = "/" + rel;
73
+ cache.set(url, html + exports.LIVE_RELOAD_SCRIPT);
74
+ if (rel === "index.html" || rel.endsWith("/index.html")) {
75
+ cache.set("/", html + exports.LIVE_RELOAD_SCRIPT);
76
+ }
77
+ }
78
+ catch (e) {
79
+ process.stderr.write(`\x1b[31m${e.message}\x1b[0m\n`);
80
+ }
81
+ }
82
+ }
83
+ compileAll();
84
+ const resolvedOut = path.resolve(opts.outDir);
85
+ let watchReady = false;
86
+ const pending = new Map();
87
+ const DEBOUNCE_MS = 300;
88
+ try {
89
+ fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
90
+ if (!filename)
91
+ return;
92
+ const abs = path.resolve(opts.projectRoot, filename);
93
+ if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut)
94
+ return;
95
+ if (pending.has(abs)) {
96
+ clearTimeout(pending.get(abs));
97
+ }
98
+ pending.set(abs, setTimeout(() => {
99
+ pending.delete(abs);
100
+ process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
101
+ compileAll();
102
+ notify();
103
+ }, DEBOUNCE_MS));
104
+ });
105
+ watchReady = true;
106
+ }
107
+ catch { }
108
+ if (!watchReady) {
109
+ const mtimes = new Map();
110
+ const poller = setInterval(() => {
111
+ const pages = (opts.files && opts.files.length > 0)
112
+ ? opts.files : (0, cli_compiler_1.findSinthPages)(opts.projectRoot, opts.outDir);
113
+ for (const p of pages) {
114
+ try {
115
+ const mtime = fs.statSync(p).mtimeMs;
116
+ if (mtimes.get(p) !== mtime) {
117
+ mtimes.set(p, mtime);
118
+ process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${path.relative(opts.projectRoot, p)}\n`);
119
+ compileAll();
120
+ notify();
121
+ break;
122
+ }
123
+ }
124
+ catch { }
125
+ }
126
+ }, 500);
127
+ process.on("exit", () => clearInterval(poller));
128
+ }
129
+ const EXT_TYPES = {
130
+ ".css": "text/css", ".js": "application/javascript",
131
+ ".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon",
132
+ ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
133
+ ".gif": "image/gif", ".webp": "image/webp",
134
+ ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf",
135
+ ".json": "application/json", ".xml": "application/xml",
136
+ };
137
+ const server = http.createServer((req, res) => {
138
+ const reqUrl = (req.url ?? "/").split("?")[0];
139
+ if (reqUrl === "/__sinth_sse__") {
140
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
141
+ clients.push(res);
142
+ req.on("close", () => { const i = clients.indexOf(res); if (i !== -1)
143
+ clients.splice(i, 1); });
144
+ return;
145
+ }
146
+ const cached = cache.get(reqUrl) ??
147
+ cache.get(reqUrl.endsWith("/") ? reqUrl + "index.html" : reqUrl + ".html");
148
+ if (cached) {
149
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
150
+ res.end(cached);
151
+ return;
152
+ }
153
+ let filePath = path.join(opts.projectRoot, reqUrl);
154
+ if (reqUrl.endsWith("/"))
155
+ filePath = path.join(filePath, "index.html");
156
+ if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
157
+ const ctype = EXT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
158
+ res.writeHead(200, { "Content-Type": ctype });
159
+ res.end(fs.readFileSync(filePath));
160
+ return;
161
+ }
162
+ res.writeHead(404, { "Content-Type": "text/plain" });
163
+ res.end("404 Not Found");
164
+ });
165
+ server.listen(opts.port, () => {
166
+ process.stdout.write(`\x1b[32m[sinth dev]\x1b[0m Serving at \x1b[4mhttp://localhost:${opts.port}\x1b[0m\n`);
167
+ });
168
+ }
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.checkForUpdate = checkForUpdate;
37
+ const https = __importStar(require("https"));
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const os = __importStar(require("os"));
41
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
42
+ const CACHE_DIR = path.join(os.tmpdir(), ".sinth-cache");
43
+ const CACHE_FILE = path.join(CACHE_DIR, "update-check.json");
44
+ function readCache() {
45
+ try {
46
+ if (fs.existsSync(CACHE_FILE)) {
47
+ return JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
48
+ }
49
+ }
50
+ catch { }
51
+ return null;
52
+ }
53
+ function writeCache() {
54
+ try {
55
+ fs.mkdirSync(CACHE_DIR, { recursive: true });
56
+ fs.writeFileSync(CACHE_FILE, JSON.stringify({ lastCheck: Date.now() }));
57
+ }
58
+ catch { }
59
+ }
60
+ function fetchLatestVersion() {
61
+ return new Promise((resolve) => {
62
+ const req = https.get("https://registry.npmjs.org/@yannosay/sinth/latest", { timeout: 3000 }, (res) => {
63
+ let data = "";
64
+ res.on("data", (chunk) => (data += chunk.toString()));
65
+ res.on("end", () => {
66
+ try {
67
+ const json = JSON.parse(data);
68
+ resolve(json.version ?? null);
69
+ }
70
+ catch {
71
+ resolve(null);
72
+ }
73
+ });
74
+ });
75
+ req.on("error", () => resolve(null));
76
+ req.on("timeout", () => {
77
+ req.destroy();
78
+ resolve(null);
79
+ });
80
+ });
81
+ }
82
+ async function checkForUpdate(currentVersion) {
83
+ const cache = readCache();
84
+ if (cache && Date.now() - cache.lastCheck < CHECK_INTERVAL_MS)
85
+ return;
86
+ writeCache();
87
+ const latest = await fetchLatestVersion();
88
+ if (!latest || latest === currentVersion)
89
+ return;
90
+ // simple semver compare (major.minor.patch)
91
+ const curParts = currentVersion.split(".").map(Number);
92
+ const latParts = latest.split(".").map(Number);
93
+ for (let i = 0; i < 3; i++) {
94
+ if ((latParts[i] ?? 0) > (curParts[i] ?? 0)) {
95
+ process.stdout.write(`\n\x1b[2m✨ Sinth ${latest} is available! Run \x1b[1msinth update\x1b[0m\x1b[2m to upgrade.\x1b[0m\n\n`);
96
+ return;
97
+ }
98
+ if ((latParts[i] ?? 0) < (curParts[i] ?? 0))
99
+ return; // local is newer (dev)
100
+ }
101
+ }
package/dist/utils.js ADDED
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fnv1a = fnv1a;
4
+ exports.camelToKebab = camelToKebab;
5
+ exports.tagNameToPascal = tagNameToPascal;
6
+ exports.esc = esc;
7
+ exports.escAttr = escAttr;
8
+ exports.litToString = litToString;
9
+ exports.interpolateAttr = interpolateAttr;
10
+ exports.renderText = renderText;
11
+ const types_1 = require("./core/types");
12
+ function fnv1a(s) {
13
+ let h = 0x811c9dc5;
14
+ for (let i = 0; i < s.length; i++) {
15
+ h ^= s.charCodeAt(i);
16
+ h = Math.imul(h, 0x01000193) >>> 0;
17
+ }
18
+ return h.toString(16).padStart(8, "0").slice(0, 8);
19
+ }
20
+ function camelToKebab(s) {
21
+ const vp = s.match(/^(Webkit|Moz|Ms)(.+)$/);
22
+ if (vp)
23
+ return `-${vp[1].toLowerCase()}-${camelToKebab(vp[2])}`;
24
+ return s.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`);
25
+ }
26
+ function tagNameToPascal(tag) {
27
+ return tag.split("-").map(p => p.charAt(0).toUpperCase() + p.slice(1)).join("");
28
+ }
29
+ function esc(s) {
30
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
31
+ }
32
+ function escAttr(s) {
33
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
34
+ }
35
+ function litToString(lit) {
36
+ switch (lit.kind) {
37
+ case "str": return lit.value;
38
+ case "num": return String(lit.value);
39
+ case "bool": return String(lit.value);
40
+ case "null": return "";
41
+ }
42
+ }
43
+ function interpolateAttr(text, params) {
44
+ let s = text.replace(/\\\{/g, "\x00LB\x00");
45
+ s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
46
+ return s.replace(/\x00LB\x00/g, "{");
47
+ }
48
+ function renderText(text, params) {
49
+ const rawSlots = new Map();
50
+ let counter = 0;
51
+ let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
52
+ s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
53
+ const val = params.get(n);
54
+ if (val === undefined)
55
+ return `$${n}`;
56
+ if (n === "slot") {
57
+ const ph = `\x00RAW${counter++}\x00`;
58
+ rawSlots.set(ph, val);
59
+ return ph;
60
+ }
61
+ return val;
62
+ });
63
+ s = esc(s);
64
+ for (const [ph, val] of rawSlots)
65
+ s = s.replace(ph, val);
66
+ s = s.replace(/\x00DOLLAR\x00/g, "$");
67
+ const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
68
+ let m;
69
+ while ((m = braceRe.exec(s)) !== null) {
70
+ types_1.SinthWarning.emit(`Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`);
71
+ }
72
+ return s;
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "1.11.6",
3
+ "version": "1.12.1",
4
4
  "description": "A declarative & reactive language that compiles to pure HTML, CSS, and JavaScript.",
5
5
  "author": "Yannosay Productions",
6
6
  "license": "AGPL-3.0",
@@ -21,28 +21,32 @@
21
21
  "web",
22
22
  "components",
23
23
  "scss",
24
- "reactive"
24
+ "reactive",
25
+ "react"
25
26
  ],
26
27
  "bin": {
27
28
  "sinth": "bin/sinth.js"
28
29
  },
29
30
  "files": [
30
31
  "bin/",
31
- "src/",
32
+ "dist/",
32
33
  "assets/",
33
- "tsconfig.json",
34
34
  "README.md",
35
35
  "LICENSE"
36
36
  ],
37
+ "scripts": {
38
+ "build": "tsc",
39
+ "prepublishOnly": "npm run build"
40
+ },
37
41
  "dependencies": {
38
- "sass": "^1.70.0",
39
- "ts-node": "^10.9.0"
42
+ "sass": "^1.70.0"
40
43
  },
41
44
  "devDependencies": {
42
45
  "@types/node": "^20.19.41",
43
- "typescript": "^5.3.0"
46
+ "typescript": "^5.3.0",
47
+ "ts-node": "^10.9.0"
44
48
  },
45
49
  "engines": {
46
50
  "node": ">=18.0.0"
47
51
  }
48
- }
52
+ }
@@ -1,72 +0,0 @@
1
- import { Lexer } from "../core/lexer.ts";
2
- import { Parser } from "../core/parser.ts";
3
- import { SinthFile, CompileCtx } from "../core/types.ts";
4
- import { buildRuntime, renderCompUse } from "../core/compiler.ts";
5
- import { fnv1a } from "../utils.ts";
6
- import { processStyleBlock } from "../core/style-processor.ts";
7
-
8
- export interface BrowserCompileResult {
9
- html: string;
10
- js: string;
11
- }
12
-
13
- export function compileSinth(source: string): BrowserCompileResult | null {
14
- const tokens = new Lexer(source, "<script>").tokenize();
15
- const parser = new Parser(tokens, "<script>");
16
- const file: SinthFile = parser.parse();
17
-
18
- if (!file.isPage) return null;
19
-
20
- const hash = fnv1a("<script>" + Math.random().toString(36));
21
- const instanceId = "s" + Math.random().toString(36).slice(2, 8);
22
-
23
- const ctx: CompileCtx = {
24
- allDefs: new Map(),
25
- functionDefs: file.functions,
26
- customEls: new Map(),
27
- cssLinks: [],
28
- jsLinks: [],
29
- scopeHash: hash,
30
- pageFile: "<script>",
31
- extraCSS: [],
32
- mixedBlocks: [],
33
- mixedCounter: 0,
34
- logicBlocks: [],
35
- ifIdCounter: 0,
36
- exprRegistry: [],
37
- exprMap: new Map(),
38
- varDecls: file.varDecls,
39
- actionButtons: [],
40
- diffingEnabled: false,
41
- declaredVars: new Set(file.varDecls.map(v => v.name)),
42
- namespace: instanceId,
43
- };
44
-
45
- const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
46
- const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
47
-
48
- const assignedVars = new Set<string>();
49
- for (const v of file.varDecls) {
50
- if (v.value) assignedVars.add(v.name);
51
- }
52
-
53
- const runtime = buildRuntime({
54
- varDecls: file.varDecls,
55
- bodyHTML,
56
- logicBlocks: ctx.logicBlocks,
57
- mixedBlocks: ctx.mixedBlocks,
58
- assignedVars,
59
- exprRegistry: ctx.exprRegistry,
60
- sharedRuntime: false,
61
- functionsJS: "",
62
- namespace: instanceId,
63
- });
64
-
65
- const js = typeof runtime === 'string' ? runtime : runtime.page;
66
- const scopedJs = js;
67
-
68
- return {
69
- html: `<div data-s="${hash}">${bodyHTML}</div><style>${pageCSS}</style>`,
70
- js: scopedJs,
71
- };
72
- }