1+ import { coupleWebSocket } from "miniflare" ;
12import { WebSocketServer } from "ws" ;
23import { UNKNOWN_HOST } from "./shared" ;
34import { nodeHeadersToWebHeaders } from "./utils" ;
@@ -12,8 +13,7 @@ import type * as vite from "vite";
1213 */
1314export function handleWebSocket (
1415 httpServer : vite . HttpServer ,
15- fetcher : ReplaceWorkersTypes < Fetcher > [ "fetch" ] ,
16- logger : vite . Logger
16+ fetcher : ReplaceWorkersTypes < Fetcher > [ "fetch" ]
1717) {
1818 const nodeWebSocket = new WebSocketServer ( { noServer : true } ) ;
1919
@@ -44,41 +44,7 @@ export function handleWebSocket(
4444 socket ,
4545 head ,
4646 async ( clientWebSocket ) => {
47- workerWebSocket . accept ( ) ;
48-
49- // Forward Worker events to client
50- workerWebSocket . addEventListener ( "message" , ( event ) => {
51- clientWebSocket . send ( event . data ) ;
52- } ) ;
53- workerWebSocket . addEventListener ( "error" , ( event ) => {
54- logger . error (
55- `WebSocket error:\n${ event . error ?. stack || event . error ?. message } ` ,
56- { error : event . error }
57- ) ;
58- } ) ;
59- workerWebSocket . addEventListener ( "close" , ( ) => {
60- clientWebSocket . close ( ) ;
61- } ) ;
62-
63- // Forward client events to Worker
64- clientWebSocket . on ( "message" , ( data , isBinary ) => {
65- workerWebSocket . send (
66- isBinary
67- ? Array . isArray ( data )
68- ? Buffer . concat ( data )
69- : data
70- : data . toString ( )
71- ) ;
72- } ) ;
73- clientWebSocket . on ( "error" , ( error ) => {
74- logger . error ( `WebSocket error:\n${ error . stack || error . message } ` , {
75- error,
76- } ) ;
77- } ) ;
78- clientWebSocket . on ( "close" , ( ) => {
79- workerWebSocket . close ( ) ;
80- } ) ;
81-
47+ coupleWebSocket ( clientWebSocket , workerWebSocket ) ;
8248 nodeWebSocket . emit ( "connection" , clientWebSocket , request ) ;
8349 }
8450 ) ;
0 commit comments