-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Copy pathws.ts
87 lines (77 loc) · 2.2 KB
/
ws.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
import chalk from 'chalk'
import { Server } from 'http'
import WebSocket from 'ws'
import { ErrorPayload, HMRPayload } from 'types/hmrPayload'
import { ResolvedConfig } from '..'
export const HMR_HEADER = 'vite-hmr'
export interface WebSocketServer {
send(payload: HMRPayload): void
close(): Promise<void>
}
export function createWebSocketServer(
server: Server | null,
config: ResolvedConfig
): WebSocketServer {
let wss: WebSocket.Server
if (server) {
wss = new WebSocket.Server({ noServer: true })
server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] === HMR_HEADER) {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req)
})
}
})
} else {
// vite dev server in middleware mode
wss = new WebSocket.Server({
port:
(typeof config.server.hmr === 'object' && config.server.hmr.port) ||
24678
})
}
wss.on('connection', (socket) => {
socket.send(JSON.stringify({ type: 'connected' }))
if (bufferedError) {
socket.send(JSON.stringify(bufferedError))
bufferedError = null
}
})
wss.on('error', (e: Error & { code: string }) => {
if (e.code !== 'EADDRINUSE') {
config.logger.error(
chalk.red(`WebSocket server error:\n${e.stack || e.message}`)
)
}
})
// On page reloads, if a file fails to compile and returns 500, the server
// sends the error payload before the client connection is established.
// If we have no open clients, buffer the error and send it to the next
// connected client.
let bufferedError: ErrorPayload | null = null
return {
send(payload: HMRPayload) {
if (payload.type === 'error' && !wss.clients.size) {
bufferedError = payload
return
}
const stringified = JSON.stringify(payload)
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(stringified)
}
})
},
close() {
return new Promise((resolve, reject) => {
wss.close((err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
}
}