BlueGit

timfa questward

Files

questward / server / src / gateway / http.js

http.js

http.js 2.3 KiB Download Raw
1import { createServer } from "node:http";
2import { createReadStream, existsSync, statSync } from "node:fs";
3import { extname, join, normalize, relative, sep } from "node:path";
4import { fileURLToPath } from "node:url";
5
6const MIME = {
7 ".html": "text/html; charset=utf-8",
8 ".js": "text/javascript; charset=utf-8",
9 ".css": "text/css; charset=utf-8",
10 ".png": "image/png",
11 ".json": "application/json; charset=utf-8",
12 ".svg": "image/svg+xml",
13 ".ico": "image/x-icon"
14};
15
16export function createHttpServer (rootDir)
17{
18 const clientDir = join(rootDir, "client");
19 const sharedDir = join(rootDir, "shared");
20 const frameworkDir = join(clientDir, "frameworkv3", "js");
21
22 return createServer((req, res) =>
23 {
24 try
25 {
26 const url = new URL(req.url ?? "/", "http://localhost");
27 const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
28 if (!filePath)
29 {
30 res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
31 res.end("Not found");
32 return;
33 }
34 res.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" });
35 createReadStream(filePath).pipe(res);
36 }
37 catch (error)
38 {
39 res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
40 res.end(error.message);
41 }
42 });
43}
44
45function resolvePublicPath (pathname, clientDir, sharedDir, frameworkDir)
46{
47 if (pathname === "/" || pathname === "/index.html")
48 { return join(clientDir, "index.html"); }
49 if (pathname === "/editor" || pathname === "/editor.html")
50 { return join(clientDir, "editor.html"); }
51
52 if (pathname.startsWith("/shared/"))
53 { return safeJoin(sharedDir, pathname.slice("/shared/".length)); }
54 if (pathname.startsWith("/framework/"))
55 { return safeJoin(frameworkDir, pathname.slice("/framework/".length)); }
56 if (pathname.startsWith("/src/") || pathname.startsWith("/assets/") || pathname.startsWith("/ui/"))
57 { return safeJoin(clientDir, pathname.slice(1)); }
58
59 return null;
60}
61
62function safeJoin (root, relativePath)
63{
64 const resolved = normalize(join(root, relativePath));
65 const rel = relative(root, resolved);
66 if (rel.startsWith("..") || rel.startsWith(sep) || rel.includes(`..${sep}`))
67 { return null; }
68 if (!existsSync(resolved) || !statSync(resolved).isFile())
69 { return null; }
70 return resolved;
71}
72
73export function repoRootFrom (url)
74{
75 return join(fileURLToPath(new URL(".", url)), "../..");
76}