/** @module Connection */ import Message from "./message"; import WebSocket from "isomorphic-ws"; import type { CloseEvent, ErrorEvent } from "isomorphic-ws"; interface Endpoint { port: number; address: string; } type MessageCallback = (arg0: Message) => any; type DisconnectCallback = (arg0: CloseEvent) => any; export default class Connection { /** * An object mapped by message types leading to an array of callbacks that takes in the message for first parameter. If undefined, no callbacks for it exists. */ protected messageCallback: { [type: string]: MessageCallback[]; }; protected disconnectCallback: DisconnectCallback[]; private waitingForJoinResult; private joinKey; private joinData; private endpoints; private endpointStrings; private timeout; developmentServer: string | null; connected: boolean; protected socket: WebSocket; constructor(developmentServer: string | null, endpoints: Endpoint[], joinKey: string, joinData?: { [key: string]: unknown; }); connect(): Promise; /** * Disconnect from the multiplayer room */ disconnect(): void; protected socketOnError(msg: ErrorEvent): void; sendMessage(message: Message): void; /** * Create a message with arguments inline: connection.createMessage('invite', arg1, arg2...) * @param {string} type * @param args NOTE THIS PROPERTY ISN'T MEANT TO BE GIVEN AS AN ARRAY, just spread it across many arguments. * @returns {Message} The message */ createMessage(type: T, ...args: any[]): Message; /** * Send a message with arguments inline: connection.createMessage('invite', arg1, arg2...) * @param {string} type The string type to give to the message. */ send(type: string, ...args: any[]): void; /** * @param {string} type Use * for all message types. * @param {Message} msg * @protected */ executeCallbacks(type: string, msg: Message): void; /** * Add a message callback for the given message type. * @param {string} type The type of message to invoke the callback for. Use '*' or null to handle all message types. * @param {function(Message)} callback The callback to be called when a message of the given type is received * * An example usage: * @example connection.addMessageCallback("*", (message) => { * if (message.type === "init") message.send("init2"); * }); */ addMessageCallback(type: string, callback: MessageCallback): void; /** * Add a callback that triggers when the connection closes. * * The CloseEvent will always have the code property, reason is provided but may be empty string. */ addDisconnectCallback(callback: DisconnectCallback): void; } export {};