Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
1857 lines (1698 loc) · 69.7 KB
/
Copy pathindex.js
File metadata and controls
1857 lines (1698 loc) · 69.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Mobium — mobile app automation on emulators, simulators and phones.
*
* import { start } from 'mobium'
*
* const device = await start({ platform: 'android', app: 'com.android.settings' })
* for (const el of await device.map()) console.log(el.ref, el.label)
* await device.tap('@e1')
* await device.quit()
*/
import { spawn } from 'node:child_process'
import { accessSync, constants, readFileSync, statSync } from 'node:fs'
import { delimiter, extname, isAbsolute, join, resolve } from 'node:path'
import { createInterface } from 'node:readline'
/**
* A tool reported that it could not do what was asked. Every failure carries
* a stable code, the same in every client and on the wire (the error codes
* in the mobium repository's docs/guides/cli.md), and each code has a subclass below, so a script
* catches the kind it can handle:
*
* try { await device.tap('text=Continue') }
* catch (e) { if (e instanceof NoSuchElementError) await device.scrollTo(...) else throw e }
*
* `remedy` says what to do about it, `retryable` whether the same call can
* succeed if made again, and `details` holds machine-readable facts. A code
* this client does not know, or a daemon too old to send one, is a plain
* MobiumError with `code` set ("error" for the latter).
*/
export class MobiumError extends Error {
static code = 'error'
constructor(message, { code, remedy = '', retryable = false, details = {} } = {}) {
super(message)
this.name = new.target.name
this.code = code ?? new.target.code
this.remedy = remedy
this.retryable = retryable
this.details = details
}
}
/** Nothing to drive: no device matches, or none is connected. */
export class NoDeviceError extends MobiumError {
static code = 'no_device'
}
/** The device is there and cannot be driven yet: locked, not trusted, Developer Mode off, not answering. The device only: a dialog or the keyboard over a target is ElementNotReachableError. */
export class DeviceNotReadyError extends MobiumError {
static code = 'device_not_ready'
}
/** Something on this machine is missing: adb, Xcode, a signing certificate. */
export class ToolchainMissingError extends MobiumError {
static code = 'toolchain_missing'
}
/** A locator or ref matched nothing on screen. Worth scrolling for. */
export class NoSuchElementError extends MobiumError {
static code = 'no_such_element'
}
/** A locator matched more than one element. Narrow it; Mobium never guesses. */
export class AmbiguousLocatorError extends MobiumError {
static code = 'ambiguous_locator'
}
/** The element cannot be touched where it is: off screen, or something is over it — a dialog, the keyboard, another screen, a control. A cover has details.check "receivesEvents" and names itself in details: dialog, keyboard, screen, cover, siri, assistant or clipboard_preview. */
export class ElementNotReachableError extends MobiumError {
static code = 'element_not_reachable'
}
/** A WebView context that is not there. */
export class NoSuchContextError extends MobiumError {
static code = 'no_such_context'
}
/** A dialog was expected and none is on screen. */
export class NoSuchAlertError extends MobiumError {
static code = 'no_such_alert'
}
/** This driver or platform cannot do it, and says why. Retrying cannot help. */
export class UnsupportedError extends MobiumError {
static code = 'unsupported'
}
/** The command reported success and reading the state back disagreed. */
export class NotConfirmedError extends MobiumError {
static code = 'not_confirmed'
}
/** Whoever started Mobium does not allow this call: a read-only Mobium asked to act, or an app outside its app list. Retrying cannot help. */
export class NotPermittedError extends MobiumError {
static code = 'not_permitted'
}
/** A wait ran out. */
export class TimedOutError extends MobiumError {
static code = 'timeout'
}
/** The request itself is wrong. */
export class InvalidArgumentError extends MobiumError {
static code = 'invalid_argument'
}
/** The device side failed (a device server, or adb, simctl, devicectl, lockdown); a server's W3C code is in details.w3c. */
export class DeviceServerError extends MobiumError {
static code = 'device_server'
}
/** A bug in Mobium. */
export class InternalError extends MobiumError {
static code = 'internal'
}
const ERRORS_BY_CODE = new Map(
[NoDeviceError, DeviceNotReadyError, ToolchainMissingError, NoSuchElementError, AmbiguousLocatorError, ElementNotReachableError, NoSuchContextError, NoSuchAlertError, UnsupportedError, NotConfirmedError, NotPermittedError, TimedOutError, InvalidArgumentError, DeviceServerError, InternalError].map(c => [c.code, c]))
/**
* The exception for a failed tool call: the text as always, and the code,
* remedy and details when the daemon sent them.
*/
export function errorFrom(text, structured) {
if (structured && typeof structured === 'object' && structured.code) {
const Cls = ERRORS_BY_CODE.get(structured.code) ?? MobiumError
return new Cls(text, {
code: structured.code,
remedy: structured.remedy ?? '',
retryable: Boolean(structured.retryable),
details: structured.details ?? {},
})
}
return new MobiumError(text)
}
/**
* Locate the mobium binary: the explicit path, then MOBIUM_BIN_PATH, then
* PATH — and nothing else. MOBIUM_BIN_PATH wins so a test run can pin a
* specific build.
*
* The current directory is never searched, not in ./bin and not through a
* relative PATH entry: a library that runs whatever mobium sits where a test
* was started runs a binary anyone could have planted there. PATH is walked
* here, to an absolute path, rather than left to spawn, which on Windows
* looks in the current directory first.
*/
export function findBinary(explicit) {
for (const candidate of [explicit, process.env.MOBIUM_BIN_PATH]) {
if (!candidate) continue
try {
accessSync(candidate, constants.X_OK)
return candidate
} catch {}
// Spelled as on Unix, without .exe: Windows would run the file it names,
// so a check's MOBIUM_BIN_PATH=.../bin/mobium is taken.
if (process.platform === 'win32' && !extname(candidate)) {
try {
accessSync(candidate + '.exe', constants.X_OK)
return candidate + '.exe'
} catch {}
}
throw new MobiumError(`${candidate} is not an executable mobium binary`)
}
const name = process.platform === 'win32' ? 'mobium.exe' : 'mobium'
for (const dir of (process.env.PATH || '').split(delimiter)) {
if (!isAbsolute(dir)) continue
const found = join(dir, name)
try {
if (statSync(found).isFile()) {
accessSync(found, constants.X_OK)
return found
}
} catch {
// Not here, or not executable; keep looking.
}
}
throw new MobiumError('mobium not found — put it on PATH or set MOBIUM_BIN_PATH to the binary')
}
function textOf(result) {
return (result.content || [])
.filter((c) => c.type === 'text')
.map((c) => c.text)
.join('\n')
.trim()
}
/** A tool's structured answer, or undefined when it only returned prose. */
function dataOf(result) {
return result.structuredContent
}
/** Bounds carry a center so callers need not recompute it. */
function toBounds(b = {}) {
const { x1 = 0, y1 = 0, x2 = 0, y2 = 0 } = b
return {
x1,
y1,
x2,
y2,
width: x2 - x1,
height: y2 - y1,
center: { x: Math.floor((x1 + x2) / 2), y: Math.floor((y1 + y2) / 2) },
}
}
function toElement(e) {
return {
ref: e.ref || '',
label: e.label || '',
role: e.role || '',
bounds: toBounds(e.bounds),
locator: e.locator ? `${e.locator.kind}=${e.locator.value}` : '',
context: e.context || '',
// A checkbox, radio or switch's state; null for anything with no such state.
checked: typeof e.checked === 'boolean' ? e.checked : null,
// What the platform reports chosen: the current tab, a segment.
selected: e.selected === true,
// What the platform reports holding input focus: the field typed into, a TV's tile.
focused: e.focused === true,
// What the platform reports not enabled: an action on it waits, then is refused.
disabled: e.disabled === true,
// What a slider reads, as the app states it; empty for anything else.
value: e.value || '',
}
}
function toElements(data) {
if (!data || !data.elements) return []
return data.elements.map(toElement)
}
/**
* Connect and open the session on the device: the device-side server is started now and, given an app, it is launched and
* in front when this resolves. End it with `quit()`.
*
* `platform` is "android" or "ios"; "ios" picks the wda driver, so none need
* be named. `device`, `driver`, `binary` and `callTimeoutMs` are as for
* `connect()`. Nothing requires it — every call opens a session on first use —
* but it puts the slow first start (installing UiAutomator2, building
* WebDriverAgent on an iPhone) where it was asked for.
*
* const device = await start({ platform: 'android', app: 'com.android.settings' })
* try { await device.map() } finally { await device.quit() }
*/
export async function start({ platform, device, app, driver, binary, callTimeoutMs, session } = {}) {
const d = await connect({ device, driver, binary, callTimeoutMs, session })
const args = { action: 'start' }
if (platform) args.platform = platform
if (app) args.app = app
let got
try {
got = (await d.conn.callTool('app_session', args)).structuredContent || {}
} catch (e) {
await d.close()
throw e
}
d.session = {
device: got.device || '', platform: got.platform || '', driver: got.driver || '',
reused: Boolean(got.reused), app: got.app || '',
}
return d
}
/**
* Connect to mobium. It does not touch the device: the session there opens on
* the first call that needs it, or with `start()`.
*
* The transport is `mobium pipe`, which forwards to the shared daemon rather
* than starting a session of its own: a device-side server holds one session
* at a time, so a client with its own would invalidate the CLI's.
*
* `callTimeoutMs` is the longest any one call may take before the connection
* is given up, the handshake included. Unset, the default, waits as long as it
* takes: the first session on an iPhone builds WebDriverAgent, which takes
* minutes. A call that runs out ends the connection -- a late answer would be
* read as the next call's -- and every call after rejects, saying so; connect
* again. Set it well above the longest `waitFor` timeout you use.
*/
export async function connect({ device, driver, binary, callTimeoutMs, session } = {}) {
if (callTimeoutMs !== undefined && !(callTimeoutMs > 0)) {
throw new InvalidArgumentError('callTimeoutMs must be a positive number of milliseconds')
}
const args = ['pipe']
if (device) args.push('--device', device)
if (driver) args.push('--driver', driver)
const child = spawn(findBinary(binary), args, {
// Progress notes about downloading a device-side server go to stderr;
// inheriting keeps a slow first run explicable rather than silent.
stdio: ['pipe', 'pipe', 'inherit'],
// A daemon of this connection's own, as MOBIUM_SESSION names one. One
// daemon serves one call at a time across every device, so parallel runs
// on different devices should each have one.
...(session ? { env: { ...process.env, MOBIUM_SESSION: session } } : {}),
})
const conn = new Connection(child, callTimeoutMs)
try {
await conn.request('initialize', {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'mobium-js', version: '0.1.0' },
})
} catch (e) {
// A handshake that fails leaves a process nobody will ever close -- and a
// child that keeps Node's event loop alive, so the script cannot exit.
// Measured: a refused handshake left mobium running.
conn.kill()
throw e
}
conn.notify('notifications/initialized')
return new Device(conn)
}
/**
* JSON for the wire, refusing NaN and Infinity. JSON has neither, and
* JSON.stringify writes them as null, so setLocation(NaN, 0) reached the
* daemon as a null latitude and came back as "latitude must be a number".
*/
function wire(payload) {
return JSON.stringify(payload, (key, value) => {
if (typeof value === 'number' && !Number.isFinite(value)) {
throw new InvalidArgumentError(`${key || 'a value'} is ${value}, which JSON cannot carry`)
}
return value
})
}
class Connection {
constructor(child, callTimeoutMs) {
this.child = child
this.timeoutMs = callTimeoutMs
this.nextId = 0
// Every request in flight, in the order it was written. The pipe answers
// one request at a time, in order, so the first entry is the one the
// next unnumbered answer belongs to.
this.pending = new Map()
// Why the connection can no longer be used, once something has made that
// true: it was closed, mobium exited or could not start, or a call timed
// out. A call abandoned half-way cannot be resynchronized, so the
// connection ends and every call after says so.
this.dead = null
this.exited = new Promise((resolve) => { this.markExited = resolve })
this.reader = createInterface({ input: child.stdout })
this.reader.on('line', (line) => this.#onLine(line))
// Without these listeners an 'error' event is thrown, and ends the
// caller's process: measured for a binary that cannot start, and for a
// call written after close().
child.on('error', (e) => {
this.#die(`could not run mobium: ${e.message}`)
// 'exit' may not follow an 'error', and close() waits for this.
this.markExited()
})
child.stdin.on('error', (e) => this.#die(`mobium closed the connection: ${e.message}`))
child.on('exit', (code, signal) => {
this.#die(this.dead ? this.dead : `mobium exited with status ${code ?? signal}`)
this.markExited()
})
}
#die(why) {
if (!this.dead) this.dead = why
for (const { reject, timer } of this.pending.values()) {
clearTimeout(timer)
reject(new MobiumError(this.dead))
}
this.pending.clear()
if (this.child.exitCode === null && this.child.signalCode === null) this.child.kill()
}
#settle(id, fn) {
const entry = this.pending.get(id)
if (!entry) return
this.pending.delete(id)
clearTimeout(entry.timer)
fn(entry)
}
#onLine(line) {
// Nothing here may throw: this runs in an event listener, where an
// exception is uncaught and ends the process. Measured: a line reading
// `null` did, at `message.id`.
if (!line.trim()) return
let message
try {
message = JSON.parse(line)
} catch {
return // not a message we can read
}
if (message === null || typeof message !== 'object' || Array.isArray(message)) return
const error = message.error && typeof message.error === 'object' ? message.error : null
if (message.id === undefined || message.id === null) {
if (!error) return // a notification
// An error with no id is mobium saying it could not read a request at
// all, which JSON-RPC answers without an id. Skipped as a notification
// is, it left the call waiting forever.
const [first] = this.pending.keys()
if (first === undefined) return
this.#settle(first, ({ reject }) => reject(new InvalidArgumentError(
`mobium could not read the request: ${error.message}${error.data ? `: ${error.data}` : ''}`)))
return
}
this.#settle(message.id, ({ resolve, reject }) => {
if (error) {
// A protocol error: the request itself was refused.
reject(new InvalidArgumentError(error.data ? `${error.message}: ${error.data}` : String(error.message)))
} else {
resolve(message.result)
}
})
}
notify(method) {
if (this.dead) return
this.child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method }) + '\n')
}
request(method, params) {
if (this.dead) return Promise.reject(new MobiumError(`this mobium connection is no longer usable: ${this.dead}`))
const id = ++this.nextId
const payload = { jsonrpc: '2.0', id, method }
if (params !== undefined) payload.params = params
let line
try {
line = wire(payload) + '\n'
} catch (e) {
return Promise.reject(e)
}
return new Promise((resolve, reject) => {
let timer
if (this.timeoutMs) {
timer = setTimeout(() => {
this.#die(`${method} got no answer within ${this.timeoutMs / 1000}s, so the connection was closed: ` +
'a reply arriving later would be read as the answer to the next call. ' +
'Connect again, with a longer callTimeoutMs if the device is slow')
}, this.timeoutMs)
}
this.pending.set(id, { resolve, reject, timer })
this.child.stdin.write(line)
})
}
async callTool(name, args) {
const result = await this.request('tools/call', { name, arguments: args || {} })
if (result === null || typeof result !== 'object') {
throw new MobiumError(`mobium answered ${name} with ${result}, not a result`)
}
// A failing tool answers with isError rather than a protocol error, so
// the reason has to be lifted out deliberately.
if (result.isError) throw errorFrom(textOf(result), result.structuredContent)
return result
}
/** Ends mobium at once, for a connection that never became usable. */
kill() {
if (!this.dead) this.dead = 'it could not be set up'
this.child.kill()
}
/**
* Asks mobium to exit and resolves once it has, killing it after ten
* seconds. Safe to call more than once; a call still waiting is rejected,
* saying the connection was closed.
*/
close() {
if (!this.dead) {
this.dead = 'it was closed'
// mobium ends the sessions a client started when the client goes
// away, and a crash closes stdin just as this does — so say first
// that this is a deliberate close, or it would quit.
this.child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'mobium/detach' }) + '\n')
this.child.stdin.end()
const force = setTimeout(() => this.child.kill(), 10000)
force.unref()
this.exited.then(() => clearTimeout(force))
}
return this.exited
}
}
/** A connected device or simulator. */
export class Device {
constructor(conn) {
this.conn = conn
/** What `start()` opened — device, platform, driver — or null after `connect()`. */
this.session = null
}
async #text(tool, args) {
return textOf(await this.conn.callTool(tool, args))
}
/**
* A tool's structured answer. Tools return data alongside their prose, so
* nothing here parses the human-readable rendering.
*/
async #data(tool, args) {
return dataOf(await this.conn.callTool(tool, args))
}
/**
* Start an Android emulator by its AVD's name, or an iOS simulator by its
* name or UDID, and resolve once it has booted: { device, name, platform,
* already }. An emulator cold-boots headless unless `window`.
*/
async boot(name, { window = false } = {}) {
const args = { name }
if (window) args.window = true
return (await this.#data('app_boot', args)) || {}
}
/**
* Shut down an emulator or a simulator — by serial, AVD name, UDID or
* simulator name — after ending the daemon's session on it, and resolve
* once it is gone. A real phone is refused.
*/
async shutdown(name) {
return (await this.#data('app_shutdown', { name })) || {}
}
/** Every attached device and simulator. */
async devices() {
const data = (await this.#data('app_devices')) || {}
return (data.devices || []).map((d) => ({
id: d.id || '',
platform: d.platform || '',
state: d.state || '',
model: d.model || '',
runtime: d.runtime || '',
emulator: !!d.emulator,
}))
}
/**
* Actionable elements on the current screen. Refs are only valid for this
* screen; call map() again after anything that changes it.
*/
async map() {
return toElements(await this.#data('app_map'))
}
/**
* What changed since the last map of this device: the elements added,
* removed and changed, each shaped as map() returns them. It maps the
* screen as map() does, so it also replaces the refs. Refs in `added` and
* in each change's `after` are the new map's; those in `removed` and in
* `before` are stale. `first` is true when there was no earlier map to
* compare with, and then the whole screen is in `added`. A change's `what` names the fields that differ:
* "label", "checked", "selected", "focused", "disabled", "value", "moved" or "resized".
*/
async mapDiff() {
const diff = ((await this.#data('app_map', { diff: true })) || {}).diff || {}
const list = (xs) => (xs || []).map(toElement)
return {
first: diff.first === true,
since: diff.since || '',
added: list(diff.added),
removed: list(diff.removed),
changed: (diff.changed || []).map((c) => ({
before: toElement(c.before),
after: toElement(c.after),
what: c.what || [],
})),
}
}
/** All readable text, or the text of one element. */
text(target) {
return this.#text('app_text', target ? { target } : {})
}
/**
* Declare how to answer a dialog, so an action that meets it carries on:
* when a dialog whose text contains `when` is in the way, press the button
* captioned `press`. It names a button, not accept or dismiss, because
* which button those press differs by platform and by dialog. Captions
* match ignoring case.
*/
async addDialogRule(when, press) {
await this.#text('app_dialogs', { when, press })
}
/** The declared rules, each with how often it has answered. */
async dialogRules() {
const data = (await this.#data('app_dialogs')) || {}
return data.rules || []
}
/** Remove every rule for this device. */
async clearDialogRules() {
await this.#text('app_dialogs', { clear: true })
}
/**
* The raw hierarchy — the page source — for when map
* leaves out the thing you need to see; map is what to act on. `source` is
* the platform's XML, or in a WebView the page's markup; `format` is "xml"
* or "html"; `units` is "px" on Android and "pt" on iOS, where map, taps and
* screenshots are in pixels, `scale` times as many. `redacted` counts the
* password fields hidden.
*/
async source() {
return (await this.#data('app_source')) || {}
}
/** Elements matching a locator, without acting on them. */
async find(locator) {
return toElements(await this.#data('app_find', { locator }))
}
/**
* Block until the screen agrees, instead of sleeping.
*
* condition is 'visible' (default), 'hidden', 'text' — which needs the
* text to wait for — 'value', a field's whole content ('' for empty; a
* password field is refused), 'enabled', 'disabled', 'checked',
* 'unchecked', 'selected', 'unselected', 'focused' or 'count' (with
* count). not waits for the
* opposite; exact makes 'text' match the whole text. Throws MobiumError if
* it never happens, saying what was on screen instead.
*
* On success the screen is remapped, so the element returned already has a
* ref that can be tapped without calling map() first. Its ref is empty when
* the map filters it out, as a plain text in a list. Nothing is returned
* when waiting for something to go away.
*/
async waitFor(target, { condition = 'visible', text, timeoutMs = 10000, not, exact, count } = {}) {
const args = { target, condition, timeout_ms: timeoutMs }
if (text !== undefined) args.text = text
if (not) args.not = true
if (exact) args.exact = true
if (count !== undefined) args.count = count
const data = await this.#data('app_wait_for', args)
return data && data.element ? toElement(data.element) : null
}
/**
* Scroll until an element is on screen, and return it with a ref.
*
* map() only sees what is currently visible, and tap(), type() and
* longPress() already scroll to a target that is not — so call this to look
* without acting, or to scroll back up. `direction` is 'down', 'up', 'left'
* or 'right' — nothing on screen says which way a container scrolls, so a
* horizontal pager needs 'left' or 'right'. Swiping the wrong way is not a
* no-op, so if a swipe navigates instead of scrolling, it stops after one.
* Throws MobiumError if it is not found.
*/
async scrollTo(target, { direction = 'down' } = {}) {
const data = await this.#data('app_scroll_to', { target, direction })
return data && data.element ? toElement(data.element) : null
}
/**
* Tap a ref, a locator, or a point in device pixels.
*
* `{ fingers }` taps with several at once, side by side: 2 for a two-finger
* tap, 3 for three (up to 5). On iOS three fingers can reach the system
* instead of the app — three-finger gestures are undo, redo, copy and paste
* there.
*/
async tap(target, { fingers } = {}) {
const extra = fingers === undefined ? {} : { fingers }
if (typeof target === 'string') {
return void (await this.#text('app_tap', { target, ...extra }))
}
if (target && typeof target === 'object') {
const { x, y } = target
return void (await this.#text('app_tap', { x, y, ...extra }))
}
throw new MobiumError('tap needs a target, or {x, y}')
}
/**
* Tap twice, as one gesture rather than as two taps.
*
* The same tool as tap with one argument set, so the target is resolved the
* same way and refused the same way when the screen has moved. The
* uiautomator dump driver refuses it: the window is 40-300ms and nothing
* there controls the interval between two adb calls.
*/
async doubleTap(target) {
if (typeof target === 'string') {
return void (await this.#text('app_tap', { target, double: true }))
}
if (target && typeof target === 'object') {
const { x, y } = target
return void (await this.#text('app_tap', { x, y, double: true }))
}
throw new MobiumError('doubleTap needs a target, or {x, y}')
}
/**
* Pick one element up, carry it onto another, and drop it.
*
* Not swipe with two targets: a swipe has no hold at either end, so pointed
* at a reorderable row it scrolls the list instead of moving the row. Both
* ends are resolved from one snapshot before anything is touched.
*
* `holdMs` is how long the finger rests at each end, defaulting to 700 —
* above Android's 500ms long-press timeout, which is what a drag-to-reorder
* list arms on. Raise it first when a drag picks nothing up.
*
* Reports that the gesture was delivered. Whether the drop was accepted is
* the app's own state, so call map() again to see it.
*/
async drag(from, to, { holdMs } = {}) {
const args = { from, to }
if (holdMs !== undefined) args.hold_ms = holdMs
return (await this.#data('app_drag', args)) || {}
}
/**
* Hold one element with a finger while a second finger taps another.
*
* The first finger lifts only after the second. Both are resolved before
* anything is touched. `leadMs` is how long the first rests before the
* second taps, 300 by default — under Android's 500ms long-press timeout.
* Reports that the gesture was delivered; call map() again to see what it
* did. Android 15 and earlier only: on iOS XCTest adds a zero-length touch
* at the second finger's target when the gesture starts, and on Android 16
* and later UiAutomator2's down times are rejected, so both refuse with
* UnsupportedError.
*/
async pressTap(hold, tap, { leadMs } = {}) {
const args = { hold, tap }
if (leadMs !== undefined) args.lead_ms = leadMs
return (await this.#data('app_press_tap', args)) || {}
}
/**
* Hold one element with a finger while a second finger drags from one
* element to another. Not drag(), which is one finger carrying something.
* Android 15 and earlier only, for pressTap's reasons.
*/
async pressDrag(hold, from, to, { leadMs } = {}) {
const args = { hold, from, to }
if (leadMs !== undefined) args.lead_ms = leadMs
return (await this.#data('app_press_drag', args)) || {}
}
/** Type into an element, after what it holds. An empty string clears it. */
async type(target, text) {
await this.#text('app_type', { target, text })
}
/** Clear an element and type into it, replacing what it held. */
async fill(target, text) {
await this.#text('app_fill', { target, text })
}
/**
* Swipe by direction ('up' | 'down' | 'left' | 'right') or exact points.
* With `target` and a direction, swipe across that element, after the
* checks a tap makes — part of the way, which reveals a list row's swipe
* actions without performing the first. Map again and tap the one you mean.
*/
async swipe(direction, { durationMs = 300, from, to, target } = {}) {
const args = { duration_ms: durationMs }
if (target && !(from && to)) args.target = target
if (from && to) {
args.x1 = from.x
args.y1 = from.y
args.x2 = to.x
args.y2 = to.y
} else if (direction) {
args.direction = direction
} else {
throw new MobiumError('swipe needs a direction or from/to points')
}
await this.#text('app_swipe', args)
}
/** Press and hold an element or a point. */
async longPress(target, { durationMs = 800 } = {}) {
const args = { duration_ms: durationMs }
if (typeof target === 'string') args.target = target
else if (target) Object.assign(args, { x: target.x, y: target.y })
else throw new MobiumError('longPress needs a target, or {x, y}')
await this.#text('app_long_press', args)
}
/** Capture the screen as PNG, optionally also writing it to a path. */
async screenshot(path) {
if (path) {
await this.#text('app_screenshot', { path })
return readFileSync(path)
}
const result = await this.conn.callTool('app_screenshot', {})
for (const block of result.content || []) {
if (block.type === 'image') return Buffer.from(block.data, 'base64')
}
throw new MobiumError('mobium returned no image')
}
/**
* Bring an app to the foreground by package name or bundle id.
*
* Every ref from the previous screen is discarded — call map(), or just
* act, since actions re-resolve their target anyway.
*
* `hitTest`, on an iOS simulator, loads the hit probe into the app as it
* launches: every action on an element in it then asks UIKit where the
* touch goes first, and is refused when it would land elsewhere. A real
* iPhone and Android refuse it.
*
* `grayBox` launches the app with Mobium's gray-box library
* turned on: the app says when it is busy, and every action waits for it
* to be idle before finding its target. It needs an app built with the
* library.
*/
async launch(app, { hitTest = false, grayBox = false } = {}) {
const args = { app }
if (hitTest) args.hit_test = true
if (grayBox) args.gray_box = true
await this.#text('app_launch', args)
}
/** Stop a running app. */
async terminate(app) {
await this.#text('app_terminate', { app })
}
/**
* Install a local .apk (Android) or .app bundle (iOS).
* Resolves to the absolute path that was installed.
*/
async install(path) {
const data = (await this.#data('app_install', { path })) || {}
return data.path || ''
}
/**
* Installed apps, each with id, name, version and whether it is a system
* app. By default only apps someone installed — a stock Android emulator
* ships about 240 system packages. Name is empty on Android.
*/
async apps({ system = false } = {}) {
const data = (await this.#data('app_list_apps', { system })) || {}
return data.apps || []
}
/**
* Remove an app, verified by listing afterwards. `adb uninstall` reports
* success when it has only removed the updates to a system app, so this
* throws rather than reporting a lie.
*/
async uninstall(app) {
await this.#text('app_uninstall', { app })
}
/**
* Delete an app's data and leave it installed — a fresh install's state,
* without reinstalling. Resolves to what was read back empty (`emptied`),
* what was kept (`kept`) and, on Android, the runtime permissions still
* granted (`still_granted`): `pm clear` revokes what the user granted. An
* iOS simulator keeps its privacy grants and keychain.
*
* A real iPhone cannot clear in place: pass the app's own `bundle`, a .app
* or .ipa, and it is uninstalled and installed again. Its data container
* is read back empty, and its permissions, which nothing outside the app
* can read, are listed in `not_read_back`. Without a bundle a phone
* refuses, and with one any other device does.
*/
async clearData(app, bundle) {
const args = { app }
if (bundle) args.path = bundle
return (await this.#data('app_clear_data', args)) || {}
}
/**
* Put a file from this machine where the device keeps downloads, so an
* app's file picker finds it. On Android that is the shared Download
* folder, one for every app, so `app` is ignored; the file is indexed in
* MediaStore, which is what the picker reads, and read back there. On an
* iOS simulator it is an app's own Documents folder — the app in front
* unless `app` names one — which the Files app shows under On My iPhone.
* On a real iPhone it is the same folder, confirmed by reading its bytes
* back. `name` is the name to give it on the
* device, a name rather than a path, and defaults to the file's own.
*
* Resolves to the transfer: `device`, `app` (iOS), `name`, `where`,
* `bytes`, `checked` (how it was confirmed at both ends) and `path`.
*/
async upload(path, { name, app } = {}) {
const args = { path }
if (name) args.name = name
if (app) args.app = app
return (await this.#data('app_upload', args)) || {}
}
/**
* Bring back a file from where the device keeps downloads — Android's
* shared Download folder, or an iOS simulator app's Documents, the app in
* front unless `app` names one — to check what an app saved. A real iPhone
* is not built yet. The copy's size is read back against the device's.
*
* With `path`, saves it there and resolves to the transfer (`device`,
* `app`, `name`, `where`, `bytes`, `checked`, `path`). Without one, resolves
* to the file's bytes. downloads() lists what there is to fetch.
*/
async download(name, { path, app } = {}) {
if (!name) throw new MobiumError('download needs the name of a file — downloads() lists them')
const args = { name }
if (path) args.path = path
if (app) args.app = app
const data = (await this.#data('app_download', args)) || {}
if (path) return data
if (typeof data.data !== 'string') throw new MobiumError(`mobium returned no contents for ${name}`)
return Buffer.from(data.data, 'base64')
}
/**
* Send a local file or folder to a path on the device, and read every
* file's size back there. On Android `devicePath` is absolute
* (`/sdcard/...`, `/data/local/tmp/...`), or with `app` a path in that
* app's private data, which needs a debuggable build. On iOS it is a path in
* an app's data container — `app`, or the one in front. Resolves to the
* transfer, with `files` and `folder`.
*/
async pushPath(local, devicePath, { app } = {}) {
const args = { path: local, device_path: devicePath }
if (app) args.app = app
return (await this.#data('app_upload', args)) || {}
}
/**
* Bring back the file or folder at a path on the device — the paths
* pushPath() takes. With `path`, saves it there (a folder needs a path that
* does not exist yet) and resolves to the transfer; without one, resolves
* to a file's bytes.
*/
async pullPath(devicePath, { path, app } = {}) {
const args = { device_path: devicePath }
if (path) args.path = path
if (app) args.app = app
const data = (await this.#data('app_download', args)) || {}
if (path) return data
if (typeof data.data !== 'string' && data.bytes) throw new MobiumError(`mobium returned no contents for ${devicePath}`)
return Buffer.from(data.data || '', 'base64')
}
/**
* What the downloads folder holds, each file with `name`, `bytes` and
* `modified`: Android's shared Download folder, or an iOS simulator app's
* Documents, the app in front unless `app` names one — on a real iPhone
* too.
*/
async downloads({ app } = {}) {
const data = (await this.#data('app_download', app ? { app } : {})) || {}
return data.files || []
}
/**
* Runs several tools in order, on this device, in one call. Each step is
* `{ name, arguments }` — a tool and the arguments it takes on its own:
*
* await device.batch([
* { name: 'app_tap', arguments: { target: 'text=Sign in' } },
* { name: 'app_fill', arguments: { target: 'testid=user', text: 'mobium' } },
* { name: 'app_wait_for', arguments: { target: 'text=Welcome' } },
* ])
*
* Every step is checked before the first runs, and the batch stops at the
* first failure, throwing that step's own error; its `details` hold `step`
* and what `completed` before it. Resolves to each step's `name`, `text`
* and `data`, in order.
*/
async batch(steps) {
const data = (await this.#data('app_batch', { steps })) || {}
return data.steps || []
}
/**
* The network: `airplane`, `online`, and the shaping — `latency_ms`,
* `download_kbps`, `upload_kbps`, zero for none. Android only.
*/
async network() {
return (await this.#data('app_network', {})) || {}
}
/**
* Turns airplane mode on (or off) and waits for the network to go (or come
* back) — on an emulator or a real Android phone.
*/
async setOffline(offline = true) {
return (await this.#data('app_network', { offline })) || {}
}
/**
* Adds latency to each round trip and limits download and upload, in
* kbit/s, replacing any shaping set before; zero is none. Needs root, so
* an emulator.
*/