@lynx-js/devtool-connector 0.19.1 → 0.20.0
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 +36 -0
- package/dist/2.js +170 -170
- package/dist/a.js +9301 -566
- package/dist/az.js +691 -0
- package/dist/command/index.js +1 -1
- package/dist/command/reactlynx/controller.d.ts +1 -1
- package/dist/command/reactlynx/session.d.ts +3 -0
- package/dist/daemon/entry.js +5 -3
- package/dist/daemon/index.js +1 -1
- package/dist/f.js +217 -109
- package/dist/f1.js +214 -140
- package/dist/h.js +147 -9431
- package/dist/h6.js +603 -0
- package/dist/index.d.ts +7 -6
- package/dist/index.js +3 -3
- package/dist/main.js +1 -1
- package/dist/rslib-runtime.js +11 -13
- package/dist/streams/cdp.d.ts +1 -1
- package/dist/streams/customized.d.ts +1 -1
- package/dist/streams/index.js +1 -1
- package/dist/t.js +2473 -1276
- package/dist/transport/android.d.ts +3 -3
- package/dist/transport/daemon.d.ts +3 -3
- package/dist/transport/hdt.d.ts +15 -0
- package/dist/transport/index.d.ts +1 -0
- package/dist/transport/index.js +3 -2
- package/dist/transport/ios.d.ts +3 -3
- package/dist/transport/simulator.d.ts +62 -0
- package/dist/transport/transport.d.ts +14 -3
- package/dist/tw.js +1405 -0
- package/dist/types.d.ts +6 -4
- package/dist/ws-stream.js +3 -3
- package/package.json +9 -7
- 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/az.js
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
import { ReadableStream } from "node:stream/web";
|
|
2
|
+
import { isGetGlobalSwitchResponse, isInitializeResponse, AppResponseTransformStream, GlobalSwitchRequestTransformStream, isListSessionResponse, createCorrelatedFilter, isSetGlobalSwitchResponse, CDPResponseTransformStream, CDPOutputTransformStream, CustomizedResponseTransformStream, CDPRequestTransformStream, CustomizedRequestTransformStream, SessionGuardTransformStream, FilterTransformStream, InspectStream, CustomizedClientIdTransformStream } from "./h.js";
|
|
3
|
+
import { ansi_createDebug, isDaemonLifecycleError } from "./2.js";
|
|
4
|
+
import { nextRequestId } from "./3.js";
|
|
5
|
+
import { DaemonTransport, HDTTransport, ClientId, withTransports } from "./f1.js";
|
|
6
|
+
function throwClientDiscoveryFailures(failures) {
|
|
7
|
+
if (1 === failures.length) throw failures[0];
|
|
8
|
+
const details = failures.map((failure)=>failure instanceof Error ? failure.message : String(failure)).join("; ");
|
|
9
|
+
throw new AggregateError(failures, `All client discovery transports failed: ${details}`);
|
|
10
|
+
}
|
|
11
|
+
function _ts_add_disposable_resource(env, value, async) {
|
|
12
|
+
if (null != value) {
|
|
13
|
+
if ("object" != typeof value && "function" != typeof value) throw new TypeError("Object expected.");
|
|
14
|
+
var dispose, inner;
|
|
15
|
+
if (async) {
|
|
16
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
17
|
+
dispose = value[Symbol.asyncDispose];
|
|
18
|
+
}
|
|
19
|
+
if (void 0 === dispose) {
|
|
20
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
21
|
+
dispose = value[Symbol.dispose];
|
|
22
|
+
if (async) inner = dispose;
|
|
23
|
+
}
|
|
24
|
+
if ("function" != typeof dispose) throw new TypeError("Object not disposable.");
|
|
25
|
+
if (inner) dispose = function() {
|
|
26
|
+
try {
|
|
27
|
+
inner.call(this);
|
|
28
|
+
} catch (e) {
|
|
29
|
+
return Promise.reject(e);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
env.stack.push({
|
|
33
|
+
value: value,
|
|
34
|
+
dispose: dispose,
|
|
35
|
+
async: async
|
|
36
|
+
});
|
|
37
|
+
} else if (async) env.stack.push({
|
|
38
|
+
async: true
|
|
39
|
+
});
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function _ts_dispose_resources(env) {
|
|
43
|
+
function fail(e) {
|
|
44
|
+
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
45
|
+
env.hasError = true;
|
|
46
|
+
}
|
|
47
|
+
var r, s = 0;
|
|
48
|
+
function next() {
|
|
49
|
+
while(r = env.stack.pop())try {
|
|
50
|
+
if (!r.async && 1 === s) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
51
|
+
if (r.dispose) {
|
|
52
|
+
var result = r.dispose.call(r.value);
|
|
53
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
54
|
+
fail(e);
|
|
55
|
+
return next();
|
|
56
|
+
});
|
|
57
|
+
} else s |= 1;
|
|
58
|
+
} catch (e) {
|
|
59
|
+
fail(e);
|
|
60
|
+
}
|
|
61
|
+
if (1 === s) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
62
|
+
if (env.hasError) throw env.error;
|
|
63
|
+
}
|
|
64
|
+
return next();
|
|
65
|
+
}
|
|
66
|
+
const debug = ansi_createDebug("devtool-mcp-server:connector");
|
|
67
|
+
const openAppClientWaitTimeoutMs = 55000;
|
|
68
|
+
const clientSetupSwitches = [
|
|
69
|
+
{
|
|
70
|
+
key: "enable_devtool",
|
|
71
|
+
value: true,
|
|
72
|
+
required: true
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
key: "enable_quickjs_debug",
|
|
76
|
+
value: true,
|
|
77
|
+
required: true
|
|
78
|
+
}
|
|
79
|
+
];
|
|
80
|
+
function hasClientList(transport) {
|
|
81
|
+
return "function" == typeof transport.listClients;
|
|
82
|
+
}
|
|
83
|
+
function describeRequest(input) {
|
|
84
|
+
if ("object" != typeof input || null === input) return "request";
|
|
85
|
+
const message = input;
|
|
86
|
+
if ("string" == typeof message["method"]) return `method ${message["method"]}`;
|
|
87
|
+
if ("string" != typeof message["event"]) return "request";
|
|
88
|
+
const data = "object" == typeof message["data"] && null !== message["data"] ? message["data"] : void 0;
|
|
89
|
+
if ("string" == typeof data?.["type"]) return `${message["event"]} ${data["type"]}`;
|
|
90
|
+
return `${message["event"]} event`;
|
|
91
|
+
}
|
|
92
|
+
function isNonEmptyListSessionResponse(response) {
|
|
93
|
+
return isListSessionResponse(response) && response.data.data.length > 0;
|
|
94
|
+
}
|
|
95
|
+
function attachAbortSignalToStream(stream, signal, onAborted) {
|
|
96
|
+
let reader;
|
|
97
|
+
let cleanup = ()=>{};
|
|
98
|
+
let finished = false;
|
|
99
|
+
return new ReadableStream({
|
|
100
|
+
start (controller) {
|
|
101
|
+
reader = stream.getReader();
|
|
102
|
+
const onAbort = ()=>{
|
|
103
|
+
if (finished) return;
|
|
104
|
+
finished = true;
|
|
105
|
+
cleanup();
|
|
106
|
+
onAborted?.();
|
|
107
|
+
const reason = signal.reason ?? new DOMException("The operation was aborted", "AbortError");
|
|
108
|
+
reader?.cancel(reason).catch(()=>{});
|
|
109
|
+
controller.error(reason);
|
|
110
|
+
};
|
|
111
|
+
cleanup = ()=>signal.removeEventListener("abort", onAbort);
|
|
112
|
+
signal.addEventListener("abort", onAbort, {
|
|
113
|
+
once: true
|
|
114
|
+
});
|
|
115
|
+
if (signal.aborted) onAbort();
|
|
116
|
+
},
|
|
117
|
+
async pull (controller) {
|
|
118
|
+
if (finished || !reader) return;
|
|
119
|
+
try {
|
|
120
|
+
const { value, done } = await reader.read();
|
|
121
|
+
if (finished) return;
|
|
122
|
+
if (done) {
|
|
123
|
+
finished = true;
|
|
124
|
+
cleanup();
|
|
125
|
+
reader.releaseLock();
|
|
126
|
+
controller.close();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
controller.enqueue(value);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (finished) return;
|
|
132
|
+
finished = true;
|
|
133
|
+
cleanup();
|
|
134
|
+
reader.releaseLock();
|
|
135
|
+
controller.error(error);
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
async cancel (reason) {
|
|
139
|
+
finished = true;
|
|
140
|
+
cleanup();
|
|
141
|
+
const activeReader = reader;
|
|
142
|
+
reader = void 0;
|
|
143
|
+
if (!activeReader) return;
|
|
144
|
+
try {
|
|
145
|
+
await activeReader.cancel(reason);
|
|
146
|
+
} finally{
|
|
147
|
+
activeReader.releaseLock();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}, {
|
|
151
|
+
highWaterMark: 0
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
class Connector {
|
|
155
|
+
#transports;
|
|
156
|
+
#hdtTransports;
|
|
157
|
+
#daemonTransports;
|
|
158
|
+
constructor(transports){
|
|
159
|
+
this.#transports = transports;
|
|
160
|
+
this.#hdtTransports = transports.filter((t)=>t instanceof HDTTransport);
|
|
161
|
+
this.#daemonTransports = transports.filter((t)=>t instanceof DaemonTransport);
|
|
162
|
+
}
|
|
163
|
+
async listClients() {
|
|
164
|
+
const discoveryFailures = [];
|
|
165
|
+
const daemonClientResults = await Promise.allSettled(this.#daemonTransports.map(async (transport)=>{
|
|
166
|
+
const clients = await transport.listClients();
|
|
167
|
+
await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
|
|
168
|
+
return clients;
|
|
169
|
+
}));
|
|
170
|
+
const fulfilledDaemonClientResults = daemonClientResults.filter((r)=>"fulfilled" === r.status);
|
|
171
|
+
discoveryFailures.push(...daemonClientResults.filter((r)=>"rejected" === r.status).map((r)=>r.reason));
|
|
172
|
+
const daemonClients = fulfilledDaemonClientResults.flatMap((r)=>r.value);
|
|
173
|
+
if (fulfilledDaemonClientResults.length > 0) {
|
|
174
|
+
debug("Using clients from daemon transport: %o", daemonClients);
|
|
175
|
+
return withTransports(daemonClients, fulfilledDaemonClientResults.flatMap((r)=>r.value.transports ?? [
|
|
176
|
+
"daemon"
|
|
177
|
+
]));
|
|
178
|
+
}
|
|
179
|
+
const daemonLifecycleFailure = daemonClientResults.filter((result)=>"rejected" === result.status).map((result)=>result.reason).find(isDaemonLifecycleError);
|
|
180
|
+
if (daemonLifecycleFailure) throw daemonLifecycleFailure;
|
|
181
|
+
const hdtClientResults = await Promise.allSettled(this.#hdtTransports.map(async (transport)=>{
|
|
182
|
+
const clients = await transport.listClients();
|
|
183
|
+
await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
|
|
184
|
+
return {
|
|
185
|
+
clients,
|
|
186
|
+
id: transport.id
|
|
187
|
+
};
|
|
188
|
+
}));
|
|
189
|
+
const fulfilledHDTClientResults = hdtClientResults.filter((r)=>"fulfilled" === r.status);
|
|
190
|
+
discoveryFailures.push(...hdtClientResults.filter((r)=>"rejected" === r.status).map((r)=>r.reason));
|
|
191
|
+
const hdtClients = fulfilledHDTClientResults.flatMap((r)=>r.value.clients);
|
|
192
|
+
if (fulfilledHDTClientResults.length > 0) {
|
|
193
|
+
debug("Using clients from HDT transport: %o", hdtClients);
|
|
194
|
+
return withTransports(hdtClients, fulfilledHDTClientResults.map((r)=>r.value.id));
|
|
195
|
+
}
|
|
196
|
+
const directTransports = this.#transports.filter((t)=>!(t instanceof DaemonTransport));
|
|
197
|
+
const clientListTransports = directTransports.filter((t)=>!(t instanceof HDTTransport)).filter(hasClientList);
|
|
198
|
+
const deviceProbeTransports = directTransports.filter((t)=>!hasClientList(t));
|
|
199
|
+
const [clientListResults, transportDevices] = await Promise.all([
|
|
200
|
+
Promise.allSettled(clientListTransports.map(async (transport)=>{
|
|
201
|
+
const clients = await transport.listClients();
|
|
202
|
+
await Promise.allSettled(clients.flatMap(({ id })=>this.#setupClient(transport, id)));
|
|
203
|
+
return {
|
|
204
|
+
clients,
|
|
205
|
+
id: transport.id
|
|
206
|
+
};
|
|
207
|
+
})),
|
|
208
|
+
Promise.allSettled(deviceProbeTransports.map(async (transport)=>({
|
|
209
|
+
transport,
|
|
210
|
+
devices: await transport.listDevices()
|
|
211
|
+
})))
|
|
212
|
+
]);
|
|
213
|
+
for (const result of clientListResults)if ("rejected" === result.status) {
|
|
214
|
+
discoveryFailures.push(result.reason);
|
|
215
|
+
debug("listClients: listClients failed on one transport: %O", result.reason);
|
|
216
|
+
}
|
|
217
|
+
for (const result of transportDevices)if ("rejected" === result.status) {
|
|
218
|
+
discoveryFailures.push(result.reason);
|
|
219
|
+
debug("listClients: listDevices failed on one transport: %O", result.reason);
|
|
220
|
+
}
|
|
221
|
+
const fulfilledClientListResults = clientListResults.filter((result)=>"fulfilled" === result.status);
|
|
222
|
+
const fulfilledTransportDevices = transportDevices.filter((result)=>"fulfilled" === result.status);
|
|
223
|
+
if (0 === fulfilledClientListResults.length && 0 === fulfilledTransportDevices.length && discoveryFailures.length > 0) throwClientDiscoveryFailures(discoveryFailures);
|
|
224
|
+
const results = await Promise.allSettled(fulfilledTransportDevices.map((r)=>r.value).flatMap(({ transport, devices })=>devices.flatMap(({ id })=>this.#listClientsForDevice(transport, id))));
|
|
225
|
+
const fulfilledClientResults = results.filter((r)=>"fulfilled" === r.status);
|
|
226
|
+
if (0 === fulfilledClientListResults.length && 0 === fulfilledClientResults.length && results.length > 0) throwClientDiscoveryFailures([
|
|
227
|
+
...discoveryFailures,
|
|
228
|
+
...results.filter((result)=>"rejected" === result.status).map((result)=>result.reason)
|
|
229
|
+
]);
|
|
230
|
+
const fulfilledTransports = [
|
|
231
|
+
...fulfilledClientListResults.map((r)=>r.value.id),
|
|
232
|
+
...fulfilledTransportDevices.map((r)=>r.value.transport.id)
|
|
233
|
+
];
|
|
234
|
+
return withTransports([
|
|
235
|
+
...fulfilledClientListResults.flatMap((r)=>r.value.clients),
|
|
236
|
+
...fulfilledClientResults.flatMap((r)=>r.value)
|
|
237
|
+
], fulfilledTransports.length > 0 ? fulfilledTransports : void 0);
|
|
238
|
+
}
|
|
239
|
+
async listDevices() {
|
|
240
|
+
const results = await Promise.allSettled(this.#transports.map((t)=>t.listDevices()));
|
|
241
|
+
return results.filter((result)=>"fulfilled" === result.status).flatMap(({ value })=>value);
|
|
242
|
+
}
|
|
243
|
+
async listAvailableApps(deviceId, options) {
|
|
244
|
+
const transport = await this.#findTransportWithDeviceId(deviceId, options?.platform);
|
|
245
|
+
return await transport.listAvailableApps(deviceId, options?.platform === void 0 ? void 0 : {
|
|
246
|
+
platform: options.platform
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
async openApp(deviceId, packageName, options) {
|
|
250
|
+
const transport = await this.#findTransportWithDeviceId(deviceId, options?.platform);
|
|
251
|
+
await transport.openApp(deviceId, packageName, options);
|
|
252
|
+
const signal = AbortSignal.any([
|
|
253
|
+
options?.signal,
|
|
254
|
+
AbortSignal.timeout(openAppClientWaitTimeoutMs)
|
|
255
|
+
].filter((i)=>void 0 !== i));
|
|
256
|
+
const { setTimeout } = await import("node:timers/promises");
|
|
257
|
+
while(!signal.aborted){
|
|
258
|
+
try {
|
|
259
|
+
const clients = hasClientList(transport) ? (await transport.listClients()).filter(({ id })=>ClientId.deserialize(id)?.deviceId === deviceId) : await this.#listClientsForDevice(transport, deviceId);
|
|
260
|
+
const appClient = clients.find(({ info })=>info.AppProcessName === packageName || info.bundleId === packageName || info.bundleName === packageName);
|
|
261
|
+
if (void 0 !== appClient) return appClient.id;
|
|
262
|
+
} catch (err) {
|
|
263
|
+
debug(`openApp ${deviceId} ${packageName} client not found %o`, err);
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
await setTimeout(1000, void 0, {
|
|
267
|
+
signal
|
|
268
|
+
});
|
|
269
|
+
} catch {
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
throw new Error(`Timed out waiting for app client ${packageName} on device ${deviceId}.`);
|
|
274
|
+
}
|
|
275
|
+
async sendMessage(clientId, message, pipeline = {
|
|
276
|
+
input: [],
|
|
277
|
+
output: []
|
|
278
|
+
}) {
|
|
279
|
+
return this.#sendMessage(clientId, message, pipeline);
|
|
280
|
+
}
|
|
281
|
+
async sendAppMessage(clientId, method, params) {
|
|
282
|
+
const id = nextRequestId();
|
|
283
|
+
return await this.#sendMessage(clientId, {
|
|
284
|
+
method,
|
|
285
|
+
params: {
|
|
286
|
+
...params
|
|
287
|
+
}
|
|
288
|
+
}, {
|
|
289
|
+
input: [
|
|
290
|
+
new CustomizedRequestTransformStream({
|
|
291
|
+
type: "App",
|
|
292
|
+
sessionId: -1,
|
|
293
|
+
messageBuilder: (message)=>({
|
|
294
|
+
id,
|
|
295
|
+
...message
|
|
296
|
+
})
|
|
297
|
+
})
|
|
298
|
+
],
|
|
299
|
+
output: [
|
|
300
|
+
new CustomizedResponseTransformStream("App", id),
|
|
301
|
+
new AppResponseTransformStream(method)
|
|
302
|
+
]
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
async openPage(clientId, url, signal) {
|
|
306
|
+
return await this.#sendMessage(clientId, {
|
|
307
|
+
event: "Customized",
|
|
308
|
+
data: {
|
|
309
|
+
type: "OpenCard",
|
|
310
|
+
data: {
|
|
311
|
+
type: "url",
|
|
312
|
+
url
|
|
313
|
+
},
|
|
314
|
+
sender: -1
|
|
315
|
+
},
|
|
316
|
+
from: -1
|
|
317
|
+
}, {
|
|
318
|
+
input: [],
|
|
319
|
+
output: [
|
|
320
|
+
new FilterTransformStream(isNonEmptyListSessionResponse)
|
|
321
|
+
]
|
|
322
|
+
}, signal);
|
|
323
|
+
}
|
|
324
|
+
async sendCDPMessage(clientId, sessionId, method, params, isMainThread = false, signal) {
|
|
325
|
+
const id = nextRequestId();
|
|
326
|
+
const SUPPORTED_DOMAIN = [
|
|
327
|
+
"Debugger",
|
|
328
|
+
"Runtime",
|
|
329
|
+
"HeapProfiler",
|
|
330
|
+
"Profiler"
|
|
331
|
+
];
|
|
332
|
+
if (isMainThread && !SUPPORTED_DOMAIN.some((domain)=>method.startsWith(domain + "."))) throw new Error(`Method ${method} is not supported for main thread. Supported domains: ${SUPPORTED_DOMAIN.join(", ")}`);
|
|
333
|
+
return await this.#sendMessage(clientId, {
|
|
334
|
+
method,
|
|
335
|
+
params,
|
|
336
|
+
sessionId: isMainThread ? "Main" : void 0
|
|
337
|
+
}, {
|
|
338
|
+
input: [
|
|
339
|
+
new CDPRequestTransformStream(sessionId, id)
|
|
340
|
+
],
|
|
341
|
+
output: [
|
|
342
|
+
new CDPResponseTransformStream(id, sessionId),
|
|
343
|
+
new CDPOutputTransformStream()
|
|
344
|
+
]
|
|
345
|
+
}, signal);
|
|
346
|
+
}
|
|
347
|
+
async sendListSessionMessage(clientId) {
|
|
348
|
+
return await this.#sendListSessionMessage(clientId);
|
|
349
|
+
}
|
|
350
|
+
async #sendListSessionMessage(clientId) {
|
|
351
|
+
const id = nextRequestId();
|
|
352
|
+
const { data: { data: sessions } } = await this.#sendMessage(clientId, {
|
|
353
|
+
event: "Customized",
|
|
354
|
+
data: {
|
|
355
|
+
type: "ListSession",
|
|
356
|
+
data: {},
|
|
357
|
+
id
|
|
358
|
+
}
|
|
359
|
+
}, {
|
|
360
|
+
input: [],
|
|
361
|
+
output: [
|
|
362
|
+
new FilterTransformStream(createCorrelatedFilter(isListSessionResponse, id))
|
|
363
|
+
]
|
|
364
|
+
});
|
|
365
|
+
return sessions.map((session)=>({
|
|
366
|
+
...session,
|
|
367
|
+
type: "" === session.type ? "lynx" : session.type
|
|
368
|
+
}));
|
|
369
|
+
}
|
|
370
|
+
async getGlobalSwitch(clientId, key) {
|
|
371
|
+
const { data: { data: { message } } } = await this.#sendMessage(clientId, {
|
|
372
|
+
key
|
|
373
|
+
}, {
|
|
374
|
+
input: [
|
|
375
|
+
new GlobalSwitchRequestTransformStream("GetGlobalSwitch")
|
|
376
|
+
],
|
|
377
|
+
output: [
|
|
378
|
+
new FilterTransformStream(isGetGlobalSwitchResponse)
|
|
379
|
+
]
|
|
380
|
+
});
|
|
381
|
+
if ("object" == typeof message) return message?.global_value === "true" || message?.global_value === true;
|
|
382
|
+
else return "true" === message || true === message;
|
|
383
|
+
}
|
|
384
|
+
async setGlobalSwitch(clientId, key, value) {
|
|
385
|
+
await this.#sendMessage(clientId, {
|
|
386
|
+
key,
|
|
387
|
+
value
|
|
388
|
+
}, {
|
|
389
|
+
input: [
|
|
390
|
+
new GlobalSwitchRequestTransformStream("SetGlobalSwitch")
|
|
391
|
+
],
|
|
392
|
+
output: [
|
|
393
|
+
new FilterTransformStream(isSetGlobalSwitchResponse)
|
|
394
|
+
]
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
async sendStream(clientId, inputStream, { signal, pipeline } = {}) {
|
|
398
|
+
const { transportId, deviceId, port } = this.#resolveClientId(clientId);
|
|
399
|
+
const transport = await this.#findTransportWithDeviceId(deviceId, transportId);
|
|
400
|
+
return await this.#connect(transport, {
|
|
401
|
+
transportId,
|
|
402
|
+
deviceId,
|
|
403
|
+
port,
|
|
404
|
+
signal
|
|
405
|
+
}, inputStream, pipeline ?? {
|
|
406
|
+
input: [],
|
|
407
|
+
output: []
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
async sendCDPStream(clientId, sessionId, inputStream, { signal } = {}) {
|
|
411
|
+
return await this.sendStream(clientId, inputStream, {
|
|
412
|
+
signal,
|
|
413
|
+
pipeline: {
|
|
414
|
+
input: [
|
|
415
|
+
new CDPRequestTransformStream(sessionId)
|
|
416
|
+
],
|
|
417
|
+
output: [
|
|
418
|
+
new SessionGuardTransformStream(sessionId),
|
|
419
|
+
new CDPResponseTransformStream(void 0, sessionId)
|
|
420
|
+
]
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
#resolveClientId(clientId) {
|
|
425
|
+
const parsed = ClientId.deserialize(clientId);
|
|
426
|
+
if (!parsed) throw new Error(`Invalid clientId: ${clientId}`);
|
|
427
|
+
return parsed;
|
|
428
|
+
}
|
|
429
|
+
async #findTransportWithDeviceId(deviceId, transportId) {
|
|
430
|
+
const [onlyTransport] = this.#transports;
|
|
431
|
+
if (1 === this.#transports.length && onlyTransport instanceof DaemonTransport) return onlyTransport;
|
|
432
|
+
const daemonTransport = await this.#findTransportWithDeviceIdInPool(this.#daemonTransports, deviceId);
|
|
433
|
+
if (daemonTransport) return daemonTransport;
|
|
434
|
+
const nonDaemonTransports = this.#transports.filter((t)=>!(t instanceof DaemonTransport));
|
|
435
|
+
if (void 0 !== transportId) {
|
|
436
|
+
const matchedById = nonDaemonTransports.find((t)=>t.id === transportId);
|
|
437
|
+
if (matchedById) return matchedById;
|
|
438
|
+
throw new Error(`Transport with id: ${transportId} not found`);
|
|
439
|
+
}
|
|
440
|
+
const transport = await this.#findTransportWithDeviceIdInPool(nonDaemonTransports, deviceId);
|
|
441
|
+
if (transport) return transport;
|
|
442
|
+
throw new Error(`Device with id: ${deviceId} not found`);
|
|
443
|
+
}
|
|
444
|
+
async #findTransportWithDeviceIdInPool(transports, deviceId) {
|
|
445
|
+
try {
|
|
446
|
+
return await Promise.any(transports.map(async (transport)=>{
|
|
447
|
+
const devices = await transport.listDevices();
|
|
448
|
+
if (devices.some(({ id })=>id === deviceId)) return transport;
|
|
449
|
+
throw new Error("Not found in this transport");
|
|
450
|
+
}));
|
|
451
|
+
} catch (error) {
|
|
452
|
+
if (error instanceof AggregateError) {
|
|
453
|
+
const daemonLifecycleFailure = error.errors.find(isDaemonLifecycleError);
|
|
454
|
+
if (daemonLifecycleFailure) throw daemonLifecycleFailure;
|
|
455
|
+
}
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
async #connect(transport, options, inputStream, pipeline) {
|
|
460
|
+
const { deviceId, port } = options;
|
|
461
|
+
const conn = transport instanceof DaemonTransport ? await transport.connect(options) : await transport.connect({
|
|
462
|
+
deviceId,
|
|
463
|
+
port,
|
|
464
|
+
signal: options.signal
|
|
465
|
+
});
|
|
466
|
+
const inputAbortController = new AbortController();
|
|
467
|
+
const inputAbortReason = new Error("Connector input stream disposed");
|
|
468
|
+
const inputSignal = options.signal ? AbortSignal.any([
|
|
469
|
+
inputAbortController.signal,
|
|
470
|
+
options.signal
|
|
471
|
+
]) : inputAbortController.signal;
|
|
472
|
+
const inputClosed = [
|
|
473
|
+
...pipeline.input,
|
|
474
|
+
new CustomizedClientIdTransformStream(port),
|
|
475
|
+
new InspectStream((msg)=>debug(`connect ${deviceId}:${port} input stream send %o`, JSON.stringify(msg)))
|
|
476
|
+
].reduce((stream, transform)=>stream.pipeThrough(transform), inputStream).pipeTo(conn.writable, {
|
|
477
|
+
preventClose: true,
|
|
478
|
+
signal: inputSignal
|
|
479
|
+
}).catch((err)=>{
|
|
480
|
+
if (err === inputAbortReason) return;
|
|
481
|
+
debug(`connect ${deviceId}:${port} input stream err %O`, err);
|
|
482
|
+
throw err;
|
|
483
|
+
});
|
|
484
|
+
const inputSettled = inputClosed.catch(()=>{});
|
|
485
|
+
let connectionDisposePromise;
|
|
486
|
+
const disposeConnection = ()=>{
|
|
487
|
+
connectionDisposePromise ??= Promise.resolve().then(()=>conn[Symbol.asyncDispose]());
|
|
488
|
+
connectionDisposePromise.catch(()=>{});
|
|
489
|
+
return connectionDisposePromise;
|
|
490
|
+
};
|
|
491
|
+
const pipedOutputStream = [
|
|
492
|
+
new InspectStream((msg)=>debug(`connect ${deviceId}:${port} output stream receive %O`, msg)),
|
|
493
|
+
...pipeline.output
|
|
494
|
+
].reduce((stream, transform)=>stream.pipeThrough(transform), conn.readable);
|
|
495
|
+
const outputStream = options.signal ? attachAbortSignalToStream(pipedOutputStream, options.signal, ()=>{
|
|
496
|
+
inputAbortController.abort(inputAbortReason);
|
|
497
|
+
disposeConnection();
|
|
498
|
+
}) : pipedOutputStream;
|
|
499
|
+
return Object.assign(outputStream, {
|
|
500
|
+
inputClosed,
|
|
501
|
+
async [Symbol.asyncDispose] () {
|
|
502
|
+
debug(`connect ${deviceId}:${port} close connection`);
|
|
503
|
+
inputAbortController.abort(inputAbortReason);
|
|
504
|
+
if (!outputStream.locked) outputStream.cancel(inputAbortReason).catch(()=>{});
|
|
505
|
+
const connectionDisposed = disposeConnection();
|
|
506
|
+
await inputSettled;
|
|
507
|
+
return connectionDisposed;
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
async #sendMessage(clientId, input, pipeline = {
|
|
512
|
+
input: [],
|
|
513
|
+
output: []
|
|
514
|
+
}, signal) {
|
|
515
|
+
const { transportId, deviceId, port } = this.#resolveClientId(clientId);
|
|
516
|
+
const transport = await this.#findTransportWithDeviceId(deviceId, transportId);
|
|
517
|
+
return this.#sendMessageWithTransport(transport, {
|
|
518
|
+
transportId,
|
|
519
|
+
deviceId,
|
|
520
|
+
port,
|
|
521
|
+
signal: signal ?? AbortSignal.timeout(10000)
|
|
522
|
+
}, input, pipeline, describeRequest(input));
|
|
523
|
+
}
|
|
524
|
+
async #sendMessageWithTransport(transport, options, input, pipeline, request = "request") {
|
|
525
|
+
const outputStream = await this.#connect(transport, options, ReadableStream.from([
|
|
526
|
+
input
|
|
527
|
+
]), pipeline);
|
|
528
|
+
const reader = outputStream.getReader();
|
|
529
|
+
let failed = false;
|
|
530
|
+
let primaryError;
|
|
531
|
+
let result;
|
|
532
|
+
try {
|
|
533
|
+
const read = reader.read();
|
|
534
|
+
await Promise.race([
|
|
535
|
+
read,
|
|
536
|
+
outputStream.inputClosed
|
|
537
|
+
]);
|
|
538
|
+
const response = await read;
|
|
539
|
+
await outputStream.inputClosed;
|
|
540
|
+
if (response.done) {
|
|
541
|
+
options.signal?.throwIfAborted();
|
|
542
|
+
const clientId = ClientId.serialize(options.transportId, options.deviceId, options.port);
|
|
543
|
+
throw new Error(`Transport ${transport.constructor.name} ended cleanly (EOF) while waiting for a response to ${request} on clientId: ${clientId}.`);
|
|
544
|
+
} else result = response.value;
|
|
545
|
+
} catch (err) {
|
|
546
|
+
failed = true;
|
|
547
|
+
primaryError = err;
|
|
548
|
+
} finally{
|
|
549
|
+
await reader.cancel(primaryError).catch(()=>{});
|
|
550
|
+
reader.releaseLock();
|
|
551
|
+
}
|
|
552
|
+
try {
|
|
553
|
+
await outputStream[Symbol.asyncDispose]();
|
|
554
|
+
} catch (err) {
|
|
555
|
+
if (failed) debug("connection cleanup suppressed after request failure %O", err);
|
|
556
|
+
else {
|
|
557
|
+
failed = true;
|
|
558
|
+
primaryError = err;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
if (failed) throw primaryError;
|
|
562
|
+
return result;
|
|
563
|
+
}
|
|
564
|
+
async #listClientsForDevice(transport, deviceId) {
|
|
565
|
+
const MIN_PORT = 8901;
|
|
566
|
+
const PORTS = Array.from({
|
|
567
|
+
length: 10
|
|
568
|
+
}, (_, i)=>MIN_PORT + i);
|
|
569
|
+
const discoverySignal = AbortSignal.timeout(5000);
|
|
570
|
+
const results = await Promise.allSettled(PORTS.map(async (port)=>{
|
|
571
|
+
const info = await this.#discoverAndSetupClient(transport, deviceId, port, discoverySignal);
|
|
572
|
+
return {
|
|
573
|
+
id: ClientId.serialize(transport.id, deviceId, port),
|
|
574
|
+
info,
|
|
575
|
+
port
|
|
576
|
+
};
|
|
577
|
+
}));
|
|
578
|
+
const clients = results.filter((result)=>"fulfilled" === result.status).map((result)=>result.value);
|
|
579
|
+
if (0 === clients.length) discoverySignal.throwIfAborted();
|
|
580
|
+
return clients;
|
|
581
|
+
}
|
|
582
|
+
async #discoverAndSetupClient(transport, deviceId, port, discoverySignal) {
|
|
583
|
+
const env = {
|
|
584
|
+
stack: [],
|
|
585
|
+
error: void 0,
|
|
586
|
+
hasError: false
|
|
587
|
+
};
|
|
588
|
+
try {
|
|
589
|
+
const lifetime = new AbortController();
|
|
590
|
+
const forwardStageSignal = (signal)=>{
|
|
591
|
+
const abort = ()=>lifetime.abort(signal.reason);
|
|
592
|
+
signal.addEventListener("abort", abort, {
|
|
593
|
+
once: true
|
|
594
|
+
});
|
|
595
|
+
if (signal.aborted) abort();
|
|
596
|
+
try {
|
|
597
|
+
lifetime.signal.throwIfAborted();
|
|
598
|
+
} catch (err) {
|
|
599
|
+
signal.removeEventListener("abort", abort);
|
|
600
|
+
throw err;
|
|
601
|
+
}
|
|
602
|
+
return ()=>signal.removeEventListener("abort", abort);
|
|
603
|
+
};
|
|
604
|
+
const exchange = async (connection, message, predicate, signal)=>{
|
|
605
|
+
const stopForwardingSignal = forwardStageSignal(signal);
|
|
606
|
+
try {
|
|
607
|
+
signal.throwIfAborted();
|
|
608
|
+
const writer = connection.writable.getWriter();
|
|
609
|
+
debug("connect input stream send %o", JSON.stringify(message));
|
|
610
|
+
await writer.write(message).finally(()=>writer.releaseLock());
|
|
611
|
+
signal.throwIfAborted();
|
|
612
|
+
for await (const value of connection.readable.values({
|
|
613
|
+
preventCancel: true
|
|
614
|
+
})){
|
|
615
|
+
signal.throwIfAborted();
|
|
616
|
+
debug("connect output stream receive %O", value);
|
|
617
|
+
if (predicate(value)) return value;
|
|
618
|
+
}
|
|
619
|
+
signal.throwIfAborted();
|
|
620
|
+
throw new Error("Connection closed before receiving the expected response");
|
|
621
|
+
} catch (err) {
|
|
622
|
+
signal.throwIfAborted();
|
|
623
|
+
throw err;
|
|
624
|
+
} finally{
|
|
625
|
+
stopForwardingSignal();
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
const stopForwardingDiscovery = forwardStageSignal(discoverySignal);
|
|
629
|
+
const connection = _ts_add_disposable_resource(env, await transport.connect({
|
|
630
|
+
deviceId,
|
|
631
|
+
port,
|
|
632
|
+
signal: lifetime.signal
|
|
633
|
+
}).finally(stopForwardingDiscovery), true);
|
|
634
|
+
const register = await exchange(connection, {
|
|
635
|
+
event: "Initialize",
|
|
636
|
+
data: port
|
|
637
|
+
}, isInitializeResponse, discoverySignal);
|
|
638
|
+
for (const { key, value, required } of clientSetupSwitches)try {
|
|
639
|
+
await exchange(connection, {
|
|
640
|
+
event: "Customized",
|
|
641
|
+
data: {
|
|
642
|
+
type: "SetGlobalSwitch",
|
|
643
|
+
data: {
|
|
644
|
+
client_id: port,
|
|
645
|
+
session_id: -1,
|
|
646
|
+
message: {
|
|
647
|
+
global_key: key,
|
|
648
|
+
global_value: value
|
|
649
|
+
}
|
|
650
|
+
},
|
|
651
|
+
sender: port
|
|
652
|
+
}
|
|
653
|
+
}, isSetGlobalSwitchResponse, AbortSignal.timeout(3000));
|
|
654
|
+
} catch (err) {
|
|
655
|
+
debug(`setupClient ${deviceId}:${port} ${key} failed %O`, err);
|
|
656
|
+
if (required) throw err;
|
|
657
|
+
}
|
|
658
|
+
return register.data.info;
|
|
659
|
+
} catch (e) {
|
|
660
|
+
env.error = e;
|
|
661
|
+
env.hasError = true;
|
|
662
|
+
} finally{
|
|
663
|
+
const result = _ts_dispose_resources(env);
|
|
664
|
+
if (result) await result;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
async #setupClient(transport, clientId) {
|
|
668
|
+
const { transportId, deviceId, port } = this.#resolveClientId(clientId);
|
|
669
|
+
for (const { key, value } of clientSetupSwitches)try {
|
|
670
|
+
await this.#sendMessageWithTransport(transport, {
|
|
671
|
+
transportId,
|
|
672
|
+
deviceId,
|
|
673
|
+
port,
|
|
674
|
+
signal: AbortSignal.timeout(3000)
|
|
675
|
+
}, {
|
|
676
|
+
key,
|
|
677
|
+
value
|
|
678
|
+
}, {
|
|
679
|
+
input: [
|
|
680
|
+
new GlobalSwitchRequestTransformStream("SetGlobalSwitch")
|
|
681
|
+
],
|
|
682
|
+
output: [
|
|
683
|
+
new FilterTransformStream(isSetGlobalSwitchResponse)
|
|
684
|
+
]
|
|
685
|
+
});
|
|
686
|
+
} catch (err) {
|
|
687
|
+
debug(`setupClient ${deviceId}:${port} ${key} failed %O`, err);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
export { Connector, throwClientDiscoveryFailures };
|