-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathserver.ts
73 lines (57 loc) · 1.74 KB
/
server.ts
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
import * as fs from "fs";
import * as path from "path";
import { createRequestHandler } from "@remix-run/server-runtime";
import * as build from "./build";
const mode = process.argv[2] === "dev" ? "development" : "production";
let requestHandler = createRequestHandler(build, mode);
setInterval(() => {
Bun.gc(true);
}, 9000);
async function handler(request: Request): Promise<Response> {
if (mode === "development") {
let newBuild = await import("./build"); // <- This is the segfault source
requestHandler = createRequestHandler(newBuild, mode);
}
const file = tryServeStaticFile("public", request);
if (file) return file;
return requestHandler(request);
}
const server = Bun.serve({
port: 3000,
fetch: mode === "development" ? liveReload(handler) : handler,
});
console.log(`Server started at ${server.hostname}`);
function tryServeStaticFile(
staticDir: string,
request: Request
): Response | undefined {
const url = new URL(request.url);
if (url.pathname.length < 2) return undefined;
const filePath = path.join(staticDir, url.pathname);
if (fs.existsSync(filePath)) {
const file = Bun.file(filePath);
return new Response(file, {
headers: {
"Content-Type": file.type,
"Cache-Control": "public, max-age=31536000",
},
});
}
return undefined;
}
function liveReload<TFunc extends Function>(callback: TFunc) {
const registry = new Map([...Loader.registry.entries()]);
function reload() {
if (Loader.registry.size !== registry.size) {
for (const key of Loader.registry.keys()) {
if (!registry.has(key)) {
Loader.registry.delete(key);
}
}
}
}
return async (...args: unknown[]) => {
reload();
return callback(...args);
};
}