@lynx-js/devtool-connector 0.13.1 → 0.16.2
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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +1 -1
- package/README.md +18 -134
- package/dist/2.js +2019 -0
- package/dist/{346.js → a.js} +102 -143
- package/dist/client-id.d.ts +0 -6
- package/dist/command/client.d.ts +8 -7
- package/dist/command/contract.d.ts +82 -24
- package/dist/command/core.d.ts +11 -10
- package/dist/command/in-process-client.d.ts +16 -0
- package/dist/command/index.d.ts +28 -20
- package/dist/command/index.js +177 -159
- package/dist/command/list-clients.d.ts +6 -0
- package/dist/command/list-sessions.d.ts +5 -0
- package/dist/command/open.d.ts +5 -0
- package/dist/command/query.d.ts +1 -1
- package/dist/command/reactlynx/controller.d.ts +3 -3
- package/dist/command/reactlynx/model.d.ts +7 -7
- package/dist/command/reactlynx/protocol.d.ts +0 -1
- package/dist/command/reactlynx/session.d.ts +3 -3
- package/dist/command/reactlynx/types.d.ts +7 -7
- package/dist/command/ref-actions.d.ts +4 -4
- package/dist/command/result.d.ts +0 -1
- package/dist/command/screenshot-annotation.d.ts +2 -2
- package/dist/command/screenshot.d.ts +2 -2
- package/dist/command/snapshot.d.ts +2 -2
- package/dist/command/source-info.d.ts +20 -0
- package/dist/command/targets.d.ts +8 -10
- package/dist/command/timeout.d.ts +3 -0
- package/dist/command/wait-for-client.d.ts +5 -0
- package/dist/daemon/device-connection.d.ts +4 -3
- package/dist/daemon/entry.js +18 -20
- package/dist/daemon/index.d.ts +7 -2
- package/dist/daemon/index.js +7 -3
- package/dist/daemon/inspector-assets.d.ts +11 -0
- package/dist/daemon/manager.d.ts +12 -4
- package/dist/daemon/protocol.d.ts +20 -16
- package/dist/daemon/server.d.ts +7 -1
- package/dist/daemon/static-server.d.ts +3 -1
- package/dist/f.js +5790 -0
- package/dist/f1.js +737 -0
- package/dist/{962.js → h.js} +841 -3259
- package/dist/{712.js → hb.js} +26 -19
- package/dist/i.js +2505 -0
- package/dist/index.d.ts +13 -18
- package/dist/index.js +3 -2
- package/dist/main.d.ts +2 -0
- package/dist/main.js +3 -0
- package/dist/request-id.d.ts +1 -0
- package/dist/streams/cdp.d.ts +3 -3
- package/dist/streams/customized.d.ts +5 -5
- package/dist/streams/index.d.ts +4 -3
- package/dist/streams/index.js +1 -1
- package/dist/streams/utils.d.ts +3 -3
- package/dist/{872.js → t.js} +364 -301
- package/dist/transport/adb-shell-types.d.ts +14 -0
- package/dist/transport/android-app-icon-helper.d.ts +1 -0
- package/dist/transport/android.d.ts +13 -3
- package/dist/transport/base.d.ts +2 -9
- package/dist/transport/daemon.d.ts +3 -2
- package/dist/transport/desktop.d.ts +1 -1
- package/dist/transport/hdt.d.ts +13 -0
- package/dist/transport/index.d.ts +9 -9
- package/dist/transport/index.js +2 -3
- package/dist/transport/ios.d.ts +2 -2
- package/dist/transport/peertalk.d.ts +4 -3
- package/dist/transport/stream-lifecycle.d.ts +4 -0
- package/dist/transport/transport.d.ts +4 -8
- package/dist/transport/usbmux.d.ts +5 -5
- package/dist/transport/ws-stream.d.ts +3 -10
- package/dist/types.d.ts +27 -54
- package/dist/{63.js → ws-stream.js} +23 -24
- package/package.json +32 -22
- package/dist/390.js +0 -329
- package/dist/556.js +0 -258
- package/dist/61.js +0 -3432
package/dist/{872.js → t.js}
RENAMED
|
@@ -1,17 +1,19 @@
|
|
|
1
|
+
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
2
3
|
import node_http from "node:http";
|
|
3
|
-
import { createDebug } from "obug";
|
|
4
|
-
import { WebSocketServer } from "ws";
|
|
5
4
|
import node_fs from "node:fs";
|
|
6
5
|
import node_path from "node:path";
|
|
7
6
|
import { fileURLToPath } from "node:url";
|
|
8
7
|
import node_zlib from "node:zlib";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
8
|
+
import { Readable } from "node:stream";
|
|
9
|
+
import { pipeline } from "node:stream/promises";
|
|
10
|
+
import "./i.js";
|
|
11
|
+
import { ansi_createDebug, 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 "./2.js";
|
|
12
|
+
import { isInitializeResponse } from "./hb.js";
|
|
13
|
+
import { decodeCommandQuery, ActionCore } from "./f.js";
|
|
14
|
+
import { Connector, throwClientDiscoveryFailures } from "./a.js";
|
|
15
|
+
import { DaemonTransport, HDTTransport, ClientId } from "./f1.js";
|
|
16
|
+
const debug = ansi_createDebug("devtool-mcp-server:daemon:device-connection");
|
|
15
17
|
class DeviceConnection {
|
|
16
18
|
key;
|
|
17
19
|
deviceId;
|
|
@@ -44,7 +46,7 @@ class DeviceConnection {
|
|
|
44
46
|
this.#registered.catch(()=>{});
|
|
45
47
|
}
|
|
46
48
|
async connect() {
|
|
47
|
-
debug(
|
|
49
|
+
debug("connecting to %s", this.key);
|
|
48
50
|
if (this.#disposed) throw new Error(`DeviceConnection ${this.key} was disposed before connect started`);
|
|
49
51
|
try {
|
|
50
52
|
this.#connectPromise = this.#transport.connect(this.#options);
|
|
@@ -60,7 +62,7 @@ class DeviceConnection {
|
|
|
60
62
|
}
|
|
61
63
|
this.#writer = this.#conn.writable.getWriter();
|
|
62
64
|
this.#readLoopPromise = this.#readLoop();
|
|
63
|
-
debug(
|
|
65
|
+
debug("connected to %s", this.key);
|
|
64
66
|
}
|
|
65
67
|
waitUntilRegistered() {
|
|
66
68
|
return this.#registered;
|
|
@@ -68,11 +70,11 @@ class DeviceConnection {
|
|
|
68
70
|
addSubscriber(subscriber) {
|
|
69
71
|
if (this.#disposed) throw new Error(`Device connection ${this.key} is no longer active`);
|
|
70
72
|
this.#subscribers.set(subscriber.id, subscriber);
|
|
71
|
-
debug(
|
|
73
|
+
debug("subscriber %d added to %s (total: %d)", subscriber.id, this.key, this.#subscribers.size);
|
|
72
74
|
}
|
|
73
75
|
removeSubscriber(id) {
|
|
74
76
|
this.#subscribers.delete(id);
|
|
75
|
-
debug(
|
|
77
|
+
debug("subscriber %d removed from %s (total: %d)", id, this.key, this.#subscribers.size);
|
|
76
78
|
}
|
|
77
79
|
get subscriberCount() {
|
|
78
80
|
return this.#subscribers.size;
|
|
@@ -80,6 +82,9 @@ class DeviceConnection {
|
|
|
80
82
|
get isDisposed() {
|
|
81
83
|
return this.#disposed;
|
|
82
84
|
}
|
|
85
|
+
get transport() {
|
|
86
|
+
return this.#transport;
|
|
87
|
+
}
|
|
83
88
|
get isPersistent() {
|
|
84
89
|
return true === this.#transport.persistent;
|
|
85
90
|
}
|
|
@@ -89,7 +94,7 @@ class DeviceConnection {
|
|
|
89
94
|
try {
|
|
90
95
|
await this.#writer.write(message);
|
|
91
96
|
} catch (err) {
|
|
92
|
-
debug(
|
|
97
|
+
debug("send to %s failed: %O", this.key, err);
|
|
93
98
|
this.#terminate(err, false);
|
|
94
99
|
throw this.#terminalCause ?? err;
|
|
95
100
|
}
|
|
@@ -100,7 +105,7 @@ class DeviceConnection {
|
|
|
100
105
|
return this.#startDisposal(true);
|
|
101
106
|
}
|
|
102
107
|
async #disposeConnection(awaitReadLoop) {
|
|
103
|
-
debug(
|
|
108
|
+
debug("disposing device connection %s", this.key);
|
|
104
109
|
let disposeFailed = false;
|
|
105
110
|
let disposeCause;
|
|
106
111
|
try {
|
|
@@ -113,7 +118,7 @@ class DeviceConnection {
|
|
|
113
118
|
try {
|
|
114
119
|
await this.#conn?.[Symbol.asyncDispose]();
|
|
115
120
|
} catch (err) {
|
|
116
|
-
debug(
|
|
121
|
+
debug("error disposing connection %s: %O", this.key, err);
|
|
117
122
|
disposeFailed = true;
|
|
118
123
|
disposeCause = err;
|
|
119
124
|
}
|
|
@@ -125,7 +130,7 @@ class DeviceConnection {
|
|
|
125
130
|
if (!this.#disposePromise) {
|
|
126
131
|
this.#disposePromise = this.#disposeConnection(awaitReadLoop);
|
|
127
132
|
this.#disposePromise.catch((err)=>{
|
|
128
|
-
debug(
|
|
133
|
+
debug("device connection %s disposal failed: %O", this.key, err);
|
|
129
134
|
});
|
|
130
135
|
}
|
|
131
136
|
return this.#disposePromise;
|
|
@@ -139,18 +144,18 @@ class DeviceConnection {
|
|
|
139
144
|
const response = message;
|
|
140
145
|
if (isInitializeResponse(response)) {
|
|
141
146
|
this.#resolveRegistration(response.data.info);
|
|
142
|
-
debug(
|
|
147
|
+
debug("captured appInfo for %s: %O", this.key, this.appInfo);
|
|
143
148
|
continue;
|
|
144
149
|
}
|
|
145
150
|
}
|
|
146
|
-
this.#broadcast(message);
|
|
151
|
+
if (!isClientListMessage(message)) this.#broadcast(message);
|
|
147
152
|
}
|
|
148
153
|
} catch (err) {
|
|
149
154
|
terminalCause = err;
|
|
150
|
-
if (!this.#disposed) debug(
|
|
155
|
+
if (!this.#disposed) debug("read loop error on %s: %O", this.key, err);
|
|
151
156
|
}
|
|
152
157
|
if (!this.#disposed) {
|
|
153
|
-
debug(
|
|
158
|
+
debug("device connection %s closed by remote", this.key);
|
|
154
159
|
this.#terminate(terminalCause ?? new Error(null === this.appInfo ? `Device connection ${this.key} closed before Register` : `Device connection ${this.key} closed by remote`), true);
|
|
155
160
|
}
|
|
156
161
|
}
|
|
@@ -177,7 +182,7 @@ class DeviceConnection {
|
|
|
177
182
|
for (const [, subscriber] of this.#subscribers)try {
|
|
178
183
|
subscriber.close();
|
|
179
184
|
} catch (err) {
|
|
180
|
-
debug(
|
|
185
|
+
debug("failed to close subscriber %d: %O", subscriber.id, err);
|
|
181
186
|
}
|
|
182
187
|
this.#subscribers.clear();
|
|
183
188
|
}
|
|
@@ -185,12 +190,15 @@ class DeviceConnection {
|
|
|
185
190
|
for (const [, subscriber] of this.#subscribers)try {
|
|
186
191
|
subscriber.send(message);
|
|
187
192
|
} catch (err) {
|
|
188
|
-
debug(
|
|
193
|
+
debug("failed to send to subscriber %d: %O", subscriber.id, err);
|
|
189
194
|
}
|
|
190
195
|
}
|
|
191
196
|
}
|
|
192
|
-
|
|
193
|
-
|
|
197
|
+
function isClientListMessage(message) {
|
|
198
|
+
return "object" == typeof message && null !== message && "ClientList" === message.event;
|
|
199
|
+
}
|
|
200
|
+
const tarball_cache_debug = ansi_createDebug("devtool-mcp-server:daemon:tarball-cache");
|
|
201
|
+
const TAR_FILTER_PREFIX = "package/static-resources/devtool/lynx/";
|
|
194
202
|
class TarballCache {
|
|
195
203
|
#files = new Map();
|
|
196
204
|
#pending = new Map();
|
|
@@ -228,28 +236,27 @@ class TarballCache {
|
|
|
228
236
|
try {
|
|
229
237
|
const response = await fetch(url);
|
|
230
238
|
if (!response.ok) throw new Error(`Failed to fetch tarball: ${response.status}`);
|
|
231
|
-
if (!response.body) throw new Error(
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
}
|
|
243
|
-
this.#consumeTar(buf);
|
|
239
|
+
if (!response.body) throw new Error("No response body");
|
|
240
|
+
await pipeline(Readable.fromWeb(response.body), node_zlib.createGunzip(), async (chunks)=>{
|
|
241
|
+
let buf = Buffer.alloc(0);
|
|
242
|
+
for await (const chunk of chunks){
|
|
243
|
+
buf = Buffer.concat([
|
|
244
|
+
buf,
|
|
245
|
+
chunk
|
|
246
|
+
]);
|
|
247
|
+
buf = this.#consumeTar(buf);
|
|
248
|
+
}
|
|
249
|
+
this.#consumeTar(buf);
|
|
250
|
+
});
|
|
244
251
|
} catch (err) {
|
|
245
252
|
this.#error = err instanceof Error ? err : new Error(String(err));
|
|
246
|
-
tarball_cache_debug(
|
|
253
|
+
tarball_cache_debug("tarball stream error: %O", this.#error);
|
|
247
254
|
} finally{
|
|
248
255
|
this.#done = true;
|
|
249
256
|
for (const [, waiters] of this.#pending)for (const { resolve, reject } of waiters)if (this.#error) reject(this.#error);
|
|
250
257
|
else resolve(null);
|
|
251
258
|
this.#pending.clear();
|
|
252
|
-
tarball_cache_debug(
|
|
259
|
+
tarball_cache_debug("tarball cache done: %d files", this.#files.size);
|
|
253
260
|
}
|
|
254
261
|
}
|
|
255
262
|
#consumeTar(buf) {
|
|
@@ -259,10 +266,10 @@ class TarballCache {
|
|
|
259
266
|
buf = buf.subarray(512);
|
|
260
267
|
continue;
|
|
261
268
|
}
|
|
262
|
-
const rawName = header.subarray(0, 100).toString(
|
|
263
|
-
const prefix = header.subarray(345, 500).toString(
|
|
269
|
+
const rawName = header.subarray(0, 100).toString("utf-8").replace(/\0.*$/, "");
|
|
270
|
+
const prefix = header.subarray(345, 500).toString("utf-8").replace(/\0.*$/, "");
|
|
264
271
|
const name = prefix ? `${prefix}/${rawName}` : rawName;
|
|
265
|
-
const sizeStr = header.subarray(124, 136).toString(
|
|
272
|
+
const sizeStr = header.subarray(124, 136).toString("utf-8").replace(/\0.*$/, "").trim();
|
|
266
273
|
const size = parseInt(sizeStr, 8) || 0;
|
|
267
274
|
const typeFlag = header[156];
|
|
268
275
|
const paddedSize = 512 * Math.ceil(size / 512);
|
|
@@ -270,7 +277,7 @@ class TarballCache {
|
|
|
270
277
|
if ((48 === typeFlag || 0 === typeFlag) && name.startsWith(TAR_FILTER_PREFIX)) {
|
|
271
278
|
const fileData = buf.subarray(512, 512 + size);
|
|
272
279
|
const ext = node_path.extname(name).toLowerCase();
|
|
273
|
-
if (
|
|
280
|
+
if (".map" !== ext) {
|
|
274
281
|
const gzipped = node_zlib.gzipSync(fileData, {
|
|
275
282
|
level: node_zlib.constants.Z_BEST_SPEED
|
|
276
283
|
});
|
|
@@ -291,110 +298,127 @@ class TarballCache {
|
|
|
291
298
|
return buf;
|
|
292
299
|
}
|
|
293
300
|
}
|
|
294
|
-
const
|
|
295
|
-
const
|
|
296
|
-
const
|
|
301
|
+
const inspector_assets_debug = ansi_createDebug("devtool-mcp-server:daemon:inspector-assets");
|
|
302
|
+
const HDT_RES_TARBALL_URL = "https://github.com/lynx-family/lynx-devtool/releases/download/devtools-frontend-lynx-7/devtool.frontend.lynx_1.0.1779085629.tar.gz";
|
|
303
|
+
const HDT_RES_PATH_PREFIX = "/devtool-frontend/";
|
|
297
304
|
const MIME_TYPES = {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
305
|
+
".html": "text/html; charset=utf-8",
|
|
306
|
+
".js": "application/javascript; charset=utf-8",
|
|
307
|
+
".css": "text/css; charset=utf-8",
|
|
308
|
+
".json": "application/json; charset=utf-8",
|
|
309
|
+
".png": "image/png",
|
|
310
|
+
".jpg": "image/jpeg",
|
|
311
|
+
".svg": "image/svg+xml",
|
|
312
|
+
".woff2": "font/woff2",
|
|
313
|
+
".woff": "font/woff",
|
|
314
|
+
".ttf": "font/ttf"
|
|
308
315
|
};
|
|
316
|
+
class InspectorAssets {
|
|
317
|
+
#hdtResCache = null;
|
|
318
|
+
async createInspectorResponse() {
|
|
319
|
+
const base = node_path.dirname(fileURLToPath(import.meta.url));
|
|
320
|
+
const primary = node_path.resolve(base, "../../public");
|
|
321
|
+
const secondary = node_path.resolve(base, "../public");
|
|
322
|
+
const filePath = [
|
|
323
|
+
primary,
|
|
324
|
+
secondary
|
|
325
|
+
].map((directory)=>node_path.join(directory, "inspector-wrapper.html")).find((candidate)=>node_fs.existsSync(candidate)) ?? node_path.join(primary, "inspector-wrapper.html");
|
|
326
|
+
try {
|
|
327
|
+
const content = await node_fs.promises.readFile(filePath, "utf-8");
|
|
328
|
+
return new Response(content, {
|
|
329
|
+
status: 200,
|
|
330
|
+
headers: {
|
|
331
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
332
|
+
"Content-Length": String(Buffer.byteLength(content)),
|
|
333
|
+
"Cache-Control": "no-store",
|
|
334
|
+
"Content-Security-Policy": "frame-ancestors 'self'"
|
|
335
|
+
}
|
|
336
|
+
});
|
|
337
|
+
} catch (error) {
|
|
338
|
+
inspector_assets_debug("failed to serve Inspector wrapper: %O", error);
|
|
339
|
+
return new Response("Not found", {
|
|
340
|
+
status: 404
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
async createHdtResourceResponse(pathname, acceptEncoding) {
|
|
345
|
+
try {
|
|
346
|
+
const relativePath = pathname.slice(HDT_RES_PATH_PREFIX.length);
|
|
347
|
+
if (!pathname.startsWith(HDT_RES_PATH_PREFIX) || relativePath.includes("..")) return new Response("Not found", {
|
|
348
|
+
status: 404
|
|
349
|
+
});
|
|
350
|
+
const ext = node_path.extname(relativePath).toLowerCase();
|
|
351
|
+
if (".map" === ext) return new Response("Not found", {
|
|
352
|
+
status: 404
|
|
353
|
+
});
|
|
354
|
+
if (!this.#hdtResCache) {
|
|
355
|
+
this.#hdtResCache = new TarballCache();
|
|
356
|
+
this.#hdtResCache.start(HDT_RES_TARBALL_URL);
|
|
357
|
+
}
|
|
358
|
+
const tarPath = relativePath;
|
|
359
|
+
const entry = this.#hdtResCache.get(tarPath) ?? await this.#hdtResCache.waitFor(tarPath);
|
|
360
|
+
if (!entry) return new Response("Not found", {
|
|
361
|
+
status: 404
|
|
362
|
+
});
|
|
363
|
+
const acceptsGzip = acceptEncoding?.includes("gzip") ?? false;
|
|
364
|
+
const body = acceptsGzip ? entry.gzipped : node_zlib.gunzipSync(entry.gzipped);
|
|
365
|
+
return new Response(Uint8Array.from(body), {
|
|
366
|
+
status: 200,
|
|
367
|
+
headers: {
|
|
368
|
+
"Content-Type": MIME_TYPES[ext] ?? "application/octet-stream",
|
|
369
|
+
...acceptsGzip ? {
|
|
370
|
+
"Content-Encoding": "gzip"
|
|
371
|
+
} : {},
|
|
372
|
+
"Content-Length": String(body.length),
|
|
373
|
+
"Cache-Control": "public, max-age=31536000, immutable"
|
|
374
|
+
}
|
|
375
|
+
});
|
|
376
|
+
} catch (error) {
|
|
377
|
+
inspector_assets_debug("failed to serve hdt-res file: %O", error);
|
|
378
|
+
return new Response("Failed to load resource", {
|
|
379
|
+
status: 502
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
const static_server_debug = ansi_createDebug("devtool-mcp-server:daemon:static-server");
|
|
309
385
|
class StaticServer {
|
|
310
|
-
#
|
|
386
|
+
#assets;
|
|
387
|
+
#resourcePrefix;
|
|
388
|
+
constructor(assets = new InspectorAssets(), resourcePrefix = HDT_RES_PATH_PREFIX){
|
|
389
|
+
this.#assets = assets;
|
|
390
|
+
this.#resourcePrefix = resourcePrefix;
|
|
391
|
+
}
|
|
311
392
|
tryHandle(req, res) {
|
|
312
|
-
if (
|
|
313
|
-
const pathname = new URL(req.url ??
|
|
393
|
+
if ("GET" !== req.method) return false;
|
|
394
|
+
const pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
|
|
314
395
|
if (pathname === DAEMON_INSPECTOR_PATH) {
|
|
315
|
-
this.#
|
|
396
|
+
this.#serveResponse(res, this.#assets.createInspectorResponse());
|
|
316
397
|
return true;
|
|
317
398
|
}
|
|
318
|
-
if (pathname.startsWith(
|
|
319
|
-
this.#
|
|
399
|
+
if (pathname.startsWith(this.#resourcePrefix)) {
|
|
400
|
+
this.#serveResponse(res, this.#assets.createHdtResourceResponse(pathname, req.headers["accept-encoding"]));
|
|
320
401
|
return true;
|
|
321
402
|
}
|
|
322
403
|
return false;
|
|
323
404
|
}
|
|
324
|
-
#
|
|
325
|
-
const base = node_path.dirname(fileURLToPath(import.meta.url));
|
|
326
|
-
const primary = node_path.resolve(base, '../../public');
|
|
327
|
-
const secondary = node_path.resolve(base, '../public');
|
|
328
|
-
const candidates = [
|
|
329
|
-
primary,
|
|
330
|
-
secondary
|
|
331
|
-
];
|
|
332
|
-
const filePath = candidates.map((d)=>node_path.join(d, 'inspector-wrapper.html')).find((f)=>node_fs.existsSync(f)) ?? node_path.join(primary, 'inspector-wrapper.html');
|
|
333
|
-
node_fs.readFile(filePath, 'utf-8', (err, content)=>{
|
|
334
|
-
if (err) {
|
|
335
|
-
res.writeHead(404);
|
|
336
|
-
res.end('Not found');
|
|
337
|
-
return;
|
|
338
|
-
}
|
|
339
|
-
res.writeHead(200, {
|
|
340
|
-
'content-type': 'text/html; charset=utf-8',
|
|
341
|
-
'content-length': Buffer.byteLength(content),
|
|
342
|
-
'cache-control': 'no-store'
|
|
343
|
-
});
|
|
344
|
-
res.end(content);
|
|
345
|
-
});
|
|
346
|
-
}
|
|
347
|
-
async #serveFrontendRes(req, res, pathname) {
|
|
405
|
+
async #serveResponse(res, responsePromise) {
|
|
348
406
|
try {
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
const ext = node_path.extname(relativePath).toLowerCase();
|
|
360
|
-
if ('.map' === ext) {
|
|
361
|
-
res.writeHead(404);
|
|
362
|
-
res.end('Not found');
|
|
363
|
-
return;
|
|
364
|
-
}
|
|
365
|
-
const entry = this.#frontendCache.get(relativePath) ?? await this.#frontendCache.waitFor(relativePath);
|
|
366
|
-
if (!entry) {
|
|
367
|
-
res.writeHead(404);
|
|
368
|
-
res.end('Not found');
|
|
369
|
-
return;
|
|
370
|
-
}
|
|
371
|
-
const contentType = MIME_TYPES[ext] ?? 'application/octet-stream';
|
|
372
|
-
const acceptGzip = req.headers['accept-encoding']?.includes('gzip');
|
|
373
|
-
if (acceptGzip) {
|
|
374
|
-
res.writeHead(200, {
|
|
375
|
-
'content-type': contentType,
|
|
376
|
-
'content-encoding': 'gzip',
|
|
377
|
-
'content-length': entry.gzipped.length,
|
|
378
|
-
'cache-control': 'public, max-age=31536000, immutable'
|
|
379
|
-
});
|
|
380
|
-
res.end(entry.gzipped);
|
|
381
|
-
} else {
|
|
382
|
-
const raw = node_zlib.gunzipSync(entry.gzipped);
|
|
383
|
-
res.writeHead(200, {
|
|
384
|
-
'content-type': contentType,
|
|
385
|
-
'content-length': raw.length,
|
|
386
|
-
'cache-control': 'public, max-age=31536000, immutable'
|
|
387
|
-
});
|
|
388
|
-
res.end(raw);
|
|
389
|
-
}
|
|
390
|
-
} catch (err) {
|
|
391
|
-
static_server_debug('failed to serve frontend file: %O', err);
|
|
392
|
-
res.writeHead(502);
|
|
393
|
-
res.end('Failed to load resource');
|
|
407
|
+
const response = await responsePromise;
|
|
408
|
+
const body = Buffer.from(await response.arrayBuffer());
|
|
409
|
+
if (res.destroyed || res.headersSent || res.writableEnded) return;
|
|
410
|
+
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
411
|
+
res.end(body);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
static_server_debug("failed to write static response: %O", error);
|
|
414
|
+
if (res.destroyed || res.headersSent || res.writableEnded) return;
|
|
415
|
+
res.writeHead(500);
|
|
416
|
+
res.end("Failed to write response");
|
|
394
417
|
}
|
|
395
418
|
}
|
|
396
419
|
}
|
|
397
|
-
const
|
|
420
|
+
const websocket_server = __webpack_require__("../../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/lib/websocket-server.js");
|
|
421
|
+
const server_debug = ansi_createDebug("devtool-mcp-server:daemon:server");
|
|
398
422
|
const IDLE_TIMEOUT_MS = 300000;
|
|
399
423
|
const DEVICE_CONN_GRACE_MS = 10000;
|
|
400
424
|
const DEVICE_DISCOVERY_TIMEOUT_MS = 2500;
|
|
@@ -403,6 +427,7 @@ class DevtoolDaemon {
|
|
|
403
427
|
#httpServer;
|
|
404
428
|
#wss = null;
|
|
405
429
|
#transports;
|
|
430
|
+
#hdtTransports;
|
|
406
431
|
#deviceConnections = new Map();
|
|
407
432
|
#pendingDeviceConnections = new Map();
|
|
408
433
|
#deviceConnectionCleanupTimers = new Map();
|
|
@@ -417,13 +442,20 @@ class DevtoolDaemon {
|
|
|
417
442
|
#shutdownAccepted = false;
|
|
418
443
|
#onIdle;
|
|
419
444
|
#onShutdown;
|
|
420
|
-
|
|
421
|
-
|
|
445
|
+
staticServer = new StaticServer();
|
|
446
|
+
actionCore = new ActionCore();
|
|
447
|
+
identity = {
|
|
448
|
+
product: DAEMON_PRODUCT,
|
|
449
|
+
version: CONNECTOR_VERSION,
|
|
450
|
+
lifecycleProtocol: 1,
|
|
451
|
+
commandProtocol: 1
|
|
452
|
+
};
|
|
422
453
|
#commandConnector = null;
|
|
423
454
|
#instanceId = randomUUID();
|
|
424
455
|
#startedAt = Date.now();
|
|
425
456
|
constructor(transports, options){
|
|
426
457
|
this.#transports = transports;
|
|
458
|
+
this.#hdtTransports = transports.filter((t)=>t instanceof HDTTransport);
|
|
427
459
|
this.#onIdle = options?.onIdle;
|
|
428
460
|
this.#onShutdown = options?.onShutdown;
|
|
429
461
|
this.#idleTimeoutMs = options?.idleTimeoutMs ?? IDLE_TIMEOUT_MS;
|
|
@@ -432,35 +464,45 @@ class DevtoolDaemon {
|
|
|
432
464
|
const isShutdownRequest = this.#isShutdownRequest(req.url);
|
|
433
465
|
if ((isCommandRequest || isShutdownRequest) && !this.#isTrustedLocalRequest(req)) return void this.#sendJson(res, 403, {
|
|
434
466
|
ok: false,
|
|
435
|
-
error:
|
|
467
|
+
error: "Daemon control requests require a same-origin loopback Host and Origin."
|
|
436
468
|
});
|
|
437
|
-
if (isCommandRequest &&
|
|
469
|
+
if (isCommandRequest && "POST" === req.method && !this.#hasJsonContentType(req)) return void this.#sendJson(res, 415, {
|
|
438
470
|
ok: false,
|
|
439
|
-
error:
|
|
440
|
-
});
|
|
441
|
-
if ('GET' === req.method && this.#isVersionRequest(req.url)) return void this.#sendJson(res, 200, {
|
|
442
|
-
product: DAEMON_PRODUCT,
|
|
443
|
-
version: CONNECTOR_VERSION,
|
|
444
|
-
lifecycleProtocol: 1,
|
|
445
|
-
commandProtocol: 1,
|
|
446
|
-
instanceId: this.#instanceId,
|
|
447
|
-
startedAt: this.#startedAt
|
|
471
|
+
error: "POST /command requests require Content-Type: application/json."
|
|
448
472
|
});
|
|
449
|
-
if (this.#
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
473
|
+
if ("GET" === req.method && this.#isVersionRequest(req.url)) {
|
|
474
|
+
this.#setVersionCorsHeaders(res);
|
|
475
|
+
this.#sendJson(res, 200, {
|
|
476
|
+
...this.identity,
|
|
477
|
+
instanceId: this.#instanceId,
|
|
478
|
+
startedAt: this.#startedAt
|
|
479
|
+
});
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
if ("OPTIONS" === req.method && this.#isVersionRequest(req.url)) {
|
|
483
|
+
this.#setVersionCorsHeaders(res);
|
|
484
|
+
res.writeHead(204, {
|
|
485
|
+
"access-control-allow-methods": "GET",
|
|
486
|
+
"cache-control": "no-store"
|
|
487
|
+
});
|
|
488
|
+
res.end();
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (this.staticServer.tryHandle(req, res)) return;
|
|
492
|
+
if ("POST" === req.method && isCommandRequest && this.#acceptsEventStream(req)) return void this.#trackCommandRequest(()=>this.#handleCommandStream(req, res));
|
|
493
|
+
if ("POST" === req.method && isCommandRequest) return void this.#trackCommandRequest(()=>this.#handleCommandRequest(req, res));
|
|
494
|
+
if ("GET" === req.method && isCommandRequest) return void this.#trackCommandRequest(()=>this.#handleCommandStream(req, res));
|
|
495
|
+
if ("POST" === req.method && isShutdownRequest) return void this.#handleShutdownRequest(req, res);
|
|
454
496
|
res.writeHead(404);
|
|
455
497
|
res.end();
|
|
456
498
|
});
|
|
457
499
|
}
|
|
458
500
|
async start(port) {
|
|
459
|
-
const wss = new
|
|
501
|
+
const wss = new websocket_server({
|
|
460
502
|
noServer: true
|
|
461
503
|
});
|
|
462
504
|
this.#wss = wss;
|
|
463
|
-
this.#httpServer.on(
|
|
505
|
+
this.#httpServer.on("upgrade", (request, socket, head)=>{
|
|
464
506
|
if (this.#closed || !request.url?.startsWith(DAEMON_WS_PATH) || !this.#isTrustedLocalRequest(request)) return void socket.destroy();
|
|
465
507
|
wss.handleUpgrade(request, socket, head, (ws)=>{
|
|
466
508
|
if (this.#closed) return void ws.terminate();
|
|
@@ -468,15 +510,15 @@ class DevtoolDaemon {
|
|
|
468
510
|
});
|
|
469
511
|
});
|
|
470
512
|
return new Promise((resolve, reject)=>{
|
|
471
|
-
this.#httpServer.once(
|
|
472
|
-
this.#httpServer.listen(port,
|
|
473
|
-
this.#httpServer.removeListener(
|
|
513
|
+
this.#httpServer.once("error", reject);
|
|
514
|
+
this.#httpServer.listen(port, "127.0.0.1", ()=>{
|
|
515
|
+
this.#httpServer.removeListener("error", reject);
|
|
474
516
|
this.#resetIdleTimer();
|
|
475
517
|
const address = this.#httpServer.address();
|
|
476
518
|
this.#commandConnector = new Connector([
|
|
477
|
-
new DaemonTransport(address.port)
|
|
519
|
+
new DaemonTransport(`ws://127.0.0.1:${address.port}${DAEMON_WS_PATH}`)
|
|
478
520
|
]);
|
|
479
|
-
server_debug(
|
|
521
|
+
server_debug("daemon listening on ws://127.0.0.1:%d%s", address.port, DAEMON_WS_PATH);
|
|
480
522
|
resolve(address.port);
|
|
481
523
|
});
|
|
482
524
|
});
|
|
@@ -488,7 +530,7 @@ class DevtoolDaemon {
|
|
|
488
530
|
async #close() {
|
|
489
531
|
this.#closed = true;
|
|
490
532
|
this.#clearIdleTimer();
|
|
491
|
-
for (const controller of this.#commandControllers)controller.abort(new Error(
|
|
533
|
+
for (const controller of this.#commandControllers)controller.abort(new Error("Connector daemon is shutting down."));
|
|
492
534
|
this.#commandControllers.clear();
|
|
493
535
|
for (const [, client] of this.#wsClients)client.close();
|
|
494
536
|
this.#wsClients.clear();
|
|
@@ -500,9 +542,9 @@ class DevtoolDaemon {
|
|
|
500
542
|
...this.#pendingDeviceConnections.values(),
|
|
501
543
|
...this.#transports.map((transport)=>Promise.resolve().then(()=>transport.close()))
|
|
502
544
|
]);
|
|
503
|
-
for (const result of shutdownResults)if (
|
|
545
|
+
for (const result of shutdownResults)if ("rejected" === result.status) server_debug("device connection did not settle cleanly during daemon shutdown: %O", result.reason);
|
|
504
546
|
const lateDisposalResults = await Promise.allSettled(Array.from(this.#deviceConnections.values(), (conn)=>conn.dispose()));
|
|
505
|
-
for (const result of lateDisposalResults)if (
|
|
547
|
+
for (const result of lateDisposalResults)if ("rejected" === result.status) server_debug("failed to dispose late device connection during daemon shutdown: %O", result.reason);
|
|
506
548
|
this.#deviceConnections.clear();
|
|
507
549
|
this.#wss?.close();
|
|
508
550
|
return new Promise((resolve)=>{
|
|
@@ -510,13 +552,17 @@ class DevtoolDaemon {
|
|
|
510
552
|
});
|
|
511
553
|
}
|
|
512
554
|
#isVersionRequest(url) {
|
|
513
|
-
return new URL(url ??
|
|
555
|
+
return new URL(url ?? "/", "http://127.0.0.1").pathname === DAEMON_VERSION_PATH;
|
|
514
556
|
}
|
|
515
557
|
#isShutdownRequest(url) {
|
|
516
|
-
return new URL(url ??
|
|
558
|
+
return new URL(url ?? "/", "http://127.0.0.1").pathname === DAEMON_SHUTDOWN_PATH;
|
|
517
559
|
}
|
|
518
560
|
#isCommandRequest(url) {
|
|
519
|
-
return new URL(url ??
|
|
561
|
+
return new URL(url ?? "/", "http://127.0.0.1").pathname.startsWith(DAEMON_COMMAND_PATH_PREFIX);
|
|
562
|
+
}
|
|
563
|
+
#setVersionCorsHeaders(res) {
|
|
564
|
+
res.setHeader("access-control-allow-origin", "*");
|
|
565
|
+
res.setHeader("access-control-allow-private-network", "true");
|
|
520
566
|
}
|
|
521
567
|
#isTrustedLocalRequest(req) {
|
|
522
568
|
const host = req.headers.host;
|
|
@@ -527,31 +573,31 @@ class DevtoolDaemon {
|
|
|
527
573
|
} catch {
|
|
528
574
|
return false;
|
|
529
575
|
}
|
|
530
|
-
if (
|
|
576
|
+
if ("127.0.0.1" !== requestOrigin.hostname && "localhost" !== requestOrigin.hostname) return false;
|
|
531
577
|
const origin = req.headers.origin;
|
|
532
578
|
if (!origin) return true;
|
|
533
579
|
try {
|
|
534
580
|
const originUrl = new URL(origin);
|
|
535
|
-
return
|
|
581
|
+
return "http:" === originUrl.protocol && originUrl.host.toLowerCase() === requestOrigin.host.toLowerCase();
|
|
536
582
|
} catch {
|
|
537
583
|
return false;
|
|
538
584
|
}
|
|
539
585
|
}
|
|
540
586
|
#hasJsonContentType(req) {
|
|
541
|
-
return req.headers[
|
|
587
|
+
return req.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() === "application/json";
|
|
542
588
|
}
|
|
543
589
|
#acceptsEventStream(req) {
|
|
544
590
|
const accept = req.headers.accept;
|
|
545
591
|
const values = Array.isArray(accept) ? accept : [
|
|
546
|
-
accept ??
|
|
592
|
+
accept ?? ""
|
|
547
593
|
];
|
|
548
|
-
return values.some((value)=>value.split(
|
|
594
|
+
return values.some((value)=>value.split(",").some((mediaType)=>mediaType.trim().toLowerCase().startsWith("text/event-stream")));
|
|
549
595
|
}
|
|
550
596
|
async #handleShutdownRequest(req, res) {
|
|
551
597
|
let parsed;
|
|
552
598
|
try {
|
|
553
599
|
const body = await this.#readBody(req);
|
|
554
|
-
parsed =
|
|
600
|
+
parsed = "" === body.trim() ? {} : JSON.parse(body);
|
|
555
601
|
} catch (error) {
|
|
556
602
|
this.#sendJson(res, 400, {
|
|
557
603
|
ok: false,
|
|
@@ -559,18 +605,18 @@ class DevtoolDaemon {
|
|
|
559
605
|
});
|
|
560
606
|
return;
|
|
561
607
|
}
|
|
562
|
-
if (
|
|
608
|
+
if ("object" != typeof parsed || null === parsed || Array.isArray(parsed)) return void this.#sendJson(res, 400, {
|
|
563
609
|
ok: false,
|
|
564
|
-
error:
|
|
610
|
+
error: "Shutdown request body must be a JSON object."
|
|
565
611
|
});
|
|
566
612
|
const { expectedInstanceId } = parsed;
|
|
567
|
-
if (
|
|
613
|
+
if ("string" != typeof expectedInstanceId || "" === expectedInstanceId) return void this.#sendJson(res, 428, {
|
|
568
614
|
ok: false,
|
|
569
|
-
error:
|
|
615
|
+
error: "Shutdown requires the expected daemon instance ID."
|
|
570
616
|
});
|
|
571
617
|
if (expectedInstanceId !== this.#instanceId) return void this.#sendJson(res, 409, {
|
|
572
618
|
ok: false,
|
|
573
|
-
error:
|
|
619
|
+
error: "Daemon instance changed before shutdown.",
|
|
574
620
|
instanceId: this.#instanceId
|
|
575
621
|
});
|
|
576
622
|
if (this.#shutdownAccepted) return void this.#sendJson(res, 202, {
|
|
@@ -582,24 +628,24 @@ class DevtoolDaemon {
|
|
|
582
628
|
ok: true
|
|
583
629
|
}, ()=>{
|
|
584
630
|
this.close().catch((err)=>{
|
|
585
|
-
server_debug(
|
|
631
|
+
server_debug("failed to close daemon after shutdown request: %O", err);
|
|
586
632
|
}).finally(()=>{
|
|
587
633
|
this.#onShutdown?.();
|
|
588
634
|
});
|
|
589
635
|
});
|
|
590
636
|
}
|
|
591
637
|
async #handleCommandRequest(req, res) {
|
|
592
|
-
const pathname = new URL(req.url ??
|
|
638
|
+
const pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
|
|
593
639
|
let action;
|
|
594
640
|
try {
|
|
595
641
|
action = decodeURIComponent(pathname.slice(DAEMON_COMMAND_PATH_PREFIX.length));
|
|
596
642
|
} catch {
|
|
597
643
|
this.#sendJson(res, 400, {
|
|
598
644
|
ok: false,
|
|
599
|
-
action:
|
|
645
|
+
action: "",
|
|
600
646
|
error: {
|
|
601
|
-
message:
|
|
602
|
-
reason:
|
|
647
|
+
message: "Command action path contains invalid percent encoding.",
|
|
648
|
+
reason: "bad-path",
|
|
603
649
|
recoverable: false,
|
|
604
650
|
nextActions: []
|
|
605
651
|
}
|
|
@@ -608,21 +654,21 @@ class DevtoolDaemon {
|
|
|
608
654
|
}
|
|
609
655
|
const controller = new AbortController();
|
|
610
656
|
this.#commandControllers.add(controller);
|
|
611
|
-
const onDisconnect = ()=>controller.abort(new Error(
|
|
612
|
-
req.once(
|
|
613
|
-
res.once(
|
|
657
|
+
const onDisconnect = ()=>controller.abort(new Error("HTTP command client disconnected."));
|
|
658
|
+
req.once("aborted", onDisconnect);
|
|
659
|
+
res.once("close", onDisconnect);
|
|
614
660
|
try {
|
|
615
661
|
let params = {};
|
|
616
662
|
try {
|
|
617
663
|
const body = await this.#readBody(req, controller.signal);
|
|
618
|
-
if (
|
|
664
|
+
if ("" !== body.trim()) {
|
|
619
665
|
const parsed = JSON.parse(body);
|
|
620
|
-
if (
|
|
666
|
+
if ("object" != typeof parsed || null === parsed || Array.isArray(parsed)) return void this.#sendJson(res, 200, {
|
|
621
667
|
ok: false,
|
|
622
668
|
action,
|
|
623
669
|
error: {
|
|
624
|
-
message:
|
|
625
|
-
reason:
|
|
670
|
+
message: "Request body must be a JSON object.",
|
|
671
|
+
reason: "bad-params",
|
|
626
672
|
recoverable: false,
|
|
627
673
|
nextActions: []
|
|
628
674
|
}
|
|
@@ -636,73 +682,73 @@ class DevtoolDaemon {
|
|
|
636
682
|
action,
|
|
637
683
|
error: {
|
|
638
684
|
message: `Invalid JSON body: ${error instanceof Error ? error.message : String(error)}`,
|
|
639
|
-
reason:
|
|
685
|
+
reason: "bad-params",
|
|
640
686
|
recoverable: false,
|
|
641
687
|
nextActions: []
|
|
642
688
|
}
|
|
643
689
|
});
|
|
644
690
|
return;
|
|
645
691
|
}
|
|
646
|
-
const result = await this
|
|
692
|
+
const result = await this.actionCore.execute(action, params, {
|
|
647
693
|
connector: this.#requireCommandConnector()
|
|
648
694
|
}, controller.signal);
|
|
649
695
|
if (!controller.signal.aborted && !res.destroyed) this.#sendJson(res, 200, result);
|
|
650
696
|
} finally{
|
|
651
|
-
req.off(
|
|
652
|
-
res.off(
|
|
697
|
+
req.off("aborted", onDisconnect);
|
|
698
|
+
res.off("close", onDisconnect);
|
|
653
699
|
this.#commandControllers.delete(controller);
|
|
654
700
|
}
|
|
655
701
|
}
|
|
656
702
|
async #handleCommandStream(req, res) {
|
|
657
|
-
const url = new URL(req.url ??
|
|
703
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
658
704
|
let action;
|
|
659
705
|
try {
|
|
660
706
|
action = decodeURIComponent(url.pathname.slice(DAEMON_COMMAND_PATH_PREFIX.length));
|
|
661
707
|
} catch {
|
|
662
708
|
this.#sendJson(res, 400, {
|
|
663
709
|
ok: false,
|
|
664
|
-
action:
|
|
710
|
+
action: "",
|
|
665
711
|
error: {
|
|
666
|
-
message:
|
|
667
|
-
reason:
|
|
712
|
+
message: "Command action path contains invalid percent encoding.",
|
|
713
|
+
reason: "bad-path",
|
|
668
714
|
recoverable: false,
|
|
669
715
|
nextActions: []
|
|
670
716
|
}
|
|
671
717
|
});
|
|
672
718
|
return;
|
|
673
719
|
}
|
|
674
|
-
if (!this
|
|
720
|
+
if (!this.actionCore.hasStream(action)) return void this.#sendJson(res, 404, {
|
|
675
721
|
ok: false,
|
|
676
722
|
action,
|
|
677
723
|
error: {
|
|
678
724
|
message: `Unknown stream action: ${action}`,
|
|
679
|
-
reason:
|
|
725
|
+
reason: "unknown-action",
|
|
680
726
|
recoverable: false,
|
|
681
|
-
nextActions: this
|
|
727
|
+
nextActions: this.actionCore.streamActions().map((name)=>`GET /command/${name}`)
|
|
682
728
|
}
|
|
683
729
|
});
|
|
684
730
|
const controller = new AbortController();
|
|
685
731
|
this.#commandControllers.add(controller);
|
|
686
|
-
const onDisconnect = ()=>controller.abort(new Error(
|
|
687
|
-
req.once(
|
|
688
|
-
res.once(
|
|
732
|
+
const onDisconnect = ()=>controller.abort(new Error("SSE command client disconnected."));
|
|
733
|
+
req.once("aborted", onDisconnect);
|
|
734
|
+
res.once("close", onDisconnect);
|
|
689
735
|
try {
|
|
690
736
|
let params;
|
|
691
737
|
try {
|
|
692
|
-
params =
|
|
738
|
+
params = "POST" === req.method ? await this.#readCommandStreamBody(req, controller.signal) : decodeCommandQuery(url.searchParams);
|
|
693
739
|
} catch (error) {
|
|
694
740
|
if (controller.signal.aborted) return;
|
|
695
741
|
res.writeHead(200, {
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
connection:
|
|
742
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
743
|
+
"cache-control": "no-store",
|
|
744
|
+
connection: "keep-alive"
|
|
699
745
|
});
|
|
700
746
|
res.end(`data: ${JSON.stringify({
|
|
701
747
|
ok: false,
|
|
702
748
|
action,
|
|
703
749
|
error: {
|
|
704
750
|
message: `Invalid JSON body: ${error instanceof Error ? error.message : String(error)}`,
|
|
705
|
-
reason:
|
|
751
|
+
reason: "bad-params",
|
|
706
752
|
recoverable: false,
|
|
707
753
|
nextActions: []
|
|
708
754
|
}
|
|
@@ -711,12 +757,12 @@ class DevtoolDaemon {
|
|
|
711
757
|
}
|
|
712
758
|
controller.signal.throwIfAborted();
|
|
713
759
|
res.writeHead(200, {
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
connection:
|
|
717
|
-
|
|
760
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
761
|
+
"cache-control": "no-store",
|
|
762
|
+
connection: "keep-alive",
|
|
763
|
+
"x-accel-buffering": "no"
|
|
718
764
|
});
|
|
719
|
-
for await (const event of this
|
|
765
|
+
for await (const event of this.actionCore.stream(action, params, {
|
|
720
766
|
connector: this.#requireCommandConnector()
|
|
721
767
|
}, controller.signal)){
|
|
722
768
|
if (controller.signal.aborted) break;
|
|
@@ -726,10 +772,10 @@ class DevtoolDaemon {
|
|
|
726
772
|
}
|
|
727
773
|
}
|
|
728
774
|
} catch (error) {
|
|
729
|
-
if (!controller.signal.aborted) server_debug(
|
|
775
|
+
if (!controller.signal.aborted) server_debug("command stream %s failed: %O", action, error);
|
|
730
776
|
} finally{
|
|
731
|
-
req.off(
|
|
732
|
-
res.off(
|
|
777
|
+
req.off("aborted", onDisconnect);
|
|
778
|
+
res.off("close", onDisconnect);
|
|
733
779
|
this.#commandControllers.delete(controller);
|
|
734
780
|
if (!res.destroyed && !res.writableEnded) res.end();
|
|
735
781
|
}
|
|
@@ -741,26 +787,26 @@ class DevtoolDaemon {
|
|
|
741
787
|
const finish = (drained)=>{
|
|
742
788
|
if (settled) return;
|
|
743
789
|
settled = true;
|
|
744
|
-
res.off(
|
|
745
|
-
res.off(
|
|
746
|
-
res.off(
|
|
747
|
-
signal.removeEventListener(
|
|
790
|
+
res.off("drain", onDrain);
|
|
791
|
+
res.off("close", onClose);
|
|
792
|
+
res.off("error", onClose);
|
|
793
|
+
signal.removeEventListener("abort", onAbort);
|
|
748
794
|
resolve(drained);
|
|
749
795
|
};
|
|
750
796
|
const onDrain = ()=>finish(true);
|
|
751
797
|
const onAbort = ()=>finish(false);
|
|
752
798
|
const onClose = ()=>finish(false);
|
|
753
|
-
res.once(
|
|
754
|
-
res.once(
|
|
755
|
-
res.once(
|
|
756
|
-
signal.addEventListener(
|
|
799
|
+
res.once("drain", onDrain);
|
|
800
|
+
res.once("close", onClose);
|
|
801
|
+
res.once("error", onClose);
|
|
802
|
+
signal.addEventListener("abort", onAbort, {
|
|
757
803
|
once: true
|
|
758
804
|
});
|
|
759
805
|
if (signal.aborted || res.destroyed) finish(false);
|
|
760
806
|
});
|
|
761
807
|
}
|
|
762
808
|
#requireCommandConnector() {
|
|
763
|
-
if (!this.#commandConnector) throw new Error(
|
|
809
|
+
if (!this.#commandConnector) throw new Error("Connector daemon has not started its command transport.");
|
|
764
810
|
return this.#commandConnector;
|
|
765
811
|
}
|
|
766
812
|
#readBody(req, signal) {
|
|
@@ -770,11 +816,11 @@ class DevtoolDaemon {
|
|
|
770
816
|
let settled = false;
|
|
771
817
|
const maxSize = 8388608;
|
|
772
818
|
const cleanup = ()=>{
|
|
773
|
-
req.off(
|
|
774
|
-
req.off(
|
|
775
|
-
req.off(
|
|
776
|
-
req.off(
|
|
777
|
-
signal?.removeEventListener(
|
|
819
|
+
req.off("data", onData);
|
|
820
|
+
req.off("end", onEnd);
|
|
821
|
+
req.off("error", onError);
|
|
822
|
+
req.off("aborted", onAborted);
|
|
823
|
+
signal?.removeEventListener("abort", onSignalAbort);
|
|
778
824
|
};
|
|
779
825
|
const finish = (callback)=>{
|
|
780
826
|
if (settled) return;
|
|
@@ -785,24 +831,24 @@ class DevtoolDaemon {
|
|
|
785
831
|
const onData = (chunk)=>{
|
|
786
832
|
size += chunk.length;
|
|
787
833
|
if (size > maxSize) {
|
|
788
|
-
finish(()=>reject(new Error(
|
|
834
|
+
finish(()=>reject(new Error("Request body exceeds 8 MiB.")));
|
|
789
835
|
req.destroy();
|
|
790
836
|
return;
|
|
791
837
|
}
|
|
792
838
|
chunks.push(chunk);
|
|
793
839
|
};
|
|
794
|
-
const onEnd = ()=>finish(()=>resolve(Buffer.concat(chunks).toString(
|
|
840
|
+
const onEnd = ()=>finish(()=>resolve(Buffer.concat(chunks).toString("utf8")));
|
|
795
841
|
const onError = (error)=>finish(()=>reject(error));
|
|
796
|
-
const onAborted = ()=>finish(()=>reject(new Error(
|
|
842
|
+
const onAborted = ()=>finish(()=>reject(new Error("Request body was aborted.")));
|
|
797
843
|
const onSignalAbort = ()=>{
|
|
798
|
-
finish(()=>reject(signal?.reason ?? new Error(
|
|
844
|
+
finish(()=>reject(signal?.reason ?? new Error("Request was aborted.")));
|
|
799
845
|
if (!req.destroyed) req.destroy();
|
|
800
846
|
};
|
|
801
|
-
req.on(
|
|
802
|
-
req.once(
|
|
803
|
-
req.once(
|
|
804
|
-
req.once(
|
|
805
|
-
signal?.addEventListener(
|
|
847
|
+
req.on("data", onData);
|
|
848
|
+
req.once("end", onEnd);
|
|
849
|
+
req.once("error", onError);
|
|
850
|
+
req.once("aborted", onAborted);
|
|
851
|
+
signal?.addEventListener("abort", onSignalAbort, {
|
|
806
852
|
once: true
|
|
807
853
|
});
|
|
808
854
|
if (signal?.aborted) onSignalAbort();
|
|
@@ -810,17 +856,17 @@ class DevtoolDaemon {
|
|
|
810
856
|
}
|
|
811
857
|
async #readCommandStreamBody(req, signal) {
|
|
812
858
|
const body = await this.#readBody(req, signal);
|
|
813
|
-
if (
|
|
859
|
+
if ("" === body.trim()) return {};
|
|
814
860
|
const parsed = JSON.parse(body);
|
|
815
|
-
if (
|
|
861
|
+
if ("object" != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error("Request body must be a JSON object.");
|
|
816
862
|
return parsed;
|
|
817
863
|
}
|
|
818
864
|
#sendJson(res, statusCode, data, callback) {
|
|
819
865
|
const body = JSON.stringify(data);
|
|
820
866
|
res.writeHead(statusCode, {
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
867
|
+
"content-type": "application/json; charset=utf-8",
|
|
868
|
+
"content-length": Buffer.byteLength(body),
|
|
869
|
+
"cache-control": "no-store"
|
|
824
870
|
});
|
|
825
871
|
res.end(body, callback);
|
|
826
872
|
}
|
|
@@ -828,7 +874,7 @@ class DevtoolDaemon {
|
|
|
828
874
|
this.#activeCommandRequests += 1;
|
|
829
875
|
this.#clearIdleTimer();
|
|
830
876
|
handler().catch((error)=>{
|
|
831
|
-
server_debug(
|
|
877
|
+
server_debug("command request failed: %O", error);
|
|
832
878
|
}).finally(()=>{
|
|
833
879
|
this.#activeCommandRequests -= 1;
|
|
834
880
|
this.#resetIdleTimer();
|
|
@@ -837,7 +883,7 @@ class DevtoolDaemon {
|
|
|
837
883
|
#handleConnection(ws) {
|
|
838
884
|
if (this.#closed) return void ws.terminate();
|
|
839
885
|
const clientId = ++this.#nextClientId;
|
|
840
|
-
server_debug(
|
|
886
|
+
server_debug("new ws client %d", clientId);
|
|
841
887
|
this.#clearIdleTimer();
|
|
842
888
|
let closing = false;
|
|
843
889
|
const session = {
|
|
@@ -853,23 +899,23 @@ class DevtoolDaemon {
|
|
|
853
899
|
if (closing) return;
|
|
854
900
|
closing = true;
|
|
855
901
|
this.#wsClients.delete(clientId);
|
|
856
|
-
ws.close(1001,
|
|
902
|
+
ws.close(1001, "device disconnected");
|
|
857
903
|
}
|
|
858
904
|
};
|
|
859
905
|
session.send({
|
|
860
|
-
event:
|
|
906
|
+
event: "Initialize",
|
|
861
907
|
data: clientId
|
|
862
908
|
});
|
|
863
|
-
ws.on(
|
|
909
|
+
ws.on("message", (raw)=>{
|
|
864
910
|
try {
|
|
865
911
|
const msg = JSON.parse(String(raw));
|
|
866
912
|
this.#handleMessage(session, msg);
|
|
867
913
|
} catch (err) {
|
|
868
|
-
server_debug(
|
|
914
|
+
server_debug("failed to parse message from client %d: %O", clientId, err);
|
|
869
915
|
}
|
|
870
916
|
});
|
|
871
|
-
ws.on(
|
|
872
|
-
server_debug(
|
|
917
|
+
ws.on("close", ()=>{
|
|
918
|
+
server_debug("ws client %d disconnected", clientId);
|
|
873
919
|
closing = true;
|
|
874
920
|
this.#wsClients.delete(clientId);
|
|
875
921
|
for (const deviceConn of session.subscriptions){
|
|
@@ -879,29 +925,29 @@ class DevtoolDaemon {
|
|
|
879
925
|
session.subscriptions.clear();
|
|
880
926
|
this.#resetIdleTimer();
|
|
881
927
|
});
|
|
882
|
-
ws.on(
|
|
883
|
-
server_debug(
|
|
928
|
+
ws.on("error", (err)=>{
|
|
929
|
+
server_debug("ws client %d error: %O", clientId, err);
|
|
884
930
|
});
|
|
885
931
|
}
|
|
886
932
|
#handleMessage(session, msg) {
|
|
887
|
-
if (session.isClosing) return void server_debug(
|
|
933
|
+
if (session.isClosing) return void server_debug("ignoring message from closing client %d", session.id);
|
|
888
934
|
if (this.#closed) return void session.close();
|
|
889
935
|
if (isRegisterEvent(msg)) {
|
|
890
936
|
this.#wsClients.set(session.id, session);
|
|
891
|
-
server_debug(
|
|
937
|
+
server_debug("client %d registered", session.id);
|
|
892
938
|
return;
|
|
893
939
|
}
|
|
894
940
|
if (isListClientsRequest(msg)) return void this.#sendClientList(session);
|
|
895
941
|
if (isPingEvent(msg)) return void session.send({
|
|
896
|
-
event:
|
|
942
|
+
event: "Pong"
|
|
897
943
|
});
|
|
898
944
|
if (isControlRequest(msg)) return void this.#handleControlRequest(session, msg);
|
|
899
945
|
if (isCustomizedMessage(msg)) return void this.#handleCustomizedMessage(session, msg);
|
|
900
|
-
server_debug(
|
|
946
|
+
server_debug("unknown message from client %d: %O", session.id, msg);
|
|
901
947
|
}
|
|
902
948
|
async #handleCustomizedMessage(session, msg) {
|
|
903
949
|
const targetPort = msg.to ?? msg.data?.data?.client_id;
|
|
904
|
-
if (
|
|
950
|
+
if ("number" != typeof targetPort && "string" != typeof targetPort) return void server_debug("cannot determine target from message: %O", msg);
|
|
905
951
|
for (const deviceConn of session.subscriptions)if (deviceConn.port === targetPort) {
|
|
906
952
|
try {
|
|
907
953
|
await deviceConn.send({
|
|
@@ -912,40 +958,40 @@ class DevtoolDaemon {
|
|
|
912
958
|
}
|
|
913
959
|
});
|
|
914
960
|
} catch (err) {
|
|
915
|
-
server_debug(
|
|
961
|
+
server_debug("failed to forward message to %s: %O", deviceConn.key, err);
|
|
916
962
|
}
|
|
917
963
|
return;
|
|
918
964
|
}
|
|
919
|
-
server_debug(
|
|
965
|
+
server_debug("no matching device connection for client %d, target %o", session.id, targetPort);
|
|
920
966
|
}
|
|
921
967
|
async #handleControlRequest(session, req) {
|
|
922
968
|
const { id, method, params } = req.data;
|
|
923
969
|
try {
|
|
924
970
|
let result;
|
|
925
971
|
switch(method){
|
|
926
|
-
case
|
|
972
|
+
case "listClients":
|
|
927
973
|
result = await this.#discoverClients();
|
|
928
974
|
break;
|
|
929
|
-
case
|
|
975
|
+
case "listDevices":
|
|
930
976
|
{
|
|
931
977
|
const devices = [];
|
|
932
978
|
const allResults = await Promise.allSettled(this.#transports.map((t)=>t.listDevices()));
|
|
933
|
-
for (const r of allResults)if (
|
|
979
|
+
for (const r of allResults)if ("fulfilled" === r.status) devices.push(...r.value);
|
|
934
980
|
result = devices;
|
|
935
981
|
break;
|
|
936
982
|
}
|
|
937
|
-
case
|
|
983
|
+
case "listAvailableApps":
|
|
938
984
|
{
|
|
939
985
|
const deviceId = params?.deviceId;
|
|
940
|
-
if (!deviceId) throw new Error(
|
|
986
|
+
if (!deviceId) throw new Error("deviceId is required");
|
|
941
987
|
const transport = await this.#findTransportWithDeviceId(deviceId);
|
|
942
988
|
result = await transport.listAvailableApps(deviceId);
|
|
943
989
|
break;
|
|
944
990
|
}
|
|
945
|
-
case
|
|
991
|
+
case "openApp":
|
|
946
992
|
{
|
|
947
993
|
const p = params ?? {};
|
|
948
|
-
if (!p.deviceId || !p.packageName) throw new Error(
|
|
994
|
+
if (!p.deviceId || !p.packageName) throw new Error("deviceId and packageName are required");
|
|
949
995
|
const transport = await this.#findTransportWithDeviceId(p.deviceId);
|
|
950
996
|
await transport.openApp(p.deviceId, p.packageName, {
|
|
951
997
|
withDataCleared: p.withDataCleared
|
|
@@ -953,10 +999,10 @@ class DevtoolDaemon {
|
|
|
953
999
|
result = null;
|
|
954
1000
|
break;
|
|
955
1001
|
}
|
|
956
|
-
case
|
|
1002
|
+
case "subscribe":
|
|
957
1003
|
{
|
|
958
1004
|
const s = params ?? {};
|
|
959
|
-
if (!s.deviceId || void 0 === s.port) throw new Error(
|
|
1005
|
+
if (!s.deviceId || void 0 === s.port) throw new Error("deviceId and port are required");
|
|
960
1006
|
const key = `${s.deviceId}:${s.port}`;
|
|
961
1007
|
let conn = this.#deviceConnections.get(key);
|
|
962
1008
|
if (!conn || conn.isDisposed) {
|
|
@@ -976,7 +1022,7 @@ class DevtoolDaemon {
|
|
|
976
1022
|
throw new Error(`Unknown control method: ${method}`);
|
|
977
1023
|
}
|
|
978
1024
|
session.send({
|
|
979
|
-
event:
|
|
1025
|
+
event: "ControlResponse",
|
|
980
1026
|
data: {
|
|
981
1027
|
id,
|
|
982
1028
|
result
|
|
@@ -985,7 +1031,7 @@ class DevtoolDaemon {
|
|
|
985
1031
|
} catch (err) {
|
|
986
1032
|
const message = err instanceof Error ? err.message : String(err);
|
|
987
1033
|
session.send({
|
|
988
|
-
event:
|
|
1034
|
+
event: "ControlResponse",
|
|
989
1035
|
data: {
|
|
990
1036
|
id,
|
|
991
1037
|
error: message
|
|
@@ -997,13 +1043,13 @@ class DevtoolDaemon {
|
|
|
997
1043
|
try {
|
|
998
1044
|
const clients = await this.#discoverClients();
|
|
999
1045
|
session.send({
|
|
1000
|
-
event:
|
|
1046
|
+
event: "ClientList",
|
|
1001
1047
|
data: clients
|
|
1002
1048
|
});
|
|
1003
1049
|
} catch (err) {
|
|
1004
|
-
server_debug(
|
|
1050
|
+
server_debug("failed to send client list: %O", err);
|
|
1005
1051
|
session.send({
|
|
1006
|
-
event:
|
|
1052
|
+
event: "ClientList",
|
|
1007
1053
|
data: []
|
|
1008
1054
|
});
|
|
1009
1055
|
}
|
|
@@ -1012,14 +1058,29 @@ class DevtoolDaemon {
|
|
|
1012
1058
|
const entries = [];
|
|
1013
1059
|
const discoveryFailures = [];
|
|
1014
1060
|
let lowerAuthorityFulfilled = false;
|
|
1015
|
-
const
|
|
1061
|
+
const hdtClientResults = await Promise.allSettled(this.#hdtTransports.map((transport)=>transport.listClients()));
|
|
1062
|
+
const fulfilledHDTClientResults = hdtClientResults.filter((r)=>"fulfilled" === r.status);
|
|
1063
|
+
discoveryFailures.push(...hdtClientResults.filter((r)=>"rejected" === r.status).map((r)=>r.reason));
|
|
1064
|
+
const hdtClients = fulfilledHDTClientResults.flatMap((r)=>r.value);
|
|
1065
|
+
if (fulfilledHDTClientResults.length > 0) {
|
|
1066
|
+
server_debug("Using clients from HDT transport: %o", hdtClients);
|
|
1067
|
+
return hdtClients.map(({ id, info })=>({
|
|
1068
|
+
id,
|
|
1069
|
+
info,
|
|
1070
|
+
type: "runtime"
|
|
1071
|
+
}));
|
|
1072
|
+
}
|
|
1073
|
+
if ([
|
|
1074
|
+
...this.#deviceConnections.values()
|
|
1075
|
+
].some((conn)=>conn.transport instanceof HDTTransport && !conn.isDisposed)) throwClientDiscoveryFailures(discoveryFailures);
|
|
1076
|
+
const clientListTransports = this.#transports.filter((t)=>!(t instanceof HDTTransport) && "function" == typeof t.listClients);
|
|
1016
1077
|
const clientListResults = await Promise.allSettled(clientListTransports.map((t)=>t.listClients()));
|
|
1017
|
-
for (const r of clientListResults)if (
|
|
1078
|
+
for (const r of clientListResults)if ("fulfilled" === r.status) {
|
|
1018
1079
|
lowerAuthorityFulfilled = true;
|
|
1019
1080
|
for (const { id, info } of r.value)entries.push({
|
|
1020
1081
|
id,
|
|
1021
1082
|
info,
|
|
1022
|
-
type:
|
|
1083
|
+
type: "runtime"
|
|
1023
1084
|
});
|
|
1024
1085
|
} else discoveryFailures.push(r.reason);
|
|
1025
1086
|
for (const [, conn] of this.#deviceConnections)if (conn.appInfo && !conn.isDisposed) {
|
|
@@ -1028,15 +1089,15 @@ class DevtoolDaemon {
|
|
|
1028
1089
|
entries.push({
|
|
1029
1090
|
id,
|
|
1030
1091
|
info: conn.appInfo,
|
|
1031
|
-
type:
|
|
1092
|
+
type: "runtime"
|
|
1032
1093
|
});
|
|
1033
1094
|
}
|
|
1034
1095
|
const allDevices = [];
|
|
1035
|
-
const transportResults = await Promise.allSettled(this.#transports.map(async (transport)=>({
|
|
1096
|
+
const transportResults = await Promise.allSettled(this.#transports.filter((transport)=>!(transport instanceof HDTTransport) && "function" != typeof transport.listClients).map(async (transport)=>({
|
|
1036
1097
|
transport,
|
|
1037
1098
|
devices: await transport.listDevices()
|
|
1038
1099
|
})));
|
|
1039
|
-
for (const r of transportResults)if (
|
|
1100
|
+
for (const r of transportResults)if ("fulfilled" === r.status) {
|
|
1040
1101
|
lowerAuthorityFulfilled = true;
|
|
1041
1102
|
allDevices.push(r.value);
|
|
1042
1103
|
} else discoveryFailures.push(r.reason);
|
|
@@ -1046,14 +1107,14 @@ class DevtoolDaemon {
|
|
|
1046
1107
|
}, (_, i)=>MIN_PORT + i);
|
|
1047
1108
|
const existingKeys = new Set(Array.from(this.#deviceConnections.entries()).filter(([, connection])=>!connection.isDisposed).map(([key])=>key));
|
|
1048
1109
|
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)))));
|
|
1049
|
-
for (const r of probeResults)if (
|
|
1110
|
+
for (const r of probeResults)if ("fulfilled" === r.status) {
|
|
1050
1111
|
const conn = r.value;
|
|
1051
1112
|
if (conn.appInfo && !conn.isDisposed) {
|
|
1052
1113
|
const clientId = ClientId.serialize(conn.deviceId, conn.port);
|
|
1053
1114
|
if (!entries.some((e)=>e.id === clientId)) entries.push({
|
|
1054
1115
|
id: clientId,
|
|
1055
1116
|
info: conn.appInfo,
|
|
1056
|
-
type:
|
|
1117
|
+
type: "runtime"
|
|
1057
1118
|
});
|
|
1058
1119
|
}
|
|
1059
1120
|
}
|
|
@@ -1090,23 +1151,25 @@ class DevtoolDaemon {
|
|
|
1090
1151
|
await withAbortSignal(connectPromise, setupAbortController.signal);
|
|
1091
1152
|
if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
|
|
1092
1153
|
await withAbortSignal(conn.send({
|
|
1093
|
-
event:
|
|
1154
|
+
event: "Initialize",
|
|
1094
1155
|
data: port
|
|
1095
1156
|
}), setupAbortController.signal);
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1157
|
+
if (!(transport instanceof HDTTransport)) {
|
|
1158
|
+
clearTimeout(setupTimeout);
|
|
1159
|
+
registerTimeout = setTimeout(()=>{
|
|
1160
|
+
registerAbortController.abort(createDeviceRegisterTimeoutError(key));
|
|
1161
|
+
}, DEVICE_DISCOVERY_TIMEOUT_MS);
|
|
1162
|
+
await withAbortSignal(conn.waitUntilRegistered(), registerAbortController.signal);
|
|
1163
|
+
if (conn.isDisposed) throw new Error(`Device connection ${key} closed immediately after Register`);
|
|
1164
|
+
}
|
|
1102
1165
|
if (this.#closed) throw new Error(`DevTool daemon closed while acquiring device connection ${key}`);
|
|
1103
1166
|
this.#deviceConnections.set(key, conn);
|
|
1104
1167
|
return conn;
|
|
1105
1168
|
} catch (err) {
|
|
1106
|
-
server_debug(
|
|
1169
|
+
server_debug("failed to connect to %s: %O", key, err);
|
|
1107
1170
|
this.#deviceConnections.set(key, conn);
|
|
1108
1171
|
conn.dispose().catch((disposeError)=>{
|
|
1109
|
-
server_debug(
|
|
1172
|
+
server_debug("failed to dispose device connection %s after setup failure: %O", key, disposeError);
|
|
1110
1173
|
});
|
|
1111
1174
|
throw err;
|
|
1112
1175
|
} finally{
|
|
@@ -1121,22 +1184,22 @@ class DevtoolDaemon {
|
|
|
1121
1184
|
}
|
|
1122
1185
|
#scheduleDeviceConnectionCleanup(conn) {
|
|
1123
1186
|
const { key } = conn;
|
|
1124
|
-
if (this.#deviceConnections.get(key) !== conn) return void server_debug(
|
|
1187
|
+
if (this.#deviceConnections.get(key) !== conn) return void server_debug("skipping cleanup for stale connection %s", key);
|
|
1125
1188
|
if (conn.isPersistent) {
|
|
1126
1189
|
this.#clearDeviceConnectionCleanup(key);
|
|
1127
|
-
server_debug(
|
|
1190
|
+
server_debug("skipping cleanup for persistent connection %s", key);
|
|
1128
1191
|
return;
|
|
1129
1192
|
}
|
|
1130
|
-
server_debug(
|
|
1193
|
+
server_debug("scheduling cleanup for %s in %dms", key, DEVICE_CONN_GRACE_MS);
|
|
1131
1194
|
this.#clearDeviceConnectionCleanup(key);
|
|
1132
1195
|
const timer = setTimeout(()=>{
|
|
1133
1196
|
this.#deviceConnectionCleanupTimers.delete(key);
|
|
1134
1197
|
if (this.#deviceConnections.get(key) === conn && 0 === conn.subscriberCount) {
|
|
1135
|
-
server_debug(
|
|
1198
|
+
server_debug("disposing idle device connection %s", key);
|
|
1136
1199
|
conn.dispose().then(()=>{
|
|
1137
1200
|
if (this.#deviceConnections.get(key) === conn) this.#deviceConnections.delete(key);
|
|
1138
1201
|
}, (err)=>{
|
|
1139
|
-
server_debug(
|
|
1202
|
+
server_debug("failed to retire idle device connection %s: %O", key, err);
|
|
1140
1203
|
});
|
|
1141
1204
|
}
|
|
1142
1205
|
}, DEVICE_CONN_GRACE_MS);
|
|
@@ -1158,10 +1221,10 @@ class DevtoolDaemon {
|
|
|
1158
1221
|
#resetIdleTimer() {
|
|
1159
1222
|
this.#clearIdleTimer();
|
|
1160
1223
|
if (0 === this.#wsClients.size && 0 === this.#activeCommandRequests && !this.#closed) {
|
|
1161
|
-
server_debug(
|
|
1224
|
+
server_debug("no clients connected, starting idle timer (%dms)", this.#idleTimeoutMs);
|
|
1162
1225
|
this.#idleTimer = setTimeout(()=>{
|
|
1163
1226
|
if (0 === this.#wsClients.size && 0 === this.#activeCommandRequests) {
|
|
1164
|
-
server_debug(
|
|
1227
|
+
server_debug("idle timeout reached, shutting down daemon");
|
|
1165
1228
|
this.#onIdle?.();
|
|
1166
1229
|
}
|
|
1167
1230
|
}, this.#idleTimeoutMs);
|
|
@@ -1184,18 +1247,18 @@ async function withAbortSignal(promise, signal) {
|
|
|
1184
1247
|
signal.throwIfAborted();
|
|
1185
1248
|
return await new Promise((resolve, reject)=>{
|
|
1186
1249
|
const abortHandler = ()=>{
|
|
1187
|
-
reject(signal.reason ?? new Error(
|
|
1250
|
+
reject(signal.reason ?? new Error("The operation was aborted"));
|
|
1188
1251
|
};
|
|
1189
|
-
signal.addEventListener(
|
|
1252
|
+
signal.addEventListener("abort", abortHandler, {
|
|
1190
1253
|
once: true
|
|
1191
1254
|
});
|
|
1192
1255
|
promise.then((value)=>{
|
|
1193
|
-
signal.removeEventListener(
|
|
1256
|
+
signal.removeEventListener("abort", abortHandler);
|
|
1194
1257
|
resolve(value);
|
|
1195
1258
|
}, (error)=>{
|
|
1196
|
-
signal.removeEventListener(
|
|
1259
|
+
signal.removeEventListener("abort", abortHandler);
|
|
1197
1260
|
reject(error);
|
|
1198
1261
|
});
|
|
1199
1262
|
});
|
|
1200
1263
|
}
|
|
1201
|
-
export { DevtoolDaemon };
|
|
1264
|
+
export { DeviceConnection, DevtoolDaemon, HDT_RES_PATH_PREFIX, InspectorAssets, StaticServer, TarballCache };
|