vite.config.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import { createRequire } from "node:module";
  2. import { mkdirSync, writeFileSync } from "node:fs";
  3. import { dirname, extname, isAbsolute, resolve } from "node:path";
  4. import { defineConfig, loadEnv, type Plugin } from "vite";
  5. import react from "@vitejs/plugin-react";
  6. import tailwindcss from "@tailwindcss/vite";
  7. import { resolveZCodeEndpointOrigin, pickProductEndpointEnv } from "@zcode/shared/zcodeEndpoint";
  8. import { pdfJsCMapsPlugin } from "../ui/vite/pdfJsCMapsPlugin.js";
  9. import { getBuildMetadata } from "./scripts/build-metadata.mjs";
  10. import { resolveDesktopProductFlavor } from "./scripts/desktop-product-identity.mjs";
  11. const buildMetadata = getBuildMetadata();
  12. const desktopRequire = createRequire(import.meta.url);
  13. interface IstanbulInstrumenter {
  14. instrumentSync(sourceCode: string, filename: string): string;
  15. lastFileCoverage(): unknown;
  16. lastSourceMap(): object | null;
  17. }
  18. interface IstanbulLibInstrument {
  19. createInstrumenter(options: {
  20. autoWrap: boolean;
  21. compact: boolean;
  22. coverageGlobalScope: string;
  23. coverageGlobalScopeFunc: boolean;
  24. esModules: boolean;
  25. parserPlugins: string[];
  26. preserveComments: boolean;
  27. produceSourceMap: boolean;
  28. }): IstanbulInstrumenter;
  29. }
  30. const { createInstrumenter } = desktopRequire("istanbul-lib-instrument") as IstanbulLibInstrument;
  31. function resolveInstalledPackageRoot(packageName: string): string {
  32. return dirname(desktopRequire.resolve(`${packageName}/package.json`));
  33. }
  34. export const desktopRendererDependencyAliases = {
  35. // pnpm hoisted/package-local 布局会随安装配置变化;硬编码 node_modules 子路径
  36. // 会让 Rolldown 依赖优化把 react/jsx-runtime 等入口解析到不存在的位置。
  37. // 通过 Node 解析真实安装根目录,既保留单 React runtime,又兼容不同 node-linker。
  38. react: resolveInstalledPackageRoot("react"),
  39. "react-dom": resolveInstalledPackageRoot("react-dom"),
  40. "lucide-react": resolveInstalledPackageRoot("lucide-react"),
  41. } as const;
  42. function resolveZCodeEnv(value: string | undefined): "test" | "production" {
  43. return value?.trim().toLowerCase() === "production" ? "production" : "test";
  44. }
  45. function createE2EUIRendererCoveragePlugin(repoRoot: string): Plugin {
  46. const sourceRoots = [
  47. resolve(repoRoot, "packages/ui/src"),
  48. resolve(repoRoot, "packages/desktop/src/renderer"),
  49. ].map(normalizePathForVite);
  50. const instrumenter = createInstrumenter({
  51. autoWrap: true,
  52. compact: false,
  53. coverageGlobalScope: "globalThis",
  54. coverageGlobalScopeFunc: false,
  55. esModules: true,
  56. parserPlugins: ["typescript", "jsx"],
  57. preserveComments: true,
  58. produceSourceMap: true,
  59. });
  60. const baselineCoverage: Record<string, unknown> = {};
  61. const baselinePath = resolve(
  62. repoRoot,
  63. "packages/desktop/out/renderer/e2e-coverage-baseline.json",
  64. );
  65. return {
  66. name: "zcode:e2e-ui-source-coverage",
  67. enforce: "pre",
  68. transform(sourceCode, id, options) {
  69. if (options?.ssr || id.startsWith("\0")) {
  70. return null;
  71. }
  72. const filename = stripViteRequestQuery(id);
  73. const absoluteFilename = isAbsolute(filename) ? filename : resolve(repoRoot, filename);
  74. const normalizedFilename = normalizePathForVite(absoluteFilename);
  75. if (!shouldInstrumentE2EUISource(normalizedFilename, sourceRoots)) {
  76. return null;
  77. }
  78. // post-transform 插桩依赖 Vite/React/esbuild 的合并 sourcemap,
  79. // 会把生成后的 JS 覆盖点反投影到 import、interface 等 TS 源码行上。
  80. // 这里先对原始 TS/TSX AST 插桩,再交给 Vite 编译,保证 coverage map 只包含真实运行时代码。
  81. const code = instrumenter.instrumentSync(sourceCode, normalizedFilename);
  82. baselineCoverage[normalizedFilename] = JSON.parse(
  83. JSON.stringify(instrumenter.lastFileCoverage()),
  84. );
  85. return {
  86. code,
  87. map: instrumenter.lastSourceMap(),
  88. };
  89. },
  90. closeBundle() {
  91. // 只读取页面 __coverage__ 会让从未加载的 lazy chunk 消失,分母被缩小。
  92. // coverage build 将完整 renderer graph 的零命中 map 留给 suite reporter 合并。
  93. mkdirSync(dirname(baselinePath), { recursive: true });
  94. writeFileSync(baselinePath, `${JSON.stringify(baselineCoverage, null, 2)}\n`, "utf-8");
  95. },
  96. };
  97. }
  98. function shouldInstrumentE2EUISource(filename: string, sourceRoots: string[]) {
  99. return (
  100. isCoverageSourceFile(filename) &&
  101. !filename.includes("/node_modules/") &&
  102. !isDeclarationFile(filename) &&
  103. !isTestSourceFile(filename) &&
  104. sourceRoots.some((sourceRoot) => isInsidePath(filename, sourceRoot))
  105. );
  106. }
  107. function isCoverageSourceFile(filename: string) {
  108. return [".cts", ".cjs", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx"].includes(extname(filename));
  109. }
  110. function isDeclarationFile(filename: string) {
  111. return /\.d\.[cm]?ts$/u.test(filename);
  112. }
  113. function isTestSourceFile(filename: string) {
  114. return /\.(?:spec|test)\.[cm]?[jt]sx?$/u.test(filename);
  115. }
  116. function isInsidePath(filename: string, directory: string) {
  117. return filename === directory || filename.startsWith(`${directory}/`);
  118. }
  119. function normalizePathForVite(path: string) {
  120. return path.replaceAll("\\", "/");
  121. }
  122. function stripViteRequestQuery(id: string) {
  123. return id.split("?")[0] ?? id;
  124. }
  125. export default defineConfig(({ mode }) => {
  126. // `.env*` 只提供链接常量;当前产品环境由启动脚本或 CI 注入 ZCODE_ENV。
  127. const env = { ...loadEnv(mode, "../..", ""), ...process.env };
  128. const repoRoot = resolve(__dirname, "../..");
  129. const zcodeEnv = resolveZCodeEnv(env.ZCODE_ENV);
  130. // 安装包身份与后端环境分轴;renderer 用它决定是否展示更新入口。
  131. const zcodeProductFlavor = resolveDesktopProductFlavor({
  132. ...process.env,
  133. ...env,
  134. ZCODE_ENV: zcodeEnv,
  135. });
  136. const e2eCoverageEnabled =
  137. env.ZCODE_E2E_COVERAGE === "1" || process.env.ZCODE_E2E_COVERAGE === "1";
  138. const e2eStoreBridgeEnabled =
  139. env.VITE_ZCODE_E2E_STORE_BRIDGE === "1" || process.env.VITE_ZCODE_E2E_STORE_BRIDGE === "1";
  140. const zcodeEndpointOrigin = resolveZCodeEndpointOrigin({
  141. env: zcodeEnv,
  142. envBaseOrigin: env.ZCODE_BASE_URL ?? env.ZCODE_ENDPOINT_ORIGIN,
  143. });
  144. const codingPlanWebviewOrigin =
  145. env.VITE_CODING_PLAN_WEBVIEW_ORIGIN ?? process.env.VITE_CODING_PLAN_WEBVIEW_ORIGIN ?? "";
  146. const plugins = [
  147. ...(e2eCoverageEnabled ? [createE2EUIRendererCoveragePlugin(repoRoot)] : []),
  148. pdfJsCMapsPlugin(),
  149. react(),
  150. tailwindcss(),
  151. ];
  152. return {
  153. root: "src/renderer",
  154. plugins,
  155. resolve: {
  156. alias: {
  157. // 修复 UI 组件库中的 @ 别名解析失败。
  158. // 问题原因:desktop 会直接打包 packages/ui 的源码,但当前 Vite 配置不知道 @ 应该指向 packages/ui/src,
  159. // 导致 spinner、alert 等组件里的内部导入在构建时全部失效。
  160. // 这里在消费端补齐别名,比逐个改组件导入更稳,也能和 web 端保持一致。
  161. "@": resolve(__dirname, "../ui/src"),
  162. ...desktopRendererDependencyAliases,
  163. // Recharts 通过 d3-shape 读取 d3-path 的 Path 导出;hoisted node_modules
  164. // 里可能残留 d3-shape/node_modules/d3-path@1.x,Vite 预构建会优先命中旧包并报 Missing export。
  165. // 这里把 d3-path 固定到根部 3.x 入口,确保桌面端依赖优化和运行时解析一致。
  166. "d3-path": resolve(__dirname, "../../node_modules/d3-path/src/index.js"),
  167. },
  168. dedupe: ["react", "react-dom", "lucide-react"],
  169. },
  170. server: { port: 5174, strictPort: true },
  171. define: {
  172. __ZCODE_ENDPOINT_ENV__: JSON.stringify(pickProductEndpointEnv(env)),
  173. __ZCODE_VERSION__: JSON.stringify(buildMetadata.appVersion),
  174. __ZCODE_COMMIT__: JSON.stringify(buildMetadata.buildCommitId),
  175. __ZCODE_BUILD_TIME__: JSON.stringify(buildMetadata.buildTime),
  176. __ZCODE_ENV__: JSON.stringify(zcodeEnv),
  177. __ZCODE_PRODUCT_FLAVOR__: JSON.stringify(zcodeProductFlavor),
  178. __ZCODE_LOCAL_DEVELOPMENT_RUNTIME__: JSON.stringify(mode !== "production"),
  179. "import.meta.env.VITE_ZCODE_BASE_URL": JSON.stringify(zcodeEndpointOrigin),
  180. // 兼容旧 renderer 读取名;新代码统一读 VITE_ZCODE_BASE_URL。
  181. "import.meta.env.VITE_ZCODE_ENDPOINT_ORIGIN": JSON.stringify(zcodeEndpointOrigin),
  182. "import.meta.env.VITE_CODING_PLAN_WEBVIEW_ORIGIN": JSON.stringify(codingPlanWebviewOrigin),
  183. "import.meta.env.VITE_REWARDS_WEBVIEW_ORIGIN": JSON.stringify(
  184. env.VITE_REWARDS_WEBVIEW_ORIGIN ?? process.env.VITE_REWARDS_WEBVIEW_ORIGIN ?? "",
  185. ),
  186. // E2E store bridge 只能由 WDIO 专用变量打开,避免把 ZCODE_ENV=test 产品环境误当成测试运行态。
  187. "import.meta.env.VITE_ZCODE_E2E_STORE_BRIDGE": JSON.stringify(
  188. e2eStoreBridgeEnabled ? "1" : "",
  189. ),
  190. },
  191. // Electron 用 file:// 协议加载页面,资源路径必须是相对路径,否则会 ERR_FILE_NOT_FOUND
  192. base: "./",
  193. worker: {
  194. rollupOptions: {
  195. // @pierre/diffs 的 worker 入口依赖 import 后注册 message 监听。
  196. // 它的 package sideEffects 漏声明会让生产 worker 子构建被摇成 0B;
  197. // 只关闭 worker 构建的摇树,避免影响主包。
  198. treeshake: false,
  199. },
  200. },
  201. build: {
  202. outDir: "../../out/renderer",
  203. emptyOutDir: true,
  204. // 生产包若直接暴露 sourceMappingURL,攻击者可在客户端侧还原业务源码。
  205. // 生产使用 hidden sourcemap:本地/发布流程保留 .map,不在产物里暴露映射入口。
  206. sourcemap: mode === "production" ? "hidden" : true,
  207. rollupOptions: {
  208. // 多入口:主窗口 + 进程监控 + CUA 权限拖拽浮窗
  209. input: {
  210. index: resolve(__dirname, "src/renderer/index.html"),
  211. "resource-manager": resolve(__dirname, "src/renderer/resource-manager.html"),
  212. "cua-permission-panel": resolve(__dirname, "src/renderer/cua-permission-panel.html"),
  213. },
  214. },
  215. },
  216. };
  217. });