Repository navigation
Expand file tree
/
Copy pathios.ts
More file actions
434 lines (388 loc) · 13.7 KB
/
Copy pathios.ts
File metadata and controls
434 lines (388 loc) · 13.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
import { isDeepLinkTarget } from '@agent-device/contracts/command';
import type {
DeviceLease,
DeviceRotation,
ProviderDeviceInstallOptions,
ProviderDeviceInstallResult,
} from '@agent-device/contracts/device';
import type {
Interactor,
SnapshotOptions,
SnapshotResult,
} from '@agent-device/contracts/interactor-types';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as sleep } from 'node:timers/promises';
import type { DoublespeedApiClient } from './api-client.ts';
import type { DoublespeedRuntimeDependencies } from './runtime-dependencies.ts';
import {
createDoublespeedSessionClient,
type DoublespeedInstalledApp,
type DoublespeedSessionClient,
type DoublespeedSessionScreen,
} from './session-client.ts';
import { flattenDoublespeedTree, toDoublespeedSelector, writeBase64File } from './snapshot.ts';
import { normalizeOptionalString } from './strings.ts';
export type DoublespeedIosSession = {
lease: DeviceLease;
simulatorId: string;
device: DeviceInfo;
client: DoublespeedSessionClient;
screen: DoublespeedSessionScreen;
readonly dependencies: Pick<DoublespeedRuntimeDependencies, 'host' | 'ios'>;
};
export type DoublespeedIosRemoteInstallOptions = {
sha256?: string;
relaunch?: boolean;
appIdentifierHint?: string;
};
export type DoublespeedIosRemoteInstallResult = {
appId?: string;
};
export function createDoublespeedIosSession(
options: {
lease: DeviceLease;
simulatorId: string;
device: DeviceInfo;
apiUrl: string;
screen: DoublespeedSessionScreen;
fetch?: typeof fetch;
},
dependencies: Pick<DoublespeedRuntimeDependencies, 'host' | 'ios'>,
): DoublespeedIosSession {
return {
lease: options.lease,
simulatorId: options.simulatorId,
device: options.device,
client: createDoublespeedSessionClient(options.apiUrl, { fetch: options.fetch }),
screen: options.screen,
dependencies,
};
}
export async function installDoublespeedIosApp(
api: DoublespeedApiClient,
session: DoublespeedIosSession,
installablePath: string,
options?: ProviderDeviceInstallOptions,
signal?: AbortSignal,
): Promise<ProviderDeviceInstallResult> {
signal?.throwIfAborted();
const prepared = await prepareIosAsset(installablePath, session.dependencies);
try {
signal?.throwIfAborted();
const digest = await fileDigest(prepared.uploadPath);
const downloadUrl = await publishAsset(api, prepared, digest, signal);
const result = await installDoublespeedIosRemoteApp(
session,
downloadUrl,
{
sha256: digest.sha256,
relaunch: options?.relaunch,
appIdentifierHint: options?.appIdentifierHint,
},
signal,
);
const bundleId = result.appId;
return {
...(bundleId ? { bundleId, launchTarget: bundleId } : {}),
...(prepared.appName ? { appName: prepared.appName } : {}),
};
} finally {
await prepared.cleanup();
}
}
async function publishAsset(
api: DoublespeedApiClient,
prepared: { uploadPath: string; assetName: string },
digest: { sha256: string; size: number },
signal?: AbortSignal,
): Promise<string> {
let asset = await api.registerAsset({ ...digest, name: prepared.assetName }, signal);
if (!asset.exists) {
if (!asset.upload_url) {
throw new AppError(
'COMMAND_FAILED',
'Doublespeed asset registration returned no upload URL.',
);
}
await api.uploadAsset(asset.upload_url, prepared.uploadPath, signal);
asset = await api.completeAsset(digest.sha256, digest.size, signal);
}
if (!asset.download_url) {
throw new AppError(
'COMMAND_FAILED',
'Doublespeed asset registration returned no download URL.',
);
}
return asset.download_url;
}
export async function installDoublespeedIosRemoteApp(
session: DoublespeedIosSession,
url: string,
options?: DoublespeedIosRemoteInstallOptions,
signal?: AbortSignal,
): Promise<DoublespeedIosRemoteInstallResult> {
signal?.throwIfAborted();
const beforeInstallApps = await session.client.listApps(signal).catch((error: unknown) => {
if (signal?.aborted) throw error;
return undefined;
});
const result = await session.client.installApp(
{
url,
sha256: options?.sha256,
launchMode: options?.relaunch ? 'RelaunchIfRunning' : 'ForegroundIfRunning',
},
signal,
);
const resultBundleId = normalizeOptionalString(result.bundleId);
const requestedBundleId = normalizeOptionalString(options?.appIdentifierHint);
let afterInstallApps: DoublespeedInstalledApp[] = [];
for (const delayMs of IOS_APP_INVENTORY_RETRY_DELAYS_MS) {
if (delayMs > 0) await sleep(delayMs, undefined, { signal });
afterInstallApps = await session.client.listApps(signal);
const verifiedBundleId = resolveInstalledIosAppId({
resultBundleId,
requestedBundleId,
beforeInstallApps,
afterInstallApps,
});
if (verifiedBundleId) return { appId: verifiedBundleId };
}
throw new AppError('COMMAND_FAILED', 'Doublespeed iOS app installation could not be verified.', {
resultBundleId,
requestedBundleId,
installedUserApps: afterInstallApps
.filter(isUserInstalledIosApp)
.map((app) => app.bundleId)
.sort(),
});
}
export function createDoublespeedIosInteractor(session: DoublespeedIosSession): Interactor {
return new DoublespeedIosInteractor(session);
}
class DoublespeedIosInteractor implements Interactor {
private readonly session: DoublespeedIosSession;
constructor(session: DoublespeedIosSession) {
this.session = session;
}
async open(app: string, options?: { url?: string }): Promise<void> {
if (options?.url) {
await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(app));
await this.session.client.openUrl(options.url);
return;
}
if (isDeepLinkTarget(app)) {
await this.session.client.openUrl(app);
return;
}
await this.session.client.launchApp(await this.session.dependencies.ios.resolveAppAlias(app));
}
async openDevice(): Promise<void> {}
async close(app: string): Promise<void> {
if (app) {
await this.session.client
.terminateApp(await this.session.dependencies.ios.resolveAppAlias(app))
.catch(() => {});
}
}
async tap(x: number, y: number): Promise<void> {
await this.session.client.tap(x, y);
}
async tapElementSelector(selector: {
key: 'id' | 'label' | 'text' | 'value';
value: string;
}): Promise<Record<string, unknown> | void> {
await this.session.client.tapElement(toDoublespeedSelector(selector));
}
async doubleTap(x: number, y: number): Promise<void> {
await this.tap(x, y);
await this.tap(x, y);
}
async longPress(x: number, y: number, durationMs?: number): Promise<void> {
await this.session.client.longPress(x, y, durationMs);
}
async focus(x: number, y: number): Promise<void> {
await this.tap(x, y);
}
async type(text: string, delayMs?: number): Promise<void> {
if (delayMs && delayMs > 0) {
for (const char of Array.from(text)) {
await this.session.client.typeText(char);
await sleep(delayMs);
}
return;
}
await this.session.client.typeText(text);
}
async fill(x: number, y: number, text: string): Promise<void> {
await this.tap(x, y);
await this.session.client.typeText(text);
}
async scroll(direction: 'up' | 'down' | 'left' | 'right', options?: { pixels?: number }) {
await this.session.client.scroll(direction, options?.pixels ?? 300);
}
async screenshot(outPath: string): Promise<void> {
const screenshot = await this.session.client.screenshot();
await writeBase64File(outPath, screenshot.base64);
}
async snapshot(_options?: SnapshotOptions): Promise<SnapshotResult> {
const tree = await this.session.client.elementTree();
return {
nodes: flattenDoublespeedTree(tree),
backend: 'xctest',
producer: 'doublespeed-ios-tree',
};
}
async back(): Promise<never> {
throw unsupported('back', DOUBLESPEED_IOS_BACK_UNSUPPORTED);
}
async home(): Promise<void> {
await this.session.client.pressKey('home');
}
async setOrientation(orientation: DeviceRotation): Promise<void> {
if (orientation === 'portrait-upside-down') {
throw unsupported(
'orientation',
'Doublespeed iOS sessions support portrait and landscape orientation, not portrait upside-down.',
);
}
await this.session.client.setOrientation(orientation === 'portrait' ? 'portrait' : 'landscape');
}
async performGesture(): Promise<never> {
throw unsupported('gesture', DOUBLESPEED_IOS_GESTURE_UNSUPPORTED);
}
async appSwitcher(): Promise<never> {
throw unsupported('app-switcher', 'Doublespeed iOS sessions do not expose app switcher yet.');
}
async tvRemote(): Promise<never> {
throw unsupported('tv-remote', 'Doublespeed iOS sessions do not expose tv remote control.');
}
async readAlert(): Promise<never> {
throw unsupported('alert', DOUBLESPEED_IOS_ALERT_UNSUPPORTED);
}
async awaitAlert(): Promise<never> {
throw unsupported('alert', DOUBLESPEED_IOS_ALERT_UNSUPPORTED);
}
async acceptAlert(): Promise<never> {
throw unsupported('alert', DOUBLESPEED_IOS_ALERT_UNSUPPORTED);
}
async dismissAlert(): Promise<never> {
throw unsupported('alert', DOUBLESPEED_IOS_ALERT_UNSUPPORTED);
}
async readClipboard(): Promise<never> {
throw unsupported('clipboard', 'Doublespeed iOS sessions do not expose clipboard read yet.');
}
async writeClipboard(): Promise<never> {
throw unsupported('clipboard', 'Doublespeed iOS sessions do not expose clipboard write yet.');
}
async setSetting(): Promise<never> {
throw unsupported('settings', 'Doublespeed iOS sessions do not expose settings changes yet.');
}
}
async function prepareIosAsset(
artifactPath: string,
dependencies: Pick<DoublespeedRuntimeDependencies, 'host' | 'ios'>,
): Promise<{
uploadPath: string;
assetName: string;
appName?: string;
cleanup: () => Promise<void>;
}> {
const stat = await fs.promises.stat(artifactPath);
if (!stat.isDirectory()) {
return {
uploadPath: artifactPath,
assetName: path.basename(artifactPath),
appName: inferAppNameFromPath(artifactPath),
cleanup: async () => {},
};
}
const tempDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), 'agent-device-doublespeed-ios-app-'),
);
const zipPath = path.join(tempDir, `${path.basename(artifactPath)}.zip`);
try {
await dependencies.host.archiveDirectory({
sourceDirectory: path.dirname(artifactPath),
entryName: path.basename(artifactPath),
archivePath: zipPath,
});
} catch (error) {
await fs.promises.rm(tempDir, { recursive: true, force: true });
throw error;
}
return {
uploadPath: zipPath,
assetName: path.basename(zipPath),
appName:
(await dependencies.ios.readBundleAppName(artifactPath)) ??
inferAppNameFromPath(artifactPath),
cleanup: async () => {
await fs.promises.rm(tempDir, { recursive: true, force: true });
},
};
}
async function fileDigest(filePath: string): Promise<{ sha256: string; size: number }> {
const hash = createHash('sha256');
let size = 0;
for await (const chunk of fs.createReadStream(filePath)) {
hash.update(chunk as Buffer);
size += (chunk as Buffer).length;
}
return { sha256: hash.digest('hex'), size };
}
function inferAppNameFromPath(appPath: string): string | undefined {
const base = path.basename(appPath).replace(/\.(?:app|ipa|zip)$/i, '');
return base || undefined;
}
const IOS_APP_INVENTORY_RETRY_DELAYS_MS = [0, 250] as const;
function resolveInstalledIosAppId(params: {
resultBundleId?: string;
requestedBundleId?: string;
beforeInstallApps: DoublespeedInstalledApp[] | undefined;
afterInstallApps: DoublespeedInstalledApp[];
}): string | undefined {
const installedBundleIds = new Set(params.afterInstallApps.map((app) => app.bundleId));
return (
(params.resultBundleId && installedBundleIds.has(params.resultBundleId)
? params.resultBundleId
: undefined) ??
(params.requestedBundleId && installedBundleIds.has(params.requestedBundleId)
? params.requestedBundleId
: undefined) ??
inferNewUserInstalledApp(params.beforeInstallApps, params.afterInstallApps)
);
}
function inferNewUserInstalledApp(
beforeInstallApps: DoublespeedInstalledApp[] | undefined,
afterInstallApps: DoublespeedInstalledApp[],
): string | undefined {
if (!beforeInstallApps) return undefined;
const beforeBundleIds = new Set(beforeInstallApps.map((app) => app.bundleId));
const candidates = afterInstallApps.filter(
(app) => isUserInstalledIosApp(app) && !beforeBundleIds.has(app.bundleId),
);
return candidates.length === 1 ? candidates[0]?.bundleId : undefined;
}
export function isUserInstalledIosApp(app: DoublespeedInstalledApp): boolean {
return (
!app.bundleId.startsWith('com.apple.') &&
!app.bundleId.startsWith('com.facebook.WebDriverAgentRunner') &&
!app.installType.toLowerCase().includes('system')
);
}
export const DOUBLESPEED_IOS_BACK_UNSUPPORTED =
'Doublespeed iOS sessions do not expose back navigation yet.';
export const DOUBLESPEED_IOS_GESTURE_UNSUPPORTED =
'Doublespeed iOS sessions do not expose portable gesture execution yet.';
/** One sentence for all four alert legs: the session API exposes no alert inspection. */
export const DOUBLESPEED_IOS_ALERT_UNSUPPORTED =
'Doublespeed iOS sessions do not expose alert inspection yet.';
function unsupported(command: string, message: string): never {
throw new AppError('UNSUPPORTED_OPERATION', message, { command });
}