-
-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (46 loc) · 1.41 KB
/
Copy pathserver.js
File metadata and controls
55 lines (46 loc) · 1.41 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
import { serve } from "bun";
import { join } from "path";
import { readFileSync, existsSync } from "fs";
const PORT = 3000;
const DIST_DIR = join(import.meta.dir, "dist");
console.log(`Starting server on http://localhost:${PORT}`);
console.log(`Serving files from: ${DIST_DIR}`);
serve({
port: PORT,
async fetch(req) {
const url = new URL(req.url);
let path = join(DIST_DIR, url.pathname);
if (url.pathname === "/") {
path = join(DIST_DIR, "index.html");
}
if (!existsSync(path)) {
// SPA fallback or 404
if (req.headers.get("accept")?.includes("text/html")) {
path = join(DIST_DIR, "index.html");
} else {
return new Response("Not Found", { status: 404 });
}
}
const file = readFileSync(path);
const extension = path.split(".").pop();
// MIME types mapping
const mimeTypes = {
"html": "text/html",
"js": "application/javascript",
"css": "text/css",
"svg": "image/svg+xml",
"wasm": "application/wasm",
"mp3": "audio/mpeg",
"bin": "application/octet-stream",
"json": "application/json"
};
const contentType = mimeTypes[extension] || "application/octet-stream";
return new Response(file, {
headers: {
"Content-Type": contentType,
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
},
});
},
});