@@ -10,6 +10,7 @@ const {
1010 ObjectDefineProperty,
1111 ObjectSetPrototypeOf,
1212 ReflectApply,
13+ SafeSet,
1314 StringPrototypeSlice,
1415 Symbol,
1516 Uint8Array,
@@ -81,6 +82,7 @@ let HTTPParser;
8182const MAX_HANDLE_RETRANSMISSIONS = 3 ;
8283const kChannelHandle = Symbol ( 'kChannelHandle' ) ;
8384const kIsUsedAsStdio = Symbol ( 'kIsUsedAsStdio' ) ;
85+ const kPendingMessages = Symbol ( 'pendingMessages' ) ;
8486
8587// This object contain function to convert TCP objects to native handle objects
8688// and back again.
@@ -526,6 +528,7 @@ class Control extends EventEmitter {
526528 constructor ( channel ) {
527529 super ( ) ;
528530 this . #channel = channel ;
531+ this [ kPendingMessages ] = new SafeSet ( ) ;
529532 }
530533
531534 // The methods keeping track of the counter are being used to track the
@@ -699,6 +702,19 @@ function setupChannel(target, channel, serializationMode) {
699702 } ) ;
700703 } ) ;
701704
705+ target . on ( 'newListener' , function ( ) {
706+ if ( ! target . channel ) return ;
707+
708+ const messages = target . channel [ kPendingMessages ] ;
709+ if ( ! messages . size ) return ;
710+
711+ for ( const messageParams of messages ) {
712+ process . nextTick ( ( ) => ReflectApply ( target . emit , target , messageParams ) ) ;
713+ }
714+
715+ messages . clear ( ) ;
716+ } ) ;
717+
702718 target . send = function ( message , handle , options , callback ) {
703719 if ( typeof handle === 'function' ) {
704720 callback = handle ;
@@ -912,7 +928,14 @@ function setupChannel(target, channel, serializationMode) {
912928 } ;
913929
914930 function emit ( event , message , handle ) {
915- target . emit ( event , message , handle ) ;
931+ const isInternalMessage = 'internalMessage' === event ;
932+ const hasListenersInstalled = target . listenerCount ( 'message' ) ;
933+ if ( hasListenersInstalled || isInternalMessage ) {
934+ target . emit ( event , message , handle ) ;
935+ return ;
936+ }
937+
938+ target . channel [ kPendingMessages ] . add ( [ event , message , handle ] ) ;
916939 }
917940
918941 function handleMessage ( message , handle , internal ) {
0 commit comments