import { createServer } from "node:http"; import { createReadStream, existsSync, statSync } from "node:fs"; import { extname, join, normalize, relative, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { buildSpriteCatalog } from "../assets/spriteCatalog.js"; const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".png": "image/png", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".ico": "image/x-icon" }; export function createHttpServer (rootDir) { const clientDir = join(rootDir, "client"); const sharedDir = join(rootDir, "shared"); const frameworkDir = join(clientDir, "frameworkv3", "js"); return createServer((req, res) => { try { const url = new URL(req.url ?? "/", "http://localhost"); if (url.pathname === "/assets/catalog.json") { const catalog = spriteCatalogFor(clientDir); res.writeHead(200, { "content-type": "application/json; charset=utf-8" }); res.end(JSON.stringify(catalog)); return; } const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir); if (!filePath) { res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }); res.end("Not found"); return; } res.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" }); createReadStream(filePath).pipe(res); } catch (error) { res.writeHead(500, { "content-type": "text/plain; charset=utf-8" }); res.end(error.message); } }); } function resolvePublicPath (pathname, clientDir, sharedDir, frameworkDir) { if (pathname === "/" || pathname === "/index.html") { return join(clientDir, "index.html"); } if (pathname === "/editor" || pathname === "/editor.html") { return join(clientDir, "editor.html"); } if (pathname.startsWith("/shared/")) { return safeJoin(sharedDir, pathname.slice("/shared/".length)); } if (pathname.startsWith("/framework/")) { return safeJoin(frameworkDir, pathname.slice("/framework/".length)); } if (pathname.startsWith("/src/") || pathname.startsWith("/assets/") || pathname.startsWith("/ui/")) { return safeJoin(clientDir, pathname.slice(1)); } return null; } function safeJoin (root, relativePath) { const resolved = normalize(join(root, relativePath)); const rel = relative(root, resolved); if (rel.startsWith("..") || rel.startsWith(sep) || rel.includes(`..${sep}`)) { return null; } if (!existsSync(resolved) || !statSync(resolved).isFile()) { return null; } return resolved; } function spriteCatalogFor (clientDir) { // Rebuild each request so deleting optional companions (e.g. *-bloom) is picked up // without a process restart. return buildSpriteCatalog(join(clientDir, "assets")); } export function repoRootFrom (url) { return join(fileURLToPath(new URL(".", url)), "../.."); }