weapp-ide-cli 6.1.2 → 6.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -98,10 +98,10 @@ weapp mcp --workspace-root .
98
98
 
99
99
  从当前版本开始,`weapp-ide-cli` 会在调用微信开发者工具前自动尝试预热本机 DevTools 配置:
100
100
 
101
- - 确保安全设置里启用服务端口
101
+ - 检测安全设置中的服务端口;未启用时请在 IDE 中开启
102
102
  - 根据命令或全局配置决定是否自动信任项目
103
103
 
104
- 在 macOS 上,它会写入 `~/Library/Application Support/微信开发者工具/*/WeappLocalData` 下对应的本地配置;如果你不希望自动处理,也可以通过下文的 `config` 配置项关闭。
104
+ 仅对 IDE 已完成导入的项目更新信任状态,并保留已有能力信息。首次打开项目时,由 IDE 负责初始化项目记录,CLI 不会提前创建不完整的本地缓存;自动化启动使用 IDE 的 `trustProject` 参数。可以通过下文的 `config` 配置项关闭自动处理。
105
105
 
106
106
  ## 支付宝小程序(minidev)支持
107
107
 
@@ -506,16 +506,6 @@ async function resolveWechatDevtoolsInstanceDirs(baseDir) {
506
506
  throw error;
507
507
  }
508
508
  }
509
- async function syncHashKeyMap(localDataDir, key) {
510
- const hash = createStorageHash(key);
511
- const hashKeyMapPath = path.join(localDataDir, "hash_key_map_2.json");
512
- const current = await readJsonObject(hashKeyMapPath);
513
- if (current[hash] !== key) {
514
- current[hash] = key;
515
- await writeJsonObject(hashKeyMapPath, current);
516
- }
517
- return hash;
518
- }
519
509
  async function detectWechatDevtoolsSecuritySettings(localDataDir) {
520
510
  for (const fileName of SETTINGS_STORAGE_FILE_NAMES) {
521
511
  const security = normalizeWechatDevtoolsSecuritySettings((await readJsonObject(path.join(localDataDir, fileName))).security);
@@ -524,18 +514,20 @@ async function detectWechatDevtoolsSecuritySettings(localDataDir) {
524
514
  }
525
515
  async function trustWechatDevtoolsProject(localDataDir, projectPath) {
526
516
  const normalizedProjectPath = path.resolve(projectPath);
527
- const projectHash = await syncHashKeyMap(localDataDir, `project2_${normalizedProjectPath}`);
517
+ const projectHash = createStorageHash(`project2_${normalizedProjectPath}`);
528
518
  const fileNames = [`localstorage_${projectHash}.json`, `ls_${projectHash}.json`];
519
+ let trusted = false;
529
520
  for (const fileName of fileNames) {
530
521
  const projectFilePath = path.join(localDataDir, fileName);
531
522
  const current = await readJsonObject(projectFilePath);
523
+ if (current.projectid !== normalizedProjectPath || current.projectpath !== normalizedProjectPath || typeof current.appid !== "string" || !current.appid || !isRecord(current.attr) || !isRecord(current.attr.setting)) continue;
532
524
  await writeJsonObject(projectFilePath, {
533
525
  ...current,
534
- projectid: typeof current.projectid === "string" && current.projectid.length > 0 ? current.projectid : normalizedProjectPath,
535
- projectpath: typeof current.projectpath === "string" && current.projectpath.length > 0 ? current.projectpath : normalizedProjectPath,
536
526
  isTrusted: true
537
527
  });
528
+ trusted = true;
538
529
  }
530
+ return trusted;
539
531
  }
540
532
  async function scanWechatDevtoolsServicePort(context) {
541
533
  const instanceDirs = await resolveWechatDevtoolsInstanceDirs(context.baseDir);
@@ -596,8 +588,7 @@ async function bootstrapWechatDevtoolsSettings(options = {}) {
596
588
  for (const instanceDir of scanResult.instanceDirs) {
597
589
  const localDataDir = path.join(instanceDir, "WeappLocalData");
598
590
  if (options.projectPath && options.trustProject !== false) {
599
- await trustWechatDevtoolsProject(localDataDir, options.projectPath);
600
- trustedProjectCount += 1;
591
+ if (await trustWechatDevtoolsProject(localDataDir, options.projectPath)) trustedProjectCount += 1;
601
592
  }
602
593
  }
603
594
  return {
@@ -1239,31 +1230,35 @@ async function launchFreshAutomator(options) {
1239
1230
  } : {}
1240
1231
  });
1241
1232
  }
1242
- function normalizeMiniProgramConnectionError(error) {
1233
+ function normalizeMiniProgramConnectionError(error, background = false) {
1234
+ const diagnostics = background ? {
1235
+ error: (message) => logger_default.debug(message),
1236
+ warn: (message) => logger_default.debug(message)
1237
+ } : logger_default;
1243
1238
  if (isAutomatorLoginError(error)) {
1244
- logger_default.error(i18nText("检测到微信开发者工具登录状态失效,请先登录后重试。", "Wechat DevTools login has expired. Please login and retry."));
1245
- logger_default.warn(formatAutomatorLoginError(error));
1239
+ diagnostics.error(i18nText("检测到微信开发者工具登录状态失效,请先登录后重试。", "Wechat DevTools login has expired. Please login and retry."));
1240
+ diagnostics.warn(formatAutomatorLoginError(error));
1246
1241
  return /* @__PURE__ */ new Error("DEVTOOLS_LOGIN_REQUIRED");
1247
1242
  }
1248
1243
  if (isDevtoolsHttpPortError(error)) {
1249
- logger_default.error(i18nText("无法连接到微信开发者工具,请确保已开启 HTTP 服务端口。", "Cannot connect to Wechat DevTools. Please ensure HTTP service port is enabled."));
1250
- logger_default.warn(i18nText("请在微信开发者工具中:设置 -> 安全设置 -> 开启服务端口", "Please enable service port in Wechat DevTools: Settings -> Security -> Service Port"));
1244
+ diagnostics.error(i18nText("无法连接到微信开发者工具,请确保已开启 HTTP 服务端口。", "Cannot connect to Wechat DevTools. Please ensure HTTP service port is enabled."));
1245
+ diagnostics.warn(i18nText("请在微信开发者工具中:设置 -> 安全设置 -> 开启服务端口", "Please enable service port in Wechat DevTools: Settings -> Security -> Service Port"));
1251
1246
  return /* @__PURE__ */ new Error("DEVTOOLS_HTTP_PORT_ERROR");
1252
1247
  }
1253
1248
  if (isDevtoolsExtensionContextInvalidatedError(error)) {
1254
- logger_default.error(i18nText("微信开发者工具自动化上下文尚未就绪,通常是刚启动或正在重载。", "Wechat DevTools automation context is not ready yet, usually because the IDE has just started or is still reloading."));
1255
- logger_default.warn(i18nText("请稍后重试;若持续失败,关闭多余的开发者工具窗口后重试。", "Please retry shortly. If it keeps failing, close extra DevTools windows and try again."));
1249
+ diagnostics.error(i18nText("微信开发者工具自动化上下文尚未就绪,通常是刚启动或正在重载。", "Wechat DevTools automation context is not ready yet, usually because the IDE has just started or is still reloading."));
1250
+ diagnostics.warn(i18nText("请稍后重试;若持续失败,关闭多余的开发者工具窗口后重试。", "Please retry shortly. If it keeps failing, close extra DevTools windows and try again."));
1256
1251
  return /* @__PURE__ */ new Error("DEVTOOLS_EXTENSION_CONTEXT_INVALIDATED");
1257
1252
  }
1258
1253
  if (isAutomatorWsConnectError(error) || isAutomatorPortInUseError(error)) {
1259
- logger_default.error(i18nText("无法连接到当前项目的微信开发者工具自动化 websocket。", "Cannot connect to the Wechat DevTools automation websocket for the current project."));
1260
- logger_default.warn(i18nText("请确认当前打开的是目标项目;若之前跑过其他 e2e / screenshot 任务,关闭多余的微信开发者工具窗口,或结束残留的 `wechatwebdevtools cli auto --project ...` 进程后重试。", "Please confirm the current DevTools window is the target project. If you recently ran other e2e / screenshot tasks, close extra windows or stop stale `wechatwebdevtools cli auto --project ...` processes and retry."));
1254
+ diagnostics.error(i18nText("无法连接到当前项目的微信开发者工具自动化 websocket。", "Cannot connect to the Wechat DevTools automation websocket for the current project."));
1255
+ diagnostics.warn(i18nText("请确认当前打开的是目标项目;若之前跑过其他 e2e / screenshot 任务,关闭多余的微信开发者工具窗口,或结束残留的 `wechatwebdevtools cli auto --project ...` 进程后重试。", "Please confirm the current DevTools window is the target project. If you recently ran other e2e / screenshot tasks, close extra windows or stop stale `wechatwebdevtools cli auto --project ...` processes and retry."));
1261
1256
  return /* @__PURE__ */ new Error("DEVTOOLS_WS_CONNECT_ERROR");
1262
1257
  }
1263
1258
  if (isAutomatorProtocolTimeoutError(error)) {
1264
1259
  const method = getAutomatorProtocolTimeoutMethod(error) ?? "unknown";
1265
- logger_default.error(i18nText(`微信开发者工具在协议调用 ${method} 上超时,未按预期返回结果。`, `Wechat DevTools timed out while executing protocol method ${method} and did not return a result.`));
1266
- logger_default.warn(i18nText("这通常表示当前 DevTools 自动化会话已卡住、窗口不在目标项目、或当前 DevTools 版本对该协议调用无响应。请重开目标项目窗口后重试;若仍复现,优先记录当前 DevTools 版本与协议方法名继续排查。", "This usually means the current DevTools automation session is stuck, the window is not on the target project, or the current DevTools version is not responding to that protocol method. Reopen the target project window and retry. If it still reproduces, record the current DevTools version and protocol method name for follow-up debugging."));
1260
+ diagnostics.error(i18nText(`微信开发者工具在协议调用 ${method} 上超时,未按预期返回结果。`, `Wechat DevTools timed out while executing protocol method ${method} and did not return a result.`));
1261
+ diagnostics.warn(i18nText("这通常表示当前 DevTools 自动化会话已卡住、窗口不在目标项目、或当前 DevTools 版本对该协议调用无响应。请重开目标项目窗口后重试;若仍复现,优先记录当前 DevTools 版本与协议方法名继续排查。", "This usually means the current DevTools automation session is stuck, the window is not on the target project, or the current DevTools version is not responding to that protocol method. Reopen the target project window and retry. If it still reproduces, record the current DevTools version and protocol method name for follow-up debugging."));
1267
1262
  return /* @__PURE__ */ new Error("DEVTOOLS_PROTOCOL_TIMEOUT");
1268
1263
  }
1269
1264
  return error instanceof Error ? error : new Error(String(error));
@@ -1271,7 +1266,7 @@ function normalizeMiniProgramConnectionError(error) {
1271
1266
  /**
1272
1267
  * @description 建立 automator 会话,并统一处理常见连接错误提示。
1273
1268
  */
1274
- async function connectMiniProgram(options) {
1269
+ async function connectMiniProgramWithDiagnostics(options, background) {
1275
1270
  const result = await runRetryableCommand({
1276
1271
  createCancelError: (result) => createWechatIdeLoginRequiredExitError(unwrapAutomatorConnectionError(result), "cancelled"),
1277
1272
  execute: async () => {
@@ -1281,7 +1276,7 @@ async function connectMiniProgram(options) {
1281
1276
  value: await launchFreshAutomator(options)
1282
1277
  };
1283
1278
  } catch (error) {
1284
- if (!isAutomatorLoginError(error)) throw normalizeMiniProgramConnectionError(error);
1279
+ if (!isAutomatorLoginError(error)) throw normalizeMiniProgramConnectionError(error, background);
1285
1280
  return {
1286
1281
  error,
1287
1282
  kind: "retryable"
@@ -1293,7 +1288,7 @@ async function connectMiniProgram(options) {
1293
1288
  value: await connectOpenedAutomator(options)
1294
1289
  };
1295
1290
  } catch (error) {
1296
- const normalizedOpenSessionError = normalizeMiniProgramConnectionError(error);
1291
+ const normalizedOpenSessionError = normalizeMiniProgramConnectionError(error, background);
1297
1292
  if (options.openedOnly || options.preferOpenedSession !== false && Boolean(options.port || options.sessionId)) throw normalizedOpenSessionError;
1298
1293
  if (normalizedOpenSessionError instanceof Error && normalizedOpenSessionError.message === "DEVTOOLS_PROTOCOL_TIMEOUT") throw normalizedOpenSessionError;
1299
1294
  try {
@@ -1302,7 +1297,7 @@ async function connectMiniProgram(options) {
1302
1297
  value: await launchFreshAutomator(options)
1303
1298
  };
1304
1299
  } catch (launchError) {
1305
- if (!isAutomatorLoginError(launchError)) throw normalizeMiniProgramConnectionError(launchError);
1300
+ if (!isAutomatorLoginError(launchError)) throw normalizeMiniProgramConnectionError(launchError, background);
1306
1301
  return {
1307
1302
  error: launchError,
1308
1303
  kind: "retryable"
@@ -1324,6 +1319,21 @@ async function connectMiniProgram(options) {
1324
1319
  if (result.kind === "retryable") throw createWechatIdeLoginRequiredExitError(result.error);
1325
1320
  return result.value;
1326
1321
  }
1322
+ /** 建立交互式会话,并报告最终连接错误。 */
1323
+ async function connectMiniProgram(options) {
1324
+ return await connectMiniProgramWithDiagnostics(options, false);
1325
+ }
1326
+ /** 后台日志桥接的连接探针,不在每次可恢复失败时输出终局错误。 */
1327
+ async function connectConsoleMiniProgram(options) {
1328
+ return await connectMiniProgramWithDiagnostics(options, true);
1329
+ }
1330
+ /** 为后台日志桥接保留共享会话所有权和诊断级别。 */
1331
+ async function acquireConsoleMiniProgram(options) {
1332
+ return await acquireSharedMiniProgram({
1333
+ connectMiniProgram: connectConsoleMiniProgram,
1334
+ normalizeConnectionError: (error) => normalizeMiniProgramConnectionError(error, true)
1335
+ }, options);
1336
+ }
1327
1337
  const runtimeHooks = {
1328
1338
  connectMiniProgram,
1329
1339
  normalizeConnectionError: normalizeMiniProgramConnectionError
@@ -1341,4 +1351,4 @@ async function withMiniProgram$1(options, runner) {
1341
1351
  return await withMiniProgram(runtimeHooks, options, runner);
1342
1352
  }
1343
1353
  //#endregion
1344
- export { createLocaleConfig as $, isAutomatorPortInUseError as A, resolveCliPath as B, configureLocaleFromArgv as C, formatAutomatorLoginError as D, connectOpenedAutomator as E, isRetryableAutomatorLaunchError as F, getDefaultCliPath as G, getConfiguredLocale as H, launchAutomator as I, colors as J, isOperatingSystemSupported as K, resolveProjectAutomatorPort as L, isAutomatorWsConnectError as M, isDevtoolsExtensionContextInvalidatedError as N, getAutomatorProtocolTimeoutMethod as O, isDevtoolsHttpPortError as P, createCustomConfig as Q, bootstrapWechatDevtoolsSettings as R, waitForExclusiveKeypress as S, validateLocaleOption as T, resolveDevtoolsAutomationDefaults as U, getConfig as V, SupportedPlatformsMap as W, createAutoBootstrapDevtoolsConfig as X, logger_default as Y, createAutoTrustProjectConfig as Z, promptRetryKeypress as _, releaseSharedMiniProgram as a, resolvePath as at, createSharedInputSession as b, RETRY_CANCEL_KEYS as c, createWechatIdeLoginRequiredExitError as d, overwriteCustomConfig as et, extractExecutionErrorText as f, isWechatIdeLoginRequiredExitError as g, isWechatIdeLoginRequiredError as h, getSharedMiniProgramSessionCount as i, defaultCustomConfigFilePath as it, isAutomatorProtocolTimeoutError as j, isAutomatorLoginError as k, RETRY_CONFIRM_KEYS as l, formatWechatIdeLoginRequiredError as m, closeSharedMiniProgram as n, removeCustomConfigKey as nt, withMiniProgram$1 as o, formatRetryHotkeyPrompt as p, operatingSystemName as q, connectMiniProgram as r, defaultCustomConfigDirPath as rt, runRetryableCommand as s, acquireSharedMiniProgram$1 as t, readCustomConfig as tt, RETRY_PROMPT_INITIAL_IGNORE_MS as u, promptWechatIdeLoginRetry as v, i18nText as w, runWithSuspendedSharedInput as x, waitForRetryKeypress as y, detectWechatDevtoolsServicePort as z };
1354
+ export { createAutoTrustProjectConfig as $, getAutomatorProtocolTimeoutMethod as A, bootstrapWechatDevtoolsSettings as B, runWithSuspendedSharedInput as C, validateLocaleOption as D, i18nText as E, isDevtoolsExtensionContextInvalidatedError as F, resolveDevtoolsAutomationDefaults as G, resolveCliPath as H, isDevtoolsHttpPortError as I, isOperatingSystemSupported as J, SupportedPlatformsMap as K, isRetryableAutomatorLaunchError as L, isAutomatorPortInUseError as M, isAutomatorProtocolTimeoutError as N, connectOpenedAutomator as O, isAutomatorWsConnectError as P, createAutoBootstrapDevtoolsConfig as Q, launchAutomator as R, createSharedInputSession as S, configureLocaleFromArgv as T, getConfig as U, detectWechatDevtoolsServicePort as V, getConfiguredLocale as W, colors as X, operatingSystemName as Y, logger_default as Z, isWechatIdeLoginRequiredError as _, connectMiniProgram as a, defaultCustomConfigDirPath as at, promptWechatIdeLoginRetry as b, withMiniProgram$1 as c, RETRY_CONFIRM_KEYS as d, createCustomConfig as et, RETRY_PROMPT_INITIAL_IGNORE_MS as f, formatWechatIdeLoginRequiredError as g, formatRetryHotkeyPrompt as h, connectConsoleMiniProgram as i, removeCustomConfigKey as it, isAutomatorLoginError as j, formatAutomatorLoginError as k, runRetryableCommand as l, extractExecutionErrorText as m, acquireSharedMiniProgram$1 as n, overwriteCustomConfig as nt, getSharedMiniProgramSessionCount as o, defaultCustomConfigFilePath as ot, createWechatIdeLoginRequiredExitError as p, getDefaultCliPath as q, closeSharedMiniProgram as r, readCustomConfig as rt, releaseSharedMiniProgram as s, resolvePath as st, acquireConsoleMiniProgram as t, createLocaleConfig as tt, RETRY_CANCEL_KEYS as u, isWechatIdeLoginRequiredExitError as v, waitForExclusiveKeypress as w, waitForRetryKeypress as x, promptRetryKeypress as y, resolveProjectAutomatorPort as z };
@@ -1,6 +1,6 @@
1
- import { $ as createLocaleConfig, B as resolveCliPath, C as configureLocaleFromArgv, H as getConfiguredLocale, J as colors, Q as createCustomConfig, T as validateLocaleOption, U as resolveDevtoolsAutomationDefaults, X as createAutoBootstrapDevtoolsConfig, Y as logger_default, Z as createAutoTrustProjectConfig, a as releaseSharedMiniProgram, et as overwriteCustomConfig, it as defaultCustomConfigFilePath, n as closeSharedMiniProgram, nt as removeCustomConfigKey, r as connectMiniProgram, t as acquireSharedMiniProgram, tt as readCustomConfig, w as i18nText } from "./automator-session-BIjYknSi.js";
2
- import { A as isWechatIdeLoggedIn, B as runWechatCliCommand, C as clearWechatIdeCache, F as quitWechatIde, G as transformArgv, H as execute, K as promptForCliPath, L as resetWechatIdeFileUtils, M as openWechatIde, N as openWechatIdeOtherProject, P as previewWechatIde, Q as startWechatIdeEngineBuildByHttp, S as buildWechatIdeNpm, T as closeWechatIdeProject, U as createAlias, W as createPathCompat, Y as pollWechatIdeEngineBuildResultByHttp, _ as autoPreviewWechatIde, a as navigateBack, b as buildWechatIdeApk, c as pageStack, d as remote, f as scrollTo, g as tap, i as input, it as removeOption, j as loginWechatIde, l as reLaunch, m as systemInfo, n as captureScreenshotBuffer, nt as readBooleanOption, o as navigateTo, p as switchTab, r as currentPage, rt as readOptionValue, s as pageData, t as audit, tt as parseAutomatorArgs, u as redirectTo, v as autoReplayWechatIde, x as buildWechatIdeIpa, y as autoWechatIde, z as uploadWechatIde } from "./commands-9WCVsqHn.js";
3
- import "./run-mcp-BTB9ire3.js";
1
+ import { $ as createAutoTrustProjectConfig, D as validateLocaleOption, E as i18nText, G as resolveDevtoolsAutomationDefaults, H as resolveCliPath, Q as createAutoBootstrapDevtoolsConfig, T as configureLocaleFromArgv, W as getConfiguredLocale, X as colors, Z as logger_default, et as createCustomConfig, i as connectConsoleMiniProgram, it as removeCustomConfigKey, nt as overwriteCustomConfig, ot as defaultCustomConfigFilePath, r as closeSharedMiniProgram, rt as readCustomConfig, s as releaseSharedMiniProgram, t as acquireConsoleMiniProgram, tt as createLocaleConfig } from "./automator-session-B0GSCA8Z.js";
2
+ import { A as isWechatIdeLoggedIn, B as runWechatCliCommand, C as clearWechatIdeCache, F as quitWechatIde, G as transformArgv, H as execute, K as promptForCliPath, L as resetWechatIdeFileUtils, M as openWechatIde, N as openWechatIdeOtherProject, P as previewWechatIde, Q as startWechatIdeEngineBuildByHttp, S as buildWechatIdeNpm, T as closeWechatIdeProject, U as createAlias, W as createPathCompat, Y as pollWechatIdeEngineBuildResultByHttp, _ as autoPreviewWechatIde, a as navigateBack, b as buildWechatIdeApk, c as pageStack, d as remote, f as scrollTo, g as tap, i as input, it as removeOption, j as loginWechatIde, l as reLaunch, m as systemInfo, n as captureScreenshotBuffer, nt as readBooleanOption, o as navigateTo, p as switchTab, r as currentPage, rt as readOptionValue, s as pageData, t as audit, tt as parseAutomatorArgs, u as redirectTo, v as autoReplayWechatIde, x as buildWechatIdeIpa, y as autoWechatIde, z as uploadWechatIde } from "./commands-C2M-B-Nd.js";
3
+ import "./run-mcp-i4WLaQoh.js";
4
4
  import fs from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { fs as fs$1 } from "@weapp-core/shared/fs";
@@ -317,7 +317,7 @@ async function runScreenshot(argv) {
317
317
  }
318
318
  const options = parseScreenshotArgs(argv);
319
319
  const isJsonOutput = argv.includes("--json");
320
- const { takeScreenshot } = await import("./commands-BsYTeMoY.js");
320
+ const { takeScreenshot } = await import("./commands-CWIOxZm3.js");
321
321
  const result = await takeScreenshot(options);
322
322
  if (isJsonOutput) {
323
323
  console.log(JSON.stringify(result, null, 2));
@@ -1034,8 +1034,20 @@ const ENGINE_BUILD_ENDPOINT_MISSING_PATTERNS = [/Cannot GET \/engine\/build\b/i,
1034
1034
  const ENGINE_BUILD_ENDPOINT_MISSING_MESSAGE = "当前微信开发者工具未提供 engine build 接口,已跳过自动 engine build 刷新。";
1035
1035
  const ENGINE_BUILD_CLI_OPENED_PATTERN = /打开项目成功|project\s+opened|open\s+project\s+success|(?:^|\n)\s*✔\s*open(?:\n|$)/i;
1036
1036
  const COMPACT_WHITESPACE_PATTERN = /\s+/g;
1037
- function sleep$1(ms) {
1038
- return new Promise((resolve) => setTimeout(resolve, ms));
1037
+ function sleep$1(ms, signal) {
1038
+ signal?.throwIfAborted();
1039
+ return new Promise((resolve, reject) => {
1040
+ let timer;
1041
+ const onAbort = () => {
1042
+ clearTimeout(timer);
1043
+ reject(signal?.reason);
1044
+ };
1045
+ timer = setTimeout(() => {
1046
+ signal?.removeEventListener("abort", onAbort);
1047
+ resolve();
1048
+ }, ms);
1049
+ signal?.addEventListener("abort", onAbort, { once: true });
1050
+ });
1039
1051
  }
1040
1052
  function createEngineBuildLogFilename() {
1041
1053
  const now = /* @__PURE__ */ new Date();
@@ -1076,20 +1088,32 @@ function compactOutput(value) {
1076
1088
  return typeof value === "string" ? value.replace(COMPACT_WHITESPACE_PATTERN, " ").trim() : "";
1077
1089
  }
1078
1090
  async function runWechatIdeEngineBuildByCli(projectPath, options = {}) {
1079
- const { cliPath } = await resolveCliPath();
1091
+ options.signal?.throwIfAborted();
1092
+ const { cliPath } = await resolveCliPath().catch((error) => {
1093
+ options.signal?.throwIfAborted();
1094
+ throw error;
1095
+ });
1096
+ options.signal?.throwIfAborted();
1080
1097
  if (!cliPath) throw createEngineBuildError("WECHAT_DEVTOOLS_CLI_NOT_FOUND", "WECHAT_DEVTOOLS_CLI_NOT_FOUND");
1081
1098
  const result = await execa(cliPath, [
1082
1099
  "engine",
1083
1100
  "build",
1084
1101
  path.resolve(projectPath)
1085
1102
  ], {
1103
+ ...options.signal ? { cancelSignal: options.signal } : {},
1104
+ killDescendants: true,
1086
1105
  reject: false,
1087
1106
  timeout: options.overallTimeoutMs ?? 12e4
1107
+ }).catch((error) => {
1108
+ options.signal?.throwIfAborted();
1109
+ throw error;
1088
1110
  });
1111
+ options.signal?.throwIfAborted();
1089
1112
  const stdout = typeof result.stdout === "string" ? result.stdout : "";
1090
1113
  const stderr = typeof result.stderr === "string" ? result.stderr : "";
1091
1114
  const output = [stdout, stderr].filter(Boolean).join("\n");
1092
1115
  await writeEngineBuildLog(options.logPath, output);
1116
+ options.signal?.throwIfAborted();
1093
1117
  if ((result.exitCode ?? 1) === 0) {
1094
1118
  if (stdout) process.stdout.write(stdout);
1095
1119
  if (stderr) process.stderr.write(stderr);
@@ -1105,15 +1129,19 @@ async function runWechatIdeEngineBuildByCli(projectPath, options = {}) {
1105
1129
  * @description 通过开发者工具 HTTP 服务端口执行 engine build,并轮询直到构建结束。
1106
1130
  */
1107
1131
  async function runWechatIdeEngineBuildByHttp(projectPath, options = {}) {
1132
+ options.signal?.throwIfAborted();
1108
1133
  await startWechatIdeEngineBuildByHttp(projectPath, options);
1109
1134
  const startedAt = Date.now();
1110
1135
  while (true) {
1136
+ options.signal?.throwIfAborted();
1111
1137
  if (Date.now() - startedAt > (options.overallTimeoutMs ?? 12e4)) throw createEngineBuildError("WECHAT_DEVTOOLS_ENGINE_BUILD_TIMEOUT", "WECHAT_DEVTOOLS_ENGINE_BUILD_TIMEOUT");
1112
1138
  const result = await pollWechatIdeEngineBuildResultByHttp(options);
1139
+ options.signal?.throwIfAborted();
1113
1140
  options.onProgress?.(result);
1141
+ options.signal?.throwIfAborted();
1114
1142
  if (result.failed) throw createEngineBuildError(result.msg || result.body || "WECHAT_DEVTOOLS_ENGINE_BUILD_FAILED", "WECHAT_DEVTOOLS_ENGINE_BUILD_FAILED");
1115
1143
  if (result.done) return result;
1116
- await sleep$1(options.pollIntervalMs ?? 1e3);
1144
+ await sleep$1(options.pollIntervalMs ?? 1e3, options.signal);
1117
1145
  }
1118
1146
  }
1119
1147
  /**
@@ -1134,8 +1162,10 @@ async function runWechatIdeEngineBuild(projectPath, options = {}) {
1134
1162
  }
1135
1163
  });
1136
1164
  await writeEngineBuildLog(options.logPath, logs.join("\n"));
1165
+ options.signal?.throwIfAborted();
1137
1166
  return result;
1138
1167
  } catch (error) {
1168
+ options.signal?.throwIfAborted();
1139
1169
  if (isEngineBuildEndpointMissingError(error)) {
1140
1170
  if (options.fallbackToCli === false) throw createEngineBuildEndpointMissingError();
1141
1171
  return await runWechatIdeEngineBuildByCli(projectPath, options);
@@ -1279,7 +1309,7 @@ async function acquireForwardConsoleMiniProgram(options) {
1279
1309
  for (let attempt = 0; attempt <= ENABLE_LOG_RETRY_TIMES; attempt += 1) {
1280
1310
  let miniProgram;
1281
1311
  try {
1282
- miniProgram = await acquireSharedMiniProgram({
1312
+ miniProgram = await acquireConsoleMiniProgram({
1283
1313
  ...options,
1284
1314
  timeout: Math.min(options.timeout ?? FORWARD_CONSOLE_SESSION_TIMEOUT_MS, FORWARD_CONSOLE_SESSION_TIMEOUT_MS)
1285
1315
  });
@@ -1295,7 +1325,7 @@ async function acquireForwardConsoleMiniProgram(options) {
1295
1325
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
1296
1326
  }
1297
1327
  async function refreshOpenedMiniProgramConsoleLog(options) {
1298
- const miniProgram = await connectMiniProgram({
1328
+ const miniProgram = await connectConsoleMiniProgram({
1299
1329
  ...options,
1300
1330
  openedOnly: true
1301
1331
  });
@@ -1368,7 +1398,7 @@ async function startForwardConsole(options) {
1368
1398
  stopEnableLogRefresh = startEnableLogRefresh(miniProgram, options, usesSharedSession);
1369
1399
  if (usesSharedSession) auxiliaryTimer = setTimeout(() => {
1370
1400
  (async () => {
1371
- const openedMiniProgram = await connectMiniProgram({
1401
+ const openedMiniProgram = await connectConsoleMiniProgram({
1372
1402
  ...options,
1373
1403
  openedOnly: true
1374
1404
  });
@@ -1774,7 +1804,7 @@ async function parse(argv) {
1774
1804
  return;
1775
1805
  }
1776
1806
  if (matchedCommand === "mcp") {
1777
- const { runMcpCommand } = await import("./run-mcp-Q3skAZs_.js");
1807
+ const { runMcpCommand } = await import("./run-mcp-BuEgRLOT.js");
1778
1808
  await runMcpCommand(argv.slice(1));
1779
1809
  return;
1780
1810
  }
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Y as logger_default } from "./automator-session-BIjYknSi.js";
2
- import { n as parse } from "./cli-CFRAOBIw.js";
1
+ import { Z as logger_default } from "./automator-session-B0GSCA8Z.js";
2
+ import { n as parse } from "./cli-DkuHSA2C.js";
3
3
  import process from "node:process";
4
4
  //#region src/cli.ts
5
5
  const argv = process.argv.slice(2);
@@ -1,4 +1,4 @@
1
- import { B as resolveCliPath, J as colors, K as isOperatingSystemSupported, Q as createCustomConfig, R as bootstrapWechatDevtoolsSettings, Y as logger_default, at as resolvePath, d as createWechatIdeLoginRequiredExitError, h as isWechatIdeLoginRequiredError, it as defaultCustomConfigFilePath, n as closeSharedMiniProgram, o as withMiniProgram, q as operatingSystemName, s as runRetryableCommand, tt as readCustomConfig, v as promptWechatIdeLoginRetry, w as i18nText, x as runWithSuspendedSharedInput, z as detectWechatDevtoolsServicePort } from "./automator-session-BIjYknSi.js";
1
+ import { B as bootstrapWechatDevtoolsSettings, C as runWithSuspendedSharedInput, E as i18nText, H as resolveCliPath, J as isOperatingSystemSupported, V as detectWechatDevtoolsServicePort, X as colors, Y as operatingSystemName, Z as logger_default, _ as isWechatIdeLoginRequiredError, b as promptWechatIdeLoginRetry, c as withMiniProgram, et as createCustomConfig, l as runRetryableCommand, ot as defaultCustomConfigFilePath, p as createWechatIdeLoginRequiredExitError, r as closeSharedMiniProgram, rt as readCustomConfig, st as resolvePath } from "./automator-session-B0GSCA8Z.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
@@ -437,21 +437,29 @@ function parseWechatDevtoolsEngineBuildResult(body) {
437
437
  }
438
438
  }
439
439
  async function requestWechatDevtoolsHttp(pathname, query, options = {}) {
440
- const url = createWechatDevtoolsHttpUrl(await resolveWechatDevtoolsHttpPort(options.port), pathname, query);
440
+ options.signal?.throwIfAborted();
441
+ const port = await resolveWechatDevtoolsHttpPort(options.port).catch((error) => {
442
+ options.signal?.throwIfAborted();
443
+ throw error;
444
+ });
445
+ options.signal?.throwIfAborted();
446
+ const url = createWechatDevtoolsHttpUrl(port, pathname, query);
441
447
  const controller = new AbortController();
448
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
442
449
  const timeout = setTimeout(() => {
443
- controller.abort();
450
+ controller.abort(createWechatDevtoolsHttpError("WECHAT_DEVTOOLS_HTTP_TIMEOUT", "WECHAT_DEVTOOLS_HTTP_TIMEOUT"));
444
451
  }, options.timeoutMs ?? 1e4);
445
452
  try {
446
453
  const response = await fetch(url, {
447
454
  method: "GET",
448
- signal: controller.signal
455
+ signal
449
456
  });
450
457
  const body = await response.text();
458
+ signal.throwIfAborted();
451
459
  if (!response.ok) throw createWechatDevtoolsHttpError(body || `HTTP ${response.status}`, "WECHAT_DEVTOOLS_HTTP_REQUEST_FAILED");
452
460
  return body;
453
461
  } catch (error) {
454
- if (error instanceof Error && error.name === "AbortError") throw createWechatDevtoolsHttpError("WECHAT_DEVTOOLS_HTTP_TIMEOUT", "WECHAT_DEVTOOLS_HTTP_TIMEOUT");
462
+ signal.throwIfAborted();
455
463
  throw error;
456
464
  } finally {
457
465
  clearTimeout(timeout);
@@ -790,6 +798,10 @@ async function openWechatIde(options = {}) {
790
798
  appendProjectLocatorArgv(argv, options);
791
799
  if (options.platform) argv.push("--platform", options.platform);
792
800
  if (options.trustProject) argv.push("--trust-project");
801
+ if (options.projectPath) try {
802
+ await openWechatIdeProjectByHttp(options.projectPath);
803
+ return;
804
+ } catch {}
793
805
  await runWechatCliCommand(argv);
794
806
  }
795
807
  /**
@@ -0,0 +1,2 @@
1
+ import { h as takeScreenshot } from "./commands-C2M-B-Nd.js";
2
+ export { takeScreenshot };