@lynx-js/devtool-connector 0.9.5 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +1 -1
  2. package/dist/346.js +635 -0
  3. package/dist/390.js +262 -35
  4. package/dist/556.js +9 -4
  5. package/dist/61.js +3432 -0
  6. package/dist/63.js +112 -30
  7. package/dist/712.js +28 -2
  8. package/dist/872.js +552 -122
  9. package/dist/962.js +25 -17
  10. package/dist/client-discovery-errors.d.ts +1 -0
  11. package/dist/client-id.d.ts +9 -2
  12. package/dist/command/client.d.ts +28 -0
  13. package/dist/command/contract.d.ts +255 -0
  14. package/dist/command/core.d.ts +32 -0
  15. package/dist/command/index.d.ts +20 -0
  16. package/dist/command/index.js +224 -0
  17. package/dist/command/query.d.ts +5 -0
  18. package/dist/command/reactlynx/controller.d.ts +71 -0
  19. package/dist/command/reactlynx/model.d.ts +48 -0
  20. package/dist/command/reactlynx/protocol.d.ts +40 -0
  21. package/dist/command/reactlynx/session.d.ts +43 -0
  22. package/dist/command/reactlynx/types.d.ts +73 -0
  23. package/dist/command/ref-actions.d.ts +17 -0
  24. package/dist/command/result.d.ts +29 -0
  25. package/dist/command/screenshot-annotation.d.ts +22 -0
  26. package/dist/command/screenshot.d.ts +28 -0
  27. package/dist/command/snapshot.d.ts +79 -0
  28. package/dist/command/targets.d.ts +15 -0
  29. package/dist/daemon/device-connection.d.ts +3 -1
  30. package/dist/daemon/entry.js +11 -0
  31. package/dist/daemon/index.d.ts +1 -0
  32. package/dist/daemon/index.js +3 -0
  33. package/dist/daemon/manager.d.ts +11 -9
  34. package/dist/daemon/protocol.d.ts +24 -3
  35. package/dist/daemon/server.d.ts +1 -0
  36. package/dist/index.d.ts +6 -2
  37. package/dist/index.js +2 -454
  38. package/dist/streams/customized.d.ts +2 -1
  39. package/dist/transport/android.d.ts +1 -1
  40. package/dist/transport/desktop.d.ts +1 -1
  41. package/dist/transport/index.js +2 -2
  42. package/dist/transport/ios.d.ts +1 -1
  43. package/dist/transport/transport.d.ts +7 -1
  44. package/dist/transport/ws-stream.d.ts +9 -0
  45. package/dist/types.d.ts +35 -0
  46. package/package.json +10 -2
  47. package/dist/187.js +0 -272
  48. package/dist/43.js +0 -20
  49. package/dist/677.js +0 -19
package/dist/872.js CHANGED
@@ -1,14 +1,17 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import node_http from "node:http";
2
- import { setTimeout as promises_setTimeout } from "node:timers/promises";
3
+ import { createDebug } from "obug";
3
4
  import { WebSocketServer } from "ws";
4
5
  import node_fs from "node:fs";
5
6
  import node_path from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
8
  import node_zlib from "node:zlib";
8
- import { isCustomizedMessage, DAEMON_VERSION_PATH, DAEMON_INSPECTOR_PATH, isListClientsRequest, DAEMON_SHUTDOWN_PATH, isPingEvent, isRegisterEvent, isControlRequest, node_createDebug, DAEMON_WS_PATH } from "./187.js";
9
- import { isInitializeResponse } from "./677.js";
10
- import { ClientId } from "./43.js";
11
- const debug = node_createDebug('devtool-mcp-server:daemon:device-connection');
9
+ import { isInitializeResponse } from "./712.js";
10
+ import { isCustomizedMessage, isRegisterEvent, DAEMON_VERSION_PATH, isListClientsRequest, DAEMON_SHUTDOWN_PATH, DAEMON_INSPECTOR_PATH, DAEMON_PRODUCT, isPingEvent, DAEMON_WS_PATH, DAEMON_COMMAND_PATH_PREFIX, isControlRequest, CONNECTOR_VERSION } from "./390.js";
11
+ import { decodeCommandQuery, ActionCore } from "./61.js";
12
+ import { Connector, ClientId, throwClientDiscoveryFailures } from "./346.js";
13
+ import { DaemonTransport } from "./556.js";
14
+ const debug = createDebug('devtool-mcp-server:daemon:device-connection');
12
15
  class DeviceConnection {
13
16
  key;
14
17
  deviceId;
@@ -19,7 +22,14 @@ class DeviceConnection {
19
22
  #transport;
20
23
  #options;
21
24
  #disposed = false;
25
+ #disposePromise = null;
26
+ #terminalCause;
27
+ #connectPromise = null;
22
28
  #readLoopPromise = null;
29
+ #registered;
30
+ #resolveRegistered;
31
+ #rejectRegistered;
32
+ #registrationSettled = false;
23
33
  appInfo = null;
24
34
  constructor(transport, options){
25
35
  this.#transport = transport;
@@ -27,21 +37,36 @@ class DeviceConnection {
27
37
  this.deviceId = options.deviceId;
28
38
  this.port = options.port;
29
39
  this.key = `${options.deviceId}:${options.port}`;
40
+ this.#registered = new Promise((resolve, reject)=>{
41
+ this.#resolveRegistered = resolve;
42
+ this.#rejectRegistered = reject;
43
+ });
44
+ this.#registered.catch(()=>{});
30
45
  }
31
46
  async connect() {
32
47
  debug('connecting to %s', this.key);
33
48
  if (this.#disposed) throw new Error(`DeviceConnection ${this.key} was disposed before connect started`);
34
- const conn = await this.#transport.connect(this.#options);
49
+ try {
50
+ this.#connectPromise = this.#transport.connect(this.#options);
51
+ this.#conn = await this.#connectPromise;
52
+ } catch (error) {
53
+ this.#rejectRegistration(error);
54
+ throw error;
55
+ }
35
56
  if (this.#disposed) {
36
- await conn[Symbol.asyncDispose]();
37
- throw new Error(`DeviceConnection ${this.key} was disposed before connect completed`);
57
+ const error = new Error(`DeviceConnection ${this.key} was disposed before connect completed`);
58
+ this.#rejectRegistration(error);
59
+ throw error;
38
60
  }
39
- this.#conn = conn;
40
61
  this.#writer = this.#conn.writable.getWriter();
41
62
  this.#readLoopPromise = this.#readLoop();
42
63
  debug('connected to %s', this.key);
43
64
  }
65
+ waitUntilRegistered() {
66
+ return this.#registered;
67
+ }
44
68
  addSubscriber(subscriber) {
69
+ if (this.#disposed) throw new Error(`Device connection ${this.key} is no longer active`);
45
70
  this.#subscribers.set(subscriber.id, subscriber);
46
71
  debug('subscriber %d added to %s (total: %d)', subscriber.id, this.key, this.#subscribers.size);
47
72
  }
@@ -59,37 +84,61 @@ class DeviceConnection {
59
84
  return true === this.#transport.persistent;
60
85
  }
61
86
  async send(message) {
87
+ if (this.#disposed) throw this.#terminalCause ?? new Error(`DeviceConnection ${this.key} is no longer active`);
62
88
  if (!this.#writer) throw new Error(`DeviceConnection ${this.key} is not connected`);
63
89
  try {
64
90
  await this.#writer.write(message);
65
91
  } catch (err) {
66
92
  debug('send to %s failed: %O', this.key, err);
67
- throw err;
93
+ this.#terminate(err, false);
94
+ throw this.#terminalCause ?? err;
68
95
  }
69
96
  }
70
- async dispose() {
71
- if (this.#disposed) return;
97
+ dispose() {
72
98
  this.#disposed = true;
99
+ this.#rejectRegistration(new Error(`DeviceConnection ${this.key} was disposed before Register`));
100
+ return this.#startDisposal(true);
101
+ }
102
+ async #disposeConnection(awaitReadLoop) {
73
103
  debug('disposing device connection %s', this.key);
104
+ let disposeFailed = false;
105
+ let disposeCause;
106
+ try {
107
+ if (!this.#conn && this.#connectPromise) this.#conn = await this.#connectPromise;
108
+ } catch {}
74
109
  try {
75
110
  this.#writer?.releaseLock();
76
111
  } catch {}
112
+ this.#writer = null;
77
113
  try {
78
114
  await this.#conn?.[Symbol.asyncDispose]();
79
115
  } catch (err) {
80
116
  debug('error disposing connection %s: %O', this.key, err);
117
+ disposeFailed = true;
118
+ disposeCause = err;
81
119
  }
82
- await this.#readLoopPromise;
120
+ if (awaitReadLoop && !disposeFailed) await this.#readLoopPromise;
83
121
  this.#subscribers.clear();
122
+ if (disposeFailed) throw disposeCause;
123
+ }
124
+ #startDisposal(awaitReadLoop) {
125
+ if (!this.#disposePromise) {
126
+ this.#disposePromise = this.#disposeConnection(awaitReadLoop);
127
+ this.#disposePromise.catch((err)=>{
128
+ debug('device connection %s disposal failed: %O', this.key, err);
129
+ });
130
+ }
131
+ return this.#disposePromise;
84
132
  }
85
133
  async #readLoop() {
86
134
  if (!this.#conn) return;
135
+ let terminalCause;
87
136
  try {
88
137
  for await (const message of this.#conn.readable){
89
138
  if (null === this.appInfo) {
90
139
  const response = message;
91
140
  if (isInitializeResponse(response)) {
92
- this.appInfo = response.data.info;
141
+ this.#resolveRegistration(response.data.info);
93
142
  debug('captured appInfo for %s: %O', this.key, this.appInfo);
94
143
  continue;
95
144
  }
@@ -97,20 +146,40 @@ class DeviceConnection {
97
146
  this.#broadcast(message);
98
147
  }
99
148
  } catch (err) {
149
+ terminalCause = err;
100
150
  if (!this.#disposed) debug('read loop error on %s: %O', this.key, err);
101
151
  }
102
152
  if (!this.#disposed) {
103
153
  debug('device connection %s closed by remote', this.key);
104
- this.#disposed = true;
105
- this.#closeAllSubscribers();
154
+ this.#terminate(terminalCause ?? new Error(null === this.appInfo ? `Device connection ${this.key} closed before Register` : `Device connection ${this.key} closed by remote`), true);
106
155
  }
107
156
  }
157
+ #terminate(cause, readLoopEnded) {
158
+ if (this.#disposed) return;
159
+ this.#disposed = true;
160
+ this.#terminalCause = cause;
161
+ this.#rejectRegistration(cause);
162
+ this.#startDisposal(!readLoopEnded);
163
+ this.#closeAllSubscribers();
164
+ }
165
+ #resolveRegistration(appInfo) {
166
+ if (this.#registrationSettled) return;
167
+ this.#registrationSettled = true;
168
+ this.appInfo = appInfo;
169
+ this.#resolveRegistered(appInfo);
170
+ }
171
+ #rejectRegistration(reason) {
172
+ if (this.#registrationSettled) return;
173
+ this.#registrationSettled = true;
174
+ this.#rejectRegistered(reason);
175
+ }
108
176
  #closeAllSubscribers() {
109
177
  for (const [, subscriber] of this.#subscribers)try {
110
178
  subscriber.close();
111
179
  } catch (err) {
112
180
  debug('failed to close subscriber %d: %O', subscriber.id, err);
113
181
  }
182
+ this.#subscribers.clear();
114
183
  }
115
184
  #broadcast(message) {
116
185
  for (const [, subscriber] of this.#subscribers)try {
@@ -120,7 +189,7 @@ class DeviceConnection {
120
189
  }
121
190
  }
122
191
  }
123
- const tarball_cache_debug = node_createDebug('devtool-mcp-server:daemon:tarball-cache');
192
+ const tarball_cache_debug = createDebug('devtool-mcp-server:daemon:tarball-cache');
124
193
  const TAR_FILTER_PREFIX = '';
125
194
  class TarballCache {
126
195
  #files = new Map();
@@ -222,7 +291,7 @@ class TarballCache {
222
291
  return buf;
223
292
  }
224
293
  }
225
- const static_server_debug = node_createDebug('devtool-mcp-server:daemon:static-server');
294
+ const static_server_debug = createDebug('devtool-mcp-server:daemon:static-server');
226
295
  const DEVTOOL_FRONTEND_TARBALL_URL = 'https://github.com/lynx-family/lynx-devtool/releases/download/devtools-frontend-lynx-7/devtool.frontend.lynx_1.0.1779085629.tar.gz';
227
296
  const DEVTOOL_FRONTEND_PATH_PREFIX = '/devtool-frontend/';
228
297
  const MIME_TYPES = {
@@ -325,16 +394,11 @@ class StaticServer {
325
394
  }
326
395
  }
327
396
  }
328
- var package_namespaceObject = {
329
- rE: "0.9.5"
330
- };
331
- const CONNECTOR_VERSION = package_namespaceObject.rE;
332
- const server_debug = node_createDebug('devtool-mcp-server:daemon:server');
397
+ const server_debug = createDebug('devtool-mcp-server:daemon:server');
333
398
  const IDLE_TIMEOUT_MS = 300000;
334
399
  const DEVICE_CONN_GRACE_MS = 10000;
335
400
  const DEVICE_DISCOVERY_TIMEOUT_MS = 2500;
336
401
  const DEVICE_CONN_SETUP_TIMEOUT_MS = 5000;
337
- const DEVICE_CONN_DISPOSE_TIMEOUT_MS = 1000;
338
402
  class DevtoolDaemon {
339
403
  #httpServer;
340
404
  #wss = null;
@@ -343,30 +407,50 @@ class DevtoolDaemon {
343
407
  #pendingDeviceConnections = new Map();
344
408
  #deviceConnectionCleanupTimers = new Map();
345
409
  #wsClients = new Map();
410
+ #commandControllers = new Set();
346
411
  #nextClientId = 0;
412
+ #activeCommandRequests = 0;
347
413
  #idleTimer = null;
414
+ #idleTimeoutMs;
348
415
  #closed = false;
416
+ #closePromise = null;
417
+ #shutdownAccepted = false;
349
418
  #onIdle;
350
419
  #onShutdown;
351
420
  #staticServer = new StaticServer();
421
+ #actionCore = new ActionCore();
422
+ #commandConnector = null;
423
+ #instanceId = randomUUID();
424
+ #startedAt = Date.now();
352
425
  constructor(transports, options){
353
426
  this.#transports = transports;
354
427
  this.#onIdle = options?.onIdle;
355
428
  this.#onShutdown = options?.onShutdown;
429
+ this.#idleTimeoutMs = options?.idleTimeoutMs ?? IDLE_TIMEOUT_MS;
356
430
  this.#httpServer = node_http.createServer((req, res)=>{
431
+ const isCommandRequest = this.#isCommandRequest(req.url);
432
+ const isShutdownRequest = this.#isShutdownRequest(req.url);
433
+ if ((isCommandRequest || isShutdownRequest) && !this.#isTrustedLocalRequest(req)) return void this.#sendJson(res, 403, {
434
+ ok: false,
435
+ error: 'Daemon control requests require a same-origin loopback Host and Origin.'
436
+ });
437
+ if (isCommandRequest && 'POST' === req.method && !this.#hasJsonContentType(req)) return void this.#sendJson(res, 415, {
438
+ ok: false,
439
+ error: 'POST /command requests require Content-Type: application/json.'
440
+ });
357
441
  if ('GET' === req.method && this.#isVersionRequest(req.url)) return void this.#sendJson(res, 200, {
358
- version: CONNECTOR_VERSION
442
+ product: DAEMON_PRODUCT,
443
+ version: CONNECTOR_VERSION,
444
+ lifecycleProtocol: 1,
445
+ commandProtocol: 1,
446
+ instanceId: this.#instanceId,
447
+ startedAt: this.#startedAt
359
448
  });
360
449
  if (this.#staticServer.tryHandle(req, res)) return;
361
- if ('POST' === req.method && this.#isShutdownRequest(req.url)) return void this.#sendJson(res, 202, {
362
- ok: true
363
- }, ()=>{
364
- this.close().catch((err)=>{
365
- server_debug('failed to close daemon after shutdown request: %O', err);
366
- }).finally(()=>{
367
- this.#onShutdown?.();
368
- });
369
- });
450
+ if ('POST' === req.method && isCommandRequest && this.#acceptsEventStream(req)) return void this.#trackCommandRequest(()=>this.#handleCommandStream(req, res));
451
+ if ('POST' === req.method && isCommandRequest) return void this.#trackCommandRequest(()=>this.#handleCommandRequest(req, res));
452
+ if ('GET' === req.method && isCommandRequest) return void this.#trackCommandRequest(()=>this.#handleCommandStream(req, res));
453
+ if ('POST' === req.method && isShutdownRequest) return void this.#handleShutdownRequest(req, res);
370
454
  res.writeHead(404);
371
455
  res.end();
372
456
  });
@@ -377,8 +461,9 @@ class DevtoolDaemon {
377
461
  });
378
462
  this.#wss = wss;
379
463
  this.#httpServer.on('upgrade', (request, socket, head)=>{
380
- if (!request.url?.startsWith(DAEMON_WS_PATH)) return void socket.destroy();
464
+ if (this.#closed || !request.url?.startsWith(DAEMON_WS_PATH) || !this.#isTrustedLocalRequest(request)) return void socket.destroy();
381
465
  wss.handleUpgrade(request, socket, head, (ws)=>{
466
+ if (this.#closed) return void ws.terminate();
382
467
  this.#handleConnection(ws);
383
468
  });
384
469
  });
@@ -388,22 +473,37 @@ class DevtoolDaemon {
388
473
  this.#httpServer.removeListener('error', reject);
389
474
  this.#resetIdleTimer();
390
475
  const address = this.#httpServer.address();
476
+ this.#commandConnector = new Connector([
477
+ new DaemonTransport(address.port)
478
+ ]);
391
479
  server_debug('daemon listening on ws://127.0.0.1:%d%s', address.port, DAEMON_WS_PATH);
392
480
  resolve(address.port);
393
481
  });
394
482
  });
395
483
  }
396
- async close() {
397
- if (this.#closed) return;
484
+ close() {
485
+ this.#closePromise ??= this.#close();
486
+ return this.#closePromise;
487
+ }
488
+ async #close() {
398
489
  this.#closed = true;
399
490
  this.#clearIdleTimer();
491
+ for (const controller of this.#commandControllers)controller.abort(new Error('Connector daemon is shutting down.'));
492
+ this.#commandControllers.clear();
400
493
  for (const [, client] of this.#wsClients)client.close();
401
494
  this.#wsClients.clear();
402
- for (const [, conn] of this.#deviceConnections)await conn.dispose();
403
- this.#deviceConnections.clear();
495
+ for (const ws of this.#wss?.clients ?? [])ws.terminate();
404
496
  for (const [, timer] of this.#deviceConnectionCleanupTimers)clearTimeout(timer);
405
497
  this.#deviceConnectionCleanupTimers.clear();
406
- for (const transport of this.#transports)await transport.close();
498
+ const shutdownResults = await Promise.allSettled([
499
+ ...Array.from(this.#deviceConnections.values(), (conn)=>conn.dispose()),
500
+ ...this.#pendingDeviceConnections.values(),
501
+ ...this.#transports.map((transport)=>Promise.resolve().then(()=>transport.close()))
502
+ ]);
503
+ for (const result of shutdownResults)if ('rejected' === result.status) server_debug('device connection did not settle cleanly during daemon shutdown: %O', result.reason);
504
+ const lateDisposalResults = await Promise.allSettled(Array.from(this.#deviceConnections.values(), (conn)=>conn.dispose()));
505
+ for (const result of lateDisposalResults)if ('rejected' === result.status) server_debug('failed to dispose late device connection during daemon shutdown: %O', result.reason);
506
+ this.#deviceConnections.clear();
407
507
  this.#wss?.close();
408
508
  return new Promise((resolve)=>{
409
509
  this.#httpServer.close(()=>resolve());
@@ -415,6 +515,306 @@ class DevtoolDaemon {
415
515
  #isShutdownRequest(url) {
416
516
  return new URL(url ?? '/', 'http://127.0.0.1').pathname === DAEMON_SHUTDOWN_PATH;
417
517
  }
518
+ #isCommandRequest(url) {
519
+ return new URL(url ?? '/', 'http://127.0.0.1').pathname.startsWith(DAEMON_COMMAND_PATH_PREFIX);
520
+ }
521
+ #isTrustedLocalRequest(req) {
522
+ const host = req.headers.host;
523
+ if (!host) return false;
524
+ let requestOrigin;
525
+ try {
526
+ requestOrigin = new URL(`http://${host}`);
527
+ } catch {
528
+ return false;
529
+ }
530
+ if ('127.0.0.1' !== requestOrigin.hostname && 'localhost' !== requestOrigin.hostname) return false;
531
+ const origin = req.headers.origin;
532
+ if (!origin) return true;
533
+ try {
534
+ const originUrl = new URL(origin);
535
+ return 'http:' === originUrl.protocol && originUrl.host.toLowerCase() === requestOrigin.host.toLowerCase();
536
+ } catch {
537
+ return false;
538
+ }
539
+ }
540
+ #hasJsonContentType(req) {
541
+ return req.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() === 'application/json';
542
+ }
543
+ #acceptsEventStream(req) {
544
+ const accept = req.headers.accept;
545
+ const values = Array.isArray(accept) ? accept : [
546
+ accept ?? ''
547
+ ];
548
+ return values.some((value)=>value.split(',').some((mediaType)=>mediaType.trim().toLowerCase().startsWith('text/event-stream')));
549
+ }
550
+ async #handleShutdownRequest(req, res) {
551
+ let parsed;
552
+ try {
553
+ const body = await this.#readBody(req);
554
+ parsed = '' === body.trim() ? {} : JSON.parse(body);
555
+ } catch (error) {
556
+ this.#sendJson(res, 400, {
557
+ ok: false,
558
+ error: `Invalid shutdown request: ${error instanceof Error ? error.message : String(error)}`
559
+ });
560
+ return;
561
+ }
562
+ if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) return void this.#sendJson(res, 400, {
563
+ ok: false,
564
+ error: 'Shutdown request body must be a JSON object.'
565
+ });
566
+ const { expectedInstanceId } = parsed;
567
+ if ('string' != typeof expectedInstanceId || '' === expectedInstanceId) return void this.#sendJson(res, 428, {
568
+ ok: false,
569
+ error: 'Shutdown requires the expected daemon instance ID.'
570
+ });
571
+ if (expectedInstanceId !== this.#instanceId) return void this.#sendJson(res, 409, {
572
+ ok: false,
573
+ error: 'Daemon instance changed before shutdown.',
574
+ instanceId: this.#instanceId
575
+ });
576
+ if (this.#shutdownAccepted) return void this.#sendJson(res, 202, {
577
+ ok: true,
578
+ alreadyStopping: true
579
+ });
580
+ this.#shutdownAccepted = true;
581
+ this.#sendJson(res, 202, {
582
+ ok: true
583
+ }, ()=>{
584
+ this.close().catch((err)=>{
585
+ server_debug('failed to close daemon after shutdown request: %O', err);
586
+ }).finally(()=>{
587
+ this.#onShutdown?.();
588
+ });
589
+ });
590
+ }
591
+ async #handleCommandRequest(req, res) {
592
+ const pathname = new URL(req.url ?? '/', 'http://127.0.0.1').pathname;
593
+ let action;
594
+ try {
595
+ action = decodeURIComponent(pathname.slice(DAEMON_COMMAND_PATH_PREFIX.length));
596
+ } catch {
597
+ this.#sendJson(res, 400, {
598
+ ok: false,
599
+ action: '',
600
+ error: {
601
+ message: 'Command action path contains invalid percent encoding.',
602
+ reason: 'bad-path',
603
+ recoverable: false,
604
+ nextActions: []
605
+ }
606
+ });
607
+ return;
608
+ }
609
+ const controller = new AbortController();
610
+ this.#commandControllers.add(controller);
611
+ const onDisconnect = ()=>controller.abort(new Error('HTTP command client disconnected.'));
612
+ req.once('aborted', onDisconnect);
613
+ res.once('close', onDisconnect);
614
+ try {
615
+ let params = {};
616
+ try {
617
+ const body = await this.#readBody(req, controller.signal);
618
+ if ('' !== body.trim()) {
619
+ const parsed = JSON.parse(body);
620
+ if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) return void this.#sendJson(res, 200, {
621
+ ok: false,
622
+ action,
623
+ error: {
624
+ message: 'Request body must be a JSON object.',
625
+ reason: 'bad-params',
626
+ recoverable: false,
627
+ nextActions: []
628
+ }
629
+ });
630
+ params = parsed;
631
+ }
632
+ } catch (error) {
633
+ if (controller.signal.aborted) return;
634
+ this.#sendJson(res, 200, {
635
+ ok: false,
636
+ action,
637
+ error: {
638
+ message: `Invalid JSON body: ${error instanceof Error ? error.message : String(error)}`,
639
+ reason: 'bad-params',
640
+ recoverable: false,
641
+ nextActions: []
642
+ }
643
+ });
644
+ return;
645
+ }
646
+ const result = await this.#actionCore.execute(action, params, {
647
+ connector: this.#requireCommandConnector()
648
+ }, controller.signal);
649
+ if (!controller.signal.aborted && !res.destroyed) this.#sendJson(res, 200, result);
650
+ } finally{
651
+ req.off('aborted', onDisconnect);
652
+ res.off('close', onDisconnect);
653
+ this.#commandControllers.delete(controller);
654
+ }
655
+ }
656
+ async #handleCommandStream(req, res) {
657
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
658
+ let action;
659
+ try {
660
+ action = decodeURIComponent(url.pathname.slice(DAEMON_COMMAND_PATH_PREFIX.length));
661
+ } catch {
662
+ this.#sendJson(res, 400, {
663
+ ok: false,
664
+ action: '',
665
+ error: {
666
+ message: 'Command action path contains invalid percent encoding.',
667
+ reason: 'bad-path',
668
+ recoverable: false,
669
+ nextActions: []
670
+ }
671
+ });
672
+ return;
673
+ }
674
+ if (!this.#actionCore.hasStream(action)) return void this.#sendJson(res, 404, {
675
+ ok: false,
676
+ action,
677
+ error: {
678
+ message: `Unknown stream action: ${action}`,
679
+ reason: 'unknown-action',
680
+ recoverable: false,
681
+ nextActions: this.#actionCore.streamActions().map((name)=>`GET /command/${name}`)
682
+ }
683
+ });
684
+ const controller = new AbortController();
685
+ this.#commandControllers.add(controller);
686
+ const onDisconnect = ()=>controller.abort(new Error('SSE command client disconnected.'));
687
+ req.once('aborted', onDisconnect);
688
+ res.once('close', onDisconnect);
689
+ try {
690
+ let params;
691
+ try {
692
+ params = 'POST' === req.method ? await this.#readCommandStreamBody(req, controller.signal) : decodeCommandQuery(url.searchParams);
693
+ } catch (error) {
694
+ if (controller.signal.aborted) return;
695
+ res.writeHead(200, {
696
+ 'content-type': 'text/event-stream; charset=utf-8',
697
+ 'cache-control': 'no-store',
698
+ connection: 'keep-alive'
699
+ });
700
+ res.end(`data: ${JSON.stringify({
701
+ ok: false,
702
+ action,
703
+ error: {
704
+ message: `Invalid JSON body: ${error instanceof Error ? error.message : String(error)}`,
705
+ reason: 'bad-params',
706
+ recoverable: false,
707
+ nextActions: []
708
+ }
709
+ })}\n\n`);
710
+ return;
711
+ }
712
+ controller.signal.throwIfAborted();
713
+ res.writeHead(200, {
714
+ 'content-type': 'text/event-stream; charset=utf-8',
715
+ 'cache-control': 'no-store',
716
+ connection: 'keep-alive',
717
+ 'x-accel-buffering': 'no'
718
+ });
719
+ for await (const event of this.#actionCore.stream(action, params, {
720
+ connector: this.#requireCommandConnector()
721
+ }, controller.signal)){
722
+ if (controller.signal.aborted) break;
723
+ if (!res.write(`data: ${JSON.stringify(event)}\n\n`)) {
724
+ const drained = await this.#waitForDrain(res, controller.signal);
725
+ if (!drained) break;
726
+ }
727
+ }
728
+ } catch (error) {
729
+ if (!controller.signal.aborted) server_debug('command stream %s failed: %O', action, error);
730
+ } finally{
731
+ req.off('aborted', onDisconnect);
732
+ res.off('close', onDisconnect);
733
+ this.#commandControllers.delete(controller);
734
+ if (!res.destroyed && !res.writableEnded) res.end();
735
+ }
736
+ }
737
+ #waitForDrain(res, signal) {
738
+ if (signal.aborted || res.destroyed) return Promise.resolve(false);
739
+ return new Promise((resolve)=>{
740
+ let settled = false;
741
+ const finish = (drained)=>{
742
+ if (settled) return;
743
+ settled = true;
744
+ res.off('drain', onDrain);
745
+ res.off('close', onClose);
746
+ res.off('error', onClose);
747
+ signal.removeEventListener('abort', onAbort);
748
+ resolve(drained);
749
+ };
750
+ const onDrain = ()=>finish(true);
751
+ const onAbort = ()=>finish(false);
752
+ const onClose = ()=>finish(false);
753
+ res.once('drain', onDrain);
754
+ res.once('close', onClose);
755
+ res.once('error', onClose);
756
+ signal.addEventListener('abort', onAbort, {
757
+ once: true
758
+ });
759
+ if (signal.aborted || res.destroyed) finish(false);
760
+ });
761
+ }
762
+ #requireCommandConnector() {
763
+ if (!this.#commandConnector) throw new Error('Connector daemon has not started its command transport.');
764
+ return this.#commandConnector;
765
+ }
766
+ #readBody(req, signal) {
767
+ return new Promise((resolve, reject)=>{
768
+ const chunks = [];
769
+ let size = 0;
770
+ let settled = false;
771
+ const maxSize = 8388608;
772
+ const cleanup = ()=>{
773
+ req.off('data', onData);
774
+ req.off('end', onEnd);
775
+ req.off('error', onError);
776
+ req.off('aborted', onAborted);
777
+ signal?.removeEventListener('abort', onSignalAbort);
778
+ };
779
+ const finish = (callback)=>{
780
+ if (settled) return;
781
+ settled = true;
782
+ cleanup();
783
+ callback();
784
+ };
785
+ const onData = (chunk)=>{
786
+ size += chunk.length;
787
+ if (size > maxSize) {
788
+ finish(()=>reject(new Error('Request body exceeds 8 MiB.')));
789
+ req.destroy();
790
+ return;
791
+ }
792
+ chunks.push(chunk);
793
+ };
794
+ const onEnd = ()=>finish(()=>resolve(Buffer.concat(chunks).toString('utf8')));
795
+ const onError = (error)=>finish(()=>reject(error));
796
+ const onAborted = ()=>finish(()=>reject(new Error('Request body was aborted.')));
797
+ const onSignalAbort = ()=>{
798
+ finish(()=>reject(signal?.reason ?? new Error('Request was aborted.')));
799
+ if (!req.destroyed) req.destroy();
800
+ };
801
+ req.on('data', onData);
802
+ req.once('end', onEnd);
803
+ req.once('error', onError);
804
+ req.once('aborted', onAborted);
805
+ signal?.addEventListener('abort', onSignalAbort, {
806
+ once: true
807
+ });
808
+ if (signal?.aborted) onSignalAbort();
809
+ });
810
+ }
811
+ async #readCommandStreamBody(req, signal) {
812
+ const body = await this.#readBody(req, signal);
813
+ if ('' === body.trim()) return {};
814
+ const parsed = JSON.parse(body);
815
+ if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('Request body must be a JSON object.');
816
+ return parsed;
817
+ }
418
818
  #sendJson(res, statusCode, data, callback) {
419
819
  const body = JSON.stringify(data);
420
820
  res.writeHead(statusCode, {
@@ -424,17 +824,35 @@ class DevtoolDaemon {
424
824
  });
425
825
  res.end(body, callback);
426
826
  }
827
+ #trackCommandRequest(handler) {
828
+ this.#activeCommandRequests += 1;
829
+ this.#clearIdleTimer();
830
+ handler().catch((error)=>{
831
+ server_debug('command request failed: %O', error);
832
+ }).finally(()=>{
833
+ this.#activeCommandRequests -= 1;
834
+ this.#resetIdleTimer();
835
+ });
836
+ }
427
837
  #handleConnection(ws) {
838
+ if (this.#closed) return void ws.terminate();
428
839
  const clientId = ++this.#nextClientId;
429
840
  server_debug('new ws client %d', clientId);
430
841
  this.#clearIdleTimer();
842
+ let closing = false;
431
843
  const session = {
432
844
  id: clientId,
845
+ get isClosing () {
846
+ return closing;
847
+ },
433
848
  subscriptions: new Set(),
434
849
  send (message) {
435
- if (1 === ws.readyState) ws.send(JSON.stringify(message));
850
+ if (!closing && 1 === ws.readyState) ws.send(JSON.stringify(message));
436
851
  },
437
- close () {
852
+ close: ()=>{
853
+ if (closing) return;
854
+ closing = true;
855
+ this.#wsClients.delete(clientId);
438
856
  ws.close(1001, 'device disconnected');
439
857
  }
440
858
  };
@@ -452,13 +870,11 @@ class DevtoolDaemon {
452
870
  });
453
871
  ws.on('close', ()=>{
454
872
  server_debug('ws client %d disconnected', clientId);
873
+ closing = true;
455
874
  this.#wsClients.delete(clientId);
456
- for (const key of session.subscriptions){
457
- const deviceConn = this.#deviceConnections.get(key);
458
- if (deviceConn) {
459
- deviceConn.removeSubscriber(clientId);
460
- if (0 === deviceConn.subscriberCount) this.#scheduleDeviceConnectionCleanup(key);
461
- }
875
+ for (const deviceConn of session.subscriptions){
876
+ deviceConn.removeSubscriber(clientId);
877
+ if (!this.#closed && 0 === deviceConn.subscriberCount) this.#scheduleDeviceConnectionCleanup(deviceConn);
462
878
  }
463
879
  session.subscriptions.clear();
464
880
  this.#resetIdleTimer();
@@ -468,6 +884,8 @@ class DevtoolDaemon {
468
884
  });
469
885
  }
470
886
  #handleMessage(session, msg) {
887
+ if (session.isClosing) return void server_debug('ignoring message from closing client %d', session.id);
888
+ if (this.#closed) return void session.close();
471
889
  if (isRegisterEvent(msg)) {
472
890
  this.#wsClients.set(session.id, session);
473
891
  server_debug('client %d registered', session.id);
@@ -483,25 +901,22 @@ class DevtoolDaemon {
483
901
  }
484
902
  async #handleCustomizedMessage(session, msg) {
485
903
  const targetPort = msg.to ?? msg.data?.data?.client_id;
486
- if ('number' != typeof targetPort) return void server_debug('cannot determine target port from message: %O', msg);
487
- for (const key of session.subscriptions){
488
- const deviceConn = this.#deviceConnections.get(key);
489
- if (deviceConn && deviceConn.port === targetPort) {
490
- try {
491
- await deviceConn.send({
492
- ...msg,
493
- data: {
494
- ...msg.data,
495
- sender: targetPort
496
- }
497
- });
498
- } catch (err) {
499
- server_debug('failed to forward message to %s: %O', key, err);
500
- }
501
- return;
904
+ if ('number' != typeof targetPort && 'string' != typeof targetPort) return void server_debug('cannot determine target from message: %O', msg);
905
+ for (const deviceConn of session.subscriptions)if (deviceConn.port === targetPort) {
906
+ try {
907
+ await deviceConn.send({
908
+ ...msg,
909
+ data: {
910
+ ...msg.data,
911
+ sender: targetPort
912
+ }
913
+ });
914
+ } catch (err) {
915
+ server_debug('failed to forward message to %s: %O', deviceConn.key, err);
502
916
  }
917
+ return;
503
918
  }
504
- server_debug('no matching device connection for client %d, port %d', session.id, targetPort);
919
+ server_debug('no matching device connection for client %d, target %o', session.id, targetPort);
505
920
  }
506
921
  async #handleControlRequest(session, req) {
507
922
  const { id, method, params } = req.data;
@@ -542,10 +957,18 @@ class DevtoolDaemon {
542
957
  {
543
958
  const s = params ?? {};
544
959
  if (!s.deviceId || void 0 === s.port) throw new Error('deviceId and port are required');
545
- const transport = await this.#findTransportWithDeviceId(s.deviceId);
546
- const conn = await this.#getOrCreateDeviceConnection(transport, s.deviceId, s.port);
960
+ const key = `${s.deviceId}:${s.port}`;
961
+ let conn = this.#deviceConnections.get(key);
962
+ if (!conn || conn.isDisposed) {
963
+ const transport = await this.#findTransportWithDeviceId(s.deviceId);
964
+ conn = await this.#getOrCreateDeviceConnection(transport, s.deviceId, s.port);
965
+ } else this.#clearDeviceConnectionCleanup(key);
966
+ if (session.isClosing || this.#wsClients.get(session.id) !== session) {
967
+ if (0 === conn.subscriberCount) this.#scheduleDeviceConnectionCleanup(conn);
968
+ throw new Error(`Daemon client ${session.id} disconnected before subscription`);
969
+ }
547
970
  conn.addSubscriber(session);
548
- session.subscriptions.add(conn.key);
971
+ session.subscriptions.add(conn);
549
972
  result = null;
550
973
  break;
551
974
  }
@@ -587,13 +1010,18 @@ class DevtoolDaemon {
587
1010
  }
588
1011
  async #discoverClients() {
589
1012
  const entries = [];
1013
+ const discoveryFailures = [];
1014
+ let lowerAuthorityFulfilled = false;
590
1015
  const clientListTransports = this.#transports.filter((t)=>'function' == typeof t.listClients);
591
1016
  const clientListResults = await Promise.allSettled(clientListTransports.map((t)=>t.listClients()));
592
- for (const r of clientListResults)if ('fulfilled' === r.status) for (const { id, info } of r.value)entries.push({
593
- id,
594
- info,
595
- type: 'runtime'
596
- });
1017
+ for (const r of clientListResults)if ('fulfilled' === r.status) {
1018
+ lowerAuthorityFulfilled = true;
1019
+ for (const { id, info } of r.value)entries.push({
1020
+ id,
1021
+ info,
1022
+ type: 'runtime'
1023
+ });
1024
+ } else discoveryFailures.push(r.reason);
597
1025
  for (const [, conn] of this.#deviceConnections)if (conn.appInfo && !conn.isDisposed) {
598
1026
  const id = ClientId.serialize(conn.deviceId, conn.port);
599
1027
  if (entries.some((e)=>e.id === id)) continue;
@@ -604,22 +1032,20 @@ class DevtoolDaemon {
604
1032
  });
605
1033
  }
606
1034
  const allDevices = [];
607
- const transportResults = await Promise.allSettled(this.#transports.filter((transport)=>'function' != typeof transport.listClients).map(async (transport)=>({
1035
+ const transportResults = await Promise.allSettled(this.#transports.map(async (transport)=>({
608
1036
  transport,
609
1037
  devices: await transport.listDevices()
610
1038
  })));
611
- for (const r of transportResults)if ('fulfilled' === r.status) allDevices.push(r.value);
1039
+ for (const r of transportResults)if ('fulfilled' === r.status) {
1040
+ lowerAuthorityFulfilled = true;
1041
+ allDevices.push(r.value);
1042
+ } else discoveryFailures.push(r.reason);
612
1043
  const MIN_PORT = 8901;
613
1044
  const PORTS = Array.from({
614
1045
  length: 10
615
1046
  }, (_, i)=>MIN_PORT + i);
616
- const existingKeys = new Set(this.#deviceConnections.keys());
617
- const probeResults = await Promise.allSettled(allDevices.flatMap(({ transport, devices })=>devices.flatMap((device)=>PORTS.filter((port)=>!existingKeys.has(`${device.id}:${port}`)).map(async (port)=>{
618
- const conn = await this.#getOrCreateDeviceConnection(transport, device.id, port);
619
- const deadline = Date.now() + DEVICE_DISCOVERY_TIMEOUT_MS;
620
- while(!conn.appInfo && !conn.isDisposed && Date.now() < deadline)await new Promise((resolve)=>setTimeout(resolve, 100));
621
- return conn;
622
- }))));
1047
+ const existingKeys = new Set(Array.from(this.#deviceConnections.entries()).filter(([, connection])=>!connection.isDisposed).map(([key])=>key));
1048
+ const probeResults = await Promise.allSettled(allDevices.flatMap(({ transport, devices })=>devices.flatMap((device)=>PORTS.filter((port)=>!existingKeys.has(`${device.id}:${port}`)).map((port)=>this.#getOrCreateDeviceConnection(transport, device.id, port)))));
623
1049
  for (const r of probeResults)if ('fulfilled' === r.status) {
624
1050
  const conn = r.value;
625
1051
  if (conn.appInfo && !conn.isDisposed) {
@@ -631,22 +1057,29 @@ class DevtoolDaemon {
631
1057
  });
632
1058
  }
633
1059
  }
1060
+ if (0 === entries.length && !lowerAuthorityFulfilled && discoveryFailures.length > 0) throwClientDiscoveryFailures(discoveryFailures);
634
1061
  return entries;
635
1062
  }
636
1063
  async #getOrCreateDeviceConnection(transport, deviceId, port) {
637
1064
  const key = `${deviceId}:${port}`;
1065
+ if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
1066
+ this.#clearDeviceConnectionCleanup(key);
638
1067
  const existing = this.#deviceConnections.get(key);
639
- if (existing && !existing.isDisposed) {
640
- this.#clearDeviceConnectionCleanup(key);
641
- return existing;
642
- }
1068
+ if (existing && !existing.isDisposed) return existing;
643
1069
  const pending = this.#pendingDeviceConnections.get(key);
644
1070
  if (pending) return await pending;
645
1071
  const connectionPromise = (async ()=>{
1072
+ if (existing) {
1073
+ await existing.dispose();
1074
+ if (this.#deviceConnections.get(key) === existing) this.#deviceConnections.delete(key);
1075
+ }
1076
+ if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
646
1077
  const setupAbortController = new AbortController();
647
1078
  const setupTimeout = setTimeout(()=>{
648
1079
  setupAbortController.abort(createDeviceConnectionSetupTimeoutError(key));
649
1080
  }, DEVICE_CONN_SETUP_TIMEOUT_MS);
1081
+ const registerAbortController = new AbortController();
1082
+ let registerTimeout;
650
1083
  const conn = new DeviceConnection(transport, {
651
1084
  deviceId,
652
1085
  port,
@@ -655,49 +1088,41 @@ class DevtoolDaemon {
655
1088
  const connectPromise = conn.connect();
656
1089
  try {
657
1090
  await withAbortSignal(connectPromise, setupAbortController.signal);
1091
+ if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
658
1092
  await withAbortSignal(conn.send({
659
1093
  event: 'Initialize',
660
1094
  data: port
661
1095
  }), setupAbortController.signal);
1096
+ clearTimeout(setupTimeout);
1097
+ registerTimeout = setTimeout(()=>{
1098
+ registerAbortController.abort(createDeviceRegisterTimeoutError(key));
1099
+ }, DEVICE_DISCOVERY_TIMEOUT_MS);
1100
+ await withAbortSignal(conn.waitUntilRegistered(), registerAbortController.signal);
1101
+ if (conn.isDisposed) throw new Error(`Device connection ${key} closed immediately after Register`);
1102
+ if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
662
1103
  this.#deviceConnections.set(key, conn);
663
1104
  return conn;
664
1105
  } catch (err) {
665
1106
  server_debug('failed to connect to %s: %O', key, err);
666
- this.#deviceConnections.delete(key);
667
- await this.#disposeDeviceConnectionBestEffort(key, conn);
1107
+ this.#deviceConnections.set(key, conn);
1108
+ conn.dispose().catch((disposeError)=>{
1109
+ server_debug('failed to dispose device connection %s after setup failure: %O', key, disposeError);
1110
+ });
668
1111
  throw err;
669
1112
  } finally{
670
1113
  clearTimeout(setupTimeout);
671
- this.#pendingDeviceConnections.delete(key);
1114
+ if (registerTimeout) clearTimeout(registerTimeout);
672
1115
  }
673
- })();
1116
+ })().finally(()=>{
1117
+ this.#pendingDeviceConnections.delete(key);
1118
+ });
674
1119
  this.#pendingDeviceConnections.set(key, connectionPromise);
675
1120
  return await connectionPromise;
676
1121
  }
677
- async #disposeDeviceConnectionBestEffort(key, conn) {
678
- const timeoutAbortController = new AbortController();
679
- const disposePromise = conn.dispose().catch((err)=>{
680
- server_debug('failed to dispose device connection %s after setup failure: %O', key, err);
681
- });
682
- const timeoutPromise = promises_setTimeout(DEVICE_CONN_DISPOSE_TIMEOUT_MS, void 0, {
683
- signal: timeoutAbortController.signal
684
- }).then(()=>{
685
- throw new Error(`Timed out disposing failed device connection ${key}`);
686
- });
687
- try {
688
- await Promise.race([
689
- disposePromise,
690
- timeoutPromise
691
- ]);
692
- } catch (err) {
693
- server_debug('best-effort dispose for %s did not complete: %O', key, err);
694
- } finally{
695
- timeoutAbortController.abort();
696
- }
697
- }
698
- #scheduleDeviceConnectionCleanup(key) {
699
- const conn = this.#deviceConnections.get(key);
700
- if (conn?.isPersistent) {
1122
+ #scheduleDeviceConnectionCleanup(conn) {
1123
+ const { key } = conn;
1124
+ if (this.#deviceConnections.get(key) !== conn) return void server_debug('skipping cleanup for stale connection %s', key);
1125
+ if (conn.isPersistent) {
701
1126
  this.#clearDeviceConnectionCleanup(key);
702
1127
  server_debug('skipping cleanup for persistent connection %s', key);
703
1128
  return;
@@ -706,11 +1131,13 @@ class DevtoolDaemon {
706
1131
  this.#clearDeviceConnectionCleanup(key);
707
1132
  const timer = setTimeout(()=>{
708
1133
  this.#deviceConnectionCleanupTimers.delete(key);
709
- const conn = this.#deviceConnections.get(key);
710
- if (conn && 0 === conn.subscriberCount) {
1134
+ if (this.#deviceConnections.get(key) === conn && 0 === conn.subscriberCount) {
711
1135
  server_debug('disposing idle device connection %s', key);
712
- this.#deviceConnections.delete(key);
713
- conn.dispose();
1136
+ conn.dispose().then(()=>{
1137
+ if (this.#deviceConnections.get(key) === conn) this.#deviceConnections.delete(key);
1138
+ }, (err)=>{
1139
+ server_debug('failed to retire idle device connection %s: %O', key, err);
1140
+ });
714
1141
  }
715
1142
  }, DEVICE_CONN_GRACE_MS);
716
1143
  this.#deviceConnectionCleanupTimers.set(key, timer);
@@ -730,14 +1157,14 @@ class DevtoolDaemon {
730
1157
  }
731
1158
  #resetIdleTimer() {
732
1159
  this.#clearIdleTimer();
733
- if (0 === this.#wsClients.size && !this.#closed) {
734
- server_debug('no clients connected, starting idle timer (%dms)', IDLE_TIMEOUT_MS);
1160
+ if (0 === this.#wsClients.size && 0 === this.#activeCommandRequests && !this.#closed) {
1161
+ server_debug('no clients connected, starting idle timer (%dms)', this.#idleTimeoutMs);
735
1162
  this.#idleTimer = setTimeout(()=>{
736
- if (0 === this.#wsClients.size) {
1163
+ if (0 === this.#wsClients.size && 0 === this.#activeCommandRequests) {
737
1164
  server_debug('idle timeout reached, shutting down daemon');
738
1165
  this.#onIdle?.();
739
1166
  }
740
- }, IDLE_TIMEOUT_MS);
1167
+ }, this.#idleTimeoutMs);
741
1168
  }
742
1169
  }
743
1170
  #clearIdleTimer() {
@@ -750,6 +1177,9 @@ class DevtoolDaemon {
750
1177
  function createDeviceConnectionSetupTimeoutError(key) {
751
1178
  return new Error(`Timed out setting up device connection ${key} after ${DEVICE_CONN_SETUP_TIMEOUT_MS}ms`);
752
1179
  }
1180
+ function createDeviceRegisterTimeoutError(key) {
1181
+ return new Error(`Timed out waiting for Register from device connection ${key} after ${DEVICE_DISCOVERY_TIMEOUT_MS}ms`);
1182
+ }
753
1183
  async function withAbortSignal(promise, signal) {
754
1184
  signal.throwIfAborted();
755
1185
  return await new Promise((resolve, reject)=>{