@limrun/api 0.77.2 → 0.77.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +35 -0
- package/destination-tunnel.d.mts.map +1 -1
- package/destination-tunnel.d.ts.map +1 -1
- package/destination-tunnel.js +3 -2
- package/destination-tunnel.js.map +1 -1
- package/destination-tunnel.mjs +3 -2
- package/destination-tunnel.mjs.map +1 -1
- package/index.d.mts +1 -0
- package/index.d.mts.map +1 -1
- package/index.d.ts +1 -0
- package/index.d.ts.map +1 -1
- package/index.js.map +1 -1
- package/index.mjs.map +1 -1
- package/package.json +1 -1
- package/resources/assets.d.mts +19 -4
- package/resources/assets.d.mts.map +1 -1
- package/resources/assets.d.ts +19 -4
- package/resources/assets.d.ts.map +1 -1
- package/resources/gradle-instances-helpers.d.mts +1 -1
- package/resources/index.d.mts +2 -0
- package/resources/index.d.mts.map +1 -1
- package/resources/index.d.ts +2 -0
- package/resources/index.d.ts.map +1 -1
- package/resources/index.js +2 -0
- package/resources/index.js.map +1 -1
- package/resources/index.mjs +2 -0
- package/resources/index.mjs.map +1 -1
- package/resources/macos-instances-helpers.d.mts +271 -0
- package/resources/macos-instances-helpers.d.mts.map +1 -0
- package/resources/macos-instances-helpers.d.ts +271 -0
- package/resources/macos-instances-helpers.d.ts.map +1 -0
- package/resources/macos-instances-helpers.js +298 -0
- package/resources/macos-instances-helpers.js.map +1 -0
- package/resources/macos-instances-helpers.mjs +296 -0
- package/resources/macos-instances-helpers.mjs.map +1 -0
- package/resources/macos-instances.d.mts +19 -0
- package/resources/macos-instances.d.mts.map +1 -1
- package/resources/macos-instances.d.ts +19 -0
- package/resources/macos-instances.d.ts.map +1 -1
- package/src/destination-tunnel.ts +3 -2
- package/src/index.ts +16 -0
- package/src/resources/assets.ts +24 -4
- package/src/resources/index.ts +11 -0
- package/src/resources/macos-instances-helpers.ts +655 -0
- package/src/resources/macos-instances.ts +30 -0
- package/src/version.ts +1 -1
- package/version.d.mts +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.mjs +1 -1
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
import { nodeProxyTransport } from '../internal/proxy-transport';
|
|
2
|
+
import { directInstanceErrorReason } from '../internal/direct-instance-errors';
|
|
3
|
+
import { instanceToken } from '../instance-token';
|
|
4
|
+
import { startTcpTunnel, type TcpTunnelOptions, type Tunnel } from '../tunnel';
|
|
5
|
+
import { type ExecChildProcess } from '../exec-client';
|
|
6
|
+
import {
|
|
7
|
+
createBuildRun,
|
|
8
|
+
createDaemonLogger,
|
|
9
|
+
type BuildRunOptions,
|
|
10
|
+
type LogLevel,
|
|
11
|
+
} from './daemon-client-shared';
|
|
12
|
+
import { MacosInstances, type MacosInstance } from './macos-instances';
|
|
13
|
+
import {
|
|
14
|
+
destinationTunnelDialOptions,
|
|
15
|
+
startDestinationTcpTunnel,
|
|
16
|
+
type DestinationTcpTunnel,
|
|
17
|
+
type DestinationTunnelStartOptions,
|
|
18
|
+
} from '../destination-tunnel-dialer';
|
|
19
|
+
import { APIPromise } from '../core/api-promise';
|
|
20
|
+
import { RequestOptions } from '../internal/request-options';
|
|
21
|
+
import { path } from '../internal/utils/path';
|
|
22
|
+
import { downloadFileToLocalPath } from '../internal/download-file';
|
|
23
|
+
import { persistFields, ttlFields, type PersistOption } from '../internal/persist-option';
|
|
24
|
+
import { streamSessionEntries } from '../internal/session-stream';
|
|
25
|
+
import { postTrustedCaCertificate, type TrustedCaCertificate } from '../internal/trusted-ca';
|
|
26
|
+
import {
|
|
27
|
+
type PerformanceSample,
|
|
28
|
+
type SessionArtifact,
|
|
29
|
+
type SessionArtifactKind,
|
|
30
|
+
type SessionEvent,
|
|
31
|
+
type SessionLogLine,
|
|
32
|
+
} from './session-artifacts';
|
|
33
|
+
import {
|
|
34
|
+
getDestinationTunnelStatus,
|
|
35
|
+
stopDestinationTunnel,
|
|
36
|
+
type DestinationTunnelStatus,
|
|
37
|
+
} from '../internal/destination-tunnel-management';
|
|
38
|
+
import { deriveDestinationTunnelURL } from '../internal/destination-tunnel-url';
|
|
39
|
+
|
|
40
|
+
export type MacosCreateClientParams = { logLevel?: LogLevel } & (
|
|
41
|
+
| { instance: MacosInstance }
|
|
42
|
+
| { apiUrl: string; token: string }
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Options of {@link MacosClient.startTunnel}, as on iOS and Android: inspection is on and bodies
|
|
47
|
+
* are off unless `inspection` says otherwise.
|
|
48
|
+
*/
|
|
49
|
+
export type MacosTunnelOptions = DestinationTunnelStartOptions;
|
|
50
|
+
|
|
51
|
+
/** Options of {@link MacosClient.startRecording}. */
|
|
52
|
+
export interface MacosRecordingOptions {
|
|
53
|
+
/** The recording's ID, `[a-z0-9][a-z0-9_-]{0,63}`. Generated when omitted; never reused. */
|
|
54
|
+
recordingId?: string;
|
|
55
|
+
/** Encoder quality from 5 to 10; the server default is 5. */
|
|
56
|
+
quality?: number;
|
|
57
|
+
/** Upload the recording to Limrun's bucket when it stops; list it with `listRecordings`. */
|
|
58
|
+
persist?: PersistOption;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Where a stopped recording goes, besides the instance's own download URL. */
|
|
62
|
+
export interface MacosRecordingDestination {
|
|
63
|
+
/** An HTTPS presigned PUT URL the instance uploads the MP4 to before the stop resolves. */
|
|
64
|
+
presignedUrl?: string;
|
|
65
|
+
/** A local path this client downloads the MP4 to. */
|
|
66
|
+
localPath?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Handlers of a live stream. `onError` fires at most once, and the stream is then closed. */
|
|
70
|
+
/**
|
|
71
|
+
* How {@link MacosClient.launchApp} treats an app that already runs: `ForegroundIfRunning` brings
|
|
72
|
+
* it to the front, `RelaunchIfRunning` stops it and starts it anew.
|
|
73
|
+
*/
|
|
74
|
+
export type MacosLaunchMode = 'ForegroundIfRunning' | 'RelaunchIfRunning';
|
|
75
|
+
|
|
76
|
+
export interface MacosLaunchAppOptions {
|
|
77
|
+
/** Defaults to `ForegroundIfRunning`. */
|
|
78
|
+
mode?: MacosLaunchMode;
|
|
79
|
+
/** Command-line arguments for the app. */
|
|
80
|
+
arguments?: string[];
|
|
81
|
+
/** Environment variables for the app. */
|
|
82
|
+
env?: Record<string, string>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface MacosLaunchAppResult {
|
|
86
|
+
bundleId: string;
|
|
87
|
+
pid: number;
|
|
88
|
+
/** False when the app already ran and was brought to the front. */
|
|
89
|
+
launched: boolean;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface MacosStreamHandlers<T> {
|
|
93
|
+
onEntry: (entry: T) => void;
|
|
94
|
+
/** Called once the entries the instance replays on connect have all arrived. */
|
|
95
|
+
onReplayed?: () => void;
|
|
96
|
+
onError?: (error: Error) => void;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A point on the screen, in pixels of `screenshot()`, from the top-left corner. */
|
|
100
|
+
export interface MacosPoint {
|
|
101
|
+
x: number;
|
|
102
|
+
y: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Modifier keys held while a key is pressed. */
|
|
106
|
+
export type MacosModifier = 'shift' | 'control' | 'option' | 'command';
|
|
107
|
+
|
|
108
|
+
/** Where the guest's SSH server can be reached once {@link MacosClient.enableSsh} returns. */
|
|
109
|
+
export interface MacosSshAccess {
|
|
110
|
+
/** The guest account the key logs in as. */
|
|
111
|
+
user: string;
|
|
112
|
+
/** The guest port sshd listens on; forward a local port to it with `startPortForward`. */
|
|
113
|
+
port: number;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* MacosClient works inside a running macOS instance: it runs shell commands
|
|
118
|
+
* as the guest's user, forwards local ports into the guest, and drives the
|
|
119
|
+
* screen with the mouse and keyboard.
|
|
120
|
+
*/
|
|
121
|
+
export interface MacosClient {
|
|
122
|
+
/**
|
|
123
|
+
* Run a shell command line as the guest's user, in its login session, with
|
|
124
|
+
* a login shell's PATH. `cwd` is relative to the user's home directory.
|
|
125
|
+
* Output streams on `stdout` and `stderr`; the promise resolves with the
|
|
126
|
+
* exit code. `kill()` ends the command and everything it started.
|
|
127
|
+
*/
|
|
128
|
+
run(commandLine: string, options?: BuildRunOptions): ExecChildProcess;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Turn on the guest's SSH server and let `publicKey` (one OpenSSH public key
|
|
132
|
+
* line) log in. Password logins stay off. Reach the server with
|
|
133
|
+
* `startPortForward(localPort, access.port)`.
|
|
134
|
+
*/
|
|
135
|
+
enableSsh(publicKey: string): Promise<MacosSshAccess>;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Accept TCP connections on `localPort` (on 127.0.0.1 unless `hostname` is
|
|
139
|
+
* given) and carry each one to `remotePort` inside the guest.
|
|
140
|
+
*/
|
|
141
|
+
startPortForward(
|
|
142
|
+
localPort: number,
|
|
143
|
+
remotePort: number,
|
|
144
|
+
options?: TcpTunnelOptions & { hostname?: string },
|
|
145
|
+
): Promise<Tunnel>;
|
|
146
|
+
|
|
147
|
+
/** A JPEG of the screen. Its pixels are the coordinates the input methods take. */
|
|
148
|
+
screenshot(): Promise<Buffer>;
|
|
149
|
+
|
|
150
|
+
/** Click at a point. */
|
|
151
|
+
tap(point: MacosPoint, options?: { button?: 'left' | 'right' }): Promise<void>;
|
|
152
|
+
|
|
153
|
+
/** Type text with key presses on the US layout. */
|
|
154
|
+
typeText(text: string): Promise<void>;
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Press one key, such as `enter`, `tab`, `escape`, `up`, `f5` or `a`, while
|
|
158
|
+
* holding the given modifiers.
|
|
159
|
+
*/
|
|
160
|
+
pressKey(key: string, modifiers?: MacosModifier[]): Promise<void>;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Scroll by `dy` (positive scrolls down) and `dx` (positive scrolls right)
|
|
164
|
+
* pixels over the point, or wherever the pointer is when none is given.
|
|
165
|
+
*/
|
|
166
|
+
scroll(options: { dx?: number; dy?: number; at?: MacosPoint }): Promise<void>;
|
|
167
|
+
|
|
168
|
+
/** Press at `from`, move to `to` over `durationMs`, and release. */
|
|
169
|
+
drag(from: MacosPoint, to: MacosPoint, options?: { durationMs?: number }): Promise<void>;
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Restore a disk snapshot into the guest and set the key the instance saves under when it
|
|
173
|
+
* terminates. A snapshot is an asset of kind `MacOSSnapshot`, so the instance's role needs read
|
|
174
|
+
* on the restore keys' asset names, and create, upload and update on `key`'s.
|
|
175
|
+
*
|
|
176
|
+
* Each restore key is tried in order: its exact name first, then the newest asset whose name
|
|
177
|
+
* starts with it, skipping snapshots saved on another macOS build. Without `restoreKeys`,
|
|
178
|
+
* `key` is restored. Without either, nothing is restored. Call it once the instance is ready
|
|
179
|
+
* and before using the guest; asking again joins the restore already running. Resolves with the
|
|
180
|
+
* final progress event; `onProgress` sees every event, with byte counts while downloading.
|
|
181
|
+
*/
|
|
182
|
+
restoreSnapshot(options: MacosSnapshotRestoreOptions): Promise<MacosSnapshotProgress>;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Let code in the guest reach destinations on this machine through a destination tunnel, as on
|
|
186
|
+
* an iOS simulator. `localhost:port` and `IPv4:port` selectors are reached at those addresses in
|
|
187
|
+
* the guest; domain selectors are resolved in the guest to addresses the tunnel serves and
|
|
188
|
+
* dialed from this machine. One tunnel serves an instance at a time.
|
|
189
|
+
*/
|
|
190
|
+
startTunnel(options: MacosTunnelOptions): Promise<DestinationTcpTunnel>;
|
|
191
|
+
|
|
192
|
+
/** The instance's tunnel, if one is active. */
|
|
193
|
+
getTunnelStatus(): Promise<DestinationTunnelStatus>;
|
|
194
|
+
|
|
195
|
+
/** Stop the tunnel with this ID; another tunnel that replaced it keeps running. */
|
|
196
|
+
stopTunnel(tunnelId: string): Promise<void>;
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Trust a PEM-encoded CA certificate system-wide in the guest, for example the CA of an
|
|
200
|
+
* intercepting proxy you record traffic with. macOS asks an administrator to confirm a new
|
|
201
|
+
* trusted root, so the instance answers that dialog itself and it shows on the screen for a
|
|
202
|
+
* few seconds. Adding a certificate the guest already trusts changes nothing.
|
|
203
|
+
*/
|
|
204
|
+
addCaCertificate(pem: string): Promise<TrustedCaCertificate>;
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Start recording the screen and return the recording's ID. Up to eight recordings may be
|
|
208
|
+
* active or uploading at once.
|
|
209
|
+
*/
|
|
210
|
+
startRecording(options?: MacosRecordingOptions): Promise<string>;
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Stop a recording, or the latest active one when `recordingId` is omitted, and return its
|
|
214
|
+
* download URL, which takes the instance token and lasts while the instance runs.
|
|
215
|
+
*/
|
|
216
|
+
stopRecording(recordingId?: string, saveTo?: MacosRecordingDestination): Promise<string>;
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Launch an app by bundle ID (`com.example.app`), name (`TextEdit`) or path
|
|
220
|
+
* (`/Applications/Safari.app`) and bring it to the front. An app launched this way has its
|
|
221
|
+
* stdout and stderr in its app log; one started any other way writes them nowhere. Arguments
|
|
222
|
+
* and environment apply only when the app starts, not when it already runs.
|
|
223
|
+
*/
|
|
224
|
+
launchApp(app: string, options?: MacosLaunchAppOptions): Promise<MacosLaunchAppResult>;
|
|
225
|
+
|
|
226
|
+
/** Stop every process of an app. Succeeds when the app is not running. */
|
|
227
|
+
terminateApp(bundleId: string): Promise<void>;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The last `lines` lines of an app's log: its stdout and stderr when it was started with
|
|
231
|
+
* {@link launchApp}, and what it wrote to the unified log in the past hour, in time order.
|
|
232
|
+
* For an app that is not Apple's, Apple's frameworks' messages are left out.
|
|
233
|
+
*/
|
|
234
|
+
appLogTail(bundleId: string, lines: number): Promise<string>;
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Follow an app's log, as {@link appLogTail} reads it, one line per `onEntry`. Returns a
|
|
238
|
+
* function that stops it.
|
|
239
|
+
*/
|
|
240
|
+
streamAppLog(bundleId: string, handlers: MacosStreamHandlers<string>): () => void;
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Start capturing an app's logs. One app log capture runs at a time. With `persist`, the
|
|
244
|
+
* capture is uploaded to Limrun's bucket when it stops or the instance terminates; list it
|
|
245
|
+
* with `macosInstances.listAppLogs`.
|
|
246
|
+
*/
|
|
247
|
+
startAppLogCapture(options: { bundleId: string; persist?: PersistOption }): Promise<void>;
|
|
248
|
+
|
|
249
|
+
/** Stop the active app log capture. */
|
|
250
|
+
stopAppLogCapture(): Promise<void>;
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Start capturing the coalesced event log of clicks, scrolls and keys sent to the screen.
|
|
254
|
+
* Typing is logged as a count of characters, never their content.
|
|
255
|
+
*/
|
|
256
|
+
startEventCapture(options?: { persist?: PersistOption }): Promise<void>;
|
|
257
|
+
|
|
258
|
+
/** Stop the active event capture. */
|
|
259
|
+
stopEventCapture(): Promise<void>;
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Start saving the running apps' performance samples. The capture always persists, kept for
|
|
263
|
+
* `ttlSeconds` (server default 72h); list it with `macosInstances.listPerformanceCaptures`.
|
|
264
|
+
*/
|
|
265
|
+
startPerformanceCapture(options?: { ttlSeconds?: number }): Promise<void>;
|
|
266
|
+
|
|
267
|
+
/** Stop the active performance capture and upload it. */
|
|
268
|
+
stopPerformanceCapture(): Promise<void>;
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Tail the live app log capture. On connect the instance replays its recent lines, and a
|
|
272
|
+
* dropped connection resumes where it left off. Returns a function that closes it.
|
|
273
|
+
*/
|
|
274
|
+
streamAppLogCapture(handlers: MacosStreamHandlers<SessionLogLine>): () => void;
|
|
275
|
+
|
|
276
|
+
/** Tail the live event capture, with {@link streamAppLogCapture}'s semantics. */
|
|
277
|
+
streamEventCapture(handlers: MacosStreamHandlers<SessionEvent>): () => void;
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Tail the running apps' CPU, memory, thread and disk samples, about once a second; no
|
|
281
|
+
* capture is needed. On connect the instance replays its recent samples.
|
|
282
|
+
*/
|
|
283
|
+
streamPerformance(handlers: MacosStreamHandlers<PerformanceSample>): () => void;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export interface MacosSnapshotRestoreOptions {
|
|
287
|
+
/** The asset name the instance saves its changes under when it terminates. Set once. */
|
|
288
|
+
key?: string;
|
|
289
|
+
/** Asset names, or name prefixes, to restore from, in order. Defaults to `key`. */
|
|
290
|
+
restoreKeys?: string[];
|
|
291
|
+
onProgress?: (progress: MacosSnapshotProgress) => void;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** A restore's progress, as the instance reports it. */
|
|
295
|
+
export interface MacosSnapshotProgress {
|
|
296
|
+
phase: 'resolving' | 'downloading' | 'extracting' | 'restored' | 'skipped' | 'failed' | string;
|
|
297
|
+
/** The asset name the restore matched. */
|
|
298
|
+
key?: string;
|
|
299
|
+
matchKind?: 'exact_hit' | 'prefix_hit' | string;
|
|
300
|
+
/** Whether the bytes came through the regional accelerator or straight from storage. */
|
|
301
|
+
source?: 'tag' | 'direct' | string;
|
|
302
|
+
totalBytes?: number;
|
|
303
|
+
doneBytes?: number;
|
|
304
|
+
reason?: string;
|
|
305
|
+
message?: string;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
declare module './macos-instances' {
|
|
309
|
+
interface MacosInstances {
|
|
310
|
+
/** Create a client that works inside a running macOS instance. */
|
|
311
|
+
createClient(params: MacosCreateClientParams): Promise<MacosClient>;
|
|
312
|
+
/** List the instance's persisted session artifacts, optionally narrowed to one kind. */
|
|
313
|
+
listSessionArtifacts(
|
|
314
|
+
id: string,
|
|
315
|
+
kind?: SessionArtifactKind,
|
|
316
|
+
options?: RequestOptions,
|
|
317
|
+
): APIPromise<SessionArtifact[]>;
|
|
318
|
+
/** List the instance's persisted screen recordings. */
|
|
319
|
+
listRecordings(id: string, options?: RequestOptions): APIPromise<SessionArtifact[]>;
|
|
320
|
+
/** List the instance's persisted app log captures. */
|
|
321
|
+
listAppLogs(id: string, options?: RequestOptions): APIPromise<SessionArtifact[]>;
|
|
322
|
+
/** List the instance's persisted event log captures. */
|
|
323
|
+
listEvents(id: string, options?: RequestOptions): APIPromise<SessionArtifact[]>;
|
|
324
|
+
/** List the instance's persisted performance captures. */
|
|
325
|
+
listPerformanceCaptures(id: string, options?: RequestOptions): APIPromise<SessionArtifact[]>;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// The method body lives in a subclass and is grafted onto the generated class,
|
|
330
|
+
// as for the other instance types, so generated files need no patch.
|
|
331
|
+
class MacosInstancesHelpers extends MacosInstances {
|
|
332
|
+
override async createClient(params: MacosCreateClientParams): Promise<MacosClient> {
|
|
333
|
+
let apiUrl: string;
|
|
334
|
+
let token: string;
|
|
335
|
+
if ('instance' in params) {
|
|
336
|
+
if (!params.instance.status.apiUrl) {
|
|
337
|
+
throw new Error('Instance not ready: apiUrl is not available');
|
|
338
|
+
}
|
|
339
|
+
apiUrl = params.instance.status.apiUrl;
|
|
340
|
+
token = instanceToken(params.instance);
|
|
341
|
+
} else {
|
|
342
|
+
apiUrl = params.apiUrl;
|
|
343
|
+
token = params.token;
|
|
344
|
+
}
|
|
345
|
+
apiUrl = apiUrl.replace(/\/+$/, '');
|
|
346
|
+
const log = createDaemonLogger('[MacosInstance]', params.logLevel ?? 'info');
|
|
347
|
+
|
|
348
|
+
async function request(path: string, init: { method: string; body?: unknown }): Promise<Response> {
|
|
349
|
+
const response = await nodeProxyTransport.fetch(`${apiUrl}${path}`, {
|
|
350
|
+
method: init.method,
|
|
351
|
+
headers: {
|
|
352
|
+
Authorization: `Bearer ${token}`,
|
|
353
|
+
...(init.body !== undefined && { 'Content-Type': 'application/json' }),
|
|
354
|
+
},
|
|
355
|
+
...(init.body !== undefined && { body: JSON.stringify(init.body) }),
|
|
356
|
+
});
|
|
357
|
+
if (!response.ok) {
|
|
358
|
+
const reason = directInstanceErrorReason(await response.text());
|
|
359
|
+
throw new Error(`${init.method} ${path} failed: ${response.status} ${reason}`.trim());
|
|
360
|
+
}
|
|
361
|
+
return response;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async function post(path: string, body: unknown): Promise<void> {
|
|
365
|
+
await request(path, { method: 'POST', body });
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function tail<T extends { ts: number }>(
|
|
369
|
+
kind: 'applogs' | 'events' | 'performance',
|
|
370
|
+
handlers: MacosStreamHandlers<T>,
|
|
371
|
+
): () => void {
|
|
372
|
+
return streamSessionEntries<T>({
|
|
373
|
+
url: `${apiUrl}/session/${kind}/events`,
|
|
374
|
+
token,
|
|
375
|
+
onEntry: handlers.onEntry,
|
|
376
|
+
onReplayed: handlers.onReplayed,
|
|
377
|
+
onError: handlers.onError,
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
run: createBuildRun({ apiUrl, token, log }),
|
|
383
|
+
|
|
384
|
+
async enableSsh(publicKey: string): Promise<MacosSshAccess> {
|
|
385
|
+
const response = await request('/ssh', { method: 'POST', body: { publicKey } });
|
|
386
|
+
return (await response.json()) as MacosSshAccess;
|
|
387
|
+
},
|
|
388
|
+
|
|
389
|
+
startPortForward(localPort, remotePort, options) {
|
|
390
|
+
const url = new URL(apiUrl);
|
|
391
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
392
|
+
url.pathname = `${url.pathname.replace(/\/$/, '')}/port-forward`;
|
|
393
|
+
url.search = '';
|
|
394
|
+
url.searchParams.set('port', String(remotePort));
|
|
395
|
+
const { hostname, ...tunnelOptions } = options ?? {};
|
|
396
|
+
return startTcpTunnel(url.toString(), token, hostname ?? '127.0.0.1', localPort, {
|
|
397
|
+
mode: 'multiplexed',
|
|
398
|
+
...tunnelOptions,
|
|
399
|
+
});
|
|
400
|
+
},
|
|
401
|
+
|
|
402
|
+
startTunnel(tunnelOptions) {
|
|
403
|
+
return startDestinationTcpTunnel(
|
|
404
|
+
deriveDestinationTunnelURL(apiUrl),
|
|
405
|
+
token,
|
|
406
|
+
destinationTunnelDialOptions(tunnelOptions, params.logLevel ?? 'info'),
|
|
407
|
+
);
|
|
408
|
+
},
|
|
409
|
+
|
|
410
|
+
addCaCertificate(pem) {
|
|
411
|
+
return postTrustedCaCertificate<TrustedCaCertificate>(`${apiUrl}/trusted-cas`, token, pem);
|
|
412
|
+
},
|
|
413
|
+
|
|
414
|
+
async startRecording(options) {
|
|
415
|
+
if (options?.recordingId !== undefined) validateRecordingId(options.recordingId);
|
|
416
|
+
const response = await request('/recordings', {
|
|
417
|
+
method: 'POST',
|
|
418
|
+
body: {
|
|
419
|
+
...(options?.recordingId !== undefined && { recordingId: options.recordingId }),
|
|
420
|
+
...(options?.quality !== undefined && { quality: options.quality }),
|
|
421
|
+
...persistFields(options?.persist),
|
|
422
|
+
},
|
|
423
|
+
});
|
|
424
|
+
return ((await response.json()) as { recordingId: string }).recordingId;
|
|
425
|
+
},
|
|
426
|
+
|
|
427
|
+
async stopRecording(recordingId, saveTo = {}) {
|
|
428
|
+
if (recordingId !== undefined) validateRecordingId(recordingId);
|
|
429
|
+
const response = await request(
|
|
430
|
+
recordingId === undefined ? '/recordings/stop' : `/recordings/${recordingId}/stop`,
|
|
431
|
+
{
|
|
432
|
+
method: 'POST',
|
|
433
|
+
body: saveTo.presignedUrl ? { presignedUrl: saveTo.presignedUrl } : {},
|
|
434
|
+
},
|
|
435
|
+
);
|
|
436
|
+
const stopped = ((await response.json()) as { recordingId?: string }).recordingId || recordingId;
|
|
437
|
+
if (!stopped) throw new Error('the instance did not say which recording stopped');
|
|
438
|
+
const downloadUrl = `${apiUrl}/files?name=${encodeURIComponent(`recording_${stopped}.mp4`)}`;
|
|
439
|
+
if (saveTo.localPath) await downloadFileToLocalPath(downloadUrl, token, saveTo.localPath);
|
|
440
|
+
return downloadUrl;
|
|
441
|
+
},
|
|
442
|
+
|
|
443
|
+
async launchApp(app, options) {
|
|
444
|
+
const response = await request('/apps/launch', {
|
|
445
|
+
method: 'POST',
|
|
446
|
+
body: {
|
|
447
|
+
app,
|
|
448
|
+
...(options?.mode !== undefined && { mode: options.mode }),
|
|
449
|
+
...(options?.arguments !== undefined && { arguments: options.arguments }),
|
|
450
|
+
...(options?.env !== undefined && { env: options.env }),
|
|
451
|
+
},
|
|
452
|
+
});
|
|
453
|
+
return (await response.json()) as MacosLaunchAppResult;
|
|
454
|
+
},
|
|
455
|
+
|
|
456
|
+
async terminateApp(bundleId) {
|
|
457
|
+
await request('/apps/terminate', { method: 'POST', body: { bundleId } });
|
|
458
|
+
},
|
|
459
|
+
|
|
460
|
+
async appLogTail(bundleId, lines) {
|
|
461
|
+
const query = new URLSearchParams({ bundleId, lines: String(lines) });
|
|
462
|
+
const response = await request(`/app-logs?${query}`, { method: 'GET' });
|
|
463
|
+
return ((await response.json()) as { logs?: string }).logs ?? '';
|
|
464
|
+
},
|
|
465
|
+
|
|
466
|
+
streamAppLog(bundleId, handlers) {
|
|
467
|
+
const controller = new AbortController();
|
|
468
|
+
void (async () => {
|
|
469
|
+
try {
|
|
470
|
+
const response = await nodeProxyTransport.fetch(
|
|
471
|
+
`${apiUrl}/app-logs/stream?${new URLSearchParams({ bundleId })}`,
|
|
472
|
+
{ headers: { Authorization: `Bearer ${token}` }, signal: controller.signal },
|
|
473
|
+
);
|
|
474
|
+
if (!response.ok || !response.body) {
|
|
475
|
+
throw new Error(
|
|
476
|
+
`GET /app-logs/stream failed: ${response.status} ${await response.text()}`.trim(),
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
for await (const event of readServerSentEvents(response.body)) handlers.onEntry(event.data);
|
|
480
|
+
if (!controller.signal.aborted) throw new Error('the app log stream ended');
|
|
481
|
+
} catch (error) {
|
|
482
|
+
if (!controller.signal.aborted) {
|
|
483
|
+
handlers.onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
})();
|
|
487
|
+
return () => controller.abort();
|
|
488
|
+
},
|
|
489
|
+
|
|
490
|
+
async startAppLogCapture({ bundleId, persist }) {
|
|
491
|
+
if (!bundleId) throw new Error('bundleId must be a non-empty string');
|
|
492
|
+
await post('/session/applogs/start', { bundleId, ...persistFields(persist) });
|
|
493
|
+
},
|
|
494
|
+
|
|
495
|
+
async stopAppLogCapture() {
|
|
496
|
+
await post('/session/applogs/stop', {});
|
|
497
|
+
},
|
|
498
|
+
|
|
499
|
+
async startEventCapture(options) {
|
|
500
|
+
await post('/session/events/start', { ...persistFields(options?.persist) });
|
|
501
|
+
},
|
|
502
|
+
|
|
503
|
+
async stopEventCapture() {
|
|
504
|
+
await post('/session/events/stop', {});
|
|
505
|
+
},
|
|
506
|
+
|
|
507
|
+
async startPerformanceCapture(options) {
|
|
508
|
+
await post('/session/performance/start', { ...ttlFields(options?.ttlSeconds) });
|
|
509
|
+
},
|
|
510
|
+
|
|
511
|
+
async stopPerformanceCapture() {
|
|
512
|
+
await post('/session/performance/stop', {});
|
|
513
|
+
},
|
|
514
|
+
|
|
515
|
+
streamAppLogCapture(handlers) {
|
|
516
|
+
return tail<SessionLogLine>('applogs', handlers);
|
|
517
|
+
},
|
|
518
|
+
|
|
519
|
+
streamEventCapture(handlers) {
|
|
520
|
+
return tail<SessionEvent>('events', handlers);
|
|
521
|
+
},
|
|
522
|
+
|
|
523
|
+
streamPerformance(handlers) {
|
|
524
|
+
return tail<PerformanceSample>('performance', handlers);
|
|
525
|
+
},
|
|
526
|
+
|
|
527
|
+
getTunnelStatus() {
|
|
528
|
+
return getDestinationTunnelStatus(apiUrl, token);
|
|
529
|
+
},
|
|
530
|
+
|
|
531
|
+
async stopTunnel(tunnelId) {
|
|
532
|
+
await stopDestinationTunnel(apiUrl, token, tunnelId);
|
|
533
|
+
},
|
|
534
|
+
|
|
535
|
+
async screenshot(): Promise<Buffer> {
|
|
536
|
+
const response = await request('/screenshot.jpg', { method: 'GET' });
|
|
537
|
+
return Buffer.from(await response.arrayBuffer());
|
|
538
|
+
},
|
|
539
|
+
|
|
540
|
+
tap(point, options) {
|
|
541
|
+
return post('/tap', { x: point.x, y: point.y, ...(options?.button && { button: options.button }) });
|
|
542
|
+
},
|
|
543
|
+
|
|
544
|
+
typeText(text) {
|
|
545
|
+
return post('/type', { text });
|
|
546
|
+
},
|
|
547
|
+
|
|
548
|
+
pressKey(key, modifiers) {
|
|
549
|
+
return post('/press-key', { key, ...(modifiers?.length && { modifiers }) });
|
|
550
|
+
},
|
|
551
|
+
|
|
552
|
+
scroll({ dx, dy, at }) {
|
|
553
|
+
return post('/scroll', { dx: dx ?? 0, dy: dy ?? 0, ...(at && { x: at.x, y: at.y }) });
|
|
554
|
+
},
|
|
555
|
+
|
|
556
|
+
async restoreSnapshot({
|
|
557
|
+
onProgress,
|
|
558
|
+
...body
|
|
559
|
+
}: MacosSnapshotRestoreOptions): Promise<MacosSnapshotProgress> {
|
|
560
|
+
const response = await request('/snapshot', { method: 'POST', body });
|
|
561
|
+
if (!response.body) throw new Error('POST /snapshot answered without a body');
|
|
562
|
+
let last: MacosSnapshotProgress | undefined;
|
|
563
|
+
for await (const event of readServerSentEvents(response.body)) {
|
|
564
|
+
if (event.event !== 'snapshot') continue;
|
|
565
|
+
last = JSON.parse(event.data) as MacosSnapshotProgress;
|
|
566
|
+
onProgress?.(last);
|
|
567
|
+
}
|
|
568
|
+
if (!last || !['restored', 'skipped', 'failed'].includes(last.phase)) {
|
|
569
|
+
throw new Error(
|
|
570
|
+
`the snapshot stream ended before the restore did (last phase: ${last?.phase ?? 'none'})`,
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
return last;
|
|
574
|
+
},
|
|
575
|
+
|
|
576
|
+
drag(from, to, options) {
|
|
577
|
+
return post('/drag', {
|
|
578
|
+
fromX: from.x,
|
|
579
|
+
fromY: from.y,
|
|
580
|
+
toX: to.x,
|
|
581
|
+
toY: to.y,
|
|
582
|
+
...(options?.durationMs !== undefined && { durationMs: options.durationMs }),
|
|
583
|
+
});
|
|
584
|
+
},
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
MacosInstances.prototype.createClient = MacosInstancesHelpers.prototype.createClient;
|
|
590
|
+
|
|
591
|
+
MacosInstances.prototype.listSessionArtifacts = function (
|
|
592
|
+
this: MacosInstances,
|
|
593
|
+
id: string,
|
|
594
|
+
kind?: SessionArtifactKind,
|
|
595
|
+
options?: RequestOptions,
|
|
596
|
+
): APIPromise<SessionArtifact[]> {
|
|
597
|
+
return this._client.get(path`/v1/macos_instances/${id}/session_artifacts`, {
|
|
598
|
+
query: kind ? { kind } : undefined,
|
|
599
|
+
...options,
|
|
600
|
+
});
|
|
601
|
+
};
|
|
602
|
+
MacosInstances.prototype.listRecordings = function (this: MacosInstances, id, options) {
|
|
603
|
+
return this.listSessionArtifacts(id, 'recording', options);
|
|
604
|
+
};
|
|
605
|
+
MacosInstances.prototype.listAppLogs = function (this: MacosInstances, id, options) {
|
|
606
|
+
return this.listSessionArtifacts(id, 'appLog', options);
|
|
607
|
+
};
|
|
608
|
+
MacosInstances.prototype.listEvents = function (this: MacosInstances, id, options) {
|
|
609
|
+
return this.listSessionArtifacts(id, 'eventLog', options);
|
|
610
|
+
};
|
|
611
|
+
MacosInstances.prototype.listPerformanceCaptures = function (this: MacosInstances, id, options) {
|
|
612
|
+
return this.listSessionArtifacts(id, 'performance', options);
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
/** validateRecordingId refuses an ID the instance would refuse, before anything is sent. */
|
|
616
|
+
function validateRecordingId(recordingId: string): void {
|
|
617
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(recordingId)) {
|
|
618
|
+
throw new Error('recordingId must match ^[a-z0-9][a-z0-9_-]{0,63}$');
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** readServerSentEvents yields the events of a server-sent event stream as they arrive. */
|
|
623
|
+
async function* readServerSentEvents(
|
|
624
|
+
body: ReadableStream<Uint8Array>,
|
|
625
|
+
): AsyncGenerator<{ event: string; data: string }> {
|
|
626
|
+
const decoder = new TextDecoder();
|
|
627
|
+
let buffer = '';
|
|
628
|
+
let event = 'message';
|
|
629
|
+
let data: string[] = [];
|
|
630
|
+
const reader = body.getReader();
|
|
631
|
+
try {
|
|
632
|
+
while (true) {
|
|
633
|
+
const { value, done } = await reader.read();
|
|
634
|
+
if (done) break;
|
|
635
|
+
buffer += decoder.decode(value, { stream: true });
|
|
636
|
+
let newline: number;
|
|
637
|
+
while ((newline = buffer.indexOf('\n')) >= 0) {
|
|
638
|
+
const line = buffer.slice(0, newline).replace(/\r$/, '');
|
|
639
|
+
buffer = buffer.slice(newline + 1);
|
|
640
|
+
if (line === '') {
|
|
641
|
+
if (data.length > 0) yield { event, data: data.join('\n') };
|
|
642
|
+
event = 'message';
|
|
643
|
+
data = [];
|
|
644
|
+
} else if (line.startsWith('event:')) {
|
|
645
|
+
event = line.slice(6).trim();
|
|
646
|
+
} else if (line.startsWith('data:')) {
|
|
647
|
+
data.push(line.slice(5).replace(/^ /, ''));
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (data.length > 0) yield { event, data: data.join('\n') };
|
|
652
|
+
} finally {
|
|
653
|
+
reader.releaseLock();
|
|
654
|
+
}
|
|
655
|
+
}
|