Files
font-tools/scripts/serve-test.mjs
T
2026-09-01 14:35:39 +02:00

56 lines
2.1 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",
),
prefix = "/font/",
types = new Map([
[".css", "text/css; charset=utf-8"],
[".html", "text/html; charset=utf-8"],
[".js", "text/javascript; charset=utf-8"],
[".json", "application/json; charset=utf-8"],
[".webmanifest", "application/manifest+json; charset=utf-8"],
[".svg", "image/svg+xml"],
[".md", "text/markdown; charset=utf-8"],
[".txt", "text/plain; charset=utf-8"],
[".woff", "font/woff"],
[".woff2", "font/woff2"],
[".ttf", "font/ttf"],
[".otf", "font/otf"],
]),
headers = {
"Content-Security-Policy":
"default-src 'self';base-uri 'self';object-src 'none';frame-ancestors 'none';form-action 'self';script-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data: blob:;font-src 'self' blob: data:;frame-src 'self' blob:;connect-src 'self';worker-src 'self' blob:;manifest-src 'self'",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
"Referrer-Policy": "no-referrer",
"X-Content-Type-Options": "nosniff",
};
createServer(async (q, s) => {
try {
const u = new URL(q.url ?? "/", "http://127.0.0.1"),
d = decodeURIComponent(u.pathname),
r = d.startsWith(prefix) ? d.slice(prefix.length) : d.replace(/^\/+/, ""),
n = path.posix.normalize(r || "index.html");
if (n === ".." || n.startsWith("../") || path.isAbsolute(n))
return void s.writeHead(400).end();
let f = path.join(root, n);
if ((await stat(f).catch(() => null))?.isDirectory())
f = path.join(f, "index.html");
const c = await readFile(f);
s.writeHead(200, {
"Content-Type": types.get(path.extname(f)) ?? "application/octet-stream",
"Cache-Control": n.startsWith("assets/")
? "public,max-age=31536000,immutable"
: "no-cache",
...headers,
});
s.end(c);
} catch {
s.writeHead(404).end("Not found");
}
}).listen(4202, "127.0.0.1", () => console.log("ready"));