-
Notifications
You must be signed in to change notification settings - Fork 395
Expand file tree
/
Copy pathios.ts
More file actions
332 lines (272 loc) · 9.29 KB
/
ios.ts
File metadata and controls
332 lines (272 loc) · 9.29 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
import { Socket } from "node:net";
import { execFileSync } from "node:child_process";
import { WebDriverAgent } from "./webdriver-agent";
import { ActionableError, Button, InstalledApp, Robot, ScreenSize, SwipeDirection, ScreenElement, Orientation } from "./robot";
const WDA_PORT = 8100;
const IOS_TUNNEL_PORT = 60105;
interface ListCommandOutput {
deviceList: string[];
}
interface VersionCommandOutput {
version: string;
}
interface InfoCommandOutput {
DeviceClass: string;
DeviceName: string;
ProductName: string;
ProductType: string;
ProductVersion: string;
PhoneNumber: string;
TimeZone: string;
}
export interface IosDevice {
deviceId: string;
deviceName: string;
}
const getGoIosPath = (): string => {
if (process.env.GO_IOS_PATH) {
return process.env.GO_IOS_PATH;
}
// fallback to go-ios in PATH via `npm install -g go-ios`
return "ios";
};
export class IosRobot implements Robot {
public constructor(private deviceId: string) {
}
private isListeningOnPort(port: number): Promise<boolean> {
return new Promise((resolve, reject) => {
const client = new Socket();
client.connect(port, "localhost", () => {
client.destroy();
resolve(true);
});
client.on("error", (err: any) => {
resolve(false);
});
});
}
private async isTunnelRunning(): Promise<boolean> {
return await this.isListeningOnPort(IOS_TUNNEL_PORT);
}
private async isWdaForwardRunning(): Promise<boolean> {
return await this.isListeningOnPort(WDA_PORT);
}
private async assertTunnelRunning(): Promise<void> {
if (await this.isTunnelRequired()) {
if (!(await this.isTunnelRunning())) {
throw new ActionableError("iOS tunnel is not running, please see https://github.com/mobile-next/mobile-mcp/wiki/");
}
}
}
private async wda(): Promise<WebDriverAgent> {
await this.assertTunnelRunning();
if (!(await this.isWdaForwardRunning())) {
throw new ActionableError("Port forwarding to WebDriverAgent is not running (tunnel okay), please see https://github.com/mobile-next/mobile-mcp/wiki/");
}
const wda = new WebDriverAgent("localhost", WDA_PORT);
if (!(await wda.isRunning())) {
throw new ActionableError("WebDriverAgent is not running on device (tunnel okay, port forwarding okay), please see https://github.com/mobile-next/mobile-mcp/wiki/");
}
return wda;
}
private async ios(...args: string[]): Promise<string> {
return execFileSync(getGoIosPath(), ["--udid", this.deviceId, ...args], {}).toString();
}
public async getIosVersion(): Promise<string> {
const output = await this.ios("info");
const json = JSON.parse(output);
return json.ProductVersion;
}
private async isTunnelRequired(): Promise<boolean> {
const version = await this.getIosVersion();
const args = version.split(".");
return parseInt(args[0], 10) >= 17;
}
public async getScreenSize(): Promise<ScreenSize> {
const wda = await this.wda();
return await wda.getScreenSize();
}
public async swipe(direction: SwipeDirection): Promise<void> {
const wda = await this.wda();
await wda.swipe(direction);
}
public async swipeFromCoordinate(x: number, y: number, direction: SwipeDirection, distance?: number): Promise<void> {
const wda = await this.wda();
await wda.swipeFromCoordinate(x, y, direction, distance);
}
public async listApps(): Promise<InstalledApp[]> {
await this.assertTunnelRunning();
const output = await this.ios("apps", "--all", "--list");
return output
.split("\n")
.map(line => {
const [packageName, appName] = line.split(" ");
return {
packageName,
appName,
};
});
}
public async launchApp(packageName: string): Promise<void> {
await this.assertTunnelRunning();
await this.ios("launch", packageName);
}
public async terminateApp(packageName: string): Promise<void> {
await this.assertTunnelRunning();
await this.ios("kill", packageName);
}
public async installApp(path: string): Promise<void> {
await this.assertTunnelRunning();
try {
await this.ios("install", "--path", path);
} catch (error: any) {
const stdout = error.stdout ? error.stdout.toString() : "";
const stderr = error.stderr ? error.stderr.toString() : "";
const output = (stdout + stderr).trim();
throw new ActionableError(output || error.message);
}
}
public async uninstallApp(bundleId: string): Promise<void> {
await this.assertTunnelRunning();
try {
await this.ios("uninstall", "--bundleid", bundleId);
} catch (error: any) {
const stdout = error.stdout ? error.stdout.toString() : "";
const stderr = error.stderr ? error.stderr.toString() : "";
const output = (stdout + stderr).trim();
throw new ActionableError(output || error.message);
}
}
public async openUrl(url: string): Promise<void> {
const wda = await this.wda();
await wda.openUrl(url);
}
public async sendKeys(text: string): Promise<void> {
const wda = await this.wda();
await wda.sendKeys(text);
}
public async pressButton(button: Button): Promise<void> {
const wda = await this.wda();
await wda.pressButton(button);
}
public async tap(x: number, y: number): Promise<void> {
const wda = await this.wda();
await wda.tap(x, y);
}
public async doubleTap(x: number, y: number): Promise<void> {
const wda = await this.wda();
await wda.doubleTap(x, y);
}
public async longPress(x: number, y: number, duration: number): Promise<void> {
const wda = await this.wda();
await wda.longPress(x, y, duration);
}
public async getElementsOnScreen(): Promise<ScreenElement[]> {
const wda = await this.wda();
return await wda.getElementsOnScreen();
}
public async getScreenshot(): Promise<Buffer> {
const wda = await this.wda();
return await wda.getScreenshot();
/* alternative:
await this.assertTunnelRunning();
const tmpFilename = path.join(tmpdir(), `screenshot-${randomBytes(8).toString("hex")}.png`);
await this.ios("screenshot", "--output", tmpFilename);
const buffer = readFileSync(tmpFilename);
unlinkSync(tmpFilename);
return buffer;
*/
}
public async setOrientation(orientation: Orientation): Promise<void> {
const wda = await this.wda();
await wda.setOrientation(orientation);
}
public async getOrientation(): Promise<Orientation> {
const wda = await this.wda();
return await wda.getOrientation();
}
public async getCurrentActivity(): Promise<{ id: string }> {
try {
const wda = await this.wda();
const source = await wda.getPageSource();
// The top-level element in the source tree represents the current app
// Try to extract bundle ID from the type attribute which usually contains it
const rootElement = source.value;
// Bundle ID is typically in the type field or name field
// Example: "XCUIElementTypeApplication" for the app under test
// The rawIdentifier often contains the bundle ID
if (rootElement.rawIdentifier) {
return { id: rootElement.rawIdentifier };
}
// Fallback: try to extract from type if it contains bundle info
if (rootElement.type) {
// Sometimes the type is formatted as "bundleId.ClassName"
const match = rootElement.type.match(/^([a-zA-Z0-9][a-zA-Z0-9.]*[a-zA-Z0-9])\.?/);
if (match) {
return { id: match[1] };
}
}
// Last fallback: try name
if (rootElement.name) {
return { id: rootElement.name };
}
throw new ActionableError("No app is in foreground. Please launch an app and try again.");
} catch (error) {
if (error instanceof ActionableError) {
throw error;
}
throw new ActionableError("Failed to get current app. Please ensure the device is properly connected and WebDriver Agent is running.");
}
}
}
export class IosManager {
public isGoIosInstalled(): boolean {
try {
const output = execFileSync(getGoIosPath(), ["version"], { stdio: ["pipe", "pipe", "ignore"] }).toString();
const json: VersionCommandOutput = JSON.parse(output);
return json.version !== undefined && (json.version.startsWith("v") || json.version === "local-build");
} catch (error) {
return false;
}
}
public getDeviceName(deviceId: string): string {
const output = execFileSync(getGoIosPath(), ["info", "--udid", deviceId]).toString();
const json: InfoCommandOutput = JSON.parse(output);
return json.DeviceName;
}
public getDeviceInfo(deviceId: string): InfoCommandOutput {
const output = execFileSync(getGoIosPath(), ["info", "--udid", deviceId]).toString();
const json: InfoCommandOutput = JSON.parse(output);
return json;
}
public listDevices(): IosDevice[] {
if (!this.isGoIosInstalled()) {
console.error("go-ios is not installed, no physical iOS devices can be detected");
return [];
}
const output = execFileSync(getGoIosPath(), ["list"]).toString();
const json: ListCommandOutput = JSON.parse(output);
const devices = json.deviceList.map(device => ({
deviceId: device,
deviceName: this.getDeviceName(device),
}));
return devices;
}
public listDevicesWithDetails(): Array<IosDevice & { version: string }> {
if (!this.isGoIosInstalled()) {
console.error("go-ios is not installed, no physical iOS devices can be detected");
return [];
}
const output = execFileSync(getGoIosPath(), ["list"]).toString();
const json: ListCommandOutput = JSON.parse(output);
const devices = json.deviceList.map(device => {
const info = this.getDeviceInfo(device);
return {
deviceId: device,
deviceName: info.DeviceName,
version: info.ProductVersion,
};
});
return devices;
}
}