-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
553 lines (518 loc) · 26.1 KB
/
Copy pathserver.mjs
File metadata and controls
553 lines (518 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/* Theme Studio server — zero dependencies, local-first, site-agnostic.
*
* Reads studio.config.json from the working directory:
*
* {
* "themeFile": "theme/theme.css",
* "sites": [
* { "name": "My site", "preview": "./dist" },
* { "name": "Live", "preview": "https://example.com" }
* ],
* "ship": { "mode": "git", "paths": ["theme"], "branch": "main" },
* "uploads": "public/",
* "fonts": true
* }
*
* `preview` is either a folder (served with the edit bridge injected) or a
* URL — a live site or a dev server — proxied with the bridge injected.
* `ship.mode` is "git" (Ship button: add, commit, pull --rebase, push —
* never force) or "none" (save-only).
*
* Ports (override base with STUDIO_PORT): 4400 studio UI + API, then one
* port per site (4401, 4402, …).
*
* Local-only by default. To edit from another device set STUDIO_HOST=0.0.0.0
* and bind to a private network (Tailscale or similar) — never port-forward
* this to the open internet, there is no auth.
*/
import http from "node:http";
import https from "node:https";
import fs from "node:fs";
import path from "node:path";
import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = process.cwd();
/* ── config ──────────────────────────────────────────────────────────────── */
const CONFIG_PATH = path.resolve(ROOT, process.env.STUDIO_CONFIG || "studio.config.json");
let config;
try {
config = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8"));
} catch (e) {
console.error(`
Theme Studio needs a studio.config.json in this directory.
(${e.code === "ENOENT" ? "None found at " + CONFIG_PATH : "Couldn't read it: " + e.message})
Quickest start: npx theme-studio init
Or write one by hand — the README shows the schema.
`);
process.exit(1);
}
const fail = (msg) => { console.error(`\n studio.config.json: ${msg}\n`); process.exit(1); };
if (!config.themeFile || typeof config.themeFile !== "string") fail(`"themeFile" is required — the CSS file that holds your tokens.`);
if (!Array.isArray(config.sites) || !config.sites.length) fail(`"sites" must be a non-empty array of { name, preview }.`);
const THEME = path.resolve(ROOT, config.themeFile);
if (!fs.existsSync(THEME)) fail(`themeFile not found: ${config.themeFile} — run \`npx theme-studio init\` to draft one.`);
const STATE_DIR = path.join(ROOT, ".theme-studio"); // prefs, fonts, defaults snapshot (gitignore it or commit it — your call)
const PREFS = path.join(STATE_DIR, "prefs.json");
const FONTS = path.join(STATE_DIR, "fonts.json");
const DEFAULTS = path.join(STATE_DIR, "defaults.json");
const UPLOADS = config.uploads ? path.resolve(ROOT, config.uploads) : null;
const FONTS_ON = config.fonts !== false;
const BASE = parseInt(process.env.STUDIO_PORT || "4400", 10);
const HOST = process.env.STUDIO_HOST || "127.0.0.1";
const SITES = config.sites.map((s, i) => {
const preview = String(s.preview || "");
const isUrl = /^https?:\/\//i.test(preview);
if (!preview) fail(`site "${s.name || i}" needs a "preview" — a folder or a URL.`);
return {
id: "site" + i,
label: s.name || `Site ${i + 1}`,
origin: isUrl ? preview.replace(/\/$/, "") : null,
dist: isUrl ? null : path.resolve(ROOT, preview),
port: BASE + 1 + i,
};
});
const SHIP = config.ship || { mode: "none" };
const GIT_ENABLED = SHIP.mode === "git";
const SHIP_PATHS = (Array.isArray(SHIP.paths) && SHIP.paths.length)
? SHIP.paths
: [path.relative(ROOT, path.dirname(THEME)) || "."]
.concat(UPLOADS && !path.relative(ROOT, UPLOADS).startsWith("..") ? [path.relative(ROOT, UPLOADS)] : []);
const CI_URL = SHIP.ciUrl || null;
const MIME = {
".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",
".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png",
".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp",
".avif": "image/avif", ".ico": "image/x-icon", ".xml": "application/xml",
".txt": "text/plain; charset=utf-8", ".woff": "font/woff", ".woff2": "font/woff2",
".ttf": "font/ttf", ".otf": "font/otf", ".map": "application/json", ".webmanifest": "application/manifest+json",
};
/* ── Bridge injected into every served/proxied site page ─────────────────── */
const BRIDGE = `<script>/* Theme Studio bridge */(function(){
function apply(d){
if(d.type==="theme-studio:css"){
var el=document.getElementById("__theme-studio");
if(!el){el=document.createElement("style");el.id="__theme-studio";document.head.appendChild(el);}
el.textContent=d.css||"";
}else if(d.type==="theme-studio:dark"){
document.documentElement.classList.toggle("dark",!!d.dark);
try{localStorage.setItem("theme",d.dark?"dark":"light");}catch(e){}
}else if(d.type==="theme-studio:fonts"){
var ft=d.fonts||{links:[]};
document.querySelectorAll("link[data-ts-font]").forEach(function(l){l.remove();});
(ft.links||[]).forEach(function(u){
if(!u)return;
var l=document.createElement("link");l.rel="stylesheet";l.href=u;l.setAttribute("data-ts-font","1");
document.head.appendChild(l);
});
}else if(d.type==="theme-studio:nav"){
if(d.nav==="back")history.back();
else if(d.nav==="reload")location.reload();
else if(d.nav==="home")location.href="/";
}
}
window.addEventListener("message",function(e){
if(e.data&&typeof e.data==="object"&&String(e.data.type||"").indexOf("theme-studio:")===0) apply(e.data);
});
function announce(){ if(window.parent!==window) window.parent.postMessage({type:"theme-studio:ready",href:location.href},"*"); }
if(document.readyState==="loading") document.addEventListener("DOMContentLoaded",announce); else announce();
})();</script>`;
/* ── theme.css parse / serialise ─────────────────────────────────────────── */
const BLOCK_RE = { light: /(^|\n):root\s*\{([\s\S]*?)\n\}/, dark: /(^|\n)\.dark\s*\{([\s\S]*?)\n\}/ };
const SNIP_RE = /(\/\*\s*THEME-STUDIO:SNIPPETS:START\s*\*\/)([\s\S]*?)(\/\*\s*THEME-STUDIO:SNIPPETS:END\s*\*\/)/;
function parseBlock(body) {
const tokens = [];
let group = "Other";
for (const line of body.split("\n")) {
const g = line.match(/\/\*\s*@group\s+(.+?)\s*\*\//);
if (g) { group = g[1]; continue; }
const t = line.match(/^\s*(--[\w-]+)\s*:\s*([^;]+);(?:\s*\/\*\s*(.*?)\s*\*\/)?/);
if (t) tokens.push({ name: t[1], value: t[2].trim(), label: (t[3] || "").trim(), group });
}
return tokens;
}
function readTheme() {
const src = fs.readFileSync(THEME, "utf8");
const lm = src.match(BLOCK_RE.light);
const dm = src.match(BLOCK_RE.dark);
const sm = src.match(SNIP_RE);
return {
light: lm ? parseBlock(lm[2]) : [],
dark: dm ? parseBlock(dm[2]) : [],
snippets: sm ? sm[2].replace(/^\n/, "").replace(/\n[ \t]*$/, "") : "",
};
}
function writeTheme(payload) {
let src = fs.readFileSync(THEME, "utf8");
if (!BLOCK_RE.light.test(src)) throw new Error(`${path.basename(THEME)}: no :root block found — the token convention needs one (see README).`);
if (Object.keys(payload.dark || {}).length && !BLOCK_RE.dark.test(src)) {
src = src.replace(/\s*$/, "\n\n.dark {\n}\n"); // first dark override: create the block
}
if (typeof payload.snippets === "string" && payload.snippets.trim() && !SNIP_RE.test(src)) {
src = src.replace(/\s*$/, "\n\n/* THEME-STUDIO:SNIPPETS:START */\n/* THEME-STUDIO:SNIPPETS:END */\n");
}
const setIn = (which, name, value) => {
const m = src.match(BLOCK_RE[which]);
if (!m) throw new Error(`theme file: ${which} block not found`);
let body = m[2];
const lineRe = new RegExp(`(^\\s*${name}\\s*:\\s*)([^;]+)(;)`, "m");
if (lineRe.test(body)) {
body = body.replace(lineRe, `$1${value}$3`);
} else {
body += `\n ${name}: ${value}; /* added by Theme Studio */`;
}
src = src.slice(0, m.index) + m[1] + (which === "light" ? ":root" : ".dark") + " {" + body + "\n}" + src.slice(m.index + m[0].length);
};
for (const [name, value] of Object.entries(payload.light || {})) setIn("light", name, String(value));
for (const [name, value] of Object.entries(payload.dark || {})) setIn("dark", name, String(value));
if (typeof payload.snippets === "string" && SNIP_RE.test(src)) {
const snip = payload.snippets.trim();
src = src.replace(SNIP_RE, (_, a, __, c) => `${a}\n${snip ? snip + "\n" : ""}${c}`);
}
const tmp = THEME + ".tmp";
fs.writeFileSync(tmp, src);
fs.renameSync(tmp, THEME);
return readTheme();
}
/* ── state files (.theme-studio/) ────────────────────────────────────────── */
function readJsonFile(fp, fallback) {
try { return JSON.parse(fs.readFileSync(fp, "utf8")); } catch { return fallback; }
}
function writeJsonFile(fp, data) {
fs.mkdirSync(path.dirname(fp), { recursive: true });
const tmp = fp + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n");
fs.renameSync(tmp, fp);
}
const readFonts = () => readJsonFile(FONTS, { links: [], faces: [] });
/* ── helpers ─────────────────────────────────────────────────────────────── */
function send(res, code, body, type = "application/json") {
const buf = typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body);
res.writeHead(code, { "content-type": type, "cache-control": "no-store" });
res.end(buf);
}
function readBody(req) {
return new Promise((resolve, reject) => {
let data = "";
req.on("data", (c) => { data += c; if (data.length > 2e6) reject(new Error("too large")); });
req.on("end", () => resolve(data));
req.on("error", reject);
});
}
function serveStatic(rootDir, req, res, inject) {
let urlPath;
try { urlPath = decodeURIComponent(new URL(req.url, "http://x").pathname); }
catch { return send(res, 400, "bad request", "text/plain"); }
let fp = path.normalize(path.join(rootDir, urlPath));
if (!fp.startsWith(rootDir)) return send(res, 403, "forbidden", "text/plain");
try {
let st = fs.existsSync(fp) ? fs.statSync(fp) : null;
if (st && st.isDirectory()) { fp = path.join(fp, "index.html"); st = fs.existsSync(fp) ? fs.statSync(fp) : null; }
if (!st && !path.extname(fp)) { fp = fp + ".html"; st = fs.existsSync(fp) ? fs.statSync(fp) : null; }
if (!st) {
const notFound = path.join(rootDir, "404.html");
if (fs.existsSync(notFound)) fp = notFound;
else return send(res, 404, "not found", "text/plain");
}
const ext = path.extname(fp).toLowerCase();
let buf = fs.readFileSync(fp);
if (inject && ext === ".html") {
let html = buf.toString("utf8");
html = html.includes("</head>") ? html.replace("</head>", BRIDGE + "</head>") : BRIDGE + html;
buf = Buffer.from(html, "utf8");
}
send(res, 200, buf, MIME[ext] || "application/octet-stream");
} catch (e) {
send(res, 500, String(e), "text/plain");
}
}
/* ── port helper: prefer the usual port, fall back to a free one ─────────── */
function listenSmart(server, preferred) {
return new Promise((resolve, reject) => {
const tryPort = (port, isFallback) => {
server.once("error", (err) => {
if (err.code === "EADDRINUSE" && !isFallback) tryPort(0, true);
else reject(err);
});
server.listen(port, HOST, () => {
server.removeAllListeners("error");
resolve({ port: server.address().port, fallback: isFallback });
});
};
tryPort(preferred, false);
});
}
/* ── live-site / dev-server proxy — injects the bridge into HTML ─────────── */
function proxySite(originBase, req, res) {
let target;
try { target = new URL(req.url, originBase); } catch { return send(res, 400, "bad request", "text/plain"); }
const lib = target.protocol === "https:" ? https : http;
const preq = lib.request(target, {
method: "GET",
headers: { "user-agent": "theme-studio-preview", accept: req.headers.accept || "*/*", "accept-encoding": "identity" },
}, (pres) => {
const ct = String(pres.headers["content-type"] || "");
const headers = { "content-type": ct || "application/octet-stream", "cache-control": "no-store" };
if (pres.headers.location) {
try {
const loc = new URL(pres.headers.location, target);
headers.location = loc.host === target.host ? loc.pathname + loc.search : pres.headers.location;
} catch { headers.location = pres.headers.location; }
}
if (ct.includes("text/html")) {
const chunks = [];
pres.on("data", (c) => chunks.push(c));
pres.on("end", () => {
let html = Buffer.concat(chunks).toString("utf8");
html = html.includes("</head>") ? html.replace("</head>", BRIDGE + "</head>") : BRIDGE + html;
send(res, pres.statusCode || 200, Buffer.from(html, "utf8"), headers["content-type"]);
});
} else {
res.writeHead(pres.statusCode || 200, headers);
pres.pipe(res);
}
});
preq.on("error", (e) => send(res, 502, "Preview proxy error: " + e.message, "text/plain"));
preq.end();
}
/* ── font self-hosting: fetch a fonts CSS, download the latin woff2 files ── */
function httpGet(target, asText, depth = 0) {
return new Promise((resolve, reject) => {
if (depth > 4) return reject(new Error("too many redirects"));
let u;
try { u = new URL(target); } catch { return reject(new Error("bad url")); }
const lib = u.protocol === "https:" ? https : http;
lib.get(u, { headers: { "user-agent": "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Chrome/126 Safari/605" } }, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume();
return resolve(httpGet(new URL(res.headers.location, u).toString(), asText, depth + 1));
}
if (res.statusCode !== 200) { res.resume(); return reject(new Error("HTTP " + res.statusCode + " for " + target)); }
const chunks = [];
res.on("data", (c) => chunks.push(c));
res.on("end", () => resolve(asText ? Buffer.concat(chunks).toString("utf8") : Buffer.concat(chunks)));
}).on("error", reject);
});
}
async function selfHostFont(cssUrl) {
if (!UPLOADS) throw new Error(`Self-hosting needs an "uploads" folder in studio.config.json (e.g. "public/").`);
const css = await httpGet(cssUrl, true);
const wanted = new Map(); // "family|weight" -> {family, weight, src}
for (const block of css.split("@font-face").slice(1)) {
const fam = (/font-family:\s*['"]?([^'";}]+)/.exec(block) || [])[1];
const weight = ((/font-weight:\s*([^;}]+)/.exec(block) || [])[1] || "400").trim();
const style = ((/font-style:\s*([^;}]+)/.exec(block) || [])[1] || "normal").trim();
const range = ((/unicode-range:\s*([^;}]+)/.exec(block) || [])[1] || "");
const src = (/src:[^;}]*url\((['"]?)([^)'"]+)\1\)/.exec(block) || [])[2];
if (!fam || !src || style !== "normal") continue;
if (range && !/U\+0(?:000|0-)/i.test(range)) continue; // latin subset only
const key = fam.trim() + "|" + weight;
if (!wanted.has(key)) wanted.set(key, { family: fam.trim(), weight, src: new URL(src, cssUrl).toString() });
}
if (!wanted.size) throw new Error("No usable @font-face blocks found at that URL.");
const faces = [];
for (const { family, weight, src } of wanted.values()) {
const buf = await httpGet(src, false);
const ext = path.extname(new URL(src).pathname) || ".woff2";
const slug = family.toLowerCase().replace(/[^a-z0-9]+/g, "-");
const dir = path.join(UPLOADS, "fonts");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `${slug}-${weight}${ext}`), buf);
faces.push({ family, src: `/fonts/${slug}-${weight}${ext}`, weight });
}
return { faces };
}
/* ── git ship — never force, never amends ────────────────────────────────── */
function git(args) {
return new Promise((resolve) => {
execFile("git", args, { cwd: ROOT, timeout: 120000 }, (err, stdout, stderr) =>
resolve({ ok: !err, out: ((stdout || "") + (stderr || "")).trim() }));
});
}
async function shipBranch() {
if (SHIP.branch) return SHIP.branch;
const r = await git(["rev-parse", "--abbrev-ref", "HEAD"]);
return r.ok && r.out && r.out !== "HEAD" ? r.out : "main";
}
async function gitStatus() {
const branch = await git(["rev-parse", "--abbrev-ref", "HEAD"]);
const dirty = await git(["status", "--porcelain", "--", ...SHIP_PATHS]);
const stat = await git(["diff", "--stat", "HEAD", "--", ...SHIP_PATHS]);
const last = await git(["log", "-1", "--format=%h %s (%cr)"]);
return { branch: branch.out, dirty: dirty.out, stat: stat.out || dirty.out, last: last.out };
}
async function gitShip(message) {
const log = [];
const step = async (label, args) => {
const r = await git(args);
log.push(`$ git ${args.join(" ")}\n${r.out}`);
if (!r.ok) throw new Error(`${label} failed:\n${r.out}`);
return r;
};
const branch = await shipBranch();
const ident = ["-c", "user.name=Theme Studio", "-c", "user.email=theme-studio@localhost"];
const dirty = await git(["status", "--porcelain", "--", ...SHIP_PATHS]);
if (!dirty.out) throw new Error("Nothing to ship — the theme files match the last commit.");
await step("stage", ["add", "--", ...SHIP_PATHS]);
await step("commit", [...ident, "commit", "-m", message || "theme: studio edits"]);
// identity also matters here: a rebase that replays commits needs a committer
const pull = await git([...ident, "pull", "--rebase", "origin", branch]);
log.push(`$ git pull --rebase origin ${branch}\n${pull.out}`);
if (!pull.ok) {
await git(["rebase", "--abort"]);
throw new Error("Pull --rebase hit a conflict — resolve it by hand, then ship again.\n" + pull.out);
}
await step("push", ["push", "origin", branch]);
return { log: log.join("\n\n"), ci: CI_URL };
}
/* ── site servers (one port each, bridge injected) ───────────────────────── */
async function startSiteServers() {
for (const site of SITES) {
const server = http.createServer((req, res) => {
// uploads win over the live site OR the built dist, so fresh images and
// fonts preview before they're shipped/rebuilt
if (UPLOADS) {
try {
const p = decodeURIComponent(new URL(req.url, "http://x").pathname);
const local = path.normalize(path.join(UPLOADS, p));
if (local.startsWith(UPLOADS) && fs.existsSync(local) && fs.statSync(local).isFile()) {
const ext = path.extname(local).toLowerCase();
return send(res, 200, fs.readFileSync(local), MIME[ext] || "application/octet-stream");
}
} catch {}
}
if (site.origin) return proxySite(site.origin, req, res);
if (!fs.existsSync(path.join(site.dist, "index.html"))) {
return send(res, 503, `<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;padding:3rem;color:#363636"><h1>${site.label}: nothing to preview</h1><p>No <code>index.html</code> in <code>${path.relative(ROOT, site.dist) || "."}</code> — build your site first, then reload.</p></body>`, "text/html; charset=utf-8");
}
serveStatic(site.dist, req, res, true);
});
const got = await listenSmart(server, site.port);
if (got.fallback) console.log(` (port ${site.port} was in use — ${site.label} moved to ${got.port})`);
site.port = got.port;
}
}
/* ── studio UI + API ─────────────────────────────────────────────────────── */
const studio = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://x");
if (url.pathname === "/api/theme" && req.method === "GET") {
try { return send(res, 200, readTheme()); }
catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/theme" && req.method === "POST") {
try {
const payload = JSON.parse(await readBody(req) || "{}");
return send(res, 200, writeTheme(payload));
} catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/fonts" && req.method === "GET") {
return send(res, 200, readFonts());
}
if (url.pathname === "/api/fonts" && req.method === "POST") {
try {
const data = JSON.parse(await readBody(req) || "{}");
writeJsonFile(FONTS, { links: data.links || [], faces: data.faces || [] });
return send(res, 200, readFonts());
} catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/upload" && req.method === "POST") {
if (!UPLOADS) return send(res, 400, { error: `Uploads need an "uploads" folder in studio.config.json.` });
let name = String(url.searchParams.get("filename") || "").toLowerCase().replace(/[^a-z0-9._-]/g, "-").replace(/^[.-]+/, "");
const ext = path.extname(name);
if (!name) return send(res, 400, { error: "filename required" });
if (![".png", ".jpg", ".jpeg", ".svg", ".webp", ".ico", ".avif", ".gif", ".woff2", ".woff", ".ttf", ".otf"].includes(ext)) {
return send(res, 400, { error: "unsupported file type: " + (ext || "none") });
}
const chunks = [];
let size = 0, overflowed = false;
req.on("data", (c) => {
size += c.length;
if (size > 5e6) { overflowed = true; req.destroy(); } else chunks.push(c);
});
req.on("end", () => {
if (overflowed) return;
try {
const fp = path.normalize(path.join(UPLOADS, name));
if (!fp.startsWith(UPLOADS)) return send(res, 403, { error: "bad filename" });
fs.mkdirSync(UPLOADS, { recursive: true });
fs.writeFileSync(fp, Buffer.concat(chunks));
send(res, 200, { path: "/" + name, bytes: size });
} catch (e) { send(res, 500, { error: String(e.message || e) }); }
});
req.on("close", () => { if (overflowed) try { send(res, 413, { error: "file too large (5 MB max)" }); } catch {} });
return;
}
if (url.pathname === "/api/prefs" && req.method === "GET") {
try { return send(res, 200, fs.existsSync(PREFS) ? fs.readFileSync(PREFS, "utf8") : "{}"); }
catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/prefs" && req.method === "POST") {
try {
const data = JSON.parse(await readBody(req) || "{}");
writeJsonFile(PREFS, data);
return send(res, 200, data);
} catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/bunny-list" && req.method === "GET") {
try {
if (!global.__bunnyList) {
global.__bunnyList = await httpGet(process.env.BUNNY_LIST_URL || "https://fonts.bunny.net/list", true);
}
return send(res, 200, global.__bunnyList);
} catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/selfhost-font" && req.method === "POST") {
try {
const { url: cssUrl } = JSON.parse(await readBody(req) || "{}");
if (!cssUrl) return send(res, 400, { error: "url required" });
return send(res, 200, await selfHostFont(cssUrl));
} catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/defaults" && req.method === "GET") {
try {
// first run: snapshot the theme as found — that's what Reset returns to.
// Re-baseline any time by deleting .theme-studio/defaults.json.
if (!fs.existsSync(DEFAULTS)) {
const t = readTheme();
const map = (arr) => Object.fromEntries(arr.map((x) => [x.name, x.value]));
writeJsonFile(DEFAULTS, {
_comment: "Theme Studio defaults — snapshot of the theme when the studio first ran. 'Reset to defaults' loads this. Delete the file to re-baseline.",
theme: { light: map(t.light), dark: map(t.dark), snippets: t.snippets },
fonts: readFonts(),
});
}
return send(res, 200, fs.readFileSync(DEFAULTS, "utf8"));
} catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/meta" && req.method === "GET") {
return send(res, 200, {
themePath: path.relative(ROOT, THEME),
git: GIT_ENABLED,
ciUrl: CI_URL,
uploads: !!UPLOADS,
fonts: FONTS_ON,
sites: SITES.map((s) => ({ id: s.id, label: s.label, port: s.port, built: !!s.origin || fs.existsSync(path.join(s.dist, "index.html")) })),
});
}
if (url.pathname === "/api/git/status" && req.method === "GET" && GIT_ENABLED) {
try { return send(res, 200, await gitStatus()); }
catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
if (url.pathname === "/api/git/ship" && req.method === "POST" && GIT_ENABLED) {
try {
const { message } = JSON.parse(await readBody(req) || "{}");
return send(res, 200, await gitShip(message));
} catch (e) { return send(res, 500, { error: String(e.message || e) }); }
}
serveStatic(path.join(__dirname, "public"), req, res, false);
});
(async () => {
await startSiteServers();
const got = await listenSmart(studio, BASE);
if (got.fallback) console.log(` (port ${BASE} was in use — the studio moved to ${got.port})`);
console.log(`\n Theme Studio → http://localhost:${got.port}\n`);
for (const s of SITES) console.log(` ${s.label.padEnd(16)} → http://localhost:${s.port} ${s.origin ? `(proxying ${s.origin})` : fs.existsSync(path.join(s.dist, "index.html")) ? "" : "(nothing built yet)"}`);
if (HOST !== "127.0.0.1") console.log(`\n Bound to ${HOST} — reachable from other devices. Keep this on a private network; there is no auth.`);
console.log(`\n Editing ${path.relative(ROOT, THEME)} — Save writes the file${GIT_ENABLED ? ", Ship commits and pushes it" : ""}.\n`);
})().catch((e) => { console.error("Theme Studio failed to start:", e.message); process.exit(1); });