dsh-apk-vm 0.10.2 → 0.11.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.
package/lib/cdp.js ADDED
@@ -0,0 +1,1166 @@
1
+ /**
2
+ * lib/cdp.js — dependency-free WebView DevTools (CDP) bridge.
3
+ *
4
+ * Android WebViews that have debugging enabled expose an abstract unix socket
5
+ * named `webview_devtools_remote_<pid>` (some builds also expose the generic
6
+ * `webview_devtools_remote`). This module discovers those sockets through adb,
7
+ * forwards each one to a host TCP port, reads `/json/list`, and speaks the
8
+ * Chrome DevTools Protocol over the resulting WebSocket.
9
+ *
10
+ * Requirements: Node.js 22+ (Node 24 recommended) for the global WebSocket and
11
+ * fetch implementations. There are no npm dependencies.
12
+ *
13
+ * Public API:
14
+ * parseForwardPort(stdout) -> number | null
15
+ * normalizeSelector(selector) -> CSS selector string
16
+ * deepQuerySelector(root, selector) -> Element | null (also injected into pages)
17
+ * class CdpBridge
18
+ * class CdpSession
19
+ *
20
+ * Security notes:
21
+ * - No page text or inserted text is echoed in return values or errors.
22
+ * - Session errors never include the WebSocket URL (which may carry a token).
23
+ * - The bridge only forwards sockets whose names match the two WebView
24
+ * devtools patterns, and only connects to the host-side forwarded port.
25
+ */
26
+
27
+ const DEFAULT_TIMEOUT_MS = 15_000;
28
+ const TARGET_CACHE_MS = 1_500;
29
+ const DEFAULT_POLL_MS = 100;
30
+ const WS_OPEN = 1;
31
+ const SOCKET_NAME_RE = /^webview_devtools_remote(?:_\d+)?$/;
32
+ const CONTROL_RE = /[\u0000-\u001f\u007f]+/g;
33
+ const WS_URL_MAX = 4096;
34
+ const TARGET_URL_MAX = 8192;
35
+ const TARGET_TITLE_MAX = 500;
36
+ const TARGET_ID_MAX = 512;
37
+
38
+ class CdpError extends Error {
39
+ constructor(message, code, cause) {
40
+ super(message, cause === undefined ? undefined : { cause });
41
+ this.name = 'CdpError';
42
+ this.code = code;
43
+ }
44
+ }
45
+
46
+ function cdpError(message, code, cause) {
47
+ return new CdpError(message, code, cause);
48
+ }
49
+
50
+ function toText(value) {
51
+ if (value == null) return '';
52
+ if (typeof value === 'string') return value;
53
+ if (Buffer.isBuffer(value)) return value.toString('utf8');
54
+ if (ArrayBuffer.isView(value)) {
55
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('utf8');
56
+ }
57
+ if (value instanceof ArrayBuffer) return Buffer.from(value).toString('utf8');
58
+ return String(value);
59
+ }
60
+
61
+ function limitText(value, limit, collapse = false) {
62
+ let text = toText(value);
63
+ if (collapse) text = text.replace(CONTROL_RE, ' ').trim();
64
+ if (text.length <= limit) return text;
65
+ return `${text.slice(0, Math.max(0, limit - 3))}...`;
66
+ }
67
+
68
+ function errorDetail(value, limit = 300) {
69
+ if (!value) return '';
70
+ if (typeof value === 'object') {
71
+ const text = toText(value.message || value.stderr || value.stdout).replace(CONTROL_RE, ' ').trim();
72
+ return limitText(text, limit);
73
+ }
74
+ return limitText(value, limit, true);
75
+ }
76
+
77
+ function checkTimeout(value) {
78
+ const timeoutMs = value == null ? DEFAULT_TIMEOUT_MS : Number(value);
79
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
80
+ throw new TypeError('timeoutMs must be a positive number');
81
+ }
82
+ return Math.max(1, Math.round(timeoutMs));
83
+ }
84
+
85
+ function normalizeHost(value) {
86
+ const host = value == null ? '127.0.0.1' : String(value).trim();
87
+ if (!host || /[\s/]/.test(host) || host.includes('://')) {
88
+ throw new TypeError('host must be a hostname or IP address without a scheme or path');
89
+ }
90
+ return host;
91
+ }
92
+
93
+ function urlHost(host) {
94
+ if (host.startsWith('[') && host.endsWith(']')) return host;
95
+ if (host.includes(':')) return `[${host}]`;
96
+ return host;
97
+ }
98
+
99
+ function checkSerial(value) {
100
+ if (typeof value !== 'string' || !value.trim()) {
101
+ throw cdpError('adb serial resolved to an empty or non-string value', 'CDP_ADB_ERROR');
102
+ }
103
+ return value.trim();
104
+ }
105
+
106
+ /**
107
+ * Parse the local port printed by `adb forward tcp:0 localabstract:...`.
108
+ * Accepts a Buffer or string, surrounding whitespace, ignored banner lines,
109
+ * and an optional `tcp:` prefix. Returns null for unparseable output.
110
+ *
111
+ * @param {string | Buffer | Uint8Array} stdout
112
+ * @returns {number | null}
113
+ */
114
+ export function parseForwardPort(stdout) {
115
+ const text = toText(stdout);
116
+ if (!text) return null;
117
+ const lines = text.split(/\r?\n/);
118
+ for (let i = lines.length - 1; i >= 0; i--) {
119
+ const line = lines[i].trim();
120
+ if (!line) continue;
121
+ const match = /^(?:tcp:)?(\d{1,5})$/i.exec(line);
122
+ if (!match) continue;
123
+ const port = Number(match[1]);
124
+ if (Number.isInteger(port) && port > 0 && port <= 65535) return port;
125
+ }
126
+ return null;
127
+ }
128
+
129
+ function escapeCssString(value) {
130
+ return String(value).replace(/[\\"\u0000-\u001f\u007f]/g, (ch) => {
131
+ if (ch === '\\') return '\\\\';
132
+ if (ch === '"') return '\\"';
133
+ return `\\${ch.charCodeAt(0).toString(16)} `;
134
+ });
135
+ }
136
+
137
+ /**
138
+ * Normalize the small selector dialect accepted by the action helpers.
139
+ * Plain CSS is passed through (outer whitespace trimmed). `testid:VALUE` is
140
+ * translated to an exact `[data-testid="VALUE"]` attribute selector.
141
+ *
142
+ * @param {string} selector
143
+ * @returns {string}
144
+ */
145
+ export function normalizeSelector(selector) {
146
+ if (typeof selector !== 'string') throw new TypeError('selector must be a string');
147
+ const trimmed = selector.trim();
148
+ if (!trimmed) throw new TypeError('selector must not be empty');
149
+ if (trimmed.startsWith('testid:')) {
150
+ const value = trimmed.slice('testid:'.length);
151
+ if (!value) throw new TypeError('testid selector must include a value');
152
+ return `[data-testid="${escapeCssString(value)}"]`;
153
+ }
154
+ return trimmed;
155
+ }
156
+
157
+ /**
158
+ * Query `root` and every open shadow root below it. The function is deliberately
159
+ * self-contained and serializable so the same implementation can be injected
160
+ * into a page with `Function.prototype.toString()`.
161
+ *
162
+ * @param {any} root usually document or a ShadowRoot
163
+ * @param {string} selector CSS selector
164
+ * @returns {any | null}
165
+ */
166
+ export function deepQuerySelector(root, selector) {
167
+ if (!root || typeof root.querySelector !== 'function') return null;
168
+ const seen = new Set([root]);
169
+ const find = (scope) => {
170
+ const direct = scope.querySelector(selector);
171
+ if (direct) return direct;
172
+ if (typeof scope.querySelectorAll !== 'function') return null;
173
+ const elements = scope.querySelectorAll('*');
174
+ for (const element of elements) {
175
+ const shadow = element && element.shadowRoot;
176
+ if (!shadow || seen.has(shadow)) continue;
177
+ seen.add(shadow);
178
+ const hit = find(shadow);
179
+ if (hit) return hit;
180
+ }
181
+ return null;
182
+ };
183
+ return find(root);
184
+ }
185
+
186
+ const DEEP_QUERY_SOURCE = deepQuerySelector.toString();
187
+
188
+ function withDeepQuery(selector, body) {
189
+ return `(() => {
190
+ const deepQuerySelector = ${DEEP_QUERY_SOURCE};
191
+ const selector = ${JSON.stringify(selector)};
192
+ try {
193
+ const element = deepQuerySelector(document, selector);
194
+ ${body}
195
+ } catch (error) {
196
+ return { ok: false, reason: 'error', error: String((error && error.message) || error).slice(0, 500) };
197
+ }
198
+ })()`;
199
+ }
200
+
201
+ function clickProbeExpression(selector) {
202
+ return withDeepQuery(
203
+ selector,
204
+ `if (!element) return { ok: false, reason: 'not-found' };
205
+ if (typeof element.scrollIntoView === 'function') {
206
+ try { element.scrollIntoView({ block: 'center', inline: 'center' }); }
207
+ catch (_) { try { element.scrollIntoView(); } catch (_) {} }
208
+ }
209
+ let rect = null;
210
+ if (typeof element.getBoundingClientRect === 'function') {
211
+ const box = element.getBoundingClientRect();
212
+ const left = Number(box && box.left);
213
+ const top = Number(box && box.top);
214
+ const width = Number(box && box.width);
215
+ const height = Number(box && box.height);
216
+ if ([left, top, width, height].every(Number.isFinite)) {
217
+ rect = { left, top, width, height, x: left + width / 2, y: top + height / 2 };
218
+ }
219
+ }
220
+ return {
221
+ ok: true,
222
+ rect,
223
+ clickable: typeof element.click === 'function',
224
+ viewport: { width: Number(window.innerWidth) || 0, height: Number(window.innerHeight) || 0 },
225
+ };`,
226
+ );
227
+ }
228
+
229
+ function domClickExpression(selector) {
230
+ return withDeepQuery(
231
+ selector,
232
+ `if (!element) return { ok: false, reason: 'not-found' };
233
+ if (typeof element.scrollIntoView === 'function') {
234
+ try { element.scrollIntoView({ block: 'center', inline: 'center' }); }
235
+ catch (_) { try { element.scrollIntoView(); } catch (_) {} }
236
+ }
237
+ if (typeof element.click !== 'function') return { ok: false, reason: 'not-clickable' };
238
+ element.click();
239
+ return { ok: true };`,
240
+ );
241
+ }
242
+
243
+ function waitExpression(selector) {
244
+ return withDeepQuery(
245
+ selector,
246
+ `return { ok: true, found: !!element };`,
247
+ );
248
+ }
249
+
250
+ function focusExpression(selector) {
251
+ return withDeepQuery(
252
+ selector,
253
+ `if (!element) return { ok: false, reason: 'not-found' };
254
+ if (typeof element.scrollIntoView === 'function') {
255
+ try { element.scrollIntoView({ block: 'center', inline: 'center' }); }
256
+ catch (_) { try { element.scrollIntoView(); } catch (_) {} }
257
+ }
258
+ if (typeof element.focus !== 'function') return { ok: false, reason: 'not-focusable' };
259
+ try { element.focus({ preventScroll: true }); }
260
+ catch (_) { element.focus(); }
261
+ return { ok: true };`,
262
+ );
263
+ }
264
+
265
+ function delay(ms) {
266
+ return new Promise((resolve) => setTimeout(resolve, ms));
267
+ }
268
+
269
+ function messageText(data) {
270
+ if (typeof data === 'string') return data;
271
+ if (data instanceof ArrayBuffer) return Buffer.from(data).toString('utf8');
272
+ if (ArrayBuffer.isView(data)) {
273
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('utf8');
274
+ }
275
+ return null;
276
+ }
277
+
278
+ function rebaseWebSocketUrl(raw, host, port) {
279
+ const text = limitText(raw, WS_URL_MAX, true);
280
+ if (!text) return '';
281
+ let url;
282
+ try {
283
+ url = new URL(text);
284
+ } catch {
285
+ return '';
286
+ }
287
+ if (url.protocol !== 'ws:' && url.protocol !== 'wss:') return '';
288
+ // Always connect through the local adb forward. DevTools servers sometimes
289
+ // advertise localhost:9222 regardless of the actual forwarded port.
290
+ return `${url.protocol}//${urlHost(host)}:${port}${url.pathname}${url.search}`;
291
+ }
292
+
293
+ function makeTarget(raw, socketName, port, ordinal, host) {
294
+ if (!raw || typeof raw !== 'object') return null;
295
+ const webSocketDebuggerUrl = rebaseWebSocketUrl(raw.webSocketDebuggerUrl, host, port);
296
+ if (!webSocketDebuggerUrl) return null;
297
+ const rawId = limitText(raw.id, TARGET_ID_MAX, true);
298
+ return {
299
+ id: rawId || `${socketName}:${ordinal}`,
300
+ title: limitText(raw.title, TARGET_TITLE_MAX, true),
301
+ url: limitText(raw.url, TARGET_URL_MAX, true),
302
+ type: limitText(raw.type || 'page', 64, true) || 'page',
303
+ webSocketDebuggerUrl,
304
+ socketName,
305
+ port,
306
+ };
307
+ }
308
+
309
+ function targetKey(target) {
310
+ return target.id || target.webSocketDebuggerUrl;
311
+ }
312
+
313
+ function copyTargets(targets) {
314
+ return targets.map((target) => ({ ...target }));
315
+ }
316
+
317
+ function matchesTarget(target, index, descriptor) {
318
+ if (descriptor.id != null && String(target.id) !== String(descriptor.id)) return false;
319
+ if (descriptor.index != null && index !== descriptor.index) return false;
320
+ if (
321
+ descriptor.urlContains != null &&
322
+ !String(target.url || '').includes(String(descriptor.urlContains))
323
+ ) {
324
+ return false;
325
+ }
326
+ if (
327
+ descriptor.titleContains != null &&
328
+ !String(target.title || '').includes(String(descriptor.titleContains))
329
+ ) {
330
+ return false;
331
+ }
332
+ return true;
333
+ }
334
+
335
+ function selectTarget(targets, descriptor) {
336
+ if (descriptor == null) return targets[0];
337
+ if (typeof descriptor === 'string') return targets.find((target) => target.id === descriptor) || null;
338
+ if (typeof descriptor === 'number') {
339
+ if (!Number.isInteger(descriptor) || descriptor < 0 || descriptor >= targets.length) return null;
340
+ return targets[descriptor];
341
+ }
342
+ if (typeof descriptor !== 'object' || Array.isArray(descriptor)) return null;
343
+
344
+ const normalized = {};
345
+ if (descriptor.id != null) normalized.id = descriptor.id;
346
+ if (descriptor.index != null) {
347
+ const index = Number(descriptor.index);
348
+ if (!Number.isInteger(index) || index < 0) return null;
349
+ normalized.index = index;
350
+ }
351
+ if (descriptor.urlContains != null) normalized.urlContains = descriptor.urlContains;
352
+ if (descriptor.titleContains != null) normalized.titleContains = descriptor.titleContains;
353
+
354
+ return targets.find((target, index) => matchesTarget(target, index, normalized)) || null;
355
+ }
356
+
357
+ function selectDescription(descriptor) {
358
+ if (descriptor == null) return 'first target';
359
+ if (typeof descriptor === 'string') return `id=${descriptor}`;
360
+ if (typeof descriptor === 'number') return `index=${descriptor}`;
361
+ if (typeof descriptor !== 'object') return 'invalid target descriptor';
362
+ const parts = [];
363
+ if (descriptor.id != null) parts.push(`id=${descriptor.id}`);
364
+ if (descriptor.index != null) parts.push(`index=${descriptor.index}`);
365
+ if (descriptor.urlContains != null) parts.push(`urlContains=${descriptor.urlContains}`);
366
+ if (descriptor.titleContains != null) parts.push(`titleContains=${descriptor.titleContains}`);
367
+ return parts.length ? parts.join(', ') : 'first target';
368
+ }
369
+
370
+ /**
371
+ * Open one Chrome DevTools Protocol WebSocket.
372
+ * @param {string} url
373
+ * @param {number} timeoutMs
374
+ * @returns {Promise<any>} an open WHATWG WebSocket
375
+ */
376
+ async function openWebSocket(url, timeoutMs) {
377
+ const WebSocketImpl = globalThis.WebSocket;
378
+ if (typeof WebSocketImpl !== 'function') {
379
+ throw cdpError('global WebSocket is unavailable (Node.js 22+ is required)', 'CDP_WEBSOCKET_UNAVAILABLE');
380
+ }
381
+
382
+ return new Promise((resolve, reject) => {
383
+ let socket;
384
+ try {
385
+ socket = new WebSocketImpl(url);
386
+ } catch (error) {
387
+ // Do not include the URL or a constructor message that may echo it: the
388
+ // DevTools URL can carry a per-session token.
389
+ reject(cdpError('Could not create CDP WebSocket', 'CDP_CONNECT_ERROR', error));
390
+ return;
391
+ }
392
+
393
+ let settled = false;
394
+ let timer = null;
395
+ const cleanup = () => {
396
+ if (timer) clearTimeout(timer);
397
+ timer = null;
398
+ try {
399
+ socket.removeEventListener('open', onOpen);
400
+ socket.removeEventListener('error', onError);
401
+ socket.removeEventListener('close', onClose);
402
+ } catch {
403
+ /* ignore */
404
+ }
405
+ };
406
+ const fail = (message) => {
407
+ if (settled) return;
408
+ settled = true;
409
+ cleanup();
410
+ try {
411
+ socket.close();
412
+ } catch {
413
+ /* ignore */
414
+ }
415
+ reject(cdpError(message, 'CDP_CONNECT_ERROR'));
416
+ };
417
+ const onOpen = () => {
418
+ if (settled) return;
419
+ settled = true;
420
+ cleanup();
421
+ try {
422
+ socket.binaryType = 'arraybuffer';
423
+ } catch {
424
+ /* text messages are all CDP needs */
425
+ }
426
+ resolve(socket);
427
+ };
428
+ const onError = () => fail('Could not connect to the WebView DevTools WebSocket');
429
+ const onClose = () => fail('The WebView DevTools WebSocket closed before it opened');
430
+
431
+ socket.addEventListener('open', onOpen, { once: true });
432
+ socket.addEventListener('error', onError, { once: true });
433
+ socket.addEventListener('close', onClose, { once: true });
434
+ timer = setTimeout(
435
+ () => fail(`Timed out connecting to the WebView DevTools WebSocket after ${timeoutMs}ms`),
436
+ timeoutMs,
437
+ );
438
+ });
439
+ }
440
+
441
+ /**
442
+ * One CDP connection. Normally obtained from `CdpBridge#open()`, but it may be
443
+ * constructed around an already-open WebSocket for tests or custom transports.
444
+ */
445
+ export class CdpSession {
446
+ /**
447
+ * @param {any} socket already-open WHATWG WebSocket
448
+ * @param {object} target sanitized target descriptor (optional, informational)
449
+ * @param {{ timeoutMs?: number, url?: string }} options
450
+ */
451
+ constructor(socket, target = {}, options = {}) {
452
+ if (!socket || typeof socket.send !== 'function' || typeof socket.addEventListener !== 'function') {
453
+ throw new TypeError('socket must be an open WHATWG WebSocket');
454
+ }
455
+ this.target = target && typeof target === 'object' ? { ...target } : {};
456
+ this.timeoutMs = checkTimeout(options.timeoutMs);
457
+ this._socket = socket;
458
+ this._url = typeof options.url === 'string' ? options.url : '';
459
+ this._nextId = 1;
460
+ this._pending = new Map();
461
+ this._closed = false;
462
+ this._reconnectUsed = false;
463
+ this._connectPromise = null;
464
+ this._attach(socket);
465
+ }
466
+
467
+ /** Build a session by opening a WebSocket. */
468
+ static async connect(url, target = {}, options = {}) {
469
+ if (typeof url !== 'string' || !/^wss?:\/\//i.test(url)) {
470
+ throw cdpError('target has no usable WebSocket debugger URL', 'CDP_NO_TARGET');
471
+ }
472
+ const timeoutMs = checkTimeout(options.timeoutMs);
473
+ const socket = await openWebSocket(url, timeoutMs);
474
+ return new CdpSession(socket, target, { ...options, timeoutMs, url });
475
+ }
476
+
477
+ _attach(socket) {
478
+ socket.addEventListener('message', (event) => {
479
+ if (this._socket !== socket) return;
480
+ this._onMessage(event);
481
+ });
482
+ socket.addEventListener('close', () => {
483
+ if (this._socket !== socket) return;
484
+ this._socket = null;
485
+ this._rejectPending(cdpError('CDP WebSocket closed unexpectedly', 'CDP_DISCONNECTED'));
486
+ });
487
+ socket.addEventListener('error', () => {
488
+ if (this._socket !== socket) return;
489
+ this._socket = null;
490
+ this._rejectPending(cdpError('CDP WebSocket failed', 'CDP_DISCONNECTED'));
491
+ try {
492
+ socket.close();
493
+ } catch {
494
+ /* already down */
495
+ }
496
+ });
497
+ }
498
+
499
+ _onMessage(event) {
500
+ const text = messageText(event && event.data);
501
+ if (text == null) return;
502
+ let message;
503
+ try {
504
+ message = JSON.parse(text);
505
+ } catch {
506
+ return;
507
+ }
508
+ if (!message || message.id == null || message.method) return;
509
+ const id = Number(message.id);
510
+ const pending = this._pending.get(id);
511
+ if (!pending) return;
512
+ this._pending.delete(id);
513
+ clearTimeout(pending.timer);
514
+ if (message.error) {
515
+ const detail = limitText(message.error.message || 'CDP request failed', 500, true);
516
+ const error = cdpError(`CDP ${pending.method} failed: ${detail}`, 'CDP_ERROR');
517
+ if (message.error.code != null) error.cdpCode = message.error.code;
518
+ pending.reject(error);
519
+ return;
520
+ }
521
+ pending.resolve(message.result && typeof message.result === 'object' ? message.result : {});
522
+ }
523
+
524
+ _rejectPending(error) {
525
+ for (const pending of this._pending.values()) {
526
+ clearTimeout(pending.timer);
527
+ pending.reject(error);
528
+ }
529
+ this._pending.clear();
530
+ }
531
+
532
+ _isOpen() {
533
+ return !!this._socket && this._socket.readyState === WS_OPEN;
534
+ }
535
+
536
+ async _ensureConnected() {
537
+ if (this._closed) throw cdpError('CDP session is closed', 'CDP_CLOSED');
538
+ if (this._isOpen()) return this._socket;
539
+ if (this._socket) {
540
+ throw cdpError('CDP WebSocket is not open', 'CDP_DISCONNECTED');
541
+ }
542
+ if (!this._url || this._reconnectUsed) {
543
+ throw cdpError('CDP session is disconnected', 'CDP_DISCONNECTED');
544
+ }
545
+ if (this._connectPromise) return this._connectPromise;
546
+
547
+ this._reconnectUsed = true;
548
+ this._connectPromise = openWebSocket(this._url, this.timeoutMs)
549
+ .then((socket) => {
550
+ if (this._closed) {
551
+ try {
552
+ socket.close();
553
+ } catch {
554
+ /* ignore */
555
+ }
556
+ throw cdpError('CDP session is closed', 'CDP_CLOSED');
557
+ }
558
+ this._attach(socket);
559
+ this._socket = socket;
560
+ return socket;
561
+ })
562
+ .finally(() => {
563
+ this._connectPromise = null;
564
+ });
565
+ return this._connectPromise;
566
+ }
567
+
568
+ /**
569
+ * Send a CDP command and resolve with its `result` object.
570
+ * @param {string} method
571
+ * @param {object} [params]
572
+ * @returns {Promise<object>}
573
+ */
574
+ async send(method, params) {
575
+ if (typeof method !== 'string' || !method.trim()) {
576
+ throw new TypeError('method must be a non-empty CDP method string');
577
+ }
578
+ if (this._closed) throw cdpError('CDP session is closed', 'CDP_CLOSED');
579
+ await this._ensureConnected();
580
+ const socket = this._socket;
581
+ if (!this._isOpen()) {
582
+ throw cdpError('CDP WebSocket is not open', 'CDP_DISCONNECTED');
583
+ }
584
+
585
+ const id = this._nextId++;
586
+ let payload;
587
+ try {
588
+ payload = JSON.stringify({ id, method, params: params === undefined ? {} : params });
589
+ } catch (error) {
590
+ throw cdpError(`Could not serialize CDP params: ${errorDetail(error)}`, 'CDP_INVALID_PARAMS', error);
591
+ }
592
+
593
+ return new Promise((resolve, reject) => {
594
+ const timer = setTimeout(() => {
595
+ if (!this._pending.has(id)) return;
596
+ this._pending.delete(id);
597
+ reject(cdpError(`CDP ${method} timed out after ${this.timeoutMs}ms`, 'CDP_TIMEOUT'));
598
+ }, this.timeoutMs);
599
+ this._pending.set(id, { method, resolve, reject, timer });
600
+ try {
601
+ socket.send(payload);
602
+ } catch (error) {
603
+ if (this._pending.delete(id)) clearTimeout(timer);
604
+ reject(cdpError(`Could not send CDP ${method}: ${errorDetail(error)}`, 'CDP_SEND_ERROR', error));
605
+ }
606
+ });
607
+ }
608
+
609
+ /**
610
+ * Evaluate JavaScript in the main frame and return a JSON-safe by-value result.
611
+ * `undefined`, DOM nodes and other non-by-value results become null. BigInt
612
+ * and special numbers are returned as their CDP `unserializableValue` string.
613
+ * @param {string} expression
614
+ * @param {{ awaitPromise?: boolean, returnByValue?: boolean }} [options]
615
+ * @returns {Promise<any>}
616
+ */
617
+ async evaluate(expression, options = {}) {
618
+ if (typeof expression !== 'string' || !expression.trim()) {
619
+ throw new TypeError('expression must be a non-empty string');
620
+ }
621
+ const result = await this.send('Runtime.evaluate', {
622
+ expression,
623
+ awaitPromise: options.awaitPromise !== false,
624
+ returnByValue: options.returnByValue !== false,
625
+ });
626
+ if (result && result.exceptionDetails) {
627
+ const details = result.exceptionDetails;
628
+ const exception = details.exception || {};
629
+ let description = exception.description || exception.value;
630
+ if (description == null) description = details.text;
631
+ if (description == null) description = 'unknown exception';
632
+ throw cdpError(
633
+ `Runtime.evaluate failed: ${limitText(description, 1000, true)}`,
634
+ 'CDP_EVALUATION_ERROR',
635
+ );
636
+ }
637
+ const remote = result && result.result;
638
+ if (!remote || typeof remote !== 'object') return null;
639
+ if (Object.prototype.hasOwnProperty.call(remote, 'value')) {
640
+ return remote.value === undefined ? null : remote.value;
641
+ }
642
+ if (typeof remote.unserializableValue === 'string') return remote.unserializableValue;
643
+ return null;
644
+ }
645
+
646
+ /**
647
+ * Click an element found through the deep (open shadow DOM) query. Mouse
648
+ * events at the viewport center are preferred; when a box is unavailable or
649
+ * the mouse dispatch fails, the page's `element.click()` is used.
650
+ * @param {string} selector CSS or `testid:VALUE`
651
+ * @returns {Promise<true>}
652
+ */
653
+ async click(selector) {
654
+ const normalized = normalizeSelector(selector);
655
+ const probe = await this.evaluate(clickProbeExpression(normalized));
656
+ if (!probe || probe.ok !== true) {
657
+ if (probe && probe.reason === 'not-found') {
658
+ throw cdpError(
659
+ `Selector not found: ${limitText(normalized, 300, true)}`,
660
+ 'CDP_SELECTOR_NOT_FOUND',
661
+ );
662
+ }
663
+ throw cdpError(
664
+ `Could not inspect selector ${limitText(normalized, 300, true)}: ${limitText(probe && probe.error, 500, true)}`,
665
+ 'CDP_EVALUATION_ERROR',
666
+ );
667
+ }
668
+
669
+ const rect = probe.rect;
670
+ const viewport = probe.viewport || {};
671
+ const vw = Number(viewport.width);
672
+ const vh = Number(viewport.height);
673
+ const x = rect ? Number(rect.x) : NaN;
674
+ const y = rect ? Number(rect.y) : NaN;
675
+ if (
676
+ rect &&
677
+ rect.width > 0 &&
678
+ rect.height > 0 &&
679
+ Number.isFinite(x) &&
680
+ Number.isFinite(y) &&
681
+ Number.isFinite(vw) &&
682
+ Number.isFinite(vh) &&
683
+ x >= 0 &&
684
+ y >= 0 &&
685
+ x < vw &&
686
+ y < vh
687
+ ) {
688
+ try {
689
+ await this.send('Input.dispatchMouseEvent', {
690
+ type: 'mouseMoved',
691
+ x,
692
+ y,
693
+ button: 'none',
694
+ buttons: 0,
695
+ });
696
+ await this.send('Input.dispatchMouseEvent', {
697
+ type: 'mousePressed',
698
+ x,
699
+ y,
700
+ button: 'left',
701
+ buttons: 1,
702
+ clickCount: 1,
703
+ });
704
+ await this.send('Input.dispatchMouseEvent', {
705
+ type: 'mouseReleased',
706
+ x,
707
+ y,
708
+ button: 'left',
709
+ buttons: 0,
710
+ clickCount: 1,
711
+ });
712
+ return true;
713
+ } catch {
714
+ // Fall through to element.click(); a screen surface may reject input
715
+ // events even though the JS click path still works.
716
+ }
717
+ }
718
+
719
+ const clicked = await this.evaluate(domClickExpression(normalized));
720
+ if (clicked && clicked.ok === true) return true;
721
+ if (clicked && clicked.reason === 'not-found') {
722
+ throw cdpError(
723
+ `Selector not found: ${limitText(normalized, 300, true)}`,
724
+ 'CDP_SELECTOR_NOT_FOUND',
725
+ );
726
+ }
727
+ if (clicked && clicked.reason === 'not-clickable') {
728
+ throw cdpError(
729
+ `Element for selector ${limitText(normalized, 300, true)} has no click() method`,
730
+ 'CDP_CLICK_FAILED',
731
+ );
732
+ }
733
+ throw cdpError(
734
+ `Could not click selector ${limitText(normalized, 300, true)}: ${limitText(clicked && clicked.error, 500, true)}`,
735
+ 'CDP_CLICK_FAILED',
736
+ );
737
+ }
738
+
739
+ /**
740
+ * Poll for a selector, including inside open shadow roots.
741
+ * @param {string} selector
742
+ * @param {{ timeoutMs?: number, pollMs?: number }} [options]
743
+ * @returns {Promise<true>}
744
+ */
745
+ async waitFor(selector, options = {}) {
746
+ const normalized = normalizeSelector(selector);
747
+ const timeoutMs = options.timeoutMs == null ? this.timeoutMs : Number(options.timeoutMs);
748
+ const pollMs = options.pollMs == null ? DEFAULT_POLL_MS : Number(options.pollMs);
749
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
750
+ throw new TypeError('timeoutMs must be a non-negative number');
751
+ }
752
+ if (!Number.isFinite(pollMs) || pollMs <= 0) {
753
+ throw new TypeError('pollMs must be a positive number');
754
+ }
755
+
756
+ const started = Date.now();
757
+ for (;;) {
758
+ const result = await this.evaluate(waitExpression(normalized));
759
+ if (result && typeof result === 'object' && result.reason === 'error') {
760
+ throw cdpError(
761
+ `Could not query selector ${limitText(normalized, 300, true)}: ${limitText(result.error, 500, true)}`,
762
+ 'CDP_EVALUATION_ERROR',
763
+ );
764
+ }
765
+ if (result && result.found === true) return true;
766
+ const elapsed = Date.now() - started;
767
+ if (elapsed >= timeoutMs) {
768
+ throw cdpError(
769
+ `Timed out waiting for selector ${limitText(normalized, 300, true)} after ${Math.round(elapsed)}ms`,
770
+ 'CDP_SELECTOR_TIMEOUT',
771
+ );
772
+ }
773
+ await delay(Math.min(pollMs, Math.max(1, timeoutMs - elapsed)));
774
+ }
775
+ }
776
+
777
+ /**
778
+ * Focus an element (when a selector is supplied) and insert Unicode text via
779
+ * `Input.insertText`. No page text is included in the return value.
780
+ * @param {string} text
781
+ * @param {{ selector?: string }} [options]
782
+ * @returns {Promise<true>}
783
+ */
784
+ async insertText(text, options = {}) {
785
+ if (typeof text !== 'string') throw new TypeError('text must be a string');
786
+ if (options.selector != null) {
787
+ const normalized = normalizeSelector(options.selector);
788
+ const focused = await this.evaluate(focusExpression(normalized));
789
+ if (!focused || focused.ok !== true) {
790
+ if (focused && focused.reason === 'not-found') {
791
+ throw cdpError(
792
+ `Selector not found for focus: ${limitText(normalized, 300, true)}`,
793
+ 'CDP_SELECTOR_NOT_FOUND',
794
+ );
795
+ }
796
+ if (focused && focused.reason === 'not-focusable') {
797
+ throw cdpError(
798
+ `Element for selector ${limitText(normalized, 300, true)} cannot be focused`,
799
+ 'CDP_FOCUS_FAILED',
800
+ );
801
+ }
802
+ throw cdpError(
803
+ `Could not focus selector ${limitText(normalized, 300, true)}: ${limitText(focused && focused.error, 500, true)}`,
804
+ 'CDP_FOCUS_FAILED',
805
+ );
806
+ }
807
+ }
808
+ await this.send('Input.insertText', { text });
809
+ return true;
810
+ }
811
+
812
+ /** Close the WebSocket and reject all pending commands. Idempotent. */
813
+ close() {
814
+ if (this._closed) return;
815
+ this._closed = true;
816
+ const socket = this._socket;
817
+ this._socket = null;
818
+ this._rejectPending(cdpError('CDP session is closed', 'CDP_CLOSED'));
819
+ if (socket) {
820
+ try {
821
+ socket.close(1000, '');
822
+ } catch {
823
+ /* ignore */
824
+ }
825
+ }
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Discover, cache, and connect to WebView DevTools targets on one adb device.
831
+ */
832
+ export class CdpBridge {
833
+ /**
834
+ * @param {{
835
+ * adb: (args: string[], options?: object) => Promise<{code:number,timedOut:boolean,stdout:any,stderr:any}>,
836
+ * serial: string | (() => string | Promise<string>),
837
+ * host?: string,
838
+ * timeoutMs?: number,
839
+ * }} options
840
+ */
841
+ constructor(options = {}) {
842
+ if (typeof options.adb !== 'function') throw new TypeError('adb must be a function');
843
+ if (typeof options.serial !== 'string' && typeof options.serial !== 'function') {
844
+ throw new TypeError('serial must be a string or an async function returning a string');
845
+ }
846
+ this.adb = options.adb;
847
+ this.serial = options.serial;
848
+ this.host = normalizeHost(options.host);
849
+ this.timeoutMs = checkTimeout(options.timeoutMs);
850
+
851
+ this._closed = false;
852
+ this._discovering = null;
853
+ this._cacheTargets = [];
854
+ this._cacheAt = 0;
855
+ this._forwards = new Map();
856
+ this._sessions = new Set();
857
+ }
858
+
859
+ async _getSerial() {
860
+ let value;
861
+ try {
862
+ value = typeof this.serial === 'function' ? await this.serial() : this.serial;
863
+ } catch (error) {
864
+ throw cdpError(`Could not resolve adb serial: ${errorDetail(error)}`, 'CDP_ADB_ERROR', error);
865
+ }
866
+ return checkSerial(value);
867
+ }
868
+
869
+ async _runAdb(args, label) {
870
+ let result;
871
+ try {
872
+ result = await this.adb(args, { timeoutMs: this.timeoutMs });
873
+ } catch (error) {
874
+ throw cdpError(`${label}: ${errorDetail(error)}`, 'CDP_ADB_ERROR', error);
875
+ }
876
+ if (!result || typeof result !== 'object') {
877
+ throw cdpError(`${label}: adb returned no result object`, 'CDP_ADB_ERROR');
878
+ }
879
+ if (result.timedOut) {
880
+ throw cdpError(`${label}: adb timed out after ${this.timeoutMs}ms`, 'CDP_ADB_ERROR');
881
+ }
882
+ if (result.code !== 0) {
883
+ const detail = errorDetail(result.stderr) || errorDetail(result.stdout);
884
+ throw cdpError(
885
+ `${label}: adb exited ${result.code}${detail ? ` (${detail})` : ''}`,
886
+ 'CDP_ADB_ERROR',
887
+ );
888
+ }
889
+ return result;
890
+ }
891
+
892
+ _socketNames(unixTable) {
893
+ const names = [];
894
+ const seen = new Set();
895
+ for (const rawLine of toText(unixTable).split(/\r?\n/)) {
896
+ const line = rawLine.trim();
897
+ if (!line) continue;
898
+ const fields = line.split(/\s+/);
899
+ const candidate = fields[fields.length - 1].replace(/^@/, '');
900
+ if (!SOCKET_NAME_RE.test(candidate) || seen.has(candidate)) continue;
901
+ seen.add(candidate);
902
+ names.push(candidate);
903
+ }
904
+ return names;
905
+ }
906
+
907
+ _forwardKey(serial, socketName) {
908
+ return `${serial}\u0000${socketName}`;
909
+ }
910
+
911
+ async _ensureForward(serial, socketName) {
912
+ const key = this._forwardKey(serial, socketName);
913
+ const cached = this._forwards.get(key);
914
+ if (cached) return cached;
915
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
916
+
917
+ const result = await this._runAdb(
918
+ ['-s', serial, 'forward', 'tcp:0', `localabstract:${socketName}`],
919
+ `Could not forward WebView socket ${socketName}`,
920
+ );
921
+ const port = parseForwardPort(result.stdout);
922
+ if (!port) {
923
+ throw cdpError(
924
+ `adb forward for ${socketName} did not report a local port: ${limitText(result.stdout, 200, true) || '(empty output)'}`,
925
+ 'CDP_FORWARD_FAILED',
926
+ );
927
+ }
928
+ if (this._closed) {
929
+ await this._removeForward({ serial, socketName, port });
930
+ throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
931
+ }
932
+ const entry = { serial, socketName, port };
933
+ this._forwards.set(key, entry);
934
+ return entry;
935
+ }
936
+
937
+ async _removeForward(entry) {
938
+ if (!entry) return;
939
+ try {
940
+ await this.adb(
941
+ ['-s', entry.serial, 'forward', '--remove', `tcp:${entry.port}`],
942
+ { timeoutMs: this.timeoutMs },
943
+ );
944
+ } catch {
945
+ /* best effort: the device may already be gone */
946
+ }
947
+ }
948
+
949
+ async _dropForward(key, entry) {
950
+ if (this._forwards.get(key) === entry) this._forwards.delete(key);
951
+ await this._removeForward(entry);
952
+ }
953
+
954
+ async _fetchTargetList(port) {
955
+ const url = `http://${urlHost(this.host)}:${port}/json/list`;
956
+ const controller = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function'
957
+ ? AbortSignal.timeout(this.timeoutMs)
958
+ : undefined;
959
+ let response;
960
+ try {
961
+ response = await fetch(url, {
962
+ method: 'GET',
963
+ headers: { accept: 'application/json' },
964
+ signal: controller,
965
+ });
966
+ } catch (error) {
967
+ const reason = error && (error.name === 'TimeoutError' || error.name === 'AbortError')
968
+ ? `timed out after ${this.timeoutMs}ms`
969
+ : errorDetail(error);
970
+ throw cdpError(`Could not read /json/list from localhost:${port}: ${reason}`, 'CDP_HTTP_ERROR', error);
971
+ }
972
+ if (response && response.ok === false) {
973
+ throw cdpError(
974
+ `Could not read /json/list from localhost:${port}: HTTP ${response.status}`,
975
+ 'CDP_HTTP_ERROR',
976
+ );
977
+ }
978
+ let data;
979
+ try {
980
+ data = await response.json();
981
+ } catch (error) {
982
+ throw cdpError(
983
+ `Could not parse /json/list from localhost:${port}: ${errorDetail(error)}`,
984
+ 'CDP_HTTP_ERROR',
985
+ error,
986
+ );
987
+ }
988
+ if (Array.isArray(data)) return data;
989
+ if (data && Array.isArray(data.targets)) return data.targets;
990
+ throw cdpError(
991
+ `Unexpected /json/list response from localhost:${port}`,
992
+ 'CDP_HTTP_ERROR',
993
+ );
994
+ }
995
+
996
+ async _discover() {
997
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
998
+ const serial = await this._getSerial();
999
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
1000
+
1001
+ const unix = await this._runAdb(
1002
+ ['-s', serial, 'shell', 'cat /proc/net/unix'],
1003
+ 'Could not list WebView devtools sockets',
1004
+ );
1005
+ const sockets = this._socketNames(unix.stdout);
1006
+ if (sockets.length === 0) {
1007
+ throw cdpError(
1008
+ 'No WebView devtools sockets found. Start the app with WebView debugging enabled and reload the page.',
1009
+ 'CDP_NO_WEBVIEWS',
1010
+ );
1011
+ }
1012
+
1013
+ const targets = [];
1014
+ const failures = [];
1015
+ const seen = new Set();
1016
+ for (const socketName of sockets) {
1017
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
1018
+ let forward;
1019
+ try {
1020
+ forward = await this._ensureForward(serial, socketName);
1021
+ } catch (error) {
1022
+ if (error && error.code === 'CDP_CLOSED') throw error;
1023
+ failures.push(`${socketName}: ${errorDetail(error)}`);
1024
+ continue;
1025
+ }
1026
+
1027
+ let list;
1028
+ try {
1029
+ list = await this._fetchTargetList(forward.port);
1030
+ } catch (error) {
1031
+ failures.push(`${socketName}: ${errorDetail(error)}`);
1032
+ await this._dropForward(this._forwardKey(serial, socketName), forward);
1033
+ continue;
1034
+ }
1035
+
1036
+ for (let ordinal = 0; ordinal < list.length; ordinal++) {
1037
+ const target = makeTarget(list[ordinal], socketName, forward.port, ordinal, this.host);
1038
+ if (!target) continue;
1039
+ const key = targetKey(target);
1040
+ if (seen.has(key)) continue;
1041
+ seen.add(key);
1042
+ targets.push(target);
1043
+ }
1044
+ }
1045
+
1046
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
1047
+ if (targets.length === 0) {
1048
+ const detail = failures.length ? ` Last error: ${failures[0]}` : '';
1049
+ throw cdpError(
1050
+ `No reachable WebView debug targets found on ${serial}.${detail}`,
1051
+ 'CDP_NO_TARGETS',
1052
+ );
1053
+ }
1054
+ this._cacheTargets = copyTargets(targets);
1055
+ this._cacheAt = Date.now();
1056
+ return copyTargets(this._cacheTargets);
1057
+ }
1058
+
1059
+ /**
1060
+ * Freshly list WebView sockets, create/reuse one forward per socket, and
1061
+ * return deduplicated, JSON-safe targets. Throws when no targets are found.
1062
+ * @returns {Promise<Array<object>>}
1063
+ */
1064
+ async discover() {
1065
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
1066
+ if (this._discovering) return this._discovering;
1067
+ const task = this._discover().finally(() => {
1068
+ if (this._discovering === task) this._discovering = null;
1069
+ });
1070
+ this._discovering = task;
1071
+ return task;
1072
+ }
1073
+
1074
+ /**
1075
+ * Cached target listing (1500 ms). Mirrors `discover()` when the cache is cold.
1076
+ * @returns {Promise<Array<object>>}
1077
+ */
1078
+ async targets() {
1079
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
1080
+ if (this._cacheTargets.length > 0 && Date.now() - this._cacheAt < TARGET_CACHE_MS) {
1081
+ return copyTargets(this._cacheTargets);
1082
+ }
1083
+ return copyTargets(await this.discover());
1084
+ }
1085
+
1086
+ /**
1087
+ * Open a target. The descriptor may be `{id}`, `{index}`, `{urlContains}`,
1088
+ * `{titleContains}` (combined predicates are ANDed), a string id, a numeric
1089
+ * index, or omitted for the first target.
1090
+ * @param {object | string | number | null} [descriptor]
1091
+ * @returns {Promise<CdpSession>}
1092
+ */
1093
+ async open(descriptor) {
1094
+ if (this._closed) throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
1095
+ const targets = await this.targets();
1096
+ const target = selectTarget(targets, descriptor);
1097
+ if (!target) {
1098
+ throw cdpError(
1099
+ `No WebView target matched ${selectDescription(descriptor)} (${targets.length} available)`,
1100
+ 'CDP_NO_TARGET',
1101
+ );
1102
+ }
1103
+ const session = await CdpSession.connect(target.webSocketDebuggerUrl, target, {
1104
+ timeoutMs: this.timeoutMs,
1105
+ });
1106
+ if (this._closed) {
1107
+ session.close();
1108
+ throw cdpError('CDP bridge is closed', 'CDP_CLOSED');
1109
+ }
1110
+ this._sessions.add(session);
1111
+ return session;
1112
+ }
1113
+
1114
+ /**
1115
+ * Query an element without a long-lived session. Returns geometry and text;
1116
+ * `found:false` is a normal result, not an error.
1117
+ * @param {string} selector CSS or `testid:VALUE`
1118
+ * @param {{ target?: object | string | number | null }} [options]
1119
+ */
1120
+ async query(selector, options = {}) {
1121
+ const normalized = normalizeSelector(selector);
1122
+ const session = await this.open(options.target);
1123
+ try {
1124
+ return await session.evaluate(withDeepQuery(
1125
+ normalized,
1126
+ `if (!element) return { found: false, selector: ${JSON.stringify(normalized)} };
1127
+ let box = { x: 0, y: 0, width: 0, height: 0 };
1128
+ try {
1129
+ if (typeof element.getBoundingClientRect === 'function') box = element.getBoundingClientRect();
1130
+ } catch (_) { /* detached or non-box element */ }
1131
+ return {
1132
+ found: true,
1133
+ selector: ${JSON.stringify(normalized)},
1134
+ tag: String(element.tagName || '').toLowerCase(),
1135
+ text: String(element.innerText || element.textContent || '').trim().slice(0, 500),
1136
+ rect: {
1137
+ x: Math.round(Number(box.x || 0) * 100) / 100,
1138
+ y: Math.round(Number(box.y || 0) * 100) / 100,
1139
+ width: Math.round(Number(box.width || 0) * 100) / 100,
1140
+ height: Math.round(Number(box.height || 0) * 100) / 100,
1141
+ },
1142
+ visible: Boolean(element.getClientRects && element.getClientRects().length),
1143
+ };`,
1144
+ ));
1145
+ } finally {
1146
+ session.close();
1147
+ }
1148
+ }
1149
+
1150
+ /** Close all sessions and remove all adb forwards. Idempotent, best effort. */
1151
+ async close() {
1152
+ if (this._closed) return;
1153
+ this._closed = true;
1154
+ for (const session of this._sessions) {
1155
+ try {
1156
+ session.close();
1157
+ } catch {
1158
+ /* best effort */
1159
+ }
1160
+ }
1161
+ this._sessions.clear();
1162
+ const forwards = [...this._forwards.values()];
1163
+ this._forwards.clear();
1164
+ await Promise.all(forwards.map((entry) => this._removeForward(entry)));
1165
+ }
1166
+ }