PromptBoost / scripts /dev-server.mjs
smlflg's picture
Initial public upload from Projekte/PromptBoost (part 5)
638c806 verified
Raw History Blame Contribute Delete
2.33 kB
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { dirname, extname, join, normalize, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { stripTypeScriptTypes } from "node:module";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const root = resolve(scriptDir, "..");
const requestedPort = Number(process.env.PORT || 5173);
const host = process.env.HOST || "127.0.0.1";
const mimeByExtension = {
".css": "text/css; charset=utf-8",
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".ts": "text/javascript; charset=utf-8",
".txt": "text/plain; charset=utf-8"
};
function requestPathToFile(url) {
const parsed = new URL(url, `http://${host}:${requestedPort}`);
const rawPath = parsed.pathname === "/" ? "/index.html" : parsed.pathname;
const safePath = normalize(rawPath).replace(/^(\.\.[/\\])+/, "");
const filePath = join(root, safePath);
if (!filePath.startsWith(root)) {
return null;
}
return filePath;
}
async function handleRequest(request, response) {
try {
const filePath = requestPathToFile(request.url || "/");
if (!filePath) {
response.writeHead(403);
response.end("Forbidden");
return;
}
const extension = extname(filePath);
let body = await readFile(filePath, "utf8");
if (extension === ".ts") {
body = stripTypeScriptTypes(body, { mode: "strip" });
}
response.writeHead(200, {
"content-type": mimeByExtension[extension] || "application/octet-stream",
"cache-control": "no-store"
});
response.end(body);
} catch (error) {
const status = error && error.code === "ENOENT" ? 404 : 500;
response.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
response.end(status === 404 ? "Not found" : String(error.stack || error));
}
}
function listen(port) {
const server = createServer(handleRequest);
server.on("error", (error) => {
if (error && error.code === "EADDRINUSE" && port < requestedPort + 50) {
listen(port + 1);
return;
}
throw error;
});
server.listen(port, host, () => {
console.log(`PromptBoost V2 running at http://${host}:${port}/`);
});
}
listen(requestedPort);