@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/dist/h6.js ADDED
@@ -0,0 +1,603 @@
1
+ import { TransformStream, WritableStream } from "node:stream/web";
2
+ import promises, { mkdir, mkdtemp, open as promises_open, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import node_os from "node:os";
4
+ import node_path from "node:path";
5
+ import node_net from "node:net";
6
+ import { Duplex } from "node:stream";
7
+ import { execFile, spawn } from "node:child_process";
8
+ import { createHash } from "node:crypto";
9
+ import { closeSync, existsSync, openSync } from "node:fs";
10
+ import { createRequire } from "node:module";
11
+ import { setTimeout as promises_setTimeout } from "node:timers/promises";
12
+ import { pathToFileURL } from "node:url";
13
+ import { promisify } from "node:util";
14
+ import { ansi_createDebug } from "./2.js";
15
+ import { Platform, ClientId, requireNumericPort } from "./f1.js";
16
+ const debug = ansi_createDebug("devtool-mcp-server:takeover");
17
+ const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), ".DebugRouterConnector");
18
+ const DEBUG_ROUTER_LOCK_DIR = node_path.join(DEBUG_ROUTER_DIR, "lockfile");
19
+ const DEBUG_ROUTER_LATEST_FILE = node_path.join(DEBUG_ROUTER_DIR, "LatestDriverProcess");
20
+ async function takeoverDebugRouterLock() {
21
+ try {
22
+ await promises.mkdir(DEBUG_ROUTER_DIR, {
23
+ recursive: true
24
+ });
25
+ await promises.rm(DEBUG_ROUTER_LOCK_DIR, {
26
+ recursive: true,
27
+ force: true
28
+ });
29
+ await promises.mkdir(DEBUG_ROUTER_LOCK_DIR, {
30
+ recursive: true
31
+ });
32
+ await promises.writeFile(DEBUG_ROUTER_LATEST_FILE, `${process.pid}`, "utf-8");
33
+ debug(`wrote PID=${process.pid}`);
34
+ } catch (err) {
35
+ debug("skipped due to filesystem error %O", err);
36
+ } finally{
37
+ try {
38
+ await promises.rm(DEBUG_ROUTER_LOCK_DIR, {
39
+ recursive: true,
40
+ force: true
41
+ });
42
+ } catch (_cleanupError) {
43
+ debug("failed to remove lock directory %O", _cleanupError);
44
+ }
45
+ }
46
+ }
47
+ class PeertalkToMessageTransformStream extends TransformStream {
48
+ constructor(){
49
+ let buffer = new Uint8Array(0);
50
+ let start = 0;
51
+ let end = 0;
52
+ const decoder = new TextDecoder();
53
+ super({
54
+ transform (chunk, controller) {
55
+ const buffered = end - start;
56
+ if (buffer.length - end < chunk.length) if (buffered + chunk.length <= buffer.length) {
57
+ buffer.copyWithin(0, start, end);
58
+ start = 0;
59
+ end = buffered;
60
+ } else {
61
+ const next = new Uint8Array(Math.max(buffered + chunk.length, Math.max(20, 2 * buffer.length)));
62
+ next.set(buffer.subarray(start, end));
63
+ buffer = next;
64
+ start = 0;
65
+ end = buffered;
66
+ }
67
+ buffer.set(chunk, end);
68
+ end += chunk.length;
69
+ while(end - start >= 20){
70
+ const view = new DataView(buffer.buffer, buffer.byteOffset + start, 20);
71
+ const len = view.getUint32(16);
72
+ if (end - start < 20 + len) break;
73
+ try {
74
+ controller.enqueue(JSON.parse(decoder.decode(buffer.subarray(start + 20, start + 20 + len))));
75
+ } catch (error) {
76
+ controller.error(error);
77
+ return;
78
+ }
79
+ start += 20 + len;
80
+ }
81
+ if (start === end) {
82
+ start = 0;
83
+ end = 0;
84
+ buffer = new Uint8Array(0);
85
+ }
86
+ }
87
+ });
88
+ }
89
+ }
90
+ const encoder = new TextEncoder();
91
+ function encodePeertalkMessage(message) {
92
+ const body = encoder.encode(JSON.stringify(message));
93
+ const len = body.length;
94
+ const data = new Uint8Array(20 + len);
95
+ const view = new DataView(data.buffer);
96
+ view.setUint32(0, 1);
97
+ view.setUint32(4, 101);
98
+ view.setUint32(8, 0);
99
+ view.setUint32(12, len + 4);
100
+ view.setUint32(16, len);
101
+ data.set(body, 20);
102
+ return data;
103
+ }
104
+ async function connectWithPeertalk(connectRaw, options, takeoverHDT = true) {
105
+ if (takeoverHDT) await takeoverDebugRouterLock();
106
+ const conn = await connectRaw(options);
107
+ let rawWriter = conn.writable.getWriter();
108
+ let writing = false;
109
+ let terminationPromise;
110
+ const releaseWriter = ()=>{
111
+ rawWriter?.releaseLock();
112
+ rawWriter = void 0;
113
+ };
114
+ const terminateConnection = (reason, abortIdleWriter = true)=>{
115
+ if (!terminationPromise) {
116
+ const writer = rawWriter;
117
+ const shouldAbort = void 0 !== writer && (abortIdleWriter || writing);
118
+ if (!shouldAbort) releaseWriter();
119
+ const rawAbort = shouldAbort ? writer.abort(reason) : Promise.resolve();
120
+ const dispose = Promise.resolve().then(()=>conn[Symbol.asyncDispose]());
121
+ terminationPromise = rawAbort.then(()=>dispose, async (error)=>{
122
+ await dispose.catch(()=>{});
123
+ throw error;
124
+ }).finally(releaseWriter);
125
+ terminationPromise.catch(()=>{});
126
+ }
127
+ return terminationPromise;
128
+ };
129
+ const writable = new WritableStream({
130
+ async write (message, controller) {
131
+ const signal = controller.signal;
132
+ const abort = ()=>{
133
+ if (writing) terminateConnection(signal.reason).catch(()=>{});
134
+ };
135
+ signal.addEventListener("abort", abort, {
136
+ once: true
137
+ });
138
+ writing = true;
139
+ try {
140
+ await rawWriter.write(encodePeertalkMessage(message));
141
+ } catch (error) {
142
+ terminateConnection(error).catch(()=>{});
143
+ throw error;
144
+ } finally{
145
+ writing = false;
146
+ signal.removeEventListener("abort", abort);
147
+ }
148
+ },
149
+ close: releaseWriter,
150
+ abort (reason) {
151
+ if (!writing) {
152
+ releaseWriter();
153
+ return Promise.resolve();
154
+ }
155
+ return terminateConnection(reason, true);
156
+ }
157
+ });
158
+ const readable = conn.readable.pipeThrough(new PeertalkToMessageTransformStream());
159
+ return {
160
+ readable,
161
+ writable,
162
+ [Symbol.asyncDispose] () {
163
+ return terminateConnection(new Error("Peertalk connection disposed"), false);
164
+ }
165
+ };
166
+ }
167
+ const desktop_debug = ansi_createDebug("devtool-mcp-server:connector:desktop");
168
+ class DesktopTransport {
169
+ id = Platform.Desktop;
170
+ #takeoverHDT;
171
+ constructor(takeoverHDT = true){
172
+ this.#takeoverHDT = takeoverHDT;
173
+ }
174
+ async connect(options) {
175
+ return connectWithPeertalk((opts)=>this.#connectRaw(opts), options, this.#takeoverHDT);
176
+ }
177
+ async close() {
178
+ desktop_debug("Desktop transport closed");
179
+ }
180
+ async listDevices() {
181
+ return [
182
+ {
183
+ id: "localhost",
184
+ os: "Desktop"
185
+ }
186
+ ];
187
+ }
188
+ async listAvailableApps(deviceId) {
189
+ return [];
190
+ }
191
+ async openApp(deviceId, packageName) {
192
+ throw new Error("openApp is not supported on DesktopTransport");
193
+ }
194
+ async #connectRaw({ deviceId, port, signal }) {
195
+ const numericPort = requireNumericPort(port);
196
+ if ("localhost" !== deviceId) throw new Error(`DesktopTransport only supports 'localhost' deviceId, got: ${deviceId}`);
197
+ desktop_debug(`connect: connecting to 127.0.0.1:${numericPort}`);
198
+ signal?.throwIfAborted();
199
+ const socket = node_net.createConnection({
200
+ host: "127.0.0.1",
201
+ port: numericPort
202
+ });
203
+ socket.setNoDelay?.(true);
204
+ const socketClosed = socket.closed ? Promise.resolve() : new Promise((resolve)=>socket.once("close", resolve));
205
+ let disposePromise;
206
+ const dispose = ()=>{
207
+ disposePromise ??= (async ()=>{
208
+ socket.destroy();
209
+ await socketClosed;
210
+ })();
211
+ return disposePromise;
212
+ };
213
+ try {
214
+ if (socket.connecting) await new Promise((resolve, reject)=>{
215
+ const onConnect = ()=>{
216
+ cleanup();
217
+ resolve();
218
+ };
219
+ const onError = (error)=>{
220
+ cleanup();
221
+ reject(error);
222
+ };
223
+ const onAbort = ()=>{
224
+ cleanup();
225
+ socket.destroy();
226
+ reject(signal?.reason ?? new DOMException("The operation was aborted", "AbortError"));
227
+ };
228
+ const cleanup = ()=>{
229
+ socket.off("connect", onConnect);
230
+ socket.off("error", onError);
231
+ signal?.removeEventListener("abort", onAbort);
232
+ };
233
+ socket.once("connect", onConnect);
234
+ socket.once("error", onError);
235
+ signal?.addEventListener("abort", onAbort, {
236
+ once: true
237
+ });
238
+ if (signal?.aborted) onAbort();
239
+ });
240
+ desktop_debug(`connect: connected to 127.0.0.1:${numericPort}`);
241
+ const { readable, writable } = Duplex.toWeb(socket);
242
+ return {
243
+ readable,
244
+ writable,
245
+ async [Symbol.asyncDispose] () {
246
+ desktop_debug(`connect: closing connection to 127.0.0.1:${numericPort}`);
247
+ await dispose();
248
+ }
249
+ };
250
+ } catch (err) {
251
+ desktop_debug(`connect: error connecting to 127.0.0.1:${numericPort} %O`, err);
252
+ await dispose();
253
+ throw err;
254
+ }
255
+ }
256
+ }
257
+ const ASSETS = node_path.join(node_path.dirname(createRequire(import.meta.url).resolve("@lynx-js/devtool-connector/package.json")), "public/simulator");
258
+ function duration(ms) {
259
+ if (!Number.isSafeInteger(ms) || ms < 1 || ms > 2147483647) throw new Error("Duration must be an integer between 1 and 2147483647 milliseconds.");
260
+ return ms;
261
+ }
262
+ class LynxSimulatorTransport extends DesktopTransport {
263
+ id = Platform.Simulator;
264
+ persistent = true;
265
+ #runs = new Map();
266
+ #prepared = new Map();
267
+ #lifetime = new AbortController();
268
+ #config;
269
+ get active() {
270
+ return [
271
+ ...this.#runs.values()
272
+ ].some((run)=>!run.info.endedAt);
273
+ }
274
+ constructor(config = {
275
+ registry: "https://registry.npmjs.org",
276
+ core: {
277
+ name: "@lynx-js/lynx-simulator-core",
278
+ version: "0.1.0-alpha.0"
279
+ },
280
+ lynxtron: {
281
+ name: "@lynx-js/lynxtron",
282
+ version: "0.0.31"
283
+ }
284
+ }){
285
+ super(false);
286
+ this.#config = config;
287
+ }
288
+ async listDevices() {
289
+ return [
290
+ {
291
+ id: "localhost",
292
+ os: "Desktop"
293
+ }
294
+ ];
295
+ }
296
+ async listClients() {
297
+ return this.list().filter((info)=>"running" === info.status).map((info)=>({
298
+ id: info.clientId,
299
+ info: {
300
+ App: "Lynx Simulator",
301
+ AppVersion: info.lynxtronVersion,
302
+ sdkVersion: info.lynxtronVersion,
303
+ debugRouterId: info.clientId,
304
+ debugRouterVersion: "unknown",
305
+ deviceModel: `${node_os.platform()}-${node_os.arch()}`,
306
+ network: "localhost",
307
+ osType: node_os.platform(),
308
+ osVersion: node_os.release(),
309
+ ...info
310
+ }
311
+ }));
312
+ }
313
+ list() {
314
+ return [
315
+ ...this.#runs.values()
316
+ ].map((run)=>({
317
+ ...run.info
318
+ }));
319
+ }
320
+ #get(clientId) {
321
+ const run = this.#runs.get(clientId);
322
+ if (!run) throw new Error(`Unknown Lynx Simulator client: ${clientId}`);
323
+ return run;
324
+ }
325
+ get(clientId) {
326
+ return {
327
+ ...this.#get(clientId).info
328
+ };
329
+ }
330
+ async logs(clientId, offset = 0) {
331
+ const run = this.#get(clientId);
332
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid log offset.");
333
+ const file = await promises_open(run.info.logPath, "r");
334
+ try {
335
+ const { size } = await file.stat();
336
+ if (offset > size) offset = size;
337
+ const bytes = Buffer.alloc(Math.min(65536, size - offset));
338
+ const { bytesRead } = await file.read(bytes, 0, bytes.length, offset);
339
+ return {
340
+ content: bytes.subarray(0, bytesRead).toString("base64"),
341
+ offset: offset + bytesRead,
342
+ size,
343
+ eof: offset + bytesRead >= size,
344
+ finished: Boolean(run.info.endedAt)
345
+ };
346
+ } finally{
347
+ await file.close();
348
+ }
349
+ }
350
+ async wait(clientId, timeoutMs, signal) {
351
+ const run = this.#get(clientId);
352
+ duration(timeoutMs);
353
+ const cancelled = new AbortController();
354
+ try {
355
+ await Promise.race([
356
+ run.finished,
357
+ promises_setTimeout(timeoutMs, void 0, {
358
+ signal: AbortSignal.any([
359
+ cancelled.signal,
360
+ ...signal ? [
361
+ signal
362
+ ] : []
363
+ ])
364
+ })
365
+ ]);
366
+ return this.get(clientId);
367
+ } finally{
368
+ cancelled.abort();
369
+ }
370
+ }
371
+ async stop(clientId) {
372
+ await this.#stop(this.#get(clientId));
373
+ return this.get(clientId);
374
+ }
375
+ connect(options) {
376
+ const run = this.#runs.get(ClientId.serialize(this.id, "localhost", Number(options.port)));
377
+ if (!run || run.info.endedAt) throw new Error("Lynx Simulator is not running.");
378
+ return super.connect({
379
+ ...options,
380
+ deviceId: "localhost"
381
+ });
382
+ }
383
+ async #prepare(cache, host, packages) {
384
+ if (existsSync(cache)) return;
385
+ await mkdir(node_path.dirname(cache), {
386
+ recursive: true
387
+ });
388
+ const staging = await mkdtemp(`${cache}-install-`);
389
+ try {
390
+ await promisify(execFile)("npm", [
391
+ "install",
392
+ "--prefix",
393
+ staging,
394
+ `--registry=${this.#config.registry}`,
395
+ "--no-audit",
396
+ "--no-fund",
397
+ "--save-exact",
398
+ "--ignore-scripts=false",
399
+ ...host.includes("-") ? [
400
+ "--legacy-peer-deps"
401
+ ] : [],
402
+ `${this.#config.core.name}@${this.#config.core.version}`,
403
+ `${this.#config.lynxtron.name}@${host}`,
404
+ ...packages
405
+ ], {
406
+ timeout: 480000,
407
+ signal: this.#lifetime.signal
408
+ });
409
+ try {
410
+ await rename(staging, cache);
411
+ } catch (error) {
412
+ if (!existsSync(cache)) throw error;
413
+ }
414
+ } finally{
415
+ await rm(staging, {
416
+ recursive: true,
417
+ force: true
418
+ });
419
+ }
420
+ }
421
+ async run(connector, signal, ttlMs, options = {}) {
422
+ if (void 0 !== ttlMs) duration(ttlMs);
423
+ const { core, lynxtron, registry } = this.#config;
424
+ const host = options.lynxtronVersion ?? lynxtron.version;
425
+ if ("string" != typeof host || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(host)) throw new Error("lynxtronVersion must be an exact version.");
426
+ const jsb = withDefaults(this.#config.jsb ?? [], packageList(options.jsb, "jsb"));
427
+ const nativeExtensions = withDefaults(this.#config.nativeExtensions?.(host) ?? [], packageList(options.nativeExtensions, "nativeExtensions"));
428
+ const cache = node_path.join(node_os.homedir(), ".cache/agent-lynx/simulator", createHash("sha256").update(JSON.stringify({
429
+ registry,
430
+ core,
431
+ host,
432
+ name: lynxtron.name,
433
+ jsb,
434
+ nativeExtensions
435
+ })).digest("hex").slice(0, 24));
436
+ const packages = [
437
+ ...jsb.map((spec, i)=>`agent-lynx-jsb-${i}@npm:${spec}`),
438
+ ...nativeExtensions.map((spec, i)=>`agent-lynx-native-${i}@npm:${spec}`)
439
+ ];
440
+ const hook = node_path.join(ASSETS, `bind-${process.platform}-${process.arch}.${"darwin" === process.platform ? "dylib" : "so"}`);
441
+ if (!existsSync(hook)) throw new Error(`Lynx Simulator does not support ${process.platform}/${process.arch}.`);
442
+ let prepared = this.#prepared.get(cache);
443
+ if (!prepared) {
444
+ prepared = this.#prepare(cache, host, packages).catch((error)=>{
445
+ this.#prepared.delete(cache);
446
+ throw error;
447
+ });
448
+ this.#prepared.set(cache, prepared);
449
+ }
450
+ await prepared;
451
+ signal?.throwIfAborted();
452
+ this.#lifetime.signal.throwIfAborted();
453
+ const listeners = [];
454
+ let port, clientId;
455
+ try {
456
+ do {
457
+ signal?.throwIfAborted();
458
+ this.#lifetime.signal.throwIfAborted();
459
+ const listener = node_net.createServer();
460
+ await new Promise((resolve, reject)=>{
461
+ listener.once("error", reject);
462
+ listener.listen(0, "127.0.0.1", resolve);
463
+ });
464
+ listeners.push(listener);
465
+ port = listener.address().port;
466
+ clientId = ClientId.serialize(this.id, "localhost", port);
467
+ }while (this.#runs.has(clientId));
468
+ } finally{
469
+ await Promise.all(listeners.map((listener)=>new Promise((resolve, reject)=>listener.close((error)=>error ? reject(error) : resolve()))));
470
+ }
471
+ const directory = await mkdtemp(node_path.join(cache, "run-"));
472
+ await writeFile(node_path.join(directory, "packages.mjs"), "export const loadPackage = name => import(name);\n");
473
+ const logPath = node_path.join(directory, "simulator.log");
474
+ const { default: executable } = await import(pathToFileURL(node_path.join(cache, "node_modules", lynxtron.name, "lynxtron_bin.js")).href);
475
+ const log = openSync(logPath, "a");
476
+ const child = spawn(executable, [
477
+ node_path.join(ASSETS, "entry.mjs")
478
+ ], {
479
+ detached: true,
480
+ stdio: [
481
+ "pipe",
482
+ log,
483
+ log
484
+ ],
485
+ env: {
486
+ ...process.env,
487
+ AGENT_LYNX_SIMULATOR_ROOT: cache,
488
+ AGENT_LYNX_SIMULATOR_CORE: core.name,
489
+ AGENT_LYNX_SIMULATOR_PACKAGES: JSON.stringify({
490
+ jsb,
491
+ nativeExtensions
492
+ }),
493
+ AGENT_LYNX_SIMULATOR_RUN: directory,
494
+ AGENT_LYNX_SIMULATOR_PORT: String(port),
495
+ AGENT_LYNX_SIMULATOR_BOUND: node_path.join(directory, "bound"),
496
+ ["darwin" === process.platform ? "DYLD_INSERT_LIBRARIES" : "LD_PRELOAD"]: hook
497
+ }
498
+ });
499
+ closeSync(log);
500
+ const info = {
501
+ clientId,
502
+ pid: child.pid ?? null,
503
+ port,
504
+ status: "starting",
505
+ logPath,
506
+ startedAt: new Date().toISOString(),
507
+ exitCode: null,
508
+ signal: null,
509
+ coreVersion: core.version,
510
+ lynxtronVersion: host,
511
+ jsb,
512
+ nativeExtensions
513
+ };
514
+ let finish;
515
+ const run = {
516
+ info,
517
+ child,
518
+ finished: new Promise((resolve)=>{
519
+ finish = resolve;
520
+ })
521
+ };
522
+ this.#runs.set(clientId, run);
523
+ const complete = (code, exitSignal, error)=>{
524
+ if (info.endedAt) return;
525
+ if (error) info.error = error.message;
526
+ info.status = info.error ? "failed" : "stopping" === info.status ? "stopped" : 0 === code ? "exited" : "failed";
527
+ Object.assign(info, {
528
+ exitCode: code,
529
+ signal: exitSignal,
530
+ endedAt: new Date().toISOString()
531
+ });
532
+ clearTimeout(run.ttl);
533
+ finish();
534
+ };
535
+ child.once("error", (error)=>complete(null, null, error));
536
+ child.once("exit", (code, exitSignal)=>complete(code, exitSignal));
537
+ try {
538
+ const deadline = Date.now() + 20000;
539
+ while(!existsSync(node_path.join(directory, "ready")) || !existsSync(node_path.join(directory, "bound"))){
540
+ signal?.throwIfAborted();
541
+ this.#lifetime.signal.throwIfAborted();
542
+ if (info.endedAt || Date.now() > deadline) throw new Error(`${info.error ?? "Lynx Simulator failed to start"}: ${await readFile(logPath, "utf8")} (${logPath})`);
543
+ await promises_setTimeout(50);
544
+ }
545
+ await connector.sendListSessionMessage(clientId);
546
+ signal?.throwIfAborted();
547
+ this.#lifetime.signal.throwIfAborted();
548
+ if ("starting" !== info.status) throw new Error("Lynx Simulator stopped during startup.");
549
+ info.status = "running";
550
+ if (void 0 !== ttlMs) {
551
+ info.expiresAt = new Date(Date.now() + ttlMs).toISOString();
552
+ run.ttl = setTimeout(()=>{
553
+ this.#stop(run, "ttl").catch(console.error);
554
+ }, ttlMs);
555
+ }
556
+ return this.get(clientId);
557
+ } catch (error) {
558
+ if (void 0 === info.stopReason) {
559
+ info.error = error instanceof Error ? error.message : String(error);
560
+ if (info.endedAt) info.status = "failed";
561
+ }
562
+ await this.#stop(run, "startup-failed");
563
+ throw error;
564
+ }
565
+ }
566
+ async #stop(run, reason = "requested") {
567
+ if (run.info.endedAt) return;
568
+ await (run.stopping ??= (async ()=>{
569
+ run.info.status = "stopping";
570
+ run.info.stopReason = reason;
571
+ run.child.stdin?.end();
572
+ const timer = setTimeout(()=>{
573
+ try {
574
+ if (run.child.pid) process.kill(-run.child.pid, "SIGKILL");
575
+ } catch (error) {
576
+ if ("ESRCH" !== error.code) console.error(error);
577
+ }
578
+ }, 3000);
579
+ await run.finished.finally(()=>clearTimeout(timer));
580
+ })());
581
+ }
582
+ async close() {
583
+ this.#lifetime.abort();
584
+ await Promise.all([
585
+ ...this.#runs.values()
586
+ ].map((run)=>this.#stop(run, "daemon")));
587
+ }
588
+ }
589
+ function packageList(value, name) {
590
+ if (void 0 === value) return [];
591
+ if (!Array.isArray(value) || !value.every((spec)=>"string" == typeof spec && /^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*(?:@[a-zA-Z0-9*^~.><=|+ -]+)?$/.test(spec))) throw new Error(`${name} must be an array of npm package names, optionally followed by @version.`);
592
+ return [
593
+ ...new Set(value)
594
+ ];
595
+ }
596
+ function withDefaults(builtins, packages) {
597
+ const name = (spec)=>spec.replace(/@[^@/]+$/, "");
598
+ return [
599
+ ...builtins.filter((builtin)=>!packages.some((spec)=>name(spec) === name(builtin))),
600
+ ...packages
601
+ ];
602
+ }
603
+ export { DesktopTransport, LynxSimulatorTransport, PeertalkToMessageTransformStream, connectWithPeertalk, encodePeertalkMessage };
package/dist/index.d.ts CHANGED
@@ -2,30 +2,31 @@ import { ReadableStream, type TransformStream } from "node:stream/web";
2
2
  import { CDPOutputTransformStream, CDPRequestTransformStream, CDPResponseTransformStream } from "./streams/cdp.js";
3
3
  export { CDPOutputTransformStream, CDPRequestTransformStream, CDPResponseTransformStream };
4
4
  import { ClientId } from "./client-id.js";
5
- import { type App, type ClientList, type Device, type OpenAppOptions, type Transport } from "./transport/transport.js";
5
+ import { type App, type ClientList, type Device, type ListAvailableAppsOptions, type OpenAppOptions, Platform, type Transport } from "./transport/transport.js";
6
6
  import { type CDPRequestMessage, type GlobalKeys, type ListSessionResponse, type Session } from "./types.js";
7
7
  interface OutputStream<O> extends AsyncDisposable, ReadableStream<O> {
8
8
  inputClosed: Promise<void>;
9
9
  }
10
- export { ClientId };
10
+ export { ClientId, Platform };
11
+ export type { ListAvailableAppsOptions, OpenAppOptions };
11
12
  type Pipeline = {
12
13
  input: TransformStream[];
13
14
  output: TransformStream[];
14
15
  };
15
- export declare class Connector {
16
+ export declare class Connector<TPlatform extends string = Platform> {
16
17
  #private;
17
18
  constructor(transports: Transport[]);
18
19
  listClients(): Promise<ClientList>;
19
20
  listDevices(): Promise<Device[]>;
20
- listAvailableApps(deviceId: string): Promise<App[]>;
21
- openApp(deviceId: string, packageName: string, options?: OpenAppOptions): Promise<string>;
21
+ listAvailableApps(deviceId: string, options?: ListAvailableAppsOptions<TPlatform>): Promise<App[]>;
22
+ openApp(deviceId: string, packageName: string, options?: OpenAppOptions<TPlatform>): Promise<string>;
22
23
  sendMessage<T, R>(clientId: string, message: T, pipeline?: Pipeline): Promise<R>;
23
24
  sendAppMessage<Output, Params = never>(clientId: string, method: string, params?: Params): Promise<Output>;
24
25
  /**
25
26
  * Open a page on the given client by sending an `OpenCard` Customized event.
26
27
  */
27
28
  openPage(clientId: string, url: string, signal?: AbortSignal): Promise<ListSessionResponse>;
28
- sendCDPMessage<Output, Params = never>(clientId: string, sessionId: number, method: string, params?: Params, isMainThread?: boolean): Promise<Output>;
29
+ sendCDPMessage<Output, Params = never>(clientId: string, sessionId: number, method: string, params?: Params, isMainThread?: boolean, signal?: AbortSignal): Promise<Output>;
29
30
  sendListSessionMessage(clientId: string): Promise<Session[]>;
30
31
  getGlobalSwitch(clientId: string, key: GlobalKeys): Promise<boolean>;
31
32
  setGlobalSwitch(clientId: string, key: GlobalKeys, value: boolean): Promise<void>;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { CDPOutputTransformStream, CDPRequestTransformStream, CDPResponseTransformStream, createCorrelatedFilter, isCustomizedResponseWithType, isGetGlobalSwitchResponse, isInitializeResponse, isListSessionResponse, isSetGlobalSwitchResponse } from "./hb.js";
2
- export { ClientId } from "./f1.js";
3
- export { Connector } from "./a.js";
1
+ export { CDPOutputTransformStream, CDPRequestTransformStream, CDPResponseTransformStream, createCorrelatedFilter, isCustomizedResponseWithType, isGetGlobalSwitchResponse, isInitializeResponse, isListSessionResponse, isSetGlobalSwitchResponse } from "./h.js";
2
+ export { ClientId, Platform } from "./f1.js";
3
+ export { Connector } from "./az.js";
4
4
  export { nextRequestId } from "./3.js";
package/dist/main.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- throw new Error("Use `npx agent-lynx` instead.");
2
+ throw new Error("Use `pnpx agent-lynx` instead.");
3
3
  export { };
@@ -1,18 +1,16 @@
1
- var __webpack_modules__ = {};
2
- var __webpack_module_cache__ = {};
3
- function __webpack_require__(moduleId) {
4
- var cachedModule = __webpack_module_cache__[moduleId];
1
+ var modules = {};
2
+ var moduleCache = {};
3
+ function rspackRequire(moduleId) {
4
+ var cachedModule = moduleCache[moduleId];
5
5
  if (void 0 !== cachedModule) return cachedModule.exports;
6
- var module = __webpack_module_cache__[moduleId] = {
6
+ var module = moduleCache[moduleId] = {
7
7
  exports: {}
8
8
  };
9
- __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
9
+ modules[moduleId].call(module.exports, module, module.exports, rspackRequire);
10
10
  return module.exports;
11
11
  }
12
- __webpack_require__.m = __webpack_modules__;
13
- (()=>{
14
- __webpack_require__.add = function(modules) {
15
- Object.assign(__webpack_require__.m, modules);
16
- };
17
- })();
18
- export { __webpack_require__ };
12
+ var moduleFactories = modules;
13
+ moduleFactories.add = function(modules) {
14
+ Object.assign(moduleFactories, modules);
15
+ };
16
+ export { rspackRequire, moduleFactories };