* Connect to a Streamer.bot WebSocket server
(timeout: number = 10_000)
| 180 | */ |
| 181 | public get ready(): boolean { |
| 182 | if (!this.socket || this.socket.readyState !== this.socket.OPEN) return false; |
| 183 | if (this._authEnabled && !this._authenticated) return false; |
| 184 | return !!this.info && !!this.version; |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * Connect to a Streamer.bot WebSocket server |
| 189 | */ |
| 190 | public async connect(timeout: number = 10_000): Promise<void> { |
| 191 | if (this.socket?.readyState !== this.socket?.CLOSED) { |
| 192 | try { |
| 193 | await this.disconnect(); |
| 194 | } catch (e) { |
| 195 | this.logger?.warn('Unexpected error while calling disconnect():', e); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | this._explicitlyClosed = false; |
| 200 | |
| 201 | this._connectController.abort(); |
| 202 | this._connectController = new AbortController(); |
| 203 | const controller = new AbortController(); |
| 204 | const { signal } = controller; |
| 205 | |
| 206 | this._connectController.signal.addEventListener('abort', () => controller.abort(), { |
| 207 | once: true, |
| 208 | signal, |
| 209 | }); |
| 210 | |
| 211 | return await withTimeout( |
| 212 | new Promise<void>((res, rej) => { |
| 213 | try { |
| 214 | if (this.options.password) this._authEnabled = true; |
| 215 | |
| 216 | const uri = `${this.options.scheme}://${this.options.host}:${this.options.port}${this.options.endpoint}`; |
| 217 | this.logger?.debug( |
| 218 | 'Connecting to Streamer.bot WebSocket server at', |
| 219 | uri, |
| 220 | this._authEnabled ? 'with authentication' : '', |
| 221 | ); |
| 222 | |
| 223 | this.socket = new WebSocket(uri); |
| 224 | |
| 225 | this.socket.onmessage = this.onMessage.bind(this); |
| 226 | this.socket.onopen = this.onOpen.bind(this); |
| 227 | this.socket.onclose = this.onClose.bind(this); |
| 228 | this.socket.onerror = this.onError.bind(this); |
| 229 | |
| 230 | this.socket.addEventListener( |
| 231 | 'open', |
| 232 | () => { |
| 233 | if (!this.socket) return rej(new Error('WebSocket not initialized')); |
| 234 | res(); |
| 235 | }, |
| 236 | { once: true, signal }, |
| 237 | ); |
| 238 |
no test coverage detected