From a32c1828768fb3d03b818c808682a83a42d9d6c3 Mon Sep 17 00:00:00 2001 From: David-Emmanuel DIVERNOIS Date: Tue, 16 May 2023 17:01:52 +0200 Subject: [PATCH] feat: allow using vite as a proxy for another vite server --- packages/vite/src/node/server/middlewares/proxy.ts | 8 +++----- packages/vite/src/node/server/ws.ts | 11 ++++++++++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/vite/src/node/server/middlewares/proxy.ts b/packages/vite/src/node/server/middlewares/proxy.ts index 66f99f94f0609d..ae289a8f8e9776 100644 --- a/packages/vite/src/node/server/middlewares/proxy.ts +++ b/packages/vite/src/node/server/middlewares/proxy.ts @@ -4,7 +4,6 @@ import httpProxy from 'http-proxy' import type { Connect } from 'dep-types/connect' import type { HttpProxy } from 'dep-types/http-proxy' import colors from 'picocolors' -import { HMR_HEADER } from '../ws' import { createDebugger } from '../../utils' import type { CommonServerOptions, ResolvedConfig } from '../..' @@ -103,10 +102,9 @@ export function proxyMiddleware( if (doesProxyContextMatchUrl(context, url)) { const [proxy, opts] = proxies[context] if ( - (opts.ws || - opts.target?.toString().startsWith('ws:') || - opts.target?.toString().startsWith('wss:')) && - req.headers['sec-websocket-protocol'] !== HMR_HEADER + opts.ws || + opts.target?.toString().startsWith('ws:') || + opts.target?.toString().startsWith('wss:') ) { if (opts.rewrite) { req.url = opts.rewrite(url) diff --git a/packages/vite/src/node/server/ws.ts b/packages/vite/src/node/server/ws.ts index 61d989080e7573..e1278959fedb27 100644 --- a/packages/vite/src/node/server/ws.ts +++ b/packages/vite/src/node/server/ws.ts @@ -1,3 +1,4 @@ +import path from 'node:path' import type { Server } from 'node:http' import { STATUS_CODES, createServer as createHttpServer } from 'node:http' import type { ServerOptions as HttpsServerOptions } from 'node:https' @@ -101,9 +102,17 @@ export function createWebSocketServer( const host = (hmr && hmr.host) || undefined if (wsServer) { + let hmrBase = config.base + const hmrPath = hmr ? hmr.path : undefined + if (hmrPath) { + hmrBase = path.posix.join(hmrBase, hmrPath) + } wss = new WebSocketServerRaw({ noServer: true }) wsServer.on('upgrade', (req, socket, head) => { - if (req.headers['sec-websocket-protocol'] === HMR_HEADER) { + if ( + req.headers['sec-websocket-protocol'] === HMR_HEADER && + req.url === hmrBase + ) { wss.handleUpgrade(req, socket as Socket, head, (ws) => { wss.emit('connection', ws, req) })