@@ -22,7 +22,7 @@ export class WindowsScriptingHost extends EventEmitter {
2222 #trace;
2323 #finalizer = new FinalizationRegistry ( this . #finalized. bind ( this ) ) ;
2424 #ref2proxy = new Map ( ) ;
25- #proxy2ref = new Map ( ) ;
25+ #proxy2ref = new WeakMap ( ) ;
2626
2727 #objectHandler = {
2828
@@ -137,21 +137,23 @@ export class WindowsScriptingHost extends EventEmitter {
137137 }
138138
139139 #getOrCreate( ref , handler ) {
140- const existingProxy = this . #ref2proxy. get ( ref ) ;
140+ const existingProxy = this . #ref2proxy. get ( ref ) . deref ( ) ;
141141 if ( existingProxy )
142142 return existingProxy ;
143143
144144 const target = handler === this . #objectHandler? new RemoteObject ( ref ) : function ( ) { } ;
145145 const newProxy = new Proxy ( target , handler ) ;
146146 target [ PROXY ] = newProxy ;
147- this . #ref2proxy. set ( ref , newProxy ) ;
147+ this . #ref2proxy. set ( ref , new WeakRef ( newProxy ) ) ; // may be overwriting a dead WeakRef
148148 this . #proxy2ref. set ( newProxy , ref ) ;
149149 this . #finalizer. register ( newProxy , ref ) ;
150150 this . emit ( 'ref' , ref , newProxy ) ;
151151 return newProxy ;
152152 }
153153
154154 #finalized( ref ) {
155+ if ( this . #ref2proxy. get ( ref ) . deref ( ) === undefined ) // otherwise, it's overwritten by a refreshed proxy
156+ this . #ref2proxy. delete ( ref ) ;
155157 const output = this . #syncline. exchange ( JSON . stringify ( [ 'unref' , ref ] ) ) ;
156158 if ( this . #trace >= TRACE_REF )
157159 switch ( output [ 0 ] ) {
@@ -186,7 +188,7 @@ export class WindowsScriptingHost extends EventEmitter {
186188 }
187189 if ( decoded instanceof RemoteObject ) {
188190 const objref = this . #proxy2ref. get ( decoded ) ;
189- if ( objref === undefined )
191+ if ( objref === undefined ) // not because garbage-collected, because clearly `decoded` is still alive
190192 throw new Error ( `remote object reference not found: ${ decoded } ` ) ;
191193 return { type : 'objref' , value : objref } ;
192194 }
@@ -196,7 +198,7 @@ export class WindowsScriptingHost extends EventEmitter {
196198 return encoded ;
197199 case 'function' :
198200 const funref = this . #proxy2ref. get ( decoded ) ;
199- if ( funref === undefined )
201+ if ( funref === undefined ) // not because garbage-collected, because clearly `decoded` is still alive
200202 throw new Error ( `functions from node are disallowed: ${ decoded } ` ) ;
201203 return { type : 'funref' , value : funref } ;
202204 case 'bigint' :
0 commit comments