weapp-vite 6.8.0 → 6.9.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 (55) hide show
  1. package/dist/auto-import-components/resolvers.d.mts +2 -0
  2. package/dist/auto-import-components/resolvers.mjs +309 -350
  3. package/dist/auto-routes.d.mts +17 -0
  4. package/dist/auto-routes.mjs +48 -78
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.mjs +2171 -2398
  7. package/dist/config-IEj3IfSy.d.mts +3128 -0
  8. package/dist/config.d.mts +2 -0
  9. package/dist/config.mjs +8 -31
  10. package/dist/createContext-CDgRHY26.mjs +19 -0
  11. package/dist/file-UprqcX9e.mjs +356 -0
  12. package/dist/getInstance-jl4yXdc0.mjs +31841 -0
  13. package/dist/index-B5wBsuYI.d.mts +56 -0
  14. package/dist/index.d.mts +13 -0
  15. package/dist/index.mjs +9 -51
  16. package/dist/json.d.mts +2 -0
  17. package/dist/json.mjs +32 -14
  18. package/dist/logger-gutcwWKE.mjs +2 -0
  19. package/dist/mcp-pzGAH7ob.mjs +6415 -0
  20. package/dist/mcp.d.mts +30 -0
  21. package/dist/mcp.mjs +3 -18
  22. package/dist/pluginHost-SJdl15d3.mjs +24 -0
  23. package/dist/routes-o20IHwXa.d.mts +13 -0
  24. package/dist/{runtime.d.ts → runtime.d.mts} +12 -11
  25. package/dist/runtime.mjs +32 -11
  26. package/dist/types.d.mts +4 -0
  27. package/dist/types.mjs +1 -37
  28. package/dist/volar.d.mts +2 -0
  29. package/dist/volar.mjs +3 -9
  30. package/package.json +26 -31
  31. package/dist/auto-import-components/resolvers.d.ts +0 -10
  32. package/dist/auto-routes.d.ts +0 -16
  33. package/dist/chunk-3BOPS2AF.mjs +0 -34
  34. package/dist/chunk-6N2JYDJN.mjs +0 -13
  35. package/dist/chunk-BKU4KQJE.mjs +0 -430
  36. package/dist/chunk-EZOXN44U.mjs +0 -48
  37. package/dist/chunk-FXWNWYDN.mjs +0 -6
  38. package/dist/chunk-GJOF3MJY.mjs +0 -39428
  39. package/dist/chunk-JFV2DERD.mjs +0 -30
  40. package/dist/chunk-LDBSARE6.mjs +0 -9911
  41. package/dist/chunk-MIQZQK74.mjs +0 -14
  42. package/dist/chunk-OU5WM7WT.mjs +0 -41
  43. package/dist/chunk-X4YQFGKK.mjs +0 -29
  44. package/dist/cli.d.ts +0 -2
  45. package/dist/config-D8v221vL.d.ts +0 -1051
  46. package/dist/config.d.ts +0 -18
  47. package/dist/file-W4JJII65.mjs +0 -29
  48. package/dist/getInstance-W65F2IS7.mjs +0 -18
  49. package/dist/index.d.ts +0 -29
  50. package/dist/json.d.ts +0 -18
  51. package/dist/mcp.d.ts +0 -47
  52. package/dist/routes-74eLuiqj.d.ts +0 -12
  53. package/dist/types-B6irZnLM.d.ts +0 -46
  54. package/dist/types.d.ts +0 -29
  55. package/dist/volar.d.ts +0 -2
package/dist/cli.mjs CHANGED
@@ -1,2543 +1,2317 @@
1
- import {
2
- createCompilerContext
3
- } from "./chunk-JFV2DERD.mjs";
4
- import {
5
- DEFAULT_MP_PLATFORM,
6
- SHARED_CHUNK_VIRTUAL_PREFIX,
7
- checkRuntime,
8
- createCjsConfigLoadError,
9
- createSharedBuildConfig,
10
- formatBytes,
11
- getProjectConfigFileName,
12
- isPathInside,
13
- normalizeMiniPlatform,
14
- resolveMiniPlatform,
15
- resolveWeappConfigFile
16
- } from "./chunk-GJOF3MJY.mjs";
17
- import {
18
- VERSION
19
- } from "./chunk-BKU4KQJE.mjs";
20
- import "./chunk-OU5WM7WT.mjs";
21
- import {
22
- resolveWeappMcpConfig,
23
- startWeappViteMcpServer
24
- } from "./chunk-LDBSARE6.mjs";
25
- import {
26
- colors,
27
- default as default2
28
- } from "./chunk-MIQZQK74.mjs";
29
- import {
30
- init_esm_shims
31
- } from "./chunk-EZOXN44U.mjs";
32
-
33
- // src/cli.ts
34
- init_esm_shims();
35
- import process10 from "process";
36
-
37
- // ../../node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
38
- init_esm_shims();
1
+ import { f as VERSION } from "./file-UprqcX9e.mjs";
2
+ import { a as formatBytes, c as resolveMiniPlatform, d as resolveWeappConfigFile, f as checkRuntime, h as isPathInside, l as createSharedBuildConfig, m as createCjsConfigLoadError, o as DEFAULT_MP_PLATFORM, p as getProjectConfigFileName, s as normalizeMiniPlatform, u as SHARED_CHUNK_VIRTUAL_PREFIX } from "./getInstance-jl4yXdc0.mjs";
3
+ import { r as logger_default, t as colors } from "./logger-gutcwWKE.mjs";
4
+ import { t as createCompilerContext } from "./createContext-CDgRHY26.mjs";
5
+ import { a as resolveWeappMcpConfig, o as startWeappViteMcpServer } from "./mcp-pzGAH7ob.mjs";
6
+ import { defu } from "@weapp-core/shared";
7
+ import path, { posix } from "pathe";
8
+ import { dirname, join } from "node:path";
9
+ import fs from "fs-extra";
10
+ import process$1 from "node:process";
11
+ import { fileURLToPath } from "node:url";
12
+ import { build, createServer, loadConfigFromFile } from "vite";
13
+ import { Buffer } from "node:buffer";
14
+ import { formatRetryHotkeyPrompt, formatWechatIdeLoginRequiredError, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, parse, waitForRetryKeypress } from "weapp-ide-cli";
15
+ import { generateJs, generateJson, generateWxml, generateWxss } from "@weapp-core/schematics";
16
+ import { initConfig } from "@weapp-core/init";
17
+ //#region ../../node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
39
18
  function toArr(any) {
40
- return any == null ? [] : Array.isArray(any) ? any : [any];
19
+ return any == null ? [] : Array.isArray(any) ? any : [any];
41
20
  }
42
21
  function toVal(out, key, val, opts) {
43
- var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
44
- out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
22
+ var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
23
+ out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
45
24
  }
46
25
  function lib_default(args, opts) {
47
- args = args || [];
48
- opts = opts || {};
49
- var k, arr, arg, name, val, out = { _: [] };
50
- var i = 0, j = 0, idx = 0, len = args.length;
51
- const alibi = opts.alias !== void 0;
52
- const strict = opts.unknown !== void 0;
53
- const defaults = opts.default !== void 0;
54
- opts.alias = opts.alias || {};
55
- opts.string = toArr(opts.string);
56
- opts.boolean = toArr(opts.boolean);
57
- if (alibi) for (k in opts.alias) {
58
- arr = opts.alias[k] = toArr(opts.alias[k]);
59
- for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
60
- }
61
- for (i = opts.boolean.length; i-- > 0; ) {
62
- arr = opts.alias[opts.boolean[i]] || [];
63
- for (j = arr.length; j-- > 0; ) opts.boolean.push(arr[j]);
64
- }
65
- for (i = opts.string.length; i-- > 0; ) {
66
- arr = opts.alias[opts.string[i]] || [];
67
- for (j = arr.length; j-- > 0; ) opts.string.push(arr[j]);
68
- }
69
- if (defaults) for (k in opts.default) {
70
- name = typeof opts.default[k];
71
- arr = opts.alias[k] = opts.alias[k] || [];
72
- if (opts[name] !== void 0) {
73
- opts[name].push(k);
74
- for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
75
- }
76
- }
77
- const keys = strict ? Object.keys(opts.alias) : [];
78
- for (i = 0; i < len; i++) {
79
- arg = args[i];
80
- if (arg === "--") {
81
- out._ = out._.concat(args.slice(++i));
82
- break;
83
- }
84
- for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
85
- if (j === 0) out._.push(arg);
86
- else if (arg.substring(j, j + 3) === "no-") {
87
- name = arg.substring(j + 3);
88
- if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
89
- out[name] = false;
90
- } else {
91
- for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
92
- name = arg.substring(j, idx);
93
- val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
94
- arr = j === 2 ? [name] : name;
95
- for (idx = 0; idx < arr.length; idx++) {
96
- name = arr[idx];
97
- if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
98
- toVal(out, name, idx + 1 < arr.length || val, opts);
99
- }
100
- }
101
- }
102
- if (defaults) {
103
- for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
104
- }
105
- if (alibi) for (k in out) {
106
- arr = opts.alias[k] || [];
107
- while (arr.length > 0) out[arr.shift()] = out[k];
108
- }
109
- return out;
26
+ args = args || [];
27
+ opts = opts || {};
28
+ var k, arr, arg, name, val, out = { _: [] };
29
+ var i = 0, j = 0, idx = 0, len = args.length;
30
+ const alibi = opts.alias !== void 0;
31
+ const strict = opts.unknown !== void 0;
32
+ const defaults = opts.default !== void 0;
33
+ opts.alias = opts.alias || {};
34
+ opts.string = toArr(opts.string);
35
+ opts.boolean = toArr(opts.boolean);
36
+ if (alibi) for (k in opts.alias) {
37
+ arr = opts.alias[k] = toArr(opts.alias[k]);
38
+ for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
39
+ }
40
+ for (i = opts.boolean.length; i-- > 0;) {
41
+ arr = opts.alias[opts.boolean[i]] || [];
42
+ for (j = arr.length; j-- > 0;) opts.boolean.push(arr[j]);
43
+ }
44
+ for (i = opts.string.length; i-- > 0;) {
45
+ arr = opts.alias[opts.string[i]] || [];
46
+ for (j = arr.length; j-- > 0;) opts.string.push(arr[j]);
47
+ }
48
+ if (defaults) for (k in opts.default) {
49
+ name = typeof opts.default[k];
50
+ arr = opts.alias[k] = opts.alias[k] || [];
51
+ if (opts[name] !== void 0) {
52
+ opts[name].push(k);
53
+ for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
54
+ }
55
+ }
56
+ const keys = strict ? Object.keys(opts.alias) : [];
57
+ for (i = 0; i < len; i++) {
58
+ arg = args[i];
59
+ if (arg === "--") {
60
+ out._ = out._.concat(args.slice(++i));
61
+ break;
62
+ }
63
+ for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
64
+ if (j === 0) out._.push(arg);
65
+ else if (arg.substring(j, j + 3) === "no-") {
66
+ name = arg.substring(j + 3);
67
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
68
+ out[name] = false;
69
+ } else {
70
+ for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
71
+ name = arg.substring(j, idx);
72
+ val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
73
+ arr = j === 2 ? [name] : name;
74
+ for (idx = 0; idx < arr.length; idx++) {
75
+ name = arr[idx];
76
+ if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
77
+ toVal(out, name, idx + 1 < arr.length || val, opts);
78
+ }
79
+ }
80
+ }
81
+ if (defaults) {
82
+ for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
83
+ }
84
+ if (alibi) for (k in out) {
85
+ arr = opts.alias[k] || [];
86
+ while (arr.length > 0) out[arr.shift()] = out[k];
87
+ }
88
+ return out;
110
89
  }
111
90
  function removeBrackets(v) {
112
- return v.replace(/[<[].+/, "").trim();
91
+ return v.replace(/[<[].+/, "").trim();
113
92
  }
114
93
  function findAllBrackets(v) {
115
- const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
116
- const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
117
- const res = [];
118
- const parse3 = (match) => {
119
- let variadic = false;
120
- let value = match[1];
121
- if (value.startsWith("...")) {
122
- value = value.slice(3);
123
- variadic = true;
124
- }
125
- return {
126
- required: match[0].startsWith("<"),
127
- value,
128
- variadic
129
- };
130
- };
131
- let angledMatch;
132
- while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse3(angledMatch));
133
- let squareMatch;
134
- while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse3(squareMatch));
135
- return res;
94
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
95
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
96
+ const res = [];
97
+ const parse = (match) => {
98
+ let variadic = false;
99
+ let value = match[1];
100
+ if (value.startsWith("...")) {
101
+ value = value.slice(3);
102
+ variadic = true;
103
+ }
104
+ return {
105
+ required: match[0].startsWith("<"),
106
+ value,
107
+ variadic
108
+ };
109
+ };
110
+ let angledMatch;
111
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
112
+ let squareMatch;
113
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
114
+ return res;
136
115
  }
137
116
  function getMriOptions(options) {
138
- const result = {
139
- alias: {},
140
- boolean: []
141
- };
142
- for (const [index, option] of options.entries()) {
143
- if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
144
- if (option.isBoolean) if (option.negated) {
145
- if (!options.some((o, i) => {
146
- return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
147
- })) result.boolean.push(option.names[0]);
148
- } else result.boolean.push(option.names[0]);
149
- }
150
- return result;
117
+ const result = {
118
+ alias: {},
119
+ boolean: []
120
+ };
121
+ for (const [index, option] of options.entries()) {
122
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
123
+ if (option.isBoolean) if (option.negated) {
124
+ if (!options.some((o, i) => {
125
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
126
+ })) result.boolean.push(option.names[0]);
127
+ } else result.boolean.push(option.names[0]);
128
+ }
129
+ return result;
151
130
  }
152
131
  function findLongest(arr) {
153
- return arr.sort((a, b) => {
154
- return a.length > b.length ? -1 : 1;
155
- })[0];
132
+ return arr.sort((a, b) => {
133
+ return a.length > b.length ? -1 : 1;
134
+ })[0];
156
135
  }
157
136
  function padRight(str, length) {
158
- return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
137
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
159
138
  }
160
139
  function camelcase(input) {
161
- return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
162
- return p1 + p2.toUpperCase();
163
- });
140
+ return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
141
+ return p1 + p2.toUpperCase();
142
+ });
164
143
  }
165
144
  function setDotProp(obj, keys, val) {
166
- let current = obj;
167
- for (let i = 0; i < keys.length; i++) {
168
- const key = keys[i];
169
- if (i === keys.length - 1) {
170
- current[key] = val;
171
- return;
172
- }
173
- if (current[key] == null) {
174
- const nextKeyIsArrayIndex = +keys[i + 1] > -1;
175
- current[key] = nextKeyIsArrayIndex ? [] : {};
176
- }
177
- current = current[key];
178
- }
145
+ let current = obj;
146
+ for (let i = 0; i < keys.length; i++) {
147
+ const key = keys[i];
148
+ if (i === keys.length - 1) {
149
+ current[key] = val;
150
+ return;
151
+ }
152
+ if (current[key] == null) {
153
+ const nextKeyIsArrayIndex = +keys[i + 1] > -1;
154
+ current[key] = nextKeyIsArrayIndex ? [] : {};
155
+ }
156
+ current = current[key];
157
+ }
179
158
  }
180
159
  function setByType(obj, transforms) {
181
- for (const key of Object.keys(transforms)) {
182
- const transform = transforms[key];
183
- if (transform.shouldTransform) {
184
- obj[key] = [obj[key]].flat();
185
- if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
186
- }
187
- }
160
+ for (const key of Object.keys(transforms)) {
161
+ const transform = transforms[key];
162
+ if (transform.shouldTransform) {
163
+ obj[key] = [obj[key]].flat();
164
+ if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
165
+ }
166
+ }
188
167
  }
189
168
  function getFileName(input) {
190
- const m = /([^\\/]+)$/.exec(input);
191
- return m ? m[1] : "";
169
+ const m = /([^\\/]+)$/.exec(input);
170
+ return m ? m[1] : "";
192
171
  }
193
172
  function camelcaseOptionName(name) {
194
- return name.split(".").map((v, i) => {
195
- return i === 0 ? camelcase(v) : v;
196
- }).join(".");
173
+ return name.split(".").map((v, i) => {
174
+ return i === 0 ? camelcase(v) : v;
175
+ }).join(".");
197
176
  }
198
177
  var CACError = class extends Error {
199
- constructor(message) {
200
- super(message);
201
- this.name = "CACError";
202
- if (typeof Error.captureStackTrace !== "function") this.stack = new Error(message).stack;
203
- }
178
+ constructor(message) {
179
+ super(message);
180
+ this.name = "CACError";
181
+ if (typeof Error.captureStackTrace !== "function") this.stack = new Error(message).stack;
182
+ }
204
183
  };
205
184
  var Option = class {
206
- rawName;
207
- description;
208
- /** Option name */
209
- name;
210
- /** Option name and aliases */
211
- names;
212
- isBoolean;
213
- required;
214
- config;
215
- negated;
216
- constructor(rawName, description, config) {
217
- this.rawName = rawName;
218
- this.description = description;
219
- this.config = Object.assign({}, config);
220
- rawName = rawName.replaceAll(".*", "");
221
- this.negated = false;
222
- this.names = removeBrackets(rawName).split(",").map((v) => {
223
- let name = v.trim().replace(/^-{1,2}/, "");
224
- if (name.startsWith("no-")) {
225
- this.negated = true;
226
- name = name.replace(/^no-/, "");
227
- }
228
- return camelcaseOptionName(name);
229
- }).sort((a, b) => a.length > b.length ? 1 : -1);
230
- this.name = this.names.at(-1);
231
- if (this.negated && this.config.default == null) this.config.default = true;
232
- if (rawName.includes("<")) this.required = true;
233
- else if (rawName.includes("[")) this.required = false;
234
- else this.isBoolean = true;
235
- }
185
+ rawName;
186
+ description;
187
+ /** Option name */
188
+ name;
189
+ /** Option name and aliases */
190
+ names;
191
+ isBoolean;
192
+ required;
193
+ config;
194
+ negated;
195
+ constructor(rawName, description, config) {
196
+ this.rawName = rawName;
197
+ this.description = description;
198
+ this.config = Object.assign({}, config);
199
+ rawName = rawName.replaceAll(".*", "");
200
+ this.negated = false;
201
+ this.names = removeBrackets(rawName).split(",").map((v) => {
202
+ let name = v.trim().replace(/^-{1,2}/, "");
203
+ if (name.startsWith("no-")) {
204
+ this.negated = true;
205
+ name = name.replace(/^no-/, "");
206
+ }
207
+ return camelcaseOptionName(name);
208
+ }).sort((a, b) => a.length > b.length ? 1 : -1);
209
+ this.name = this.names.at(-1);
210
+ if (this.negated && this.config.default == null) this.config.default = true;
211
+ if (rawName.includes("<")) this.required = true;
212
+ else if (rawName.includes("[")) this.required = false;
213
+ else this.isBoolean = true;
214
+ }
236
215
  };
237
- var runtimeProcessArgs;
238
- var runtimeInfo;
216
+ let runtimeProcessArgs;
217
+ let runtimeInfo;
239
218
  if (typeof process !== "undefined") {
240
- let runtimeName;
241
- if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string") runtimeName = "deno";
242
- else if (typeof Bun !== "undefined" && typeof Bun.version === "string") runtimeName = "bun";
243
- else runtimeName = "node";
244
- runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
245
- runtimeProcessArgs = process.argv;
219
+ let runtimeName;
220
+ if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string") runtimeName = "deno";
221
+ else if (typeof Bun !== "undefined" && typeof Bun.version === "string") runtimeName = "bun";
222
+ else runtimeName = "node";
223
+ runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
224
+ runtimeProcessArgs = process.argv;
246
225
  } else if (typeof navigator === "undefined") runtimeInfo = `unknown`;
247
226
  else runtimeInfo = `${navigator.platform} ${navigator.userAgent}`;
248
227
  var Command = class {
249
- rawName;
250
- description;
251
- config;
252
- cli;
253
- options;
254
- aliasNames;
255
- name;
256
- args;
257
- commandAction;
258
- usageText;
259
- versionNumber;
260
- examples;
261
- helpCallback;
262
- globalCommand;
263
- constructor(rawName, description, config = {}, cli2) {
264
- this.rawName = rawName;
265
- this.description = description;
266
- this.config = config;
267
- this.cli = cli2;
268
- this.options = [];
269
- this.aliasNames = [];
270
- this.name = removeBrackets(rawName);
271
- this.args = findAllBrackets(rawName);
272
- this.examples = [];
273
- }
274
- usage(text) {
275
- this.usageText = text;
276
- return this;
277
- }
278
- allowUnknownOptions() {
279
- this.config.allowUnknownOptions = true;
280
- return this;
281
- }
282
- ignoreOptionDefaultValue() {
283
- this.config.ignoreOptionDefaultValue = true;
284
- return this;
285
- }
286
- version(version, customFlags = "-v, --version") {
287
- this.versionNumber = version;
288
- this.option(customFlags, "Display version number");
289
- return this;
290
- }
291
- example(example) {
292
- this.examples.push(example);
293
- return this;
294
- }
295
- /**
296
- * Add a option for this command
297
- * @param rawName Raw option name(s)
298
- * @param description Option description
299
- * @param config Option config
300
- */
301
- option(rawName, description, config) {
302
- const option = new Option(rawName, description, config);
303
- this.options.push(option);
304
- return this;
305
- }
306
- alias(name) {
307
- this.aliasNames.push(name);
308
- return this;
309
- }
310
- action(callback) {
311
- this.commandAction = callback;
312
- return this;
313
- }
314
- /**
315
- * Check if a command name is matched by this command
316
- * @param name Command name
317
- */
318
- isMatched(name) {
319
- return this.name === name || this.aliasNames.includes(name);
320
- }
321
- get isDefaultCommand() {
322
- return this.name === "" || this.aliasNames.includes("!");
323
- }
324
- get isGlobalCommand() {
325
- return this instanceof GlobalCommand;
326
- }
327
- /**
328
- * Check if an option is registered in this command
329
- * @param name Option name
330
- */
331
- hasOption(name) {
332
- name = name.split(".")[0];
333
- return this.options.find((option) => {
334
- return option.names.includes(name);
335
- });
336
- }
337
- outputHelp() {
338
- const { name, commands } = this.cli;
339
- const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
340
- let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
341
- sections.push({
342
- title: "Usage",
343
- body: ` $ ${name} ${this.usageText || this.rawName}`
344
- });
345
- if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
346
- const longestCommandName = findLongest(commands.map((command) => command.rawName));
347
- sections.push({
348
- title: "Commands",
349
- body: commands.map((command) => {
350
- return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
351
- }).join("\n")
352
- }, {
353
- title: `For more info, run any command with the \`--help\` flag`,
354
- body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
355
- });
356
- }
357
- let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
358
- if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
359
- if (options.length > 0) {
360
- const longestOptionName = findLongest(options.map((option) => option.rawName));
361
- sections.push({
362
- title: "Options",
363
- body: options.map((option) => {
364
- return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
365
- }).join("\n")
366
- });
367
- }
368
- if (this.examples.length > 0) sections.push({
369
- title: "Examples",
370
- body: this.examples.map((example) => {
371
- if (typeof example === "function") return example(name);
372
- return example;
373
- }).join("\n")
374
- });
375
- if (helpCallback) sections = helpCallback(sections) || sections;
376
- console.info(sections.map((section) => {
377
- return section.title ? `${section.title}:
378
- ${section.body}` : section.body;
379
- }).join("\n\n"));
380
- }
381
- outputVersion() {
382
- const { name } = this.cli;
383
- const { versionNumber } = this.cli.globalCommand;
384
- if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
385
- }
386
- checkRequiredArgs() {
387
- const minimalArgsCount = this.args.filter((arg) => arg.required).length;
388
- if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
389
- }
390
- /**
391
- * Check if the parsed options contain any unknown options
392
- *
393
- * Exit and output error when true
394
- */
395
- checkUnknownOptions() {
396
- const { options, globalCommand } = this.cli;
397
- if (!this.config.allowUnknownOptions) {
398
- for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
399
- }
400
- }
401
- /**
402
- * Check if the required string-type options exist
403
- */
404
- checkOptionValue() {
405
- const { options: parsedOptions, globalCommand } = this.cli;
406
- const options = [...globalCommand.options, ...this.options];
407
- for (const option of options) {
408
- const value = parsedOptions[option.name.split(".")[0]];
409
- if (option.required) {
410
- const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
411
- if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
412
- }
413
- }
414
- }
415
- /**
416
- * Check if the number of args is more than expected
417
- */
418
- checkUnusedArgs() {
419
- const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
420
- if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
421
- }
228
+ rawName;
229
+ description;
230
+ config;
231
+ cli;
232
+ options;
233
+ aliasNames;
234
+ name;
235
+ args;
236
+ commandAction;
237
+ usageText;
238
+ versionNumber;
239
+ examples;
240
+ helpCallback;
241
+ globalCommand;
242
+ constructor(rawName, description, config = {}, cli) {
243
+ this.rawName = rawName;
244
+ this.description = description;
245
+ this.config = config;
246
+ this.cli = cli;
247
+ this.options = [];
248
+ this.aliasNames = [];
249
+ this.name = removeBrackets(rawName);
250
+ this.args = findAllBrackets(rawName);
251
+ this.examples = [];
252
+ }
253
+ usage(text) {
254
+ this.usageText = text;
255
+ return this;
256
+ }
257
+ allowUnknownOptions() {
258
+ this.config.allowUnknownOptions = true;
259
+ return this;
260
+ }
261
+ ignoreOptionDefaultValue() {
262
+ this.config.ignoreOptionDefaultValue = true;
263
+ return this;
264
+ }
265
+ version(version, customFlags = "-v, --version") {
266
+ this.versionNumber = version;
267
+ this.option(customFlags, "Display version number");
268
+ return this;
269
+ }
270
+ example(example) {
271
+ this.examples.push(example);
272
+ return this;
273
+ }
274
+ /**
275
+ * Add a option for this command
276
+ * @param rawName Raw option name(s)
277
+ * @param description Option description
278
+ * @param config Option config
279
+ */
280
+ option(rawName, description, config) {
281
+ const option = new Option(rawName, description, config);
282
+ this.options.push(option);
283
+ return this;
284
+ }
285
+ alias(name) {
286
+ this.aliasNames.push(name);
287
+ return this;
288
+ }
289
+ action(callback) {
290
+ this.commandAction = callback;
291
+ return this;
292
+ }
293
+ /**
294
+ * Check if a command name is matched by this command
295
+ * @param name Command name
296
+ */
297
+ isMatched(name) {
298
+ return this.name === name || this.aliasNames.includes(name);
299
+ }
300
+ get isDefaultCommand() {
301
+ return this.name === "" || this.aliasNames.includes("!");
302
+ }
303
+ get isGlobalCommand() {
304
+ return this instanceof GlobalCommand;
305
+ }
306
+ /**
307
+ * Check if an option is registered in this command
308
+ * @param name Option name
309
+ */
310
+ hasOption(name) {
311
+ name = name.split(".")[0];
312
+ return this.options.find((option) => {
313
+ return option.names.includes(name);
314
+ });
315
+ }
316
+ outputHelp() {
317
+ const { name, commands } = this.cli;
318
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
319
+ let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
320
+ sections.push({
321
+ title: "Usage",
322
+ body: ` $ ${name} ${this.usageText || this.rawName}`
323
+ });
324
+ if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
325
+ const longestCommandName = findLongest(commands.map((command) => command.rawName));
326
+ sections.push({
327
+ title: "Commands",
328
+ body: commands.map((command) => {
329
+ return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
330
+ }).join("\n")
331
+ }, {
332
+ title: `For more info, run any command with the \`--help\` flag`,
333
+ body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
334
+ });
335
+ }
336
+ let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
337
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
338
+ if (options.length > 0) {
339
+ const longestOptionName = findLongest(options.map((option) => option.rawName));
340
+ sections.push({
341
+ title: "Options",
342
+ body: options.map((option) => {
343
+ return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
344
+ }).join("\n")
345
+ });
346
+ }
347
+ if (this.examples.length > 0) sections.push({
348
+ title: "Examples",
349
+ body: this.examples.map((example) => {
350
+ if (typeof example === "function") return example(name);
351
+ return example;
352
+ }).join("\n")
353
+ });
354
+ if (helpCallback) sections = helpCallback(sections) || sections;
355
+ console.info(sections.map((section) => {
356
+ return section.title ? `${section.title}:\n${section.body}` : section.body;
357
+ }).join("\n\n"));
358
+ }
359
+ outputVersion() {
360
+ const { name } = this.cli;
361
+ const { versionNumber } = this.cli.globalCommand;
362
+ if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
363
+ }
364
+ checkRequiredArgs() {
365
+ const minimalArgsCount = this.args.filter((arg) => arg.required).length;
366
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
367
+ }
368
+ /**
369
+ * Check if the parsed options contain any unknown options
370
+ *
371
+ * Exit and output error when true
372
+ */
373
+ checkUnknownOptions() {
374
+ const { options, globalCommand } = this.cli;
375
+ if (!this.config.allowUnknownOptions) {
376
+ for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
377
+ }
378
+ }
379
+ /**
380
+ * Check if the required string-type options exist
381
+ */
382
+ checkOptionValue() {
383
+ const { options: parsedOptions, globalCommand } = this.cli;
384
+ const options = [...globalCommand.options, ...this.options];
385
+ for (const option of options) {
386
+ const value = parsedOptions[option.name.split(".")[0]];
387
+ if (option.required) {
388
+ const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
389
+ if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
390
+ }
391
+ }
392
+ }
393
+ /**
394
+ * Check if the number of args is more than expected
395
+ */
396
+ checkUnusedArgs() {
397
+ const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
398
+ if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
399
+ }
422
400
  };
423
401
  var GlobalCommand = class extends Command {
424
- constructor(cli2) {
425
- super("@@global@@", "", {}, cli2);
426
- }
402
+ constructor(cli) {
403
+ super("@@global@@", "", {}, cli);
404
+ }
427
405
  };
428
406
  var CAC = class extends EventTarget {
429
- /** The program name to display in help and version message */
430
- name;
431
- commands;
432
- globalCommand;
433
- matchedCommand;
434
- matchedCommandName;
435
- /**
436
- * Raw CLI arguments
437
- */
438
- rawArgs;
439
- /**
440
- * Parsed CLI arguments
441
- */
442
- args;
443
- /**
444
- * Parsed CLI options, camelCased
445
- */
446
- options;
447
- showHelpOnExit;
448
- showVersionOnExit;
449
- /**
450
- * @param name The program name to display in help and version message
451
- */
452
- constructor(name = "") {
453
- super();
454
- this.name = name;
455
- this.commands = [];
456
- this.rawArgs = [];
457
- this.args = [];
458
- this.options = {};
459
- this.globalCommand = new GlobalCommand(this);
460
- this.globalCommand.usage("<command> [options]");
461
- }
462
- /**
463
- * Add a global usage text.
464
- *
465
- * This is not used by sub-commands.
466
- */
467
- usage(text) {
468
- this.globalCommand.usage(text);
469
- return this;
470
- }
471
- /**
472
- * Add a sub-command
473
- */
474
- command(rawName, description, config) {
475
- const command = new Command(rawName, description || "", config, this);
476
- command.globalCommand = this.globalCommand;
477
- this.commands.push(command);
478
- return command;
479
- }
480
- /**
481
- * Add a global CLI option.
482
- *
483
- * Which is also applied to sub-commands.
484
- */
485
- option(rawName, description, config) {
486
- this.globalCommand.option(rawName, description, config);
487
- return this;
488
- }
489
- /**
490
- * Show help message when `-h, --help` flags appear.
491
- *
492
- */
493
- help(callback) {
494
- this.globalCommand.option("-h, --help", "Display this message");
495
- this.globalCommand.helpCallback = callback;
496
- this.showHelpOnExit = true;
497
- return this;
498
- }
499
- /**
500
- * Show version number when `-v, --version` flags appear.
501
- *
502
- */
503
- version(version, customFlags = "-v, --version") {
504
- this.globalCommand.version(version, customFlags);
505
- this.showVersionOnExit = true;
506
- return this;
507
- }
508
- /**
509
- * Add a global example.
510
- *
511
- * This example added here will not be used by sub-commands.
512
- */
513
- example(example) {
514
- this.globalCommand.example(example);
515
- return this;
516
- }
517
- /**
518
- * Output the corresponding help message
519
- * When a sub-command is matched, output the help message for the command
520
- * Otherwise output the global one.
521
- *
522
- */
523
- outputHelp() {
524
- if (this.matchedCommand) this.matchedCommand.outputHelp();
525
- else this.globalCommand.outputHelp();
526
- }
527
- /**
528
- * Output the version number.
529
- *
530
- */
531
- outputVersion() {
532
- this.globalCommand.outputVersion();
533
- }
534
- setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
535
- this.args = args;
536
- this.options = options;
537
- if (matchedCommand) this.matchedCommand = matchedCommand;
538
- if (matchedCommandName) this.matchedCommandName = matchedCommandName;
539
- return this;
540
- }
541
- unsetMatchedCommand() {
542
- this.matchedCommand = void 0;
543
- this.matchedCommandName = void 0;
544
- }
545
- /**
546
- * Parse argv
547
- */
548
- parse(argv, { run = true } = {}) {
549
- if (!argv) {
550
- if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
551
- argv = runtimeProcessArgs;
552
- }
553
- this.rawArgs = argv;
554
- if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
555
- let shouldParse = true;
556
- for (const command of this.commands) {
557
- const parsed = this.mri(argv.slice(2), command);
558
- const commandName = parsed.args[0];
559
- if (command.isMatched(commandName)) {
560
- shouldParse = false;
561
- const parsedInfo = {
562
- ...parsed,
563
- args: parsed.args.slice(1)
564
- };
565
- this.setParsedInfo(parsedInfo, command, commandName);
566
- this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
567
- }
568
- }
569
- if (shouldParse) {
570
- for (const command of this.commands) if (command.isDefaultCommand) {
571
- shouldParse = false;
572
- const parsed = this.mri(argv.slice(2), command);
573
- this.setParsedInfo(parsed, command);
574
- this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
575
- }
576
- }
577
- if (shouldParse) {
578
- const parsed = this.mri(argv.slice(2));
579
- this.setParsedInfo(parsed);
580
- }
581
- if (this.options.help && this.showHelpOnExit) {
582
- this.outputHelp();
583
- run = false;
584
- this.unsetMatchedCommand();
585
- }
586
- if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
587
- this.outputVersion();
588
- run = false;
589
- this.unsetMatchedCommand();
590
- }
591
- const parsedArgv = {
592
- args: this.args,
593
- options: this.options
594
- };
595
- if (run) this.runMatchedCommand();
596
- if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
597
- return parsedArgv;
598
- }
599
- mri(argv, command) {
600
- const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
601
- const mriOptions = getMriOptions(cliOptions);
602
- let argsAfterDoubleDashes = [];
603
- const doubleDashesIndex = argv.indexOf("--");
604
- if (doubleDashesIndex !== -1) {
605
- argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
606
- argv = argv.slice(0, doubleDashesIndex);
607
- }
608
- let parsed = lib_default(argv, mriOptions);
609
- parsed = Object.keys(parsed).reduce((res, name) => {
610
- return {
611
- ...res,
612
- [camelcaseOptionName(name)]: parsed[name]
613
- };
614
- }, { _: [] });
615
- const args = parsed._;
616
- const options = { "--": argsAfterDoubleDashes };
617
- const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
618
- const transforms = /* @__PURE__ */ Object.create(null);
619
- for (const cliOption of cliOptions) {
620
- if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
621
- if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === void 0) {
622
- transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
623
- transforms[cliOption.name].shouldTransform = true;
624
- transforms[cliOption.name].transformFunction = cliOption.config.type[0];
625
- }
626
- }
627
- for (const key of Object.keys(parsed)) if (key !== "_") {
628
- setDotProp(options, key.split("."), parsed[key]);
629
- setByType(options, transforms);
630
- }
631
- return {
632
- args,
633
- options
634
- };
635
- }
636
- runMatchedCommand() {
637
- const { args, options, matchedCommand: command } = this;
638
- if (!command || !command.commandAction) return;
639
- command.checkUnknownOptions();
640
- command.checkOptionValue();
641
- command.checkRequiredArgs();
642
- command.checkUnusedArgs();
643
- const actionArgs = [];
644
- command.args.forEach((arg, index) => {
645
- if (arg.variadic) actionArgs.push(args.slice(index));
646
- else actionArgs.push(args[index]);
647
- });
648
- actionArgs.push(options);
649
- return command.commandAction.apply(this, actionArgs);
650
- }
407
+ /** The program name to display in help and version message */
408
+ name;
409
+ commands;
410
+ globalCommand;
411
+ matchedCommand;
412
+ matchedCommandName;
413
+ /**
414
+ * Raw CLI arguments
415
+ */
416
+ rawArgs;
417
+ /**
418
+ * Parsed CLI arguments
419
+ */
420
+ args;
421
+ /**
422
+ * Parsed CLI options, camelCased
423
+ */
424
+ options;
425
+ showHelpOnExit;
426
+ showVersionOnExit;
427
+ /**
428
+ * @param name The program name to display in help and version message
429
+ */
430
+ constructor(name = "") {
431
+ super();
432
+ this.name = name;
433
+ this.commands = [];
434
+ this.rawArgs = [];
435
+ this.args = [];
436
+ this.options = {};
437
+ this.globalCommand = new GlobalCommand(this);
438
+ this.globalCommand.usage("<command> [options]");
439
+ }
440
+ /**
441
+ * Add a global usage text.
442
+ *
443
+ * This is not used by sub-commands.
444
+ */
445
+ usage(text) {
446
+ this.globalCommand.usage(text);
447
+ return this;
448
+ }
449
+ /**
450
+ * Add a sub-command
451
+ */
452
+ command(rawName, description, config) {
453
+ const command = new Command(rawName, description || "", config, this);
454
+ command.globalCommand = this.globalCommand;
455
+ this.commands.push(command);
456
+ return command;
457
+ }
458
+ /**
459
+ * Add a global CLI option.
460
+ *
461
+ * Which is also applied to sub-commands.
462
+ */
463
+ option(rawName, description, config) {
464
+ this.globalCommand.option(rawName, description, config);
465
+ return this;
466
+ }
467
+ /**
468
+ * Show help message when `-h, --help` flags appear.
469
+ *
470
+ */
471
+ help(callback) {
472
+ this.globalCommand.option("-h, --help", "Display this message");
473
+ this.globalCommand.helpCallback = callback;
474
+ this.showHelpOnExit = true;
475
+ return this;
476
+ }
477
+ /**
478
+ * Show version number when `-v, --version` flags appear.
479
+ *
480
+ */
481
+ version(version, customFlags = "-v, --version") {
482
+ this.globalCommand.version(version, customFlags);
483
+ this.showVersionOnExit = true;
484
+ return this;
485
+ }
486
+ /**
487
+ * Add a global example.
488
+ *
489
+ * This example added here will not be used by sub-commands.
490
+ */
491
+ example(example) {
492
+ this.globalCommand.example(example);
493
+ return this;
494
+ }
495
+ /**
496
+ * Output the corresponding help message
497
+ * When a sub-command is matched, output the help message for the command
498
+ * Otherwise output the global one.
499
+ *
500
+ */
501
+ outputHelp() {
502
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
503
+ else this.globalCommand.outputHelp();
504
+ }
505
+ /**
506
+ * Output the version number.
507
+ *
508
+ */
509
+ outputVersion() {
510
+ this.globalCommand.outputVersion();
511
+ }
512
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
513
+ this.args = args;
514
+ this.options = options;
515
+ if (matchedCommand) this.matchedCommand = matchedCommand;
516
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
517
+ return this;
518
+ }
519
+ unsetMatchedCommand() {
520
+ this.matchedCommand = void 0;
521
+ this.matchedCommandName = void 0;
522
+ }
523
+ /**
524
+ * Parse argv
525
+ */
526
+ parse(argv, { run = true } = {}) {
527
+ if (!argv) {
528
+ if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
529
+ argv = runtimeProcessArgs;
530
+ }
531
+ this.rawArgs = argv;
532
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
533
+ let shouldParse = true;
534
+ for (const command of this.commands) {
535
+ const parsed = this.mri(argv.slice(2), command);
536
+ const commandName = parsed.args[0];
537
+ if (command.isMatched(commandName)) {
538
+ shouldParse = false;
539
+ const parsedInfo = {
540
+ ...parsed,
541
+ args: parsed.args.slice(1)
542
+ };
543
+ this.setParsedInfo(parsedInfo, command, commandName);
544
+ this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
545
+ }
546
+ }
547
+ if (shouldParse) {
548
+ for (const command of this.commands) if (command.isDefaultCommand) {
549
+ shouldParse = false;
550
+ const parsed = this.mri(argv.slice(2), command);
551
+ this.setParsedInfo(parsed, command);
552
+ this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
553
+ }
554
+ }
555
+ if (shouldParse) {
556
+ const parsed = this.mri(argv.slice(2));
557
+ this.setParsedInfo(parsed);
558
+ }
559
+ if (this.options.help && this.showHelpOnExit) {
560
+ this.outputHelp();
561
+ run = false;
562
+ this.unsetMatchedCommand();
563
+ }
564
+ if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
565
+ this.outputVersion();
566
+ run = false;
567
+ this.unsetMatchedCommand();
568
+ }
569
+ const parsedArgv = {
570
+ args: this.args,
571
+ options: this.options
572
+ };
573
+ if (run) this.runMatchedCommand();
574
+ if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
575
+ return parsedArgv;
576
+ }
577
+ mri(argv, command) {
578
+ const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
579
+ const mriOptions = getMriOptions(cliOptions);
580
+ let argsAfterDoubleDashes = [];
581
+ const doubleDashesIndex = argv.indexOf("--");
582
+ if (doubleDashesIndex !== -1) {
583
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
584
+ argv = argv.slice(0, doubleDashesIndex);
585
+ }
586
+ let parsed = lib_default(argv, mriOptions);
587
+ parsed = Object.keys(parsed).reduce((res, name) => {
588
+ return {
589
+ ...res,
590
+ [camelcaseOptionName(name)]: parsed[name]
591
+ };
592
+ }, { _: [] });
593
+ const args = parsed._;
594
+ const options = { "--": argsAfterDoubleDashes };
595
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
596
+ const transforms = Object.create(null);
597
+ for (const cliOption of cliOptions) {
598
+ if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
599
+ if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === void 0) {
600
+ transforms[cliOption.name] = Object.create(null);
601
+ transforms[cliOption.name].shouldTransform = true;
602
+ transforms[cliOption.name].transformFunction = cliOption.config.type[0];
603
+ }
604
+ }
605
+ for (const key of Object.keys(parsed)) if (key !== "_") {
606
+ setDotProp(options, key.split("."), parsed[key]);
607
+ setByType(options, transforms);
608
+ }
609
+ return {
610
+ args,
611
+ options
612
+ };
613
+ }
614
+ runMatchedCommand() {
615
+ const { args, options, matchedCommand: command } = this;
616
+ if (!command || !command.commandAction) return;
617
+ command.checkUnknownOptions();
618
+ command.checkOptionValue();
619
+ command.checkRequiredArgs();
620
+ command.checkUnusedArgs();
621
+ const actionArgs = [];
622
+ command.args.forEach((arg, index) => {
623
+ if (arg.variadic) actionArgs.push(args.slice(index));
624
+ else actionArgs.push(args[index]);
625
+ });
626
+ actionArgs.push(options);
627
+ return command.commandAction.apply(this, actionArgs);
628
+ }
651
629
  };
652
- var cac = (name = "") => new CAC(name);
653
-
654
- // src/cli/commands/analyze.ts
655
- init_esm_shims();
656
- import process3 from "process";
657
- import fs3 from "fs-extra";
658
- import path3 from "pathe";
659
-
660
- // src/analyze/subpackages/index.ts
661
- init_esm_shims();
662
- import { build } from "vite";
663
-
664
- // src/analyze/subpackages/output.ts
665
- init_esm_shims();
666
- import { Buffer } from "buffer";
667
-
668
- // src/analyze/subpackages/classifier.ts
669
- init_esm_shims();
670
- import { posix as path } from "pathe";
671
- var VIRTUAL_MODULE_INDICATOR = "\0";
672
- var VIRTUAL_PREFIX = `${SHARED_CHUNK_VIRTUAL_PREFIX}/`;
630
+ /**
631
+ * @param name The program name to display in help and version message
632
+ */
633
+ const cac = (name = "") => new CAC(name);
634
+ //#endregion
635
+ //#region src/analyze/subpackages/classifier.ts
636
+ const VIRTUAL_MODULE_INDICATOR = "\0";
637
+ const VIRTUAL_PREFIX = `${SHARED_CHUNK_VIRTUAL_PREFIX}/`;
673
638
  function classifyPackage(fileName, origin, context) {
674
- if (fileName.startsWith(VIRTUAL_PREFIX)) {
675
- const combination = fileName.slice(VIRTUAL_PREFIX.length).split("/")[0] || "shared";
676
- return {
677
- id: `virtual:${combination}`,
678
- label: `\u5171\u4EAB\u865A\u62DF\u5305 ${combination}`,
679
- type: "virtual"
680
- };
681
- }
682
- const segments = fileName.split("/");
683
- const rootCandidate = segments[0] ?? "";
684
- if (rootCandidate && context.subPackageRoots.has(rootCandidate)) {
685
- const isIndependent = context.independentRoots.has(rootCandidate);
686
- return {
687
- id: rootCandidate,
688
- label: `${isIndependent ? "\u72EC\u7ACB\u5206\u5305" : "\u5206\u5305"} ${rootCandidate}`,
689
- type: isIndependent || origin === "independent" ? "independent" : "subPackage"
690
- };
691
- }
692
- return {
693
- id: "__main__",
694
- label: "\u4E3B\u5305",
695
- type: "main"
696
- };
639
+ if (fileName.startsWith(VIRTUAL_PREFIX)) {
640
+ const combination = fileName.slice(VIRTUAL_PREFIX.length).split("/")[0] || "shared";
641
+ return {
642
+ id: `virtual:${combination}`,
643
+ label: `共享虚拟包 ${combination}`,
644
+ type: "virtual"
645
+ };
646
+ }
647
+ const rootCandidate = fileName.split("/")[0] ?? "";
648
+ if (rootCandidate && context.subPackageRoots.has(rootCandidate)) {
649
+ const isIndependent = context.independentRoots.has(rootCandidate);
650
+ return {
651
+ id: rootCandidate,
652
+ label: `${isIndependent ? "独立分包" : "分包"} ${rootCandidate}`,
653
+ type: isIndependent || origin === "independent" ? "independent" : "subPackage"
654
+ };
655
+ }
656
+ return {
657
+ id: "__main__",
658
+ label: "主包",
659
+ type: "main"
660
+ };
697
661
  }
698
662
  function normalizeModuleId(id) {
699
- if (!id || id.includes(VIRTUAL_MODULE_INDICATOR)) {
700
- return void 0;
701
- }
702
- if (!path.isAbsolute(id)) {
703
- return void 0;
704
- }
705
- return path.normalize(id);
663
+ if (!id || id.includes(VIRTUAL_MODULE_INDICATOR)) return;
664
+ if (!posix.isAbsolute(id)) return;
665
+ return posix.normalize(id);
706
666
  }
707
667
  function resolveModuleSourceType(absoluteId, ctx) {
708
- const { configService } = ctx;
709
- const isNodeModule = absoluteId.includes("/node_modules/") || absoluteId.includes("\\node_modules\\");
710
- const pluginRoot = configService.absolutePluginRoot;
711
- const srcRoot = configService.absoluteSrcRoot;
712
- const inSrc = isPathInside(srcRoot, absoluteId);
713
- const inPlugin = pluginRoot ? isPathInside(pluginRoot, absoluteId) : false;
714
- let sourceType;
715
- if (isNodeModule) {
716
- sourceType = "node_modules";
717
- } else if (inSrc) {
718
- sourceType = "src";
719
- } else if (inPlugin) {
720
- sourceType = "plugin";
721
- } else {
722
- sourceType = "workspace";
723
- }
724
- return {
725
- source: configService.relativeAbsoluteSrcRoot(absoluteId),
726
- sourceType
727
- };
668
+ const { configService } = ctx;
669
+ const isNodeModule = absoluteId.includes("/node_modules/") || absoluteId.includes("\\node_modules\\");
670
+ const pluginRoot = configService.absolutePluginRoot;
671
+ const srcRoot = configService.absoluteSrcRoot;
672
+ const inSrc = isPathInside(srcRoot, absoluteId);
673
+ const inPlugin = pluginRoot ? isPathInside(pluginRoot, absoluteId) : false;
674
+ let sourceType;
675
+ if (isNodeModule) sourceType = "node_modules";
676
+ else if (inSrc) sourceType = "src";
677
+ else if (inPlugin) sourceType = "plugin";
678
+ else sourceType = "workspace";
679
+ return {
680
+ source: configService.relativeAbsoluteSrcRoot(absoluteId),
681
+ sourceType
682
+ };
728
683
  }
729
684
  function resolveAssetSource(fileName, ctx) {
730
- const { configService } = ctx;
731
- const normalized = path.normalize(fileName);
732
- const srcCandidate = path.resolve(configService.absoluteSrcRoot, normalized);
733
- if (isPathInside(configService.absoluteSrcRoot, srcCandidate)) {
734
- return {
735
- absolute: srcCandidate,
736
- source: configService.relativeAbsoluteSrcRoot(srcCandidate),
737
- sourceType: "src"
738
- };
739
- }
740
- const pluginRoot = configService.absolutePluginRoot;
741
- if (pluginRoot) {
742
- const pluginBase = path.basename(pluginRoot);
743
- if (normalized === pluginBase || normalized.startsWith(`${pluginBase}/`)) {
744
- const relative = normalized === pluginBase ? "" : normalized.slice(pluginBase.length + 1);
745
- const absolute = path.resolve(pluginRoot, relative);
746
- if (isPathInside(pluginRoot, absolute)) {
747
- return {
748
- absolute,
749
- source: configService.relativeAbsoluteSrcRoot(absolute),
750
- sourceType: "plugin"
751
- };
752
- }
753
- }
754
- }
755
- }
756
-
757
- // src/analyze/subpackages/registry.ts
758
- init_esm_shims();
685
+ const { configService } = ctx;
686
+ const normalized = posix.normalize(fileName);
687
+ const srcCandidate = posix.resolve(configService.absoluteSrcRoot, normalized);
688
+ if (isPathInside(configService.absoluteSrcRoot, srcCandidate)) return {
689
+ absolute: srcCandidate,
690
+ source: configService.relativeAbsoluteSrcRoot(srcCandidate),
691
+ sourceType: "src"
692
+ };
693
+ const pluginRoot = configService.absolutePluginRoot;
694
+ if (pluginRoot) {
695
+ const pluginBase = posix.basename(pluginRoot);
696
+ if (normalized === pluginBase || normalized.startsWith(`${pluginBase}/`)) {
697
+ const relative = normalized === pluginBase ? "" : normalized.slice(pluginBase.length + 1);
698
+ const absolute = posix.resolve(pluginRoot, relative);
699
+ if (isPathInside(pluginRoot, absolute)) return {
700
+ absolute,
701
+ source: configService.relativeAbsoluteSrcRoot(absolute),
702
+ sourceType: "plugin"
703
+ };
704
+ }
705
+ }
706
+ }
707
+ //#endregion
708
+ //#region src/analyze/subpackages/registry.ts
759
709
  function ensurePackage(packages, classification) {
760
- const existing = packages.get(classification.id);
761
- if (existing) {
762
- return existing;
763
- }
764
- const created = {
765
- ...classification,
766
- files: /* @__PURE__ */ new Map()
767
- };
768
- packages.set(classification.id, created);
769
- return created;
710
+ const existing = packages.get(classification.id);
711
+ if (existing) return existing;
712
+ const created = {
713
+ ...classification,
714
+ files: /* @__PURE__ */ new Map()
715
+ };
716
+ packages.set(classification.id, created);
717
+ return created;
770
718
  }
771
719
  function ensureModule(modules, id, source, sourceType) {
772
- const existing = modules.get(id);
773
- if (existing) {
774
- return existing;
775
- }
776
- const created = {
777
- id,
778
- source,
779
- sourceType,
780
- packages: /* @__PURE__ */ new Map()
781
- };
782
- modules.set(id, created);
783
- return created;
720
+ const existing = modules.get(id);
721
+ if (existing) return existing;
722
+ const created = {
723
+ id,
724
+ source,
725
+ sourceType,
726
+ packages: /* @__PURE__ */ new Map()
727
+ };
728
+ modules.set(id, created);
729
+ return created;
784
730
  }
785
731
  function registerModuleInPackage(modules, moduleId, source, sourceType, packageId, fileName) {
786
- const moduleEntry = ensureModule(modules, moduleId, source, sourceType);
787
- const files = moduleEntry.packages.get(packageId) ?? /* @__PURE__ */ new Set();
788
- files.add(fileName);
789
- moduleEntry.packages.set(packageId, files);
732
+ const moduleEntry = ensureModule(modules, moduleId, source, sourceType);
733
+ const files = moduleEntry.packages.get(packageId) ?? /* @__PURE__ */ new Set();
734
+ files.add(fileName);
735
+ moduleEntry.packages.set(packageId, files);
790
736
  }
791
-
792
- // src/analyze/subpackages/output.ts
737
+ //#endregion
738
+ //#region src/analyze/subpackages/output.ts
793
739
  function getAssetSize(asset) {
794
- if (typeof asset.source === "string") {
795
- return Buffer.byteLength(asset.source, "utf8");
796
- }
797
- if (asset.source instanceof Uint8Array) {
798
- return asset.source.byteLength;
799
- }
740
+ if (typeof asset.source === "string") return Buffer.byteLength(asset.source, "utf8");
741
+ if (asset.source instanceof Uint8Array) return asset.source.byteLength;
800
742
  }
801
743
  function processChunk(chunk, origin, ctx, classifierContext, packages, modules) {
802
- const classification = classifyPackage(chunk.fileName, origin, classifierContext);
803
- const packageEntry = ensurePackage(packages, classification);
804
- const chunkEntry = {
805
- file: chunk.fileName,
806
- type: "chunk",
807
- from: origin,
808
- size: typeof chunk.code === "string" ? Buffer.byteLength(chunk.code, "utf8") : void 0,
809
- isEntry: chunk.isEntry,
810
- modules: []
811
- };
812
- const moduleEntries = Object.entries(chunk.modules ?? {});
813
- for (const [rawModuleId, info] of moduleEntries) {
814
- const absoluteId = normalizeModuleId(rawModuleId);
815
- if (!absoluteId) {
816
- continue;
817
- }
818
- const { source, sourceType } = resolveModuleSourceType(absoluteId, ctx);
819
- const moduleEntry = {
820
- id: absoluteId,
821
- source,
822
- sourceType,
823
- bytes: info?.renderedLength
824
- };
825
- if (typeof info?.code === "string") {
826
- moduleEntry.originalBytes = Buffer.byteLength(info.code, "utf8");
827
- }
828
- chunkEntry.modules.push(moduleEntry);
829
- registerModuleInPackage(
830
- modules,
831
- absoluteId,
832
- source,
833
- sourceType,
834
- classification.id,
835
- chunk.fileName
836
- );
837
- }
838
- if (chunkEntry.modules) {
839
- chunkEntry.modules.sort((a, b) => a.source.localeCompare(b.source));
840
- }
841
- packageEntry.files.set(chunk.fileName, chunkEntry);
744
+ const classification = classifyPackage(chunk.fileName, origin, classifierContext);
745
+ const packageEntry = ensurePackage(packages, classification);
746
+ const chunkEntry = {
747
+ file: chunk.fileName,
748
+ type: "chunk",
749
+ from: origin,
750
+ size: typeof chunk.code === "string" ? Buffer.byteLength(chunk.code, "utf8") : void 0,
751
+ isEntry: chunk.isEntry,
752
+ modules: []
753
+ };
754
+ const moduleEntries = Object.entries(chunk.modules ?? {});
755
+ for (const [rawModuleId, info] of moduleEntries) {
756
+ const absoluteId = normalizeModuleId(rawModuleId);
757
+ if (!absoluteId) continue;
758
+ const { source, sourceType } = resolveModuleSourceType(absoluteId, ctx);
759
+ const moduleEntry = {
760
+ id: absoluteId,
761
+ source,
762
+ sourceType,
763
+ bytes: info?.renderedLength
764
+ };
765
+ if (typeof info?.code === "string") moduleEntry.originalBytes = Buffer.byteLength(info.code, "utf8");
766
+ chunkEntry.modules.push(moduleEntry);
767
+ registerModuleInPackage(modules, absoluteId, source, sourceType, classification.id, chunk.fileName);
768
+ }
769
+ if (chunkEntry.modules) chunkEntry.modules.sort((a, b) => a.source.localeCompare(b.source));
770
+ packageEntry.files.set(chunk.fileName, chunkEntry);
842
771
  }
843
772
  function processAsset(asset, origin, ctx, classifierContext, packages, modules) {
844
- const classification = classifyPackage(asset.fileName, origin, classifierContext);
845
- const packageEntry = ensurePackage(packages, classification);
846
- const entry = {
847
- file: asset.fileName,
848
- type: "asset",
849
- from: origin,
850
- size: getAssetSize(asset)
851
- };
852
- const assetSource = resolveAssetSource(asset.fileName, ctx);
853
- if (assetSource) {
854
- entry.source = assetSource.source;
855
- registerModuleInPackage(
856
- modules,
857
- assetSource.absolute,
858
- assetSource.source,
859
- assetSource.sourceType,
860
- classification.id,
861
- asset.fileName
862
- );
863
- }
864
- packageEntry.files.set(asset.fileName, entry);
773
+ const classification = classifyPackage(asset.fileName, origin, classifierContext);
774
+ const packageEntry = ensurePackage(packages, classification);
775
+ const entry = {
776
+ file: asset.fileName,
777
+ type: "asset",
778
+ from: origin,
779
+ size: getAssetSize(asset)
780
+ };
781
+ const assetSource = resolveAssetSource(asset.fileName, ctx);
782
+ if (assetSource) {
783
+ entry.source = assetSource.source;
784
+ registerModuleInPackage(modules, assetSource.absolute, assetSource.source, assetSource.sourceType, classification.id, asset.fileName);
785
+ }
786
+ packageEntry.files.set(asset.fileName, entry);
865
787
  }
866
788
  function processOutput(output, origin, ctx, classifierContext, packages, modules) {
867
- if (!output) {
868
- return;
869
- }
870
- for (const item of output.output ?? []) {
871
- if (item.type === "chunk") {
872
- processChunk(item, origin, ctx, classifierContext, packages, modules);
873
- } else if (item.type === "asset") {
874
- processAsset(item, origin, ctx, classifierContext, packages, modules);
875
- }
876
- }
877
- }
878
-
879
- // src/analyze/subpackages/summary.ts
880
- init_esm_shims();
881
- import { posix as path2 } from "pathe";
789
+ if (!output) return;
790
+ for (const item of output.output ?? []) if (item.type === "chunk") processChunk(item, origin, ctx, classifierContext, packages, modules);
791
+ else if (item.type === "asset") processAsset(item, origin, ctx, classifierContext, packages, modules);
792
+ }
793
+ //#endregion
794
+ //#region src/analyze/subpackages/summary.ts
882
795
  function toArray(value) {
883
- return Array.from(value);
796
+ return Array.from(value);
884
797
  }
885
798
  function summarizePackages(packages) {
886
- const order = {
887
- main: 0,
888
- subPackage: 1,
889
- independent: 2,
890
- virtual: 3
891
- };
892
- const reports = toArray(packages.values()).map((pkg) => {
893
- const files = toArray(pkg.files.values());
894
- files.sort((a, b) => a.file.localeCompare(b.file));
895
- return {
896
- id: pkg.id,
897
- label: pkg.label,
898
- type: pkg.type,
899
- files
900
- };
901
- });
902
- reports.sort((a, b) => {
903
- const delta = order[a.type] - order[b.type];
904
- if (delta !== 0) {
905
- return delta;
906
- }
907
- if (a.id === "__main__") {
908
- return -1;
909
- }
910
- if (b.id === "__main__") {
911
- return 1;
912
- }
913
- return a.id.localeCompare(b.id);
914
- });
915
- return reports;
799
+ const order = {
800
+ main: 0,
801
+ subPackage: 1,
802
+ independent: 2,
803
+ virtual: 3
804
+ };
805
+ const reports = toArray(packages.values()).map((pkg) => {
806
+ const files = toArray(pkg.files.values());
807
+ files.sort((a, b) => a.file.localeCompare(b.file));
808
+ return {
809
+ id: pkg.id,
810
+ label: pkg.label,
811
+ type: pkg.type,
812
+ files
813
+ };
814
+ });
815
+ reports.sort((a, b) => {
816
+ const delta = order[a.type] - order[b.type];
817
+ if (delta !== 0) return delta;
818
+ if (a.id === "__main__") return -1;
819
+ if (b.id === "__main__") return 1;
820
+ return a.id.localeCompare(b.id);
821
+ });
822
+ return reports;
916
823
  }
917
824
  function summarizeModules(modules) {
918
- const usage = toArray(modules.values()).map((module) => {
919
- const packages = toArray(module.packages.entries()).map(([packageId, files]) => {
920
- const sortedFiles = toArray(files).sort((a, b) => a.localeCompare(b));
921
- return {
922
- packageId,
923
- files: sortedFiles
924
- };
925
- }).sort((a, b) => {
926
- if (a.packageId === b.packageId) {
927
- return 0;
928
- }
929
- if (a.packageId === "__main__") {
930
- return -1;
931
- }
932
- if (b.packageId === "__main__") {
933
- return 1;
934
- }
935
- return a.packageId.localeCompare(b.packageId);
936
- });
937
- return {
938
- id: module.id,
939
- source: module.source,
940
- sourceType: module.sourceType,
941
- packages
942
- };
943
- });
944
- usage.sort((a, b) => a.source.localeCompare(b.source));
945
- return usage;
825
+ const usage = toArray(modules.values()).map((module) => {
826
+ const packages = toArray(module.packages.entries()).map(([packageId, files]) => {
827
+ return {
828
+ packageId,
829
+ files: toArray(files).sort((a, b) => a.localeCompare(b))
830
+ };
831
+ }).sort((a, b) => {
832
+ if (a.packageId === b.packageId) return 0;
833
+ if (a.packageId === "__main__") return -1;
834
+ if (b.packageId === "__main__") return 1;
835
+ return a.packageId.localeCompare(b.packageId);
836
+ });
837
+ return {
838
+ id: module.id,
839
+ source: module.source,
840
+ sourceType: module.sourceType,
841
+ packages
842
+ };
843
+ });
844
+ usage.sort((a, b) => a.source.localeCompare(b.source));
845
+ return usage;
946
846
  }
947
847
  function expandVirtualModulePlacements(modules, packages, context) {
948
- for (const moduleEntry of modules.values()) {
949
- const virtualEntries = Array.from(moduleEntry.packages.entries()).filter(([packageId]) => packageId.startsWith("virtual:"));
950
- if (!virtualEntries.length) {
951
- continue;
952
- }
953
- const virtualFileBases = /* @__PURE__ */ new Map();
954
- for (const [virtualPackageId, files] of virtualEntries) {
955
- const combination = virtualPackageId.slice("virtual:".length);
956
- if (!combination) {
957
- continue;
958
- }
959
- const segments = combination.split(/[_+]/).map((segment) => segment.trim()).filter(Boolean);
960
- if (!segments.length) {
961
- continue;
962
- }
963
- let matchingBases = virtualFileBases.get(virtualPackageId);
964
- if (!matchingBases) {
965
- matchingBases = Array.from(files).map((file) => path2.basename(file));
966
- virtualFileBases.set(virtualPackageId, matchingBases);
967
- }
968
- for (const root of segments) {
969
- if (!context.subPackageRoots.has(root)) {
970
- continue;
971
- }
972
- const targetPackage = packages.get(root);
973
- if (!targetPackage) {
974
- continue;
975
- }
976
- const moduleFiles = moduleEntry.packages.get(root) ?? /* @__PURE__ */ new Set();
977
- const targetFiles = Array.from(targetPackage.files.values()).filter((fileEntry) => {
978
- if (!matchingBases?.length) {
979
- return true;
980
- }
981
- const base = path2.basename(fileEntry.file);
982
- return matchingBases.includes(base);
983
- }).map((fileEntry) => fileEntry.file);
984
- if (targetFiles.length === 0) {
985
- const fallback = targetPackage.files.values().next().value;
986
- if (fallback) {
987
- moduleFiles.add(fallback.file);
988
- }
989
- } else {
990
- for (const fileName of targetFiles) {
991
- moduleFiles.add(fileName);
992
- }
993
- }
994
- if (moduleFiles.size > 0) {
995
- moduleEntry.packages.set(root, moduleFiles);
996
- }
997
- }
998
- }
999
- }
848
+ for (const moduleEntry of modules.values()) {
849
+ const virtualEntries = Array.from(moduleEntry.packages.entries()).filter(([packageId]) => packageId.startsWith("virtual:"));
850
+ if (!virtualEntries.length) continue;
851
+ const virtualFileBases = /* @__PURE__ */ new Map();
852
+ for (const [virtualPackageId, files] of virtualEntries) {
853
+ const combination = virtualPackageId.slice(8);
854
+ if (!combination) continue;
855
+ const segments = combination.split(/[_+]/).map((segment) => segment.trim()).filter(Boolean);
856
+ if (!segments.length) continue;
857
+ let matchingBases = virtualFileBases.get(virtualPackageId);
858
+ if (!matchingBases) {
859
+ matchingBases = Array.from(files).map((file) => posix.basename(file));
860
+ virtualFileBases.set(virtualPackageId, matchingBases);
861
+ }
862
+ for (const root of segments) {
863
+ if (!context.subPackageRoots.has(root)) continue;
864
+ const targetPackage = packages.get(root);
865
+ if (!targetPackage) continue;
866
+ const moduleFiles = moduleEntry.packages.get(root) ?? /* @__PURE__ */ new Set();
867
+ const targetFiles = Array.from(targetPackage.files.values()).filter((fileEntry) => {
868
+ if (!matchingBases?.length) return true;
869
+ const base = posix.basename(fileEntry.file);
870
+ return matchingBases.includes(base);
871
+ }).map((fileEntry) => fileEntry.file);
872
+ if (targetFiles.length === 0) {
873
+ const fallback = targetPackage.files.values().next().value;
874
+ if (fallback) moduleFiles.add(fallback.file);
875
+ } else for (const fileName of targetFiles) moduleFiles.add(fileName);
876
+ if (moduleFiles.size > 0) moduleEntry.packages.set(root, moduleFiles);
877
+ }
878
+ }
879
+ }
1000
880
  }
1001
881
  function summarizeSubPackages(metas) {
1002
- const descriptors = metas.map((meta) => {
1003
- const root = meta.subPackage.root ?? "";
1004
- return {
1005
- root,
1006
- independent: Boolean(meta.subPackage.independent),
1007
- name: meta.subPackage.name
1008
- };
1009
- }).filter((descriptor) => descriptor.root);
1010
- descriptors.sort((a, b) => a.root.localeCompare(b.root));
1011
- return descriptors;
1012
- }
1013
-
1014
- // src/analyze/subpackages/index.ts
882
+ const descriptors = metas.map((meta) => {
883
+ return {
884
+ root: meta.subPackage.root ?? "",
885
+ independent: Boolean(meta.subPackage.independent),
886
+ name: meta.subPackage.name
887
+ };
888
+ }).filter((descriptor) => descriptor.root);
889
+ descriptors.sort((a, b) => a.root.localeCompare(b.root));
890
+ return descriptors;
891
+ }
892
+ //#endregion
893
+ //#region src/analyze/subpackages/index.ts
1015
894
  async function analyzeSubpackages(ctx) {
1016
- const { configService, scanService, buildService } = ctx;
1017
- if (!configService || !scanService || !buildService) {
1018
- throw new Error("analyzeSubpackages \u9700\u8981\u5148\u521D\u59CB\u5316 configService\u3001scanService \u548C buildService\u3002");
1019
- }
1020
- await scanService.loadAppEntry();
1021
- const subPackageMetas = scanService.loadSubPackages();
1022
- const subPackageRoots = /* @__PURE__ */ new Set();
1023
- const independentRoots = /* @__PURE__ */ new Set();
1024
- for (const meta of subPackageMetas) {
1025
- const root = meta.subPackage.root;
1026
- if (root) {
1027
- subPackageRoots.add(root);
1028
- if (meta.subPackage.independent) {
1029
- independentRoots.add(root);
1030
- }
1031
- }
1032
- }
1033
- const classifierContext = {
1034
- subPackageRoots,
1035
- independentRoots
1036
- };
1037
- const analysisConfig = configService.merge(
1038
- void 0,
1039
- createSharedBuildConfig(configService, scanService),
1040
- {
1041
- build: {
1042
- write: false,
1043
- watch: null
1044
- }
1045
- }
1046
- );
1047
- const mainResult = await build(analysisConfig);
1048
- const mainOutputs = Array.isArray(mainResult) ? mainResult : [mainResult];
1049
- const packages = /* @__PURE__ */ new Map();
1050
- const modules = /* @__PURE__ */ new Map();
1051
- for (const output of mainOutputs) {
1052
- processOutput(output, "main", ctx, classifierContext, packages, modules);
1053
- }
1054
- for (const root of independentRoots) {
1055
- const output = buildService.getIndependentOutput(root);
1056
- processOutput(output, "independent", ctx, classifierContext, packages, modules);
1057
- }
1058
- expandVirtualModulePlacements(modules, packages, classifierContext);
1059
- return {
1060
- packages: summarizePackages(packages),
1061
- modules: summarizeModules(modules),
1062
- subPackages: summarizeSubPackages(subPackageMetas)
1063
- };
1064
- }
1065
-
1066
- // src/cli/analyze/dashboard.ts
1067
- init_esm_shims();
1068
- import process2 from "process";
1069
- import fs2 from "fs-extra";
1070
- import { createServer } from "vite";
1071
-
1072
- // src/packagePaths.ts
1073
- init_esm_shims();
1074
- import { dirname, join } from "path";
1075
- import { fileURLToPath } from "url";
1076
- import fs from "fs-extra";
895
+ const { configService, scanService, buildService } = ctx;
896
+ if (!configService || !scanService || !buildService) throw new Error("analyzeSubpackages 需要先初始化 configService、scanService 和 buildService。");
897
+ await scanService.loadAppEntry();
898
+ const subPackageMetas = scanService.loadSubPackages();
899
+ const subPackageRoots = /* @__PURE__ */ new Set();
900
+ const independentRoots = /* @__PURE__ */ new Set();
901
+ for (const meta of subPackageMetas) {
902
+ const root = meta.subPackage.root;
903
+ if (root) {
904
+ subPackageRoots.add(root);
905
+ if (meta.subPackage.independent) independentRoots.add(root);
906
+ }
907
+ }
908
+ const classifierContext = {
909
+ subPackageRoots,
910
+ independentRoots
911
+ };
912
+ const mainResult = await build(configService.merge(void 0, createSharedBuildConfig(configService, scanService), { build: {
913
+ write: false,
914
+ watch: null
915
+ } }));
916
+ const mainOutputs = Array.isArray(mainResult) ? mainResult : [mainResult];
917
+ const packages = /* @__PURE__ */ new Map();
918
+ const modules = /* @__PURE__ */ new Map();
919
+ for (const output of mainOutputs) processOutput(output, "main", ctx, classifierContext, packages, modules);
920
+ for (const root of independentRoots) processOutput(buildService.getIndependentOutput(root), "independent", ctx, classifierContext, packages, modules);
921
+ expandVirtualModulePlacements(modules, packages, classifierContext);
922
+ return {
923
+ packages: summarizePackages(packages),
924
+ modules: summarizeModules(modules),
925
+ subPackages: summarizeSubPackages(subPackageMetas)
926
+ };
927
+ }
928
+ //#endregion
929
+ //#region src/packagePaths.ts
1077
930
  function findPackageRoot(from) {
1078
- let current = from;
1079
- while (true) {
1080
- if (fs.existsSync(join(current, "package.json"))) {
1081
- return current;
1082
- }
1083
- const parent = dirname(current);
1084
- if (parent === current) {
1085
- break;
1086
- }
1087
- current = parent;
1088
- }
1089
- throw new Error("\u65E0\u6CD5\u5B9A\u4F4D weapp-vite \u5305\u6839\u76EE\u5F55\uFF0C\u8BF7\u68C0\u67E5\u5B89\u88C5\u8DEF\u5F84\u3002");
1090
- }
1091
- var CURRENT_DIR = dirname(fileURLToPath(import.meta.url));
1092
- var PACKAGE_ROOT = findPackageRoot(CURRENT_DIR);
1093
- var ANALYZE_DASHBOARD_ROOT = join(PACKAGE_ROOT, "modules/analyze-dashboard");
1094
-
1095
- // src/cli/analyze/dashboard.ts
1096
- var ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_ANALYZE_RESULT__";
931
+ let current = from;
932
+ while (true) {
933
+ if (fs.existsSync(join(current, "package.json"))) return current;
934
+ const parent = dirname(current);
935
+ if (parent === current) break;
936
+ current = parent;
937
+ }
938
+ throw new Error("无法定位 weapp-vite 包根目录,请检查安装路径。");
939
+ }
940
+ const ANALYZE_DASHBOARD_ROOT = join(findPackageRoot(dirname(fileURLToPath(import.meta.url))), "modules/analyze-dashboard");
941
+ //#endregion
942
+ //#region src/cli/analyze/dashboard.ts
943
+ const ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_ANALYZE_RESULT__";
1097
944
  function resolveDashboardRoot() {
1098
- if (fs2.existsSync(ANALYZE_DASHBOARD_ROOT)) {
1099
- return {
1100
- root: ANALYZE_DASHBOARD_ROOT
1101
- };
1102
- }
1103
- throw new Error(
1104
- "[weapp-vite analyze] \u672A\u627E\u5230\u4EEA\u8868\u76D8\u4EA7\u7269\uFF0C\u8BF7\u5148\u6267\u884C `pnpm --filter weapp-vite run build:dashboard` \u751F\u6210\u3002"
1105
- );
945
+ if (fs.existsSync(ANALYZE_DASHBOARD_ROOT)) return { root: ANALYZE_DASHBOARD_ROOT };
946
+ throw new Error("[weapp-vite analyze] 未找到仪表盘产物,请先执行 `pnpm --filter weapp-vite run build:dashboard` 生成。");
1106
947
  }
1107
948
  function createAnalyzeHtmlPlugin(state, onServerInstance) {
1108
- return {
1109
- name: "weapp-vite-analyze-html",
1110
- transformIndexHtml(html) {
1111
- return {
1112
- html,
1113
- tags: [
1114
- {
1115
- tag: "script",
1116
- children: `window.${ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.current)}`,
1117
- injectTo: "head-prepend"
1118
- }
1119
- ]
1120
- };
1121
- },
1122
- configureServer(server) {
1123
- onServerInstance(server);
1124
- }
1125
- };
949
+ return {
950
+ name: "weapp-vite-analyze-html",
951
+ transformIndexHtml(html) {
952
+ return {
953
+ html,
954
+ tags: [{
955
+ tag: "script",
956
+ children: `window.${ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.current)}`,
957
+ injectTo: "head-prepend"
958
+ }]
959
+ };
960
+ },
961
+ configureServer(server) {
962
+ onServerInstance(server);
963
+ }
964
+ };
1126
965
  }
1127
966
  async function waitForServerExit(server) {
1128
- let resolved = false;
1129
- const cleanup = async () => {
1130
- if (resolved) {
1131
- return;
1132
- }
1133
- resolved = true;
1134
- try {
1135
- await server.close();
1136
- } catch (error) {
1137
- default2.error(error);
1138
- }
1139
- };
1140
- const signals = ["SIGINT", "SIGTERM"];
1141
- await new Promise((resolvePromise) => {
1142
- const resolveOnce = async () => {
1143
- await cleanup();
1144
- signals.forEach((signal) => {
1145
- process2.removeListener(signal, resolveOnce);
1146
- });
1147
- resolvePromise();
1148
- };
1149
- signals.forEach((signal) => {
1150
- process2.once(signal, resolveOnce);
1151
- });
1152
- server.httpServer?.once("close", resolveOnce);
1153
- });
967
+ let resolved = false;
968
+ const cleanup = async () => {
969
+ if (resolved) return;
970
+ resolved = true;
971
+ try {
972
+ await server.close();
973
+ } catch (error) {
974
+ logger_default.error(error);
975
+ }
976
+ };
977
+ const signals = ["SIGINT", "SIGTERM"];
978
+ await new Promise((resolvePromise) => {
979
+ const resolveOnce = async () => {
980
+ await cleanup();
981
+ signals.forEach((signal) => {
982
+ process$1.removeListener(signal, resolveOnce);
983
+ });
984
+ resolvePromise();
985
+ };
986
+ signals.forEach((signal) => {
987
+ process$1.once(signal, resolveOnce);
988
+ });
989
+ server.httpServer?.once("close", resolveOnce);
990
+ });
1154
991
  }
1155
992
  async function startAnalyzeDashboard(result, options) {
1156
- const { root } = resolveDashboardRoot();
1157
- const state = { current: result };
1158
- let serverRef;
1159
- const plugins = [
1160
- createAnalyzeHtmlPlugin(state, (server2) => {
1161
- serverRef = server2;
1162
- })
1163
- ];
1164
- const server = await createServer({
1165
- root,
1166
- clearScreen: false,
1167
- appType: "spa",
1168
- publicDir: false,
1169
- plugins,
1170
- server: {
1171
- host: "127.0.0.1",
1172
- port: 0
1173
- },
1174
- logLevel: "error"
1175
- });
1176
- await server.listen();
1177
- serverRef ??= server;
1178
- server.printUrls();
1179
- const urls = (() => {
1180
- const resolved = server.resolvedUrls;
1181
- if (!resolved) {
1182
- return [];
1183
- }
1184
- return [
1185
- ...resolved.local ?? [],
1186
- ...resolved.network ?? []
1187
- ];
1188
- })();
1189
- const waitPromise = waitForServerExit(server);
1190
- if (serverRef?.ws) {
1191
- serverRef.ws.send({
1192
- type: "custom",
1193
- event: "weapp-analyze:update",
1194
- data: state.current
1195
- });
1196
- }
1197
- const handle = {
1198
- async update(nextResult) {
1199
- state.current = nextResult;
1200
- if (serverRef) {
1201
- serverRef.ws.send({
1202
- type: "custom",
1203
- event: "weapp-analyze:update",
1204
- data: nextResult
1205
- });
1206
- }
1207
- },
1208
- waitForExit: () => waitPromise,
1209
- close: async () => {
1210
- await server.close();
1211
- },
1212
- urls
1213
- };
1214
- if (options?.watch) {
1215
- default2.info("\u5206\u6790\u4EEA\u8868\u76D8\u5DF2\u542F\u52A8\uFF08\u5B9E\u65F6\u6A21\u5F0F\uFF09\uFF0C\u6309 Ctrl+C \u9000\u51FA\u3002");
1216
- for (const url of handle.urls) {
1217
- default2.info(`\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8\uFF1A${url}`);
1218
- }
1219
- void waitPromise;
1220
- return handle;
1221
- }
1222
- default2.info("\u5206\u6790\u4EEA\u8868\u76D8\u5DF2\u542F\u52A8\uFF08\u9759\u6001\u6A21\u5F0F\uFF09\uFF0C\u6309 Ctrl+C \u9000\u51FA\u3002");
1223
- for (const url of handle.urls) {
1224
- default2.info(`\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8\uFF1A${url}`);
1225
- }
1226
- await waitPromise;
1227
- }
1228
-
1229
- // src/cli/options.ts
1230
- init_esm_shims();
993
+ const { root } = resolveDashboardRoot();
994
+ const state = { current: result };
995
+ let serverRef;
996
+ const server = await createServer({
997
+ root,
998
+ clearScreen: false,
999
+ appType: "spa",
1000
+ publicDir: false,
1001
+ plugins: [createAnalyzeHtmlPlugin(state, (server) => {
1002
+ serverRef = server;
1003
+ })],
1004
+ server: {
1005
+ host: "127.0.0.1",
1006
+ port: 0
1007
+ },
1008
+ logLevel: "error"
1009
+ });
1010
+ await server.listen();
1011
+ serverRef ??= server;
1012
+ server.printUrls();
1013
+ const urls = (() => {
1014
+ const resolved = server.resolvedUrls;
1015
+ if (!resolved) return [];
1016
+ return [...resolved.local ?? [], ...resolved.network ?? []];
1017
+ })();
1018
+ const waitPromise = waitForServerExit(server);
1019
+ if (serverRef?.ws) serverRef.ws.send({
1020
+ type: "custom",
1021
+ event: "weapp-analyze:update",
1022
+ data: state.current
1023
+ });
1024
+ const handle = {
1025
+ async update(nextResult) {
1026
+ state.current = nextResult;
1027
+ if (serverRef) serverRef.ws.send({
1028
+ type: "custom",
1029
+ event: "weapp-analyze:update",
1030
+ data: nextResult
1031
+ });
1032
+ },
1033
+ waitForExit: () => waitPromise,
1034
+ close: async () => {
1035
+ await server.close();
1036
+ },
1037
+ urls
1038
+ };
1039
+ if (options?.watch) {
1040
+ logger_default.info("分析仪表盘已启动(实时模式),按 Ctrl+C 退出。");
1041
+ for (const url of handle.urls) logger_default.info(`分包分析仪表盘:${url}`);
1042
+ return handle;
1043
+ }
1044
+ logger_default.info("分析仪表盘已启动(静态模式),按 Ctrl+C 退出。");
1045
+ for (const url of handle.urls) logger_default.info(`分包分析仪表盘:${url}`);
1046
+ await waitPromise;
1047
+ }
1048
+ //#endregion
1049
+ //#region src/cli/options.ts
1231
1050
  function filterDuplicateOptions(options) {
1232
- for (const [key, value] of Object.entries(options)) {
1233
- if (Array.isArray(value)) {
1234
- options[key] = value[value.length - 1];
1235
- }
1236
- }
1051
+ for (const [key, value] of Object.entries(options)) if (Array.isArray(value)) options[key] = value[value.length - 1];
1237
1052
  }
1238
1053
  function resolveConfigFile(options) {
1239
- if (typeof options.config === "string") {
1240
- return options.config;
1241
- }
1242
- if (typeof options.c === "string") {
1243
- return options.c;
1244
- }
1054
+ if (typeof options.config === "string") return options.config;
1055
+ if (typeof options.c === "string") return options.c;
1245
1056
  }
1246
1057
  function convertBase(value) {
1247
- if (value === 0) {
1248
- return "";
1249
- }
1250
- return value;
1058
+ if (value === 0) return "";
1059
+ return value;
1251
1060
  }
1252
1061
  function coerceBooleanOption(value) {
1253
- if (value === void 0) {
1254
- return void 0;
1255
- }
1256
- if (typeof value === "boolean") {
1257
- return value;
1258
- }
1259
- if (typeof value === "string") {
1260
- const normalized = value.trim().toLowerCase();
1261
- if (normalized === "") {
1262
- return true;
1263
- }
1264
- if (normalized === "false" || normalized === "0" || normalized === "off" || normalized === "no") {
1265
- return false;
1266
- }
1267
- if (normalized === "true" || normalized === "1" || normalized === "on" || normalized === "yes") {
1268
- return true;
1269
- }
1270
- return true;
1271
- }
1272
- if (typeof value === "number") {
1273
- return value !== 0;
1274
- }
1275
- return Boolean(value);
1276
- }
1277
-
1278
- // src/cli/runtime.ts
1279
- init_esm_shims();
1062
+ if (value === void 0) return;
1063
+ if (typeof value === "boolean") return value;
1064
+ if (typeof value === "string") {
1065
+ const normalized = value.trim().toLowerCase();
1066
+ if (normalized === "") return true;
1067
+ if (normalized === "false" || normalized === "0" || normalized === "off" || normalized === "no") return false;
1068
+ if (normalized === "true" || normalized === "1" || normalized === "on" || normalized === "yes") return true;
1069
+ return true;
1070
+ }
1071
+ if (typeof value === "number") return value !== 0;
1072
+ return Boolean(value);
1073
+ }
1074
+ //#endregion
1075
+ //#region src/cli/runtime.ts
1280
1076
  function logRuntimeTarget(targets, options = {}) {
1281
- if (options.silent) {
1282
- return;
1283
- }
1284
- if (targets.label === "config") {
1285
- const resolvedPlatform = targets.mpPlatform ?? options.resolvedConfigPlatform;
1286
- if (resolvedPlatform) {
1287
- default2.info(`\u76EE\u6807\u5E73\u53F0\uFF1A${colors.green(resolvedPlatform)}`);
1288
- return;
1289
- }
1290
- default2.info(`\u76EE\u6807\u5E73\u53F0\uFF1A\u4F7F\u7528\u914D\u7F6E\u6587\u4EF6\u4E2D\u7684 ${colors.bold(colors.green("weapp.platform"))}`);
1291
- return;
1292
- }
1293
- default2.info(`\u76EE\u6807\u5E73\u53F0\uFF1A${colors.green(targets.label)}`);
1077
+ if (options.silent) return;
1078
+ if (targets.label === "config") {
1079
+ const resolvedPlatform = targets.mpPlatform ?? options.resolvedConfigPlatform;
1080
+ if (resolvedPlatform) {
1081
+ logger_default.info(`目标平台:${colors.green(resolvedPlatform)}`);
1082
+ return;
1083
+ }
1084
+ logger_default.info(`目标平台:使用配置文件中的 ${colors.bold(colors.green("weapp.platform"))}`);
1085
+ return;
1086
+ }
1087
+ logger_default.info(`目标平台:${colors.green(targets.label)}`);
1294
1088
  }
1295
1089
  function resolveRuntimeTargets(options) {
1296
- const rawPlatform = typeof options.platform === "string" ? options.platform : typeof options.p === "string" ? options.p : void 0;
1297
- if (!rawPlatform) {
1298
- return {
1299
- runMini: true,
1300
- runWeb: false,
1301
- mpPlatform: void 0,
1302
- label: "config",
1303
- rawPlatform
1304
- };
1305
- }
1306
- const normalized = normalizeMiniPlatform(rawPlatform);
1307
- if (!normalized) {
1308
- return {
1309
- runMini: true,
1310
- runWeb: false,
1311
- mpPlatform: DEFAULT_MP_PLATFORM,
1312
- label: DEFAULT_MP_PLATFORM,
1313
- rawPlatform
1314
- };
1315
- }
1316
- if (normalized === "h5" || normalized === "web") {
1317
- return {
1318
- runMini: false,
1319
- runWeb: true,
1320
- mpPlatform: void 0,
1321
- label: normalized === "h5" ? "h5" : "web",
1322
- rawPlatform
1323
- };
1324
- }
1325
- const mpPlatform = resolveMiniPlatform(normalized);
1326
- if (mpPlatform) {
1327
- return {
1328
- runMini: true,
1329
- runWeb: false,
1330
- mpPlatform,
1331
- label: mpPlatform,
1332
- rawPlatform
1333
- };
1334
- }
1335
- default2.warn(`\u672A\u8BC6\u522B\u7684\u5E73\u53F0 "${colors.yellow(rawPlatform)}"\uFF0C\u5DF2\u56DE\u9000\u5230 ${colors.green(DEFAULT_MP_PLATFORM)}`);
1336
- return {
1337
- runMini: true,
1338
- runWeb: false,
1339
- mpPlatform: DEFAULT_MP_PLATFORM,
1340
- label: DEFAULT_MP_PLATFORM,
1341
- rawPlatform
1342
- };
1090
+ const rawPlatform = typeof options.platform === "string" ? options.platform : typeof options.p === "string" ? options.p : void 0;
1091
+ if (!rawPlatform) return {
1092
+ runMini: true,
1093
+ runWeb: false,
1094
+ mpPlatform: void 0,
1095
+ label: "config",
1096
+ rawPlatform
1097
+ };
1098
+ const normalized = normalizeMiniPlatform(rawPlatform);
1099
+ if (!normalized) return {
1100
+ runMini: true,
1101
+ runWeb: false,
1102
+ mpPlatform: DEFAULT_MP_PLATFORM,
1103
+ label: DEFAULT_MP_PLATFORM,
1104
+ rawPlatform
1105
+ };
1106
+ if (normalized === "h5" || normalized === "web") return {
1107
+ runMini: false,
1108
+ runWeb: true,
1109
+ mpPlatform: void 0,
1110
+ label: normalized === "h5" ? "h5" : "web",
1111
+ rawPlatform
1112
+ };
1113
+ const mpPlatform = resolveMiniPlatform(normalized);
1114
+ if (mpPlatform) return {
1115
+ runMini: true,
1116
+ runWeb: false,
1117
+ mpPlatform,
1118
+ label: mpPlatform,
1119
+ rawPlatform
1120
+ };
1121
+ logger_default.warn(`未识别的平台 "${colors.yellow(rawPlatform)}",已回退到 ${colors.green(DEFAULT_MP_PLATFORM)}`);
1122
+ return {
1123
+ runMini: true,
1124
+ runWeb: false,
1125
+ mpPlatform: DEFAULT_MP_PLATFORM,
1126
+ label: DEFAULT_MP_PLATFORM,
1127
+ rawPlatform
1128
+ };
1343
1129
  }
1344
1130
  function createInlineConfig(mpPlatform) {
1345
- if (!mpPlatform) {
1346
- return void 0;
1347
- }
1348
- return {
1349
- weapp: {
1350
- platform: mpPlatform
1351
- }
1352
- };
1353
- }
1354
-
1355
- // src/cli/commands/analyze.ts
1131
+ if (!mpPlatform) return;
1132
+ return { weapp: { platform: mpPlatform } };
1133
+ }
1134
+ //#endregion
1135
+ //#region src/cli/commands/analyze.ts
1356
1136
  function normalizeDisplayPath(value) {
1357
- return value || ".";
1137
+ return value || ".";
1358
1138
  }
1359
1139
  function getDefaultWebAnalyzeScopes() {
1360
- return {
1361
- supported: [
1362
- "weapp.web \u914D\u7F6E\u89E3\u6790\uFF08enable/root/srcDir/outDir\uFF09",
1363
- "runtime.executionMode \u9759\u6001\u89E3\u6790\uFF08compat/safe/strict\uFF09",
1364
- "JSON \u62A5\u544A\u8F93\u51FA\uFF08--json/--output\uFF09"
1365
- ],
1366
- unsupported: [
1367
- "\u5206\u5305\u4EA7\u7269\u4F53\u79EF\u5206\u6790\uFF08\u4EC5\u5C0F\u7A0B\u5E8F\uFF09",
1368
- "\u6E90\u7801\u6A21\u5757\u5305\u4F53\u6620\u5C04\uFF08\u4EC5\u5C0F\u7A0B\u5E8F\uFF09",
1369
- "\u5206\u6790\u4EEA\u8868\u76D8\uFF08dashboard\uFF09"
1370
- ]
1371
- };
1140
+ return {
1141
+ supported: [
1142
+ "weapp.web 配置解析(enable/root/srcDir/outDir",
1143
+ "runtime.executionMode 静态解析(compat/safe/strict",
1144
+ "JSON 报告输出(--json/--output"
1145
+ ],
1146
+ unsupported: [
1147
+ "分包产物体积分析(仅小程序)",
1148
+ "源码模块包体映射(仅小程序)",
1149
+ "分析仪表盘(dashboard)"
1150
+ ]
1151
+ };
1372
1152
  }
1373
1153
  function createWebAnalyzeResult(configService, options) {
1374
- const webConfig = configService.weappWebConfig;
1375
- const executionMode = webConfig?.pluginOptions.runtime?.executionMode ?? "compat";
1376
- const scope = getDefaultWebAnalyzeScopes();
1377
- const limitations = [
1378
- "\u5F53\u524D\u4EC5\u63D0\u4F9B\u9759\u6001\u914D\u7F6E\u5206\u6790\uFF0C\u4E0D\u6267\u884C Web \u4EA7\u7269\u626B\u63CF\u3002"
1379
- ];
1380
- if (!webConfig?.enabled) {
1381
- limitations.push("\u672A\u68C0\u6D4B\u5230\u542F\u7528\u7684 weapp.web \u914D\u7F6E\u3002");
1382
- }
1383
- return {
1384
- runtime: "web",
1385
- platform: options.platform,
1386
- mode: configService.mode,
1387
- generatedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
1388
- experimental: true,
1389
- configFile: configService.configFilePath ? normalizeDisplayPath(configService.relativeCwd(configService.configFilePath)) : void 0,
1390
- web: {
1391
- enabled: Boolean(webConfig?.enabled),
1392
- root: webConfig?.root ? normalizeDisplayPath(configService.relativeCwd(webConfig.root)) : void 0,
1393
- srcDir: webConfig?.srcDir,
1394
- outDir: webConfig?.outDir ? normalizeDisplayPath(configService.relativeCwd(webConfig.outDir)) : void 0,
1395
- executionMode
1396
- },
1397
- supportedScopes: scope.supported,
1398
- unsupportedScopes: scope.unsupported,
1399
- limitations
1400
- };
1154
+ const webConfig = configService.weappWebConfig;
1155
+ const executionMode = webConfig?.pluginOptions.runtime?.executionMode ?? "compat";
1156
+ const scope = getDefaultWebAnalyzeScopes();
1157
+ const limitations = ["当前仅提供静态配置分析,不执行 Web 产物扫描。"];
1158
+ if (!webConfig?.enabled) limitations.push("未检测到启用的 weapp.web 配置。");
1159
+ return {
1160
+ runtime: "web",
1161
+ platform: options.platform,
1162
+ mode: configService.mode,
1163
+ generatedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
1164
+ experimental: true,
1165
+ configFile: configService.configFilePath ? normalizeDisplayPath(configService.relativeCwd(configService.configFilePath)) : void 0,
1166
+ web: {
1167
+ enabled: Boolean(webConfig?.enabled),
1168
+ root: webConfig?.root ? normalizeDisplayPath(configService.relativeCwd(webConfig.root)) : void 0,
1169
+ srcDir: webConfig?.srcDir,
1170
+ outDir: webConfig?.outDir ? normalizeDisplayPath(configService.relativeCwd(webConfig.outDir)) : void 0,
1171
+ executionMode
1172
+ },
1173
+ supportedScopes: scope.supported,
1174
+ unsupportedScopes: scope.unsupported,
1175
+ limitations
1176
+ };
1401
1177
  }
1402
1178
  function printAnalysisSummary(result) {
1403
- const packageLabelMap = /* @__PURE__ */ new Map();
1404
- const packageModuleSet = /* @__PURE__ */ new Map();
1405
- for (const pkg of result.packages) {
1406
- packageLabelMap.set(pkg.id, pkg.label);
1407
- }
1408
- for (const module of result.modules) {
1409
- for (const pkgRef of module.packages) {
1410
- const set = packageModuleSet.get(pkgRef.packageId) ?? /* @__PURE__ */ new Set();
1411
- set.add(module.id);
1412
- packageModuleSet.set(pkgRef.packageId, set);
1413
- }
1414
- }
1415
- default2.success("\u5206\u5305\u5206\u6790\u5B8C\u6210");
1416
- for (const pkg of result.packages) {
1417
- const chunkCount = pkg.files.filter((file) => file.type === "chunk").length;
1418
- const assetCount = pkg.files.length - chunkCount;
1419
- const moduleCount = packageModuleSet.get(pkg.id)?.size ?? 0;
1420
- default2.info(`- ${pkg.label}\uFF1A${chunkCount} \u4E2A\u6A21\u5757\u4EA7\u7269\uFF0C${assetCount} \u4E2A\u8D44\u6E90\uFF0C\u8986\u76D6 ${moduleCount} \u4E2A\u6E90\u7801\u6A21\u5757`);
1421
- }
1422
- if (result.subPackages.length > 0) {
1423
- default2.info("\u5206\u5305\u914D\u7F6E\uFF1A");
1424
- for (const descriptor of result.subPackages) {
1425
- const segments = [descriptor.root];
1426
- if (descriptor.name) {
1427
- segments.push(`\u522B\u540D\uFF1A${descriptor.name}`);
1428
- }
1429
- if (descriptor.independent) {
1430
- segments.push("\u72EC\u7ACB\u6784\u5EFA");
1431
- }
1432
- default2.info(`- ${segments.join("\uFF0C")}`);
1433
- }
1434
- }
1435
- const duplicates = result.modules.filter((module) => module.packages.length > 1);
1436
- if (duplicates.length === 0) {
1437
- default2.info("\u672A\u68C0\u6D4B\u5230\u8DE8\u5305\u590D\u7528\u7684\u6E90\u7801\u6A21\u5757\u3002");
1438
- return;
1439
- }
1440
- default2.info(`\u8DE8\u5305\u590D\u7528/\u590D\u5236\u6E90\u7801\u5171 ${duplicates.length} \u9879\uFF1A`);
1441
- const limit = 10;
1442
- const entries = duplicates.slice(0, limit);
1443
- for (const module of entries) {
1444
- const placements = module.packages.map((pkgRef) => {
1445
- const label = packageLabelMap.get(pkgRef.packageId) ?? pkgRef.packageId;
1446
- return `${label} \u2192 ${pkgRef.files.join(", ")}`;
1447
- }).join("\uFF1B");
1448
- default2.info(`- ${module.source} (${module.sourceType})\uFF1A${placements}`);
1449
- }
1450
- if (duplicates.length > limit) {
1451
- default2.info(`- \u2026\u5176\u4F59 ${duplicates.length - limit} \u9879\u8BF7\u4F7F\u7528 ${colors.bold(colors.green("weapp-vite analyze --json"))} \u67E5\u770B`);
1452
- }
1179
+ const packageLabelMap = /* @__PURE__ */ new Map();
1180
+ const packageModuleSet = /* @__PURE__ */ new Map();
1181
+ for (const pkg of result.packages) packageLabelMap.set(pkg.id, pkg.label);
1182
+ for (const module of result.modules) for (const pkgRef of module.packages) {
1183
+ const set = packageModuleSet.get(pkgRef.packageId) ?? /* @__PURE__ */ new Set();
1184
+ set.add(module.id);
1185
+ packageModuleSet.set(pkgRef.packageId, set);
1186
+ }
1187
+ logger_default.success("分包分析完成");
1188
+ for (const pkg of result.packages) {
1189
+ const chunkCount = pkg.files.filter((file) => file.type === "chunk").length;
1190
+ const assetCount = pkg.files.length - chunkCount;
1191
+ const moduleCount = packageModuleSet.get(pkg.id)?.size ?? 0;
1192
+ logger_default.info(`- ${pkg.label}:${chunkCount} 个模块产物,${assetCount} 个资源,覆盖 ${moduleCount} 个源码模块`);
1193
+ }
1194
+ if (result.subPackages.length > 0) {
1195
+ logger_default.info("分包配置:");
1196
+ for (const descriptor of result.subPackages) {
1197
+ const segments = [descriptor.root];
1198
+ if (descriptor.name) segments.push(`别名:${descriptor.name}`);
1199
+ if (descriptor.independent) segments.push("独立构建");
1200
+ logger_default.info(`- ${segments.join(",")}`);
1201
+ }
1202
+ }
1203
+ const duplicates = result.modules.filter((module) => module.packages.length > 1);
1204
+ if (duplicates.length === 0) {
1205
+ logger_default.info("未检测到跨包复用的源码模块。");
1206
+ return;
1207
+ }
1208
+ logger_default.info(`跨包复用/复制源码共 ${duplicates.length} 项:`);
1209
+ const limit = 10;
1210
+ const entries = duplicates.slice(0, limit);
1211
+ for (const module of entries) {
1212
+ const placements = module.packages.map((pkgRef) => {
1213
+ return `${packageLabelMap.get(pkgRef.packageId) ?? pkgRef.packageId} → ${pkgRef.files.join(", ")}`;
1214
+ }).join(";");
1215
+ logger_default.info(`- ${module.source} (${module.sourceType}):${placements}`);
1216
+ }
1217
+ if (duplicates.length > limit) logger_default.info(`- …其余 ${duplicates.length - limit} 项请使用 ${colors.bold(colors.green("weapp-vite analyze --json"))} 查看`);
1453
1218
  }
1454
1219
  function printWebAnalysisSummary(result) {
1455
- default2.success("Web \u9759\u6001\u5206\u6790\u5B8C\u6210");
1456
- default2.info(`- \u914D\u7F6E\u72B6\u6001\uFF1A${result.web.enabled ? "\u5DF2\u542F\u7528 weapp.web" : "\u672A\u542F\u7528 weapp.web"}`);
1457
- if (result.web.enabled) {
1458
- default2.info(`- root\uFF1A${result.web.root ?? "."}`);
1459
- default2.info(`- srcDir\uFF1A${result.web.srcDir ?? "."}`);
1460
- default2.info(`- outDir\uFF1A${result.web.outDir ?? "dist/web"}`);
1461
- }
1462
- default2.info(`- executionMode\uFF1A${result.web.executionMode}`);
1463
- default2.info(`- \u652F\u6301\u8303\u56F4\uFF1A${result.supportedScopes.join("\uFF1B")}`);
1464
- default2.warn(`- \u672A\u652F\u6301\u8303\u56F4\uFF1A${result.unsupportedScopes.join("\uFF1B")}`);
1465
- for (const limitation of result.limitations) {
1466
- default2.warn(`- \u9650\u5236\uFF1A${limitation}`);
1467
- }
1220
+ logger_default.success("Web 静态分析完成");
1221
+ logger_default.info(`- 配置状态:${result.web.enabled ? "已启用 weapp.web" : "未启用 weapp.web"}`);
1222
+ if (result.web.enabled) {
1223
+ logger_default.info(`- root:${result.web.root ?? "."}`);
1224
+ logger_default.info(`- srcDir:${result.web.srcDir ?? "."}`);
1225
+ logger_default.info(`- outDir:${result.web.outDir ?? "dist/web"}`);
1226
+ }
1227
+ logger_default.info(`- executionMode:${result.web.executionMode}`);
1228
+ logger_default.info(`- 支持范围:${result.supportedScopes.join("")}`);
1229
+ logger_default.warn(`- 未支持范围:${result.unsupportedScopes.join("")}`);
1230
+ for (const limitation of result.limitations) logger_default.warn(`- 限制:${limitation}`);
1468
1231
  }
1469
1232
  async function writeAnalyzeResult(result, outputOption, configService) {
1470
- if (!outputOption) {
1471
- return void 0;
1472
- }
1473
- const baseDir = configService.cwd;
1474
- const resolvedOutputPath = path3.isAbsolute(outputOption) ? outputOption : path3.resolve(baseDir, outputOption);
1475
- await fs3.ensureDir(path3.dirname(resolvedOutputPath));
1476
- await fs3.writeFile(resolvedOutputPath, `${JSON.stringify(result, null, 2)}
1477
- `, "utf8");
1478
- const relativeOutput = configService.relativeCwd(resolvedOutputPath);
1479
- default2.success(`\u5206\u6790\u7ED3\u679C\u5DF2\u5199\u5165 ${colors.green(relativeOutput)}`);
1480
- return resolvedOutputPath;
1481
- }
1482
- function registerAnalyzeCommand(cli2) {
1483
- cli2.command("analyze [root]", "analyze \u4E24\u7AEF\u5305\u4F53\u4E0E\u6E90\u7801\u6620\u5C04").option("--json", `[boolean] \u8F93\u51FA JSON \u7ED3\u679C`).option("--output <file>", `[string] \u5C06\u5206\u6790\u7ED3\u679C\u5199\u5165\u6307\u5B9A\u6587\u4EF6\uFF08JSON\uFF09`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).action(async (root, options) => {
1484
- filterDuplicateOptions(options);
1485
- const configFile = resolveConfigFile(options);
1486
- const outputJson = coerceBooleanOption(options.json);
1487
- const targets = resolveRuntimeTargets(options);
1488
- const inlineConfig = createInlineConfig(targets.mpPlatform);
1489
- try {
1490
- const ctx = await createCompilerContext({
1491
- cwd: root,
1492
- mode: options.mode ?? "production",
1493
- configFile,
1494
- inlineConfig,
1495
- cliPlatform: targets.rawPlatform,
1496
- projectConfigPath: options.projectConfig
1497
- });
1498
- logRuntimeTarget(targets, {
1499
- silent: outputJson,
1500
- resolvedConfigPlatform: ctx.configService.platform
1501
- });
1502
- const outputOption = typeof options.output === "string" ? options.output.trim() : "";
1503
- if (targets.runWeb) {
1504
- const webResult = createWebAnalyzeResult(ctx.configService, {
1505
- platform: targets.label === "web" ? "web" : "h5"
1506
- });
1507
- const writtenPath2 = await writeAnalyzeResult(webResult, outputOption, ctx.configService);
1508
- if (outputJson) {
1509
- if (!writtenPath2) {
1510
- process3.stdout.write(`${JSON.stringify(webResult, null, 2)}
1511
- `);
1512
- }
1513
- } else {
1514
- printWebAnalysisSummary(webResult);
1515
- }
1516
- return;
1517
- }
1518
- if (!targets.runMini) {
1519
- default2.warn("\u5F53\u524D\u547D\u4EE4\u4E0D\u652F\u6301\u8BE5\u5E73\u53F0\uFF0C\u8BF7\u901A\u8FC7 --platform weapp \u6216 --platform h5 \u6307\u5B9A\u76EE\u6807\u3002");
1520
- return;
1521
- }
1522
- const result = await analyzeSubpackages(ctx);
1523
- const writtenPath = await writeAnalyzeResult(result, outputOption, ctx.configService);
1524
- if (outputJson) {
1525
- if (!writtenPath) {
1526
- process3.stdout.write(`${JSON.stringify(result, null, 2)}
1527
- `);
1528
- }
1529
- } else {
1530
- printAnalysisSummary(result);
1531
- await startAnalyzeDashboard(result);
1532
- }
1533
- } catch (error) {
1534
- default2.error(error);
1535
- process3.exitCode = 1;
1536
- }
1537
- });
1538
- }
1539
-
1540
- // src/cli/commands/build.ts
1541
- init_esm_shims();
1542
- import process4 from "process";
1543
-
1544
- // src/cli/logBuildAppFinish.ts
1545
- init_esm_shims();
1546
-
1547
- // ../../node_modules/.pnpm/package-manager-detector@1.6.0/node_modules/package-manager-detector/dist/commands.mjs
1548
- init_esm_shims();
1233
+ if (!outputOption) return;
1234
+ const baseDir = configService.cwd;
1235
+ const resolvedOutputPath = path.isAbsolute(outputOption) ? outputOption : path.resolve(baseDir, outputOption);
1236
+ await fs.ensureDir(path.dirname(resolvedOutputPath));
1237
+ await fs.writeFile(resolvedOutputPath, `${JSON.stringify(result, null, 2)}\n`, "utf8");
1238
+ const relativeOutput = configService.relativeCwd(resolvedOutputPath);
1239
+ logger_default.success(`分析结果已写入 ${colors.green(relativeOutput)}`);
1240
+ return resolvedOutputPath;
1241
+ }
1242
+ function registerAnalyzeCommand(cli) {
1243
+ cli.command("analyze [root]", "analyze 两端包体与源码映射").option("--json", `[boolean] 输出 JSON 结果`).option("--output <file>", `[string] 将分析结果写入指定文件(JSON)`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).action(async (root, options) => {
1244
+ filterDuplicateOptions(options);
1245
+ const configFile = resolveConfigFile(options);
1246
+ const outputJson = coerceBooleanOption(options.json);
1247
+ const targets = resolveRuntimeTargets(options);
1248
+ const inlineConfig = createInlineConfig(targets.mpPlatform);
1249
+ try {
1250
+ const ctx = await createCompilerContext({
1251
+ cwd: root,
1252
+ mode: options.mode ?? "production",
1253
+ configFile,
1254
+ inlineConfig,
1255
+ cliPlatform: targets.rawPlatform,
1256
+ projectConfigPath: options.projectConfig
1257
+ });
1258
+ logRuntimeTarget(targets, {
1259
+ silent: outputJson,
1260
+ resolvedConfigPlatform: ctx.configService.platform
1261
+ });
1262
+ const outputOption = typeof options.output === "string" ? options.output.trim() : "";
1263
+ if (targets.runWeb) {
1264
+ const webResult = createWebAnalyzeResult(ctx.configService, { platform: targets.label === "web" ? "web" : "h5" });
1265
+ const writtenPath = await writeAnalyzeResult(webResult, outputOption, ctx.configService);
1266
+ if (outputJson) {
1267
+ if (!writtenPath) process$1.stdout.write(`${JSON.stringify(webResult, null, 2)}\n`);
1268
+ } else printWebAnalysisSummary(webResult);
1269
+ return;
1270
+ }
1271
+ if (!targets.runMini) {
1272
+ logger_default.warn("当前命令不支持该平台,请通过 --platform weapp 或 --platform h5 指定目标。");
1273
+ return;
1274
+ }
1275
+ const result = await analyzeSubpackages(ctx);
1276
+ const writtenPath = await writeAnalyzeResult(result, outputOption, ctx.configService);
1277
+ if (outputJson) {
1278
+ if (!writtenPath) process$1.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1279
+ } else {
1280
+ printAnalysisSummary(result);
1281
+ await startAnalyzeDashboard(result);
1282
+ }
1283
+ } catch (error) {
1284
+ logger_default.error(error);
1285
+ process$1.exitCode = 1;
1286
+ }
1287
+ });
1288
+ }
1289
+ //#endregion
1290
+ //#region ../../node_modules/.pnpm/package-manager-detector@1.6.0/node_modules/package-manager-detector/dist/commands.mjs
1549
1291
  function dashDashArg(agent, agentCommand) {
1550
- return (args) => {
1551
- if (args.length > 1) {
1552
- return [agent, agentCommand, args[0], "--", ...args.slice(1)];
1553
- } else {
1554
- return [agent, agentCommand, args[0]];
1555
- }
1556
- };
1292
+ return (args) => {
1293
+ if (args.length > 1) return [
1294
+ agent,
1295
+ agentCommand,
1296
+ args[0],
1297
+ "--",
1298
+ ...args.slice(1)
1299
+ ];
1300
+ else return [
1301
+ agent,
1302
+ agentCommand,
1303
+ args[0]
1304
+ ];
1305
+ };
1557
1306
  }
1558
1307
  function denoExecute() {
1559
- return (args) => {
1560
- return ["deno", "run", `npm:${args[0]}`, ...args.slice(1)];
1561
- };
1562
- }
1563
- var npm = {
1564
- "agent": ["npm", 0],
1565
- "run": dashDashArg("npm", "run"),
1566
- "install": ["npm", "i", 0],
1567
- "frozen": ["npm", "ci", 0],
1568
- "global": ["npm", "i", "-g", 0],
1569
- "add": ["npm", "i", 0],
1570
- "upgrade": ["npm", "update", 0],
1571
- "upgrade-interactive": null,
1572
- "dedupe": ["npm", "dedupe", 0],
1573
- "execute": ["npx", 0],
1574
- "execute-local": ["npx", 0],
1575
- "uninstall": ["npm", "uninstall", 0],
1576
- "global_uninstall": ["npm", "uninstall", "-g", 0]
1308
+ return (args) => {
1309
+ return [
1310
+ "deno",
1311
+ "run",
1312
+ `npm:${args[0]}`,
1313
+ ...args.slice(1)
1314
+ ];
1315
+ };
1316
+ }
1317
+ const npm = {
1318
+ "agent": ["npm", 0],
1319
+ "run": dashDashArg("npm", "run"),
1320
+ "install": [
1321
+ "npm",
1322
+ "i",
1323
+ 0
1324
+ ],
1325
+ "frozen": [
1326
+ "npm",
1327
+ "ci",
1328
+ 0
1329
+ ],
1330
+ "global": [
1331
+ "npm",
1332
+ "i",
1333
+ "-g",
1334
+ 0
1335
+ ],
1336
+ "add": [
1337
+ "npm",
1338
+ "i",
1339
+ 0
1340
+ ],
1341
+ "upgrade": [
1342
+ "npm",
1343
+ "update",
1344
+ 0
1345
+ ],
1346
+ "upgrade-interactive": null,
1347
+ "dedupe": [
1348
+ "npm",
1349
+ "dedupe",
1350
+ 0
1351
+ ],
1352
+ "execute": ["npx", 0],
1353
+ "execute-local": ["npx", 0],
1354
+ "uninstall": [
1355
+ "npm",
1356
+ "uninstall",
1357
+ 0
1358
+ ],
1359
+ "global_uninstall": [
1360
+ "npm",
1361
+ "uninstall",
1362
+ "-g",
1363
+ 0
1364
+ ]
1577
1365
  };
1578
- var yarn = {
1579
- "agent": ["yarn", 0],
1580
- "run": ["yarn", "run", 0],
1581
- "install": ["yarn", "install", 0],
1582
- "frozen": ["yarn", "install", "--frozen-lockfile", 0],
1583
- "global": ["yarn", "global", "add", 0],
1584
- "add": ["yarn", "add", 0],
1585
- "upgrade": ["yarn", "upgrade", 0],
1586
- "upgrade-interactive": ["yarn", "upgrade-interactive", 0],
1587
- "dedupe": null,
1588
- "execute": ["npx", 0],
1589
- "execute-local": dashDashArg("yarn", "exec"),
1590
- "uninstall": ["yarn", "remove", 0],
1591
- "global_uninstall": ["yarn", "global", "remove", 0]
1366
+ const yarn = {
1367
+ "agent": ["yarn", 0],
1368
+ "run": [
1369
+ "yarn",
1370
+ "run",
1371
+ 0
1372
+ ],
1373
+ "install": [
1374
+ "yarn",
1375
+ "install",
1376
+ 0
1377
+ ],
1378
+ "frozen": [
1379
+ "yarn",
1380
+ "install",
1381
+ "--frozen-lockfile",
1382
+ 0
1383
+ ],
1384
+ "global": [
1385
+ "yarn",
1386
+ "global",
1387
+ "add",
1388
+ 0
1389
+ ],
1390
+ "add": [
1391
+ "yarn",
1392
+ "add",
1393
+ 0
1394
+ ],
1395
+ "upgrade": [
1396
+ "yarn",
1397
+ "upgrade",
1398
+ 0
1399
+ ],
1400
+ "upgrade-interactive": [
1401
+ "yarn",
1402
+ "upgrade-interactive",
1403
+ 0
1404
+ ],
1405
+ "dedupe": null,
1406
+ "execute": ["npx", 0],
1407
+ "execute-local": dashDashArg("yarn", "exec"),
1408
+ "uninstall": [
1409
+ "yarn",
1410
+ "remove",
1411
+ 0
1412
+ ],
1413
+ "global_uninstall": [
1414
+ "yarn",
1415
+ "global",
1416
+ "remove",
1417
+ 0
1418
+ ]
1592
1419
  };
1593
- var yarnBerry = {
1594
- ...yarn,
1595
- "frozen": ["yarn", "install", "--immutable", 0],
1596
- "upgrade": ["yarn", "up", 0],
1597
- "upgrade-interactive": ["yarn", "up", "-i", 0],
1598
- "dedupe": ["yarn", "dedupe", 0],
1599
- "execute": ["yarn", "dlx", 0],
1600
- "execute-local": ["yarn", "exec", 0],
1601
- // Yarn 2+ removed 'global', see https://github.com/yarnpkg/berry/issues/821
1602
- "global": ["npm", "i", "-g", 0],
1603
- "global_uninstall": ["npm", "uninstall", "-g", 0]
1420
+ const yarnBerry = {
1421
+ ...yarn,
1422
+ "frozen": [
1423
+ "yarn",
1424
+ "install",
1425
+ "--immutable",
1426
+ 0
1427
+ ],
1428
+ "upgrade": [
1429
+ "yarn",
1430
+ "up",
1431
+ 0
1432
+ ],
1433
+ "upgrade-interactive": [
1434
+ "yarn",
1435
+ "up",
1436
+ "-i",
1437
+ 0
1438
+ ],
1439
+ "dedupe": [
1440
+ "yarn",
1441
+ "dedupe",
1442
+ 0
1443
+ ],
1444
+ "execute": [
1445
+ "yarn",
1446
+ "dlx",
1447
+ 0
1448
+ ],
1449
+ "execute-local": [
1450
+ "yarn",
1451
+ "exec",
1452
+ 0
1453
+ ],
1454
+ "global": [
1455
+ "npm",
1456
+ "i",
1457
+ "-g",
1458
+ 0
1459
+ ],
1460
+ "global_uninstall": [
1461
+ "npm",
1462
+ "uninstall",
1463
+ "-g",
1464
+ 0
1465
+ ]
1604
1466
  };
1605
- var pnpm = {
1606
- "agent": ["pnpm", 0],
1607
- "run": ["pnpm", "run", 0],
1608
- "install": ["pnpm", "i", 0],
1609
- "frozen": ["pnpm", "i", "--frozen-lockfile", 0],
1610
- "global": ["pnpm", "add", "-g", 0],
1611
- "add": ["pnpm", "add", 0],
1612
- "upgrade": ["pnpm", "update", 0],
1613
- "upgrade-interactive": ["pnpm", "update", "-i", 0],
1614
- "dedupe": ["pnpm", "dedupe", 0],
1615
- "execute": ["pnpm", "dlx", 0],
1616
- "execute-local": ["pnpm", "exec", 0],
1617
- "uninstall": ["pnpm", "remove", 0],
1618
- "global_uninstall": ["pnpm", "remove", "--global", 0]
1467
+ const pnpm = {
1468
+ "agent": ["pnpm", 0],
1469
+ "run": [
1470
+ "pnpm",
1471
+ "run",
1472
+ 0
1473
+ ],
1474
+ "install": [
1475
+ "pnpm",
1476
+ "i",
1477
+ 0
1478
+ ],
1479
+ "frozen": [
1480
+ "pnpm",
1481
+ "i",
1482
+ "--frozen-lockfile",
1483
+ 0
1484
+ ],
1485
+ "global": [
1486
+ "pnpm",
1487
+ "add",
1488
+ "-g",
1489
+ 0
1490
+ ],
1491
+ "add": [
1492
+ "pnpm",
1493
+ "add",
1494
+ 0
1495
+ ],
1496
+ "upgrade": [
1497
+ "pnpm",
1498
+ "update",
1499
+ 0
1500
+ ],
1501
+ "upgrade-interactive": [
1502
+ "pnpm",
1503
+ "update",
1504
+ "-i",
1505
+ 0
1506
+ ],
1507
+ "dedupe": [
1508
+ "pnpm",
1509
+ "dedupe",
1510
+ 0
1511
+ ],
1512
+ "execute": [
1513
+ "pnpm",
1514
+ "dlx",
1515
+ 0
1516
+ ],
1517
+ "execute-local": [
1518
+ "pnpm",
1519
+ "exec",
1520
+ 0
1521
+ ],
1522
+ "uninstall": [
1523
+ "pnpm",
1524
+ "remove",
1525
+ 0
1526
+ ],
1527
+ "global_uninstall": [
1528
+ "pnpm",
1529
+ "remove",
1530
+ "--global",
1531
+ 0
1532
+ ]
1619
1533
  };
1620
- var bun = {
1621
- "agent": ["bun", 0],
1622
- "run": ["bun", "run", 0],
1623
- "install": ["bun", "install", 0],
1624
- "frozen": ["bun", "install", "--frozen-lockfile", 0],
1625
- "global": ["bun", "add", "-g", 0],
1626
- "add": ["bun", "add", 0],
1627
- "upgrade": ["bun", "update", 0],
1628
- "upgrade-interactive": ["bun", "update", "-i", 0],
1629
- "dedupe": null,
1630
- "execute": ["bun", "x", 0],
1631
- "execute-local": ["bun", "x", 0],
1632
- "uninstall": ["bun", "remove", 0],
1633
- "global_uninstall": ["bun", "remove", "-g", 0]
1534
+ const bun = {
1535
+ "agent": ["bun", 0],
1536
+ "run": [
1537
+ "bun",
1538
+ "run",
1539
+ 0
1540
+ ],
1541
+ "install": [
1542
+ "bun",
1543
+ "install",
1544
+ 0
1545
+ ],
1546
+ "frozen": [
1547
+ "bun",
1548
+ "install",
1549
+ "--frozen-lockfile",
1550
+ 0
1551
+ ],
1552
+ "global": [
1553
+ "bun",
1554
+ "add",
1555
+ "-g",
1556
+ 0
1557
+ ],
1558
+ "add": [
1559
+ "bun",
1560
+ "add",
1561
+ 0
1562
+ ],
1563
+ "upgrade": [
1564
+ "bun",
1565
+ "update",
1566
+ 0
1567
+ ],
1568
+ "upgrade-interactive": [
1569
+ "bun",
1570
+ "update",
1571
+ "-i",
1572
+ 0
1573
+ ],
1574
+ "dedupe": null,
1575
+ "execute": [
1576
+ "bun",
1577
+ "x",
1578
+ 0
1579
+ ],
1580
+ "execute-local": [
1581
+ "bun",
1582
+ "x",
1583
+ 0
1584
+ ],
1585
+ "uninstall": [
1586
+ "bun",
1587
+ "remove",
1588
+ 0
1589
+ ],
1590
+ "global_uninstall": [
1591
+ "bun",
1592
+ "remove",
1593
+ "-g",
1594
+ 0
1595
+ ]
1634
1596
  };
1635
- var deno = {
1636
- "agent": ["deno", 0],
1637
- "run": ["deno", "task", 0],
1638
- "install": ["deno", "install", 0],
1639
- "frozen": ["deno", "install", "--frozen", 0],
1640
- "global": ["deno", "install", "-g", 0],
1641
- "add": ["deno", "add", 0],
1642
- "upgrade": ["deno", "outdated", "--update", 0],
1643
- "upgrade-interactive": ["deno", "outdated", "--update", 0],
1644
- "dedupe": null,
1645
- "execute": denoExecute(),
1646
- "execute-local": ["deno", "task", "--eval", 0],
1647
- "uninstall": ["deno", "remove", 0],
1648
- "global_uninstall": ["deno", "uninstall", "-g", 0]
1597
+ const deno = {
1598
+ "agent": ["deno", 0],
1599
+ "run": [
1600
+ "deno",
1601
+ "task",
1602
+ 0
1603
+ ],
1604
+ "install": [
1605
+ "deno",
1606
+ "install",
1607
+ 0
1608
+ ],
1609
+ "frozen": [
1610
+ "deno",
1611
+ "install",
1612
+ "--frozen",
1613
+ 0
1614
+ ],
1615
+ "global": [
1616
+ "deno",
1617
+ "install",
1618
+ "-g",
1619
+ 0
1620
+ ],
1621
+ "add": [
1622
+ "deno",
1623
+ "add",
1624
+ 0
1625
+ ],
1626
+ "upgrade": [
1627
+ "deno",
1628
+ "outdated",
1629
+ "--update",
1630
+ 0
1631
+ ],
1632
+ "upgrade-interactive": [
1633
+ "deno",
1634
+ "outdated",
1635
+ "--update",
1636
+ 0
1637
+ ],
1638
+ "dedupe": null,
1639
+ "execute": denoExecute(),
1640
+ "execute-local": [
1641
+ "deno",
1642
+ "task",
1643
+ "--eval",
1644
+ 0
1645
+ ],
1646
+ "uninstall": [
1647
+ "deno",
1648
+ "remove",
1649
+ 0
1650
+ ],
1651
+ "global_uninstall": [
1652
+ "deno",
1653
+ "uninstall",
1654
+ "-g",
1655
+ 0
1656
+ ]
1649
1657
  };
1650
- var COMMANDS = {
1651
- "npm": npm,
1652
- "yarn": yarn,
1653
- "yarn@berry": yarnBerry,
1654
- "pnpm": pnpm,
1655
- // pnpm v6.x or below
1656
- "pnpm@6": {
1657
- ...pnpm,
1658
- run: dashDashArg("pnpm", "run")
1659
- },
1660
- "bun": bun,
1661
- "deno": deno
1658
+ const COMMANDS = {
1659
+ "npm": npm,
1660
+ "yarn": yarn,
1661
+ "yarn@berry": yarnBerry,
1662
+ "pnpm": pnpm,
1663
+ "pnpm@6": {
1664
+ ...pnpm,
1665
+ run: dashDashArg("pnpm", "run")
1666
+ },
1667
+ "bun": bun,
1668
+ "deno": deno
1662
1669
  };
1663
1670
  function resolveCommand(agent, command, args) {
1664
- const value = COMMANDS[agent][command];
1665
- return constructCommand(value, args);
1671
+ const value = COMMANDS[agent][command];
1672
+ return constructCommand(value, args);
1666
1673
  }
1667
1674
  function constructCommand(value, args) {
1668
- if (value == null)
1669
- return null;
1670
- const list = typeof value === "function" ? value(args) : value.flatMap((v) => {
1671
- if (typeof v === "number")
1672
- return args;
1673
- return [v];
1674
- });
1675
- return {
1676
- command: list[0],
1677
- args: list.slice(1)
1678
- };
1679
- }
1680
-
1681
- // src/cli/logBuildAppFinish.ts
1682
- var logBuildAppFinishOnlyShowOnce = false;
1675
+ if (value == null) return null;
1676
+ const list = typeof value === "function" ? value(args) : value.flatMap((v) => {
1677
+ if (typeof v === "number") return args;
1678
+ return [v];
1679
+ });
1680
+ return {
1681
+ command: list[0],
1682
+ args: list.slice(1)
1683
+ };
1684
+ }
1685
+ //#endregion
1686
+ //#region src/cli/logBuildAppFinish.ts
1687
+ let logBuildAppFinishOnlyShowOnce = false;
1683
1688
  function logBuildAppFinish(configService, webServer, options = {}) {
1684
- if (logBuildAppFinishOnlyShowOnce) {
1685
- return;
1686
- }
1687
- const { skipMini = false, skipWeb = false } = options;
1688
- if (skipMini) {
1689
- if (webServer) {
1690
- const urls = webServer.resolvedUrls;
1691
- const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
1692
- if (candidates.length > 0) {
1693
- default2.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A");
1694
- for (const url of candidates) {
1695
- default2.info(` \u279C ${colors.cyan(url)}`);
1696
- }
1697
- } else {
1698
- default2.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1699
- }
1700
- } else {
1701
- default2.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1702
- }
1703
- logBuildAppFinishOnlyShowOnce = true;
1704
- return;
1705
- }
1706
- const { command, args } = resolveCommand(
1707
- configService.packageManager.agent,
1708
- "run",
1709
- ["open"]
1710
- ) ?? {
1711
- command: "npm",
1712
- args: ["run", "open"]
1713
- };
1714
- const devCommand = `${command} ${args.join(" ")}`;
1715
- default2.success("\u5E94\u7528\u6784\u5EFA\u5B8C\u6210\uFF01\u9884\u89C8\u65B9\u5F0F\uFF082 \u79CD\u9009\u5176\u4E00\u5373\u53EF\uFF09\uFF1A");
1716
- default2.info(`\u6267\u884C ${colors.bold(colors.green(devCommand))} \u53EF\u4EE5\u76F4\u63A5\u5728\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\u91CC\u6253\u5F00\u5F53\u524D\u5E94\u7528`);
1717
- const projectConfigFileName = getProjectConfigFileName(configService.platform);
1718
- default2.info(`\u6216\u624B\u52A8\u6253\u5F00\u5BF9\u5E94\u5E73\u53F0\u5F00\u53D1\u8005\u5DE5\u5177\uFF0C\u5BFC\u5165\u6839\u76EE\u5F55\uFF08${colors.green(projectConfigFileName)} \u6587\u4EF6\u6240\u5728\u76EE\u5F55\uFF09\uFF0C\u5373\u53EF\u9884\u89C8\u6548\u679C`);
1719
- if (!skipWeb && webServer) {
1720
- const urls = webServer.resolvedUrls;
1721
- const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
1722
- if (candidates.length > 0) {
1723
- default2.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A");
1724
- for (const url of candidates) {
1725
- default2.info(` \u279C ${colors.cyan(url)}`);
1726
- }
1727
- } else {
1728
- default2.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1729
- }
1730
- }
1731
- logBuildAppFinishOnlyShowOnce = true;
1732
- }
1733
-
1734
- // src/cli/logBuildPackageSizeReport.ts
1735
- init_esm_shims();
1736
- import { Buffer as Buffer2 } from "buffer";
1737
- var DEFAULT_PACKAGE_SIZE_WARNING_BYTES = 2 * 1024 * 1024;
1738
- var WINDOWS_SEPARATOR_RE = /\\/g;
1689
+ if (logBuildAppFinishOnlyShowOnce) return;
1690
+ const { skipMini = false, skipWeb = false } = options;
1691
+ if (skipMini) {
1692
+ if (webServer) {
1693
+ const urls = webServer.resolvedUrls;
1694
+ const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
1695
+ if (candidates.length > 0) {
1696
+ logger_default.success("Web 运行时已启动,浏览器访问:");
1697
+ for (const url of candidates) logger_default.info(` ➜ ${colors.cyan(url)}`);
1698
+ } else logger_default.success("Web 运行时已启动");
1699
+ } else logger_default.success("Web 运行时已启动");
1700
+ logBuildAppFinishOnlyShowOnce = true;
1701
+ return;
1702
+ }
1703
+ const { command, args } = resolveCommand(configService.packageManager.agent, "run", ["open"]) ?? {
1704
+ command: "npm",
1705
+ args: ["run", "open"]
1706
+ };
1707
+ const devCommand = `${command} ${args.join(" ")}`;
1708
+ logger_default.success("应用构建完成!预览方式(2 种选其一即可):");
1709
+ logger_default.info(`执行 ${colors.bold(colors.green(devCommand))} 可以直接在微信开发者工具里打开当前应用`);
1710
+ const projectConfigFileName = getProjectConfigFileName(configService.platform);
1711
+ logger_default.info(`或手动打开对应平台开发者工具,导入根目录(${colors.green(projectConfigFileName)} 文件所在目录),即可预览效果`);
1712
+ if (!skipWeb && webServer) {
1713
+ const urls = webServer.resolvedUrls;
1714
+ const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
1715
+ if (candidates.length > 0) {
1716
+ logger_default.success("Web 运行时已启动,浏览器访问:");
1717
+ for (const url of candidates) logger_default.info(` ➜ ${colors.cyan(url)}`);
1718
+ } else logger_default.success("Web 运行时已启动");
1719
+ }
1720
+ logBuildAppFinishOnlyShowOnce = true;
1721
+ }
1722
+ const WINDOWS_SEPARATOR_RE = /\\/g;
1739
1723
  function normalizeFileName(fileName) {
1740
- return fileName.replace(WINDOWS_SEPARATOR_RE, "/");
1724
+ return fileName.replace(WINDOWS_SEPARATOR_RE, "/");
1741
1725
  }
1742
1726
  function getOutputItemBytes(item) {
1743
- if (item.type === "chunk") {
1744
- return typeof item.code === "string" ? Buffer2.byteLength(item.code, "utf8") : 0;
1745
- }
1746
- if (typeof item.source === "string") {
1747
- return Buffer2.byteLength(item.source, "utf8");
1748
- }
1749
- if (item.source instanceof Uint8Array) {
1750
- return item.source.byteLength;
1751
- }
1752
- return 0;
1727
+ if (item.type === "chunk") return typeof item.code === "string" ? Buffer.byteLength(item.code, "utf8") : 0;
1728
+ if (typeof item.source === "string") return Buffer.byteLength(item.source, "utf8");
1729
+ if (item.source instanceof Uint8Array) return item.source.byteLength;
1730
+ return 0;
1753
1731
  }
1754
1732
  function resolveSubPackageRoot(fileName, roots) {
1755
- const normalized = normalizeFileName(fileName);
1756
- return roots.find((root) => normalized === root || normalized.startsWith(`${root}/`));
1733
+ const normalized = normalizeFileName(fileName);
1734
+ return roots.find((root) => normalized === root || normalized.startsWith(`${root}/`));
1757
1735
  }
1758
1736
  function collectPackageSizeReports(output, subPackageMap) {
1759
- const outputs = Array.isArray(output) ? output : [output];
1760
- const roots = [...subPackageMap?.keys() ?? []].filter(Boolean).sort((a, b) => b.length - a.length || a.localeCompare(b));
1761
- const packageBytes = /* @__PURE__ */ new Map([["__main__", 0]]);
1762
- for (const root of roots) {
1763
- packageBytes.set(root, 0);
1764
- }
1765
- for (const current of outputs) {
1766
- for (const item of current.output ?? []) {
1767
- const root = resolveSubPackageRoot(item.fileName, roots) ?? "__main__";
1768
- packageBytes.set(root, (packageBytes.get(root) ?? 0) + getOutputItemBytes(item));
1769
- }
1770
- }
1771
- const reports = [
1772
- {
1773
- root: "__main__",
1774
- label: "\u4E3B\u5305",
1775
- bytes: packageBytes.get("__main__") ?? 0
1776
- }
1777
- ];
1778
- for (const root of roots) {
1779
- const meta = subPackageMap?.get(root);
1780
- const isIndependent = Boolean(meta?.subPackage.independent);
1781
- reports.push({
1782
- root,
1783
- label: `${isIndependent ? "\u72EC\u7ACB\u5206\u5305" : "\u5206\u5305"} ${root}`,
1784
- bytes: packageBytes.get(root) ?? 0
1785
- });
1786
- }
1787
- return reports;
1737
+ const outputs = Array.isArray(output) ? output : [output];
1738
+ const roots = [...subPackageMap?.keys() ?? []].filter(Boolean).sort((a, b) => b.length - a.length || a.localeCompare(b));
1739
+ const packageBytes = new Map([["__main__", 0]]);
1740
+ for (const root of roots) packageBytes.set(root, 0);
1741
+ for (const current of outputs) for (const item of current.output ?? []) {
1742
+ const root = resolveSubPackageRoot(item.fileName, roots) ?? "__main__";
1743
+ packageBytes.set(root, (packageBytes.get(root) ?? 0) + getOutputItemBytes(item));
1744
+ }
1745
+ const reports = [{
1746
+ root: "__main__",
1747
+ label: "主包",
1748
+ bytes: packageBytes.get("__main__") ?? 0
1749
+ }];
1750
+ for (const root of roots) {
1751
+ const meta = subPackageMap?.get(root);
1752
+ const isIndependent = Boolean(meta?.subPackage.independent);
1753
+ reports.push({
1754
+ root,
1755
+ label: `${isIndependent ? "独立分包" : "分包"} ${root}`,
1756
+ bytes: packageBytes.get(root) ?? 0
1757
+ });
1758
+ }
1759
+ return reports;
1788
1760
  }
1789
1761
  function logBuildPackageSizeReport(options) {
1790
- const warningBytes = Number(options.warningBytes ?? DEFAULT_PACKAGE_SIZE_WARNING_BYTES);
1791
- const reports = collectPackageSizeReports(options.output, options.subPackageMap);
1792
- default2.success("\u4E3B\u5305/\u5206\u5305\u4F53\u79EF\u62A5\u544A\uFF1A");
1793
- for (const report of reports) {
1794
- default2.info(`${report.label}\uFF1A${formatBytes(report.bytes)}`);
1795
- }
1796
- const shouldWarn = Number.isFinite(warningBytes) && warningBytes > 0;
1797
- if (!shouldWarn) {
1798
- return;
1799
- }
1800
- for (const report of reports) {
1801
- if (report.bytes <= warningBytes) {
1802
- continue;
1803
- }
1804
- default2.warn(
1805
- `[\u5305\u4F53\u79EF] ${colors.yellow(report.label)} \u4F53\u79EF ${colors.yellow(formatBytes(report.bytes))}\uFF0C\u5DF2\u8D85\u8FC7\u9608\u503C ${colors.yellow(formatBytes(warningBytes))}\u3002`
1806
- );
1807
- }
1808
- }
1809
-
1810
- // src/cli/openIde.ts
1811
- init_esm_shims();
1812
- import path4 from "pathe";
1813
- import {
1814
- formatRetryHotkeyPrompt,
1815
- formatWechatIdeLoginRequiredError,
1816
- isWechatIdeLoginRequiredError,
1817
- parse,
1818
- waitForRetryKeypress
1819
- } from "weapp-ide-cli";
1762
+ const warningBytes = Number(options.warningBytes ?? 2097152);
1763
+ const reports = collectPackageSizeReports(options.output, options.subPackageMap);
1764
+ logger_default.success("主包/分包体积报告:");
1765
+ for (const report of reports) logger_default.info(`${report.label}:${formatBytes(report.bytes)}`);
1766
+ if (!(Number.isFinite(warningBytes) && warningBytes > 0)) return;
1767
+ for (const report of reports) {
1768
+ if (report.bytes <= warningBytes) continue;
1769
+ logger_default.warn(`[包体积] ${colors.yellow(report.label)} 体积 ${colors.yellow(formatBytes(report.bytes))},已超过阈值 ${colors.yellow(formatBytes(warningBytes))}。`);
1770
+ }
1771
+ }
1772
+ //#endregion
1773
+ //#region src/cli/openIde.ts
1820
1774
  async function openIde(platform, projectPath) {
1821
- const argv = ["open", "-p"];
1822
- if (projectPath) {
1823
- argv.push(projectPath);
1824
- }
1825
- if (platform === "alipay") {
1826
- argv.push("--platform", platform);
1827
- }
1828
- await runWechatIdeOpenWithRetry(argv);
1829
- }
1775
+ const argv = ["open", "-p"];
1776
+ if (projectPath) argv.push(projectPath);
1777
+ if (platform === "alipay") argv.push("--platform", platform);
1778
+ await runWechatIdeOpenWithRetry(argv);
1779
+ }
1780
+ /**
1781
+ * @description 执行 IDE 打开流程,并在登录失效时允许按键重试。
1782
+ */
1830
1783
  async function runWechatIdeOpenWithRetry(argv) {
1831
- let retrying = true;
1832
- while (retrying) {
1833
- try {
1834
- await parse(argv);
1835
- return;
1836
- } catch (error) {
1837
- if (!isWechatIdeLoginRequiredError(error)) {
1838
- default2.error(error);
1839
- return;
1840
- }
1841
- default2.error("\u68C0\u6D4B\u5230\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\u767B\u5F55\u72B6\u6001\u5931\u6548\uFF0C\u8BF7\u5148\u767B\u5F55\u540E\u91CD\u8BD5\u3002");
1842
- default2.warn(formatWechatIdeLoginRequiredError(error));
1843
- default2.info(formatRetryHotkeyPrompt());
1844
- const shouldRetry = await waitForRetryKeypress();
1845
- if (!shouldRetry) {
1846
- default2.warn("\u5DF2\u53D6\u6D88\u91CD\u8BD5\u3002\u5B8C\u6210\u767B\u5F55\u540E\u8BF7\u91CD\u65B0\u6267\u884C\u5F53\u524D\u547D\u4EE4\u3002");
1847
- retrying = false;
1848
- continue;
1849
- }
1850
- default2.info(colors.bold(colors.green("\u6B63\u5728\u91CD\u8BD5\u8FDE\u63A5\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177...")));
1851
- }
1852
- }
1853
- }
1784
+ let retrying = true;
1785
+ while (retrying) try {
1786
+ await parse(argv);
1787
+ return;
1788
+ } catch (error) {
1789
+ if (!isWechatIdeLoginRequiredError(error)) {
1790
+ logger_default.error(error);
1791
+ return;
1792
+ }
1793
+ logger_default.error("检测到微信开发者工具登录状态失效,请先登录后重试。");
1794
+ logger_default.warn(formatWechatIdeLoginRequiredError(error));
1795
+ logger_default.info(formatRetryHotkeyPrompt());
1796
+ if (!await waitForRetryKeypress()) {
1797
+ logger_default.warn("已取消重试。完成登录后请重新执行当前命令。");
1798
+ retrying = false;
1799
+ continue;
1800
+ }
1801
+ logger_default.info(colors.bold(colors.green("正在重试连接微信开发者工具...")));
1802
+ }
1803
+ }
1804
+ /**
1805
+ * @description 根据 mpDistRoot 推导 IDE 项目目录(目录内应包含 project/mini 配置)
1806
+ */
1854
1807
  function resolveIdeProjectPath(mpDistRoot) {
1855
- if (!mpDistRoot || !mpDistRoot.trim()) {
1856
- return void 0;
1857
- }
1858
- const parent = path4.dirname(mpDistRoot);
1859
- if (!parent || parent === ".") {
1860
- return void 0;
1861
- }
1862
- return parent;
1863
- }
1864
-
1865
- // src/cli/commands/build.ts
1866
- function registerBuildCommand(cli2) {
1867
- cli2.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'modules')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).option(
1868
- "--sourcemap [output]",
1869
- `[boolean | "inline" | "hidden"] output source maps for build (default: false)`
1870
- ).option(
1871
- "--minify [minifier]",
1872
- `[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)`
1873
- ).option(
1874
- "--emptyOutDir",
1875
- `[boolean] force empty outDir when it's outside of root`
1876
- ).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).option("--analyze", `[boolean] \u8F93\u51FA\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8`, { default: false }).action(async (root, options) => {
1877
- filterDuplicateOptions(options);
1878
- const configFile = resolveConfigFile(options);
1879
- const targets = resolveRuntimeTargets(options);
1880
- const inlineConfig = createInlineConfig(targets.mpPlatform);
1881
- const ctx = await createCompilerContext({
1882
- cwd: root,
1883
- mode: options.mode ?? "production",
1884
- configFile,
1885
- inlineConfig,
1886
- cliPlatform: targets.rawPlatform,
1887
- projectConfigPath: options.projectConfig
1888
- });
1889
- const { buildService, configService, webService } = ctx;
1890
- logRuntimeTarget(targets, { resolvedConfigPlatform: configService.platform });
1891
- const enableAnalyze = Boolean(options.analyze && targets.runMini);
1892
- let analyzeHandle;
1893
- if (targets.runMini) {
1894
- const output = await buildService.build(options);
1895
- if (!Array.isArray(output) && "output" in output) {
1896
- logBuildPackageSizeReport({
1897
- output,
1898
- subPackageMap: ctx.scanService?.subPackageMap,
1899
- warningBytes: configService.weappViteConfig.packageSizeWarningBytes
1900
- });
1901
- }
1902
- if (enableAnalyze) {
1903
- const analyzeResult = await analyzeSubpackages(ctx);
1904
- analyzeHandle = await startAnalyzeDashboard(analyzeResult, { watch: true }) ?? void 0;
1905
- }
1906
- }
1907
- const webConfig = configService.weappWebConfig;
1908
- if (targets.runWeb && webConfig?.enabled) {
1909
- try {
1910
- await webService?.build();
1911
- default2.success(`Web \u6784\u5EFA\u5B8C\u6210\uFF0C\u8F93\u51FA\u76EE\u5F55\uFF1A${colors.green(configService.relativeCwd(webConfig.outDir))}`);
1912
- } catch (error) {
1913
- default2.error(error);
1914
- throw error;
1915
- }
1916
- }
1917
- if (targets.runMini) {
1918
- logBuildAppFinish(configService, void 0, { skipWeb: !targets.runWeb });
1919
- }
1920
- if (options.open && targets.runMini) {
1921
- await openIde(configService.platform, resolveIdeProjectPath(configService.mpDistRoot));
1922
- }
1923
- if (analyzeHandle) {
1924
- await analyzeHandle.waitForExit();
1925
- }
1926
- ctx.watcherService?.closeAll();
1927
- terminateStaleSassEmbeddedProcess();
1928
- });
1808
+ if (!mpDistRoot || !mpDistRoot.trim()) return;
1809
+ const parent = path.dirname(mpDistRoot);
1810
+ if (!parent || parent === ".") return;
1811
+ return parent;
1812
+ }
1813
+ //#endregion
1814
+ //#region src/cli/commands/build.ts
1815
+ function registerBuildCommand(cli) {
1816
+ cli.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'modules')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).option("--sourcemap [output]", `[boolean | "inline" | "hidden"] output source maps for build (default: false)`).option("--minify [minifier]", "[boolean | \"terser\" | \"esbuild\"] enable/disable minification, or specify minifier to use (default: esbuild)").option("--emptyOutDir", `[boolean] force empty outDir when it's outside of root`).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).option("--analyze", `[boolean] 输出分包分析仪表盘`, { default: false }).action(async (root, options) => {
1817
+ filterDuplicateOptions(options);
1818
+ const configFile = resolveConfigFile(options);
1819
+ const targets = resolveRuntimeTargets(options);
1820
+ const inlineConfig = createInlineConfig(targets.mpPlatform);
1821
+ const ctx = await createCompilerContext({
1822
+ cwd: root,
1823
+ mode: options.mode ?? "production",
1824
+ configFile,
1825
+ inlineConfig,
1826
+ cliPlatform: targets.rawPlatform,
1827
+ projectConfigPath: options.projectConfig
1828
+ });
1829
+ const { buildService, configService, webService } = ctx;
1830
+ logRuntimeTarget(targets, { resolvedConfigPlatform: configService.platform });
1831
+ const enableAnalyze = Boolean(options.analyze && targets.runMini);
1832
+ let analyzeHandle;
1833
+ if (targets.runMini) {
1834
+ const output = await buildService.build(options);
1835
+ if (!Array.isArray(output) && "output" in output) logBuildPackageSizeReport({
1836
+ output,
1837
+ subPackageMap: ctx.scanService?.subPackageMap,
1838
+ warningBytes: configService.weappViteConfig.packageSizeWarningBytes
1839
+ });
1840
+ if (enableAnalyze) analyzeHandle = await startAnalyzeDashboard(await analyzeSubpackages(ctx), { watch: true }) ?? void 0;
1841
+ }
1842
+ const webConfig = configService.weappWebConfig;
1843
+ if (targets.runWeb && webConfig?.enabled) try {
1844
+ await webService?.build();
1845
+ logger_default.success(`Web 构建完成,输出目录:${colors.green(configService.relativeCwd(webConfig.outDir))}`);
1846
+ } catch (error) {
1847
+ logger_default.error(error);
1848
+ throw error;
1849
+ }
1850
+ if (targets.runMini) logBuildAppFinish(configService, void 0, { skipWeb: !targets.runWeb });
1851
+ if (options.open && targets.runMini) await openIde(configService.platform, resolveIdeProjectPath(configService.mpDistRoot));
1852
+ if (analyzeHandle) await analyzeHandle.waitForExit();
1853
+ ctx.watcherService?.closeAll();
1854
+ terminateStaleSassEmbeddedProcess();
1855
+ });
1929
1856
  }
1930
1857
  function terminateStaleSassEmbeddedProcess() {
1931
- const getHandles = process4._getActiveHandles;
1932
- const handles = typeof getHandles === "function" ? getHandles() : void 0;
1933
- if (!Array.isArray(handles)) {
1934
- return;
1935
- }
1936
- for (const handle of handles) {
1937
- if (isSassEmbeddedChild(handle)) {
1938
- try {
1939
- handle.kill();
1940
- } catch {
1941
- }
1942
- }
1943
- }
1858
+ const getHandles = process$1._getActiveHandles;
1859
+ const handles = typeof getHandles === "function" ? getHandles() : void 0;
1860
+ if (!Array.isArray(handles)) return;
1861
+ for (const handle of handles) if (isSassEmbeddedChild(handle)) try {
1862
+ handle.kill();
1863
+ } catch {}
1944
1864
  }
1945
1865
  function isSassEmbeddedChild(handle) {
1946
- return Boolean(
1947
- handle && typeof handle === "object" && "kill" in handle && "spawnfile" in handle && typeof handle.spawnfile === "string" && handle.spawnfile?.includes("sass-embedded")
1948
- );
1949
- }
1950
-
1951
- // src/cli/commands/generate.ts
1952
- init_esm_shims();
1953
- import path7 from "pathe";
1954
-
1955
- // src/schematics.ts
1956
- init_esm_shims();
1957
- import process5 from "process";
1958
- import { generateJs, generateJson, generateWxml, generateWxss } from "@weapp-core/schematics";
1959
- import { defu } from "@weapp-core/shared";
1960
- import fs4 from "fs-extra";
1961
- import path5 from "pathe";
1866
+ return Boolean(handle && typeof handle === "object" && "kill" in handle && "spawnfile" in handle && typeof handle.spawnfile === "string" && handle.spawnfile?.includes("sass-embedded"));
1867
+ }
1868
+ //#endregion
1869
+ //#region src/schematics.ts
1962
1870
  function composePath(outDir, filename) {
1963
- return `${outDir}${outDir ? "/" : ""}${filename}`;
1871
+ return `${outDir}${outDir ? "/" : ""}${filename}`;
1964
1872
  }
1965
- var defaultExtensions = {
1966
- js: "js",
1967
- json: "json",
1968
- wxml: "wxml",
1969
- wxss: "wxss"
1873
+ const defaultExtensions = {
1874
+ js: "js",
1875
+ json: "json",
1876
+ wxml: "wxml",
1877
+ wxss: "wxss"
1970
1878
  };
1971
1879
  function resolveExtension(extension) {
1972
- return extension ? extension.startsWith(".") ? extension : `.${extension}` : "";
1880
+ return extension ? extension.startsWith(".") ? extension : `.${extension}` : "";
1973
1881
  }
1974
1882
  async function readTemplateFile(templatePath, context) {
1975
- const absolutePath = path5.isAbsolute(templatePath) ? templatePath : path5.resolve(context.cwd, templatePath);
1976
- return fs4.readFile(absolutePath, "utf8");
1883
+ const absolutePath = path.isAbsolute(templatePath) ? templatePath : path.resolve(context.cwd, templatePath);
1884
+ return fs.readFile(absolutePath, "utf8");
1977
1885
  }
1978
1886
  async function loadTemplate(template, context) {
1979
- if (template === void 0) {
1980
- return void 0;
1981
- }
1982
- if (typeof template === "function") {
1983
- const result = await template(context);
1984
- return result == null ? void 0 : String(result);
1985
- }
1986
- if (typeof template === "string") {
1987
- return readTemplateFile(template, context);
1988
- }
1989
- if ("content" in template && typeof template.content === "string") {
1990
- return template.content;
1991
- }
1992
- if ("path" in template && typeof template.path === "string") {
1993
- return readTemplateFile(template.path, context);
1994
- }
1995
- return void 0;
1887
+ if (template === void 0) return;
1888
+ if (typeof template === "function") {
1889
+ const result = await template(context);
1890
+ return result == null ? void 0 : String(result);
1891
+ }
1892
+ if (typeof template === "string") return readTemplateFile(template, context);
1893
+ if ("content" in template && typeof template.content === "string") return template.content;
1894
+ if ("path" in template && typeof template.path === "string") return readTemplateFile(template.path, context);
1996
1895
  }
1997
1896
  function resolveTemplate(templates, type, fileType) {
1998
- const scoped = templates?.[type]?.[fileType];
1999
- if (scoped !== void 0) {
2000
- return scoped;
2001
- }
2002
- return templates?.shared?.[fileType];
1897
+ const scoped = templates?.[type]?.[fileType];
1898
+ if (scoped !== void 0) return scoped;
1899
+ return templates?.shared?.[fileType];
2003
1900
  }
2004
1901
  async function generate(options) {
2005
- let { fileName, outDir, extensions, type, cwd, templates } = defu(options, {
2006
- type: "component",
2007
- extensions: {
2008
- ...defaultExtensions
2009
- },
2010
- cwd: process5.cwd(),
2011
- templates: void 0
2012
- });
2013
- if (fileName === void 0) {
2014
- fileName = path5.basename(outDir);
2015
- }
2016
- const basepath = path5.resolve(cwd, outDir);
2017
- const targetFileTypes = type === "app" ? ["js", "wxss", "json"] : ["js", "wxss", "json", "wxml"];
2018
- const files = [];
2019
- for (const fileType of targetFileTypes) {
2020
- const configuredExt = extensions[fileType] ?? defaultExtensions[fileType];
2021
- let resolvedExt = configuredExt;
2022
- let defaultCode;
2023
- if (fileType === "js") {
2024
- defaultCode = generateJs(type);
2025
- } else if (fileType === "wxss") {
2026
- defaultCode = generateWxss();
2027
- } else if (fileType === "wxml") {
2028
- defaultCode = generateWxml(path5.join(outDir, fileName));
2029
- } else if (fileType === "json") {
2030
- defaultCode = generateJson(type, configuredExt);
2031
- if (configuredExt === "js" || configuredExt === "ts") {
2032
- resolvedExt = `json.${configuredExt}`;
2033
- }
2034
- }
2035
- const context = {
2036
- type,
2037
- fileType,
2038
- fileName,
2039
- outDir,
2040
- extension: resolvedExt,
2041
- cwd,
2042
- defaultCode
2043
- };
2044
- const template = resolveTemplate(templates, type, fileType);
2045
- const customCode = await loadTemplate(template, context);
2046
- const finalCode = customCode ?? defaultCode;
2047
- if (finalCode !== void 0) {
2048
- files.push({
2049
- fileName: `${fileName}${resolveExtension(resolvedExt)}`,
2050
- code: finalCode
2051
- });
2052
- }
2053
- }
2054
- for (const { code, fileName: fileName2 } of files) {
2055
- if (code !== void 0) {
2056
- await fs4.outputFile(path5.resolve(basepath, fileName2), code, "utf8");
2057
- default2.success(`${composePath(outDir, fileName2)} \u521B\u5EFA\u6210\u529F\uFF01`);
2058
- }
2059
- }
2060
- }
2061
-
2062
- // src/cli/loadConfig.ts
2063
- init_esm_shims();
2064
- import process6 from "process";
2065
- import { defu as defu2 } from "@weapp-core/shared";
2066
- import path6 from "pathe";
2067
- import { loadConfigFromFile } from "vite";
1902
+ let { fileName, outDir, extensions, type, cwd, templates } = defu(options, {
1903
+ type: "component",
1904
+ extensions: { ...defaultExtensions },
1905
+ cwd: process$1.cwd(),
1906
+ templates: void 0
1907
+ });
1908
+ if (fileName === void 0) fileName = path.basename(outDir);
1909
+ const basepath = path.resolve(cwd, outDir);
1910
+ const targetFileTypes = type === "app" ? [
1911
+ "js",
1912
+ "wxss",
1913
+ "json"
1914
+ ] : [
1915
+ "js",
1916
+ "wxss",
1917
+ "json",
1918
+ "wxml"
1919
+ ];
1920
+ const files = [];
1921
+ for (const fileType of targetFileTypes) {
1922
+ const configuredExt = extensions[fileType] ?? defaultExtensions[fileType];
1923
+ let resolvedExt = configuredExt;
1924
+ let defaultCode;
1925
+ if (fileType === "js") defaultCode = generateJs(type);
1926
+ else if (fileType === "wxss") defaultCode = generateWxss();
1927
+ else if (fileType === "wxml") defaultCode = generateWxml(path.join(outDir, fileName));
1928
+ else if (fileType === "json") {
1929
+ defaultCode = generateJson(type, configuredExt);
1930
+ if (configuredExt === "js" || configuredExt === "ts") resolvedExt = `json.${configuredExt}`;
1931
+ }
1932
+ const context = {
1933
+ type,
1934
+ fileType,
1935
+ fileName,
1936
+ outDir,
1937
+ extension: resolvedExt,
1938
+ cwd,
1939
+ defaultCode
1940
+ };
1941
+ const finalCode = await loadTemplate(resolveTemplate(templates, type, fileType), context) ?? defaultCode;
1942
+ if (finalCode !== void 0) files.push({
1943
+ fileName: `${fileName}${resolveExtension(resolvedExt)}`,
1944
+ code: finalCode
1945
+ });
1946
+ }
1947
+ for (const { code, fileName } of files) if (code !== void 0) {
1948
+ await fs.outputFile(path.resolve(basepath, fileName), code, "utf8");
1949
+ logger_default.success(`${composePath(outDir, fileName)} 创建成功!`);
1950
+ }
1951
+ }
1952
+ //#endregion
1953
+ //#region src/cli/loadConfig.ts
2068
1954
  async function loadConfig(configFile) {
2069
- const cwd = process6.cwd();
2070
- let resolvedConfigFile = configFile;
2071
- if (resolvedConfigFile && !path6.isAbsolute(resolvedConfigFile)) {
2072
- resolvedConfigFile = path6.resolve(cwd, resolvedConfigFile);
2073
- }
2074
- const configEnv = {
2075
- command: "serve",
2076
- mode: "development"
2077
- };
2078
- let loaded;
2079
- try {
2080
- loaded = await loadConfigFromFile(configEnv, resolvedConfigFile, cwd, void 0, void 0, "runner");
2081
- } catch (error) {
2082
- const cjsError = createCjsConfigLoadError({
2083
- error,
2084
- configPath: resolvedConfigFile,
2085
- cwd
2086
- });
2087
- if (cjsError) {
2088
- throw cjsError;
2089
- }
2090
- throw error;
2091
- }
2092
- const weappConfigFilePath = await resolveWeappConfigFile({
2093
- root: cwd,
2094
- specified: resolvedConfigFile
2095
- });
2096
- let weappLoaded;
2097
- if (weappConfigFilePath) {
2098
- const normalizedWeappPath = path6.resolve(weappConfigFilePath);
2099
- const normalizedLoadedPath = loaded?.path ? path6.resolve(loaded.path) : void 0;
2100
- if (normalizedLoadedPath && normalizedLoadedPath === normalizedWeappPath) {
2101
- weappLoaded = loaded;
2102
- } else {
2103
- try {
2104
- weappLoaded = await loadConfigFromFile(configEnv, weappConfigFilePath, cwd, void 0, void 0, "runner");
2105
- } catch (error) {
2106
- const cjsError = createCjsConfigLoadError({
2107
- error,
2108
- configPath: weappConfigFilePath,
2109
- cwd
2110
- });
2111
- if (cjsError) {
2112
- throw cjsError;
2113
- }
2114
- throw error;
2115
- }
2116
- }
2117
- }
2118
- if (!loaded && !weappLoaded) {
2119
- return void 0;
2120
- }
2121
- const config = loaded?.config ?? (weappLoaded?.config ?? {});
2122
- if (weappLoaded?.config?.weapp) {
2123
- config.weapp = defu2(
2124
- weappLoaded.config.weapp,
2125
- config.weapp ?? {}
2126
- );
2127
- }
2128
- const dependencySet = /* @__PURE__ */ new Set();
2129
- for (const dependency of loaded?.dependencies ?? []) {
2130
- dependencySet.add(dependency);
2131
- }
2132
- for (const dependency of weappLoaded?.dependencies ?? []) {
2133
- dependencySet.add(dependency);
2134
- }
2135
- return {
2136
- config,
2137
- path: weappLoaded?.path ?? loaded?.path ?? resolvedConfigFile,
2138
- dependencies: Array.from(dependencySet)
2139
- };
2140
- }
2141
-
2142
- // src/cli/commands/generate.ts
2143
- function registerGenerateCommand(cli2) {
2144
- cli2.command("g [filepath]", "generate component").alias("generate").option("-a, --app", "type app").option("-p, --page", "type app").option("-n, --name <name>", "filename").action(async (filepath, options) => {
2145
- filterDuplicateOptions(options);
2146
- const config = await loadConfig(resolveConfigFile(options));
2147
- let type = "component";
2148
- let fileName = options.name;
2149
- if (options.app) {
2150
- type = "app";
2151
- if (filepath === void 0) {
2152
- filepath = "";
2153
- }
2154
- fileName = "app";
2155
- }
2156
- if (filepath === void 0) {
2157
- default2.error("weapp-vite generate <outDir> \u547D\u4EE4\u5FC5\u987B\u4F20\u5165\u8DEF\u5F84\u53C2\u6570 outDir");
2158
- return;
2159
- }
2160
- if (options.page) {
2161
- type = "page";
2162
- }
2163
- const generateOptions = config?.config.weapp?.generate;
2164
- fileName = generateOptions?.filenames?.[type] ?? fileName;
2165
- await generate({
2166
- outDir: path7.join(generateOptions?.dirs?.[type] ?? "", filepath),
2167
- type,
2168
- fileName,
2169
- extensions: generateOptions?.extensions,
2170
- templates: generateOptions?.templates
2171
- });
2172
- });
2173
- }
2174
-
2175
- // src/cli/commands/init.ts
2176
- init_esm_shims();
2177
- import { initConfig } from "@weapp-core/init";
2178
- function registerInitCommand(cli2) {
2179
- cli2.command("init").action(async () => {
2180
- try {
2181
- await initConfig({
2182
- command: "weapp-vite"
2183
- });
2184
- } catch (error) {
2185
- default2.error(error);
2186
- }
2187
- });
2188
- }
2189
-
2190
- // src/cli/commands/mcp.ts
2191
- init_esm_shims();
1955
+ const cwd = process$1.cwd();
1956
+ let resolvedConfigFile = configFile;
1957
+ if (resolvedConfigFile && !path.isAbsolute(resolvedConfigFile)) resolvedConfigFile = path.resolve(cwd, resolvedConfigFile);
1958
+ const configEnv = {
1959
+ command: "serve",
1960
+ mode: "development"
1961
+ };
1962
+ let loaded;
1963
+ try {
1964
+ loaded = await loadConfigFromFile(configEnv, resolvedConfigFile, cwd, void 0, void 0, "runner");
1965
+ } catch (error) {
1966
+ const cjsError = createCjsConfigLoadError({
1967
+ error,
1968
+ configPath: resolvedConfigFile,
1969
+ cwd
1970
+ });
1971
+ if (cjsError) throw cjsError;
1972
+ throw error;
1973
+ }
1974
+ const weappConfigFilePath = await resolveWeappConfigFile({
1975
+ root: cwd,
1976
+ specified: resolvedConfigFile
1977
+ });
1978
+ let weappLoaded;
1979
+ if (weappConfigFilePath) {
1980
+ const normalizedWeappPath = path.resolve(weappConfigFilePath);
1981
+ const normalizedLoadedPath = loaded?.path ? path.resolve(loaded.path) : void 0;
1982
+ if (normalizedLoadedPath && normalizedLoadedPath === normalizedWeappPath) weappLoaded = loaded;
1983
+ else try {
1984
+ weappLoaded = await loadConfigFromFile(configEnv, weappConfigFilePath, cwd, void 0, void 0, "runner");
1985
+ } catch (error) {
1986
+ const cjsError = createCjsConfigLoadError({
1987
+ error,
1988
+ configPath: weappConfigFilePath,
1989
+ cwd
1990
+ });
1991
+ if (cjsError) throw cjsError;
1992
+ throw error;
1993
+ }
1994
+ }
1995
+ if (!loaded && !weappLoaded) return;
1996
+ const config = loaded?.config ?? weappLoaded?.config ?? {};
1997
+ if (weappLoaded?.config?.weapp) config.weapp = defu(weappLoaded.config.weapp, config.weapp ?? {});
1998
+ const dependencySet = /* @__PURE__ */ new Set();
1999
+ for (const dependency of loaded?.dependencies ?? []) dependencySet.add(dependency);
2000
+ for (const dependency of weappLoaded?.dependencies ?? []) dependencySet.add(dependency);
2001
+ return {
2002
+ config,
2003
+ path: weappLoaded?.path ?? loaded?.path ?? resolvedConfigFile,
2004
+ dependencies: Array.from(dependencySet)
2005
+ };
2006
+ }
2007
+ //#endregion
2008
+ //#region src/cli/commands/generate.ts
2009
+ function registerGenerateCommand(cli) {
2010
+ cli.command("g [filepath]", "generate component").alias("generate").option("-a, --app", "type app").option("-p, --page", "type app").option("-n, --name <name>", "filename").action(async (filepath, options) => {
2011
+ filterDuplicateOptions(options);
2012
+ const config = await loadConfig(resolveConfigFile(options));
2013
+ let type = "component";
2014
+ let fileName = options.name;
2015
+ if (options.app) {
2016
+ type = "app";
2017
+ if (filepath === void 0) filepath = "";
2018
+ fileName = "app";
2019
+ }
2020
+ if (filepath === void 0) {
2021
+ logger_default.error("weapp-vite generate <outDir> 命令必须传入路径参数 outDir");
2022
+ return;
2023
+ }
2024
+ if (options.page) type = "page";
2025
+ const generateOptions = config?.config.weapp?.generate;
2026
+ fileName = generateOptions?.filenames?.[type] ?? fileName;
2027
+ await generate({
2028
+ outDir: path.join(generateOptions?.dirs?.[type] ?? "", filepath),
2029
+ type,
2030
+ fileName,
2031
+ extensions: generateOptions?.extensions,
2032
+ templates: generateOptions?.templates
2033
+ });
2034
+ });
2035
+ }
2036
+ //#endregion
2037
+ //#region src/cli/commands/init.ts
2038
+ function registerInitCommand(cli) {
2039
+ cli.command("init").action(async () => {
2040
+ try {
2041
+ await initConfig({ command: "weapp-vite" });
2042
+ } catch (error) {
2043
+ logger_default.error(error);
2044
+ }
2045
+ });
2046
+ }
2047
+ //#endregion
2048
+ //#region src/cli/commands/mcp.ts
2192
2049
  function resolvePort(port) {
2193
- if (typeof port === "number" && Number.isInteger(port)) {
2194
- return port;
2195
- }
2196
- if (typeof port === "string" && port.trim()) {
2197
- const parsed = Number.parseInt(port, 10);
2198
- if (Number.isInteger(parsed)) {
2199
- return parsed;
2200
- }
2201
- }
2202
- }
2203
- function registerMcpCommand(cli2) {
2204
- cli2.command("mcp", "start weapp-vite MCP server").option("--transport <type>", "[string] stdio | streamable-http", { default: "stdio" }).option("--host <host>", "[string] streamable-http host").option("--port <port>", "[number] streamable-http port").option("--endpoint <path>", "[string] streamable-http endpoint path").option("--unref", "[boolean] unref HTTP server to not block process exit").option("--workspace-root <path>", "[string] workspace root path, defaults to auto detect from cwd").action(async (options) => {
2205
- const { startWeappViteMcpServer: startWeappViteMcpServer2 } = await import("./mcp.mjs");
2206
- await startWeappViteMcpServer2({
2207
- endpoint: options.endpoint,
2208
- host: options.host,
2209
- port: resolvePort(options.port),
2210
- transport: options.transport,
2211
- unref: options.unref,
2212
- workspaceRoot: options.workspaceRoot
2213
- });
2214
- });
2215
- }
2216
-
2217
- // src/cli/commands/npm.ts
2218
- init_esm_shims();
2219
- import { parse as parse2 } from "weapp-ide-cli";
2220
- function registerNpmCommand(cli2) {
2221
- cli2.command("npm").alias("build:npm").alias("build-npm").action(async () => {
2222
- try {
2223
- await parse2(["build-npm", "-p"]);
2224
- } catch (error) {
2225
- default2.error(error);
2226
- }
2227
- });
2228
- }
2229
-
2230
- // src/cli/commands/open.ts
2231
- init_esm_shims();
2232
- import process7 from "process";
2233
- function registerOpenCommand(cli2) {
2234
- cli2.command("open [root]").option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).action(async (root, options) => {
2235
- filterDuplicateOptions(options);
2236
- const configFile = resolveConfigFile(options);
2237
- const targets = resolveRuntimeTargets(options);
2238
- let platform = targets.mpPlatform;
2239
- let projectPath = root;
2240
- if (targets.runMini && (!platform || !projectPath)) {
2241
- try {
2242
- const ctx = await createCompilerContext({
2243
- cwd: process7.cwd(),
2244
- mode: options.mode ?? "development",
2245
- configFile,
2246
- inlineConfig: createInlineConfig(platform),
2247
- cliPlatform: targets.rawPlatform
2248
- });
2249
- platform ??= ctx.configService.platform;
2250
- if (!projectPath) {
2251
- projectPath = resolveIdeProjectPath(ctx.configService.mpDistRoot);
2252
- }
2253
- } catch {
2254
- }
2255
- }
2256
- if (!projectPath && platform === "alipay") {
2257
- projectPath = resolveIdeProjectPath("dist/alipay/dist");
2258
- }
2259
- await openIde(platform, projectPath);
2260
- });
2261
- }
2262
-
2263
- // src/cli/commands/serve.ts
2264
- init_esm_shims();
2265
- function registerServeCommand(cli2) {
2266
- cli2.command("[root]", "start dev server").alias("serve").alias("dev").option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).option("--host [host]", `[string] web dev server host`).option("--analyze", `[boolean] \u542F\u52A8\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8 (\u5B9E\u9A8C\u7279\u6027)`, { default: false }).action(async (root, options) => {
2267
- filterDuplicateOptions(options);
2268
- const configFile = resolveConfigFile(options);
2269
- const targets = resolveRuntimeTargets(options);
2270
- let inlineConfig = createInlineConfig(targets.mpPlatform);
2271
- if (targets.runWeb) {
2272
- const host = resolveWebHost(options.host);
2273
- if (host !== void 0) {
2274
- inlineConfig = {
2275
- ...inlineConfig,
2276
- server: {
2277
- ...inlineConfig?.server ?? {},
2278
- host
2279
- }
2280
- };
2281
- }
2282
- }
2283
- const ctx = await createCompilerContext({
2284
- cwd: root,
2285
- mode: options.mode ?? "development",
2286
- isDev: true,
2287
- configFile,
2288
- inlineConfig,
2289
- cliPlatform: targets.rawPlatform,
2290
- projectConfigPath: options.projectConfig
2291
- });
2292
- const { buildService, configService, webService } = ctx;
2293
- logRuntimeTarget(targets, { resolvedConfigPlatform: configService.platform });
2294
- const enableAnalyze = Boolean(options.analyze && targets.runMini);
2295
- let analyzeHandle;
2296
- const triggerAnalyzeUpdate = async () => {
2297
- if (!analyzeHandle) {
2298
- return;
2299
- }
2300
- const next = await analyzeSubpackages(ctx);
2301
- await analyzeHandle.update(next);
2302
- };
2303
- if (targets.runMini) {
2304
- const buildResult = await buildService.build(options);
2305
- if (enableAnalyze) {
2306
- const initialResult = await analyzeSubpackages(ctx);
2307
- analyzeHandle = await startAnalyzeDashboard(initialResult, { watch: true }) ?? void 0;
2308
- if (analyzeHandle && buildResult && typeof buildResult.on === "function") {
2309
- const watcher = buildResult;
2310
- let updating = false;
2311
- watcher.on("event", (event) => {
2312
- if (event.code !== "END" || updating) {
2313
- return;
2314
- }
2315
- updating = true;
2316
- triggerAnalyzeUpdate().finally(() => {
2317
- updating = false;
2318
- });
2319
- });
2320
- } else if (analyzeHandle) {
2321
- await triggerAnalyzeUpdate();
2322
- }
2323
- }
2324
- }
2325
- let webServer;
2326
- if (targets.runWeb) {
2327
- try {
2328
- webServer = await webService?.startDevServer();
2329
- } catch (error) {
2330
- default2.error(error);
2331
- throw error;
2332
- }
2333
- }
2334
- if (targets.runMini) {
2335
- logBuildAppFinish(configService, webServer, { skipWeb: !targets.runWeb });
2336
- } else if (targets.runWeb) {
2337
- logBuildAppFinish(configService, webServer, { skipMini: true });
2338
- }
2339
- if (options.open && targets.runMini) {
2340
- await openIde(configService.platform, resolveIdeProjectPath(configService.mpDistRoot));
2341
- }
2342
- if (analyzeHandle) {
2343
- await analyzeHandle.waitForExit();
2344
- }
2345
- });
2050
+ if (typeof port === "number" && Number.isInteger(port)) return port;
2051
+ if (typeof port === "string" && port.trim()) {
2052
+ const parsed = Number.parseInt(port, 10);
2053
+ if (Number.isInteger(parsed)) return parsed;
2054
+ }
2055
+ }
2056
+ function registerMcpCommand(cli) {
2057
+ cli.command("mcp", "start weapp-vite MCP server").option("--transport <type>", "[string] stdio | streamable-http", { default: "stdio" }).option("--host <host>", "[string] streamable-http host").option("--port <port>", "[number] streamable-http port").option("--endpoint <path>", "[string] streamable-http endpoint path").option("--unref", "[boolean] unref HTTP server to not block process exit").option("--workspace-root <path>", "[string] workspace root path, defaults to auto detect from cwd").action(async (options) => {
2058
+ const { startWeappViteMcpServer } = await import("./mcp.mjs");
2059
+ await startWeappViteMcpServer({
2060
+ endpoint: options.endpoint,
2061
+ host: options.host,
2062
+ port: resolvePort(options.port),
2063
+ transport: options.transport,
2064
+ unref: options.unref,
2065
+ workspaceRoot: options.workspaceRoot
2066
+ });
2067
+ });
2068
+ }
2069
+ //#endregion
2070
+ //#region src/cli/commands/npm.ts
2071
+ function registerNpmCommand(cli) {
2072
+ cli.command("npm").alias("build:npm").alias("build-npm").action(async () => {
2073
+ try {
2074
+ await parse(["build-npm", "-p"]);
2075
+ } catch (error) {
2076
+ logger_default.error(error);
2077
+ }
2078
+ });
2079
+ }
2080
+ //#endregion
2081
+ //#region src/cli/commands/open.ts
2082
+ function registerOpenCommand(cli) {
2083
+ cli.command("open [root]").option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).action(async (root, options) => {
2084
+ filterDuplicateOptions(options);
2085
+ const configFile = resolveConfigFile(options);
2086
+ const targets = resolveRuntimeTargets(options);
2087
+ let platform = targets.mpPlatform;
2088
+ let projectPath = root;
2089
+ if (targets.runMini && (!platform || !projectPath)) try {
2090
+ const ctx = await createCompilerContext({
2091
+ cwd: process$1.cwd(),
2092
+ mode: options.mode ?? "development",
2093
+ configFile,
2094
+ inlineConfig: createInlineConfig(platform),
2095
+ cliPlatform: targets.rawPlatform
2096
+ });
2097
+ platform ??= ctx.configService.platform;
2098
+ if (!projectPath) projectPath = resolveIdeProjectPath(ctx.configService.mpDistRoot);
2099
+ } catch {}
2100
+ if (!projectPath && platform === "alipay") projectPath = resolveIdeProjectPath("dist/alipay/dist");
2101
+ await openIde(platform, projectPath);
2102
+ });
2103
+ }
2104
+ //#endregion
2105
+ //#region src/cli/commands/serve.ts
2106
+ function registerServeCommand(cli) {
2107
+ cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).option("--host [host]", `[string] web dev server host`).option("--analyze", `[boolean] 启动分包分析仪表盘 (实验特性)`, { default: false }).action(async (root, options) => {
2108
+ filterDuplicateOptions(options);
2109
+ const configFile = resolveConfigFile(options);
2110
+ const targets = resolveRuntimeTargets(options);
2111
+ let inlineConfig = createInlineConfig(targets.mpPlatform);
2112
+ if (targets.runWeb) {
2113
+ const host = resolveWebHost(options.host);
2114
+ if (host !== void 0) inlineConfig = {
2115
+ ...inlineConfig,
2116
+ server: {
2117
+ ...inlineConfig?.server ?? {},
2118
+ host
2119
+ }
2120
+ };
2121
+ }
2122
+ const ctx = await createCompilerContext({
2123
+ cwd: root,
2124
+ mode: options.mode ?? "development",
2125
+ isDev: true,
2126
+ configFile,
2127
+ inlineConfig,
2128
+ cliPlatform: targets.rawPlatform,
2129
+ projectConfigPath: options.projectConfig
2130
+ });
2131
+ const { buildService, configService, webService } = ctx;
2132
+ logRuntimeTarget(targets, { resolvedConfigPlatform: configService.platform });
2133
+ const enableAnalyze = Boolean(options.analyze && targets.runMini);
2134
+ let analyzeHandle;
2135
+ const triggerAnalyzeUpdate = async () => {
2136
+ if (!analyzeHandle) return;
2137
+ const next = await analyzeSubpackages(ctx);
2138
+ await analyzeHandle.update(next);
2139
+ };
2140
+ if (targets.runMini) {
2141
+ const buildResult = await buildService.build(options);
2142
+ if (enableAnalyze) {
2143
+ analyzeHandle = await startAnalyzeDashboard(await analyzeSubpackages(ctx), { watch: true }) ?? void 0;
2144
+ if (analyzeHandle && buildResult && typeof buildResult.on === "function") {
2145
+ const watcher = buildResult;
2146
+ let updating = false;
2147
+ watcher.on("event", (event) => {
2148
+ if (event.code !== "END" || updating) return;
2149
+ updating = true;
2150
+ triggerAnalyzeUpdate().finally(() => {
2151
+ updating = false;
2152
+ });
2153
+ });
2154
+ } else if (analyzeHandle) await triggerAnalyzeUpdate();
2155
+ }
2156
+ }
2157
+ let webServer;
2158
+ if (targets.runWeb) try {
2159
+ webServer = await webService?.startDevServer();
2160
+ } catch (error) {
2161
+ logger_default.error(error);
2162
+ throw error;
2163
+ }
2164
+ if (targets.runMini) logBuildAppFinish(configService, webServer, { skipWeb: !targets.runWeb });
2165
+ else if (targets.runWeb) logBuildAppFinish(configService, webServer, { skipMini: true });
2166
+ if (options.open && targets.runMini) await openIde(configService.platform, resolveIdeProjectPath(configService.mpDistRoot));
2167
+ if (analyzeHandle) await analyzeHandle.waitForExit();
2168
+ });
2346
2169
  }
2347
2170
  function resolveWebHost(host) {
2348
- if (host === void 0) {
2349
- return void 0;
2350
- }
2351
- if (typeof host === "boolean") {
2352
- return host;
2353
- }
2354
- if (typeof host === "string") {
2355
- return host;
2356
- }
2357
- return String(host);
2358
- }
2359
-
2360
- // src/cli/error.ts
2361
- init_esm_shims();
2362
- import process8 from "process";
2363
- var watchLimitErrorCodes = /* @__PURE__ */ new Set(["EMFILE", "ENOSPC"]);
2364
- var watchLimitMessagePattern = /EMFILE|ENOSPC|unable to start FSEvent stream/i;
2171
+ if (host === void 0) return;
2172
+ if (typeof host === "boolean") return host;
2173
+ if (typeof host === "string") return host;
2174
+ return String(host);
2175
+ }
2176
+ //#endregion
2177
+ //#region src/cli/error.ts
2178
+ const watchLimitErrorCodes = new Set(["EMFILE", "ENOSPC"]);
2179
+ const watchLimitMessagePattern = /EMFILE|ENOSPC|unable to start FSEvent stream/i;
2365
2180
  function findWatchLimitErrorCode(error) {
2366
- const visited = /* @__PURE__ */ new Set();
2367
- const visit = (value) => {
2368
- if (!value || typeof value !== "object") {
2369
- return void 0;
2370
- }
2371
- if (visited.has(value)) {
2372
- return void 0;
2373
- }
2374
- visited.add(value);
2375
- const maybeError = value;
2376
- if (typeof maybeError.code === "string" && watchLimitErrorCodes.has(maybeError.code)) {
2377
- return maybeError.code;
2378
- }
2379
- if (typeof maybeError.message === "string" && watchLimitMessagePattern.test(maybeError.message)) {
2380
- const match = maybeError.message.match(/EMFILE|ENOSPC/i);
2381
- if (match?.[0]) {
2382
- return match[0].toUpperCase();
2383
- }
2384
- return "EMFILE";
2385
- }
2386
- if (Array.isArray(maybeError.errors)) {
2387
- for (const item of maybeError.errors) {
2388
- const found = visit(item);
2389
- if (found) {
2390
- return found;
2391
- }
2392
- }
2393
- }
2394
- const fromError = visit(maybeError.error);
2395
- if (fromError) {
2396
- return fromError;
2397
- }
2398
- return visit(maybeError.cause);
2399
- };
2400
- return visit(error);
2181
+ const visited = /* @__PURE__ */ new Set();
2182
+ const visit = (value) => {
2183
+ if (!value || typeof value !== "object") return;
2184
+ if (visited.has(value)) return;
2185
+ visited.add(value);
2186
+ const maybeError = value;
2187
+ if (typeof maybeError.code === "string" && watchLimitErrorCodes.has(maybeError.code)) return maybeError.code;
2188
+ if (typeof maybeError.message === "string" && watchLimitMessagePattern.test(maybeError.message)) {
2189
+ const match = maybeError.message.match(/EMFILE|ENOSPC/i);
2190
+ if (match?.[0]) return match[0].toUpperCase();
2191
+ return "EMFILE";
2192
+ }
2193
+ if (Array.isArray(maybeError.errors)) for (const item of maybeError.errors) {
2194
+ const found = visit(item);
2195
+ if (found) return found;
2196
+ }
2197
+ const fromError = visit(maybeError.error);
2198
+ if (fromError) return fromError;
2199
+ return visit(maybeError.cause);
2200
+ };
2201
+ return visit(error);
2401
2202
  }
2402
2203
  function handleCLIError(error) {
2403
- const code = findWatchLimitErrorCode(error);
2404
- if (code) {
2405
- const tip = process8.platform === "darwin" ? "\u53EF\u5148\u6267\u884C `ulimit -n 65536` \u540E\u91CD\u8BD5\u3002" : "\u8BF7\u63D0\u9AD8\u7CFB\u7EDF\u6587\u4EF6\u63CF\u8FF0\u7B26\u4E0A\u9650\u540E\u91CD\u8BD5\u3002";
2406
- default2.error(`[\u76D1\u542C] \u6587\u4EF6\u76D1\u542C\u6570\u91CF\u8FBE\u5230\u4E0A\u9650 (${code})\uFF0C${tip}`);
2407
- return;
2408
- }
2409
- default2.error(error);
2410
- }
2411
-
2412
- // src/cli/ide.ts
2413
- init_esm_shims();
2414
- import { isWeappIdeTopLevelCommand, parse as parseWeappIdeCli } from "weapp-ide-cli";
2415
- var WEAPP_VITE_NATIVE_COMMANDS = /* @__PURE__ */ new Set([
2416
- "dev",
2417
- "serve",
2418
- "build",
2419
- "analyze",
2420
- "init",
2421
- "open",
2422
- "npm",
2423
- "build:npm",
2424
- "build-npm",
2425
- "generate",
2426
- "g",
2427
- "mcp"
2204
+ const code = findWatchLimitErrorCode(error);
2205
+ if (code) {
2206
+ const tip = process$1.platform === "darwin" ? "可先执行 `ulimit -n 65536` 后重试。" : "请提高系统文件描述符上限后重试。";
2207
+ logger_default.error(`[监听] 文件监听数量达到上限 (${code}),${tip}`);
2208
+ return;
2209
+ }
2210
+ logger_default.error(error);
2211
+ }
2212
+ //#endregion
2213
+ //#region src/cli/ide.ts
2214
+ const WEAPP_VITE_NATIVE_COMMANDS = new Set([
2215
+ "dev",
2216
+ "serve",
2217
+ "build",
2218
+ "analyze",
2219
+ "init",
2220
+ "open",
2221
+ "npm",
2222
+ "build:npm",
2223
+ "build-npm",
2224
+ "generate",
2225
+ "g",
2226
+ "mcp"
2428
2227
  ]);
2228
+ /**
2229
+ * @description 让 weapp-vite 在未命中自身命令时,回退到 weapp-ide-cli。
2230
+ */
2429
2231
  async function tryRunIdeCommand(argv) {
2430
- const command = argv[0];
2431
- if (!command) {
2432
- return false;
2433
- }
2434
- if (command === "ide") {
2435
- await parseWeappIdeCli(argv.slice(1));
2436
- return true;
2437
- }
2438
- if (command.startsWith("-")) {
2439
- return false;
2440
- }
2441
- if (command === "help") {
2442
- const target = argv[1];
2443
- if (!target || WEAPP_VITE_NATIVE_COMMANDS.has(target) || !isWeappIdeTopLevelCommand(target)) {
2444
- return false;
2445
- }
2446
- await parseWeappIdeCli(argv);
2447
- return true;
2448
- }
2449
- if (WEAPP_VITE_NATIVE_COMMANDS.has(command) || !isWeappIdeTopLevelCommand(command)) {
2450
- return false;
2451
- }
2452
- await parseWeappIdeCli(argv);
2453
- return true;
2454
- }
2455
-
2456
- // src/cli/mcpAutoStart.ts
2457
- init_esm_shims();
2458
- import process9 from "process";
2459
- var SKIP_COMMANDS = /* @__PURE__ */ new Set([
2460
- "--help",
2461
- "--version",
2462
- "-h",
2463
- "-v",
2464
- "help",
2465
- "ide",
2466
- "mcp"
2467
- ]);
2468
- var DEV_COMMANDS = /* @__PURE__ */ new Set([
2469
- "dev",
2470
- "serve"
2232
+ const command = argv[0];
2233
+ if (!command) return false;
2234
+ if (command === "ide") {
2235
+ await parse(argv.slice(1));
2236
+ return true;
2237
+ }
2238
+ if (command.startsWith("-")) return false;
2239
+ if (command === "help") {
2240
+ const target = argv[1];
2241
+ if (!target || WEAPP_VITE_NATIVE_COMMANDS.has(target) || !isWeappIdeTopLevelCommand(target)) return false;
2242
+ await parse(argv);
2243
+ return true;
2244
+ }
2245
+ if (WEAPP_VITE_NATIVE_COMMANDS.has(command) || !isWeappIdeTopLevelCommand(command)) return false;
2246
+ await parse(argv);
2247
+ return true;
2248
+ }
2249
+ //#endregion
2250
+ //#region src/cli/mcpAutoStart.ts
2251
+ const SKIP_COMMANDS = new Set([
2252
+ "--help",
2253
+ "--version",
2254
+ "-h",
2255
+ "-v",
2256
+ "help",
2257
+ "ide",
2258
+ "mcp"
2471
2259
  ]);
2472
- var started = false;
2260
+ const DEV_COMMANDS = new Set(["dev", "serve"]);
2261
+ let started = false;
2473
2262
  function shouldAutoStartMcp(argv) {
2474
- const command = argv[0];
2475
- if (!command || command.startsWith("-")) {
2476
- return true;
2477
- }
2478
- if (SKIP_COMMANDS.has(command)) {
2479
- return false;
2480
- }
2481
- if (DEV_COMMANDS.has(command)) {
2482
- return true;
2483
- }
2484
- return command.includes("/") || command.includes("\\") || command.startsWith(".");
2263
+ const command = argv[0];
2264
+ if (!command || command.startsWith("-")) return true;
2265
+ if (SKIP_COMMANDS.has(command)) return false;
2266
+ if (DEV_COMMANDS.has(command)) return true;
2267
+ return command.includes("/") || command.includes("\\") || command.startsWith(".");
2485
2268
  }
2486
2269
  async function maybeAutoStartMcpServer(argv, cliOptions) {
2487
- if (started || !shouldAutoStartMcp(argv)) {
2488
- return;
2489
- }
2490
- const configFile = resolveConfigFile(cliOptions);
2491
- let rawMcpConfig;
2492
- try {
2493
- const loaded = await loadConfig(configFile);
2494
- rawMcpConfig = loaded?.config?.weapp?.mcp;
2495
- } catch (error) {
2496
- default2.warn(`[mcp] \u8BFB\u53D6\u914D\u7F6E\u5931\u8D25\uFF0C\u4F7F\u7528\u9ED8\u8BA4 MCP \u914D\u7F6E\u81EA\u52A8\u542F\u52A8\uFF1A${error instanceof Error ? error.message : String(error)}`);
2497
- }
2498
- const maybeMcpConfig = rawMcpConfig;
2499
- const resolvedMcp = resolveWeappMcpConfig(maybeMcpConfig);
2500
- if (!resolvedMcp.enabled || !resolvedMcp.autoStart) {
2501
- return;
2502
- }
2503
- try {
2504
- await startWeappViteMcpServer({
2505
- endpoint: resolvedMcp.endpoint,
2506
- host: resolvedMcp.host,
2507
- port: resolvedMcp.port,
2508
- quiet: true,
2509
- transport: "streamable-http",
2510
- unref: true,
2511
- workspaceRoot: process9.cwd()
2512
- });
2513
- started = true;
2514
- const mcpUrl = `http://${resolvedMcp.host}:${resolvedMcp.port}${resolvedMcp.endpoint}`;
2515
- default2.success("MCP \u670D\u52A1\u5DF2\u81EA\u52A8\u542F\u52A8\uFF1A");
2516
- default2.info(` \u279C ${colors.cyan(mcpUrl)}`);
2517
- } catch (error) {
2518
- const message = error instanceof Error ? error.message : String(error);
2519
- if (/EADDRINUSE/.test(message)) {
2520
- default2.info(`[mcp] \u7AEF\u53E3 ${resolvedMcp.port} \u5DF2\u88AB\u5360\u7528\uFF0C\u8DF3\u8FC7\u81EA\u52A8\u542F\u52A8\u3002`);
2521
- started = true;
2522
- return;
2523
- }
2524
- default2.warn(`[mcp] \u81EA\u52A8\u542F\u52A8\u5931\u8D25\uFF1A${message}`);
2525
- }
2526
- }
2527
-
2528
- // src/cli.ts
2529
- var cli = cac("weapp-vite");
2270
+ if (started || !shouldAutoStartMcp(argv)) return;
2271
+ const configFile = resolveConfigFile(cliOptions);
2272
+ let rawMcpConfig;
2273
+ try {
2274
+ rawMcpConfig = (await loadConfig(configFile))?.config?.weapp?.mcp;
2275
+ } catch (error) {
2276
+ logger_default.warn(`[mcp] 读取配置失败,使用默认 MCP 配置自动启动:${error instanceof Error ? error.message : String(error)}`);
2277
+ }
2278
+ const resolvedMcp = resolveWeappMcpConfig(rawMcpConfig);
2279
+ if (!resolvedMcp.enabled || !resolvedMcp.autoStart) return;
2280
+ try {
2281
+ await startWeappViteMcpServer({
2282
+ endpoint: resolvedMcp.endpoint,
2283
+ host: resolvedMcp.host,
2284
+ port: resolvedMcp.port,
2285
+ quiet: true,
2286
+ transport: "streamable-http",
2287
+ unref: true,
2288
+ workspaceRoot: process$1.cwd()
2289
+ });
2290
+ started = true;
2291
+ const mcpUrl = `http://${resolvedMcp.host}:${resolvedMcp.port}${resolvedMcp.endpoint}`;
2292
+ logger_default.success("MCP 服务已自动启动:");
2293
+ logger_default.info(` ➜ ${colors.cyan(mcpUrl)}`);
2294
+ } catch (error) {
2295
+ const message = error instanceof Error ? error.message : String(error);
2296
+ if (/EADDRINUSE/.test(message)) {
2297
+ logger_default.info(`[mcp] 端口 ${resolvedMcp.port} 已被占用,跳过自动启动。`);
2298
+ started = true;
2299
+ return;
2300
+ }
2301
+ logger_default.warn(`[mcp] 自动启动失败:${message}`);
2302
+ }
2303
+ }
2304
+ //#endregion
2305
+ //#region src/cli.ts
2306
+ const cli = cac("weapp-vite");
2530
2307
  try {
2531
- checkRuntime({
2532
- bun: "0.0.0",
2533
- deno: "0.0.0",
2534
- node: "^20.19.0 || >=22.12.0"
2535
- });
2536
- } catch {
2537
- }
2538
- cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, {
2539
- type: [convertBase]
2540
- }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
2308
+ checkRuntime({
2309
+ bun: "0.0.0",
2310
+ deno: "0.0.0",
2311
+ node: "^20.19.0 || >=22.12.0"
2312
+ });
2313
+ } catch {}
2314
+ cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, { type: [convertBase] }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
2541
2315
  registerServeCommand(cli);
2542
2316
  registerBuildCommand(cli);
2543
2317
  registerAnalyzeCommand(cli);
@@ -2549,19 +2323,18 @@ registerMcpCommand(cli);
2549
2323
  cli.help();
2550
2324
  cli.version(VERSION);
2551
2325
  try {
2552
- Promise.resolve().then(async () => {
2553
- const forwarded = await tryRunIdeCommand(process10.argv.slice(2));
2554
- if (forwarded) {
2555
- return;
2556
- }
2557
- cli.parse(process10.argv, { run: false });
2558
- await maybeAutoStartMcpServer(process10.argv.slice(2), cli.options);
2559
- await cli.runMatchedCommand();
2560
- }).catch((error) => {
2561
- handleCLIError(error);
2562
- process10.exitCode = 1;
2563
- });
2326
+ Promise.resolve().then(async () => {
2327
+ if (await tryRunIdeCommand(process$1.argv.slice(2))) return;
2328
+ cli.parse(process$1.argv, { run: false });
2329
+ await maybeAutoStartMcpServer(process$1.argv.slice(2), cli.options);
2330
+ await cli.runMatchedCommand();
2331
+ }).catch((error) => {
2332
+ handleCLIError(error);
2333
+ process$1.exitCode = 1;
2334
+ });
2564
2335
  } catch (error) {
2565
- handleCLIError(error);
2566
- process10.exitCode = 1;
2336
+ handleCLIError(error);
2337
+ process$1.exitCode = 1;
2567
2338
  }
2339
+ //#endregion
2340
+ export {};