Files
helper-tools/scripts/serve-test.mjs
T
2026-09-01 02:33:45 +02:00

69 lines
2.4 KiB
JavaScript

import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"..",
"dist",
);
const nestedPrefix = "/deep/nested/helpers/";
const mediaTypes = new Map([
[".css", "text/css; charset=utf-8"],
[".html", "text/html; charset=utf-8"],
[".js", "application/javascript; charset=utf-8"],
[".json", "application/json; charset=utf-8"],
[".md", "text/markdown; charset=utf-8"],
[".svg", "image/svg+xml"],
[".txt", "text/plain; charset=utf-8"],
[".webmanifest", "application/manifest+json"],
]);
const headers = {
"Content-Security-Policy":
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; object-src 'none'; base-uri 'self'; form-action 'none'; frame-ancestors 'none'",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
"Referrer-Policy": "no-referrer",
"X-Content-Type-Options": "nosniff",
};
createServer(async (request, response) => {
try {
const url = new URL(request.url ?? "/", "http://127.0.0.1");
if (!url.pathname.startsWith(nestedPrefix)) {
response.writeHead(404, headers).end("Not found");
return;
}
let relative = decodeURIComponent(url.pathname.slice(nestedPrefix.length));
if (!relative || relative.endsWith("/")) relative += "index.html";
if (relative.includes("\\") || relative.split("/").includes("..")) {
response.writeHead(400, headers).end("Bad path");
return;
}
const absolute = path.resolve(root, relative);
if (
!absolute.startsWith(`${root}${path.sep}`) ||
!(await stat(absolute)).isFile()
) {
response.writeHead(404, headers).end("Not found");
return;
}
const body = await readFile(absolute);
response.writeHead(200, {
...headers,
"Content-Type":
mediaTypes.get(path.extname(absolute)) ?? "application/octet-stream",
"Cache-Control": relative.startsWith("assets/")
? "public, max-age=31536000, immutable"
: "no-cache",
});
response.end(body);
} catch {
response.writeHead(404, headers).end("Not found");
}
}).listen(4173, "127.0.0.1", () => {
console.log(`Serving Helper Tools at http://127.0.0.1:4173${nestedPrefix}`);
});