@metamask/device-mcp 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/README.md +55 -2
  3. package/dist/backends/adb-backend.cjs +12 -5
  4. package/dist/backends/adb-backend.cjs.map +1 -1
  5. package/dist/backends/adb-backend.d.cts +8 -2
  6. package/dist/backends/adb-backend.d.cts.map +1 -1
  7. package/dist/backends/adb-backend.d.mts +8 -2
  8. package/dist/backends/adb-backend.d.mts.map +1 -1
  9. package/dist/backends/adb-backend.mjs +12 -5
  10. package/dist/backends/adb-backend.mjs.map +1 -1
  11. package/dist/backends/appium-backend.cjs +16 -7
  12. package/dist/backends/appium-backend.cjs.map +1 -1
  13. package/dist/backends/appium-backend.d.cts +8 -2
  14. package/dist/backends/appium-backend.d.cts.map +1 -1
  15. package/dist/backends/appium-backend.d.mts +8 -2
  16. package/dist/backends/appium-backend.d.mts.map +1 -1
  17. package/dist/backends/appium-backend.mjs +16 -7
  18. package/dist/backends/appium-backend.mjs.map +1 -1
  19. package/dist/backends/idb-backend.cjs +12 -5
  20. package/dist/backends/idb-backend.cjs.map +1 -1
  21. package/dist/backends/idb-backend.d.cts +8 -2
  22. package/dist/backends/idb-backend.d.cts.map +1 -1
  23. package/dist/backends/idb-backend.d.mts +8 -2
  24. package/dist/backends/idb-backend.d.mts.map +1 -1
  25. package/dist/backends/idb-backend.mjs +12 -5
  26. package/dist/backends/idb-backend.mjs.map +1 -1
  27. package/dist/backends/index.cjs +4 -3
  28. package/dist/backends/index.cjs.map +1 -1
  29. package/dist/backends/index.d.cts.map +1 -1
  30. package/dist/backends/index.d.mts.map +1 -1
  31. package/dist/backends/index.mjs +4 -3
  32. package/dist/backends/index.mjs.map +1 -1
  33. package/dist/backends/types.cjs.map +1 -1
  34. package/dist/backends/types.d.cts +19 -1
  35. package/dist/backends/types.d.cts.map +1 -1
  36. package/dist/backends/types.d.mts +19 -1
  37. package/dist/backends/types.d.mts.map +1 -1
  38. package/dist/backends/types.mjs.map +1 -1
  39. package/dist/hermes/hermes-cdp.cjs +674 -0
  40. package/dist/hermes/hermes-cdp.cjs.map +1 -0
  41. package/dist/hermes/hermes-cdp.d.cts +248 -0
  42. package/dist/hermes/hermes-cdp.d.cts.map +1 -0
  43. package/dist/hermes/hermes-cdp.d.mts +248 -0
  44. package/dist/hermes/hermes-cdp.d.mts.map +1 -0
  45. package/dist/hermes/hermes-cdp.mjs +665 -0
  46. package/dist/hermes/hermes-cdp.mjs.map +1 -0
  47. package/dist/hermes/session.cjs +196 -0
  48. package/dist/hermes/session.cjs.map +1 -0
  49. package/dist/hermes/session.d.cts +163 -0
  50. package/dist/hermes/session.d.cts.map +1 -0
  51. package/dist/hermes/session.d.mts +163 -0
  52. package/dist/hermes/session.d.mts.map +1 -0
  53. package/dist/hermes/session.mjs +189 -0
  54. package/dist/hermes/session.mjs.map +1 -0
  55. package/dist/index.cjs +16 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +5 -1
  58. package/dist/index.d.cts.map +1 -1
  59. package/dist/index.d.mts +5 -1
  60. package/dist/index.d.mts.map +1 -1
  61. package/dist/index.mjs +2 -0
  62. package/dist/index.mjs.map +1 -1
  63. package/dist/server.cjs +3 -0
  64. package/dist/server.cjs.map +1 -1
  65. package/dist/server.d.cts.map +1 -1
  66. package/dist/server.d.mts.map +1 -1
  67. package/dist/server.mjs +4 -1
  68. package/dist/server.mjs.map +1 -1
  69. package/dist/tools/hermes-cdp.cjs +102 -0
  70. package/dist/tools/hermes-cdp.cjs.map +1 -0
  71. package/dist/tools/hermes-cdp.d.cts +18 -0
  72. package/dist/tools/hermes-cdp.d.cts.map +1 -0
  73. package/dist/tools/hermes-cdp.d.mts +18 -0
  74. package/dist/tools/hermes-cdp.d.mts.map +1 -0
  75. package/dist/tools/hermes-cdp.mjs +99 -0
  76. package/dist/tools/hermes-cdp.mjs.map +1 -0
  77. package/dist/tools/hermes-targets.cjs +127 -0
  78. package/dist/tools/hermes-targets.cjs.map +1 -0
  79. package/dist/tools/hermes-targets.d.cts +20 -0
  80. package/dist/tools/hermes-targets.d.cts.map +1 -0
  81. package/dist/tools/hermes-targets.d.mts +20 -0
  82. package/dist/tools/hermes-targets.d.mts.map +1 -0
  83. package/dist/tools/hermes-targets.mjs +124 -0
  84. package/dist/tools/hermes-targets.mjs.map +1 -0
  85. package/dist/tools/index.cjs +5 -1
  86. package/dist/tools/index.cjs.map +1 -1
  87. package/dist/tools/index.d.cts +2 -0
  88. package/dist/tools/index.d.cts.map +1 -1
  89. package/dist/tools/index.d.mts +2 -0
  90. package/dist/tools/index.d.mts.map +1 -1
  91. package/dist/tools/index.mjs +2 -0
  92. package/dist/tools/index.mjs.map +1 -1
  93. package/dist/tools/screenshot.cjs +8 -3
  94. package/dist/tools/screenshot.cjs.map +1 -1
  95. package/dist/tools/screenshot.d.cts.map +1 -1
  96. package/dist/tools/screenshot.d.mts.map +1 -1
  97. package/dist/tools/screenshot.mjs +8 -3
  98. package/dist/tools/screenshot.mjs.map +1 -1
  99. package/dist/utils/output-path.cjs +128 -0
  100. package/dist/utils/output-path.cjs.map +1 -0
  101. package/dist/utils/output-path.d.cts +41 -0
  102. package/dist/utils/output-path.d.cts.map +1 -0
  103. package/dist/utils/output-path.d.mts +41 -0
  104. package/dist/utils/output-path.d.mts.map +1 -0
  105. package/dist/utils/output-path.mjs +123 -0
  106. package/dist/utils/output-path.mjs.map +1 -0
  107. package/package.json +1 -1
@@ -0,0 +1,674 @@
1
+ "use strict";
2
+ /**
3
+ * Pure Hermes Chrome DevTools Protocol (CDP) core for `@metamask/device-mcp`.
4
+ *
5
+ * Ported from `@metamask/client-mcp-core`'s `src/tools/hermes-cdp.ts`, decoupled
6
+ * from that repo's `ToolContext`/`ErrorCodes`/`createToolError|Success`. Every
7
+ * function here takes EXPLICIT parameters (port, appId, pin) and returns a
8
+ * discriminated {@link HermesCdpResult} so this module is MCP-free and
9
+ * unit-testable. The tools layer is responsible for resolving session state and
10
+ * for PERSISTING the device pin — this file never imports `HermesSession`.
11
+ *
12
+ * Mechanism: the React Native Hermes runtime connects out to Metro's inspector
13
+ * proxy; Metro exposes debuggable targets over `http://localhost:<metroPort>/json`
14
+ * and a per-target `webSocketDebuggerUrl`. We speak real CDP over that WebSocket
15
+ * using the GLOBAL `WebSocket` (no library) and the global `fetch` for discovery.
16
+ *
17
+ * Five fail-closed safety checks are preserved VERBATIM from the reference:
18
+ * 1. Strict `appId` match (`===`, no substring, no `targets[0]` fallback).
19
+ * 2. `HermesInternal.getRuntimeProperties()` identity probe before the user method.
20
+ * 3. Device pin on `reactNative.logicalDeviceId` (set on first success).
21
+ * 4. Multi-device fail-closed (missing or >1 distinct `logicalDeviceId`).
22
+ * 5. WebSocket URL validation (protocol/hostname/port).
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.IDENTITY_PROBE_EXPR = exports.LEGACY_SYNTHETIC_TITLE = exports.HERMES_WEBSOCKET_UNAVAILABLE = exports.HERMES_CDP_FAILED = exports.HERMES_TIMEOUT = exports.HERMES_CONNECTION_FAILED = exports.HERMES_INVALID_WS_URL = exports.HERMES_BLOCKED_METHOD = exports.HERMES_DEVICE_PIN_MISMATCH = exports.HERMES_MULTIPLE_DEVICES = exports.HERMES_NOT_VERIFIED = exports.HERMES_TARGET_NOT_FOUND = void 0;
26
+ exports.runHermesCdp = runHermesCdp;
27
+ exports.fetchDiscoveryTargets = fetchDiscoveryTargets;
28
+ exports.selectHermesTarget = selectHermesTarget;
29
+ exports.hasAmbiguousTarget = hasAmbiguousTarget;
30
+ exports.validateWebSocketUrl = validateWebSocketUrl;
31
+ exports.executeVerifiedCdpCommand = executeVerifiedCdpCommand;
32
+ /**
33
+ * No Hermes debug target matched the expected appId (after synthetic-title and
34
+ * pin filtering). Often means Metro is up but the app is not registered.
35
+ */
36
+ exports.HERMES_TARGET_NOT_FOUND = 'HERMES_TARGET_NOT_FOUND';
37
+ /**
38
+ * A target was found but could not be verified as the expected Hermes runtime
39
+ * (identity probe failed, missing `logicalDeviceId`, or non-JSON probe payload).
40
+ */
41
+ exports.HERMES_NOT_VERIFIED = 'HERMES_NOT_VERIFIED';
42
+ /**
43
+ * Multiple distinct logical devices are registered without a session pin (or a
44
+ * candidate is missing its `logicalDeviceId`); routing would be a guess, so we
45
+ * fail closed.
46
+ */
47
+ exports.HERMES_MULTIPLE_DEVICES = 'HERMES_MULTIPLE_DEVICES';
48
+ /**
49
+ * The resolved target's `logicalDeviceId` does not match the session pin.
50
+ */
51
+ exports.HERMES_DEVICE_PIN_MISMATCH = 'HERMES_DEVICE_PIN_MISMATCH';
52
+ /**
53
+ * The requested CDP method is in the destructive blocked set.
54
+ */
55
+ exports.HERMES_BLOCKED_METHOD = 'HERMES_BLOCKED_METHOD';
56
+ /**
57
+ * The target's `webSocketDebuggerUrl` failed protocol/hostname/port validation.
58
+ */
59
+ exports.HERMES_INVALID_WS_URL = 'HERMES_INVALID_WS_URL';
60
+ /**
61
+ * The underlying connection (discovery fetch or WebSocket) failed.
62
+ */
63
+ exports.HERMES_CONNECTION_FAILED = 'HERMES_CONNECTION_FAILED';
64
+ /**
65
+ * A discovery, socket-open, or CDP round-trip exceeded the configured timeout.
66
+ */
67
+ exports.HERMES_TIMEOUT = 'HERMES_TIMEOUT';
68
+ /**
69
+ * The user's CDP method returned a CDP-level error.
70
+ */
71
+ exports.HERMES_CDP_FAILED = 'HERMES_CDP_FAILED';
72
+ /**
73
+ * The global `WebSocket` constructor is unavailable in this Node runtime.
74
+ */
75
+ exports.HERMES_WEBSOCKET_UNAVAILABLE = 'HERMES_WEBSOCKET_UNAVAILABLE';
76
+ /**
77
+ * CDP methods blocked for safety. Ported VERBATIM from the reference — do not
78
+ * weaken.
79
+ */
80
+ const HERMES_BLOCKED_METHODS = new Set([
81
+ 'Runtime.terminateExecution',
82
+ 'Inspector.detached',
83
+ ]);
84
+ const DISCOVERY_PATHS = ['/json', '/json/list'];
85
+ const ALLOWED_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
86
+ /**
87
+ * Title of the synthetic legacy "Improved Chrome Reloads" page that Metro
88
+ * registers alongside the real Hermes target. Filtered out during selection.
89
+ * Ported VERBATIM from the reference.
90
+ */
91
+ exports.LEGACY_SYNTHETIC_TITLE = 'React Native Experimental (Improved Chrome Reloads)';
92
+ /**
93
+ * JavaScript expression evaluated against a candidate target BEFORE the user's
94
+ * method, to verify it is a genuine Hermes runtime. Copied VERBATIM from the
95
+ * reference — do not alter the verification semantics.
96
+ */
97
+ exports.IDENTITY_PROBE_EXPR = `(function () {
98
+ try {
99
+ var hi = typeof HermesInternal !== 'undefined' ? HermesInternal : null;
100
+ var p =
101
+ hi && typeof hi.getRuntimeProperties === 'function'
102
+ ? hi.getRuntimeProperties()
103
+ : null;
104
+ return JSON.stringify({
105
+ isHermes: !!hi,
106
+ ossVersion: p ? p['OSS Release Version'] : null,
107
+ debuggerEnabled: p ? p['Debugger Enabled'] : null,
108
+ });
109
+ } catch (e) {
110
+ return JSON.stringify({ error: String(e) });
111
+ }
112
+ })();`;
113
+ /**
114
+ * Orchestrates a single verified Hermes CDP command end to end.
115
+ *
116
+ * Resolves a target from Metro discovery, enforces all five fail-closed safety
117
+ * checks, runs the identity probe, persists the device pin via `onPin` on first
118
+ * success, sends the user's method, and returns the raw CDP `result`. The caller
119
+ * supplies the resolved port/appId/pin and persists the pin — this function is
120
+ * pure with respect to session state.
121
+ *
122
+ * @param input - Method, params, timeout, resolved port/appId/pin, and the pin
123
+ * persistence callback. See {@link RunHermesCdpInput}.
124
+ * @returns A discriminated {@link HermesCdpResult}.
125
+ */
126
+ async function runHermesCdp(input) {
127
+ if (HERMES_BLOCKED_METHODS.has(input.method)) {
128
+ return {
129
+ ok: false,
130
+ code: exports.HERMES_BLOCKED_METHOD,
131
+ message: `CDP method "${input.method}" is blocked for safety. ` +
132
+ `Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`,
133
+ };
134
+ }
135
+ if (typeof WebSocket !== 'function') {
136
+ return {
137
+ ok: false,
138
+ code: exports.HERMES_WEBSOCKET_UNAVAILABLE,
139
+ message: 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +
140
+ 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).',
141
+ };
142
+ }
143
+ try {
144
+ const targets = await fetchDiscoveryTargets(input.metroPort, input.timeoutMs);
145
+ const selection = selectHermesTarget(targets, input.appId, input.pinnedDeviceId);
146
+ if (!selection.ok) {
147
+ return { ok: false, code: selection.code, message: selection.message };
148
+ }
149
+ const validation = validateWebSocketUrl(selection.target.webSocketDebuggerUrl, input.metroPort);
150
+ if (!validation.ok) {
151
+ return {
152
+ ok: false,
153
+ code: exports.HERMES_INVALID_WS_URL,
154
+ message: validation.message,
155
+ };
156
+ }
157
+ return await executeVerifiedCdpCommand(selection.target, input, input.pinnedDeviceId, input.onPin);
158
+ }
159
+ catch (error) {
160
+ const message = error instanceof Error ? error.message : String(error);
161
+ return {
162
+ ok: false,
163
+ code: exports.HERMES_CONNECTION_FAILED,
164
+ message: `Hermes CDP connection failed: ${message}`,
165
+ };
166
+ }
167
+ }
168
+ /**
169
+ * Fetches debuggable Hermes targets from Metro, trying `/json` then falling
170
+ * back to `/json/list`. Each attempt is bounded by an `AbortController`
171
+ * timeout. The payload must be an array; non-object entries are filtered out.
172
+ *
173
+ * @param metroPort - The Metro inspector proxy port.
174
+ * @param timeoutMs - Per-attempt timeout in milliseconds.
175
+ * @returns The discovered targets (objects only).
176
+ * @throws The last error encountered if all discovery paths fail.
177
+ */
178
+ async function fetchDiscoveryTargets(metroPort, timeoutMs) {
179
+ let lastError;
180
+ for (const path of DISCOVERY_PATHS) {
181
+ const controller = new AbortController();
182
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
183
+ try {
184
+ const response = await fetch(`http://localhost:${metroPort}${path}`, {
185
+ signal: controller.signal,
186
+ });
187
+ if (!response.ok) {
188
+ throw new Error(`Metro ${path} returned HTTP ${response.status}`);
189
+ }
190
+ const payload = await response.json();
191
+ if (!Array.isArray(payload)) {
192
+ throw new Error(`Metro ${path} returned a non-array response`);
193
+ }
194
+ return payload.filter(isHermesTarget);
195
+ }
196
+ catch (error) {
197
+ lastError = error;
198
+ }
199
+ finally {
200
+ clearTimeout(timer);
201
+ }
202
+ }
203
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
204
+ }
205
+ /**
206
+ * Narrows an unknown discovery entry to a {@link HermesTarget} (object guard).
207
+ *
208
+ * @param value - A raw entry from the Metro discovery payload.
209
+ * @returns True when `value` is a non-null object.
210
+ */
211
+ function isHermesTarget(value) {
212
+ return typeof value === 'object' && value !== null;
213
+ }
214
+ /**
215
+ * Selects the single safe Hermes target for the expected app, applying the
216
+ * fail-closed selection algorithm VERBATIM from the reference:
217
+ *
218
+ * `webSocketDebuggerUrl` present → drop the synthetic legacy title → strict
219
+ * `appId` match (`===`) → pin filter → ambiguity check ({@link hasAmbiguousTarget})
220
+ * → `nativePageReloads` tiebreak → last-in-array.
221
+ *
222
+ * @param targets - All discovered targets.
223
+ * @param expectedAppId - The strict app bundle identifier to match.
224
+ * @param pinnedDeviceId - The session pin, if set, used to filter candidates.
225
+ * @returns The selected target or a classified failure.
226
+ */
227
+ function selectHermesTarget(targets, expectedAppId, pinnedDeviceId) {
228
+ const seenAppIds = [...new Set(targets.map((target) => target.appId))].filter((appId) => typeof appId === 'string');
229
+ let candidates = targets
230
+ .filter((target) => Boolean(target.webSocketDebuggerUrl))
231
+ .filter((target) => target.title !== exports.LEGACY_SYNTHETIC_TITLE)
232
+ .filter((target) => target.appId === expectedAppId);
233
+ if (pinnedDeviceId) {
234
+ candidates = candidates.filter((target) => target.reactNative?.logicalDeviceId === pinnedDeviceId);
235
+ }
236
+ if (candidates.length === 0) {
237
+ return {
238
+ ok: false,
239
+ code: exports.HERMES_TARGET_NOT_FOUND,
240
+ message: `No Hermes debug target found for appId ${expectedAppId}. Saw appIds: ${JSON.stringify(seenAppIds)}`,
241
+ };
242
+ }
243
+ if (hasAmbiguousTarget(candidates)) {
244
+ return {
245
+ ok: false,
246
+ code: exports.HERMES_MULTIPLE_DEVICES,
247
+ message: `Ambiguous Hermes target after pin filtering. Candidates: ${candidates
248
+ .map((target) => `${target.id ?? '<unknown>'} (device=${target.reactNative?.logicalDeviceId ?? '<missing>'})`)
249
+ .join(', ')}`,
250
+ };
251
+ }
252
+ // Same-device tiebreak: prefer pages with nativePageReloads (newer RN page
253
+ // registrations) over stale entries left behind after in-app reloads.
254
+ const nativeReloadTargets = candidates.filter((target) => target.reactNative?.capabilities?.nativePageReloads === true);
255
+ if (nativeReloadTargets.length > 0) {
256
+ candidates = nativeReloadTargets;
257
+ }
258
+ return { ok: true, target: candidates[candidates.length - 1] };
259
+ }
260
+ /**
261
+ * Determines whether a multi-candidate target list is too ambiguous to choose
262
+ * from safely. Returns true when:
263
+ * - any candidate is missing a `reactNative.logicalDeviceId` (we can't route safely), or
264
+ * - candidates resolve to more than one distinct `logicalDeviceId` (multi-device
265
+ * without a session pin — picking any one would silently bind the wrong device).
266
+ *
267
+ * Returns false when all candidates share the same logical device ID. In that
268
+ * case the caller falls through to the "last-in-array" tiebreak, matching the
269
+ * React Native convention that the most recent page registration wins (e.g.,
270
+ * stale + fresh page after an in-app reload).
271
+ *
272
+ * @param candidates - Targets remaining after appId/pin/capability filtering.
273
+ * @returns True when the caller must fail closed; false when tiebreak is safe.
274
+ */
275
+ function hasAmbiguousTarget(candidates) {
276
+ if (candidates.length <= 1) {
277
+ return false;
278
+ }
279
+ const deviceIds = candidates.map((target) => target.reactNative?.logicalDeviceId);
280
+ // Any candidate missing a logicalDeviceId → can't safely route.
281
+ if (deviceIds.some((id) => !id)) {
282
+ return true;
283
+ }
284
+ // Multiple distinct device IDs → multi-device without pin.
285
+ return new Set(deviceIds).size > 1;
286
+ }
287
+ /**
288
+ * Validates a target's `webSocketDebuggerUrl` before connecting. The protocol
289
+ * must be `ws:`, the hostname must be loopback (`localhost`, `127.0.0.1`, `::1`,
290
+ * or `[::1]`), and the port must equal the resolved Metro port. Ported VERBATIM
291
+ * from the reference.
292
+ *
293
+ * @param rawUrl - The candidate `webSocketDebuggerUrl`.
294
+ * @param expectedPort - The resolved Metro port the URL must point at.
295
+ * @returns `{ ok: true }` when valid, otherwise a failure with a message.
296
+ */
297
+ function validateWebSocketUrl(rawUrl, expectedPort) {
298
+ if (!rawUrl) {
299
+ return { ok: false, message: 'webSocketDebuggerUrl is missing' };
300
+ }
301
+ let parsed;
302
+ try {
303
+ parsed = new URL(rawUrl);
304
+ }
305
+ catch {
306
+ return {
307
+ ok: false,
308
+ message: `webSocketDebuggerUrl is not a valid URL: ${rawUrl}`,
309
+ };
310
+ }
311
+ if (parsed.protocol !== 'ws:') {
312
+ return { ok: false, message: `Unexpected protocol '${parsed.protocol}'` };
313
+ }
314
+ if (!ALLOWED_HOSTNAMES.has(parsed.hostname)) {
315
+ return { ok: false, message: `Unexpected hostname '${parsed.hostname}'` };
316
+ }
317
+ if (Number(parsed.port) !== expectedPort) {
318
+ return {
319
+ ok: false,
320
+ message: `Port mismatch: target=${parsed.port} expected=${expectedPort}`,
321
+ };
322
+ }
323
+ return { ok: true };
324
+ }
325
+ /**
326
+ * Opens the target WebSocket, runs the identity probe, enforces the device pin
327
+ * (persisting it via `onPin` on first success, failing closed on mismatch),
328
+ * sends the user's method, matches the response by `id`, and always closes the
329
+ * socket in a `finally`. Ported faithfully from the reference.
330
+ *
331
+ * @param target - The validated, selected target.
332
+ * @param input - The original {@link RunHermesCdpInput} (method/params/timeout).
333
+ * @param pinnedDeviceId - The session pin, if set.
334
+ * @param onPin - Callback to persist the resolved pin on first success.
335
+ * @returns A discriminated {@link HermesCdpResult}.
336
+ */
337
+ async function executeVerifiedCdpCommand(target, input, pinnedDeviceId, onPin) {
338
+ if (!target.webSocketDebuggerUrl) {
339
+ return {
340
+ ok: false,
341
+ code: exports.HERMES_INVALID_WS_URL,
342
+ message: 'Target is missing webSocketDebuggerUrl',
343
+ };
344
+ }
345
+ if (typeof WebSocket !== 'function') {
346
+ return {
347
+ ok: false,
348
+ code: exports.HERMES_WEBSOCKET_UNAVAILABLE,
349
+ message: 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +
350
+ 'NODE_OPTIONS="--experimental-websocket" (or use Node 22+).',
351
+ };
352
+ }
353
+ const socket = new WebSocket(target.webSocketDebuggerUrl);
354
+ let nextId = 1;
355
+ try {
356
+ await waitForSocketOpen(socket, input.timeoutMs);
357
+ const probe = await runIdentityProbe(socket, input.timeoutMs, nextId);
358
+ nextId += 1;
359
+ if (!probe.ok) {
360
+ return { ok: false, code: probe.code, message: probe.message };
361
+ }
362
+ const targetDeviceId = target.reactNative?.logicalDeviceId;
363
+ if (!targetDeviceId) {
364
+ return {
365
+ ok: false,
366
+ code: exports.HERMES_NOT_VERIFIED,
367
+ message: 'Target is missing reactNative.logicalDeviceId',
368
+ };
369
+ }
370
+ if (!pinnedDeviceId) {
371
+ onPin?.(targetDeviceId);
372
+ }
373
+ else if (pinnedDeviceId !== targetDeviceId) {
374
+ return {
375
+ ok: false,
376
+ code: exports.HERMES_DEVICE_PIN_MISMATCH,
377
+ message: `Hermes target device ${targetDeviceId} does not match session pin ${pinnedDeviceId}`,
378
+ };
379
+ }
380
+ const response = await sendUserMethod(socket, input, nextId);
381
+ nextId += 1;
382
+ if (isCdpErrorResponse(response)) {
383
+ return {
384
+ ok: false,
385
+ code: exports.HERMES_CDP_FAILED,
386
+ message: `Hermes CDP "${input.method}" failed: ${formatCdpError(response)}`,
387
+ };
388
+ }
389
+ return { ok: true, result: response.result };
390
+ }
391
+ finally {
392
+ closeSocket(socket);
393
+ }
394
+ }
395
+ /**
396
+ * Runs the {@link IDENTITY_PROBE_EXPR} against an open socket and verifies the
397
+ * response confirms a Hermes runtime. Distinguishes timeout from connection
398
+ * failure and unverified payloads.
399
+ *
400
+ * @param socket - The open target WebSocket.
401
+ * @param timeoutMs - Round-trip timeout in milliseconds.
402
+ * @param id - The CDP message id to use for this probe.
403
+ * @returns A {@link ProbeResult}.
404
+ */
405
+ async function runIdentityProbe(socket, timeoutMs, id) {
406
+ socket.send(JSON.stringify({
407
+ id,
408
+ method: 'Runtime.evaluate',
409
+ params: { expression: exports.IDENTITY_PROBE_EXPR, returnByValue: true },
410
+ }));
411
+ let response;
412
+ try {
413
+ response = await waitForCdpResponse(socket, id, timeoutMs);
414
+ }
415
+ catch (error) {
416
+ const message = error instanceof Error ? error.message : String(error);
417
+ if (message.includes('timed out')) {
418
+ return {
419
+ ok: false,
420
+ code: exports.HERMES_TIMEOUT,
421
+ message: `Identity probe timed out after ${timeoutMs}ms`,
422
+ };
423
+ }
424
+ return {
425
+ ok: false,
426
+ code: exports.HERMES_CONNECTION_FAILED,
427
+ message: `Hermes CDP connection failed: ${message}`,
428
+ };
429
+ }
430
+ if (isCdpErrorResponse(response)) {
431
+ return {
432
+ ok: false,
433
+ code: exports.HERMES_NOT_VERIFIED,
434
+ message: `Identity probe failed: ${formatCdpError(response)}`,
435
+ };
436
+ }
437
+ const remoteResult = getProbeRemoteResult(response);
438
+ if (remoteResult.subtype === 'error') {
439
+ return {
440
+ ok: false,
441
+ code: exports.HERMES_NOT_VERIFIED,
442
+ message: 'Identity probe evaluation returned an error subtype',
443
+ };
444
+ }
445
+ if (remoteResult.value === undefined || remoteResult.value === null) {
446
+ return {
447
+ ok: false,
448
+ code: exports.HERMES_NOT_VERIFIED,
449
+ message: 'Identity probe response missing result.value',
450
+ };
451
+ }
452
+ const raw = typeof remoteResult.value === 'string'
453
+ ? remoteResult.value
454
+ : JSON.stringify(remoteResult.value);
455
+ let parsed;
456
+ try {
457
+ parsed = JSON.parse(raw);
458
+ }
459
+ catch {
460
+ return {
461
+ ok: false,
462
+ code: exports.HERMES_NOT_VERIFIED,
463
+ message: `Identity probe returned non-JSON: ${raw}`,
464
+ };
465
+ }
466
+ if (!isHermesProbePayload(parsed)) {
467
+ return {
468
+ ok: false,
469
+ code: exports.HERMES_NOT_VERIFIED,
470
+ message: `Identity probe did not verify Hermes runtime: ${raw}`,
471
+ };
472
+ }
473
+ return { ok: true };
474
+ }
475
+ /**
476
+ * Safely extracts the nested CDP `result.result` (the remote object) from a
477
+ * `Runtime.evaluate` success response.
478
+ *
479
+ * @param response - A CDP success response.
480
+ * @returns The remote object's `subtype`/`value`, or an empty object.
481
+ */
482
+ function getProbeRemoteResult(response) {
483
+ if (typeof response.result !== 'object' || response.result === null) {
484
+ return {};
485
+ }
486
+ const outer = response.result;
487
+ if (typeof outer.result !== 'object' || outer.result === null) {
488
+ return {};
489
+ }
490
+ return outer.result;
491
+ }
492
+ /**
493
+ * Narrows a parsed probe payload to one confirming a Hermes runtime.
494
+ *
495
+ * @param value - The parsed probe JSON payload.
496
+ * @returns True when `isHermes === true`.
497
+ */
498
+ function isHermesProbePayload(value) {
499
+ return (typeof value === 'object' &&
500
+ value !== null &&
501
+ value.isHermes === true);
502
+ }
503
+ /**
504
+ * Sends the user's CDP method over an open, verified socket and awaits the
505
+ * matching response by id.
506
+ *
507
+ * @param socket - The open, verified target WebSocket.
508
+ * @param input - The original input carrying method/params/timeout.
509
+ * @param id - The CDP message id to use.
510
+ * @returns The matching CDP success or error response.
511
+ */
512
+ async function sendUserMethod(socket, input, id) {
513
+ socket.send(JSON.stringify({
514
+ id,
515
+ method: input.method,
516
+ params: input.params ?? {},
517
+ }));
518
+ return await waitForCdpResponse(socket, id, input.timeoutMs);
519
+ }
520
+ /**
521
+ * Resolves once the socket reaches the OPEN state, rejecting on error or
522
+ * timeout. Listeners are always cleaned up.
523
+ *
524
+ * @param socket - The connecting target WebSocket.
525
+ * @param timeoutMs - Connection timeout in milliseconds.
526
+ * @returns A promise that resolves when the socket is open.
527
+ */
528
+ async function waitForSocketOpen(socket, timeoutMs) {
529
+ if (socket.readyState === WebSocket.OPEN) {
530
+ return Promise.resolve();
531
+ }
532
+ return new Promise((resolve, reject) => {
533
+ let cleanup = () => undefined;
534
+ const handleOpen = () => {
535
+ cleanup();
536
+ resolve();
537
+ };
538
+ const handleError = () => {
539
+ cleanup();
540
+ reject(new Error('WebSocket connection error'));
541
+ };
542
+ const timer = setTimeout(() => {
543
+ cleanup();
544
+ reject(new Error(`WebSocket connection timed out after ${timeoutMs}ms`));
545
+ }, timeoutMs);
546
+ cleanup = () => {
547
+ clearTimeout(timer);
548
+ socket.removeEventListener('open', handleOpen);
549
+ socket.removeEventListener('error', handleError);
550
+ };
551
+ socket.addEventListener('open', handleOpen);
552
+ socket.addEventListener('error', handleError);
553
+ });
554
+ }
555
+ /**
556
+ * Resolves with the CDP response whose `id` matches, rejecting on socket error,
557
+ * premature close, or timeout. Listeners are always cleaned up.
558
+ *
559
+ * @param socket - The open target WebSocket.
560
+ * @param id - The CDP message id to match.
561
+ * @param timeoutMs - Round-trip timeout in milliseconds.
562
+ * @returns The matching CDP success or error response.
563
+ */
564
+ async function waitForCdpResponse(socket, id, timeoutMs) {
565
+ return new Promise((resolve, reject) => {
566
+ let cleanup = () => undefined;
567
+ const handleMessage = (event) => {
568
+ try {
569
+ const parsed = parseCdpResponse(event.data);
570
+ if (parsed?.id !== id) {
571
+ return;
572
+ }
573
+ cleanup();
574
+ resolve(parsed);
575
+ }
576
+ catch (error) {
577
+ cleanup();
578
+ reject(error);
579
+ }
580
+ };
581
+ const handleError = () => {
582
+ cleanup();
583
+ reject(new Error('WebSocket message error'));
584
+ };
585
+ const handleClose = () => {
586
+ cleanup();
587
+ reject(new Error('WebSocket closed before CDP response'));
588
+ };
589
+ const timer = setTimeout(() => {
590
+ cleanup();
591
+ reject(new Error(`Hermes CDP call timed out after ${timeoutMs}ms`));
592
+ }, timeoutMs);
593
+ cleanup = () => {
594
+ clearTimeout(timer);
595
+ socket.removeEventListener('message', handleMessage);
596
+ socket.removeEventListener('error', handleError);
597
+ socket.removeEventListener('close', handleClose);
598
+ };
599
+ socket.addEventListener('message', handleMessage);
600
+ socket.addEventListener('error', handleError);
601
+ socket.addEventListener('close', handleClose);
602
+ });
603
+ }
604
+ /**
605
+ * Parses a raw WebSocket frame into a CDP response, returning undefined when it
606
+ * is not an addressable (`id`-bearing) message.
607
+ *
608
+ * @param data - The raw `MessageEvent.data`.
609
+ * @returns A CDP success/error response, or undefined when not addressable.
610
+ * @throws When the frame is not a text frame.
611
+ */
612
+ function parseCdpResponse(data) {
613
+ if (typeof data !== 'string') {
614
+ throw new Error('Hermes CDP returned a non-text WebSocket frame');
615
+ }
616
+ const parsed = JSON.parse(data);
617
+ if (typeof parsed !== 'object' || parsed === null) {
618
+ return undefined;
619
+ }
620
+ const candidate = parsed;
621
+ if (typeof candidate.id !== 'number') {
622
+ return undefined;
623
+ }
624
+ if (isCdpError(candidate.error)) {
625
+ return { id: candidate.id, error: candidate.error };
626
+ }
627
+ return { id: candidate.id, result: candidate.result };
628
+ }
629
+ /**
630
+ * Narrows an unknown value to a CDP error object.
631
+ *
632
+ * @param value - The candidate `error` field.
633
+ * @returns True when `value` is a non-null object.
634
+ */
635
+ function isCdpError(value) {
636
+ return typeof value === 'object' && value !== null;
637
+ }
638
+ /**
639
+ * Discriminates a CDP response as an error response.
640
+ *
641
+ * @param response - A CDP success or error response.
642
+ * @returns True when the response carries an `error` field.
643
+ */
644
+ function isCdpErrorResponse(response) {
645
+ return 'error' in response;
646
+ }
647
+ /**
648
+ * Formats a CDP error response into a single human-readable line.
649
+ *
650
+ * @param response - The CDP error response.
651
+ * @returns A combined message including code and data when present.
652
+ */
653
+ function formatCdpError(response) {
654
+ const parts = [response.error.message ?? 'Unknown CDP error'];
655
+ if (typeof response.error.code === 'number') {
656
+ parts.push(`code ${response.error.code}`);
657
+ }
658
+ if (response.error.data !== undefined) {
659
+ parts.push(JSON.stringify(response.error.data));
660
+ }
661
+ return parts.join(' - ');
662
+ }
663
+ /**
664
+ * Closes the socket if it is still connecting or open.
665
+ *
666
+ * @param socket - The target WebSocket.
667
+ */
668
+ function closeSocket(socket) {
669
+ if (socket.readyState === WebSocket.CONNECTING ||
670
+ socket.readyState === WebSocket.OPEN) {
671
+ socket.close();
672
+ }
673
+ }
674
+ //# sourceMappingURL=hermes-cdp.cjs.map