@@ -11,6 +11,7 @@ export class WebSocketTransport implements ConnectionTransport {
1111 private _ws : WebSocket ;
1212 private _pingInterval : NodeJS . Timer ;
1313 private _chunks : Uint8Array [ ] = [ ] ;
14+ private closeResolver : PromiseWithResolvers < void > ;
1415 onmessage ?: ( message : ProtocolResponse ) => void ;
1516 onclose ?: ( ) => void ;
1617 readonly sessionId : string ;
@@ -36,15 +37,20 @@ export class WebSocketTransport implements ConnectionTransport {
3637 this . onmessage ! ( JSON . parse ( message ) as ProtocolResponse ) ;
3738 } ) ;
3839 this . _ws . addEventListener ( 'close' , ( ) => {
40+ // https://github.com/cloudflare/workerd/issues/4327#issuecomment-3670433485
41+ if ( this . _ws . readyState !== WebSocket . CLOSED )
42+ this . _ws . close ( ) ;
3943 clearInterval ( this . _pingInterval as NodeJS . Timeout ) ;
4044 if ( this . onclose )
4145 this . onclose ( ) ;
46+ this . closeResolver . resolve ( ) ;
4247 } ) ;
4348 this . _ws . addEventListener ( 'error' , e => {
4449 // eslint-disable-next-line no-console
4550 console . error ( `Websocket error: SessionID: ${ sessionId } ` , e ) ;
4651 clearInterval ( this . _pingInterval as NodeJS . Timeout ) ;
4752 } ) ;
53+ this . closeResolver = Promise . withResolvers ( ) ;
4854 }
4955
5056 send ( message : ProtocolRequest ) : void {
@@ -62,7 +68,7 @@ export class WebSocketTransport implements ConnectionTransport {
6268 if ( this . _ws . readyState === WebSocket . CLOSED )
6369 return ;
6470 this . close ( ) ;
65- // TODO wait for close event
71+ await this . closeResolver . promise ;
6672 }
6773
6874 toString ( ) : string {
0 commit comments