e2e-node-coverage.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /* eslint-disable max-lines -- Node coverage reporter 需在同一文件保持 V8 归一化、源码基线与 Istanbul 输出合同。 */
  2. import { execFileSync } from "node:child_process";
  3. import {
  4. existsSync,
  5. mkdirSync,
  6. readFileSync,
  7. readdirSync,
  8. renameSync,
  9. statSync,
  10. writeFileSync,
  11. } from "node:fs";
  12. import { basename, dirname, isAbsolute, resolve } from "node:path";
  13. import { fileURLToPath, pathToFileURL } from "node:url";
  14. import {
  15. createCoverageMap,
  16. type CoverageMapData,
  17. } from "istanbul-lib-coverage";
  18. import { createInstrumenter } from "istanbul-lib-instrument";
  19. import { createContext } from "istanbul-lib-report";
  20. import { create as createIstanbulReport } from "istanbul-reports";
  21. export type E2ENodeCoverageDomain = "main" | "host" | "cli";
  22. interface CoverageMetricSummary {
  23. covered: number;
  24. pct: number | string;
  25. skipped: number;
  26. total: number;
  27. }
  28. interface C8CoverageSummary {
  29. total?: {
  30. branches: CoverageMetricSummary;
  31. functions: CoverageMetricSummary;
  32. lines: CoverageMetricSummary;
  33. statements: CoverageMetricSummary;
  34. };
  35. }
  36. export interface E2ENodeCoverageDomainSummary {
  37. baselineFailureCount: number;
  38. complete: boolean;
  39. domain: E2ENodeCoverageDomain;
  40. expectedProcessCount?: number;
  41. files: {
  42. coverageFinalJson: string;
  43. coverageSummaryJson: string;
  44. htmlIndex: string;
  45. lcov: string;
  46. reportDir: string;
  47. sourceManifest: string;
  48. };
  49. rawFileCount: number;
  50. missingRawProcessCount: number;
  51. preEntryProcessCount?: number;
  52. sourceFileCount: number;
  53. totals?: C8CoverageSummary["total"];
  54. }
  55. export interface E2ENodeCoverageSummary {
  56. complete: boolean;
  57. domains: Record<E2ENodeCoverageDomain, E2ENodeCoverageDomainSummary>;
  58. enabled: boolean;
  59. generatedAt: string;
  60. }
  61. interface E2ENodeCoverageCollectorOptions {
  62. artifactDir: string;
  63. desktopDir: string;
  64. repoRoot: string;
  65. }
  66. interface SourceMapPayload {
  67. mappings?: string;
  68. names?: string[];
  69. sourceRoot?: string;
  70. sources?: string[];
  71. sourcesContent?: Array<string | null>;
  72. version?: number;
  73. }
  74. interface V8CoveragePayload {
  75. result?: Array<{ url?: string }>;
  76. "source-map-cache"?: Record<
  77. string,
  78. {
  79. data?: SourceMapPayload | null;
  80. lineLengths?: number[];
  81. url?: string | null;
  82. }
  83. >;
  84. "zcode-e2e-normalized-source-map-root"?: string;
  85. }
  86. const COVERAGE_ENABLED_VALUE = "1";
  87. const DOMAINS: E2ENodeCoverageDomain[] = ["main", "host", "cli"];
  88. const SOURCE_EXTENSIONS = [".cjs", ".cts", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx"];
  89. const SOURCE_MAP_CACHE_INDEX_MARKER = ".zcode-source-map-cache-index-v2.marker";
  90. const COMPACTED_FILE_INDEX_MARKER = ".zcode-compacted-coverage-files-v1.marker";
  91. export function createE2ENodeCoverageCollector(
  92. options: E2ENodeCoverageCollectorOptions,
  93. ) {
  94. const enabled = process.env.ZCODE_E2E_COVERAGE === COVERAGE_ENABLED_VALUE;
  95. const coverageDir = resolve(options.artifactDir, "coverage");
  96. const rawRoot = resolve(coverageDir, "raw");
  97. const sourceMapRoots: Record<E2ENodeCoverageDomain, string> = {
  98. cli: resolve(options.repoRoot, "apps/zcode-cli/packages/cli/dist"),
  99. host: resolve(options.desktopDir, "out/host"),
  100. main: resolve(options.desktopDir, "out/main"),
  101. };
  102. function rawDir(domain: E2ENodeCoverageDomain) {
  103. return resolve(rawRoot, domain);
  104. }
  105. function prepare() {
  106. if (!enabled) return;
  107. for (const domain of DOMAINS) {
  108. mkdirSync(rawDir(domain), { recursive: true });
  109. }
  110. }
  111. function beforeSession() {
  112. if (!enabled) return;
  113. prepare();
  114. // Electron main 必须从进程启动时就继承 NODE_V8_COVERAGE;host 与 CLI
  115. // 会在各自 spawn 边界覆盖到独立目录,避免运行域数据混写。
  116. process.env.NODE_V8_COVERAGE = rawDir("main");
  117. }
  118. function compactRawCoverage() {
  119. if (!enabled) return;
  120. prepare();
  121. for (const domain of DOMAINS) {
  122. compactV8CoverageDirectory({
  123. rawDir: rawDir(domain),
  124. sourceMapRoot: sourceMapRoots[domain],
  125. });
  126. }
  127. }
  128. function finalize(): E2ENodeCoverageSummary | undefined {
  129. if (!enabled) return undefined;
  130. prepare();
  131. compactRawCoverage();
  132. const domains = Object.fromEntries(
  133. DOMAINS.map((domain) => [
  134. domain,
  135. writeDomainReport({
  136. artifactDir: options.artifactDir,
  137. domain,
  138. rawDir: rawDir(domain),
  139. reportDir: resolve(coverageDir, domain),
  140. repoRoot: options.repoRoot,
  141. sourceMapRoot: sourceMapRoots[domain],
  142. }),
  143. ]),
  144. ) as Record<E2ENodeCoverageDomain, E2ENodeCoverageDomainSummary>;
  145. return {
  146. complete: DOMAINS.every((domain) => domains[domain].complete),
  147. domains,
  148. enabled: true,
  149. generatedAt: new Date().toISOString(),
  150. };
  151. }
  152. return { beforeSession, compactRawCoverage, enabled, finalize, prepare };
  153. }
  154. export function compactV8CoverageDirectory(params: {
  155. rawDir: string;
  156. sourceMapRoot: string;
  157. }) {
  158. mkdirSync(params.rawDir, { recursive: true });
  159. const normalizedSourceMapRoot = normalizePath(resolve(params.sourceMapRoot));
  160. const sourceMapCacheMarker = resolve(params.rawDir, SOURCE_MAP_CACHE_INDEX_MARKER);
  161. const compactedFileMarker = resolve(params.rawDir, COMPACTED_FILE_INDEX_MARKER);
  162. const retainedSourceMapUrls = readRetainedSourceMapUrls(sourceMapCacheMarker);
  163. const compactedFileNames = readMarkerLines(compactedFileMarker);
  164. let compactedFileIndexChanged = false;
  165. let compactedFileCount = 0;
  166. for (const rawPath of listFiles(params.rawDir, (path) => path.endsWith(".json"))) {
  167. const rawFileName = basename(rawPath);
  168. // Bug 根因:仅在 JSON payload 内记录 normalized 标记时,后续每个 worker 仍会重新
  169. // 读取并 parse 此前数千个大文件,全量 after-session 因此额外耗时约一小时。
  170. // V8 raw 文件名在同一 domain 内唯一且落盘后不可变,sidecar 可在文件 IO 前安全跳过。
  171. if (compactedFileNames.has(rawFileName)) continue;
  172. let payload: V8CoveragePayload;
  173. try {
  174. payload = JSON.parse(readFileSync(rawPath, "utf-8")) as V8CoveragePayload;
  175. } catch {
  176. continue;
  177. }
  178. if (payload["zcode-e2e-normalized-source-map-root"] === normalizedSourceMapRoot) {
  179. compactedFileNames.add(rawFileName);
  180. compactedFileIndexChanged = true;
  181. continue;
  182. }
  183. normalizeV8CoveragePayload(payload, params.sourceMapRoot, {
  184. excludeSourceMapUrls: retainedSourceMapUrls,
  185. });
  186. payload["zcode-e2e-normalized-source-map-root"] = normalizedSourceMapRoot;
  187. const retainedByThisFile = Object.keys(payload["source-map-cache"] ?? {});
  188. // Bug 根因:V8 会为每个短生命周期 Electron/Host/CLI 进程重复落整份 bundle
  189. // source map,全量(含 manual-review)在 finalize 前即可超过百 GB。进程退出后立即
  190. // 原地剪到当前运行域,并用原子替换避免中断时留下半份 JSON;每个 bundle 的 map
  191. // 只保留一份,后续首次出现的动态 chunk 仍会进入索引,避免覆盖率映射缺口。
  192. const temporaryPath = `${rawPath}.normalized-${process.pid}.tmp`;
  193. writeFileSync(temporaryPath, JSON.stringify(payload), "utf-8");
  194. renameSync(temporaryPath, rawPath);
  195. compactedFileNames.add(rawFileName);
  196. compactedFileIndexChanged = true;
  197. compactedFileCount += 1;
  198. if (retainedByThisFile.length > 0) {
  199. for (const url of retainedByThisFile) retainedSourceMapUrls.add(url);
  200. writeFileSync(
  201. sourceMapCacheMarker,
  202. `${[...retainedSourceMapUrls].sort().join("\n")}\n`,
  203. "utf-8",
  204. );
  205. }
  206. }
  207. if (compactedFileIndexChanged) {
  208. writeMarkerLines(compactedFileMarker, compactedFileNames);
  209. }
  210. return {
  211. compactedFileCount,
  212. sourceMapCacheRetained: retainedSourceMapUrls.size > 0,
  213. };
  214. }
  215. function readRetainedSourceMapUrls(markerPath: string) {
  216. return readMarkerLines(markerPath);
  217. }
  218. function readMarkerLines(markerPath: string) {
  219. if (!existsSync(markerPath)) return new Set<string>();
  220. return new Set(
  221. readFileSync(markerPath, "utf-8")
  222. .split("\n")
  223. .map((line) => line.trim())
  224. .filter(Boolean),
  225. );
  226. }
  227. function writeMarkerLines(markerPath: string, values: Set<string>) {
  228. const temporaryPath = `${markerPath}.${process.pid}.tmp`;
  229. writeFileSync(temporaryPath, `${[...values].sort().join("\n")}\n`, "utf-8");
  230. renameSync(temporaryPath, markerPath);
  231. }
  232. function writeDomainReport(params: {
  233. artifactDir: string;
  234. domain: E2ENodeCoverageDomain;
  235. rawDir: string;
  236. reportDir: string;
  237. repoRoot: string;
  238. sourceMapRoot: string;
  239. }): E2ENodeCoverageDomainSummary {
  240. mkdirSync(params.reportDir, { recursive: true });
  241. const rawFileCount = listFiles(params.rawDir, (path) => path.endsWith(".json")).length;
  242. const rawProcessPids = collectRawProcessPids(params.rawDir);
  243. const readyProcessPids = collectReadyProcessPids(params.rawDir);
  244. const expectedProcessPids = collectExpectedProcessPids(
  245. params.artifactDir,
  246. params.domain,
  247. );
  248. const missingRawProcessCount = expectedProcessPids
  249. ? [...expectedProcessPids].filter(
  250. (pid) => readyProcessPids.has(pid) && !rawProcessPids.has(pid),
  251. ).length
  252. : 0;
  253. const preEntryProcessCount = expectedProcessPids
  254. ? [...expectedProcessPids].filter(
  255. (pid) => !readyProcessPids.has(pid) && !rawProcessPids.has(pid),
  256. ).length
  257. : 0;
  258. const sourceFiles = collectFirstPartySources(
  259. params.domain,
  260. params.sourceMapRoot,
  261. params.repoRoot,
  262. );
  263. const sourceManifest = resolve(params.reportDir, "source-manifest.json");
  264. writeFileSync(sourceManifest, `${JSON.stringify(sourceFiles, null, 2)}\n`, "utf-8");
  265. const coverageFinalJson = resolve(params.reportDir, "coverage-final.json");
  266. const coverageSummaryJson = resolve(params.reportDir, "coverage-summary.json");
  267. const lcov = resolve(params.reportDir, "lcov.info");
  268. const htmlIndex = resolve(params.reportDir, "index.html");
  269. let baselineFailureCount = 0;
  270. if (rawFileCount > 0 && sourceFiles.length > 0) {
  271. const normalizedRawDir = writeNormalizedV8Coverage({
  272. rawDir: params.rawDir,
  273. reportDir: params.reportDir,
  274. sourceMapRoot: params.sourceMapRoot,
  275. });
  276. const convertedCoveragePath = runC8Conversion({
  277. rawDir: normalizedRawDir,
  278. reportDir: params.reportDir,
  279. repoRoot: params.repoRoot,
  280. });
  281. baselineFailureCount = writeNodeIstanbulReports({
  282. convertedCoveragePath,
  283. reportDir: params.reportDir,
  284. repoRoot: params.repoRoot,
  285. sourceFiles,
  286. });
  287. }
  288. return {
  289. baselineFailureCount,
  290. complete:
  291. rawFileCount > 0 &&
  292. sourceFiles.length > 0 &&
  293. baselineFailureCount === 0 &&
  294. missingRawProcessCount === 0 &&
  295. existsSync(coverageSummaryJson),
  296. domain: params.domain,
  297. expectedProcessCount: expectedProcessPids?.size,
  298. files: {
  299. coverageFinalJson,
  300. coverageSummaryJson,
  301. htmlIndex,
  302. lcov,
  303. reportDir: params.reportDir,
  304. sourceManifest,
  305. },
  306. rawFileCount,
  307. missingRawProcessCount,
  308. preEntryProcessCount,
  309. sourceFileCount: sourceFiles.length,
  310. totals: readCoverageTotals(coverageSummaryJson),
  311. };
  312. }
  313. function collectRawProcessPids(rawDir: string) {
  314. const pids = new Set<number>();
  315. for (const path of listFiles(rawDir, (candidate) => candidate.endsWith(".json"))) {
  316. const match = /(?:^|[\\/])coverage-(\d+)-/u.exec(path);
  317. if (match?.[1]) pids.add(Number(match[1]));
  318. }
  319. return pids;
  320. }
  321. function collectReadyProcessPids(rawDir: string) {
  322. const pids = new Set<number>();
  323. for (const path of listFiles(rawDir, (candidate) => candidate.endsWith(".marker"))) {
  324. const match = /(?:^|[\\/])coverage-ready-(\d+)\.marker$/u.exec(path);
  325. if (match?.[1]) pids.add(Number(match[1]));
  326. }
  327. return pids;
  328. }
  329. function collectExpectedProcessPids(
  330. artifactDir: string,
  331. domain: E2ENodeCoverageDomain,
  332. ) {
  333. if (domain !== "cli") return undefined;
  334. const pids = new Set<number>();
  335. const runtimeLogsDir = resolve(artifactDir, "runtime-logs");
  336. for (const logPath of listFiles(runtimeLogsDir, (path) => path.endsWith(".log"))) {
  337. const content = readFileSync(logPath, "utf-8");
  338. for (const line of content.split("\n")) {
  339. if (!line.includes("ZCode agent process exited")) continue;
  340. const match = /"pid":(\d+),"runtimeIdentity"/u.exec(line);
  341. if (match?.[1]) pids.add(Number(match[1]));
  342. }
  343. }
  344. return pids.size > 0 ? pids : undefined;
  345. }
  346. function runC8Conversion(params: {
  347. rawDir: string;
  348. reportDir: string;
  349. repoRoot: string;
  350. }) {
  351. const convertedDir = resolve(params.reportDir, "converted");
  352. const configPath = resolve(params.reportDir, "c8-convert-config.json");
  353. writeFileSync(
  354. configPath,
  355. `${JSON.stringify(createC8ConversionConfig(params.rawDir, convertedDir), null, 2)}\n`,
  356. "utf-8",
  357. );
  358. const reportEnv = { ...process.env };
  359. // 修复原因:reporter 自身若继续继承 NODE_V8_COVERAGE,会把 c8 进程的
  360. // coverage 写回待消费目录,既污染运行域数据,也可能让汇总时间持续增长。
  361. delete reportEnv.NODE_V8_COVERAGE;
  362. execFileSync(
  363. process.execPath,
  364. [resolve(params.repoRoot, "node_modules/c8/bin/c8.js"), "report", "--config", configPath],
  365. {
  366. cwd: params.repoRoot,
  367. env: reportEnv,
  368. stdio: "inherit",
  369. },
  370. );
  371. return resolve(convertedDir, "coverage-final.json");
  372. }
  373. export function createC8ConversionConfig(rawDir: string, convertedDir: string) {
  374. return {
  375. all: false,
  376. clean: false,
  377. "exclude-after-remap": false,
  378. // Bug 根因:c8 默认先把每个 Node 进程的 coverage 全部载入数组;全量 E2E 会在
  379. // 合并开始前耗尽堆。增量模式逐文件读取并合并,覆盖率计数语义保持一致。
  380. "merge-async": true,
  381. reporter: ["json"],
  382. "reports-dir": convertedDir,
  383. "temp-directory": rawDir,
  384. };
  385. }
  386. function writeNodeIstanbulReports(params: {
  387. convertedCoveragePath: string;
  388. reportDir: string;
  389. repoRoot: string;
  390. sourceFiles: string[];
  391. }) {
  392. const sourceSet = new Set(params.sourceFiles.map((path) => normalizePath(resolve(path))));
  393. const converted = existsSync(params.convertedCoveragePath)
  394. ? (JSON.parse(readFileSync(params.convertedCoveragePath, "utf-8")) as CoverageMapData)
  395. : {};
  396. const coverageMap = createCoverageMap(converted);
  397. coverageMap.filter((path) => sourceSet.has(normalizePath(resolve(path))));
  398. const loadedPaths = new Set(
  399. coverageMap.files().map((path) => normalizePath(resolve(path))),
  400. );
  401. let baselineFailureCount = 0;
  402. for (const sourceFile of params.sourceFiles) {
  403. if (loadedPaths.has(normalizePath(resolve(sourceFile)))) continue;
  404. try {
  405. const instrumenter = createInstrumenter({
  406. coverageVariable: "__zcode_e2e_node_baseline__",
  407. parserPlugins: ["typescript", "jsx"],
  408. produceSourceMap: false,
  409. });
  410. instrumenter.instrumentSync(readFileSync(sourceFile, "utf-8"), sourceFile);
  411. const baseline = instrumenter.lastFileCoverage();
  412. if (baseline) coverageMap.addFileCoverage(baseline);
  413. } catch {
  414. baselineFailureCount += 1;
  415. }
  416. }
  417. const context = createContext({
  418. coverageMap,
  419. defaultSummarizer: "nested",
  420. dir: params.reportDir,
  421. sourceFinder(path) {
  422. return readFileSync(path, "utf-8");
  423. },
  424. });
  425. createIstanbulReport("json", { file: "coverage-final.json" }).execute(context);
  426. createIstanbulReport("json-summary", { file: "coverage-summary.json" }).execute(context);
  427. createIstanbulReport("lcovonly", {
  428. file: "lcov.info",
  429. projectRoot: params.repoRoot,
  430. }).execute(context);
  431. createIstanbulReport("html", {
  432. skipEmpty: false,
  433. subdir: ".",
  434. verbose: false,
  435. }).execute(context);
  436. return baselineFailureCount;
  437. }
  438. function collectFirstPartySources(
  439. domain: E2ENodeCoverageDomain,
  440. sourceMapRoot: string,
  441. repoRoot: string,
  442. ) {
  443. const sources = new Set<string>();
  444. for (const mapPath of listFiles(sourceMapRoot, (path) => path.endsWith(".map"))) {
  445. let payload: SourceMapPayload;
  446. try {
  447. payload = JSON.parse(readFileSync(mapPath, "utf-8")) as SourceMapPayload;
  448. } catch {
  449. continue;
  450. }
  451. for (const source of payload.sources ?? []) {
  452. const path = resolveSourceMapSource(mapPath, payload.sourceRoot, source);
  453. if (path && isFirstPartyRuntimeSource(domain, path, repoRoot)) {
  454. sources.add(path);
  455. }
  456. }
  457. }
  458. return [...sources].sort();
  459. }
  460. function resolveSourceMapSource(mapPath: string, sourceRoot: string | undefined, source: string) {
  461. if (!source || source.startsWith("node:") || source.startsWith("<")) return undefined;
  462. try {
  463. if (source.startsWith("file://")) return fileURLToPath(source);
  464. if (isAbsolute(source)) return resolve(source);
  465. return resolve(dirname(mapPath), sourceRoot ?? "", source);
  466. } catch {
  467. return undefined;
  468. }
  469. }
  470. function isFirstPartyRuntimeSource(
  471. domain: E2ENodeCoverageDomain,
  472. path: string,
  473. repoRoot: string,
  474. ) {
  475. const normalized = normalizePath(resolve(path));
  476. const root = `${normalizePath(resolve(repoRoot))}/`;
  477. if (!normalized.startsWith(root) || normalized.includes("/node_modules/")) return false;
  478. if (!SOURCE_EXTENSIONS.some((extension) => normalized.endsWith(extension))) return false;
  479. return !(
  480. (domain !== "cli" && normalized.includes("/dist/")) ||
  481. normalized.includes("/out/") ||
  482. normalized.includes("/test/") ||
  483. normalized.includes("/tests/") ||
  484. normalized.includes("/fixtures/") ||
  485. normalized.includes("/generated/") ||
  486. /(?:\.d\.ts|\.(?:spec|test)\.[cm]?[jt]sx?)$/u.test(normalized)
  487. );
  488. }
  489. function writeNormalizedV8Coverage(params: {
  490. rawDir: string;
  491. reportDir: string;
  492. sourceMapRoot: string;
  493. }) {
  494. const normalizedDir = resolve(params.reportDir, "normalized-raw");
  495. mkdirSync(normalizedDir, { recursive: true });
  496. const sourceMapUrlsWritten = new Set<string>();
  497. for (const rawPath of listFiles(params.rawDir, (path) => path.endsWith(".json"))) {
  498. let payload: V8CoveragePayload;
  499. try {
  500. payload = JSON.parse(readFileSync(rawPath, "utf-8")) as V8CoveragePayload;
  501. } catch {
  502. continue;
  503. }
  504. normalizeV8CoveragePayload(payload, params.sourceMapRoot, {
  505. excludeSourceMapUrls: sourceMapUrlsWritten,
  506. });
  507. for (const url of Object.keys(payload["source-map-cache"] ?? {})) {
  508. sourceMapUrlsWritten.add(url);
  509. }
  510. writeFileSync(
  511. resolve(normalizedDir, rawPath.split(/[\\/]/u).at(-1) ?? "coverage.json"),
  512. JSON.stringify(payload),
  513. "utf-8",
  514. );
  515. }
  516. return normalizedDir;
  517. }
  518. export function normalizeV8CoveragePayload(
  519. payload: V8CoveragePayload,
  520. sourceMapRoot: string,
  521. options: {
  522. excludeSourceMapUrls?: ReadonlySet<string>;
  523. includeSourceMapCache?: boolean;
  524. } = {},
  525. ) {
  526. // Bug 根因:V8 文件还包含 Node 内置模块和整个三方依赖图。全量 E2E 的 CLI 原始
  527. // coverage 可达数十 GB;若把无关条目原样复制给 c8,会在 JSON.parse 阶段耗尽堆。
  528. // 报告最终只消费能映射回当前运行域 source map 的 bundle,因此在归一化边界提前剪枝。
  529. payload.result = (payload.result ?? []).filter((entry) => {
  530. const canonicalUrl = resolveCanonicalGeneratedUrl(entry.url, sourceMapRoot);
  531. if (!canonicalUrl) return false;
  532. entry.url = canonicalUrl;
  533. return true;
  534. });
  535. const sourceMapCache = payload["source-map-cache"];
  536. if (!sourceMapCache) return;
  537. if (options.includeSourceMapCache === false) {
  538. // 同一运行域的每份 V8 文件都内嵌同一份 bundle source map(CLI 单份约 38MB)。
  539. // c8 增量合并会在整个目录处理期间复用缓存,只需保留一份,不能重复上千次落盘。
  540. delete payload["source-map-cache"];
  541. return;
  542. }
  543. const normalizedCache: NonNullable<V8CoveragePayload["source-map-cache"]> = {};
  544. for (const [generatedUrl, cacheEntry] of Object.entries(sourceMapCache)) {
  545. const canonicalUrl = resolveCanonicalGeneratedUrl(generatedUrl, sourceMapRoot);
  546. if (!canonicalUrl) continue;
  547. if (options.excludeSourceMapUrls?.has(canonicalUrl)) continue;
  548. const mapPath = `${fileURLToPath(canonicalUrl)}.map`;
  549. const map = readSourceMap(mapPath);
  550. normalizedCache[canonicalUrl] = map
  551. ? {
  552. ...cacheEntry,
  553. data: {
  554. ...map,
  555. sources: (map.sources ?? []).map((source) => {
  556. const resolvedSource = resolveSourceMapSource(mapPath, map.sourceRoot, source);
  557. return resolvedSource ? pathToFileURL(resolvedSource).href : source;
  558. }),
  559. sourceRoot: undefined,
  560. },
  561. }
  562. : cacheEntry;
  563. }
  564. if (Object.keys(normalizedCache).length > 0) {
  565. payload["source-map-cache"] = normalizedCache;
  566. } else {
  567. delete payload["source-map-cache"];
  568. }
  569. }
  570. function resolveCanonicalGeneratedUrl(url: string | undefined, sourceMapRoot: string) {
  571. if (!url?.startsWith("file://")) return undefined;
  572. try {
  573. const generatedPath = fileURLToPath(url);
  574. const generatedName = generatedPath.split(/[\\/]/u).at(-1);
  575. if (!generatedName) return undefined;
  576. const canonicalRoot = resolve(sourceMapRoot);
  577. // 同名的 dependency/index.js 不能映射成 out/main/index.js。桌面 staging 目录会变化,
  578. // 但运行域末级目录仍稳定为 main/host;CLI 则直接从 canonical dist 启动。
  579. if (
  580. dirname(resolve(generatedPath)) !== canonicalRoot &&
  581. basename(dirname(generatedPath)) !== basename(canonicalRoot)
  582. ) {
  583. return undefined;
  584. }
  585. const canonicalPath = resolve(canonicalRoot, generatedName);
  586. if (!existsSync(canonicalPath) || !existsSync(`${canonicalPath}.map`)) return undefined;
  587. return pathToFileURL(canonicalPath).href;
  588. } catch {
  589. return undefined;
  590. }
  591. }
  592. function readSourceMap(path: string) {
  593. try {
  594. return JSON.parse(readFileSync(path, "utf-8")) as SourceMapPayload;
  595. } catch {
  596. return undefined;
  597. }
  598. }
  599. function listFiles(root: string, accept: (path: string) => boolean): string[] {
  600. if (!existsSync(root)) return [];
  601. const result: string[] = [];
  602. const visit = (path: string) => {
  603. if (statSync(path).isDirectory()) {
  604. for (const name of readdirSync(path)) visit(resolve(path, name));
  605. return;
  606. }
  607. if (accept(path)) result.push(path);
  608. };
  609. visit(root);
  610. return result.sort();
  611. }
  612. function readCoverageTotals(path: string) {
  613. if (!existsSync(path)) return undefined;
  614. try {
  615. return (JSON.parse(readFileSync(path, "utf-8")) as C8CoverageSummary).total;
  616. } catch {
  617. return undefined;
  618. }
  619. }
  620. function normalizePath(path: string) {
  621. return path.replaceAll("\\", "/");
  622. }