import { v4 as uuidv4 } from 'uuid' ; import ipc from 'node-ipc' ; const replyHandlers = new Map ( ) ; const listeners = new Map ( ) ; let messageQueue = [ ] ; let socketClient = null ; export const connectSocket = ( socketId ) => { ipc . config . silent = true ; ipc . connectTo ( socketId , ( ) => { const client = ipc . of [ socketId ] ; client . on ( 'message' , ( data ) => { const msg = JSON . parse ( data ) ; if ( msg . type === 'error' ) { const { id } = msg ; replyHandlers . delete ( id ) ; } else if ( msg . type === 'reply' ) { const { id , result } = msg ; const handler = replyHandlers . get ( id ) ; if ( handler ) { replyHandlers . delete ( id ) ; handler . resolve ( result ) ; } } else if ( msg . type === 'push' ) { const { name , payload } = msg ; const listens = listeners . get ( name ) ; if ( listens ) { listens . forEach ( ( listener ) => { listener ( payload ) ; } ) ; } } else { throw new Error ( `Unknown message type: ${ JSON . stringify ( msg ) }` ) ; } } ) ; client . on ( 'connect' , ( ) => { socketClient = client ; if ( messageQueue . length > 0 ) { messageQueue . forEach ( ( msg ) => client . emit ( 'message' , msg ) ) ; messageQueue = [ ] ; } console . log ( `Connected! ${ socketId }` ) ; } ) ; client . on ( 'disconnect' , ( ) => { socketClient = null ; } ) ; } ) ; } ; export const sendBackIpc = ( name , payload = { } ) : Promise < unknown > => { return new Promise ( ( resolve , reject ) => { const id = uuidv4 ( ) ; replyHandlers . set ( id , { resolve , reject } ) ; if ( socketClient ) { socketClient . emit ( 'message' , JSON . stringify ( { id , name , payload } ) ) ; } else { messageQueue . push ( JSON . stringify ( { id , name , payload } ) ) ; } } ) ; } ; export function listenBackIpc ( name , cb ) { if ( ! listeners . get ( name ) ) { listeners . set ( name , [ ] ) ; } listeners . get ( name ) . push ( cb ) ; return ( ) => { const arr = listeners . get ( name ) ; listeners . set ( name , arr . filter ( ( cb_ ) => cb_ !== cb ) ) ; } ; } export function unlistenBackIpc ( name ) { listeners . set ( name , [ ] ) ; }