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