@deeeed/metamask-harness 0.74.0 → 0.76.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 (96) hide show
  1. package/CHANGELOG.md +39 -1
  2. package/README.md +1 -1
  3. package/adapters/shared/ensure-runner-deps.sh +15 -3
  4. package/adapters/shared/reap-checkout-metros.sh +9 -0
  5. package/dist/action-values.js +15 -0
  6. package/dist/adapters/core/actions.js +20 -0
  7. package/dist/adapters/core/live-script-env.js +36 -0
  8. package/dist/adapters/core/overlay.js +34 -0
  9. package/dist/adapters/core/readiness.js +8 -0
  10. package/dist/adapters/core/run.js +54 -0
  11. package/dist/adapters/core/surface.js +12 -1
  12. package/dist/adapters/extension/action-inputs.js +206 -0
  13. package/dist/adapters/extension/actions.js +51 -0
  14. package/dist/adapters/extension/console-capture.js +13 -1
  15. package/dist/adapters/extension/doctor-checks.js +135 -0
  16. package/dist/adapters/extension/fixtures.js +103 -0
  17. package/dist/adapters/extension/launch.js +315 -0
  18. package/dist/adapters/extension/launched-browser.js +51 -0
  19. package/dist/adapters/extension/overlay.js +55 -0
  20. package/dist/adapters/extension/readiness.js +32 -0
  21. package/dist/adapters/extension/reload.js +40 -0
  22. package/dist/adapters/extension/run.js +105 -0
  23. package/dist/adapters/extension/surface.js +31 -3
  24. package/dist/adapters/harness-freshness.js +4 -2
  25. package/dist/adapters/mobile/actions.js +54 -0
  26. package/dist/adapters/mobile/devices.js +21 -0
  27. package/dist/adapters/mobile/doctor-checks.js +40 -0
  28. package/dist/adapters/mobile/fixtures.js +141 -0
  29. package/dist/adapters/mobile/launch.js +192 -0
  30. package/dist/adapters/mobile/lifecycle.js +300 -0
  31. package/dist/adapters/mobile/overlay.js +27 -0
  32. package/dist/adapters/mobile/prepare-target.js +38 -0
  33. package/dist/adapters/mobile/readiness.js +39 -0
  34. package/dist/adapters/mobile/reload.js +15 -0
  35. package/dist/adapters/mobile/run.js +156 -0
  36. package/dist/adapters/mobile/runtime-identity.js +34 -0
  37. package/dist/adapters/mobile/surface.js +39 -3
  38. package/dist/adapters/mobile/ui.js +701 -0
  39. package/dist/adapters/performance/cdp-trace.js +24 -6
  40. package/dist/adapters/performance/device-platform.js +10 -0
  41. package/dist/adapters/registry.js +1 -1
  42. package/dist/adapters/terminal/actions.js +43 -0
  43. package/dist/adapters/terminal/console-capture.js +14 -1
  44. package/dist/adapters/terminal/doctor-checks.js +22 -0
  45. package/dist/adapters/terminal/overlay.js +18 -0
  46. package/dist/adapters/terminal/readiness.js +11 -0
  47. package/dist/adapters/terminal/run.js +30 -0
  48. package/dist/adapters/terminal/surface.js +21 -3
  49. package/dist/adapters.js +32 -824
  50. package/dist/cli-commands.js +1 -0
  51. package/dist/cli.js +3 -1
  52. package/dist/command-contract.js +3 -0
  53. package/dist/commands/call.js +2 -5
  54. package/dist/commands/debug.js +6 -25
  55. package/dist/commands/device-target.js +2 -1
  56. package/dist/commands/doctor.js +26 -137
  57. package/dist/commands/fixtures.js +13 -217
  58. package/dist/commands/launch/device.js +2 -6
  59. package/dist/commands/launch/extension.js +3 -303
  60. package/dist/commands/launch/index.js +1 -1
  61. package/dist/commands/launch/mobile.js +2 -190
  62. package/dist/commands/launch/quote.js +7 -0
  63. package/dist/commands/logs.js +1 -1
  64. package/dist/commands/parse-args.js +9 -4
  65. package/dist/commands/pin.js +226 -0
  66. package/dist/commands/prepare.js +23 -53
  67. package/dist/commands/provision.js +3 -7
  68. package/dist/commands/reload.js +8 -47
  69. package/dist/commands/run-engine.js +38 -138
  70. package/dist/commands/run-report.js +4 -48
  71. package/dist/commands/run.js +6 -48
  72. package/dist/commands/runtime-decision.js +5 -27
  73. package/dist/commands/self-test.js +1 -3
  74. package/dist/commands/status.js +20 -28
  75. package/dist/commands/stop.js +1 -1
  76. package/dist/doctor.js +12 -120
  77. package/dist/execution-provenance.js +3 -2
  78. package/dist/harness-pin.js +10 -0
  79. package/dist/harness.js +31 -100
  80. package/dist/heal-bounds.js +3 -2
  81. package/dist/live-adapter-contract.js +8 -34
  82. package/dist/manifest.js +3 -5
  83. package/dist/metamask-action-validation.js +5 -196
  84. package/dist/mm-harness-cli.js +30 -4
  85. package/dist/network-observation.js +10 -3
  86. package/dist/paths.js +8 -2
  87. package/dist/performance-observation.js +15 -22
  88. package/dist/pr-body/render.js +3 -1
  89. package/dist/recording-target.js +4 -39
  90. package/dist/run-diagnostics.js +21 -60
  91. package/dist/run-recording.js +5 -4
  92. package/dist/runner.js +20 -368
  93. package/dist/runtime-context.js +12 -17
  94. package/docs/CONTRIBUTING.md +29 -7
  95. package/package.json +2 -1
  96. package/scripts/completions.sh +2 -1
@@ -5,15 +5,11 @@ import { runnerDir, walletFixturePath } from "../paths.js";
5
5
  import { getAdapterSurface } from "../adapters/surface.js";
6
6
  import { fixtureFileSummary, fixtureSummary } from "../doctor.js";
7
7
  import { acquireCheckoutLock } from "../checkout-lock.js";
8
- import { colorHumanMessage } from "../cli-color.js";
9
8
  import { applyDeviceTargeting } from "./device-target.js";
10
9
  import { ADAPTER_DETECT_NEXT, checkoutBusyOut, EXIT, flag, parseFlags, resolveAdapter, scriptOverride, spawnScript, spawnScriptStreaming, str, targetOf, usageOut } from "./shared.js";
11
- import { FeatureFlagSpecError, fixtureFeatureFlags, parseRemoteFlagSpec, sameFeatureFlags } from "../feature-flags.js";
12
- import { readExtensionPinnedFlags } from "../adapters/extension/feature-flags.js";
10
+ import { FeatureFlagSpecError, fixtureFeatureFlags, parseRemoteFlagSpec } from "../feature-flags.js";
13
11
  const FIXTURES_BOOLEANS = /* @__PURE__ */ new Set(["dev", "force", "json"]);
14
12
  const FIXTURE_STREAM_TIMEOUT_MS = 12e4;
15
- const FIXTURE_BRIDGE_READY_TIMEOUT_MS = 18e4;
16
- const MOBILE_SETUP_WALLET_TIMEOUT_MS = 36e4;
17
13
  async function handleFixtures(argv) {
18
14
  const { positional, options } = parseFlags(argv, FIXTURES_BOOLEANS);
19
15
  if (!positional[0]) return fixturesStatus(options);
@@ -52,7 +48,7 @@ function fixturesStatus(options) {
52
48
  const fixture = { ...summary, path: canonical };
53
49
  const ready = summary.status === "ready";
54
50
  const nextCommand = ready ? "mm-harness fixtures set" : "mm-harness fixtures init --from <path> # or: mm-harness fixtures init --dev";
55
- const operations = adapter === "extension" ? ["init", "sync", "set", "reset", "generate", "finalize"] : adapter === "mobile" ? ["init", "sync", "set", "reset"] : ["init", "sync", "set"];
51
+ const operations = [...getAdapterSurface(adapter).fixtures.operations];
56
52
  if (json) {
57
53
  console.log(JSON.stringify({
58
54
  schemaVersion: 1,
@@ -191,217 +187,16 @@ async function handleFixturesLocked(argv) {
191
187
  if (!(error instanceof FeatureFlagSpecError)) throw error;
192
188
  return usageOut(json, "fixtures", error.message, error.userAction);
193
189
  }
194
- const fixtureFlagsJson = JSON.stringify(fixtureFlags);
195
- if (adapter === "extension") {
196
- return applyExtensionFixture(target, fixturePath, canonicalFixture, json, sub, fixtureFlags);
197
- }
198
- const reset = sub === "reset";
199
- process.stderr.write(`\u2192 fixtures ${sub} ${adapter} \u2014 ${reset ? "resetting selected app data, relaunching, then applying" : "connecting bridge + applying"} wallet fixture (can take ~30s)\u2026
200
- `);
201
- let status;
202
- let mobileSetupResult;
203
- let resetError;
204
- if (adapter === "mobile") {
205
- const setupWalletSh = path.join(runnerDir, "adapters/mobile/bridge-runtime/setup-wallet.sh");
206
- const previousAppRoot = process.env.APP_ROOT;
207
- process.env.APP_ROOT = target;
208
- try {
209
- if (reset) {
210
- const platform = process.env.PLATFORM === "android" || process.env.ADB_SERIAL || process.env.ANDROID_SERIAL ? "android" : "ios";
211
- const port = process.env.WATCHER_PORT ?? process.env.METRO_PORT ?? "8081";
212
- const resetAppData = path.join(runnerDir, "adapters/mobile/reset-app-data.sh");
213
- const resetArgs = ["--platform", platform, "--target", target];
214
- if (platform === "ios") {
215
- resetArgs.push("--simulator", process.env.SIM_UDID || process.env.IOS_SIMULATOR || "booted");
216
- } else if (process.env.ADB_SERIAL || process.env.ANDROID_SERIAL) {
217
- resetArgs.push("--adb-serial", process.env.ADB_SERIAL || process.env.ANDROID_SERIAL || "");
218
- }
219
- const resetResult = await spawnScriptStreaming(resetAppData, resetArgs, target, {
220
- timeoutMs: FIXTURE_STREAM_TIMEOUT_MS
221
- });
222
- if (resetResult.status !== 0) {
223
- resetError = new Error("Mobile app data reset failed.");
224
- } else {
225
- const prewarmBundle = path.join(runnerDir, "adapters/mobile/prewarm-bundle.sh");
226
- const prewarmResult = await spawnScriptStreaming(
227
- prewarmBundle,
228
- ["--platform", platform, "--target", target, "--port", port],
229
- target,
230
- {
231
- timeoutMs: FIXTURE_STREAM_TIMEOUT_MS
232
- }
233
- );
234
- if (prewarmResult.status !== 0) {
235
- resetError = new Error("Mobile bundle prewarm failed after app data reset.");
236
- }
237
- }
238
- if (!resetError) {
239
- const openDevice = path.join(runnerDir, "adapters/mobile/open-device.sh");
240
- const openArgs = ["--platform", platform, "--target", target, "--port", port, "--preflight-mode", "fast", "--restart"];
241
- if (platform === "ios") {
242
- openArgs.push("--simulator", process.env.SIM_UDID || process.env.IOS_SIMULATOR || "booted");
243
- } else if (process.env.ADB_SERIAL || process.env.ANDROID_SERIAL) {
244
- openArgs.push("--adb-serial", process.env.ADB_SERIAL || process.env.ANDROID_SERIAL || "");
245
- }
246
- const openResult = await spawnScriptStreaming(openDevice, openArgs, target, {
247
- timeoutMs: FIXTURE_STREAM_TIMEOUT_MS
248
- });
249
- if (openResult.status !== 0) {
250
- resetError = new Error("Mobile app relaunch after data reset failed.");
251
- } else {
252
- const waitForBridge = path.join(runnerDir, "adapters/mobile/wait-for-bridge.sh");
253
- const waitResult = await spawnScriptStreaming(
254
- waitForBridge,
255
- ["--target", target, "--port", port, "--platform", platform, "--timeout-ms", String(FIXTURE_BRIDGE_READY_TIMEOUT_MS)],
256
- target,
257
- { timeoutMs: FIXTURE_BRIDGE_READY_TIMEOUT_MS + 1e4 }
258
- );
259
- if (waitResult.status !== 0) {
260
- resetError = new Error("Mobile bridge did not return after app data reset.");
261
- }
262
- }
263
- }
264
- }
265
- const configuredTimeout = Number(process.env.MM_HARNESS_FIXTURES_SET_TIMEOUT_MS ?? MOBILE_SETUP_WALLET_TIMEOUT_MS);
266
- const timeoutMs = Number.isFinite(configuredTimeout) && configuredTimeout > 0 ? configuredTimeout : MOBILE_SETUP_WALLET_TIMEOUT_MS;
267
- if (!resetError) {
268
- mobileSetupResult = await spawnScriptStreaming(
269
- setupWalletSh,
270
- ["--fixture", fixturePath, "--remote-flags-json", fixtureFlagsJson],
271
- target,
272
- {
273
- env: {
274
- APP_ROOT: target,
275
- WATCHER_PORT: process.env.WATCHER_PORT ?? "8081",
276
- METRO_PORT: process.env.METRO_PORT ?? process.env.WATCHER_PORT ?? "8081"
277
- },
278
- timeoutMs
279
- }
280
- );
281
- }
282
- status = !resetError && mobileSetupResult?.status === 0 ? "pass" : "fail";
283
- } finally {
284
- if (previousAppRoot === void 0) delete process.env.APP_ROOT;
285
- else process.env.APP_ROOT = previousAppRoot;
286
- }
287
- if (!json && status === "fail") {
288
- console.error(` Next: ${retryHint}`);
289
- }
290
- }
291
- const teaching = status === "pass" ? `Wallet fixture applied. Want different accounts? Edit: ${canonicalFixture}` : "Wallet fixture was not applied.";
292
- if (json) {
293
- console.log(
294
- JSON.stringify(
295
- {
296
- schemaVersion: 1,
297
- command: "fixtures",
298
- action: sub,
299
- adapter,
300
- fixture: fixturePath,
301
- canonicalFixture,
302
- status,
303
- exitCode: status === "pass" ? EXIT.ok : EXIT.runtime,
304
- walletReset: reset && status === "pass",
305
- message: teaching,
306
- error: status === "fail" ? {
307
- code: resetError ? "MOBILE_WALLET_RESET_FAILED" : mobileSetupResult?.timedOut ? "SETUP_WALLET_TIMEOUT" : "SETUP_WALLET_FAILED",
308
- message: resetError ? `wallet reset failed: ${resetError instanceof Error ? resetError.message : String(resetError)}` : mobileSetupResult?.timedOut ? `wallet fixture setup exceeded its ${String(mobileSetupResult.timeoutMs)}ms bound on Metro port ${process.env.WATCHER_PORT ?? "8081"}` : `wallet fixture setup failed on ${process.env.WATCHER_PORT ?? "8081"}`,
309
- userAction: retryHint
310
- } : null
311
- },
312
- null,
313
- 2
314
- )
190
+ const apply = surface.fixtures.apply;
191
+ if (!apply) {
192
+ return usageOut(
193
+ json,
194
+ "fixtures",
195
+ `fixtures ${sub} has no wallet to apply on ${adapter}.`,
196
+ surface.hints.launch
315
197
  );
316
- } else if (status === "pass") {
317
- console.error(teaching);
318
- }
319
- return status === "pass" ? EXIT.ok : EXIT.runtime;
320
- }
321
- async function applyExtensionFixture(target, fixturePath, canonicalFixture, json, action, fixtureFlags) {
322
- const distManifest = path.join(target, "dist/chrome/manifest.json");
323
- const userAction = `mm-harness launch --build --verify --target ${JSON.stringify(target)}`;
324
- if (!fs.existsSync(distManifest)) {
325
- const message2 = `Extension fixture needs an existing dist/chrome build; no manifest was found at ${distManifest}.`;
326
- if (json) {
327
- console.log(JSON.stringify({
328
- schemaVersion: 1,
329
- command: "fixtures",
330
- action,
331
- adapter: "extension",
332
- fixture: fixturePath,
333
- canonicalFixture,
334
- status: "fail",
335
- exitCode: EXIT.runtime,
336
- error: { code: "EXTENSION_FIXTURE_BUILD_REQUIRED", message: message2, userAction }
337
- }, null, 2));
338
- } else {
339
- console.error(`\u2717 mm-harness fixtures ${action}: ${message2}
340
- Next: ${userAction}`);
341
- }
342
- return EXIT.runtime;
343
198
  }
344
- process.stderr.write(`${colorHumanMessage(`\u2192 fixtures ${action} extension \u2014 resetting and seeding the slot-owned profile from the existing build\u2026`)}
345
- `);
346
- const liveScript = path.join(runnerDir, "adapters/extension/live.sh");
347
- const args = ["--target", target, "--launch-existing-dist", "--launch-only", "--reset-profile"];
348
- const flagKeys = Object.keys(fixtureFlags);
349
- if (flagKeys.length > 0) args.push("--remote-flags-json", JSON.stringify(fixtureFlags));
350
- if (process.env.CDP_PORT) args.push("--cdp-port", process.env.CDP_PORT);
351
- const result = await spawnScriptStreaming(liveScript, args, target, {
352
- env: { RECIPE_WALLET_FIXTURE: fixturePath },
353
- timeoutMs: FIXTURE_STREAM_TIMEOUT_MS
354
- });
355
- const pinned = readExtensionPinnedFlags(target);
356
- const pinnedFlags = pinned.pinned ?? {};
357
- const flagMismatch = result.status === 0 && !pinned.error && (pinned.pinned === null || !sameFeatureFlags(pinnedFlags, fixtureFlags)) ? [.../* @__PURE__ */ new Set([...flagKeys, ...Object.keys(pinnedFlags)])].filter(
358
- (key) => JSON.stringify(pinnedFlags[key]) !== JSON.stringify(fixtureFlags[key])
359
- ) : [];
360
- if (result.status === 0 && (pinned.error || flagMismatch.length > 0)) {
361
- const detail = pinned.error ? `the launched snapshot manifest could not be read (${pinned.sourcePath ?? "unknown path"}): ${pinned.error}` : `snapshot pin disagrees with the fixture for: ${flagMismatch.join(", ")}`;
362
- const flagNext = `mm-harness launch --adapter extension --build --target ${JSON.stringify(target)}`;
363
- if (json) {
364
- console.log(JSON.stringify({
365
- schemaVersion: 1,
366
- command: "fixtures",
367
- action,
368
- adapter: "extension",
369
- fixture: fixturePath,
370
- canonicalFixture,
371
- status: "fail",
372
- exitCode: EXIT.runtime,
373
- error: { code: "EXTENSION_FIXTURE_FLAGS_NOT_APPLIED", message: detail, userAction: flagNext }
374
- }, null, 2));
375
- } else {
376
- console.error(`\u2717 mm-harness fixtures ${action}: ${detail}
377
- Next: ${flagNext}`);
378
- }
379
- return EXIT.runtime;
380
- }
381
- const status = result.status === 0 ? "pass" : "fail";
382
- const exitCode = status === "pass" ? EXIT.ok : EXIT.runtime;
383
- const message = status === "pass" ? `Wallet fixture applied and validated. Want different accounts? Edit: ${canonicalFixture}` : "Extension wallet fixture could not be applied and validated.";
384
- if (json) {
385
- console.log(JSON.stringify({
386
- schemaVersion: 1,
387
- command: "fixtures",
388
- action,
389
- adapter: "extension",
390
- fixture: fixturePath,
391
- canonicalFixture,
392
- status,
393
- exitCode,
394
- profileReset: status === "pass",
395
- message,
396
- error: status === "fail" ? { code: "EXTENSION_FIXTURE_APPLY_FAILED", message, userAction } : null
397
- }, null, 2));
398
- } else if (status === "pass") {
399
- console.error(message);
400
- } else {
401
- console.error(`\u2717 mm-harness fixtures ${action}: ${message}
402
- Next: ${userAction}`);
403
- }
404
- return exitCode;
199
+ return apply({ target, sub, fixturePath, canonicalFixture, fixtureFlags, json, retryHint });
405
200
  }
406
201
  const EXT_FIXTURE_LEAF = "adapters/extension/wallet-fixture-state.cjs";
407
202
  function emitLeafMissing(json, action, fields, leaf) {
@@ -422,7 +217,7 @@ function emitLeafMissing(json, action, fields, leaf) {
422
217
  return EXIT.runtime;
423
218
  }
424
219
  function fixturesGenerate(adapter, target, options, json) {
425
- if (adapter !== "extension") {
220
+ if (!getAdapterSurface(adapter).fixtures.operations.includes("generate")) {
426
221
  return usageOut(
427
222
  json,
428
223
  "fixtures",
@@ -486,7 +281,7 @@ function fixturesGenerate(adapter, target, options, json) {
486
281
  return exitCode;
487
282
  }
488
283
  async function fixturesFinalize(adapter, target, options, json) {
489
- if (adapter !== "extension") {
284
+ if (!getAdapterSurface(adapter).fixtures.operations.includes("finalize")) {
490
285
  return usageOut(
491
286
  json,
492
287
  "fixtures",
@@ -678,5 +473,6 @@ Wallet fixture: ${canonical}`);
678
473
  return EXIT.ok;
679
474
  }
680
475
  export {
476
+ FIXTURE_STREAM_TIMEOUT_MS,
681
477
  handleFixtures
682
478
  };
@@ -17,6 +17,7 @@ import {
17
17
  remoteFlagRequestFor
18
18
  } from "../../feature-flags.js";
19
19
  import { terminalOnlyLaunchFlags } from "../../adapters/terminal/launch.js";
20
+ import { shellQuote } from "./quote.js";
20
21
  async function runDeviceLaunch(context, profile) {
21
22
  const { adapter, options, target, heal, jsonOutput, machine, stream, usage } = context;
22
23
  const terminalOnly = terminalOnlyLaunchFlags(options);
@@ -182,10 +183,6 @@ function readinessBlockFailure(result) {
182
183
  exitCode: result.status
183
184
  };
184
185
  }
185
- function shellQuote(value) {
186
- if (/^[A-Za-z0-9_./:@%+=,-]+$/u.test(value)) return value;
187
- return `'${value.replace(/'/gu, `'"'"'`)}'`;
188
- }
189
186
  function nativeInputsChanged(target, paths) {
190
187
  const baselineFile = recipeRuntimePath(target, ".last-build-ref");
191
188
  let baseline;
@@ -341,6 +338,5 @@ ${failure.originalError}` : "") + `
341
338
  return failure.exitCode;
342
339
  }
343
340
  export {
344
- runDeviceLaunch,
345
- shellQuote
341
+ runDeviceLaunch
346
342
  };
@@ -12,8 +12,7 @@ import {
12
12
  importRecipeHarnessRuntimeCdp,
13
13
  recipeHarnessPath,
14
14
  recipeRuntimeDir,
15
- runnerDir,
16
- walletFixturePath
15
+ runnerDir
17
16
  } from "../../paths.js";
18
17
  import { extensionIdFromKey } from "../../adapters/extension/extension-id.js";
19
18
  import {
@@ -30,16 +29,9 @@ import {
30
29
  import { checkExtensionRuntimeHealth } from "../../adapters/extension/runtime.js";
31
30
  import { ensureHarnessFresh } from "../../adapters/harness-freshness.js";
32
31
  import { isExtensionWatcherLive, stopExtensionWatcher } from "../../adapters/slot-ports.js";
33
- import { EXIT, spawnScript, spawnScriptStreaming } from "../shared.js";
32
+ import { EXIT, spawnScriptStreaming } from "../shared.js";
34
33
  import { readExtensionPinnedFlags } from "../../adapters/extension/feature-flags.js";
35
- import { ensureExtensionConsoleCapture } from "../../adapters/extension/console-capture.js";
36
- import {
37
- fixtureFeatureFlags,
38
- sameFeatureFlags,
39
- toRemoteFlagSpec
40
- } from "../../feature-flags.js";
41
- import { RECOVERY_CODE } from "../../heal-bounds.js";
42
- import { shellQuote } from "./device.js";
34
+ import { sameFeatureFlags } from "../../feature-flags.js";
43
35
  const { CdpSession } = await importRecipeHarnessRuntimeCdp();
44
36
  const { RUNTIME_IDENTITY_FILENAME, RUNTIME_NONCE_PREFIX } = createRequire(import.meta.url)(
45
37
  path.join(runnerDir, "adapters/extension/lib/chrome-args.cjs")
@@ -487,301 +479,9 @@ async function extensionRebuild(target, remoteFlags) {
487
479
  }
488
480
  return result;
489
481
  }
490
- const DEFAULT_EXTENSION_DAPP_URL = "https://metamask.github.io/test-dapp/";
491
- function verifyExtensionPin(target, requested) {
492
- const pinned = readExtensionPinnedFlags(target);
493
- if (pinned.error) {
494
- return {
495
- ok: false,
496
- flags: {},
497
- code: "RUNTIME_MANIFEST_UNREADABLE",
498
- message: `the launched dist snapshot manifest could not be read (${pinned.sourcePath ?? "unknown path"}): ${pinned.error}`
499
- };
500
- }
501
- if (pinned.overrides !== null && pinned.pinned === null) {
502
- return {
503
- ok: false,
504
- flags: {},
505
- code: "REMOTE_FLAG_NOT_APPLIED",
506
- message: `the launched dist snapshot manifest (${pinned.sourcePath ?? "unknown path"}) carries no harness pin record; it was not written by this launch.`
507
- };
508
- }
509
- const actual = pinned.pinned ?? {};
510
- if (!sameFeatureFlags(actual, requested)) {
511
- const mismatched = [.../* @__PURE__ */ new Set([...Object.keys(requested), ...Object.keys(actual)])].filter(
512
- (key) => JSON.stringify(actual[key]) !== JSON.stringify(requested[key])
513
- );
514
- return {
515
- ok: false,
516
- flags: {},
517
- code: "REMOTE_FLAG_NOT_APPLIED",
518
- message: `the remote feature-flag pin ${toRemoteFlagSpec(requested) || "(none)"} does not match the launched snapshot manifest: ` + mismatched.map((key) => `${key} expected ${JSON.stringify(requested[key])}, got ${JSON.stringify(actual[key])}`).join("; ")
519
- };
520
- }
521
- return { ok: true, flags: actual, message: "" };
522
- }
523
- function extensionQuickReattachFailed(output) {
524
- return /\[reattach\]|extension quick reattach|mm-harness launch --build/u.test(output);
525
- }
526
- function extensionRuntimeBlocked(output) {
527
- return /ERR_BLOCKED_BY_CLIENT|has been blocked by Chromium/u.test(output);
528
- }
529
- function extensionBrowserMissing(output) {
530
- return /Playwright Chromium is not installed|No compatible Chromium binary selected/u.test(output);
531
- }
532
- function extensionProductConfigMissing(output) {
533
- return /EXTENSION_PRODUCT_CONFIG_REQUIRED:/u.test(output);
534
- }
535
- function extensionEvmRpcUnreachable(output) {
536
- return /EVM_RPC_UNREACHABLE|EVM RPC readiness probe failed|Infura configured ≠ RPC reachable/u.test(output);
537
- }
538
- const extensionLaunchProfile = {
539
- refuseFlags({ target }, { watch, runway, clearMetro, remoteFlagSpec }) {
540
- if (runway) return { message: "runway is mobile-only.", userAction: "drop --runway for the extension" };
541
- if (clearMetro) return { message: "--clear-metro is mobile-only.", userAction: "drop --clear-metro for the extension" };
542
- if (remoteFlagSpec !== void 0 && watch) {
543
- return {
544
- message: "--remote-flag cannot be applied with --watch: the watcher never re-creates the dist snapshot that carries the pin.",
545
- userAction: `mm-harness launch --adapter extension --remote-flag ${remoteFlagSpec} --target ${shellQuote(target)}`
546
- };
547
- }
548
- return void 0;
549
- },
550
- // --url: initial main-tab page for extension launches (dapp beside the
551
- // sidepanel); travels to live.sh/launch-browser via env. Sidepanel mode has a
552
- // useful default so `mm-harness launch --sidepanel` opens a working dapp, not
553
- // just a wallet panel with no page to connect from.
554
- start({ options, displayMode, machine, wantWatch, tier }) {
555
- const requestedUrl = typeof options["url"] === "string" && options["url"] ? options["url"] : "";
556
- if (requestedUrl || displayMode === "sidepanel") {
557
- process.env.EXTENSION_START_URL = requestedUrl || DEFAULT_EXTENSION_DAPP_URL;
558
- }
559
- if (machine) return;
560
- const modeNote = displayMode === "sidepanel" ? `sidepanel \xB7 dapp ${process.env.EXTENSION_START_URL ?? DEFAULT_EXTENSION_DAPP_URL}` : "fullscreen";
561
- const workNote = wantWatch ? "watch only" : tier === "build" ? "clean build" : "quick reuse probe";
562
- console.error(colorHumanMessage(
563
- `\u2192 extension launch \u2014 ${modeNote} \xB7 CDP :${process.env.CDP_PORT ?? "default"} \xB7 ${workNote}`
564
- ));
565
- },
566
- nativeInputs: ["package.json", "yarn.lock", "webpack.config.js"],
567
- rebuildCommand: () => "mm-harness launch --build",
568
- // Source-development launch paths require checkout tooling. A verified local
569
- // release artifact can reuse its healthy browser without building or watching.
570
- async healthcheck(launch, state) {
571
- const { target, tier, wantWatch, heal, stream } = launch;
572
- const artifact = releaseArtifactState(target);
573
- const reusable = !wantWatch && tier !== "build" && await extensionRuntimeReusable(target, artifact);
574
- const verifiedReleaseReuse = artifact.status === "valid" && reusable;
575
- const verifiedReleaseLaunch = !wantWatch && tier !== "build" && artifact.status === "valid" && runtimeDistCheck(target, artifact).status === "fresh";
576
- const willBuild = !reusable;
577
- if (willBuild) {
578
- const productConfigBlock = extensionProductConfigBlock(target);
579
- if (productConfigBlock) {
580
- return launch.fail(state, {
581
- code: "EXTENSION_PRODUCT_CONFIG_REQUIRED",
582
- message: productConfigBlock.message,
583
- recoverable: false,
584
- userAction: productConfigBlock.userAction,
585
- exitCode: EXIT.infra
586
- });
587
- }
588
- }
589
- const depsBlock = verifiedReleaseReuse || verifiedReleaseLaunch ? null : extensionDepsBlock(target);
590
- if (depsBlock) {
591
- if (heal === "off") return launch.usage(depsBlock.message, depsBlock.userAction);
592
- const recoveryCode = "deps.installed";
593
- state.attemptedRecoveries.push(recoveryCode);
594
- stream.phase("recover");
595
- const repaired = await installExtensionDeps(target);
596
- if (repaired.status !== 0 || extensionDepsBlock(target)) {
597
- return launch.fail(state, {
598
- code: "DEPENDENCY_INSTALL_FAILED",
599
- message: depsBlock.message,
600
- recoverable: false,
601
- userAction: "install the checkout-pinned Node version, then re-run mm-harness launch",
602
- originalError: repaired.output,
603
- exitCode: EXIT.infra
604
- });
605
- }
606
- state.recovered.push(recoveryCode);
607
- state.mutations.push({ type: "dependencies", action: "installed", path: target });
608
- }
609
- return void 0;
610
- },
611
- compose: ({ target, wantWatch, displayMode, remoteFlagRequest }, tier) => launchExtension(target, tier, wantWatch, displayMode, remoteFlagRequest),
612
- classify({ target, remoteFlagRequest }, output) {
613
- if (output.includes("REMOTE_FLAG_NOT_PINNABLE:")) {
614
- return {
615
- code: "REMOTE_FLAG_NOT_PINNABLE",
616
- message: `a verified release artifact cannot carry a remote feature-flag pin (${remoteFlagRequest?.spec ?? ""}); its manifest is signed evidence and is never rewritten. Validate the artifact as shipped (drop --remote-flag and the fixture's remoteFeatureFlags) or validate the variant on a source build.`,
617
- recoverable: false,
618
- // The next step must leave the artifact alone: a --build here would replace
619
- // the artifact under validation with a source build.
620
- userAction: Object.keys(fixtureFeatureFlags(walletFixturePath(target))).length > 0 ? `remove remoteFeatureFlags from ${shellQuote(walletFixturePath(target))}, then: mm-harness launch --adapter extension --target ${shellQuote(target)}` : `mm-harness launch --adapter extension --target ${shellQuote(target)}`,
621
- exitCode: EXIT.infra,
622
- originalError: output.trim() || void 0
623
- };
624
- }
625
- if (extensionProductConfigMissing(output)) {
626
- const block = extensionProductConfigBlock(target);
627
- return {
628
- code: "EXTENSION_PRODUCT_CONFIG_REQUIRED",
629
- message: block?.message ?? "Extension product configuration was not ready when the build started.",
630
- recoverable: false,
631
- userAction: block?.userAction ?? `mm-harness launch --adapter extension --target ${shellQuote(target)}`,
632
- exitCode: EXIT.infra
633
- };
634
- }
635
- if (extensionBrowserMissing(output)) {
636
- return {
637
- code: "EXTENSION_BROWSER_REQUIRED",
638
- message: "the checkout Playwright browser is not installed; system Chrome is not a compatible unpacked-extension fallback. Installing the browser cache requires user approval.",
639
- recoverable: false,
640
- userAction: `ask the user for approval, then run: cd ${shellQuote(target)} && yarn playwright install chromium`,
641
- exitCode: EXIT.infra
642
- };
643
- }
644
- if (output.includes("EXTENSION_BACKGROUND_UNRESPONSIVE:") || output.includes("EXTENSION_STARTUP_UNVERIFIED:")) {
645
- return {
646
- code: output.includes("EXTENSION_BACKGROUND_UNRESPONSIVE:") ? "EXTENSION_BACKGROUND_UNRESPONSIVE" : "EXTENSION_STARTUP_UNVERIFIED",
647
- message: "Extension startup is not healthy; inspect the background error before restarting or resetting wallet state.",
648
- recoverable: false,
649
- userAction: `mm-harness logs --target ${shellQuote(target)} --full`,
650
- exitCode: EXIT.runtime,
651
- originalError: output.trim() || void 0
652
- };
653
- }
654
- if (output.includes("EVM_RPC_EXECUTION_FAILED:")) {
655
- return {
656
- code: "EVM_RPC_EXECUTION_FAILED",
657
- message: "Background RPC fetch failed during JavaScript execution; this does not establish an Infura authentication or connectivity failure.",
658
- recoverable: false,
659
- userAction: `mm-harness logs --target ${shellQuote(target)} --full`,
660
- exitCode: EXIT.runtime,
661
- originalError: output.trim() || void 0
662
- };
663
- }
664
- if (extensionEvmRpcUnreachable(output)) {
665
- return {
666
- code: "EVM_RPC_UNREACHABLE",
667
- message: "EVM RPC readiness failed; Infura configured does not mean RPC reachable.",
668
- recoverable: false,
669
- userAction: `Check the effective INFURA_PROJECT_ID from the environment, .metamaskprodrc, or ${shellQuote(path.join(target, ".metamaskrc"))}, then rerun: mm-harness launch --verify --target ${shellQuote(target)}`,
670
- exitCode: EXIT.runtime,
671
- originalError: output.trim() || void 0
672
- };
673
- }
674
- return void 0;
675
- },
676
- async beforeHeal(launch, attempt, state) {
677
- if (launch.tier !== "quick" || !extensionQuickReattachFailed(attempt.output)) return void 0;
678
- const recoveryCode = "chrome.relaunched";
679
- state.attemptedRecoveries.push(recoveryCode);
680
- launch.stream.phase("recover");
681
- const rebuildAttempt = await launch.compose("build");
682
- if (rebuildAttempt.status === 0) {
683
- state.recovered.push(recoveryCode);
684
- return await launch.settle(state, rebuildAttempt.remoteFeatureFlags);
685
- }
686
- return launch.fail(state, {
687
- code: "EXTENSION_RELAUNCH_FAILED",
688
- message: "quick reattach failed, and clean relaunch failed too.",
689
- recoverable: false,
690
- exitCode: EXIT.infra,
691
- originalError: rebuildAttempt.output.trim() || void 0
692
- });
693
- },
694
- recovery: () => ({ code: RECOVERY_CODE.extension, restartApp: false }),
695
- // --watch only restarts the webpack watcher; the snapshot, and its pin, are
696
- // untouched, so the live record is reported rather than verified against a
697
- // request the watcher could never apply (--remote-flag is refused with it;
698
- // the fixture baseline stays whatever the last launch pinned).
699
- provenFlags({ target, wantWatch, remoteFlagRequest }, requested) {
700
- if (wantWatch) return { flags: readExtensionPinnedFlags(target).pinned };
701
- const pinned = verifyExtensionPin(target, requested);
702
- if (pinned.ok) return { flags: pinned.flags };
703
- const spec = remoteFlagRequest?.spec;
704
- return {
705
- code: pinned.code ?? "REMOTE_FLAG_NOT_APPLIED",
706
- message: pinned.message,
707
- recoverable: false,
708
- // A rebuild re-creates the snapshot; the flag is repeated only when one was asked for.
709
- userAction: `mm-harness launch --adapter extension --build${spec ? ` --remote-flag ${spec}` : ""} --target ${shellQuote(target)}`,
710
- exitCode: EXIT.runtime
711
- };
712
- },
713
- async finish(launch, state, sidepanelRecoveryAllowed) {
714
- const { target, machine, displayMode, tier, stream } = launch;
715
- const sidepanelSh = path.join(runnerDir, "adapters/extension/sidepanel-toggle.sh");
716
- if (displayMode === "fullscreen") {
717
- const sidepanelArgs = ["close"];
718
- if (process.env.CDP_PORT) sidepanelArgs.push("--cdp-port", process.env.CDP_PORT);
719
- const fullscreen = spawnScript(sidepanelSh, sidepanelArgs, target, machine, { REPO: target });
720
- if (fullscreen.status !== 0) {
721
- return launch.fail(state, {
722
- code: "FULLSCREEN_OPEN_FAILED",
723
- message: "app launched but restoring the fullscreen Extension surface failed.",
724
- recoverable: false,
725
- userAction: `bash adapters/extension/sidepanel-toggle.sh close --cdp-port ${process.env.CDP_PORT ?? "<CDP_PORT>"}`,
726
- exitCode: EXIT.runtime,
727
- originalError: fullscreen.output.trim() || void 0
728
- });
729
- }
730
- }
731
- if (displayMode === "sidepanel") {
732
- const sidepanelArgs = ["open"];
733
- if (process.env.CDP_PORT) sidepanelArgs.push("--cdp-port", process.env.CDP_PORT);
734
- if (!machine) {
735
- console.error(
736
- `[sidepanel] opening panel beside ${process.env.EXTENSION_START_URL ?? DEFAULT_EXTENSION_DAPP_URL}`
737
- );
738
- }
739
- const sidepanel = spawnScript(sidepanelSh, sidepanelArgs, target, machine, { REPO: target });
740
- if (sidepanel.status !== 0) {
741
- const recoveryCode = "chrome.relaunched";
742
- if (sidepanelRecoveryAllowed && tier === "quick" && extensionRuntimeBlocked(sidepanel.output) && !state.attemptedRecoveries.includes(recoveryCode)) {
743
- state.attemptedRecoveries.push(recoveryCode);
744
- stream.phase("recover");
745
- const rebuildAttempt = await launch.compose("build");
746
- if (rebuildAttempt.status === 0) {
747
- state.recovered.push(recoveryCode);
748
- return await launch.settle(state, void 0, false);
749
- }
750
- return launch.fail(state, {
751
- code: "EXTENSION_RELAUNCH_FAILED",
752
- message: "sidepanel open found a blocked extension runtime, and clean relaunch failed too.",
753
- recoverable: false,
754
- exitCode: EXIT.infra,
755
- originalError: rebuildAttempt.output.trim() || void 0
756
- });
757
- }
758
- return launch.fail(state, {
759
- code: "SIDEPANEL_OPEN_FAILED",
760
- message: "app launched but opening the side panel failed.",
761
- recoverable: false,
762
- userAction: `bash adapters/extension/sidepanel-toggle.sh open --cdp-port ${process.env.CDP_PORT ?? "<CDP_PORT>"}`,
763
- exitCode: EXIT.runtime,
764
- originalError: sidepanel.output.trim() || void 0
765
- });
766
- }
767
- }
768
- try {
769
- await ensureExtensionConsoleCapture(target);
770
- } catch (error) {
771
- if (!machine) {
772
- console.error(`WARN: Extension console capture unavailable: ${error instanceof Error ? error.message : String(error)}`);
773
- }
774
- }
775
- return void 0;
776
- },
777
- verifyArgs: () => process.env.CDP_PORT ? ["--cdp-port", process.env.CDP_PORT] : [],
778
- platformLabel: ({ mobileTarget, displayMode }) => mobileTarget ?? displayMode,
779
- deviceLabel: ({ displayMode }) => displayMode
780
- };
781
482
  export {
782
483
  extensionDepsBlock,
783
484
  extensionLaunchDevelopment,
784
- extensionLaunchProfile,
785
485
  extensionReattach,
786
486
  extensionRebuild,
787
487
  extensionRuntimeReusable,
@@ -14,7 +14,7 @@ import {
14
14
  import { parseHeal } from "../../heal-bounds.js";
15
15
  import { acquireCheckoutLock } from "../../checkout-lock.js";
16
16
  import { JsonStreamWriter } from "../../json-stream.js";
17
- import { shellQuote } from "./device.js";
17
+ import { shellQuote } from "./quote.js";
18
18
  const LAUNCH_BOOLEANS = /* @__PURE__ */ new Set([
19
19
  "build",
20
20
  "watch",