weapp-ide-cli 5.2.2 → 5.2.4

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
@@ -2,13 +2,12 @@
2
2
 
3
3
  `weapp-ide-cli` 是对「微信开发者工具」官方命令行的增强封装,提供更友好的参数体验、路径兼容与配置管理能力,帮助你在本地与持续集成环境中高效调用工具链。
4
4
 
5
- > 开始前请在微信开发者工具中打开「设置 → 安全设置 → 服务端口」。
6
-
7
5
  ## 功能亮点
8
6
 
9
7
  - 自动识别或记忆微信开发者工具 `cli` 所在位置,避免反复输入路径。
10
8
  - 为 `-p / --project`、`--qr-output` 等选项自动补全绝对路径,默认使用当前工作目录。
11
9
  - 使用与官方指令完全一致的调用方式,便于在脚本中无缝迁移。
10
+ - 在 `open` / `auto` / `auto-preview` / automator 启动前,自动预热微信开发者工具安全设置,并可自动信任目标项目。
12
11
  - 支持 macOS、Windows 以及安装了社区版工具的 Linux 桌面环境。
13
12
  - 内置支付宝小程序 CLI 入口,直接转发至官方 `minidev` 工具。
14
13
 
@@ -34,6 +33,9 @@ weapp open -p
34
33
  # 启动并加载指定项目
35
34
  weapp open --project ./dist/dev/mp-weixin
36
35
 
36
+ # 显式要求信任项目
37
+ weapp open --project ./dist/dev/mp-weixin --trust-project
38
+
37
39
  # 执行预览、上传等官方支持的命令
38
40
  weapp preview
39
41
  weapp upload --project ./dist/build/mp-weixin
@@ -43,6 +45,13 @@ weapp cache --clean all
43
45
 
44
46
  `weapp` 与 `weapp-ide-cli` 等价,选择任一前缀即可。
45
47
 
48
+ 从当前版本开始,`weapp-ide-cli` 会在调用微信开发者工具前自动尝试预热本机 DevTools 配置:
49
+
50
+ - 确保安全设置里启用服务端口
51
+ - 根据命令或全局配置决定是否自动信任项目
52
+
53
+ 在 macOS 上,它会写入 `~/Library/Application Support/微信开发者工具/*/WeappLocalData` 下对应的本地配置;如果你不希望自动处理,也可以通过下文的 `config` 配置项关闭。
54
+
46
55
  ## 支付宝小程序(minidev)支持
47
56
 
48
57
  封装内置了支付宝官方 CLI —— `minidev` 的调用入口,可通过 `weapp alipay` 或 `weapp ali` 直接转发指令:
@@ -155,18 +164,18 @@ weapp navigate --help
155
164
 
156
165
  ### 3. config 子命令
157
166
 
158
- | 命令 | 说明 |
159
- | -------------------------------------------- | ----------------------------------- |
160
- | `weapp config` | 交互式配置 CLI 路径 |
161
- | `weapp config lang <zh\|en>` | 切换并保存语言 |
162
- | `weapp config set-lang <zh\|en>` | `lang` 的别名 |
163
- | `weapp config show` | 显示完整配置 JSON |
164
- | `weapp config get <cliPath\|locale>` | 读取单个配置项 |
165
- | `weapp config set <cliPath\|locale> <value>` | 写入配置项 |
166
- | `weapp config unset <cliPath\|locale>` | 删除配置项 |
167
- | `weapp config doctor` | 配置健康诊断 |
168
- | `weapp config export [path]` | 导出配置(不传 path 则输出 stdout) |
169
- | `weapp config import <path>` | 从 JSON 文件导入配置 |
167
+ | 命令 | 说明 |
168
+ | ------------------------------------------------------------------------------------- | ----------------------------------- |
169
+ | `weapp config` | 交互式配置 CLI 路径 |
170
+ | `weapp config lang <zh\|en>` | 切换并保存语言 |
171
+ | `weapp config set-lang <zh\|en>` | `lang` 的别名 |
172
+ | `weapp config show` | 显示完整配置 JSON(含生效默认值) |
173
+ | `weapp config get <cliPath\|locale\|autoBootstrapDevtools\|autoTrustProject>` | 读取单个配置项 |
174
+ | `weapp config set <cliPath\|locale\|autoBootstrapDevtools\|autoTrustProject> <value>` | 写入配置项 |
175
+ | `weapp config unset <cliPath\|locale\|autoBootstrapDevtools\|autoTrustProject>` | 删除配置项 |
176
+ | `weapp config doctor` | 配置健康诊断(含生效默认值) |
177
+ | `weapp config export [path]` | 导出配置(不传 path 则输出 stdout) |
178
+ | `weapp config import <path>` | 从 JSON 文件导入配置 |
170
179
 
171
180
  ### 4. 支付宝 minidev 转发命令
172
181
 
@@ -223,14 +232,20 @@ weapp config show
223
232
  # 读取单个配置项
224
233
  weapp config get cliPath
225
234
  weapp config get locale
235
+ weapp config get autoBootstrapDevtools
236
+ weapp config get autoTrustProject
226
237
 
227
238
  # 设置配置项
228
239
  weapp config set cliPath /Applications/wechatwebdevtools.app/Contents/MacOS/cli
229
240
  weapp config set locale en
241
+ weapp config set autoBootstrapDevtools true
242
+ weapp config set autoTrustProject true
230
243
 
231
244
  # 清除配置项
232
245
  weapp config unset cliPath
233
246
  weapp config unset locale
247
+ weapp config unset autoBootstrapDevtools
248
+ weapp config unset autoTrustProject
234
249
 
235
250
  # 诊断配置可用性
236
251
  weapp config doctor
@@ -252,10 +267,36 @@ weapp config import ./weapp-ide-cli.config.json
252
267
  ```json
253
268
  {
254
269
  "cliPath": "/Applications/wechatwebdevtools.app/Contents/MacOS/cli",
255
- "locale": "zh"
270
+ "locale": "zh",
271
+ "autoBootstrapDevtools": true,
272
+ "autoTrustProject": false
256
273
  }
257
274
  ```
258
275
 
276
+ 开发者工具自动预热相关配置说明:
277
+
278
+ - `autoBootstrapDevtools`
279
+ - 默认生效值:`true`
280
+ - 含义:在 `weapp open`、`weapp auto`、`weapp auto-preview` 以及 automator 启动前,自动预写入微信开发者工具安全设置
281
+ - `autoTrustProject`
282
+ - 默认生效值:`false`
283
+ - 含义:在未显式传 `--trust-project` 时,是否默认把目标项目写成已信任
284
+
285
+ 推荐配置:
286
+
287
+ ```sh
288
+ weapp config set autoBootstrapDevtools true
289
+ weapp config set autoTrustProject true
290
+ ```
291
+
292
+ 这样以后就可以直接执行:
293
+
294
+ ```sh
295
+ weapp open --project ./dist/dev/mp-weixin
296
+ ```
297
+
298
+ 而不用每次都补 `--trust-project`。
299
+
259
300
  ## 平台支持与限制
260
301
 
261
302
  | 平台 | 支持情况 | 默认查找路径 |
@@ -268,7 +309,7 @@ weapp config import ./weapp-ide-cli.config.json
268
309
 
269
310
  ## 在脚本或 CI 中使用
270
311
 
271
- 1. 确保执行环境已安装微信开发者工具并开启服务端口。
312
+ 1. 确保执行环境已安装微信开发者工具,并且当前账号已登录。
272
313
  2. 首次运行前可通过 `weapp config` 写入 CLI 路径,也可在 CI 中直接向 `~/.weapp-ide-cli/config.json` 写入。
273
314
  3. 在自动化流程中建议加上 `--qr-output`、`--result-output` 等参数,以便收集产物或日志。
274
315
 
@@ -316,8 +357,9 @@ WEAPP_IDE_CLI_LANG=en weapp navigate pages/index/index -p ./mini-app
316
357
 
317
358
  ## 常见问题
318
359
 
319
- - **命令执行后无反应**:请确认微信开发者工具已开启服务端口,并尝试重新登录或升级工具版本。
360
+ - **命令执行后无反应**:请确认微信开发者工具已登录,并尝试重新打开工具或升级版本;默认情况下 CLI 会先自动预热服务端口配置。
320
361
  - **提示 `需要重新登录` 或 `code: 10`**:表示微信开发者工具登录态失效。交互模式下可按 `r` 重试,按 `q`、`Esc` 或 `Ctrl+C` 取消;非交互模式(含 CI / 非TTY)会直接失败返回非 0。
362
+ - **不想自动改本机 DevTools 配置**:执行 `weapp config set autoBootstrapDevtools false` 关闭默认预热;如只想关闭默认自动信任项目,可执行 `weapp config set autoTrustProject false`。
321
363
  - **提示未找到 CLI**:检查配置文件中的路径是否真实存在,可使用绝对路径避免解析误差。
322
364
  - **Linux 环境报错**:需安装社区版工具并将 `wechat-devtools-cli` 加入 `PATH`,否则只能手动指定路径。
323
365
  - **`upload` 报参数缺失**:`weapp upload` 现在会在本地前置校验 `--version/-v` 与 `--desc/-d`,缺失时直接报错以避免触发远端失败。
@@ -1,6 +1,6 @@
1
- import { B as createLocaleConfig, C as configureLocaleFromArgv, G as defaultCustomConfigFilePath, H as readCustomConfig, I as resolveCliPath, K as resolvePath, Q as logger_default, R as getConfiguredLocale, T as validateLocaleOption, U as removeCustomConfigKey, V as overwriteCustomConfig, X as operatingSystemName, Y as isOperatingSystemSupported, Z as colors, a as navigateBack, c as pageStack, d as remote, f as scrollTo, g as tap, i as input, l as reLaunch, m as systemInfo, n as captureScreenshotBuffer, o as navigateTo, p as switchTab, r as currentPage, s as pageData, t as audit, u as redirectTo, w as i18nText, y as connectMiniProgram, z as createCustomConfig } from "./commands-38LzU5ML.js";
1
+ import { $ as readCustomConfig, B as getConfiguredLocale, C as configureLocaleFromArgv, G as operatingSystemName, I as bootstrapWechatDevtoolsSettings, J as createAutoBootstrapDevtoolsConfig, K as colors, Q as overwriteCustomConfig, R as resolveCliPath, T as validateLocaleOption, V as resolveDevtoolsAutomationDefaults, W as isOperatingSystemSupported, X as createCustomConfig, Y as createAutoTrustProjectConfig, Z as createLocaleConfig, a as navigateBack, c as pageStack, d as remote, et as removeCustomConfigKey, f as scrollTo, g as tap, i as input, l as reLaunch, m as systemInfo, n as captureScreenshotBuffer, nt as defaultCustomConfigFilePath, o as navigateTo, p as switchTab, q as logger_default, r as currentPage, rt as resolvePath, s as pageData, t as audit, u as redirectTo, w as i18nText, y as connectMiniProgram } from "./commands-XD_wemcg.js";
2
2
  import fs from "node:fs/promises";
3
- import { fs as fs$1 } from "@weapp-core/shared";
3
+ import { fs as fs$1 } from "@weapp-core/shared/fs";
4
4
  import process, { stdin, stdout } from "node:process";
5
5
  import { PNG } from "pngjs";
6
6
  import pixelmatch from "pixelmatch";
@@ -402,7 +402,7 @@ async function runScreenshot(argv) {
402
402
  }
403
403
  const options = parseScreenshotArgs(argv);
404
404
  const isJsonOutput = argv.includes("--json");
405
- const { takeScreenshot } = await import("./commands-msx1PSZ8.js");
405
+ const { takeScreenshot } = await import("./commands-CVibHgp4.js");
406
406
  const result = await takeScreenshot(options);
407
407
  if (isJsonOutput) {
408
408
  console.log(JSON.stringify(result, null, 2));
@@ -819,6 +819,12 @@ async function promptForCliPath() {
819
819
  }
820
820
  //#endregion
821
821
  //#region src/cli/config-command.ts
822
+ function parseBooleanConfigValue(rawValue) {
823
+ const normalized = rawValue.trim().toLowerCase();
824
+ if (normalized === "true" || normalized === "1" || normalized === "on") return true;
825
+ if (normalized === "false" || normalized === "0" || normalized === "off") return false;
826
+ throw new Error(i18nText(`无效的布尔配置值: ${rawValue}(请使用 true/false)`, `Invalid boolean config value: ${rawValue} (use true/false)`));
827
+ }
822
828
  /**
823
829
  * @description 处理 config 子命令。
824
830
  */
@@ -837,18 +843,26 @@ async function handleConfigCommand(argv) {
837
843
  }
838
844
  if (action === "show") {
839
845
  const config = await readCustomConfig();
846
+ const effectiveDevtoolsDefaults = resolveDevtoolsAutomationDefaults(config);
840
847
  logger_default.info(i18nText(`配置文件路径:${colors.green(defaultCustomConfigFilePath)}`, `Config file: ${colors.green(defaultCustomConfigFilePath)}`));
841
- console.log(JSON.stringify(config, null, 2));
848
+ console.log(JSON.stringify({
849
+ ...config,
850
+ effective: effectiveDevtoolsDefaults
851
+ }, null, 2));
842
852
  return;
843
853
  }
844
854
  if (action === "get") {
845
855
  const key = argv[1];
846
- if (key !== "cliPath" && key !== "locale") throw new Error(i18nText("仅支持读取配置项:cliPath | locale", "Supported keys: cliPath | locale"));
856
+ if (key !== "cliPath" && key !== "locale" && key !== "autoBootstrapDevtools" && key !== "autoTrustProject") throw new Error(i18nText("仅支持读取配置项:cliPath | locale | autoBootstrapDevtools | autoTrustProject", "Supported keys: cliPath | locale | autoBootstrapDevtools | autoTrustProject"));
847
857
  const value = (await readCustomConfig())[key];
848
858
  if (typeof value === "string") {
849
859
  console.log(value);
850
860
  return;
851
861
  }
862
+ if (typeof value === "boolean") {
863
+ console.log(String(value));
864
+ return;
865
+ }
852
866
  console.log("");
853
867
  return;
854
868
  }
@@ -867,11 +881,23 @@ async function handleConfigCommand(argv) {
867
881
  logger_default.info(i18nText(`语言已切换为:${value === "zh" ? "中文" : "英文"}`, `Language switched to: ${value}`));
868
882
  return;
869
883
  }
870
- throw new Error(i18nText("仅支持设置配置项:cliPath | locale", "Supported keys for set: cliPath | locale"));
884
+ if (key === "autoBootstrapDevtools") {
885
+ const parsed = parseBooleanConfigValue(value);
886
+ await createAutoBootstrapDevtoolsConfig(parsed);
887
+ logger_default.info(i18nText(`autoBootstrapDevtools 已更新为:${parsed}`, `autoBootstrapDevtools updated to: ${parsed}`));
888
+ return;
889
+ }
890
+ if (key === "autoTrustProject") {
891
+ const parsed = parseBooleanConfigValue(value);
892
+ await createAutoTrustProjectConfig(parsed);
893
+ logger_default.info(i18nText(`autoTrustProject 已更新为:${parsed}`, `autoTrustProject updated to: ${parsed}`));
894
+ return;
895
+ }
896
+ throw new Error(i18nText("仅支持设置配置项:cliPath | locale | autoBootstrapDevtools | autoTrustProject", "Supported keys for set: cliPath | locale | autoBootstrapDevtools | autoTrustProject"));
871
897
  }
872
898
  if (action === "unset") {
873
899
  const key = argv[1];
874
- if (key !== "cliPath" && key !== "locale") throw new Error(i18nText("仅支持清除配置项:cliPath | locale", "Supported keys for unset: cliPath | locale"));
900
+ if (key !== "cliPath" && key !== "locale" && key !== "autoBootstrapDevtools" && key !== "autoTrustProject") throw new Error(i18nText("仅支持清除配置项:cliPath | locale | autoBootstrapDevtools | autoTrustProject", "Supported keys for unset: cliPath | locale | autoBootstrapDevtools | autoTrustProject"));
875
901
  await removeCustomConfigKey(key);
876
902
  logger_default.info(i18nText(`已清除配置项:${key}`, `Config key cleared: ${key}`));
877
903
  return;
@@ -883,12 +909,17 @@ async function handleConfigCommand(argv) {
883
909
  const hasCustomCli = typeof rawConfig.cliPath === "string" && rawConfig.cliPath.length > 0;
884
910
  const hasValidCli = Boolean(resolvedCli.cliPath);
885
911
  const locale = rawConfig.locale ?? "zh";
912
+ const effectiveDevtoolsDefaults = resolveDevtoolsAutomationDefaults(rawConfig);
886
913
  const report = {
887
914
  configFile: defaultCustomConfigFilePath,
888
915
  configFileExists: hasConfigFile,
889
916
  cliPath: rawConfig.cliPath ?? null,
890
917
  cliPathValid: hasValidCli,
891
918
  locale,
919
+ autoBootstrapDevtools: rawConfig.autoBootstrapDevtools ?? null,
920
+ autoTrustProject: rawConfig.autoTrustProject ?? null,
921
+ effectiveAutoBootstrapDevtools: effectiveDevtoolsDefaults.autoBootstrapDevtools,
922
+ effectiveAutoTrustProject: effectiveDevtoolsDefaults.autoTrustProject,
892
923
  source: resolvedCli.source
893
924
  };
894
925
  logger_default.info(i18nText("配置诊断结果:", "Configuration diagnostics:"));
@@ -919,7 +950,9 @@ async function handleConfigCommand(argv) {
919
950
  const candidate = imported;
920
951
  await overwriteCustomConfig({
921
952
  cliPath: typeof candidate.cliPath === "string" ? candidate.cliPath : void 0,
922
- locale: candidate.locale === "zh" || candidate.locale === "en" ? candidate.locale : void 0
953
+ locale: candidate.locale === "zh" || candidate.locale === "en" ? candidate.locale : void 0,
954
+ autoBootstrapDevtools: typeof candidate.autoBootstrapDevtools === "boolean" ? candidate.autoBootstrapDevtools : void 0,
955
+ autoTrustProject: typeof candidate.autoTrustProject === "boolean" ? candidate.autoTrustProject : void 0
923
956
  });
924
957
  logger_default.info(i18nText(`配置已从 ${colors.green(inputPath)} 导入`, `Config imported from ${colors.green(inputPath)}`));
925
958
  return;
@@ -1469,6 +1502,30 @@ function createMinidevOpenArgv(argv) {
1469
1502
  nextArgv[0] = "ide";
1470
1503
  return removeOption(nextArgv, "--platform");
1471
1504
  }
1505
+ function shouldBootstrapWechatDevtools(command) {
1506
+ return command === "open" || command === "auto" || command === "auto-preview";
1507
+ }
1508
+ function resolveBooleanCliOption(argv, optionName) {
1509
+ if (argv.includes(optionName)) return true;
1510
+ const rawValue = readOptionValue(argv, optionName);
1511
+ if (rawValue === void 0) return;
1512
+ const normalized = rawValue.trim().toLowerCase();
1513
+ if (normalized === "" || normalized === "true" || normalized === "1" || normalized === "on") return true;
1514
+ if (normalized === "false" || normalized === "0" || normalized === "off") return false;
1515
+ return true;
1516
+ }
1517
+ async function maybeBootstrapWechatDevtoolsSettings(argv) {
1518
+ const command = argv[0];
1519
+ if (!shouldBootstrapWechatDevtools(command)) return;
1520
+ const config = await readCustomConfig();
1521
+ if (config.autoBootstrapDevtools === false) return;
1522
+ const projectPath = readOptionValue(argv, "--project");
1523
+ const trustProjectOption = resolveBooleanCliOption(argv, "--trust-project");
1524
+ await bootstrapWechatDevtoolsSettings({
1525
+ projectPath,
1526
+ trustProject: trustProjectOption === void 0 ? config.autoTrustProject ?? false : trustProjectOption
1527
+ });
1528
+ }
1472
1529
  /**
1473
1530
  * @description CLI 入口解析与分发。
1474
1531
  */
@@ -1513,6 +1570,7 @@ async function parse(argv) {
1513
1570
  await handleMissingCliPath(source);
1514
1571
  return;
1515
1572
  }
1573
+ await maybeBootstrapWechatDevtoolsSettings(formattedArgv);
1516
1574
  await runWechatCliWithRetry(cliPath, formattedArgv);
1517
1575
  }
1518
1576
  //#endregion
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Q as logger_default } from "./commands-38LzU5ML.js";
2
- import { n as parse } from "./cli-1zieDX-6.js";
1
+ import { q as logger_default } from "./commands-XD_wemcg.js";
2
+ import { n as parse } from "./cli-CfovXw-V.js";
3
3
  import process from "node:process";
4
4
  //#region src/cli.ts
5
5
  const argv = process.argv.slice(2);
@@ -0,0 +1,2 @@
1
+ import { h as takeScreenshot } from "./commands-XD_wemcg.js";
2
+ export { takeScreenshot };
@@ -3,84 +3,12 @@ import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { Launcher } from "@weapp-vite/miniprogram-automator";
6
- import { fs as fs$1 } from "@weapp-core/shared";
7
- import logger, { colors } from "@weapp-core/logger";
6
+ import { fs as fs$1 } from "@weapp-core/shared/fs";
8
7
  import process from "node:process";
9
8
  import path$1 from "pathe";
9
+ import logger, { colors } from "@weapp-core/logger";
10
+ import { createHash } from "node:crypto";
10
11
  import { PNG } from "pngjs";
11
- //#region src/logger.ts
12
- var logger_default = logger;
13
- //#endregion
14
- //#region src/runtime/platform.ts
15
- /**
16
- * @description 官方微信开发者工具只支持 Windows、macOS,Linux 只有社区版
17
- * https://github.com/msojocs/wechat-web-devtools-linux
18
- */
19
- const SupportedPlatformsMap = {
20
- Windows_NT: "Windows_NT",
21
- Darwin: "Darwin",
22
- Linux: "Linux"
23
- };
24
- /**
25
- * @description 判断当前系统是否支持微信开发者工具
26
- */
27
- function isOperatingSystemSupported(osName = os.type()) {
28
- return osName === SupportedPlatformsMap.Windows_NT || osName === SupportedPlatformsMap.Darwin || osName === SupportedPlatformsMap.Linux;
29
- }
30
- /**
31
- * @description 当前系统名称
32
- */
33
- const operatingSystemName = os.type();
34
- async function getFirstBinaryPath(command) {
35
- const pathDirs = (process.env.PATH || "").split(path$1.delimiter);
36
- for (const dir of pathDirs) {
37
- const fullPath = path$1.join(dir, command);
38
- try {
39
- await fs$1.access(fullPath, fs$1.constants.X_OK);
40
- return fullPath;
41
- } catch {
42
- continue;
43
- }
44
- }
45
- }
46
- function createLinuxCliResolver() {
47
- let resolvedPath;
48
- let attempted = false;
49
- let pending = null;
50
- return async () => {
51
- if (attempted) return resolvedPath;
52
- if (!pending) pending = (async () => {
53
- try {
54
- const envPath = await getFirstBinaryPath("wechat-devtools-cli");
55
- if (envPath) resolvedPath = envPath;
56
- } catch (error) {
57
- const reason = error instanceof Error ? error.message : String(error);
58
- logger_default.warn(`获取 Linux wechat-devtools-cli 路径失败:${reason}`);
59
- } finally {
60
- attempted = true;
61
- }
62
- return resolvedPath;
63
- })();
64
- return pending;
65
- };
66
- }
67
- const linuxCliResolver = createLinuxCliResolver();
68
- const WINDOWS_DEFAULT_CLI = "C:\\Program Files (x86)\\Tencent\\微信web开发者工具\\cli.bat";
69
- const DARWIN_DEFAULT_CLI = "/Applications/wechatwebdevtools.app/Contents/MacOS/cli";
70
- const cliPathResolvers = {
71
- [SupportedPlatformsMap.Windows_NT]: async () => WINDOWS_DEFAULT_CLI,
72
- [SupportedPlatformsMap.Darwin]: async () => DARWIN_DEFAULT_CLI,
73
- [SupportedPlatformsMap.Linux]: linuxCliResolver
74
- };
75
- /**
76
- * @description 获取默认 CLI 路径(按系统)
77
- */
78
- async function getDefaultCliPath(targetOs = operatingSystemName) {
79
- if (!isOperatingSystemSupported(targetOs)) return;
80
- const resolver = cliPathResolvers[targetOs];
81
- return await resolver();
82
- }
83
- //#endregion
84
12
  //#region src/utils/path.ts
85
13
  /**
86
14
  * @description 解析为绝对路径(基于当前工作目录)
@@ -115,6 +43,8 @@ async function readCustomConfig() {
115
43
  const next = {};
116
44
  if (typeof candidate.cliPath === "string" && candidate.cliPath.trim()) next.cliPath = candidate.cliPath.trim();
117
45
  if (candidate.locale === "zh" || candidate.locale === "en") next.locale = candidate.locale;
46
+ if (typeof candidate.autoBootstrapDevtools === "boolean") next.autoBootstrapDevtools = candidate.autoBootstrapDevtools;
47
+ if (typeof candidate.autoTrustProject === "boolean") next.autoTrustProject = candidate.autoTrustProject;
118
48
  return next;
119
49
  } catch {
120
50
  return {};
@@ -146,6 +76,20 @@ async function createLocaleConfig(locale) {
146
76
  return locale;
147
77
  }
148
78
  /**
79
+ * @description 写入开发者工具自动预热配置。
80
+ */
81
+ async function createAutoBootstrapDevtoolsConfig(value) {
82
+ await writeCustomConfig({ autoBootstrapDevtools: value });
83
+ return value;
84
+ }
85
+ /**
86
+ * @description 写入项目自动信任配置。
87
+ */
88
+ async function createAutoTrustProjectConfig(value) {
89
+ await writeCustomConfig({ autoTrustProject: value });
90
+ return value;
91
+ }
92
+ /**
149
93
  * @description 删除指定配置项。
150
94
  */
151
95
  async function removeCustomConfigKey(key) {
@@ -162,14 +106,133 @@ async function overwriteCustomConfig(config) {
162
106
  const nextConfig = {};
163
107
  if (typeof config.cliPath === "string" && config.cliPath.trim()) nextConfig.cliPath = resolvePath(config.cliPath.trim());
164
108
  if (config.locale === "zh" || config.locale === "en") nextConfig.locale = config.locale;
109
+ if (typeof config.autoBootstrapDevtools === "boolean") nextConfig.autoBootstrapDevtools = config.autoBootstrapDevtools;
110
+ if (typeof config.autoTrustProject === "boolean") nextConfig.autoTrustProject = config.autoTrustProject;
165
111
  await writeCustomConfig(nextConfig, { replace: true });
166
112
  }
167
113
  //#endregion
114
+ //#region src/logger.ts
115
+ var logger_default = logger;
116
+ //#endregion
117
+ //#region src/runtime/platform.ts
118
+ /**
119
+ * @description 官方微信开发者工具只支持 Windows、macOS,Linux 只有社区版。
120
+ * https://github.com/msojocs/wechat-web-devtools-linux
121
+ */
122
+ const SupportedPlatformsMap = {
123
+ Windows_NT: "Windows_NT",
124
+ Darwin: "Darwin",
125
+ Linux: "Linux"
126
+ };
127
+ /**
128
+ * @description 判断当前系统是否支持微信开发者工具。
129
+ */
130
+ function isOperatingSystemSupported(osName = os.type()) {
131
+ return osName === SupportedPlatformsMap.Windows_NT || osName === SupportedPlatformsMap.Darwin || osName === SupportedPlatformsMap.Linux;
132
+ }
133
+ /**
134
+ * @description 当前系统名称。
135
+ */
136
+ const operatingSystemName = os.type();
137
+ async function findFirstExistingPath(candidates) {
138
+ for (const candidate of candidates) {
139
+ if (!candidate) continue;
140
+ if (await fs$1.pathExists(candidate)) return candidate;
141
+ }
142
+ }
143
+ async function getFirstBinaryPath(command) {
144
+ const pathDirs = (process.env.PATH || "").split(path$1.delimiter);
145
+ for (const dir of pathDirs) {
146
+ const fullPath = path$1.join(dir, command);
147
+ try {
148
+ await fs$1.access(fullPath, fs$1.constants.X_OK);
149
+ return fullPath;
150
+ } catch {
151
+ continue;
152
+ }
153
+ }
154
+ }
155
+ function createLinuxCliResolver() {
156
+ let resolvedPath;
157
+ let attempted = false;
158
+ let pending = null;
159
+ return async () => {
160
+ if (attempted) return resolvedPath;
161
+ if (!pending) pending = (async () => {
162
+ try {
163
+ const envPath = await getFirstBinaryPath("wechat-devtools-cli");
164
+ if (envPath) resolvedPath = envPath;
165
+ } catch (error) {
166
+ const reason = error instanceof Error ? error.message : String(error);
167
+ logger_default.warn(`获取 Linux wechat-devtools-cli 路径失败:${reason}`);
168
+ } finally {
169
+ attempted = true;
170
+ }
171
+ return resolvedPath;
172
+ })();
173
+ return pending;
174
+ };
175
+ }
176
+ function createWindowsCliResolver() {
177
+ let resolvedPath;
178
+ let attempted = false;
179
+ let pending = null;
180
+ return async () => {
181
+ if (attempted) return resolvedPath;
182
+ if (!pending) pending = (async () => {
183
+ const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
184
+ const programFiles = process.env.ProgramFiles || "C:\\Program Files";
185
+ const localAppData = process.env.LOCALAPPDATA || path$1.join(os.homedir(), "AppData", "Local");
186
+ const candidates = [
187
+ path$1.join(programFilesX86, "Tencent", "微信web开发者工具", "cli.bat"),
188
+ path$1.join(programFiles, "Tencent", "微信web开发者工具", "cli.bat"),
189
+ path$1.join(localAppData, "Programs", "微信开发者工具", "cli.bat"),
190
+ path$1.join(localAppData, "Tencent", "微信web开发者工具", "cli.bat")
191
+ ];
192
+ try {
193
+ resolvedPath = await findFirstExistingPath(candidates);
194
+ } catch (error) {
195
+ const reason = error instanceof Error ? error.message : String(error);
196
+ logger_default.warn(`获取 Windows 微信开发者工具 CLI 路径失败:${reason}`);
197
+ } finally {
198
+ attempted = true;
199
+ }
200
+ return resolvedPath;
201
+ })();
202
+ return pending;
203
+ };
204
+ }
205
+ const linuxCliResolver = createLinuxCliResolver();
206
+ const windowsCliResolver = createWindowsCliResolver();
207
+ const DARWIN_DEFAULT_CLI = "/Applications/wechatwebdevtools.app/Contents/MacOS/cli";
208
+ const cliPathResolvers = {
209
+ [SupportedPlatformsMap.Windows_NT]: windowsCliResolver,
210
+ [SupportedPlatformsMap.Darwin]: async () => DARWIN_DEFAULT_CLI,
211
+ [SupportedPlatformsMap.Linux]: linuxCliResolver
212
+ };
213
+ /**
214
+ * @description 获取默认 CLI 路径(按系统)。
215
+ */
216
+ async function getDefaultCliPath(targetOs = operatingSystemName) {
217
+ if (!isOperatingSystemSupported(targetOs)) return;
218
+ const resolver = cliPathResolvers[targetOs];
219
+ return await resolver();
220
+ }
221
+ //#endregion
168
222
  //#region src/config/resolver.ts
169
223
  function isCustomConfigJson(value) {
170
224
  return typeof value === "object" && value !== null;
171
225
  }
172
226
  /**
227
+ * @description 解析开发者工具自动预热相关配置的最终生效值。
228
+ */
229
+ function resolveDevtoolsAutomationDefaults(config) {
230
+ return {
231
+ autoBootstrapDevtools: config.autoBootstrapDevtools ?? true,
232
+ autoTrustProject: config.autoTrustProject ?? false
233
+ };
234
+ }
235
+ /**
173
236
  * @description 读取并解析 CLI 配置(自定义优先)
174
237
  */
175
238
  async function getConfig() {
@@ -178,12 +241,16 @@ async function getConfig() {
178
241
  const config = isCustomConfigJson(rawConfig) ? rawConfig : {};
179
242
  const cliPath = typeof config.cliPath === "string" ? config.cliPath.trim() : "";
180
243
  const locale = config.locale === "zh" || config.locale === "en" ? config.locale : void 0;
244
+ const autoBootstrapDevtools = typeof config.autoBootstrapDevtools === "boolean" ? config.autoBootstrapDevtools : void 0;
245
+ const autoTrustProject = typeof config.autoTrustProject === "boolean" ? config.autoTrustProject : void 0;
181
246
  if (cliPath) {
182
247
  logger_default.info(`全局配置文件路径:${colors.green(defaultCustomConfigFilePath)}`);
183
248
  logger_default.info(`自定义 CLI 路径:${colors.green(cliPath)}`);
184
249
  return {
185
250
  cliPath,
186
251
  locale,
252
+ autoBootstrapDevtools,
253
+ autoTrustProject,
187
254
  source: "custom"
188
255
  };
189
256
  }
@@ -196,11 +263,15 @@ async function getConfig() {
196
263
  if (fallbackPath) return {
197
264
  cliPath: fallbackPath,
198
265
  locale: void 0,
266
+ autoBootstrapDevtools: void 0,
267
+ autoTrustProject: void 0,
199
268
  source: "default"
200
269
  };
201
270
  return {
202
271
  cliPath: "",
203
272
  locale: void 0,
273
+ autoBootstrapDevtools: void 0,
274
+ autoTrustProject: void 0,
204
275
  source: "missing"
205
276
  };
206
277
  }
@@ -227,6 +298,199 @@ async function resolveCliPath() {
227
298
  };
228
299
  }
229
300
  //#endregion
301
+ //#region src/cli/wechatDevtoolsSettings.ts
302
+ function createStorageHash(key) {
303
+ return createHash("md5").update(key).digest("hex");
304
+ }
305
+ const SETTINGS_STORAGE_HASH = createStorageHash("reduxPersist:settings");
306
+ const SETTINGS_STORAGE_FILE_NAMES = [`localstorage_${SETTINGS_STORAGE_HASH}.json`, `ls_${SETTINGS_STORAGE_HASH}.json`];
307
+ function resolveWechatDevtoolsBaseDir(homeDir, platform, localAppDataDir) {
308
+ if (platform === "darwin") return path.join(homeDir, "Library", "Application Support", "微信开发者工具");
309
+ if (platform === "win32") return path.join(localAppDataDir, "微信开发者工具", "User Data");
310
+ }
311
+ function isRecord(value) {
312
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
313
+ }
314
+ function normalizePort(value) {
315
+ if (typeof value !== "number" || !Number.isInteger(value)) return;
316
+ if (value <= 0 || value > 65535) return;
317
+ return value;
318
+ }
319
+ function normalizeWechatDevtoolsSecuritySettings(value) {
320
+ if (!isRecord(value)) return;
321
+ const normalized = {};
322
+ if (typeof value.enableServicePort === "boolean") normalized.enableServicePort = value.enableServicePort;
323
+ const port = normalizePort(value.port);
324
+ if (port !== void 0) normalized.port = port;
325
+ if (typeof value.allowGetTicket === "boolean") normalized.allowGetTicket = value.allowGetTicket;
326
+ if (typeof value.trustWhenAuto === "boolean") normalized.trustWhenAuto = value.trustWhenAuto;
327
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
328
+ }
329
+ function shouldPreferServicePortCandidate(current, next) {
330
+ if (current.enabled === void 0 && current.port === void 0) return true;
331
+ if (next.enabled === true && current.enabled !== true) return true;
332
+ if (next.enabled === current.enabled && next.port !== void 0 && current.port === void 0) return true;
333
+ return false;
334
+ }
335
+ function createResolvedWechatDevtoolsContext(options = {}) {
336
+ const platform = options.platform ?? process.platform;
337
+ const homeDir = options.homeDir ?? process.env.USERPROFILE ?? process.env.HOME ?? os.homedir();
338
+ if (!homeDir) return;
339
+ const localAppDataDir = options.localAppDataDir ?? process.env.LOCALAPPDATA ?? path.join(homeDir, "AppData", "Local");
340
+ const baseDir = resolveWechatDevtoolsBaseDir(homeDir, platform, localAppDataDir);
341
+ if (!baseDir) return;
342
+ return {
343
+ baseDir,
344
+ homeDir,
345
+ localAppDataDir,
346
+ platform
347
+ };
348
+ }
349
+ async function readJsonObject(filePath) {
350
+ try {
351
+ const raw = await fs.readFile(filePath, "utf8");
352
+ const parsed = JSON.parse(raw);
353
+ if (!isRecord(parsed)) return {};
354
+ return parsed;
355
+ } catch (error) {
356
+ if (error.code === "ENOENT") return {};
357
+ if (error instanceof SyntaxError) return {};
358
+ throw error;
359
+ }
360
+ }
361
+ async function writeJsonObject(filePath, value) {
362
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
363
+ await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
364
+ }
365
+ async function resolveWechatDevtoolsInstanceDirs(baseDir) {
366
+ try {
367
+ const entries = await fs.readdir(baseDir, { withFileTypes: true });
368
+ const instanceDirs = [];
369
+ const seenDirs = /* @__PURE__ */ new Set();
370
+ const appendInstanceDir = async (instanceDir) => {
371
+ if (seenDirs.has(instanceDir)) return;
372
+ try {
373
+ if ((await fs.stat(path.join(instanceDir, "WeappLocalData"))).isDirectory()) {
374
+ instanceDirs.push(instanceDir);
375
+ seenDirs.add(instanceDir);
376
+ }
377
+ } catch {}
378
+ };
379
+ await appendInstanceDir(baseDir);
380
+ for (const entry of entries) {
381
+ if (!entry.isDirectory()) continue;
382
+ await appendInstanceDir(path.join(baseDir, entry.name));
383
+ }
384
+ return instanceDirs;
385
+ } catch (error) {
386
+ if (error.code === "ENOENT") return [];
387
+ throw error;
388
+ }
389
+ }
390
+ async function syncHashKeyMap(localDataDir, key) {
391
+ const hash = createStorageHash(key);
392
+ const hashKeyMapPath = path.join(localDataDir, "hash_key_map_2.json");
393
+ const current = await readJsonObject(hashKeyMapPath);
394
+ if (current[hash] !== key) {
395
+ current[hash] = key;
396
+ await writeJsonObject(hashKeyMapPath, current);
397
+ }
398
+ return hash;
399
+ }
400
+ async function detectWechatDevtoolsSecuritySettings(localDataDir) {
401
+ for (const fileName of SETTINGS_STORAGE_FILE_NAMES) {
402
+ const security = normalizeWechatDevtoolsSecuritySettings((await readJsonObject(path.join(localDataDir, fileName))).security);
403
+ if (security) return security;
404
+ }
405
+ }
406
+ async function trustWechatDevtoolsProject(localDataDir, projectPath) {
407
+ const normalizedProjectPath = path.resolve(projectPath);
408
+ const projectHash = await syncHashKeyMap(localDataDir, `project2_${normalizedProjectPath}`);
409
+ const fileNames = [`localstorage_${projectHash}.json`, `ls_${projectHash}.json`];
410
+ for (const fileName of fileNames) {
411
+ const projectFilePath = path.join(localDataDir, fileName);
412
+ const current = await readJsonObject(projectFilePath);
413
+ await writeJsonObject(projectFilePath, {
414
+ ...current,
415
+ projectid: typeof current.projectid === "string" && current.projectid.length > 0 ? current.projectid : normalizedProjectPath,
416
+ projectpath: typeof current.projectpath === "string" && current.projectpath.length > 0 ? current.projectpath : normalizedProjectPath,
417
+ isTrusted: true
418
+ });
419
+ }
420
+ }
421
+ async function scanWechatDevtoolsServicePort(context) {
422
+ const instanceDirs = await resolveWechatDevtoolsInstanceDirs(context.baseDir);
423
+ let detectedSecurityCount = 0;
424
+ let detectedServicePort = {};
425
+ for (const instanceDir of instanceDirs) {
426
+ const security = await detectWechatDevtoolsSecuritySettings(path.join(instanceDir, "WeappLocalData"));
427
+ if (!security) continue;
428
+ detectedSecurityCount += 1;
429
+ const candidate = {
430
+ enabled: security.enableServicePort,
431
+ port: security.port
432
+ };
433
+ if (shouldPreferServicePortCandidate(detectedServicePort, candidate)) detectedServicePort = candidate;
434
+ }
435
+ return {
436
+ instanceDirs,
437
+ touchedInstanceCount: instanceDirs.length,
438
+ detectedSecurityCount,
439
+ servicePort: detectedServicePort.port,
440
+ servicePortEnabled: detectedServicePort.enabled
441
+ };
442
+ }
443
+ /**
444
+ * @description 检测微信开发者工具当前服务端口配置,严格沿用用户已有设置。
445
+ */
446
+ async function detectWechatDevtoolsServicePort(options = {}) {
447
+ const context = createResolvedWechatDevtoolsContext(options);
448
+ if (!context) return {
449
+ touchedInstanceCount: 0,
450
+ detectedSecurityCount: 0,
451
+ servicePort: void 0,
452
+ servicePortEnabled: void 0
453
+ };
454
+ const result = await scanWechatDevtoolsServicePort(context);
455
+ return {
456
+ touchedInstanceCount: result.touchedInstanceCount,
457
+ detectedSecurityCount: result.detectedSecurityCount,
458
+ servicePort: result.servicePort,
459
+ servicePortEnabled: result.servicePortEnabled
460
+ };
461
+ }
462
+ /**
463
+ * @description 在启动微信开发者工具前,检测服务端口配置,并按需写入项目信任信息。
464
+ */
465
+ async function bootstrapWechatDevtoolsSettings(options = {}) {
466
+ const context = createResolvedWechatDevtoolsContext(options);
467
+ if (!context) return {
468
+ touchedInstanceCount: 0,
469
+ detectedSecurityCount: 0,
470
+ updatedSecurityCount: 0,
471
+ trustedProjectCount: 0,
472
+ servicePort: void 0,
473
+ servicePortEnabled: void 0
474
+ };
475
+ const scanResult = await scanWechatDevtoolsServicePort(context);
476
+ let trustedProjectCount = 0;
477
+ for (const instanceDir of scanResult.instanceDirs) {
478
+ const localDataDir = path.join(instanceDir, "WeappLocalData");
479
+ if (options.projectPath && options.trustProject !== false) {
480
+ await trustWechatDevtoolsProject(localDataDir, options.projectPath);
481
+ trustedProjectCount += 1;
482
+ }
483
+ }
484
+ return {
485
+ touchedInstanceCount: scanResult.touchedInstanceCount,
486
+ detectedSecurityCount: scanResult.detectedSecurityCount,
487
+ updatedSecurityCount: 0,
488
+ trustedProjectCount,
489
+ servicePort: scanResult.servicePort,
490
+ servicePortEnabled: scanResult.servicePortEnabled
491
+ };
492
+ }
493
+ //#endregion
230
494
  //#region src/cli/automator.ts
231
495
  const ERROR_STACK_PREFIX_RE = /^at /;
232
496
  const ERROR_PREFIX_RE = /^\[error\]\s*/i;
@@ -378,16 +642,24 @@ function formatAutomatorLoginError(error) {
378
642
  * @description 基于当前配置解析 CLI 路径,并通过现代化 automator 入口启动会话。
379
643
  */
380
644
  async function launchAutomator(options) {
381
- const { cliPath, projectPath, timeout = 3e4, trustProject = false } = options;
645
+ const { cliPath, projectPath, timeout = 3e4 } = options;
382
646
  const resolvedCliPath = cliPath ?? (await resolveCliPath()).cliPath ?? void 0;
647
+ const config = await readCustomConfig();
648
+ const resolvedTrustProject = options.trustProject ?? config.autoTrustProject ?? false;
383
649
  const launcher = new Launcher();
384
650
  let lastError = null;
651
+ let bootstrapResult;
652
+ if (config.autoBootstrapDevtools !== false) bootstrapResult = await bootstrapWechatDevtoolsSettings({
653
+ projectPath,
654
+ trustProject: resolvedTrustProject
655
+ });
656
+ if (bootstrapResult?.servicePortEnabled === false) throw new Error("Detected WeChat DevTools service port is disabled in current settings. Please enable it manually; existing user settings were not modified.");
385
657
  for (let attempt = 0; attempt < 2; attempt += 1) try {
386
658
  const miniProgram = await launcher.launch({
387
659
  cliPath: resolvedCliPath,
388
660
  projectPath,
389
661
  timeout,
390
- trustProject
662
+ trustProject: resolvedTrustProject
391
663
  });
392
664
  const sessionMetadata = Reflect.get(miniProgram, "__WEAPP_VITE_SESSION_METADATA");
393
665
  if (typeof sessionMetadata?.wsEndpoint === "string" && sessionMetadata.wsEndpoint) await persistAutomatorSession(projectPath, sessionMetadata.wsEndpoint);
@@ -931,4 +1203,4 @@ async function remote(options) {
931
1203
  });
932
1204
  }
933
1205
  //#endregion
934
- export { isAutomatorProtocolTimeoutError as A, createLocaleConfig as B, configureLocaleFromArgv as C, formatAutomatorLoginError as D, connectOpenedAutomator as E, launchAutomator as F, defaultCustomConfigFilePath as G, readCustomConfig as H, resolveCliPath as I, getDefaultCliPath as J, resolvePath as K, getConfig as L, isDevtoolsExtensionContextInvalidatedError as M, isDevtoolsHttpPortError as N, getAutomatorProtocolTimeoutMethod as O, isRetryableAutomatorLaunchError as P, logger_default as Q, getConfiguredLocale as R, withMiniProgram as S, validateLocaleOption as T, removeCustomConfigKey as U, overwriteCustomConfig as V, defaultCustomConfigDirPath as W, operatingSystemName as X, isOperatingSystemSupported as Y, colors as Z, acquireSharedMiniProgram as _, navigateBack as a, getSharedMiniProgramSessionCount as b, pageStack as c, remote as d, scrollTo as f, tap as g, takeScreenshot as h, input as i, isAutomatorWsConnectError as j, isAutomatorLoginError as k, reLaunch as l, systemInfo as m, captureScreenshotBuffer as n, navigateTo as o, switchTab as p, SupportedPlatformsMap as q, currentPage as r, pageData as s, audit as t, redirectTo as u, closeSharedMiniProgram as v, i18nText as w, releaseSharedMiniProgram as x, connectMiniProgram as y, createCustomConfig as z };
1206
+ export { readCustomConfig as $, isAutomatorProtocolTimeoutError as A, getConfiguredLocale as B, configureLocaleFromArgv as C, formatAutomatorLoginError as D, connectOpenedAutomator as E, launchAutomator as F, operatingSystemName as G, SupportedPlatformsMap as H, bootstrapWechatDevtoolsSettings as I, createAutoBootstrapDevtoolsConfig as J, colors as K, detectWechatDevtoolsServicePort as L, isDevtoolsExtensionContextInvalidatedError as M, isDevtoolsHttpPortError as N, getAutomatorProtocolTimeoutMethod as O, isRetryableAutomatorLaunchError as P, overwriteCustomConfig as Q, resolveCliPath as R, withMiniProgram as S, validateLocaleOption as T, getDefaultCliPath as U, resolveDevtoolsAutomationDefaults as V, isOperatingSystemSupported as W, createCustomConfig as X, createAutoTrustProjectConfig as Y, createLocaleConfig as Z, acquireSharedMiniProgram as _, navigateBack as a, getSharedMiniProgramSessionCount as b, pageStack as c, remote as d, removeCustomConfigKey as et, scrollTo as f, tap as g, takeScreenshot as h, input as i, isAutomatorWsConnectError as j, isAutomatorLoginError as k, reLaunch as l, systemInfo as m, captureScreenshotBuffer as n, defaultCustomConfigFilePath as nt, navigateTo as o, switchTab as p, logger_default as q, currentPage as r, resolvePath as rt, pageData as s, audit as t, defaultCustomConfigDirPath as tt, redirectTo as u, closeSharedMiniProgram as v, i18nText as w, releaseSharedMiniProgram as x, connectMiniProgram as y, getConfig as z };
package/dist/index.d.ts CHANGED
@@ -377,6 +377,45 @@ declare function parseScreenshotArgs(argv: string[]): ScreenshotOptions;
377
377
  */
378
378
  declare function validateWechatCliCommandArgs(argv: readonly string[]): void;
379
379
  //#endregion
380
+ //#region src/cli/wechatDevtoolsSettings.d.ts
381
+ interface WechatDevtoolsSecuritySettings {
382
+ enableServicePort: boolean;
383
+ port: number;
384
+ allowGetTicket: boolean;
385
+ trustWhenAuto: boolean;
386
+ }
387
+ interface DetectedWechatDevtoolsServicePortSettings {
388
+ enabled?: boolean;
389
+ port?: number;
390
+ }
391
+ interface DetectWechatDevtoolsServicePortOptions {
392
+ homeDir?: string;
393
+ localAppDataDir?: string;
394
+ platform?: NodeJS.Platform;
395
+ }
396
+ interface DetectWechatDevtoolsServicePortResult {
397
+ touchedInstanceCount: number;
398
+ detectedSecurityCount: number;
399
+ servicePort?: number;
400
+ servicePortEnabled?: boolean;
401
+ }
402
+ interface BootstrapWechatDevtoolsSettingsOptions extends DetectWechatDevtoolsServicePortOptions {
403
+ projectPath?: string;
404
+ trustProject?: boolean;
405
+ }
406
+ interface BootstrapWechatDevtoolsSettingsResult extends DetectWechatDevtoolsServicePortResult {
407
+ updatedSecurityCount: number;
408
+ trustedProjectCount: number;
409
+ }
410
+ /**
411
+ * @description 检测微信开发者工具当前服务端口配置,严格沿用用户已有设置。
412
+ */
413
+ declare function detectWechatDevtoolsServicePort(options?: DetectWechatDevtoolsServicePortOptions): Promise<DetectWechatDevtoolsServicePortResult>;
414
+ /**
415
+ * @description 在启动微信开发者工具前,检测服务端口配置,并按需写入项目信任信息。
416
+ */
417
+ declare function bootstrapWechatDevtoolsSettings(options?: BootstrapWechatDevtoolsSettingsOptions): Promise<BootstrapWechatDevtoolsSettingsResult>;
418
+ //#endregion
380
419
  //#region src/types.d.ts
381
420
  /**
382
421
  * @description 基础配置
@@ -384,6 +423,8 @@ declare function validateWechatCliCommandArgs(argv: readonly string[]): void;
384
423
  interface BaseConfig {
385
424
  cliPath: string;
386
425
  locale?: 'zh' | 'en';
426
+ autoBootstrapDevtools?: boolean;
427
+ autoTrustProject?: boolean;
387
428
  }
388
429
  /**
389
430
  * @description 配置来源
@@ -407,6 +448,8 @@ interface AliasEntry {
407
448
  interface CustomConfigFile {
408
449
  cliPath?: string;
409
450
  locale?: 'zh' | 'en';
451
+ autoBootstrapDevtools?: boolean;
452
+ autoTrustProject?: boolean;
410
453
  }
411
454
  declare function readCustomConfig(): Promise<CustomConfigFile>;
412
455
  /**
@@ -417,6 +460,14 @@ declare function createCustomConfig(params: BaseConfig): Promise<string>;
417
460
  * @description 写入语言配置(zh / en)。
418
461
  */
419
462
  declare function createLocaleConfig(locale: 'zh' | 'en'): Promise<"zh" | "en">;
463
+ /**
464
+ * @description 写入开发者工具自动预热配置。
465
+ */
466
+ declare function createAutoBootstrapDevtoolsConfig(value: boolean): Promise<boolean>;
467
+ /**
468
+ * @description 写入项目自动信任配置。
469
+ */
470
+ declare function createAutoTrustProjectConfig(value: boolean): Promise<boolean>;
420
471
  /**
421
472
  * @description 删除指定配置项。
422
473
  */
@@ -437,6 +488,16 @@ declare const defaultCustomConfigDirPath: string;
437
488
  declare const defaultCustomConfigFilePath: string;
438
489
  //#endregion
439
490
  //#region src/config/resolver.d.ts
491
+ /**
492
+ * @description 解析开发者工具自动预热相关配置的最终生效值。
493
+ */
494
+ declare function resolveDevtoolsAutomationDefaults(config: {
495
+ autoBootstrapDevtools?: boolean;
496
+ autoTrustProject?: boolean;
497
+ }): {
498
+ autoBootstrapDevtools: boolean;
499
+ autoTrustProject: boolean;
500
+ };
440
501
  /**
441
502
  * @description 读取并解析 CLI 配置(自定义优先)
442
503
  */
@@ -448,7 +509,7 @@ declare function getConfiguredLocale(): Promise<"zh" | "en" | undefined>;
448
509
  //#endregion
449
510
  //#region src/runtime/platform.d.ts
450
511
  /**
451
- * @description 官方微信开发者工具只支持 Windows、macOS,Linux 只有社区版
512
+ * @description 官方微信开发者工具只支持 Windows、macOS,Linux 只有社区版。
452
513
  * https://github.com/msojocs/wechat-web-devtools-linux
453
514
  */
454
515
  declare const SupportedPlatformsMap: {
@@ -457,19 +518,19 @@ declare const SupportedPlatformsMap: {
457
518
  readonly Linux: "Linux";
458
519
  };
459
520
  /**
460
- * @description 支持的系统类型
521
+ * @description 支持的系统类型。
461
522
  */
462
523
  type SupportedPlatform = (typeof SupportedPlatformsMap)[keyof typeof SupportedPlatformsMap];
463
524
  /**
464
- * @description 判断当前系统是否支持微信开发者工具
525
+ * @description 判断当前系统是否支持微信开发者工具。
465
526
  */
466
527
  declare function isOperatingSystemSupported(osName?: string): osName is SupportedPlatform;
467
528
  /**
468
- * @description 当前系统名称
529
+ * @description 当前系统名称。
469
530
  */
470
531
  declare const operatingSystemName: string;
471
532
  /**
472
- * @description 获取默认 CLI 路径(按系统)
533
+ * @description 获取默认 CLI 路径(按系统)。
473
534
  */
474
535
  declare function getDefaultCliPath(targetOs?: string): Promise<string | undefined>;
475
536
  //#endregion
@@ -507,4 +568,4 @@ declare function execute(cliPath: string, argv: string[], options?: ExecuteOptio
507
568
  */
508
569
  declare function resolvePath(filePath: string): string;
509
570
  //#endregion
510
- export { AUTOMATOR_COMMAND_NAMES, ArgvTransform, AuditOptions, AutomatorCommandOptions, AutomatorOptions, AutomatorSessionOptions, type BaseConfig, CONFIG_COMMAND_NAME, type ConfigSource, ForwardConsoleEvent, ForwardConsoleLogLevel, ForwardConsoleOptions, ForwardConsoleSession, InputOptions, LoginRetryMode, MINIDEV_NAMESPACE_COMMAND_NAMES, MiniProgramElement, MiniProgramEventMap, MiniProgramLike, MiniProgramPage, NavigateOptions, PageDataOptions, PageInfoOptions, ParsedAutomatorArgs, RemoteOptions, type ResolvedConfig, RetryKeypressOptions, RetryPromptResult, type ScreenshotOptions, type ScreenshotResult, ScrollOptions, SelectorOptions, SupportedPlatform, SupportedPlatformsMap, TapOptions, WEAPP_IDE_TOP_LEVEL_COMMAND_NAMES, WECHAT_CLI_COMMAND_NAMES, acquireSharedMiniProgram, audit, captureScreenshotBuffer, closeSharedMiniProgram, connectMiniProgram, connectOpenedAutomator, createAlias, createCli, createCustomConfig, createLocaleConfig, createPathCompat, createWechatIdeLoginRequiredExitError, currentPage, defaultCustomConfigDirPath, defaultCustomConfigFilePath, execute, extractExecutionErrorText, formatAutomatorLoginError, formatRetryHotkeyPrompt, formatWechatIdeLoginRequiredError, getAutomatorCommandHelp, getAutomatorProtocolTimeoutMethod, getConfig, getConfiguredLocale, getDefaultCliPath, getSharedMiniProgramSessionCount, handleConfigCommand, input, isAutomatorCommand, isAutomatorLoginError, isAutomatorProtocolTimeoutError, isAutomatorWsConnectError, isDevtoolsExtensionContextInvalidatedError, isDevtoolsHttpPortError, isOperatingSystemSupported, isRetryableAutomatorLaunchError, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, launchAutomator, navigateBack, navigateTo, operatingSystemName, overwriteCustomConfig, pageData, pageStack, parse, parseAutomatorArgs, parseCompareArgs, parseScreenshotArgs, printCompareHelp, printScreenshotHelp, promptForCliPath, reLaunch, readCustomConfig, readOptionValue, redirectTo, releaseSharedMiniProgram, remote, removeCustomConfigKey, removeOption, resolveCliPath, resolvePath, runAutomatorCommand, runMinidev, runWechatCliWithRetry, scrollTo, startForwardConsole, switchTab, systemInfo, takeScreenshot, tap, transformArgv, validateWechatCliCommandArgs, waitForRetryKeypress, withMiniProgram };
571
+ export { AUTOMATOR_COMMAND_NAMES, ArgvTransform, AuditOptions, AutomatorCommandOptions, AutomatorOptions, AutomatorSessionOptions, type BaseConfig, BootstrapWechatDevtoolsSettingsOptions, BootstrapWechatDevtoolsSettingsResult, CONFIG_COMMAND_NAME, type ConfigSource, DetectWechatDevtoolsServicePortOptions, DetectWechatDevtoolsServicePortResult, DetectedWechatDevtoolsServicePortSettings, ForwardConsoleEvent, ForwardConsoleLogLevel, ForwardConsoleOptions, ForwardConsoleSession, InputOptions, LoginRetryMode, MINIDEV_NAMESPACE_COMMAND_NAMES, MiniProgramElement, MiniProgramEventMap, MiniProgramLike, MiniProgramPage, NavigateOptions, PageDataOptions, PageInfoOptions, ParsedAutomatorArgs, RemoteOptions, type ResolvedConfig, RetryKeypressOptions, RetryPromptResult, type ScreenshotOptions, type ScreenshotResult, ScrollOptions, SelectorOptions, SupportedPlatform, SupportedPlatformsMap, TapOptions, WEAPP_IDE_TOP_LEVEL_COMMAND_NAMES, WECHAT_CLI_COMMAND_NAMES, WechatDevtoolsSecuritySettings, acquireSharedMiniProgram, audit, bootstrapWechatDevtoolsSettings, captureScreenshotBuffer, closeSharedMiniProgram, connectMiniProgram, connectOpenedAutomator, createAlias, createAutoBootstrapDevtoolsConfig, createAutoTrustProjectConfig, createCli, createCustomConfig, createLocaleConfig, createPathCompat, createWechatIdeLoginRequiredExitError, currentPage, defaultCustomConfigDirPath, defaultCustomConfigFilePath, detectWechatDevtoolsServicePort, execute, extractExecutionErrorText, formatAutomatorLoginError, formatRetryHotkeyPrompt, formatWechatIdeLoginRequiredError, getAutomatorCommandHelp, getAutomatorProtocolTimeoutMethod, getConfig, getConfiguredLocale, getDefaultCliPath, getSharedMiniProgramSessionCount, handleConfigCommand, input, isAutomatorCommand, isAutomatorLoginError, isAutomatorProtocolTimeoutError, isAutomatorWsConnectError, isDevtoolsExtensionContextInvalidatedError, isDevtoolsHttpPortError, isOperatingSystemSupported, isRetryableAutomatorLaunchError, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, launchAutomator, navigateBack, navigateTo, operatingSystemName, overwriteCustomConfig, pageData, pageStack, parse, parseAutomatorArgs, parseCompareArgs, parseScreenshotArgs, printCompareHelp, printScreenshotHelp, promptForCliPath, reLaunch, readCustomConfig, readOptionValue, redirectTo, releaseSharedMiniProgram, remote, removeCustomConfigKey, removeOption, resolveCliPath, resolveDevtoolsAutomationDefaults, resolvePath, runAutomatorCommand, runMinidev, runWechatCliWithRetry, scrollTo, startForwardConsole, switchTab, systemInfo, takeScreenshot, tap, transformArgv, validateWechatCliCommandArgs, waitForRetryKeypress, withMiniProgram };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { A as isAutomatorProtocolTimeoutError, B as createLocaleConfig, D as formatAutomatorLoginError, E as connectOpenedAutomator, F as launchAutomator, G as defaultCustomConfigFilePath, H as readCustomConfig, I as resolveCliPath, J as getDefaultCliPath, K as resolvePath, L as getConfig, M as isDevtoolsExtensionContextInvalidatedError, N as isDevtoolsHttpPortError, O as getAutomatorProtocolTimeoutMethod, P as isRetryableAutomatorLaunchError, R as getConfiguredLocale, S as withMiniProgram, U as removeCustomConfigKey, V as overwriteCustomConfig, W as defaultCustomConfigDirPath, X as operatingSystemName, Y as isOperatingSystemSupported, _ as acquireSharedMiniProgram, a as navigateBack, b as getSharedMiniProgramSessionCount, c as pageStack, d as remote, f as scrollTo, g as tap, h as takeScreenshot, i as input, j as isAutomatorWsConnectError, k as isAutomatorLoginError, l as reLaunch, m as systemInfo, n as captureScreenshotBuffer, o as navigateTo, p as switchTab, q as SupportedPlatformsMap, r as currentPage, s as pageData, t as audit, u as redirectTo, v as closeSharedMiniProgram, x as releaseSharedMiniProgram, y as connectMiniProgram, z as createCustomConfig } from "./commands-38LzU5ML.js";
2
- import { A as parseCompareArgs, C as isWeappIdeTopLevelCommand, D as runAutomatorCommand, E as isAutomatorCommand, M as parseAutomatorArgs, N as readOptionValue, O as parseScreenshotArgs, P as removeOption, S as WECHAT_CLI_COMMAND_NAMES, T as getAutomatorCommandHelp, _ as handleConfigCommand, a as createWechatIdeLoginRequiredExitError, b as MINIDEV_NAMESPACE_COMMAND_NAMES, c as formatWechatIdeLoginRequiredError, d as runMinidev, f as execute, g as startForwardConsole, h as transformArgv, i as runWechatCliWithRetry, j as printCompareHelp, k as printScreenshotHelp, l as isWechatIdeLoginRequiredError, m as createPathCompat, n as parse, o as extractExecutionErrorText, p as createAlias, r as validateWechatCliCommandArgs, s as formatRetryHotkeyPrompt, t as createCli, u as waitForRetryKeypress, v as promptForCliPath, w as AUTOMATOR_COMMAND_NAMES, x as WEAPP_IDE_TOP_LEVEL_COMMAND_NAMES, y as CONFIG_COMMAND_NAME } from "./cli-1zieDX-6.js";
3
- export { AUTOMATOR_COMMAND_NAMES, CONFIG_COMMAND_NAME, MINIDEV_NAMESPACE_COMMAND_NAMES, SupportedPlatformsMap, WEAPP_IDE_TOP_LEVEL_COMMAND_NAMES, WECHAT_CLI_COMMAND_NAMES, acquireSharedMiniProgram, audit, captureScreenshotBuffer, closeSharedMiniProgram, connectMiniProgram, connectOpenedAutomator, createAlias, createCli, createCustomConfig, createLocaleConfig, createPathCompat, createWechatIdeLoginRequiredExitError, currentPage, defaultCustomConfigDirPath, defaultCustomConfigFilePath, execute, extractExecutionErrorText, formatAutomatorLoginError, formatRetryHotkeyPrompt, formatWechatIdeLoginRequiredError, getAutomatorCommandHelp, getAutomatorProtocolTimeoutMethod, getConfig, getConfiguredLocale, getDefaultCliPath, getSharedMiniProgramSessionCount, handleConfigCommand, input, isAutomatorCommand, isAutomatorLoginError, isAutomatorProtocolTimeoutError, isAutomatorWsConnectError, isDevtoolsExtensionContextInvalidatedError, isDevtoolsHttpPortError, isOperatingSystemSupported, isRetryableAutomatorLaunchError, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, launchAutomator, navigateBack, navigateTo, operatingSystemName, overwriteCustomConfig, pageData, pageStack, parse, parseAutomatorArgs, parseCompareArgs, parseScreenshotArgs, printCompareHelp, printScreenshotHelp, promptForCliPath, reLaunch, readCustomConfig, readOptionValue, redirectTo, releaseSharedMiniProgram, remote, removeCustomConfigKey, removeOption, resolveCliPath, resolvePath, runAutomatorCommand, runMinidev, runWechatCliWithRetry, scrollTo, startForwardConsole, switchTab, systemInfo, takeScreenshot, tap, transformArgv, validateWechatCliCommandArgs, waitForRetryKeypress, withMiniProgram };
1
+ import { $ as readCustomConfig, A as isAutomatorProtocolTimeoutError, B as getConfiguredLocale, D as formatAutomatorLoginError, E as connectOpenedAutomator, F as launchAutomator, G as operatingSystemName, H as SupportedPlatformsMap, I as bootstrapWechatDevtoolsSettings, J as createAutoBootstrapDevtoolsConfig, L as detectWechatDevtoolsServicePort, M as isDevtoolsExtensionContextInvalidatedError, N as isDevtoolsHttpPortError, O as getAutomatorProtocolTimeoutMethod, P as isRetryableAutomatorLaunchError, Q as overwriteCustomConfig, R as resolveCliPath, S as withMiniProgram, U as getDefaultCliPath, V as resolveDevtoolsAutomationDefaults, W as isOperatingSystemSupported, X as createCustomConfig, Y as createAutoTrustProjectConfig, Z as createLocaleConfig, _ as acquireSharedMiniProgram, a as navigateBack, b as getSharedMiniProgramSessionCount, c as pageStack, d as remote, et as removeCustomConfigKey, f as scrollTo, g as tap, h as takeScreenshot, i as input, j as isAutomatorWsConnectError, k as isAutomatorLoginError, l as reLaunch, m as systemInfo, n as captureScreenshotBuffer, nt as defaultCustomConfigFilePath, o as navigateTo, p as switchTab, r as currentPage, rt as resolvePath, s as pageData, t as audit, tt as defaultCustomConfigDirPath, u as redirectTo, v as closeSharedMiniProgram, x as releaseSharedMiniProgram, y as connectMiniProgram, z as getConfig } from "./commands-XD_wemcg.js";
2
+ import { A as parseCompareArgs, C as isWeappIdeTopLevelCommand, D as runAutomatorCommand, E as isAutomatorCommand, M as parseAutomatorArgs, N as readOptionValue, O as parseScreenshotArgs, P as removeOption, S as WECHAT_CLI_COMMAND_NAMES, T as getAutomatorCommandHelp, _ as handleConfigCommand, a as createWechatIdeLoginRequiredExitError, b as MINIDEV_NAMESPACE_COMMAND_NAMES, c as formatWechatIdeLoginRequiredError, d as runMinidev, f as execute, g as startForwardConsole, h as transformArgv, i as runWechatCliWithRetry, j as printCompareHelp, k as printScreenshotHelp, l as isWechatIdeLoginRequiredError, m as createPathCompat, n as parse, o as extractExecutionErrorText, p as createAlias, r as validateWechatCliCommandArgs, s as formatRetryHotkeyPrompt, t as createCli, u as waitForRetryKeypress, v as promptForCliPath, w as AUTOMATOR_COMMAND_NAMES, x as WEAPP_IDE_TOP_LEVEL_COMMAND_NAMES, y as CONFIG_COMMAND_NAME } from "./cli-CfovXw-V.js";
3
+ export { AUTOMATOR_COMMAND_NAMES, CONFIG_COMMAND_NAME, MINIDEV_NAMESPACE_COMMAND_NAMES, SupportedPlatformsMap, WEAPP_IDE_TOP_LEVEL_COMMAND_NAMES, WECHAT_CLI_COMMAND_NAMES, acquireSharedMiniProgram, audit, bootstrapWechatDevtoolsSettings, captureScreenshotBuffer, closeSharedMiniProgram, connectMiniProgram, connectOpenedAutomator, createAlias, createAutoBootstrapDevtoolsConfig, createAutoTrustProjectConfig, createCli, createCustomConfig, createLocaleConfig, createPathCompat, createWechatIdeLoginRequiredExitError, currentPage, defaultCustomConfigDirPath, defaultCustomConfigFilePath, detectWechatDevtoolsServicePort, execute, extractExecutionErrorText, formatAutomatorLoginError, formatRetryHotkeyPrompt, formatWechatIdeLoginRequiredError, getAutomatorCommandHelp, getAutomatorProtocolTimeoutMethod, getConfig, getConfiguredLocale, getDefaultCliPath, getSharedMiniProgramSessionCount, handleConfigCommand, input, isAutomatorCommand, isAutomatorLoginError, isAutomatorProtocolTimeoutError, isAutomatorWsConnectError, isDevtoolsExtensionContextInvalidatedError, isDevtoolsHttpPortError, isOperatingSystemSupported, isRetryableAutomatorLaunchError, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, launchAutomator, navigateBack, navigateTo, operatingSystemName, overwriteCustomConfig, pageData, pageStack, parse, parseAutomatorArgs, parseCompareArgs, parseScreenshotArgs, printCompareHelp, printScreenshotHelp, promptForCliPath, reLaunch, readCustomConfig, readOptionValue, redirectTo, releaseSharedMiniProgram, remote, removeCustomConfigKey, removeOption, resolveCliPath, resolveDevtoolsAutomationDefaults, resolvePath, runAutomatorCommand, runMinidev, runWechatCliWithRetry, scrollTo, startForwardConsole, switchTab, systemInfo, takeScreenshot, tap, transformArgv, validateWechatCliCommandArgs, waitForRetryKeypress, withMiniProgram };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "weapp-ide-cli",
3
3
  "type": "module",
4
- "version": "5.2.2",
4
+ "version": "5.2.4",
5
5
  "description": "让微信开发者工具,用起来更加方便!",
6
6
  "author": "ice breaker <1324318532@qq.com>",
7
7
  "license": "MIT",
@@ -68,8 +68,8 @@
68
68
  "pixelmatch": "^7.1.0",
69
69
  "pngjs": "^7.0.0",
70
70
  "@weapp-core/logger": "^3.1.1",
71
- "@weapp-core/shared": "^3.0.3",
72
- "@weapp-vite/miniprogram-automator": "1.0.2"
71
+ "@weapp-core/shared": "^3.0.4",
72
+ "@weapp-vite/miniprogram-automator": "1.0.3"
73
73
  },
74
74
  "scripts": {
75
75
  "dev": "tsdown -w --sourcemap",
@@ -1,2 +0,0 @@
1
- import { h as takeScreenshot } from "./commands-38LzU5ML.js";
2
- export { takeScreenshot };