-
-
Notifications
You must be signed in to change notification settings - Fork 998
Expand file tree
/
Copy pathserver.mjs
More file actions
143 lines (125 loc) · 4.11 KB
/
Copy pathserver.mjs
File metadata and controls
143 lines (125 loc) · 4.11 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import { createServer } from "node:http";
import { createReadStream, existsSync, statSync } from "node:fs";
import { extname, normalize, resolve } from "node:path";
import { Readable } from "node:stream";
import serverEntry from "./dist/server/server.js";
const clientDir = resolve(process.cwd(), "dist/client");
const port = Number(process.env.PORT || 3000);
const host = process.env.HOSTNAME || "0.0.0.0";
const MIME_TYPES = {
".css": "text/css; charset=utf-8",
".gif": "image/gif",
".html": "text/html; charset=utf-8",
".ico": "image/x-icon",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".map": "application/json; charset=utf-8",
".png": "image/png",
".svg": "image/svg+xml",
".txt": "text/plain; charset=utf-8",
".ttf": "font/ttf",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
".xml": "application/xml; charset=utf-8"
};
function getContentType(filePath) {
const extension = extname(filePath).toLowerCase();
return MIME_TYPES[extension] || "application/octet-stream";
}
function toHeaders(nodeHeaders) {
const headers = new Headers();
for (const [key, value] of Object.entries(nodeHeaders)) {
if (typeof value === "undefined") continue;
if (Array.isArray(value)) {
for (const item of value) headers.append(key, item);
} else {
headers.set(key, value);
}
}
return headers;
}
function resolveStaticFile(pathname) {
const decoded = decodeURIComponent(pathname);
const normalized = normalize(decoded).replace(/^[/\\]+/, "");
const absolutePath = resolve(clientDir, normalized);
if (!absolutePath.startsWith(clientDir)) return null;
if (!existsSync(absolutePath)) return null;
const stats = statSync(absolutePath);
if (!stats.isFile()) return null;
return absolutePath;
}
function tryServeStatic(req, res, url) {
if (!url.pathname || url.pathname.endsWith("/")) return false;
const filePath = resolveStaticFile(url.pathname);
if (!filePath) return false;
res.statusCode = 200;
res.setHeader("Content-Type", getContentType(filePath));
if (url.pathname.startsWith("/assets/")) {
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
} else {
res.setHeader("Cache-Control", "public, max-age=3600");
}
if (req.method === "HEAD") {
res.end();
return true;
}
createReadStream(filePath).pipe(res);
return true;
}
function appendSetCookie(res, value) {
const existing = res.getHeader("set-cookie");
if (!existing) {
res.setHeader("set-cookie", value);
return;
}
if (Array.isArray(existing)) {
res.setHeader("set-cookie", [...existing, value]);
return;
}
res.setHeader("set-cookie", [String(existing), value]);
}
createServer(async (req, res) => {
try {
const hostHeader = req.headers.host || `localhost:${port}`;
const protocol = (req.headers["x-forwarded-proto"] || "http").toString().split(",")[0].trim();
const url = new URL(req.url || "/", `${protocol}://${hostHeader}`);
if (tryServeStatic(req, res, url)) return;
const method = (req.method || "GET").toUpperCase();
const hasBody = method !== "GET" && method !== "HEAD";
const init = {
method,
headers: toHeaders(req.headers)
};
if (hasBody) {
init.body = Readable.toWeb(req);
init.duplex = "half";
}
const request = new Request(url, init);
const response = await serverEntry.fetch(request);
res.statusCode = response.status;
response.headers.forEach((value, key) => {
if (key.toLowerCase() === "set-cookie") {
appendSetCookie(res, value);
} else {
res.setHeader(key, value);
}
});
if (method === "HEAD" || !response.body) {
res.end();
return;
}
Readable.fromWeb(response.body).pipe(res);
} catch (error) {
console.error("Server error:", error);
if (!res.headersSent) {
res.statusCode = 500;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
}
res.end("Internal Server Error");
}
}).listen(port, host, () => {
console.log(`Server running at http://${host}:${port}`);
});