| 36 | |
| 37 | /** @class */ |
| 38 | module.exports = class Client { |
| 39 | #ws; |
| 40 | |
| 41 | #logged = false; |
| 42 | |
| 43 | /** If the client is logged in */ |
| 44 | get isLogged() { |
| 45 | return this.#logged; |
| 46 | } |
| 47 | |
| 48 | /** If the cient was closed */ |
| 49 | get isOpen() { |
| 50 | return this.#ws.readyState === this.#ws.OPEN; |
| 51 | } |
| 52 | |
| 53 | /** @type {SessionList} */ |
| 54 | #sessions = {}; |
| 55 | |
| 56 | #callbacks = { |
| 57 | connected: [], |
| 58 | disconnected: [], |
| 59 | logged: [], |
| 60 | ping: [], |
| 61 | data: [], |
| 62 | |
| 63 | error: [], |
| 64 | event: [], |
| 65 | }; |
| 66 | |
| 67 | /** |
| 68 | * @param {ClientEvent} ev Client event |
| 69 | * @param {...{}} data Packet data |
| 70 | */ |
| 71 | #handleEvent(ev, ...data) { |
| 72 | this.#callbacks[ev].forEach((e) => e(...data)); |
| 73 | this.#callbacks.event.forEach((e) => e(ev, ...data)); |
| 74 | } |
| 75 | |
| 76 | #handleError(...msgs) { |
| 77 | if (this.#callbacks.error.length === 0) console.error(...msgs); |
| 78 | else this.#handleEvent('error', ...msgs); |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * When client is connected |
| 83 | * @param {() => void} cb Callback |
| 84 | * @event onConnected |
| 85 | */ |
| 86 | onConnected(cb) { |
| 87 | this.#callbacks.connected.push(cb); |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * When client is disconnected |
| 92 | * @param {() => void} cb Callback |
| 93 | * @event onDisconnected |
| 94 | */ |
| 95 | onDisconnected(cb) { |