const http = require("http"); const https = require("https"); const fs = require("fs"); const path = require("path"); const url = require("url"); const PORT = 7860; const DIST_DIR = path.join(__dirname, "dist"); const BACKEND_URL = process.env.VITE_API_BASE_URL || ""; const MIME = { ".html": "text/html", ".js": "application/javascript", ".mjs": "application/javascript", ".css": "text/css", ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".svg": "image/svg+xml", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".webp": "image/webp", }; console.log(`Starting server on port ${PORT}`); console.log(`Backend URL: ${BACKEND_URL || "(not set)"}`); const server = http.createServer((req, res) => { const parsed = url.parse(req.url); // Proxy /api/* to backend if (parsed.pathname.startsWith("/api/") && BACKEND_URL) { const backend = url.parse(BACKEND_URL); const isHttps = backend.protocol === "https:"; const transport = isHttps ? https : http; const options = { hostname: backend.hostname, port: backend.port || (isHttps ? 443 : 80), path: req.url, method: req.method, headers: { ...req.headers, host: backend.hostname }, }; const proxyReq = transport.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(res); }); proxyReq.on("error", (err) => { console.error("Proxy error:", err.message); res.writeHead(502); res.end("Bad Gateway"); }); req.pipe(proxyReq); return; } // Serve static files let filePath = path.join(DIST_DIR, parsed.pathname); try { const stat = fs.statSync(filePath); if (stat.isDirectory()) filePath = path.join(filePath, "index.html"); } catch { // Not found → SPA fallback filePath = path.join(DIST_DIR, "index.html"); } fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(404); res.end("Not Found"); return; } const ext = path.extname(filePath).toLowerCase(); res.writeHead(200, { "Content-Type": MIME[ext] || "application/octet-stream" }); res.end(data); }); }); server.listen(PORT);