diff --git a/src/hermes/hermes-cdp.test.ts b/src/hermes/hermes-cdp.test.ts index 6a77300..bb3523f 100644 --- a/src/hermes/hermes-cdp.test.ts +++ b/src/hermes/hermes-cdp.test.ts @@ -729,7 +729,7 @@ describe('runHermesCdp', () => { expect(result.message).toContain('timed out'); }); - it('user-method timeout → HERMES_CONNECTION_FAILED via finally close', async () => { + it('user-method timeout → HERMES_TIMEOUT and closes the socket', async () => { vi.useFakeTimers(); MockWebSocket.responseFactory = (request) => request.id === 1 ? defaultResponseFactory(request) : undefined; @@ -740,7 +740,8 @@ describe('runHermesCdp', () => { await vi.advanceTimersByTimeAsync(1_000); const result = await resultPromise; - expect(result.ok).toBe(false); + expectError(result, HERMES_TIMEOUT); + expect(result.message).toContain('timed out'); expect(socketAt(0).readyState).toBe(MockWebSocket.closed); }); diff --git a/src/hermes/hermes-cdp.ts b/src/hermes/hermes-cdp.ts index 1375547..f74270f 100644 --- a/src/hermes/hermes-cdp.ts +++ b/src/hermes/hermes-cdp.ts @@ -1,3 +1,8 @@ +// `hermes-client.ts` imports this module's discovery and socket helpers, so the +// two modules import each other. The cycle is safe: `hermes-client.ts` reads +// those bindings only while connecting, never during module evaluation. +import { HermesClient } from './hermes-client.js'; + /** * Pure Hermes Chrome DevTools Protocol (CDP) core for `@metamask/device-mcp`. * @@ -105,20 +110,33 @@ type CdpSuccessResponse = { result?: unknown; }; +/** + * A CDP-level error payload. + */ +export type HermesCdpErrorInfo = { + /** The CDP error message. */ + message?: string; + /** The CDP error code. */ + code?: number; + /** Optional structured error details. */ + data?: unknown; +}; + type CdpErrorResponse = { id: number; - error: { - message?: string; - code?: number; - data?: unknown; - }; + error: HermesCdpErrorInfo; }; type TargetSelection = | { ok: true; target: HermesTarget } | { ok: false; code: string; message: string }; -type ProbeResult = { ok: true } | { ok: false; code: string; message: string }; +/** + * Result of the Hermes identity probe. + */ +export type HermesIdentityProbeResult = + | { ok: true } + | { ok: false; code: string; message: string }; /** * No Hermes debug target matched the expected appId (after synthetic-title and @@ -174,6 +192,12 @@ export const HERMES_CDP_FAILED = 'HERMES_CDP_FAILED'; */ export const HERMES_WEBSOCKET_UNAVAILABLE = 'HERMES_WEBSOCKET_UNAVAILABLE'; +/** + * A pending CDP call was aborted through its `AbortSignal`. The pending entry is + * removed, so a late response is ignored. + */ +export const HERMES_ABORTED = 'HERMES_ABORTED'; + /** * CDP methods blocked for safety. Ported VERBATIM from the reference — do not * weaken. @@ -216,6 +240,46 @@ export const IDENTITY_PROBE_EXPR = `(function () { } })();`; +/** + * Returns the fail-closed result for a CDP method in the blocked set. + * + * @param method - The requested CDP method. + * @returns The `HERMES_BLOCKED_METHOD` failure, or undefined when not blocked. + */ +export function createBlockedMethodResult( + method: string, +): HermesCdpResult | undefined { + if (!HERMES_BLOCKED_METHODS.has(method)) { + return undefined; + } + return { + ok: false, + code: HERMES_BLOCKED_METHOD, + message: + `CDP method "${method}" is blocked for safety. ` + + `Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`, + }; +} + +/** + * Returns the failure result for a runtime without a global `WebSocket`. + * + * @returns The `HERMES_WEBSOCKET_UNAVAILABLE` failure. + */ +export function websocketUnavailableResult(): { + ok: false; + code: string; + message: string; +} { + return { + ok: false, + code: HERMES_WEBSOCKET_UNAVAILABLE, + message: + 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' + + 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).', + }; +} + /** * Orchestrates a single verified Hermes CDP command end to end. * @@ -225,6 +289,9 @@ export const IDENTITY_PROBE_EXPR = `(function () { * supplies the resolved port/appId/pin and persists the pin — this function is * pure with respect to session state. * + * Implemented on {@link HermesClient}: one client, one connect, one send, then + * close. Auto-reconnect is disabled because a one-shot call owns the socket. + * * @param input - Method, params, timeout, resolved port/appId/pin, and the pin * persistence callback. See {@link RunHermesCdpInput}. * @returns A discriminated {@link HermesCdpResult}. @@ -232,65 +299,24 @@ export const IDENTITY_PROBE_EXPR = `(function () { export async function runHermesCdp( input: RunHermesCdpInput, ): Promise { - if (HERMES_BLOCKED_METHODS.has(input.method)) { - return { - ok: false, - code: HERMES_BLOCKED_METHOD, - message: - `CDP method "${input.method}" is blocked for safety. ` + - `Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`, - }; - } - - if (typeof WebSocket !== 'function') { - return { - ok: false, - code: HERMES_WEBSOCKET_UNAVAILABLE, - message: - 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' + - 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).', - }; - } + const client = new HermesClient({ + metroPort: input.metroPort, + appId: input.appId, + origin: input.origin, + pinnedDeviceId: input.pinnedDeviceId, + onPin: input.onPin, + reconnect: { maxAttempts: 0 }, + // The one-shot path must not pay for (or expose) context tracking, and its + // wire traffic stays probe + one method. + trackContexts: false, + }); try { - const targets = await fetchDiscoveryTargets( - input.metroPort, - input.timeoutMs, - ); - const selection = selectHermesTarget( - targets, - input.appId, - input.pinnedDeviceId, - ); - if (!selection.ok) { - return { ok: false, code: selection.code, message: selection.message }; - } - - const validation = validateWebSocketUrl( - selection.target.webSocketDebuggerUrl, - input.metroPort, - ); - if (!validation.ok) { - return { - ok: false, - code: HERMES_INVALID_WS_URL, - message: validation.message, - }; - } - - return await executeVerifiedCdpCommand( - selection.target, - input, - input.pinnedDeviceId, - input.onPin, - ); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - return { - ok: false, - code: HERMES_CONNECTION_FAILED, - message: `Hermes CDP connection failed: ${message}`, - }; + return await client.send(input.method, input.params, { + timeoutMs: input.timeoutMs, + }); + } finally { + client.close(); } } @@ -501,8 +527,9 @@ export function validateWebSocketUrl( * @param webSocketUrl - The target's WebSocket URL. * @param override - An explicit HTTP(S) origin, if configured. * @returns The HTTP(S) origin to send in the handshake. + * @throws When the explicit override is not a bare HTTP(S) origin. */ -function resolveWebSocketOrigin( +export function resolveWebSocketOrigin( webSocketUrl: string, override: string | undefined, ): string { @@ -562,13 +589,7 @@ export async function executeVerifiedCdpCommand( }; } if (typeof WebSocket !== 'function') { - return { - ok: false, - code: HERMES_WEBSOCKET_UNAVAILABLE, - message: - 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' + - 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).', - }; + return websocketUnavailableResult(); } // Node's WebSocket supports this headers overload on Node 20 (with the @@ -616,7 +637,7 @@ export async function executeVerifiedCdpCommand( ok: false, code: HERMES_CDP_FAILED, message: `Hermes CDP "${input.method}" failed: ${formatCdpError( - response, + response.error, )}`, }; } @@ -635,13 +656,13 @@ export async function executeVerifiedCdpCommand( * @param socket - The open target WebSocket. * @param timeoutMs - Round-trip timeout in milliseconds. * @param id - The CDP message id to use for this probe. - * @returns A {@link ProbeResult}. + * @returns A {@link HermesIdentityProbeResult}. */ -async function runIdentityProbe( +export async function runIdentityProbe( socket: WebSocket, timeoutMs: number, id: number, -): Promise { +): Promise { socket.send( JSON.stringify({ id, @@ -673,7 +694,7 @@ async function runIdentityProbe( return { ok: false, code: HERMES_NOT_VERIFIED, - message: `Identity probe failed: ${formatCdpError(response)}`, + message: `Identity probe failed: ${formatCdpError(response.error)}`, }; } @@ -786,7 +807,7 @@ async function sendUserMethod( * @param timeoutMs - Connection timeout in milliseconds. * @returns A promise that resolves when the socket is open. */ -async function waitForSocketOpen( +export async function waitForSocketOpen( socket: WebSocket, timeoutMs: number, ): Promise { @@ -925,18 +946,18 @@ function isCdpErrorResponse( } /** - * Formats a CDP error response into a single human-readable line. + * Formats a CDP error payload into a single human-readable line. * - * @param response - The CDP error response. + * @param error - The CDP error payload. * @returns A combined message including code and data when present. */ -function formatCdpError(response: CdpErrorResponse): string { - const parts = [response.error.message ?? 'Unknown CDP error']; - if (typeof response.error.code === 'number') { - parts.push(`code ${response.error.code}`); +export function formatCdpError(error: HermesCdpErrorInfo): string { + const parts = [error.message ?? 'Unknown CDP error']; + if (typeof error.code === 'number') { + parts.push(`code ${error.code}`); } - if (response.error.data !== undefined) { - parts.push(JSON.stringify(response.error.data)); + if (error.data !== undefined) { + parts.push(JSON.stringify(error.data)); } return parts.join(' - '); } @@ -946,7 +967,7 @@ function formatCdpError(response: CdpErrorResponse): string { * * @param socket - The target WebSocket. */ -function closeSocket(socket: WebSocket): void { +export function closeSocket(socket: WebSocket): void { if ( socket.readyState === WebSocket.CONNECTING || socket.readyState === WebSocket.OPEN diff --git a/src/hermes/hermes-client.test.ts b/src/hermes/hermes-client.test.ts new file mode 100644 index 0000000..4e48986 --- /dev/null +++ b/src/hermes/hermes-client.test.ts @@ -0,0 +1,2057 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { HermesCdpResult } from './hermes-cdp.js'; +import { + HERMES_ABORTED, + HERMES_BLOCKED_METHOD, + HERMES_CDP_FAILED, + HERMES_CONNECTION_FAILED, + HERMES_DEVICE_PIN_MISMATCH, + HERMES_TARGET_NOT_FOUND, + HERMES_TIMEOUT, + HERMES_WEBSOCKET_UNAVAILABLE, + IDENTITY_PROBE_EXPR, +} from './hermes-cdp.js'; +import { HermesClient } from './hermes-client.js'; +import type { + HermesCdpEvent, + HermesClientOptions, + HermesContextCreatedEvent, + HermesContextDestroyedEvent, + HermesListenerErrorEvent, + HermesReconnectFailedEvent, +} from './hermes-client.js'; + +const APP_ID = 'io.metamask.MetaMask'; +const METRO_PORT = 8085; +const SOCKET_URL = `ws://localhost:${METRO_PORT}/inspector/debug?device=device-1&page=1`; + +type CdpRequest = { + id?: number; + method?: string; + params?: Record; +}; + +type MockResponse = Record | string | undefined; + +class FakeWebSocket extends EventTarget { + static readonly connecting = 0; + + static readonly openState = 1; + + static readonly closing = 2; + + static readonly closed = 3; + + static instances: FakeWebSocket[] = []; + + static autoOpen = true; + + static responseFactory: ((request: CdpRequest) => MockResponse) | undefined; + + readonly url: string; + + readonly options: { headers: { origin: string } } | undefined; + + readonly sent: CdpRequest[] = []; + + readyState = FakeWebSocket.connecting; + + constructor(url: string, options?: { headers: { origin: string } }) { + super(); + this.url = url; + this.options = options; + FakeWebSocket.instances.push(this); + + if (FakeWebSocket.autoOpen) { + queueMicrotask(() => this.open()); + } + } + + send(raw: string): void { + const request = JSON.parse(raw) as CdpRequest; + this.sent.push(request); + const response = FakeWebSocket.responseFactory?.(request); + if (response !== undefined) { + const payload = + typeof response === 'string' ? response : JSON.stringify(response); + queueMicrotask(() => this.receive(payload)); + } + } + + /** + * Closes the socket. Like Node's WebSocket, closing a CONNECTING socket fires + * `error` and then `close` at once. + */ + close(): void { + if (this.readyState === FakeWebSocket.closed) { + return; + } + const wasConnecting = this.readyState === FakeWebSocket.connecting; + this.readyState = FakeWebSocket.closed; + if (wasConnecting) { + this.dispatchEvent(new Event('error')); + } + this.dispatchEvent(new Event('close')); + } + + open(): void { + if (this.readyState !== FakeWebSocket.connecting) { + return; + } + this.readyState = FakeWebSocket.openState; + this.dispatchEvent(new Event('open')); + } + + receive(data: string): void { + this.dispatchEvent(new MessageEvent('message', { data })); + } + + /** + * Simulates the app reloading or Metro restarting: the remote end drops the + * socket without the client asking for it. + * + * @param reason - The close reason reported by the remote end. + */ + drop(reason = ''): void { + this.readyState = FakeWebSocket.closed; + const event = new Event('close'); + Object.defineProperty(event, 'reason', { value: reason }); + this.dispatchEvent(event); + } +} + +Object.defineProperties(FakeWebSocket, { + CONNECTING: { value: FakeWebSocket.connecting }, + OPEN: { value: FakeWebSocket.openState }, + CLOSING: { value: FakeWebSocket.closing }, + CLOSED: { value: FakeWebSocket.closed }, +}); + +let fetchMock: ReturnType; + +function target( + overrides: Record = {}, +): Record { + return { + id: 'device-page-1', + title: 'io.metamask.MetaMask (iPhone 15)', + appId: APP_ID, + webSocketDebuggerUrl: SOCKET_URL, + reactNative: { + logicalDeviceId: 'logical-device-1', + capabilities: { nativePageReloads: true }, + }, + ...overrides, + }; +} + +/** + * A MetaMask target on another simulator (a different logical device). + * + * @returns The discovery entry. + */ +function otherDeviceTarget(): Record { + return target({ + id: 'other-device', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-2&page=1`, + reactNative: { + logicalDeviceId: 'logical-device-2', + capabilities: { nativePageReloads: true }, + }, + }); +} + +function mockDiscovery(targets: unknown[]): void { + fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: vi.fn().mockResolvedValue(targets), + }); + vi.stubGlobal('fetch', fetchMock); +} + +function isIdentityProbe(request: CdpRequest): boolean { + return request.params?.expression === IDENTITY_PROBE_EXPR; +} + +function probeResponse(request: CdpRequest): Record { + return { + id: request.id, + result: { + result: { + type: 'string', + value: '{"isHermes":true,"ossVersion":"0.19.0","debuggerEnabled":true}', + }, + }, + }; +} + +function defaultResponseFactory(request: CdpRequest): Record { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + return { id: request.id, result: { result: { type: 'number', value: 2 } } }; +} + +function isRuntimeEnable(request: CdpRequest): boolean { + return request.method === 'Runtime.enable'; +} + +/** + * Answers the identity probe and the client's internal `Runtime.enable`, but + * leaves user methods unanswered. + * + * @param request - The sent CDP request. + * @returns The mocked response, or undefined to stay pending. + */ +function controlOnly(request: CdpRequest): MockResponse { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + return { id: request.id, result: {} }; + } + return undefined; +} + +function socketAt(index: number): FakeWebSocket { + const socket = FakeWebSocket.instances[index]; + if (!socket) { + throw new Error(`Missing FakeWebSocket instance ${index}`); + } + return socket; +} + +function createClient( + overrides: Partial = {}, +): HermesClient { + return new HermesClient({ + metroPort: METRO_PORT, + appId: APP_ID, + ...overrides, + }); +} + +function expectError( + result: HermesCdpResult, + code: string, +): asserts result is { ok: false; code: string; message: string } { + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.code).toBe(code); + } +} + +/** + * Lets every pending microtask (discovery, socket open, probe) settle. + * + * @returns A promise resolved after a macrotask. + */ +async function flush(): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)); +} + +describe('HermesClient', () => { + beforeEach(() => { + FakeWebSocket.instances = []; + FakeWebSocket.autoOpen = true; + FakeWebSocket.responseFactory = defaultResponseFactory; + vi.stubGlobal('WebSocket', FakeWebSocket); + mockDiscovery([target()]); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it('connects once and runs the identity probe once across many sends', async () => { + const client = createClient({ trackContexts: true }); + + const first = await client.send( + 'Runtime.evaluate', + { expression: '1+1', returnByValue: true }, + { timeoutMs: 1_000 }, + ); + const second = await client.send( + 'Runtime.evaluate', + { expression: '2+2', returnByValue: true }, + { timeoutMs: 1_000 }, + ); + + expect(first).toStrictEqual({ + ok: true, + result: { result: { type: 'number', value: 2 } }, + }); + expect(second.ok).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + + const socket = socketAt(0); + expect(socket.sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, 4, + ]); + expect(socket.sent.filter(isIdentityProbe)).toHaveLength(1); + expect(socket.sent.filter(isRuntimeEnable)).toHaveLength(1); + expect(socket.options?.headers.origin).toBe( + `http://127.0.0.1:${METRO_PORT}`, + ); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('shares one in-flight connect and emits contextCreated once', async () => { + const client = createClient(); + const created = vi.fn(); + client.on('contextCreated', created); + + const [first, second] = await Promise.all([ + client.connect({ timeoutMs: 1_000 }), + client.connect({ timeoutMs: 1_000 }), + ]); + + expect(first.ok).toBe(true); + expect(second).toStrictEqual(first); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(created).toHaveBeenCalledTimes(1); + expect(created).toHaveBeenCalledWith({ + target: { + id: 'device-page-1', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }, + reconnected: false, + reason: 'connect', + }); + }); + + it('sends Runtime.enable once per socket', async () => { + const client = createClient({ trackContexts: true }); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + const enableMessages = socketAt(0).sent.filter(isRuntimeEnable); + expect(enableMessages).toStrictEqual([ + { id: 2, method: 'Runtime.enable', params: {} }, + ]); + }); + + it('does not send Runtime.enable or report reloads by default', async () => { + const client = createClient(); + const created: HermesContextCreatedEvent[] = []; + const destroyed = vi.fn(); + client.on('contextCreated', (event) => created.push(event)); + client.on('contextDestroyed', destroyed); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + expect(socket.sent.filter(isRuntimeEnable)).toHaveLength(0); + expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2]); + + // Even if Hermes streamed context events, no reload is reported. + for (const message of [ + { + method: 'Runtime.executionContextCreated', + params: { context: { id: 1 } }, + }, + { method: 'Runtime.executionContextDestroyed', params: {} }, + { method: 'Runtime.executionContextsCleared', params: {} }, + { + method: 'Runtime.executionContextCreated', + params: { context: { id: 2 } }, + }, + ]) { + socket.receive(JSON.stringify(message)); + } + + expect(destroyed).not.toHaveBeenCalled(); + expect(created).toStrictEqual([ + expect.objectContaining({ reason: 'connect' }), + ]); + }); + + it('does not send Runtime.enable when trackContexts is off', async () => { + const client = createClient({ trackContexts: false }); + const created = vi.fn(); + client.on('contextCreated', created); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + expect(socket.sent.map((request) => request.id)).toStrictEqual([1, 2]); + expect(socket.sent.filter(isRuntimeEnable)).toHaveLength(0); + + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }), + ); + expect(created).toHaveBeenCalledTimes(1); + }); + + it('emits one contextDestroyed and one reload contextCreated when the app reloads on the same socket', async () => { + const client = createClient({ trackContexts: true }); + const created: HermesContextCreatedEvent[] = []; + const destroyed: HermesContextDestroyedEvent[] = []; + const raw: HermesCdpEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + client.on('contextDestroyed', (event) => destroyed.push(event)); + client.on('Runtime.executionContextCreated', (event) => raw.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + const socket = socketAt(0); + const expectedTarget = { + id: 'device-page-1', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }; + + // The first context after Runtime.enable is the one connect already + // reported, so it must not produce a second contextCreated. + const firstContext = { + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }; + socket.receive(JSON.stringify(firstContext)); + expect(created).toStrictEqual([ + { target: expectedTarget, reconnected: false, reason: 'connect' }, + ]); + // Raw CDP events still reach listeners. + expect(raw).toStrictEqual([firstContext]); + + // Reload: Hermes sends both destroy events; they coalesce into one. + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextDestroyed', + params: { executionContextId: 2 }, + }), + ); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextsCleared', + params: {}, + }), + ); + expect(destroyed).toStrictEqual([{ reason: 'reload' }]); + + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 3 } }, + }), + ); + expect(created).toHaveLength(2); + expect(created[1]).toStrictEqual({ + target: expectedTarget, + reconnected: false, + reason: 'reload', + executionContextId: 3, + }); + }); + + it('keeps the connection when Runtime.enable fails', async () => { + FakeWebSocket.responseFactory = (request) => { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + return { + id: request.id, + error: { message: 'Method not found', code: -32601 }, + }; + } + return undefined; + }; + const client = createClient({ trackContexts: true }); + const created = vi.fn(); + client.on('contextCreated', created); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result.ok).toBe(true); + expect(client.isConnected).toBe(true); + + socketAt(0).receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }), + ); + expect(created).toHaveBeenCalledTimes(1); + expect(created).toHaveBeenCalledWith( + expect.objectContaining({ reason: 'connect' }), + ); + }); + + it('returns the current target when already connected', async () => { + const client = createClient(); + await client.connect({ timeoutMs: 1_000 }); + + const again = await client.connect({ timeoutMs: 1_000 }); + + expect(again.ok).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(1); + }); + + it('matches concurrent responses by id, even out of order', async () => { + FakeWebSocket.responseFactory = controlOnly; + const client = createClient({ trackContexts: true }); + + const first = client.send( + 'Runtime.evaluate', + { expression: 'a' }, + { timeoutMs: 5_000 }, + ); + const second = client.send( + 'Runtime.evaluate', + { expression: 'b' }, + { timeoutMs: 5_000 }, + ); + + await flush(); + const socket = socketAt(0); + expect(socket.sent).toHaveLength(4); + + socket.receive(JSON.stringify({ id: 4, result: 'b' })); + socket.receive(JSON.stringify({ id: 3, result: 'a' })); + + expect(await second).toStrictEqual({ ok: true, result: 'b' }); + expect(await first).toStrictEqual({ ok: true, result: 'a' }); + }); + + it('fails with HERMES_TIMEOUT on a per-call timeout and drops the pending entry', async () => { + FakeWebSocket.responseFactory = controlOnly; + const client = createClient({ trackContexts: true }); + + const result = await client.send( + 'Runtime.evaluate', + { expression: 'never' }, + { timeoutMs: 30 }, + ); + + expectError(result, HERMES_TIMEOUT); + expect(result.message).toBe('Hermes CDP call timed out after 30ms'); + + // The late response must be ignored, and the next call gets a fresh id. + const socket = socketAt(0); + socket.receive(JSON.stringify({ id: 3, result: 'late' })); + FakeWebSocket.responseFactory = defaultResponseFactory; + const next = await client.send( + 'Runtime.evaluate', + {}, + { timeoutMs: 1_000 }, + ); + + expect(next.ok).toBe(true); + expect(socket.sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, 4, + ]); + }); + + it('fails with HERMES_ABORTED when the signal aborts and drops the pending entry', async () => { + FakeWebSocket.responseFactory = controlOnly; + const controller = new AbortController(); + const client = createClient({ trackContexts: true }); + + const pending = client.send( + 'Runtime.evaluate', + { expression: 'slow' }, + { timeoutMs: 5_000, signal: controller.signal }, + ); + await flush(); + controller.abort(); + + const result = await pending; + expectError(result, HERMES_ABORTED); + expect(result.message).toContain('aborted'); + + const socket = socketAt(0); + socket.receive(JSON.stringify({ id: 3, result: 'late' })); + FakeWebSocket.responseFactory = defaultResponseFactory; + const next = await client.send( + 'Runtime.evaluate', + {}, + { timeoutMs: 1_000 }, + ); + + expect(next.ok).toBe(true); + expect(socket.sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, 4, + ]); + }); + + it('does not connect for an already-aborted signal', async () => { + const controller = new AbortController(); + controller.abort(); + const client = createClient(); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + signal: controller.signal, + }); + + expectError(result, HERMES_ABORTED); + expect(fetchMock).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + }); + + it('formats a CDP error into HERMES_CDP_FAILED', async () => { + FakeWebSocket.responseFactory = (request) => { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + return { id: request.id, result: {} }; + } + return { + id: request.id, + error: { + message: 'Bad params', + code: -32602, + data: { reason: 'invalid' }, + }, + }; + }; + const client = createClient(); + + const result = await client.send('Missing.method', undefined, { + timeoutMs: 1_000, + }); + + expectError(result, HERMES_CDP_FAILED); + expect(result.message).toContain('"Missing.method"'); + expect(result.message).toContain('Bad params'); + expect(result.message).toContain('{"reason":"invalid"}'); + }); + + it('dispatches CDP events to on() listeners and stops after off()', async () => { + const client = createClient(); + const received: HermesCdpEvent[] = []; + const listener = (event: HermesCdpEvent): void => { + received.push(event); + }; + client.on('Runtime.consoleAPICalled', listener); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + socket.receive( + JSON.stringify({ + method: 'Runtime.consoleAPICalled', + params: { type: 'log', args: [] }, + }), + ); + expect(received).toStrictEqual([ + { + method: 'Runtime.consoleAPICalled', + params: { type: 'log', args: [] }, + }, + ]); + + client.off('Runtime.consoleAPICalled', listener); + socket.receive( + JSON.stringify({ method: 'Runtime.consoleAPICalled', params: {} }), + ); + expect(received).toHaveLength(1); + }); + + it('keeps dispatching when a listener throws', async () => { + const client = createClient(); + const received: HermesCdpEvent[] = []; + client.on('Runtime.consoleAPICalled', () => { + throw new Error('listener failed'); + }); + client.on('Runtime.consoleAPICalled', (event: HermesCdpEvent) => { + received.push(event); + }); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + socket.receive( + JSON.stringify({ method: 'Runtime.consoleAPICalled', params: {} }), + ); + + expect(received).toHaveLength(1); + const next = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(next.ok).toBe(true); + }); + + it('ignores malformed and unknown-id frames', async () => { + const client = createClient(); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + const socket = socketAt(0); + + socket.receive('not json'); + socket.receive('42'); + socket.receive(JSON.stringify({ result: { ignored: true } })); + socket.receive(JSON.stringify({ id: 999, result: 'unknown' })); + + const next = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(next.ok).toBe(true); + }); + + it('pins the device on first connect and does not call onPin again', async () => { + const onPin = vi.fn(); + const client = createClient({ onPin }); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + expect(onPin).toHaveBeenCalledTimes(1); + expect(onPin).toHaveBeenCalledWith('logical-device-1'); + }); + + it('does not call onPin when a pin already exists', async () => { + const onPin = vi.fn(); + const client = createClient({ pinnedDeviceId: 'logical-device-1', onPin }); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + expect(onPin).not.toHaveBeenCalled(); + }); + + it('treats an empty pinnedDeviceId as no pin and pins on first connect', async () => { + const onPin = vi.fn(); + const client = createClient({ pinnedDeviceId: '', onPin }); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result.ok).toBe(true); + expect(onPin).toHaveBeenCalledTimes(1); + expect(onPin).toHaveBeenCalledWith('logical-device-1'); + }); + + it('fails with HERMES_BLOCKED_METHOD without discovering or connecting', async () => { + const client = createClient(); + + const result = await client.send('Runtime.terminateExecution', undefined, { + timeoutMs: 1_000, + }); + + expectError(result, HERMES_BLOCKED_METHOD); + expect(result.message).toContain('Inspector.detached'); + expect(fetchMock).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + }); + + it('fails with HERMES_WEBSOCKET_UNAVAILABLE without discovering', async () => { + vi.stubGlobal('WebSocket', undefined); + const client = createClient(); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_WEBSOCKET_UNAVAILABLE, + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('propagates a discovery failure as HERMES_CONNECTION_FAILED', async () => { + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + const client = createClient(); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('ECONNREFUSED'), + }); + expect(client.isConnected).toBe(false); + }); + + it('closing fails pending calls and closes the socket', async () => { + FakeWebSocket.responseFactory = controlOnly; + const client = createClient(); + + const pending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 5_000, + }); + await flush(); + client.close(); + client.close(); + + const result = await pending; + expectError(result, HERMES_CONNECTION_FAILED); + expect(result.message).toContain('HermesClient is closed'); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + expect(client.isConnected).toBe(false); + }); + + it('fails a send after close() without connecting until connect() reopens', async () => { + const client = createClient(); + client.close(); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result).toStrictEqual({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'HermesClient is closed', + }); + expect(fetchMock).not.toHaveBeenCalled(); + + expect((await client.connect({ timeoutMs: 1_000 })).ok).toBe(true); + const reopened = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(reopened.ok).toBe(true); + + client.close(); + }); + + it('fails a call with HERMES_CONNECTION_FAILED when socket.send throws', async () => { + const client = createClient(); + await client.connect({ timeoutMs: 1_000 }); + const socket = socketAt(0); + vi.spyOn(socket, 'send').mockImplementation(() => { + throw new Error('socket buffer full'); + }); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result).toStrictEqual({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'Hermes CDP connection failed: socket buffer full', + }); + // The pending entry was removed: the connection stays usable. + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('keeps the selection failure on reconnect when the unpinned targets are ambiguous', async () => { + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { maxAttempts: 0 }, + }); + await client.connect({ timeoutMs: 1_000 }); + + mockDiscovery([ + otherDeviceTarget(), + target({ + id: 'third-device', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-3&page=1`, + reactNative: { logicalDeviceId: 'logical-device-3' }, + }), + ]); + socketAt(0).drop('metro restart'); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_TARGET_NOT_FOUND, + }); + expect(FakeWebSocket.instances).toHaveLength(1); + }); + + it('keeps the selection failure on reconnect when no target is usable', async () => { + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { maxAttempts: 0 }, + }); + await client.connect({ timeoutMs: 1_000 }); + + // The pinned device is listed, but without a debugger URL: neither the + // pinned nor the unpinned selection finds a usable target. + const { webSocketDebuggerUrl: _url, ...withoutUrl } = target(); + mockDiscovery([withoutUrl]); + socketAt(0).drop('metro restart'); + + const result = await client.connect({ timeoutMs: 1_000 }); + + expect(result).toMatchObject({ + ok: false, + code: HERMES_TARGET_NOT_FOUND, + }); + expect(FakeWebSocket.instances).toHaveLength(1); + }); + + it('reports the configured port and app id', () => { + const client = createClient({ appId: 'io.metamask', metroPort: 9000 }); + + expect(client.metroPort).toBe(9000); + expect(client.appId).toBe('io.metamask'); + }); + + it('reconnects after an unexpected close, rediscovers the target and emits contextCreated again', async () => { + const client = createClient({ + trackContexts: true, + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const disconnected: { reason: string }[] = []; + const reconnected: unknown[] = []; + const created: unknown[] = []; + client.on('disconnected', (event) => disconnected.push(event)); + client.on('reconnected', (event) => reconnected.push(event)); + client.on('contextCreated', (event) => created.push(event)); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + expect(created).toHaveLength(1); + expect(FakeWebSocket.instances).toHaveLength(1); + + FakeWebSocket.responseFactory = controlOnly; + const pending = client.send('Network.enable', undefined, { + timeoutMs: 5_000, + }); + await flush(); + expect(socketAt(0).sent).toHaveLength(4); + + // The app reloads: the target id and URL change behind the same Metro port. + mockDiscovery([ + target({ + id: 'device-page-2', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-1&page=2`, + }), + ]); + socketAt(0).drop('app reload'); + + const pendingResult = await pending; + expectError(pendingResult, HERMES_CONNECTION_FAILED); + expect(pendingResult.message).toContain('app reload'); + expect(disconnected).toStrictEqual([{ reason: 'app reload' }]); + expect(client.isConnected).toBe(false); + + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(2)); + await vi.waitFor(() => expect(created).toHaveLength(2)); + + expect(socketAt(1).url).toContain('page=2'); + // The reconnect re-ran discovery through the second fetch stub. + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(reconnected).toStrictEqual([ + { + target: { + id: 'device-page-2', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }, + attempts: 1, + }, + ]); + expect(created[1]).toMatchObject({ + reconnected: true, + reason: 'reconnect', + target: { id: 'device-page-2' }, + }); + expect(client.isConnected).toBe(true); + + // eslint-disable-next-line require-atomic-updates -- test-double state, not shared across async work + FakeWebSocket.responseFactory = defaultResponseFactory; + const after = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expect(after.ok).toBe(true); + expect(socketAt(1).sent.map((request) => request.id)).toStrictEqual([ + 1, 2, 3, + ]); + }); + + it('retries with backoff and gives up after maxAttempts', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 5, maxDelayMs: 10, maxAttempts: 2 }, + }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('app reload'); + + // Backoff is 5 ms, then 10 ms: both attempts have run by 15 ms. + await vi.advanceTimersByTimeAsync(4); + expect(fetchMock).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(fetchMock).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(10); + + // Two attempts, then the client gives up (no socket was ever adopted). + expect(fetchMock).toHaveBeenCalledTimes(4); + await vi.advanceTimersByTimeAsync(60_000); + expect(fetchMock).toHaveBeenCalledTimes(4); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + }); + + it('does not reconnect to a different device after a reload (pin mismatch)', async () => { + vi.useFakeTimers(); + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const reconnected = vi.fn(); + const created = vi.fn(); + client.on('reconnected', reconnected); + client.on('contextCreated', created); + + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + expect(FakeWebSocket.instances).toHaveLength(1); + + mockDiscovery([ + target({ + id: 'other-device', + webSocketDebuggerUrl: `ws://localhost:${METRO_PORT}/inspector/debug?device=device-2&page=1`, + reactNative: { + logicalDeviceId: 'logical-device-2', + capabilities: { nativePageReloads: true }, + }, + }), + ]); + socketAt(0).drop('app reload'); + + await vi.advanceTimersByTimeAsync(1_000); + + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + expect(reconnected).not.toHaveBeenCalled(); + expect(created).toHaveBeenCalledTimes(1); + // Three attempts (10, 20, 40 ms), none of which opened a socket. + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + it('close() stops a scheduled reconnect', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 20, maxDelayMs: 40, maxAttempts: 3 }, + }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + socketAt(0).drop('app reload'); + client.close(); + + await vi.advanceTimersByTimeAsync(60_000); + + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('connects again on the next send after the reconnect loop gave up', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 5, maxDelayMs: 10, maxAttempts: 1 }, + }); + await client.send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('app reload'); + await vi.advanceTimersByTimeAsync(5); + expect(fetchMock).toHaveBeenCalledTimes(2); + + mockDiscovery([target({ id: 'device-page-3' })]); + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result.ok).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(socketAt(1).url).toBe(SOCKET_URL); + }); + + it('keeps reconnecting when a send fails during the reconnect wait', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 40, maxDelayMs: 80, maxAttempts: 5 }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + + // Metro goes down before the first scheduled attempt runs. + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + const failed = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 100, + }); + + expectError(failed, HERMES_CONNECTION_FAILED); + expect(client.isConnected).toBe(false); + + // Metro comes back: the background loop must still be running. + mockDiscovery([target({ id: 'device-page-2' })]); + + // The failed send restarted nothing: the loop's first attempt still + // fires at 40 ms. + await vi.advanceTimersByTimeAsync(39); + expect(client.isConnected).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(client.isConnected).toBe(true); + + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + target: { id: 'device-page-2' }, + }); + + client.close(); + }); + + it('emits reconnectFailed once when the loop gives up on a listen-only client', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + const disconnected = vi.fn(); + const created = vi.fn(); + client.on('reconnectFailed', (event) => failed.push(event)); + client.on('disconnected', disconnected); + client.on('contextCreated', created); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + await vi.advanceTimersByTimeAsync(1_000); + + // Three attempts, each trying /json then /json/list. + expect(fetchMock).toHaveBeenCalledTimes(6); + expect(failed).toStrictEqual([ + { + attempts: 3, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('ECONNREFUSED'), + }, + ]); + expect(disconnected).toHaveBeenCalledTimes(1); + + // Nothing retries for a client that only listens. + await vi.advanceTimersByTimeAsync(60_000); + expect(fetchMock).toHaveBeenCalledTimes(6); + expect(failed).toHaveLength(1); + expect(created).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + }); + + it('restarts the stopped reconnect loop when a send fails after it gave up', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 2 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + const created: HermesContextCreatedEvent[] = []; + const reconnected = vi.fn(); + client.on('reconnectFailed', (event) => failed.push(event)); + client.on('contextCreated', (event) => created.push(event)); + client.on('reconnected', reconnected); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(1_000); + expect(failed).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(4); + + // A caller tries while Metro is still down: its failure restarts the loop. + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await vi.advanceTimersByTimeAsync(0); + expectError(await sending, HERMES_CONNECTION_FAILED); + expect(fetchMock).toHaveBeenCalledTimes(6); + + // The restarted loop begins at the first backoff delay (10 ms). + await vi.advanceTimersByTimeAsync(10); + expect(fetchMock).toHaveBeenCalledTimes(8); + + // Metro comes back before the restarted loop gives up. + mockDiscovery([target({ id: 'device-page-2' })]); + await vi.advanceTimersByTimeAsync(20); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect( + created.filter((event) => event.reason === 'reconnect'), + ).toHaveLength(1); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + target: { id: 'device-page-2' }, + }); + expect(reconnected).toHaveBeenCalledTimes(1); + expect(reconnected).toHaveBeenCalledWith( + expect.objectContaining({ attempts: 2 }), + ); + expect(failed).toHaveLength(1); + + // Connected again: no further attempt runs. + await vi.advanceTimersByTimeAsync(1_000); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(2); + + client.close(); + }); + + it('retries a pin mismatch and reports it in reconnectFailed when the loop gives up', async () => { + vi.useFakeTimers(); + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + client.on('reconnectFailed', (event) => failed.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + mockDiscovery([otherDeviceTarget()]); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(1_000); + + // Every attempt retried; none opened a socket to the other device. + expect(fetchMock).toHaveBeenCalledTimes(3); + expect(failed).toStrictEqual([ + { + attempts: 3, + code: HERMES_DEVICE_PIN_MISMATCH, + message: expect.stringContaining('logical-device-2'), + }, + ]); + expect(FakeWebSocket.instances).toHaveLength(1); + + // A caller's pin mismatch restarts the stopped loop like any retryable + // failure. + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await vi.advanceTimersByTimeAsync(0); + expectError(await sending, HERMES_DEVICE_PIN_MISMATCH); + expect(fetchMock).toHaveBeenCalledTimes(4); + + await vi.advanceTimersByTimeAsync(1_000); + expect(fetchMock).toHaveBeenCalledTimes(7); + expect(failed).toHaveLength(2); + expect(FakeWebSocket.instances).toHaveLength(1); + + client.close(); + }); + + it('reconnects to the pinned device once it returns after a pin mismatch', async () => { + vi.useFakeTimers(); + const onPin = vi.fn(); + const client = createClient({ + pinnedDeviceId: 'logical-device-1', + onPin, + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 6 }, + }); + const failed = vi.fn(); + const created: HermesContextCreatedEvent[] = []; + client.on('reconnectFailed', failed); + client.on('contextCreated', (event) => created.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // Metro restarts and only the other simulator registers at first. + mockDiscovery([otherDeviceTarget()]); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(40); + expect(fetchMock.mock.calls.length).toBeGreaterThanOrEqual(2); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(false); + + // The pinned device registers too. + mockDiscovery([otherDeviceTarget(), target({ id: 'device-page-2' })]); + await vi.advanceTimersByTimeAsync(200); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(socketAt(1).url).toBe(SOCKET_URL); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + target: { id: 'device-page-2', logicalDeviceId: 'logical-device-1' }, + }); + expect(failed).not.toHaveBeenCalled(); + expect(onPin).not.toHaveBeenCalled(); + + client.close(); + }); + + it('emits reconnectFailed once when WebSocket becomes unavailable and never restarts the loop', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 10, maxDelayMs: 40, maxAttempts: 3 }, + }); + const failed: HermesReconnectFailedEvent[] = []; + client.on('reconnectFailed', (event) => failed.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + socketAt(0).drop('metro restart'); + vi.stubGlobal('WebSocket', undefined); + await vi.advanceTimersByTimeAsync(1_000); + + expect(failed).toStrictEqual([ + { + attempts: 1, + code: HERMES_WEBSOCKET_UNAVAILABLE, + message: expect.any(String), + }, + ]); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + expectError(result, HERMES_WEBSOCKET_UNAVAILABLE); + + await vi.advanceTimersByTimeAsync(60_000); + expect(failed).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('does not emit reconnectFailed when auto-reconnect is disabled', async () => { + vi.useFakeTimers(); + const client = createClient({ reconnect: { maxAttempts: 0 } }); + const failed = vi.fn(); + client.on('reconnectFailed', failed); + + await client.connect({ timeoutMs: 1_000 }); + fetchMock = vi.fn().mockRejectedValue(new Error('ECONNREFUSED')); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await vi.advanceTimersByTimeAsync(60_000); + + expectError(result, HERMES_CONNECTION_FAILED); + expect(failed).not.toHaveBeenCalled(); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it('reports reason reconnect when a send reconnects after a socket loss', async () => { + const client = createClient({ reconnect: { maxAttempts: 0 } }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + mockDiscovery([target({ id: 'device-page-2' })]); + socketAt(0).drop('metro restart'); + + const result = await client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + + expect(result.ok).toBe(true); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + target: { id: 'device-page-2' }, + }); + }); + + it('opens one socket when a disconnected listener sends and the reconnect timer fires', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 40, maxDelayMs: 40, maxAttempts: 3 }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + client.on('disconnected', () => { + client + .send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }) + .catch(() => undefined); + }); + + await client.connect({ timeoutMs: 1_000 }); + socketAt(0).drop('metro restart'); + + await vi.advanceTimersByTimeAsync(0); + expect(client.isConnected).toBe(true); + // Let the scheduled attempt fire at 40 ms: it must find the caller's + // socket and open nothing. + await vi.advanceTimersByTimeAsync(100); + + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reconnect', + reconnected: true, + }); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + expect(socketAt(1).readyState).toBe(FakeWebSocket.openState); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('treats a context after contextDestroyed as a reload when no initial context arrived', async () => { + const client = createClient({ trackContexts: true }); + const created: HermesContextCreatedEvent[] = []; + const destroyed: HermesContextDestroyedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + client.on('contextDestroyed', (event) => destroyed.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + const socket = socketAt(0); + + // This socket never reported its first execution context. + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextsCleared', + params: {}, + }), + ); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 5 } }, + }), + ); + + expect(destroyed).toStrictEqual([{ reason: 'reload' }]); + expect(created).toHaveLength(2); + expect(created[1]).toStrictEqual({ + target: { + id: 'device-page-1', + logicalDeviceId: 'logical-device-1', + title: 'io.metamask.MetaMask (iPhone 15)', + }, + reconnected: false, + reason: 'reload', + executionContextId: 5, + }); + }); + + it('tracks the first context when it arrives before the Runtime.enable response', async () => { + FakeWebSocket.responseFactory = (request) => { + if (isIdentityProbe(request)) { + return probeResponse(request); + } + if (isRuntimeEnable(request)) { + socketAt(FakeWebSocket.instances.length - 1).receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 2 } }, + }), + ); + return { id: request.id, result: {} }; + } + return undefined; + }; + const client = createClient({ trackContexts: true }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + + // The context seen during Runtime.enable is the connect context: no second + // event, and a later context is a reload, not the socket's first context. + expect(created).toHaveLength(1); + expect(created[0]).toMatchObject({ reason: 'connect' }); + + const socket = socketAt(0); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextDestroyed', + params: { executionContextId: 2 }, + }), + ); + socket.receive( + JSON.stringify({ + method: 'Runtime.executionContextCreated', + params: { context: { name: 'main', id: 3 } }, + }), + ); + + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ + reason: 'reload', + reconnected: false, + executionContextId: 3, + }); + }); + + it('uses reconnect.connectTimeoutMs for reconnect attempts, not the last caller timeout', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { + initialDelayMs: 10, + maxDelayMs: 10, + maxAttempts: 3, + connectTimeoutMs: 30, + }, + }); + // The last caller asks for a 5 s connect. + await client.send('Runtime.evaluate', undefined, { timeoutMs: 5_000 }); + + const abortedAfter: number[] = []; + const startedAt = Date.now(); + fetchMock = vi.fn( + async (_url: string, init?: { signal?: AbortSignal }) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => { + abortedAfter.push(Date.now() - startedAt); + reject(new Error('discovery aborted')); + }); + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + // The attempt fires at 10 ms; its discovery is aborted 30 ms later, far + // below the caller's 5 s. + await vi.advanceTimersByTimeAsync(40); + expect(abortedAfter).toStrictEqual([40]); + expect(client.isConnected).toBe(false); + + client.close(); + }); + + it('bounds a send that joins a background reconnect attempt by its own timeout', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { + initialDelayMs: 10, + maxDelayMs: 10, + maxAttempts: 3, + connectTimeoutMs: 10_000, + }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // Metro is slow to answer: the background attempt's discovery hangs. + let resolveDiscovery!: (value: unknown) => void; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + resolveDiscovery = resolve; + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(10); + expect(fetchMock).toHaveBeenCalledTimes(1); + + let settledAt: number | undefined; + const startedAt = Date.now(); + const sending = client + .send('Runtime.evaluate', undefined, { timeoutMs: 1_000 }) + .then((result) => { + settledAt = Date.now() - startedAt; + return result; + }); + + await vi.advanceTimersByTimeAsync(999); + expect(settledAt).toBeUndefined(); + await vi.advanceTimersByTimeAsync(1); + + const result = await sending; + expectError(result, HERMES_TIMEOUT); + expect(settledAt).toBe(1_000); + // The send joined the attempt: no discovery or socket of its own. + expect(fetchMock).toHaveBeenCalledTimes(1); + + // The background attempt keeps running and succeeds later, within its own + // 10 s budget. + await vi.advanceTimersByTimeAsync(4_000); + resolveDiscovery({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + await vi.advanceTimersByTimeAsync(0); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ reason: 'reconnect' }); + + client.close(); + }); + + it('gives a background attempt its full connectTimeoutMs after a short caller connect fails', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { + initialDelayMs: 100, + maxDelayMs: 100, + maxAttempts: 1, + connectTimeoutMs: 10_000, + }, + }); + const created: HermesContextCreatedEvent[] = []; + const failed = vi.fn(); + client.on('contextCreated', (event) => created.push(event)); + client.on('reconnectFailed', failed); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // Discovery hangs until it is aborted; record each abort time. + const resolvers: ((value: unknown) => void)[] = []; + const abortedAt: number[] = []; + const startedAt = Date.now(); + fetchMock = vi.fn( + async (_url: string, init?: { signal?: AbortSignal }) => + new Promise((resolve, reject) => { + resolvers.push(resolve); + init?.signal?.addEventListener('abort', () => { + abortedAt.push(Date.now() - startedAt); + reject(new Error('discovery aborted')); + }); + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + // A caller starts a short connect before the background attempt fires. + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 200, + }); + await vi.advanceTimersByTimeAsync(0); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // The background attempt fires at 100 ms and meets the caller's connect. + await vi.advanceTimersByTimeAsync(100); + expect(fetchMock).toHaveBeenCalledTimes(1); + + // The caller's connect gives up at 200 ms per discovery path. + await vi.advanceTimersByTimeAsync(300); + expectError(await sending, HERMES_CONNECTION_FAILED); + expect(abortedAt).toStrictEqual([200, 400]); + + // The attempt then runs its own connect: its discovery is not aborted at + // the caller's 200 ms, only at its own 10 s. + expect(fetchMock).toHaveBeenCalledTimes(3); + await vi.advanceTimersByTimeAsync(9_999); + expect(abortedAt).toStrictEqual([200, 400]); + expect(failed).not.toHaveBeenCalled(); + + resolvers[2]?.({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + await vi.advanceTimersByTimeAsync(0); + + expect(client.isConnected).toBe(true); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ reason: 'reconnect' }); + expect(failed).not.toHaveBeenCalled(); + + client.close(); + }); + + it('opens one socket when a background attempt meets a caller connect that succeeds', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 100, maxDelayMs: 100, maxAttempts: 3 }, + }); + const created: HermesContextCreatedEvent[] = []; + client.on('contextCreated', (event) => created.push(event)); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + let resolveDiscovery!: (value: unknown) => void; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + resolveDiscovery = resolve; + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + + const sending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 1_000, + }); + await vi.advanceTimersByTimeAsync(150); + resolveDiscovery({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + await vi.advanceTimersByTimeAsync(0); + + expect((await sending).ok).toBe(true); + await vi.advanceTimersByTimeAsync(1_000); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(created).toHaveLength(2); + expect(created[1]).toMatchObject({ reason: 'reconnect' }); + + client.close(); + }); + + it('fails a send with HERMES_ABORTED while it is still connecting', async () => { + fetchMock = vi.fn(async () => new Promise(() => undefined)); + vi.stubGlobal('fetch', fetchMock); + const client = createClient(); + const controller = new AbortController(); + + const sentAt = Date.now(); + const pending = client.send('Runtime.evaluate', undefined, { + timeoutMs: 500, + signal: controller.signal, + }); + await flush(); + controller.abort(); + + const result = await pending; + + expectError(result, HERMES_ABORTED); + expect(result.message).toContain('aborted'); + expect(Date.now() - sentAt).toBeLessThan(1_000); + expect(FakeWebSocket.instances).toHaveLength(0); + }); + + it('does not pin, adopt or reconnect when close() lands during discovery', async () => { + vi.useFakeTimers(); + const onPin = vi.fn(); + const client = createClient({ onPin }); + let resolveDiscovery!: (value: unknown) => void; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + resolveDiscovery = resolve; + }), + ); + vi.stubGlobal('fetch', fetchMock); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + client.close(); + resolveDiscovery({ ok: true, json: vi.fn().mockResolvedValue([target()]) }); + + const result = await connecting; + + expect(result).toMatchObject({ ok: false, code: HERMES_CONNECTION_FAILED }); + expect(onPin).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + expect(client.isConnected).toBe(false); + + await vi.advanceTimersByTimeAsync(60_000); + expect(FakeWebSocket.instances).toHaveLength(0); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('does not pin or adopt when close() lands during the identity probe', async () => { + vi.useFakeTimers(); + FakeWebSocket.responseFactory = () => undefined; + const onPin = vi.fn(); + const client = createClient({ onPin }); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(socketAt(0).readyState).toBe(FakeWebSocket.openState); + + client.close(); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + + const result = await connecting; + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(onPin).not.toHaveBeenCalled(); + expect(client.isConnected).toBe(false); + + await vi.advanceTimersByTimeAsync(100); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('does not pin or adopt when close() lands right after the socket opens', async () => { + FakeWebSocket.autoOpen = false; + const onPin = vi.fn(); + const client = createClient({ onPin }); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1)); + const socket = socketAt(0); + // Runs after the client's own open listener, before its connect resumes. + socket.addEventListener('open', () => client.close()); + socket.open(); + + const result = await connecting; + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(socket.sent).toHaveLength(0); + expect(socket.readyState).toBe(FakeWebSocket.closed); + expect(onPin).not.toHaveBeenCalled(); + expect(client.isConnected).toBe(false); + }); + + it('does not report a connect when close() lands during Runtime.enable', async () => { + FakeWebSocket.responseFactory = (request) => + isIdentityProbe(request) ? probeResponse(request) : undefined; + const client = createClient({ trackContexts: true }); + const created = vi.fn(); + client.on('contextCreated', created); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.waitFor(() => + expect(socketAt(0).sent.filter(isRuntimeEnable)).toHaveLength(1), + ); + client.close(); + + const result = await connecting; + + expect(result).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(created).not.toHaveBeenCalled(); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + expect(client.isConnected).toBe(false); + }); + + it('starts a fresh connect on reopen and never pins from the abandoned one (S1)', async () => { + const onPin = vi.fn(); + const client = createClient({ onPin }); + const discoveries: ((value: unknown) => void)[] = []; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + discoveries.push(resolve); + }), + ); + vi.stubGlobal('fetch', fetchMock); + const discovered = { ok: true, json: async () => [target()] }; + + const first = client.connect({ timeoutMs: 1_000 }); + await flush(); + client.close(); + const second = client.connect({ timeoutMs: 1_000 }); + await flush(); + + // The reopen ran its own discovery instead of joining the abandoned one. + expect(fetchMock).toHaveBeenCalledTimes(2); + + discoveries[0]?.(discovered); + expect(await first).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(onPin).not.toHaveBeenCalled(); + expect(FakeWebSocket.instances).toHaveLength(0); + + discoveries[1]?.(discovered); + expect((await second).ok).toBe(true); + expect(onPin).toHaveBeenCalledTimes(1); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('reopens with a fresh socket after close() lands while the socket is connecting (S2)', async () => { + FakeWebSocket.autoOpen = false; + const client = createClient(); + + const first = client.connect({ timeoutMs: 1_000 }); + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1)); + client.close(); + const second = client.connect({ timeoutMs: 1_000 }); + + expect(await first).toMatchObject({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: expect.stringContaining('closed'), + }); + expect(socketAt(0).readyState).toBe(FakeWebSocket.closed); + + await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(2)); + socketAt(1).open(); + + expect((await second).ok).toBe(true); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('reports a reopen as connect, not reconnect, when a background attempt was in flight (S3)', async () => { + vi.useFakeTimers(); + const client = createClient({ + reconnect: { initialDelayMs: 5, maxDelayMs: 5, maxAttempts: 3 }, + }); + const events: string[] = []; + client.on('reconnected', () => events.push('reconnected')); + client.on('contextCreated', (event) => + events.push(`created:${event.reason}`), + ); + await client.connect({ timeoutMs: 1_000 }); + + const discoveries: ((value: unknown) => void)[] = []; + fetchMock = vi.fn( + async () => + new Promise((resolve) => { + discoveries.push(resolve); + }), + ); + vi.stubGlobal('fetch', fetchMock); + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(5); + expect(fetchMock).toHaveBeenCalledTimes(1); + + client.close(); + const reopened = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect(fetchMock).toHaveBeenCalledTimes(2); + + const discovered = { ok: true, json: async () => [target()] }; + discoveries[0]?.(discovered); + discoveries[1]?.(discovered); + + expect((await reopened).ok).toBe(true); + await vi.advanceTimersByTimeAsync(60_000); + + expect(events).toStrictEqual(['created:connect', 'created:connect']); + expect(FakeWebSocket.instances).toHaveLength(2); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('fails a first connect whose socket is lost during Runtime.enable, without disconnected (S4)', async () => { + vi.useFakeTimers(); + FakeWebSocket.responseFactory = (request) => + isIdentityProbe(request) ? probeResponse(request) : undefined; + const client = createClient({ + trackContexts: true, + reconnect: { initialDelayMs: 5, maxDelayMs: 5, maxAttempts: 2 }, + }); + const events: string[] = []; + client.on('contextCreated', (event) => + events.push(`created:${event.reason}`), + ); + client.on('disconnected', () => events.push('disconnected')); + client.on('reconnectFailed', () => events.push('reconnectFailed')); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect(socketAt(0).sent.filter(isRuntimeEnable)).toHaveLength(1); + socketAt(0).drop('gone'); + + expect(await connecting).toStrictEqual({ + ok: false, + code: HERMES_CONNECTION_FAILED, + message: + 'Hermes CDP connection failed: the socket closed while enabling runtime events', + }); + + // Listeners never saw this connection, so they hear nothing about it, and + // no reconnect loop runs for a connection that never completed. + await vi.advanceTimersByTimeAsync(1_000); + expect(events).toStrictEqual([]); + expect(client.isConnected).toBe(false); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('keeps reconnecting when a reconnect socket is lost during Runtime.enable', async () => { + vi.useFakeTimers(); + const client = createClient({ + trackContexts: true, + reconnect: { initialDelayMs: 10, maxDelayMs: 10, maxAttempts: 3 }, + }); + const events: string[] = []; + client.on('contextCreated', (event) => + events.push(`created:${event.reason}`), + ); + client.on('disconnected', () => events.push('disconnected')); + client.on('reconnected', () => events.push('reconnected')); + + const connecting = client.connect({ timeoutMs: 1_000 }); + await vi.advanceTimersByTimeAsync(0); + expect((await connecting).ok).toBe(true); + + // The first reconnect socket never answers Runtime.enable and drops. + FakeWebSocket.responseFactory = (request) => + isIdentityProbe(request) ? probeResponse(request) : undefined; + socketAt(0).drop('metro restart'); + await vi.advanceTimersByTimeAsync(10); + expect(FakeWebSocket.instances).toHaveLength(2); + + FakeWebSocket.responseFactory = defaultResponseFactory; + socketAt(1).drop('gone again'); + + await vi.advanceTimersByTimeAsync(10); + + expect(events).toStrictEqual([ + 'created:connect', + 'disconnected', + 'reconnected', + 'created:reconnect', + ]); + expect(FakeWebSocket.instances).toHaveLength(3); + expect(client.isConnected).toBe(true); + + client.close(); + }); + + it('reports a throwing listener through the listenerError event', async () => { + const client = createClient(); + const errors: HermesListenerErrorEvent[] = []; + const received: HermesCdpEvent[] = []; + const failure = new Error('listener failed'); + client.on('listenerError', () => { + throw new Error('nested listener failure'); + }); + client.on('listenerError', (event) => errors.push(event)); + client.on('Runtime.consoleAPICalled', () => { + throw failure; + }); + client.on('Runtime.consoleAPICalled', (event) => received.push(event)); + + await client.connect({ timeoutMs: 1_000 }); + socketAt(0).receive( + JSON.stringify({ method: 'Runtime.consoleAPICalled', params: {} }), + ); + + expect(received).toHaveLength(1); + expect(errors).toStrictEqual([ + { event: 'Runtime.consoleAPICalled', error: failure }, + ]); + }); +}); diff --git a/src/hermes/hermes-client.ts b/src/hermes/hermes-client.ts new file mode 100644 index 0000000..c8b2d40 --- /dev/null +++ b/src/hermes/hermes-client.ts @@ -0,0 +1,1674 @@ +/** + * Persistent Hermes Chrome DevTools Protocol (CDP) client for + * `@metamask/device-mcp`. + * + * `runHermesCdp` opens one WebSocket per call, which costs a `/json` discovery + * fetch and a handshake every time and cannot receive CDP events. This client + * keeps ONE verified socket open for many calls and dispatches the CDP events + * (messages without an `id`, e.g. `Runtime.consoleAPICalled`) to listeners. + * + * It keeps every fail-closed safety check of the one-shot path: strict `appId` + * selection, the Hermes identity probe once per socket, the device pin, the + * WebSocket URL validation, and the blocked-method set. + * + * When Metro restarts (or the socket is otherwise lost) the socket closes. + * Pending calls are failed with `HERMES_CONNECTION_FAILED` and NOT resent (they + * may have run), then the client rediscovers the target and reconnects with + * exponential backoff. Every successful (re)connect emits `contextCreated`. + * + * An app reload does NOT close the socket: the runtime swaps its JavaScript + * context in place. With `trackContexts` on (off by default) the client enables + * `Runtime` context events, emits `contextDestroyed` when the old context goes + * away and `contextCreated` (`reason: 'reload'`) for the new one, so callers can + * re-apply their scripts. With it off, a reload is not reported. + */ + +import type { HermesCdpResult } from './hermes-cdp.js'; +import { + closeSocket, + createBlockedMethodResult, + fetchDiscoveryTargets, + formatCdpError, + HERMES_ABORTED, + HERMES_CDP_FAILED, + HERMES_CONNECTION_FAILED, + HERMES_DEVICE_PIN_MISMATCH, + HERMES_INVALID_WS_URL, + HERMES_NOT_VERIFIED, + HERMES_TARGET_NOT_FOUND, + HERMES_TIMEOUT, + HERMES_WEBSOCKET_UNAVAILABLE, + resolveWebSocketOrigin, + runIdentityProbe, + selectHermesTarget, + validateWebSocketUrl, + waitForSocketOpen, + websocketUnavailableResult, +} from './hermes-cdp.js'; + +/** Default first backoff delay after an unexpected disconnect. */ +const DEFAULT_RECONNECT_INITIAL_DELAY_MS = 250; + +/** Default upper bound for the exponential backoff delay. */ +const DEFAULT_RECONNECT_MAX_DELAY_MS = 5_000; + +/** Default number of automatic reconnect attempts before giving up. */ +const DEFAULT_RECONNECT_MAX_ATTEMPTS = 6; + +/** Default connect timeout used by the automatic reconnect loop. */ +const DEFAULT_RECONNECT_TIMEOUT_MS = 10_000; + +/** Lifecycle event name used to report a throwing listener. */ +const LISTENER_ERROR_EVENT = 'listenerError'; + +/** Message used when a call is made after {@link HermesClient.close}. */ +const CLIENT_CLOSED_MESSAGE = 'HermesClient is closed'; + +/** + * Options for the automatic reconnect loop. + */ +export type HermesClientReconnectOptions = { + /** First backoff delay in milliseconds (doubles on every attempt). */ + initialDelayMs?: number; + /** Upper bound for the backoff delay in milliseconds. */ + maxDelayMs?: number; + /** + * Number of attempts before giving up. When the loop gives up it emits + * `reconnectFailed`, the client stays disconnected, and the next + * {@link HermesClient.send} tries a fresh connect; if that connect fails, the + * loop starts again from the first backoff delay. `0` disables + * auto-reconnect (and `reconnectFailed`). + */ + maxAttempts?: number; + /** + * Connect timeout for automatic reconnect attempts, in milliseconds + * (default 10 s). Like a caller's `timeoutMs`, it applies to each connect + * step on its own: the `/json` and the fallback `/json/list` discovery, the + * WebSocket open, the identity probe and, with `trackContexts` on, + * `Runtime.enable`. One attempt can therefore take up to about 4 × this + * value (5 × with `trackContexts` on). + * + * Per-call `timeoutMs` values never shorten a reconnect attempt: an attempt + * that finds a caller's connect in flight waits for it (so no second socket + * opens) and, if it fails, then runs its own connect with this full timeout. + */ + connectTimeoutMs?: number; +}; + +/** + * Options for constructing a {@link HermesClient}. + */ +export type HermesClientOptions = { + /** The resolved Metro inspector proxy port. */ + metroPort: number; + /** The expected app bundle identifier (strict-matched against targets). */ + appId: string; + /** Override the HTTP(S) Origin for Metro's debugger WebSocket handshake. */ + origin?: string; + /** + * The pinned `logicalDeviceId` for this session, if one has been set. An + * empty string means no pin. + */ + pinnedDeviceId?: string; + /** + * Callback invoked with the resolved `logicalDeviceId` on the FIRST + * successful identity probe so the caller can persist the pin. + */ + onPin?: (logicalDeviceId: string) => void; + /** Automatic reconnect tuning. */ + reconnect?: HermesClientReconnectOptions; + /** + * Track JavaScript execution contexts and emit `contextDestroyed` and + * `contextCreated` (`reason: 'reload'`) lifecycle events for an app reload + * (default `false`). The `connect` and `reconnect` `contextCreated` events + * fire either way. + * + * When enabled, the client sends `Runtime.enable` itself after each + * connection so Hermes streams `Runtime.executionContextCreated`, + * `Runtime.executionContextDestroyed` and `Runtime.executionContextsCleared` + * over the socket; an app reload keeps the socket open, so this is the only + * signal that the JavaScript context was replaced. + * + * Cost, while the socket is open: `Runtime.enable` also makes Hermes send a + * `Runtime.consoleAPICalled` event, with object previews, for every + * `console.*` call in the app, which costs JS-thread time. Hermes also keeps + * every object argument of those calls alive in its remote-objects table + * (object group `ConsoleObjectGroup`) until a + * `Runtime.releaseObjectGroup { objectGroup: 'ConsoleObjectGroup' }`, which + * this client never sends. A long session therefore holds every logged + * object; callers that turn this on and log a lot should send that release + * themselves from time to time. Leave it off unless you need reload events. + */ + trackContexts?: boolean; +}; + +/** + * Options for {@link HermesClient.connect}. + */ +export type HermesConnectOptions = { + /** + * Timeout in milliseconds for each connect step on its own: the `/json` and + * the fallback `/json/list` discovery, the socket open, the probe and, with + * `trackContexts` on, `Runtime.enable` (up to about 4 × `timeoutMs` in all, + * 5 × with tracking). + */ + timeoutMs: number; +}; + +/** + * The verified target the client is (or was last) connected to. + */ +export type HermesConnectedTarget = { + /** Metro's per-target identifier (changes after an app reload). */ + id: string | undefined; + /** The verified `reactNative.logicalDeviceId` of the target. */ + logicalDeviceId: string; + /** Human-readable target title. */ + title: string | undefined; +}; + +/** + * The failure branch shared by the connect and send results. + */ +type HermesFailureResult = { ok: false; code: string; message: string }; + +/** + * Result of {@link HermesClient.connect}. + */ +export type HermesConnectResult = + | { ok: true; target: HermesConnectedTarget } + | HermesFailureResult; + +/** + * Options for {@link HermesClient.send}. + */ +export type HermesSendOptions = { + /** + * Per-step timeout in milliseconds. It bounds each step of the call on its + * own, not their sum: + * - Connect, when the client is not connected. If this call starts the + * connect, each of these steps gets its own `timeoutMs`, as in + * `runHermesCdp`: + * 1. discovery of `/json`, then 2. of `/json/list` (only if `/json` + * failed); + * 3. the WebSocket open; + * 4. the identity probe; + * 5. `Runtime.enable`, only with `trackContexts` on. + * + * If a connect is already in flight (another call's, or a background + * reconnect attempt), this call instead waits for it at most `timeoutMs`, + * then fails with `HERMES_TIMEOUT`; the shared connect keeps running for + * the others. + * - Response: once connected, the CDP response gets `timeoutMs`. + * + * So a cold `send` can take up to about 5 × `timeoutMs` (6 × with + * `trackContexts` on); a connected one, `timeoutMs`. To bound the total + * time, pass `signal: AbortSignal.timeout(n)`. + */ + timeoutMs: number; + /** + * Aborts the call, including its wait for a connect; the pending response is + * discarded. `AbortSignal.timeout(n)` bounds the total time of the call. + */ + signal?: AbortSignal; +}; + +/** + * A CDP event: a message without an `id` that carries a `method`. + */ +export type HermesCdpEvent = { + /** The CDP event method, e.g. `Runtime.consoleAPICalled`. */ + method: string; + /** The event payload as sent by Hermes. */ + params: unknown; +}; + +/** + * Why a `contextCreated` lifecycle event fired: + * - `connect`: the first connection of this client. + * - `reconnect`: a new socket after the old one closed (Metro restart, socket + * loss). + * - `reload`: a new JS context on the SAME socket (app reload / fast refresh). + * Only reported with `trackContexts` on. + */ +export type HermesContextCreatedReason = 'connect' | 'reconnect' | 'reload'; + +/** + * Payload of the `contextCreated` lifecycle event: emitted after every + * successful connect, after every reconnect, and, with `trackContexts` on, for + * every new JavaScript execution context created on an open socket (app + * reload). + */ +export type HermesContextCreatedEvent = { + /** The verified target of the connection. */ + target: HermesConnectedTarget; + /** True for a reconnect, false for the initial connect or a reload. */ + reconnected: boolean; + /** Why the event fired. */ + reason: HermesContextCreatedReason; + /** The CDP execution context id for a `reload`, when Hermes reported one. */ + executionContextId?: number; +}; + +/** + * Payload of the `contextDestroyed` lifecycle event, emitted when an open + * socket reports that its JavaScript context went away (a reload started). + * Only emitted with `trackContexts` on. + */ +export type HermesContextDestroyedEvent = { + /** Contexts are only destroyed by a reload on the same socket. */ + reason: 'reload'; +}; + +/** + * Payload of the `disconnected` lifecycle event. + */ +export type HermesDisconnectedEvent = { + /** Why the socket was lost (close reason or `WebSocket error`). */ + reason: string; +}; + +/** + * Payload of the `reconnected` lifecycle event, emitted just before the + * `contextCreated` event of a successful automatic reconnect. + */ +export type HermesReconnectedEvent = { + /** The verified target of the new connection. */ + target: HermesConnectedTarget; + /** How many backoff attempts were needed. */ + attempts: number; +}; + +/** + * Payload of the `reconnectFailed` lifecycle event, emitted once each time the + * background reconnect loop gives up: after `maxAttempts` failed attempts (the + * last one may be `HERMES_DEVICE_PIN_MISMATCH` when Metro only lists another + * device), or at once when `HERMES_WEBSOCKET_UNAVAILABLE`, the only terminal + * failure. The client then stays disconnected until a caller connects. + */ +export type HermesReconnectFailedEvent = { + /** How many backoff attempts ran before the loop gave up. */ + attempts: number; + /** The stable error code of the last failed attempt. */ + code: string; + /** The human-readable message of the last failed attempt. */ + message: string; +}; + +/** + * Payload of the `listenerError` lifecycle event, emitted when one of the + * client's own listeners throws. The exception is isolated so it cannot break + * the socket handler or the other listeners; this event surfaces it. + */ +export type HermesListenerErrorEvent = { + /** The event name whose listener threw. */ + event: string; + /** The thrown value. */ + error: unknown; +}; + +/** + * Lifecycle events with a typed payload. Any other event name is a CDP event + * and receives a {@link HermesCdpEvent}. + */ +export type HermesClientEventMap = { + contextCreated: HermesContextCreatedEvent; + contextDestroyed: HermesContextDestroyedEvent; + disconnected: HermesDisconnectedEvent; + reconnected: HermesReconnectedEvent; + reconnectFailed: HermesReconnectFailedEvent; + listenerError: HermesListenerErrorEvent; +}; + +type HermesClientStatus = 'idle' | 'connecting' | 'open' | 'closed'; + +type HermesEventListener = (payload: never) => void; + +type PendingCall = { + /** The CDP method, used in error messages. */ + method: string; + /** Per-call timeout handle. */ + timer: ReturnType; + /** Removes the abort listener, if one was registered. */ + detachAbort: () => void; + /** Resolves the caller exactly once. */ + resolve: (result: HermesCdpResult) => void; +}; + +/** + * Persistent, verified Hermes CDP connection. + * + * Create one per session, call {@link send} for CDP methods (it connects on the + * first call), subscribe with {@link on}, and call {@link close} when done: an + * open socket keeps the Node process alive. + * + * One socket serves every call, so CDP domain state lasts across calls until + * the socket is lost or closed: an enabled domain (`Debugger.enable`), + * breakpoints, a paused debugger, object groups. `runHermesCdp` opened and + * closed a socket per call, which reset that state each time; callers that + * set such state should undo it (or {@link close} the client) when done. + * + * Reloads keep the socket open, so a closed socket only means a lost connection + * (Metro restart). When `trackContexts` is on (it is off by default, see + * {@link HermesClientOptions.trackContexts} for its cost), the client enables + * `Runtime` context events and emits a `contextCreated` lifecycle event for + * every new JavaScript context on the open socket, so callers can re-apply + * their scripts. + * + * An unexpected socket loss starts a background reconnect loop. A caller's + * {@link connect} or {@link send} never stops that loop, and a successful one is + * reported as `contextCreated` with `reason: 'reconnect'`. When the loop gives + * up (after `maxAttempts`, or at once when no `WebSocket` implementation + * exists) it emits `reconnectFailed` and the client stays disconnected. + * While the connection is lost, a failed caller-driven attempt continues a + * running loop, or restarts a stopped one from the first backoff delay. The + * decision depends only on that caller's own failure: every code restarts the + * loop except `HERMES_WEBSOCKET_UNAVAILABLE`. A device pin mismatch is + * retryable (Metro may list the other device first after a restart); the pin + * filter means a socket is never opened to, or adopted for, the wrong device. + * A client that only listens should handle `reconnectFailed`: nothing else + * retries for it. + * + * A listener that throws is isolated and reported through the `listenerError` + * lifecycle event; it never breaks the socket handler or the other listeners. + */ +export class HermesClient { + readonly #metroPort: number; + + readonly #appId: string; + + readonly #origin: string | undefined; + + readonly #onPin: ((logicalDeviceId: string) => void) | undefined; + + readonly #reconnect: Required; + + readonly #trackContexts: boolean; + + readonly #listeners = new Map>(); + + readonly #pending = new Map(); + + #pinnedDeviceId: string | undefined; + + #socket: WebSocket | undefined; + + /** + * The socket of an in-flight connect, before it is adopted. Kept so + * {@link close} can abandon the connect promptly. + */ + #connectingSocket: WebSocket | undefined; + + #target: HermesConnectedTarget | undefined; + + #status: HermesClientStatus = 'idle'; + + #nextId = 1; + + /** + * Whether the adopted socket streams `Runtime` execution-context events. + * True while `Runtime.enable` is in flight or succeeded; false when + * `trackContexts` is off or `Runtime.enable` failed. + */ + #socketTracksContexts = false; + + /** + * Whether the first execution context of the adopted socket was already seen. + * The connect `contextCreated` event covers it, so it is not re-emitted. + */ + #sawContextOnSocket = false; + + /** + * Whether a `contextDestroyed` event was already emitted for the current + * reload; coalesces `executionContextDestroyed` and + * `executionContextsCleared`. Also marks a reload in progress, so the next + * context is reported as `reload` even when the socket never reported its + * first context. + */ + #contextDestroyedForReload = false; + + /** + * Whether the adopted socket was reported to listeners with `contextCreated`. + * A socket is adopted before `Runtime.enable` runs; if it is lost before the + * connect completes, the connect fails and no `disconnected` is emitted for a + * connection listeners never saw. + */ + #socketReported = false; + + /** + * Whether the last connection was lost unexpectedly (not through + * {@link close}). Set on an unexpected loss, cleared on a successful connect + * and by {@link close}. Drives the `reconnect` reason of a caller-driven + * connect and whether a failed caller-driven attempt restarts the loop. + */ + #socketLost = false; + + #inFlightConnect: Promise | undefined; + + #reconnectTimer: ReturnType | undefined; + + #reconnectAttempt = 0; + + /** + * Whether the background reconnect loop is running: a backoff timer is + * pending, or an attempt (its own or a caller's it waits on) is in flight. + * False before any loss, after a successful connect, after {@link close}, + * and once the loop gave up. + */ + #reconnectRunning = false; + + /** + * Bumped every time the loop starts, stops or resets, so an attempt that was + * in flight across that change does not schedule (or report) anything. + */ + #reconnectGeneration = 0; + + #explicitlyClosed = false; + + /** + * Bumped by {@link close}. A connect started under an older epoch was + * abandoned: it must not pin, call `onPin`, adopt its socket, touch the + * connection state or emit events, and a reopen never joins it. + */ + #connectEpoch = 0; + + constructor(options: HermesClientOptions) { + this.#metroPort = options.metroPort; + this.#appId = options.appId; + this.#origin = options.origin; + // An empty pin means no pin, as in the one-shot path's `!pinnedDeviceId`. + this.#pinnedDeviceId = options.pinnedDeviceId || undefined; + this.#onPin = options.onPin; + this.#trackContexts = options.trackContexts ?? false; + this.#reconnect = { + initialDelayMs: + options.reconnect?.initialDelayMs ?? DEFAULT_RECONNECT_INITIAL_DELAY_MS, + maxDelayMs: + options.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS, + maxAttempts: + options.reconnect?.maxAttempts ?? DEFAULT_RECONNECT_MAX_ATTEMPTS, + connectTimeoutMs: + options.reconnect?.connectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS, + }; + } + + /** + * The Metro inspector proxy port this client discovers targets on. + * + * @returns The configured port. + */ + get metroPort(): number { + return this.#metroPort; + } + + /** + * The app bundle identifier this client strictly matches targets against. + * + * @returns The configured app id. + */ + get appId(): string { + return this.#appId; + } + + /** + * Whether an adopted, verified socket is currently open. + * + * @returns True while the client can send without connecting. + */ + get isConnected(): boolean { + return this.#status === 'open' && this.#socket !== undefined; + } + + /** + * Discovers, opens, verifies and adopts a Hermes target. + * + * Idempotent: when already connected it resolves with the current target, and + * concurrent callers share one in-flight connect (one discovery fetch, one + * socket, one identity probe). A caller that joins a connect already in + * flight waits for it at most its own `timeoutMs`, then gets + * `HERMES_TIMEOUT` while the connect keeps running. Emits `contextCreated` + * on success, with `reason: 'reconnect'` when the previous connection was + * lost unexpectedly. + * A client closed with {@link close} reopens. + * + * A connect never stops the background reconnect loop. When it fails while + * the connection is lost and the loop has stopped (it gave up), the loop + * restarts from the first backoff delay, unless this connect's own failure is + * `HERMES_WEBSOCKET_UNAVAILABLE`, the only terminal failure. A running loop + * keeps its own schedule. + * + * @param options - The connect timeout. + * @returns The verified target or a classified failure. + */ + async connect(options: HermesConnectOptions): Promise { + const { timeoutMs } = options; + this.#explicitlyClosed = false; + + if (this.isConnected && this.#target) { + return { ok: true, target: this.#target }; + } + + const joined = this.#inFlightConnect; + if (joined) { + // Another caller or the reconnect loop owns this connect and its + // timeouts: wait for it at most this call's own timeout. It keeps running + // for the others when this call stops waiting. + return await waitAtMost(joined, timeoutMs); + } + + const epoch = this.#connectEpoch; + const result = await this.#connectOnce(timeoutMs); + if (epoch === this.#connectEpoch) { + this.#resumeReconnectAfterFailedCall(result); + } + return result; + } + + /** + * Sends one CDP method over the persistent socket and awaits its response. + * + * Connects first when needed; see {@link HermesSendOptions.timeoutMs} for how + * the timeout applies to the connect and the response. Many calls can be in + * flight: responses are matched by CDP `id`. On timeout the call fails with + * `HERMES_TIMEOUT`; on abort with `HERMES_ABORTED`. Both remove the pending + * entry, so a late response is ignored. A CDP-level error becomes + * `HERMES_CDP_FAILED`. + * + * @param method - The CDP method, e.g. `Runtime.evaluate`. + * @param params - The CDP parameters. + * @param options - Per-call timeout and optional abort signal. + * @returns The raw CDP `result`, or a classified failure. + */ + async send( + method: string, + params: Record | undefined, + options: HermesSendOptions, + ): Promise { + const { timeoutMs, signal } = options; + + const blocked = createBlockedMethodResult(method); + if (blocked) { + return blocked; + } + if (this.#explicitlyClosed) { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: CLIENT_CLOSED_MESSAGE, + }; + } + if (signal?.aborted) { + return abortedResult(method); + } + + if (!this.isConnected) { + const connected = await this.#connectWithAbort(timeoutMs, signal); + if (connected === undefined) { + return abortedResult(method); + } + if (!connected.ok) { + return connected; + } + } + if (signal?.aborted) { + return abortedResult(method); + } + + const socket = this.#socket; + if (socket === undefined) { + return connectionNotOpenResult(); + } + if (socket.readyState !== WebSocket.OPEN) { + return connectionNotOpenResult(); + } + + const id = this.#nextId; + this.#nextId += 1; + const response = new Promise((resolve) => { + const timer = setTimeout(() => { + this.#settle(id, { + ok: false, + code: HERMES_TIMEOUT, + message: `Hermes CDP call timed out after ${timeoutMs}ms`, + }); + }, timeoutMs); + unrefTimer(timer); + + let detachAbort = (): void => undefined; + if (signal) { + const handleAbort = (): void => { + this.#settle(id, abortedResult(method)); + }; + signal.addEventListener('abort', handleAbort); + detachAbort = (): void => { + signal.removeEventListener('abort', handleAbort); + }; + } + + this.#pending.set(id, { method, timer, detachAbort, resolve }); + }); + + try { + socket.send(JSON.stringify({ id, method, params: params ?? {} })); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + this.#settle(id, { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `Hermes CDP connection failed: ${message}`, + }); + } + + return await response; + } + + /** + * Subscribes to a lifecycle event or a CDP event. + * + * Lifecycle names are the keys of {@link HermesClientEventMap}: + * `contextCreated`, `contextDestroyed`, `disconnected`, `reconnected`, + * `reconnectFailed` and `listenerError`. Any other name receives the CDP + * event messages of that `method` (for example `Runtime.consoleAPICalled`). + * + * @param event - The lifecycle event name or CDP method name. + * @param listener - Called with the typed lifecycle payload or the CDP event. + */ + on( + event: EventName, + listener: (payload: HermesClientEventMap[EventName]) => void, + ): void; + + on(event: string, listener: (payload: HermesCdpEvent) => void): void; + + on(event: string, listener: HermesEventListener): void { + let listeners = this.#listeners.get(event); + if (!listeners) { + listeners = new Set(); + this.#listeners.set(event, listeners); + } + listeners.add(listener); + } + + /** + * Removes a listener previously added with {@link on}. + * + * @param event - The event name the listener was registered for. + * @param listener - The listener reference to remove. + */ + off( + event: EventName, + listener: (payload: HermesClientEventMap[EventName]) => void, + ): void; + + off(event: string, listener: (payload: HermesCdpEvent) => void): void; + + off(event: string, listener: HermesEventListener): void { + this.#listeners.get(event)?.delete(listener); + } + + /** + * Stops reconnecting, closes the socket and fails pending calls. + * + * Call it when done: the client's timers are unref'd, but an open WebSocket + * keeps the Node process alive. + * + * An in-flight connect is abandoned: its callers get a failure, it closes any + * socket it opened, and it never pins, adopts or emits. Idempotent. A later + * {@link connect} reopens the client with a fresh connect. + */ + close(): void { + this.#explicitlyClosed = true; + this.#connectEpoch += 1; + this.#inFlightConnect = undefined; + this.#socketLost = false; + this.#resetReconnect(); + this.#failAllPending( + HERMES_CONNECTION_FAILED, + `${CLIENT_CLOSED_MESSAGE}: the connection was closed`, + ); + + const socket = this.#socket; + this.#socket = undefined; + this.#target = undefined; + this.#status = 'closed'; + + if (socket) { + this.#detachSocket(); + closeSocket(socket); + } + + const connecting = this.#connectingSocket; + this.#connectingSocket = undefined; + if (connecting) { + closeSocket(connecting); + } + } + + /** + * Shares one in-flight connect between concurrent callers and emits the + * connect lifecycle events once. + * + * The `reconnect` reason is taken from the connection state at the start of + * the attempt: after an unexpected socket loss the next successful connect is + * a reconnect, whether the background loop or a caller triggered it. + * + * @param timeoutMs - The connect timeout. + * @param reconnectAttempts - Set for a background reconnect attempt, used for + * the `reconnected` payload. A caller-driven reconnect only emits + * `contextCreated`. + * @returns The connect result. + */ + async #connectOnce( + timeoutMs: number, + reconnectAttempts?: number, + ): Promise { + const existing = this.#inFlightConnect; + if (existing) { + return await existing; + } + + const reconnected = this.#socketLost; + const epoch = this.#connectEpoch; + const promise = this.#doConnect(timeoutMs, reconnected, epoch) + .then((result) => { + if (result.ok && epoch === this.#connectEpoch) { + this.#socketLost = false; + this.#socketReported = true; + this.#resetReconnect(); + if (reconnectAttempts !== undefined) { + this.#emit('reconnected', { + target: result.target, + attempts: reconnectAttempts, + }); + } + this.#emit('contextCreated', { + target: result.target, + reconnected, + reason: reconnected ? 'reconnect' : 'connect', + }); + } + return result; + }) + .finally(() => { + if (this.#inFlightConnect === promise) { + this.#inFlightConnect = undefined; + } + }); + + this.#inFlightConnect = promise; + return await promise; + } + + /** + * Discovers, opens, probes and adopts a target. Never throws. + * + * Every await is followed by an epoch check: a connect abandoned by + * {@link close} closes its own socket and returns without pinning, calling + * `onPin`, adopting the socket or changing the connection status, even when + * the client was reopened in the meantime. + * + * @param timeoutMs - The connect timeout. + * @param reconnected - True when the previous connection was lost + * unexpectedly, used to fail closed on a device pin mismatch. + * @param epoch - The {@link close} epoch this connect started in. + * @returns The verified target or a classified failure. + */ + async #doConnect( + timeoutMs: number, + reconnected: boolean, + epoch: number, + ): Promise { + if (typeof WebSocket !== 'function') { + this.#status = 'closed'; + return websocketUnavailableResult(); + } + + this.#status = 'connecting'; + let socket: WebSocket | undefined; + let adopted = false; + + try { + const targets = await fetchDiscoveryTargets(this.#metroPort, timeoutMs); + if (epoch !== this.#connectEpoch) { + return closedDuringConnectResult(); + } + + const selection = selectHermesTarget( + targets, + this.#appId, + this.#pinnedDeviceId, + ); + if (!selection.ok) { + const pinMismatch = this.#detectReconnectPinMismatch( + targets, + selection.code, + reconnected, + ); + if (pinMismatch) { + return pinMismatch; + } + return { + ok: false, + code: selection.code, + message: selection.message, + }; + } + + const url = selection.target.webSocketDebuggerUrl; + if (!url) { + return { + ok: false, + code: HERMES_INVALID_WS_URL, + message: 'Target is missing webSocketDebuggerUrl', + }; + } + const validation = validateWebSocketUrl(url, this.#metroPort); + if (!validation.ok) { + return { + ok: false, + code: HERMES_INVALID_WS_URL, + message: validation.message, + }; + } + + const origin = resolveWebSocketOrigin(url, this.#origin); + const WebSocketWithHeaders = WebSocket as typeof WebSocket & + (new ( + wsUrl: string, + options: { headers: { origin: string } }, + ) => WebSocket); + const connectingSocket = new WebSocketWithHeaders(url, { + headers: { origin }, + }); + socket = connectingSocket; + this.#connectingSocket = connectingSocket; + + await waitForSocketOpen(connectingSocket, timeoutMs); + if (epoch !== this.#connectEpoch) { + return closedDuringConnectResult(); + } + + // The probe runs once per socket, with id 1; user calls start at 2. + const probe = await runIdentityProbe(connectingSocket, timeoutMs, 1); + // Checked after every await of the connect path: a close() during the + // connect must not pin the device, call `onPin` or adopt the socket. + // close() closes this socket, which also fails the probe. + if (epoch !== this.#connectEpoch) { + return closedDuringConnectResult(); + } + if (!probe.ok) { + return { ok: false, code: probe.code, message: probe.message }; + } + + const targetDeviceId = selection.target.reactNative?.logicalDeviceId; + if (!targetDeviceId) { + return { + ok: false, + code: HERMES_NOT_VERIFIED, + message: 'Target is missing reactNative.logicalDeviceId', + }; + } + if (this.#pinnedDeviceId === undefined) { + this.#pinnedDeviceId = targetDeviceId; + this.#onPin?.(targetDeviceId); + } else if (this.#pinnedDeviceId !== targetDeviceId) { + return { + ok: false, + code: HERMES_DEVICE_PIN_MISMATCH, + message: `Hermes target device ${targetDeviceId} does not match session pin ${this.#pinnedDeviceId}`, + }; + } + + this.#adopt(connectingSocket); + adopted = true; + this.#status = 'open'; + + const target: HermesConnectedTarget = { + id: selection.target.id, + logicalDeviceId: targetDeviceId, + title: selection.target.title, + }; + this.#target = target; + + if (this.#trackContexts) { + // Mark tracking before sending: Hermes can emit the first + // `executionContextCreated` before the `Runtime.enable` response, and + // that first context must be recorded (so a later reload is not + // mistaken for it) even though it is not re-emitted. + this.#socketTracksContexts = true; + // Enabling contexts is best effort: a failure only disables the + // `contextCreated` / `contextDestroyed` lifecycle detection for this + // socket, it never fails the connect. + const enabled = await this.send('Runtime.enable', undefined, { + timeoutMs, + }); + // close() fails the pending Runtime.enable, so this also covers a + // close() while it was in flight. + if (epoch !== this.#connectEpoch) { + return closedDuringConnectResult(); + } + if (!enabled.ok) { + this.#socketTracksContexts = false; + this.#sawContextOnSocket = false; + if (!this.isConnected) { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: + 'Hermes CDP connection failed: the socket closed while enabling runtime events', + }; + } + } + } + + return { ok: true, target }; + } catch (error) { + // close() closes the connecting socket, which rejects the open wait. + if (epoch !== this.#connectEpoch) { + return closedDuringConnectResult(); + } + const message = error instanceof Error ? error.message : String(error); + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `Hermes CDP connection failed: ${message}`, + }; + } finally { + if (this.#connectingSocket === socket) { + this.#connectingSocket = undefined; + } + if (!adopted) { + // An abandoned connect must not mark a reopened client's connect (or + // its adopted socket) closed. + if (epoch === this.#connectEpoch) { + this.#status = 'closed'; + } + if (socket) { + closeSocket(socket); + } + } + } + } + + /** + * Awaits a connect, giving up with `undefined` as soon as the signal aborts. + * The shared connect itself keeps running for other callers. + * + * @param timeoutMs - The connect timeout. + * @param signal - The call's abort signal, if any. + * @returns The connect result, or undefined when the call was aborted. + */ + async #connectWithAbort( + timeoutMs: number, + signal: AbortSignal | undefined, + ): Promise { + const connecting = this.connect({ timeoutMs }); + if (!signal) { + return await connecting; + } + if (signal.aborted) { + return undefined; + } + + let handleAbort = (): void => undefined; + const aborted = new Promise((resolve) => { + handleAbort = (): void => resolve(undefined); + signal.addEventListener('abort', handleAbort, { once: true }); + }); + + try { + return await Promise.race([connecting, aborted]); + } finally { + signal.removeEventListener('abort', handleAbort); + } + } + + /** + * Restarts the stopped reconnect loop from the first backoff delay after a + * caller-driven connect failed while the connection was lost, so a client + * whose loop gave up recovers once a caller tries again. + * + * Does nothing after {@link close}, while the loop is still running, or when + * the failure is terminal (`HERMES_WEBSOCKET_UNAVAILABLE`): retrying cannot + * fix that. The decision depends only on this failure, not on how the loop + * stopped. + * + * @param result - The failed caller-driven connect result. + */ + #resumeReconnectAfterFailedCall(result: HermesConnectResult): void { + if (result.ok || !this.#socketLost || this.#explicitlyClosed) { + return; + } + if (isTerminalConnectFailure(result)) { + return; + } + this.#startReconnect(); + } + + /** + * Turns a pinned selection failure into `HERMES_DEVICE_PIN_MISMATCH` during a + * reconnect when Metro reports a different device. Inspection only: no socket + * is opened for the wrong device. The code is informative (it names the + * device Metro listed); the reconnect loop retries it like any other failure. + * + * @param targets - All discovered targets. + * @param code - The selection failure code. + * @param reconnected - True when the previous connection was lost. + * @returns The mismatch result, or undefined to keep the selection failure. + */ + #detectReconnectPinMismatch( + targets: Parameters[0], + code: string, + reconnected: boolean, + ): { ok: false; code: string; message: string } | undefined { + const pinnedDeviceId = this.#pinnedDeviceId; + if (!reconnected || !pinnedDeviceId || code !== HERMES_TARGET_NOT_FOUND) { + return undefined; + } + + const unpinned = selectHermesTarget(targets, this.#appId, undefined); + if (!unpinned.ok) { + return undefined; + } + // Never the pinned device: the pinned selection is this selection filtered + // by the pin, and it found nothing. + const deviceId = + unpinned.target.reactNative?.logicalDeviceId ?? ''; + return { + ok: false, + code: HERMES_DEVICE_PIN_MISMATCH, + message: `Hermes target device ${deviceId} does not match session pin ${pinnedDeviceId}`, + }; + } + + /** + * Adopts an open, verified socket: installs the dispatcher, resets the CDP id + * sequence for the new connection and closes any socket it replaces, so a + * reconnect never leaks the previous socket. + * + * @param socket - The verified socket. + */ + #adopt(socket: WebSocket): void { + const previous = this.#socket; + this.#detachSocket(); + this.#socket = socket; + if (previous && previous !== socket) { + closeSocket(previous); + } + this.#nextId = 2; + this.#socketReported = false; + this.#socketTracksContexts = false; + this.#sawContextOnSocket = false; + this.#contextDestroyedForReload = false; + socket.addEventListener('message', this.#handleMessage); + socket.addEventListener('close', this.#handleClose); + socket.addEventListener('error', this.#handleError); + } + + /** + * Removes this client's listeners from the adopted socket, if any. + */ + #detachSocket(): void { + const socket = this.#socket; + if (!socket) { + return; + } + socket.removeEventListener('message', this.#handleMessage); + socket.removeEventListener('close', this.#handleClose); + socket.removeEventListener('error', this.#handleError); + } + + /** + * Dispatches one WebSocket frame: settles a matching pending call, or emits + * the frame as a CDP event. + * + * @param event - The WebSocket message event. + */ + readonly #handleMessage = (event: MessageEvent): void => { + if (typeof event.data !== 'string') { + this.#onSocketLost( + 'Hermes CDP returned a non-text WebSocket frame', + 'Hermes CDP connection failed: Hermes CDP returned a non-text WebSocket frame', + ); + return; + } + + let parsed: unknown; + try { + parsed = JSON.parse(event.data); + } catch { + return; + } + if (typeof parsed !== 'object' || parsed === null) { + return; + } + + const message = parsed as Record; + if (typeof message.id === 'number') { + this.#handleResponse(message); + return; + } + if (typeof message.method === 'string') { + this.#emit(message.method, { + method: message.method, + params: message.params, + }); + this.#trackExecutionContext(message.method, message.params); + } + }; + + /** + * Derives `contextCreated` / `contextDestroyed` lifecycle events from the + * `Runtime` execution-context events of the adopted socket. + * + * The first context of a socket is the one the connect `contextCreated` event + * already described, so it is not re-emitted. A later context means the app + * reloaded while the socket stayed open. + * + * @param method - The CDP event method. + * @param params - The CDP event payload. + */ + #trackExecutionContext(method: string, params: unknown): void { + if (!this.#socketTracksContexts) { + return; + } + + if (method === 'Runtime.executionContextCreated') { + this.#handleExecutionCreated(params); + return; + } + if ( + method === 'Runtime.executionContextDestroyed' || + method === 'Runtime.executionContextsCleared' + ) { + if (this.#contextDestroyedForReload) { + return; + } + this.#contextDestroyedForReload = true; + this.#emit('contextDestroyed', { reason: 'reload' }); + } + } + + /** + * Emits `contextCreated` for a reload. + * + * The first context of a socket is covered by the connect event and is not + * re-emitted, unless a `contextDestroyed{reload}` was already seen on this + * socket: some devices do not report the initial context, so the next one + * after a destroy is a reload, not the socket's first context. + * + * @param params - The `Runtime.executionContextCreated` payload. + */ + #handleExecutionCreated(params: unknown): void { + const executionContextId = readExecutionContextId(params); + if (!this.#sawContextOnSocket) { + this.#sawContextOnSocket = true; + if (!this.#contextDestroyedForReload) { + return; + } + } + + const target = this.#target; + if (!target) { + return; + } + + this.#contextDestroyedForReload = false; + const event: HermesContextCreatedEvent = { + target, + reconnected: false, + reason: 'reload', + }; + if (executionContextId !== undefined) { + event.executionContextId = executionContextId; + } + this.#emit('contextCreated', event); + } + + /** + * Settles the pending call whose id matches a CDP response. + * + * @param message - The parsed CDP response. + */ + #handleResponse(message: Record): void { + const id = message.id as number; + const pending = this.#pending.get(id); + if (!pending) { + return; + } + + if (typeof message.error === 'object' && message.error !== null) { + this.#settle(id, { + ok: false, + code: HERMES_CDP_FAILED, + message: `Hermes CDP "${pending.method}" failed: ${formatCdpError( + message.error, + )}`, + }); + return; + } + this.#settle(id, { ok: true, result: message.result }); + } + + /** + * Handles a socket close event from the adopted socket. + * + * @param event - The close event, read for its reason. + */ + readonly #handleClose = (event: Event): void => { + if (!this.#socket) { + return; + } + this.#onSocketLost(readCloseReason(event)); + }; + + /** + * Handles a socket error event. Node follows it with `close`; the adopted + * socket is released here so the error is not lost if it does not. + */ + readonly #handleError = (): void => { + this.#onSocketLost( + 'WebSocket error', + 'Hermes CDP connection failed: WebSocket message error', + ); + }; + + /** + * Releases the adopted socket after an unexpected loss, fails pending calls, + * starts the reconnect loop and then emits `disconnected`. + * + * The loop starts first on purpose: a `disconnected` listener may call + * {@link send}, and the socket it opens must already be the one the next + * scheduled attempt finds. + * + * A socket lost before its connect completed (during `Runtime.enable`) was + * never reported: it is released and its pending calls fail, which fails the + * connect, but the connection state is left as it was and no `disconnected` + * is emitted. The failed connect then follows the normal rules: a first + * connect simply fails, and a reconnect continues or restarts the loop. + * + * @param reason - Why the socket was lost, used for the `disconnected` event. + * @param pendingMessage - Overrides the pending-call failure message. + */ + #onSocketLost(reason: string, pendingMessage?: string): void { + const socket = this.#socket; + if (!socket) { + return; + } + + const reported = this.#socketReported; + this.#detachSocket(); + this.#socket = undefined; + this.#socketReported = false; + this.#target = undefined; + this.#status = 'closed'; + if (reported) { + this.#socketLost = true; + } + closeSocket(socket); + + this.#failAllPending( + HERMES_CONNECTION_FAILED, + pendingMessage ?? `Hermes CDP connection closed: ${reason}`, + ); + + if (!reported) { + return; + } + if (!this.#explicitlyClosed) { + this.#startReconnect(); + } + this.#emit('disconnected', { reason }); + } + + /** + * Starts the reconnect loop from the first backoff delay, unless it is + * already running or auto-reconnect is disabled (`maxAttempts: 0`). + */ + #startReconnect(): void { + if ( + this.#explicitlyClosed || + this.#reconnectRunning || + this.#reconnect.maxAttempts === 0 + ) { + return; + } + this.#reconnectGeneration += 1; + this.#reconnectRunning = true; + this.#reconnectAttempt = 0; + this.#scheduleReconnect(); + } + + /** + * Schedules the next reconnect attempt with exponential backoff, or gives up + * after `maxAttempts`: it then emits `reconnectFailed` and the client stays + * disconnected until a caller connects. + * + * @param failure - The failure of the attempt that just ran, reported by + * `reconnectFailed` if the loop gives up now. + */ + #scheduleReconnect(failure?: HermesFailureResult): void { + if (this.#explicitlyClosed || this.#reconnectTimer !== undefined) { + return; + } + if (this.#reconnectAttempt >= this.#reconnect.maxAttempts) { + this.#stopReconnect( + failure ?? { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'Hermes CDP reconnect gave up', + }, + ); + return; + } + + const delay = Math.min( + this.#reconnect.initialDelayMs * 2 ** this.#reconnectAttempt, + this.#reconnect.maxDelayMs, + ); + this.#reconnectAttempt += 1; + + const timer = setTimeout(() => { + this.#reconnectTimer = undefined; + this.#attemptReconnect().catch(() => undefined); + }, delay); + unrefTimer(timer); + this.#reconnectTimer = timer; + } + + /** + * Runs one reconnect attempt. Called only from the backoff timer, which + * every successful connect and every {@link close} clear, so the client is + * open and disconnected when it starts. + * + * A caller (for example a `disconnected` listener) may have started a + * connect before the timer fired; the attempt waits for it, and a second + * socket is never opened. Failures, including a device pin mismatch, + * schedule the next backoff step; a missing WebSocket stops the loop at once + * (and emits `reconnectFailed`). Never rejects. + */ + async #attemptReconnect(): Promise { + const generation = this.#reconnectGeneration; + // A caller's connect is already in flight, with the caller's (possibly + // shorter) timeouts. Wait for it instead of opening a second socket; if it + // fails, this attempt then runs its own connect with the full + // `connectTimeoutMs`. Connect promises never reject. + let callerConnect = this.#inFlightConnect; + while (callerConnect) { + await callerConnect; + // Every successful connect and every close() bumps the generation (via + // #resetReconnect), so an unchanged generation means the client is still + // disconnected and this loop still owns the retry. + if (generation !== this.#reconnectGeneration) { + return; + } + callerConnect = this.#inFlightConnect; + } + const result = await this.#connectOnce( + this.#reconnect.connectTimeoutMs, + this.#reconnectAttempt, + ); + // Same rule: a success (`result.ok`), a close() or a restart while this + // attempt was in flight already decided what happens next. `result.ok` + // only narrows the type: a success always changed the generation. + if (generation !== this.#reconnectGeneration || result.ok) { + return; + } + if (isTerminalConnectFailure(result)) { + this.#stopReconnect(result); + return; + } + this.#scheduleReconnect(result); + } + + /** + * Stops the reconnect loop for good (until a caller restarts it) and emits + * `reconnectFailed` once. + * + * @param failure - The failure of the last attempt. + */ + #stopReconnect(failure: HermesFailureResult): void { + this.#clearReconnectTimer(); + this.#reconnectGeneration += 1; + this.#reconnectRunning = false; + this.#status = 'closed'; + this.#emit('reconnectFailed', { + attempts: this.#reconnectAttempt, + code: failure.code, + message: failure.message, + }); + } + + /** + * Stops the reconnect loop after a successful connect or {@link close}: clears + * the pending timer and resets the backoff counter. + */ + #resetReconnect(): void { + this.#clearReconnectTimer(); + this.#reconnectGeneration += 1; + this.#reconnectRunning = false; + this.#reconnectAttempt = 0; + } + + /** + * Clears the pending reconnect timer, if any. + */ + #clearReconnectTimer(): void { + if (this.#reconnectTimer !== undefined) { + clearTimeout(this.#reconnectTimer); + this.#reconnectTimer = undefined; + } + } + + /** + * Fails every pending call with the same code and message. + * + * @param code - The stable error code. + * @param message - The human-readable message. + */ + #failAllPending(code: string, message: string): void { + for (const id of [...this.#pending.keys()]) { + this.#settle(id, { ok: false, code, message }); + } + } + + /** + * Resolves one pending call and removes it, so a late response is ignored. + * + * @param id - The CDP message id of the pending call. + * @param result - The result to resolve with. + */ + #settle(id: number, result: HermesCdpResult): void { + const pending = this.#pending.get(id); + if (!pending) { + return; + } + this.#pending.delete(id); + clearTimeout(pending.timer); + pending.detachAbort(); + pending.resolve(result); + } + + /** + * Calls every listener registered for an event. + * + * A throwing listener is isolated (the socket handler and the other listeners + * keep working) and reported to the `listenerError` listeners. A throwing + * `listenerError` listener is swallowed, so the report never recurses. + * + * @param event - The lifecycle event name or CDP method name. + * @param payload - The payload to deliver. + */ + #emit(event: string, payload: unknown): void { + const listeners = this.#listeners.get(event); + if (!listeners) { + return; + } + for (const listener of [...listeners]) { + try { + (listener as (value: unknown) => void)(payload); + } catch (error) { + if (event !== LISTENER_ERROR_EVENT) { + this.#emitListenerError(event, error); + } + } + } + } + + /** + * Reports a throwing listener to the `listenerError` listeners. + * + * @param event - The event name whose listener threw. + * @param error - The thrown value. + */ + #emitListenerError(event: string, error: unknown): void { + const listeners = this.#listeners.get(LISTENER_ERROR_EVENT); + if (!listeners) { + return; + } + const payload: HermesListenerErrorEvent = { event, error }; + for (const listener of [...listeners]) { + try { + (listener as (value: HermesListenerErrorEvent) => void)(payload); + } catch { + // A failing `listenerError` listener must not recurse or break the + // socket handler. + } + } + } +} + +/** + * Builds the failure result for a connect that was still in flight when the + * client was closed. + * + * @returns A `HERMES_CONNECTION_FAILED` failure. + */ +function closedDuringConnectResult(): HermesFailureResult { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: `${CLIENT_CLOSED_MESSAGE} before the connection completed`, + }; +} + +/** + * Waits for a shared connect at most `timeoutMs`. The connect itself keeps + * running; only this wait stops. + * + * @param connecting - The shared in-flight connect. + * @param timeoutMs - The longest this caller waits, in milliseconds. + * @returns The connect result, or `HERMES_TIMEOUT` when the wait ran out first. + */ +async function waitAtMost( + connecting: Promise, + timeoutMs: number, +): Promise { + let timer: ReturnType | undefined; + const timedOut = new Promise((resolve) => { + timer = setTimeout(() => { + resolve({ + ok: false, + code: HERMES_TIMEOUT, + message: `Hermes CDP connect did not complete within ${timeoutMs}ms`, + }); + }, timeoutMs); + unrefTimer(timer); + }); + + try { + return await Promise.race([connecting, timedOut]); + } finally { + clearTimeout(timer); + } +} + +/** + * Whether a connect failure is terminal for the reconnect loop: retrying cannot + * fix a missing WebSocket implementation. A device pin mismatch is NOT + * terminal: target selection filters by the pin, so no socket is ever opened to + * the other device, and the pinned device may register with Metro later. + * + * @param result - The failed connect result. + * @returns True when the loop must stop and not restart on its own. + */ +function isTerminalConnectFailure(result: HermesFailureResult): boolean { + return result.code === HERMES_WEBSOCKET_UNAVAILABLE; +} + +/** + * Builds the failure result for a call made while the socket is not open. + * + * @returns A `HERMES_CONNECTION_FAILED` failure. + */ +function connectionNotOpenResult(): HermesCdpResult { + return { + ok: false, + code: HERMES_CONNECTION_FAILED, + message: 'Hermes CDP connection is not open', + }; +} + +/** + * Builds the failure result for an aborted call. + * + * @param method - The CDP method that was aborted. + * @returns A `HERMES_ABORTED` failure. + */ +function abortedResult(method: string): HermesCdpResult { + return { + ok: false, + code: HERMES_ABORTED, + message: `Hermes CDP call "${method}" was aborted`, + }; +} + +/** + * Reads the execution context id from a `Runtime.executionContextCreated` + * payload. + * + * @param params - The CDP event payload. + * @returns The numeric context id, or undefined when absent. + */ +function readExecutionContextId(params: unknown): number | undefined { + if (typeof params !== 'object' || params === null) { + return undefined; + } + const { context } = params as { context?: unknown }; + if (typeof context !== 'object' || context === null) { + return undefined; + } + const { id } = context as { id?: unknown }; + return typeof id === 'number' ? id : undefined; +} + +/** + * Reads the close reason from a close event, tolerating a plain `Event`. + * + * @param event - The socket close event. + * @returns The close reason, or `socket closed` when empty. + */ +function readCloseReason(event: Event): string { + const { reason } = event as { reason?: unknown }; + return typeof reason === 'string' && reason.length > 0 + ? reason + : 'socket closed'; +} + +/** + * Unrefs a Node timer so the client's own timers (call timeouts, backoff) never + * keep the process alive. An open WebSocket still does: a connected client + * keeps Node running until {@link HermesClient.close} is called. + * + * @param timer - The timer handle (a `NodeJS.Timeout` in Node). + */ +function unrefTimer(timer: unknown): void { + if ( + typeof timer === 'object' && + timer !== null && + 'unref' in timer && + typeof (timer as { unref?: unknown }).unref === 'function' + ) { + (timer as { unref: () => void }).unref(); + } +} diff --git a/src/index.test.ts b/src/index.test.ts index a9ed952..e6b97c9 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1,6 +1,15 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, expectTypeOf } from 'vitest'; import * as publicApi from './index.js'; +import type { + HermesClientEventMap, + HermesContextCreatedEvent, + HermesContextDestroyedEvent, + HermesDisconnectedEvent, + HermesListenerErrorEvent, + HermesReconnectedEvent, + HermesReconnectFailedEvent, +} from './index.js'; describe('public API surface', () => { it('exports the element locator helpers consumers depend on', () => { @@ -28,6 +37,18 @@ describe('public API surface', () => { }); }); + it('exports HermesClient and every payload type of its event map', () => { + expect(typeof publicApi.HermesClient).toBe('function'); + expectTypeOf().toEqualTypeOf<{ + contextCreated: HermesContextCreatedEvent; + contextDestroyed: HermesContextDestroyedEvent; + disconnected: HermesDisconnectedEvent; + reconnected: HermesReconnectedEvent; + reconnectFailed: HermesReconnectFailedEvent; + listenerError: HermesListenerErrorEvent; + }>(); + }); + it('exports the typed idb transport error', () => { expect( new publicApi.IdbUnavailableError('IDB_HID_UNAVAILABLE', 'u', 'x').code, diff --git a/src/index.ts b/src/index.ts index fc49fa0..424a197 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,13 +47,34 @@ export { hasAmbiguousTarget, validateWebSocketUrl, LEGACY_SYNTHETIC_TITLE, + HERMES_ABORTED, } from './hermes/hermes-cdp.js'; export type { HermesTarget, HermesCdpResult, + HermesCdpErrorInfo, RunHermesCdpInput, } from './hermes/hermes-cdp.js'; +export { HermesClient } from './hermes/hermes-client.js'; +export type { + HermesClientOptions, + HermesClientReconnectOptions, + HermesConnectOptions, + HermesConnectResult, + HermesConnectedTarget, + HermesSendOptions, + HermesCdpEvent, + HermesClientEventMap, + HermesContextCreatedEvent, + HermesContextCreatedReason, + HermesContextDestroyedEvent, + HermesDisconnectedEvent, + HermesListenerErrorEvent, + HermesReconnectedEvent, + HermesReconnectFailedEvent, +} from './hermes/hermes-client.js'; + export { runWebViewCdp, fetchWebViewTargets,