import WebSocket from "ws" ; import { EventEmitter } from "events" ; export class Tiane extends EventEmitter { private readonly websocket : WebSocket ; private constructor ( websocket ) { super ( ) ; this . websocket = websocket ; this . websocket . onmessage = ( evt ) => { const data = evt . data as string ; if ( data !== undefined ) { const json = JSON . parse ( data ) ; switch ( json . action ) { case "say" : { this . emit ( "say-" + json . room , json . msg , json . ping ) ; break ; } case "event" : { this . emit ( "event-" + json . name , json . data ) ; } } this . emit ( "message" , json . msg , json . ping ) ; } } ; } static async connect ( address ) { if ( ! address . includes ( "://" ) ) { address = "ws://" + address ; } const websocket = new WebSocket ( address ) ; await new Promise ( ( resolve , reject ) => { websocket . once ( "error" , reject ) ; websocket . on ( "open" , ( ) => { websocket . off ( "error" , reject ) ; resolve ( undefined ) ; } ) ; } ) ; return new Tiane ( websocket ) ; } close ( ) { this . websocket . close ( ) ; } param room onsay ( room , handler ) { super . on ( "say-" + room , handler ) ; return this ; } /**
     * Add a listener when a TIANE module sends an event.
     */ onevent ( event , handler ) { super . on ( "event-" + event , handler ) ; return this ; } eventNames ( ) { return [ "message" ] ; } param text param user param room param role param explicit send ( text , user , room , role , explicit ) { this . websocket . send ( JSON . stringify ( { action : "listen" , msg : text , user : user , room : room , role : role , explicit : explicit } ) ) ; } /**
     * TIANE will tell the given user the given text.
     */ notify ( text , user ) { this . websocket . send ( JSON . stringify ( { action : "notify" , msg : text , user : user } ) ) ; } param secure newRoom ( name , secure ) { this . websocket . send ( JSON . stringify ( { action : "create_room" , room : name , secure : secure } ) ) ; } /**
     * Associate the given output type with a room previously created with `newRoom`.
     */ roomOutput ( room , output ) { this . websocket . send ( JSON . stringify ( { action : "set_output" , room : room , output : output } ) ) ; } /**
     * Moves the given user to the given room.
     */ moveTo ( user , room ) { this . websocket . send ( JSON . stringify ( { action : "set_user_to_room" , user : user , room : room } ) ) ; } }