import { NodeCG } from "nodecg-types/types/server" ; import { Result , emptySuccess , success , ServiceBundle , Logger } from "nodecg-io-core" ; import WebSocket from "ws" ; interface WSClientServiceConfig { address : string ; } export class WSClientServiceClient extends WebSocket { constructor ( address ) { super ( address ) ; } onClose ( func ) { return this . on ( "close" , func ) ; } onMessage ( func ) { return this . on ( "message" , func ) ; } onError ( func ) { return this . on ( "error" , func ) ; } } module . exports = ( nodecg ) => { new WSClientService ( nodecg , "websocket-client" , __dirname , "../ws-schema.json" ) . register ( ) ; } ; class WSClientService extends ServiceBundle < WSClientServiceConfig , WSClientServiceClient > { async validateConfig ( config ) { const client = new WSClientServiceClient ( config . address ) ; await new Promise ( ( resolve , reject ) => { client . once ( "error" , reject ) ; client . on ( "open" , ( ) => { client . off ( "error" , reject ) ; resolve ( undefined ) ; } ) ; } ) ; client . close ( ) ; return emptySuccess ( ) ; } async createClient ( config , logger ) { const client = new WSClientServiceClient ( config . address ) ; await new Promise ( ( resolve , reject ) => { client . once ( "error" , reject ) ; client . on ( "open" , ( ) => { client . off ( "error" , reject ) ; resolve ( undefined ) ; } ) ; } ) ; logger . info ( "Successfully connected to the WebSocket server." ) ; return success ( client ) ; } stopClient ( client ) { client . close ( ) ; } removeHandlers ( client ) { client . removeAllListeners ( ) ; } }