@lynx-js/devtool-connector 0.9.5 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +1 -1
  2. package/dist/346.js +635 -0
  3. package/dist/390.js +262 -35
  4. package/dist/556.js +9 -4
  5. package/dist/61.js +3432 -0
  6. package/dist/63.js +112 -30
  7. package/dist/712.js +28 -2
  8. package/dist/872.js +552 -122
  9. package/dist/962.js +25 -17
  10. package/dist/client-discovery-errors.d.ts +1 -0
  11. package/dist/client-id.d.ts +9 -2
  12. package/dist/command/client.d.ts +28 -0
  13. package/dist/command/contract.d.ts +255 -0
  14. package/dist/command/core.d.ts +32 -0
  15. package/dist/command/index.d.ts +20 -0
  16. package/dist/command/index.js +224 -0
  17. package/dist/command/query.d.ts +5 -0
  18. package/dist/command/reactlynx/controller.d.ts +71 -0
  19. package/dist/command/reactlynx/model.d.ts +48 -0
  20. package/dist/command/reactlynx/protocol.d.ts +40 -0
  21. package/dist/command/reactlynx/session.d.ts +43 -0
  22. package/dist/command/reactlynx/types.d.ts +73 -0
  23. package/dist/command/ref-actions.d.ts +17 -0
  24. package/dist/command/result.d.ts +29 -0
  25. package/dist/command/screenshot-annotation.d.ts +22 -0
  26. package/dist/command/screenshot.d.ts +28 -0
  27. package/dist/command/snapshot.d.ts +79 -0
  28. package/dist/command/targets.d.ts +15 -0
  29. package/dist/daemon/device-connection.d.ts +3 -1
  30. package/dist/daemon/entry.js +11 -0
  31. package/dist/daemon/index.d.ts +1 -0
  32. package/dist/daemon/index.js +3 -0
  33. package/dist/daemon/manager.d.ts +11 -9
  34. package/dist/daemon/protocol.d.ts +24 -3
  35. package/dist/daemon/server.d.ts +1 -0
  36. package/dist/index.d.ts +6 -2
  37. package/dist/index.js +2 -454
  38. package/dist/streams/customized.d.ts +2 -1
  39. package/dist/transport/android.d.ts +1 -1
  40. package/dist/transport/desktop.d.ts +1 -1
  41. package/dist/transport/index.js +2 -2
  42. package/dist/transport/ios.d.ts +1 -1
  43. package/dist/transport/transport.d.ts +7 -1
  44. package/dist/transport/ws-stream.d.ts +9 -0
  45. package/dist/types.d.ts +35 -0
  46. package/package.json +10 -2
  47. package/dist/187.js +0 -272
  48. package/dist/43.js +0 -20
  49. package/dist/677.js +0 -19
package/dist/390.js CHANGED
@@ -1,44 +1,159 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { closeSync, openSync } from "node:fs";
3
3
  import promises from "node:fs/promises";
4
+ import node_http from "node:http";
4
5
  import { createRequire } from "node:module";
5
6
  import node_net from "node:net";
6
7
  import node_os from "node:os";
7
8
  import node_path from "node:path";
8
9
  import { setTimeout as promises_setTimeout } from "node:timers/promises";
9
- import { DAEMON_WS_PATH, node_createDebug } from "./187.js";
10
- const debug = node_createDebug('devtool-mcp-server:daemon:manager');
10
+ import { createDebug } from "obug";
11
+ import { gt, valid } from "semver";
12
+ const DAEMON_PRODUCT = '@lynx-js/devtool-connector';
13
+ function isCustomizedMessage(msg) {
14
+ return 'object' == typeof msg && null !== msg && 'Customized' === msg.event;
15
+ }
16
+ function isControlRequest(msg) {
17
+ return 'object' == typeof msg && null !== msg && 'Control' === msg.event;
18
+ }
19
+ function isListClientsRequest(msg) {
20
+ return 'object' == typeof msg && null !== msg && 'ListClients' === msg.event;
21
+ }
22
+ function isPingEvent(msg) {
23
+ return 'object' == typeof msg && null !== msg && 'Ping' === msg.event;
24
+ }
25
+ function isRegisterEvent(msg) {
26
+ return 'object' == typeof msg && null !== msg && 'Register' === msg.event;
27
+ }
28
+ const DAEMON_WS_PATH = '/devtool/connector';
29
+ const DAEMON_VERSION_PATH = `${DAEMON_WS_PATH}/version`;
30
+ const DAEMON_SHUTDOWN_PATH = `${DAEMON_WS_PATH}/shutdown`;
31
+ const DAEMON_INSPECTOR_PATH = `${DAEMON_WS_PATH}/inspector`;
32
+ const DAEMON_COMMAND_PATH_PREFIX = '/command/';
33
+ var package_namespaceObject = {
34
+ rE: "0.13.1"
35
+ };
36
+ const CONNECTOR_VERSION = package_namespaceObject.rE;
37
+ const debug = createDebug('devtool-mcp-server:daemon:manager');
11
38
  const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), '.DebugRouterConnector');
12
- const PIDFILE = node_path.join(DEBUG_ROUTER_DIR, 'daemon.pid');
13
39
  const LOG = node_path.join(DEBUG_ROUTER_DIR, 'daemon.log');
14
40
  const ERR = node_path.join(DEBUG_ROUTER_DIR, 'daemon.err');
41
+ const MAX_LIFECYCLE_TRANSITIONS = 8;
42
+ const DIRECT_TRANSPORT_ENVIRONMENT_VARIABLES = [
43
+ 'ADB_SERVER_HOST',
44
+ 'ADB_SERVER_PORT'
45
+ ];
46
+ function createDaemonProcessEnvironment(env) {
47
+ const daemonEnvironment = {
48
+ ...env,
49
+ DEBUG: env['DEBUG'] ?? ''
50
+ };
51
+ for (const name of DIRECT_TRANSPORT_ENVIRONMENT_VARIABLES)delete daemonEnvironment[name];
52
+ return daemonEnvironment;
53
+ }
54
+ class DaemonLifecycleError extends Error {
55
+ code = 'ERR_DAEMON_LIFECYCLE';
56
+ constructor(message, options){
57
+ super(message, options);
58
+ this.name = 'DaemonLifecycleError';
59
+ }
60
+ }
61
+ function isDaemonLifecycleError(error) {
62
+ if (error instanceof DaemonLifecycleError) return true;
63
+ return 'object' == typeof error && null !== error && 'code' in error && 'ERR_DAEMON_LIFECYCLE' === error.code;
64
+ }
15
65
  function resolveDaemonEntryPath(moduleUrl = import.meta.url) {
16
66
  return createRequire(moduleUrl).resolve('#daemon-entry');
17
67
  }
18
68
  class DaemonManager {
19
- static async ensureRunning(port = 21783) {
69
+ static #ensureTasks = new Map();
70
+ static ensureRunning(port = 21783, options = {}) {
71
+ debug('ensuring daemon on port %d (commandProtocol requested: %o)', port, options.commandProtocol ?? false);
72
+ const existing = DaemonManager.#ensureTasks.get(port);
73
+ if (existing) return existing;
74
+ const task = DaemonManager.#ensureCompatibleDaemon(port);
75
+ DaemonManager.#ensureTasks.set(port, task);
76
+ return task.finally(()=>{
77
+ if (DaemonManager.#ensureTasks.get(port) === task) DaemonManager.#ensureTasks.delete(port);
78
+ });
79
+ }
80
+ static async kill(port = 21783) {
81
+ const probe = await DaemonManager.#probe(port);
82
+ if ('daemon' !== probe.kind) throw new Error(`Refusing to stop the unknown process listening on port ${port}.`);
83
+ const result = await DaemonManager.#requestShutdown(port, probe.metadata);
84
+ if ('conflict' === result) throw new DaemonLifecycleError(`Connector daemon on port ${port} changed before it could be stopped. Retry against the current instance.`);
85
+ if ('accepted' !== result) throw new Error(`Connector daemon on port ${port} refused the shutdown request.`);
86
+ if (!await DaemonManager.#waitForInstanceChange(port, probe.metadata, 3000)) throw new DaemonLifecycleError(`Connector daemon ${DaemonManager.#describe(probe.metadata)} did not stop within 3000ms.`);
87
+ }
88
+ static async #ensureCompatibleDaemon(port) {
20
89
  const url = `ws://127.0.0.1:${port}${DAEMON_WS_PATH}`;
21
- if (await DaemonManager.#isAlive(port)) {
22
- debug('daemon already running on port %d', port);
23
- return url;
24
- }
25
- debug('daemon not running, spawning...');
26
- await DaemonManager.#spawn(port);
27
- await DaemonManager.#waitReady(port, 5000);
28
- debug('daemon is ready on port %d', port);
29
- return url;
30
- }
31
- static async kill() {
32
- try {
33
- const pidStr = await promises.readFile(PIDFILE, 'utf-8');
34
- const pid = Number.parseInt(pidStr.trim(), 10);
35
- if (!Number.isNaN(pid)) {
36
- debug('killing daemon pid %d', pid);
37
- process.kill(pid, 'SIGTERM');
90
+ for(let transition = 0; transition < MAX_LIFECYCLE_TRANSITIONS; transition += 1){
91
+ const probe = await DaemonManager.#probe(port);
92
+ if ('unknown' === probe.kind) throw new DaemonLifecycleError(`Port ${port} is occupied by an unknown process. Stop it or choose another port, then retry.`);
93
+ if ('absent' === probe.kind) {
94
+ debug('daemon not running on port %d, spawning', port);
95
+ await DaemonManager.#spawn(port);
96
+ const started = await DaemonManager.#waitReady(port, 5000);
97
+ if ('daemon' === started.kind && DaemonManager.#isCompatible(started.metadata)) {
98
+ debug('daemon is ready on port %d: %O', port, started.metadata);
99
+ return url;
100
+ }
101
+ if ('unknown' === started.kind) throw new DaemonLifecycleError(`Port ${port} was claimed by an unknown process while the connector daemon was starting.`);
102
+ if ('absent' === started.kind) throw new DaemonLifecycleError(`Daemon failed to start within 5000ms on port ${port}.`);
103
+ continue;
104
+ }
105
+ if (DaemonManager.#isCompatible(probe.metadata)) {
106
+ debug('compatible daemon already running on port %d: %O', port, probe.metadata);
107
+ return url;
108
+ }
109
+ DaemonManager.#assertSafeUpgrade(probe.metadata, port);
110
+ debug('stopping incompatible daemon on port %d: %O', port, probe.metadata);
111
+ const shutdown = await DaemonManager.#requestShutdown(port, probe.metadata);
112
+ if ('conflict' === shutdown) {
113
+ debug('daemon changed before shutdown on port %d; probing the winner', port);
114
+ continue;
38
115
  }
39
- } catch {
40
- debug('no pidfile found or cannot read it');
116
+ if ('accepted' !== shutdown) {
117
+ if (await DaemonManager.#waitForInstanceChange(port, probe.metadata, 3000)) {
118
+ debug('daemon changed after a competing shutdown on port %d; probing the winner', port);
119
+ continue;
120
+ }
121
+ throw new DaemonLifecycleError(`Connector daemon ${DaemonManager.#describe(probe.metadata)} on port ${port} refused a safe restart.`);
122
+ }
123
+ if (!await DaemonManager.#waitForInstanceChange(port, probe.metadata, 3000)) throw new DaemonLifecycleError(`Connector daemon ${DaemonManager.#describe(probe.metadata)} on port ${port} did not stop within 3000ms.`);
41
124
  }
125
+ throw new DaemonLifecycleError(`Connector daemon on port ${port} changed too many times while selecting a compatible instance.`);
126
+ }
127
+ static #isCompatible(metadata) {
128
+ return metadata.product === DAEMON_PRODUCT && metadata.version === CONNECTOR_VERSION && 1 === metadata.lifecycleProtocol && 1 === metadata.commandProtocol && 'string' == typeof metadata.instanceId && '' !== metadata.instanceId;
129
+ }
130
+ static #assertSafeUpgrade(metadata, port) {
131
+ if (void 0 !== metadata.product && metadata.product !== DAEMON_PRODUCT) throw new DaemonLifecycleError(`Port ${port} reports daemon product ${JSON.stringify(metadata.product)} instead of ${DAEMON_PRODUCT}. Refusing to replace it.`);
132
+ if (metadata.version === CONNECTOR_VERSION) return;
133
+ const runningVersion = valid(metadata.version);
134
+ const callerVersion = valid(CONNECTOR_VERSION);
135
+ if (!runningVersion || !callerVersion) throw new DaemonLifecycleError(`Cannot safely compare connector daemon version ${JSON.stringify(metadata.version)} with caller version ${JSON.stringify(CONNECTOR_VERSION)} on port ${port}.`);
136
+ if (gt(runningVersion, callerVersion)) throw new DaemonLifecycleError(`Connector daemon ${runningVersion} on port ${port} is newer than caller ${callerVersion}. Upgrade the caller instead of downgrading the daemon.`);
137
+ }
138
+ static async #probe(port) {
139
+ const firstMetadata = await DaemonManager.#getMetadata(port);
140
+ if (firstMetadata) return {
141
+ kind: 'daemon',
142
+ metadata: firstMetadata
143
+ };
144
+ if (!await DaemonManager.#isAlive(port)) return {
145
+ kind: 'absent'
146
+ };
147
+ const secondMetadata = await DaemonManager.#getMetadata(port);
148
+ if (secondMetadata) return {
149
+ kind: 'daemon',
150
+ metadata: secondMetadata
151
+ };
152
+ return await DaemonManager.#isAlive(port) ? {
153
+ kind: 'unknown'
154
+ } : {
155
+ kind: 'absent'
156
+ };
42
157
  }
43
158
  static async #isAlive(port) {
44
159
  return new Promise((resolve)=>{
@@ -59,6 +174,116 @@ class DaemonManager {
59
174
  });
60
175
  });
61
176
  }
177
+ static #getMetadata(port) {
178
+ return new Promise((resolve)=>{
179
+ let settled = false;
180
+ const finish = (value)=>{
181
+ if (settled) return;
182
+ settled = true;
183
+ resolve(value);
184
+ };
185
+ const request = node_http.get({
186
+ headers: {
187
+ connection: 'close'
188
+ },
189
+ host: '127.0.0.1',
190
+ path: DAEMON_VERSION_PATH,
191
+ port,
192
+ timeout: 1000
193
+ }, (response)=>{
194
+ let body = '';
195
+ response.setEncoding('utf8');
196
+ response.on('data', (chunk)=>{
197
+ if (body.length < 16384) body += chunk;
198
+ });
199
+ response.on('aborted', ()=>finish(null));
200
+ response.on('error', ()=>finish(null));
201
+ response.on('end', ()=>{
202
+ if (200 !== response.statusCode) return void finish(null);
203
+ try {
204
+ finish(DaemonManager.#parseMetadata(JSON.parse(body)));
205
+ } catch {
206
+ finish(null);
207
+ }
208
+ });
209
+ });
210
+ request.on('timeout', ()=>{
211
+ finish(null);
212
+ request.destroy();
213
+ });
214
+ request.on('error', ()=>finish(null));
215
+ });
216
+ }
217
+ static #parseMetadata(value) {
218
+ if ('object' != typeof value || null === value || Array.isArray(value)) return null;
219
+ const record = value;
220
+ if ('string' != typeof record['version'] || '' === record['version']) return null;
221
+ const metadata = {
222
+ version: record['version']
223
+ };
224
+ if ('string' == typeof record['product']) metadata.product = record['product'];
225
+ if ('number' == typeof record['lifecycleProtocol']) metadata.lifecycleProtocol = record['lifecycleProtocol'];
226
+ if ('number' == typeof record['commandProtocol']) metadata.commandProtocol = record['commandProtocol'];
227
+ if ('string' == typeof record['instanceId']) metadata.instanceId = record['instanceId'];
228
+ if ('number' == typeof record['startedAt']) metadata.startedAt = record['startedAt'];
229
+ return metadata;
230
+ }
231
+ static #requestShutdown(port, metadata) {
232
+ return new Promise((resolve)=>{
233
+ let settled = false;
234
+ const finish = (result)=>{
235
+ if (settled) return;
236
+ settled = true;
237
+ resolve(result);
238
+ };
239
+ const shutdownRequest = void 0 === metadata.instanceId ? void 0 : {
240
+ expectedInstanceId: metadata.instanceId
241
+ };
242
+ const body = void 0 === shutdownRequest ? void 0 : JSON.stringify(shutdownRequest);
243
+ const request = node_http.request({
244
+ headers: void 0 === body ? {
245
+ connection: 'close'
246
+ } : {
247
+ connection: 'close',
248
+ 'content-length': Buffer.byteLength(body),
249
+ 'content-type': 'application/json'
250
+ },
251
+ host: '127.0.0.1',
252
+ method: 'POST',
253
+ path: DAEMON_SHUTDOWN_PATH,
254
+ port,
255
+ timeout: 1000
256
+ }, (response)=>{
257
+ response.resume();
258
+ response.on('aborted', ()=>finish('refused'));
259
+ response.on('error', ()=>finish('refused'));
260
+ response.on('end', ()=>{
261
+ if (202 === response.statusCode) finish('accepted');
262
+ else 409 === response.statusCode ? finish('conflict') : finish('refused');
263
+ });
264
+ });
265
+ request.on('timeout', ()=>{
266
+ finish('refused');
267
+ request.destroy();
268
+ });
269
+ request.on('error', ()=>finish('refused'));
270
+ request.end(body);
271
+ });
272
+ }
273
+ static async #waitForInstanceChange(port, previous, timeoutMs) {
274
+ const deadline = Date.now() + timeoutMs;
275
+ while(Date.now() < deadline){
276
+ const current = await DaemonManager.#probe(port);
277
+ if ('absent' === current.kind) return true;
278
+ if ('daemon' === current.kind && !DaemonManager.#isSameInstance(previous, current.metadata)) return true;
279
+ await promises_setTimeout(100);
280
+ }
281
+ return false;
282
+ }
283
+ static #isSameInstance(left, right) {
284
+ if (void 0 !== left.instanceId) return left.instanceId === right.instanceId;
285
+ return void 0 === right.instanceId && left.product === right.product && left.version === right.version;
286
+ }
62
287
  static async #spawn(port) {
63
288
  await promises.mkdir(DEBUG_ROUTER_DIR, {
64
289
  recursive: true
@@ -77,26 +302,28 @@ class DaemonManager {
77
302
  out,
78
303
  err
79
304
  ],
80
- env: {
81
- ...process.env,
82
- DEBUG: process.env['DEBUG'] ?? ''
83
- }
305
+ env: createDaemonProcessEnvironment(process.env)
84
306
  });
85
307
  closeSync(out);
86
308
  closeSync(err);
87
309
  child.unref();
88
- if (void 0 !== child.pid) {
89
- await promises.writeFile(PIDFILE, String(child.pid), 'utf-8');
90
- debug('spawned daemon with pid %d', child.pid);
91
- }
310
+ debug('spawned daemon candidate with pid %d', child.pid);
92
311
  }
93
312
  static async #waitReady(port, timeoutMs) {
94
313
  const deadline = Date.now() + timeoutMs;
314
+ let lastProbe = {
315
+ kind: 'absent'
316
+ };
95
317
  while(Date.now() < deadline){
96
- if (await DaemonManager.#isAlive(port)) return;
97
- await promises_setTimeout(200);
318
+ lastProbe = await DaemonManager.#probe(port);
319
+ if ('daemon' === lastProbe.kind) break;
320
+ await promises_setTimeout(100);
98
321
  }
99
- throw new Error(`Daemon failed to start within ${timeoutMs}ms on port ${port}`);
322
+ return lastProbe;
323
+ }
324
+ static #describe(metadata) {
325
+ const instance = metadata.instanceId ? ` instance ${metadata.instanceId}` : ' legacy instance';
326
+ return `${metadata.version}${instance}`;
100
327
  }
101
328
  }
102
- export { DaemonManager };
329
+ export { CONNECTOR_VERSION, DAEMON_COMMAND_PATH_PREFIX, DAEMON_INSPECTOR_PATH, DAEMON_PRODUCT, DAEMON_SHUTDOWN_PATH, DAEMON_VERSION_PATH, DAEMON_WS_PATH, DaemonLifecycleError, DaemonManager, isControlRequest, isCustomizedMessage, isDaemonLifecycleError, isListClientsRequest, isPingEvent, isRegisterEvent };
package/dist/556.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { randomInt } from "node:crypto";
2
2
  import { TransformStream, WritableStream } from "node:stream/web";
3
+ import { createDebug } from "obug";
3
4
  import { DaemonManager } from "./390.js";
4
- import { node_createDebug } from "./187.js";
5
- const debug = node_createDebug('devtool-mcp-server:daemon:transport');
5
+ const debug = createDebug('devtool-mcp-server:daemon:transport');
6
6
  class DaemonTransport {
7
7
  #port;
8
8
  constructor(port = 21783){
@@ -117,8 +117,13 @@ class DaemonTransport {
117
117
  try {
118
118
  const { readable, writable } = await this.#withAbortSignal(wss.opened, signal);
119
119
  const reader = readable.getReader();
120
- const { value, done } = await reader.read();
121
- reader.releaseLock();
120
+ const { value, done } = await (async ()=>{
121
+ try {
122
+ return await reader.read();
123
+ } finally{
124
+ reader.releaseLock();
125
+ }
126
+ })();
122
127
  if (done) throw new Error('WebSocket closed before initialization.');
123
128
  const initMsg = JSON.parse(value);
124
129
  if ('Initialize' !== initMsg.event) throw new Error(`Expected Initialize, got ${initMsg.event}`);