weapp-vite 6.16.4 → 6.16.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { C as getDefaultIdeProjectRoot, S as createCjsConfigLoadError, T as isPathInside, _ as resolveWeappConfigFile, b as loadViteConfigFile, f as resolveWeappViteTarget, h as resolveHmrProfileJsonPath, m as SHARED_CHUNK_VIRTUAL_PREFIX, n as syncProjectSupportFiles, p as createSharedBuildConfig, r as syncManagedTsconfigBootstrapFiles, s as formatBytes, t as createCompilerContext, v as checkRuntime, w as shouldPassPlatformArgToIdeOpen, x as parseCommentJson, y as getProjectConfigFileName } from "./createContext-CoTaL8he.mjs";
1
+ import { C as getDefaultIdeProjectRoot, S as createCjsConfigLoadError, T as isPathInside, _ as resolveWeappConfigFile, b as loadViteConfigFile, f as resolveWeappViteTarget, h as resolveHmrProfileJsonPath, m as SHARED_CHUNK_VIRTUAL_PREFIX, n as syncProjectSupportFiles, p as createSharedBuildConfig, r as syncManagedTsconfigBootstrapFiles, s as formatBytes, t as createCompilerContext, v as checkRuntime, w as shouldPassPlatformArgToIdeOpen, x as parseCommentJson, y as getProjectConfigFileName } from "./createContext-CnilYzXS.mjs";
2
2
  import { r as logger_default, t as colors } from "./logger-CgxdNjvb.mjs";
3
- import { h as VERSION } from "./file-D57m5ljp.mjs";
3
+ import { h as VERSION } from "./file-D_s683Q5.mjs";
4
4
  import { o as resolveWeappMcpConfig, s as startWeappViteMcpServer } from "./mcp-DV3K2AVD.mjs";
5
5
  import { createRequire } from "node:module";
6
6
  import path, { posix } from "pathe";
@@ -11,2299 +11,2384 @@ import process from "node:process";
11
11
  import fs$2 from "node:fs/promises";
12
12
  import { build, createServer } from "vite";
13
13
  import os from "node:os";
14
- import { execFile } from "node:child_process";
14
+ import { execFile, spawn } from "node:child_process";
15
15
  import { Buffer } from "node:buffer";
16
16
  import { cac } from "cac";
17
- import { brotliCompressSync, gzipSync } from "node:zlib";
18
- import { resolveCommand } from "package-manager-detector/commands";
19
17
  import { RETRY_CANCEL_KEYS, RETRY_CONFIRM_KEYS, bootstrapWechatDevtoolsSettings, buildWechatIdeNpm, clearWechatIdeCache, clearWechatIdeCacheByAutomator, closeSharedMiniProgram, closeWechatIdeProject, compileWechatIdeByAutomator, connectOpenedAutomator, createSharedInputSession, dispatchWechatCliCommand, formatAutomatorLoginError, getConfig, getWechatIdeTestAccounts, getWechatIdeTicket, getWechatIdeToolInfo, isAutomatorLoginError, isWeappIdeTopLevelCommand, isWechatIdeLoginRequiredError, launchAutomator, openWechatIdeProjectByHttp, parse, promptRetryKeypress, promptWechatIdeLoginRetry, quitWechatIde, refreshWechatIdeTicket, resetWechatIdeFileUtilsByHttp, runRetryableCommand, runWechatIdeEngineBuild, runWithSuspendedSharedInput, setWechatIdeTicket, startForwardConsole, takeScreenshot } from "weapp-ide-cli";
20
18
  import { promisify } from "node:util";
19
+ import { brotliCompressSync, gzipSync } from "node:zlib";
20
+ import { resolveCommand } from "package-manager-detector/commands";
21
21
  import { generateJs, generateJson, generateWxml, generateWxss } from "@weapp-core/schematics";
22
22
  import { determineAgent } from "@vercel/detect-agent";
23
23
  import { initConfig } from "@weapp-core/init";
24
24
  import { createInterface } from "node:readline/promises";
25
25
  import { clearTimeout, setTimeout as setTimeout$1 } from "node:timers";
26
- //#region src/analyze/hmr.ts
27
- function createMetricSummary(values) {
28
- if (!values.length) return { count: 0 };
29
- const total = values.reduce((sum, value) => sum + value, 0);
26
+ //#region src/cli/runtime.ts
27
+ function logRuntimeTarget(targets, options = {}) {
28
+ if (options.silent) return;
29
+ if (targets.label === "config") {
30
+ const resolvedPlatform = targets.platform ?? options.resolvedConfigPlatform;
31
+ if (resolvedPlatform) {
32
+ logger_default.info(`目标平台:${colors.green(resolvedPlatform)}`);
33
+ return;
34
+ }
35
+ logger_default.info(`目标平台:使用配置文件中的 ${colors.bold(colors.green("weapp.platform"))}`);
36
+ return;
37
+ }
38
+ logger_default.info(`目标平台:${colors.green(targets.label)}`);
39
+ }
40
+ function resolveRuntimeTargets(options) {
41
+ const rawPlatform = typeof options.platform === "string" ? options.platform : typeof options.p === "string" ? options.p : void 0;
42
+ const target = resolveWeappViteTarget(rawPlatform, { warn: (message) => logger_default.warn(message) });
30
43
  return {
31
- count: values.length,
32
- averageMs: total / values.length,
33
- maxMs: Math.max(...values)
44
+ runMini: target.runMini,
45
+ runWeb: target.runWeb,
46
+ platform: target.kind === "miniprogram" ? target.platform : void 0,
47
+ label: target.label,
48
+ rawPlatform
34
49
  };
35
50
  }
36
- function sortCountEntries(map) {
37
- return [...map.entries()].sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0])).map(([name, count]) => ({
38
- name,
39
- count
40
- }));
51
+ function createInlineConfig(platform) {
52
+ if (!platform) return;
53
+ return { weapp: { platform } };
41
54
  }
42
- function collectCounts(target, values) {
43
- for (const value of values ?? []) {
44
- if (!value) continue;
45
- target.set(value, (target.get(value) ?? 0) + 1);
55
+ //#endregion
56
+ //#region src/cli/openIde/execute.ts
57
+ function readArgOption(argv, ...names) {
58
+ for (let index = 0; index < argv.length; index += 1) {
59
+ const current = argv[index];
60
+ if (!names.includes(current)) continue;
61
+ const next = argv[index + 1];
62
+ if (typeof next === "string" && !next.startsWith("-")) return next;
46
63
  }
47
64
  }
48
- function isFiniteNumber$1(value) {
49
- return typeof value === "number" && Number.isFinite(value);
65
+ async function tryExecuteWechatIdeCliCommandByAutomator(argv, projectPath) {
66
+ if (!projectPath) return false;
67
+ const command = argv[0];
68
+ if (!command) return false;
69
+ if (command === "compile") {
70
+ await compileWechatIdeByAutomator({ projectPath });
71
+ return true;
72
+ }
73
+ if (command === "cache") {
74
+ const cleanType = readArgOption(argv, "--clean", "-c");
75
+ if (cleanType !== "compile" && cleanType !== "all") return false;
76
+ await clearWechatIdeCacheByAutomator({
77
+ clean: cleanType,
78
+ projectPath
79
+ });
80
+ return true;
81
+ }
82
+ return false;
83
+ }
84
+ async function tryExecuteWechatIdeCliCommandByHttp(argv, projectPath) {
85
+ const command = argv[0];
86
+ if (!command) return false;
87
+ if (command === "compile") {
88
+ if (!projectPath) return false;
89
+ await openWechatIdeProjectByHttp(projectPath);
90
+ return true;
91
+ }
92
+ if (command === "reset-fileutils") {
93
+ if (!projectPath) return false;
94
+ await resetWechatIdeFileUtilsByHttp(projectPath);
95
+ return true;
96
+ }
97
+ if (command === "engine" && argv[1] === "build") {
98
+ const engineProjectPath = argv[2] || projectPath;
99
+ if (!engineProjectPath) return false;
100
+ await runWechatIdeEngineBuild(engineProjectPath, { logPath: readArgOption(argv, "--logPath", "-l") });
101
+ return true;
102
+ }
103
+ return false;
104
+ }
105
+ async function tryExecuteWechatIdeCliCommandByHelper(argv) {
106
+ const command = argv[0];
107
+ if (!command) return false;
108
+ if (command === "close") {
109
+ await closeWechatIdeProject();
110
+ return true;
111
+ }
112
+ if (command === "quit") {
113
+ await quitWechatIde();
114
+ return true;
115
+ }
116
+ if (command === "cache") {
117
+ const cleanType = readArgOption(argv, "--clean", "-c");
118
+ if (!cleanType) return false;
119
+ await clearWechatIdeCache({ clean: cleanType });
120
+ return true;
121
+ }
122
+ return false;
50
123
  }
51
124
  /**
52
- * @description 聚合 HMR JSONL profile,为命令行与后续仪表盘复用。
125
+ * @description 统一执行 weapp-ide-cli 命令,并在登录失效时复用同一套重试交互。
53
126
  */
54
- async function analyzeHmrProfile(options) {
55
- const lines = (await fs.readFile(options.profilePath, "utf8")).split(/\r?\n/);
56
- const samples = [];
57
- let skippedLineCount = 0;
58
- for (const line of lines) {
59
- const trimmed = line.trim();
60
- if (!trimmed) continue;
127
+ async function executeWechatIdeCliCommand(argv, options = {}) {
128
+ const { automatorMode = "prefer", cancelLevel = "warn", httpMode = "prefer", onNonLoginError, onRetry, projectPath } = options;
129
+ await runWithSuspendedSharedInput(async () => {
130
+ if (httpMode !== "skip") try {
131
+ if (await tryExecuteWechatIdeCliCommandByHttp(argv, projectPath)) return;
132
+ } catch (error) {
133
+ if (httpMode === "require") throw error;
134
+ }
61
135
  try {
62
- const parsed = JSON.parse(trimmed);
63
- if (!isFiniteNumber$1(parsed.totalMs)) {
64
- skippedLineCount += 1;
65
- continue;
136
+ if (await tryExecuteWechatIdeCliCommandByAutomator(argv, projectPath)) return;
137
+ } catch (error) {
138
+ if (automatorMode === "require") throw error;
139
+ }
140
+ try {
141
+ if (await tryExecuteWechatIdeCliCommandByHelper(argv)) return;
142
+ } catch (error) {
143
+ if (onNonLoginError) {
144
+ onNonLoginError(error);
145
+ return;
66
146
  }
67
- samples.push(parsed);
68
- } catch {
69
- skippedLineCount += 1;
147
+ throw error;
70
148
  }
71
- }
72
- const eventCounts = /* @__PURE__ */ new Map();
73
- const dirtyReasonCounts = /* @__PURE__ */ new Map();
74
- const pendingReasonCounts = /* @__PURE__ */ new Map();
75
- const totalValues = [];
76
- const buildCoreValues = [];
77
- const transformValues = [];
78
- const writeValues = [];
79
- const watchToDirtyValues = [];
80
- const emitValues = [];
81
- const sharedChunkValues = [];
82
- for (const sample of samples) {
83
- totalValues.push(sample.totalMs);
84
- if (sample.event) eventCounts.set(sample.event, (eventCounts.get(sample.event) ?? 0) + 1);
85
- if (isFiniteNumber$1(sample.buildCoreMs)) buildCoreValues.push(sample.buildCoreMs);
86
- if (isFiniteNumber$1(sample.transformMs)) transformValues.push(sample.transformMs);
87
- if (isFiniteNumber$1(sample.writeMs)) writeValues.push(sample.writeMs);
88
- if (isFiniteNumber$1(sample.watchToDirtyMs)) watchToDirtyValues.push(sample.watchToDirtyMs);
89
- if (isFiniteNumber$1(sample.emitMs)) emitValues.push(sample.emitMs);
90
- if (isFiniteNumber$1(sample.sharedChunkResolveMs)) sharedChunkValues.push(sample.sharedChunkResolveMs);
91
- collectCounts(dirtyReasonCounts, sample.dirtyReasonSummary);
92
- collectCounts(pendingReasonCounts, sample.pendingReasonSummary);
93
- }
94
- const orderedByTime = [...samples].sort((left, right) => {
95
- const leftTime = typeof left.timestamp === "string" ? Date.parse(left.timestamp) : NaN;
96
- const rightTime = typeof right.timestamp === "string" ? Date.parse(right.timestamp) : NaN;
97
- if (Number.isFinite(leftTime) && Number.isFinite(rightTime)) return leftTime - rightTime;
98
- return 0;
149
+ await runRetryableCommand({
150
+ createCancelError: () => /* @__PURE__ */ new Error("cancelled"),
151
+ execute: async () => {
152
+ try {
153
+ await parse(argv);
154
+ return null;
155
+ } catch (error) {
156
+ if (!isWechatIdeLoginRequiredError(error)) {
157
+ if (onNonLoginError) {
158
+ onNonLoginError(error);
159
+ return null;
160
+ }
161
+ throw error;
162
+ }
163
+ return error;
164
+ }
165
+ },
166
+ isRetryableResult: (result) => result !== null,
167
+ onCancel: () => {},
168
+ onRetry: () => {
169
+ onRetry?.();
170
+ },
171
+ promptRetry: async (error) => await promptWechatIdeLoginRetry({
172
+ cancelLevel,
173
+ error,
174
+ logger: logger_default
175
+ }),
176
+ shouldRetry: (action) => action === "retry"
177
+ });
99
178
  });
100
- const slowestSamples = [...samples].sort((left, right) => (right.totalMs ?? 0) - (left.totalMs ?? 0)).slice(0, options.topSlowest ?? 5);
101
- return {
102
- runtime: "mini",
103
- kind: "hmr-profile",
104
- generatedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
105
- profilePath: options.profilePath,
106
- sampleCount: samples.length,
107
- skippedLineCount,
108
- firstTimestamp: orderedByTime[0]?.timestamp,
109
- lastTimestamp: orderedByTime.at(-1)?.timestamp,
110
- metrics: {
111
- totalMs: createMetricSummary(totalValues),
112
- buildCoreMs: createMetricSummary(buildCoreValues),
113
- transformMs: createMetricSummary(transformValues),
114
- writeMs: createMetricSummary(writeValues),
115
- watchToDirtyMs: createMetricSummary(watchToDirtyValues),
116
- emitMs: createMetricSummary(emitValues),
117
- sharedChunkResolveMs: createMetricSummary(sharedChunkValues)
118
- },
119
- events: sortCountEntries(eventCounts),
120
- dirtyReasons: sortCountEntries(dirtyReasonCounts),
121
- pendingReasons: sortCountEntries(pendingReasonCounts),
122
- slowestSamples
123
- };
124
179
  }
125
180
  //#endregion
126
- //#region src/analyze/components/suggestions.ts
127
- function createComponentSuggestion(usage) {
128
- if (usage.componentPackage !== "__main__" || usage.crossPackageUsageCount === 0) return;
129
- if (usage.crossPackageUsageCount === usage.placeholderCoveredCrossPackageUsageCount) return;
130
- const pagePackages = Array.from(new Set(Array.from(usage.pages.values()).map((page) => page.packageId))).sort((left, right) => {
131
- if (left === "__main__") return -1;
132
- if (right === "__main__") return 1;
133
- return left.localeCompare(right);
134
- });
135
- const subPackageIds = pagePackages.filter((packageId) => packageId !== "__main__");
136
- const usedByMain = pagePackages.includes("__main__");
137
- if (subPackageIds.length === 1 && !usedByMain) {
138
- const targetPackage = subPackageIds[0];
139
- return {
140
- kind: "move-to-subpackage",
141
- component: usage.component,
142
- componentPackage: usage.componentPackage,
143
- targetPackage,
144
- pagePackages,
145
- message: `主包组件 ${usage.component} 仅被分包 ${targetPackage} 使用,建议评估移动到该分包。`
146
- };
147
- }
148
- if (subPackageIds.length > 1) return {
149
- kind: "shared-subpackage-or-placeholder",
150
- component: usage.component,
151
- componentPackage: usage.componentPackage,
152
- pagePackages,
153
- message: `主包组件 ${usage.component} 被多个分包使用,建议评估分包归属、共享策略或 componentPlaceholder。`
154
- };
155
- if (usedByMain && subPackageIds.length > 0) return {
156
- kind: "split-or-async",
157
- component: usage.component,
158
- componentPackage: usage.componentPackage,
159
- pagePackages,
160
- message: `主包组件 ${usage.component} 同时被主包和分包使用,建议评估组件拆分、归属或异步化策略。`
161
- };
181
+ //#region src/cli/openIde/close.ts
182
+ const execFileAsync = promisify(execFile);
183
+ async function closeIdeByAppleScript() {
184
+ if (process.platform !== "darwin") return false;
185
+ const appName = process.env.WEAPP_DEVTOOLS_APP_NAME || "wechatwebdevtools";
186
+ try {
187
+ await execFileAsync("osascript", ["-e", `tell application "${appName}" to quit`]);
188
+ return true;
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+ async function closeIdeByProcessKill(cliPath) {
194
+ if (!cliPath) return false;
195
+ const appContentsRoot = cliPath.includes(".app/") ? cliPath.slice(0, cliPath.indexOf(".app/") + 4) : path.dirname(path.dirname(cliPath));
196
+ try {
197
+ await execFileAsync("pkill", ["-f", appContentsRoot]);
198
+ return true;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+ /**
204
+ * @description 关闭微信开发者工具,并在 CLI 不可用时回退到系统级关闭。
205
+ */
206
+ async function closeIde$1() {
207
+ const config = await getConfig();
208
+ const cliPath = config.cliPath?.trim() ? config.cliPath : null;
209
+ try {
210
+ await closeWechatIdeProject();
211
+ return true;
212
+ } catch (error) {
213
+ if (isWechatIdeLoginRequiredError(error)) try {
214
+ await executeWechatIdeCliCommand(["close"], {
215
+ cancelLevel: "warn",
216
+ onNonLoginError: (retryError) => logger_default.error(retryError),
217
+ onRetry: () => logger_default.info("正在重试连接微信开发者工具...")
218
+ });
219
+ return true;
220
+ } catch (retryError) {
221
+ logger_default.error(retryError);
222
+ }
223
+ else {
224
+ logger_default.warn("微信开发者工具 CLI close 执行失败,尝试回退为系统级关闭。");
225
+ logger_default.error(error);
226
+ }
227
+ if (await closeIdeByAppleScript()) {
228
+ logger_default.info("已回退为系统级关闭微信开发者工具。");
229
+ return true;
230
+ }
231
+ if (await closeIdeByProcessKill(cliPath)) {
232
+ logger_default.info("已回退为进程级关闭微信开发者工具。");
233
+ return true;
234
+ }
235
+ return false;
236
+ }
162
237
  }
163
238
  //#endregion
164
- //#region src/analyze/components/index.ts
165
- function normalizeRoute(value) {
166
- return posix.normalize(value.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\.json$/, ""));
239
+ //#region src/cli/openIde/reuse.ts
240
+ function formatReuseOpenedWechatIdePrompt() {
241
+ return `目标项目已在微信开发者工具中打开,已跳过重复打开。按 ${colors.bold(colors.green("r"))} 关闭当前窗口后重新打开。`;
167
242
  }
168
- function isRecord(value) {
169
- return typeof value === "object" && value !== null && !Array.isArray(value);
243
+ async function openWechatIdeByAutomator(projectPath) {
244
+ (await launchAutomator({
245
+ projectPath,
246
+ trustProject: true
247
+ })).disconnect();
170
248
  }
171
- function toStringArray(value) {
172
- return Array.isArray(value) ? value.filter((item) => typeof item === "string" && item.trim() !== "") : [];
249
+ async function connectOpenedProject(projectPath) {
250
+ try {
251
+ return await connectOpenedAutomator({
252
+ projectPath,
253
+ timeout: 3e3
254
+ });
255
+ } catch {
256
+ return null;
257
+ }
173
258
  }
174
- function readUsingComponents(config) {
175
- if (!isRecord(config) || !isRecord(config.usingComponents)) return [];
176
- return Object.entries(config.usingComponents).filter((entry) => typeof entry[1] === "string" && entry[1].trim() !== "");
259
+ /**
260
+ * @description 若当前项目已在微信开发者工具中打开且自动化可连通,则直接复用现有会话,避免重复拉起 IDE。
261
+ */
262
+ async function tryReuseOpenedWechatIde(projectPath, closeIde) {
263
+ const miniProgram = await connectOpenedProject(projectPath);
264
+ if (!miniProgram) return null;
265
+ miniProgram.disconnect();
266
+ logger_default.info(formatReuseOpenedWechatIdePrompt());
267
+ if (await promptRetryKeypress({ logger: logger_default }) !== "retry") return {
268
+ reopened: false,
269
+ reused: true
270
+ };
271
+ logger_default.info(colors.bold(colors.green("正在关闭当前已打开项目,并重新拉起微信开发者工具...")));
272
+ if (!await closeIde()) logger_default.warn("关闭当前微信开发者工具失败,仍继续尝试重新打开目标项目。");
273
+ await openWechatIdeByAutomator(projectPath);
274
+ return {
275
+ reopened: true,
276
+ reused: false
277
+ };
177
278
  }
178
- function readComponentPlaceholder(config) {
179
- if (!isRecord(config) || !isRecord(config.componentPlaceholder)) return /* @__PURE__ */ new Set();
180
- return new Set(Object.keys(config.componentPlaceholder));
279
+ /**
280
+ * @description 对已打开的目标项目执行强制重开,以刷新最新构建产物。
281
+ */
282
+ async function reopenOpenedWechatIde(projectPath, closeIde) {
283
+ const miniProgram = await connectOpenedProject(projectPath);
284
+ if (!miniProgram) return false;
285
+ miniProgram.disconnect();
286
+ logger_default.info("目标项目已在微信开发者工具中打开,当前命令将主动重开以刷新最新构建产物。");
287
+ if (!await closeIde()) logger_default.warn("关闭当前微信开发者工具失败,仍继续尝试重新打开目标项目。");
288
+ await openWechatIdeByAutomator(projectPath);
289
+ return true;
181
290
  }
182
- function resolveComponentRoute(owner, request) {
183
- const normalizedRequest = request.replace(/\\/g, "/").trim();
184
- if (!normalizedRequest || normalizedRequest.startsWith("plugin://")) return;
185
- if (normalizedRequest.startsWith(".")) return normalizeRoute(posix.join(posix.dirname(owner), normalizedRequest));
186
- if (normalizedRequest.startsWith("/")) return normalizeRoute(normalizedRequest);
187
- return normalizeRoute(normalizedRequest);
291
+ //#endregion
292
+ //#region src/cli/openIde/index.ts
293
+ function shouldLogAutomatorFallbackError() {
294
+ const flag = process.env.WEAPP_VITE_DEBUG_AUTOMATOR_OPEN;
295
+ return flag === "1" || flag === "true";
188
296
  }
189
- function resolvePackageId(route, subPackages) {
190
- return subPackages.map((item) => item.root).filter(Boolean).sort((left, right) => right.length - left.length).find((root) => route === root || route.startsWith(`${root}/`)) ?? "__main__";
297
+ /**
298
+ * @description 执行 IDE 打开流程,并在登录失效时允许按键重试。
299
+ */
300
+ async function runWechatIdeOpenWithRetry(argv) {
301
+ await executeWechatIdeCliCommand(argv, {
302
+ cancelLevel: "warn",
303
+ onNonLoginError: (error) => logger_default.error(error),
304
+ onRetry: () => {
305
+ logger_default.info(colors.bold(colors.green("正在重试连接微信开发者工具...")));
306
+ }
307
+ });
191
308
  }
192
- function collectAppPages(configs) {
193
- const appJson = configs.get("app");
194
- if (!isRecord(appJson)) return /* @__PURE__ */ new Set();
195
- const pages = /* @__PURE__ */ new Set();
196
- for (const page of toStringArray(appJson.pages)) pages.add(normalizeRoute(page));
197
- const subPackages = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
198
- for (const item of subPackages) {
199
- if (!isRecord(item) || typeof item.root !== "string") continue;
200
- for (const page of toStringArray(item.pages)) pages.add(normalizeRoute(posix.join(item.root, page)));
201
- }
202
- return pages;
309
+ /**
310
+ * @description 根据 mpDistRoot 推导 IDE 项目目录(目录内应包含 project/mini 配置)
311
+ */
312
+ function resolveIdeProjectPath(mpDistRoot) {
313
+ if (!mpDistRoot || !mpDistRoot.trim()) return;
314
+ const parent = path.dirname(mpDistRoot);
315
+ if (!parent || parent === "." || parent === "/") return;
316
+ return parent;
203
317
  }
204
- function registerUsage(usageMap, edge, page, pagePackage, componentPackage) {
205
- const usage = usageMap.get(edge.component) ?? {
206
- component: edge.component,
207
- componentPackage,
208
- totalUsageCount: 0,
209
- pages: /* @__PURE__ */ new Map(),
210
- crossPackageUsageCount: 0,
211
- placeholderCoveredCrossPackageUsageCount: 0
212
- };
213
- usage.totalUsageCount += 1;
214
- const pageUsage = usage.pages.get(page) ?? {
215
- page,
216
- packageId: pagePackage,
217
- usageCount: 0
218
- };
219
- pageUsage.usageCount += 1;
220
- usage.pages.set(page, pageUsage);
221
- if (pagePackage !== componentPackage) {
222
- usage.crossPackageUsageCount += 1;
223
- if (edge.placeholderCovered) usage.placeholderCoveredCrossPackageUsageCount += 1;
318
+ /**
319
+ * @description 结合 mpDistRoot 与配置根目录解析最终 IDE 项目目录。
320
+ */
321
+ function resolveIdeProjectRoot(mpDistRoot, cwd) {
322
+ return resolveIdeProjectPath(mpDistRoot) ?? cwd;
323
+ }
324
+ async function closeIde() {
325
+ return await closeIde$1();
326
+ }
327
+ async function tryOpenWechatIdeByAutomator(projectPath, options) {
328
+ if (options.reuseOpenedProject === false) {
329
+ if (await reopenOpenedWechatIde(projectPath, closeIde)) return true;
224
330
  }
225
- usageMap.set(edge.component, usage);
331
+ const reuseResult = await tryReuseOpenedWechatIde(projectPath, closeIde);
332
+ if (reuseResult?.reused || reuseResult?.reopened) return true;
333
+ await openWechatIdeByAutomator(projectPath);
334
+ return true;
226
335
  }
227
- function collectAnalyzeComponentJsonConfigs(output) {
228
- if (!output) return [];
229
- const configs = [];
230
- for (const item of output.output ?? []) {
231
- if (item.type !== "asset" || !item.fileName.endsWith(".json")) continue;
232
- const asset = item;
233
- if (typeof asset.source !== "string") continue;
336
+ /**
337
+ * @description 打开后主动刷新微信开发者工具的项目索引,避免模拟器沿用过期 app 配置。
338
+ */
339
+ async function stabilizeOpenedWechatIdeProject(projectPath, servicePortEnabled) {
340
+ if (servicePortEnabled === false) return;
341
+ try {
342
+ await executeWechatIdeCliCommand(["compile"], {
343
+ httpMode: "prefer",
344
+ onNonLoginError: (error) => logger_default.error(error),
345
+ projectPath
346
+ });
347
+ await executeWechatIdeCliCommand([
348
+ "reset-fileutils",
349
+ "-p",
350
+ projectPath
351
+ ], {
352
+ httpMode: "prefer",
353
+ onNonLoginError: (error) => logger_default.error(error),
354
+ projectPath
355
+ });
356
+ await executeWechatIdeCliCommand([
357
+ "engine",
358
+ "build",
359
+ projectPath
360
+ ], {
361
+ httpMode: "prefer",
362
+ onNonLoginError: (error) => logger_default.error(error),
363
+ projectPath
364
+ });
234
365
  try {
235
- configs.push({
236
- file: normalizeRoute(asset.fileName),
237
- config: JSON.parse(asset.source)
366
+ await executeWechatIdeCliCommand(["compile"], {
367
+ automatorMode: "require",
368
+ httpMode: "skip",
369
+ projectPath
238
370
  });
239
- } catch {}
371
+ } catch (error) {
372
+ if (shouldLogAutomatorFallbackError()) logger_default.error(error);
373
+ }
374
+ } catch (error) {
375
+ logger_default.warn("刷新微信开发者工具项目索引失败,已保留当前打开状态;如模拟器仍显示旧状态,可手动刷新一次。");
376
+ if (shouldLogAutomatorFallbackError()) logger_default.error(error);
240
377
  }
241
- return configs;
242
378
  }
243
- function analyzeComponentUsage(options) {
244
- const configs = /* @__PURE__ */ new Map();
245
- for (const item of options.jsonConfigs) configs.set(normalizeRoute(item.file), item.config);
246
- const pages = collectAppPages(configs);
247
- const graph = /* @__PURE__ */ new Map();
248
- const packageMap = /* @__PURE__ */ new Map();
249
- for (const route of configs.keys()) packageMap.set(route, resolvePackageId(route, options.subPackages));
250
- for (const [owner, config] of configs) {
251
- const placeholders = readComponentPlaceholder(config);
252
- const edges = readUsingComponents(config).map(([name, request]) => {
253
- const component = resolveComponentRoute(owner, request);
254
- return component && configs.has(component) ? {
255
- owner,
256
- component,
257
- placeholderCovered: placeholders.has(name)
258
- } : void 0;
259
- }).filter((edge) => Boolean(edge));
260
- if (edges.length > 0) graph.set(owner, edges);
379
+ function createIdeOpenArgv(platform, projectPath, options = {}) {
380
+ const argv = ["open", "-p"];
381
+ if (projectPath) argv.push(projectPath);
382
+ if (platform === "weapp" && options.trustProject !== false) argv.push("--trust-project");
383
+ if (platform && shouldPassPlatformArgToIdeOpen(platform)) argv.push("--platform", platform);
384
+ return argv;
385
+ }
386
+ async function openIde(platform, projectPath, options = {}) {
387
+ let bootstrapResult;
388
+ if (platform === "weapp" && projectPath) try {
389
+ bootstrapResult = await bootstrapWechatDevtoolsSettings({
390
+ projectPath,
391
+ trustProject: options.trustProject
392
+ });
393
+ } catch (error) {
394
+ logger_default.warn("检测微信开发者工具服务端口或写入项目信任状态失败,继续执行 open 流程。");
395
+ logger_default.error(error);
261
396
  }
262
- const usageMap = /* @__PURE__ */ new Map();
263
- const visit = (owner, page, stack) => {
264
- for (const edge of graph.get(owner) ?? []) {
265
- const componentPackage = packageMap.get(edge.component) ?? "__main__";
266
- registerUsage(usageMap, edge, page, packageMap.get(page) ?? "__main__", componentPackage);
267
- if (stack.has(edge.component)) continue;
268
- const nextStack = new Set(stack);
269
- nextStack.add(edge.component);
270
- visit(edge.component, page, nextStack);
397
+ if (platform === "weapp" && projectPath && bootstrapResult?.servicePortEnabled === false) logger_default.warn("检测到微信开发者工具服务端口当前处于关闭状态,已保留用户设置并回退到普通 open 流程。");
398
+ if (platform === "weapp" && projectPath && options.trustProject !== false && bootstrapResult?.servicePortEnabled !== false) try {
399
+ if (await tryOpenWechatIdeByAutomator(projectPath, options)) {
400
+ await stabilizeOpenedWechatIdeProject(projectPath, bootstrapResult?.servicePortEnabled);
401
+ return;
271
402
  }
272
- };
273
- for (const page of pages) visit(page, page, new Set([page]));
274
- return Array.from(usageMap.values()).map((usage) => {
275
- const pages = Array.from(usage.pages.values()).sort((left, right) => left.page.localeCompare(right.page));
276
- const suggestions = [createComponentSuggestion(usage)].filter((item) => Boolean(item));
403
+ } catch (error) {
404
+ if (isAutomatorLoginError(error)) {
405
+ logger_default.error("检测到微信开发者工具登录状态失效,请先登录后重试。");
406
+ logger_default.warn(formatAutomatorLoginError(error));
407
+ }
408
+ logger_default.warn("通过 automator 启动微信开发者工具并自动信任项目失败,回退到普通 open 流程。");
409
+ if (shouldLogAutomatorFallbackError()) logger_default.error(error);
410
+ }
411
+ await runWechatIdeOpenWithRetry(createIdeOpenArgv(platform, projectPath, options));
412
+ if (platform === "weapp" && projectPath) await stabilizeOpenedWechatIdeProject(projectPath, bootstrapResult?.servicePortEnabled);
413
+ }
414
+ /**
415
+ * @description 解析 IDE 相关命令所需的平台、项目目录与配置上下文。
416
+ */
417
+ async function resolveIdeCommandContext(options) {
418
+ const cwd = options.cwd ?? process.cwd();
419
+ let platform = options.platform;
420
+ let projectPath = options.projectPath;
421
+ if (!platform || !projectPath) try {
422
+ const ctx = await createCompilerContext({
423
+ cwd,
424
+ mode: options.mode ?? "development",
425
+ configFile: options.configFile,
426
+ inlineConfig: createInlineConfig(platform),
427
+ cliPlatform: options.cliPlatform
428
+ });
429
+ platform ??= ctx.configService.platform;
430
+ if (!projectPath) projectPath = resolveIdeProjectRoot(ctx.configService.mpDistRoot, ctx.configService.cwd);
277
431
  return {
278
- component: usage.component,
279
- componentPackage: usage.componentPackage,
280
- totalUsageCount: usage.totalUsageCount,
281
- pageUsageCount: pages.length,
282
- pages,
283
- suggestions
432
+ cwd: ctx.configService.cwd,
433
+ platform,
434
+ projectPath,
435
+ weappViteConfig: ctx.configService.weappViteConfig,
436
+ mpDistRoot: ctx.configService.mpDistRoot
284
437
  };
285
- }).sort((left, right) => {
286
- const usageDelta = right.totalUsageCount - left.totalUsageCount;
287
- return usageDelta !== 0 ? usageDelta : left.component.localeCompare(right.component);
288
- });
289
- }
290
- //#endregion
291
- //#region src/analyze/subpackages/metadata.ts
292
- const defaultTotalBudgetBytes = 20 * 1024 * 1024;
293
- const defaultPackageBudgetBytes = 2 * 1024 * 1024;
294
- const defaultWarningRatio = .85;
295
- const defaultHistoryDir = ".weapp-vite/analyze-history";
296
- const defaultHistoryLimit = 20;
297
- function resolveBudgetValue(value, fallback) {
298
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
299
- }
300
- function resolveHistoryLimit(value) {
301
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : defaultHistoryLimit;
302
- }
303
- function resolveAnalyzeBudgets(configService) {
304
- const budgets = configService.weappViteConfig.analyze?.budgets;
305
- const legacyPackageBudget = configService.weappViteConfig.packageSizeWarningBytes;
306
- const packageFallback = resolveBudgetValue(legacyPackageBudget, defaultPackageBudgetBytes);
307
- return {
308
- totalBytes: resolveBudgetValue(budgets?.totalBytes, defaultTotalBudgetBytes),
309
- mainBytes: resolveBudgetValue(budgets?.mainBytes, packageFallback),
310
- subPackageBytes: resolveBudgetValue(budgets?.subPackageBytes, packageFallback),
311
- independentBytes: resolveBudgetValue(budgets?.independentBytes, packageFallback),
312
- warningRatio: resolveBudgetValue(budgets?.warningRatio, defaultWarningRatio),
313
- source: budgets ? "config" : "default"
314
- };
315
- }
316
- function resolveAnalyzeHistoryMetadata(configService) {
317
- const history = configService.weappViteConfig.analyze?.history;
318
- if (history === false) return {
319
- enabled: false,
320
- dir: path.resolve(configService.cwd, defaultHistoryDir),
321
- limit: defaultHistoryLimit
322
- };
323
- const historyConfig = typeof history === "object" && history ? history : {};
324
- const rawDir = typeof historyConfig.dir === "string" && historyConfig.dir.trim() ? historyConfig.dir.trim() : defaultHistoryDir;
325
- return {
326
- enabled: historyConfig.enabled !== false,
327
- dir: path.isAbsolute(rawDir) ? rawDir : path.resolve(configService.cwd, rawDir),
328
- limit: resolveHistoryLimit(historyConfig.limit)
329
- };
330
- }
331
- function createAnalyzeMetadata(configService, now = /* @__PURE__ */ new Date()) {
332
- const history = resolveAnalyzeHistoryMetadata(configService);
438
+ } catch {}
439
+ if (!projectPath) {
440
+ const defaultProjectRoot = getDefaultIdeProjectRoot(platform);
441
+ if (defaultProjectRoot) projectPath = resolveIdeProjectRoot(defaultProjectRoot, cwd);
442
+ }
333
443
  return {
334
- generatedAt: now.toISOString(),
335
- budgets: resolveAnalyzeBudgets(configService),
336
- history: {
337
- ...history,
338
- dir: configService.relativeCwd(history.dir)
339
- }
444
+ cwd,
445
+ platform,
446
+ projectPath
340
447
  };
341
448
  }
342
449
  //#endregion
343
- //#region src/analyze/subpackages/classifier.ts
344
- const VIRTUAL_MODULE_INDICATOR = "\0";
345
- const VIRTUAL_PREFIX = `${SHARED_CHUNK_VIRTUAL_PREFIX}/`;
346
- function classifyModuleSourceKind(options) {
347
- if (options.isNodeModule) return "node_modules";
348
- if (options.inSrc) return "src";
349
- if (options.inPlugin) return "plugin";
350
- return "workspace";
450
+ //#region src/cli/options.ts
451
+ function filterDuplicateOptions(options) {
452
+ for (const [key, value] of Object.entries(options)) if (Array.isArray(value)) options[key] = value.at(-1);
351
453
  }
352
- function resolvePluginAssetAbsolute(normalizedFileName, pluginRoot) {
353
- if (!pluginRoot) return;
354
- const pluginBase = posix.basename(pluginRoot);
355
- if (normalizedFileName !== pluginBase && !normalizedFileName.startsWith(`${pluginBase}/`)) return;
356
- const relative = normalizedFileName === pluginBase ? "" : normalizedFileName.slice(pluginBase.length + 1);
357
- const absolute = posix.resolve(pluginRoot, relative);
358
- return isPathInside(pluginRoot, absolute) ? absolute : void 0;
454
+ function resolveConfigFile(options) {
455
+ if (typeof options.config === "string") return options.config;
456
+ if (typeof options.c === "string") return options.c;
359
457
  }
360
- function resolveSubPackageRoot$1(fileName, context) {
361
- const normalized = posix.normalize(fileName);
362
- return Array.from(context.subPackageRoots).filter(Boolean).sort((left, right) => right.length - left.length).find((root) => normalized === root || normalized.startsWith(`${root}/`));
458
+ function convertBase(value) {
459
+ if (value === 0) return "";
460
+ return value;
363
461
  }
364
- function classifyPackage(fileName, origin, context) {
365
- if (fileName.startsWith(VIRTUAL_PREFIX)) {
366
- const combination = fileName.slice(VIRTUAL_PREFIX.length).split("/")[0] || "shared";
367
- return {
368
- id: `virtual:${combination}`,
369
- label: `共享虚拟包 ${combination}`,
370
- type: "virtual"
371
- };
372
- }
373
- const rootCandidate = resolveSubPackageRoot$1(fileName, context);
374
- if (rootCandidate) {
375
- const isIndependent = context.independentRoots.has(rootCandidate);
376
- return {
377
- id: rootCandidate,
378
- label: `${isIndependent ? "独立分包" : "分包"} ${rootCandidate}`,
379
- type: isIndependent || origin === "independent" ? "independent" : "subPackage"
380
- };
462
+ function coerceBooleanOption(value) {
463
+ if (value === void 0) return;
464
+ if (typeof value === "boolean") return value;
465
+ if (typeof value === "string") {
466
+ const normalized = value.trim().toLowerCase();
467
+ if (normalized === "") return true;
468
+ if (normalized === "false" || normalized === "0" || normalized === "off" || normalized === "no") return false;
469
+ if (normalized === "true" || normalized === "1" || normalized === "on" || normalized === "yes") return true;
470
+ return true;
381
471
  }
472
+ if (typeof value === "number") return value !== 0;
473
+ return Boolean(value);
474
+ }
475
+ function isUiEnabled(options) {
476
+ return Boolean(options.ui || options.analyze);
477
+ }
478
+ //#endregion
479
+ //#region src/cli/commands/alipayExecute.ts
480
+ function createSpawnOptions() {
382
481
  return {
383
- id: "__main__",
384
- label: "主包",
385
- type: "main"
482
+ shell: process.platform === "win32",
483
+ stdio: "inherit"
386
484
  };
387
485
  }
388
- function normalizeModuleId(id) {
389
- if (!id || id.includes(VIRTUAL_MODULE_INDICATOR)) return;
390
- if (!posix.isAbsolute(id)) return;
391
- return posix.normalize(id);
486
+ /**
487
+ * @description 执行本机 minidev 命令。
488
+ */
489
+ async function runSpawnMinidev(command, argv, runner) {
490
+ await new Promise((resolve, reject) => {
491
+ const child = runner(command, argv, createSpawnOptions());
492
+ child.on("error", (error) => {
493
+ reject(error);
494
+ });
495
+ child.on("exit", (code, signal) => {
496
+ if (code === 0) {
497
+ resolve();
498
+ return;
499
+ }
500
+ reject(/* @__PURE__ */ new Error(signal ? `minidev ${argv[0] ?? ""} exited with signal ${signal}` : `minidev ${argv[0] ?? ""} exited with code ${code ?? "unknown"}`));
501
+ });
502
+ });
392
503
  }
393
- function resolveModuleSourceType(absoluteId, ctx) {
394
- const { configService } = ctx;
395
- const isNodeModule = absoluteId.includes("/node_modules/") || absoluteId.includes("\\node_modules\\");
396
- const pluginRoot = configService.absolutePluginRoot;
397
- const srcRoot = configService.absoluteSrcRoot;
398
- const sourceType = classifyModuleSourceKind({
399
- isNodeModule,
400
- inSrc: isPathInside(srcRoot, absoluteId),
401
- inPlugin: pluginRoot ? isPathInside(pluginRoot, absoluteId) : false
504
+ /**
505
+ * @description 使用系统进程执行本机 minidev 命令。
506
+ */
507
+ async function spawnMinidev(command, argv) {
508
+ return await runSpawnMinidev(command, argv, spawn);
509
+ }
510
+ //#endregion
511
+ //#region src/cli/commands/alipay.ts
512
+ function normalizePassthroughArgs(args) {
513
+ return Array.isArray(args) ? args.filter((arg) => typeof arg === "string") : [];
514
+ }
515
+ function appendOption(argv, name, value) {
516
+ if (typeof value === "string" && value.trim()) argv.push(name, value);
517
+ }
518
+ function hasOption(argv, ...names) {
519
+ return argv.some((arg) => names.includes(arg) || names.some((name) => arg.startsWith(`${name}=`)));
520
+ }
521
+ function normalizeAlipayAction(action) {
522
+ if (action === "open") return "ide";
523
+ if (action === "ide" || action === "login" || action === "preview" || action === "upload") return action;
524
+ throw new Error(`未知 alipay 子命令: ${action ?? "(empty)"}`);
525
+ }
526
+ function resolveProjectPath(root, resolvedProjectPath, options) {
527
+ if (typeof options.project === "string" && options.project.trim()) return options.project;
528
+ return root ?? resolvedProjectPath;
529
+ }
530
+ function resolveMinidevCommand(options) {
531
+ return typeof options.minidev === "string" && options.minidev.trim() ? options.minidev : "minidev";
532
+ }
533
+ function createMinidevArgv(action, root, resolvedProjectPath, options) {
534
+ const passthroughArgs = normalizePassthroughArgs(options["--"]);
535
+ const argv = [action];
536
+ const projectPath = resolveProjectPath(root, resolvedProjectPath, options);
537
+ if ((action === "ide" || action === "preview" || action === "upload") && projectPath && !hasOption(passthroughArgs, "--project", "-p")) argv.push("--project", path.normalize(projectPath));
538
+ if ((action === "preview" || action === "upload") && !hasOption(passthroughArgs, "--app-id", "-a")) appendOption(argv, "--app-id", options.appId);
539
+ if ((action === "login" || action === "preview" || action === "upload") && !hasOption(passthroughArgs, "--client-type", "-c")) appendOption(argv, "--client-type", options.clientType);
540
+ if (action === "upload" && !hasOption(passthroughArgs, "--version", "-v")) appendOption(argv, "--version", options.version);
541
+ argv.push(...passthroughArgs);
542
+ return argv;
543
+ }
544
+ async function runAlipayCommand(action, root, options) {
545
+ const normalizedAction = normalizeAlipayAction(action);
546
+ filterDuplicateOptions(options);
547
+ const argv = createMinidevArgv(normalizedAction, root, (await resolveIdeCommandContext({
548
+ configFile: resolveConfigFile(options),
549
+ mode: options.mode ?? (normalizedAction === "upload" ? "production" : "development"),
550
+ platform: "alipay",
551
+ projectPath: root ?? options.project,
552
+ cliPlatform: "alipay"
553
+ })).projectPath, options);
554
+ const command = resolveMinidevCommand(options);
555
+ logger_default.info(`执行支付宝小程序 CLI:${command} ${argv.join(" ")}`);
556
+ await spawnMinidev(command, argv);
557
+ }
558
+ function registerAlipayCommand(cli) {
559
+ cli.command("alipay [action] [root]", "run Alipay minidev ide, login, preview, or upload").option("-a, --app-id <appId>", "[string] Alipay mini program appId").option("-c, --client-type <clientType>", "[string] minidev client type").option("--minidev <command>", "[string] minidev executable path or command name").option("--project <path>", "[string] Alipay mini program project path").option("--version <version>", "[string] upload version").allowUnknownOptions().action(async (action, root, options) => {
560
+ await runAlipayCommand(action, root, options);
402
561
  });
562
+ }
563
+ //#endregion
564
+ //#region src/analyze/hmr.ts
565
+ function createMetricSummary(values) {
566
+ if (!values.length) return { count: 0 };
567
+ const total = values.reduce((sum, value) => sum + value, 0);
403
568
  return {
404
- source: configService.relativeAbsoluteSrcRoot(absoluteId),
405
- sourceType
569
+ count: values.length,
570
+ averageMs: total / values.length,
571
+ maxMs: Math.max(...values)
406
572
  };
407
573
  }
408
- function resolveAssetSource(fileName, ctx) {
409
- const { configService } = ctx;
410
- const normalized = posix.normalize(fileName);
411
- const srcCandidate = posix.resolve(configService.absoluteSrcRoot, normalized);
412
- if (isPathInside(configService.absoluteSrcRoot, srcCandidate)) return {
413
- absolute: srcCandidate,
414
- source: configService.relativeAbsoluteSrcRoot(srcCandidate),
415
- sourceType: "src"
416
- };
417
- const pluginAbsolute = resolvePluginAssetAbsolute(normalized, configService.absolutePluginRoot);
418
- if (pluginAbsolute) return {
419
- absolute: pluginAbsolute,
420
- source: configService.relativeAbsoluteSrcRoot(pluginAbsolute),
421
- sourceType: "plugin"
422
- };
423
- }
424
- //#endregion
425
- //#region src/analyze/subpackages/registry.ts
426
- function ensurePackage(packages, classification) {
427
- const existing = packages.get(classification.id);
428
- if (existing) return existing;
429
- const created = {
430
- ...classification,
431
- files: /* @__PURE__ */ new Map()
432
- };
433
- packages.set(classification.id, created);
434
- return created;
435
- }
436
- function ensureModule(modules, id, source, sourceType) {
437
- const existing = modules.get(id);
438
- if (existing) return existing;
439
- const created = {
440
- id,
441
- source,
442
- sourceType,
443
- packages: /* @__PURE__ */ new Map()
444
- };
445
- modules.set(id, created);
446
- return created;
574
+ function sortCountEntries(map) {
575
+ return [...map.entries()].sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0])).map(([name, count]) => ({
576
+ name,
577
+ count
578
+ }));
447
579
  }
448
- function registerModuleInPackage(modules, moduleId, source, sourceType, packageId, fileName) {
449
- const moduleEntry = ensureModule(modules, moduleId, source, sourceType);
450
- const files = moduleEntry.packages.get(packageId) ?? /* @__PURE__ */ new Set();
451
- files.add(fileName);
452
- moduleEntry.packages.set(packageId, files);
580
+ function collectCounts(target, values) {
581
+ for (const value of values ?? []) {
582
+ if (!value) continue;
583
+ target.set(value, (target.get(value) ?? 0) + 1);
584
+ }
453
585
  }
454
- //#endregion
455
- //#region src/analyze/subpackages/output.ts
456
- function getAssetBuffer(asset) {
457
- if (typeof asset.source === "string") return Buffer.from(asset.source, "utf8");
458
- if (asset.source instanceof Uint8Array) return Buffer.from(asset.source);
586
+ function isFiniteNumber$1(value) {
587
+ return typeof value === "number" && Number.isFinite(value);
459
588
  }
460
- function getCompressedSizes$1(content) {
461
- if (content === void 0) return {};
462
- const buffer = typeof content === "string" ? Buffer.from(content, "utf8") : Buffer.from(content);
589
+ /**
590
+ * @description 聚合 HMR JSONL profile,为命令行与后续仪表盘复用。
591
+ */
592
+ async function analyzeHmrProfile(options) {
593
+ const lines = (await fs.readFile(options.profilePath, "utf8")).split(/\r?\n/);
594
+ const samples = [];
595
+ let skippedLineCount = 0;
596
+ for (const line of lines) {
597
+ const trimmed = line.trim();
598
+ if (!trimmed) continue;
599
+ try {
600
+ const parsed = JSON.parse(trimmed);
601
+ if (!isFiniteNumber$1(parsed.totalMs)) {
602
+ skippedLineCount += 1;
603
+ continue;
604
+ }
605
+ samples.push(parsed);
606
+ } catch {
607
+ skippedLineCount += 1;
608
+ }
609
+ }
610
+ const eventCounts = /* @__PURE__ */ new Map();
611
+ const dirtyReasonCounts = /* @__PURE__ */ new Map();
612
+ const pendingReasonCounts = /* @__PURE__ */ new Map();
613
+ const totalValues = [];
614
+ const buildCoreValues = [];
615
+ const transformValues = [];
616
+ const writeValues = [];
617
+ const watchToDirtyValues = [];
618
+ const emitValues = [];
619
+ const sharedChunkValues = [];
620
+ for (const sample of samples) {
621
+ totalValues.push(sample.totalMs);
622
+ if (sample.event) eventCounts.set(sample.event, (eventCounts.get(sample.event) ?? 0) + 1);
623
+ if (isFiniteNumber$1(sample.buildCoreMs)) buildCoreValues.push(sample.buildCoreMs);
624
+ if (isFiniteNumber$1(sample.transformMs)) transformValues.push(sample.transformMs);
625
+ if (isFiniteNumber$1(sample.writeMs)) writeValues.push(sample.writeMs);
626
+ if (isFiniteNumber$1(sample.watchToDirtyMs)) watchToDirtyValues.push(sample.watchToDirtyMs);
627
+ if (isFiniteNumber$1(sample.emitMs)) emitValues.push(sample.emitMs);
628
+ if (isFiniteNumber$1(sample.sharedChunkResolveMs)) sharedChunkValues.push(sample.sharedChunkResolveMs);
629
+ collectCounts(dirtyReasonCounts, sample.dirtyReasonSummary);
630
+ collectCounts(pendingReasonCounts, sample.pendingReasonSummary);
631
+ }
632
+ const orderedByTime = [...samples].sort((left, right) => {
633
+ const leftTime = typeof left.timestamp === "string" ? Date.parse(left.timestamp) : NaN;
634
+ const rightTime = typeof right.timestamp === "string" ? Date.parse(right.timestamp) : NaN;
635
+ if (Number.isFinite(leftTime) && Number.isFinite(rightTime)) return leftTime - rightTime;
636
+ return 0;
637
+ });
638
+ const slowestSamples = [...samples].sort((left, right) => (right.totalMs ?? 0) - (left.totalMs ?? 0)).slice(0, options.topSlowest ?? 5);
463
639
  return {
464
- gzipSize: gzipSync(buffer).byteLength,
465
- brotliSize: brotliCompressSync(buffer).byteLength
640
+ runtime: "mini",
641
+ kind: "hmr-profile",
642
+ generatedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
643
+ profilePath: options.profilePath,
644
+ sampleCount: samples.length,
645
+ skippedLineCount,
646
+ firstTimestamp: orderedByTime[0]?.timestamp,
647
+ lastTimestamp: orderedByTime.at(-1)?.timestamp,
648
+ metrics: {
649
+ totalMs: createMetricSummary(totalValues),
650
+ buildCoreMs: createMetricSummary(buildCoreValues),
651
+ transformMs: createMetricSummary(transformValues),
652
+ writeMs: createMetricSummary(writeValues),
653
+ watchToDirtyMs: createMetricSummary(watchToDirtyValues),
654
+ emitMs: createMetricSummary(emitValues),
655
+ sharedChunkResolveMs: createMetricSummary(sharedChunkValues)
656
+ },
657
+ events: sortCountEntries(eventCounts),
658
+ dirtyReasons: sortCountEntries(dirtyReasonCounts),
659
+ pendingReasons: sortCountEntries(pendingReasonCounts),
660
+ slowestSamples
466
661
  };
467
662
  }
468
- function processChunk(chunk, origin, ctx, classifierContext, packages, modules) {
469
- const classification = classifyPackage(chunk.fileName, origin, classifierContext);
470
- const packageEntry = ensurePackage(packages, classification);
471
- const chunkEntry = {
472
- file: chunk.fileName,
473
- type: "chunk",
474
- from: origin,
475
- size: typeof chunk.code === "string" ? Buffer.byteLength(chunk.code, "utf8") : void 0,
476
- ...getCompressedSizes$1(chunk.code),
477
- isEntry: chunk.isEntry,
478
- modules: []
479
- };
480
- const moduleEntries = Object.entries(chunk.modules ?? {});
481
- for (const [rawModuleId, info] of moduleEntries) {
482
- const absoluteId = normalizeModuleId(rawModuleId);
483
- if (!absoluteId) continue;
484
- const { source, sourceType } = resolveModuleSourceType(absoluteId, ctx);
485
- const moduleEntry = {
486
- id: absoluteId,
487
- source,
488
- sourceType,
489
- bytes: info?.renderedLength
663
+ //#endregion
664
+ //#region src/analyze/components/suggestions.ts
665
+ function createComponentSuggestion(usage) {
666
+ if (usage.componentPackage !== "__main__" || usage.crossPackageUsageCount === 0) return;
667
+ if (usage.crossPackageUsageCount === usage.placeholderCoveredCrossPackageUsageCount) return;
668
+ const pagePackages = Array.from(new Set(Array.from(usage.pages.values()).map((page) => page.packageId))).sort((left, right) => {
669
+ if (left === "__main__") return -1;
670
+ if (right === "__main__") return 1;
671
+ return left.localeCompare(right);
672
+ });
673
+ const subPackageIds = pagePackages.filter((packageId) => packageId !== "__main__");
674
+ const usedByMain = pagePackages.includes("__main__");
675
+ if (subPackageIds.length === 1 && !usedByMain) {
676
+ const targetPackage = subPackageIds[0];
677
+ return {
678
+ kind: "move-to-subpackage",
679
+ component: usage.component,
680
+ componentPackage: usage.componentPackage,
681
+ targetPackage,
682
+ pagePackages,
683
+ message: `主包组件 ${usage.component} 仅被分包 ${targetPackage} 使用,建议评估移动到该分包。`
490
684
  };
491
- if (typeof info?.code === "string") moduleEntry.originalBytes = Buffer.byteLength(info.code, "utf8");
492
- chunkEntry.modules.push(moduleEntry);
493
- registerModuleInPackage(modules, absoluteId, source, sourceType, classification.id, chunk.fileName);
494
685
  }
495
- if (chunkEntry.modules) chunkEntry.modules.sort((a, b) => a.source.localeCompare(b.source));
496
- packageEntry.files.set(chunk.fileName, chunkEntry);
497
- }
498
- function processAsset(asset, origin, ctx, classifierContext, packages, modules) {
499
- const classification = classifyPackage(asset.fileName, origin, classifierContext);
500
- const packageEntry = ensurePackage(packages, classification);
501
- const assetBuffer = getAssetBuffer(asset);
502
- const entry = {
503
- file: asset.fileName,
504
- type: "asset",
505
- from: origin,
506
- size: assetBuffer?.byteLength,
507
- ...getCompressedSizes$1(assetBuffer)
686
+ if (subPackageIds.length > 1) return {
687
+ kind: "shared-subpackage-or-placeholder",
688
+ component: usage.component,
689
+ componentPackage: usage.componentPackage,
690
+ pagePackages,
691
+ message: `主包组件 ${usage.component} 被多个分包使用,建议评估分包归属、共享策略或 componentPlaceholder。`
692
+ };
693
+ if (usedByMain && subPackageIds.length > 0) return {
694
+ kind: "split-or-async",
695
+ component: usage.component,
696
+ componentPackage: usage.componentPackage,
697
+ pagePackages,
698
+ message: `主包组件 ${usage.component} 同时被主包和分包使用,建议评估组件拆分、归属或异步化策略。`
508
699
  };
509
- const assetSource = resolveAssetSource(asset.fileName, ctx);
510
- if (assetSource) {
511
- entry.source = assetSource.source;
512
- registerModuleInPackage(modules, assetSource.absolute, assetSource.source, assetSource.sourceType, classification.id, asset.fileName);
513
- }
514
- packageEntry.files.set(asset.fileName, entry);
515
- }
516
- function processOutput(output, origin, ctx, classifierContext, packages, modules) {
517
- if (!output) return;
518
- for (const item of output.output ?? []) if (item.type === "chunk") processChunk(item, origin, ctx, classifierContext, packages, modules);
519
- else if (item.type === "asset") processAsset(item, origin, ctx, classifierContext, packages, modules);
520
700
  }
521
701
  //#endregion
522
- //#region src/analyze/subpackages/summary.ts
523
- function toArray(value) {
524
- return Array.from(value);
702
+ //#region src/analyze/components/index.ts
703
+ function normalizeRoute(value) {
704
+ return posix.normalize(value.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\.json$/, ""));
525
705
  }
526
- function summarizePackages(packages) {
527
- const order = {
528
- main: 0,
529
- subPackage: 1,
530
- independent: 2,
531
- virtual: 3
532
- };
533
- const reports = toArray(packages.values()).map((pkg) => {
534
- const files = toArray(pkg.files.values());
535
- files.sort((a, b) => a.file.localeCompare(b.file));
536
- return {
537
- id: pkg.id,
538
- label: pkg.label,
539
- type: pkg.type,
540
- files
541
- };
542
- });
543
- reports.sort((a, b) => {
544
- const delta = order[a.type] - order[b.type];
545
- if (delta !== 0) return delta;
546
- if (a.id === "__main__") return -1;
547
- if (b.id === "__main__") return 1;
548
- return a.id.localeCompare(b.id);
549
- });
550
- return reports;
706
+ function isRecord(value) {
707
+ return typeof value === "object" && value !== null && !Array.isArray(value);
551
708
  }
552
- function summarizeModules(modules) {
553
- const usage = toArray(modules.values()).map((module) => {
554
- const packages = toArray(module.packages.entries()).map(([packageId, files]) => {
555
- return {
556
- packageId,
557
- files: toArray(files).sort((a, b) => a.localeCompare(b))
558
- };
559
- }).sort((a, b) => {
560
- if (a.packageId === b.packageId) return 0;
561
- if (a.packageId === "__main__") return -1;
562
- if (b.packageId === "__main__") return 1;
563
- return a.packageId.localeCompare(b.packageId);
564
- });
565
- return {
566
- id: module.id,
567
- source: module.source,
568
- sourceType: module.sourceType,
569
- packages
570
- };
571
- });
572
- usage.sort((a, b) => a.source.localeCompare(b.source));
573
- return usage;
709
+ function toStringArray(value) {
710
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string" && item.trim() !== "") : [];
574
711
  }
575
- function expandVirtualModulePlacements(modules, packages, context) {
576
- for (const moduleEntry of modules.values()) {
577
- const virtualEntries = Array.from(moduleEntry.packages.entries()).filter(([packageId]) => packageId.startsWith("virtual:"));
578
- if (!virtualEntries.length) continue;
579
- const virtualFileBases = /* @__PURE__ */ new Map();
580
- for (const [virtualPackageId, files] of virtualEntries) {
581
- const combination = virtualPackageId.slice(8);
582
- if (!combination) continue;
583
- const segments = combination.split(/[_+]/).map((segment) => segment.trim()).filter(Boolean);
584
- if (!segments.length) continue;
585
- let matchingBases = virtualFileBases.get(virtualPackageId);
586
- if (!matchingBases) {
587
- matchingBases = Array.from(files).map((file) => posix.basename(file));
588
- virtualFileBases.set(virtualPackageId, matchingBases);
589
- }
590
- for (const root of segments) {
591
- if (!context.subPackageRoots.has(root)) continue;
592
- const targetPackage = packages.get(root);
593
- if (!targetPackage) continue;
594
- const moduleFiles = moduleEntry.packages.get(root) ?? /* @__PURE__ */ new Set();
595
- const targetFiles = Array.from(targetPackage.files.values()).filter((fileEntry) => {
596
- if (!matchingBases?.length) return true;
597
- const base = posix.basename(fileEntry.file);
598
- return matchingBases.includes(base);
599
- }).map((fileEntry) => fileEntry.file);
600
- if (targetFiles.length === 0) {
601
- const fallback = targetPackage.files.values().next().value;
602
- if (fallback) moduleFiles.add(fallback.file);
603
- } else for (const fileName of targetFiles) moduleFiles.add(fileName);
604
- if (moduleFiles.size > 0) moduleEntry.packages.set(root, moduleFiles);
605
- }
606
- }
607
- }
712
+ function readUsingComponents(config) {
713
+ if (!isRecord(config) || !isRecord(config.usingComponents)) return [];
714
+ return Object.entries(config.usingComponents).filter((entry) => typeof entry[1] === "string" && entry[1].trim() !== "");
608
715
  }
609
- function summarizeSubPackages(metas) {
610
- const descriptors = metas.map((meta) => {
611
- return {
612
- root: meta.subPackage.root ?? "",
613
- independent: Boolean(meta.subPackage.independent),
614
- name: meta.subPackage.name
615
- };
616
- }).filter((descriptor) => descriptor.root);
617
- descriptors.sort((a, b) => a.root.localeCompare(b.root));
618
- return descriptors;
716
+ function readComponentPlaceholder(config) {
717
+ if (!isRecord(config) || !isRecord(config.componentPlaceholder)) return /* @__PURE__ */ new Set();
718
+ return new Set(Object.keys(config.componentPlaceholder));
619
719
  }
620
- //#endregion
621
- //#region src/analyze/subpackages/index.ts
622
- async function analyzeSubpackages(ctx) {
623
- const { configService, scanService, buildService } = ctx;
624
- if (!configService || !scanService || !buildService) throw new Error("analyzeSubpackages 需要先初始化 configService、scanService 和 buildService。");
625
- await scanService.loadAppEntry();
626
- const subPackageMetas = scanService.loadSubPackages();
627
- const subPackageRoots = /* @__PURE__ */ new Set();
628
- const independentRoots = /* @__PURE__ */ new Set();
629
- for (const meta of subPackageMetas) {
630
- const root = meta.subPackage.root;
631
- if (root) {
632
- subPackageRoots.add(root);
633
- if (meta.subPackage.independent) independentRoots.add(root);
634
- }
635
- }
636
- const classifierContext = {
637
- subPackageRoots,
638
- independentRoots
639
- };
640
- const mainResult = await build(configService.merge(void 0, createSharedBuildConfig(configService, scanService), { build: {
641
- write: false,
642
- watch: null
643
- } }));
644
- const mainOutputs = Array.isArray(mainResult) ? mainResult : [mainResult];
645
- const packages = /* @__PURE__ */ new Map();
646
- const modules = /* @__PURE__ */ new Map();
647
- const componentJsonConfigs = [];
648
- for (const output of mainOutputs) {
649
- processOutput(output, "main", ctx, classifierContext, packages, modules);
650
- componentJsonConfigs.push(...collectAnalyzeComponentJsonConfigs(output));
651
- }
652
- for (const root of independentRoots) {
653
- const output = buildService.getIndependentOutput(root);
654
- processOutput(output, "independent", ctx, classifierContext, packages, modules);
655
- componentJsonConfigs.push(...collectAnalyzeComponentJsonConfigs(output));
656
- }
657
- expandVirtualModulePlacements(modules, packages, classifierContext);
658
- const subPackages = summarizeSubPackages(subPackageMetas);
659
- return {
660
- metadata: createAnalyzeMetadata(ctx.configService),
661
- packages: summarizePackages(packages),
662
- modules: summarizeModules(modules),
663
- subPackages,
664
- components: analyzeComponentUsage({
665
- jsonConfigs: componentJsonConfigs,
666
- subPackages
667
- })
668
- };
720
+ function resolveComponentRoute(owner, request) {
721
+ const normalizedRequest = request.replace(/\\/g, "/").trim();
722
+ if (!normalizedRequest || normalizedRequest.startsWith("plugin://")) return;
723
+ if (normalizedRequest.startsWith(".")) return normalizeRoute(posix.join(posix.dirname(owner), normalizedRequest));
724
+ if (normalizedRequest.startsWith("/")) return normalizeRoute(normalizedRequest);
725
+ return normalizeRoute(normalizedRequest);
669
726
  }
670
- //#endregion
671
- //#region src/analyze/subpackages/history.ts
672
- const jsonExtension = ".json";
673
- function createSnapshotFileName(date = /* @__PURE__ */ new Date()) {
674
- return `${date.toISOString().replace(/[:.]/g, "-")}${jsonExtension}`;
727
+ function resolvePackageId(route, subPackages) {
728
+ return subPackages.map((item) => item.root).filter(Boolean).sort((left, right) => right.length - left.length).find((root) => route === root || route.startsWith(`${root}/`)) ?? "__main__";
675
729
  }
676
- function isAnalyzeResult(value) {
677
- return Boolean(value && typeof value === "object" && Array.isArray(value.packages) && Array.isArray(value.modules) && Array.isArray(value.subPackages));
730
+ function collectAppPages(configs) {
731
+ const appJson = configs.get("app");
732
+ if (!isRecord(appJson)) return /* @__PURE__ */ new Set();
733
+ const pages = /* @__PURE__ */ new Set();
734
+ for (const page of toStringArray(appJson.pages)) pages.add(normalizeRoute(page));
735
+ const subPackages = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
736
+ for (const item of subPackages) {
737
+ if (!isRecord(item) || typeof item.root !== "string") continue;
738
+ for (const page of toStringArray(item.pages)) pages.add(normalizeRoute(posix.join(item.root, page)));
739
+ }
740
+ return pages;
678
741
  }
679
- async function listSnapshotFiles(dir) {
680
- try {
681
- return (await fs$2.readdir(dir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(jsonExtension)).map((entry) => path.join(dir, entry.name)).sort((a, b) => b.localeCompare(a));
682
- } catch {
683
- return [];
742
+ function registerUsage(usageMap, edge, page, pagePackage, componentPackage) {
743
+ const usage = usageMap.get(edge.component) ?? {
744
+ component: edge.component,
745
+ componentPackage,
746
+ totalUsageCount: 0,
747
+ pages: /* @__PURE__ */ new Map(),
748
+ crossPackageUsageCount: 0,
749
+ placeholderCoveredCrossPackageUsageCount: 0
750
+ };
751
+ usage.totalUsageCount += 1;
752
+ const pageUsage = usage.pages.get(page) ?? {
753
+ page,
754
+ packageId: pagePackage,
755
+ usageCount: 0
756
+ };
757
+ pageUsage.usageCount += 1;
758
+ usage.pages.set(page, pageUsage);
759
+ if (pagePackage !== componentPackage) {
760
+ usage.crossPackageUsageCount += 1;
761
+ if (edge.placeholderCovered) usage.placeholderCoveredCrossPackageUsageCount += 1;
684
762
  }
763
+ usageMap.set(edge.component, usage);
685
764
  }
686
- async function trimSnapshotFiles(dir, limit) {
687
- const staleFiles = (await listSnapshotFiles(dir)).slice(limit);
688
- await Promise.all(staleFiles.map(async (file) => {
765
+ function collectAnalyzeComponentJsonConfigs(output) {
766
+ if (!output) return [];
767
+ const configs = [];
768
+ for (const item of output.output ?? []) {
769
+ if (item.type !== "asset" || !item.fileName.endsWith(".json")) continue;
770
+ const asset = item;
771
+ if (typeof asset.source !== "string") continue;
689
772
  try {
690
- await fs$2.unlink(file);
773
+ configs.push({
774
+ file: normalizeRoute(asset.fileName),
775
+ config: JSON.parse(asset.source)
776
+ });
691
777
  } catch {}
692
- }));
693
- }
694
- async function readLatestAnalyzeHistorySnapshot(configService) {
695
- const history = resolveAnalyzeHistoryMetadata(configService);
696
- if (!history.enabled) return null;
697
- const files = await listSnapshotFiles(history.dir);
698
- for (const file of files) try {
699
- const parsed = JSON.parse(await fs$2.readFile(file, "utf8"));
700
- if (isAnalyzeResult(parsed)) return parsed;
701
- } catch {}
702
- return null;
778
+ }
779
+ return configs;
703
780
  }
704
- async function writeAnalyzeHistorySnapshot(result, configService, now = /* @__PURE__ */ new Date()) {
705
- const history = resolveAnalyzeHistoryMetadata(configService);
706
- if (!history.enabled) return;
707
- await fs$2.mkdir(history.dir, { recursive: true });
708
- const snapshotPath = path.join(history.dir, createSnapshotFileName(now));
709
- if (result.metadata) result.metadata = {
710
- ...result.metadata,
711
- history: {
712
- ...history,
713
- dir: configService.relativeCwd(history.dir),
714
- latestSnapshot: configService.relativeCwd(snapshotPath)
781
+ function analyzeComponentUsage(options) {
782
+ const configs = /* @__PURE__ */ new Map();
783
+ for (const item of options.jsonConfigs) configs.set(normalizeRoute(item.file), item.config);
784
+ const pages = collectAppPages(configs);
785
+ const graph = /* @__PURE__ */ new Map();
786
+ const packageMap = /* @__PURE__ */ new Map();
787
+ for (const route of configs.keys()) packageMap.set(route, resolvePackageId(route, options.subPackages));
788
+ for (const [owner, config] of configs) {
789
+ const placeholders = readComponentPlaceholder(config);
790
+ const edges = readUsingComponents(config).map(([name, request]) => {
791
+ const component = resolveComponentRoute(owner, request);
792
+ return component && configs.has(component) ? {
793
+ owner,
794
+ component,
795
+ placeholderCovered: placeholders.has(name)
796
+ } : void 0;
797
+ }).filter((edge) => Boolean(edge));
798
+ if (edges.length > 0) graph.set(owner, edges);
799
+ }
800
+ const usageMap = /* @__PURE__ */ new Map();
801
+ const visit = (owner, page, stack) => {
802
+ for (const edge of graph.get(owner) ?? []) {
803
+ const componentPackage = packageMap.get(edge.component) ?? "__main__";
804
+ registerUsage(usageMap, edge, page, packageMap.get(page) ?? "__main__", componentPackage);
805
+ if (stack.has(edge.component)) continue;
806
+ const nextStack = new Set(stack);
807
+ nextStack.add(edge.component);
808
+ visit(edge.component, page, nextStack);
715
809
  }
716
810
  };
717
- await fs$2.writeFile(snapshotPath, `${JSON.stringify(result, null, 2)}\n`, "utf8");
718
- await trimSnapshotFiles(history.dir, history.limit);
719
- return snapshotPath;
720
- }
721
- //#endregion
722
- //#region src/analyze/subpackages/report.ts
723
- function formatAnalyzeBytes(bytes) {
724
- if (!bytes || Number.isNaN(bytes)) return "0 B";
725
- const units = [
726
- "B",
727
- "KB",
728
- "MB",
729
- "GB"
730
- ];
731
- let value = bytes;
732
- let unitIndex = 0;
733
- while (value >= 1024 && unitIndex < units.length - 1) {
734
- value /= 1024;
735
- unitIndex++;
736
- }
737
- return `${value.toFixed(value >= 100 || unitIndex === 0 ? 0 : 2)} ${units[unitIndex]}`;
811
+ for (const page of pages) visit(page, page, new Set([page]));
812
+ return Array.from(usageMap.values()).map((usage) => {
813
+ const pages = Array.from(usage.pages.values()).sort((left, right) => left.page.localeCompare(right.page));
814
+ const suggestions = [createComponentSuggestion(usage)].filter((item) => Boolean(item));
815
+ return {
816
+ component: usage.component,
817
+ componentPackage: usage.componentPackage,
818
+ totalUsageCount: usage.totalUsageCount,
819
+ pageUsageCount: pages.length,
820
+ pages,
821
+ suggestions
822
+ };
823
+ }).sort((left, right) => {
824
+ const usageDelta = right.totalUsageCount - left.totalUsageCount;
825
+ return usageDelta !== 0 ? usageDelta : left.component.localeCompare(right.component);
826
+ });
738
827
  }
739
- function formatDelta(bytes) {
740
- if (typeof bytes !== "number" || Number.isNaN(bytes) || bytes === 0) return "无变化";
741
- return `${bytes > 0 ? "+" : "-"}${formatAnalyzeBytes(Math.abs(bytes))}`;
828
+ //#endregion
829
+ //#region src/analyze/subpackages/metadata.ts
830
+ const defaultTotalBudgetBytes = 20 * 1024 * 1024;
831
+ const defaultPackageBudgetBytes = 2 * 1024 * 1024;
832
+ const defaultWarningRatio = .85;
833
+ const defaultHistoryDir = ".weapp-vite/analyze-history";
834
+ const defaultHistoryLimit = 20;
835
+ function resolveBudgetValue(value, fallback) {
836
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
742
837
  }
743
- function getFileSize(file) {
744
- return file.size ?? 0;
838
+ function resolveHistoryLimit(value) {
839
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : defaultHistoryLimit;
745
840
  }
746
- function getCompressedSize(file) {
747
- return file.brotliSize ?? file.gzipSize ?? 0;
841
+ function resolveAnalyzeBudgets(configService) {
842
+ const budgets = configService.weappViteConfig.analyze?.budgets;
843
+ const legacyPackageBudget = configService.weappViteConfig.packageSizeWarningBytes;
844
+ const packageFallback = resolveBudgetValue(legacyPackageBudget, defaultPackageBudgetBytes);
845
+ return {
846
+ totalBytes: resolveBudgetValue(budgets?.totalBytes, defaultTotalBudgetBytes),
847
+ mainBytes: resolveBudgetValue(budgets?.mainBytes, packageFallback),
848
+ subPackageBytes: resolveBudgetValue(budgets?.subPackageBytes, packageFallback),
849
+ independentBytes: resolveBudgetValue(budgets?.independentBytes, packageFallback),
850
+ warningRatio: resolveBudgetValue(budgets?.warningRatio, defaultWarningRatio),
851
+ source: budgets ? "config" : "default"
852
+ };
748
853
  }
749
- function getBudgetLimit(type, budgets) {
750
- if (!budgets) return;
751
- if (type === "main") return budgets.mainBytes;
752
- if (type === "subPackage") return budgets.subPackageBytes;
753
- if (type === "independent") return budgets.independentBytes;
854
+ function resolveAnalyzeHistoryMetadata(configService) {
855
+ const history = configService.weappViteConfig.analyze?.history;
856
+ if (history === false) return {
857
+ enabled: false,
858
+ dir: path.resolve(configService.cwd, defaultHistoryDir),
859
+ limit: defaultHistoryLimit
860
+ };
861
+ const historyConfig = typeof history === "object" && history ? history : {};
862
+ const rawDir = typeof historyConfig.dir === "string" && historyConfig.dir.trim() ? historyConfig.dir.trim() : defaultHistoryDir;
863
+ return {
864
+ enabled: historyConfig.enabled !== false,
865
+ dir: path.isAbsolute(rawDir) ? rawDir : path.resolve(configService.cwd, rawDir),
866
+ limit: resolveHistoryLimit(historyConfig.limit)
867
+ };
754
868
  }
755
- function createPackageSizeMap(result) {
756
- return new Map((result?.packages ?? []).map((pkg) => {
757
- const totalBytes = pkg.files.reduce((sum, file) => sum + getFileSize(file), 0);
758
- return [pkg.id, totalBytes];
759
- }));
869
+ function createAnalyzeMetadata(configService, now = /* @__PURE__ */ new Date()) {
870
+ const history = resolveAnalyzeHistoryMetadata(configService);
871
+ return {
872
+ generatedAt: now.toISOString(),
873
+ budgets: resolveAnalyzeBudgets(configService),
874
+ history: {
875
+ ...history,
876
+ dir: configService.relativeCwd(history.dir)
877
+ }
878
+ };
760
879
  }
761
- function createFileKey(packageId, fileName) {
762
- return `${packageId}\u0000${fileName}`;
880
+ //#endregion
881
+ //#region src/analyze/subpackages/classifier.ts
882
+ const VIRTUAL_MODULE_INDICATOR = "\0";
883
+ const VIRTUAL_PREFIX = `${SHARED_CHUNK_VIRTUAL_PREFIX}/`;
884
+ function classifyModuleSourceKind(options) {
885
+ if (options.isNodeModule) return "node_modules";
886
+ if (options.inSrc) return "src";
887
+ if (options.inPlugin) return "plugin";
888
+ return "workspace";
763
889
  }
764
- function createFileSizeMap(result) {
765
- const map = /* @__PURE__ */ new Map();
766
- for (const pkg of result?.packages ?? []) for (const file of pkg.files) map.set(createFileKey(pkg.id, file.file), getFileSize(file));
767
- return map;
890
+ function resolvePluginAssetAbsolute(normalizedFileName, pluginRoot) {
891
+ if (!pluginRoot) return;
892
+ const pluginBase = posix.basename(pluginRoot);
893
+ if (normalizedFileName !== pluginBase && !normalizedFileName.startsWith(`${pluginBase}/`)) return;
894
+ const relative = normalizedFileName === pluginBase ? "" : normalizedFileName.slice(pluginBase.length + 1);
895
+ const absolute = posix.resolve(pluginRoot, relative);
896
+ return isPathInside(pluginRoot, absolute) ? absolute : void 0;
768
897
  }
769
- function createPackageTypeMap(result) {
770
- return new Map(result.packages.map((pkg) => [pkg.id, pkg.type]));
898
+ function resolveSubPackageRoot$1(fileName, context) {
899
+ const normalized = posix.normalize(fileName);
900
+ return Array.from(context.subPackageRoots).filter(Boolean).sort((left, right) => right.length - left.length).find((root) => normalized === root || normalized.startsWith(`${root}/`));
771
901
  }
772
- function createModuleByteMap(result) {
773
- const map = /* @__PURE__ */ new Map();
774
- for (const pkg of result.packages) for (const file of pkg.files) for (const mod of file.modules ?? []) {
775
- const bytes = mod.bytes ?? mod.originalBytes ?? 0;
776
- map.set(mod.id, Math.max(map.get(mod.id) ?? 0, bytes));
902
+ function classifyPackage(fileName, origin, context) {
903
+ if (fileName.startsWith(VIRTUAL_PREFIX)) {
904
+ const combination = fileName.slice(VIRTUAL_PREFIX.length).split("/")[0] || "shared";
905
+ return {
906
+ id: `virtual:${combination}`,
907
+ label: `共享虚拟包 ${combination}`,
908
+ type: "virtual"
909
+ };
777
910
  }
778
- return map;
911
+ const rootCandidate = resolveSubPackageRoot$1(fileName, context);
912
+ if (rootCandidate) {
913
+ const isIndependent = context.independentRoots.has(rootCandidate);
914
+ return {
915
+ id: rootCandidate,
916
+ label: `${isIndependent ? "独立分包" : "分包"} ${rootCandidate}`,
917
+ type: isIndependent || origin === "independent" ? "independent" : "subPackage"
918
+ };
919
+ }
920
+ return {
921
+ id: "__main__",
922
+ label: "主包",
923
+ type: "main"
924
+ };
779
925
  }
780
- function classifyIncrementCategory(source, sourceType) {
781
- if (source.includes("wevu") || source.includes("@weapp-vite/dashboard")) return "WeVu / runtime";
782
- if (sourceType === "node_modules" || source.includes("node_modules")) return "第三方依赖";
783
- if (sourceType === "workspace") return "工作区包";
784
- if (sourceType === "plugin") return "插件生成";
785
- if (source.endsWith(".wxss") || source.endsWith(".css") || source.endsWith(".scss")) return "样式资源";
786
- if (source.endsWith(".wxml") || source.endsWith(".json")) return "页面结构";
787
- return "业务源码";
926
+ function normalizeModuleId(id) {
927
+ if (!id || id.includes(VIRTUAL_MODULE_INDICATOR)) return;
928
+ if (!posix.isAbsolute(id)) return;
929
+ return posix.normalize(id);
788
930
  }
789
- function createIncrementAdvice(item) {
790
- if (item.category === "第三方依赖") return "检查依赖是否只在必要分包引用,必要时收敛到公共入口或替换轻量实现。";
791
- if (item.category === "WeVu / runtime") return "确认运行时能力是否被新页面引入,优先排查组件和 API 引用边界。";
792
- if (item.category === "样式资源") return "检查样式重复、原子类生成范围和组件样式裁剪。";
793
- if (item.type === "new-file" || item.type === "new-module") return "确认是否为本次需求必要新增,评估分包归属和懒加载边界。";
794
- return "对比本次变更,优先查看新增引用、共享模块和大对象常量。";
931
+ function resolveModuleSourceType(absoluteId, ctx) {
932
+ const { configService } = ctx;
933
+ const isNodeModule = absoluteId.includes("/node_modules/") || absoluteId.includes("\\node_modules\\");
934
+ const pluginRoot = configService.absolutePluginRoot;
935
+ const srcRoot = configService.absoluteSrcRoot;
936
+ const sourceType = classifyModuleSourceKind({
937
+ isNodeModule,
938
+ inSrc: isPathInside(srcRoot, absoluteId),
939
+ inPlugin: pluginRoot ? isPathInside(pluginRoot, absoluteId) : false
940
+ });
941
+ return {
942
+ source: configService.relativeAbsoluteSrcRoot(absoluteId),
943
+ sourceType
944
+ };
795
945
  }
796
- function createModuleSizeMap(result) {
797
- const map = /* @__PURE__ */ new Map();
798
- for (const pkg of result?.packages ?? []) for (const file of pkg.files) for (const module of file.modules ?? []) {
799
- const bytes = module.bytes ?? module.originalBytes ?? 0;
800
- const existing = map.get(module.id);
801
- if (existing && existing.bytes >= bytes) continue;
802
- map.set(module.id, {
803
- source: module.source,
804
- sourceType: module.sourceType,
805
- bytes,
806
- packageLabel: pkg.label,
807
- file: file.file
808
- });
809
- }
810
- return map;
946
+ function resolveAssetSource(fileName, ctx) {
947
+ const { configService } = ctx;
948
+ const normalized = posix.normalize(fileName);
949
+ const srcCandidate = posix.resolve(configService.absoluteSrcRoot, normalized);
950
+ if (isPathInside(configService.absoluteSrcRoot, srcCandidate)) return {
951
+ absolute: srcCandidate,
952
+ source: configService.relativeAbsoluteSrcRoot(srcCandidate),
953
+ sourceType: "src"
954
+ };
955
+ const pluginAbsolute = resolvePluginAssetAbsolute(normalized, configService.absolutePluginRoot);
956
+ if (pluginAbsolute) return {
957
+ absolute: pluginAbsolute,
958
+ source: configService.relativeAbsoluteSrcRoot(pluginAbsolute),
959
+ sourceType: "plugin"
960
+ };
811
961
  }
812
- function createDuplicateAdvice(sourceType, packageIds, packageTypeMap, estimatedSavingBytes) {
813
- if (packageIds.some((packageId) => packageTypeMap.get(packageId) === "independent")) return estimatedSavingBytes > 0 ? "含独立分包,先确认隔离要求,再评估是否抽公共入口。" : "含独立分包,重复可能来自隔离边界。";
814
- if (sourceType === "node_modules") return "依赖被多个包带入,检查引用边界或考虑主包公共入口。";
815
- if (sourceType === "src" || sourceType === "workspace") return "共享源码跨包重复,优先抽公共模块或调整分包归属。";
816
- if (sourceType === "plugin") return "插件生成内容跨包重复,检查插件产物输出策略。";
817
- return "检查该模块是否需要在多个包内重复存在。";
962
+ //#endregion
963
+ //#region src/analyze/subpackages/registry.ts
964
+ function ensurePackage(packages, classification) {
965
+ const existing = packages.get(classification.id);
966
+ if (existing) return existing;
967
+ const created = {
968
+ ...classification,
969
+ files: /* @__PURE__ */ new Map()
970
+ };
971
+ packages.set(classification.id, created);
972
+ return created;
818
973
  }
819
- function formatBudgetStatus(item) {
820
- if (item.status === "ok") return "正常";
821
- return `${item.status === "exceeded" ? "超预算" : "接近预算"} ${(item.ratio * 100).toFixed(1)}%`;
974
+ function ensureModule(modules, id, source, sourceType) {
975
+ const existing = modules.get(id);
976
+ if (existing) return existing;
977
+ const created = {
978
+ id,
979
+ source,
980
+ sourceType,
981
+ packages: /* @__PURE__ */ new Map()
982
+ };
983
+ modules.set(id, created);
984
+ return created;
822
985
  }
823
- function createActionItems(options) {
824
- const actions = [];
825
- const exceededItems = options.budgetItems.filter((item) => item.status === "exceeded");
826
- const warningItems = options.budgetItems.filter((item) => item.status === "warning");
827
- const topDuplicate = options.duplicateInsights.find((item) => item.estimatedSavingBytes > 0);
828
- if (exceededItems.length > 0) actions.push(`处理 ${exceededItems[0].label} 预算超限:当前 ${formatAnalyzeBytes(exceededItems[0].currentBytes)},限制 ${formatAnalyzeBytes(exceededItems[0].limitBytes)}。`);
829
- else if (warningItems.length > 0) actions.push(`关注 ${warningItems[0].label} 预算接近阈值:当前 ${(warningItems[0].ratio * 100).toFixed(1)}%。`);
830
- if (topDuplicate) actions.push(`优先处理重复模块 ${topDuplicate.source},估算可节省 ${formatAnalyzeBytes(topDuplicate.estimatedSavingBytes)}。`);
831
- if (actions.length === 0) actions.push("当前没有预算超限或高收益重复模块,保持观察即可。");
832
- return actions;
986
+ function registerModuleInPackage(modules, moduleId, source, sourceType, packageId, fileName) {
987
+ const moduleEntry = ensureModule(modules, moduleId, source, sourceType);
988
+ const files = moduleEntry.packages.get(packageId) ?? /* @__PURE__ */ new Set();
989
+ files.add(fileName);
990
+ moduleEntry.packages.set(packageId, files);
833
991
  }
834
- function createAnalyzeBudgetCheck(result) {
835
- const budgets = result.metadata?.budgets;
836
- if (!budgets) return [];
837
- const items = [];
838
- const totalBytes = result.packages.flatMap((pkg) => pkg.files).reduce((sum, file) => sum + getFileSize(file), 0);
839
- const warningRatio = budgets.warningRatio;
840
- const createItem = (options) => {
841
- const ratio = options.limitBytes > 0 ? options.currentBytes / options.limitBytes : 0;
842
- const status = ratio >= 1 ? "exceeded" : ratio >= warningRatio ? "warning" : "ok";
843
- return {
844
- ...options,
845
- ratio,
846
- status
992
+ //#endregion
993
+ //#region src/analyze/subpackages/output.ts
994
+ function getAssetBuffer(asset) {
995
+ if (typeof asset.source === "string") return Buffer.from(asset.source, "utf8");
996
+ if (asset.source instanceof Uint8Array) return Buffer.from(asset.source);
997
+ }
998
+ function getCompressedSizes$1(content) {
999
+ if (content === void 0) return {};
1000
+ const buffer = typeof content === "string" ? Buffer.from(content, "utf8") : Buffer.from(content);
1001
+ return {
1002
+ gzipSize: gzipSync(buffer).byteLength,
1003
+ brotliSize: brotliCompressSync(buffer).byteLength
1004
+ };
1005
+ }
1006
+ function processChunk(chunk, origin, ctx, classifierContext, packages, modules) {
1007
+ const classification = classifyPackage(chunk.fileName, origin, classifierContext);
1008
+ const packageEntry = ensurePackage(packages, classification);
1009
+ const chunkEntry = {
1010
+ file: chunk.fileName,
1011
+ type: "chunk",
1012
+ from: origin,
1013
+ size: typeof chunk.code === "string" ? Buffer.byteLength(chunk.code, "utf8") : void 0,
1014
+ ...getCompressedSizes$1(chunk.code),
1015
+ isEntry: chunk.isEntry,
1016
+ modules: []
1017
+ };
1018
+ const moduleEntries = Object.entries(chunk.modules ?? {});
1019
+ for (const [rawModuleId, info] of moduleEntries) {
1020
+ const absoluteId = normalizeModuleId(rawModuleId);
1021
+ if (!absoluteId) continue;
1022
+ const { source, sourceType } = resolveModuleSourceType(absoluteId, ctx);
1023
+ const moduleEntry = {
1024
+ id: absoluteId,
1025
+ source,
1026
+ sourceType,
1027
+ bytes: info?.renderedLength
847
1028
  };
1029
+ if (typeof info?.code === "string") moduleEntry.originalBytes = Buffer.byteLength(info.code, "utf8");
1030
+ chunkEntry.modules.push(moduleEntry);
1031
+ registerModuleInPackage(modules, absoluteId, source, sourceType, classification.id, chunk.fileName);
1032
+ }
1033
+ if (chunkEntry.modules) chunkEntry.modules.sort((a, b) => a.source.localeCompare(b.source));
1034
+ packageEntry.files.set(chunk.fileName, chunkEntry);
1035
+ }
1036
+ function processAsset(asset, origin, ctx, classifierContext, packages, modules) {
1037
+ const classification = classifyPackage(asset.fileName, origin, classifierContext);
1038
+ const packageEntry = ensurePackage(packages, classification);
1039
+ const assetBuffer = getAssetBuffer(asset);
1040
+ const entry = {
1041
+ file: asset.fileName,
1042
+ type: "asset",
1043
+ from: origin,
1044
+ size: assetBuffer?.byteLength,
1045
+ ...getCompressedSizes$1(assetBuffer)
848
1046
  };
849
- items.push(createItem({
850
- id: "__total__",
851
- label: "总包",
852
- scope: "total",
853
- currentBytes: totalBytes,
854
- limitBytes: budgets.totalBytes
855
- }));
856
- for (const pkg of result.packages) {
857
- const limitBytes = getBudgetLimit(pkg.type, budgets);
858
- if (!limitBytes) continue;
859
- items.push(createItem({
1047
+ const assetSource = resolveAssetSource(asset.fileName, ctx);
1048
+ if (assetSource) {
1049
+ entry.source = assetSource.source;
1050
+ registerModuleInPackage(modules, assetSource.absolute, assetSource.source, assetSource.sourceType, classification.id, asset.fileName);
1051
+ }
1052
+ packageEntry.files.set(asset.fileName, entry);
1053
+ }
1054
+ function processOutput(output, origin, ctx, classifierContext, packages, modules) {
1055
+ if (!output) return;
1056
+ for (const item of output.output ?? []) if (item.type === "chunk") processChunk(item, origin, ctx, classifierContext, packages, modules);
1057
+ else if (item.type === "asset") processAsset(item, origin, ctx, classifierContext, packages, modules);
1058
+ }
1059
+ //#endregion
1060
+ //#region src/analyze/subpackages/summary.ts
1061
+ function toArray(value) {
1062
+ return Array.from(value);
1063
+ }
1064
+ function summarizePackages(packages) {
1065
+ const order = {
1066
+ main: 0,
1067
+ subPackage: 1,
1068
+ independent: 2,
1069
+ virtual: 3
1070
+ };
1071
+ const reports = toArray(packages.values()).map((pkg) => {
1072
+ const files = toArray(pkg.files.values());
1073
+ files.sort((a, b) => a.file.localeCompare(b.file));
1074
+ return {
860
1075
  id: pkg.id,
861
1076
  label: pkg.label,
862
- scope: pkg.type,
863
- currentBytes: pkg.files.reduce((sum, file) => sum + getFileSize(file), 0),
864
- limitBytes
865
- }));
866
- }
867
- return items.sort((a, b) => b.ratio - a.ratio || a.label.localeCompare(b.label));
1077
+ type: pkg.type,
1078
+ files
1079
+ };
1080
+ });
1081
+ reports.sort((a, b) => {
1082
+ const delta = order[a.type] - order[b.type];
1083
+ if (delta !== 0) return delta;
1084
+ if (a.id === "__main__") return -1;
1085
+ if (b.id === "__main__") return 1;
1086
+ return a.id.localeCompare(b.id);
1087
+ });
1088
+ return reports;
868
1089
  }
869
- function createDuplicateModuleInsights(result) {
870
- const moduleByteMap = createModuleByteMap(result);
871
- const packageTypeMap = createPackageTypeMap(result);
872
- return result.modules.filter((module) => module.packages.length > 1).map((module) => {
873
- const bytes = moduleByteMap.get(module.id) ?? 0;
874
- const packageIds = module.packages.map((pkg) => pkg.packageId);
875
- const estimatedSavingBytes = bytes * Math.max(module.packages.length - 1, 0);
1090
+ function summarizeModules(modules) {
1091
+ const usage = toArray(modules.values()).map((module) => {
1092
+ const packages = toArray(module.packages.entries()).map(([packageId, files]) => {
1093
+ return {
1094
+ packageId,
1095
+ files: toArray(files).sort((a, b) => a.localeCompare(b))
1096
+ };
1097
+ }).sort((a, b) => {
1098
+ if (a.packageId === b.packageId) return 0;
1099
+ if (a.packageId === "__main__") return -1;
1100
+ if (b.packageId === "__main__") return 1;
1101
+ return a.packageId.localeCompare(b.packageId);
1102
+ });
876
1103
  return {
877
1104
  id: module.id,
878
1105
  source: module.source,
879
1106
  sourceType: module.sourceType,
880
- packageCount: module.packages.length,
881
- bytes,
882
- estimatedSavingBytes,
883
- packages: packageIds,
884
- advice: createDuplicateAdvice(module.sourceType, packageIds, packageTypeMap, estimatedSavingBytes)
1107
+ packages
885
1108
  };
886
- }).sort((a, b) => b.estimatedSavingBytes - a.estimatedSavingBytes || b.packageCount - a.packageCount || a.source.localeCompare(b.source));
1109
+ });
1110
+ usage.sort((a, b) => a.source.localeCompare(b.source));
1111
+ return usage;
887
1112
  }
888
- function createAnalyzeIncrementAttribution(result, previousResult) {
889
- if (!previousResult) return [];
890
- const previousFiles = createFileSizeMap(previousResult);
891
- const previousModules = createModuleSizeMap(previousResult);
892
- const currentModules = createModuleSizeMap(result);
893
- const items = [];
894
- for (const pkg of result.packages) for (const file of pkg.files) {
895
- const currentBytes = getFileSize(file);
896
- const previousBytes = previousFiles.get(createFileKey(pkg.id, file.file)) ?? 0;
897
- const deltaBytes = currentBytes - previousBytes;
898
- if (deltaBytes <= 0) continue;
899
- const type = previousBytes > 0 ? "increased-file" : "new-file";
900
- const item = {
901
- key: `file:${pkg.id}:${file.file}`,
902
- type,
903
- label: file.file,
904
- category: classifyIncrementCategory(file.source ?? file.file),
905
- packageLabel: pkg.label,
906
- file: file.file,
907
- currentBytes,
908
- previousBytes,
909
- deltaBytes,
910
- advice: ""
911
- };
912
- items.push({
913
- ...item,
914
- advice: createIncrementAdvice(item)
915
- });
916
- }
917
- for (const [id, module] of currentModules) {
918
- const previousBytes = previousModules.get(id)?.bytes ?? 0;
919
- const deltaBytes = module.bytes - previousBytes;
920
- if (deltaBytes <= 0) continue;
921
- const type = previousBytes > 0 ? "increased-module" : "new-module";
922
- const item = {
923
- key: `module:${id}`,
924
- type,
925
- label: module.source,
926
- category: classifyIncrementCategory(module.source, module.sourceType),
927
- packageLabel: module.packageLabel,
928
- file: module.file,
929
- currentBytes: module.bytes,
930
- previousBytes,
931
- deltaBytes,
932
- advice: ""
933
- };
934
- items.push({
935
- ...item,
936
- advice: createIncrementAdvice(item)
937
- });
1113
+ function expandVirtualModulePlacements(modules, packages, context) {
1114
+ for (const moduleEntry of modules.values()) {
1115
+ const virtualEntries = Array.from(moduleEntry.packages.entries()).filter(([packageId]) => packageId.startsWith("virtual:"));
1116
+ if (!virtualEntries.length) continue;
1117
+ const virtualFileBases = /* @__PURE__ */ new Map();
1118
+ for (const [virtualPackageId, files] of virtualEntries) {
1119
+ const combination = virtualPackageId.slice(8);
1120
+ if (!combination) continue;
1121
+ const segments = combination.split(/[_+]/).map((segment) => segment.trim()).filter(Boolean);
1122
+ if (!segments.length) continue;
1123
+ let matchingBases = virtualFileBases.get(virtualPackageId);
1124
+ if (!matchingBases) {
1125
+ matchingBases = Array.from(files).map((file) => posix.basename(file));
1126
+ virtualFileBases.set(virtualPackageId, matchingBases);
1127
+ }
1128
+ for (const root of segments) {
1129
+ if (!context.subPackageRoots.has(root)) continue;
1130
+ const targetPackage = packages.get(root);
1131
+ if (!targetPackage) continue;
1132
+ const moduleFiles = moduleEntry.packages.get(root) ?? /* @__PURE__ */ new Set();
1133
+ const targetFiles = Array.from(targetPackage.files.values()).filter((fileEntry) => {
1134
+ if (!matchingBases?.length) return true;
1135
+ const base = posix.basename(fileEntry.file);
1136
+ return matchingBases.includes(base);
1137
+ }).map((fileEntry) => fileEntry.file);
1138
+ if (targetFiles.length === 0) {
1139
+ const fallback = targetPackage.files.values().next().value;
1140
+ if (fallback) moduleFiles.add(fallback.file);
1141
+ } else for (const fileName of targetFiles) moduleFiles.add(fileName);
1142
+ if (moduleFiles.size > 0) moduleEntry.packages.set(root, moduleFiles);
1143
+ }
1144
+ }
938
1145
  }
939
- return items.sort((a, b) => b.deltaBytes - a.deltaBytes || a.category.localeCompare(b.category) || a.label.localeCompare(b.label));
940
1146
  }
941
- function createAnalyzeIncrementCategorySummary(items) {
942
- const map = /* @__PURE__ */ new Map();
943
- for (const item of items) {
944
- const entry = map.get(item.category) ?? {
945
- category: item.category,
946
- count: 0,
947
- deltaBytes: 0
1147
+ function summarizeSubPackages(metas) {
1148
+ const descriptors = metas.map((meta) => {
1149
+ return {
1150
+ root: meta.subPackage.root ?? "",
1151
+ independent: Boolean(meta.subPackage.independent),
1152
+ name: meta.subPackage.name
948
1153
  };
949
- entry.count += 1;
950
- entry.deltaBytes += item.deltaBytes;
951
- map.set(item.category, entry);
952
- }
953
- return [...map.values()].sort((a, b) => b.deltaBytes - a.deltaBytes || b.count - a.count || a.category.localeCompare(b.category));
954
- }
955
- function createAnalyzePrMarkdownReport(result, previousResult) {
956
- const files = result.packages.flatMap((pkg) => pkg.files.map((file) => ({
957
- pkg,
958
- file
959
- })));
960
- const totalBytes = files.reduce((sum, item) => sum + getFileSize(item.file), 0);
961
- const compressedBytes = files.reduce((sum, item) => sum + getCompressedSize(item.file), 0);
962
- const previousTotalBytes = previousResult?.packages.flatMap((pkg) => pkg.files).reduce((sum, file) => sum + getFileSize(file), 0);
963
- const incrementItems = createAnalyzeIncrementAttribution(result, previousResult);
964
- const incrementSummary = createAnalyzeIncrementCategorySummary(incrementItems);
965
- const duplicateInsights = createDuplicateModuleInsights(result);
966
- const budgetItems = createAnalyzeBudgetCheck(result);
967
- const budgetIssues = budgetItems.filter((item) => item.status !== "ok");
968
- const actionItems = createActionItems({
969
- budgetItems,
970
- duplicateInsights
971
- }).slice(0, 3);
972
- const budgetRows = budgetIssues.slice(0, 5).map((item) => `| ${item.label} | ${formatAnalyzeBytes(item.currentBytes)} | ${formatAnalyzeBytes(item.limitBytes)} | ${formatBudgetStatus(item)} |`).join("\n");
973
- const incrementRows = incrementItems.slice(0, 8).map((item) => `| ${item.label} | ${item.category} | ${item.packageLabel} | ${formatAnalyzeBytes(item.deltaBytes)} | ${item.advice} |`).join("\n");
974
- const sourceRows = incrementSummary.slice(0, 6).map((item) => `| ${item.category} | ${item.count} | ${formatAnalyzeBytes(item.deltaBytes)} |`).join("\n");
975
- const duplicateRows = duplicateInsights.slice(0, 5).map((module) => `| ${module.source} | ${module.packageCount} | ${formatAnalyzeBytes(module.estimatedSavingBytes)} | ${module.advice} |`).join("\n");
976
- return [
977
- "## weapp-vite analyze PR 摘要",
978
- "",
979
- `- 总产物体积:${formatAnalyzeBytes(totalBytes)}(较上次 ${formatDelta(typeof previousTotalBytes === "number" ? totalBytes - previousTotalBytes : void 0)})`,
980
- `- 压缩后体积:${formatAnalyzeBytes(compressedBytes)}`,
981
- `- 预算告警:${budgetIssues.length}`,
982
- `- 增量归因:${incrementItems.length > 0 ? `${incrementItems.length} 项正向增长` : "无正向增长"}`,
983
- `- 跨包复用:${duplicateInsights.length}`,
984
- "",
985
- "### 建议动作",
986
- "",
987
- ...actionItems.map((item) => `- ${item}`),
988
- "",
989
- "### 预算状态",
990
- "",
991
- "| 对象 | 当前体积 | 预算 | 状态 |",
992
- "| --- | ---: | ---: | --- |",
993
- budgetRows || "| - | 0 B | 0 B | 正常 |",
994
- "",
995
- "### 增量来源",
996
- "",
997
- "| 来源 | 项数 | 增量 |",
998
- "| --- | ---: | ---: |",
999
- sourceRows || "| - | 0 | 0 B |",
1000
- "",
1001
- "### Top 增量",
1002
- "",
1003
- "| 文件/模块 | 来源 | 包 | 增量 | 建议 |",
1004
- "| --- | --- | --- | ---: | --- |",
1005
- incrementRows || "| - | - | - | 0 B | - |",
1006
- "",
1007
- "### 重复模块",
1008
- "",
1009
- "| 模块 | 包数量 | 估算可节省 | 建议 |",
1010
- "| --- | ---: | ---: | --- |",
1011
- duplicateRows || "| - | 0 | 0 B | - |",
1012
- ""
1013
- ].join("\n");
1014
- }
1015
- function createAnalyzeMarkdownReport(result, previousResult) {
1016
- const files = result.packages.flatMap((pkg) => pkg.files.map((file) => ({
1017
- pkg,
1018
- file
1019
- })));
1020
- const totalBytes = files.reduce((sum, item) => sum + getFileSize(item.file), 0);
1021
- const compressedBytes = files.reduce((sum, item) => sum + getCompressedSize(item.file), 0);
1022
- const duplicateInsights = createDuplicateModuleInsights(result);
1023
- const incrementItems = createAnalyzeIncrementAttribution(result, previousResult);
1024
- const incrementSummary = createAnalyzeIncrementCategorySummary(incrementItems);
1025
- const budgetItems = createAnalyzeBudgetCheck(result);
1026
- const previousTotalBytes = previousResult?.packages.flatMap((pkg) => pkg.files).reduce((sum, file) => sum + getFileSize(file), 0);
1027
- const previousPackageSizes = createPackageSizeMap(previousResult);
1028
- const budgets = result.metadata?.budgets;
1029
- const budgetIssues = budgetItems.filter((item) => item.status !== "ok");
1030
- const actionItems = createActionItems({
1031
- budgetItems,
1032
- duplicateInsights
1033
- });
1034
- const packageRows = result.packages.map((pkg) => {
1035
- const size = pkg.files.reduce((sum, file) => sum + getFileSize(file), 0);
1036
- const compressed = pkg.files.reduce((sum, file) => sum + getCompressedSize(file), 0);
1037
- const previousSize = previousPackageSizes.get(pkg.id);
1038
- const budgetStatus = budgetItems.find((item) => item.id === pkg.id);
1039
- return `| ${pkg.label} | ${pkg.type} | ${formatAnalyzeBytes(size)} | ${formatAnalyzeBytes(compressed)} | ${formatDelta(typeof previousSize === "number" ? size - previousSize : void 0)} | ${budgetStatus ? formatBudgetStatus(budgetStatus) : "正常"} |`;
1040
- }).join("\n");
1041
- const topFileRows = files.sort((a, b) => getFileSize(b.file) - getFileSize(a.file) || a.file.file.localeCompare(b.file.file)).slice(0, 10).map((item) => `| ${item.file.file} | ${item.pkg.label} | ${item.file.type} | ${formatAnalyzeBytes(getFileSize(item.file))} | ${formatAnalyzeBytes(getCompressedSize(item.file))} |`).join("\n");
1042
- const duplicateRows = duplicateInsights.slice(0, 10).map((module) => `| ${module.source} | ${module.sourceType} | ${module.packageCount} | ${formatAnalyzeBytes(module.estimatedSavingBytes)} | ${module.advice} |`).join("\n");
1043
- const budgetRows = budgetIssues.map((item) => `| ${item.label} | ${item.scope} | ${formatAnalyzeBytes(item.currentBytes)} | ${formatAnalyzeBytes(item.limitBytes)} | ${formatBudgetStatus(item)} |`).join("\n");
1044
- const incrementRows = incrementItems.slice(0, 10).map((item) => `| ${item.label} | ${item.category} | ${item.packageLabel} | ${formatAnalyzeBytes(item.deltaBytes)} | ${item.advice} |`).join("\n");
1045
- const incrementSummaryRows = incrementSummary.slice(0, 8).map((item) => `| ${item.category} | ${item.count} | ${formatAnalyzeBytes(item.deltaBytes)} |`).join("\n");
1046
- return [
1047
- "# weapp-vite analyze 报告",
1048
- "",
1049
- `生成时间:${result.metadata?.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString()}`,
1050
- "",
1051
- "## 本次变化摘要",
1052
- "",
1053
- `- 总产物体积:${formatAnalyzeBytes(totalBytes)}`,
1054
- `- 压缩后体积:${formatAnalyzeBytes(compressedBytes)}`,
1055
- `- 较上次:${formatDelta(typeof previousTotalBytes === "number" ? totalBytes - previousTotalBytes : void 0)}`,
1056
- `- 包体数量:${result.packages.length}`,
1057
- `- 源码模块:${result.modules.length}`,
1058
- `- 跨包复用:${duplicateInsights.length}`,
1059
- `- 预算来源:${budgets?.source === "config" ? "配置" : "默认"}`,
1060
- "",
1061
- "## 预算告警",
1062
- "",
1063
- "| 对象 | 范围 | 当前体积 | 预算 | 状态 |",
1064
- "| --- | --- | ---: | ---: | --- |",
1065
- budgetRows || "| - | - | 0 B | 0 B | 正常 |",
1066
- "",
1067
- "## 建议动作",
1068
- "",
1069
- ...actionItems.map((item) => `- ${item}`),
1070
- "",
1071
- "## 增量归因",
1072
- "",
1073
- "| 来源 | 项数 | 增量 |",
1074
- "| --- | ---: | ---: |",
1075
- incrementSummaryRows || "| - | 0 | 0 B |",
1076
- "",
1077
- "| 文件/模块 | 来源 | 包 | 增量 | 建议 |",
1078
- "| --- | --- | --- | ---: | --- |",
1079
- incrementRows || "| - | - | - | 0 B | - |",
1080
- "",
1081
- "## 包体预算",
1082
- "",
1083
- "| 包 | 类型 | 体积 | 压缩后 | 较上次 | 预算 |",
1084
- "| --- | --- | ---: | ---: | ---: | --- |",
1085
- packageRows || "| - | - | 0 B | 0 B | 无变化 | 正常 |",
1086
- "",
1087
- "## Top 文件",
1088
- "",
1089
- "| 文件 | 包 | 类型 | 体积 | 压缩后 |",
1090
- "| --- | --- | --- | ---: | ---: |",
1091
- topFileRows || "| - | - | - | 0 B | 0 B |",
1092
- "",
1093
- "## 重复模块",
1094
- "",
1095
- "| 模块 | 来源 | 包数量 | 估算可节省 | 建议 |",
1096
- "| --- | --- | ---: | ---: | --- |",
1097
- duplicateRows || "| - | - | 0 | 0 B | - |",
1098
- ""
1099
- ].join("\n");
1154
+ }).filter((descriptor) => descriptor.root);
1155
+ descriptors.sort((a, b) => a.root.localeCompare(b.root));
1156
+ return descriptors;
1100
1157
  }
1101
1158
  //#endregion
1102
- //#region src/cli/analyze/dashboard.ts
1103
- const ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_ANALYZE_RESULT__";
1104
- const PREVIOUS_ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_PREVIOUS_ANALYZE_RESULT__";
1105
- const DASHBOARD_EVENTS_GLOBAL_KEY = "__WEAPP_VITE_DASHBOARD_EVENTS__";
1106
- const ANALYZE_DASHBOARD_PACKAGE_NAME = "@weapp-vite/dashboard";
1107
- const ANALYZE_SSE_PATH = "/__weapp_vite_analyze";
1108
- const FILE_CONTENT_PATH = "/__weapp_vite_file_content";
1109
- const DASHBOARD_EVENT_NAME = "weapp-dashboard:event";
1110
- const MAX_FILE_CONTENT_BYTES = 2 * 1024 * 1024;
1111
- const require = createRequire(import.meta.url);
1112
- function createInstallCommand(agent) {
1113
- const resolved = resolveCommand(agent ?? "npm", "install", [ANALYZE_DASHBOARD_PACKAGE_NAME]);
1114
- if (!resolved) return `npm install ${ANALYZE_DASHBOARD_PACKAGE_NAME}`;
1115
- return `${resolved.command} ${resolved.args.join(" ")}`;
1116
- }
1117
- function formatEventTimestamp(date = /* @__PURE__ */ new Date()) {
1118
- return date.toLocaleTimeString("zh-CN", { hour12: false });
1119
- }
1120
- function createDashboardRuntimeEvent(input) {
1121
- return {
1122
- id: `dashboard:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,
1123
- kind: input.kind,
1124
- level: input.level,
1125
- title: input.title,
1126
- detail: input.detail,
1127
- timestamp: formatEventTimestamp(),
1128
- source: input.source ?? "weapp-vite",
1129
- durationMs: input.durationMs,
1130
- tags: input.tags,
1131
- profile: input.profile
1159
+ //#region src/analyze/subpackages/index.ts
1160
+ async function analyzeSubpackages(ctx) {
1161
+ const { configService, scanService, buildService } = ctx;
1162
+ if (!configService || !scanService || !buildService) throw new Error("analyzeSubpackages 需要先初始化 configService、scanService 和 buildService。");
1163
+ await scanService.loadAppEntry();
1164
+ const subPackageMetas = scanService.loadSubPackages();
1165
+ const subPackageRoots = /* @__PURE__ */ new Set();
1166
+ const independentRoots = /* @__PURE__ */ new Set();
1167
+ for (const meta of subPackageMetas) {
1168
+ const root = meta.subPackage.root;
1169
+ if (root) {
1170
+ subPackageRoots.add(root);
1171
+ if (meta.subPackage.independent) independentRoots.add(root);
1172
+ }
1173
+ }
1174
+ const classifierContext = {
1175
+ subPackageRoots,
1176
+ independentRoots
1132
1177
  };
1133
- }
1134
- function readDashboardManifest(packageJsonPath) {
1135
- try {
1136
- return parseCommentJson(fs$1.readFileSync(packageJsonPath, "utf8"));
1137
- } catch {
1138
- return;
1178
+ const mainResult = await build(configService.merge(void 0, createSharedBuildConfig(configService, scanService), { build: {
1179
+ write: false,
1180
+ watch: null
1181
+ } }));
1182
+ const mainOutputs = Array.isArray(mainResult) ? mainResult : [mainResult];
1183
+ const packages = /* @__PURE__ */ new Map();
1184
+ const modules = /* @__PURE__ */ new Map();
1185
+ const componentJsonConfigs = [];
1186
+ for (const output of mainOutputs) {
1187
+ processOutput(output, "main", ctx, classifierContext, packages, modules);
1188
+ componentJsonConfigs.push(...collectAnalyzeComponentJsonConfigs(output));
1139
1189
  }
1140
- }
1141
- function resolveDashboardDistRoot(packageRoot, manifest) {
1142
- const distDir = manifest?.weappViteDashboard?.distDir ?? "dist";
1143
- const distRoot = path.resolve(packageRoot, distDir);
1144
- if (!fs$1.existsSync(distRoot)) return;
1145
- return { root: distRoot };
1146
- }
1147
- function resolveDashboardDevRoot(packageRoot, manifest) {
1148
- const devRoot = manifest?.weappViteDashboard?.devRoot;
1149
- const devConfigFile = manifest?.weappViteDashboard?.devConfigFile;
1150
- if (!devRoot || !devConfigFile) return;
1151
- const root = path.resolve(packageRoot, devRoot);
1152
- const configFile = path.resolve(root, devConfigFile);
1153
- if (!fs$1.existsSync(root) || !fs$1.existsSync(configFile)) return;
1190
+ for (const root of independentRoots) {
1191
+ const output = buildService.getIndependentOutput(root);
1192
+ processOutput(output, "independent", ctx, classifierContext, packages, modules);
1193
+ componentJsonConfigs.push(...collectAnalyzeComponentJsonConfigs(output));
1194
+ }
1195
+ expandVirtualModulePlacements(modules, packages, classifierContext);
1196
+ const subPackages = summarizeSubPackages(subPackageMetas);
1154
1197
  return {
1155
- root,
1156
- configFile
1198
+ metadata: createAnalyzeMetadata(ctx.configService),
1199
+ packages: summarizePackages(packages),
1200
+ modules: summarizeModules(modules),
1201
+ subPackages,
1202
+ components: analyzeComponentUsage({
1203
+ jsonConfigs: componentJsonConfigs,
1204
+ subPackages
1205
+ })
1157
1206
  };
1158
1207
  }
1159
- function resolveDashboardRoot(options) {
1160
- const resolvePaths = options?.cwd && options.cwd !== process.cwd() ? [options.cwd, process.cwd()] : options?.cwd ? [options.cwd] : void 0;
1161
- let dashboardPackageRoot;
1162
- let dashboardManifest;
1208
+ //#endregion
1209
+ //#region src/analyze/subpackages/history.ts
1210
+ const jsonExtension = ".json";
1211
+ function createSnapshotFileName(date = /* @__PURE__ */ new Date()) {
1212
+ return `${date.toISOString().replace(/[:.]/g, "-")}${jsonExtension}`;
1213
+ }
1214
+ function isAnalyzeResult(value) {
1215
+ return Boolean(value && typeof value === "object" && Array.isArray(value.packages) && Array.isArray(value.modules) && Array.isArray(value.subPackages));
1216
+ }
1217
+ async function listSnapshotFiles(dir) {
1163
1218
  try {
1164
- const dashboardPackageJsonPath = require.resolve(`${ANALYZE_DASHBOARD_PACKAGE_NAME}/package.json`, { paths: resolvePaths });
1165
- dashboardPackageRoot = path.dirname(dashboardPackageJsonPath);
1166
- dashboardManifest = readDashboardManifest(dashboardPackageJsonPath);
1219
+ return (await fs$2.readdir(dir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(jsonExtension)).map((entry) => path.join(dir, entry.name)).sort((a, b) => b.localeCompare(a));
1167
1220
  } catch {
1168
- dashboardPackageRoot = void 0;
1169
- dashboardManifest = void 0;
1221
+ return [];
1170
1222
  }
1171
- if (dashboardPackageRoot) {
1172
- const devResolved = resolveDashboardDevRoot(dashboardPackageRoot, dashboardManifest);
1173
- if (devResolved) return devResolved;
1174
- const distResolved = resolveDashboardDistRoot(dashboardPackageRoot, dashboardManifest);
1175
- if (distResolved) return distResolved;
1176
- }
1177
- logger_default.warn(`[weapp-vite ui] 未安装可选仪表盘包 ${colors.bold(colors.green(ANALYZE_DASHBOARD_PACKAGE_NAME))},已自动降级关闭 dashboard 能力。`);
1178
- logger_default.info(`如需启用,请执行 ${colors.bold(colors.green(createInstallCommand(options?.packageManagerAgent)))}`);
1179
1223
  }
1180
- function normalizeDashboardRelativePath(value) {
1181
- return value.replaceAll("\\", "/");
1224
+ async function trimSnapshotFiles(dir, limit) {
1225
+ const staleFiles = (await listSnapshotFiles(dir)).slice(limit);
1226
+ await Promise.all(staleFiles.map(async (file) => {
1227
+ try {
1228
+ await fs$2.unlink(file);
1229
+ } catch {}
1230
+ }));
1182
1231
  }
1183
- function stripDashboardFileQuery(value) {
1184
- const queryIndex = value.indexOf("?");
1185
- return queryIndex === -1 ? value : value.slice(0, queryIndex);
1232
+ async function readLatestAnalyzeHistorySnapshot(configService) {
1233
+ const history = resolveAnalyzeHistoryMetadata(configService);
1234
+ if (!history.enabled) return null;
1235
+ const files = await listSnapshotFiles(history.dir);
1236
+ for (const file of files) try {
1237
+ const parsed = JSON.parse(await fs$2.readFile(file, "utf8"));
1238
+ if (isAnalyzeResult(parsed)) return parsed;
1239
+ } catch {}
1240
+ return null;
1186
1241
  }
1187
- function addDashboardAllowedPath(paths, value) {
1188
- if (!value || value.includes("\0")) return;
1189
- const normalizedPath = normalizeDashboardRelativePath(stripDashboardFileQuery(value));
1190
- if (!normalizedPath || path.isAbsolute(normalizedPath)) return;
1191
- paths.add(normalizedPath);
1242
+ async function writeAnalyzeHistorySnapshot(result, configService, now = /* @__PURE__ */ new Date()) {
1243
+ const history = resolveAnalyzeHistoryMetadata(configService);
1244
+ if (!history.enabled) return;
1245
+ await fs$2.mkdir(history.dir, { recursive: true });
1246
+ const snapshotPath = path.join(history.dir, createSnapshotFileName(now));
1247
+ if (result.metadata) result.metadata = {
1248
+ ...result.metadata,
1249
+ history: {
1250
+ ...history,
1251
+ dir: configService.relativeCwd(history.dir),
1252
+ latestSnapshot: configService.relativeCwd(snapshotPath)
1253
+ }
1254
+ };
1255
+ await fs$2.writeFile(snapshotPath, `${JSON.stringify(result, null, 2)}\n`, "utf8");
1256
+ await trimSnapshotFiles(history.dir, history.limit);
1257
+ return snapshotPath;
1192
1258
  }
1193
- function createDashboardContentAllowlist(result) {
1194
- const artifactPaths = /* @__PURE__ */ new Set();
1195
- const sourcePaths = /* @__PURE__ */ new Set();
1196
- for (const packageReport of result.packages) for (const file of packageReport.files) {
1197
- addDashboardAllowedPath(artifactPaths, file.file);
1198
- addDashboardAllowedPath(sourcePaths, file.source);
1199
- for (const module of file.modules ?? []) addDashboardAllowedPath(sourcePaths, module.source);
1259
+ //#endregion
1260
+ //#region src/analyze/subpackages/report.ts
1261
+ function formatAnalyzeBytes(bytes) {
1262
+ if (!bytes || Number.isNaN(bytes)) return "0 B";
1263
+ const units = [
1264
+ "B",
1265
+ "KB",
1266
+ "MB",
1267
+ "GB"
1268
+ ];
1269
+ let value = bytes;
1270
+ let unitIndex = 0;
1271
+ while (value >= 1024 && unitIndex < units.length - 1) {
1272
+ value /= 1024;
1273
+ unitIndex++;
1200
1274
  }
1201
- return {
1202
- artifactPaths,
1203
- sourcePaths
1204
- };
1275
+ return `${value.toFixed(value >= 100 || unitIndex === 0 ? 0 : 2)} ${units[unitIndex]}`;
1205
1276
  }
1206
- function resolveDashboardContentPath(root, requestPath, options) {
1207
- if (!root || !requestPath || requestPath.includes("\0")) return;
1208
- const normalizedRequestPath = normalizeDashboardRelativePath(stripDashboardFileQuery(requestPath));
1209
- if (path.isAbsolute(normalizedRequestPath)) return;
1210
- if (!options.allowedPaths.has(normalizedRequestPath)) return;
1211
- const resolvedRoot = path.resolve(root);
1212
- const absolutePath = path.resolve(resolvedRoot, normalizedRequestPath);
1213
- const relativePath = path.relative(resolvedRoot, absolutePath);
1214
- if (!relativePath) return;
1215
- if (!options.allowParent && (relativePath.startsWith("..") || path.isAbsolute(relativePath))) return;
1216
- return {
1217
- absolutePath,
1218
- relativePath: options.allowParent ? normalizedRequestPath : normalizeDashboardRelativePath(relativePath)
1219
- };
1277
+ function formatDelta(bytes) {
1278
+ if (typeof bytes !== "number" || Number.isNaN(bytes) || bytes === 0) return "无变化";
1279
+ return `${bytes > 0 ? "+" : "-"}${formatAnalyzeBytes(Math.abs(bytes))}`;
1220
1280
  }
1221
- function resolveDashboardFileLanguage(filePath) {
1222
- const extension = path.extname(filePath).toLowerCase();
1223
- if (extension === ".js" || extension === ".mjs" || extension === ".cjs" || extension === ".wxs" || extension === ".sjs") return "javascript";
1224
- if (extension === ".ts" || extension === ".mts" || extension === ".cts") return "typescript";
1225
- if (extension === ".json" || extension === ".map") return "json";
1226
- if (extension === ".css" || extension === ".wxss" || extension === ".scss" || extension === ".sass" || extension === ".less") return "css";
1227
- if (extension === ".vue" || extension === ".wxml" || extension === ".html") return "html";
1228
- return "plaintext";
1281
+ function getFileSize(file) {
1282
+ return file.size ?? 0;
1229
1283
  }
1230
- function sendDashboardJson(res, statusCode, payload) {
1231
- res.statusCode = statusCode;
1232
- res.setHeader("Content-Type", "application/json; charset=utf-8");
1233
- res.end(JSON.stringify(payload));
1284
+ function getCompressedSize(file) {
1285
+ return file.brotliSize ?? file.gzipSize ?? 0;
1234
1286
  }
1235
- async function sendDashboardFileContent(res, roots, allowlist, kind, requestPath) {
1236
- const resolved = resolveDashboardContentPath(kind === "artifact" ? roots.artifactRoot : kind === "source" ? roots.sourceRoot : void 0, requestPath, {
1237
- allowParent: kind === "source",
1238
- allowedPaths: kind === "artifact" ? allowlist.artifactPaths : allowlist.sourcePaths
1239
- });
1240
- if (!resolved || kind !== "source" && kind !== "artifact") {
1241
- sendDashboardJson(res, 400, {
1242
- error: "invalid_request",
1243
- message: "必须传入合法的 kind 和相对路径。"
1244
- });
1245
- return;
1287
+ function getBudgetLimit(type, budgets) {
1288
+ if (!budgets) return;
1289
+ if (type === "main") return budgets.mainBytes;
1290
+ if (type === "subPackage") return budgets.subPackageBytes;
1291
+ if (type === "independent") return budgets.independentBytes;
1292
+ }
1293
+ function createPackageSizeMap(result) {
1294
+ return new Map((result?.packages ?? []).map((pkg) => {
1295
+ const totalBytes = pkg.files.reduce((sum, file) => sum + getFileSize(file), 0);
1296
+ return [pkg.id, totalBytes];
1297
+ }));
1298
+ }
1299
+ function createFileKey(packageId, fileName) {
1300
+ return `${packageId}\u0000${fileName}`;
1301
+ }
1302
+ function createFileSizeMap(result) {
1303
+ const map = /* @__PURE__ */ new Map();
1304
+ for (const pkg of result?.packages ?? []) for (const file of pkg.files) map.set(createFileKey(pkg.id, file.file), getFileSize(file));
1305
+ return map;
1306
+ }
1307
+ function createPackageTypeMap(result) {
1308
+ return new Map(result.packages.map((pkg) => [pkg.id, pkg.type]));
1309
+ }
1310
+ function createModuleByteMap(result) {
1311
+ const map = /* @__PURE__ */ new Map();
1312
+ for (const pkg of result.packages) for (const file of pkg.files) for (const mod of file.modules ?? []) {
1313
+ const bytes = mod.bytes ?? mod.originalBytes ?? 0;
1314
+ map.set(mod.id, Math.max(map.get(mod.id) ?? 0, bytes));
1246
1315
  }
1247
- try {
1248
- const stat = await fs$1.promises.stat(resolved.absolutePath);
1249
- if (!stat.isFile()) {
1250
- sendDashboardJson(res, 400, {
1251
- error: "not_file",
1252
- message: "目标路径不是文件。"
1253
- });
1254
- return;
1255
- }
1256
- if (stat.size > MAX_FILE_CONTENT_BYTES) {
1257
- sendDashboardJson(res, 413, {
1258
- error: "file_too_large",
1259
- message: `文件超过 ${MAX_FILE_CONTENT_BYTES} 字节,已拒绝读取。`
1260
- });
1261
- return;
1262
- }
1263
- sendDashboardJson(res, 200, {
1264
- kind,
1265
- path: resolved.relativePath,
1266
- language: resolveDashboardFileLanguage(resolved.relativePath),
1267
- size: stat.size,
1268
- content: await fs$1.promises.readFile(resolved.absolutePath, "utf8")
1269
- });
1270
- } catch (error) {
1271
- const code = typeof error === "object" && error && "code" in error ? String(error.code) : "";
1272
- sendDashboardJson(res, code === "ENOENT" ? 404 : 500, {
1273
- error: code === "ENOENT" ? "not_found" : "read_failed",
1274
- message: code === "ENOENT" ? "文件不存在。" : "读取文件失败。"
1316
+ return map;
1317
+ }
1318
+ function classifyIncrementCategory(source, sourceType) {
1319
+ if (source.includes("wevu") || source.includes("@weapp-vite/dashboard")) return "WeVu / runtime";
1320
+ if (sourceType === "node_modules" || source.includes("node_modules")) return "第三方依赖";
1321
+ if (sourceType === "workspace") return "工作区包";
1322
+ if (sourceType === "plugin") return "插件生成";
1323
+ if (source.endsWith(".wxss") || source.endsWith(".css") || source.endsWith(".scss")) return "样式资源";
1324
+ if (source.endsWith(".wxml") || source.endsWith(".json")) return "页面结构";
1325
+ return "业务源码";
1326
+ }
1327
+ function createIncrementAdvice(item) {
1328
+ if (item.category === "第三方依赖") return "检查依赖是否只在必要分包引用,必要时收敛到公共入口或替换轻量实现。";
1329
+ if (item.category === "WeVu / runtime") return "确认运行时能力是否被新页面引入,优先排查组件和 API 引用边界。";
1330
+ if (item.category === "样式资源") return "检查样式重复、原子类生成范围和组件样式裁剪。";
1331
+ if (item.type === "new-file" || item.type === "new-module") return "确认是否为本次需求必要新增,评估分包归属和懒加载边界。";
1332
+ return "对比本次变更,优先查看新增引用、共享模块和大对象常量。";
1333
+ }
1334
+ function createModuleSizeMap(result) {
1335
+ const map = /* @__PURE__ */ new Map();
1336
+ for (const pkg of result?.packages ?? []) for (const file of pkg.files) for (const module of file.modules ?? []) {
1337
+ const bytes = module.bytes ?? module.originalBytes ?? 0;
1338
+ const existing = map.get(module.id);
1339
+ if (existing && existing.bytes >= bytes) continue;
1340
+ map.set(module.id, {
1341
+ source: module.source,
1342
+ sourceType: module.sourceType,
1343
+ bytes,
1344
+ packageLabel: pkg.label,
1345
+ file: file.file
1275
1346
  });
1276
1347
  }
1348
+ return map;
1277
1349
  }
1278
- function createAnalyzeHtmlPlugin(state, runtimeEvents, contentRoots, contentAllowlist, onServerInstance, onBroadcastReady) {
1279
- const sseClients = /* @__PURE__ */ new Set();
1280
- const hotBridgeScript = `
1281
- const applyAnalyzePayload = (payload) => {
1282
- const current = payload?.current ?? payload
1283
- const previous = payload?.previous ?? window.${PREVIOUS_ANALYZE_GLOBAL_KEY} ?? null
1284
- window.${ANALYZE_GLOBAL_KEY} = current
1285
- window.${PREVIOUS_ANALYZE_GLOBAL_KEY} = previous
1286
- window.dispatchEvent(new CustomEvent('weapp-analyze:update', { detail: { current, previous } }))
1287
- }
1288
- const applyDashboardEvents = (payload) => {
1289
- const events = Array.isArray(payload) ? payload : [payload]
1290
- const nextEvents = events.filter(Boolean)
1291
- if (nextEvents.length === 0) {
1292
- return
1293
- }
1294
- window.${DASHBOARD_EVENTS_GLOBAL_KEY} = [
1295
- ...(window.${DASHBOARD_EVENTS_GLOBAL_KEY} ?? []),
1296
- ...nextEvents,
1297
- ]
1298
- window.dispatchEvent(new CustomEvent('${DASHBOARD_EVENT_NAME}', { detail: nextEvents }))
1299
- }
1300
- const source = new EventSource('${ANALYZE_SSE_PATH}')
1301
- source.onmessage = (event) => {
1302
- try {
1303
- applyAnalyzePayload(JSON.parse(event.data))
1304
- }
1305
- catch {}
1306
- }
1307
- if (import.meta.hot) {
1308
- import.meta.hot.on('weapp-analyze:update', (payload) => {
1309
- applyAnalyzePayload(payload)
1310
- })
1311
- import.meta.hot.on('${DASHBOARD_EVENT_NAME}', (payload) => {
1312
- applyDashboardEvents(payload)
1313
- })
1314
- }
1315
- `.trim();
1316
- const broadcast = (payload) => {
1317
- const serialized = `data: ${JSON.stringify(payload)}\n\n`;
1318
- for (const client of sseClients) client.write(serialized);
1319
- };
1320
- onBroadcastReady(broadcast);
1321
- return {
1322
- name: "weapp-vite-analyze-html",
1323
- transformIndexHtml(html) {
1324
- return {
1325
- html,
1326
- tags: [
1327
- {
1328
- tag: "script",
1329
- children: `window.${ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.current)}`,
1330
- injectTo: "head-prepend"
1331
- },
1332
- {
1333
- tag: "script",
1334
- children: `window.${PREVIOUS_ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.previous)}`,
1335
- injectTo: "head-prepend"
1336
- },
1337
- {
1338
- tag: "script",
1339
- children: `window.${DASHBOARD_EVENTS_GLOBAL_KEY} = ${JSON.stringify(runtimeEvents.current)}`,
1340
- injectTo: "head-prepend"
1341
- },
1342
- {
1343
- tag: "script",
1344
- attrs: {
1345
- type: "module",
1346
- src: "/@vite/client"
1347
- },
1348
- injectTo: "head"
1349
- },
1350
- {
1351
- tag: "script",
1352
- attrs: { type: "module" },
1353
- children: hotBridgeScript,
1354
- injectTo: "body"
1355
- }
1356
- ]
1357
- };
1358
- },
1359
- configureServer(server) {
1360
- onServerInstance(server);
1361
- server.middlewares.use((req, res, next) => {
1362
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
1363
- if (url.pathname === FILE_CONTENT_PATH) {
1364
- sendDashboardFileContent(res, contentRoots, contentAllowlist.current, url.searchParams.get("kind"), url.searchParams.get("path"));
1365
- return;
1366
- }
1367
- if (url.pathname !== ANALYZE_SSE_PATH) {
1368
- next();
1369
- return;
1370
- }
1371
- res.statusCode = 200;
1372
- res.setHeader("Content-Type", "text/event-stream");
1373
- res.setHeader("Cache-Control", "no-cache, no-transform");
1374
- res.setHeader("Connection", "keep-alive");
1375
- res.write(`data: ${JSON.stringify(state)}\n\n`);
1376
- sseClients.add(res);
1377
- req.on("close", () => {
1378
- sseClients.delete(res);
1379
- });
1380
- });
1381
- }
1382
- };
1383
- }
1384
- async function waitForServerExit(server) {
1385
- let resolved = false;
1386
- const cleanup = async () => {
1387
- if (resolved) return;
1388
- resolved = true;
1389
- try {
1390
- await server.close();
1391
- } catch (error) {
1392
- logger_default.error(error);
1393
- }
1394
- };
1395
- const signals = ["SIGINT", "SIGTERM"];
1396
- await new Promise((resolvePromise) => {
1397
- const resolveOnce = async () => {
1398
- await cleanup();
1399
- signals.forEach((signal) => {
1400
- process.removeListener(signal, resolveOnce);
1401
- });
1402
- resolvePromise();
1403
- };
1404
- signals.forEach((signal) => {
1405
- process.once(signal, resolveOnce);
1406
- });
1407
- server.httpServer?.once("close", resolveOnce);
1408
- });
1409
- }
1410
- async function startAnalyzeDashboard(result, options) {
1411
- const resolved = resolveDashboardRoot(options);
1412
- if (!resolved) return;
1413
- const { root, configFile } = resolved;
1414
- const state = {
1415
- current: result,
1416
- previous: options?.previousResult ?? null
1417
- };
1418
- const contentAllowlist = { current: createDashboardContentAllowlist(result) };
1419
- const runtimeEvents = { current: [createDashboardRuntimeEvent({
1420
- kind: "command",
1421
- level: "success",
1422
- title: options?.watch ? "dashboard watch session started" : "dashboard static session started",
1423
- detail: options?.watch ? "weapp-vite UI 已进入实时分析模式,后续 analyze 结果会继续推送到 dashboard。" : "weapp-vite UI 已进入静态分析模式,当前页面展示的是一次性分析结果。",
1424
- tags: options?.watch ? ["watch", "analyze"] : ["static", "analyze"]
1425
- }), ...(options?.initialEvents ?? []).map((event) => createDashboardRuntimeEvent(event))] };
1426
- let serverRef;
1427
- let broadcastAnalyzeResult;
1428
- const plugins = [createAnalyzeHtmlPlugin(state, runtimeEvents, {
1429
- artifactRoot: options?.artifactRoot ?? (options?.cwd ? path.resolve(options.cwd, "dist") : void 0),
1430
- sourceRoot: options?.cwd
1431
- }, contentAllowlist, (server) => {
1432
- serverRef = server;
1433
- }, (broadcast) => {
1434
- broadcastAnalyzeResult = broadcast;
1435
- })];
1436
- const serverOptions = {
1437
- root,
1438
- configFile: configFile ?? false,
1439
- clearScreen: false,
1440
- appType: "spa",
1441
- publicDir: false,
1442
- plugins,
1443
- server: {
1444
- host: "127.0.0.1",
1445
- port: 0,
1446
- watch: { ignored: ["**/*"] }
1447
- },
1448
- logLevel: "error"
1449
- };
1450
- const server = await createServer(serverOptions);
1451
- const requestedPort = typeof serverOptions.server?.port === "number" ? serverOptions.server.port : void 0;
1452
- await server.listen(requestedPort);
1453
- serverRef ??= server;
1454
- server.printUrls();
1455
- const urls = (() => {
1456
- const resolved = server.resolvedUrls;
1457
- if (!resolved) return [];
1458
- return [...resolved.local ?? [], ...resolved.network ?? []];
1459
- })();
1460
- const waitPromise = waitForServerExit(server);
1461
- if (serverRef?.ws) {
1462
- serverRef.ws.send({
1463
- type: "custom",
1464
- event: "weapp-analyze:update",
1465
- data: state
1466
- });
1467
- serverRef.ws.send({
1468
- type: "custom",
1469
- event: DASHBOARD_EVENT_NAME,
1470
- data: runtimeEvents.current
1471
- });
1472
- }
1473
- broadcastAnalyzeResult?.(state);
1474
- const emitRuntimeEvents = (events) => {
1475
- if (events.length === 0) return;
1476
- const nextEvents = events.map((event) => createDashboardRuntimeEvent(event));
1477
- runtimeEvents.current = [...nextEvents, ...runtimeEvents.current].slice(0, 24);
1478
- if (serverRef) serverRef.ws.send({
1479
- type: "custom",
1480
- event: DASHBOARD_EVENT_NAME,
1481
- data: nextEvents
1482
- });
1483
- };
1484
- const handle = {
1485
- async update(nextResult, previousResult) {
1486
- state.previous = previousResult ?? state.current;
1487
- state.current = nextResult;
1488
- contentAllowlist.current = createDashboardContentAllowlist(nextResult);
1489
- emitRuntimeEvents([{
1490
- kind: "build",
1491
- level: "info",
1492
- title: "analyze payload refreshed",
1493
- detail: `已推送新的 analyze 结果,当前包含 ${nextResult.packages.length} 个包与 ${nextResult.modules.length} 个模块。`,
1494
- tags: ["analyze", "refresh"]
1495
- }]);
1496
- if (serverRef) serverRef.ws.send({
1497
- type: "custom",
1498
- event: "weapp-analyze:update",
1499
- data: state
1500
- });
1501
- broadcastAnalyzeResult?.(state);
1502
- },
1503
- emitRuntimeEvents,
1504
- waitForExit: () => waitPromise,
1505
- close: async () => {
1506
- await server.close();
1507
- },
1508
- urls
1509
- };
1510
- if (options?.watch) {
1511
- if (!options.silentStartupLog) {
1512
- logger_default.info("weapp-vite UI 已启动(分析视图,实时模式),按 Ctrl+C 退出。");
1513
- for (const url of handle.urls) logger_default.info(` ➜ ${colors.bold(colors.cyan(url))}`);
1514
- }
1515
- return handle;
1516
- }
1517
- if (!options?.silentStartupLog) {
1518
- logger_default.info("weapp-vite UI 已启动(分析视图,静态模式),按 Ctrl+C 退出。");
1519
- for (const url of handle.urls) logger_default.info(` ➜ ${colors.bold(colors.cyan(url))}`);
1520
- }
1521
- await waitPromise;
1522
- }
1523
- //#endregion
1524
- //#region src/cli/options.ts
1525
- function filterDuplicateOptions(options) {
1526
- for (const [key, value] of Object.entries(options)) if (Array.isArray(value)) options[key] = value.at(-1);
1527
- }
1528
- function resolveConfigFile(options) {
1529
- if (typeof options.config === "string") return options.config;
1530
- if (typeof options.c === "string") return options.c;
1531
- }
1532
- function convertBase(value) {
1533
- if (value === 0) return "";
1534
- return value;
1535
- }
1536
- function coerceBooleanOption(value) {
1537
- if (value === void 0) return;
1538
- if (typeof value === "boolean") return value;
1539
- if (typeof value === "string") {
1540
- const normalized = value.trim().toLowerCase();
1541
- if (normalized === "") return true;
1542
- if (normalized === "false" || normalized === "0" || normalized === "off" || normalized === "no") return false;
1543
- if (normalized === "true" || normalized === "1" || normalized === "on" || normalized === "yes") return true;
1544
- return true;
1545
- }
1546
- if (typeof value === "number") return value !== 0;
1547
- return Boolean(value);
1548
- }
1549
- function isUiEnabled(options) {
1550
- return Boolean(options.ui || options.analyze);
1551
- }
1552
- //#endregion
1553
- //#region src/cli/runtime.ts
1554
- function logRuntimeTarget(targets, options = {}) {
1555
- if (options.silent) return;
1556
- if (targets.label === "config") {
1557
- const resolvedPlatform = targets.platform ?? options.resolvedConfigPlatform;
1558
- if (resolvedPlatform) {
1559
- logger_default.info(`目标平台:${colors.green(resolvedPlatform)}`);
1560
- return;
1561
- }
1562
- logger_default.info(`目标平台:使用配置文件中的 ${colors.bold(colors.green("weapp.platform"))}`);
1563
- return;
1564
- }
1565
- logger_default.info(`目标平台:${colors.green(targets.label)}`);
1566
- }
1567
- function resolveRuntimeTargets(options) {
1568
- const rawPlatform = typeof options.platform === "string" ? options.platform : typeof options.p === "string" ? options.p : void 0;
1569
- const target = resolveWeappViteTarget(rawPlatform, { warn: (message) => logger_default.warn(message) });
1570
- return {
1571
- runMini: target.runMini,
1572
- runWeb: target.runWeb,
1573
- platform: target.kind === "miniprogram" ? target.platform : void 0,
1574
- label: target.label,
1575
- rawPlatform
1576
- };
1577
- }
1578
- function createInlineConfig(platform) {
1579
- if (!platform) return;
1580
- return { weapp: { platform } };
1581
- }
1582
- //#endregion
1583
- //#region src/cli/commands/analyze.ts
1584
- function normalizeDisplayPath(value) {
1585
- return value || ".";
1586
- }
1587
- function getDefaultWebAnalyzeScopes() {
1588
- return {
1589
- supported: [
1590
- "weapp.web 配置解析(enable/root/srcDir/outDir)",
1591
- "runtime.executionMode 静态解析(compat/safe/strict)",
1592
- "JSON 报告输出(--json/--output)"
1593
- ],
1594
- unsupported: [
1595
- "分包产物体积分析(仅小程序)",
1596
- "源码模块包体映射(仅小程序)",
1597
- "分析仪表盘(dashboard)"
1598
- ]
1599
- };
1600
- }
1601
- function createWebAnalyzeResult(configService, options) {
1602
- const webConfig = configService.weappWebConfig;
1603
- const executionMode = webConfig?.pluginOptions.runtime?.executionMode ?? "compat";
1604
- const scope = getDefaultWebAnalyzeScopes();
1605
- const limitations = ["当前仅提供静态配置分析,不执行 Web 产物扫描。"];
1606
- if (!webConfig?.enabled) limitations.push("未检测到启用的 weapp.web 配置。");
1607
- return {
1608
- runtime: "web",
1609
- platform: options.platform,
1610
- mode: configService.mode,
1611
- generatedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
1612
- experimental: true,
1613
- configFile: configService.configFilePath ? normalizeDisplayPath(configService.relativeCwd(configService.configFilePath)) : void 0,
1614
- web: {
1615
- enabled: Boolean(webConfig?.enabled),
1616
- root: webConfig?.root ? normalizeDisplayPath(configService.relativeCwd(webConfig.root)) : void 0,
1617
- srcDir: webConfig?.srcDir,
1618
- outDir: webConfig?.outDir ? normalizeDisplayPath(configService.relativeCwd(webConfig.outDir)) : void 0,
1619
- executionMode
1620
- },
1621
- supportedScopes: scope.supported,
1622
- unsupportedScopes: scope.unsupported,
1623
- limitations
1624
- };
1625
- }
1626
- function printAnalysisSummary(result) {
1627
- const packageLabelMap = /* @__PURE__ */ new Map();
1628
- const packageModuleSet = /* @__PURE__ */ new Map();
1629
- for (const pkg of result.packages) packageLabelMap.set(pkg.id, pkg.label);
1630
- for (const module of result.modules) for (const pkgRef of module.packages) {
1631
- const set = packageModuleSet.get(pkgRef.packageId) ?? /* @__PURE__ */ new Set();
1632
- set.add(module.id);
1633
- packageModuleSet.set(pkgRef.packageId, set);
1634
- }
1635
- logger_default.success("分包分析完成");
1636
- for (const pkg of result.packages) {
1637
- const chunkCount = pkg.files.filter((file) => file.type === "chunk").length;
1638
- const assetCount = pkg.files.length - chunkCount;
1639
- const moduleCount = packageModuleSet.get(pkg.id)?.size ?? 0;
1640
- logger_default.info(`- ${pkg.label}:${chunkCount} 个模块产物,${assetCount} 个资源,覆盖 ${moduleCount} 个源码模块`);
1641
- }
1642
- if (result.subPackages.length > 0) {
1643
- logger_default.info("分包配置:");
1644
- for (const descriptor of result.subPackages) {
1645
- const segments = [descriptor.root];
1646
- if (descriptor.name) segments.push(`别名:${descriptor.name}`);
1647
- if (descriptor.independent) segments.push("独立构建");
1648
- logger_default.info(`- ${segments.join(",")}`);
1649
- }
1650
- }
1651
- const componentUsages = result.components ?? [];
1652
- if (componentUsages.length > 0) {
1653
- const suggestions = componentUsages.flatMap((component) => component.suggestions);
1654
- logger_default.info(`组件依赖:${componentUsages.length} 个组件,${suggestions.length} 条分包优化建议`);
1655
- for (const suggestion of suggestions.slice(0, 5)) logger_default.info(`- ${suggestion.message}`);
1656
- if (suggestions.length > 5) logger_default.info(`- …其余 ${suggestions.length - 5} 条组件建议请使用 ${colors.bold(colors.green("weapp-vite analyze --json"))} 查看`);
1657
- }
1658
- const duplicates = result.modules.filter((module) => module.packages.length > 1);
1659
- if (duplicates.length === 0) {
1660
- logger_default.info("未检测到跨包复用的源码模块。");
1661
- return;
1662
- }
1663
- logger_default.info(`跨包复用/复制源码共 ${duplicates.length} 项:`);
1664
- const limit = 10;
1665
- const entries = duplicates.slice(0, limit);
1666
- for (const module of entries) {
1667
- const placements = module.packages.map((pkgRef) => {
1668
- return `${packageLabelMap.get(pkgRef.packageId) ?? pkgRef.packageId} → ${pkgRef.files.join(", ")}`;
1669
- }).join(";");
1670
- logger_default.info(`- ${module.source} (${module.sourceType}):${placements}`);
1671
- }
1672
- if (duplicates.length > limit) logger_default.info(`- …其余 ${duplicates.length - limit} 项请使用 ${colors.bold(colors.green("weapp-vite analyze --json"))} 查看`);
1673
- }
1674
- function printBudgetCheckSummary(result) {
1675
- const exceededItems = createAnalyzeBudgetCheck(result).filter((item) => item.status === "exceeded");
1676
- if (exceededItems.length === 0) {
1677
- logger_default.success("包体预算检查通过");
1678
- return false;
1679
- }
1680
- logger_default.error(`包体预算检查失败:${exceededItems.length} 项超限`);
1681
- for (const item of exceededItems) logger_default.error(`- ${item.label}:${formatAnalyzeBytes(item.currentBytes)} / ${formatAnalyzeBytes(item.limitBytes)} (${(item.ratio * 100).toFixed(1)}%)`);
1682
- return true;
1350
+ function createDuplicateAdvice(sourceType, packageIds, packageTypeMap, estimatedSavingBytes) {
1351
+ if (packageIds.some((packageId) => packageTypeMap.get(packageId) === "independent")) return estimatedSavingBytes > 0 ? "含独立分包,先确认隔离要求,再评估是否抽公共入口。" : "含独立分包,重复可能来自隔离边界。";
1352
+ if (sourceType === "node_modules") return "依赖被多个包带入,检查引用边界或考虑主包公共入口。";
1353
+ if (sourceType === "src" || sourceType === "workspace") return "共享源码跨包重复,优先抽公共模块或调整分包归属。";
1354
+ if (sourceType === "plugin") return "插件生成内容跨包重复,检查插件产物输出策略。";
1355
+ return "检查该模块是否需要在多个包内重复存在。";
1683
1356
  }
1684
- function printWebAnalysisSummary(result) {
1685
- logger_default.success("Web 静态分析完成");
1686
- logger_default.info(`- 配置状态:${result.web.enabled ? "已启用 weapp.web" : "未启用 weapp.web"}`);
1687
- if (result.web.enabled) {
1688
- logger_default.info(`- root:${result.web.root ?? "."}`);
1689
- logger_default.info(`- srcDir:${result.web.srcDir ?? "."}`);
1690
- logger_default.info(`- outDir:${result.web.outDir ?? "dist/web"}`);
1691
- }
1692
- logger_default.info(`- executionMode:${result.web.executionMode}`);
1693
- logger_default.info(`- 支持范围:${result.supportedScopes.join(";")}`);
1694
- logger_default.warn(`- 未支持范围:${result.unsupportedScopes.join(";")}`);
1695
- for (const limitation of result.limitations) logger_default.warn(`- 限制:${limitation}`);
1357
+ function formatBudgetStatus(item) {
1358
+ if (item.status === "ok") return "正常";
1359
+ return `${item.status === "exceeded" ? "超预算" : "接近预算"} ${(item.ratio * 100).toFixed(1)}%`;
1696
1360
  }
1697
- async function writeAnalyzeResult(result, outputOption, configService, format = "json", previousResult) {
1698
- if (!outputOption) return;
1699
- const baseDir = configService.cwd;
1700
- const resolvedOutputPath = path.isAbsolute(outputOption) ? outputOption : path.resolve(baseDir, outputOption);
1701
- await fs.ensureDir(path.dirname(resolvedOutputPath));
1702
- const content = format === "markdown" && "packages" in result ? createAnalyzeMarkdownReport(result, previousResult) : format === "pr" && "packages" in result ? createAnalyzePrMarkdownReport(result, previousResult) : JSON.stringify(result, null, 2);
1703
- await fs.writeFile(resolvedOutputPath, `${content}\n`, "utf8");
1704
- const relativeOutput = configService.relativeCwd(resolvedOutputPath);
1705
- logger_default.success(`分析结果已写入 ${colors.green(relativeOutput)}`);
1706
- return resolvedOutputPath;
1361
+ function createActionItems(options) {
1362
+ const actions = [];
1363
+ const exceededItems = options.budgetItems.filter((item) => item.status === "exceeded");
1364
+ const warningItems = options.budgetItems.filter((item) => item.status === "warning");
1365
+ const topDuplicate = options.duplicateInsights.find((item) => item.estimatedSavingBytes > 0);
1366
+ if (exceededItems.length > 0) actions.push(`处理 ${exceededItems[0].label} 预算超限:当前 ${formatAnalyzeBytes(exceededItems[0].currentBytes)},限制 ${formatAnalyzeBytes(exceededItems[0].limitBytes)}。`);
1367
+ else if (warningItems.length > 0) actions.push(`关注 ${warningItems[0].label} 预算接近阈值:当前 ${(warningItems[0].ratio * 100).toFixed(1)}%。`);
1368
+ if (topDuplicate) actions.push(`优先处理重复模块 ${topDuplicate.source},估算可节省 ${formatAnalyzeBytes(topDuplicate.estimatedSavingBytes)}。`);
1369
+ if (actions.length === 0) actions.push("当前没有预算超限或高收益重复模块,保持观察即可。");
1370
+ return actions;
1707
1371
  }
1708
- function formatMetricSummary(label, metric) {
1709
- if (!metric.count || metric.averageMs === void 0 || metric.maxMs === void 0) return;
1710
- return `${label} avg ${metric.averageMs.toFixed(2)} ms,max ${metric.maxMs.toFixed(2)} ms`;
1372
+ function createAnalyzeBudgetCheck(result) {
1373
+ const budgets = result.metadata?.budgets;
1374
+ if (!budgets) return [];
1375
+ const items = [];
1376
+ const totalBytes = result.packages.flatMap((pkg) => pkg.files).reduce((sum, file) => sum + getFileSize(file), 0);
1377
+ const warningRatio = budgets.warningRatio;
1378
+ const createItem = (options) => {
1379
+ const ratio = options.limitBytes > 0 ? options.currentBytes / options.limitBytes : 0;
1380
+ const status = ratio >= 1 ? "exceeded" : ratio >= warningRatio ? "warning" : "ok";
1381
+ return {
1382
+ ...options,
1383
+ ratio,
1384
+ status
1385
+ };
1386
+ };
1387
+ items.push(createItem({
1388
+ id: "__total__",
1389
+ label: "总包",
1390
+ scope: "total",
1391
+ currentBytes: totalBytes,
1392
+ limitBytes: budgets.totalBytes
1393
+ }));
1394
+ for (const pkg of result.packages) {
1395
+ const limitBytes = getBudgetLimit(pkg.type, budgets);
1396
+ if (!limitBytes) continue;
1397
+ items.push(createItem({
1398
+ id: pkg.id,
1399
+ label: pkg.label,
1400
+ scope: pkg.type,
1401
+ currentBytes: pkg.files.reduce((sum, file) => sum + getFileSize(file), 0),
1402
+ limitBytes
1403
+ }));
1404
+ }
1405
+ return items.sort((a, b) => b.ratio - a.ratio || a.label.localeCompare(b.label));
1711
1406
  }
1712
- function formatCountItems(items, limit = 5) {
1713
- return items.slice(0, limit).map((item) => `${item.name} x${item.count}`).join(",");
1407
+ function createDuplicateModuleInsights(result) {
1408
+ const moduleByteMap = createModuleByteMap(result);
1409
+ const packageTypeMap = createPackageTypeMap(result);
1410
+ return result.modules.filter((module) => module.packages.length > 1).map((module) => {
1411
+ const bytes = moduleByteMap.get(module.id) ?? 0;
1412
+ const packageIds = module.packages.map((pkg) => pkg.packageId);
1413
+ const estimatedSavingBytes = bytes * Math.max(module.packages.length - 1, 0);
1414
+ return {
1415
+ id: module.id,
1416
+ source: module.source,
1417
+ sourceType: module.sourceType,
1418
+ packageCount: module.packages.length,
1419
+ bytes,
1420
+ estimatedSavingBytes,
1421
+ packages: packageIds,
1422
+ advice: createDuplicateAdvice(module.sourceType, packageIds, packageTypeMap, estimatedSavingBytes)
1423
+ };
1424
+ }).sort((a, b) => b.estimatedSavingBytes - a.estimatedSavingBytes || b.packageCount - a.packageCount || a.source.localeCompare(b.source));
1714
1425
  }
1715
- function printHmrProfileAnalysisSummary(result, configService) {
1716
- logger_default.success("HMR profile 分析完成");
1717
- logger_default.info(`- profile:${colors.green(configService.relativeCwd(result.profilePath))}`);
1718
- logger_default.info(`- 样本:${result.sampleCount} 条`);
1719
- if (result.firstTimestamp && result.lastTimestamp) logger_default.info(`- 时间范围:${result.firstTimestamp} -> ${result.lastTimestamp}`);
1720
- const totalSummary = formatMetricSummary("total", result.metrics.totalMs);
1721
- const watchSummary = formatMetricSummary("watch->dirty", result.metrics.watchToDirtyMs);
1722
- const emitSummary = formatMetricSummary("emit", result.metrics.emitMs);
1723
- const sharedSummary = formatMetricSummary("shared", result.metrics.sharedChunkResolveMs);
1724
- for (const summary of [
1725
- totalSummary,
1726
- watchSummary,
1727
- emitSummary,
1728
- sharedSummary
1729
- ]) if (summary) logger_default.info(`- ${summary}`);
1730
- if (result.events.length) logger_default.info(`- 事件分布:${formatCountItems(result.events)}`);
1731
- if (result.dirtyReasons.length) logger_default.info(`- 主要 dirty 原因:${formatCountItems(result.dirtyReasons)}`);
1732
- if (result.pendingReasons.length) logger_default.info(`- 主要 pending 原因:${formatCountItems(result.pendingReasons)}`);
1733
- if (result.skippedLineCount > 0) logger_default.warn(`- 跳过 ${result.skippedLineCount} 条无法解析的 profile 记录`);
1734
- if (result.slowestSamples.length) {
1735
- logger_default.info("- 最慢样本:");
1736
- for (const sample of result.slowestSamples.slice(0, 3)) {
1737
- const fileLabel = sample.file ? configService.relativeCwd(sample.file) : "(unknown)";
1738
- logger_default.info(` - ${sample.totalMs?.toFixed(2) ?? "0.00"} ms,${sample.event ?? "unknown"},${fileLabel}`);
1739
- }
1426
+ function createAnalyzeIncrementAttribution(result, previousResult) {
1427
+ if (!previousResult) return [];
1428
+ const previousFiles = createFileSizeMap(previousResult);
1429
+ const previousModules = createModuleSizeMap(previousResult);
1430
+ const currentModules = createModuleSizeMap(result);
1431
+ const items = [];
1432
+ for (const pkg of result.packages) for (const file of pkg.files) {
1433
+ const currentBytes = getFileSize(file);
1434
+ const previousBytes = previousFiles.get(createFileKey(pkg.id, file.file)) ?? 0;
1435
+ const deltaBytes = currentBytes - previousBytes;
1436
+ if (deltaBytes <= 0) continue;
1437
+ const type = previousBytes > 0 ? "increased-file" : "new-file";
1438
+ const item = {
1439
+ key: `file:${pkg.id}:${file.file}`,
1440
+ type,
1441
+ label: file.file,
1442
+ category: classifyIncrementCategory(file.source ?? file.file),
1443
+ packageLabel: pkg.label,
1444
+ file: file.file,
1445
+ currentBytes,
1446
+ previousBytes,
1447
+ deltaBytes,
1448
+ advice: ""
1449
+ };
1450
+ items.push({
1451
+ ...item,
1452
+ advice: createIncrementAdvice(item)
1453
+ });
1454
+ }
1455
+ for (const [id, module] of currentModules) {
1456
+ const previousBytes = previousModules.get(id)?.bytes ?? 0;
1457
+ const deltaBytes = module.bytes - previousBytes;
1458
+ if (deltaBytes <= 0) continue;
1459
+ const type = previousBytes > 0 ? "increased-module" : "new-module";
1460
+ const item = {
1461
+ key: `module:${id}`,
1462
+ type,
1463
+ label: module.source,
1464
+ category: classifyIncrementCategory(module.source, module.sourceType),
1465
+ packageLabel: module.packageLabel,
1466
+ file: module.file,
1467
+ currentBytes: module.bytes,
1468
+ previousBytes,
1469
+ deltaBytes,
1470
+ advice: ""
1471
+ };
1472
+ items.push({
1473
+ ...item,
1474
+ advice: createIncrementAdvice(item)
1475
+ });
1740
1476
  }
1477
+ return items.sort((a, b) => b.deltaBytes - a.deltaBytes || a.category.localeCompare(b.category) || a.label.localeCompare(b.label));
1741
1478
  }
1742
- function registerAnalyzeCommand(cli) {
1743
- cli.command("analyze [root]", "analyze 两端包体与源码映射").option("--hmr-profile [file]", `[string | boolean] 分析 HMR JSONL profile,省略值时优先读取配置,否则回退到默认路径`).option("--json", `[boolean] 输出 JSON 结果`).option("--markdown", `[boolean] 输出 Markdown 报告`).option("--report <type>", `[string] 输出指定报告类型(pr)`).option("--budget-check", `[boolean] 检查 analyze 预算,超过预算时返回非 0 退出码`).option("--output <file>", `[string] 将分析结果写入指定文件(JSON 或 Markdown)`).option("-p, --platform <platform>", `[string] target platform (weapp | web)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).action(async (root, options) => {
1744
- filterDuplicateOptions(options);
1745
- const configFile = resolveConfigFile(options);
1746
- const outputJson = coerceBooleanOption(options.json);
1747
- const outputMarkdown = coerceBooleanOption(options.markdown);
1748
- const reportType = typeof options.report === "string" ? options.report.trim() : "";
1749
- const outputPrReport = reportType === "pr";
1750
- if (reportType && !outputPrReport) throw new Error(`不支持的 analyze report 类型:${reportType}`);
1751
- const budgetCheck = coerceBooleanOption(options.budgetCheck);
1752
- const targets = resolveRuntimeTargets(options);
1753
- const inlineConfig = createInlineConfig(targets.platform);
1754
- try {
1755
- const ctx = await createCompilerContext({
1756
- cwd: root,
1757
- mode: options.mode ?? "production",
1758
- configFile,
1759
- inlineConfig,
1760
- cliPlatform: targets.rawPlatform,
1761
- projectConfigPath: options.projectConfig
1762
- });
1763
- logRuntimeTarget(targets, {
1764
- silent: outputJson || outputMarkdown,
1765
- resolvedConfigPlatform: ctx.configService.platform
1766
- });
1767
- const outputOption = typeof options.output === "string" ? options.output.trim() : "";
1768
- if (options.hmrProfile !== void 0 && options.hmrProfile !== false) {
1769
- const profileOption = typeof options.hmrProfile === "string" && options.hmrProfile.trim() ? options.hmrProfile.trim() : ctx.configService.weappViteConfig.hmr?.profileJson;
1770
- const profilePath = resolveHmrProfileJsonPath({
1771
- cwd: ctx.configService.cwd,
1772
- option: profileOption,
1773
- fallbackToDefault: true
1774
- });
1775
- if (!profilePath) throw new Error("未找到可用的 HMR profile 文件路径");
1776
- const hmrProfileResult = await analyzeHmrProfile({ profilePath });
1777
- const writtenPath = await writeAnalyzeResult(hmrProfileResult, outputOption, ctx.configService);
1778
- if (outputJson) {
1779
- if (!writtenPath) process.stdout.write(`${JSON.stringify(hmrProfileResult, null, 2)}\n`);
1780
- } else printHmrProfileAnalysisSummary(hmrProfileResult, ctx.configService);
1781
- return;
1782
- }
1783
- if (targets.runWeb) {
1784
- const webResult = createWebAnalyzeResult(ctx.configService, { platform: "web" });
1785
- const writtenPath = await writeAnalyzeResult(webResult, outputOption, ctx.configService);
1786
- if (outputJson) {
1787
- if (!writtenPath) process.stdout.write(`${JSON.stringify(webResult, null, 2)}\n`);
1788
- } else printWebAnalysisSummary(webResult);
1789
- return;
1790
- }
1791
- if (!targets.runMini) {
1792
- logger_default.warn("当前命令不支持该平台,请通过 --platform weapp --platform web 指定目标。");
1793
- return;
1794
- }
1795
- const previousResult = await readLatestAnalyzeHistorySnapshot(ctx.configService);
1796
- const result = await analyzeSubpackages(ctx);
1797
- await writeAnalyzeHistorySnapshot(result, ctx.configService);
1798
- const writtenPath = await writeAnalyzeResult(result, outputOption, ctx.configService, outputPrReport ? "pr" : outputMarkdown ? "markdown" : "json", previousResult);
1799
- if (outputPrReport) {
1800
- if (!writtenPath) process.stdout.write(`${createAnalyzePrMarkdownReport(result, previousResult)}\n`);
1801
- } else if (outputMarkdown) {
1802
- if (!writtenPath) process.stdout.write(`${createAnalyzeMarkdownReport(result, previousResult)}\n`);
1803
- } else if (outputJson) {
1804
- if (!writtenPath) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1805
- }
1806
- if (budgetCheck ? printBudgetCheckSummary(result) : false) process.exitCode = 1;
1807
- if (budgetCheck) return;
1808
- if (!outputPrReport && !outputMarkdown && !outputJson) {
1809
- printAnalysisSummary(result);
1810
- await startAnalyzeDashboard(result, {
1811
- artifactRoot: ctx.configService.outDir,
1812
- cwd: ctx.configService.cwd,
1813
- packageManagerAgent: ctx.configService.packageManager.agent,
1814
- previousResult
1815
- });
1816
- }
1817
- } catch (error) {
1818
- logger_default.error(error);
1819
- process.exitCode = 1;
1820
- }
1479
+ function createAnalyzeIncrementCategorySummary(items) {
1480
+ const map = /* @__PURE__ */ new Map();
1481
+ for (const item of items) {
1482
+ const entry = map.get(item.category) ?? {
1483
+ category: item.category,
1484
+ count: 0,
1485
+ deltaBytes: 0
1486
+ };
1487
+ entry.count += 1;
1488
+ entry.deltaBytes += item.deltaBytes;
1489
+ map.set(item.category, entry);
1490
+ }
1491
+ return [...map.values()].sort((a, b) => b.deltaBytes - a.deltaBytes || b.count - a.count || a.category.localeCompare(b.category));
1492
+ }
1493
+ function createAnalyzePrMarkdownReport(result, previousResult) {
1494
+ const files = result.packages.flatMap((pkg) => pkg.files.map((file) => ({
1495
+ pkg,
1496
+ file
1497
+ })));
1498
+ const totalBytes = files.reduce((sum, item) => sum + getFileSize(item.file), 0);
1499
+ const compressedBytes = files.reduce((sum, item) => sum + getCompressedSize(item.file), 0);
1500
+ const previousTotalBytes = previousResult?.packages.flatMap((pkg) => pkg.files).reduce((sum, file) => sum + getFileSize(file), 0);
1501
+ const incrementItems = createAnalyzeIncrementAttribution(result, previousResult);
1502
+ const incrementSummary = createAnalyzeIncrementCategorySummary(incrementItems);
1503
+ const duplicateInsights = createDuplicateModuleInsights(result);
1504
+ const budgetItems = createAnalyzeBudgetCheck(result);
1505
+ const budgetIssues = budgetItems.filter((item) => item.status !== "ok");
1506
+ const actionItems = createActionItems({
1507
+ budgetItems,
1508
+ duplicateInsights
1509
+ }).slice(0, 3);
1510
+ const budgetRows = budgetIssues.slice(0, 5).map((item) => `| ${item.label} | ${formatAnalyzeBytes(item.currentBytes)} | ${formatAnalyzeBytes(item.limitBytes)} | ${formatBudgetStatus(item)} |`).join("\n");
1511
+ const incrementRows = incrementItems.slice(0, 8).map((item) => `| ${item.label} | ${item.category} | ${item.packageLabel} | ${formatAnalyzeBytes(item.deltaBytes)} | ${item.advice} |`).join("\n");
1512
+ const sourceRows = incrementSummary.slice(0, 6).map((item) => `| ${item.category} | ${item.count} | ${formatAnalyzeBytes(item.deltaBytes)} |`).join("\n");
1513
+ const duplicateRows = duplicateInsights.slice(0, 5).map((module) => `| ${module.source} | ${module.packageCount} | ${formatAnalyzeBytes(module.estimatedSavingBytes)} | ${module.advice} |`).join("\n");
1514
+ return [
1515
+ "## weapp-vite analyze PR 摘要",
1516
+ "",
1517
+ `- 总产物体积:${formatAnalyzeBytes(totalBytes)}(较上次 ${formatDelta(typeof previousTotalBytes === "number" ? totalBytes - previousTotalBytes : void 0)})`,
1518
+ `- 压缩后体积:${formatAnalyzeBytes(compressedBytes)}`,
1519
+ `- 预算告警:${budgetIssues.length}`,
1520
+ `- 增量归因:${incrementItems.length > 0 ? `${incrementItems.length} 项正向增长` : "无正向增长"}`,
1521
+ `- 跨包复用:${duplicateInsights.length}`,
1522
+ "",
1523
+ "### 建议动作",
1524
+ "",
1525
+ ...actionItems.map((item) => `- ${item}`),
1526
+ "",
1527
+ "### 预算状态",
1528
+ "",
1529
+ "| 对象 | 当前体积 | 预算 | 状态 |",
1530
+ "| --- | ---: | ---: | --- |",
1531
+ budgetRows || "| - | 0 B | 0 B | 正常 |",
1532
+ "",
1533
+ "### 增量来源",
1534
+ "",
1535
+ "| 来源 | 项数 | 增量 |",
1536
+ "| --- | ---: | ---: |",
1537
+ sourceRows || "| - | 0 | 0 B |",
1538
+ "",
1539
+ "### Top 增量",
1540
+ "",
1541
+ "| 文件/模块 | 来源 | 包 | 增量 | 建议 |",
1542
+ "| --- | --- | --- | ---: | --- |",
1543
+ incrementRows || "| - | - | - | 0 B | - |",
1544
+ "",
1545
+ "### 重复模块",
1546
+ "",
1547
+ "| 模块 | 包数量 | 估算可节省 | 建议 |",
1548
+ "| --- | ---: | ---: | --- |",
1549
+ duplicateRows || "| - | 0 | 0 B | - |",
1550
+ ""
1551
+ ].join("\n");
1552
+ }
1553
+ function createAnalyzeMarkdownReport(result, previousResult) {
1554
+ const files = result.packages.flatMap((pkg) => pkg.files.map((file) => ({
1555
+ pkg,
1556
+ file
1557
+ })));
1558
+ const totalBytes = files.reduce((sum, item) => sum + getFileSize(item.file), 0);
1559
+ const compressedBytes = files.reduce((sum, item) => sum + getCompressedSize(item.file), 0);
1560
+ const duplicateInsights = createDuplicateModuleInsights(result);
1561
+ const incrementItems = createAnalyzeIncrementAttribution(result, previousResult);
1562
+ const incrementSummary = createAnalyzeIncrementCategorySummary(incrementItems);
1563
+ const budgetItems = createAnalyzeBudgetCheck(result);
1564
+ const previousTotalBytes = previousResult?.packages.flatMap((pkg) => pkg.files).reduce((sum, file) => sum + getFileSize(file), 0);
1565
+ const previousPackageSizes = createPackageSizeMap(previousResult);
1566
+ const budgets = result.metadata?.budgets;
1567
+ const budgetIssues = budgetItems.filter((item) => item.status !== "ok");
1568
+ const actionItems = createActionItems({
1569
+ budgetItems,
1570
+ duplicateInsights
1821
1571
  });
1572
+ const packageRows = result.packages.map((pkg) => {
1573
+ const size = pkg.files.reduce((sum, file) => sum + getFileSize(file), 0);
1574
+ const compressed = pkg.files.reduce((sum, file) => sum + getCompressedSize(file), 0);
1575
+ const previousSize = previousPackageSizes.get(pkg.id);
1576
+ const budgetStatus = budgetItems.find((item) => item.id === pkg.id);
1577
+ return `| ${pkg.label} | ${pkg.type} | ${formatAnalyzeBytes(size)} | ${formatAnalyzeBytes(compressed)} | ${formatDelta(typeof previousSize === "number" ? size - previousSize : void 0)} | ${budgetStatus ? formatBudgetStatus(budgetStatus) : "正常"} |`;
1578
+ }).join("\n");
1579
+ const topFileRows = files.sort((a, b) => getFileSize(b.file) - getFileSize(a.file) || a.file.file.localeCompare(b.file.file)).slice(0, 10).map((item) => `| ${item.file.file} | ${item.pkg.label} | ${item.file.type} | ${formatAnalyzeBytes(getFileSize(item.file))} | ${formatAnalyzeBytes(getCompressedSize(item.file))} |`).join("\n");
1580
+ const duplicateRows = duplicateInsights.slice(0, 10).map((module) => `| ${module.source} | ${module.sourceType} | ${module.packageCount} | ${formatAnalyzeBytes(module.estimatedSavingBytes)} | ${module.advice} |`).join("\n");
1581
+ const budgetRows = budgetIssues.map((item) => `| ${item.label} | ${item.scope} | ${formatAnalyzeBytes(item.currentBytes)} | ${formatAnalyzeBytes(item.limitBytes)} | ${formatBudgetStatus(item)} |`).join("\n");
1582
+ const incrementRows = incrementItems.slice(0, 10).map((item) => `| ${item.label} | ${item.category} | ${item.packageLabel} | ${formatAnalyzeBytes(item.deltaBytes)} | ${item.advice} |`).join("\n");
1583
+ const incrementSummaryRows = incrementSummary.slice(0, 8).map((item) => `| ${item.category} | ${item.count} | ${formatAnalyzeBytes(item.deltaBytes)} |`).join("\n");
1584
+ return [
1585
+ "# weapp-vite analyze 报告",
1586
+ "",
1587
+ `生成时间:${result.metadata?.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString()}`,
1588
+ "",
1589
+ "## 本次变化摘要",
1590
+ "",
1591
+ `- 总产物体积:${formatAnalyzeBytes(totalBytes)}`,
1592
+ `- 压缩后体积:${formatAnalyzeBytes(compressedBytes)}`,
1593
+ `- 较上次:${formatDelta(typeof previousTotalBytes === "number" ? totalBytes - previousTotalBytes : void 0)}`,
1594
+ `- 包体数量:${result.packages.length}`,
1595
+ `- 源码模块:${result.modules.length}`,
1596
+ `- 跨包复用:${duplicateInsights.length}`,
1597
+ `- 预算来源:${budgets?.source === "config" ? "配置" : "默认"}`,
1598
+ "",
1599
+ "## 预算告警",
1600
+ "",
1601
+ "| 对象 | 范围 | 当前体积 | 预算 | 状态 |",
1602
+ "| --- | --- | ---: | ---: | --- |",
1603
+ budgetRows || "| - | - | 0 B | 0 B | 正常 |",
1604
+ "",
1605
+ "## 建议动作",
1606
+ "",
1607
+ ...actionItems.map((item) => `- ${item}`),
1608
+ "",
1609
+ "## 增量归因",
1610
+ "",
1611
+ "| 来源 | 项数 | 增量 |",
1612
+ "| --- | ---: | ---: |",
1613
+ incrementSummaryRows || "| - | 0 | 0 B |",
1614
+ "",
1615
+ "| 文件/模块 | 来源 | 包 | 增量 | 建议 |",
1616
+ "| --- | --- | --- | ---: | --- |",
1617
+ incrementRows || "| - | - | - | 0 B | - |",
1618
+ "",
1619
+ "## 包体预算",
1620
+ "",
1621
+ "| 包 | 类型 | 体积 | 压缩后 | 较上次 | 预算 |",
1622
+ "| --- | --- | ---: | ---: | ---: | --- |",
1623
+ packageRows || "| - | - | 0 B | 0 B | 无变化 | 正常 |",
1624
+ "",
1625
+ "## Top 文件",
1626
+ "",
1627
+ "| 文件 | 包 | 类型 | 体积 | 压缩后 |",
1628
+ "| --- | --- | --- | ---: | ---: |",
1629
+ topFileRows || "| - | - | - | 0 B | 0 B |",
1630
+ "",
1631
+ "## 重复模块",
1632
+ "",
1633
+ "| 模块 | 来源 | 包数量 | 估算可节省 | 建议 |",
1634
+ "| --- | --- | ---: | ---: | --- |",
1635
+ duplicateRows || "| - | - | 0 | 0 B | - |",
1636
+ ""
1637
+ ].join("\n");
1822
1638
  }
1823
1639
  //#endregion
1824
- //#region src/cli/formatDuration.ts
1825
- /**
1826
- * 将毫秒耗时格式化为适合 CLI 展示的文本。
1827
- */
1828
- function formatDuration(durationMs) {
1829
- return `${durationMs}ms`;
1640
+ //#region src/cli/analyze/dashboard.ts
1641
+ const ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_ANALYZE_RESULT__";
1642
+ const PREVIOUS_ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_PREVIOUS_ANALYZE_RESULT__";
1643
+ const DASHBOARD_EVENTS_GLOBAL_KEY = "__WEAPP_VITE_DASHBOARD_EVENTS__";
1644
+ const ANALYZE_DASHBOARD_PACKAGE_NAME = "@weapp-vite/dashboard";
1645
+ const ANALYZE_SSE_PATH = "/__weapp_vite_analyze";
1646
+ const FILE_CONTENT_PATH = "/__weapp_vite_file_content";
1647
+ const DASHBOARD_EVENT_NAME = "weapp-dashboard:event";
1648
+ const MAX_FILE_CONTENT_BYTES = 2 * 1024 * 1024;
1649
+ const require = createRequire(import.meta.url);
1650
+ function createInstallCommand(agent) {
1651
+ const resolved = resolveCommand(agent ?? "npm", "install", [ANALYZE_DASHBOARD_PACKAGE_NAME]);
1652
+ if (!resolved) return `npm install ${ANALYZE_DASHBOARD_PACKAGE_NAME}`;
1653
+ return `${resolved.command} ${resolved.args.join(" ")}`;
1830
1654
  }
1831
- //#endregion
1832
- //#region src/cli/logBuildAppFinish.ts
1833
- let logBuildAppFinishOnlyShowOnce = false;
1834
- function collectServerUrls(webServer) {
1835
- const urls = webServer?.resolvedUrls;
1836
- if (!urls) return [];
1837
- return [...urls.local ?? [], ...urls.network ?? []];
1655
+ function formatEventTimestamp(date = /* @__PURE__ */ new Date()) {
1656
+ return date.toLocaleTimeString("zh-CN", { hour12: false });
1838
1657
  }
1839
- function logBuildAppFinish(configService, webServer, options = {}) {
1840
- if (logBuildAppFinishOnlyShowOnce) return;
1841
- const { skipMini = false, skipWeb = false, uiUrls = [] } = options;
1842
- const webUrls = skipWeb ? [] : collectServerUrls(webServer);
1843
- if (skipMini) {
1844
- logger_default.success("开发服务已就绪:");
1845
- if (webUrls.length > 0) logger_default.info(`Web:${colors.cyan(webUrls[0])}`);
1846
- else logger_default.info("Web:已启动");
1847
- logBuildAppFinishOnlyShowOnce = true;
1658
+ function createDashboardRuntimeEvent(input) {
1659
+ return {
1660
+ id: `dashboard:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,
1661
+ kind: input.kind,
1662
+ level: input.level,
1663
+ title: input.title,
1664
+ detail: input.detail,
1665
+ timestamp: formatEventTimestamp(),
1666
+ source: input.source ?? "weapp-vite",
1667
+ durationMs: input.durationMs,
1668
+ tags: input.tags,
1669
+ profile: input.profile
1670
+ };
1671
+ }
1672
+ function readDashboardManifest(packageJsonPath) {
1673
+ try {
1674
+ return parseCommentJson(fs$1.readFileSync(packageJsonPath, "utf8"));
1675
+ } catch {
1848
1676
  return;
1849
1677
  }
1850
- const { command, args } = resolveCommand(configService.packageManager.agent, "run", ["open"]) ?? {
1851
- command: "npm",
1852
- args: ["run", "open"]
1678
+ }
1679
+ function resolveDashboardDistRoot(packageRoot, manifest) {
1680
+ const distDir = manifest?.weappViteDashboard?.distDir ?? "dist";
1681
+ const distRoot = path.resolve(packageRoot, distDir);
1682
+ if (!fs$1.existsSync(distRoot)) return;
1683
+ return { root: distRoot };
1684
+ }
1685
+ function resolveDashboardDevRoot(packageRoot, manifest) {
1686
+ const devRoot = manifest?.weappViteDashboard?.devRoot;
1687
+ const devConfigFile = manifest?.weappViteDashboard?.devConfigFile;
1688
+ if (!devRoot || !devConfigFile) return;
1689
+ const root = path.resolve(packageRoot, devRoot);
1690
+ const configFile = path.resolve(root, devConfigFile);
1691
+ if (!fs$1.existsSync(root) || !fs$1.existsSync(configFile)) return;
1692
+ return {
1693
+ root,
1694
+ configFile
1853
1695
  };
1854
- const devCommand = `${command} ${args.join(" ")}`;
1855
- logger_default.success("开发服务已就绪:");
1856
- logger_default.info(`小程序:执行 ${colors.bold(colors.green(devCommand))},或手动导入 ${colors.green(getProjectConfigFileName(configService.platform))}`);
1857
- if (uiUrls.length > 0) logger_default.info(`UI:${colors.cyan(uiUrls[0])}`);
1858
- else if (!skipMini) logger_default.info("UI:未启用");
1859
- if (webUrls.length > 0) logger_default.info(`Web:${colors.cyan(webUrls[0])}`);
1860
- const projectConfigFileName = getProjectConfigFileName(configService.platform);
1861
- if (!uiUrls.length && !webUrls.length) logger_default.info(`提示:手动打开对应平台开发者工具,导入根目录(${colors.green(projectConfigFileName)} 文件所在目录)`);
1862
- logBuildAppFinishOnlyShowOnce = true;
1863
1696
  }
1864
- const WINDOWS_SEPARATOR_RE = /\\/g;
1865
- function normalizeFileName(fileName) {
1866
- return fileName.replace(WINDOWS_SEPARATOR_RE, "/");
1697
+ function resolveDashboardRoot(options) {
1698
+ const resolvePaths = options?.cwd && options.cwd !== process.cwd() ? [options.cwd, process.cwd()] : options?.cwd ? [options.cwd] : void 0;
1699
+ let dashboardPackageRoot;
1700
+ let dashboardManifest;
1701
+ try {
1702
+ const dashboardPackageJsonPath = require.resolve(`${ANALYZE_DASHBOARD_PACKAGE_NAME}/package.json`, { paths: resolvePaths });
1703
+ dashboardPackageRoot = path.dirname(dashboardPackageJsonPath);
1704
+ dashboardManifest = readDashboardManifest(dashboardPackageJsonPath);
1705
+ } catch {
1706
+ dashboardPackageRoot = void 0;
1707
+ dashboardManifest = void 0;
1708
+ }
1709
+ if (dashboardPackageRoot) {
1710
+ const devResolved = resolveDashboardDevRoot(dashboardPackageRoot, dashboardManifest);
1711
+ if (devResolved) return devResolved;
1712
+ const distResolved = resolveDashboardDistRoot(dashboardPackageRoot, dashboardManifest);
1713
+ if (distResolved) return distResolved;
1714
+ }
1715
+ logger_default.warn(`[weapp-vite ui] 未安装可选仪表盘包 ${colors.bold(colors.green(ANALYZE_DASHBOARD_PACKAGE_NAME))},已自动降级关闭 dashboard 能力。`);
1716
+ logger_default.info(`如需启用,请执行 ${colors.bold(colors.green(createInstallCommand(options?.packageManagerAgent)))}`);
1867
1717
  }
1868
- function getOutputItemBytes(item) {
1869
- if (item.type === "chunk") return typeof item.code === "string" ? Buffer.byteLength(item.code, "utf8") : 0;
1870
- if (typeof item.source === "string") return Buffer.byteLength(item.source, "utf8");
1871
- if (item.source instanceof Uint8Array) return item.source.byteLength;
1872
- return 0;
1718
+ function normalizeDashboardRelativePath(value) {
1719
+ return value.replaceAll("\\", "/");
1873
1720
  }
1874
- function resolveSubPackageRoot(fileName, roots) {
1875
- const normalized = normalizeFileName(fileName);
1876
- return roots.find((root) => normalized === root || normalized.startsWith(`${root}/`));
1721
+ function stripDashboardFileQuery(value) {
1722
+ const queryIndex = value.indexOf("?");
1723
+ return queryIndex === -1 ? value : value.slice(0, queryIndex);
1877
1724
  }
1878
- function collectPackageSizeReports(output, subPackageMap) {
1879
- const outputs = Array.isArray(output) ? output : [output];
1880
- const roots = [...subPackageMap?.keys() ?? []].filter(Boolean).sort((a, b) => b.length - a.length || a.localeCompare(b));
1881
- const packageBytes = new Map([["__main__", 0]]);
1882
- for (const root of roots) packageBytes.set(root, 0);
1883
- for (const current of outputs) for (const item of current.output ?? []) {
1884
- const root = resolveSubPackageRoot(item.fileName, roots) ?? "__main__";
1885
- packageBytes.set(root, (packageBytes.get(root) ?? 0) + getOutputItemBytes(item));
1886
- }
1887
- const reports = [{
1888
- root: "__main__",
1889
- label: "主包",
1890
- bytes: packageBytes.get("__main__") ?? 0
1891
- }];
1892
- for (const root of roots) {
1893
- const meta = subPackageMap?.get(root);
1894
- const isIndependent = Boolean(meta?.subPackage.independent);
1895
- reports.push({
1896
- root,
1897
- label: `${isIndependent ? "独立分包" : "分包"} ${root}`,
1898
- bytes: packageBytes.get(root) ?? 0
1899
- });
1900
- }
1901
- return reports;
1725
+ function addDashboardAllowedPath(paths, value) {
1726
+ if (!value || value.includes("\0")) return;
1727
+ const normalizedPath = normalizeDashboardRelativePath(stripDashboardFileQuery(value));
1728
+ if (!normalizedPath || path.isAbsolute(normalizedPath)) return;
1729
+ paths.add(normalizedPath);
1902
1730
  }
1903
- function logBuildPackageSizeReport(options) {
1904
- const warningBytes = Number(options.warningBytes ?? 2097152);
1905
- const reports = collectPackageSizeReports(options.output, options.subPackageMap);
1906
- logger_default.success("主包/分包体积报告:");
1907
- for (const report of reports) logger_default.info(`${report.label}:${formatBytes(report.bytes)}`);
1908
- if (!(Number.isFinite(warningBytes) && warningBytes > 0)) return;
1909
- for (const report of reports) {
1910
- if (report.bytes <= warningBytes) continue;
1911
- logger_default.warn(`[包体积] ${colors.yellow(report.label)} 体积 ${colors.yellow(formatBytes(report.bytes))},已超过阈值 ${colors.yellow(formatBytes(warningBytes))}。`);
1731
+ function createDashboardContentAllowlist(result) {
1732
+ const artifactPaths = /* @__PURE__ */ new Set();
1733
+ const sourcePaths = /* @__PURE__ */ new Set();
1734
+ for (const packageReport of result.packages) for (const file of packageReport.files) {
1735
+ addDashboardAllowedPath(artifactPaths, file.file);
1736
+ addDashboardAllowedPath(sourcePaths, file.source);
1737
+ for (const module of file.modules ?? []) addDashboardAllowedPath(sourcePaths, module.source);
1912
1738
  }
1739
+ return {
1740
+ artifactPaths,
1741
+ sourcePaths
1742
+ };
1913
1743
  }
1914
- //#endregion
1915
- //#region src/cli/openIde/execute.ts
1916
- function readArgOption(argv, ...names) {
1917
- for (let index = 0; index < argv.length; index += 1) {
1918
- const current = argv[index];
1919
- if (!names.includes(current)) continue;
1920
- const next = argv[index + 1];
1921
- if (typeof next === "string" && !next.startsWith("-")) return next;
1922
- }
1744
+ function resolveDashboardContentPath(root, requestPath, options) {
1745
+ if (!root || !requestPath || requestPath.includes("\0")) return;
1746
+ const normalizedRequestPath = normalizeDashboardRelativePath(stripDashboardFileQuery(requestPath));
1747
+ if (path.isAbsolute(normalizedRequestPath)) return;
1748
+ if (!options.allowedPaths.has(normalizedRequestPath)) return;
1749
+ const resolvedRoot = path.resolve(root);
1750
+ const absolutePath = path.resolve(resolvedRoot, normalizedRequestPath);
1751
+ const relativePath = path.relative(resolvedRoot, absolutePath);
1752
+ if (!relativePath) return;
1753
+ if (!options.allowParent && (relativePath.startsWith("..") || path.isAbsolute(relativePath))) return;
1754
+ return {
1755
+ absolutePath,
1756
+ relativePath: options.allowParent ? normalizedRequestPath : normalizeDashboardRelativePath(relativePath)
1757
+ };
1923
1758
  }
1924
- async function tryExecuteWechatIdeCliCommandByAutomator(argv, projectPath) {
1925
- if (!projectPath) return false;
1926
- const command = argv[0];
1927
- if (!command) return false;
1928
- if (command === "compile") {
1929
- await compileWechatIdeByAutomator({ projectPath });
1930
- return true;
1931
- }
1932
- if (command === "cache") {
1933
- const cleanType = readArgOption(argv, "--clean", "-c");
1934
- if (cleanType !== "compile" && cleanType !== "all") return false;
1935
- await clearWechatIdeCacheByAutomator({
1936
- clean: cleanType,
1937
- projectPath
1938
- });
1939
- return true;
1940
- }
1941
- return false;
1759
+ function resolveDashboardFileLanguage(filePath) {
1760
+ const extension = path.extname(filePath).toLowerCase();
1761
+ if (extension === ".js" || extension === ".mjs" || extension === ".cjs" || extension === ".wxs" || extension === ".sjs") return "javascript";
1762
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") return "typescript";
1763
+ if (extension === ".json" || extension === ".map") return "json";
1764
+ if (extension === ".css" || extension === ".wxss" || extension === ".scss" || extension === ".sass" || extension === ".less") return "css";
1765
+ if (extension === ".vue" || extension === ".wxml" || extension === ".html") return "html";
1766
+ return "plaintext";
1942
1767
  }
1943
- async function tryExecuteWechatIdeCliCommandByHttp(argv, projectPath) {
1944
- const command = argv[0];
1945
- if (!command) return false;
1946
- if (command === "compile") {
1947
- if (!projectPath) return false;
1948
- await openWechatIdeProjectByHttp(projectPath);
1949
- return true;
1950
- }
1951
- if (command === "reset-fileutils") {
1952
- if (!projectPath) return false;
1953
- await resetWechatIdeFileUtilsByHttp(projectPath);
1954
- return true;
1955
- }
1956
- if (command === "engine" && argv[1] === "build") {
1957
- const engineProjectPath = argv[2] || projectPath;
1958
- if (!engineProjectPath) return false;
1959
- await runWechatIdeEngineBuild(engineProjectPath, { logPath: readArgOption(argv, "--logPath", "-l") });
1960
- return true;
1961
- }
1962
- return false;
1768
+ function sendDashboardJson(res, statusCode, payload) {
1769
+ res.statusCode = statusCode;
1770
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
1771
+ res.end(JSON.stringify(payload));
1963
1772
  }
1964
- async function tryExecuteWechatIdeCliCommandByHelper(argv) {
1965
- const command = argv[0];
1966
- if (!command) return false;
1967
- if (command === "close") {
1968
- await closeWechatIdeProject();
1969
- return true;
1970
- }
1971
- if (command === "quit") {
1972
- await quitWechatIde();
1973
- return true;
1773
+ async function sendDashboardFileContent(res, roots, allowlist, kind, requestPath) {
1774
+ const resolved = resolveDashboardContentPath(kind === "artifact" ? roots.artifactRoot : kind === "source" ? roots.sourceRoot : void 0, requestPath, {
1775
+ allowParent: kind === "source",
1776
+ allowedPaths: kind === "artifact" ? allowlist.artifactPaths : allowlist.sourcePaths
1777
+ });
1778
+ if (!resolved || kind !== "source" && kind !== "artifact") {
1779
+ sendDashboardJson(res, 400, {
1780
+ error: "invalid_request",
1781
+ message: "必须传入合法的 kind 和相对路径。"
1782
+ });
1783
+ return;
1974
1784
  }
1975
- if (command === "cache") {
1976
- const cleanType = readArgOption(argv, "--clean", "-c");
1977
- if (!cleanType) return false;
1978
- await clearWechatIdeCache({ clean: cleanType });
1979
- return true;
1785
+ try {
1786
+ const stat = await fs$1.promises.stat(resolved.absolutePath);
1787
+ if (!stat.isFile()) {
1788
+ sendDashboardJson(res, 400, {
1789
+ error: "not_file",
1790
+ message: "目标路径不是文件。"
1791
+ });
1792
+ return;
1793
+ }
1794
+ if (stat.size > MAX_FILE_CONTENT_BYTES) {
1795
+ sendDashboardJson(res, 413, {
1796
+ error: "file_too_large",
1797
+ message: `文件超过 ${MAX_FILE_CONTENT_BYTES} 字节,已拒绝读取。`
1798
+ });
1799
+ return;
1800
+ }
1801
+ sendDashboardJson(res, 200, {
1802
+ kind,
1803
+ path: resolved.relativePath,
1804
+ language: resolveDashboardFileLanguage(resolved.relativePath),
1805
+ size: stat.size,
1806
+ content: await fs$1.promises.readFile(resolved.absolutePath, "utf8")
1807
+ });
1808
+ } catch (error) {
1809
+ const code = typeof error === "object" && error && "code" in error ? String(error.code) : "";
1810
+ sendDashboardJson(res, code === "ENOENT" ? 404 : 500, {
1811
+ error: code === "ENOENT" ? "not_found" : "read_failed",
1812
+ message: code === "ENOENT" ? "文件不存在。" : "读取文件失败。"
1813
+ });
1980
1814
  }
1981
- return false;
1982
1815
  }
1983
- /**
1984
- * @description 统一执行 weapp-ide-cli 命令,并在登录失效时复用同一套重试交互。
1985
- */
1986
- async function executeWechatIdeCliCommand(argv, options = {}) {
1987
- const { automatorMode = "prefer", cancelLevel = "warn", httpMode = "prefer", onNonLoginError, onRetry, projectPath } = options;
1988
- await runWithSuspendedSharedInput(async () => {
1989
- if (httpMode !== "skip") try {
1990
- if (await tryExecuteWechatIdeCliCommandByHttp(argv, projectPath)) return;
1991
- } catch (error) {
1992
- if (httpMode === "require") throw error;
1993
- }
1994
- try {
1995
- if (await tryExecuteWechatIdeCliCommandByAutomator(argv, projectPath)) return;
1996
- } catch (error) {
1997
- if (automatorMode === "require") throw error;
1816
+ function createAnalyzeHtmlPlugin(state, runtimeEvents, contentRoots, contentAllowlist, onServerInstance, onBroadcastReady) {
1817
+ const sseClients = /* @__PURE__ */ new Set();
1818
+ const hotBridgeScript = `
1819
+ const applyAnalyzePayload = (payload) => {
1820
+ const current = payload?.current ?? payload
1821
+ const previous = payload?.previous ?? window.${PREVIOUS_ANALYZE_GLOBAL_KEY} ?? null
1822
+ window.${ANALYZE_GLOBAL_KEY} = current
1823
+ window.${PREVIOUS_ANALYZE_GLOBAL_KEY} = previous
1824
+ window.dispatchEvent(new CustomEvent('weapp-analyze:update', { detail: { current, previous } }))
1825
+ }
1826
+ const applyDashboardEvents = (payload) => {
1827
+ const events = Array.isArray(payload) ? payload : [payload]
1828
+ const nextEvents = events.filter(Boolean)
1829
+ if (nextEvents.length === 0) {
1830
+ return
1831
+ }
1832
+ window.${DASHBOARD_EVENTS_GLOBAL_KEY} = [
1833
+ ...(window.${DASHBOARD_EVENTS_GLOBAL_KEY} ?? []),
1834
+ ...nextEvents,
1835
+ ]
1836
+ window.dispatchEvent(new CustomEvent('${DASHBOARD_EVENT_NAME}', { detail: nextEvents }))
1837
+ }
1838
+ const source = new EventSource('${ANALYZE_SSE_PATH}')
1839
+ source.onmessage = (event) => {
1840
+ try {
1841
+ applyAnalyzePayload(JSON.parse(event.data))
1842
+ }
1843
+ catch {}
1844
+ }
1845
+ if (import.meta.hot) {
1846
+ import.meta.hot.on('weapp-analyze:update', (payload) => {
1847
+ applyAnalyzePayload(payload)
1848
+ })
1849
+ import.meta.hot.on('${DASHBOARD_EVENT_NAME}', (payload) => {
1850
+ applyDashboardEvents(payload)
1851
+ })
1852
+ }
1853
+ `.trim();
1854
+ const broadcast = (payload) => {
1855
+ const serialized = `data: ${JSON.stringify(payload)}\n\n`;
1856
+ for (const client of sseClients) client.write(serialized);
1857
+ };
1858
+ onBroadcastReady(broadcast);
1859
+ return {
1860
+ name: "weapp-vite-analyze-html",
1861
+ transformIndexHtml(html) {
1862
+ return {
1863
+ html,
1864
+ tags: [
1865
+ {
1866
+ tag: "script",
1867
+ children: `window.${ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.current)}`,
1868
+ injectTo: "head-prepend"
1869
+ },
1870
+ {
1871
+ tag: "script",
1872
+ children: `window.${PREVIOUS_ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.previous)}`,
1873
+ injectTo: "head-prepend"
1874
+ },
1875
+ {
1876
+ tag: "script",
1877
+ children: `window.${DASHBOARD_EVENTS_GLOBAL_KEY} = ${JSON.stringify(runtimeEvents.current)}`,
1878
+ injectTo: "head-prepend"
1879
+ },
1880
+ {
1881
+ tag: "script",
1882
+ attrs: {
1883
+ type: "module",
1884
+ src: "/@vite/client"
1885
+ },
1886
+ injectTo: "head"
1887
+ },
1888
+ {
1889
+ tag: "script",
1890
+ attrs: { type: "module" },
1891
+ children: hotBridgeScript,
1892
+ injectTo: "body"
1893
+ }
1894
+ ]
1895
+ };
1896
+ },
1897
+ configureServer(server) {
1898
+ onServerInstance(server);
1899
+ server.middlewares.use((req, res, next) => {
1900
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
1901
+ if (url.pathname === FILE_CONTENT_PATH) {
1902
+ sendDashboardFileContent(res, contentRoots, contentAllowlist.current, url.searchParams.get("kind"), url.searchParams.get("path"));
1903
+ return;
1904
+ }
1905
+ if (url.pathname !== ANALYZE_SSE_PATH) {
1906
+ next();
1907
+ return;
1908
+ }
1909
+ res.statusCode = 200;
1910
+ res.setHeader("Content-Type", "text/event-stream");
1911
+ res.setHeader("Cache-Control", "no-cache, no-transform");
1912
+ res.setHeader("Connection", "keep-alive");
1913
+ res.write(`data: ${JSON.stringify(state)}\n\n`);
1914
+ sseClients.add(res);
1915
+ req.on("close", () => {
1916
+ sseClients.delete(res);
1917
+ });
1918
+ });
1998
1919
  }
1920
+ };
1921
+ }
1922
+ async function waitForServerExit(server) {
1923
+ let resolved = false;
1924
+ const cleanup = async () => {
1925
+ if (resolved) return;
1926
+ resolved = true;
1999
1927
  try {
2000
- if (await tryExecuteWechatIdeCliCommandByHelper(argv)) return;
1928
+ await server.close();
2001
1929
  } catch (error) {
2002
- if (onNonLoginError) {
2003
- onNonLoginError(error);
2004
- return;
2005
- }
2006
- throw error;
1930
+ logger_default.error(error);
2007
1931
  }
2008
- await runRetryableCommand({
2009
- createCancelError: () => /* @__PURE__ */ new Error("cancelled"),
2010
- execute: async () => {
2011
- try {
2012
- await parse(argv);
2013
- return null;
2014
- } catch (error) {
2015
- if (!isWechatIdeLoginRequiredError(error)) {
2016
- if (onNonLoginError) {
2017
- onNonLoginError(error);
2018
- return null;
2019
- }
2020
- throw error;
2021
- }
2022
- return error;
2023
- }
2024
- },
2025
- isRetryableResult: (result) => result !== null,
2026
- onCancel: () => {},
2027
- onRetry: () => {
2028
- onRetry?.();
2029
- },
2030
- promptRetry: async (error) => await promptWechatIdeLoginRetry({
2031
- cancelLevel,
2032
- error,
2033
- logger: logger_default
2034
- }),
2035
- shouldRetry: (action) => action === "retry"
1932
+ };
1933
+ const signals = ["SIGINT", "SIGTERM"];
1934
+ await new Promise((resolvePromise) => {
1935
+ const resolveOnce = async () => {
1936
+ await cleanup();
1937
+ signals.forEach((signal) => {
1938
+ process.removeListener(signal, resolveOnce);
1939
+ });
1940
+ resolvePromise();
1941
+ };
1942
+ signals.forEach((signal) => {
1943
+ process.once(signal, resolveOnce);
2036
1944
  });
1945
+ server.httpServer?.once("close", resolveOnce);
2037
1946
  });
2038
1947
  }
2039
- //#endregion
2040
- //#region src/cli/openIde/close.ts
2041
- const execFileAsync = promisify(execFile);
2042
- async function closeIdeByAppleScript() {
2043
- if (process.platform !== "darwin") return false;
2044
- const appName = process.env.WEAPP_DEVTOOLS_APP_NAME || "wechatwebdevtools";
2045
- try {
2046
- await execFileAsync("osascript", ["-e", `tell application "${appName}" to quit`]);
2047
- return true;
2048
- } catch {
2049
- return false;
2050
- }
2051
- }
2052
- async function closeIdeByProcessKill(cliPath) {
2053
- if (!cliPath) return false;
2054
- const appContentsRoot = cliPath.includes(".app/") ? cliPath.slice(0, cliPath.indexOf(".app/") + 4) : path.dirname(path.dirname(cliPath));
2055
- try {
2056
- await execFileAsync("pkill", ["-f", appContentsRoot]);
2057
- return true;
2058
- } catch {
2059
- return false;
1948
+ async function startAnalyzeDashboard(result, options) {
1949
+ const resolved = resolveDashboardRoot(options);
1950
+ if (!resolved) return;
1951
+ const { root, configFile } = resolved;
1952
+ const state = {
1953
+ current: result,
1954
+ previous: options?.previousResult ?? null
1955
+ };
1956
+ const contentAllowlist = { current: createDashboardContentAllowlist(result) };
1957
+ const runtimeEvents = { current: [createDashboardRuntimeEvent({
1958
+ kind: "command",
1959
+ level: "success",
1960
+ title: options?.watch ? "dashboard watch session started" : "dashboard static session started",
1961
+ detail: options?.watch ? "weapp-vite UI 已进入实时分析模式,后续 analyze 结果会继续推送到 dashboard。" : "weapp-vite UI 已进入静态分析模式,当前页面展示的是一次性分析结果。",
1962
+ tags: options?.watch ? ["watch", "analyze"] : ["static", "analyze"]
1963
+ }), ...(options?.initialEvents ?? []).map((event) => createDashboardRuntimeEvent(event))] };
1964
+ let serverRef;
1965
+ let broadcastAnalyzeResult;
1966
+ const plugins = [createAnalyzeHtmlPlugin(state, runtimeEvents, {
1967
+ artifactRoot: options?.artifactRoot ?? (options?.cwd ? path.resolve(options.cwd, "dist") : void 0),
1968
+ sourceRoot: options?.cwd
1969
+ }, contentAllowlist, (server) => {
1970
+ serverRef = server;
1971
+ }, (broadcast) => {
1972
+ broadcastAnalyzeResult = broadcast;
1973
+ })];
1974
+ const serverOptions = {
1975
+ root,
1976
+ configFile: configFile ?? false,
1977
+ clearScreen: false,
1978
+ appType: "spa",
1979
+ publicDir: false,
1980
+ plugins,
1981
+ server: {
1982
+ host: "127.0.0.1",
1983
+ port: 0,
1984
+ watch: { ignored: ["**/*"] }
1985
+ },
1986
+ logLevel: "error"
1987
+ };
1988
+ const server = await createServer(serverOptions);
1989
+ const requestedPort = typeof serverOptions.server?.port === "number" ? serverOptions.server.port : void 0;
1990
+ await server.listen(requestedPort);
1991
+ serverRef ??= server;
1992
+ server.printUrls();
1993
+ const urls = (() => {
1994
+ const resolved = server.resolvedUrls;
1995
+ if (!resolved) return [];
1996
+ return [...resolved.local ?? [], ...resolved.network ?? []];
1997
+ })();
1998
+ const waitPromise = waitForServerExit(server);
1999
+ if (serverRef?.ws) {
2000
+ serverRef.ws.send({
2001
+ type: "custom",
2002
+ event: "weapp-analyze:update",
2003
+ data: state
2004
+ });
2005
+ serverRef.ws.send({
2006
+ type: "custom",
2007
+ event: DASHBOARD_EVENT_NAME,
2008
+ data: runtimeEvents.current
2009
+ });
2060
2010
  }
2061
- }
2062
- /**
2063
- * @description 关闭微信开发者工具,并在 CLI 不可用时回退到系统级关闭。
2064
- */
2065
- async function closeIde$1() {
2066
- const config = await getConfig();
2067
- const cliPath = config.cliPath?.trim() ? config.cliPath : null;
2068
- try {
2069
- await closeWechatIdeProject();
2070
- return true;
2071
- } catch (error) {
2072
- if (isWechatIdeLoginRequiredError(error)) try {
2073
- await executeWechatIdeCliCommand(["close"], {
2074
- cancelLevel: "warn",
2075
- onNonLoginError: (retryError) => logger_default.error(retryError),
2076
- onRetry: () => logger_default.info("正在重试连接微信开发者工具...")
2011
+ broadcastAnalyzeResult?.(state);
2012
+ const emitRuntimeEvents = (events) => {
2013
+ if (events.length === 0) return;
2014
+ const nextEvents = events.map((event) => createDashboardRuntimeEvent(event));
2015
+ runtimeEvents.current = [...nextEvents, ...runtimeEvents.current].slice(0, 24);
2016
+ if (serverRef) serverRef.ws.send({
2017
+ type: "custom",
2018
+ event: DASHBOARD_EVENT_NAME,
2019
+ data: nextEvents
2020
+ });
2021
+ };
2022
+ const handle = {
2023
+ async update(nextResult, previousResult) {
2024
+ state.previous = previousResult ?? state.current;
2025
+ state.current = nextResult;
2026
+ contentAllowlist.current = createDashboardContentAllowlist(nextResult);
2027
+ emitRuntimeEvents([{
2028
+ kind: "build",
2029
+ level: "info",
2030
+ title: "analyze payload refreshed",
2031
+ detail: `已推送新的 analyze 结果,当前包含 ${nextResult.packages.length} 个包与 ${nextResult.modules.length} 个模块。`,
2032
+ tags: ["analyze", "refresh"]
2033
+ }]);
2034
+ if (serverRef) serverRef.ws.send({
2035
+ type: "custom",
2036
+ event: "weapp-analyze:update",
2037
+ data: state
2077
2038
  });
2078
- return true;
2079
- } catch (retryError) {
2080
- logger_default.error(retryError);
2081
- }
2082
- else {
2083
- logger_default.warn("微信开发者工具 CLI close 执行失败,尝试回退为系统级关闭。");
2084
- logger_default.error(error);
2085
- }
2086
- if (await closeIdeByAppleScript()) {
2087
- logger_default.info("已回退为系统级关闭微信开发者工具。");
2088
- return true;
2089
- }
2090
- if (await closeIdeByProcessKill(cliPath)) {
2091
- logger_default.info("已回退为进程级关闭微信开发者工具。");
2092
- return true;
2039
+ broadcastAnalyzeResult?.(state);
2040
+ },
2041
+ emitRuntimeEvents,
2042
+ waitForExit: () => waitPromise,
2043
+ close: async () => {
2044
+ await server.close();
2045
+ },
2046
+ urls
2047
+ };
2048
+ if (options?.watch) {
2049
+ if (!options.silentStartupLog) {
2050
+ logger_default.info("weapp-vite UI 已启动(分析视图,实时模式),按 Ctrl+C 退出。");
2051
+ for (const url of handle.urls) logger_default.info(` ➜ ${colors.bold(colors.cyan(url))}`);
2093
2052
  }
2094
- return false;
2053
+ return handle;
2054
+ }
2055
+ if (!options?.silentStartupLog) {
2056
+ logger_default.info("weapp-vite UI 已启动(分析视图,静态模式),按 Ctrl+C 退出。");
2057
+ for (const url of handle.urls) logger_default.info(` ➜ ${colors.bold(colors.cyan(url))}`);
2095
2058
  }
2059
+ await waitPromise;
2096
2060
  }
2097
2061
  //#endregion
2098
- //#region src/cli/openIde/reuse.ts
2099
- function formatReuseOpenedWechatIdePrompt() {
2100
- return `目标项目已在微信开发者工具中打开,已跳过重复打开。按 ${colors.bold(colors.green("r"))} 关闭当前窗口后重新打开。`;
2101
- }
2102
- async function openWechatIdeByAutomator(projectPath) {
2103
- (await launchAutomator({
2104
- projectPath,
2105
- trustProject: true
2106
- })).disconnect();
2107
- }
2108
- async function connectOpenedProject(projectPath) {
2109
- try {
2110
- return await connectOpenedAutomator({
2111
- projectPath,
2112
- timeout: 3e3
2113
- });
2114
- } catch {
2115
- return null;
2116
- }
2062
+ //#region src/cli/commands/analyze.ts
2063
+ function normalizeDisplayPath(value) {
2064
+ return value || ".";
2117
2065
  }
2118
- /**
2119
- * @description 若当前项目已在微信开发者工具中打开且自动化可连通,则直接复用现有会话,避免重复拉起 IDE。
2120
- */
2121
- async function tryReuseOpenedWechatIde(projectPath, closeIde) {
2122
- const miniProgram = await connectOpenedProject(projectPath);
2123
- if (!miniProgram) return null;
2124
- miniProgram.disconnect();
2125
- logger_default.info(formatReuseOpenedWechatIdePrompt());
2126
- if (await promptRetryKeypress({ logger: logger_default }) !== "retry") return {
2127
- reopened: false,
2128
- reused: true
2066
+ function getDefaultWebAnalyzeScopes() {
2067
+ return {
2068
+ supported: [
2069
+ "weapp.web 配置解析(enable/root/srcDir/outDir)",
2070
+ "runtime.executionMode 静态解析(compat/safe/strict)",
2071
+ "JSON 报告输出(--json/--output)"
2072
+ ],
2073
+ unsupported: [
2074
+ "分包产物体积分析(仅小程序)",
2075
+ "源码模块包体映射(仅小程序)",
2076
+ "分析仪表盘(dashboard)"
2077
+ ]
2129
2078
  };
2130
- logger_default.info(colors.bold(colors.green("正在关闭当前已打开项目,并重新拉起微信开发者工具...")));
2131
- if (!await closeIde()) logger_default.warn("关闭当前微信开发者工具失败,仍继续尝试重新打开目标项目。");
2132
- await openWechatIdeByAutomator(projectPath);
2079
+ }
2080
+ function createWebAnalyzeResult(configService, options) {
2081
+ const webConfig = configService.weappWebConfig;
2082
+ const executionMode = webConfig?.pluginOptions.runtime?.executionMode ?? "compat";
2083
+ const scope = getDefaultWebAnalyzeScopes();
2084
+ const limitations = ["当前仅提供静态配置分析,不执行 Web 产物扫描。"];
2085
+ if (!webConfig?.enabled) limitations.push("未检测到启用的 weapp.web 配置。");
2133
2086
  return {
2134
- reopened: true,
2135
- reused: false
2087
+ runtime: "web",
2088
+ platform: options.platform,
2089
+ mode: configService.mode,
2090
+ generatedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
2091
+ experimental: true,
2092
+ configFile: configService.configFilePath ? normalizeDisplayPath(configService.relativeCwd(configService.configFilePath)) : void 0,
2093
+ web: {
2094
+ enabled: Boolean(webConfig?.enabled),
2095
+ root: webConfig?.root ? normalizeDisplayPath(configService.relativeCwd(webConfig.root)) : void 0,
2096
+ srcDir: webConfig?.srcDir,
2097
+ outDir: webConfig?.outDir ? normalizeDisplayPath(configService.relativeCwd(webConfig.outDir)) : void 0,
2098
+ executionMode
2099
+ },
2100
+ supportedScopes: scope.supported,
2101
+ unsupportedScopes: scope.unsupported,
2102
+ limitations
2136
2103
  };
2137
2104
  }
2138
- /**
2139
- * @description 对已打开的目标项目执行强制重开,以刷新最新构建产物。
2140
- */
2141
- async function reopenOpenedWechatIde(projectPath, closeIde) {
2142
- const miniProgram = await connectOpenedProject(projectPath);
2143
- if (!miniProgram) return false;
2144
- miniProgram.disconnect();
2145
- logger_default.info("目标项目已在微信开发者工具中打开,当前命令将主动重开以刷新最新构建产物。");
2146
- if (!await closeIde()) logger_default.warn("关闭当前微信开发者工具失败,仍继续尝试重新打开目标项目。");
2147
- await openWechatIdeByAutomator(projectPath);
2105
+ function printAnalysisSummary(result) {
2106
+ const packageLabelMap = /* @__PURE__ */ new Map();
2107
+ const packageModuleSet = /* @__PURE__ */ new Map();
2108
+ for (const pkg of result.packages) packageLabelMap.set(pkg.id, pkg.label);
2109
+ for (const module of result.modules) for (const pkgRef of module.packages) {
2110
+ const set = packageModuleSet.get(pkgRef.packageId) ?? /* @__PURE__ */ new Set();
2111
+ set.add(module.id);
2112
+ packageModuleSet.set(pkgRef.packageId, set);
2113
+ }
2114
+ logger_default.success("分包分析完成");
2115
+ for (const pkg of result.packages) {
2116
+ const chunkCount = pkg.files.filter((file) => file.type === "chunk").length;
2117
+ const assetCount = pkg.files.length - chunkCount;
2118
+ const moduleCount = packageModuleSet.get(pkg.id)?.size ?? 0;
2119
+ logger_default.info(`- ${pkg.label}:${chunkCount} 个模块产物,${assetCount} 个资源,覆盖 ${moduleCount} 个源码模块`);
2120
+ }
2121
+ if (result.subPackages.length > 0) {
2122
+ logger_default.info("分包配置:");
2123
+ for (const descriptor of result.subPackages) {
2124
+ const segments = [descriptor.root];
2125
+ if (descriptor.name) segments.push(`别名:${descriptor.name}`);
2126
+ if (descriptor.independent) segments.push("独立构建");
2127
+ logger_default.info(`- ${segments.join(",")}`);
2128
+ }
2129
+ }
2130
+ const componentUsages = result.components ?? [];
2131
+ if (componentUsages.length > 0) {
2132
+ const suggestions = componentUsages.flatMap((component) => component.suggestions);
2133
+ logger_default.info(`组件依赖:${componentUsages.length} 个组件,${suggestions.length} 条分包优化建议`);
2134
+ for (const suggestion of suggestions.slice(0, 5)) logger_default.info(`- ${suggestion.message}`);
2135
+ if (suggestions.length > 5) logger_default.info(`- …其余 ${suggestions.length - 5} 条组件建议请使用 ${colors.bold(colors.green("weapp-vite analyze --json"))} 查看`);
2136
+ }
2137
+ const duplicates = result.modules.filter((module) => module.packages.length > 1);
2138
+ if (duplicates.length === 0) {
2139
+ logger_default.info("未检测到跨包复用的源码模块。");
2140
+ return;
2141
+ }
2142
+ logger_default.info(`跨包复用/复制源码共 ${duplicates.length} 项:`);
2143
+ const limit = 10;
2144
+ const entries = duplicates.slice(0, limit);
2145
+ for (const module of entries) {
2146
+ const placements = module.packages.map((pkgRef) => {
2147
+ return `${packageLabelMap.get(pkgRef.packageId) ?? pkgRef.packageId} → ${pkgRef.files.join(", ")}`;
2148
+ }).join(";");
2149
+ logger_default.info(`- ${module.source} (${module.sourceType}):${placements}`);
2150
+ }
2151
+ if (duplicates.length > limit) logger_default.info(`- …其余 ${duplicates.length - limit} 项请使用 ${colors.bold(colors.green("weapp-vite analyze --json"))} 查看`);
2152
+ }
2153
+ function printBudgetCheckSummary(result) {
2154
+ const exceededItems = createAnalyzeBudgetCheck(result).filter((item) => item.status === "exceeded");
2155
+ if (exceededItems.length === 0) {
2156
+ logger_default.success("包体预算检查通过");
2157
+ return false;
2158
+ }
2159
+ logger_default.error(`包体预算检查失败:${exceededItems.length} 项超限`);
2160
+ for (const item of exceededItems) logger_default.error(`- ${item.label}:${formatAnalyzeBytes(item.currentBytes)} / ${formatAnalyzeBytes(item.limitBytes)} (${(item.ratio * 100).toFixed(1)}%)`);
2148
2161
  return true;
2149
2162
  }
2150
- //#endregion
2151
- //#region src/cli/openIde/index.ts
2152
- function shouldLogAutomatorFallbackError() {
2153
- const flag = process.env.WEAPP_VITE_DEBUG_AUTOMATOR_OPEN;
2154
- return flag === "1" || flag === "true";
2163
+ function printWebAnalysisSummary(result) {
2164
+ logger_default.success("Web 静态分析完成");
2165
+ logger_default.info(`- 配置状态:${result.web.enabled ? "已启用 weapp.web" : "未启用 weapp.web"}`);
2166
+ if (result.web.enabled) {
2167
+ logger_default.info(`- root:${result.web.root ?? "."}`);
2168
+ logger_default.info(`- srcDir:${result.web.srcDir ?? "."}`);
2169
+ logger_default.info(`- outDir:${result.web.outDir ?? "dist/web"}`);
2170
+ }
2171
+ logger_default.info(`- executionMode:${result.web.executionMode}`);
2172
+ logger_default.info(`- 支持范围:${result.supportedScopes.join(";")}`);
2173
+ logger_default.warn(`- 未支持范围:${result.unsupportedScopes.join(";")}`);
2174
+ for (const limitation of result.limitations) logger_default.warn(`- 限制:${limitation}`);
2155
2175
  }
2156
- /**
2157
- * @description 执行 IDE 打开流程,并在登录失效时允许按键重试。
2158
- */
2159
- async function runWechatIdeOpenWithRetry(argv) {
2160
- await executeWechatIdeCliCommand(argv, {
2161
- cancelLevel: "warn",
2162
- onNonLoginError: (error) => logger_default.error(error),
2163
- onRetry: () => {
2164
- logger_default.info(colors.bold(colors.green("正在重试连接微信开发者工具...")));
2176
+ async function writeAnalyzeResult(result, outputOption, configService, format = "json", previousResult) {
2177
+ if (!outputOption) return;
2178
+ const baseDir = configService.cwd;
2179
+ const resolvedOutputPath = path.isAbsolute(outputOption) ? outputOption : path.resolve(baseDir, outputOption);
2180
+ await fs.ensureDir(path.dirname(resolvedOutputPath));
2181
+ const content = format === "markdown" && "packages" in result ? createAnalyzeMarkdownReport(result, previousResult) : format === "pr" && "packages" in result ? createAnalyzePrMarkdownReport(result, previousResult) : JSON.stringify(result, null, 2);
2182
+ await fs.writeFile(resolvedOutputPath, `${content}\n`, "utf8");
2183
+ const relativeOutput = configService.relativeCwd(resolvedOutputPath);
2184
+ logger_default.success(`分析结果已写入 ${colors.green(relativeOutput)}`);
2185
+ return resolvedOutputPath;
2186
+ }
2187
+ function formatMetricSummary(label, metric) {
2188
+ if (!metric.count || metric.averageMs === void 0 || metric.maxMs === void 0) return;
2189
+ return `${label} avg ${metric.averageMs.toFixed(2)} ms,max ${metric.maxMs.toFixed(2)} ms`;
2190
+ }
2191
+ function formatCountItems(items, limit = 5) {
2192
+ return items.slice(0, limit).map((item) => `${item.name} x${item.count}`).join(",");
2193
+ }
2194
+ function printHmrProfileAnalysisSummary(result, configService) {
2195
+ logger_default.success("HMR profile 分析完成");
2196
+ logger_default.info(`- profile:${colors.green(configService.relativeCwd(result.profilePath))}`);
2197
+ logger_default.info(`- 样本:${result.sampleCount} 条`);
2198
+ if (result.firstTimestamp && result.lastTimestamp) logger_default.info(`- 时间范围:${result.firstTimestamp} -> ${result.lastTimestamp}`);
2199
+ const totalSummary = formatMetricSummary("total", result.metrics.totalMs);
2200
+ const watchSummary = formatMetricSummary("watch->dirty", result.metrics.watchToDirtyMs);
2201
+ const emitSummary = formatMetricSummary("emit", result.metrics.emitMs);
2202
+ const sharedSummary = formatMetricSummary("shared", result.metrics.sharedChunkResolveMs);
2203
+ for (const summary of [
2204
+ totalSummary,
2205
+ watchSummary,
2206
+ emitSummary,
2207
+ sharedSummary
2208
+ ]) if (summary) logger_default.info(`- ${summary}`);
2209
+ if (result.events.length) logger_default.info(`- 事件分布:${formatCountItems(result.events)}`);
2210
+ if (result.dirtyReasons.length) logger_default.info(`- 主要 dirty 原因:${formatCountItems(result.dirtyReasons)}`);
2211
+ if (result.pendingReasons.length) logger_default.info(`- 主要 pending 原因:${formatCountItems(result.pendingReasons)}`);
2212
+ if (result.skippedLineCount > 0) logger_default.warn(`- 跳过 ${result.skippedLineCount} 条无法解析的 profile 记录`);
2213
+ if (result.slowestSamples.length) {
2214
+ logger_default.info("- 最慢样本:");
2215
+ for (const sample of result.slowestSamples.slice(0, 3)) {
2216
+ const fileLabel = sample.file ? configService.relativeCwd(sample.file) : "(unknown)";
2217
+ logger_default.info(` - ${sample.totalMs?.toFixed(2) ?? "0.00"} ms,${sample.event ?? "unknown"},${fileLabel}`);
2218
+ }
2219
+ }
2220
+ }
2221
+ function registerAnalyzeCommand(cli) {
2222
+ cli.command("analyze [root]", "analyze 两端包体与源码映射").option("--hmr-profile [file]", `[string | boolean] 分析 HMR JSONL profile,省略值时优先读取配置,否则回退到默认路径`).option("--json", `[boolean] 输出 JSON 结果`).option("--markdown", `[boolean] 输出 Markdown 报告`).option("--report <type>", `[string] 输出指定报告类型(pr)`).option("--budget-check", `[boolean] 检查 analyze 预算,超过预算时返回非 0 退出码`).option("--output <file>", `[string] 将分析结果写入指定文件(JSON 或 Markdown)`).option("-p, --platform <platform>", `[string] target platform (weapp | web)`).option("--project-config <path>", `[string] project config path (miniprogram only)`).action(async (root, options) => {
2223
+ filterDuplicateOptions(options);
2224
+ const configFile = resolveConfigFile(options);
2225
+ const outputJson = coerceBooleanOption(options.json);
2226
+ const outputMarkdown = coerceBooleanOption(options.markdown);
2227
+ const reportType = typeof options.report === "string" ? options.report.trim() : "";
2228
+ const outputPrReport = reportType === "pr";
2229
+ if (reportType && !outputPrReport) throw new Error(`不支持的 analyze report 类型:${reportType}`);
2230
+ const budgetCheck = coerceBooleanOption(options.budgetCheck);
2231
+ const targets = resolveRuntimeTargets(options);
2232
+ const inlineConfig = createInlineConfig(targets.platform);
2233
+ try {
2234
+ const ctx = await createCompilerContext({
2235
+ cwd: root,
2236
+ mode: options.mode ?? "production",
2237
+ configFile,
2238
+ inlineConfig,
2239
+ cliPlatform: targets.rawPlatform,
2240
+ projectConfigPath: options.projectConfig
2241
+ });
2242
+ logRuntimeTarget(targets, {
2243
+ silent: outputJson || outputMarkdown,
2244
+ resolvedConfigPlatform: ctx.configService.platform
2245
+ });
2246
+ const outputOption = typeof options.output === "string" ? options.output.trim() : "";
2247
+ if (options.hmrProfile !== void 0 && options.hmrProfile !== false) {
2248
+ const profileOption = typeof options.hmrProfile === "string" && options.hmrProfile.trim() ? options.hmrProfile.trim() : ctx.configService.weappViteConfig.hmr?.profileJson;
2249
+ const profilePath = resolveHmrProfileJsonPath({
2250
+ cwd: ctx.configService.cwd,
2251
+ option: profileOption,
2252
+ fallbackToDefault: true
2253
+ });
2254
+ if (!profilePath) throw new Error("未找到可用的 HMR profile 文件路径");
2255
+ const hmrProfileResult = await analyzeHmrProfile({ profilePath });
2256
+ const writtenPath = await writeAnalyzeResult(hmrProfileResult, outputOption, ctx.configService);
2257
+ if (outputJson) {
2258
+ if (!writtenPath) process.stdout.write(`${JSON.stringify(hmrProfileResult, null, 2)}\n`);
2259
+ } else printHmrProfileAnalysisSummary(hmrProfileResult, ctx.configService);
2260
+ return;
2261
+ }
2262
+ if (targets.runWeb) {
2263
+ const webResult = createWebAnalyzeResult(ctx.configService, { platform: "web" });
2264
+ const writtenPath = await writeAnalyzeResult(webResult, outputOption, ctx.configService);
2265
+ if (outputJson) {
2266
+ if (!writtenPath) process.stdout.write(`${JSON.stringify(webResult, null, 2)}\n`);
2267
+ } else printWebAnalysisSummary(webResult);
2268
+ return;
2269
+ }
2270
+ if (!targets.runMini) {
2271
+ logger_default.warn("当前命令不支持该平台,请通过 --platform weapp 或 --platform web 指定目标。");
2272
+ return;
2273
+ }
2274
+ const previousResult = await readLatestAnalyzeHistorySnapshot(ctx.configService);
2275
+ const result = await analyzeSubpackages(ctx);
2276
+ await writeAnalyzeHistorySnapshot(result, ctx.configService);
2277
+ const writtenPath = await writeAnalyzeResult(result, outputOption, ctx.configService, outputPrReport ? "pr" : outputMarkdown ? "markdown" : "json", previousResult);
2278
+ if (outputPrReport) {
2279
+ if (!writtenPath) process.stdout.write(`${createAnalyzePrMarkdownReport(result, previousResult)}\n`);
2280
+ } else if (outputMarkdown) {
2281
+ if (!writtenPath) process.stdout.write(`${createAnalyzeMarkdownReport(result, previousResult)}\n`);
2282
+ } else if (outputJson) {
2283
+ if (!writtenPath) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
2284
+ }
2285
+ if (budgetCheck ? printBudgetCheckSummary(result) : false) process.exitCode = 1;
2286
+ if (budgetCheck) return;
2287
+ if (!outputPrReport && !outputMarkdown && !outputJson) {
2288
+ printAnalysisSummary(result);
2289
+ await startAnalyzeDashboard(result, {
2290
+ artifactRoot: ctx.configService.outDir,
2291
+ cwd: ctx.configService.cwd,
2292
+ packageManagerAgent: ctx.configService.packageManager.agent,
2293
+ previousResult
2294
+ });
2295
+ }
2296
+ } catch (error) {
2297
+ logger_default.error(error);
2298
+ process.exitCode = 1;
2165
2299
  }
2166
2300
  });
2167
2301
  }
2302
+ //#endregion
2303
+ //#region src/cli/formatDuration.ts
2168
2304
  /**
2169
- * @description 根据 mpDistRoot 推导 IDE 项目目录(目录内应包含 project/mini 配置)
2170
- */
2171
- function resolveIdeProjectPath(mpDistRoot) {
2172
- if (!mpDistRoot || !mpDistRoot.trim()) return;
2173
- const parent = path.dirname(mpDistRoot);
2174
- if (!parent || parent === "." || parent === "/") return;
2175
- return parent;
2176
- }
2177
- /**
2178
- * @description 结合 mpDistRoot 与配置根目录解析最终 IDE 项目目录。
2305
+ * 将毫秒耗时格式化为适合 CLI 展示的文本。
2179
2306
  */
2180
- function resolveIdeProjectRoot(mpDistRoot, cwd) {
2181
- return resolveIdeProjectPath(mpDistRoot) ?? cwd;
2307
+ function formatDuration(durationMs) {
2308
+ return `${durationMs}ms`;
2182
2309
  }
2183
- async function closeIde() {
2184
- return await closeIde$1();
2310
+ //#endregion
2311
+ //#region src/cli/logBuildAppFinish.ts
2312
+ let logBuildAppFinishOnlyShowOnce = false;
2313
+ function collectServerUrls(webServer) {
2314
+ const urls = webServer?.resolvedUrls;
2315
+ if (!urls) return [];
2316
+ return [...urls.local ?? [], ...urls.network ?? []];
2185
2317
  }
2186
- async function tryOpenWechatIdeByAutomator(projectPath, options) {
2187
- if (options.reuseOpenedProject === false) {
2188
- if (await reopenOpenedWechatIde(projectPath, closeIde)) return true;
2318
+ function logBuildAppFinish(configService, webServer, options = {}) {
2319
+ if (logBuildAppFinishOnlyShowOnce) return;
2320
+ const { skipMini = false, skipWeb = false, uiUrls = [] } = options;
2321
+ const webUrls = skipWeb ? [] : collectServerUrls(webServer);
2322
+ if (skipMini) {
2323
+ logger_default.success("开发服务已就绪:");
2324
+ if (webUrls.length > 0) logger_default.info(`Web:${colors.cyan(webUrls[0])}`);
2325
+ else logger_default.info("Web:已启动");
2326
+ logBuildAppFinishOnlyShowOnce = true;
2327
+ return;
2189
2328
  }
2190
- const reuseResult = await tryReuseOpenedWechatIde(projectPath, closeIde);
2191
- if (reuseResult?.reused || reuseResult?.reopened) return true;
2192
- await openWechatIdeByAutomator(projectPath);
2193
- return true;
2329
+ const { command, args } = resolveCommand(configService.packageManager.agent, "run", ["open"]) ?? {
2330
+ command: "npm",
2331
+ args: ["run", "open"]
2332
+ };
2333
+ const devCommand = `${command} ${args.join(" ")}`;
2334
+ logger_default.success("开发服务已就绪:");
2335
+ logger_default.info(`小程序:执行 ${colors.bold(colors.green(devCommand))},或手动导入 ${colors.green(getProjectConfigFileName(configService.platform))}`);
2336
+ if (uiUrls.length > 0) logger_default.info(`UI:${colors.cyan(uiUrls[0])}`);
2337
+ else if (!skipMini) logger_default.info("UI:未启用");
2338
+ if (webUrls.length > 0) logger_default.info(`Web:${colors.cyan(webUrls[0])}`);
2339
+ const projectConfigFileName = getProjectConfigFileName(configService.platform);
2340
+ if (!uiUrls.length && !webUrls.length) logger_default.info(`提示:手动打开对应平台开发者工具,导入根目录(${colors.green(projectConfigFileName)} 文件所在目录)`);
2341
+ logBuildAppFinishOnlyShowOnce = true;
2194
2342
  }
2195
- /**
2196
- * @description 打开后主动刷新微信开发者工具的项目索引,避免模拟器沿用过期 app 配置。
2197
- */
2198
- async function stabilizeOpenedWechatIdeProject(projectPath, servicePortEnabled) {
2199
- if (servicePortEnabled === false) return;
2200
- try {
2201
- await executeWechatIdeCliCommand(["compile"], {
2202
- httpMode: "prefer",
2203
- onNonLoginError: (error) => logger_default.error(error),
2204
- projectPath
2205
- });
2206
- await executeWechatIdeCliCommand([
2207
- "reset-fileutils",
2208
- "-p",
2209
- projectPath
2210
- ], {
2211
- httpMode: "prefer",
2212
- onNonLoginError: (error) => logger_default.error(error),
2213
- projectPath
2214
- });
2215
- await executeWechatIdeCliCommand([
2216
- "engine",
2217
- "build",
2218
- projectPath
2219
- ], {
2220
- httpMode: "prefer",
2221
- onNonLoginError: (error) => logger_default.error(error),
2222
- projectPath
2223
- });
2224
- try {
2225
- await executeWechatIdeCliCommand(["compile"], {
2226
- automatorMode: "require",
2227
- httpMode: "skip",
2228
- projectPath
2229
- });
2230
- } catch (error) {
2231
- if (shouldLogAutomatorFallbackError()) logger_default.error(error);
2232
- }
2233
- } catch (error) {
2234
- logger_default.warn("刷新微信开发者工具项目索引失败,已保留当前打开状态;如模拟器仍显示旧状态,可手动刷新一次。");
2235
- if (shouldLogAutomatorFallbackError()) logger_default.error(error);
2236
- }
2343
+ const WINDOWS_SEPARATOR_RE = /\\/g;
2344
+ function normalizeFileName(fileName) {
2345
+ return fileName.replace(WINDOWS_SEPARATOR_RE, "/");
2237
2346
  }
2238
- function createIdeOpenArgv(platform, projectPath, options = {}) {
2239
- const argv = ["open", "-p"];
2240
- if (projectPath) argv.push(projectPath);
2241
- if (platform === "weapp" && options.trustProject !== false) argv.push("--trust-project");
2242
- if (platform && shouldPassPlatformArgToIdeOpen(platform)) argv.push("--platform", platform);
2243
- return argv;
2347
+ function getOutputItemBytes(item) {
2348
+ if (item.type === "chunk") return typeof item.code === "string" ? Buffer.byteLength(item.code, "utf8") : 0;
2349
+ if (typeof item.source === "string") return Buffer.byteLength(item.source, "utf8");
2350
+ if (item.source instanceof Uint8Array) return item.source.byteLength;
2351
+ return 0;
2244
2352
  }
2245
- async function openIde(platform, projectPath, options = {}) {
2246
- let bootstrapResult;
2247
- if (platform === "weapp" && projectPath) try {
2248
- bootstrapResult = await bootstrapWechatDevtoolsSettings({
2249
- projectPath,
2250
- trustProject: options.trustProject
2251
- });
2252
- } catch (error) {
2253
- logger_default.warn("检测微信开发者工具服务端口或写入项目信任状态失败,继续执行 open 流程。");
2254
- logger_default.error(error);
2353
+ function resolveSubPackageRoot(fileName, roots) {
2354
+ const normalized = normalizeFileName(fileName);
2355
+ return roots.find((root) => normalized === root || normalized.startsWith(`${root}/`));
2356
+ }
2357
+ function collectPackageSizeReports(output, subPackageMap) {
2358
+ const outputs = Array.isArray(output) ? output : [output];
2359
+ const roots = [...subPackageMap?.keys() ?? []].filter(Boolean).sort((a, b) => b.length - a.length || a.localeCompare(b));
2360
+ const packageBytes = new Map([["__main__", 0]]);
2361
+ for (const root of roots) packageBytes.set(root, 0);
2362
+ for (const current of outputs) for (const item of current.output ?? []) {
2363
+ const root = resolveSubPackageRoot(item.fileName, roots) ?? "__main__";
2364
+ packageBytes.set(root, (packageBytes.get(root) ?? 0) + getOutputItemBytes(item));
2255
2365
  }
2256
- if (platform === "weapp" && projectPath && bootstrapResult?.servicePortEnabled === false) logger_default.warn("检测到微信开发者工具服务端口当前处于关闭状态,已保留用户设置并回退到普通 open 流程。");
2257
- if (platform === "weapp" && projectPath && options.trustProject !== false && bootstrapResult?.servicePortEnabled !== false) try {
2258
- if (await tryOpenWechatIdeByAutomator(projectPath, options)) {
2259
- await stabilizeOpenedWechatIdeProject(projectPath, bootstrapResult?.servicePortEnabled);
2260
- return;
2261
- }
2262
- } catch (error) {
2263
- if (isAutomatorLoginError(error)) {
2264
- logger_default.error("检测到微信开发者工具登录状态失效,请先登录后重试。");
2265
- logger_default.warn(formatAutomatorLoginError(error));
2266
- }
2267
- logger_default.warn("通过 automator 启动微信开发者工具并自动信任项目失败,回退到普通 open 流程。");
2268
- if (shouldLogAutomatorFallbackError()) logger_default.error(error);
2366
+ const reports = [{
2367
+ root: "__main__",
2368
+ label: "主包",
2369
+ bytes: packageBytes.get("__main__") ?? 0
2370
+ }];
2371
+ for (const root of roots) {
2372
+ const meta = subPackageMap?.get(root);
2373
+ const isIndependent = Boolean(meta?.subPackage.independent);
2374
+ reports.push({
2375
+ root,
2376
+ label: `${isIndependent ? "独立分包" : "分包"} ${root}`,
2377
+ bytes: packageBytes.get(root) ?? 0
2378
+ });
2269
2379
  }
2270
- await runWechatIdeOpenWithRetry(createIdeOpenArgv(platform, projectPath, options));
2271
- if (platform === "weapp" && projectPath) await stabilizeOpenedWechatIdeProject(projectPath, bootstrapResult?.servicePortEnabled);
2380
+ return reports;
2272
2381
  }
2273
- /**
2274
- * @description 解析 IDE 相关命令所需的平台、项目目录与配置上下文。
2275
- */
2276
- async function resolveIdeCommandContext(options) {
2277
- const cwd = options.cwd ?? process.cwd();
2278
- let platform = options.platform;
2279
- let projectPath = options.projectPath;
2280
- if (!platform || !projectPath) try {
2281
- const ctx = await createCompilerContext({
2282
- cwd,
2283
- mode: options.mode ?? "development",
2284
- configFile: options.configFile,
2285
- inlineConfig: createInlineConfig(platform),
2286
- cliPlatform: options.cliPlatform
2287
- });
2288
- platform ??= ctx.configService.platform;
2289
- if (!projectPath) projectPath = resolveIdeProjectRoot(ctx.configService.mpDistRoot, ctx.configService.cwd);
2290
- return {
2291
- cwd: ctx.configService.cwd,
2292
- platform,
2293
- projectPath,
2294
- weappViteConfig: ctx.configService.weappViteConfig,
2295
- mpDistRoot: ctx.configService.mpDistRoot
2296
- };
2297
- } catch {}
2298
- if (!projectPath) {
2299
- const defaultProjectRoot = getDefaultIdeProjectRoot(platform);
2300
- if (defaultProjectRoot) projectPath = resolveIdeProjectRoot(defaultProjectRoot, cwd);
2382
+ function logBuildPackageSizeReport(options) {
2383
+ const warningBytes = Number(options.warningBytes ?? 2097152);
2384
+ const reports = collectPackageSizeReports(options.output, options.subPackageMap);
2385
+ logger_default.success("主包/分包体积报告:");
2386
+ for (const report of reports) logger_default.info(`${report.label}:${formatBytes(report.bytes)}`);
2387
+ if (!(Number.isFinite(warningBytes) && warningBytes > 0)) return;
2388
+ for (const report of reports) {
2389
+ if (report.bytes <= warningBytes) continue;
2390
+ logger_default.warn(`[包体积] ${colors.yellow(report.label)} 体积 ${colors.yellow(formatBytes(report.bytes))},已超过阈值 ${colors.yellow(formatBytes(warningBytes))}。`);
2301
2391
  }
2302
- return {
2303
- cwd,
2304
- platform,
2305
- projectPath
2306
- };
2307
2392
  }
2308
2393
  //#endregion
2309
2394
  //#region src/cli/commands/build.ts
@@ -3616,7 +3701,7 @@ function resolveRunnableHotkeyDefinition(input) {
3616
3701
  }
3617
3702
  //#endregion
3618
3703
  //#region package.json
3619
- var version = "6.16.4";
3704
+ var version = "6.16.5";
3620
3705
  //#endregion
3621
3706
  //#region src/cli/devHotkeys/format.ts
3622
3707
  const FULLWIDTH_ASCII_START = 65281;
@@ -4420,6 +4505,7 @@ const WEAPP_VITE_NATIVE_COMMANDS = new Set([
4420
4505
  "build",
4421
4506
  "close",
4422
4507
  "analyze",
4508
+ "alipay",
4423
4509
  "init",
4424
4510
  "open",
4425
4511
  "npm",
@@ -4537,6 +4623,7 @@ try {
4537
4623
  } catch {}
4538
4624
  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`);
4539
4625
  registerIdeCommand(cli);
4626
+ registerAlipayCommand(cli);
4540
4627
  registerBuildCommand(cli);
4541
4628
  registerCloseCommand(cli);
4542
4629
  registerAnalyzeCommand(cli);
@@ -4555,7 +4642,8 @@ const skipManagedTsconfigBootstrapCommands = new Set([
4555
4642
  "ide",
4556
4643
  "init",
4557
4644
  "mcp",
4558
- "npm"
4645
+ "npm",
4646
+ "alipay"
4559
4647
  ]);
4560
4648
  function resolveManagedTsconfigBootstrapRoot(args) {
4561
4649
  const [firstArg, secondArg] = args;