@yannosay/sinth 4.0.0 → 5.1.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/DOCS.md +1359 -0
  3. package/README.md +83 -74
  4. package/bin/sinth.js +2 -1
  5. package/dist/cli/args.d.ts +11 -0
  6. package/dist/cli/args.js +74 -0
  7. package/dist/cli/index.d.ts +1 -0
  8. package/dist/cli/index.js +437 -0
  9. package/dist/cli/templates.d.ts +10 -0
  10. package/dist/cli/templates.js +193 -0
  11. package/dist/cli/ui.d.ts +28 -0
  12. package/dist/cli/ui.js +61 -0
  13. package/dist/cli/update-check.d.ts +2 -0
  14. package/dist/cli/update-check.js +124 -0
  15. package/dist/compiler/ast.d.ts +315 -0
  16. package/dist/compiler/ast.js +4 -0
  17. package/dist/compiler/codegen.d.ts +143 -0
  18. package/dist/compiler/codegen.js +1326 -0
  19. package/dist/compiler/diagnostics.d.ts +36 -0
  20. package/dist/compiler/diagnostics.js +142 -0
  21. package/dist/compiler/elements.d.ts +14 -0
  22. package/dist/compiler/elements.js +78 -0
  23. package/dist/compiler/globals.d.ts +2 -0
  24. package/dist/compiler/globals.js +27 -0
  25. package/dist/compiler/html.d.ts +37 -0
  26. package/dist/compiler/html.js +152 -0
  27. package/dist/compiler/lexer.d.ts +42 -0
  28. package/dist/compiler/lexer.js +404 -0
  29. package/dist/compiler/parser.d.ts +95 -0
  30. package/dist/compiler/parser.js +1374 -0
  31. package/dist/compiler/prerender.d.ts +72 -0
  32. package/dist/compiler/prerender.js +910 -0
  33. package/dist/compiler/script-analysis.d.ts +6 -0
  34. package/dist/compiler/script-analysis.js +106 -0
  35. package/dist/compiler/style.d.ts +39 -0
  36. package/dist/compiler/style.js +463 -0
  37. package/dist/deploy/cloudflare.d.ts +9 -0
  38. package/dist/deploy/cloudflare.js +111 -0
  39. package/dist/index.d.ts +13 -0
  40. package/dist/index.js +23 -0
  41. package/dist/project/build.d.ts +31 -0
  42. package/dist/project/build.js +425 -0
  43. package/dist/project/config.d.ts +33 -0
  44. package/dist/project/config.js +142 -0
  45. package/dist/project/project.d.ts +74 -0
  46. package/dist/project/project.js +535 -0
  47. package/dist/runtime/index.d.ts +68 -0
  48. package/dist/runtime/index.js +912 -0
  49. package/dist/server/client.d.ts +1 -0
  50. package/dist/server/client.js +112 -0
  51. package/dist/server/dev.d.ts +8 -0
  52. package/dist/server/dev.js +244 -0
  53. package/dist/server/preview.d.ts +6 -0
  54. package/dist/server/preview.js +106 -0
  55. package/dist/server/static.d.ts +10 -0
  56. package/dist/server/static.js +136 -0
  57. package/lib/ui/index.sinth +436 -0
  58. package/package.json +33 -15
  59. package/schema/sinth.config.schema.json +54 -0
  60. package/dist/browser/compile.js +0 -62
  61. package/dist/cli.js +0 -509
  62. package/dist/core/builtins.js +0 -117
  63. package/dist/core/cli-compiler.js +0 -683
  64. package/dist/core/compiler.js +0 -1428
  65. package/dist/core/expr.js +0 -125
  66. package/dist/core/head-builder.js +0 -130
  67. package/dist/core/lexer.js +0 -414
  68. package/dist/core/parser.js +0 -1665
  69. package/dist/core/runtime/custom-element.js +0 -81
  70. package/dist/core/runtime/functions.js +0 -99
  71. package/dist/core/runtime/helpers.js +0 -347
  72. package/dist/core/runtime/render.js +0 -136
  73. package/dist/core/style-processor.js +0 -317
  74. package/dist/core/types.js +0 -93
  75. package/dist/resolver.js +0 -175
  76. package/dist/server.js +0 -174
  77. package/dist/update-check.js +0 -109
  78. package/dist/utils.js +0 -80
@@ -0,0 +1 @@
1
+ export declare const DEV_CLIENT: string;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEV_CLIENT = void 0;
4
+ exports.DEV_CLIENT = String.raw `
5
+ const OVERLAY_ID = "__sinth_overlay";
6
+ const state = { hashes: null, connected: false };
7
+
8
+ function escapeHtml(s) {
9
+ return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
10
+ }
11
+
12
+ function currentRoute() {
13
+ let p = location.pathname.replace(/\/index\.html$/, "/").replace(/\.html$/, "");
14
+ if (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
15
+ return p || "/";
16
+ }
17
+
18
+ function showOverlay(title, message, kind) {
19
+ hideOverlay();
20
+ const host = document.createElement("div");
21
+ host.id = OVERLAY_ID;
22
+ const root = host.attachShadow({ mode: "open" });
23
+ root.innerHTML =
24
+ "<style>" +
25
+ ":host{all:initial}" +
26
+ ".backdrop{position:fixed;inset:0;z-index:2147483647;background:rgba(10,10,11,.86);backdrop-filter:blur(6px);display:flex;align-items:flex-start;justify-content:center;padding:6vh 16px;overflow:auto;font-family:ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif;color:#F5F5F6}" +
27
+ ".panel{width:min(920px,100%);background:#141416;border:1px solid #2a2a2e;border-radius:14px;box-shadow:0 30px 80px rgba(0,0,0,.5);overflow:hidden}" +
28
+ ".head{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #2a2a2e}" +
29
+ ".badge{font-size:11px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;padding:4px 8px;border-radius:6px;background:" + (kind === "runtime" ? "#3b2a10;color:#fbbf24" : "#3a1418;color:#f87171") + "}" +
30
+ ".title{font-size:15px;font-weight:600;flex:1}" +
31
+ "button{all:unset;cursor:pointer;color:#a1a1aa;font-size:13px;padding:6px 10px;border-radius:6px}button:hover{background:#232327;color:#F5F5F6}" +
32
+ "pre{margin:0;padding:20px;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word;color:#e4e4e7}" +
33
+ ".foot{padding:12px 20px;border-top:1px solid #2a2a2e;font-size:12px;color:#71717a}" +
34
+ "</style>" +
35
+ "<div class='backdrop'><div class='panel' role='alertdialog' aria-modal='true'>" +
36
+ "<div class='head'><span class='badge'>" + (kind === "runtime" ? "Runtime error" : "Compile error") + "</span><span class='title'>" + escapeHtml(title) + "</span><button type='button'>Dismiss (Esc)</button></div>" +
37
+ "<pre>" + escapeHtml(message) + "</pre>" +
38
+ "<div class='foot'>Fix the problem and save. The page updates automatically.</div>" +
39
+ "</div></div>";
40
+ root.querySelector("button").addEventListener("click", hideOverlay);
41
+ document.documentElement.appendChild(host);
42
+ }
43
+
44
+ function hideOverlay() {
45
+ const el = document.getElementById(OVERLAY_ID);
46
+ if (el) el.remove();
47
+ }
48
+
49
+ addEventListener("keydown", e => { if (e.key === "Escape") hideOverlay(); });
50
+
51
+ globalThis.__sinth_error__ = err => {
52
+ showOverlay(err && err.message ? err.message : String(err), err && err.stack ? err.stack : String(err), "runtime");
53
+ };
54
+ addEventListener("error", e => { if (e.error) globalThis.__sinth_error__(e.error); });
55
+ addEventListener("unhandledrejection", e => globalThis.__sinth_error__(e.reason));
56
+
57
+ function swapCss(href) {
58
+ const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
59
+ const base = href.split("?")[0];
60
+ const old = links.find(l => l.getAttribute("href").split("?")[0] === base);
61
+ const next = document.createElement("link");
62
+ next.rel = "stylesheet";
63
+ next.href = base + "?t=" + Date.now();
64
+ next.onload = () => { if (old) old.remove(); };
65
+ if (old) old.after(next); else document.head.appendChild(next);
66
+ }
67
+
68
+ async function hotSwap(js) {
69
+ const app = globalThis.__sinth_app__;
70
+ if (app) app.dispose();
71
+ await import(js + "?t=" + Date.now());
72
+ }
73
+
74
+ function apply(pages) {
75
+ const route = currentRoute();
76
+ const me = pages.find(p => p.route === route);
77
+ const prev = state.hashes && state.hashes.find(p => p.route === route);
78
+ state.hashes = pages;
79
+ if (!me || !prev) return;
80
+ if (me.head !== prev.head || (!!me.js) !== (!!prev.js) || (!me.js && me.body !== prev.body)) {
81
+ location.reload();
82
+ return;
83
+ }
84
+ if (me.cssHash !== prev.cssHash && me.css) swapCss(me.css);
85
+ if (me.jsHash !== prev.jsHash && me.js) hotSwap(me.js).catch(err => { console.error(err); location.reload(); });
86
+ }
87
+
88
+ function connect() {
89
+ const es = new EventSource("/__sinth/events");
90
+ es.onopen = () => {
91
+ if (state.connected === "lost") location.reload();
92
+ state.connected = true;
93
+ };
94
+ es.onmessage = e => {
95
+ const msg = JSON.parse(e.data);
96
+ if (msg.type === "error") showOverlay(msg.title, msg.message, "compile");
97
+ else if (msg.type === "reload") location.reload();
98
+ else if (msg.type === "update") {
99
+ hideOverlay();
100
+ if (msg.full) location.reload();
101
+ else apply(msg.pages);
102
+ } else if (msg.type === "init") {
103
+ state.hashes = msg.pages;
104
+ if (msg.error) showOverlay(msg.error.title, msg.error.message, "compile");
105
+ }
106
+ };
107
+ es.onerror = () => {
108
+ if (state.connected === true) state.connected = "lost";
109
+ };
110
+ }
111
+ connect();
112
+ `;
@@ -0,0 +1,8 @@
1
+ import { Project } from "../project/project";
2
+ export interface DevServerOptions {
3
+ port: number;
4
+ host: string;
5
+ open: boolean;
6
+ }
7
+ export declare function startDevServer(project: Project, opts: DevServerOptions): Promise<void>;
8
+ export declare function openBrowser(url: string): void;
@@ -0,0 +1,244 @@
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.startDevServer = startDevServer;
37
+ exports.openBrowser = openBrowser;
38
+ const crypto = __importStar(require("crypto"));
39
+ const fs = __importStar(require("fs"));
40
+ const http = __importStar(require("http"));
41
+ const path = __importStar(require("path"));
42
+ const diagnostics_1 = require("../compiler/diagnostics");
43
+ const html_1 = require("../compiler/html");
44
+ const build_1 = require("../project/build");
45
+ const ui_1 = require("../cli/ui");
46
+ const client_1 = require("./client");
47
+ const static_1 = require("./static");
48
+ const CLIENT_URL = "/__sinth/client.js";
49
+ const IGNORED = /(^|[\\/])(node_modules|\.git|\.sinth|\.wrangler|dist)([\\/]|$)/;
50
+ const WATCHED_EXT = /\.(sinth|css|scss|sass|js|mjs|ts|tsx|jsx|json|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|otf|txt|xml|webmanifest|html)$/i;
51
+ function hash(data) {
52
+ if (!data)
53
+ return "";
54
+ return crypto.createHash("sha1").update(data).digest("base64").slice(0, 12);
55
+ }
56
+ function errorPage(title, message) {
57
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sinth error</title>
58
+ <style>body{margin:0;background:#0A0A0B;color:#F5F5F6;font-family:ui-sans-serif,system-ui,sans-serif}main{max-width:920px;margin:8vh auto;padding:0 16px}h1{font-size:18px;color:#f87171}pre{background:#141416;border:1px solid #2a2a2e;border-radius:12px;padding:20px;white-space:pre-wrap;font:13px/1.6 ui-monospace,Menlo,Consolas,monospace}</style>
59
+ <script type="module" src="${CLIENT_URL}"></script></head><body><main><h1>${(0, html_1.escapeHtml)(title)}</h1><pre>${(0, html_1.escapeHtml)(message)}</pre><p>Fix the problem and save. This page reloads automatically.</p></main></body></html>`;
60
+ }
61
+ async function startDevServer(project, opts) {
62
+ const cfg = project.config;
63
+ const clients = new Set();
64
+ let output = null;
65
+ let lastError = null;
66
+ let hashes = [];
67
+ let building = null;
68
+ let pending = false;
69
+ const broadcast = (msg) => {
70
+ const data = `data: ${JSON.stringify(msg)}\n\n`;
71
+ for (const res of clients)
72
+ res.write(data);
73
+ };
74
+ const computeHashes = (out) => out.pages.map(p => {
75
+ const headEnd = p.html.indexOf("</head>");
76
+ const fileFor = (url) => (url ? out.files.get(url.slice(cfg.base.length))?.contents : undefined);
77
+ return {
78
+ route: p.page.route, js: p.js, css: p.css, jsHash: hash(fileFor(p.js)), cssHash: hash(fileFor(p.css)),
79
+ head: hash(p.html.slice(0, headEnd).replace(/\?t=\d+/g, "")), body: hash(p.html.slice(headEnd)),
80
+ };
81
+ });
82
+ const rebuild = async (changed) => {
83
+ const started = Date.now();
84
+ try {
85
+ const out = await (0, build_1.buildProject)(project, { write: false, devClient: CLIENT_URL });
86
+ output = out;
87
+ lastError = null;
88
+ const next = computeHashes(out);
89
+ const routesChanged = next.map(p => p.route).join() !== hashes.map(p => p.route).join();
90
+ hashes = next;
91
+ for (const w of out.warnings)
92
+ (0, ui_1.printDiagnostic)(w);
93
+ broadcast({ type: "update", pages: next, full: routesChanged });
94
+ if (changed)
95
+ ui_1.log.success(`${ui_1.c.gray(path.relative(project.root, changed))} ${ui_1.c.dim("updated in " + (0, ui_1.formatMs)(Date.now() - started))}`);
96
+ }
97
+ catch (err) {
98
+ if (!(err instanceof diagnostics_1.SinthError)) {
99
+ ui_1.log.error(err.stack ?? String(err));
100
+ lastError = { title: "Internal error", message: String(err.stack ?? err) };
101
+ }
102
+ else {
103
+ (0, ui_1.printDiagnostic)(err.diagnostic);
104
+ lastError = { title: err.diagnostic.message, message: (0, diagnostics_1.formatDiagnostic)(err.diagnostic, false) };
105
+ }
106
+ broadcast({ type: "error", ...lastError });
107
+ }
108
+ };
109
+ const queueRebuild = (file) => {
110
+ if (building) {
111
+ pending = true;
112
+ return;
113
+ }
114
+ building = rebuild(file).finally(() => {
115
+ building = null;
116
+ if (pending) {
117
+ pending = false;
118
+ queueRebuild(file);
119
+ }
120
+ });
121
+ };
122
+ const started = Date.now();
123
+ await rebuild();
124
+ const findPage = (urlPath) => {
125
+ if (!output)
126
+ return undefined;
127
+ for (const cand of (0, static_1.routeCandidates)(urlPath)) {
128
+ const f = output.files.get(cand.slice(1));
129
+ if (f && cand.endsWith(".html"))
130
+ return Buffer.from(f.contents).toString("utf-8");
131
+ }
132
+ return undefined;
133
+ };
134
+ const server = http.createServer((req, res) => {
135
+ const urlPath = (0, static_1.decodePath)(req.url);
136
+ if (!urlPath)
137
+ return (0, static_1.send)(res, 400, "Bad request", "text/plain");
138
+ if (req.method !== "GET" && req.method !== "HEAD")
139
+ return (0, static_1.send)(res, 405, "Method not allowed", "text/plain");
140
+ if (urlPath === "/__sinth/events") {
141
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
142
+ res.write(`data: ${JSON.stringify({ type: "init", pages: hashes, error: lastError })}\n\n`);
143
+ clients.add(res);
144
+ req.on("close", () => clients.delete(res));
145
+ return;
146
+ }
147
+ if (urlPath === CLIENT_URL)
148
+ return (0, static_1.send)(res, 200, client_1.DEV_CLIENT, "text/javascript; charset=utf-8", { "Cache-Control": "no-store" });
149
+ const isPageRequest = !/\.[a-z0-9]+$/i.test(urlPath) || urlPath.endsWith(".html");
150
+ if (isPageRequest && lastError && !output)
151
+ return (0, static_1.send)(res, 500, errorPage(lastError.title, lastError.message), "text/html; charset=utf-8");
152
+ const html = isPageRequest ? findPage(urlPath) : undefined;
153
+ if (html)
154
+ return (0, static_1.send)(res, 200, html, "text/html; charset=utf-8", { "Cache-Control": "no-store" });
155
+ const rel = urlPath.slice(1);
156
+ const mem = output?.files.get(rel);
157
+ if (mem)
158
+ return (0, static_1.send)(res, 200, mem.contents, (0, static_1.mimeType)(rel), { "Cache-Control": "no-store" });
159
+ const fromPublic = (0, static_1.fileIfExists)((0, static_1.safeJoin)(cfg.publicDir, urlPath));
160
+ const fromRoot = cfg.staticDirs.some(d => urlPath.startsWith("/" + d + "/")) ? (0, static_1.fileIfExists)((0, static_1.safeJoin)(project.root, urlPath)) : null;
161
+ const file = fromPublic ?? fromRoot;
162
+ if (file)
163
+ return (0, static_1.send)(res, 200, fs.readFileSync(file), (0, static_1.mimeType)(file), { "Cache-Control": "no-store" });
164
+ const notFound = findPage("/404");
165
+ return (0, static_1.send)(res, 404, notFound ?? errorPage("404 Not Found", `No page or file matches ${urlPath}`), "text/html; charset=utf-8");
166
+ });
167
+ const port = await (0, static_1.listen)(server, opts.port, opts.host);
168
+ const url = `http://${(0, static_1.displayHost)(opts.host)}:${port}`;
169
+ ui_1.log.blank();
170
+ console.log(` ${ui_1.c.green("➜")} ${ui_1.c.bold("Local:")} ${ui_1.c.cyan(url)}`);
171
+ if (opts.host === "0.0.0.0" || opts.host === "::")
172
+ console.log(` ${ui_1.c.green("➜")} ${ui_1.c.bold("Network:")} exposed on all interfaces`);
173
+ else
174
+ console.log(` ${ui_1.c.gray("➜")} ${ui_1.c.gray("Network: use --host to expose")}`);
175
+ const initial = output;
176
+ console.log(` ${ui_1.c.gray("ready in " + (0, ui_1.formatMs)(Date.now() - started))}${initial ? ui_1.c.gray(`, ${initial.pages.length} page(s)`) : ""}`);
177
+ ui_1.log.blank();
178
+ if (port !== opts.port)
179
+ ui_1.log.warn(`Port ${opts.port} is in use, using ${port} instead`);
180
+ const timers = new Map();
181
+ const onChange = (file) => {
182
+ if (IGNORED.test(path.relative(project.root, file)) || file.startsWith(cfg.outDir) || !WATCHED_EXT.test(file))
183
+ return;
184
+ clearTimeout(timers.get(file));
185
+ timers.set(file, setTimeout(() => {
186
+ timers.delete(file);
187
+ const inStatic = file.startsWith(cfg.publicDir + path.sep) || cfg.staticDirs.some(d => file.startsWith(path.resolve(project.root, d) + path.sep));
188
+ if (inStatic && !file.endsWith(".css") && !file.endsWith(".sinth")) {
189
+ broadcast({ type: "reload" });
190
+ return;
191
+ }
192
+ if (path.basename(file) === "sinth.config.json") {
193
+ ui_1.log.warn("sinth.config.json changed. Restart the dev server to apply it.");
194
+ return;
195
+ }
196
+ queueRebuild(file);
197
+ }, 40));
198
+ };
199
+ try {
200
+ const watcher = fs.watch(project.root, { recursive: true }, (_event, name) => {
201
+ if (name)
202
+ onChange(path.join(project.root, name.toString()));
203
+ });
204
+ watcher.on("error", () => undefined);
205
+ }
206
+ catch {
207
+ ui_1.log.warn("Recursive file watching is not supported here; falling back to polling");
208
+ const mtimes = new Map();
209
+ const scan = (dir) => {
210
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
211
+ const full = path.join(dir, e.name);
212
+ if (IGNORED.test(full))
213
+ continue;
214
+ if (e.isDirectory())
215
+ scan(full);
216
+ else {
217
+ const m = fs.statSync(full).mtimeMs;
218
+ const prev = mtimes.get(full);
219
+ mtimes.set(full, m);
220
+ if (prev !== undefined && prev !== m)
221
+ onChange(full);
222
+ }
223
+ }
224
+ };
225
+ setInterval(() => scan(project.root), 400).unref();
226
+ }
227
+ if (opts.open)
228
+ openBrowser(url);
229
+ const shutdown = () => {
230
+ for (const res of clients)
231
+ res.end();
232
+ server.close();
233
+ process.exit(0);
234
+ };
235
+ process.on("SIGINT", shutdown);
236
+ process.on("SIGTERM", shutdown);
237
+ }
238
+ function openBrowser(url) {
239
+ Promise.resolve().then(() => __importStar(require("child_process"))).then(cp => {
240
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
241
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
242
+ cp.spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
243
+ }).catch(() => undefined);
244
+ }
@@ -0,0 +1,6 @@
1
+ export interface PreviewOptions {
2
+ port: number;
3
+ host: string;
4
+ open: boolean;
5
+ }
6
+ export declare function startPreview(outDir: string, opts: PreviewOptions): Promise<void>;
@@ -0,0 +1,106 @@
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.startPreview = startPreview;
37
+ const fs = __importStar(require("fs"));
38
+ const http = __importStar(require("http"));
39
+ const path = __importStar(require("path"));
40
+ const diagnostics_1 = require("../compiler/diagnostics");
41
+ const ui_1 = require("../cli/ui");
42
+ const dev_1 = require("./dev");
43
+ const static_1 = require("./static");
44
+ function parseHeadersFile(file) {
45
+ if (!fs.existsSync(file))
46
+ return [];
47
+ const rules = [];
48
+ let current = null;
49
+ for (const line of fs.readFileSync(file, "utf-8").split(/\r?\n/)) {
50
+ if (!line.trim() || line.trim().startsWith("#"))
51
+ continue;
52
+ if (!/^\s/.test(line)) {
53
+ const pattern = new RegExp("^" + line.trim().replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
54
+ current = { pattern, headers: {} };
55
+ rules.push(current);
56
+ }
57
+ else if (current) {
58
+ const idx = line.indexOf(":");
59
+ if (idx > 0)
60
+ current.headers[line.slice(0, idx).trim()] = line.slice(idx + 1).trim();
61
+ }
62
+ }
63
+ return rules;
64
+ }
65
+ async function startPreview(outDir, opts) {
66
+ if (!fs.existsSync(outDir)) {
67
+ throw new diagnostics_1.SinthError("E1000", `No build found at ${outDir}`, undefined, "Run 'sinth build' first");
68
+ }
69
+ const rules = parseHeadersFile(path.join(outDir, "_headers"));
70
+ const headersFor = (urlPath) => {
71
+ const out = {};
72
+ for (const r of rules)
73
+ if (r.pattern.test(urlPath))
74
+ Object.assign(out, r.headers);
75
+ return out;
76
+ };
77
+ const server = http.createServer((req, res) => {
78
+ const urlPath = (0, static_1.decodePath)(req.url);
79
+ if (!urlPath)
80
+ return (0, static_1.send)(res, 400, "Bad request", "text/plain");
81
+ if (req.method !== "GET" && req.method !== "HEAD")
82
+ return (0, static_1.send)(res, 405, "Method not allowed", "text/plain");
83
+ if (urlPath.endsWith(".html") && urlPath !== "/404.html") {
84
+ const clean = urlPath.replace(/(index)?\.html$/, "");
85
+ res.writeHead(308, { Location: clean || "/" });
86
+ res.end();
87
+ return;
88
+ }
89
+ for (const cand of (0, static_1.routeCandidates)(urlPath)) {
90
+ const file = (0, static_1.fileIfExists)((0, static_1.safeJoin)(outDir, cand));
91
+ if (file && path.basename(file) !== "_headers") {
92
+ return (0, static_1.send)(res, 200, fs.readFileSync(file), (0, static_1.mimeType)(file), headersFor(urlPath));
93
+ }
94
+ }
95
+ const notFound = (0, static_1.fileIfExists)(path.join(outDir, "404.html"));
96
+ return (0, static_1.send)(res, 404, notFound ? fs.readFileSync(notFound) : "404 Not Found", notFound ? "text/html; charset=utf-8" : "text/plain", headersFor(urlPath));
97
+ });
98
+ const port = await (0, static_1.listen)(server, opts.port, opts.host);
99
+ const url = `http://${(0, static_1.displayHost)(opts.host)}:${port}`;
100
+ ui_1.log.blank();
101
+ console.log(` ${ui_1.c.green("➜")} ${ui_1.c.bold("Preview:")} ${ui_1.c.cyan(url)}`);
102
+ console.log(` ${ui_1.c.gray("Serving " + path.relative(process.cwd(), outDir) + " with production headers")}`);
103
+ ui_1.log.blank();
104
+ if (opts.open)
105
+ (0, dev_1.openBrowser)(url);
106
+ }
@@ -0,0 +1,10 @@
1
+ import * as http from "http";
2
+ export declare const MIME: Record<string, string>;
3
+ export declare function mimeType(file: string): string;
4
+ export declare function decodePath(url: string | undefined): string | null;
5
+ export declare function safeJoin(root: string, urlPath: string): string | null;
6
+ export declare function fileIfExists(file: string | null): string | null;
7
+ export declare function send(res: http.ServerResponse, status: number, body: string | Uint8Array, type: string, headers?: Record<string, string>): void;
8
+ export declare function routeCandidates(urlPath: string): string[];
9
+ export declare function listen(server: http.Server, port: number, host: string, attempts?: number): Promise<number>;
10
+ export declare function displayHost(host: string): string;
@@ -0,0 +1,136 @@
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.MIME = void 0;
37
+ exports.mimeType = mimeType;
38
+ exports.decodePath = decodePath;
39
+ exports.safeJoin = safeJoin;
40
+ exports.fileIfExists = fileIfExists;
41
+ exports.send = send;
42
+ exports.routeCandidates = routeCandidates;
43
+ exports.listen = listen;
44
+ exports.displayHost = displayHost;
45
+ const fs = __importStar(require("fs"));
46
+ const path = __importStar(require("path"));
47
+ exports.MIME = {
48
+ ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8",
49
+ ".mjs": "text/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".map": "application/json",
50
+ ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
51
+ ".webp": "image/webp", ".avif": "image/avif", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2",
52
+ ".ttf": "font/ttf", ".otf": "font/otf", ".txt": "text/plain; charset=utf-8", ".xml": "application/xml",
53
+ ".webmanifest": "application/manifest+json", ".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg",
54
+ ".wav": "audio/wav", ".pdf": "application/pdf", ".wasm": "application/wasm",
55
+ };
56
+ function mimeType(file) {
57
+ return exports.MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream";
58
+ }
59
+ function decodePath(url) {
60
+ const raw = (url ?? "/").split(/[?#]/)[0];
61
+ let decoded;
62
+ try {
63
+ decoded = decodeURIComponent(raw);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ if (decoded.includes("\0"))
69
+ return null;
70
+ const normalized = path.posix.normalize(decoded.replace(/\\/g, "/"));
71
+ if (!normalized.startsWith("/") || normalized.split("/").includes(".."))
72
+ return null;
73
+ return normalized;
74
+ }
75
+ function safeJoin(root, urlPath) {
76
+ const resolvedRoot = path.resolve(root);
77
+ const full = path.resolve(resolvedRoot, "." + urlPath);
78
+ if (full !== resolvedRoot && !full.startsWith(resolvedRoot + path.sep))
79
+ return null;
80
+ return full;
81
+ }
82
+ function fileIfExists(file) {
83
+ if (!file)
84
+ return null;
85
+ try {
86
+ const st = fs.statSync(file);
87
+ if (st.isFile())
88
+ return file;
89
+ if (st.isDirectory()) {
90
+ const idx = path.join(file, "index.html");
91
+ if (fs.existsSync(idx))
92
+ return idx;
93
+ }
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ return null;
99
+ }
100
+ function send(res, status, body, type, headers = {}) {
101
+ res.writeHead(status, {
102
+ "Content-Type": type,
103
+ "Content-Length": String(typeof body === "string" ? Buffer.byteLength(body) : body.byteLength),
104
+ "X-Content-Type-Options": "nosniff",
105
+ ...headers,
106
+ });
107
+ res.end(body);
108
+ }
109
+ function routeCandidates(urlPath) {
110
+ const clean = urlPath.replace(/\/+$/, "") || "/";
111
+ if (clean === "/")
112
+ return ["/index.html"];
113
+ if (/\.[a-z0-9]+$/i.test(clean))
114
+ return [clean];
115
+ return [clean + ".html", clean + "/index.html"];
116
+ }
117
+ function listen(server, port, host, attempts = 10) {
118
+ return new Promise((resolve, reject) => {
119
+ let current = port;
120
+ const tryListen = () => {
121
+ server.once("error", (err) => {
122
+ if (err.code === "EADDRINUSE" && current < port + attempts) {
123
+ current++;
124
+ tryListen();
125
+ }
126
+ else
127
+ reject(err);
128
+ });
129
+ server.listen(current, host, () => resolve(current));
130
+ };
131
+ tryListen();
132
+ });
133
+ }
134
+ function displayHost(host) {
135
+ return host === "127.0.0.1" || host === "::1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
136
+ }