@@ -109,7 +109,14 @@ export interface BirpcGroupFn<T> {
109109
110110export type BirpcReturn < RemoteFunctions , LocalFunctions = Record < string , never > > = {
111111 [ K in keyof RemoteFunctions ] : BirpcFn < RemoteFunctions [ K ] >
112- } & { $functions : LocalFunctions , $close : ( error ?: Error ) => void , $closed : boolean }
112+ } & {
113+ $functions : LocalFunctions
114+ $close : ( error ?: Error ) => void
115+ $closed : boolean
116+ $rejectPendingCalls : ( handler ?: PendingCallHandler ) => Promise < void > [ ]
117+ }
118+
119+ type PendingCallHandler = ( options : Pick < PromiseEntry , 'method' | 'reject' > ) => void | Promise < void >
113120
114121export type BirpcGroupReturn < RemoteFunctions > = {
115122 [ K in keyof RemoteFunctions ] : BirpcGroupFn < RemoteFunctions [ K ] >
@@ -122,6 +129,13 @@ export interface BirpcGroup<RemoteFunctions, LocalFunctions = Record<string, nev
122129 updateChannels : ( fn ?: ( ( channels : ChannelOptions [ ] ) => void ) ) => BirpcReturn < RemoteFunctions , LocalFunctions > [ ]
123130}
124131
132+ interface PromiseEntry {
133+ resolve : ( arg : any ) => void
134+ reject : ( error : any ) => void
135+ method : string
136+ timeoutId ?: ReturnType < typeof setTimeout >
137+ }
138+
125139const TYPE_REQUEST = 'q' as const
126140const TYPE_RESPONSE = 's' as const
127141
@@ -192,12 +206,7 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
192206 timeout = DEFAULT_TIMEOUT ,
193207 } = options
194208
195- const rpcPromiseMap = new Map < string , {
196- resolve : ( arg : any ) => void
197- reject : ( error : any ) => void
198- method : string
199- timeoutId ?: ReturnType < typeof setTimeout >
200- } > ( )
209+ const rpcPromiseMap = new Map < string , PromiseEntry > ( )
201210
202211 let _promise : Promise < any > | any
203212 let closed = false
@@ -210,6 +219,10 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
210219 if ( method === '$close' )
211220 return close
212221
222+ if ( method === '$rejectPendingCalls' ) {
223+ return rejectPendingCalls
224+ }
225+
213226 if ( method === '$closed' )
214227 return closed
215228
@@ -285,6 +298,22 @@ export function createBirpc<RemoteFunctions = Record<string, never>, LocalFuncti
285298 off ( onMessage )
286299 }
287300
301+ function rejectPendingCalls ( handler ?: PendingCallHandler ) {
302+ const entries = Array . from ( rpcPromiseMap . values ( ) )
303+
304+ const handlerResults = entries . map ( ( { method, reject } ) => {
305+ if ( ! handler ) {
306+ return reject ( new Error ( `[birpc]: rejected pending call "${ method } ".` ) )
307+ }
308+
309+ return handler ( { method, reject } )
310+ } )
311+
312+ rpcPromiseMap . clear ( )
313+
314+ return handlerResults
315+ }
316+
288317 async function onMessage ( data : any , ...extra : any [ ] ) {
289318 let msg : RPCMessage
290319
0 commit comments