-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.ts
97 lines (86 loc) · 2.98 KB
/
watch.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// @ts-ignore
import index from "./index.html" with { type: "text" };
import { readdir } from "fs/promises";
import { watchFile } from "fs";
import UnpluginTypia from "@ryoppippi/unplugin-typia/bun";
const [out, src] = await Promise.all([
readdir("out"),
readdir("src").then((a) => a.map((v) => "src/" + v)),
]);
async function buildClient() {
console.log("Building client...");
await Bun.build({
entrypoints: ["src/client.ts"],
outdir: "out",
target: "browser",
sourcemap: "linked",
plugins: [UnpluginTypia()],
define: {
DEBUG: process.env.DEBUG ?? "false",
},
})
.then(() => console.log("Client build success."))
.catch(() => console.log("Client build failed."));
}
await buildClient();
watchFile("./src/client.ts", { interval: 50 }, buildClient);
const server = Bun.serve({
port: 6969,
fetch(request) {
if (request.method !== "GET") {
return new Response("Method Not Allowed", {
status: 405,
statusText: "Method Not Allowed",
headers: { "Content-Type": "text/plain" },
});
}
const url = new URL(request.url);
if (url.pathname === "/") {
return new Response(index, {
headers: { "Content-Type": "text/html" },
});
} else {
let path = url.pathname.slice(1);
if (path.endsWith("/")) {
path = path.slice(0, -1);
}
if (out.includes(path)) {
const file = Bun.file(`./out/${path}`);
// directory or binary file
if (file.type === "application/octet-stream") {
return new Response("Not Found", {
status: 404,
headers: { "Content-Type": "text/plain" },
});
}
return new Response(file, {
headers: {
"Content-Type": file.type,
},
});
}
// For when clicking in error stacktrace w/ the mapped source in the browser
else if (src.includes(path)) {
const file = Bun.file(path);
// directory or binary file
if (file.type === "application/octet-stream") {
return new Response("Not Found", {
status: 404,
headers: { "Content-Type": "text/plain" },
});
}
return new Response(file, {
headers: {
"Content-Type": file.type,
},
});
}
}
return new Response("Not Found", {
status: 404,
statusText: "Not Found",
headers: { "Content-Type": "text/plain" },
});
},
});
console.log(`HTTP: Listening on ${server.hostname}:${server.port}`);