-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathdispatch.ts
More file actions
522 lines (507 loc) · 17.7 KB
/
dispatch.ts
File metadata and controls
522 lines (507 loc) · 17.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
import { promises as fs } from 'node:fs';
import pathModule from 'node:path';
import { AppError } from '../utils/errors.ts';
import type { DeviceInfo } from '../utils/device.ts';
import {
dismissAndroidKeyboard,
getAndroidKeyboardState,
} from '../platforms/android/device-input-state.ts';
import { pressAndroidEnter } from '../platforms/android/input-actions.ts';
import { pushAndroidNotification } from '../platforms/android/notifications.ts';
import { getInteractor } from './interactors.ts';
import type { Interactor, RunnerContext } from './interactor-types.ts';
import { runIosRunnerCommand } from '../platforms/ios/runner-client.ts';
import { clearIosSimulatorAppState, pushIosNotification } from '../platforms/ios/apps.ts';
import { isDeepLinkTarget } from './open-target.ts';
import { parseTriggerAppEventArgs, resolveAppEventUrl } from './app-events.ts';
import {
LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE,
LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE,
} from './launch-console.ts';
import { emitDiagnostic, withDiagnosticTimer } from '../utils/diagnostics.ts';
import { readLocationCoordinate } from '../utils/location-coordinates.ts';
import { successText, withSuccessText } from '../utils/success-text.ts';
import { screenshotOptionsFromFlags } from '../commands/capture-screenshot-options.ts';
import { isKeyboardAction, type KeyboardAction } from '../utils/keyboard-actions.ts';
import type { DispatchContext } from './dispatch-context.ts';
import {
handleFillCommand,
handleFlingCommand,
handleFocusCommand,
handleLongPressCommand,
handlePanCommand,
handlePinchCommand,
handlePressCommand,
handleReadCommand,
handleRotateGestureCommand,
handleScrollCommand,
handleSwipeCommand,
handleTransformGestureCommand,
handleTypeCommand,
} from './dispatch-interactions.ts';
import { readNotificationPayload } from './dispatch-payload.ts';
import { parseDeviceRotation } from './device-rotation.ts';
export { resolveTargetDevice } from './dispatch-resolve.ts';
export type { CommandFlags, DispatchContext } from './dispatch-context.ts';
export async function dispatchCommand(
device: DeviceInfo,
command: string,
positionals: string[],
outPath?: string,
context?: DispatchContext,
): Promise<Record<string, unknown> | void> {
const runnerCtx: RunnerContext = {
requestId: context?.requestId,
appBundleId: context?.appBundleId,
verbose: context?.verbose,
logPath: context?.logPath,
traceLogPath: context?.traceLogPath,
};
const interactor = getInteractor(device, runnerCtx);
emitDiagnostic({
level: 'debug',
phase: 'platform_command_prepare',
data: {
command,
platform: device.platform,
kind: device.kind,
},
});
return await withDiagnosticTimer(
'platform_command',
async () => {
return await dispatchKnownCommand(
device,
interactor,
command,
positionals,
outPath,
context,
runnerCtx,
);
},
{
command,
platform: device.platform,
},
);
}
// fallow-ignore-next-line complexity
async function dispatchKnownCommand(
device: DeviceInfo,
interactor: Interactor,
command: string,
positionals: string[],
outPath: string | undefined,
context: DispatchContext | undefined,
runnerCtx: RunnerContext,
): Promise<Record<string, unknown> | void> {
switch (command) {
case 'open':
return await handleOpenCommand(device, interactor, positionals, context);
case 'close': {
const app = positionals[0];
if (!app) return { closed: 'session', ...successText('Closed session') };
await interactor.close(app);
return { app, ...successText(`Closed: ${app}`) };
}
case 'press':
return await handlePressCommand(device, interactor, positionals, context);
case 'swipe':
return await handleSwipeCommand(device, interactor, positionals, context);
case 'pan':
return await handlePanCommand(interactor, positionals);
case 'fling':
return await handleFlingCommand(interactor, positionals);
case 'longpress':
return await handleLongPressCommand(interactor, positionals);
case 'focus':
return await handleFocusCommand(interactor, positionals);
case 'type':
return await handleTypeCommand(interactor, positionals, context);
case 'fill':
return await handleFillCommand(interactor, positionals, context);
case 'scroll':
return await handleScrollCommand(interactor, positionals, context);
case 'pinch':
return await handlePinchCommand(device, interactor, positionals, context);
case 'rotate-gesture':
return await handleRotateGestureCommand(device, interactor, positionals);
case 'transform-gesture':
return await handleTransformGestureCommand(device, interactor, positionals);
case 'trigger-app-event':
return await handleTriggerAppEventCommand(device, interactor, positionals, context);
case 'screenshot':
return await handleScreenshotCommand(interactor, positionals, outPath, context);
case 'back':
await interactor.back(context?.backMode);
return { action: 'back', mode: context?.backMode ?? 'in-app', ...successText('Back') };
case 'home':
await interactor.home();
return { action: 'home', ...successText('Home') };
case 'rotate': {
const orientation = parseDeviceRotation(positionals[0]);
await interactor.rotate(orientation);
return { action: 'rotate', orientation, ...successText(`Rotated to ${orientation}`) };
}
case 'app-switcher':
await interactor.appSwitcher();
return { action: 'app-switcher', ...successText('Opened app switcher') };
case 'clipboard':
return await handleClipboardCommand(interactor, positionals);
case 'keyboard':
return await handleKeyboardCommand(device, positionals, context, runnerCtx);
case 'settings':
return await handleSettingsCommand(device, interactor, positionals, context);
case 'push':
return await handlePushCommand(device, positionals, context);
case 'snapshot':
return await handleSnapshotCommand(interactor, context);
case 'read':
return await handleReadCommand(device, positionals, context);
default:
throw new AppError('INVALID_ARGS', `Unknown command: ${command}`);
}
}
// ---------------------------------------------------------------------------
// Command handlers
// ---------------------------------------------------------------------------
// fallow-ignore-next-line complexity
async function handleOpenCommand(
device: DeviceInfo,
interactor: Interactor,
positionals: string[],
context: DispatchContext | undefined,
): Promise<Record<string, unknown>> {
const app = positionals[0];
const url = positionals[1];
const launchConsole = context?.launchConsole;
if (positionals.length > 2) {
throw new AppError('INVALID_ARGS', 'open accepts at most two arguments: <app|url> [url]');
}
if (!app) {
if (launchConsole) {
throw new AppError('INVALID_ARGS', '--launch-console requires an app target');
}
await interactor.openDevice();
return { app: null, ...successText('Opened device') };
}
if (launchConsole && (device.platform !== 'ios' || device.kind !== 'simulator')) {
throw new AppError('UNSUPPORTED_OPERATION', LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE);
}
if (url !== undefined) {
if (isDeepLinkTarget(app)) {
throw new AppError(
'INVALID_ARGS',
'open <app> <url> requires an app target as the first argument',
);
}
if (!isDeepLinkTarget(url)) {
throw new AppError('INVALID_ARGS', 'open <app> <url> requires a valid URL target');
}
if (launchConsole) {
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
}
await interactor.open(app, {
activity: context?.activity,
appBundleId: context?.appBundleId,
launchArgs: context?.launchArgs,
url,
});
return { app, url, ...successText(`Opened: ${app}`) };
}
if (launchConsole && isDeepLinkTarget(app)) {
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
}
if (device.platform === 'android' && context?.launchArgs && context.launchArgs.length > 0) {
throw new AppError(
'UNSUPPORTED_OPERATION',
'Launch arguments are currently supported only on Apple platforms.',
);
}
if (context?.clearAppState) {
if (isDeepLinkTarget(app)) {
throw new AppError(
'INVALID_ARGS',
'Clearing app state requires an app target, not a deep link.',
);
}
if (device.platform !== 'ios' || device.kind !== 'simulator') {
throw new AppError(
'UNSUPPORTED_OPERATION',
'Clearing app state is currently supported only on iOS simulators.',
);
}
await clearIosSimulatorAppState(device, app);
}
await interactor.open(app, {
activity: context?.activity,
appBundleId: context?.appBundleId,
launchConsole,
launchArgs: context?.launchArgs,
});
return { app, ...(launchConsole ? { launchConsole } : {}), ...successText(`Opened: ${app}`) };
}
async function handleTriggerAppEventCommand(
device: DeviceInfo,
interactor: Interactor,
positionals: string[],
context: DispatchContext | undefined,
): Promise<Record<string, unknown>> {
const { eventName, payload } = parseTriggerAppEventArgs(positionals);
const eventUrl = resolveAppEventUrl(device.platform, eventName, payload);
await interactor.open(eventUrl, { appBundleId: context?.appBundleId });
return {
event: eventName,
eventUrl,
transport: 'deep-link',
...successText(`Triggered app event: ${eventName}`),
};
}
async function handleScreenshotCommand(
interactor: Interactor,
positionals: string[],
outPath: string | undefined,
context: DispatchContext | undefined,
): Promise<Record<string, unknown>> {
const positionalPath = positionals[0];
const screenshotPath = positionalPath ?? outPath ?? `./screenshot-${Date.now()}.png`;
await fs.mkdir(pathModule.dirname(screenshotPath), { recursive: true });
const screenshotOptions = screenshotOptionsFromFlags(context);
await interactor.screenshot(screenshotPath, {
appBundleId: context?.appBundleId,
fullscreen: screenshotOptions.fullscreen,
stabilize: screenshotOptions.stabilize,
surface: context?.surface,
});
return { path: screenshotPath, ...successText(`Saved screenshot: ${screenshotPath}`) };
}
async function handleClipboardCommand(
interactor: Interactor,
positionals: string[],
): Promise<Record<string, unknown>> {
const action = (positionals[0] ?? '').toLowerCase();
if (action !== 'read' && action !== 'write') {
throw new AppError('INVALID_ARGS', 'clipboard requires a subcommand: read or write');
}
if (action === 'read') {
if (positionals.length !== 1) {
throw new AppError('INVALID_ARGS', 'clipboard read does not accept additional arguments');
}
const text = await interactor.readClipboard();
return { action, text };
}
if (positionals.length < 2) {
throw new AppError('INVALID_ARGS', 'clipboard write requires text (use "" to clear clipboard)');
}
const text = positionals.slice(1).join(' ');
await interactor.writeClipboard(text);
return {
action,
textLength: Array.from(text).length,
...successText('Clipboard updated'),
};
}
async function handleKeyboardCommand(
device: DeviceInfo,
positionals: string[],
context: DispatchContext | undefined,
runnerCtx: RunnerContext,
): Promise<Record<string, unknown>> {
const action = (positionals[0] ?? 'status').toLowerCase();
if (!isKeyboardAction(action)) {
throw new AppError(
'INVALID_ARGS',
'keyboard requires a subcommand: status, get, dismiss, enter, or return',
);
}
if (positionals.length > 1) {
throw new AppError('INVALID_ARGS', 'keyboard accepts at most one subcommand argument');
}
if (device.platform === 'android') {
return await handleAndroidKeyboardCommand(device, action);
}
if (device.platform === 'ios') {
return await handleIosKeyboardCommand(device, action, context, runnerCtx);
}
throw new AppError('UNSUPPORTED_OPERATION', 'keyboard is supported only on Android and iOS');
}
async function handleAndroidKeyboardCommand(
device: DeviceInfo,
action: KeyboardAction,
): Promise<Record<string, unknown>> {
if (action === 'enter' || action === 'return') {
await pressAndroidEnter(device);
return {
platform: 'android',
action: 'enter',
...successText('Keyboard enter pressed'),
};
}
if (action === 'dismiss') {
const result = await dismissAndroidKeyboard(device);
return {
platform: 'android',
action: 'dismiss',
attempts: result.attempts,
wasVisible: result.wasVisible,
dismissed: result.dismissed,
visible: result.visible,
inputType: result.inputType,
type: result.type,
inputMethodPackage: result.inputMethodPackage,
focusedPackage: result.focusedPackage,
focusedResourceId: result.focusedResourceId,
inputOwner: result.inputOwner,
};
}
const state = await getAndroidKeyboardState(device);
return {
platform: 'android',
action: 'status',
visible: state.visible,
inputType: state.inputType,
type: state.type,
inputMethodPackage: state.inputMethodPackage,
focusedPackage: state.focusedPackage,
focusedResourceId: state.focusedResourceId,
inputOwner: state.inputOwner,
};
}
async function handleIosKeyboardCommand(
device: DeviceInfo,
action: KeyboardAction,
context: DispatchContext | undefined,
runnerCtx: RunnerContext,
): Promise<Record<string, unknown>> {
if (action !== 'dismiss' && action !== 'enter' && action !== 'return') {
throw new AppError(
'UNSUPPORTED_OPERATION',
'keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS',
);
}
if (action === 'enter' || action === 'return') {
const result = await runIosRunnerCommand(
device,
{ command: 'keyboardReturn', appBundleId: context?.appBundleId },
runnerCtx,
);
return {
platform: 'ios',
action: 'enter',
visible: result.visible,
wasVisible: result.wasVisible,
...successText('Keyboard enter pressed'),
};
}
const result = await runIosRunnerCommand(
device,
{ command: 'keyboardDismiss', appBundleId: context?.appBundleId },
runnerCtx,
);
return {
platform: 'ios',
action: 'dismiss',
wasVisible: result.wasVisible,
dismissed: result.dismissed,
visible: result.visible,
...successText(result.dismissed ? 'Keyboard dismissed' : 'Keyboard already hidden'),
};
}
async function handleSettingsCommand(
device: DeviceInfo,
interactor: Interactor,
positionals: string[],
context: DispatchContext | undefined,
): Promise<Record<string, unknown>> {
const [setting, state, target, mode] = positionals;
if (!setting || !state) {
throw new AppError('INVALID_ARGS', 'settings requires setting state');
}
const isLocationSet = setting === 'location' && state === 'set';
const usesPayloadAppBundleSlot = setting === 'permission' || isLocationSet;
const appBundleId =
(usesPayloadAppBundleSlot ? positionals[4] : positionals[2]) ?? context?.appBundleId;
const settingOptions =
setting === 'permission'
? {
permissionTarget: target,
permissionMode: mode,
}
: isLocationSet
? {
latitude: readLocationCoordinate(target, 'latitude'),
longitude: readLocationCoordinate(mode, 'longitude'),
}
: undefined;
const diagnosticPayload = isLocationSet
? { setting, state, latitude: target, longitude: mode, platform: device.platform }
: setting === 'permission'
? {
setting,
state,
permissionTarget: target,
permissionMode: mode,
platform: device.platform,
}
: { setting, state, appBundleId, platform: device.platform };
emitDiagnostic({
level: 'debug',
phase: 'settings_apply',
data: diagnosticPayload,
});
const result = await interactor.setSetting(setting, state, appBundleId, settingOptions);
return result && typeof result === 'object'
? withSuccessText(
{ setting, state, ...result },
readResultMessage(result) ?? `Updated setting: ${setting}`,
)
: { setting, state, ...successText(`Updated setting: ${setting}`) };
}
async function handlePushCommand(
device: DeviceInfo,
positionals: string[],
_context: DispatchContext | undefined,
): Promise<Record<string, unknown>> {
const target = positionals[0]?.trim();
const payloadArg = positionals[1]?.trim();
if (!target || !payloadArg) {
throw new AppError('INVALID_ARGS', 'push requires <bundle|package> <payload.json|inline-json>');
}
const payload = await readNotificationPayload(payloadArg);
if (device.platform === 'ios') {
await pushIosNotification(device, target, payload);
return {
platform: 'ios',
bundleId: target,
...successText(`Pushed notification to ${target}`),
};
}
const androidResult = await pushAndroidNotification(device, target, payload);
return {
platform: 'android',
package: target,
action: androidResult.action,
extrasCount: androidResult.extrasCount,
...successText(`Pushed notification to ${target}`),
};
}
async function handleSnapshotCommand(
interactor: Interactor,
context: DispatchContext | undefined,
): Promise<Record<string, unknown>> {
return await interactor.snapshot({
appBundleId: context?.appBundleId,
interactiveOnly: context?.snapshotInteractiveOnly,
compact: context?.snapshotCompact,
depth: context?.snapshotDepth,
scope: context?.snapshotScope,
raw: context?.snapshotRaw,
surface: context?.surface,
});
}
function readResultMessage(result: Record<string, unknown>): string | undefined {
return typeof result.message === 'string' && result.message.length > 0
? result.message
: undefined;
}