forked from matrix-org/thirdroom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preview-server.ts
82 lines (65 loc) · 1.77 KB
/
preview-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
74
75
76
77
78
79
80
81
82
import chokidar from "chokidar";
import { build, InlineConfig, preview, UserConfig } from "vite";
import { WebSocket, WebSocketServer } from "ws";
import config from "./vite.config";
const userConfig = config as UserConfig;
const devServerConfig: InlineConfig = {
...userConfig,
mode: "preview",
build: {
minify: false,
sourcemap: true,
},
preview: {
...userConfig.preview,
open: true,
port: 3000,
},
};
await build(devServerConfig);
const previewServer = await preview(devServerConfig);
previewServer.httpServer.prependListener("request", (_req, res) => {
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
});
let sockets: WebSocket[] = [];
const wss = new WebSocketServer({ server: previewServer.httpServer });
wss.on("connection", (ws) => {
ws.addEventListener("close", () => {
sockets = sockets.filter((s) => s !== ws);
});
sockets.push(ws);
});
console.log("\n");
previewServer.printUrls();
console.log("\n");
const debounce = (callback: (...args: any[]) => void, wait: number) => {
let timeout: NodeJS.Timeout;
return (...args: any[]) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
clearTimeout(timeout);
callback(...args);
}, wait);
};
};
async function rebuild() {
try {
await build(devServerConfig);
for (const socket of sockets) {
socket.send("rebuilt");
}
} catch (error) {
console.log(error);
}
}
const debouncedRebuild = debounce(rebuild, 500);
chokidar
.watch(["./src", "index.html"], {
ignoreInitial: true,
})
.on("add", debouncedRebuild)
.on("change", debouncedRebuild)
.on("unlink", debouncedRebuild)
.on("addDir", debouncedRebuild)
.on("unlinkDir", debouncedRebuild);