| 182 | } |
| 183 | |
| 184 | private dispatchMessage(msg: Record<string, unknown>): void { |
| 185 | if (msg['request']) { |
| 186 | // The device sends us incoming requests (configure handshake, and Messages.ts responses |
| 187 | // routed back via forward_client_payload). Auto-respond to all of them. |
| 188 | const req = msg['request'] as Record<string, unknown>; |
| 189 | const reqId = req['request_id'] as string; |
| 190 | const respKey = Object.keys(req).find((k) => k !== 'request_id'); |
| 191 | if (respKey) { |
| 192 | this.socket.write(encodePacket({ response: { [respKey]: {}, request_id: reqId } })); |
| 193 | if (respKey === 'configure') { |
| 194 | this.configureData = req['configure'] as Record<string, unknown>; |
| 195 | if (this.configureReady) { |
| 196 | const waiter = this.configureReady; |
| 197 | this.configureReady = null; |
| 198 | waiter.resolve(req); |
| 199 | } |
| 200 | } else if (respKey === 'forward_client_payload') { |
| 201 | // Device is returning a Messages.ts response routed back to us. |
| 202 | const fcp = req['forward_client_payload'] as Record<string, unknown> | undefined; |
| 203 | if (fcp) { |
| 204 | try { |
| 205 | const inner = JSON.parse(fcp['payload_string'] as string) as Record<string, unknown>; |
| 206 | const msgId = String(inner['requestId']); |
| 207 | const listener = this.payloadListeners.get(msgId); |
| 208 | if (listener) { |
| 209 | this.payloadListeners.delete(msgId); |
| 210 | listener.resolve(inner); |
| 211 | } |
| 212 | } catch { |
| 213 | // ignore malformed inner payload |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | } else if (msg['response']) { |
| 219 | const resp = msg['response'] as Record<string, unknown>; |
| 220 | const reqId = resp['request_id'] as string; |
| 221 | const pending = this.pendingRequests.get(reqId); |
| 222 | if (pending) { |
| 223 | this.pendingRequests.delete(reqId); |
| 224 | if (resp['error']) { |
| 225 | const errMsg = (resp['error'] as Record<string, unknown>)['error_message'] as string; |
| 226 | pending.reject(new Error(errMsg)); |
| 227 | } else { |
| 228 | pending.resolve(resp); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | // Note: events from the device (js_debugger_info, new_logs, etc.) are ignored. |
| 233 | } |
| 234 | |
| 235 | private sendRequest( |
| 236 | payload: Record<string, unknown>, |