@9l/playwright 0.6.0-beta.1 → 0.6.0-beta.3
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/README.md +72 -2
- package/dist/android-device.d.ts +64 -0
- package/dist/android-device.js +134 -0
- package/dist/android-env.d.ts +65 -0
- package/dist/android-env.js +114 -0
- package/dist/android-runtime.d.ts +16 -4
- package/dist/android-runtime.js +8 -3
- package/dist/android.d.ts +98 -18
- package/dist/android.js +690 -49
- package/dist/index.d.ts +2 -2
- package/dist/index.js +4 -1
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/dist/reporter.js +71 -1
- package/dist/target-setup.d.ts +50 -0
- package/dist/target-setup.js +73 -0
- package/dist/targets.d.ts +151 -4
- package/dist/targets.js +382 -54
- package/package.json +1 -1
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,48 @@ 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; } });
|
|
33
|
+
const matchers = ['text', 'accessibilityId', 'accessibilityIdSuffix', 'accessibilityIdContains', 'hint'];
|
|
34
|
+
/** Test IDs: an app resource entry name, which Android reports as
|
|
35
|
+
* `<package>:id/<id>`, or an identifier a framework reports bare (Flutter's
|
|
36
|
+
* `Semantics(identifier:)`), which may also contain `.` and `-`. */
|
|
37
|
+
const testIdPattern = /^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/;
|
|
38
|
+
// UiAutomator2's selector parser unescapes only \" inside a string
|
|
39
|
+
// argument; every other backslash reaches the matcher as written. Text and
|
|
40
|
+
// description aliases holding a backslash are refused, and IDs cannot hold
|
|
41
|
+
// one, so the only backslashes in a selector are \Q and \E.
|
|
42
|
+
const selectorString = (value) => `"${value.replaceAll('"', '\\"')}"`;
|
|
43
|
+
const quoted = (value) => `\\Q${value}\\E`;
|
|
44
|
+
// An XPath 1.0 string literal has no escapes: a value holding both quote
|
|
45
|
+
// characters is assembled with concat().
|
|
46
|
+
const xpathLiteral = (value) => !value.includes('"') ? `"${value}"` : !value.includes("'") ? `'${value}'`
|
|
47
|
+
: `concat(${value.split('"').map(part => `"${part}"`).join(`, '"', `)})`;
|
|
19
48
|
const failure = (reason) => new Error(`9lives Android: ${reason}`);
|
|
49
|
+
// One fixed script per call; every interpolated value is validated by the
|
|
50
|
+
// caller's option checks. The device shell runs it; nothing else does.
|
|
51
|
+
const shellArgs = (script) => ['shell', 'sh', '-c', `'${script}'`];
|
|
52
|
+
/** The host-local lease that gives one owner exclusive use of a device.
|
|
53
|
+
* The driver and installInPlace both take it, so an installation cannot
|
|
54
|
+
* replace the app under a running test or interleave with another installer. */
|
|
55
|
+
function androidLeasePath(serial) {
|
|
56
|
+
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`);
|
|
57
|
+
}
|
|
20
58
|
const elementKey = 'element-6066-11e4-a52e-4f735466cecf';
|
|
21
59
|
const timeout = (c) => {
|
|
22
60
|
c.signal.throwIfAborted();
|
|
@@ -26,10 +64,10 @@ const timeout = (c) => {
|
|
|
26
64
|
};
|
|
27
65
|
// Native command output stays in memory and never becomes an error message,
|
|
28
66
|
// diagnostic artifact or receipt. These commands have explicit, fixed arguments.
|
|
29
|
-
function command(file, args, c, env) {
|
|
67
|
+
function command(file, args, c, env, streams = 'stdout') {
|
|
30
68
|
return new Promise((yes, no) => (0, node_child_process_1.execFile)(file, args, {
|
|
31
69
|
signal: c.signal, timeout: timeout(c), maxBuffer: 64 * 1024, env,
|
|
32
|
-
}, (error, stdout) => error ? no(failure('device_command_failed')) : yes(stdout.trim())));
|
|
70
|
+
}, (error, stdout, stderr) => error ? no(failure('device_command_failed')) : yes((streams === 'both' ? `${stdout}\n${stderr}` : stdout).trim())));
|
|
33
71
|
}
|
|
34
72
|
async function freePort() {
|
|
35
73
|
const server = (0, node_net_1.createServer)();
|
|
@@ -116,26 +154,62 @@ function androidTargetDriver(options) {
|
|
|
116
154
|
(physical ? !/^[a-zA-Z0-9_.:-]{1,128}$/.test(options.deviceSerial) || options.deviceSerial.startsWith('emulator-') || options.avd !== undefined || options.apk !== undefined
|
|
117
155
|
: !/^[a-zA-Z0-9_.-]{1,100}$/.test(options.avd)) ||
|
|
118
156
|
!/^[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))
|
|
157
|
+
!/^[a-zA-Z0-9_.]+$/.test(options.activity) || (options.apkSHA256 === undefined ? options.expected?.apk === undefined : !/^[a-f0-9]{64}$/.test(options.apkSHA256)))
|
|
158
|
+
throw failure('invalid_configuration');
|
|
159
|
+
const expected = options.expected;
|
|
160
|
+
if (expected !== undefined && (Object.keys(expected).some(k => !['apk', 'versionCode', 'versionName', 'signerSHA256'].includes(k)) || Object.keys(expected).length === 0 ||
|
|
161
|
+
(expected.apk !== undefined && (typeof expected.apk !== 'string' || !expected.apk)) ||
|
|
162
|
+
(expected.versionCode !== undefined && !/^[0-9]{1,10}$/.test(expected.versionCode)) ||
|
|
163
|
+
(expected.versionName !== undefined && !/^[A-Za-z0-9._+-]{1,64}$/.test(expected.versionName)) ||
|
|
164
|
+
(expected.signerSHA256 !== undefined && !/^[a-f0-9]{64}$/.test(expected.signerSHA256))))
|
|
120
165
|
throw failure('invalid_configuration');
|
|
166
|
+
// Resolved at open: the declared artifact's digest wins over apkSHA256.
|
|
167
|
+
let expectedDigest = options.apkSHA256 ?? '';
|
|
121
168
|
if (Object.keys(controls).length > 128)
|
|
122
169
|
throw failure('invalid_controls');
|
|
170
|
+
const expectedWindows = options.baseline?.windows ?? 1;
|
|
171
|
+
const backPresses = options.recovery?.back ?? 0;
|
|
172
|
+
if ((options.baseline !== undefined && (Object.keys(options.baseline).some(k => k !== 'windows') || !Number.isInteger(expectedWindows) || expectedWindows < 1 || expectedWindows > 16)) ||
|
|
173
|
+
(options.recovery !== undefined && (Object.keys(options.recovery).some(k => k !== 'back') || !Number.isInteger(backPresses) || backPresses < 1 || backPresses > 16)) ||
|
|
174
|
+
((options.baseline !== undefined || options.recovery !== undefined) && !physical) ||
|
|
175
|
+
(options.diagnostics !== undefined && (Object.keys(options.diagnostics).some(k => k !== 'gestures') || typeof options.diagnostics.gestures !== 'boolean')))
|
|
176
|
+
throw failure('invalid_configuration');
|
|
177
|
+
const diagnostics = options.diagnostics?.gestures === true;
|
|
178
|
+
const biometrics = options.biometrics;
|
|
179
|
+
if (biometrics !== undefined && (physical || !biometrics || typeof biometrics !== 'object' || Object.keys(biometrics).some(k => k !== 'snapshot') ||
|
|
180
|
+
typeof biometrics.snapshot !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(biometrics.snapshot)))
|
|
181
|
+
throw failure('invalid_configuration');
|
|
182
|
+
const requires = options.requires;
|
|
183
|
+
if (requires !== undefined && (Object.keys(requires).some(k => !['posture', 'minWidthDp'].includes(k)) || Object.keys(requires).length === 0 ||
|
|
184
|
+
(requires.posture !== undefined && !['opened', 'half-opened', 'closed', 'flat'].includes(requires.posture)) ||
|
|
185
|
+
(requires.minWidthDp !== undefined && (!Number.isInteger(requires.minWidthDp) || requires.minWidthDp < 1 || requires.minWidthDp > 10000))))
|
|
186
|
+
throw failure('invalid_configuration');
|
|
123
187
|
for (const [id, control] of Object.entries(controls)) {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
!/^[^\x00-\x1f\x7f]{1,128}$/.test(
|
|
188
|
+
const declared = control ? matchers.filter(k => control[k] !== undefined) : [];
|
|
189
|
+
const literal = declared.length === 1 ? control[declared[0]] : undefined;
|
|
190
|
+
if (!testIdPattern.test(id) || !control ||
|
|
191
|
+
Object.keys(control).some(k => !matchers.includes(k) && k !== 'className' && k !== 'selected') ||
|
|
192
|
+
typeof literal !== 'string' || !/^[^\x00-\x1f\x7f]{1,128}$/.test(literal) || (declared[0] !== 'hint' && literal.includes('\\')) ||
|
|
129
193
|
(control.className !== undefined && !/^android\.(view|widget)\.[A-Za-z]{1,64}$/.test(control.className)) ||
|
|
130
194
|
(control.selected !== undefined && typeof control.selected !== 'boolean'))
|
|
131
195
|
throw failure('invalid_controls');
|
|
132
196
|
}
|
|
133
|
-
|
|
134
|
-
const
|
|
197
|
+
// Explicit roots win; omitted ones come from the same discovery doctor reports.
|
|
198
|
+
const defaults = options.sdkRoot === undefined || options.toolsRoot === undefined ? (0, android_env_1.androidDefaults)() : {};
|
|
199
|
+
const sdkRoot = options.sdkRoot ?? defaults.sdkRoot, toolsRoot = options.toolsRoot ?? defaults.toolsRoot;
|
|
200
|
+
if (!sdkRoot)
|
|
201
|
+
throw failure('sdk_not_found');
|
|
202
|
+
if (!toolsRoot)
|
|
203
|
+
throw failure('tools_not_found');
|
|
204
|
+
const sdk = (0, node_path_1.resolve)(sdkRoot), tools = (0, node_path_1.resolve)(toolsRoot);
|
|
205
|
+
const sdkTools = (0, android_env_1.androidToolPaths)(sdk), tooling = (0, android_env_1.androidToolingPaths)(tools);
|
|
206
|
+
const adb = sdkTools.adb, emulatorPath = sdkTools.emulator;
|
|
135
207
|
// Explicit environment allowlist: no application/provider credentials reach
|
|
136
208
|
// Appium, adb or the emulator. Go --pass-env remains necessary for test data.
|
|
137
209
|
const env = {};
|
|
138
|
-
|
|
210
|
+
// The AVD and user-config locations are paths, not credentials: without
|
|
211
|
+
// them an emulator whose AVDs live outside ~/.android/avd is not found.
|
|
212
|
+
for (const key of ['PATH', 'HOME', 'TMPDIR', 'JAVA_HOME', 'SYSTEMROOT', 'ANDROID_AVD_HOME', 'ANDROID_USER_HOME', 'ANDROID_EMULATOR_HOME'])
|
|
139
213
|
if (process.env[key])
|
|
140
214
|
env[key] = process.env[key];
|
|
141
215
|
env.ANDROID_HOME = sdk;
|
|
@@ -150,17 +224,144 @@ function androidTargetDriver(options) {
|
|
|
150
224
|
const mockStore = '/data/local/tmp/mock_apps.json';
|
|
151
225
|
const mockBackup = `/data/local/tmp/9l-${owner}-mock-apps.json`;
|
|
152
226
|
let mockStorePresent, mockPermission;
|
|
153
|
-
const shell =
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
227
|
+
const shell = shellArgs;
|
|
228
|
+
// Device-state reads filter on the device and stay in memory. They never
|
|
229
|
+
// request, store or bypass a credential, and never change lock settings.
|
|
230
|
+
// A failed device read during cancellation, past the deadline or after
|
|
231
|
+
// close is that interruption, never a reading of the device.
|
|
232
|
+
const interrupted = (c) => c.signal.aborted || Date.now() >= c.deadlineMs || closed;
|
|
233
|
+
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));
|
|
234
|
+
// A dump that yields neither a window nor a focus line was not observed
|
|
235
|
+
// (unavailable or empty); it is never read as zero windows. Nor was one cut
|
|
236
|
+
// at the byte bound: only output ending in the completion marker counts.
|
|
237
|
+
// The window list comes from `dumpsys window windows`; the focus line is
|
|
238
|
+
// in `dumpsys window displays` (API 35 prints it only there), and the
|
|
239
|
+
// first focus line read wins.
|
|
240
|
+
const windowsEnd = '9l-windows-end';
|
|
241
|
+
const readWindows = async (c) => {
|
|
242
|
+
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);
|
|
243
|
+
if (!dump.endsWith(windowsEnd))
|
|
244
|
+
return undefined;
|
|
245
|
+
const windows = (0, android_device_1.parseWindows)(dump.slice(0, -windowsEnd.length), options.appPackage);
|
|
246
|
+
return windows.windows === 0 && windows.focus === 'unknown' ? undefined : windows;
|
|
247
|
+
};
|
|
248
|
+
// With diagnostics, the window state before the last gesture; a read that
|
|
249
|
+
// fails leaves the gesture to proceed and the observation absent. The
|
|
250
|
+
// observation stays as diagnostic metadata, but any operation other than a
|
|
251
|
+
// visibility read between the gesture and a hidden assertion disarms the
|
|
252
|
+
// observer heuristic: it describes a dismissal sequence (gesture, then the
|
|
253
|
+
// control should be gone), nothing else.
|
|
254
|
+
// A touch's requested point stays with its observation, so a failure
|
|
255
|
+
// after the touch (the hidden assertion) still reports where it was sent;
|
|
256
|
+
// any other gesture replaces it.
|
|
257
|
+
let lastGesture, lastPoint, armed = false;
|
|
258
|
+
const observeGesture = async (c, point) => {
|
|
259
|
+
if (!diagnostics)
|
|
260
|
+
return;
|
|
261
|
+
lastPoint = point;
|
|
262
|
+
try {
|
|
263
|
+
lastGesture = await readWindows(c);
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
lastGesture = undefined;
|
|
267
|
+
}
|
|
268
|
+
armed = lastGesture !== undefined;
|
|
269
|
+
};
|
|
270
|
+
const disarm = () => { armed = false; };
|
|
271
|
+
// A baseline reading is clean only when every component was observed as
|
|
272
|
+
// declared; a difference is a dirty reason; anything else is unknown and
|
|
273
|
+
// can neither classify the state nor count as a restored baseline.
|
|
274
|
+
const readBaseline = async (c) => {
|
|
275
|
+
const windows = await readWindows(c);
|
|
276
|
+
if (!windows)
|
|
277
|
+
return 'unknown';
|
|
278
|
+
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));
|
|
279
|
+
if (windows.focus === 'foreign')
|
|
280
|
+
return 'foreign-focus';
|
|
281
|
+
if (windows.windows > expectedWindows)
|
|
282
|
+
return 'extra-window';
|
|
283
|
+
if (ime === 'shown')
|
|
284
|
+
return 'ime-showing';
|
|
285
|
+
return windows.focus === 'app' && windows.windows === expectedWindows && ime === 'hidden' ? 'clean' : 'unknown';
|
|
286
|
+
};
|
|
287
|
+
const dirty = (reading) => reading !== 'clean' && reading !== 'unknown';
|
|
288
|
+
let setupRecord;
|
|
289
|
+
// The display the session targets. Screenshots name it explicitly, so a
|
|
290
|
+
// multi-display device never answers with its first display by default.
|
|
291
|
+
// The recorded size and density are the display's current logical layout
|
|
292
|
+
// (rotation and density overrides applied) when the dump reports one, and
|
|
293
|
+
// its physical metrics otherwise. Read before any session can launch the
|
|
294
|
+
// app, so a mismatch changes nothing.
|
|
295
|
+
let display, posture = 'unknown';
|
|
296
|
+
// A dump cut at its byte bound may have lost a display, so it names none:
|
|
297
|
+
// only output ending in the completion marker is discovery data.
|
|
298
|
+
const displaysEnd = '9l-displays-end';
|
|
299
|
+
const readDisplays = async (c) => {
|
|
300
|
+
const output = await adbRun(shell(`{ dumpsys display 2>/dev/null | grep -E "${android_device_1.displayPattern}"; echo ${displaysEnd}; } | head -c 32768`), c);
|
|
301
|
+
const dump = output.endsWith(displaysEnd) ? output.slice(0, -displaysEnd.length) : '';
|
|
302
|
+
display = (0, android_device_1.activeDisplay)((0, android_device_1.parseDisplays)(dump));
|
|
303
|
+
const logical = display && (0, android_device_1.parseLogicalDisplays)(dump).get(display.id);
|
|
304
|
+
if (display && logical)
|
|
305
|
+
display = { ...display, ...logical };
|
|
306
|
+
posture = (0, android_device_1.parsePosture)(await adbRun(shell(`dumpsys device_state 2>&1 | grep -E "${android_device_1.posturePattern}" | head -c 2048`), c));
|
|
307
|
+
if (requires?.posture !== undefined && posture !== requires.posture)
|
|
308
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'posture', stage: 'open' });
|
|
309
|
+
if (requires?.minWidthDp !== undefined && (!display || Math.floor(display.width * 160 / display.density) < requires.minWidthDp))
|
|
310
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'display-width', stage: 'open' });
|
|
311
|
+
};
|
|
312
|
+
// The PNG stays in memory and leaves only as a digest.
|
|
313
|
+
// Closing the driver cancels a pending capture, as it does a request.
|
|
314
|
+
const screenDigest = (c) => new Promise((yes, no) => (0, node_child_process_1.execFile)(adb, ['-s', serial, 'exec-out', 'screencap', '-p', ...(display ? ['-d', display.id] : [])], {
|
|
315
|
+
signal: AbortSignal.any([c.signal, controller.signal]), timeout: timeout(c), maxBuffer: 64 * 1024 * 1024, env, encoding: 'buffer',
|
|
316
|
+
}, (error, stdout) => {
|
|
317
|
+
if (error || !Buffer.isBuffer(stdout) || stdout.length < 8 || stdout.subarray(0, 8).toString('latin1') !== '\x89PNG\r\n\x1a\n')
|
|
318
|
+
return no(failure('screenshot_failed'));
|
|
319
|
+
yes((0, node_crypto_1.createHash)('sha256').update(stdout).digest('hex'));
|
|
320
|
+
}));
|
|
321
|
+
const installedPath = async (c) => {
|
|
157
322
|
const path = await adbRun(['shell', 'pm', 'path', options.appPackage], c);
|
|
158
323
|
// Split builds require a digest of the entire installation; fail closed.
|
|
159
324
|
if (!/^package:(\/data\/app\/[A-Za-z0-9_./=+~\-]+\/base\.apk)$/.test(path))
|
|
160
325
|
throw failure('unsupported_installed_build');
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
326
|
+
return path.slice(8);
|
|
327
|
+
};
|
|
328
|
+
// A wrong or stale installed build is a setup mismatch, not a driver fault.
|
|
329
|
+
const installedBuild = async (c) => {
|
|
330
|
+
if (await adbRun(['get-state'], c) !== 'device' || await adbRun(['shell', 'getprop', 'ro.kernel.qemu'], c) === '1')
|
|
331
|
+
throw failure('not_physical_device');
|
|
332
|
+
const digest = await adbRun(['shell', 'sha256sum', await installedPath(c)], c);
|
|
333
|
+
if (digest.split(/\s+/)[0] !== expectedDigest)
|
|
334
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-digest', stage: 'open' });
|
|
335
|
+
};
|
|
336
|
+
// apksigner prints only certificate facts; the first signer's digest is kept.
|
|
337
|
+
const signerOf = async (apk, c) => {
|
|
338
|
+
const signer = (0, android_device_1.parseSigner)(await command(sdkTools.apksigner, ['verify', '--print-certs', apk], c, env));
|
|
339
|
+
if (!signer)
|
|
340
|
+
throw failure('unreadable_signer');
|
|
341
|
+
return signer;
|
|
342
|
+
};
|
|
343
|
+
let versionCode = 'unknown', versionName = 'unknown', signer = 'unknown';
|
|
344
|
+
// Version from the package manager; the signer from the local APK (owned
|
|
345
|
+
// emulator) or, when declared, from the installed base APK pulled into the
|
|
346
|
+
// attempt's private scratch directory and removed with it.
|
|
347
|
+
const buildIdentity = async (c, localAPK) => {
|
|
348
|
+
({ 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)));
|
|
349
|
+
if (expected?.versionCode !== undefined && versionCode !== expected.versionCode)
|
|
350
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-version', stage: 'open' });
|
|
351
|
+
if (expected?.versionName !== undefined && versionName !== expected.versionName)
|
|
352
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-version', stage: 'open' });
|
|
353
|
+
if (localAPK)
|
|
354
|
+
signer = await signerOf(localAPK, c);
|
|
355
|
+
else if (expected?.signerSHA256 !== undefined) {
|
|
356
|
+
const pulled = (0, node_path_1.join)(directory, 'installed.apk');
|
|
357
|
+
await adbRun(['pull', await installedPath(c), pulled], c);
|
|
358
|
+
if ((0, node_crypto_1.createHash)('sha256').update(await (0, promises_1.readFile)(pulled)).digest('hex') !== expectedDigest)
|
|
359
|
+
throw failure('pulled_build_changed');
|
|
360
|
+
signer = await signerOf(pulled, c);
|
|
361
|
+
await (0, promises_1.rm)(pulled, { force: true });
|
|
362
|
+
}
|
|
363
|
+
if (expected?.signerSHA256 !== undefined && signer !== expected.signerSHA256)
|
|
364
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-signer', stage: 'open' });
|
|
164
365
|
};
|
|
165
366
|
const children = () => [emulator, server].filter((child) => !!child);
|
|
166
367
|
const check = (c) => {
|
|
@@ -217,28 +418,67 @@ function androidTargetDriver(options) {
|
|
|
217
418
|
throw failure('session_unavailable');
|
|
218
419
|
return request(`/session/${session}${path}`, c, method, body);
|
|
219
420
|
};
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
421
|
+
// The control as one generated, package-scoped XPath. It finds hint
|
|
422
|
+
// aliases (UiSelector has no hint matcher) and reads content-invalid,
|
|
423
|
+
// which UiAutomator2 exposes in its hierarchy but not as an element attribute.
|
|
424
|
+
const xpathOf = (id) => {
|
|
223
425
|
const control = Object.hasOwn(controls, id) ? controls[id] : undefined;
|
|
224
|
-
let
|
|
225
|
-
if (control)
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
426
|
+
let path = `//*[@package=${xpathLiteral(options.appPackage)}]`;
|
|
427
|
+
if (!control)
|
|
428
|
+
return `${path}[@resource-id=${xpathLiteral(id)} or @resource-id=${xpathLiteral(`${options.appPackage}:id/${id}`)}]`;
|
|
429
|
+
if (control.hint !== undefined)
|
|
430
|
+
path += `[@hint=${xpathLiteral(control.hint)}]`;
|
|
431
|
+
else if (control.text !== undefined)
|
|
432
|
+
path += `[@text=${xpathLiteral(control.text)}]`;
|
|
433
|
+
else if (control.accessibilityId !== undefined)
|
|
434
|
+
path += `[@content-desc=${xpathLiteral(control.accessibilityId)}]`;
|
|
435
|
+
else if (control.accessibilityIdContains !== undefined)
|
|
436
|
+
path += `[contains(@content-desc, ${xpathLiteral(control.accessibilityIdContains)})]`;
|
|
437
|
+
else {
|
|
438
|
+
const suffix = xpathLiteral(control.accessibilityIdSuffix);
|
|
439
|
+
path += `[substring(@content-desc, string-length(@content-desc) - string-length(${suffix}) + 1) = ${suffix}]`;
|
|
440
|
+
}
|
|
441
|
+
if (control.className)
|
|
442
|
+
path += `[@class=${xpathLiteral(control.className)}]`;
|
|
443
|
+
if (control.selected !== undefined)
|
|
444
|
+
path += `[@selected="${control.selected}"]`;
|
|
445
|
+
return path;
|
|
446
|
+
};
|
|
447
|
+
// One fixed query per control. A test ID matches the app's prefixed
|
|
448
|
+
// resource name or the same name reported bare, both in one query, so a
|
|
449
|
+
// control reported both ways is ambiguous rather than a first match.
|
|
450
|
+
// UiSelector regexes match the whole value, across line breaks.
|
|
451
|
+
const query = (id) => {
|
|
452
|
+
const control = Object.hasOwn(controls, id) ? controls[id] : undefined;
|
|
453
|
+
if (control?.hint !== undefined)
|
|
454
|
+
return { using: 'xpath', value: xpathOf(id) };
|
|
455
|
+
let selector = `new UiSelector().packageName(${selectorString(options.appPackage)})`;
|
|
456
|
+
if (!control)
|
|
457
|
+
selector += `.resourceIdMatches(${selectorString(`(?:${quoted(`${options.appPackage}:id/`)})?${quoted(id)}`)})`;
|
|
458
|
+
else {
|
|
459
|
+
if (control.accessibilityIdSuffix !== undefined)
|
|
460
|
+
selector += `.descriptionMatches(${selectorString(`(?s).*${quoted(control.accessibilityIdSuffix)}`)})`;
|
|
461
|
+
else if (control.accessibilityIdContains !== undefined)
|
|
462
|
+
selector += `.descriptionContains(${selectorString(control.accessibilityIdContains)})`;
|
|
230
463
|
else
|
|
231
|
-
selector += control.accessibilityId === undefined ? `.text(${
|
|
464
|
+
selector += control.accessibilityId === undefined ? `.text(${selectorString(control.text)})` : `.description(${selectorString(control.accessibilityId)})`;
|
|
232
465
|
if (control.className)
|
|
233
|
-
selector += `.className(${
|
|
466
|
+
selector += `.className(${selectorString(control.className)})`;
|
|
234
467
|
if (control.selected !== undefined)
|
|
235
468
|
selector += `.selected(${control.selected})`;
|
|
236
469
|
}
|
|
237
|
-
|
|
470
|
+
return { using: '-android uiautomator', value: selector };
|
|
471
|
+
};
|
|
472
|
+
const elements = (result) => {
|
|
238
473
|
if (!Array.isArray(result) || result.length > 512 || result.some(value => typeof value?.[elementKey] !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(value[elementKey])))
|
|
239
474
|
throw failure('invalid_elements');
|
|
240
475
|
return result.map(value => value[elementKey]);
|
|
241
476
|
};
|
|
477
|
+
const matches = async (id, c) => {
|
|
478
|
+
if (!testIdPattern.test(id))
|
|
479
|
+
throw failure('invalid_resource_id');
|
|
480
|
+
return elements(await endpoint('/elements', c, 'POST', query(id)));
|
|
481
|
+
};
|
|
242
482
|
const resolveOne = async (id, c) => {
|
|
243
483
|
const result = await matches(id, c);
|
|
244
484
|
if (result.length !== 1)
|
|
@@ -246,31 +486,92 @@ function androidTargetDriver(options) {
|
|
|
246
486
|
return result[0];
|
|
247
487
|
};
|
|
248
488
|
const handle = (id) => ({
|
|
249
|
-
tap: async (c) => {
|
|
489
|
+
tap: async (c) => { const ref = await resolveOne(id, c); await observeGesture(c); await endpoint(`/element/${ref}/click`, c, 'POST', {}); },
|
|
250
490
|
fill: async (value, c) => {
|
|
491
|
+
disarm();
|
|
251
492
|
const ref = await resolveOne(id, c);
|
|
252
493
|
await endpoint(`/element/${ref}/clear`, c, 'POST', {});
|
|
253
494
|
await endpoint(`/element/${ref}/value`, c, 'POST', { text: value });
|
|
254
495
|
},
|
|
496
|
+
// A control that vanished since it was observed is not visible; two
|
|
497
|
+
// matches are still ambiguous.
|
|
255
498
|
visible: async (c) => {
|
|
256
|
-
const
|
|
499
|
+
const found = await matches(id, c);
|
|
500
|
+
if (found.length > 1)
|
|
501
|
+
throw failure('ambiguous_resource_id');
|
|
502
|
+
if (found.length === 0)
|
|
503
|
+
return false;
|
|
504
|
+
const value = await endpoint(`/element/${found[0]}/displayed`, c);
|
|
257
505
|
if (typeof value !== 'boolean')
|
|
258
506
|
throw failure('invalid_property');
|
|
259
507
|
return value;
|
|
260
508
|
},
|
|
261
509
|
text: async (c) => {
|
|
510
|
+
disarm();
|
|
262
511
|
const value = await endpoint(`/element/${await resolveOne(id, c)}/text`, c);
|
|
263
512
|
if (typeof value !== 'string' || Buffer.byteLength(value) > 4096)
|
|
264
513
|
throw failure('invalid_property');
|
|
265
514
|
return value;
|
|
266
515
|
},
|
|
267
516
|
state: async (name, c) => {
|
|
517
|
+
disarm();
|
|
268
518
|
const value = await endpoint(`/element/${await resolveOne(id, c)}/attribute/${name}`, c);
|
|
269
519
|
if (value !== 'true' && value !== 'false' && typeof value !== 'boolean')
|
|
270
520
|
throw failure('unavailable_state');
|
|
271
521
|
return value === true || value === 'true';
|
|
272
522
|
},
|
|
523
|
+
// The node's content-invalid flag: an input reporting a validation
|
|
524
|
+
// error. UiAutomator2 reads it only through its hierarchy, so the flag
|
|
525
|
+
// is the set of nodes the same criteria match with it set, and no single
|
|
526
|
+
// request returns both the control and its flag. The read is bracketed:
|
|
527
|
+
// the control resolves to one element before and after it, the same
|
|
528
|
+
// element both times (element IDs are stable per node), and a flagged
|
|
529
|
+
// result is that element. A control that vanished, was replaced or
|
|
530
|
+
// became ambiguous in between is a failed read, never a state.
|
|
531
|
+
invalid: async (c) => {
|
|
532
|
+
disarm();
|
|
533
|
+
const before = await resolveOne(id, c);
|
|
534
|
+
const flagged = elements(await endpoint('/elements', c, 'POST', { using: 'xpath', value: `${xpathOf(id)}[@content-invalid="true"]` }));
|
|
535
|
+
const after = await resolveOne(id, c);
|
|
536
|
+
if (after !== before || flagged.some(ref => ref !== before))
|
|
537
|
+
throw failure('stale_element_reference');
|
|
538
|
+
return flagged.length === 1;
|
|
539
|
+
},
|
|
540
|
+
// One supported UiAutomator2 gesture inside the resolved element; the
|
|
541
|
+
// driver reports whether more content exists, which is not retained.
|
|
542
|
+
scroll: async (direction, percent, c) => {
|
|
543
|
+
const ref = await resolveOne(id, c);
|
|
544
|
+
await observeGesture(c);
|
|
545
|
+
await endpoint('/execute/sync', c, 'POST', { script: 'mobile: scrollGesture', args: [{ elementId: ref, direction, percent }] });
|
|
546
|
+
},
|
|
547
|
+
bounds: async (c) => { disarm(); return rect(await endpoint(`/element/${await resolveOne(id, c)}/rect`, c)); },
|
|
273
548
|
});
|
|
549
|
+
const pixel = (value) => Number.isInteger(value) && value >= 0 && value <= 65_535;
|
|
550
|
+
const offset = (value) => Number.isInteger(value) && value >= -65_535 && value <= 65_535;
|
|
551
|
+
// Only finite numbers are rounded: a null or boolean field is a malformed
|
|
552
|
+
// response, never a zero. Origins may be negative for a partly scrolled-out control.
|
|
553
|
+
const rect = (value) => {
|
|
554
|
+
const fields = [value?.x, value?.y, value?.width, value?.height];
|
|
555
|
+
if (!fields.every(field => typeof field === 'number' && Number.isFinite(field)))
|
|
556
|
+
throw failure('invalid_property');
|
|
557
|
+
const r = { x: Math.round(value.x), y: Math.round(value.y), width: Math.round(value.width), height: Math.round(value.height) };
|
|
558
|
+
if (!offset(r.x) || !offset(r.y) || !pixel(r.width) || !pixel(r.height))
|
|
559
|
+
throw failure('invalid_property');
|
|
560
|
+
return r;
|
|
561
|
+
};
|
|
562
|
+
const keyboardShown = async (c) => {
|
|
563
|
+
check(c);
|
|
564
|
+
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));
|
|
565
|
+
if (ime === 'unknown')
|
|
566
|
+
throw failure('unavailable_state');
|
|
567
|
+
return ime === 'shown';
|
|
568
|
+
};
|
|
569
|
+
// Brought to the front with the launcher intent, which matches the task's
|
|
570
|
+
// root intent: a bare `am start -n` stacks a second instance of a
|
|
571
|
+
// standard-launch activity on top of the one the session started.
|
|
572
|
+
const launch = ['shell', 'am', 'start', '-W', '-a', 'android.intent.action.MAIN', '-c', 'android.intent.category.LAUNCHER',
|
|
573
|
+
'-n', `${options.appPackage}/${options.activity}`];
|
|
574
|
+
const appCommand = (script, c) => endpoint('/execute/sync', c, 'POST', { script, args: [{ appId: options.appPackage }] });
|
|
274
575
|
const cleanup = async () => {
|
|
275
576
|
await Promise.all([stop(emulator), stop(server)]);
|
|
276
577
|
// Aborting HTTP alone cannot stop an already dispatched native action.
|
|
@@ -331,17 +632,28 @@ function androidTargetDriver(options) {
|
|
|
331
632
|
let stage = 'configuration';
|
|
332
633
|
try {
|
|
333
634
|
let apkBytes;
|
|
635
|
+
if (expected?.apk !== undefined) {
|
|
636
|
+
const artifact = (0, node_path_1.resolve)(expected.apk);
|
|
637
|
+
const info = await (0, promises_1.stat)(artifact);
|
|
638
|
+
if (!info.isFile() || info.size > 256 * 1024 * 1024)
|
|
639
|
+
throw failure('invalid_expected_apk');
|
|
640
|
+
const digest = (0, node_crypto_1.createHash)('sha256').update(await (0, promises_1.readFile)(artifact)).digest('hex');
|
|
641
|
+
// Two declarations that disagree are a configuration error, not a device finding.
|
|
642
|
+
if (options.apkSHA256 !== undefined && digest !== options.apkSHA256)
|
|
643
|
+
throw failure('expected_apk_digest_conflict');
|
|
644
|
+
expectedDigest = digest;
|
|
645
|
+
}
|
|
334
646
|
if (!physical) {
|
|
335
647
|
const apk = (0, node_path_1.resolve)(options.apk);
|
|
336
648
|
const info = await (0, promises_1.stat)(apk);
|
|
337
649
|
if (!info.isFile() || info.size > 256 * 1024 * 1024)
|
|
338
650
|
throw failure('invalid_apk');
|
|
339
651
|
apkBytes = await (0, promises_1.readFile)(apk);
|
|
340
|
-
if ((0, node_crypto_1.createHash)('sha256').update(apkBytes).digest('hex') !==
|
|
341
|
-
throw
|
|
652
|
+
if ((0, node_crypto_1.createHash)('sha256').update(apkBytes).digest('hex') !== expectedDigest)
|
|
653
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'build-digest', stage: 'open' });
|
|
342
654
|
}
|
|
343
|
-
const appiumPkg = JSON.parse(await (0, promises_1.readFile)(
|
|
344
|
-
const driverPkg = JSON.parse(await (0, promises_1.readFile)(
|
|
655
|
+
const appiumPkg = JSON.parse(await (0, promises_1.readFile)(tooling.appium, 'utf8'));
|
|
656
|
+
const driverPkg = JSON.parse(await (0, promises_1.readFile)(tooling.uiautomator2, 'utf8'));
|
|
345
657
|
if (appiumPkg.version !== android_runtime_1.androidVersions.appium || driverPkg.version !== android_runtime_1.androidVersions.uiautomator2)
|
|
346
658
|
throw failure('driver_version_mismatch');
|
|
347
659
|
const scratch = process.env.NINELIVES_TARGET_SCRATCH_DIR;
|
|
@@ -357,7 +669,7 @@ function androidTargetDriver(options) {
|
|
|
357
669
|
const installedAPK = (0, node_path_1.join)(directory, 'fixture.apk');
|
|
358
670
|
if (apkBytes) {
|
|
359
671
|
await (0, promises_1.writeFile)(installedAPK, apkBytes, { mode: 0o400 });
|
|
360
|
-
const badging = await command(
|
|
672
|
+
const badging = await command(sdkTools.aapt2, ['dump', 'badging', installedAPK], c, env);
|
|
361
673
|
if (/^package: name='([^']+)'/.exec(badging)?.[1] !== options.appPackage)
|
|
362
674
|
throw failure('apk_package_mismatch');
|
|
363
675
|
}
|
|
@@ -368,14 +680,34 @@ function androidTargetDriver(options) {
|
|
|
368
680
|
if (physical) {
|
|
369
681
|
stage = 'device_attach';
|
|
370
682
|
serial = options.deviceSerial;
|
|
371
|
-
const
|
|
372
|
-
const lock = (0, node_path_1.join)(leaseRoot, `9l-android-${(0, node_crypto_1.createHash)('sha256').update(serial).digest('hex')}.lock`);
|
|
683
|
+
const lock = androidLeasePath(serial);
|
|
373
684
|
// Never recover a stale lease automatically: a killed worker may have
|
|
374
685
|
// left automation running. Manual inspection is required in that case.
|
|
375
|
-
await (0, promises_1.mkdir)(
|
|
686
|
+
await (0, promises_1.mkdir)((0, node_path_1.dirname)(lock), { recursive: true, mode: 0o700 });
|
|
376
687
|
await (0, promises_1.mkdir)(lock, { mode: 0o700 });
|
|
377
688
|
lease = lock;
|
|
378
689
|
await installedBuild(c);
|
|
690
|
+
// Version and signer are checked before any device change or session.
|
|
691
|
+
stage = 'build_identity';
|
|
692
|
+
await buildIdentity(c);
|
|
693
|
+
stage = 'device_state';
|
|
694
|
+
// A phone that cannot be read before the test is in an unknown
|
|
695
|
+
// state, not an open failure; cancellation, the deadline and a
|
|
696
|
+
// closed driver still propagate.
|
|
697
|
+
let state;
|
|
698
|
+
try {
|
|
699
|
+
state = await readDeviceState(c);
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
if (interrupted(c))
|
|
703
|
+
throw error;
|
|
704
|
+
throw new targets_1.TargetSetupError({ classification: 'unknown', reason: 'device-state-unknown', stage: 'open' });
|
|
705
|
+
}
|
|
706
|
+
if (state === 'locked' || state === 'screen-off')
|
|
707
|
+
throw new targets_1.TargetSetupError({ classification: 'blocked', reason: state === 'locked' ? 'device-locked' : 'screen-off', stage: 'open' });
|
|
708
|
+
stage = 'displays';
|
|
709
|
+
await readDisplays(c);
|
|
710
|
+
stage = 'device_attach';
|
|
379
711
|
if (await adbRun(['shell', 'sh', '-c', "'pidof io.appium.uiautomator2.server io.appium.uiautomator2.server.test || true'"], c))
|
|
380
712
|
throw failure('device_automation_in_use');
|
|
381
713
|
for (const key of ['hidden_api_policy_pre_p_apps', 'hidden_api_policy_p_apps', 'hidden_api_policy']) {
|
|
@@ -410,7 +742,9 @@ function androidTargetDriver(options) {
|
|
|
410
742
|
if (Buffer.byteLength(consoleSocket) > 103)
|
|
411
743
|
throw failure('scratch_path_too_long');
|
|
412
744
|
const port = await reportedConsole(consoleSocket, c, () => {
|
|
413
|
-
|
|
745
|
+
// A declared biometric snapshot is loaded and never saved, so
|
|
746
|
+
// every test still starts from the same state.
|
|
747
|
+
emulator = (0, node_child_process_1.spawn)(emulatorPath, ['-avd', options.avd, '-read-only', ...(biometrics ? ['-snapshot', biometrics.snapshot, '-no-snapshot-save'] : ['-no-snapshot']), '-no-audio', '-report-console', `unix:${consoleSocket}`, ...(options.headless === false ? [] : ['-no-window']), '-gpu', 'swiftshader_indirect'], { env, stdio: 'ignore' });
|
|
414
748
|
emulator.on('error', () => { });
|
|
415
749
|
return emulator;
|
|
416
750
|
});
|
|
@@ -430,14 +764,35 @@ function androidTargetDriver(options) {
|
|
|
430
764
|
}
|
|
431
765
|
await (0, promises_2.setTimeout)(250, undefined, { signal: c.signal });
|
|
432
766
|
}
|
|
767
|
+
if (biometrics) {
|
|
768
|
+
// The snapshot must resume unlocked with a fingerprint enrolled;
|
|
769
|
+
// the driver has no PIN to unlock it with.
|
|
770
|
+
stage = 'biometrics';
|
|
771
|
+
let state;
|
|
772
|
+
try {
|
|
773
|
+
state = await readDeviceState(c);
|
|
774
|
+
}
|
|
775
|
+
catch (error) {
|
|
776
|
+
if (interrupted(c))
|
|
777
|
+
throw error;
|
|
778
|
+
state = 'unknown';
|
|
779
|
+
}
|
|
780
|
+
const enrolled = [...(await adbRun(shell('dumpsys fingerprint 2>/dev/null | head -c 4096'), c)).matchAll(/"count":([0-9]{1,4})/g)].reduce((sum, m) => sum + Number(m[1]), 0);
|
|
781
|
+
if (state !== 'unlocked' || enrolled < 1)
|
|
782
|
+
throw new targets_1.TargetSetupError({ classification: 'mismatch', reason: 'biometrics-unavailable', stage: 'open' });
|
|
783
|
+
}
|
|
784
|
+
stage = 'displays';
|
|
785
|
+
await readDisplays(c);
|
|
433
786
|
stage = 'apk_install';
|
|
434
787
|
await adbRun(['install', '--no-streaming', '-r', installedAPK], c);
|
|
788
|
+
stage = 'build_identity';
|
|
789
|
+
await buildIdentity(c, installedAPK);
|
|
435
790
|
}
|
|
436
791
|
const appiumPort = await freePort();
|
|
437
792
|
base = `http://127.0.0.1:${appiumPort}/${owner}`;
|
|
438
793
|
check(c);
|
|
439
794
|
stage = 'server_start';
|
|
440
|
-
server = (0, node_child_process_1.spawn)(process.execPath, [
|
|
795
|
+
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
796
|
server.on('error', () => { });
|
|
442
797
|
for (;;) {
|
|
443
798
|
check(c);
|
|
@@ -482,33 +837,78 @@ function androidTargetDriver(options) {
|
|
|
482
837
|
let identity;
|
|
483
838
|
if (physical) {
|
|
484
839
|
await installedBuild(c);
|
|
485
|
-
await adbRun(
|
|
840
|
+
await adbRun(launch, c);
|
|
841
|
+
stage = 'baseline';
|
|
842
|
+
let reading = await readBaseline(c);
|
|
843
|
+
if (dirty(reading) && backPresses > 0) {
|
|
844
|
+
// Declared, recorded and bounded: Back until the baseline is
|
|
845
|
+
// observed again. An unknown reading after Back is not a
|
|
846
|
+
// restored baseline.
|
|
847
|
+
const reason = reading;
|
|
848
|
+
let presses = 0;
|
|
849
|
+
// A failed Back or a failed read after one leaves an unknown,
|
|
850
|
+
// unrestored baseline: the presses already completed stay on the
|
|
851
|
+
// record. Cancellation, the deadline and a closed driver still propagate.
|
|
852
|
+
while (dirty(reading) && presses < backPresses) {
|
|
853
|
+
check(c);
|
|
854
|
+
try {
|
|
855
|
+
await adbRun(['shell', 'input', 'keyevent', 'KEYCODE_BACK'], c);
|
|
856
|
+
}
|
|
857
|
+
catch (error) {
|
|
858
|
+
if (interrupted(c))
|
|
859
|
+
throw error;
|
|
860
|
+
reading = 'unknown';
|
|
861
|
+
break;
|
|
862
|
+
}
|
|
863
|
+
presses++;
|
|
864
|
+
await (0, promises_2.setTimeout)(500, undefined, { signal: c.signal });
|
|
865
|
+
try {
|
|
866
|
+
reading = await readBaseline(c);
|
|
867
|
+
}
|
|
868
|
+
catch (error) {
|
|
869
|
+
if (interrupted(c))
|
|
870
|
+
throw error;
|
|
871
|
+
reading = 'unknown';
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
const recovery = { method: 'back', presses, restored: reading === 'clean' };
|
|
875
|
+
if (reading !== 'clean')
|
|
876
|
+
throw new targets_1.TargetSetupError({ classification: 'dirty', reason, stage: 'open', recovery });
|
|
877
|
+
setupRecord = { classification: 'dirty', reason, stage: 'open', recovery };
|
|
878
|
+
}
|
|
879
|
+
else if (dirty(reading))
|
|
880
|
+
throw new targets_1.TargetSetupError({ classification: 'dirty', reason: reading, stage: 'open' });
|
|
486
881
|
identity = { device: 'physical', deviceHash: (0, node_crypto_1.createHash)('sha256').update(serial).digest('hex') };
|
|
487
882
|
}
|
|
488
883
|
else {
|
|
489
|
-
|
|
490
|
-
const
|
|
884
|
+
// Read within 10 s from both streams, else from the package revision.
|
|
885
|
+
const bounded = { ...c, deadlineMs: Math.min(c.deadlineMs, Date.now() + 10_000) };
|
|
886
|
+
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
887
|
if (!version)
|
|
492
888
|
throw failure('unknown_emulator_version');
|
|
493
889
|
identity = { emulator: version };
|
|
494
890
|
}
|
|
495
891
|
evidence = {
|
|
496
|
-
appPackage: options.appPackage, apkSHA256:
|
|
892
|
+
appPackage: options.appPackage, apkSHA256: expectedDigest, versionCode, versionName, signer,
|
|
497
893
|
api: await adbRun(['shell', 'getprop', 'ro.build.version.sdk'], c),
|
|
498
894
|
release: await adbRun(['shell', 'getprop', 'ro.build.version.release'], c),
|
|
499
895
|
abi: await adbRun(['shell', 'getprop', 'ro.product.cpu.abi'], c),
|
|
896
|
+
display: display?.id ?? 'unknown', displayWidth: String(display?.width ?? 0), displayHeight: String(display?.height ?? 0), density: String(display?.density ?? 0), posture,
|
|
500
897
|
...identity, ...android_runtime_1.androidVersions, worker: (0, node_crypto_1.createHash)('sha256').update(`${owner}:${process.pid}`).digest('hex'),
|
|
501
898
|
};
|
|
502
899
|
}
|
|
503
|
-
catch {
|
|
900
|
+
catch (error) {
|
|
504
901
|
closed = true;
|
|
505
902
|
await cleanup();
|
|
903
|
+
if (error instanceof targets_1.TargetSetupError)
|
|
904
|
+
throw error;
|
|
506
905
|
throw failure(`open_failed_${stage}`);
|
|
507
906
|
}
|
|
508
907
|
})();
|
|
509
908
|
return opening;
|
|
510
909
|
},
|
|
511
910
|
async reset(c) {
|
|
911
|
+
disarm();
|
|
512
912
|
if (physical)
|
|
513
913
|
throw failure('reset_unsupported_on_attached_device');
|
|
514
914
|
check(c);
|
|
@@ -517,9 +917,250 @@ function androidTargetDriver(options) {
|
|
|
517
917
|
await adbRun(['shell', 'am', 'force-stop', options.appPackage], c);
|
|
518
918
|
if (await adbRun(['shell', 'pm', 'clear', options.appPackage], c) !== 'Success')
|
|
519
919
|
throw failure('reset_failed');
|
|
520
|
-
await adbRun(
|
|
920
|
+
await adbRun(launch, c);
|
|
521
921
|
},
|
|
522
922
|
async observeTestId(id, c) { return (await matches(id, c)).slice(0, 2).map(() => handle(id)); },
|
|
923
|
+
setup: () => setupRecord,
|
|
924
|
+
async back(c) { await observeGesture(c); await endpoint('/back', c, 'POST', {}); },
|
|
925
|
+
async keyboardShown(c) { disarm(); return keyboardShown(c); },
|
|
926
|
+
// Back dismisses a shown keyboard without touching the selected input
|
|
927
|
+
// method; the result is read back rather than assumed.
|
|
928
|
+
async hideKeyboard(c) {
|
|
929
|
+
disarm();
|
|
930
|
+
if (!await keyboardShown(c))
|
|
931
|
+
return;
|
|
932
|
+
await endpoint('/back', c, 'POST', {});
|
|
933
|
+
for (;;) {
|
|
934
|
+
if (!await keyboardShown(c))
|
|
935
|
+
return;
|
|
936
|
+
if (Date.now() + 100 >= c.deadlineMs)
|
|
937
|
+
throw failure('keyboard_not_hidden');
|
|
938
|
+
await (0, promises_2.setTimeout)(100, undefined, { signal: c.signal });
|
|
939
|
+
}
|
|
940
|
+
},
|
|
941
|
+
async tapAt(point, c) {
|
|
942
|
+
if (!pixel(point.x) || !pixel(point.y))
|
|
943
|
+
throw failure('invalid_point');
|
|
944
|
+
await observeGesture(c, { x: point.x, y: point.y });
|
|
945
|
+
await endpoint('/actions', c, 'POST', { actions: [{ type: 'pointer', id: 'finger1', parameters: { pointerType: 'touch' }, actions: [
|
|
946
|
+
{ type: 'pointerMove', duration: 0, x: point.x, y: point.y }, { type: 'pointerDown', button: 0 }, { type: 'pause', duration: 50 }, { type: 'pointerUp', button: 0 },
|
|
947
|
+
] }] });
|
|
948
|
+
},
|
|
949
|
+
async screenDigest(c) { check(c); return screenDigest(c); },
|
|
950
|
+
async viewport(c) {
|
|
951
|
+
disarm();
|
|
952
|
+
const r = rect(await endpoint('/window/rect', c));
|
|
953
|
+
if (r.width === 0 || r.height === 0)
|
|
954
|
+
throw failure('invalid_property');
|
|
955
|
+
return { width: r.width, height: r.height };
|
|
956
|
+
},
|
|
957
|
+
// Terminate is a force-stop of the configured package only; data, the
|
|
958
|
+
// installation and device settings are untouched. Activate relaunches it.
|
|
959
|
+
// The driver's own force-stop of the configured package, then a bounded
|
|
960
|
+
// wait until no process of it is left: Appium's terminateApp gave up after
|
|
961
|
+
// its own short exit check on a slow emulator.
|
|
962
|
+
async terminate(c) {
|
|
963
|
+
disarm();
|
|
964
|
+
check(c);
|
|
965
|
+
await adbRun(['shell', 'am', 'force-stop', options.appPackage], c);
|
|
966
|
+
for (;;) {
|
|
967
|
+
if (await adbRun(shell(`pidof ${options.appPackage} || true`), c) === '')
|
|
968
|
+
return;
|
|
969
|
+
if (Date.now() + 250 >= c.deadlineMs)
|
|
970
|
+
throw failure('terminate_failed');
|
|
971
|
+
await (0, promises_2.setTimeout)(250, undefined, { signal: c.signal });
|
|
972
|
+
}
|
|
973
|
+
},
|
|
974
|
+
async activate(c) { disarm(); await appCommand('mobile: activateApp', c); },
|
|
975
|
+
// The focused window's package, from the same filtered window dump the
|
|
976
|
+
// baseline reads: the app's, another package's (system UI, a permission
|
|
977
|
+
// controller, Settings) or none. An unreadable dump is not a state.
|
|
978
|
+
async foreground(c) {
|
|
979
|
+
disarm();
|
|
980
|
+
check(c);
|
|
981
|
+
const windows = await readWindows(c);
|
|
982
|
+
if (!windows || windows.focus === 'unknown')
|
|
983
|
+
throw failure('unavailable_state');
|
|
984
|
+
return windows.focus;
|
|
985
|
+
},
|
|
986
|
+
// Owned emulator: the serial its console handshake established; attached
|
|
987
|
+
// phone: the serial the spec configured. Only while the session is open.
|
|
988
|
+
deviceSerial: () => session && !closed ? serial : undefined,
|
|
989
|
+
// The emulator's virtual sensor through its console: a touch, a short
|
|
990
|
+
// hold and a lift. Present only on an owned emulator with biometrics.
|
|
991
|
+
// The console exits 0 even when it refuses a command and prints `KO`.
|
|
992
|
+
...(biometrics && !physical ? { fingerprint: async (finger, c) => {
|
|
993
|
+
disarm();
|
|
994
|
+
check(c);
|
|
995
|
+
if (!Number.isInteger(finger) || finger < 1 || finger > 10)
|
|
996
|
+
throw failure('invalid_value');
|
|
997
|
+
// A prompt drops a touch that arrives while it is still animating in,
|
|
998
|
+
// though the sensor service already reports the session: wait, within
|
|
999
|
+
// the bound, until two captures 250 ms apart are equal. The touch is
|
|
1000
|
+
// made once; it is never repeated.
|
|
1001
|
+
for (let previous = '';;) {
|
|
1002
|
+
if (Date.now() + 1500 >= c.deadlineMs)
|
|
1003
|
+
throw failure('display_not_settled');
|
|
1004
|
+
const current = await screenDigest(c);
|
|
1005
|
+
if (current === previous)
|
|
1006
|
+
break;
|
|
1007
|
+
previous = current;
|
|
1008
|
+
await (0, promises_2.setTimeout)(250, undefined, { signal: c.signal });
|
|
1009
|
+
}
|
|
1010
|
+
const sensor = async (action) => {
|
|
1011
|
+
if (/(^|\n)KO\b/.test(await command(adb, ['-s', serial, 'emu', 'finger', action, String(finger)], c, env, 'both')))
|
|
1012
|
+
throw failure('fingerprint_failed');
|
|
1013
|
+
};
|
|
1014
|
+
await sensor('touch');
|
|
1015
|
+
// Held about as long as a person rests a finger on the sensor.
|
|
1016
|
+
await (0, promises_2.setTimeout)(1000, undefined, { signal: c.signal });
|
|
1017
|
+
await sensor('remove');
|
|
1018
|
+
} } : {}),
|
|
1019
|
+
// After a completed assertion failure: did the phone become unavailable?
|
|
1020
|
+
// Read-only; an owned emulator cannot lock itself. With diagnostics, a
|
|
1021
|
+
// hidden assertion that failed although the app lost a window since the
|
|
1022
|
+
// last gesture is the accessibility snapshot disagreeing with the window
|
|
1023
|
+
// manager: observer staleness, attributed to neither the app nor the tap.
|
|
1024
|
+
async recheck(c, failed) {
|
|
1025
|
+
if (!session)
|
|
1026
|
+
return undefined;
|
|
1027
|
+
check(c);
|
|
1028
|
+
if (physical) {
|
|
1029
|
+
let state;
|
|
1030
|
+
try {
|
|
1031
|
+
state = await readDeviceState(c);
|
|
1032
|
+
}
|
|
1033
|
+
catch (error) {
|
|
1034
|
+
// A phone that cannot be read (disconnected, adb gone) has an unknown
|
|
1035
|
+
// state; cancellation, the deadline and a closed driver still propagate.
|
|
1036
|
+
if (interrupted(c))
|
|
1037
|
+
throw error;
|
|
1038
|
+
state = 'unknown';
|
|
1039
|
+
}
|
|
1040
|
+
if (state === 'unknown')
|
|
1041
|
+
return { classification: 'unknown', reason: 'device-state-unknown', stage: 'recheck' };
|
|
1042
|
+
if (state !== 'unlocked')
|
|
1043
|
+
return { classification: 'blocked', reason: state === 'locked' ? 'device-locked' : 'screen-off', stage: 'recheck' };
|
|
1044
|
+
}
|
|
1045
|
+
// Heuristic, opt-in and limited to a dismissal sequence: UiAutomator2
|
|
1046
|
+
// does not say which window an element belongs to, so a hidden
|
|
1047
|
+
// assertion that fails right after a gesture while the app lost a
|
|
1048
|
+
// window is attributed to the snapshot, not proven. The diagnostic
|
|
1049
|
+
// keeps the counts either way.
|
|
1050
|
+
if (diagnostics && armed && failed.operation === 'assert-hidden' && lastGesture && lastGesture.windows > 0) {
|
|
1051
|
+
const now = await readWindows(c);
|
|
1052
|
+
if (now && now.windows < lastGesture.windows)
|
|
1053
|
+
return { classification: 'observer', reason: 'window-gone-element-displayed', stage: 'recheck' };
|
|
1054
|
+
}
|
|
1055
|
+
return undefined;
|
|
1056
|
+
},
|
|
1057
|
+
// Metadata only: what was asked, how long it took, and the app's windows
|
|
1058
|
+
// before the last gesture and now. Nothing is retried and no cause is claimed.
|
|
1059
|
+
async diagnose(f, c) {
|
|
1060
|
+
if (!diagnostics)
|
|
1061
|
+
return undefined;
|
|
1062
|
+
const point = f.point ?? lastPoint;
|
|
1063
|
+
const record = { operation: f.operation, reason: f.reason, elapsedMs: f.elapsedMs, windowsBefore: lastGesture?.windows ?? -1, windowsAfter: -1,
|
|
1064
|
+
...(point ? { x: point.x, y: point.y, point: true } : {}), ...(lastGesture ? { focusBefore: lastGesture.focus } : {}) };
|
|
1065
|
+
if (closed || !session)
|
|
1066
|
+
return record;
|
|
1067
|
+
try {
|
|
1068
|
+
const after = await readWindows(c);
|
|
1069
|
+
if (after) {
|
|
1070
|
+
record.windowsAfter = after.windows;
|
|
1071
|
+
record.focusAfter = after.focus;
|
|
1072
|
+
}
|
|
1073
|
+
const r = rect(await endpoint('/window/rect', c));
|
|
1074
|
+
if (r.width > 0 && r.height > 0) {
|
|
1075
|
+
record.viewportWidth = r.width;
|
|
1076
|
+
record.viewportHeight = r.height;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
catch { /* partial record */ }
|
|
1080
|
+
return record;
|
|
1081
|
+
},
|
|
523
1082
|
close,
|
|
524
1083
|
};
|
|
525
1084
|
}
|
|
1085
|
+
const maxApkBytes = 256 * 1024 * 1024;
|
|
1086
|
+
/** Install or update an app on an explicitly selected device without
|
|
1087
|
+
* uninstalling or clearing its data. The APK's signing certificate must
|
|
1088
|
+
* match the installed app's, read through the local apksigner; a different
|
|
1089
|
+
* signer refuses before any device change. Returns the installed identity
|
|
1090
|
+
* for the project's reviewed build metadata. Never runs inside a test. */
|
|
1091
|
+
async function installInPlace(options) {
|
|
1092
|
+
if (!/^[a-zA-Z0-9_.:-]{1,128}$/.test(options.deviceSerial) || options.deviceSerial.startsWith('emulator-') || !options.apk)
|
|
1093
|
+
throw failure('invalid_configuration');
|
|
1094
|
+
const sdkRoot = options.sdkRoot ?? (0, android_env_1.androidDefaults)().sdkRoot;
|
|
1095
|
+
if (!sdkRoot)
|
|
1096
|
+
throw failure('sdk_not_found');
|
|
1097
|
+
const sdk = (0, node_path_1.resolve)(sdkRoot), { adb, aapt2, apksigner } = (0, android_env_1.androidToolPaths)(sdk);
|
|
1098
|
+
const env = { ANDROID_HOME: sdk, ANDROID_SDK_ROOT: sdk };
|
|
1099
|
+
for (const key of ['PATH', 'HOME', 'TMPDIR', 'JAVA_HOME', 'SYSTEMROOT'])
|
|
1100
|
+
if (process.env[key])
|
|
1101
|
+
env[key] = process.env[key];
|
|
1102
|
+
const c = { signal: new AbortController().signal, deadlineMs: Date.now() + Math.min(Math.max(options.timeoutMs ?? 300_000, 1_000), 900_000) };
|
|
1103
|
+
const apk = (0, node_path_1.resolve)(options.apk);
|
|
1104
|
+
const info = await (0, promises_1.stat)(apk);
|
|
1105
|
+
if (!info.isFile() || info.size > maxApkBytes)
|
|
1106
|
+
throw failure('invalid_apk');
|
|
1107
|
+
// One private snapshot is hashed, inspected, verified and installed, so a
|
|
1108
|
+
// build or download replacing the caller's file meanwhile changes nothing.
|
|
1109
|
+
const bytes = await (0, promises_1.readFile)(apk);
|
|
1110
|
+
if (bytes.length > maxApkBytes)
|
|
1111
|
+
throw failure('invalid_apk');
|
|
1112
|
+
const apkSHA256 = (0, node_crypto_1.createHash)('sha256').update(bytes).digest('hex');
|
|
1113
|
+
const scratch = await (0, promises_1.mkdtemp)((0, node_path_1.join)(process.env.TMPDIR ?? (0, node_os_1.homedir)(), '9l-install-'));
|
|
1114
|
+
try {
|
|
1115
|
+
const snapshot = (0, node_path_1.join)(scratch, 'app.apk');
|
|
1116
|
+
await (0, promises_1.writeFile)(snapshot, bytes, { mode: 0o600 });
|
|
1117
|
+
const badging = await command(aapt2, ['dump', 'badging', snapshot], c, env);
|
|
1118
|
+
const appPackage = /^package: name='([a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)+)'/m.exec(badging)?.[1];
|
|
1119
|
+
if (!appPackage)
|
|
1120
|
+
throw failure('unreadable_package');
|
|
1121
|
+
const signer = (0, android_device_1.parseSigner)(await command(apksigner, ['verify', '--print-certs', snapshot], c, env));
|
|
1122
|
+
if (!signer)
|
|
1123
|
+
throw failure('unreadable_signer');
|
|
1124
|
+
const run = (args) => command(adb, ['-s', options.deviceSerial, ...args], c, env);
|
|
1125
|
+
// The same exclusive lease a test takes: never install under a running
|
|
1126
|
+
// test or beside another installer. Only the lease this call created is released.
|
|
1127
|
+
const lock = androidLeasePath(options.deviceSerial);
|
|
1128
|
+
await (0, promises_1.mkdir)((0, node_path_1.dirname)(lock), { recursive: true, mode: 0o700 });
|
|
1129
|
+
try {
|
|
1130
|
+
await (0, promises_1.mkdir)(lock, { mode: 0o700 });
|
|
1131
|
+
}
|
|
1132
|
+
catch {
|
|
1133
|
+
throw failure('device_in_use');
|
|
1134
|
+
}
|
|
1135
|
+
try {
|
|
1136
|
+
if (await run(['get-state']) !== 'device' || await run(['shell', 'getprop', 'ro.kernel.qemu']) === '1')
|
|
1137
|
+
throw failure('not_physical_device');
|
|
1138
|
+
// pm path exits nonzero for an absent package: a first installation, not a transport failure.
|
|
1139
|
+
const path = await run(shellArgs(`pm path ${appPackage} 2>/dev/null || true`));
|
|
1140
|
+
if (path) {
|
|
1141
|
+
if (!/^package:(\/data\/app\/[A-Za-z0-9_./=+~\-]+\/base\.apk)$/.test(path))
|
|
1142
|
+
throw failure('unsupported_installed_build');
|
|
1143
|
+
const pulled = (0, node_path_1.join)(scratch, 'installed.apk');
|
|
1144
|
+
await run(['pull', path.slice(8), pulled]);
|
|
1145
|
+
const installed = (0, android_device_1.parseSigner)(await command(apksigner, ['verify', '--print-certs', pulled], c, env));
|
|
1146
|
+
if (installed !== signer)
|
|
1147
|
+
throw failure('signer_mismatch');
|
|
1148
|
+
}
|
|
1149
|
+
await run(['install', '--no-streaming', '-r', snapshot]);
|
|
1150
|
+
const installedPath = await run(['shell', 'pm', 'path', appPackage]);
|
|
1151
|
+
if (!/^package:(\/data\/app\/[A-Za-z0-9_./=+~\-]+\/base\.apk)$/.test(installedPath))
|
|
1152
|
+
throw failure('unsupported_installed_build');
|
|
1153
|
+
const digest = (await run(['shell', 'sha256sum', installedPath.slice(8)])).split(/\s+/)[0];
|
|
1154
|
+
if (digest !== apkSHA256)
|
|
1155
|
+
throw failure('installed_build_changed');
|
|
1156
|
+
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`)));
|
|
1157
|
+
return { appPackage, apkSHA256, signer, ...version };
|
|
1158
|
+
}
|
|
1159
|
+
finally {
|
|
1160
|
+
await (0, promises_1.rm)(lock, { recursive: true, force: true });
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
finally {
|
|
1164
|
+
await (0, promises_1.rm)(scratch, { recursive: true, force: true });
|
|
1165
|
+
}
|
|
1166
|
+
}
|