@9l/playwright 0.6.0-beta.1 → 0.6.0-beta.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.
package/dist/android.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validAndroidRuntime = exports.androidRuntimeType = exports.androidVersions = void 0;
3
+ exports.androidBuildTools = exports.androidToolsInstall = exports.androidToolingPaths = exports.androidToolPaths = exports.androidSdkVariables = exports.androidSdkCandidates = exports.androidDefaults = exports.validAndroidRuntime = exports.androidRuntimeType = exports.androidVersions = exports.TargetSetupError = void 0;
4
+ exports.androidLeasePath = androidLeasePath;
4
5
  exports.androidTargetDriver = androidTargetDriver;
6
+ exports.installInPlace = installInPlace;
5
7
  const node_child_process_1 = require("node:child_process");
6
8
  const node_crypto_1 = require("node:crypto");
7
9
  const promises_1 = require("node:fs/promises");
@@ -11,12 +13,33 @@ const node_net_1 = require("node:net");
11
13
  const promises_2 = require("node:timers/promises");
12
14
  const protocol_1 = require("./protocol");
13
15
  const targets_1 = require("./targets");
16
+ const android_device_1 = require("./android-device");
17
+ var targets_2 = require("./targets");
18
+ Object.defineProperty(exports, "TargetSetupError", { enumerable: true, get: function () { return targets_2.TargetSetupError; } });
14
19
  const android_runtime_1 = require("./android-runtime");
20
+ const android_env_1 = require("./android-env");
15
21
  var android_runtime_2 = require("./android-runtime");
16
22
  Object.defineProperty(exports, "androidVersions", { enumerable: true, get: function () { return android_runtime_2.androidVersions; } });
17
23
  Object.defineProperty(exports, "androidRuntimeType", { enumerable: true, get: function () { return android_runtime_2.androidRuntimeType; } });
18
24
  Object.defineProperty(exports, "validAndroidRuntime", { enumerable: true, get: function () { return android_runtime_2.validAndroidRuntime; } });
25
+ var android_env_2 = require("./android-env");
26
+ Object.defineProperty(exports, "androidDefaults", { enumerable: true, get: function () { return android_env_2.androidDefaults; } });
27
+ Object.defineProperty(exports, "androidSdkCandidates", { enumerable: true, get: function () { return android_env_2.androidSdkCandidates; } });
28
+ Object.defineProperty(exports, "androidSdkVariables", { enumerable: true, get: function () { return android_env_2.androidSdkVariables; } });
29
+ Object.defineProperty(exports, "androidToolPaths", { enumerable: true, get: function () { return android_env_2.androidToolPaths; } });
30
+ Object.defineProperty(exports, "androidToolingPaths", { enumerable: true, get: function () { return android_env_2.androidToolingPaths; } });
31
+ Object.defineProperty(exports, "androidToolsInstall", { enumerable: true, get: function () { return android_env_2.androidToolsInstall; } });
32
+ Object.defineProperty(exports, "androidBuildTools", { enumerable: true, get: function () { return android_env_2.androidBuildTools; } });
19
33
  const failure = (reason) => new Error(`9lives Android: ${reason}`);
34
+ // One fixed script per call; every interpolated value is validated by the
35
+ // caller's option checks. The device shell runs it; nothing else does.
36
+ const shellArgs = (script) => ['shell', 'sh', '-c', `'${script}'`];
37
+ /** The host-local lease that gives one owner exclusive use of a device.
38
+ * The driver and installInPlace both take it, so an installation cannot
39
+ * replace the app under a running test or interleave with another installer. */
40
+ function androidLeasePath(serial) {
41
+ return (0, node_path_1.join)((0, node_os_1.homedir)(), '.9lives', 'android-leases', `9l-android-${(0, node_crypto_1.createHash)('sha256').update(serial).digest('hex')}.lock`);
42
+ }
20
43
  const elementKey = 'element-6066-11e4-a52e-4f735466cecf';
21
44
  const timeout = (c) => {
22
45
  c.signal.throwIfAborted();
@@ -26,10 +49,10 @@ const timeout = (c) => {
26
49
  };
27
50
  // Native command output stays in memory and never becomes an error message,
28
51
  // diagnostic artifact or receipt. These commands have explicit, fixed arguments.
29
- function command(file, args, c, env) {
52
+ function command(file, args, c, env, streams = 'stdout') {
30
53
  return new Promise((yes, no) => (0, node_child_process_1.execFile)(file, args, {
31
54
  signal: c.signal, timeout: timeout(c), maxBuffer: 64 * 1024, env,
32
- }, (error, stdout) => error ? no(failure('device_command_failed')) : yes(stdout.trim())));
55
+ }, (error, stdout, stderr) => error ? no(failure('device_command_failed')) : yes((streams === 'both' ? `${stdout}\n${stderr}` : stdout).trim())));
33
56
  }
34
57
  async function freePort() {
35
58
  const server = (0, node_net_1.createServer)();
@@ -116,10 +139,32 @@ function androidTargetDriver(options) {
116
139
  (physical ? !/^[a-zA-Z0-9_.:-]{1,128}$/.test(options.deviceSerial) || options.deviceSerial.startsWith('emulator-') || options.avd !== undefined || options.apk !== undefined
117
140
  : !/^[a-zA-Z0-9_.-]{1,100}$/.test(options.avd)) ||
118
141
  !/^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)+$/.test(options.appPackage) ||
119
- !/^[a-zA-Z0-9_.]+$/.test(options.activity) || !/^[a-f0-9]{64}$/.test(options.apkSHA256))
142
+ !/^[a-zA-Z0-9_.]+$/.test(options.activity) || (options.apkSHA256 === undefined ? options.expected?.apk === undefined : !/^[a-f0-9]{64}$/.test(options.apkSHA256)))
143
+ throw failure('invalid_configuration');
144
+ const expected = options.expected;
145
+ if (expected !== undefined && (Object.keys(expected).some(k => !['apk', 'versionCode', 'versionName', 'signerSHA256'].includes(k)) || Object.keys(expected).length === 0 ||
146
+ (expected.apk !== undefined && (typeof expected.apk !== 'string' || !expected.apk)) ||
147
+ (expected.versionCode !== undefined && !/^[0-9]{1,10}$/.test(expected.versionCode)) ||
148
+ (expected.versionName !== undefined && !/^[A-Za-z0-9._+-]{1,64}$/.test(expected.versionName)) ||
149
+ (expected.signerSHA256 !== undefined && !/^[a-f0-9]{64}$/.test(expected.signerSHA256))))
120
150
  throw failure('invalid_configuration');
151
+ // Resolved at open: the declared artifact's digest wins over apkSHA256.
152
+ let expectedDigest = options.apkSHA256 ?? '';
121
153
  if (Object.keys(controls).length > 128)
122
154
  throw failure('invalid_controls');
155
+ const expectedWindows = options.baseline?.windows ?? 1;
156
+ const backPresses = options.recovery?.back ?? 0;
157
+ if ((options.baseline !== undefined && (Object.keys(options.baseline).some(k => k !== 'windows') || !Number.isInteger(expectedWindows) || expectedWindows < 1 || expectedWindows > 16)) ||
158
+ (options.recovery !== undefined && (Object.keys(options.recovery).some(k => k !== 'back') || !Number.isInteger(backPresses) || backPresses < 1 || backPresses > 16)) ||
159
+ ((options.baseline !== undefined || options.recovery !== undefined) && !physical) ||
160
+ (options.diagnostics !== undefined && (Object.keys(options.diagnostics).some(k => k !== 'gestures') || typeof options.diagnostics.gestures !== 'boolean')))
161
+ throw failure('invalid_configuration');
162
+ const diagnostics = options.diagnostics?.gestures === true;
163
+ const requires = options.requires;
164
+ if (requires !== undefined && (Object.keys(requires).some(k => !['posture', 'minWidthDp'].includes(k)) || Object.keys(requires).length === 0 ||
165
+ (requires.posture !== undefined && !['opened', 'half-opened', 'closed', 'flat'].includes(requires.posture)) ||
166
+ (requires.minWidthDp !== undefined && (!Number.isInteger(requires.minWidthDp) || requires.minWidthDp < 1 || requires.minWidthDp > 10000))))
167
+ throw failure('invalid_configuration');
123
168
  for (const [id, control] of Object.entries(controls)) {
124
169
  if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/.test(id) || !control ||
125
170
  Object.keys(control).some(k => !['text', 'accessibilityId', 'accessibilityIdSuffix', 'className', 'selected'].includes(k)) ||
@@ -130,12 +175,22 @@ function androidTargetDriver(options) {
130
175
  (control.selected !== undefined && typeof control.selected !== 'boolean'))
131
176
  throw failure('invalid_controls');
132
177
  }
133
- const sdk = (0, node_path_1.resolve)(options.sdkRoot), tools = (0, node_path_1.resolve)(options.toolsRoot);
134
- const adb = (0, node_path_1.join)(sdk, 'platform-tools', 'adb'), emulatorPath = (0, node_path_1.join)(sdk, 'emulator', 'emulator');
178
+ // Explicit roots win; omitted ones come from the same discovery doctor reports.
179
+ const defaults = options.sdkRoot === undefined || options.toolsRoot === undefined ? (0, android_env_1.androidDefaults)() : {};
180
+ const sdkRoot = options.sdkRoot ?? defaults.sdkRoot, toolsRoot = options.toolsRoot ?? defaults.toolsRoot;
181
+ if (!sdkRoot)
182
+ throw failure('sdk_not_found');
183
+ if (!toolsRoot)
184
+ throw failure('tools_not_found');
185
+ const sdk = (0, node_path_1.resolve)(sdkRoot), tools = (0, node_path_1.resolve)(toolsRoot);
186
+ const sdkTools = (0, android_env_1.androidToolPaths)(sdk), tooling = (0, android_env_1.androidToolingPaths)(tools);
187
+ const adb = sdkTools.adb, emulatorPath = sdkTools.emulator;
135
188
  // Explicit environment allowlist: no application/provider credentials reach
136
189
  // Appium, adb or the emulator. Go --pass-env remains necessary for test data.
137
190
  const env = {};
138
- for (const key of ['PATH', 'HOME', 'TMPDIR', 'JAVA_HOME', 'SYSTEMROOT'])
191
+ // The AVD and user-config locations are paths, not credentials: without
192
+ // them an emulator whose AVDs live outside ~/.android/avd is not found.
193
+ for (const key of ['PATH', 'HOME', 'TMPDIR', 'JAVA_HOME', 'SYSTEMROOT', 'ANDROID_AVD_HOME', 'ANDROID_USER_HOME', 'ANDROID_EMULATOR_HOME'])
139
194
  if (process.env[key])
140
195
  env[key] = process.env[key];
141
196
  env.ANDROID_HOME = sdk;
@@ -150,17 +205,144 @@ function androidTargetDriver(options) {
150
205
  const mockStore = '/data/local/tmp/mock_apps.json';
151
206
  const mockBackup = `/data/local/tmp/9l-${owner}-mock-apps.json`;
152
207
  let mockStorePresent, mockPermission;
153
- const shell = (script) => ['shell', 'sh', '-c', `'${script}'`];
154
- const installedBuild = async (c) => {
155
- if (await adbRun(['get-state'], c) !== 'device' || await adbRun(['shell', 'getprop', 'ro.kernel.qemu'], c) === '1')
156
- throw failure('not_physical_device');
208
+ const shell = shellArgs;
209
+ // Device-state reads filter on the device and stay in memory. They never
210
+ // request, store or bypass a credential, and never change lock settings.
211
+ // A failed device read during cancellation, past the deadline or after
212
+ // close is that interruption, never a reading of the device.
213
+ const interrupted = (c) => c.signal.aborted || Date.now() >= c.deadlineMs || closed;
214
+ const readDeviceState = async (c) => (0, android_device_1.parseDeviceState)(await adbRun(shell(`(dumpsys window; dumpsys power) 2>/dev/null | grep -E "${android_device_1.deviceStatePattern}" | head -c 4096`), c));
215
+ // A dump that yields neither a window nor a focus line was not observed
216
+ // (unavailable or empty); it is never read as zero windows. Nor was one cut
217
+ // at the byte bound: only output ending in the completion marker counts.
218
+ // The window list comes from `dumpsys window windows`; the focus line is
219
+ // in `dumpsys window displays` (API 35 prints it only there), and the
220
+ // first focus line read wins.
221
+ const windowsEnd = '9l-windows-end';
222
+ const readWindows = async (c) => {
223
+ const dump = await adbRun(shell(`{ { dumpsys window windows; dumpsys window displays; } 2>/dev/null | grep -E "${android_device_1.windowPattern}"; echo ${windowsEnd}; } | head -c 8192`), c);
224
+ if (!dump.endsWith(windowsEnd))
225
+ return undefined;
226
+ const windows = (0, android_device_1.parseWindows)(dump.slice(0, -windowsEnd.length), options.appPackage);
227
+ return windows.windows === 0 && windows.focus === 'unknown' ? undefined : windows;
228
+ };
229
+ // With diagnostics, the window state before the last gesture; a read that
230
+ // fails leaves the gesture to proceed and the observation absent. The
231
+ // observation stays as diagnostic metadata, but any operation other than a
232
+ // visibility read between the gesture and a hidden assertion disarms the
233
+ // observer heuristic: it describes a dismissal sequence (gesture, then the
234
+ // control should be gone), nothing else.
235
+ // A touch's requested point stays with its observation, so a failure
236
+ // after the touch (the hidden assertion) still reports where it was sent;
237
+ // any other gesture replaces it.
238
+ let lastGesture, lastPoint, armed = false;
239
+ const observeGesture = async (c, point) => {
240
+ if (!diagnostics)
241
+ return;
242
+ lastPoint = point;
243
+ try {
244
+ lastGesture = await readWindows(c);
245
+ }
246
+ catch {
247
+ lastGesture = undefined;
248
+ }
249
+ armed = lastGesture !== undefined;
250
+ };
251
+ const disarm = () => { armed = false; };
252
+ // A baseline reading is clean only when every component was observed as
253
+ // declared; a difference is a dirty reason; anything else is unknown and
254
+ // can neither classify the state nor count as a restored baseline.
255
+ const readBaseline = async (c) => {
256
+ const windows = await readWindows(c);
257
+ if (!windows)
258
+ return 'unknown';
259
+ const ime = (0, android_device_1.parseIme)(await adbRun(shell(`dumpsys input_method 2>/dev/null | grep -E "${android_device_1.imePattern}" | head -c 1024`), c));
260
+ if (windows.focus === 'foreign')
261
+ return 'foreign-focus';
262
+ if (windows.windows > expectedWindows)
263
+ return 'extra-window';
264
+ if (ime === 'shown')
265
+ return 'ime-showing';
266
+ return windows.focus === 'app' && windows.windows === expectedWindows && ime === 'hidden' ? 'clean' : 'unknown';
267
+ };
268
+ const dirty = (reading) => reading !== 'clean' && reading !== 'unknown';
269
+ let setupRecord;
270
+ // The display the session targets. Screenshots name it explicitly, so a
271
+ // multi-display device never answers with its first display by default.
272
+ // The recorded size and density are the display's current logical layout
273
+ // (rotation and density overrides applied) when the dump reports one, and
274
+ // its physical metrics otherwise. Read before any session can launch the
275
+ // app, so a mismatch changes nothing.
276
+ let display, posture = 'unknown';
277
+ // A dump cut at its byte bound may have lost a display, so it names none:
278
+ // only output ending in the completion marker is discovery data.
279
+ const displaysEnd = '9l-displays-end';
280
+ const readDisplays = async (c) => {
281
+ const output = await adbRun(shell(`{ dumpsys display 2>/dev/null | grep -E "${android_device_1.displayPattern}"; echo ${displaysEnd}; } | head -c 32768`), c);
282
+ const dump = output.endsWith(displaysEnd) ? output.slice(0, -displaysEnd.length) : '';
283
+ display = (0, android_device_1.activeDisplay)((0, android_device_1.parseDisplays)(dump));
284
+ const logical = display && (0, android_device_1.parseLogicalDisplays)(dump).get(display.id);
285
+ if (display && logical)
286
+ display = { ...display, ...logical };
287
+ posture = (0, android_device_1.parsePosture)(await adbRun(shell(`dumpsys device_state 2>&1 | grep -E "${android_device_1.posturePattern}" | head -c 2048`), c));
288
+ if (requires?.posture !== undefined && posture !== requires.posture)
289
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'posture', stage: 'open' });
290
+ if (requires?.minWidthDp !== undefined && (!display || Math.floor(display.width * 160 / display.density) < requires.minWidthDp))
291
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'display-width', stage: 'open' });
292
+ };
293
+ // The PNG stays in memory and leaves only as a digest.
294
+ // Closing the driver cancels a pending capture, as it does a request.
295
+ const screenDigest = (c) => new Promise((yes, no) => (0, node_child_process_1.execFile)(adb, ['-s', serial, 'exec-out', 'screencap', '-p', ...(display ? ['-d', display.id] : [])], {
296
+ signal: AbortSignal.any([c.signal, controller.signal]), timeout: timeout(c), maxBuffer: 64 * 1024 * 1024, env, encoding: 'buffer',
297
+ }, (error, stdout) => {
298
+ if (error || !Buffer.isBuffer(stdout) || stdout.length < 8 || stdout.subarray(0, 8).toString('latin1') !== '\x89PNG\r\n\x1a\n')
299
+ return no(failure('screenshot_failed'));
300
+ yes((0, node_crypto_1.createHash)('sha256').update(stdout).digest('hex'));
301
+ }));
302
+ const installedPath = async (c) => {
157
303
  const path = await adbRun(['shell', 'pm', 'path', options.appPackage], c);
158
304
  // Split builds require a digest of the entire installation; fail closed.
159
305
  if (!/^package:(\/data\/app\/[A-Za-z0-9_./=+~\-]+\/base\.apk)$/.test(path))
160
306
  throw failure('unsupported_installed_build');
161
- const digest = await adbRun(['shell', 'sha256sum', path.slice(8)], c);
162
- if (digest.split(/\s+/)[0] !== options.apkSHA256)
163
- throw failure('apk_digest_mismatch');
307
+ return path.slice(8);
308
+ };
309
+ // A wrong or stale installed build is a setup mismatch, not a driver fault.
310
+ const installedBuild = async (c) => {
311
+ if (await adbRun(['get-state'], c) !== 'device' || await adbRun(['shell', 'getprop', 'ro.kernel.qemu'], c) === '1')
312
+ throw failure('not_physical_device');
313
+ const digest = await adbRun(['shell', 'sha256sum', await installedPath(c)], c);
314
+ if (digest.split(/\s+/)[0] !== expectedDigest)
315
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-digest', stage: 'open' });
316
+ };
317
+ // apksigner prints only certificate facts; the first signer's digest is kept.
318
+ const signerOf = async (apk, c) => {
319
+ const signer = (0, android_device_1.parseSigner)(await command(sdkTools.apksigner, ['verify', '--print-certs', apk], c, env));
320
+ if (!signer)
321
+ throw failure('unreadable_signer');
322
+ return signer;
323
+ };
324
+ let versionCode = 'unknown', versionName = 'unknown', signer = 'unknown';
325
+ // Version from the package manager; the signer from the local APK (owned
326
+ // emulator) or, when declared, from the installed base APK pulled into the
327
+ // attempt's private scratch directory and removed with it.
328
+ const buildIdentity = async (c, localAPK) => {
329
+ ({ versionCode, versionName } = (0, android_device_1.parsePackageVersion)(await adbRun(shell(`dumpsys package ${options.appPackage} 2>/dev/null | grep -E "${android_device_1.packagePattern}" | head -c 2048`), c)));
330
+ if (expected?.versionCode !== undefined && versionCode !== expected.versionCode)
331
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-version', stage: 'open' });
332
+ if (expected?.versionName !== undefined && versionName !== expected.versionName)
333
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-version', stage: 'open' });
334
+ if (localAPK)
335
+ signer = await signerOf(localAPK, c);
336
+ else if (expected?.signerSHA256 !== undefined) {
337
+ const pulled = (0, node_path_1.join)(directory, 'installed.apk');
338
+ await adbRun(['pull', await installedPath(c), pulled], c);
339
+ if ((0, node_crypto_1.createHash)('sha256').update(await (0, promises_1.readFile)(pulled)).digest('hex') !== expectedDigest)
340
+ throw failure('pulled_build_changed');
341
+ signer = await signerOf(pulled, c);
342
+ await (0, promises_1.rm)(pulled, { force: true });
343
+ }
344
+ if (expected?.signerSHA256 !== undefined && signer !== expected.signerSHA256)
345
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-signer', stage: 'open' });
164
346
  };
165
347
  const children = () => [emulator, server].filter((child) => !!child);
166
348
  const check = (c) => {
@@ -246,8 +428,9 @@ function androidTargetDriver(options) {
246
428
  return result[0];
247
429
  };
248
430
  const handle = (id) => ({
249
- tap: async (c) => { await endpoint(`/element/${await resolveOne(id, c)}/click`, c, 'POST', {}); },
431
+ tap: async (c) => { const ref = await resolveOne(id, c); await observeGesture(c); await endpoint(`/element/${ref}/click`, c, 'POST', {}); },
250
432
  fill: async (value, c) => {
433
+ disarm();
251
434
  const ref = await resolveOne(id, c);
252
435
  await endpoint(`/element/${ref}/clear`, c, 'POST', {});
253
436
  await endpoint(`/element/${ref}/value`, c, 'POST', { text: value });
@@ -259,18 +442,54 @@ function androidTargetDriver(options) {
259
442
  return value;
260
443
  },
261
444
  text: async (c) => {
445
+ disarm();
262
446
  const value = await endpoint(`/element/${await resolveOne(id, c)}/text`, c);
263
447
  if (typeof value !== 'string' || Buffer.byteLength(value) > 4096)
264
448
  throw failure('invalid_property');
265
449
  return value;
266
450
  },
267
451
  state: async (name, c) => {
452
+ disarm();
268
453
  const value = await endpoint(`/element/${await resolveOne(id, c)}/attribute/${name}`, c);
269
454
  if (value !== 'true' && value !== 'false' && typeof value !== 'boolean')
270
455
  throw failure('unavailable_state');
271
456
  return value === true || value === 'true';
272
457
  },
458
+ // One supported UiAutomator2 gesture inside the resolved element; the
459
+ // driver reports whether more content exists, which is not retained.
460
+ scroll: async (direction, percent, c) => {
461
+ const ref = await resolveOne(id, c);
462
+ await observeGesture(c);
463
+ await endpoint('/execute/sync', c, 'POST', { script: 'mobile: scrollGesture', args: [{ elementId: ref, direction, percent }] });
464
+ },
465
+ bounds: async (c) => { disarm(); return rect(await endpoint(`/element/${await resolveOne(id, c)}/rect`, c)); },
273
466
  });
467
+ const pixel = (value) => Number.isInteger(value) && value >= 0 && value <= 65_535;
468
+ const offset = (value) => Number.isInteger(value) && value >= -65_535 && value <= 65_535;
469
+ // Only finite numbers are rounded: a null or boolean field is a malformed
470
+ // response, never a zero. Origins may be negative for a partly scrolled-out control.
471
+ const rect = (value) => {
472
+ const fields = [value?.x, value?.y, value?.width, value?.height];
473
+ if (!fields.every(field => typeof field === 'number' && Number.isFinite(field)))
474
+ throw failure('invalid_property');
475
+ const r = { x: Math.round(value.x), y: Math.round(value.y), width: Math.round(value.width), height: Math.round(value.height) };
476
+ if (!offset(r.x) || !offset(r.y) || !pixel(r.width) || !pixel(r.height))
477
+ throw failure('invalid_property');
478
+ return r;
479
+ };
480
+ const keyboardShown = async (c) => {
481
+ check(c);
482
+ const ime = (0, android_device_1.parseIme)(await adbRun(shell(`dumpsys input_method 2>/dev/null | grep -E "${android_device_1.imePattern}" | head -c 1024`), c));
483
+ if (ime === 'unknown')
484
+ throw failure('unavailable_state');
485
+ return ime === 'shown';
486
+ };
487
+ // Brought to the front with the launcher intent, which matches the task's
488
+ // root intent: a bare `am start -n` stacks a second instance of a
489
+ // standard-launch activity on top of the one the session started.
490
+ const launch = ['shell', 'am', 'start', '-W', '-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER',
491
+ '-n', `${options.appPackage}/${options.activity}`];
492
+ const appCommand = (script, c) => endpoint('/execute/sync', c, 'POST', { script, args: [{ appId: options.appPackage }] });
274
493
  const cleanup = async () => {
275
494
  await Promise.all([stop(emulator), stop(server)]);
276
495
  // Aborting HTTP alone cannot stop an already dispatched native action.
@@ -331,17 +550,28 @@ function androidTargetDriver(options) {
331
550
  let stage = 'configuration';
332
551
  try {
333
552
  let apkBytes;
553
+ if (expected?.apk !== undefined) {
554
+ const artifact = (0, node_path_1.resolve)(expected.apk);
555
+ const info = await (0, promises_1.stat)(artifact);
556
+ if (!info.isFile() || info.size > 256 * 1024 * 1024)
557
+ throw failure('invalid_expected_apk');
558
+ const digest = (0, node_crypto_1.createHash)('sha256').update(await (0, promises_1.readFile)(artifact)).digest('hex');
559
+ // Two declarations that disagree are a configuration error, not a device finding.
560
+ if (options.apkSHA256 !== undefined && digest !== options.apkSHA256)
561
+ throw failure('expected_apk_digest_conflict');
562
+ expectedDigest = digest;
563
+ }
334
564
  if (!physical) {
335
565
  const apk = (0, node_path_1.resolve)(options.apk);
336
566
  const info = await (0, promises_1.stat)(apk);
337
567
  if (!info.isFile() || info.size > 256 * 1024 * 1024)
338
568
  throw failure('invalid_apk');
339
569
  apkBytes = await (0, promises_1.readFile)(apk);
340
- if ((0, node_crypto_1.createHash)('sha256').update(apkBytes).digest('hex') !== options.apkSHA256)
341
- throw failure('apk_digest_mismatch');
570
+ if ((0, node_crypto_1.createHash)('sha256').update(apkBytes).digest('hex') !== expectedDigest)
571
+ throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-digest', stage: 'open' });
342
572
  }
343
- const appiumPkg = JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(tools, 'node_modules/appium/package.json'), 'utf8'));
344
- const driverPkg = JSON.parse(await (0, promises_1.readFile)((0, node_path_1.join)(tools, 'node_modules/appium-uiautomator2-driver/package.json'), 'utf8'));
573
+ const appiumPkg = JSON.parse(await (0, promises_1.readFile)(tooling.appium, 'utf8'));
574
+ const driverPkg = JSON.parse(await (0, promises_1.readFile)(tooling.uiautomator2, 'utf8'));
345
575
  if (appiumPkg.version !== android_runtime_1.androidVersions.appium || driverPkg.version !== android_runtime_1.androidVersions.uiautomator2)
346
576
  throw failure('driver_version_mismatch');
347
577
  const scratch = process.env.NINELIVES_TARGET_SCRATCH_DIR;
@@ -357,7 +587,7 @@ function androidTargetDriver(options) {
357
587
  const installedAPK = (0, node_path_1.join)(directory, 'fixture.apk');
358
588
  if (apkBytes) {
359
589
  await (0, promises_1.writeFile)(installedAPK, apkBytes, { mode: 0o400 });
360
- const badging = await command((0, node_path_1.join)(sdk, 'build-tools/35.0.0/aapt2'), ['dump', 'badging', installedAPK], c, env);
590
+ const badging = await command(sdkTools.aapt2, ['dump', 'badging', installedAPK], c, env);
361
591
  if (/^package: name='([^']+)'/.exec(badging)?.[1] !== options.appPackage)
362
592
  throw failure('apk_package_mismatch');
363
593
  }
@@ -368,14 +598,34 @@ function androidTargetDriver(options) {
368
598
  if (physical) {
369
599
  stage = 'device_attach';
370
600
  serial = options.deviceSerial;
371
- const leaseRoot = (0, node_path_1.join)((0, node_os_1.homedir)(), '.9lives', 'android-leases');
372
- const lock = (0, node_path_1.join)(leaseRoot, `9l-android-${(0, node_crypto_1.createHash)('sha256').update(serial).digest('hex')}.lock`);
601
+ const lock = androidLeasePath(serial);
373
602
  // Never recover a stale lease automatically: a killed worker may have
374
603
  // left automation running. Manual inspection is required in that case.
375
- await (0, promises_1.mkdir)(leaseRoot, { recursive: true, mode: 0o700 });
604
+ await (0, promises_1.mkdir)((0, node_path_1.dirname)(lock), { recursive: true, mode: 0o700 });
376
605
  await (0, promises_1.mkdir)(lock, { mode: 0o700 });
377
606
  lease = lock;
378
607
  await installedBuild(c);
608
+ // Version and signer are checked before any device change or session.
609
+ stage = 'build_identity';
610
+ await buildIdentity(c);
611
+ stage = 'device_state';
612
+ // A phone that cannot be read before the test is in an unknown
613
+ // state, not an open failure; cancellation, the deadline and a
614
+ // closed driver still propagate.
615
+ let state;
616
+ try {
617
+ state = await readDeviceState(c);
618
+ }
619
+ catch (error) {
620
+ if (interrupted(c))
621
+ throw error;
622
+ throw new targets_1.TargetSetupError({ classification: 'unknown', reason: 'device-state-unknown', stage: 'open' });
623
+ }
624
+ if (state === 'locked' || state === 'screen-off')
625
+ throw new targets_1.TargetSetupError({ classification: 'blocked', reason: state === 'locked' ? 'device-locked' : 'screen-off', stage: 'open' });
626
+ stage = 'displays';
627
+ await readDisplays(c);
628
+ stage = 'device_attach';
379
629
  if (await adbRun(['shell', 'sh', '-c', "'pidof io.appium.uiautomator2.server io.appium.uiautomator2.server.test || true'"], c))
380
630
  throw failure('device_automation_in_use');
381
631
  for (const key of ['hidden_api_policy_pre_p_apps', 'hidden_api_policy_p_apps', 'hidden_api_policy']) {
@@ -430,14 +680,18 @@ function androidTargetDriver(options) {
430
680
  }
431
681
  await (0, promises_2.setTimeout)(250, undefined, { signal: c.signal });
432
682
  }
683
+ stage = 'displays';
684
+ await readDisplays(c);
433
685
  stage = 'apk_install';
434
686
  await adbRun(['install', '--no-streaming', '-r', installedAPK], c);
687
+ stage = 'build_identity';
688
+ await buildIdentity(c, installedAPK);
435
689
  }
436
690
  const appiumPort = await freePort();
437
691
  base = `http://127.0.0.1:${appiumPort}/${owner}`;
438
692
  check(c);
439
693
  stage = 'server_start';
440
- server = (0, node_child_process_1.spawn)(process.execPath, [(0, node_path_1.join)(tools, 'node_modules/appium/index.js'), '--address', '127.0.0.1', '--port', String(appiumPort), '--base-path', `/${owner}`, '--use-drivers', 'uiautomator2', '--log-level', 'error', '--log-no-colors'], { env, cwd: directory, stdio: 'ignore' });
694
+ server = (0, node_child_process_1.spawn)(process.execPath, [tooling.appiumEntry, '--address', '127.0.0.1', '--port', String(appiumPort), '--base-path', `/${owner}`, '--use-drivers', 'uiautomator2', '--log-level', 'error', '--log-no-colors'], { env, cwd: directory, stdio: 'ignore' });
441
695
  server.on('error', () => { });
442
696
  for (;;) {
443
697
  check(c);
@@ -482,33 +736,78 @@ function androidTargetDriver(options) {
482
736
  let identity;
483
737
  if (physical) {
484
738
  await installedBuild(c);
485
- await adbRun(['shell', 'am', 'start', '-W', '-n', `${options.appPackage}/${options.activity}`], c);
739
+ await adbRun(launch, c);
740
+ stage = 'baseline';
741
+ let reading = await readBaseline(c);
742
+ if (dirty(reading) && backPresses > 0) {
743
+ // Declared, recorded and bounded: Back until the baseline is
744
+ // observed again. An unknown reading after Back is not a
745
+ // restored baseline.
746
+ const reason = reading;
747
+ let presses = 0;
748
+ // A failed Back or a failed read after one leaves an unknown,
749
+ // unrestored baseline: the presses already completed stay on the
750
+ // record. Cancellation, the deadline and a closed driver still propagate.
751
+ while (dirty(reading) && presses < backPresses) {
752
+ check(c);
753
+ try {
754
+ await adbRun(['shell', 'input', 'keyevent', 'KEYCODE_BACK'], c);
755
+ }
756
+ catch (error) {
757
+ if (interrupted(c))
758
+ throw error;
759
+ reading = 'unknown';
760
+ break;
761
+ }
762
+ presses++;
763
+ await (0, promises_2.setTimeout)(500, undefined, { signal: c.signal });
764
+ try {
765
+ reading = await readBaseline(c);
766
+ }
767
+ catch (error) {
768
+ if (interrupted(c))
769
+ throw error;
770
+ reading = 'unknown';
771
+ }
772
+ }
773
+ const recovery = { method: 'back', presses, restored: reading === 'clean' };
774
+ if (reading !== 'clean')
775
+ throw new targets_1.TargetSetupError({ classification: 'dirty', reason, stage: 'open', recovery });
776
+ setupRecord = { classification: 'dirty', reason, stage: 'open', recovery };
777
+ }
778
+ else if (dirty(reading))
779
+ throw new targets_1.TargetSetupError({ classification: 'dirty', reason: reading, stage: 'open' });
486
780
  identity = { device: 'physical', deviceHash: (0, node_crypto_1.createHash)('sha256').update(serial).digest('hex') };
487
781
  }
488
782
  else {
489
- const emulatorVersion = await command(emulatorPath, ['-version'], c, env);
490
- const version = /Android emulator version ([0-9.]+)/.exec(emulatorVersion)?.[1];
783
+ // Read within 10 s from both streams, else from the package revision.
784
+ const bounded = { ...c, deadlineMs: Math.min(c.deadlineMs, Date.now() + 10_000) };
785
+ const version = await (0, android_device_1.emulatorVersion)(() => command(emulatorPath, ['-version'], bounded, env, 'both'), () => (0, promises_1.readFile)((0, node_path_1.join)(sdk, 'emulator', 'source.properties'), 'utf8'), () => check(c));
491
786
  if (!version)
492
787
  throw failure('unknown_emulator_version');
493
788
  identity = { emulator: version };
494
789
  }
495
790
  evidence = {
496
- appPackage: options.appPackage, apkSHA256: options.apkSHA256,
791
+ appPackage: options.appPackage, apkSHA256: expectedDigest, versionCode, versionName, signer,
497
792
  api: await adbRun(['shell', 'getprop', 'ro.build.version.sdk'], c),
498
793
  release: await adbRun(['shell', 'getprop', 'ro.build.version.release'], c),
499
794
  abi: await adbRun(['shell', 'getprop', 'ro.product.cpu.abi'], c),
795
+ display: display?.id ?? 'unknown', displayWidth: String(display?.width ?? 0), displayHeight: String(display?.height ?? 0), density: String(display?.density ?? 0), posture,
500
796
  ...identity, ...android_runtime_1.androidVersions, worker: (0, node_crypto_1.createHash)('sha256').update(`${owner}:${process.pid}`).digest('hex'),
501
797
  };
502
798
  }
503
- catch {
799
+ catch (error) {
504
800
  closed = true;
505
801
  await cleanup();
802
+ if (error instanceof targets_1.TargetSetupError)
803
+ throw error;
506
804
  throw failure(`open_failed_${stage}`);
507
805
  }
508
806
  })();
509
807
  return opening;
510
808
  },
511
809
  async reset(c) {
810
+ disarm();
512
811
  if (physical)
513
812
  throw failure('reset_unsupported_on_attached_device');
514
813
  check(c);
@@ -517,9 +816,206 @@ function androidTargetDriver(options) {
517
816
  await adbRun(['shell', 'am', 'force-stop', options.appPackage], c);
518
817
  if (await adbRun(['shell', 'pm', 'clear', options.appPackage], c) !== 'Success')
519
818
  throw failure('reset_failed');
520
- await adbRun(['shell', 'am', 'start', '-W', '-n', `${options.appPackage}/${options.activity}`], c);
819
+ await adbRun(launch, c);
521
820
  },
522
821
  async observeTestId(id, c) { return (await matches(id, c)).slice(0, 2).map(() => handle(id)); },
822
+ setup: () => setupRecord,
823
+ async back(c) { await observeGesture(c); await endpoint('/back', c, 'POST', {}); },
824
+ async keyboardShown(c) { disarm(); return keyboardShown(c); },
825
+ // Back dismisses a shown keyboard without touching the selected input
826
+ // method; the result is read back rather than assumed.
827
+ async hideKeyboard(c) {
828
+ disarm();
829
+ if (!await keyboardShown(c))
830
+ return;
831
+ await endpoint('/back', c, 'POST', {});
832
+ for (;;) {
833
+ if (!await keyboardShown(c))
834
+ return;
835
+ if (Date.now() + 100 >= c.deadlineMs)
836
+ throw failure('keyboard_not_hidden');
837
+ await (0, promises_2.setTimeout)(100, undefined, { signal: c.signal });
838
+ }
839
+ },
840
+ async tapAt(point, c) {
841
+ if (!pixel(point.x) || !pixel(point.y))
842
+ throw failure('invalid_point');
843
+ await observeGesture(c, { x: point.x, y: point.y });
844
+ await endpoint('/actions', c, 'POST', { actions: [{ type: 'pointer', id: 'finger1', parameters: { pointerType: 'touch' }, actions: [
845
+ { type: 'pointerMove', duration: 0, x: point.x, y: point.y }, { type: 'pointerDown', button: 0 }, { type: 'pause', duration: 50 }, { type: 'pointerUp', button: 0 },
846
+ ] }] });
847
+ },
848
+ async screenDigest(c) { check(c); return screenDigest(c); },
849
+ async viewport(c) {
850
+ disarm();
851
+ const r = rect(await endpoint('/window/rect', c));
852
+ if (r.width === 0 || r.height === 0)
853
+ throw failure('invalid_property');
854
+ return { width: r.width, height: r.height };
855
+ },
856
+ // Terminate is a force-stop of the configured package only; data, the
857
+ // installation and device settings are untouched. Activate relaunches it.
858
+ // The driver's own force-stop of the configured package, then a bounded
859
+ // wait until no process of it is left: Appium's terminateApp gave up after
860
+ // its own short exit check on a slow emulator.
861
+ async terminate(c) {
862
+ disarm();
863
+ check(c);
864
+ await adbRun(['shell', 'am', 'force-stop', options.appPackage], c);
865
+ for (;;) {
866
+ if (await adbRun(shell(`pidof ${options.appPackage} || true`), c) === '')
867
+ return;
868
+ if (Date.now() + 250 >= c.deadlineMs)
869
+ throw failure('terminate_failed');
870
+ await (0, promises_2.setTimeout)(250, undefined, { signal: c.signal });
871
+ }
872
+ },
873
+ async activate(c) { disarm(); await appCommand('mobile: activateApp', c); },
874
+ // After a completed assertion failure: did the phone become unavailable?
875
+ // Read-only; an owned emulator cannot lock itself. With diagnostics, a
876
+ // hidden assertion that failed although the app lost a window since the
877
+ // last gesture is the accessibility snapshot disagreeing with the window
878
+ // manager: observer staleness, attributed to neither the app nor the tap.
879
+ async recheck(c, failed) {
880
+ if (!session)
881
+ return undefined;
882
+ check(c);
883
+ if (physical) {
884
+ let state;
885
+ try {
886
+ state = await readDeviceState(c);
887
+ }
888
+ catch (error) {
889
+ // A phone that cannot be read (disconnected, adb gone) has an unknown
890
+ // state; cancellation, the deadline and a closed driver still propagate.
891
+ if (interrupted(c))
892
+ throw error;
893
+ state = 'unknown';
894
+ }
895
+ if (state === 'unknown')
896
+ return { classification: 'unknown', reason: 'device-state-unknown', stage: 'recheck' };
897
+ if (state !== 'unlocked')
898
+ return { classification: 'blocked', reason: state === 'locked' ? 'device-locked' : 'screen-off', stage: 'recheck' };
899
+ }
900
+ // Heuristic, opt-in and limited to a dismissal sequence: UiAutomator2
901
+ // does not say which window an element belongs to, so a hidden
902
+ // assertion that fails right after a gesture while the app lost a
903
+ // window is attributed to the snapshot, not proven. The diagnostic
904
+ // keeps the counts either way.
905
+ if (diagnostics && armed && failed.operation === 'assert-hidden' && lastGesture && lastGesture.windows > 0) {
906
+ const now = await readWindows(c);
907
+ if (now && now.windows < lastGesture.windows)
908
+ return { classification: 'observer', reason: 'window-gone-element-displayed', stage: 'recheck' };
909
+ }
910
+ return undefined;
911
+ },
912
+ // Metadata only: what was asked, how long it took, and the app's windows
913
+ // before the last gesture and now. Nothing is retried and no cause is claimed.
914
+ async diagnose(f, c) {
915
+ if (!diagnostics)
916
+ return undefined;
917
+ const point = f.point ?? lastPoint;
918
+ const record = { operation: f.operation, reason: f.reason, elapsedMs: f.elapsedMs, windowsBefore: lastGesture?.windows ?? -1, windowsAfter: -1,
919
+ ...(point ? { x: point.x, y: point.y, point: true } : {}), ...(lastGesture ? { focusBefore: lastGesture.focus } : {}) };
920
+ if (closed || !session)
921
+ return record;
922
+ try {
923
+ const after = await readWindows(c);
924
+ if (after) {
925
+ record.windowsAfter = after.windows;
926
+ record.focusAfter = after.focus;
927
+ }
928
+ const r = rect(await endpoint('/window/rect', c));
929
+ if (r.width > 0 && r.height > 0) {
930
+ record.viewportWidth = r.width;
931
+ record.viewportHeight = r.height;
932
+ }
933
+ }
934
+ catch { /* partial record */ }
935
+ return record;
936
+ },
523
937
  close,
524
938
  };
525
939
  }
940
+ const maxApkBytes = 256 * 1024 * 1024;
941
+ /** Install or update an app on an explicitly selected device without
942
+ * uninstalling or clearing its data. The APK's signing certificate must
943
+ * match the installed app's, read through the local apksigner; a different
944
+ * signer refuses before any device change. Returns the installed identity
945
+ * for the project's reviewed build metadata. Never runs inside a test. */
946
+ async function installInPlace(options) {
947
+ if (!/^[a-zA-Z0-9_.:-]{1,128}$/.test(options.deviceSerial) || options.deviceSerial.startsWith('emulator-') || !options.apk)
948
+ throw failure('invalid_configuration');
949
+ const sdkRoot = options.sdkRoot ?? (0, android_env_1.androidDefaults)().sdkRoot;
950
+ if (!sdkRoot)
951
+ throw failure('sdk_not_found');
952
+ const sdk = (0, node_path_1.resolve)(sdkRoot), { adb, aapt2, apksigner } = (0, android_env_1.androidToolPaths)(sdk);
953
+ const env = { ANDROID_HOME: sdk, ANDROID_SDK_ROOT: sdk };
954
+ for (const key of ['PATH', 'HOME', 'TMPDIR', 'JAVA_HOME', 'SYSTEMROOT'])
955
+ if (process.env[key])
956
+ env[key] = process.env[key];
957
+ const c = { signal: new AbortController().signal, deadlineMs: Date.now() + Math.min(Math.max(options.timeoutMs ?? 300_000, 1_000), 900_000) };
958
+ const apk = (0, node_path_1.resolve)(options.apk);
959
+ const info = await (0, promises_1.stat)(apk);
960
+ if (!info.isFile() || info.size > maxApkBytes)
961
+ throw failure('invalid_apk');
962
+ // One private snapshot is hashed, inspected, verified and installed, so a
963
+ // build or download replacing the caller's file meanwhile changes nothing.
964
+ const bytes = await (0, promises_1.readFile)(apk);
965
+ if (bytes.length > maxApkBytes)
966
+ throw failure('invalid_apk');
967
+ const apkSHA256 = (0, node_crypto_1.createHash)('sha256').update(bytes).digest('hex');
968
+ const scratch = await (0, promises_1.mkdtemp)((0, node_path_1.join)(process.env.TMPDIR ?? (0, node_os_1.homedir)(), '9l-install-'));
969
+ try {
970
+ const snapshot = (0, node_path_1.join)(scratch, 'app.apk');
971
+ await (0, promises_1.writeFile)(snapshot, bytes, { mode: 0o600 });
972
+ const badging = await command(aapt2, ['dump', 'badging', snapshot], c, env);
973
+ const appPackage = /^package: name='([a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)+)'/m.exec(badging)?.[1];
974
+ if (!appPackage)
975
+ throw failure('unreadable_package');
976
+ const signer = (0, android_device_1.parseSigner)(await command(apksigner, ['verify', '--print-certs', snapshot], c, env));
977
+ if (!signer)
978
+ throw failure('unreadable_signer');
979
+ const run = (args) => command(adb, ['-s', options.deviceSerial, ...args], c, env);
980
+ // The same exclusive lease a test takes: never install under a running
981
+ // test or beside another installer. Only the lease this call created is released.
982
+ const lock = androidLeasePath(options.deviceSerial);
983
+ await (0, promises_1.mkdir)((0, node_path_1.dirname)(lock), { recursive: true, mode: 0o700 });
984
+ try {
985
+ await (0, promises_1.mkdir)(lock, { mode: 0o700 });
986
+ }
987
+ catch {
988
+ throw failure('device_in_use');
989
+ }
990
+ try {
991
+ if (await run(['get-state']) !== 'device' || await run(['shell', 'getprop', 'ro.kernel.qemu']) === '1')
992
+ throw failure('not_physical_device');
993
+ // pm path exits nonzero for an absent package: a first installation, not a transport failure.
994
+ const path = await run(shellArgs(`pm path ${appPackage} 2>/dev/null || true`));
995
+ if (path) {
996
+ if (!/^package:(\/data\/app\/[A-Za-z0-9_./=+~\-]+\/base\.apk)$/.test(path))
997
+ throw failure('unsupported_installed_build');
998
+ const pulled = (0, node_path_1.join)(scratch, 'installed.apk');
999
+ await run(['pull', path.slice(8), pulled]);
1000
+ const installed = (0, android_device_1.parseSigner)(await command(apksigner, ['verify', '--print-certs', pulled], c, env));
1001
+ if (installed !== signer)
1002
+ throw failure('signer_mismatch');
1003
+ }
1004
+ await run(['install', '--no-streaming', '-r', snapshot]);
1005
+ const installedPath = await run(['shell', 'pm', 'path', appPackage]);
1006
+ if (!/^package:(\/data\/app\/[A-Za-z0-9_./=+~\-]+\/base\.apk)$/.test(installedPath))
1007
+ throw failure('unsupported_installed_build');
1008
+ const digest = (await run(['shell', 'sha256sum', installedPath.slice(8)])).split(/\s+/)[0];
1009
+ if (digest !== apkSHA256)
1010
+ throw failure('installed_build_changed');
1011
+ const version = (0, android_device_1.parsePackageVersion)(await run(shellArgs(`dumpsys package ${appPackage} 2>/dev/null | grep -E "${android_device_1.packagePattern}" | head -c 2048`)));
1012
+ return { appPackage, apkSHA256, signer, ...version };
1013
+ }
1014
+ finally {
1015
+ await (0, promises_1.rm)(lock, { recursive: true, force: true });
1016
+ }
1017
+ }
1018
+ finally {
1019
+ await (0, promises_1.rm)(scratch, { recursive: true, force: true });
1020
+ }
1021
+ }