import { createReadStream, existsSync } from "node:fs"; import { extname, join, normalize } from "node:path"; import { createServer } from "node:http"; import { createServer as createViteServer } from "vite"; import { bootstrap } from "./bootstrap.mjs"; import { handleAuthApi } from "./auth.mjs"; import { handleGithubApi } from "./github.mjs"; import { handleSettingsApi } from "./settings.mjs"; const isProduction = process.env.NODE_ENV === "production"; const port = Number(process.env.PORT || 5173); const root = process.cwd(); bootstrap(); const mimeTypes = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", }; const vite = isProduction ? undefined : await createViteServer({ server: { middlewareMode: true, host: "0.0.0.0", }, appType: "spa", }); function sendNotFound(response) { response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); response.end("Not found"); } function serveStatic(request, response) { const pathname = decodeURIComponent(new URL(request.url ?? "/", `http://localhost:${port}`).pathname); const requestedPath = normalize(join(root, "dist", pathname === "/" ? "index.html" : pathname)); const fallbackPath = join(root, "dist", "index.html"); const filePath = existsSync(requestedPath) ? requestedPath : fallbackPath; if (!filePath.startsWith(join(root, "dist")) || !existsSync(filePath)) { sendNotFound(response); return; } response.writeHead(200, { "Content-Type": mimeTypes[extname(filePath)] || "application/octet-stream", }); createReadStream(filePath).pipe(response); } const server = createServer(async (request, response) => { const url = new URL(request.url ?? "/", `http://localhost:${port}`); if (await handleAuthApi(request, response, url)) { return; } if (await handleSettingsApi(request, response, url)) { return; } if (await handleGithubApi(request, response, url)) { return; } if (vite) { vite.middlewares(request, response, () => sendNotFound(response)); return; } serveStatic(request, response); }); server.listen(port, "0.0.0.0", () => { console.log(`VitePress-CMS running at http://localhost:${port}`); });