From 049404c2ba5cbf0292d23552d4e292cf33798d16 Mon Sep 17 00:00:00 2001 From: dave caruso Date: Fri, 21 Jul 2023 00:24:40 -0700 Subject: [PATCH] fix: use Bun's implementation of `ws` instead of the bundled one (#13901) --- packages/vite/src/node/server/ws.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/server/ws.ts b/packages/vite/src/node/server/ws.ts index e1278959fedb27..4a298cac1eebd2 100644 --- a/packages/vite/src/node/server/ws.ts +++ b/packages/vite/src/node/server/ws.ts @@ -6,13 +6,21 @@ import { createServer as createHttpsServer } from 'node:https' import type { Socket } from 'node:net' import colors from 'picocolors' import type { WebSocket as WebSocketRaw } from 'ws' -import { WebSocketServer as WebSocketServerRaw } from 'ws' +import { WebSocketServer as WebSocketServerRaw_ } from 'ws' import type { WebSocket as WebSocketTypes } from 'dep-types/ws' import type { CustomPayload, ErrorPayload, HMRPayload } from 'types/hmrPayload' import type { InferCustomEventPayload } from 'types/customEvent' import type { ResolvedConfig } from '..' import { isObject } from '../utils' +/* In Bun, the `ws` module is overridden to hook into the native code. Using the bundled `js` version + * of `ws` will not work as Bun's req.socket does not allow reading/writing to the underlying socket. + */ +const WebSocketServerRaw = process.versions.bun + ? // @ts-expect-error: Bun defines `import.meta.require` + import.meta.require('ws').WebSocketServer + : WebSocketServerRaw_ + export const HMR_HEADER = 'vite-hmr' export type WebSocketCustomListener = ( @@ -87,7 +95,7 @@ export function createWebSocketServer( config: ResolvedConfig, httpsOptions?: HttpsServerOptions, ): WebSocketServer { - let wss: WebSocketServerRaw + let wss: WebSocketServerRaw_ let wsHttpServer: Server | undefined = undefined const hmr = isObject(config.server.hmr) && config.server.hmr