e2e-coverage-heatmap.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /* eslint-disable max-lines -- 自包含热度图需要同时保留 coverage 聚合合同和离线报告模板。 */
  2. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
  3. import { relative, resolve } from "node:path";
  4. export type CoverageHeatmapDomain = "renderer" | "main" | "host" | "cli";
  5. interface IstanbulFunctionLocation {
  6. start?: {
  7. line?: number;
  8. };
  9. }
  10. interface IstanbulFunctionMapEntry {
  11. decl?: IstanbulFunctionLocation;
  12. loc?: IstanbulFunctionLocation;
  13. name?: string;
  14. }
  15. interface IstanbulFileCoverage {
  16. f?: Record<string, number>;
  17. fnMap?: Record<string, IstanbulFunctionMapEntry>;
  18. path?: string;
  19. }
  20. interface CoverageHeatmapFunction {
  21. hits: number;
  22. line?: number;
  23. name: string;
  24. path: string;
  25. }
  26. export interface CoverageHeatmapFile {
  27. coveredFunctions: number;
  28. functionHits: number;
  29. functions: number;
  30. hottestFunction?: CoverageHeatmapFunction;
  31. path: string;
  32. }
  33. export interface CoverageHeatmapDomainData {
  34. coveredFunctions: number;
  35. domain: CoverageHeatmapDomain;
  36. files: CoverageHeatmapFile[];
  37. functionHits: number;
  38. functions: number;
  39. }
  40. export interface CoverageHeatmapData {
  41. domains: CoverageHeatmapDomainData[];
  42. generatedAt: string;
  43. scale: "log1p";
  44. }
  45. export interface CoverageHeatmapSummary {
  46. dataJson: string;
  47. domainCount: number;
  48. fileCount: number;
  49. htmlIndex: string;
  50. }
  51. interface WriteCoverageHeatmapOptions {
  52. coverageDir: string;
  53. repoRoot: string;
  54. }
  55. const DOMAIN_COVERAGE_PATHS: Record<CoverageHeatmapDomain, string[]> = {
  56. renderer: ["coverage-final.json"],
  57. main: ["main", "coverage-final.json"],
  58. host: ["host", "coverage-final.json"],
  59. cli: ["cli", "coverage-final.json"],
  60. };
  61. const DOMAIN_ORDER = Object.keys(
  62. DOMAIN_COVERAGE_PATHS,
  63. ) as CoverageHeatmapDomain[];
  64. export function writeE2ECoverageHeatmap(
  65. options: WriteCoverageHeatmapOptions,
  66. ): CoverageHeatmapSummary | undefined {
  67. const data = buildCoverageHeatmapData(options);
  68. if (data.domains.length === 0) return undefined;
  69. const reportDir = resolve(options.coverageDir, "heatmap");
  70. const dataJson = resolve(reportDir, "data.json");
  71. const htmlIndex = resolve(reportDir, "index.html");
  72. mkdirSync(reportDir, { recursive: true });
  73. writeFileSync(dataJson, `${JSON.stringify(data, null, 2)}\n`, "utf-8");
  74. writeFileSync(htmlIndex, renderCoverageHeatmapHtml(data), "utf-8");
  75. return {
  76. dataJson,
  77. domainCount: data.domains.length,
  78. fileCount: data.domains.reduce(
  79. (total, domain) => total + domain.files.length,
  80. 0,
  81. ),
  82. htmlIndex,
  83. };
  84. }
  85. export function buildCoverageHeatmapData(
  86. options: WriteCoverageHeatmapOptions,
  87. ): CoverageHeatmapData {
  88. const domains = DOMAIN_ORDER.flatMap((domain) => {
  89. const coveragePath = resolve(
  90. options.coverageDir,
  91. ...DOMAIN_COVERAGE_PATHS[domain],
  92. );
  93. if (!existsSync(coveragePath)) return [];
  94. const coverage = readCoverageFile(coveragePath);
  95. if (!coverage) return [];
  96. return [buildDomainData(domain, coverage, options.repoRoot)];
  97. });
  98. return {
  99. domains,
  100. generatedAt: new Date().toISOString(),
  101. scale: "log1p",
  102. };
  103. }
  104. function readCoverageFile(path: string) {
  105. try {
  106. return JSON.parse(readFileSync(path, "utf-8")) as Record<
  107. string,
  108. IstanbulFileCoverage
  109. >;
  110. } catch {
  111. return undefined;
  112. }
  113. }
  114. function buildDomainData(
  115. domain: CoverageHeatmapDomain,
  116. coverage: Record<string, IstanbulFileCoverage>,
  117. repoRoot: string,
  118. ): CoverageHeatmapDomainData {
  119. const files = Object.entries(coverage)
  120. .map(([coveragePath, fileCoverage]) =>
  121. buildFileData(coveragePath, fileCoverage, repoRoot),
  122. )
  123. .sort((left, right) => left.path.localeCompare(right.path));
  124. return {
  125. coveredFunctions: files.reduce(
  126. (total, file) => total + file.coveredFunctions,
  127. 0,
  128. ),
  129. domain,
  130. files,
  131. functionHits: files.reduce((total, file) => total + file.functionHits, 0),
  132. functions: files.reduce((total, file) => total + file.functions, 0),
  133. };
  134. }
  135. function buildFileData(
  136. coveragePath: string,
  137. fileCoverage: IstanbulFileCoverage,
  138. repoRoot: string,
  139. ): CoverageHeatmapFile {
  140. const counters = fileCoverage.f ?? {};
  141. const functionMap = fileCoverage.fnMap ?? {};
  142. const normalizedPath = normalizeCoveragePath(
  143. fileCoverage.path ?? coveragePath,
  144. repoRoot,
  145. );
  146. const functionHits = Object.values(counters).reduce(
  147. (total, hits) => total + normalizeHits(hits),
  148. 0,
  149. );
  150. const hottestEntry = Object.entries(counters).reduce<
  151. [string, number] | undefined
  152. >((hottest, entry) => {
  153. const normalized: [string, number] = [entry[0], normalizeHits(entry[1])];
  154. return !hottest || normalized[1] > hottest[1] ? normalized : hottest;
  155. }, undefined);
  156. const hottestFunction =
  157. hottestEntry && hottestEntry[1] > 0
  158. ? buildHottestFunction(
  159. hottestEntry,
  160. functionMap[hottestEntry[0]],
  161. normalizedPath,
  162. )
  163. : undefined;
  164. return {
  165. coveredFunctions: Object.values(counters).filter((hits) => hits > 0).length,
  166. functionHits,
  167. functions: Object.keys(counters).length,
  168. hottestFunction,
  169. path: normalizedPath,
  170. };
  171. }
  172. function buildHottestFunction(
  173. entry: [string, number],
  174. metadata: IstanbulFunctionMapEntry | undefined,
  175. path: string,
  176. ): CoverageHeatmapFunction {
  177. return {
  178. hits: entry[1],
  179. line: metadata?.loc?.start?.line ?? metadata?.decl?.start?.line,
  180. name: metadata?.name?.trim() || `(anonymous ${entry[0]})`,
  181. path,
  182. };
  183. }
  184. function normalizeHits(value: number) {
  185. return Number.isFinite(value) && value > 0 ? value : 0;
  186. }
  187. function normalizeCoveragePath(path: string, repoRoot: string) {
  188. const normalizedPath = path.split("?")[0]?.replaceAll("\\", "/") ?? path;
  189. const normalizedRoot = resolve(repoRoot).replaceAll("\\", "/");
  190. const relativePath = normalizedPath.startsWith(`${normalizedRoot}/`)
  191. ? relative(normalizedRoot, normalizedPath)
  192. : normalizedPath.replace(/^\.\//u, "");
  193. return relativePath.replaceAll("\\", "/");
  194. }
  195. function renderCoverageHeatmapHtml(data: CoverageHeatmapData) {
  196. const inlineData = JSON.stringify(data)
  197. .replaceAll("<", "\\u003c")
  198. .replaceAll("\u2028", "\\u2028")
  199. .replaceAll("\u2029", "\\u2029");
  200. return `<!doctype html>
  201. <html lang="zh-CN">
  202. <head>
  203. <meta charset="utf-8">
  204. <meta name="viewport" content="width=device-width, initial-scale=1">
  205. <title>Desktop E2E 函数执行热度图</title>
  206. <style>
  207. :root {
  208. color-scheme: light dark;
  209. --background: #f7f8fa;
  210. --foreground: #1b1f24;
  211. --muted: #656d76;
  212. --panel: #ffffff;
  213. --border: #d0d7de;
  214. --tile-zero: #e8ebef;
  215. --tile-low: #fff0c2;
  216. --tile-high: #ff8a00;
  217. --tile-hot-text: #211400;
  218. --focus: #0969da;
  219. }
  220. @media (prefers-color-scheme: dark) {
  221. :root {
  222. --background: #0d1117;
  223. --foreground: #e6edf3;
  224. --muted: #8b949e;
  225. --panel: #161b22;
  226. --border: #30363d;
  227. --tile-zero: #171b22;
  228. --tile-low: #3a2500;
  229. --tile-high: #ffd43b;
  230. --tile-hot-text: #17120a;
  231. --focus: #58a6ff;
  232. }
  233. }
  234. * { box-sizing: border-box; }
  235. body {
  236. margin: 0;
  237. background: var(--background);
  238. color: var(--foreground);
  239. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
  240. }
  241. main { max-width: 1480px; margin: 0 auto; padding: 24px; }
  242. h1 { margin: 0 0 6px; font-size: 24px; font-weight: 600; }
  243. .subtitle { margin: 0 0 20px; color: var(--muted); }
  244. .toolbar, .domain-tabs, .legend, .summary {
  245. display: flex;
  246. align-items: center;
  247. flex-wrap: wrap;
  248. gap: 8px;
  249. }
  250. .toolbar { justify-content: space-between; margin-bottom: 14px; }
  251. button, select {
  252. border: 1px solid var(--border);
  253. border-radius: 7px;
  254. background: var(--panel);
  255. color: var(--foreground);
  256. font: inherit;
  257. }
  258. button { padding: 7px 11px; cursor: pointer; }
  259. button:hover { border-color: var(--focus); }
  260. button:focus-visible, select:focus-visible {
  261. outline: 2px solid var(--focus);
  262. outline-offset: 2px;
  263. }
  264. .domain-tab[aria-pressed="true"] {
  265. border-color: var(--focus);
  266. background: var(--focus);
  267. color: #ffffff;
  268. }
  269. label { color: var(--muted); }
  270. select { margin-left: 6px; padding: 7px 28px 7px 9px; }
  271. .heat-grid {
  272. display: grid;
  273. gap: 2px;
  274. width: 100%;
  275. height: min(68vh, 720px);
  276. min-height: 480px;
  277. overflow: hidden;
  278. padding: 2px;
  279. border: 1px solid var(--border);
  280. border-radius: 10px;
  281. background: var(--border);
  282. }
  283. .heat-tile {
  284. width: 100%;
  285. height: 100%;
  286. min-width: 0;
  287. min-height: 0;
  288. overflow: hidden;
  289. border: 0;
  290. border-radius: 3px;
  291. padding: 2px;
  292. text-align: left;
  293. transition: filter 120ms ease, transform 120ms ease;
  294. }
  295. .heat-tile:hover, .heat-tile:focus-visible { z-index: 2; filter: brightness(1.08); }
  296. .heat-tile:focus-visible { outline-offset: -3px; }
  297. .heat-tile[aria-pressed="true"] { box-shadow: inset 0 0 0 3px var(--focus); z-index: 3; }
  298. .tile-name, .tile-meta { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  299. .tile-name { font-weight: 600; }
  300. .tile-meta { margin-top: 4px; font-size: 12px; opacity: 0.82; }
  301. .summary {
  302. min-height: 58px;
  303. margin-top: 12px;
  304. padding: 10px 12px;
  305. border: 1px solid var(--border);
  306. border-radius: 8px;
  307. background: var(--panel);
  308. }
  309. .summary strong { overflow-wrap: anywhere; }
  310. .summary span { color: var(--muted); }
  311. .legend { justify-content: flex-end; margin-top: 10px; color: var(--muted); font-size: 13px; }
  312. .legend-swatch { width: 28px; height: 12px; border-radius: 3px; }
  313. .legend-zero { background: var(--tile-zero); }
  314. .legend-low { background: var(--tile-low); }
  315. .legend-high { background: var(--tile-high); }
  316. .empty { display: grid; place-items: center; height: 100%; color: var(--muted); }
  317. @media (max-width: 640px) {
  318. main { padding: 14px; }
  319. .toolbar { align-items: flex-start; flex-direction: column; }
  320. .heat-grid { height: 520px; min-height: 420px; }
  321. .tile-meta { display: none; }
  322. }
  323. @media (prefers-reduced-motion: reduce) {
  324. .heat-tile { transition: none; }
  325. }
  326. </style>
  327. </head>
  328. <body>
  329. <main>
  330. <h1>Desktop E2E 函数执行热度图</h1>
  331. <p class="subtitle">每个等大 tile 代表一个源码文件;越亮表示执行越频繁。</p>
  332. <div class="toolbar">
  333. <div id="domain-tabs" class="domain-tabs" aria-label="运行域"></div>
  334. <label>亮度指标
  335. <select id="metric-select">
  336. <option value="total">函数总命中</option>
  337. <option value="average">每函数平均命中</option>
  338. </select>
  339. </label>
  340. </div>
  341. <div id="heat-grid" class="heat-grid" role="group" aria-label="等面积文件执行热度图"></div>
  342. <div id="summary" class="summary" aria-live="polite"></div>
  343. <div class="legend" aria-label="颜色图例">
  344. <span>0</span><span class="legend-swatch legend-zero"></span>
  345. <span>低</span><span class="legend-swatch legend-low"></span>
  346. <span>高</span><span class="legend-swatch legend-high"></span>
  347. <span>对数刻度,当前运行域全局归一化</span>
  348. </div>
  349. </main>
  350. <script id="coverage-heatmap-data" type="application/json">${inlineData}</script>
  351. <script>
  352. (() => {
  353. const report = JSON.parse(document.getElementById("coverage-heatmap-data").textContent);
  354. const domainTabs = document.getElementById("domain-tabs");
  355. const metricSelect = document.getElementById("metric-select");
  356. const heatGrid = document.getElementById("heat-grid");
  357. const summary = document.getElementById("summary");
  358. const number = new Intl.NumberFormat("zh-CN", { maximumFractionDigits: 1 });
  359. let domain = report.domains[0];
  360. let selected = null;
  361. function buildItems() {
  362. return domain.files
  363. .map((file) => ({
  364. ...file,
  365. kind: "file",
  366. name: file.path.split("/").at(-1) || file.path,
  367. }))
  368. .sort((left, right) => left.path.localeCompare(right.path));
  369. }
  370. function domainNode() {
  371. const hottestFunction = domain.files.reduce(
  372. (hottest, file) => !hottest || (file.hottestFunction && file.hottestFunction.hits > hottest.hits)
  373. ? file.hottestFunction
  374. : hottest,
  375. undefined,
  376. );
  377. return {
  378. coveredFunctions: domain.coveredFunctions,
  379. functionHits: domain.functionHits,
  380. functions: domain.functions,
  381. hottestFunction,
  382. kind: "domain",
  383. name: domain.domain,
  384. path: domain.domain,
  385. };
  386. }
  387. function metricValue(node) {
  388. return metricSelect.value === "average"
  389. ? node.functionHits / Math.max(1, node.functions)
  390. : node.functionHits;
  391. }
  392. function formatPercent(node) {
  393. if (!node.functions) return "0%";
  394. return number.format((node.coveredFunctions / node.functions) * 100) + "%";
  395. }
  396. function describe(node) {
  397. const hottest = node.hottestFunction
  398. ? "最热函数 " + node.hottestFunction.name + " · " + node.hottestFunction.path + (node.hottestFunction.line ? ":" + node.hottestFunction.line : "") + " · " + number.format(node.hottestFunction.hits) + " 次"
  399. : "没有函数命中";
  400. return (node.path || domain.domain) + ";" + number.format(node.functionHits) + " 次函数命中;" + node.coveredFunctions + "/" + node.functions + " 个函数已覆盖;" + hottest;
  401. }
  402. function showSummary(node) {
  403. summary.replaceChildren();
  404. const path = document.createElement("strong");
  405. path.textContent = node.path || domain.domain;
  406. const metrics = document.createElement("span");
  407. metrics.textContent = number.format(node.functionHits) + " 次函数命中 · " + node.coveredFunctions + "/" + node.functions + " 函数已覆盖(" + formatPercent(node) + ")";
  408. const hottest = document.createElement("span");
  409. hottest.textContent = node.hottestFunction
  410. ? "最热:" + node.hottestFunction.name + " · " + node.hottestFunction.path + (node.hottestFunction.line ? ":" + node.hottestFunction.line : "") + " · " + number.format(node.hottestFunction.hits) + " 次"
  411. : "无命中函数";
  412. summary.append(path, metrics, hottest);
  413. }
  414. function renderTabs() {
  415. domainTabs.replaceChildren();
  416. for (const candidate of report.domains) {
  417. const button = document.createElement("button");
  418. button.type = "button";
  419. button.className = "domain-tab";
  420. button.textContent = candidate.domain;
  421. button.setAttribute("aria-pressed", String(candidate.domain === domain.domain));
  422. button.addEventListener("click", () => {
  423. domain = candidate;
  424. selected = null;
  425. render();
  426. });
  427. domainTabs.append(button);
  428. }
  429. }
  430. function renderHeatGrid() {
  431. heatGrid.replaceChildren();
  432. const items = buildItems();
  433. if (items.length === 0) {
  434. const empty = document.createElement("div");
  435. empty.className = "empty";
  436. empty.textContent = "当前运行域没有可展示的函数";
  437. heatGrid.append(empty);
  438. return;
  439. }
  440. const width = Math.max(1, heatGrid.clientWidth - 6);
  441. const height = Math.max(1, heatGrid.clientHeight - 6);
  442. const columns = Math.max(1, Math.ceil(Math.sqrt(items.length * width / height)));
  443. const rows = Math.max(1, Math.ceil(items.length / columns));
  444. const cellWidth = (width - Math.max(0, columns - 1) * 2) / columns;
  445. const cellHeight = (height - Math.max(0, rows - 1) * 2) / rows;
  446. heatGrid.style.gridTemplateColumns = "repeat(" + columns + ", minmax(0, 1fr))";
  447. heatGrid.style.gridTemplateRows = "repeat(" + rows + ", minmax(0, 1fr))";
  448. const maxHeat = Math.max(...items.map(metricValue), 0);
  449. for (const node of items) {
  450. const heat = metricValue(node);
  451. const logRatio = heat <= 0 || maxHeat <= 0 ? 0 : Math.log1p(heat) / Math.log1p(maxHeat);
  452. const level = Math.pow(logRatio, 3);
  453. const tile = document.createElement("button");
  454. tile.type = "button";
  455. tile.className = "heat-tile";
  456. tile.style.background = level === 0
  457. ? "var(--tile-zero)"
  458. : "color-mix(in srgb, var(--tile-low), var(--tile-high) " + Math.round(level * 100) + "%)";
  459. tile.style.color = level > 0.68 ? "var(--tile-hot-text)" : "var(--foreground)";
  460. tile.setAttribute("aria-label", describe(node));
  461. tile.setAttribute("aria-pressed", String(selected?.path === node.path));
  462. if (cellWidth >= 64 && cellHeight >= 28) {
  463. const name = document.createElement("span");
  464. name.className = "tile-name";
  465. name.textContent = node.name;
  466. tile.append(name);
  467. }
  468. if (cellWidth >= 110 && cellHeight >= 48) {
  469. const meta = document.createElement("span");
  470. meta.className = "tile-meta";
  471. meta.textContent = number.format(node.functionHits) + " 次 · " + node.functions + " 函数";
  472. tile.append(meta);
  473. }
  474. tile.addEventListener("mouseenter", () => showSummary(node));
  475. tile.addEventListener("focus", () => showSummary(node));
  476. tile.addEventListener("mouseleave", () => showSummary(selected || domainNode()));
  477. tile.addEventListener("click", () => {
  478. selected = node;
  479. renderHeatGrid();
  480. showSummary(node);
  481. });
  482. heatGrid.append(tile);
  483. }
  484. }
  485. function render() {
  486. renderTabs();
  487. renderHeatGrid();
  488. showSummary(selected || domainNode());
  489. }
  490. metricSelect.addEventListener("change", () => {
  491. selected = null;
  492. render();
  493. });
  494. let resizeFrame;
  495. window.addEventListener("resize", () => {
  496. cancelAnimationFrame(resizeFrame);
  497. resizeFrame = requestAnimationFrame(renderHeatGrid);
  498. });
  499. render();
  500. })();
  501. </script>
  502. </body>
  503. </html>
  504. `;
  505. }