electron-builder.config.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. /* eslint-disable max-lines -- Electron Builder config keeps related packaging hooks together so build order stays explicit. */
  2. import { cpSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
  3. import { readdir, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join, resolve } from "node:path";
  6. import { createRequire } from "node:module";
  7. import { runCommand, runCommandAndReadStdout } from "../../scripts/spawn-command.mjs";
  8. import { loadBuiltinProviderConfig } from "../../scripts/builtin-provider-config.mjs";
  9. import { noticesFileName, stageElectronNotices } from "../../scripts/third-party-notices.mjs";
  10. import { resolveNativeSearchReleasePlan } from "../../scripts/native-search-tools-config.mjs";
  11. import { getBuildMetadata } from "./scripts/build-metadata.mjs";
  12. import { collectRuntimeModuleClosureEntries } from "./scripts/runtime-dependency-closure.mjs";
  13. import {
  14. resolvePackagedNodePtyPrebuildPath,
  15. restoreTargetNodePtyPrebuild,
  16. } from "./scripts/node-pty-package-assets.mjs";
  17. import { cleanupPackagedSourcemaps } from "./scripts/packaged-sourcemap-cleanup.mjs";
  18. import { getTargetPlatform } from "./scripts/target-platform.mjs";
  19. import {
  20. resolveDesktopArtifactSuffix,
  21. resolveDesktopProductIdentity,
  22. } from "./scripts/desktop-product-identity.mjs";
  23. import { verifyStagedKoffi } from "./scripts/koffi-package-assets.mjs";
  24. const ELECTRON_BUILDER_ARCH = {
  25. 1: "x64",
  26. 3: "arm64",
  27. };
  28. function resolveElectronBuilderWindowsTarget({
  29. electronPlatformName,
  30. arch,
  31. configuredTargetPlatform,
  32. }) {
  33. if (electronPlatformName !== "win32") {
  34. throw new Error(
  35. `[electron-builder.config] context platform is not win32: ${String(electronPlatformName)}`,
  36. );
  37. }
  38. const actualArch = ELECTRON_BUILDER_ARCH[arch];
  39. if (!actualArch) {
  40. throw new Error(
  41. `[electron-builder.config] unsupported electron-builder Windows architecture: ${String(arch)}`,
  42. );
  43. }
  44. const actualTarget = {
  45. os: "win32",
  46. arch: actualArch,
  47. key: `win32-${actualArch}`,
  48. };
  49. if (
  50. configuredTargetPlatform?.os !== actualTarget.os ||
  51. configuredTargetPlatform?.arch !== actualTarget.arch ||
  52. configuredTargetPlatform?.key !== actualTarget.key
  53. ) {
  54. throw new Error(
  55. `[electron-builder.config] configured target ${String(configuredTargetPlatform?.key)} does not match electron-builder target ${actualTarget.key}`,
  56. );
  57. }
  58. return actualTarget;
  59. }
  60. import {
  61. findDesktopNativePackageViolations,
  62. createDesktopNativePackagePrunePatterns,
  63. parseAsarListWithPackState,
  64. } from "./scripts/desktop-native-package-policy.mjs";
  65. import { replaceAppAsarFromStaging } from "./scripts/app-asar-repack.mjs";
  66. import {
  67. patchNsisInstallSectionFile,
  68. restoreNsisInstallSectionFileSync,
  69. } from "./scripts/patch-nsis-install-section.mjs";
  70. const buildMetadata = getBuildMetadata();
  71. const targetPlatform = getTargetPlatform();
  72. const builtinProviderConfig = await loadBuiltinProviderConfig();
  73. const desktopProductIdentity = resolveDesktopProductIdentity({
  74. ...process.env,
  75. ZCODE_ENV: builtinProviderConfig.environment,
  76. });
  77. const nativeSearchReleasePlan = resolveNativeSearchReleasePlan({
  78. platform: targetPlatform.os,
  79. arch: targetPlatform.arch,
  80. });
  81. const rawMacSigningIdentity = process.env.APPLE_SIGNING_IDENTITY || process.env.CSC_NAME;
  82. const macSigningIdentity =
  83. rawMacSigningIdentity?.replace(/^Developer ID Application:\s*/, "") ?? null;
  84. const shouldEnableMacSigning =
  85. process.env.ZCODE_ENABLE_MAC_SIGN === "1" && Boolean(macSigningIdentity);
  86. const workspaceRoot = resolve(import.meta.dirname, "../..");
  87. const desktopPackageRoot = import.meta.dirname;
  88. const runtimeModuleLookupRoots = [
  89. desktopPackageRoot,
  90. workspaceRoot,
  91. resolve(desktopPackageRoot, "node_modules", ".pnpm", "node_modules"),
  92. resolve(workspaceRoot, "node_modules", ".pnpm", "node_modules"),
  93. ];
  94. const desktopDistDir = process.env.ZCODE_DESKTOP_DIST_DIR || "dist";
  95. const DEFAULT_ELECTRON_MIRROR = "https://npmmirror.com/mirrors/electron/";
  96. // `pnpm exec asar` 依赖 `.bin/asar`,但 @electron/asar 仅是 electron-builder 传递依赖时,
  97. // Linux CI(pnpm hoisted)往往解析不到该二进制,`asar list` 未运行即 exit 1。
  98. // 显式依赖 @electron/asar 并用 Node 直接执行 CLI,避免跨平台找不齐 shim。
  99. const requireFromConfig = createRequire(import.meta.url);
  100. let nsisInstallSectionPatched = false;
  101. let nsisInstallSectionOriginalSource = null;
  102. let nsisInstallSectionPath = null;
  103. const desktopElectronVersion = requireFromConfig("./package.json").devDependencies.electron;
  104. const asarCliPath = resolve(
  105. dirname(requireFromConfig.resolve("@electron/asar/package.json")),
  106. "bin",
  107. "asar.js",
  108. );
  109. const REQUIRED_ASAR_RUNTIME_MODULES = [
  110. "module-details-from-path",
  111. "@opentelemetry/api-logs",
  112. // Bugfix: telemetry 的 OTLP exporter 会在启动阶段加载 sdk-metrics。pnpm 开发态可从
  113. // workspace 根目录解析,但 electron-builder 不会稳定复制这条 hoisted 依赖,导致安装包启动即崩溃。
  114. // 将 sdk-metrics 作为闭包根注入,同时递归带齐它的 OpenTelemetry 运行时依赖。
  115. "@opentelemetry/sdk-metrics",
  116. // OTLP proto 导出链闭包根:递归带齐 otlp-transformer/protobufjs 及其子依赖,
  117. // 否则 hoisted 布局漏 protobufjs 时已安装应用启动即报 Cannot find module 'protobufjs/minimal'。
  118. "@opentelemetry/exporter-trace-otlp-proto",
  119. "@opentelemetry/exporter-metrics-otlp-proto",
  120. "pngjs",
  121. // @zcode/services 的代理连通性探测会动态 require("undici") 取 ProxyAgent。
  122. // tsup 虽然把 services 代码并进了主/host 产物,但不会把这个运行时 require 的包内联进去,
  123. // electron-builder 产物又可能漏掉 hoisted 的 undici,最终 mac 安装包启动即报 Cannot find module "undici"。
  124. // 这里把 undici 和其他兜底依赖一样强制注入 app.asar,避免用户在已安装应用里主进程直接崩溃。
  125. "undici",
  126. // node-forge 一直只写在 bundle.mjs 的校验名单里,靠 electron-builder 自己打进 app.asar;
  127. // 这与 yauzl 漏 pend 是同一类隐患——校验要求的模块必须有人负责补齐。node-forge 无子依赖,
  128. // 已在产物里时 afterPack 扫描会跳过它,不改变现有打包结果。
  129. "node-forge",
  130. // 2.7.0 起 services 新增反馈日志压缩链路并引入 yazl;2.6.0 没有这条启动期依赖,
  131. // pnpm hoisted 布局下 yazl 可能进了 app.asar,但子依赖 buffer-crc32 没有稳定随包进入产物;
  132. // 这里显式以 yazl 作为闭包根注入,让递归依赖收集把 ZIP 打包链路所需依赖一起补齐。
  133. "yazl",
  134. // yauzl 成为 desktop/services 的直接生产依赖后,pnpm list --prod 会把顶层 yauzl 节点
  135. // 去重成没有子依赖的空节点;electron-builder 的 pnpm collector 以先登记的空节点为准,
  136. // 跳过后面带完整子树的那个,于是 app.asar 里有 yauzl 却没有它的运行时依赖 pend,
  137. // 要到 bundle 校验阶段才报「缺少运行时依赖 pend」。这里以 yauzl 作为闭包根注入,
  138. // 与 bundle.mjs 的校验名单保持一致,让递归依赖收集把 pend 一起补进产物。
  139. "yauzl",
  140. // 生产态里 ssh2 虽然被打进 app.asar,但它的依赖链偶发被 electron-builder 漏拷。
  141. // 已出现线上报错 Cannot find module 'asn1'(Require stack: ssh2 keyParser)。
  142. // 这里把 ssh2 关键依赖链一起注入,避免远程 SSH 连接在已安装应用里因缺包直接失败。
  143. "asn1",
  144. "bcrypt-pbkdf",
  145. "tweetnacl",
  146. // electron-updater → builder-util-runtime → debug 运行时 require("ms")。
  147. // pnpm hoisted 布局下 electron-builder 偶发漏拷这个叶子依赖;3.4.0(ci/cua-v0.3.17 打的)
  148. // 已在线上触发安装包启动即报 Cannot find module 'ms'(Require stack: debug/src/common.js),
  149. // 自动更新链路直接崩。ms 是叶子包,显式注入即可让 debug 在 app.asar 内稳定解析。
  150. "ms",
  151. ];
  152. // pacman 依赖必须使用 Arch 官方仓库中的包名。electron-builder 的历史默认集合包含
  153. // 已移除的 libappindicator-gtk3/http-parser,且缺少 Electron 实际需要的运行库;显式
  154. // 维护最小运行时闭包,避免 pacman -U 无法解析依赖或启动时才暴露缺库。
  155. const PACMAN_RUNTIME_DEPENDENCIES = [
  156. "gtk3",
  157. "nss",
  158. "libxss",
  159. "libxtst",
  160. "libnotify",
  161. "alsa-lib",
  162. "mesa",
  163. "xdg-utils",
  164. ];
  165. const WINDOWS_INSTALL_MANIFEST_NAME = ".zcode-install-manifest";
  166. async function writeWindowsInstallManifest(context) {
  167. if (context.electronPlatformName !== "win32") return;
  168. const root = context.appOutDir;
  169. const files = [];
  170. const visit = async (directory, relativeDirectory = "") => {
  171. for (const entry of await readdir(directory, { withFileTypes: true })) {
  172. const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;
  173. const absolutePath = join(directory, entry.name);
  174. if (entry.isDirectory()) {
  175. await visit(absolutePath, relativePath);
  176. } else if (entry.isFile() || entry.isSymbolicLink()) {
  177. files.push(relativePath.replaceAll("/", "\\"));
  178. }
  179. }
  180. };
  181. await visit(root);
  182. files.sort();
  183. await writeFile(join(root, WINDOWS_INSTALL_MANIFEST_NAME), `${files.join("\r\n")}\r\n`, "utf8");
  184. }
  185. function resolveElectronDownloadMirror(env = process.env) {
  186. const existingMirror =
  187. env.ZCODE_ELECTRON_RUNTIME_MIRROR ||
  188. env.NPM_CONFIG_ELECTRON_MIRROR ||
  189. env.npm_config_electron_mirror ||
  190. env.npm_package_config_electron_mirror ||
  191. env.ELECTRON_MIRROR;
  192. if (existingMirror?.trim()) {
  193. return existingMirror.trim();
  194. }
  195. return DEFAULT_ELECTRON_MIRROR;
  196. }
  197. const commandStdoutMaxBuffer = 64 * 1024 * 1024;
  198. // 产物后缀只标记后端环境(_TEST);身份靠 productName 区分,生产后端的 Preview 包没有后缀。
  199. const desktopArtifactEnvSuffix = resolveDesktopArtifactSuffix(process.env);
  200. // Preview 是内部签名测试包。CI 明确打开 macOS 签名时若没有身份,必须在生成未签名包前失败,
  201. // 避免“产物存在”被误认为已经走完和生产版相同的签名链路。
  202. if (
  203. desktopProductIdentity.flavor === "preview" &&
  204. process.env.ZCODE_ENABLE_MAC_SIGN === "1" &&
  205. !macSigningIdentity
  206. ) {
  207. throw new Error(
  208. "ZCode Preview macOS packaging requires APPLE_SIGNING_IDENTITY or CSC_NAME when ZCODE_ENABLE_MAC_SIGN=1",
  209. );
  210. }
  211. const PACKAGING_PRUNE_PATTERNS = [
  212. "!**/*.map",
  213. "!**/*.pdb",
  214. "!**/__tests__/**",
  215. "!**/test/**",
  216. "!**/tests/**",
  217. "!**/example/**",
  218. "!**/examples/**",
  219. "!**/README*",
  220. "!**/CHANGELOG*",
  221. "!**/CONTRIBUTING*",
  222. "!**/CODE_OF_CONDUCT*",
  223. "!**/SECURITY*",
  224. ];
  225. function buildDesktopArtifactName(platformName, extension = "${ext}") {
  226. // 测试环境产物必须和正式安装包文件名区分,避免上传、下载或人工验收时混用。
  227. return `\${productName}-\${version}-${platformName}-\${arch}${desktopArtifactEnvSuffix}.${extension}`;
  228. }
  229. function runAsarCommand(args) {
  230. runCommand(process.execPath, [asarCliPath, ...args], {
  231. cwd: import.meta.dirname,
  232. env: process.env,
  233. });
  234. }
  235. function runAsarCommandAndReadStdout(args) {
  236. return runCommandAndReadStdout(process.execPath, [asarCliPath, ...args], {
  237. cwd: import.meta.dirname,
  238. env: process.env,
  239. // app.asar 在当前桌面包体积较大,asar list 输出可能超过默认缓冲并触发 ENOBUFS。
  240. // 这里显式放大缓冲,避免“为了判断是否需要注入”反而把打包流程误判失败。
  241. maxBuffer: commandStdoutMaxBuffer,
  242. stdio: ["ignore", "pipe", "inherit"],
  243. });
  244. }
  245. function runTimedSync(label, fn) {
  246. const startMs = Date.now();
  247. console.log(`[ci][timer] ${label} start`);
  248. try {
  249. return fn();
  250. } finally {
  251. console.log(`[ci][timer] ${label} end duration_ms=${Date.now() - startMs}`);
  252. }
  253. }
  254. async function runTimedAsync(label, fn) {
  255. const startMs = Date.now();
  256. console.log(`[ci][timer] ${label} start`);
  257. try {
  258. return await fn();
  259. } finally {
  260. console.log(`[ci][timer] ${label} end duration_ms=${Date.now() - startMs}`);
  261. }
  262. }
  263. function resolveAppAsarPath(context) {
  264. if (context.electronPlatformName === "darwin") {
  265. const appName = `${context.packager?.appInfo?.productFilename ?? "ZCode"}.app`;
  266. return resolve(context.appOutDir, appName, "Contents", "Resources", "app.asar");
  267. }
  268. return resolve(context.appOutDir, "resources", "app.asar");
  269. }
  270. function resolvePackagedResourcesDir(context) {
  271. if (context.electronPlatformName === "darwin") {
  272. const appName = `${context.packager?.appInfo?.productFilename ?? "ZCode"}.app`;
  273. return resolve(context.appOutDir, appName, "Contents", "Resources");
  274. }
  275. return resolve(context.appOutDir, "resources");
  276. }
  277. function normalizeAsarEntry(entry) {
  278. return entry.trim().replaceAll("\\", "/");
  279. }
  280. function resolveMissingRuntimeModules(appAsarPath) {
  281. const asarEntries = runAsarCommandAndReadStdout(["list", appAsarPath])
  282. .split("\n")
  283. .map(normalizeAsarEntry)
  284. .filter(Boolean);
  285. const asarEntrySet = new Set(asarEntries);
  286. const runtimeModules = collectRuntimeModuleClosureEntries(
  287. REQUIRED_ASAR_RUNTIME_MODULES,
  288. runtimeModuleLookupRoots,
  289. );
  290. const resolvableRuntimeModules = runtimeModules.filter((entry) => {
  291. if (!entry.sourceModulePath) {
  292. // 不同平台/安装布局下,部分运行时依赖可能被裁剪或未落到本次打包工作区。
  293. // 之前这里直接在 copy 阶段抛错会中断整个平台出包;改为记录告警并跳过该模块,
  294. // 让 afterPack 只处理当前环境确实可解析的依赖,避免 CI 因单个可选依赖缺失全量失败。
  295. console.warn(
  296. `[afterPack] runtime module not found, skip injection: ${entry.moduleName}; searched=${runtimeModuleLookupRoots
  297. .map((lookupRoot) => resolve(lookupRoot, "node_modules", entry.moduleName))
  298. .join(", ")}`,
  299. );
  300. return false;
  301. }
  302. return true;
  303. });
  304. return resolvableRuntimeModules.filter((entry) => {
  305. const { moduleName } = entry;
  306. const moduleRoot = `/node_modules/${moduleName}`;
  307. if (asarEntrySet.has(moduleRoot)) {
  308. return false;
  309. }
  310. for (const entry of asarEntrySet) {
  311. if (entry.startsWith(`${moduleRoot}/`)) {
  312. return false;
  313. }
  314. }
  315. return true;
  316. });
  317. }
  318. async function injectHoistedRuntimeModulesIntoAsar(context) {
  319. const appAsarPath = resolveAppAsarPath(context);
  320. if (!existsSync(appAsarPath)) {
  321. throw new Error(`打包产物缺少 app.asar: ${appAsarPath}`);
  322. }
  323. const missingRuntimeModules = runTimedSync("afterPack:scan-missing-runtime-modules", () =>
  324. resolveMissingRuntimeModules(appAsarPath),
  325. );
  326. if (missingRuntimeModules.length === 0) {
  327. // 之前 afterPack 每次都完整 extract/pack app.asar,即使运行时依赖已经齐全也会重复重写。
  328. // 这会把每次打包固定拉长十几秒到几十秒。先做缺失扫描,只有真的缺包才执行重写流程。
  329. console.log("[afterPack] runtime modules already complete, skip app.asar rewrite");
  330. return;
  331. }
  332. console.log(`[afterPack] missing runtime modules count=${missingRuntimeModules.length}`);
  333. // CI 会把 TMPDIR 指到项目内 .tmp,GitLab get_sources/clean 可能在脚本启动前清掉该目录。
  334. // afterPack 里重写 app.asar 同样依赖 mkdtempSync,必须自己兜底创建父目录,避免后续签名阶段只看到 .app 消失。
  335. mkdirSync(tmpdir(), { recursive: true });
  336. const stagingDir = mkdtempSync(resolve(tmpdir(), "zcode-app-asar-"));
  337. try {
  338. runTimedSync("afterPack:asar-extract", () =>
  339. runAsarCommand(["extract", appAsarPath, stagingDir]),
  340. );
  341. const stagingNodeModulesDir = resolve(stagingDir, "node_modules");
  342. mkdirSync(stagingNodeModulesDir, { recursive: true });
  343. runTimedSync("afterPack:copy-runtime-modules", () => {
  344. for (const runtimeModule of missingRuntimeModules) {
  345. const { moduleName, sourceModulePath } = runtimeModule;
  346. const targetModulePath = resolve(stagingNodeModulesDir, moduleName);
  347. if (!sourceModulePath) {
  348. throw new Error(
  349. `未找到运行时依赖 ${moduleName},已搜索: ${runtimeModuleLookupRoots
  350. .map((lookupRoot) => resolve(lookupRoot, "node_modules", moduleName))
  351. .join(", ")}`,
  352. );
  353. }
  354. // pnpm hoisted 布局下,electron-builder 可能把主包打进 app.asar,
  355. // 却漏掉它解析时还要去根 node_modules 找的运行时依赖。
  356. // 之前 require-in-the-middle 漏过 module-details-from-path,这次 @fiahfy/icns 又漏了 pngjs,
  357. // 最终都会在已安装应用里触发 Cannot find module 并让主进程启动直接崩溃。
  358. // 这里按 package.json 递归补齐依赖闭包,避免每次只补一个缺失包、上线后再暴露下一个子依赖。
  359. // 只靠 package.json 显式依赖、本包 node_modules 镜像、files include 都没让它稳定进 asar,
  360. // 所以在 afterPack 阶段直接重写 app.asar,先把这些运行时包补进去,再交给后续签名和出包。
  361. mkdirSync(dirname(targetModulePath), { recursive: true });
  362. rmSync(targetModulePath, { force: true, recursive: true });
  363. cpSync(sourceModulePath, targetModulePath, { recursive: true });
  364. }
  365. });
  366. await runTimedAsync("afterPack:asar-pack", () =>
  367. replaceAppAsarFromStaging({
  368. sourceDir: stagingDir,
  369. appAsarPath,
  370. targetPlatformKey: targetPlatform.key,
  371. runAsarCommand,
  372. }),
  373. );
  374. } finally {
  375. rmSync(stagingDir, { force: true, recursive: true });
  376. }
  377. }
  378. async function stripPackagedSourcemapReferences(context) {
  379. // electron-builder 的 files 规则能排除 .map 文件,但无法删除 JS/CSS 末尾
  380. // 指向 sourcemap 的注释;afterPack 注入运行时依赖后也可能重新带入第三方 sourceMappingURL。
  381. // 这里统一清理 app.asar 与 unpacked/extraResources,保证最终发布包不暴露 sourcemap 路径入口。
  382. await cleanupPackagedSourcemaps({
  383. appAsarPath: resolveAppAsarPath(context),
  384. resourcesDir: resolvePackagedResourcesDir(context),
  385. runAsarCommand,
  386. runTimedSync,
  387. runTimedAsync,
  388. replaceAppAsarFromStaging: ({ sourceDir, appAsarPath }) =>
  389. replaceAppAsarFromStaging({
  390. sourceDir,
  391. appAsarPath,
  392. targetPlatformKey: targetPlatform.key,
  393. runAsarCommand,
  394. }),
  395. });
  396. }
  397. function assertPackagedNativeResourcePolicy(context) {
  398. const appAsarPath = resolveAppAsarPath(context);
  399. const entries = parseAsarListWithPackState(
  400. runAsarCommandAndReadStdout(["list", "--is-pack", appAsarPath]),
  401. );
  402. const violations = findDesktopNativePackageViolations(entries, targetPlatform.key);
  403. if (violations.length > 0) {
  404. // supportedArchitectures 允许工作区准备多平台依赖,但安装包只能携带目标平台资源。
  405. // 之前 Canvas 和 node-pty 的其他平台 native 被同时写进 asar/unpacked,包体被放大数百 MiB。
  406. throw new Error(`桌面 native 资源边界校验失败:\n- ${violations.join("\n- ")}`);
  407. }
  408. }
  409. function assertPackagedNodePtyPrebuild(context) {
  410. const targetBinaryPath = resolvePackagedNodePtyPrebuildPath({
  411. resourcesDir: resolvePackagedResourcesDir(context),
  412. platformKey: targetPlatform.key,
  413. });
  414. if (!existsSync(targetBinaryPath))
  415. throw new Error(`node-pty 预编译产物缺失: ${targetBinaryPath}`);
  416. }
  417. /** @type {import("electron-builder").Configuration} */
  418. export default {
  419. appId: desktopProductIdentity.appId,
  420. // Linux deb 打包(fpm)会校验 package metadata 中的 homepage、author.email、maintainer。
  421. // CI 环境下若这些字段缺失会在产物阶段直接失败。这里统一在构建配置补齐,避免依赖外部注入。
  422. extraMetadata: {
  423. version: buildMetadata.appVersion,
  424. zcodeProductFlavor: desktopProductIdentity.flavor,
  425. homepage: "https://zcode.z.ai",
  426. author: {
  427. name: "ZCode",
  428. email: "dev@zcode.z.ai",
  429. },
  430. },
  431. // macOS 签名阶段会对 Electron Framework 下每个语言包逐个 codesign。
  432. // 默认全量语言会产生大量 locale.pak 签名调用,显著拉长打包时长。
  433. // 这里仅保留当前产品必需语言,减少签名文件数并缩短 CI 总耗时。
  434. electronLanguages: ["en-US", "zh-CN"],
  435. // pnpm workspace + semver range(如 ^41.0.3)下,electron-builder
  436. // 有时无法从依赖树里稳定推导出 Electron 版本,导致 bundle 直接中断。
  437. // 显式写死当前桌面端使用的 Electron 版本,避免打包阶段再做不可靠的猜测。
  438. electronVersion: "41.0.3",
  439. electronDownload: {
  440. // ELECTRON_MIRROR 是 @electron/get 的全局环境变量,会覆盖 dmg-builder 等
  441. // generic artifact 自己传入的 mirrorOptions,导致 builder 辅助包被错误拼到 Electron runtime 镜像目录。
  442. // 这里改用 electron-builder 的专用配置,只影响 Electron runtime zip 下载。
  443. mirror: resolveElectronDownloadMirror(),
  444. },
  445. productName: desktopProductIdentity.productName,
  446. directories: {
  447. // macOS arm64/x64 CI 可能共享同一个 checkout 并行打包。
  448. // 输出根目录允许按架构隔离,避免一个 job 清理 dist 时删除另一个 job 正在签名的 .app。
  449. output: desktopDistDir,
  450. buildResources: "build",
  451. },
  452. files: [
  453. "out/**/*",
  454. "package.json",
  455. // app.asar 会把桌面端运行时 node_modules 一并打进去,依赖包自带的 .map / README
  456. // 默认也会原样进入安装包。这里统一在主包层做一次裁剪,只移除非运行时文件,LICENSE 继续保留。
  457. ...PACKAGING_PRUNE_PATTERNS,
  458. ...createDesktopNativePackagePrunePatterns(targetPlatform.key),
  459. "!node_modules/@zcode/**",
  460. "!node_modules/react/**",
  461. "!node_modules/react-dom/**",
  462. ],
  463. asarUnpack: [
  464. // node-pty 的 target prebuild 还包含 spawn-helper / winpty-agent.exe 等辅助可执行文件,
  465. // 整个目标目录必须 unpack;其他平台目录已由 files 规则裁剪。
  466. `node_modules/node-pty/prebuilds/${targetPlatform.key}/**`,
  467. ],
  468. beforePack: async (context) => {
  469. runTimedSync("beforePack:restoreTargetNodePtyPrebuild", () =>
  470. restoreTargetNodePtyPrebuild({ desktopPackageRoot, targetPlatform }),
  471. );
  472. if (context.electronPlatformName !== "win32" || nsisInstallSectionPatched) {
  473. return;
  474. }
  475. nsisInstallSectionPath = resolve(
  476. dirname(requireFromConfig.resolve("app-builder-lib/package.json")),
  477. "templates",
  478. "nsis",
  479. "installSection.nsh",
  480. );
  481. const patchResult = await runTimedAsync("beforePack:patchNsisInstallSection", () =>
  482. patchNsisInstallSectionFile(nsisInstallSectionPath),
  483. );
  484. nsisInstallSectionPatched = true;
  485. nsisInstallSectionOriginalSource = patchResult.originalSource;
  486. if (patchResult.changed) {
  487. // electron-builder 在当前进程内随后才会编译 NSIS;等整个构建进程退出后恢复 node_modules
  488. // 中的上游模板,避免把一次打包的定制内容永久留在开发依赖里。
  489. process.once("exit", () => {
  490. restoreNsisInstallSectionFileSync({
  491. filePath: nsisInstallSectionPath,
  492. originalSource: nsisInstallSectionOriginalSource,
  493. });
  494. });
  495. }
  496. },
  497. afterExtract: async (context) => {
  498. // 修复:macOS 重命名阶段会删除归档顶层许可证,必须在 afterExtract 保留目标平台原文。
  499. const framework = context.packager.info.framework;
  500. const resources =
  501. context.electronPlatformName === "darwin"
  502. ? resolve(context.appOutDir, framework.distMacOsAppName, "Contents", "Resources")
  503. : resolve(context.appOutDir, "resources");
  504. await stageElectronNotices(context.appOutDir, resources, framework.version);
  505. },
  506. afterPack: async (context) => {
  507. const actualWindowsTarget =
  508. context.electronPlatformName === "win32"
  509. ? resolveElectronBuilderWindowsTarget({
  510. electronPlatformName: context.electronPlatformName,
  511. arch: context.arch,
  512. configuredTargetPlatform: targetPlatform,
  513. })
  514. : null;
  515. await runTimedAsync("afterPack:injectHoistedRuntimeModulesIntoAsar", () =>
  516. injectHoistedRuntimeModulesIntoAsar(context),
  517. );
  518. await runTimedAsync("afterPack:stripPackagedSourcemapReferences", () =>
  519. stripPackagedSourcemapReferences(context),
  520. );
  521. runTimedSync("afterPack:assertPackagedNativeResourcePolicy", () =>
  522. assertPackagedNativeResourcePolicy(context),
  523. );
  524. runTimedSync("afterPack:assertPackagedNodePtyPrebuild", () =>
  525. assertPackagedNodePtyPrebuild(context),
  526. );
  527. if (actualWindowsTarget) {
  528. await runTimedAsync("afterPack:writeWindowsInstallManifest", () =>
  529. writeWindowsInstallManifest(context),
  530. );
  531. }
  532. },
  533. extraResources: [
  534. { from: resolve(workspaceRoot, noticesFileName), to: noticesFileName },
  535. ...(targetPlatform.os === "darwin"
  536. ? [
  537. {
  538. // CUA 权限浮窗的吸附数据源(CGWindowListCopyWindowInfo,不需要任何 TCC 权限)。
  539. // 主进程按 process.resourcesPath 解析;缺失时 watcher fail-open,浮窗仍可用
  540. // 只是不吸附,所以这里不做存在性断言。
  541. from: "resources/macos-window-bounds/zcode-window-bounds",
  542. to: "macos-window-bounds/zcode-window-bounds",
  543. },
  544. ]
  545. : []),
  546. {
  547. // 正式包不能依赖仓库目录读取社区、反馈等内置兜底配置。
  548. // 显式放入 resources/config,与主进程的 process.resourcesPath 解析保持一致。
  549. from: resolve(workspaceRoot, "config/default.json"),
  550. to: "config/default.json",
  551. },
  552. {
  553. // Provider Registry 的 ZCode Built-in Config 是静态 Provider/Model 事实的唯一内置来源。
  554. // 显式随包发布,避免正式 Host 回退到旧 Catalog/Preset hardcode。
  555. from: builtinProviderConfig.sourcePath,
  556. to: "config/provider/zcode-builtin.json",
  557. },
  558. {
  559. // 应用图标:打包后放入 resources 目录,主进程通过 process.resourcesPath 加载
  560. from: "build/icon.png",
  561. to: "icon.png",
  562. },
  563. ...(targetPlatform.os === "linux"
  564. ? [
  565. {
  566. // AppImage 用户级 hicolor 图标安装使用真实 512x512 资源,避免目录标称尺寸和 PNG IHDR 不一致。
  567. from: "build/icons/512x512.png",
  568. to: "icon_512x512.png",
  569. },
  570. ]
  571. : []),
  572. {
  573. // Windows 独立图标:开发态和打包态都统一走同一套任务栏/窗口图标资源。
  574. from: "build/icon_windows.png",
  575. to: "icon_windows.png",
  576. },
  577. ...(targetPlatform.os === "win32"
  578. ? [
  579. {
  580. // Windows 托盘图标:Tray 在打包态只能稳定读取 resources 下的独立资源。
  581. // 这里不复用窗口 PNG,避免通知区域在高 DPI 下退化成模糊缩放图。
  582. from: "build/icon.ico",
  583. to: "tray_icon.ico",
  584. },
  585. ]
  586. : []),
  587. {
  588. // agent 运行时资产,打包到 resources/glm。
  589. // 桌面端内置的是 agent 的 JS bundle(glm/zcode.cjs,由 prepare:agent-bundle 生成),
  590. // Host 进程用 app 自带的 Electron Node runtime(ELECTRON_RUN_AS_NODE)执行 `zcode.cjs app-server --stdio`,
  591. // 不再随包内置独立 Node 二进制。远端 SSH/WSL 仍走原生二进制(无 Electron)。
  592. from: `bundled-agents/${targetPlatform.key}/glm`,
  593. to: "glm",
  594. filter: ["**/*", "!**/*.map"],
  595. },
  596. {
  597. // agent shell 之前完全依赖宿主系统 PATH,GUI 启动时经常拿不到用户自己装的 rg。
  598. // 这里把 ripgrep 作为桌面端内置 runtime tool 打进 resources/tools,
  599. // 后续 host/server 把该目录追加到 PATH;用户版本优先,缺失时再由随包 rg 兜底。
  600. from: `bundled-tools/${targetPlatform.key}/ripgrep`,
  601. to: "tools/ripgrep",
  602. filter: ["**/*"],
  603. },
  604. ...nativeSearchReleasePlan.extraResourceToolIds.map((toolId) => ({
  605. from: `bundled-tools/${targetPlatform.key}/${toolId}`,
  606. to: `tools/${toolId}`,
  607. filter: ["**/*"],
  608. })),
  609. ],
  610. // postinstall 会先优先复用 node-pty 自带的 Windows 预编译产物,其他平台再按需 electron-rebuild。
  611. // 打包阶段统一复用安装时准备好的原生文件,避免 electron-builder 再触发一轮不受控的本地编译。
  612. npmRebuild: false,
  613. // OAuth deep link 协议注册(macOS 打包后需要 Info.plist 中声明 CFBundleURLTypes)
  614. protocols: [
  615. {
  616. // 协议处理器的展示名之前使用小写 scheme,打包产物里的协议描述无法体现产品名。
  617. // 展示名跟随安装包身份;scheme 仍保持 zcode,因此两个应用中最后注册者会成为默认 handler。
  618. name: desktopProductIdentity.productName,
  619. schemes: ["zcode"],
  620. },
  621. ],
  622. mac: {
  623. target: ["dmg", "zip"],
  624. category: "public.app-category.developer-tools",
  625. artifactName: buildDesktopArtifactName("mac"),
  626. extendInfo: {
  627. NSAppleEventsUsageDescription: `${desktopProductIdentity.productName} needs Apple Events access to coordinate local automation workflows with user-approved desktop apps.`,
  628. },
  629. // 预签名脚本走的是原生 codesign,要求完整的 "Developer ID Application: ..." 身份串;
  630. // 但 electron-builder 的 mac.identity 在 26.x 下会拒绝带此前缀的名字。
  631. // 这里仅对 electron-builder 侧做前缀归一化,避免本地预签名和最终 .app 签名互相打架。
  632. // z-code 之前只有本地未签名打包配置,CI 即使注入了证书变量,
  633. // electron-builder 也不会自动切到 hardened runtime / entitlement 这套发布参数。
  634. // 这里显式收拢到环境开关,保证本地开发不被签名配置绑死,CI 发布时再按需打开。
  635. identity: shouldEnableMacSigning ? macSigningIdentity : null,
  636. // macOS 产物采用“build 阶段签名 + 独立公证阶段”的两段式流水线。
  637. // 如果这里不显式关闭 electron-builder 内置 notarize,它会在 build 阶段读取 Apple 凭据后直接尝试公证,
  638. // 并强制要求 APPLE_APP_SPECIFIC_PASSWORD,导致 build 还没产出 DMG 就提前失败。
  639. notarize: false,
  640. hardenedRuntime: shouldEnableMacSigning,
  641. gatekeeperAssess: false,
  642. entitlements: "build/entitlements.mac.plist",
  643. entitlementsInherit: "build/entitlements.mac.inherit.plist",
  644. // runtime 可执行文件已在打包前的独立预签名阶段完成签名,
  645. // electron-builder 在签主 app 时若继续深度扫描这些目录,会显著拉长 macOS codesign 时长。
  646. // 这里按“任意前缀 + Contents/Resources”匹配绝对路径,避免 ^Contents/... 在 CI 中无法命中。
  647. // 命中后可跳过已预签名目录的重复签名/遍历,同时保留主 app 与框架签名。
  648. // CUA Helper 在独立 job 中已完成 Developer ID 签名和 notarization staple;
  649. // electron-builder 若再次签名嵌套 Helper 会改变 CDHash,使最终用户包中的 staple 失效。
  650. signIgnore: [
  651. "[/\\\\]Contents[/\\\\]Resources[/\\\\]glm([/\\\\]|$)",
  652. "[/\\\\]Contents[/\\\\]Resources[/\\\\]tools([/\\\\]|$)",
  653. ],
  654. },
  655. win: {
  656. target: ["nsis"],
  657. artifactName: buildDesktopArtifactName("win"),
  658. },
  659. linux: {
  660. target: ["AppImage", "deb", "rpm", "pacman"],
  661. artifactName: buildDesktopArtifactName("linux"),
  662. // desktop 包名是 scoped package(@zcode/desktop),electron-builder 默认会把
  663. // Linux executable/Icon 推成 @zcodedesktop。部分桌面环境无法按这个 icon name 命中
  664. // hicolor 图标,最终回退成系统齿轮。这里固定成稳定的小写名称,让 Icon=zcode
  665. // 与 /usr/share/icons/hicolor/*/apps/zcode.png 保持一致。
  666. executableName: desktopProductIdentity.linuxExecutableName,
  667. category: "Development",
  668. maintainer: "ZCode <dev@zcode.z.ai>",
  669. },
  670. deb: {
  671. // 生产版与 Preview 必须是两个 dpkg package;只改可执行名仍会让安装器把另一版本当成升级替换。
  672. packageName: desktopProductIdentity.linuxPackageName,
  673. },
  674. pacman: {
  675. // 与 deb/rpm 保持相同的 flavor 隔离,避免 Preview/Production 被 pacman 当作同一包覆盖。
  676. packageName: desktopProductIdentity.linuxPackageName,
  677. // 显式列出 Arch 官方仓库可解析的 Electron 运行时依赖,替换 electron-builder
  678. // 陈旧默认集合,避免安装阶段因已移除包名直接失败。
  679. depends: PACMAN_RUNTIME_DEPENDENCIES,
  680. // Electron Builder 默认把 pacman target 命名为 .pacman;Arch 原生包的标准扩展名是 .pkg.tar.zst。
  681. artifactName: buildDesktopArtifactName("linux", "pkg.tar.zst"),
  682. },
  683. rpm: {
  684. // 与 deb 同一约束:生产版与 Preview 必须是两个独立 rpm 包,否则 dnf 会把另一 flavor 当成升级替换。
  685. // rpm 面向 RHEL 8+(glibc 2.28)分发;整包 glibc 下限由 node-pty prebuild 与 bfs/ugrep 抬到 2.28,
  686. // Electron 41 主二进制只引用到 2.25,不会更高。fpm 产 rpm 需要构建机提供 rpmbuild 与 xz。
  687. packageName: desktopProductIdentity.linuxPackageName,
  688. // electron-builder 的 rpm 默认 Requires(gtk3/nss/libXtst 等)不包含 Electron ELF 实际
  689. // DT_NEEDED 的 mesa-libgbm 与 alsa-lib;rockylinux:8 最小化容器实测装完后启动报
  690. // libgbm.so.1 缺失。这里用 fpm 追加 -d(在默认 Requires 之后累积),不能用 depends——
  691. // depends 会整组替换默认 Requires 集。
  692. fpm: ["-d", "mesa-libgbm", "-d", "alsa-lib"],
  693. },
  694. dmg: {
  695. // 当前安装包携带的运行时资源(尤其 agent node_modules)体积已超过默认 DMG 估算值。
  696. // 之前依赖自动容量时,生成的 DMG 挂载卷只有约 1.9Gi,复制 .app 过程中会因为空间耗尽
  697. // 丢失 Electron Framework 主二进制,安装后启动直接报 DYLD Library missing。
  698. // 显式放大 DMG 容量,避免拷贝截断导致的“Framework 目录存在但核心文件缺失”。
  699. size: "3200m",
  700. // 使用自定义安装背景图。
  701. background: "build/dmg_background.png",
  702. // 安装盘图标统一使用安装专用素材,避免复用应用图标导致安装识别度不足。
  703. icon: "build/icon_installer.icns",
  704. contents: [
  705. // 实验性调整:为隐藏资源文件显式指定图标坐标,尽量把它们移到角落区域。
  706. { x: 640, y: 56, type: "file", path: ".background.tiff" },
  707. { x: 640, y: 56, type: "file", path: ".VolumeIcon.icns" },
  708. { x: 130, y: 220 },
  709. { x: 410, y: 220, type: "link", path: "/Applications" },
  710. ],
  711. },
  712. nsis: {
  713. oneClick: false,
  714. allowToChangeInstallationDirectory: true,
  715. // Windows 安装流程使用独立安装图标,和应用运行时图标解耦。
  716. installerIcon: "build/icon_installer.ico",
  717. uninstallerIcon: "build/icon_installer.ico",
  718. installerHeaderIcon: "build/icon_installer.ico",
  719. },
  720. detectUpdateChannel: false,
  721. publish: {
  722. provider: "generic",
  723. // 当前 OSS/CDN 对多 Range 请求返回 206,但 Content-Type 仍是 application/x-msdownload,
  724. // electron-updater 会因缺少 multipart/byteranges 直接回退整包下载。关闭 multiple range 后仍走差分,
  725. // 只是按单 Range 顺序拉取差异块,避免 Windows 用户更新时从约 15MB 退化成 300MB+ 全量包。
  726. useMultipleRangeRequest: false,
  727. // 新客户端运行时使用服务端 manifest provider;这里仅保留 electron-builder 必需的
  728. // generic publish 占位,避免打包产物继续携带可配置的旧 stable feed。
  729. url: "http://localhost:8081",
  730. },
  731. };