-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathclient.ts
More file actions
378 lines (366 loc) · 14.2 KB
/
Copy pathclient.ts
File metadata and controls
378 lines (366 loc) · 14.2 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
import { sendToDaemon } from './daemon-client.ts';
import { prepareMetroRuntime, reloadMetro } from './client-metro.ts';
import { INTERNAL_COMMANDS } from './command-catalog.ts';
import {
prepareDaemonCommandRequest,
type DaemonCommandName,
} from './commands/command-projection.ts';
import { throwDaemonError } from './daemon-error.ts';
import {
buildFlags,
buildMeta,
normalizeDeployResult,
normalizeDevice,
normalizeInstallFromSourceResult,
normalizeMaterializationReleaseResult,
normalizeOpenDevice,
readScreenshotOverlayRefs,
normalizeRuntimeHints,
normalizeSession,
normalizeStartupSample,
readOptionalString,
readRequiredString,
readSnapshotNodes,
resolveSessionName,
} from './client-normalizers.ts';
import type {
AgentDeviceClient,
AgentDeviceClientConfig,
AgentDeviceDaemonTransport,
AppCloseOptions,
AppDeployOptions,
AppInstallFromSourceOptions,
AppListOptions,
AppOpenOptions,
CaptureScreenshotOptions,
CaptureSnapshotOptions,
CaptureSnapshotResult,
InternalRequestOptions,
Lease,
MaterializationReleaseOptions,
MetroPrepareOptions,
} from './client-types.ts';
export function createAgentDeviceClient(
config: AgentDeviceClientConfig = {},
deps: { transport?: AgentDeviceDaemonTransport } = {},
): AgentDeviceClient {
const transport = deps.transport ?? sendToDaemon;
const execute = async (
command: string,
positionals: string[] = [],
options: InternalRequestOptions = {},
): Promise<Record<string, unknown>> => {
const merged = mergeClientOptions(config, options);
const response = await transport({
session: resolveSessionName(merged.session),
command,
positionals,
flags: buildFlags(merged),
runtime: merged.runtime,
meta: buildMeta(merged),
});
if (!response.ok) {
throwDaemonError(response.error);
}
return (response.data ?? {}) as Record<string, unknown>;
};
const listSessions = async (options = {}) => {
const data = await execute(INTERNAL_COMMANDS.sessionList, [], options);
const sessions = Array.isArray(data.sessions) ? data.sessions : [];
return sessions.map(normalizeSession);
};
const executeCommand = async <T>(
command: DaemonCommandName,
options: InternalRequestOptions = {},
): Promise<T> => {
const request = prepareDaemonCommandRequest(command, options);
return (await execute(request.command, request.positionals, request.options)) as T;
};
const resolveRequestSession = (options: InternalRequestOptions = {}) =>
resolveSessionName(mergeClientOptions(config, options).session);
return {
command: {
wait: async (options) => await executeCommand('wait', options),
alert: async (options = {}) => await executeCommand('alert', options),
appState: async (options = {}) => await executeCommand('appstate', options),
back: async (options = {}) => await executeCommand('back', options),
home: async (options = {}) => await executeCommand('home', options),
rotate: async (options) => await executeCommand('rotate', options),
appSwitcher: async (options = {}) => await executeCommand('app-switcher', options),
keyboard: async (options = {}) => await executeCommand('keyboard', options),
clipboard: async (options) => await executeCommand('clipboard', options),
reactNative: async (options) => await executeCommand('react-native', options),
},
devices: {
list: async (options = {}) => {
const data = await executeCommand<Record<string, unknown>>('devices', options);
const devices = Array.isArray(data.devices) ? data.devices : [];
return devices.map(normalizeDevice);
},
boot: async (options = {}) => await executeCommand('boot', options),
},
sessions: {
list: async (options = {}) => await listSessions(options),
close: async (options = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('close', options);
const shutdown = data.shutdown;
return {
session,
shutdown:
typeof shutdown === 'object' && shutdown !== null
? (shutdown as Record<string, unknown>)
: undefined,
identifiers: { session },
};
},
},
apps: {
install: async (options: AppDeployOptions) =>
normalizeDeployResult(
await executeCommand('install', options),
resolveRequestSession(options),
),
reinstall: async (options: AppDeployOptions) =>
normalizeDeployResult(
await executeCommand('reinstall', options),
resolveRequestSession(options),
),
installFromSource: async (options: AppInstallFromSourceOptions) =>
normalizeInstallFromSourceResult(
await executeCommand('install-from-source', options),
resolveRequestSession(options),
),
list: async (options: AppListOptions = {}) => {
const data = await executeCommand<Record<string, unknown>>('apps', options);
return Array.isArray(data.apps)
? data.apps.filter((app): app is string => typeof app === 'string')
: [];
},
open: async (options: AppOpenOptions) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('open', options);
const device = normalizeOpenDevice(data);
const appBundleId = readOptionalString(data, 'appBundleId');
const appId = appBundleId;
return {
session,
sessionStateDir: readOptionalString(data, 'sessionStateDir'),
appName: readOptionalString(data, 'appName'),
appBundleId,
appId,
startup: normalizeStartupSample(data.startup),
runtime: normalizeRuntimeHints(data.runtime),
device,
identifiers: {
session,
deviceId: device?.id,
deviceName: device?.name,
udid: device?.ios?.udid,
serial: device?.android?.serial,
appId,
appBundleId,
},
};
},
close: async (options: AppCloseOptions = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('close', options);
const shutdown = data.shutdown;
return {
session,
closedApp: options.app,
shutdown:
typeof shutdown === 'object' && shutdown !== null
? (shutdown as Record<string, unknown>)
: undefined,
identifiers: { session },
};
},
push: async (options) => await executeCommand('push', options),
triggerEvent: async (options) => await executeCommand('trigger-app-event', options),
},
materializations: {
release: async (options: MaterializationReleaseOptions) =>
normalizeMaterializationReleaseResult(
await execute(INTERNAL_COMMANDS.releaseMaterializedPaths, [], {
...options,
materializationId: options.materializationId,
}),
),
},
leases: {
allocate: async (options) =>
normalizeLease(
await execute(INTERNAL_COMMANDS.leaseAllocate, [], {
...options,
leaseId: undefined,
leaseTtlMs: options.ttlMs,
}),
),
heartbeat: async (options) =>
normalizeLease(
await execute(INTERNAL_COMMANDS.leaseHeartbeat, [], {
...options,
leaseTtlMs: options.ttlMs,
}),
),
release: async (options) => {
const data = await execute(INTERNAL_COMMANDS.leaseRelease, [], options);
return { released: data.released === true };
},
},
metro: {
prepare: async (options: MetroPrepareOptions) =>
await prepareMetroRuntime({
projectRoot: options.projectRoot ?? config.cwd,
kind: options.kind,
publicBaseUrl: options.publicBaseUrl,
proxyBaseUrl: options.proxyBaseUrl,
proxyBearerToken: options.bearerToken,
bridgeScope: options.bridgeScope,
launchUrl: options.launchUrl,
companionProfileKey: options.companionProfileKey,
companionConsumerKey: options.companionConsumerKey,
metroPort: options.port,
listenHost: options.listenHost,
statusHost: options.statusHost,
startupTimeoutMs: options.startupTimeoutMs,
probeTimeoutMs: options.probeTimeoutMs,
reuseExisting: options.reuseExisting,
installDependenciesIfNeeded: options.installDependenciesIfNeeded,
runtimeFilePath: options.runtimeFilePath,
logPath: options.logPath,
}),
reload: async (options = {}) =>
await reloadMetro({
metroHost: options.metroHost,
metroPort: options.metroPort,
bundleUrl: options.bundleUrl,
runtime: config.runtime,
timeoutMs: options.timeoutMs,
}),
},
capture: {
snapshot: async (options: CaptureSnapshotOptions = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('snapshot', options);
return normalizeSnapshotResult(data, session);
},
screenshot: async (options: CaptureScreenshotOptions = {}) => {
const session = resolveRequestSession(options);
const data = await executeCommand<Record<string, unknown>>('screenshot', options);
return {
path: readRequiredString(data, 'path'),
overlayRefs: readScreenshotOverlayRefs(data),
identifiers: { session },
};
},
diff: async (options) => await executeCommand('diff', options),
},
interactions: {
click: async (options) => await executeCommand('click', options),
press: async (options) => await executeCommand('press', options),
longPress: async (options) => await executeCommand('longpress', options),
swipe: async (options) => await executeCommand('swipe', options),
pan: async (options) => await executeCommand('gesture-pan', options),
fling: async (options) => await executeCommand('gesture-fling', options),
swipeGesture: async (options) => await executeCommand('gesture-swipe', options),
focus: async (options) => await executeCommand('focus', options),
type: async (options) => await executeCommand('type', options),
fill: async (options) => await executeCommand('fill', options),
scroll: async (options) => await executeCommand('scroll', options),
pinch: async (options) => await executeCommand('gesture-pinch', options),
rotateGesture: async (options) => await executeCommand('gesture-rotate', options),
transformGesture: async (options) => await executeCommand('gesture-transform', options),
get: async (options) => await executeCommand('get', options),
is: async (options) => await executeCommand('is', options),
find: async (options) => await executeCommand('find', options),
},
replay: {
run: async (options) => await executeCommand('replay', options),
test: async (options) => await executeCommand('test', options),
},
batch: {
run: async (options) => await executeCommand('batch', options),
},
observability: {
perf: async (options = {}) => await executeCommand('perf', options),
logs: async (options = {}) => await executeCommand('logs', options),
network: async (options = {}) => await executeCommand('network', options),
},
recording: {
record: async (options) => await executeCommand('record', options),
trace: async (options) => await executeCommand('trace', options),
},
settings: {
update: async (options) => await executeCommand('settings', options),
},
};
}
function normalizeSnapshotResult(
data: Record<string, unknown>,
session: string | undefined,
): CaptureSnapshotResult {
const appBundleId = readOptionalString(data, 'appBundleId');
return {
nodes: readSnapshotNodes(data.nodes),
truncated: data.truncated === true,
appName: readOptionalString(data, 'appName'),
appBundleId,
...optionalSnapshotResponseFields(data),
identifiers: {
session,
appId: appBundleId,
appBundleId,
},
};
}
function optionalSnapshotResponseFields(
data: Record<string, unknown>,
): Partial<
Pick<CaptureSnapshotResult, 'androidSnapshot' | 'unchanged' | 'visibility' | 'warnings'>
> {
const visibility = readObject(data.visibility);
const androidSnapshot = readObject(data.androidSnapshot);
const unchanged = readObject(data.unchanged);
const warnings = Array.isArray(data.warnings)
? data.warnings.filter((entry): entry is string => typeof entry === 'string')
: undefined;
return {
...(visibility ? { visibility: visibility as CaptureSnapshotResult['visibility'] } : {}),
...(androidSnapshot
? { androidSnapshot: androidSnapshot as CaptureSnapshotResult['androidSnapshot'] }
: {}),
...(unchanged ? { unchanged: unchanged as CaptureSnapshotResult['unchanged'] } : {}),
...(warnings ? { warnings } : {}),
};
}
function readObject(value: unknown): Record<string, unknown> | undefined {
return typeof value === 'object' && value !== null
? (value as Record<string, unknown>)
: undefined;
}
function mergeClientOptions(
config: AgentDeviceClientConfig,
options: InternalRequestOptions,
): InternalRequestOptions {
return { ...config, ...options };
}
function normalizeLease(data: Record<string, unknown>): Lease {
const rawLease = data.lease;
if (!rawLease || typeof rawLease !== 'object' || Array.isArray(rawLease)) {
throw new Error('Invalid lease response from daemon');
}
const lease = rawLease as Record<string, unknown>;
return {
leaseId: readRequiredString(lease, 'leaseId'),
tenantId: readRequiredString(lease, 'tenantId'),
runId: readRequiredString(lease, 'runId'),
backend: readRequiredString(lease, 'backend') as Lease['backend'],
createdAt: typeof lease.createdAt === 'number' ? lease.createdAt : undefined,
heartbeatAt: typeof lease.heartbeatAt === 'number' ? lease.heartbeatAt : undefined,
expiresAt: typeof lease.expiresAt === 'number' ? lease.expiresAt : undefined,
};
}
export type * from './client-types.ts';