File size: 2,328 Bytes
638c806 | 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 | 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);
|