@limrun/api 0.79.0 → 0.79.2
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 +26 -0
- package/destination-tunnel-dialer.d.mts.map +1 -1
- package/destination-tunnel-dialer.d.ts.map +1 -1
- package/destination-tunnel-dialer.js +23 -14
- package/destination-tunnel-dialer.js.map +1 -1
- package/destination-tunnel-dialer.mjs +23 -14
- package/destination-tunnel-dialer.mjs.map +1 -1
- package/internal/app-log-events.d.mts +21 -0
- package/internal/app-log-events.d.mts.map +1 -0
- package/internal/app-log-events.d.ts +21 -0
- package/internal/app-log-events.d.ts.map +1 -0
- package/internal/app-log-events.js +73 -0
- package/internal/app-log-events.js.map +1 -0
- package/internal/app-log-events.mjs +69 -0
- package/internal/app-log-events.mjs.map +1 -0
- package/internal/signaling-transport.d.mts +79 -0
- package/internal/signaling-transport.d.mts.map +1 -0
- package/internal/signaling-transport.d.ts +79 -0
- package/internal/signaling-transport.d.ts.map +1 -0
- package/internal/signaling-transport.js +320 -0
- package/internal/signaling-transport.js.map +1 -0
- package/internal/signaling-transport.mjs +316 -0
- package/internal/signaling-transport.mjs.map +1 -0
- package/ios-client.d.mts +4 -9
- package/ios-client.d.mts.map +1 -1
- package/ios-client.d.ts +4 -9
- package/ios-client.d.ts.map +1 -1
- package/ios-client.js +172 -412
- package/ios-client.js.map +1 -1
- package/ios-client.mjs +173 -413
- package/ios-client.mjs.map +1 -1
- package/log-stream.d.mts +11 -4
- package/log-stream.d.mts.map +1 -1
- package/log-stream.d.ts +11 -4
- package/log-stream.d.ts.map +1 -1
- package/log-stream.js +45 -8
- package/log-stream.js.map +1 -1
- package/log-stream.mjs +45 -8
- package/log-stream.mjs.map +1 -1
- package/package.json +1 -1
- package/resources/macos-instances-helpers.d.mts +12 -0
- package/resources/macos-instances-helpers.d.mts.map +1 -1
- package/resources/macos-instances-helpers.d.ts +12 -0
- package/resources/macos-instances-helpers.d.ts.map +1 -1
- package/resources/macos-instances-helpers.js +118 -141
- package/resources/macos-instances-helpers.js.map +1 -1
- package/resources/macos-instances-helpers.mjs +118 -141
- package/resources/macos-instances-helpers.mjs.map +1 -1
- package/src/destination-tunnel-dialer.ts +23 -14
- package/src/internal/app-log-events.ts +76 -0
- package/src/internal/signaling-transport.ts +454 -0
- package/src/ios-client.ts +193 -471
- package/src/log-stream.ts +54 -11
- package/src/resources/macos-instances-helpers.ts +153 -136
- 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
package/src/ios-client.ts
CHANGED
|
@@ -2,9 +2,8 @@ import os from 'os';
|
|
|
2
2
|
import crypto from 'crypto';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import fs from 'fs';
|
|
5
|
-
import { WebSocket, Data } from 'ws';
|
|
6
5
|
import { EventEmitter } from 'events';
|
|
7
|
-
import { assertPort,
|
|
6
|
+
import { assertPort, startReverseTcpTunnel, type ReverseTunnel } from './tunnel';
|
|
8
7
|
import {
|
|
9
8
|
destinationTunnelDialOptions,
|
|
10
9
|
startDestinationTcpTunnel,
|
|
@@ -36,19 +35,18 @@ import { persistFields, ttlFields, type PersistOption } from './internal/persist
|
|
|
36
35
|
import { streamSessionEntries } from './internal/session-stream';
|
|
37
36
|
import type { SessionLogLine, SessionEvent, PerformanceSample } from './resources/session-artifacts';
|
|
38
37
|
import { LogStream } from './log-stream';
|
|
38
|
+
import {
|
|
39
|
+
openSignalingTransport,
|
|
40
|
+
type ConnectionState,
|
|
41
|
+
type ConnectionStateCallback,
|
|
42
|
+
type SignalingMessage,
|
|
43
|
+
type SignalingTransport,
|
|
44
|
+
} from './internal/signaling-transport';
|
|
39
45
|
|
|
40
46
|
export { type PersistOption } from './internal/persist-option';
|
|
41
47
|
export { LogStream, type LogStreamEvents } from './log-stream';
|
|
42
48
|
|
|
43
|
-
|
|
44
|
-
* Connection state of the instance client
|
|
45
|
-
*/
|
|
46
|
-
export type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'reconnecting';
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Callback function for connection state changes
|
|
50
|
-
*/
|
|
51
|
-
export type ConnectionStateCallback = (state: ConnectionState) => void;
|
|
49
|
+
export { type ConnectionState, type ConnectionStateCallback } from './internal/signaling-transport';
|
|
52
50
|
|
|
53
51
|
const ACTIVE_RECORDING_FILENAME = 'recording.mp4';
|
|
54
52
|
export const REVERSE_TUNNEL_REMOTE_PORT_MIN = 57090;
|
|
@@ -1070,7 +1068,8 @@ export type InstanceClient = {
|
|
|
1070
1068
|
appLogTail: (bundleId: string, lines: number) => Promise<string>;
|
|
1071
1069
|
|
|
1072
1070
|
/**
|
|
1073
|
-
* Stream app logs for a bundle ID
|
|
1071
|
+
* Stream app logs for a bundle ID, one line per event, over the instance's
|
|
1072
|
+
* `/app-logs/stream` server-sent events. The stream closes when the instance ends it.
|
|
1074
1073
|
* @param bundleId Bundle identifier of the app
|
|
1075
1074
|
* @returns LogStream handle (use .stop() to unsubscribe)
|
|
1076
1075
|
*/
|
|
@@ -2162,23 +2161,9 @@ export function streamPerformance(options: PerformanceStreamOptions): () => void
|
|
|
2162
2161
|
* @returns An InstanceClient for controlling the instance
|
|
2163
2162
|
*/
|
|
2164
2163
|
export async function createInstanceClient(options: InstanceClientOptions): Promise<InstanceClient> {
|
|
2165
|
-
const endpointWebSocketUrl = `${options.apiUrl
|
|
2166
|
-
.replace('https://', 'wss://')
|
|
2167
|
-
.replace('http://', 'ws://')}/signaling?token=${options.token}`;
|
|
2168
2164
|
const logLevel = options.logLevel ?? 'info';
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
const maxReconnectDelay = options.maxReconnectDelay ?? 30000;
|
|
2172
|
-
|
|
2173
|
-
let ws: WebSocket | undefined = undefined;
|
|
2174
|
-
let connectionState: ConnectionState = 'connecting';
|
|
2175
|
-
let reconnectAttempts = 0;
|
|
2176
|
-
let reconnectTimeout: NodeJS.Timeout | undefined;
|
|
2177
|
-
let handshakeDeadline: NodeJS.Timeout | undefined;
|
|
2178
|
-
let intentionalDisconnect = false;
|
|
2179
|
-
let lastError: string | undefined;
|
|
2180
|
-
// Centralized pending requests map - handles all request/response patterns
|
|
2181
|
-
const pendingRequests: Map<string, PendingRequest<any>> = new Map();
|
|
2165
|
+
// Set once the signaling socket opens, before any method can run.
|
|
2166
|
+
let transport!: SignalingTransport;
|
|
2182
2167
|
|
|
2183
2168
|
// Simctl uses streaming, so it needs separate handling
|
|
2184
2169
|
const simctlExecutions: Map<string, SimctlExecution> = new Map();
|
|
@@ -2192,8 +2177,6 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
2192
2177
|
const xcrunShimCleanups: Array<() => Promise<void>> = [];
|
|
2193
2178
|
const httpProxyCleanups: Array<() => Promise<void>> = [];
|
|
2194
2179
|
|
|
2195
|
-
const stateChangeCallbacks: Set<ConnectionStateCallback> = new Set();
|
|
2196
|
-
|
|
2197
2180
|
// Logger functions
|
|
2198
2181
|
const logger = {
|
|
2199
2182
|
debug: (...args: any[]) => {
|
|
@@ -2210,52 +2193,11 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
2210
2193
|
},
|
|
2211
2194
|
};
|
|
2212
2195
|
|
|
2213
|
-
const
|
|
2214
|
-
if (connectionState !== newState) {
|
|
2215
|
-
connectionState = newState;
|
|
2216
|
-
logger.debug(`Connection state changed to: ${newState}`);
|
|
2217
|
-
stateChangeCallbacks.forEach((callback) => {
|
|
2218
|
-
try {
|
|
2219
|
-
callback(newState);
|
|
2220
|
-
} catch (err) {
|
|
2221
|
-
logger.error('Error in connection state callback:', err);
|
|
2222
|
-
}
|
|
2223
|
-
});
|
|
2224
|
-
}
|
|
2225
|
-
};
|
|
2226
|
-
|
|
2227
|
-
const failPendingRequests = (reason: string): void => {
|
|
2228
|
-
pendingRequests.forEach((request) => {
|
|
2229
|
-
clearTimeout(request.timeout);
|
|
2230
|
-
request.reject(new Error(reason));
|
|
2231
|
-
});
|
|
2232
|
-
pendingRequests.clear();
|
|
2233
|
-
|
|
2196
|
+
const failExecutions = (reason: string): void => {
|
|
2234
2197
|
simctlExecutions.forEach((execution) => execution._handleError(new Error(reason)));
|
|
2235
2198
|
simctlExecutions.clear();
|
|
2236
2199
|
};
|
|
2237
2200
|
|
|
2238
|
-
const cleanupConnection = (): void => {
|
|
2239
|
-
clearTimeout(handshakeDeadline);
|
|
2240
|
-
if (reconnectTimeout) {
|
|
2241
|
-
clearTimeout(reconnectTimeout);
|
|
2242
|
-
reconnectTimeout = undefined;
|
|
2243
|
-
}
|
|
2244
|
-
if (pingInterval) {
|
|
2245
|
-
clearInterval(pingInterval);
|
|
2246
|
-
pingInterval = undefined;
|
|
2247
|
-
}
|
|
2248
|
-
if (ws) {
|
|
2249
|
-
ws.removeAllListeners();
|
|
2250
|
-
// A retired socket can emit an error when an unfinished handshake is cancelled.
|
|
2251
|
-
ws.on('error', () => {});
|
|
2252
|
-
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
|
|
2253
|
-
ws.close();
|
|
2254
|
-
}
|
|
2255
|
-
ws = undefined;
|
|
2256
|
-
}
|
|
2257
|
-
};
|
|
2258
|
-
|
|
2259
2201
|
const cleanupClientResources = (): void => {
|
|
2260
2202
|
const shimCleanups = xcrunShimCleanups.splice(0);
|
|
2261
2203
|
for (const closeShim of shimCleanups) {
|
|
@@ -2267,11 +2209,6 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
2267
2209
|
}
|
|
2268
2210
|
};
|
|
2269
2211
|
|
|
2270
|
-
const cleanup = (): void => {
|
|
2271
|
-
cleanupConnection();
|
|
2272
|
-
cleanupClientResources();
|
|
2273
|
-
};
|
|
2274
|
-
|
|
2275
2212
|
const registerServerNotification = (
|
|
2276
2213
|
type: string,
|
|
2277
2214
|
notificationId: string,
|
|
@@ -2323,47 +2260,7 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
2323
2260
|
serverNotifications.clear();
|
|
2324
2261
|
};
|
|
2325
2262
|
|
|
2326
|
-
|
|
2327
|
-
const keepAliveSessionId =
|
|
2328
|
-
Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
|
2329
|
-
|
|
2330
|
-
return new Promise<InstanceClient>((resolveConnection, rejectConnection) => {
|
|
2331
|
-
let hasResolved = false;
|
|
2332
|
-
let retriedHandshake = false;
|
|
2333
|
-
|
|
2334
|
-
// Reconnection logic with exponential backoff
|
|
2335
|
-
const scheduleReconnect = (): void => {
|
|
2336
|
-
if (intentionalDisconnect) {
|
|
2337
|
-
logger.debug('Skipping reconnection (intentional disconnect)');
|
|
2338
|
-
return;
|
|
2339
|
-
}
|
|
2340
|
-
|
|
2341
|
-
if (isNonRetryableError(lastError ?? '')) {
|
|
2342
|
-
logger.error(`Skipping reconnection (non-retryable error): ${lastError}`);
|
|
2343
|
-
updateConnectionState('disconnected');
|
|
2344
|
-
clearServerNotifications();
|
|
2345
|
-
return;
|
|
2346
|
-
}
|
|
2347
|
-
|
|
2348
|
-
if (reconnectAttempts >= maxReconnectAttempts) {
|
|
2349
|
-
logger.error(`Max reconnection attempts (${maxReconnectAttempts}) reached. Giving up.`);
|
|
2350
|
-
updateConnectionState('disconnected');
|
|
2351
|
-
clearServerNotifications();
|
|
2352
|
-
return;
|
|
2353
|
-
}
|
|
2354
|
-
|
|
2355
|
-
const currentDelay = Math.min(reconnectDelay * Math.pow(2, reconnectAttempts), maxReconnectDelay);
|
|
2356
|
-
|
|
2357
|
-
reconnectAttempts++;
|
|
2358
|
-
logger.debug(`Scheduling reconnection attempt ${reconnectAttempts} in ${currentDelay}ms...`);
|
|
2359
|
-
updateConnectionState('reconnecting');
|
|
2360
|
-
|
|
2361
|
-
reconnectTimeout = setTimeout(() => {
|
|
2362
|
-
logger.debug(`Attempting to reconnect (attempt ${reconnectAttempts})...`);
|
|
2363
|
-
setupWebSocket();
|
|
2364
|
-
}, currentDelay);
|
|
2365
|
-
};
|
|
2366
|
-
|
|
2263
|
+
{
|
|
2367
2264
|
// Generate unique request ID
|
|
2368
2265
|
const generateId = (): string => {
|
|
2369
2266
|
return `ts-client-${Date.now()}-${Math.random().toString(36).substring(7)}`;
|
|
@@ -2392,43 +2289,12 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
2392
2289
|
return new CommandError(message.error!, source.code, source.written);
|
|
2393
2290
|
};
|
|
2394
2291
|
|
|
2395
|
-
// Generic request sender with timeout and response handling
|
|
2396
2292
|
const sendRequest = <T>(
|
|
2397
2293
|
type: string,
|
|
2398
2294
|
params: Record<string, unknown> = {},
|
|
2399
2295
|
transform?: (message: ServerResponse) => T,
|
|
2400
2296
|
timeoutMs: number = 30000,
|
|
2401
|
-
): Promise<T> =>
|
|
2402
|
-
return new Promise((resolve, reject) => {
|
|
2403
|
-
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
2404
|
-
reject(new Error('WebSocket is not connected or connection is not open.'));
|
|
2405
|
-
return;
|
|
2406
|
-
}
|
|
2407
|
-
|
|
2408
|
-
const id = generateId();
|
|
2409
|
-
const timeout = setTimeout(() => {
|
|
2410
|
-
pendingRequests.delete(id);
|
|
2411
|
-
reject(new Error(`Request ${type} timed out`));
|
|
2412
|
-
}, timeoutMs);
|
|
2413
|
-
|
|
2414
|
-
pendingRequests.set(
|
|
2415
|
-
id,
|
|
2416
|
-
transform ? { resolve, reject, timeout, transform } : { resolve, reject, timeout },
|
|
2417
|
-
);
|
|
2418
|
-
|
|
2419
|
-
const request = { type, id, ...params };
|
|
2420
|
-
logger.debug('Sending request:', redactRequestForDebug(request));
|
|
2421
|
-
|
|
2422
|
-
ws.send(JSON.stringify(request), (err?: Error) => {
|
|
2423
|
-
if (err) {
|
|
2424
|
-
clearTimeout(timeout);
|
|
2425
|
-
pendingRequests.delete(id);
|
|
2426
|
-
logger.error(`Failed to send ${type} request:`, err);
|
|
2427
|
-
reject(err);
|
|
2428
|
-
}
|
|
2429
|
-
});
|
|
2430
|
-
});
|
|
2431
|
-
};
|
|
2297
|
+
): Promise<T> => transport.request<T>(type, params, transform as any, timeoutMs);
|
|
2432
2298
|
|
|
2433
2299
|
const splitAppLogTail = (logs: string): string[] => {
|
|
2434
2300
|
if (logs.length === 0) {
|
|
@@ -2569,278 +2435,6 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
2569
2435
|
}),
|
|
2570
2436
|
};
|
|
2571
2437
|
|
|
2572
|
-
const setupWebSocket = (): void => {
|
|
2573
|
-
cleanupConnection();
|
|
2574
|
-
updateConnectionState('connecting');
|
|
2575
|
-
|
|
2576
|
-
const proxyAgent = nodeProxyTransport.getWebSocketAgent(endpointWebSocketUrl);
|
|
2577
|
-
let opened = false;
|
|
2578
|
-
let handshakeError: Error | undefined;
|
|
2579
|
-
const socket = new WebSocket(endpointWebSocketUrl, proxyAgent ? { agent: proxyAgent } : {});
|
|
2580
|
-
ws = socket;
|
|
2581
|
-
// A socket inactivity timeout allows a slow TLS peer to keep the first command waiting.
|
|
2582
|
-
handshakeDeadline = setTimeout(() => {
|
|
2583
|
-
handshakeError = Object.assign(new Error('Opening handshake has timed out'), { code: 'ETIMEDOUT' });
|
|
2584
|
-
socket.terminate();
|
|
2585
|
-
}, 5000);
|
|
2586
|
-
|
|
2587
|
-
ws.on('message', (data: Data) => {
|
|
2588
|
-
let message: ServerResponse;
|
|
2589
|
-
try {
|
|
2590
|
-
message = JSON.parse(data.toString());
|
|
2591
|
-
} catch (e) {
|
|
2592
|
-
logger.error({ data, error: e }, 'Failed to parse JSON message');
|
|
2593
|
-
return;
|
|
2594
|
-
}
|
|
2595
|
-
|
|
2596
|
-
if (handleAppExit(message) || handleAppHang(message)) {
|
|
2597
|
-
return;
|
|
2598
|
-
}
|
|
2599
|
-
|
|
2600
|
-
// Handle simctl streaming separately (it uses multiple messages per request)
|
|
2601
|
-
if (message.type === 'simctlStream') {
|
|
2602
|
-
const execution = simctlExecutions.get(message.id);
|
|
2603
|
-
if (!execution) {
|
|
2604
|
-
logger.debug(`Received simctl stream for unknown execution: ${message.id}`);
|
|
2605
|
-
return;
|
|
2606
|
-
}
|
|
2607
|
-
if (execution instanceof LldbExecution) {
|
|
2608
|
-
execution._handleStarted();
|
|
2609
|
-
}
|
|
2610
|
-
|
|
2611
|
-
if (message.stdout) {
|
|
2612
|
-
try {
|
|
2613
|
-
execution._handleStdout(Buffer.from(message.stdout, 'base64'));
|
|
2614
|
-
} catch (err) {
|
|
2615
|
-
logger.error('Failed to decode stdout data:', err);
|
|
2616
|
-
}
|
|
2617
|
-
}
|
|
2618
|
-
|
|
2619
|
-
if (message.stderr) {
|
|
2620
|
-
try {
|
|
2621
|
-
execution._handleStderr(Buffer.from(message.stderr, 'base64'));
|
|
2622
|
-
} catch (err) {
|
|
2623
|
-
logger.error('Failed to decode stderr data:', err);
|
|
2624
|
-
}
|
|
2625
|
-
}
|
|
2626
|
-
|
|
2627
|
-
if (message.exitCode !== undefined) {
|
|
2628
|
-
logger.debug(`Simctl execution ${message.id} completed with exit code ${message.exitCode}`);
|
|
2629
|
-
// Forget the execution first: an exit listener may disconnect, and disconnecting
|
|
2630
|
-
// fails every execution still tracked, including this one.
|
|
2631
|
-
simctlExecutions.delete(message.id);
|
|
2632
|
-
execution._handleExit(message.exitCode);
|
|
2633
|
-
}
|
|
2634
|
-
return;
|
|
2635
|
-
}
|
|
2636
|
-
|
|
2637
|
-
// Handle all other request/response patterns generically
|
|
2638
|
-
const request = pendingRequests.get(message.id);
|
|
2639
|
-
if (!request) {
|
|
2640
|
-
logger.debug(`Received response for unknown or already handled request: ${message.id}`);
|
|
2641
|
-
return;
|
|
2642
|
-
}
|
|
2643
|
-
|
|
2644
|
-
clearTimeout(request.timeout);
|
|
2645
|
-
pendingRequests.delete(message.id);
|
|
2646
|
-
|
|
2647
|
-
if (message.error) {
|
|
2648
|
-
logger.debug(`Server error for ${message.type}: ${message.error}`);
|
|
2649
|
-
request.reject(commandError(message));
|
|
2650
|
-
return;
|
|
2651
|
-
}
|
|
2652
|
-
|
|
2653
|
-
// Use handler to transform response, or resolve with raw message
|
|
2654
|
-
const handler = request.transform ?? responseHandlers[message.type];
|
|
2655
|
-
if (handler) {
|
|
2656
|
-
try {
|
|
2657
|
-
request.resolve(handler(message));
|
|
2658
|
-
} catch (err) {
|
|
2659
|
-
request.reject(err as Error);
|
|
2660
|
-
}
|
|
2661
|
-
} else {
|
|
2662
|
-
logger.warn('Received unexpected message type:', message.type);
|
|
2663
|
-
request.resolve(message);
|
|
2664
|
-
}
|
|
2665
|
-
});
|
|
2666
|
-
|
|
2667
|
-
ws.on('error', (err: Error) => {
|
|
2668
|
-
lastError = err.message;
|
|
2669
|
-
logger.error('WebSocket error:', err.message);
|
|
2670
|
-
if (!opened) handshakeError ??= err;
|
|
2671
|
-
});
|
|
2672
|
-
|
|
2673
|
-
ws.on('close', () => {
|
|
2674
|
-
clearTimeout(handshakeDeadline);
|
|
2675
|
-
if (pingInterval) {
|
|
2676
|
-
clearInterval(pingInterval);
|
|
2677
|
-
pingInterval = undefined;
|
|
2678
|
-
}
|
|
2679
|
-
|
|
2680
|
-
const shouldReconnect =
|
|
2681
|
-
!intentionalDisconnect &&
|
|
2682
|
-
!isNonRetryableError(lastError ?? '') &&
|
|
2683
|
-
connectionState !== 'disconnected';
|
|
2684
|
-
updateConnectionState('disconnected');
|
|
2685
|
-
|
|
2686
|
-
logger.debug('Disconnected from server.');
|
|
2687
|
-
|
|
2688
|
-
failPendingRequests('Connection closed');
|
|
2689
|
-
|
|
2690
|
-
if (!hasResolved) {
|
|
2691
|
-
const err = handshakeError ?? new Error('Connection closed before the client was ready');
|
|
2692
|
-
// Retry only the opening handshake. Once open, deviceInfo owns its failure.
|
|
2693
|
-
const code = (err as NodeJS.ErrnoException).code;
|
|
2694
|
-
const transient =
|
|
2695
|
-
['ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN'].includes(
|
|
2696
|
-
code ?? '',
|
|
2697
|
-
) ||
|
|
2698
|
-
/^(Opening handshake has timed out|socket hang up|Unexpected server response: 50[234])$/.test(
|
|
2699
|
-
err.message,
|
|
2700
|
-
);
|
|
2701
|
-
if (!opened && !retriedHandshake && maxReconnectAttempts > 0 && transient) {
|
|
2702
|
-
retriedHandshake = true;
|
|
2703
|
-
updateConnectionState('reconnecting');
|
|
2704
|
-
reconnectTimeout = setTimeout(setupWebSocket, 100 + Math.floor(Math.random() * 151));
|
|
2705
|
-
} else {
|
|
2706
|
-
cleanupConnection();
|
|
2707
|
-
rejectConnection(err);
|
|
2708
|
-
}
|
|
2709
|
-
return;
|
|
2710
|
-
}
|
|
2711
|
-
if (shouldReconnect) {
|
|
2712
|
-
scheduleReconnect();
|
|
2713
|
-
} else if (isNonRetryableError(lastError ?? '')) {
|
|
2714
|
-
logger.error(`Closing connection due to non-retryable error: ${lastError}`);
|
|
2715
|
-
cleanup();
|
|
2716
|
-
updateConnectionState('disconnected');
|
|
2717
|
-
failPendingRequests('Non-retryable error');
|
|
2718
|
-
clearServerNotifications();
|
|
2719
|
-
logger.debug('Non-retryable error. Closing connection.');
|
|
2720
|
-
}
|
|
2721
|
-
});
|
|
2722
|
-
|
|
2723
|
-
ws.on('open', async () => {
|
|
2724
|
-
clearTimeout(handshakeDeadline);
|
|
2725
|
-
opened = true;
|
|
2726
|
-
logger.debug('WebSocket connected');
|
|
2727
|
-
reconnectAttempts = 0;
|
|
2728
|
-
lastError = undefined;
|
|
2729
|
-
updateConnectionState('connected');
|
|
2730
|
-
|
|
2731
|
-
pingInterval = setInterval(() => {
|
|
2732
|
-
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
2733
|
-
(ws as any).ping();
|
|
2734
|
-
}
|
|
2735
|
-
}, 30_000);
|
|
2736
|
-
|
|
2737
|
-
if (!hasResolved) {
|
|
2738
|
-
try {
|
|
2739
|
-
// Fetch device info before resolving connection
|
|
2740
|
-
cachedDeviceInfo = await fetchDeviceInfo();
|
|
2741
|
-
logger.debug('Device info fetched:', cachedDeviceInfo);
|
|
2742
|
-
} catch (err) {
|
|
2743
|
-
logger.error('Failed to fetch device info:', err);
|
|
2744
|
-
cleanupConnection();
|
|
2745
|
-
updateConnectionState('disconnected');
|
|
2746
|
-
rejectConnection(err as Error);
|
|
2747
|
-
return;
|
|
2748
|
-
}
|
|
2749
|
-
|
|
2750
|
-
hasResolved = true;
|
|
2751
|
-
resolveConnection({
|
|
2752
|
-
screenshot,
|
|
2753
|
-
elementTree,
|
|
2754
|
-
elementTreeRaw,
|
|
2755
|
-
readElementTree,
|
|
2756
|
-
focusedElement,
|
|
2757
|
-
tap,
|
|
2758
|
-
tapWithScreenSize,
|
|
2759
|
-
tapElement,
|
|
2760
|
-
incrementElement,
|
|
2761
|
-
decrementElement,
|
|
2762
|
-
setElementValue,
|
|
2763
|
-
typeText,
|
|
2764
|
-
pressKey,
|
|
2765
|
-
toggleKeyboard,
|
|
2766
|
-
launchApp,
|
|
2767
|
-
terminateApp,
|
|
2768
|
-
watchApp,
|
|
2769
|
-
monitorApp,
|
|
2770
|
-
appLogTail,
|
|
2771
|
-
streamAppLog,
|
|
2772
|
-
streamSyslog,
|
|
2773
|
-
listApps,
|
|
2774
|
-
openUrl,
|
|
2775
|
-
installApp,
|
|
2776
|
-
saveKeychain,
|
|
2777
|
-
restoreKeychain,
|
|
2778
|
-
resetKeychain,
|
|
2779
|
-
setPermission,
|
|
2780
|
-
getPermission,
|
|
2781
|
-
restartServices,
|
|
2782
|
-
setOrientation,
|
|
2783
|
-
getFoldState,
|
|
2784
|
-
screenshotDisplay,
|
|
2785
|
-
tapDisplay,
|
|
2786
|
-
setDuoOrientation,
|
|
2787
|
-
setHingeAngle,
|
|
2788
|
-
scroll,
|
|
2789
|
-
performActions,
|
|
2790
|
-
startRecording,
|
|
2791
|
-
stopRecording,
|
|
2792
|
-
startRecordingSession,
|
|
2793
|
-
stopRecordingSession,
|
|
2794
|
-
startAppLogCapture,
|
|
2795
|
-
stopAppLogCapture,
|
|
2796
|
-
startEventCapture,
|
|
2797
|
-
stopEventCapture,
|
|
2798
|
-
streamAppLogCapture,
|
|
2799
|
-
streamEventCapture,
|
|
2800
|
-
startPerformanceCapture,
|
|
2801
|
-
stopPerformanceCapture,
|
|
2802
|
-
streamPerformance: streamClientPerformance,
|
|
2803
|
-
playOnMicrophone,
|
|
2804
|
-
stopMicrophonePlayback,
|
|
2805
|
-
microphoneStatus,
|
|
2806
|
-
keepAlive,
|
|
2807
|
-
syncApp,
|
|
2808
|
-
setStoreKitConfig,
|
|
2809
|
-
addCaCertificate,
|
|
2810
|
-
setBlockedDomains,
|
|
2811
|
-
getBlockedDomains,
|
|
2812
|
-
clearStoreKitConfig,
|
|
2813
|
-
discoverStoreKitConfig,
|
|
2814
|
-
softReset,
|
|
2815
|
-
startReverseTunnel,
|
|
2816
|
-
startTunnel,
|
|
2817
|
-
getTunnelStatus,
|
|
2818
|
-
stopTunnel,
|
|
2819
|
-
targetHttpPortUrl,
|
|
2820
|
-
startHttpProxy,
|
|
2821
|
-
startForwardHttpProxy,
|
|
2822
|
-
disconnect,
|
|
2823
|
-
getConnectionState,
|
|
2824
|
-
onConnectionStateChange,
|
|
2825
|
-
simctl,
|
|
2826
|
-
lldb,
|
|
2827
|
-
xcrun,
|
|
2828
|
-
startXcrunShim,
|
|
2829
|
-
xcodebuild,
|
|
2830
|
-
pushFile,
|
|
2831
|
-
pullFile,
|
|
2832
|
-
listFiles,
|
|
2833
|
-
deleteFile,
|
|
2834
|
-
setCameraVideo,
|
|
2835
|
-
clearCameraVideo,
|
|
2836
|
-
lsof,
|
|
2837
|
-
deviceInfo: cachedDeviceInfo,
|
|
2838
|
-
getDeviceInfo,
|
|
2839
|
-
});
|
|
2840
|
-
}
|
|
2841
|
-
});
|
|
2842
|
-
};
|
|
2843
|
-
|
|
2844
2438
|
// ========================================================================
|
|
2845
2439
|
// Client Methods - using centralized sendRequest
|
|
2846
2440
|
// ========================================================================
|
|
@@ -3209,15 +2803,14 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
3209
2803
|
};
|
|
3210
2804
|
|
|
3211
2805
|
const streamAppLog = (bundleId: string): LogStream => {
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
return new LogStream(endpointWebSocketUrl, subscribeMessage, 'streamAppLogTerminate', id);
|
|
2806
|
+
// The instance serves app logs as server-sent events; appLogTail stays on signaling.
|
|
2807
|
+
return new LogStream({ apiUrl: options.apiUrl, token: options.token, bundleId });
|
|
3215
2808
|
};
|
|
3216
2809
|
|
|
3217
2810
|
const streamSyslog = (): LogStream => {
|
|
3218
2811
|
const id = generateId();
|
|
3219
2812
|
const subscribeMessage = { type: 'streamSyslog', id };
|
|
3220
|
-
return new LogStream(
|
|
2813
|
+
return new LogStream(transport.url, subscribeMessage, 'streamSyslogTerminate', id);
|
|
3221
2814
|
};
|
|
3222
2815
|
|
|
3223
2816
|
const listApps = (): Promise<InstalledApp[]> => {
|
|
@@ -3479,17 +3072,7 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
3479
3072
|
return sendRequest<IosMicrophoneStatus>('microphoneStatus');
|
|
3480
3073
|
};
|
|
3481
3074
|
|
|
3482
|
-
const keepAlive = (): void =>
|
|
3483
|
-
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
3484
|
-
return;
|
|
3485
|
-
}
|
|
3486
|
-
ws.send(
|
|
3487
|
-
JSON.stringify({
|
|
3488
|
-
type: 'keepAlive',
|
|
3489
|
-
sessionId: keepAliveSessionId,
|
|
3490
|
-
}),
|
|
3491
|
-
);
|
|
3492
|
-
};
|
|
3075
|
+
const keepAlive = (): void => transport.keepAlive();
|
|
3493
3076
|
|
|
3494
3077
|
const syncApp: InstanceClient['syncApp'] = async (
|
|
3495
3078
|
localAppBundlePath: string,
|
|
@@ -3601,7 +3184,7 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
3601
3184
|
};
|
|
3602
3185
|
|
|
3603
3186
|
// Cached device info, populated during connection
|
|
3604
|
-
let cachedDeviceInfo
|
|
3187
|
+
let cachedDeviceInfo!: DeviceInfo;
|
|
3605
3188
|
|
|
3606
3189
|
/** Tracks a streamed command, sends its request, and returns the handle. */
|
|
3607
3190
|
const startExecution = <E extends SimctlExecution>(
|
|
@@ -3625,7 +3208,7 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
3625
3208
|
}
|
|
3626
3209
|
|
|
3627
3210
|
// Send request asynchronously
|
|
3628
|
-
if (!
|
|
3211
|
+
if (!transport.isOpen()) {
|
|
3629
3212
|
// Defer error to next tick to allow caller to attach listeners
|
|
3630
3213
|
process.nextTick(() => {
|
|
3631
3214
|
simctlExecutions.delete(id);
|
|
@@ -3636,7 +3219,7 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
3636
3219
|
|
|
3637
3220
|
// stdin can carry secrets such as one-time codes, so it stays out of the log.
|
|
3638
3221
|
logger.debug(`Sending ${request.type} request:`, { ...request, stdin: undefined });
|
|
3639
|
-
|
|
3222
|
+
transport.send(request as unknown as Record<string, unknown>, (err?: Error) => {
|
|
3640
3223
|
if (err) {
|
|
3641
3224
|
logger.error(`Failed to send ${request.type} request:`, err);
|
|
3642
3225
|
simctlExecutions.delete(id);
|
|
@@ -3677,24 +3260,19 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
3677
3260
|
const lldb = (args: string[], opts: LldbOptions = {}): LldbExecution => {
|
|
3678
3261
|
const id = generateId();
|
|
3679
3262
|
const sendInput = (data: Buffer | undefined, close: boolean, sequence: number) => {
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
...(close && { close }),
|
|
3688
|
-
}),
|
|
3689
|
-
);
|
|
3263
|
+
transport.send({
|
|
3264
|
+
type: 'lldbInput',
|
|
3265
|
+
id,
|
|
3266
|
+
sequence,
|
|
3267
|
+
...(data && { data: data.toString('base64') }),
|
|
3268
|
+
...(close && { close }),
|
|
3269
|
+
});
|
|
3690
3270
|
};
|
|
3691
3271
|
const execution: LldbExecution = new LldbExecution(() => {
|
|
3692
3272
|
// The session stays tracked: the instance answers with the exit of LLDB, which is what
|
|
3693
3273
|
// ends `wait()`. A session dropped without `end` would otherwise keep the app stopped.
|
|
3694
3274
|
if (!execution.isRunning) return;
|
|
3695
|
-
if (
|
|
3696
|
-
ws.send(JSON.stringify({ type: 'simctlTerminate', id }));
|
|
3697
|
-
} else {
|
|
3275
|
+
if (!transport.send({ type: 'simctlTerminate', id })) {
|
|
3698
3276
|
// Without a connection the instance has already ended the session and cannot say so.
|
|
3699
3277
|
simctlExecutions.delete(id);
|
|
3700
3278
|
execution._handleExit(143);
|
|
@@ -4019,25 +3597,169 @@ export async function createInstanceClient(options: InstanceClientOptions): Prom
|
|
|
4019
3597
|
return proxy.port;
|
|
4020
3598
|
};
|
|
4021
3599
|
|
|
4022
|
-
const disconnect = (): void =>
|
|
4023
|
-
intentionalDisconnect = true;
|
|
4024
|
-
cleanup();
|
|
4025
|
-
updateConnectionState('disconnected');
|
|
4026
|
-
failPendingRequests('Intentional disconnect');
|
|
4027
|
-
clearServerNotifications();
|
|
4028
|
-
logger.debug('Intentionally disconnected from WebSocket.');
|
|
4029
|
-
};
|
|
3600
|
+
const disconnect = (): void => transport.disconnect();
|
|
4030
3601
|
|
|
4031
|
-
const getConnectionState = (): ConnectionState =>
|
|
4032
|
-
return connectionState;
|
|
4033
|
-
};
|
|
3602
|
+
const getConnectionState = (): ConnectionState => transport.getConnectionState();
|
|
4034
3603
|
|
|
4035
|
-
const onConnectionStateChange = (callback: ConnectionStateCallback): (() => void) =>
|
|
4036
|
-
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
3604
|
+
const onConnectionStateChange = (callback: ConnectionStateCallback): (() => void) =>
|
|
3605
|
+
transport.onConnectionStateChange(callback);
|
|
3606
|
+
|
|
3607
|
+
transport = await openSignalingTransport({
|
|
3608
|
+
apiUrl: options.apiUrl,
|
|
3609
|
+
token: options.token,
|
|
3610
|
+
logger,
|
|
3611
|
+
...(options.maxReconnectAttempts !== undefined && {
|
|
3612
|
+
maxReconnectAttempts: options.maxReconnectAttempts,
|
|
3613
|
+
}),
|
|
3614
|
+
...(options.reconnectDelay !== undefined && { reconnectDelay: options.reconnectDelay }),
|
|
3615
|
+
...(options.maxReconnectDelay !== undefined && { maxReconnectDelay: options.maxReconnectDelay }),
|
|
3616
|
+
responseHandlers: responseHandlers as Record<string, (message: SignalingMessage) => unknown>,
|
|
3617
|
+
replyError: (message) => commandError(message as unknown as ServerResponse),
|
|
3618
|
+
redactRequest: redactRequestForDebug,
|
|
3619
|
+
handleMessage: (signal) => {
|
|
3620
|
+
const message = signal as unknown as ServerResponse;
|
|
3621
|
+
if (handleAppExit(message) || handleAppHang(message)) {
|
|
3622
|
+
return true;
|
|
3623
|
+
}
|
|
3624
|
+
|
|
3625
|
+
// Handle simctl streaming separately (it uses multiple messages per request)
|
|
3626
|
+
if (message.type === 'simctlStream') {
|
|
3627
|
+
const execution = simctlExecutions.get(message.id);
|
|
3628
|
+
if (!execution) {
|
|
3629
|
+
logger.debug(`Received simctl stream for unknown execution: ${message.id}`);
|
|
3630
|
+
return true;
|
|
3631
|
+
}
|
|
3632
|
+
if (execution instanceof LldbExecution) {
|
|
3633
|
+
execution._handleStarted();
|
|
3634
|
+
}
|
|
3635
|
+
|
|
3636
|
+
if (message.stdout) {
|
|
3637
|
+
try {
|
|
3638
|
+
execution._handleStdout(Buffer.from(message.stdout, 'base64'));
|
|
3639
|
+
} catch (err) {
|
|
3640
|
+
logger.error('Failed to decode stdout data:', err);
|
|
3641
|
+
}
|
|
3642
|
+
}
|
|
3643
|
+
|
|
3644
|
+
if (message.stderr) {
|
|
3645
|
+
try {
|
|
3646
|
+
execution._handleStderr(Buffer.from(message.stderr, 'base64'));
|
|
3647
|
+
} catch (err) {
|
|
3648
|
+
logger.error('Failed to decode stderr data:', err);
|
|
3649
|
+
}
|
|
3650
|
+
}
|
|
3651
|
+
|
|
3652
|
+
if (message.exitCode !== undefined) {
|
|
3653
|
+
logger.debug(`Simctl execution ${message.id} completed with exit code ${message.exitCode}`);
|
|
3654
|
+
// Forget the execution first: an exit listener may disconnect, and disconnecting
|
|
3655
|
+
// fails every execution still tracked, including this one.
|
|
3656
|
+
simctlExecutions.delete(message.id);
|
|
3657
|
+
execution._handleExit(message.exitCode);
|
|
3658
|
+
}
|
|
3659
|
+
return true;
|
|
3660
|
+
}
|
|
3661
|
+
return false;
|
|
3662
|
+
},
|
|
3663
|
+
onConnectionLost: failExecutions,
|
|
3664
|
+
onClosed: () => {
|
|
3665
|
+
cleanupClientResources();
|
|
3666
|
+
clearServerNotifications();
|
|
3667
|
+
},
|
|
3668
|
+
onFirstOpen: async (opened) => {
|
|
3669
|
+
transport = opened;
|
|
3670
|
+
cachedDeviceInfo = await fetchDeviceInfo();
|
|
3671
|
+
logger.debug('Device info fetched:', cachedDeviceInfo);
|
|
3672
|
+
},
|
|
3673
|
+
});
|
|
3674
|
+
|
|
3675
|
+
return {
|
|
3676
|
+
screenshot,
|
|
3677
|
+
elementTree,
|
|
3678
|
+
elementTreeRaw,
|
|
3679
|
+
focusedElement,
|
|
3680
|
+
readElementTree,
|
|
3681
|
+
tap,
|
|
3682
|
+
tapWithScreenSize,
|
|
3683
|
+
tapElement,
|
|
3684
|
+
incrementElement,
|
|
3685
|
+
decrementElement,
|
|
3686
|
+
setElementValue,
|
|
3687
|
+
typeText,
|
|
3688
|
+
pressKey,
|
|
3689
|
+
toggleKeyboard,
|
|
3690
|
+
launchApp,
|
|
3691
|
+
terminateApp,
|
|
3692
|
+
watchApp,
|
|
3693
|
+
monitorApp,
|
|
3694
|
+
appLogTail,
|
|
3695
|
+
streamAppLog,
|
|
3696
|
+
streamSyslog,
|
|
3697
|
+
listApps,
|
|
3698
|
+
openUrl,
|
|
3699
|
+
installApp,
|
|
3700
|
+
saveKeychain,
|
|
3701
|
+
restoreKeychain,
|
|
3702
|
+
resetKeychain,
|
|
3703
|
+
setPermission,
|
|
3704
|
+
getPermission,
|
|
3705
|
+
restartServices,
|
|
3706
|
+
setOrientation,
|
|
3707
|
+
getFoldState,
|
|
3708
|
+
screenshotDisplay,
|
|
3709
|
+
tapDisplay,
|
|
3710
|
+
setDuoOrientation,
|
|
3711
|
+
setHingeAngle,
|
|
3712
|
+
scroll,
|
|
3713
|
+
performActions,
|
|
3714
|
+
startRecording,
|
|
3715
|
+
stopRecording,
|
|
3716
|
+
startRecordingSession,
|
|
3717
|
+
stopRecordingSession,
|
|
3718
|
+
startAppLogCapture,
|
|
3719
|
+
stopAppLogCapture,
|
|
3720
|
+
startEventCapture,
|
|
3721
|
+
stopEventCapture,
|
|
3722
|
+
streamAppLogCapture,
|
|
3723
|
+
streamEventCapture,
|
|
3724
|
+
startPerformanceCapture,
|
|
3725
|
+
stopPerformanceCapture,
|
|
3726
|
+
streamPerformance: streamClientPerformance,
|
|
3727
|
+
playOnMicrophone,
|
|
3728
|
+
stopMicrophonePlayback,
|
|
3729
|
+
microphoneStatus,
|
|
3730
|
+
keepAlive,
|
|
3731
|
+
syncApp,
|
|
3732
|
+
setStoreKitConfig,
|
|
3733
|
+
addCaCertificate,
|
|
3734
|
+
setBlockedDomains,
|
|
3735
|
+
getBlockedDomains,
|
|
3736
|
+
clearStoreKitConfig,
|
|
3737
|
+
discoverStoreKitConfig,
|
|
3738
|
+
softReset,
|
|
3739
|
+
startReverseTunnel,
|
|
3740
|
+
startTunnel,
|
|
3741
|
+
getTunnelStatus,
|
|
3742
|
+
stopTunnel,
|
|
3743
|
+
targetHttpPortUrl,
|
|
3744
|
+
startHttpProxy,
|
|
3745
|
+
startForwardHttpProxy,
|
|
3746
|
+
disconnect,
|
|
3747
|
+
getConnectionState,
|
|
3748
|
+
onConnectionStateChange,
|
|
3749
|
+
simctl,
|
|
3750
|
+
lldb,
|
|
3751
|
+
xcrun,
|
|
3752
|
+
startXcrunShim,
|
|
3753
|
+
xcodebuild,
|
|
3754
|
+
pushFile,
|
|
3755
|
+
pullFile,
|
|
3756
|
+
listFiles,
|
|
3757
|
+
deleteFile,
|
|
3758
|
+
setCameraVideo,
|
|
3759
|
+
clearCameraVideo,
|
|
3760
|
+
lsof,
|
|
3761
|
+
deviceInfo: cachedDeviceInfo,
|
|
3762
|
+
getDeviceInfo,
|
|
4040
3763
|
};
|
|
4041
|
-
|
|
4042
|
-
});
|
|
3764
|
+
}
|
|
4043
3765
|
}
|