dsh-apk-vm 0.12.0 → 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1526 @@
1
+ /**
2
+ * Unified emulator inventory: Android emulators/AVDs/devices available on this
3
+ * host *and* on saved remote SSH hosts, in one stable JSON document.
4
+ *
5
+ * Wiring example (the panel exposes this as `GET /apk-vm/emulators`):
6
+ *
7
+ * import {
8
+ * collectLocalInventory,
9
+ * collectRemoteInventory,
10
+ * buildEmulatorInventory,
11
+ * } from './lib/emulator-inventory.js';
12
+ *
13
+ * const local = await collectLocalInventory({
14
+ * emulatorPath, // optional; derived from sdkRoot when omitted
15
+ * adbPath, // optional; derived from sdkRoot when omitted
16
+ * avdHome, // default: ANDROID_AVD_HOME || ~/.android/avd
17
+ * sdkRoot,
18
+ * runningInstances: instanceManager.list(), // {id, avdName, serial, kind, state}
19
+ * });
20
+ * const remotes = await Promise.all(profiles.map((profile) =>
21
+ * collectRemoteInventory({ profile, timeoutMs: 8000 })));
22
+ * sendJson(res, 200, buildEmulatorInventory({ local, remotes }));
23
+ *
24
+ * Design rules (all functions in this module follow them):
25
+ * - zero dependencies, pure ESM, works on Node >= 20;
26
+ * - every filesystem and child_process access is injectable (`fs`, `exec`)
27
+ * so spikes are hermetic and fast; a missing tool never throws;
28
+ * - `collectLocalInventory`/`collectRemoteInventory`/`buildEmulatorInventory`
29
+ * never throw for expected failures — they return `{ok:false, error}` plus
30
+ * empty/default data instead. Parse helpers are total: garbage in, empty
31
+ * list/object out;
32
+ * - remote collection uses exactly ONE non-interactive ssh invocation with
33
+ * section markers to avoid several slow round trips; profile values are
34
+ * validated and single-quote escaped before they reach a shell, and the
35
+ * resulting inventory only exposes `{host, user, sshPort, sdkRoot}` from a
36
+ * profile (never key paths, key material or the ssh executable path).
37
+ */
38
+ import { spawn } from 'node:child_process';
39
+ import { promises as fsp } from 'node:fs';
40
+ import os from 'node:os';
41
+ import path from 'node:path';
42
+
43
+ /** Bounded timeout for each local `emulator`/`adb` probe. */
44
+ export const DEFAULT_LOCAL_TIMEOUT_MS = 5000;
45
+ /** Bounded timeout for the single remote ssh inventory invocation. */
46
+ export const DEFAULT_REMOTE_TIMEOUT_MS = 8000;
47
+ /** Per-stream output cap for injected/child_process exec calls. */
48
+ export const DEFAULT_EXEC_MAX_BYTES = 512 * 1024;
49
+ /** Section markers printed by the remote inventory command. */
50
+ export const REMOTE_SECTION = Object.freeze({
51
+ avds: '@@SECTION:AVDS',
52
+ devices: '@@SECTION:DEVICES',
53
+ host: '@@SECTION:HOST',
54
+ });
55
+
56
+ const ARCH_RE = /^(?:x86_64|amd64|aarch64|arm64|armv[5-8]l?|i[3-6]86|ppc64le?|s390x|riscv64|mips64?)$/i;
57
+ const HOSTNAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$/;
58
+ const SERIAL_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
59
+ const ADB_DEVICE_STATES = new Set([
60
+ 'device',
61
+ 'offline',
62
+ 'unauthorized',
63
+ 'no permissions',
64
+ 'recovery',
65
+ 'sideload',
66
+ 'bootloader',
67
+ 'fastboot',
68
+ 'host',
69
+ 'connecting',
70
+ 'authorizing',
71
+ 'disconnected',
72
+ ]);
73
+ const AVD_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
74
+ const REMOTE_HOST_RE = /^[A-Za-z0-9._:-]{1,253}$/;
75
+ const REMOTE_USER_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}$/;
76
+ const SSH_PATH_RE = /^[A-Za-z0-9._][A-Za-z0-9._/\\:-]{0,499}$/;
77
+ const CONTROL_CHARS_RE = /[\u0000-\u001f\u007f]/;
78
+
79
+ // ---------------------------------------------------------------------------
80
+ // Small tolerant primitives
81
+ // ---------------------------------------------------------------------------
82
+
83
+ function isRecord(value) {
84
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
85
+ }
86
+
87
+ function toText(value) {
88
+ if (value === undefined || value === null) return '';
89
+ if (Buffer.isBuffer(value)) return value.toString('utf8');
90
+ return String(value);
91
+ }
92
+
93
+ /** Trim and cap free-form text; strips non-printable control characters. */
94
+ function cleanText(value, max = 500) {
95
+ const text = toText(value).replace(CONTROL_CHARS_RE, ' ').trim();
96
+ return text.length > max ? text.slice(0, max) : text;
97
+ }
98
+
99
+ function nullableText(value, max = 500) {
100
+ const text = cleanText(value, max);
101
+ return text ? text : null;
102
+ }
103
+
104
+ function shortError(error, max = 300) {
105
+ if (error === undefined || error === null) return 'unknown error';
106
+ const message = isRecord(error) && error.message !== undefined ? error.message : error;
107
+ return cleanText(message, max) || 'unknown error';
108
+ }
109
+
110
+ function clampInt(value, fallback, min, max) {
111
+ const number = Number(value);
112
+ if (!Number.isFinite(number)) return fallback;
113
+ return Math.min(max, Math.max(min, Math.floor(number)));
114
+ }
115
+
116
+ function positiveIntOrNull(value) {
117
+ const number = Number(value);
118
+ if (!Number.isFinite(number) || number <= 0) return null;
119
+ return Math.round(number);
120
+ }
121
+
122
+ function nonNegativeIntOrNull(value) {
123
+ if (value === undefined || value === null || value === '') return null;
124
+ const number = Number(value);
125
+ if (!Number.isFinite(number) || number < 0) return null;
126
+ return Math.round(number);
127
+ }
128
+
129
+ function firstNonEmpty(...values) {
130
+ for (const value of values) {
131
+ const text = toText(value).trim();
132
+ if (text) return text;
133
+ }
134
+ return '';
135
+ }
136
+
137
+ function expandHome(value, home = os.homedir()) {
138
+ const text = toText(value).trim();
139
+ if (!text) return '';
140
+ if (text === '~') return home;
141
+ if (/^~[\\/]/.test(text)) return path.join(home, text.slice(2));
142
+ return text;
143
+ }
144
+
145
+ /** True for Windows drive paths and POSIX/UNC absolute paths (both separators). */
146
+ function isAbsoluteAny(value) {
147
+ return /^(?:[A-Za-z]:[\\/]|[\\/])/.test(toText(value));
148
+ }
149
+
150
+ function sortByName(a, b) {
151
+ const left = String(a && a.name ? a.name : '').toLowerCase();
152
+ const right = String(b && b.name ? b.name : '').toLowerCase();
153
+ if (left < right) return -1;
154
+ if (left > right) return 1;
155
+ const rawLeft = String(a && a.name ? a.name : '');
156
+ const rawRight = String(b && b.name ? b.name : '');
157
+ return rawLeft < rawRight ? -1 : rawLeft > rawRight ? 1 : 0;
158
+ }
159
+
160
+ function uniqueStrings(list) {
161
+ const out = [];
162
+ const seen = new Set();
163
+ for (const item of list) {
164
+ const text = cleanText(item, 400);
165
+ if (!text || seen.has(text)) continue;
166
+ seen.add(text);
167
+ out.push(text);
168
+ }
169
+ return out;
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // AVD home + AVD config parsing
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * Default AVD directory: `ANDROID_AVD_HOME` when set, else `<home>/.android/avd`.
178
+ * `env`/`platform`/`home` are injectable for tests (defaults: process/os).
179
+ */
180
+ export function defaultAvdHome(options = {}) {
181
+ const opts = isRecord(options) ? options : {};
182
+ const env = isRecord(opts.env) ? opts.env : process.env;
183
+ const home = firstNonEmpty(opts.home) || os.homedir();
184
+ const fromEnv = expandHome(env.ANDROID_AVD_HOME, home);
185
+ if (fromEnv) return fromEnv;
186
+ return path.join(home, '.android', 'avd');
187
+ }
188
+
189
+ /**
190
+ * Parse one AVD `.ini`/`config.ini` file into a flat object.
191
+ *
192
+ * Tolerant by design: BOM, CRLF, `#`/`;` comments, `[section]` lines, spaces
193
+ * around `=`, missing trailing newline and values containing `=` are handled.
194
+ * Returns `{}` for non-string input; never throws.
195
+ */
196
+ export function parseAvdIni(text) {
197
+ const out = {};
198
+ try {
199
+ const clean = toText(text).replace(/^\uFEFF/, '');
200
+ for (const rawLine of clean.split(/\r\n?|\n/)) {
201
+ const line = rawLine.trim();
202
+ if (!line) continue;
203
+ if (line.startsWith('#') || line.startsWith(';')) continue;
204
+ if (line.startsWith('[') && line.endsWith(']')) continue;
205
+ const eq = line.indexOf('=');
206
+ if (eq <= 0) continue;
207
+ const key = line.slice(0, eq).trim();
208
+ if (!key) continue;
209
+ let value = line.slice(eq + 1).trim();
210
+ if (
211
+ value.length >= 2 &&
212
+ ((value.startsWith('"') && value.endsWith('"')) ||
213
+ (value.startsWith("'") && value.endsWith("'")))
214
+ ) {
215
+ value = value.slice(1, -1);
216
+ }
217
+ out[key] = value;
218
+ }
219
+ } catch {
220
+ /* total parser: garbage in, {} out */
221
+ }
222
+ return out;
223
+ }
224
+
225
+ function configValue(config, ...keys) {
226
+ for (const key of keys) {
227
+ const value = config[key];
228
+ if (value !== undefined && value !== null && String(value).trim() !== '') {
229
+ return String(value).trim();
230
+ }
231
+ }
232
+ return '';
233
+ }
234
+
235
+ function toIntOrNull(value) {
236
+ const text = toText(value).trim();
237
+ if (!text) return null;
238
+ const number = Number(text);
239
+ return Number.isFinite(number) ? Math.trunc(number) : null;
240
+ }
241
+
242
+ /** Parse `1536M`, `2G`, `512 MB`, `6442450944` into a number. */
243
+ function parseSizeNumber(value) {
244
+ const text = toText(value).trim();
245
+ if (!text) return null;
246
+ const match = /^(\d+(?:\.\d+)?)\s*([KMGT]?)(?:I?B)?$/i.exec(text);
247
+ if (!match) return null;
248
+ const number = Number(match[1]);
249
+ if (!Number.isFinite(number)) return null;
250
+ const unit = match[2].toUpperCase();
251
+ const multiplier =
252
+ unit === 'K' ? 1024 : unit === 'M' ? 1024 ** 2 : unit === 'G' ? 1024 ** 3 : unit === 'T' ? 1024 ** 4 : 1;
253
+ return Math.round(number * multiplier);
254
+ }
255
+
256
+ /** `hw.ramSize` is MB by convention (`1536M` or a bare `1536`). */
257
+ function parseRamMb(value) {
258
+ const text = toText(value).trim();
259
+ if (!text) return null;
260
+ const match = /^(\d+(?:\.\d+)?)\s*([KMGT]?)(?:I?B)?$/i.exec(text);
261
+ if (!match) return null;
262
+ const number = Number(match[1]);
263
+ if (!Number.isFinite(number)) return null;
264
+ const unit = match[2].toUpperCase();
265
+ if (unit === 'G') return Math.round(number * 1024);
266
+ if (unit === 'K') return Math.round(number / 1024);
267
+ if (unit === 'T') return Math.round(number * 1024 * 1024);
268
+ return Math.round(number);
269
+ }
270
+
271
+ function parseHwLcd(config) {
272
+ const width = toIntOrNull(config['hw.lcd.width']);
273
+ const height = toIntOrNull(config['hw.lcd.height']);
274
+ if (width === null || height === null || width <= 0 || height <= 0) return null;
275
+ return {
276
+ width,
277
+ height,
278
+ density: toIntOrNull(config['hw.lcd.density']),
279
+ };
280
+ }
281
+
282
+ function sysdirSegments(value) {
283
+ return toText(value)
284
+ .trim()
285
+ .split(/[\\/]+/)
286
+ .filter(Boolean);
287
+ }
288
+
289
+ /** Resolve `image.sysdir.1` against an optional local SDK root. */
290
+ function resolveSysdir(sdkRoot, relative) {
291
+ const raw = toText(relative).trim();
292
+ if (!raw) return null;
293
+ if (!sdkRoot) return raw;
294
+ const segments = sysdirSegments(raw);
295
+ if (!segments.length) return sdkRoot;
296
+ return path.join(sdkRoot, ...segments);
297
+ }
298
+
299
+ function deriveTarget(ini, config) {
300
+ const explicit = configValue(ini, 'target') || configValue(config, 'target');
301
+ if (explicit) return explicit;
302
+ const sysdir = configValue(config, 'image.sysdir.1', 'image.sysdir.2');
303
+ const match = /(?:^|[\\/])android-(\d+)(?:[\\/]|$)/.exec(sysdir);
304
+ if (match) return `android-${match[1]}`;
305
+ return null;
306
+ }
307
+
308
+ function deriveAbi(config) {
309
+ const explicit = configValue(config, 'abi.type', 'hw.cpu.arch').toLowerCase();
310
+ if (explicit) return explicit;
311
+ const segments = sysdirSegments(configValue(config, 'image.sysdir.1'));
312
+ const last = segments.length ? segments[segments.length - 1].toLowerCase() : '';
313
+ return /^(?:x86_64|x86|arm64-v8a|armeabi-v7a|mips|mips64)$/.test(last) ? last : null;
314
+ }
315
+
316
+ /** Resolve the `.avd` directory from `path`/`path.rel`, defaulting to `<avdHome>/<name>.avd`. */
317
+ function resolveAvdPath(ini, avdHome, name) {
318
+ const declared = toText(ini.path).trim();
319
+ if (declared) {
320
+ return isAbsoluteAny(declared) ? declared : path.resolve(avdHome, declared);
321
+ }
322
+ const relative = toText(ini['path.rel']).trim();
323
+ if (relative) return path.resolve(avdHome, relative);
324
+ return path.join(avdHome, `${name}.avd`);
325
+ }
326
+
327
+ function fileSystemFor(override) {
328
+ if (!isRecord(override)) return fsp;
329
+ return {
330
+ readdir: typeof override.readdir === 'function' ? override.readdir : fsp.readdir,
331
+ readFile: typeof override.readFile === 'function' ? override.readFile : fsp.readFile,
332
+ stat: typeof override.stat === 'function' ? override.stat : fsp.stat,
333
+ };
334
+ }
335
+
336
+ function direntInfo(entry) {
337
+ if (typeof entry === 'string') return { name: entry, file: true };
338
+ if (!isRecord(entry)) return null;
339
+ const name = toText(entry.name);
340
+ if (!name) return null;
341
+ let file = true;
342
+ if (typeof entry.isFile === 'function') {
343
+ try {
344
+ file = entry.isFile() === true;
345
+ } catch {
346
+ file = true;
347
+ }
348
+ }
349
+ return { name, file };
350
+ }
351
+
352
+ function makeAvd(name, fields = {}) {
353
+ return {
354
+ name,
355
+ path: fields.path === undefined ? null : fields.path,
356
+ target: fields.target === undefined ? null : fields.target,
357
+ abi: fields.abi === undefined ? null : fields.abi,
358
+ sysdir: fields.sysdir === undefined ? null : fields.sysdir,
359
+ hwLcd: fields.hwLcd === undefined ? null : fields.hwLcd,
360
+ hwRamMb: fields.hwRamMb === undefined ? null : fields.hwRamMb,
361
+ diskBytes: fields.diskBytes === undefined ? null : fields.diskBytes,
362
+ snapshotCount: fields.snapshotCount === undefined ? null : fields.snapshotCount,
363
+ ...(fields.error ? { error: fields.error } : {}),
364
+ };
365
+ }
366
+
367
+ async function scanOneAvd(io, avdHome, name, sdkRoot) {
368
+ const iniPath = path.join(avdHome, `${name}.ini`);
369
+ let ini;
370
+ try {
371
+ ini = parseAvdIni(await io.readFile(iniPath, 'utf8'));
372
+ } catch (error) {
373
+ return makeAvd(name, {
374
+ path: path.join(avdHome, `${name}.avd`),
375
+ error:
376
+ error && error.code === 'ENOENT'
377
+ ? 'missing AVD ini'
378
+ : `unreadable AVD ini (${shortError(error, 120)})`,
379
+ });
380
+ }
381
+ const avdPath = resolveAvdPath(ini, avdHome, name);
382
+ let config = {};
383
+ let error;
384
+ try {
385
+ config = parseAvdIni(await io.readFile(path.join(avdPath, 'config.ini'), 'utf8'));
386
+ } catch (cause) {
387
+ error =
388
+ cause && cause.code === 'ENOENT'
389
+ ? 'missing config.ini'
390
+ : `unreadable config.ini (${shortError(cause, 120)})`;
391
+ }
392
+ let snapshotCount = null;
393
+ try {
394
+ const snapshots = await io.readdir(path.join(avdPath, 'snapshots'), { withFileTypes: true });
395
+ snapshotCount = Array.isArray(snapshots) ? snapshots.length : null;
396
+ } catch (cause) {
397
+ snapshotCount = cause && cause.code === 'ENOENT' ? 0 : null;
398
+ }
399
+ const sysdir = resolveSysdir(sdkRoot, configValue(config, 'image.sysdir.1'));
400
+ return makeAvd(name, {
401
+ path: avdPath,
402
+ target: deriveTarget(ini, config),
403
+ abi: deriveAbi(config),
404
+ sysdir,
405
+ hwLcd: parseHwLcd(config),
406
+ hwRamMb: parseRamMb(configValue(config, 'hw.ramSize')),
407
+ diskBytes: parseSizeNumber(configValue(config, 'disk.dataPartition.size')),
408
+ snapshotCount,
409
+ ...(error ? { error } : {}),
410
+ });
411
+ }
412
+
413
+ function resolveAvdHome(options, env) {
414
+ const explicit = expandHome(options.avdHome, options.home || os.homedir());
415
+ if (explicit) return explicit;
416
+ return defaultAvdHome({
417
+ env,
418
+ platform: options.platform || process.platform,
419
+ home: options.home || os.homedir(),
420
+ });
421
+ }
422
+
423
+ /**
424
+ * Scan `avdHome` and report diagnostics: `{ok, avdHome, avds, error?}`.
425
+ * Never throws for unreadable directories or broken AVD configs.
426
+ */
427
+ export async function scanLocalAvdsReport(options = {}) {
428
+ const opts = isRecord(options) ? options : {};
429
+ const env = isRecord(opts.env) ? opts.env : process.env;
430
+ let avdHome;
431
+ try {
432
+ avdHome = resolveAvdHome(opts, env);
433
+ } catch (error) {
434
+ return { ok: false, avdHome: null, avds: [], error: shortError(error) };
435
+ }
436
+ const io = fileSystemFor(opts.fs);
437
+ const sdkRoot = firstNonEmpty(opts.sdkRoot);
438
+ let entries;
439
+ try {
440
+ entries = await io.readdir(avdHome, { withFileTypes: true });
441
+ } catch (error) {
442
+ return {
443
+ ok: true,
444
+ avdHome,
445
+ avds: [],
446
+ error: `AVD home is not readable (${shortError(error, 200)})`,
447
+ };
448
+ }
449
+ const names = [];
450
+ const seen = new Set();
451
+ for (const entry of Array.isArray(entries) ? entries : []) {
452
+ const info = direntInfo(entry);
453
+ if (!info || !info.file) continue;
454
+ if (!/\.ini$/i.test(info.name)) continue;
455
+ const name = info.name.slice(0, -4);
456
+ if (!name || seen.has(name)) continue;
457
+ seen.add(name);
458
+ names.push(name);
459
+ }
460
+ names.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()) || (a < b ? -1 : a > b ? 1 : 0));
461
+ const avds = [];
462
+ try {
463
+ for (const name of names) {
464
+ avds.push(await scanOneAvd(io, avdHome, name, sdkRoot));
465
+ }
466
+ } catch (error) {
467
+ return { ok: false, avdHome, avds, error: shortError(error) };
468
+ }
469
+ return { ok: true, avdHome, avds };
470
+ }
471
+
472
+ /**
473
+ * List locally installed AVDs from the AVD home (filesystem only; no tools are
474
+ * spawned). Always returns an array; broken entries carry an `error` field.
475
+ */
476
+ export async function scanLocalAvds(options = {}) {
477
+ const report = await scanLocalAvdsReport(options);
478
+ return report.avds;
479
+ }
480
+
481
+ // ---------------------------------------------------------------------------
482
+ // Text parsers for tool output (`emulator -list-avds`, `adb devices -l`, host)
483
+ // ---------------------------------------------------------------------------
484
+
485
+ /**
486
+ * Parse `adb devices -l` output.
487
+ * Returns `[{serial, state, product?, model?, device?, transportId?}]`.
488
+ * Handles CRLF, network serials, offline/unauthorized/no-permissions states and
489
+ * skips adb daemon/header/error lines. Never throws.
490
+ */
491
+ export function parseAdbDevices(text) {
492
+ const out = [];
493
+ const seen = new Set();
494
+ try {
495
+ const clean = toText(text).replace(/\r\n?/g, '\n');
496
+ for (const rawLine of clean.split('\n')) {
497
+ const line = rawLine.trim();
498
+ if (!line) continue;
499
+ if (/^list of devices attached\b/i.test(line)) continue;
500
+ if (/^[*-]/.test(line)) continue;
501
+ if (/^(?:adb|error|warning|failed|unknown|cannot|unable)\b/i.test(line)) continue;
502
+ const tokens = line.split(/\s+/);
503
+ if (tokens.length < 2) continue;
504
+ const serial = tokens[0];
505
+ if (!SERIAL_RE.test(serial)) continue;
506
+ let state = tokens[1].toLowerCase();
507
+ let index = 2;
508
+ if (state === 'no' && (tokens[2] || '').toLowerCase() === 'permissions') {
509
+ state = 'no permissions';
510
+ index = 3;
511
+ } else if (!ADB_DEVICE_STATES.has(state)) {
512
+ continue;
513
+ }
514
+ const device = { serial, state };
515
+ for (; index < tokens.length; index += 1) {
516
+ const field = /^([A-Za-z][A-Za-z0-9_]*):(.*)$/.exec(tokens[index]);
517
+ if (!field) continue;
518
+ const key = field[1];
519
+ const value = field[2];
520
+ if (key === 'product' || key === 'model' || key === 'device') {
521
+ device[key] = cleanText(value, 128);
522
+ } else if (key === 'transport_id') {
523
+ const transportId = Number(value);
524
+ device.transportId = Number.isFinite(transportId) ? transportId : cleanText(value, 64);
525
+ }
526
+ }
527
+ if (seen.has(serial)) continue;
528
+ seen.add(serial);
529
+ out.push(device);
530
+ }
531
+ } catch {
532
+ /* total parser: garbage in, [] out */
533
+ }
534
+ return out;
535
+ }
536
+
537
+ /**
538
+ * Parse `emulator -list-avds` stdout into AVD names. Trims CRLF/blank lines,
539
+ * ignores INFO/WARNING/ERROR/PANIC chatter and shell "not found" noise, and
540
+ * dedupes while preserving order. Never throws.
541
+ */
542
+ export function parseEmulatorList(text) {
543
+ const out = [];
544
+ const seen = new Set();
545
+ try {
546
+ const clean = toText(text).replace(/\r\n?/g, '\n');
547
+ for (const rawLine of clean.split('\n')) {
548
+ const line = rawLine.trim();
549
+ if (!line) continue;
550
+ if (/^(?:INFO|WARNING|WARN|ERROR|ERR|FATAL|PANIC|DEBUG|TRACE)\b/i.test(line)) continue;
551
+ if (/^(?:[>*#$]|sh:|bash:|emulator:|adb:|zsh:)/i.test(line)) continue;
552
+ if (/command not found|no such file|permission denied|missing emulator engine|could not launch|failed to (?:load|start|launch)/i.test(line)) {
553
+ continue;
554
+ }
555
+ // AVD names are shell/path friendly and never contain whitespace; this
556
+ // also filters multi-word error messages that slipped past the prefixes.
557
+ if (/\s/.test(line)) continue;
558
+ if (line.length > 128) continue;
559
+ if (!AVD_NAME_RE.test(line)) continue;
560
+ if (seen.has(line)) continue;
561
+ seen.add(line);
562
+ out.push(line);
563
+ }
564
+ } catch {
565
+ /* total parser: garbage in, [] out */
566
+ }
567
+ return out;
568
+ }
569
+
570
+ /**
571
+ * Parse Linux `uptime` output into
572
+ * `{text, up, upSeconds, users, loadAverage}`. Returns null-ish fields for
573
+ * unparseable input; never throws.
574
+ */
575
+ export function parseUptime(text) {
576
+ const raw = cleanText(text, 300);
577
+ const out = { text: raw, up: null, upSeconds: null, users: null, loadAverage: [] };
578
+ if (!raw) return out;
579
+ try {
580
+ const loadMatch = /load averages?:\s*([0-9][0-9.,\s]*)/i.exec(raw);
581
+ if (loadMatch) {
582
+ const values = loadMatch[1]
583
+ .replace(/,/g, ' ')
584
+ .trim()
585
+ .split(/\s+/)
586
+ .slice(0, 3)
587
+ .map(Number)
588
+ .filter((value) => Number.isFinite(value));
589
+ if (values.length) out.loadAverage = values;
590
+ }
591
+ const usersMatch = /(\d+)\s+users?\b/i.exec(raw);
592
+ if (usersMatch) out.users = Number(usersMatch[1]);
593
+ const upMatch = /\bup\s+(.+?)(?=,\s*\d+\s+users?\b|,\s*load averages?:|$)/i.exec(raw);
594
+ if (upMatch) {
595
+ const span = upMatch[1].replace(/\s+/g, ' ').replace(/,\s*$/, '').trim();
596
+ if (span) {
597
+ out.up = `up ${span}`;
598
+ let seconds = 0;
599
+ let matched = false;
600
+ const days = /(\d+)\s+days?\b/i.exec(span);
601
+ if (days) {
602
+ seconds += Number(days[1]) * 86400;
603
+ matched = true;
604
+ }
605
+ const hoursMinutes = /(\d+):(\d{2})/.exec(span);
606
+ if (hoursMinutes) {
607
+ seconds += Number(hoursMinutes[1]) * 3600 + Number(hoursMinutes[2]) * 60;
608
+ matched = true;
609
+ }
610
+ const minutes = /(\d+)\s+min(?:ute)?s?/i.exec(span);
611
+ if (minutes) {
612
+ seconds += Number(minutes[1]) * 60;
613
+ matched = true;
614
+ }
615
+ if (matched) out.upSeconds = seconds;
616
+ }
617
+ }
618
+ } catch {
619
+ /* total parser */
620
+ }
621
+ return out;
622
+ }
623
+
624
+ /**
625
+ * Parse the remote host section (`hostname; uname -m; uptime`) into
626
+ * `{hostname, arch, uptime}`. Missing/garbled commands leave `null` fields;
627
+ * never throws.
628
+ */
629
+ export function parseHostInfo(text) {
630
+ const out = { hostname: null, arch: null, uptime: null };
631
+ try {
632
+ const lines = toText(text)
633
+ .replace(/\r/g, '')
634
+ .split('\n')
635
+ .map((line) => line.trim())
636
+ .filter(Boolean);
637
+ for (const line of lines) {
638
+ if (!out.arch && ARCH_RE.test(line)) {
639
+ out.arch = line;
640
+ continue;
641
+ }
642
+ if (
643
+ !out.uptime &&
644
+ (/load averages?:/i.test(line) || /(?:^|\s)up\s+\d/i.test(line))
645
+ ) {
646
+ const parsed = parseUptime(line);
647
+ out.uptime = parsed.up || cleanText(line, 200) || null;
648
+ continue;
649
+ }
650
+ if (!out.hostname && HOSTNAME_RE.test(line) && !ARCH_RE.test(line)) {
651
+ out.hostname = line;
652
+ }
653
+ }
654
+ } catch {
655
+ /* total parser */
656
+ }
657
+ return out;
658
+ }
659
+
660
+ // ---------------------------------------------------------------------------
661
+ // Bounded exec (default child_process runner + injected runner support)
662
+ // ---------------------------------------------------------------------------
663
+
664
+ /**
665
+ * Default exec runner with the injected-exec contract:
666
+ * `(file, args, {timeoutMs, maxBytes, env}) => Promise<{code, stdout, stderr,
667
+ * error, timedOut}>`. argv-only (no shell), output-bounded, timeout-bounded,
668
+ * never rejects.
669
+ */
670
+ export function defaultExec(file, args, options = {}) {
671
+ const opts = isRecord(options) ? options : {};
672
+ const timeoutMs = clampInt(opts.timeoutMs, DEFAULT_LOCAL_TIMEOUT_MS, 250, 120000);
673
+ const maxBytes = clampInt(opts.maxBytes, DEFAULT_EXEC_MAX_BYTES, 1024, 16 * 1024 * 1024);
674
+ const env = isRecord(opts.env) ? { ...process.env, ...opts.env } : process.env;
675
+ return new Promise((resolve) => {
676
+ if (typeof file !== 'string' || !file.trim()) {
677
+ resolve({ code: null, stdout: '', stderr: '', error: 'missing executable path', timedOut: false });
678
+ return;
679
+ }
680
+ let child;
681
+ try {
682
+ child = spawn(file, Array.isArray(args) ? args.map(String) : [], {
683
+ windowsHide: true,
684
+ stdio: ['ignore', 'pipe', 'pipe'],
685
+ env,
686
+ });
687
+ } catch (error) {
688
+ resolve({ code: null, stdout: '', stderr: '', error: shortError(error), timedOut: false });
689
+ return;
690
+ }
691
+ const stdoutChunks = [];
692
+ const stderrChunks = [];
693
+ const stdoutState = { bytes: 0 };
694
+ const stderrState = { bytes: 0 };
695
+ let settled = false;
696
+ let timer = null;
697
+ const append = (chunks, state, chunk) => {
698
+ if (settled || !chunk || chunk.length === 0 || state.bytes >= maxBytes) return;
699
+ const remaining = maxBytes - state.bytes;
700
+ const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
701
+ chunks.push(Buffer.from(slice));
702
+ state.bytes += slice.length;
703
+ };
704
+ const finish = (extra) => {
705
+ if (settled) return;
706
+ settled = true;
707
+ if (timer) clearTimeout(timer);
708
+ resolve({
709
+ code: null,
710
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
711
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
712
+ error: null,
713
+ timedOut: false,
714
+ ...extra,
715
+ });
716
+ };
717
+ if (child.stdout) child.stdout.on('data', (chunk) => append(stdoutChunks, stdoutState, chunk));
718
+ if (child.stderr) child.stderr.on('data', (chunk) => append(stderrChunks, stderrState, chunk));
719
+ child.once('error', (error) => finish({ error: shortError(error) }));
720
+ child.once('close', (code) => finish({ code: typeof code === 'number' ? code : null }));
721
+ timer = setTimeout(() => {
722
+ try {
723
+ child.kill('SIGKILL');
724
+ } catch {
725
+ /* already gone */
726
+ }
727
+ finish({ timedOut: true, error: `timed out after ${timeoutMs}ms` });
728
+ }, timeoutMs);
729
+ });
730
+ }
731
+
732
+ function normalizeExecResult(raw, maxBytes) {
733
+ if (!isRecord(raw)) {
734
+ return { code: null, stdout: '', stderr: '', error: 'exec returned no result object', timedOut: false };
735
+ }
736
+ let stdout = toText(raw.stdout);
737
+ let stderr = toText(raw.stderr);
738
+ if (stdout.length > maxBytes) stdout = stdout.slice(0, maxBytes);
739
+ if (stderr.length > maxBytes) stderr = stderr.slice(0, maxBytes);
740
+ let code = null;
741
+ if (raw.code !== undefined && raw.code !== null && raw.code !== '') {
742
+ const number = Number(raw.code);
743
+ if (Number.isFinite(number)) code = number;
744
+ }
745
+ return {
746
+ code,
747
+ stdout,
748
+ stderr,
749
+ error: raw.error === undefined || raw.error === null ? null : shortError(raw.error),
750
+ timedOut: raw.timedOut === true,
751
+ };
752
+ }
753
+
754
+ /** Race a promise against a hard deadline so a broken injected exec cannot hang us. */
755
+ function raceHardTimeout(promise, timeoutMs) {
756
+ let timer = null;
757
+ const guarded = Promise.resolve(promise).then(
758
+ (value) => ({ value }),
759
+ (error) => ({ error }),
760
+ );
761
+ const deadline = new Promise((resolve) => {
762
+ timer = setTimeout(() => resolve({ hardTimeout: true }), Math.max(50, timeoutMs));
763
+ });
764
+ return Promise.race([guarded, deadline]).finally(() => {
765
+ if (timer) clearTimeout(timer);
766
+ });
767
+ }
768
+
769
+ /**
770
+ * Run one exec call through the (possibly injected) runner. Never rejects:
771
+ * thrown errors and hard timeouts become `{code:null, error, timedOut}`.
772
+ */
773
+ async function runExecBounded(exec, file, args, options = {}) {
774
+ const timeoutMs = clampInt(options.timeoutMs, DEFAULT_LOCAL_TIMEOUT_MS, 250, 120000);
775
+ const maxBytes = clampInt(options.maxBytes, DEFAULT_EXEC_MAX_BYTES, 1024, 16 * 1024 * 1024);
776
+ const callOptions = { timeoutMs, maxBytes, ...(options.env ? { env: options.env } : {}) };
777
+ const raced = await raceHardTimeout(
778
+ Promise.resolve().then(() => exec(file, args, callOptions)),
779
+ timeoutMs + 1500,
780
+ );
781
+ if (raced.hardTimeout) {
782
+ return {
783
+ code: null,
784
+ stdout: '',
785
+ stderr: '',
786
+ error: `exec timed out after ${timeoutMs}ms`,
787
+ timedOut: true,
788
+ };
789
+ }
790
+ if (raced.error !== undefined) {
791
+ return { code: null, stdout: '', stderr: '', error: shortError(raced.error), timedOut: false };
792
+ }
793
+ return normalizeExecResult(raced.value, maxBytes);
794
+ }
795
+
796
+ // ---------------------------------------------------------------------------
797
+ // Running-instance merge helpers
798
+ // ---------------------------------------------------------------------------
799
+
800
+ /**
801
+ * Normalize instance summaries (`{id, avdName, serial, kind, state}`) into a
802
+ * JSON-safe array; drops malformed entries and optionally remote instances.
803
+ */
804
+ export function normalizeRunningInstances(list, options = {}) {
805
+ const out = [];
806
+ if (!Array.isArray(list)) return out;
807
+ const excludeRemote = options.excludeRemote === true;
808
+ for (const item of list) {
809
+ if (!isRecord(item)) continue;
810
+ const id = item.id === undefined || item.id === null ? null : cleanText(item.id, 120) || null;
811
+ const avdName = item.avdName === undefined || item.avdName === null ? null : cleanText(item.avdName, 128) || null;
812
+ const kind = item.kind === undefined || item.kind === null ? null : cleanText(item.kind, 32) || null;
813
+ if (excludeRemote && kind === 'remote') continue;
814
+ if (id === null && avdName === null) continue;
815
+ out.push({
816
+ id,
817
+ avdName,
818
+ serial: item.serial === undefined || item.serial === null ? null : cleanText(item.serial, 128) || null,
819
+ kind,
820
+ state: item.state === undefined || item.state === null ? 'unknown' : cleanText(item.state, 32) || 'unknown',
821
+ });
822
+ }
823
+ return out;
824
+ }
825
+
826
+ function runningRef(instance) {
827
+ return {
828
+ instanceId: instance.id === undefined ? null : instance.id,
829
+ serial: instance.serial === undefined ? null : instance.serial,
830
+ state: instance.state === undefined ? 'unknown' : instance.state,
831
+ };
832
+ }
833
+
834
+ /**
835
+ * Attach `running` references to AVDs (case-insensitive fallback for Windows)
836
+ * and append AVDs that are only known from a running instance. Mutates and
837
+ * returns the given array.
838
+ */
839
+ function attachRunningInstances(avds, runningInstances) {
840
+ const byExact = new Map();
841
+ const byLower = new Map();
842
+ for (const avd of avds) {
843
+ if (!byExact.has(avd.name)) byExact.set(avd.name, avd);
844
+ const lower = avd.name.toLowerCase();
845
+ if (!byLower.has(lower)) byLower.set(lower, avd);
846
+ }
847
+ const append = [];
848
+ for (const instance of runningInstances) {
849
+ if (!instance.avdName) continue;
850
+ const target = byExact.get(instance.avdName) || byLower.get(instance.avdName.toLowerCase());
851
+ if (target) {
852
+ if (!target.running) target.running = runningRef(instance);
853
+ continue;
854
+ }
855
+ const placeholder = makeAvd(instance.avdName, {});
856
+ placeholder.source = 'running';
857
+ placeholder.running = runningRef(instance);
858
+ append.push(placeholder);
859
+ byExact.set(placeholder.name, placeholder);
860
+ byLower.set(placeholder.name.toLowerCase(), placeholder);
861
+ }
862
+ for (const avd of append) avds.push(avd);
863
+ return avds;
864
+ }
865
+
866
+ // ---------------------------------------------------------------------------
867
+ // Local collection
868
+ // ---------------------------------------------------------------------------
869
+
870
+ function toolExecNote(label, result, timeoutMs) {
871
+ if (!result) return null;
872
+ if (result.hardTimeout === true) return `${label} timed out after ${timeoutMs}ms`;
873
+ if (result.timedOut) return `${label} timed out after ${timeoutMs}ms`;
874
+ if (result.error) return `${label} failed: ${shortError(result.error, 200)}`;
875
+ if (result.code !== null && result.code !== 0) {
876
+ const detail = cleanText(result.stderr || result.stdout, 200);
877
+ return `${label} exited with code ${result.code}${detail ? `: ${detail}` : ''}`;
878
+ }
879
+ return null;
880
+ }
881
+
882
+ function normalizeScannedAvd(avd) {
883
+ if (!isRecord(avd)) return null;
884
+ const name = cleanText(avd.name, 128);
885
+ if (!name) return null;
886
+ return makeAvd(name, {
887
+ path: nullableText(avd.path, 4096),
888
+ target: nullableText(avd.target, 128),
889
+ abi: nullableText(avd.abi, 64),
890
+ sysdir: nullableText(avd.sysdir, 4096),
891
+ hwLcd: isRecord(avd.hwLcd)
892
+ ? {
893
+ width: positiveIntOrNull(avd.hwLcd.width),
894
+ height: positiveIntOrNull(avd.hwLcd.height),
895
+ density: nonNegativeIntOrNull(avd.hwLcd.density),
896
+ }
897
+ : null,
898
+ hwRamMb: positiveIntOrNull(avd.hwRamMb),
899
+ diskBytes: positiveIntOrNull(avd.diskBytes),
900
+ snapshotCount: nonNegativeIntOrNull(avd.snapshotCount),
901
+ ...(avd.error ? { error: cleanText(avd.error, 300) } : {}),
902
+ });
903
+ }
904
+
905
+ function mergeLocalAvds(scanned, emulatorNames, runningInstances) {
906
+ const byName = new Map();
907
+ const byLower = new Map();
908
+ const lookup = (name) => byName.get(name) || byLower.get(name.toLowerCase());
909
+ const remember = (avd) => {
910
+ byName.set(avd.name, avd);
911
+ if (!byLower.has(avd.name.toLowerCase())) byLower.set(avd.name.toLowerCase(), avd);
912
+ return avd;
913
+ };
914
+ for (const raw of scanned) {
915
+ const avd = normalizeScannedAvd(raw);
916
+ if (!avd) continue;
917
+ if (lookup(avd.name)) continue;
918
+ avd.source = 'filesystem';
919
+ avd.running = null;
920
+ remember(avd);
921
+ }
922
+ for (const rawName of Array.isArray(emulatorNames) ? emulatorNames : []) {
923
+ const name = cleanText(rawName, 128);
924
+ if (!name) continue;
925
+ const existing = lookup(name);
926
+ if (existing) {
927
+ if (existing.source === 'filesystem') existing.source = 'both';
928
+ continue;
929
+ }
930
+ const placeholder = makeAvd(name, {});
931
+ placeholder.source = 'emulator';
932
+ placeholder.running = null;
933
+ remember(placeholder);
934
+ }
935
+ const avds = [...byName.values()];
936
+ attachRunningInstances(avds, runningInstances);
937
+ return avds.sort(sortByName);
938
+ }
939
+
940
+ /**
941
+ * Collect the local emulator inventory.
942
+ *
943
+ * Runs `emulator -list-avds` and `adb devices -l` when binaries are configured
944
+ * (or derivable from `sdkRoot`), concurrently with a filesystem AVD scan, then
945
+ * merges everything. Bounded timeouts; missing tools/thrown execs/timeouts are
946
+ * reported in `notes` instead of throwing.
947
+ *
948
+ * Returns `{ok, avdHome, emulatorPath, adbPath, avds, devices,
949
+ * runningInstances, notes}`; catastrophic failures return `ok:false, error`.
950
+ * Every AVD has `running: {instanceId, serial, state} | null` and a `source`
951
+ * (`filesystem` | `emulator` | `both` | `running`).
952
+ */
953
+ export async function collectLocalInventory(options = {}) {
954
+ const opts = isRecord(options) ? options : {};
955
+ const env = isRecord(opts.env) ? opts.env : process.env;
956
+ const timeoutMs = clampInt(opts.timeoutMs, DEFAULT_LOCAL_TIMEOUT_MS, 500, 30000);
957
+ const exec = typeof opts.exec === 'function' ? opts.exec : defaultExec;
958
+ const platform = opts.platform || process.platform;
959
+ let avdHome;
960
+ try {
961
+ avdHome = resolveAvdHome(opts, env);
962
+ } catch (error) {
963
+ return {
964
+ ok: false,
965
+ avdHome: null,
966
+ emulatorPath: null,
967
+ adbPath: null,
968
+ avds: [],
969
+ devices: [],
970
+ runningInstances: [],
971
+ notes: [],
972
+ error: shortError(error),
973
+ };
974
+ }
975
+ const sdkRoot = firstNonEmpty(opts.sdkRoot, env.ANDROID_SDK_ROOT, env.ANDROID_HOME);
976
+ const exeSuffix = platform === 'win32' ? '.exe' : '';
977
+ const emulatorPath =
978
+ firstNonEmpty(opts.emulatorPath) ||
979
+ (sdkRoot ? path.join(sdkRoot, 'emulator', `emulator${exeSuffix}`) : null);
980
+ const adbPath =
981
+ firstNonEmpty(opts.adbPath) ||
982
+ (sdkRoot ? path.join(sdkRoot, 'platform-tools', `adb${exeSuffix}`) : null);
983
+ const runningInstances = normalizeRunningInstances(opts.runningInstances, { excludeRemote: true });
984
+ const notes = [];
985
+
986
+ const scanTask = scanLocalAvdsReport({
987
+ avdHome,
988
+ sdkRoot: sdkRoot || undefined,
989
+ fs: opts.fs,
990
+ env,
991
+ platform,
992
+ home: opts.home,
993
+ }).catch((error) => ({ ok: false, avdHome, avds: [], error: shortError(error) }));
994
+ const emulatorTask = emulatorPath
995
+ ? runExecBounded(exec, emulatorPath, ['-list-avds'], {
996
+ timeoutMs,
997
+ maxBytes: DEFAULT_EXEC_MAX_BYTES,
998
+ env: { ANDROID_AVD_HOME: avdHome, ...(isRecord(opts.env) ? opts.env : {}) },
999
+ })
1000
+ : Promise.resolve(null);
1001
+ const adbTask = adbPath
1002
+ ? runExecBounded(exec, adbPath, ['devices', '-l'], {
1003
+ timeoutMs,
1004
+ maxBytes: DEFAULT_EXEC_MAX_BYTES,
1005
+ })
1006
+ : Promise.resolve(null);
1007
+
1008
+ let scanReport;
1009
+ let emulatorResult;
1010
+ let adbResult;
1011
+ try {
1012
+ [scanReport, emulatorResult, adbResult] = await Promise.all([scanTask, emulatorTask, adbTask]);
1013
+ } catch (error) {
1014
+ return {
1015
+ ok: false,
1016
+ avdHome,
1017
+ emulatorPath,
1018
+ adbPath,
1019
+ avds: [],
1020
+ devices: [],
1021
+ runningInstances,
1022
+ notes,
1023
+ error: shortError(error),
1024
+ };
1025
+ }
1026
+
1027
+ if (scanReport && scanReport.error) notes.push(`AVD scan: ${scanReport.error}`);
1028
+ const emulatorNames = emulatorResult ? parseEmulatorList(emulatorResult.stdout) : [];
1029
+ const emulatorNote = toolExecNote('emulator -list-avds', emulatorResult, timeoutMs);
1030
+ if (emulatorNote) notes.push(emulatorNote);
1031
+ const devices = adbResult ? parseAdbDevices(adbResult.stdout) : [];
1032
+ const adbNote = toolExecNote('adb devices', adbResult, timeoutMs);
1033
+ if (adbNote) notes.push(adbNote);
1034
+ if (!emulatorPath) {
1035
+ notes.push('emulator binary is not configured; AVDs were only read from the filesystem');
1036
+ }
1037
+ if (!adbPath) {
1038
+ notes.push('adb binary is not configured; connected devices are unavailable');
1039
+ }
1040
+ if (emulatorResult && emulatorResult.timedOut && emulatorNames.length === 0) {
1041
+ notes.push('emulator -list-avds timed out before printing any AVD');
1042
+ }
1043
+ if (adbResult && adbResult.timedOut && devices.length === 0) {
1044
+ notes.push('adb devices timed out before printing any device');
1045
+ }
1046
+
1047
+ const avds = mergeLocalAvds(scanReport && scanReport.avds, emulatorNames, runningInstances);
1048
+ return {
1049
+ ok: true,
1050
+ avdHome,
1051
+ emulatorPath: emulatorPath || null,
1052
+ adbPath: adbPath || null,
1053
+ avds,
1054
+ devices,
1055
+ runningInstances,
1056
+ notes: uniqueStrings(notes),
1057
+ };
1058
+ }
1059
+
1060
+ // ---------------------------------------------------------------------------
1061
+ // Remote collection (one ssh invocation, section markers)
1062
+ // ---------------------------------------------------------------------------
1063
+
1064
+ /** Quote one string as a POSIX `sh` word (single quotes, `'` escaped). */
1065
+ function quotePosix(value) {
1066
+ const text = toText(value);
1067
+ if (!text) throw new Error('remote command argument is empty');
1068
+ if (CONTROL_CHARS_RE.test(text)) throw new Error('remote command argument contains control characters');
1069
+ return `'${text.replace(/'/g, `'\\''`)}'`;
1070
+ }
1071
+
1072
+ function normalizeSshPort(value, fallback = 22) {
1073
+ const number = Number(value);
1074
+ if (!Number.isInteger(number) || number < 1 || number > 65535) return fallback;
1075
+ return number;
1076
+ }
1077
+
1078
+ function requireRemoteHost(value) {
1079
+ const host = toText(value).trim();
1080
+ if (!host) throw new Error('remote inventory requires an SSH host');
1081
+ if (!REMOTE_HOST_RE.test(host)) {
1082
+ throw new Error(`invalid SSH host: ${JSON.stringify(host.slice(0, 80))}`);
1083
+ }
1084
+ return host;
1085
+ }
1086
+
1087
+ function requireRemoteUser(value) {
1088
+ const user = toText(value).trim();
1089
+ if (!user) return 'root';
1090
+ if (!REMOTE_USER_RE.test(user)) {
1091
+ throw new Error(`invalid SSH user: ${JSON.stringify(user.slice(0, 80))}`);
1092
+ }
1093
+ return user;
1094
+ }
1095
+
1096
+ function optionalRemotePath(value, label) {
1097
+ const text = toText(value).trim();
1098
+ if (!text) return '';
1099
+ if (text.length > 500) throw new Error(`${label} is too long`);
1100
+ if (CONTROL_CHARS_RE.test(text)) throw new Error(`${label} contains control characters`);
1101
+ return text;
1102
+ }
1103
+
1104
+ function optionalSshFile(value, label) {
1105
+ const text = toText(value).trim();
1106
+ if (!text) return '';
1107
+ if (text.length > 1000) throw new Error(`${label} is too long`);
1108
+ if (CONTROL_CHARS_RE.test(text)) throw new Error(`${label} contains control characters`);
1109
+ return text;
1110
+ }
1111
+
1112
+ function trimRemoteSlash(value) {
1113
+ return String(value).replace(/[\\/]+$/, '');
1114
+ }
1115
+
1116
+ /**
1117
+ * Build the single remote inventory command + ssh argv.
1118
+ *
1119
+ * Returns `{host, user, sshPort, sshPath, sdkRoot, emulatorPath, adbPath,
1120
+ * timeoutMs, maxBytes, command, args}` where `args` is the full ssh argv
1121
+ * (everything after the ssh executable). Throws on invalid/injection-shaped
1122
+ * profile values; the caller (`collectRemoteInventory`) catches and reports it.
1123
+ */
1124
+ export function buildRemoteInventoryCommand(profile = {}, options = {}) {
1125
+ const src = isRecord(profile) ? profile : {};
1126
+ const opts = isRecord(options) ? options : {};
1127
+ const host = requireRemoteHost(src.host);
1128
+ const user = requireRemoteUser(src.user);
1129
+ const sshPort = normalizeSshPort(src.sshPort, 22);
1130
+ const timeoutMs = clampInt(opts.timeoutMs, DEFAULT_REMOTE_TIMEOUT_MS, 1000, 120000);
1131
+ const maxBytes = clampInt(opts.maxBytes, DEFAULT_EXEC_MAX_BYTES, 4096, 4 * 1024 * 1024);
1132
+ const sdkRoot = optionalRemotePath(src.sdkRoot, 'remote SDK root');
1133
+ const emulatorPath =
1134
+ optionalRemotePath(src.emulatorPath, 'remote emulator path') ||
1135
+ (sdkRoot ? `${trimRemoteSlash(sdkRoot)}/emulator/emulator` : 'emulator');
1136
+ const adbPath =
1137
+ optionalRemotePath(src.adbPath, 'remote adb path') ||
1138
+ (sdkRoot ? `${trimRemoteSlash(sdkRoot)}/platform-tools/adb` : 'adb');
1139
+ const keyPath = optionalSshFile(src.keyPath, 'remote SSH key path');
1140
+ const sshPath = optionalSshFile(src.sshPath, 'ssh executable') || 'ssh';
1141
+ if (!SSH_PATH_RE.test(sshPath)) throw new Error(`invalid ssh executable: ${JSON.stringify(sshPath.slice(0, 80))}`);
1142
+
1143
+ const command = [
1144
+ `echo ${REMOTE_SECTION.avds}`,
1145
+ `${quotePosix(emulatorPath)} -list-avds 2>&1`,
1146
+ `echo ${REMOTE_SECTION.devices}`,
1147
+ `${quotePosix(adbPath)} devices -l 2>&1`,
1148
+ `echo ${REMOTE_SECTION.host}`,
1149
+ 'hostname 2>&1',
1150
+ 'uname -m 2>&1',
1151
+ 'uptime 2>&1',
1152
+ ].join('; ');
1153
+
1154
+ const connectTimeoutSec = Math.max(1, Math.ceil(timeoutMs / 1000));
1155
+ const args = ['-o', 'BatchMode=yes', '-o', `ConnectTimeout=${connectTimeoutSec}`];
1156
+ if (keyPath) args.push('-i', keyPath);
1157
+ args.push('-p', String(sshPort), `${user}@${host}`, command);
1158
+
1159
+ return {
1160
+ host,
1161
+ user,
1162
+ sshPort,
1163
+ sshPath,
1164
+ sdkRoot: sdkRoot || null,
1165
+ emulatorPath,
1166
+ adbPath,
1167
+ timeoutMs,
1168
+ maxBytes,
1169
+ command,
1170
+ args,
1171
+ };
1172
+ }
1173
+
1174
+ function splitMarkerSections(stdout) {
1175
+ const text = toText(stdout);
1176
+ const sections = { avds: null, devices: null, host: null };
1177
+ const found = [];
1178
+ const markerRe = /@@SECTION:(AVDS|DEVICES|HOST)\r?\n?/g;
1179
+ const marks = [];
1180
+ let match;
1181
+ while ((match = markerRe.exec(text))) {
1182
+ marks.push({ key: match[1].toLowerCase(), start: match.index, contentStart: markerRe.lastIndex });
1183
+ }
1184
+ for (let index = 0; index < marks.length; index += 1) {
1185
+ const mark = marks[index];
1186
+ const end = index + 1 < marks.length ? marks[index + 1].start : text.length;
1187
+ sections[mark.key] = text.slice(mark.contentStart, end);
1188
+ found.push(mark.key);
1189
+ }
1190
+ return { sections, found, sawMarker: marks.length > 0 };
1191
+ }
1192
+
1193
+ function firstMeaningfulLine(text) {
1194
+ for (const rawLine of toText(text).replace(/\r/g, '').split('\n')) {
1195
+ const line = rawLine.trim();
1196
+ if (line) return cleanText(line, 200);
1197
+ }
1198
+ return '';
1199
+ }
1200
+
1201
+ /**
1202
+ * Parse the marker-delimited remote output into `{avds, devices, host, notes}`.
1203
+ * Tolerant of missing markers/sections, shell "not found" noise and garbage.
1204
+ */
1205
+ export function parseRemoteInventoryOutput(stdout) {
1206
+ const { sections, found } = splitMarkerSections(stdout);
1207
+ const notes = [];
1208
+ const avds = [];
1209
+ const devices = [];
1210
+ let host = { hostname: null, arch: null, uptime: null };
1211
+ if (!found.length) {
1212
+ notes.push('remote output could not be parsed (no section markers)');
1213
+ return { avds, devices, host, notes };
1214
+ }
1215
+ for (const key of ['avds', 'devices', 'host']) {
1216
+ if (sections[key] === null) notes.push(`remote output is missing the ${key} section`);
1217
+ }
1218
+ if (sections.avds !== null) {
1219
+ const names = parseEmulatorList(sections.avds);
1220
+ for (const name of names) avds.push({ name, target: null, path: null });
1221
+ if (!names.length) {
1222
+ if (/command not found|not found|no such file|permission denied|panic|could not launch/i.test(sections.avds)) {
1223
+ notes.push('remote emulator is not available');
1224
+ } else if (firstMeaningfulLine(sections.avds)) {
1225
+ notes.push('remote emulator output could not be parsed');
1226
+ }
1227
+ }
1228
+ }
1229
+ if (sections.devices !== null) {
1230
+ devices.push(...parseAdbDevices(sections.devices));
1231
+ if (!devices.length) {
1232
+ if (/command not found|not found|no such file|permission denied/i.test(sections.devices)) {
1233
+ notes.push('remote adb is not available');
1234
+ } else if (/error:/i.test(sections.devices)) {
1235
+ notes.push(`remote adb reported an error: ${firstMeaningfulLine(sections.devices)}`);
1236
+ }
1237
+ }
1238
+ }
1239
+ if (sections.host !== null) {
1240
+ host = parseHostInfo(sections.host);
1241
+ if (!host.hostname && !host.arch && !host.uptime && sections.host.trim()) {
1242
+ notes.push('remote host information could not be parsed');
1243
+ }
1244
+ }
1245
+ return { avds, devices, host, notes: uniqueStrings(notes) };
1246
+ }
1247
+
1248
+ /** Public, secret-free view of a remote profile. */
1249
+ function publicRemoteProfile(profile) {
1250
+ const src = isRecord(profile) ? profile : {};
1251
+ return {
1252
+ host: nullableText(src.host, 253),
1253
+ user: nullableText(src.user, 64),
1254
+ sshPort: normalizeSshPort(src.sshPort, 22),
1255
+ sdkRoot: nullableText(src.sdkRoot, 500),
1256
+ };
1257
+ }
1258
+
1259
+ function emptyRemoteHost(reachable) {
1260
+ return { reachable, hostname: null, arch: null, uptime: null, note: null };
1261
+ }
1262
+
1263
+ /**
1264
+ * Collect the inventory of one remote SSH host using exactly ONE ssh
1265
+ * invocation. Never throws: invalid profiles, ssh failures, timeouts and
1266
+ * partial/garbage output become `{ok:false, error}` or `note` fields.
1267
+ *
1268
+ * Returns `{ok, profile:{host,user,sshPort,sdkRoot}, host:{reachable, hostname,
1269
+ * arch, uptime, note}, avds:[{name,target,path}], devices:[...], error?}`.
1270
+ */
1271
+ export async function collectRemoteInventory(options = {}) {
1272
+ const opts = isRecord(options) ? options : {};
1273
+ const exec = typeof opts.exec === 'function' ? opts.exec : defaultExec;
1274
+ const timeoutMs = clampInt(opts.timeoutMs, DEFAULT_REMOTE_TIMEOUT_MS, 1000, 120000);
1275
+ const publicProfile = publicRemoteProfile(opts.profile);
1276
+ const fail = (error) => ({
1277
+ ok: false,
1278
+ profile: publicProfile,
1279
+ host: emptyRemoteHost(false),
1280
+ avds: [],
1281
+ devices: [],
1282
+ error: shortError(error, 400),
1283
+ });
1284
+
1285
+ let built;
1286
+ try {
1287
+ built = buildRemoteInventoryCommand(opts.profile, { timeoutMs, maxBytes: opts.maxBytes });
1288
+ } catch (error) {
1289
+ return fail(error);
1290
+ }
1291
+ const result = await runExecBounded(exec, built.sshPath, built.args, {
1292
+ timeoutMs,
1293
+ maxBytes: built.maxBytes,
1294
+ env: isRecord(opts.env) ? opts.env : undefined,
1295
+ });
1296
+ if (result.timedOut) return fail(`remote inventory timed out after ${timeoutMs}ms`);
1297
+ if (result.error) return fail(`ssh failed: ${shortError(result.error, 300)}`);
1298
+ if (result.code !== null && result.code !== 0) {
1299
+ const detail = cleanText(result.stderr || result.stdout, 300);
1300
+ return fail(`ssh exited with code ${result.code}${detail ? `: ${detail}` : ''}`);
1301
+ }
1302
+ const parsed = parseRemoteInventoryOutput(result.stdout);
1303
+ const note = parsed.notes.length ? parsed.notes.join('; ') : null;
1304
+ return {
1305
+ ok: true,
1306
+ profile: {
1307
+ host: built.host,
1308
+ user: built.user,
1309
+ sshPort: built.sshPort,
1310
+ sdkRoot: built.sdkRoot,
1311
+ },
1312
+ host: {
1313
+ reachable: true,
1314
+ hostname: hostField(parsed.host.hostname),
1315
+ arch: hostField(parsed.host.arch),
1316
+ uptime: hostField(parsed.host.uptime),
1317
+ note,
1318
+ },
1319
+ avds: parsed.avds,
1320
+ devices: parsed.devices,
1321
+ };
1322
+ }
1323
+
1324
+ function hostField(value) {
1325
+ const text = cleanText(value, 500);
1326
+ return text ? text : null;
1327
+ }
1328
+
1329
+ // ---------------------------------------------------------------------------
1330
+ // Inventory assembly
1331
+ // ---------------------------------------------------------------------------
1332
+
1333
+ function normalizeUpdatedAt(value) {
1334
+ if (typeof value === 'string') {
1335
+ const text = value.trim();
1336
+ if (text && Number.isFinite(Date.parse(text))) return text;
1337
+ }
1338
+ if (value instanceof Date && Number.isFinite(value.getTime())) return value.toISOString();
1339
+ const number = Number(value);
1340
+ if (Number.isFinite(number) && number > 0) return new Date(number).toISOString();
1341
+ return new Date().toISOString();
1342
+ }
1343
+
1344
+ function normalizeHwLcd(value) {
1345
+ if (!isRecord(value)) return null;
1346
+ const width = positiveIntOrNull(value.width);
1347
+ const height = positiveIntOrNull(value.height);
1348
+ if (width === null || height === null) return null;
1349
+ return { width, height, density: nonNegativeIntOrNull(value.density) };
1350
+ }
1351
+
1352
+ function normalizeAvdEntry(avd) {
1353
+ if (!isRecord(avd)) return null;
1354
+ const name = cleanText(avd.name, 128);
1355
+ if (!name) return null;
1356
+ const source = cleanText(avd.source, 32) || 'filesystem';
1357
+ return {
1358
+ name,
1359
+ path: nullableText(avd.path, 4096),
1360
+ target: nullableText(avd.target, 128),
1361
+ abi: nullableText(avd.abi, 64),
1362
+ sysdir: nullableText(avd.sysdir, 4096),
1363
+ hwLcd: normalizeHwLcd(avd.hwLcd),
1364
+ hwRamMb: positiveIntOrNull(avd.hwRamMb),
1365
+ diskBytes: positiveIntOrNull(avd.diskBytes),
1366
+ snapshotCount: nonNegativeIntOrNull(avd.snapshotCount),
1367
+ source,
1368
+ running: normalizeRunningRef(avd.running),
1369
+ ...(avd.error ? { error: cleanText(avd.error, 300) } : {}),
1370
+ };
1371
+ }
1372
+
1373
+ function normalizeRunningRef(value) {
1374
+ if (!isRecord(value)) return null;
1375
+ return {
1376
+ instanceId: value.instanceId === undefined ? null : nullableText(value.instanceId, 120),
1377
+ serial: value.serial === undefined ? null : nullableText(value.serial, 128),
1378
+ state: nullableText(value.state, 32) || 'unknown',
1379
+ };
1380
+ }
1381
+
1382
+ function dedupeAvds(avlList) {
1383
+ const byName = new Map();
1384
+ const byLower = new Map();
1385
+ const lookup = (name) => byName.get(name) || byLower.get(name.toLowerCase());
1386
+ for (const avd of avlList) {
1387
+ const existing = lookup(avd.name);
1388
+ if (!existing) {
1389
+ byName.set(avd.name, avd);
1390
+ if (!byLower.has(avd.name.toLowerCase())) byLower.set(avd.name.toLowerCase(), avd);
1391
+ continue;
1392
+ }
1393
+ // Merge missing facts from later duplicates (never throw information away).
1394
+ for (const key of ['path', 'target', 'abi', 'sysdir', 'hwLcd', 'hwRamMb', 'diskBytes', 'snapshotCount', 'error']) {
1395
+ if (existing[key] === null || existing[key] === undefined) {
1396
+ if (avd[key] !== null && avd[key] !== undefined) existing[key] = avd[key];
1397
+ }
1398
+ }
1399
+ if (!existing.running && avd.running) existing.running = avd.running;
1400
+ if (existing.source !== avd.source) existing.source = 'both';
1401
+ }
1402
+ return [...byName.values()].sort(sortByName);
1403
+ }
1404
+
1405
+ function dedupeDevices(deviceList) {
1406
+ const out = [];
1407
+ const seen = new Set();
1408
+ for (const device of deviceList) {
1409
+ if (!isRecord(device)) continue;
1410
+ const serial = cleanText(device.serial, 256);
1411
+ if (!serial || seen.has(serial)) continue;
1412
+ seen.add(serial);
1413
+ const entry = { serial, state: cleanText(device.state, 32) || 'unknown' };
1414
+ for (const key of ['product', 'model', 'device']) {
1415
+ const value = nullableText(device[key], 128);
1416
+ if (value) entry[key] = value;
1417
+ }
1418
+ const transportId = Number(device.transportId);
1419
+ if (Number.isFinite(transportId)) entry.transportId = transportId;
1420
+ out.push(entry);
1421
+ }
1422
+ return out;
1423
+ }
1424
+
1425
+ function normalizeLocalInventory(local) {
1426
+ const src = isRecord(local) ? local : {};
1427
+ const runningInstances = normalizeRunningInstances(src.runningInstances, { excludeRemote: true });
1428
+ const avds = [];
1429
+ for (const raw of Array.isArray(src.avds) ? src.avds : []) {
1430
+ const avd = normalizeAvdEntry(raw);
1431
+ if (avd) avds.push(avd);
1432
+ }
1433
+ const normalized = dedupeAvds(avds);
1434
+ attachRunningInstances(normalized, runningInstances);
1435
+ normalized.sort(sortByName);
1436
+ const out = {
1437
+ avds: normalized,
1438
+ devices: dedupeDevices(Array.isArray(src.devices) ? src.devices : []),
1439
+ runningInstances,
1440
+ };
1441
+ if (src.error) out.error = cleanText(src.error, 500);
1442
+ const notes = Array.isArray(src.notes) ? uniqueStrings(src.notes) : [];
1443
+ if (notes.length) out.notes = notes;
1444
+ return out;
1445
+ }
1446
+
1447
+ function normalizeRemoteEntry(remote) {
1448
+ const src = isRecord(remote) ? remote : {};
1449
+ const hostSrc = isRecord(src.host) ? src.host : {};
1450
+ const avds = [];
1451
+ for (const raw of Array.isArray(src.avds) ? src.avds : []) {
1452
+ if (!isRecord(raw)) continue;
1453
+ const name = cleanText(raw.name, 128);
1454
+ if (!name) continue;
1455
+ avds.push({
1456
+ name,
1457
+ target: nullableText(raw.target, 128),
1458
+ path: nullableText(raw.path, 4096),
1459
+ });
1460
+ }
1461
+ const dedupedAvds = [];
1462
+ const seenAvds = new Set();
1463
+ for (const avd of avds) {
1464
+ const key = avd.name.toLowerCase();
1465
+ if (seenAvds.has(key)) continue;
1466
+ seenAvds.add(key);
1467
+ dedupedAvds.push(avd);
1468
+ }
1469
+ dedupedAvds.sort(sortByName);
1470
+ const entry = {
1471
+ ok: src.ok !== false,
1472
+ profile: publicRemoteProfile(src.profile),
1473
+ host: {
1474
+ reachable: hostSrc.reachable === true,
1475
+ hostname: nullableText(hostSrc.hostname, 253),
1476
+ arch: nullableText(hostSrc.arch, 64),
1477
+ uptime: nullableText(hostSrc.uptime, 200),
1478
+ note: nullableText(hostSrc.note, 500),
1479
+ },
1480
+ avds: dedupedAvds,
1481
+ devices: dedupeDevices(Array.isArray(src.devices) ? src.devices : []),
1482
+ };
1483
+ if (src.error) entry.error = cleanText(src.error, 500);
1484
+ return entry;
1485
+ }
1486
+
1487
+ function normalizeRemotes(remotes) {
1488
+ if (!Array.isArray(remotes)) return [];
1489
+ const out = [];
1490
+ for (const remote of remotes) {
1491
+ if (!isRecord(remote)) continue;
1492
+ out.push(normalizeRemoteEntry(remote));
1493
+ }
1494
+ return out;
1495
+ }
1496
+
1497
+ /**
1498
+ * Assemble the final stable, JSON-safe inventory document:
1499
+ * `{ok, updatedAt, local:{avds, devices, runningInstances, error?}, remotes:[...]}`.
1500
+ *
1501
+ * Dedupes devices by serial and AVDs by name within each host, attaches
1502
+ * running-instance references, sorts AVDs by name, and strips every remote
1503
+ * profile down to `{host, user, sshPort, sdkRoot}`. Never throws: bad input
1504
+ * becomes empty/default collections with `ok:true`, except unexpected internal
1505
+ * failures which return `ok:false`.
1506
+ */
1507
+ export function buildEmulatorInventory(options = {}) {
1508
+ const opts = isRecord(options) ? options : {};
1509
+ const updatedAt = normalizeUpdatedAt(opts.updatedAt);
1510
+ try {
1511
+ return {
1512
+ ok: true,
1513
+ updatedAt,
1514
+ local: normalizeLocalInventory(opts.local),
1515
+ remotes: normalizeRemotes(opts.remotes),
1516
+ };
1517
+ } catch (error) {
1518
+ return {
1519
+ ok: false,
1520
+ updatedAt,
1521
+ local: { avds: [], devices: [], runningInstances: [] },
1522
+ remotes: [],
1523
+ error: shortError(error),
1524
+ };
1525
+ }
1526
+ }