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