build.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { chmod, readFile, rm } from "node:fs/promises";
  2. import { basename, dirname, relative, resolve } from "node:path";
  3. import { pathToFileURL } from "node:url";
  4. import { build } from "esbuild";
  5. import { stageBuiltinProviderConfig } from "../../../../../scripts/builtin-provider-config.mjs";
  6. import { stageThirdPartyNotices } from "../../../../../scripts/third-party-notices.mjs";
  7. const cliRoot = resolve(import.meta.dirname, "..");
  8. const projectRoot = resolve(cliRoot, "../..");
  9. const executableFileMode = 0o755;
  10. const packageJsonFile = "package.json";
  11. const rootPackageVersionError = "Root package.json must define a non-empty string version.";
  12. const desktopAgentBuildFlag = "--desktop-agent";
  13. export const resolveBuildExternal = () => ["@zcode/tui", "playwright-core", "koffi"];
  14. export const readZodBuildVersion = async () => {
  15. const sharedPackage = JSON.parse(
  16. await readFile(resolve(projectRoot, "../../packages/shared/package.json"), "utf8"),
  17. );
  18. const version = sharedPackage.dependencies?.zod;
  19. if (typeof version !== "string" || !/^4\.\d+\.\d+$/.test(version)) {
  20. throw new Error("packages/shared must pin one exact Zod v4 version.");
  21. }
  22. return version;
  23. };
  24. async function readZodPackage(file, cache) {
  25. for (
  26. let directory = dirname(file);
  27. directory !== dirname(directory);
  28. directory = dirname(directory)
  29. ) {
  30. if (basename(directory) !== "zod") continue;
  31. if (!cache.has(directory)) {
  32. cache.set(
  33. directory,
  34. readFile(resolve(directory, "package.json"), "utf8").then((text) => {
  35. const manifest = JSON.parse(text);
  36. if (manifest.name !== "zod" || typeof manifest.version !== "string") {
  37. throw new Error(`Invalid Zod package metadata: ${directory}`);
  38. }
  39. return { root: directory, version: manifest.version };
  40. }),
  41. );
  42. }
  43. return cache.get(directory);
  44. }
  45. return undefined;
  46. }
  47. function assertZodVersion(pkg, expectedV4Version) {
  48. if (pkg.version.startsWith("4.") && pkg.version !== expectedV4Version) {
  49. throw new Error(`Expected Zod v4 ${expectedV4Version}, found ${pkg.version}: ${pkg.root}`);
  50. }
  51. }
  52. export async function assertZodBundleIdentity(metafile, { workingDirectory, expectedV4Version }) {
  53. if (!metafile) throw new Error("Zod bundle validation requires an esbuild metafile.");
  54. const packages = new Map();
  55. const cache = new Map();
  56. for (const input of Object.keys(metafile.inputs)) {
  57. if (!/(?:^|[/\\])zod[/\\]/.test(input)) continue;
  58. const pkg = await readZodPackage(resolve(workingDirectory, input), cache);
  59. if (!pkg) continue;
  60. assertZodVersion(pkg, expectedV4Version);
  61. const previous = packages.get(pkg.version);
  62. if (previous && previous !== pkg.root) {
  63. throw new Error(`Duplicate Zod ${pkg.version} in bundle: ${previous}, ${pkg.root}`);
  64. }
  65. packages.set(pkg.version, pkg.root);
  66. }
  67. }
  68. export function createZodDedupePlugin({ expectedV4Version }) {
  69. return {
  70. name: "zcode-zod-dedupe",
  71. setup(builder) {
  72. const packages = new Map();
  73. const cache = new Map();
  74. // hoisted 安装可能给多个消费者留下字节相同、路径不同的 Zod。
  75. // 必须先按原消费者解析版本和 exports,再归并安装根,不能把 v3 alias 成 v4。
  76. builder.onResolve({ filter: /^zod(?:\/|$)/ }, async (args) => {
  77. if (args.pluginData?.zcodeZodResolving) return;
  78. const resolved = await builder.resolve(args.path, {
  79. importer: args.importer,
  80. resolveDir: args.resolveDir,
  81. kind: args.kind,
  82. pluginData: { zcodeZodResolving: true },
  83. });
  84. if (resolved.errors.length || resolved.external) return resolved;
  85. const pkg = await readZodPackage(resolved.path, cache);
  86. if (!pkg) throw new Error(`Cannot identify resolved Zod package: ${resolved.path}`);
  87. assertZodVersion(pkg, expectedV4Version);
  88. if (!packages.has(pkg.version)) packages.set(pkg.version, pkg.root);
  89. return {
  90. ...resolved,
  91. // 保留 exports 已选出的子入口和 .js/.cjs,不能再用 require.resolve 改写条件。
  92. path: resolve(packages.get(pkg.version), relative(pkg.root, resolved.path)),
  93. pluginData: args.pluginData,
  94. };
  95. });
  96. builder.onEnd(async (result) => {
  97. if (result.errors.length) return;
  98. await assertZodBundleIdentity(result.metafile, {
  99. workingDirectory: builder.initialOptions.absWorkingDir ?? process.cwd(),
  100. expectedV4Version,
  101. });
  102. });
  103. },
  104. };
  105. }
  106. export const readRootPackageVersion = async ({ root = projectRoot } = {}) => {
  107. const packageJson = JSON.parse(await readFile(resolve(root, packageJsonFile), "utf8"));
  108. if (typeof packageJson.version !== "string" || packageJson.version.trim() === "") {
  109. throw new Error(rootPackageVersionError);
  110. }
  111. return packageJson.version;
  112. };
  113. export const resolveBuildOptions = (args = [], env = process.env) => {
  114. const desktopAgent = args.includes(desktopAgentBuildFlag);
  115. const e2eCoverage = env.ZCODE_E2E_COVERAGE === "1";
  116. return {
  117. // desktop-agent 正常发布仍需压缩且不携带 map;E2E coverage
  118. // 专用构建必须保留原始符号和 source map,c8 才能回映到各 package 的 TS 源码。
  119. minify: desktopAgent && !e2eCoverage,
  120. sourcemap: e2eCoverage || !desktopAgent,
  121. };
  122. };
  123. export const resolveBuildAliases = ({
  124. cliDirectory = cliRoot,
  125. rootDirectory = projectRoot,
  126. } = {}) => ({
  127. "@zcode/shared-types": resolve(cliDirectory, "../shared-types/dist/index.js"),
  128. // plugin-host 启动只需这些独立入口,不能经通用 alias 重新求值 shared 总入口。
  129. "@zcode/shared/runtime-env": resolve(rootDirectory, "../../packages/shared/src/runtimeEnv.ts"),
  130. "@zcode/shared/mcp": resolve(rootDirectory, "../../packages/shared/src/mcp.ts"),
  131. "@zcode/shared/runtime-tool-runtime": resolve(
  132. rootDirectory,
  133. "../../packages/shared/src/runtime-tool-runtime.ts",
  134. ),
  135. // esbuild alias 按前缀改写导入路径。所有 shared subpath 必须在通用入口前精确声明,
  136. // 否则会被错误解析为 `src/index.ts/<subpath>` 并让 Desktop agent/SEA 打包失败。
  137. "@zcode/shared/zcode-protocol-v4": resolve(
  138. rootDirectory,
  139. "../../packages/shared/src/zcode-protocol-v4/index.ts",
  140. ),
  141. // ModelSelection schema 改为 shared 单一事实源后新增了本子路径引用。
  142. // esbuild alias 按前缀改写;若不在通用入口前精确声明,会错误拼到
  143. // `src/index.ts/model-selection`,导致 Desktop agent 打包失败。
  144. "@zcode/shared/model-selection": resolve(
  145. rootDirectory,
  146. "../../packages/shared/src/model-selection.ts",
  147. ),
  148. // 共享 Model Schema 新增的子路径不能被通用 alias 拼到 index.ts 后面。
  149. "@zcode/shared/model-config": resolve(rootDirectory, "../../packages/shared/src/model-config.ts"),
  150. // 进程异常边界在 bootstrap 之前使用该轻量契约,不能落入 shared 的通用前缀 alias。
  151. "@zcode/shared/process-diagnostic": resolve(
  152. rootDirectory,
  153. "../../packages/shared/src/process-diagnostic.ts",
  154. ),
  155. "@zcode/shared/config-schema": resolve(
  156. rootDirectory,
  157. "../../packages/shared/src/config-schema.ts",
  158. ),
  159. "@zcode/shared/workspace-hook-discovery": resolve(
  160. rootDirectory,
  161. "../../packages/shared/src/workspace-hook-discovery.ts",
  162. ),
  163. // review controller 直连 WorkspaceHookMutationError 需要本精确
  164. // alias(esbuild 前缀改写规则同上,漏声明会在 Desktop agent/SEA 打包失败)。
  165. "@zcode/shared/workspace-hook-mutation": resolve(
  166. rootDirectory,
  167. "../../packages/shared/src/workspace-hook-mutation.ts",
  168. ),
  169. // verdict 直连 import 需要本精确 alias;漏声明会被通用
  170. // "@zcode/shared" 前缀改写成 `src/index.ts/workspace-hook-review-monotonicity`,
  171. // Desktop agent/SEA 打包直接失败。
  172. "@zcode/shared/workspace-hook-review-monotonicity": resolve(
  173. rootDirectory,
  174. "../../packages/shared/src/workspace-hook-review-monotonicity.ts",
  175. ),
  176. // trust store 文件 schema 单源下沉后的新 subpath;漏声明会被通用
  177. // "@zcode/shared" 前缀改写成 `src/index.ts/workspace-hook-trust-store-file`,
  178. // Desktop agent/SEA 打包失败(同上两类既有规则)。
  179. "@zcode/shared/workspace-hook-trust-store-file": resolve(
  180. rootDirectory,
  181. "../../packages/shared/src/workspace-hook-trust-store-file.ts",
  182. ),
  183. "@zcode/shared/zcodeEndpoint": resolve(
  184. rootDirectory,
  185. "../../packages/shared/src/zcodeEndpoint.ts",
  186. ),
  187. // 插件 UI(MCP Apps)协议子路径:adapters/core/contracts 的 dist 引用它,同样要先于通用入口声明。
  188. "@zcode/shared/mcp-apps": resolve(rootDirectory, "../../packages/shared/src/mcp-apps/index.ts"),
  189. "@zcode/shared/node": resolve(rootDirectory, "../../packages/shared/src/node.ts"),
  190. // 通用 alias 会把子入口拼到 index.ts 后,发行实现必须独立解析。
  191. "@zcode/shared/request-security": resolve(
  192. rootDirectory,
  193. "../../packages/shared/src/request-security-edition/index.ts",
  194. ),
  195. "@zcode/shared": resolve(rootDirectory, "../../packages/shared/src/index.ts"),
  196. "@zcode/core": resolve(cliDirectory, "../core/dist/index.js"),
  197. });
  198. export const buildCli = async ({
  199. cliDirectory = cliRoot,
  200. rootDirectory = projectRoot,
  201. minify = false,
  202. sourcemap = true,
  203. env = process.env,
  204. version = readRootPackageVersion({
  205. root: rootDirectory,
  206. }),
  207. } = {}) => {
  208. const cliVersion = await version;
  209. const outfile = resolve(cliDirectory, "dist/zcode.cjs");
  210. const sourcemapFile = `${outfile}.map`;
  211. await stageBuiltinProviderConfig({
  212. root: resolve(rootDirectory, "../.."),
  213. directory: resolve(cliDirectory, "dist/provider"),
  214. env,
  215. });
  216. await build({
  217. banner: {
  218. js: "#!/usr/bin/env node",
  219. },
  220. bundle: true,
  221. define: {
  222. __CLI_VERSION__: JSON.stringify(cliVersion),
  223. },
  224. entryPoints: [resolve(cliDirectory, "src/main.ts")],
  225. // Ink 7 and yoga-layout use top-level await, so the CJS CLI bundle loads the TUI
  226. // through Node's native dynamic import path instead of forcing esbuild to lower it.
  227. // playwright-core 依赖运行时 package assets 与 require.resolve,相比内联 bundle 必须保持外置。
  228. // managed headless adapter 只在显式 --browser-use=headless 时延迟加载,不影响 app-server/普通 CLI。
  229. // koffi 会按当前平台动态 require 原生 `.node` 文件;内联会让 esbuild 遍历所有
  230. // 平台产物并直接报 "No loader is configured for .node"。运行时仍从依赖包加载,
  231. // SEA 资源由 build-sea 的 native asset 收集阶段单独处理。
  232. external: resolveBuildExternal(),
  233. format: "cjs",
  234. // 桌面 app 集成只内置 zcode.cjs,旧 desktop-agent 构建复用 CLI 调试产物,
  235. // 未压缩且会留下指向未随包复制的 sourcemap。桌面 agent 模式压缩 JS,同时保留
  236. // 函数/类名,避免依赖 name 的诊断与注册逻辑被 esbuild 标识符压缩影响。
  237. keepNames: minify,
  238. legalComments: "none",
  239. logLevel: "info",
  240. minify,
  241. metafile: true,
  242. plugins: [createZodDedupePlugin({ expectedV4Version: await readZodBuildVersion() })],
  243. outfile,
  244. platform: "node",
  245. sourcemap,
  246. // target 取所有承载运行时里最低的 Node 版本:桌面用 Electron 内置 Node 24,
  247. // 远端 SSH 复用已部署的独立 Node v22.16 跑同一份 zcode.cjs。降到 node22 保证这份产物
  248. // 在两端都不会用到目标运行时不支持的语法/特性。
  249. target: "node22",
  250. alias: resolveBuildAliases({ cliDirectory, rootDirectory }),
  251. });
  252. if (!sourcemap) {
  253. await rm(sourcemapFile, { force: true });
  254. }
  255. await chmod(outfile, executableFileMode);
  256. // zcode.cjs 内联了第三方代码;dist 旁的伴随声明供发行 CLI 与统一分发包(build-zcode)复制。
  257. await stageThirdPartyNotices(resolve(cliDirectory, "dist"), resolve(rootDirectory, "../.."));
  258. };
  259. const entryPath = process.argv[1];
  260. if (entryPath && import.meta.url === pathToFileURL(entryPath).href) {
  261. await buildCli(resolveBuildOptions(process.argv.slice(2)));
  262. }