electron-builder.config.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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 { HELPER_APP_NAME } from "@zcode/zcode-cua/broker/helperConstants";
  8. import { runCommand, runCommandAndReadStdout } from "../../scripts/spawn-command.mjs";
  9. import { loadBuiltinProviderConfig } from "../../scripts/builtin-provider-config.mjs";
  10. import { noticesFileName, stageElectronNotices } from "../../scripts/third-party-notices.mjs";
  11. import { resolveNativeSearchReleasePlan } from "../../scripts/native-search-tools-config.mjs";
  12. import { getBuildMetadata } from "./scripts/build-metadata.mjs";
  13. import { collectRuntimeModuleClosureEntries } from "./scripts/runtime-dependency-closure.mjs";
  14. import {
  15. resolvePackagedNodePtyPrebuildPath,
  16. restoreTargetNodePtyPrebuild,
  17. } from "./scripts/node-pty-package-assets.mjs";
  18. import { cleanupPackagedSourcemaps } from "./scripts/packaged-sourcemap-cleanup.mjs";
  19. import { pruneIncompatiblePlatformPackages } from "./scripts/packaged-platform-dependency-prune.mjs";
  20. import { getTargetPlatform } from "./scripts/target-platform.mjs";
  21. import {
  22. resolveDesktopArtifactSuffix,
  23. resolveDesktopProductIdentity,
  24. } from "./scripts/desktop-product-identity.mjs";
  25. import { createWindowsPowerShellSecurityArgs } from "./scripts/powershell-command.mjs";
  26. import { writeWindowsUpdatePublisher } from "./scripts/windows-update-publisher.mjs";
  27. import {
  28. isSharpRequiredByComputerUse,
  29. verifyStagedSharp,
  30. } from "./scripts/sharp-package-assets.mjs";
  31. import { isRealComputerUseProducerInstalled } from "./scripts/computer-use-producer.mjs";
  32. import {
  33. MAC_ELECTRON_LANGUAGES,
  34. findMissingMacElectronLocales,
  35. resolveMacElectronFrameworkResourcesDir,
  36. } from "./scripts/mac-electron-locales.mjs";
  37. import { verifyStagedKoffi } from "./scripts/koffi-package-assets.mjs";
  38. import {
  39. finalizePackagedWindowsCuaHelper,
  40. resolveElectronBuilderWindowsTarget,
  41. } from "./scripts/windows-cua-helper-assets.mjs";
  42. import {
  43. findDesktopNativePackageViolations,
  44. createDesktopNativePackagePrunePatterns,
  45. parseAsarListWithPackState,
  46. } from "./scripts/desktop-native-package-policy.mjs";
  47. import { replaceAppAsarFromStaging } from "./scripts/app-asar-repack.mjs";
  48. import {
  49. patchNsisInstallSectionFile,
  50. patchNsisInstallUtilFile,
  51. restoreNsisInstallSectionFileSync,
  52. } from "./scripts/patch-nsis-install-section.mjs";
  53. const buildMetadata = getBuildMetadata();
  54. const targetPlatform = getTargetPlatform();
  55. // 修复原因:Windows Chrome 导入入口已暂时隐藏,默认安装包不应继续携带、签名或校验原生 helper。
  56. // 代码和完整供应链保留在显式 opt-in 后,便于未来恢复而不影响当前发布流程。
  57. const shouldPackageWindowsBrowserImportHelper =
  58. targetPlatform.os === "win32" && process.env.ZCODE_ENABLE_WINDOWS_BROWSER_IMPORT === "1";
  59. const builtinProviderConfig = await loadBuiltinProviderConfig();
  60. const desktopProductIdentity = resolveDesktopProductIdentity({
  61. ...process.env,
  62. ZCODE_ENV: builtinProviderConfig.environment,
  63. });
  64. const nativeSearchReleasePlan = resolveNativeSearchReleasePlan({
  65. platform: targetPlatform.os,
  66. arch: targetPlatform.arch,
  67. });
  68. const rawMacSigningIdentity = process.env.APPLE_SIGNING_IDENTITY || process.env.CSC_NAME;
  69. const macSigningIdentity =
  70. rawMacSigningIdentity?.replace(/^Developer ID Application:\s*/, "") ?? null;
  71. const shouldEnableMacSigning =
  72. process.env.ZCODE_ENABLE_MAC_SIGN === "1" && Boolean(macSigningIdentity);
  73. const workspaceRoot = resolve(import.meta.dirname, "../..");
  74. const desktopPackageRoot = import.meta.dirname;
  75. // Computer Use Helper(macOS .app、Windows runtime)只随真实 producer 打包;开源占位包下跳过随包资源与校验。
  76. const shouldPackageComputerUseHelper = isRealComputerUseProducerInstalled({ desktopPackageRoot });
  77. const HELPER_FILENAME = "zcode-browser-import-helper.exe";
  78. // 预装工具的 Windows 入口 shim 会被复制到用户的预装 bin 目录,由 Agent 直接运行,必须与 App 同一签名。
  79. const PREINSTALLED_ENTRY_SHIM = "preinstalled-entry-shim/zcode-preinstalled-entry-shim.exe";
  80. const BROWSER_IMPORT_HELPER = `browser-import/${HELPER_FILENAME}`;
  81. const runtimeModuleLookupRoots = [
  82. desktopPackageRoot,
  83. workspaceRoot,
  84. resolve(desktopPackageRoot, "node_modules", ".pnpm", "node_modules"),
  85. resolve(workspaceRoot, "node_modules", ".pnpm", "node_modules"),
  86. ];
  87. const desktopDistDir = process.env.ZCODE_DESKTOP_DIST_DIR || "dist";
  88. const bundledCuaHelperSource = resolve(
  89. desktopPackageRoot,
  90. "bundled-cua-helper",
  91. targetPlatform.arch,
  92. HELPER_APP_NAME,
  93. );
  94. const DEFAULT_ELECTRON_MIRROR = "https://npmmirror.com/mirrors/electron/";
  95. // `pnpm exec asar` 依赖 `.bin/asar`,但 @electron/asar 仅是 electron-builder 传递依赖时,
  96. // Linux CI(pnpm hoisted)往往解析不到该二进制,`asar list` 未运行即 exit 1。
  97. // 显式依赖 @electron/asar 并用 Node 直接执行 CLI,避免跨平台找不齐 shim。
  98. const requireFromConfig = createRequire(import.meta.url);
  99. let nsisInstallSectionPatched = false;
  100. let nsisInstallSectionOriginalSource = null;
  101. let nsisInstallSectionPath = null;
  102. const desktopElectronVersion = requireFromConfig("./package.json").devDependencies.electron;
  103. const asarCliPath = resolve(
  104. dirname(requireFromConfig.resolve("@electron/asar/package.json")),
  105. "bin",
  106. "asar.js",
  107. );
  108. const REQUIRED_ASAR_RUNTIME_MODULES = [
  109. "module-details-from-path",
  110. "@opentelemetry/api-logs",
  111. // Bugfix: telemetry 的 OTLP exporter 会在启动阶段加载 sdk-metrics。pnpm 开发态可从
  112. // workspace 根目录解析,但 electron-builder 不会稳定复制这条 hoisted 依赖,导致安装包启动即崩溃。
  113. // 将 sdk-metrics 作为闭包根注入,同时递归带齐它的 OpenTelemetry 运行时依赖。
  114. "@opentelemetry/sdk-metrics",
  115. // Bugfix:主进程的本地 TTFT / renderer 动作追踪导出器使用 OTLP proto 导出链。pnpm hoisted 布局下
  116. // electron-builder 会把 otlp-transformer 打进 app.asar,却漏拷其传递依赖 protobufjs,已安装应用启动即报
  117. // Cannot find module protobufjs/minimal(开源侧 3.14.0 arm64 DMG 实测复现)。以两个 proto exporter
  118. // 作为闭包根注入,递归带齐 otlp-transformer、protobufjs 与 @protobufjs/* 全链。
  119. "@opentelemetry/exporter-trace-otlp-proto",
  120. "@opentelemetry/exporter-metrics-otlp-proto",
  121. "pngjs",
  122. // Bugfix: @arms/rum-core 把 @babel/runtime 声明成 peerDependency,pnpm 安装时可由 peer 解析兜住,
  123. // 但 electron-builder 重打 app.asar 时不会因为 @arms/rum-electron 本体进包,就稳定把这个 peer 运行时一起带上。
  124. // 线上已出现安装包启动即报 Cannot find module '@babel/runtime/helpers/interopRequireDefault',
  125. // 这里显式把 @babel/runtime 作为闭包根注入,确保 ARMS 主进程埋点链路在生产包内可解析。
  126. "@babel/runtime",
  127. // Bugfix: @zcode/services 的代理连通性探测会动态 require("undici") 取 ProxyAgent。
  128. // tsup 虽然把 services 代码并进了主/host 产物,但不会把这个运行时 require 的包内联进去,
  129. // electron-builder 产物又可能漏掉 hoisted 的 undici,最终 mac 安装包启动即报 Cannot find module "undici"。
  130. // 这里把 undici 和其他兜底依赖一样强制注入 app.asar,避免用户在已安装应用里主进程直接崩溃。
  131. "undici",
  132. // node-forge 一直只写在 bundle.mjs 的校验名单里,靠 electron-builder 自己打进 app.asar;
  133. // 这与 yauzl 漏 pend 是同一类隐患——校验要求的模块必须有人负责补齐。node-forge 无子依赖,
  134. // 已在产物里时 afterPack 扫描会跳过它,不改变现有打包结果。
  135. "node-forge",
  136. // Main 静态依赖 PKIjs;收集其完整闭包并校验产物,避免 pnpm 去重后漏包。
  137. "pkijs",
  138. // 2.7.0 起 services 新增反馈日志压缩链路并引入 yazl;2.6.0 没有这条启动期依赖,
  139. // pnpm hoisted 布局下 yazl 可能进了 app.asar,但子依赖 buffer-crc32 没有稳定随包进入产物;
  140. // 这里显式以 yazl 作为闭包根注入,让递归依赖收集把 ZIP 打包链路所需依赖一起补齐。
  141. "yazl",
  142. // yauzl 成为 desktop/services 的直接生产依赖后,pnpm list --prod 会把顶层 yauzl 节点
  143. // 去重成没有子依赖的空节点;electron-builder 的 pnpm collector 以先登记的空节点为准,
  144. // 跳过后面带完整子树的那个,于是 app.asar 里有 yauzl 却没有它的运行时依赖 pend,
  145. // 要到 bundle 校验阶段才报「缺少运行时依赖 pend」。这里以 yauzl 作为闭包根注入,
  146. // 与 bundle.mjs 的校验名单保持一致,让递归依赖收集把 pend 一起补进产物。
  147. "yauzl",
  148. // Bugfix: 飞书 SDK 被 desktop main/host 外置后,安装包运行时必须能从 app.asar 解析到它。
  149. // 这里显式注入 scoped 包,避免开发态正常、生产包启动时才报 Cannot find module。
  150. "@larksuiteoapi/node-sdk",
  151. // 生产态里 ssh2 虽然被打进 app.asar,但它的依赖链偶发被 electron-builder 漏拷。
  152. // 已出现线上报错 Cannot find module 'asn1'(Require stack: ssh2 keyParser)。
  153. // 这里把 ssh2 关键依赖链一起注入,避免远程 SSH 连接在已安装应用里因缺包直接失败。
  154. "asn1",
  155. "bcrypt-pbkdf",
  156. "tweetnacl",
  157. // 26.17.0 的 pnpm collector 仍可能漏掉 deduped 传递依赖。以 updater 入口展开完整闭包,
  158. // 与现有 afterPack 补齐和最终产物校验共同阻止安装后才暴露 MODULE_NOT_FOUND。
  159. "electron-updater",
  160. // electron-updater → builder-util-runtime → debug 运行时 require("ms")。
  161. // pnpm hoisted 布局下 electron-builder 偶发漏拷这个叶子依赖;3.4.0(ci/cua-v0.3.17 打的)
  162. // 已在线上触发安装包启动即报 Cannot find module 'ms'(Require stack: debug/src/common.js),
  163. // 自动更新链路直接崩。ms 是叶子包,显式注入即可让 debug 在 app.asar 内稳定解析。
  164. "ms",
  165. ];
  166. // pacman 依赖必须使用 Arch 官方仓库中的包名。electron-builder 的历史默认集合包含
  167. // 已移除的 libappindicator-gtk3/http-parser,且缺少 Electron 实际需要的运行库;显式
  168. // 维护最小运行时闭包,避免 pacman -U 无法解析依赖或启动时才暴露缺库。
  169. const PACMAN_RUNTIME_DEPENDENCIES = [
  170. "gtk3",
  171. "nss",
  172. "libxss",
  173. "libxtst",
  174. "libnotify",
  175. "alsa-lib",
  176. "mesa",
  177. "xdg-utils",
  178. ];
  179. const WINDOWS_INSTALL_MANIFEST_NAME = ".zcode-install-manifest";
  180. async function writeWindowsInstallManifest(context) {
  181. if (context.electronPlatformName !== "win32") return;
  182. const root = context.appOutDir;
  183. const files = [];
  184. const visit = async (directory, relativeDirectory = "") => {
  185. for (const entry of await readdir(directory, { withFileTypes: true })) {
  186. const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;
  187. const absolutePath = join(directory, entry.name);
  188. if (entry.isDirectory()) {
  189. await visit(absolutePath, relativePath);
  190. } else if (entry.isFile() || entry.isSymbolicLink()) {
  191. files.push(relativePath.replaceAll("/", "\\"));
  192. }
  193. }
  194. };
  195. await visit(root);
  196. files.sort();
  197. await writeFile(join(root, WINDOWS_INSTALL_MANIFEST_NAME), `${files.join("\r\n")}\r\n`, "utf8");
  198. }
  199. function resolveElectronDownloadMirror(env = process.env) {
  200. const existingMirror =
  201. env.ZCODE_ELECTRON_RUNTIME_MIRROR ||
  202. env.NPM_CONFIG_ELECTRON_MIRROR ||
  203. env.npm_config_electron_mirror ||
  204. env.npm_package_config_electron_mirror ||
  205. env.ELECTRON_MIRROR;
  206. if (existingMirror?.trim()) {
  207. return existingMirror.trim();
  208. }
  209. return DEFAULT_ELECTRON_MIRROR;
  210. }
  211. function assertPackagedMacElectronLocales(context) {
  212. if (context.electronPlatformName !== "darwin") return;
  213. // .app 名以 electron-builder 的 productFilename 为准,和同文件 asar 路径同源。
  214. const resourcesDir = resolveMacElectronFrameworkResourcesDir(
  215. join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`),
  216. );
  217. const missing = findMissingMacElectronLocales(resourcesDir);
  218. if (missing.length > 0) {
  219. // 语言包名对不上时 electron-builder 会静默删光所有 lproj,3.16.2 就因此丢了视频菜单文案。
  220. throw new Error(
  221. `Packaged ZCode is missing Electron locales: ${missing.map((l) => `${l}.lproj`).join(", ")} in ${resourcesDir}`,
  222. );
  223. }
  224. }
  225. function assertPackagedCuaHelper(context) {
  226. if (targetPlatform.os !== "darwin" || !shouldPackageComputerUseHelper) return;
  227. const appPath = join(
  228. context.appOutDir,
  229. `${desktopProductIdentity.productName}.app`,
  230. "Contents",
  231. "Resources",
  232. "cua-helper",
  233. HELPER_APP_NAME,
  234. );
  235. if (!existsSync(appPath)) {
  236. throw new Error(`Packaged ZCode is missing bundled Computer Use Helper: ${appPath}`);
  237. }
  238. }
  239. const shouldEnableWindowsVsign =
  240. process.platform === "win32" && process.env.ZCODE_ENABLE_WINDOWS_SIGN === "1";
  241. const commandStdoutMaxBuffer = 64 * 1024 * 1024;
  242. // 产物后缀只标记后端环境(_TEST);身份靠 productName 区分,生产后端的 Preview 包没有后缀。
  243. const desktopArtifactEnvSuffix = resolveDesktopArtifactSuffix(process.env);
  244. // Preview 是内部签名测试包。CI 明确打开 macOS 签名时若没有身份,必须在生成未签名包前失败,
  245. // 避免“产物存在”被误认为已经走完和生产版相同的签名链路。
  246. if (
  247. desktopProductIdentity.flavor === "preview" &&
  248. process.env.ZCODE_ENABLE_MAC_SIGN === "1" &&
  249. !macSigningIdentity
  250. ) {
  251. throw new Error(
  252. "ZCode Preview macOS packaging requires APPLE_SIGNING_IDENTITY or CSC_NAME when ZCODE_ENABLE_MAC_SIGN=1",
  253. );
  254. }
  255. const PACKAGING_PRUNE_PATTERNS = [
  256. "!**/*.map",
  257. "!**/*.pdb",
  258. "!**/__tests__/**",
  259. "!**/test/**",
  260. "!**/tests/**",
  261. "!**/example/**",
  262. "!**/examples/**",
  263. "!**/README*",
  264. "!**/CHANGELOG*",
  265. "!**/CONTRIBUTING*",
  266. "!**/CODE_OF_CONDUCT*",
  267. "!**/SECURITY*",
  268. // 26.17 的 pnpm 收集器按 lockfile 全平台图收包,会把纯构建期依赖带进 app.asar
  269. // (2026-10-26 与 26.8.1 产物 asar 逐包对账 +24MB 未压缩)。以下均已核实零运行时引用:
  270. // - shadcn 是 @zcode/ui 误声明在生产位的组件脚手架 CLI,连带 @ts-morph/ts-morph、
  271. // @babel 生态与 caniuse-lite/browserslist/baseline-browser-mapping 数据包;
  272. // - node-gyp/node-addon-api 是 CUA 原生模块构建工具链;
  273. // - cpu-features/nan 是 ssh2 的可选原生加速,缺失时 ssh2 自动降级。
  274. // @babel/runtime 可能被在包库运行时 require,紧随整目录排除后重新包含。
  275. "!node_modules/shadcn/**",
  276. "!node_modules/@ts-morph/**",
  277. "!node_modules/ts-morph/**",
  278. "!node_modules/@babel/**",
  279. "node_modules/@babel/runtime/**",
  280. "!node_modules/caniuse-lite/**",
  281. "!node_modules/browserslist/**",
  282. "!node_modules/baseline-browser-mapping/**",
  283. "!node_modules/node-gyp/**",
  284. "!node_modules/node-addon-api/**",
  285. "!node_modules/cpu-features/**",
  286. "!node_modules/nan/**",
  287. ];
  288. function buildDesktopArtifactName(platformName, extension = "${ext}") {
  289. // 测试环境产物必须和正式安装包文件名区分,避免上传、下载或人工验收时混用。
  290. return `\${productName}-\${version}-${platformName}-\${arch}${desktopArtifactEnvSuffix}.${extension}`;
  291. }
  292. function runAsarCommand(args) {
  293. runCommand(process.execPath, [asarCliPath, ...args], {
  294. cwd: import.meta.dirname,
  295. env: process.env,
  296. });
  297. }
  298. function runAsarCommandAndReadStdout(args) {
  299. return runCommandAndReadStdout(process.execPath, [asarCliPath, ...args], {
  300. cwd: import.meta.dirname,
  301. env: process.env,
  302. // app.asar 在当前桌面包体积较大,asar list 输出可能超过默认缓冲并触发 ENOBUFS。
  303. // 这里显式放大缓冲,避免“为了判断是否需要注入”反而把打包流程误判失败。
  304. maxBuffer: commandStdoutMaxBuffer,
  305. stdio: ["ignore", "pipe", "inherit"],
  306. });
  307. }
  308. function runTimedSync(label, fn) {
  309. const startMs = Date.now();
  310. console.log(`[ci][timer] ${label} start`);
  311. try {
  312. return fn();
  313. } finally {
  314. console.log(`[ci][timer] ${label} end duration_ms=${Date.now() - startMs}`);
  315. }
  316. }
  317. async function runTimedAsync(label, fn) {
  318. const startMs = Date.now();
  319. console.log(`[ci][timer] ${label} start`);
  320. try {
  321. return await fn();
  322. } finally {
  323. console.log(`[ci][timer] ${label} end duration_ms=${Date.now() - startMs}`);
  324. }
  325. }
  326. function resolveAppAsarPath(context) {
  327. if (context.electronPlatformName === "darwin") {
  328. const appName = `${context.packager?.appInfo?.productFilename ?? "ZCode"}.app`;
  329. return resolve(context.appOutDir, appName, "Contents", "Resources", "app.asar");
  330. }
  331. return resolve(context.appOutDir, "resources", "app.asar");
  332. }
  333. function resolvePackagedResourcesDir(context) {
  334. if (context.electronPlatformName === "darwin") {
  335. const appName = `${context.packager?.appInfo?.productFilename ?? "ZCode"}.app`;
  336. return resolve(context.appOutDir, appName, "Contents", "Resources");
  337. }
  338. return resolve(context.appOutDir, "resources");
  339. }
  340. function normalizeAsarEntry(entry) {
  341. return entry.trim().replaceAll("\\", "/");
  342. }
  343. function resolveMissingRuntimeModules(appAsarPath) {
  344. const asarEntries = runAsarCommandAndReadStdout(["list", appAsarPath])
  345. .split("\n")
  346. .map(normalizeAsarEntry)
  347. .filter(Boolean);
  348. const asarEntrySet = new Set(asarEntries);
  349. const runtimeModules = collectRuntimeModuleClosureEntries(
  350. REQUIRED_ASAR_RUNTIME_MODULES,
  351. runtimeModuleLookupRoots,
  352. );
  353. const resolvableRuntimeModules = runtimeModules.filter((entry) => {
  354. if (!entry.sourceModulePath) {
  355. // 不同平台/安装布局下,部分运行时依赖可能被裁剪或未落到本次打包工作区。
  356. // 之前这里直接在 copy 阶段抛错会中断整个平台出包;改为记录告警并跳过该模块,
  357. // 让 afterPack 只处理当前环境确实可解析的依赖,避免 CI 因单个可选依赖缺失全量失败。
  358. console.warn(
  359. `[afterPack] runtime module not found, skip injection: ${entry.moduleName}; searched=${runtimeModuleLookupRoots
  360. .map((lookupRoot) => resolve(lookupRoot, "node_modules", entry.moduleName))
  361. .join(", ")}`,
  362. );
  363. return false;
  364. }
  365. return true;
  366. });
  367. return resolvableRuntimeModules.filter((entry) => {
  368. const { moduleName } = entry;
  369. const moduleRoot = `/node_modules/${moduleName}`;
  370. if (asarEntrySet.has(moduleRoot)) {
  371. return false;
  372. }
  373. for (const entry of asarEntrySet) {
  374. if (entry.startsWith(`${moduleRoot}/`)) {
  375. return false;
  376. }
  377. }
  378. return true;
  379. });
  380. }
  381. async function injectHoistedRuntimeModulesIntoAsar(context) {
  382. const appAsarPath = resolveAppAsarPath(context);
  383. if (!existsSync(appAsarPath)) {
  384. throw new Error(`打包产物缺少 app.asar: ${appAsarPath}`);
  385. }
  386. const missingRuntimeModules = runTimedSync("afterPack:scan-missing-runtime-modules", () =>
  387. resolveMissingRuntimeModules(appAsarPath),
  388. );
  389. if (missingRuntimeModules.length === 0) {
  390. // 之前 afterPack 每次都完整 extract/pack app.asar,即使运行时依赖已经齐全也会重复重写。
  391. // 这会把每次打包固定拉长十几秒到几十秒。先做缺失扫描,只有真的缺包才执行重写流程。
  392. console.log("[afterPack] runtime modules already complete, skip app.asar rewrite");
  393. return;
  394. }
  395. console.log(`[afterPack] missing runtime modules count=${missingRuntimeModules.length}`);
  396. // CI 会把 TMPDIR 指到项目内 .tmp,GitLab get_sources/clean 可能在脚本启动前清掉该目录。
  397. // afterPack 里重写 app.asar 同样依赖 mkdtempSync,必须自己兜底创建父目录,避免后续签名阶段只看到 .app 消失。
  398. mkdirSync(tmpdir(), { recursive: true });
  399. const stagingDir = mkdtempSync(resolve(tmpdir(), "zcode-app-asar-"));
  400. try {
  401. runTimedSync("afterPack:asar-extract", () =>
  402. runAsarCommand(["extract", appAsarPath, stagingDir]),
  403. );
  404. const stagingNodeModulesDir = resolve(stagingDir, "node_modules");
  405. mkdirSync(stagingNodeModulesDir, { recursive: true });
  406. runTimedSync("afterPack:copy-runtime-modules", () => {
  407. for (const runtimeModule of missingRuntimeModules) {
  408. const { moduleName, sourceModulePath } = runtimeModule;
  409. const targetModulePath = resolve(stagingNodeModulesDir, moduleName);
  410. if (!sourceModulePath) {
  411. throw new Error(
  412. `未找到运行时依赖 ${moduleName},已搜索: ${runtimeModuleLookupRoots
  413. .map((lookupRoot) => resolve(lookupRoot, "node_modules", moduleName))
  414. .join(", ")}`,
  415. );
  416. }
  417. // pnpm hoisted 布局下,electron-builder 可能把主包打进 app.asar,
  418. // 却漏掉它解析时还要去根 node_modules 找的运行时依赖。
  419. // 之前 require-in-the-middle 漏过 module-details-from-path,这次 @fiahfy/icns 又漏了 pngjs,
  420. // 最终都会在已安装应用里触发 Cannot find module 并让主进程启动直接崩溃。
  421. // 这里按 package.json 递归补齐依赖闭包,避免每次只补一个缺失包、上线后再暴露下一个子依赖。
  422. // 只靠 package.json 显式依赖、本包 node_modules 镜像、files include 都没让它稳定进 asar,
  423. // 所以在 afterPack 阶段直接重写 app.asar,先把这些运行时包补进去,再交给后续签名和出包。
  424. mkdirSync(dirname(targetModulePath), { recursive: true });
  425. rmSync(targetModulePath, { force: true, recursive: true });
  426. cpSync(sourceModulePath, targetModulePath, { recursive: true });
  427. }
  428. });
  429. await runTimedAsync("afterPack:asar-pack", () =>
  430. replaceAppAsarFromStaging({
  431. sourceDir: stagingDir,
  432. appAsarPath,
  433. targetPlatformKey: targetPlatform.key,
  434. runAsarCommand,
  435. }),
  436. );
  437. } finally {
  438. rmSync(stagingDir, { force: true, recursive: true });
  439. }
  440. }
  441. async function stripPackagedSourcemapReferences(context) {
  442. // electron-builder 的 files 规则能排除 .map 文件,但无法删除 JS/CSS 末尾
  443. // 指向 sourcemap 的注释;afterPack 注入运行时依赖后也可能重新带入第三方 sourceMappingURL。
  444. // 这里统一清理 app.asar 与 unpacked/extraResources,保证最终发布包不暴露 sourcemap 路径入口。
  445. await cleanupPackagedSourcemaps({
  446. appAsarPath: resolveAppAsarPath(context),
  447. resourcesDir: resolvePackagedResourcesDir(context),
  448. runAsarCommand,
  449. runTimedSync,
  450. runTimedAsync,
  451. replaceAppAsarFromStaging: ({ sourceDir, appAsarPath }) =>
  452. replaceAppAsarFromStaging({
  453. sourceDir,
  454. appAsarPath,
  455. targetPlatformKey: targetPlatform.key,
  456. runAsarCommand,
  457. }),
  458. pruneStagingDirectory:
  459. targetPlatform.key === "win32-x64" &&
  460. process.env.ZCODE_PRUNE_PACKAGED_PLATFORM_DEPENDENCIES === "1"
  461. ? (stagingDir) => pruneIncompatiblePlatformPackages(stagingDir, targetPlatform)
  462. : null,
  463. });
  464. }
  465. function assertPackagedNativeResourcePolicy(context) {
  466. const appAsarPath = resolveAppAsarPath(context);
  467. const entries = parseAsarListWithPackState(
  468. runAsarCommandAndReadStdout(["list", "--is-pack", appAsarPath]),
  469. );
  470. const violations = findDesktopNativePackageViolations(entries, targetPlatform.key);
  471. if (violations.length > 0) {
  472. // supportedArchitectures 允许工作区准备多平台依赖,但安装包只能携带目标平台资源。
  473. // 之前 Canvas 和 node-pty 的其他平台 native 被同时写进 asar/unpacked,包体被放大数百 MiB。
  474. throw new Error(`桌面 native 资源边界校验失败:\n- ${violations.join("\n- ")}`);
  475. }
  476. }
  477. function assertPackagedNodePtyPrebuild(context) {
  478. const targetBinaryPath = resolvePackagedNodePtyPrebuildPath({
  479. resourcesDir: resolvePackagedResourcesDir(context),
  480. platformKey: targetPlatform.key,
  481. });
  482. if (!existsSync(targetBinaryPath))
  483. throw new Error(`node-pty 预编译产物缺失: ${targetBinaryPath}`);
  484. }
  485. function assertPackagedCuaSharp(context) {
  486. if (!isSharpRequiredByComputerUse({ desktopPackageRoot })) return;
  487. const problems = [
  488. [
  489. "packages/browser-use-plugin",
  490. verifyStagedSharp({
  491. resourcesDir: resolvePackagedResourcesDir(context),
  492. targetPlatform,
  493. pluginRelativePath: "packages/browser-use-plugin",
  494. }),
  495. ],
  496. [
  497. "packages/zcode-cua-plugin",
  498. verifyStagedSharp({
  499. resourcesDir: resolvePackagedResourcesDir(context),
  500. targetPlatform,
  501. pluginRelativePath: "packages/zcode-cua-plugin",
  502. }),
  503. ],
  504. ].flatMap(([pluginPath, pluginProblems]) =>
  505. pluginProblems.map((problem) => `${pluginPath}: ${problem}`),
  506. );
  507. if (problems.length > 0) {
  508. throw new Error(
  509. `node_repl sharp runtime is incomplete in the packaged app:\n- ${problems.join("\n- ")}`,
  510. );
  511. }
  512. }
  513. function assertPackagedCuaKoffi(context) {
  514. const problems = verifyStagedKoffi({
  515. resourcesDir: resolvePackagedResourcesDir(context),
  516. targetPlatform,
  517. });
  518. if (problems.length > 0) {
  519. throw new Error(
  520. `CUA plugin koffi runtime is incomplete in the packaged app:\n- ${problems.join("\n- ")}`,
  521. );
  522. }
  523. }
  524. function assertSignedWindowsHelper(context, relativeHelperPath) {
  525. if (context.electronPlatformName !== "win32" || !shouldEnableWindowsVsign) return;
  526. const helperPath = resolve(context.appOutDir, "resources", relativeHelperPath);
  527. const appExecutablePath = resolve(
  528. context.appOutDir,
  529. `${context.packager.appInfo.productFilename}.exe`,
  530. );
  531. const script = [
  532. "$helper=Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -LiteralPath $zcodeArg0;",
  533. "$app=Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -LiteralPath $zcodeArg1;",
  534. "if($helper.Status -ne 'Valid' -or $app.Status -ne 'Valid'){",
  535. "[Console]::Error.WriteLine(('Authenticode status invalid: helper={0} ({1}); app={2} ({3})' -f $helper.Status,$helper.StatusMessage,$app.Status,$app.StatusMessage));",
  536. "exit 23};",
  537. "if($null -eq $helper.SignerCertificate -or $null -eq $app.SignerCertificate){",
  538. "[Console]::Error.WriteLine('Authenticode signer certificate missing');exit 24};",
  539. "if($helper.SignerCertificate.Thumbprint -ne $app.SignerCertificate.Thumbprint){",
  540. "[Console]::Error.WriteLine(('Authenticode signer mismatch: helper={0}; app={1}' -f $helper.SignerCertificate.Thumbprint,$app.SignerCertificate.Thumbprint));",
  541. "exit 25};",
  542. ].join("");
  543. // Bugfix 原因:extraResources 下的 EXE 是否进入 electron-builder 默认签名遍历会随版本变化;
  544. // 同时 Windows PowerShell 的 `-Command` 不会把尾随路径放进 `$args`,旧校验因此固定误报 exit 23。
  545. // 发布态改用 EncodedCommand,并从 PSHOME 显式加载系统 Security 模块,避免 pwsh 继承的
  546. // PSModulePath 让 Windows PowerShell 5.1 错误加载不兼容模块。
  547. runCommand(
  548. "powershell.exe",
  549. createWindowsPowerShellSecurityArgs(script, [helperPath, appExecutablePath]),
  550. );
  551. }
  552. function signWindowsHelper(context, relativeHelperPath) {
  553. if (context.electronPlatformName !== "win32" || !shouldEnableWindowsVsign) return;
  554. const helperPath = resolve(context.appOutDir, "resources", relativeHelperPath);
  555. runCommand("powershell.exe", [
  556. "-NoLogo",
  557. "-NoProfile",
  558. "-NonInteractive",
  559. "-ExecutionPolicy",
  560. "Bypass",
  561. "-File",
  562. resolve(workspaceRoot, "scripts/sign-windows.ps1"),
  563. "-FilePath",
  564. helperPath,
  565. ]);
  566. }
  567. // CR-01 修复原因:普通 NSIS 构建只提供 APP_64/APP_ARM64(压缩包路径),没有 APP_DIR_*;
  568. // installer.nsh 无法自行推导 helper 来源。afterPack 先于 makensis 执行,在这里把实际
  569. // appOutDir 下的 helper 写成按架构命名的生成 define 文件,NSIS 编译时按架构 include。
  570. export function installerProcessHelperDefineLine(appOutDir) {
  571. const helperPath = join(
  572. appOutDir,
  573. "resources",
  574. "tools",
  575. "runtime-host",
  576. "zcode-installer-process-helper.exe",
  577. );
  578. // NSIS 的 File 指令只认反斜杠绝对路径;引号字符串中 $ 与 " 需转义,属防御性处理。
  579. const escaped = helperPath.replaceAll("$", "$$").replaceAll('"', '$\\"');
  580. return `!define ZCODE_INSTALLER_PROCESS_HELPER "${escaped}"\n`;
  581. }
  582. async function writeInstallerProcessHelperDefine(context, archName) {
  583. const helperPath = resolve(
  584. context.appOutDir,
  585. "resources",
  586. "tools",
  587. "runtime-host",
  588. "zcode-installer-process-helper.exe",
  589. );
  590. if (!existsSync(helperPath)) {
  591. throw new Error(`Installer process helper missing after pack: ${helperPath}`);
  592. }
  593. mkdirSync(join(desktopPackageRoot, "build", "generated"), { recursive: true });
  594. await writeFile(
  595. join(desktopPackageRoot, "build", "generated", `zcode-process-helper-${archName}.nsh`),
  596. installerProcessHelperDefineLine(context.appOutDir),
  597. "utf8",
  598. );
  599. }
  600. /** @type {import("electron-builder").Configuration} */
  601. export default {
  602. appId: desktopProductIdentity.appId,
  603. // Linux deb 打包(fpm)会校验 package metadata 中的 homepage、author.email、maintainer。
  604. // CI 环境下若这些字段缺失会在产物阶段直接失败。这里统一在构建配置补齐,避免依赖外部注入。
  605. extraMetadata: {
  606. version: buildMetadata.appVersion,
  607. zcodeProductFlavor: desktopProductIdentity.flavor,
  608. homepage: "https://zcode.z.ai",
  609. author: {
  610. name: "ZCode",
  611. email: "dev@zcode.z.ai",
  612. },
  613. },
  614. // macOS 签名阶段会对 Electron Framework 下每个语言包逐个 codesign。
  615. // 默认全量语言会产生大量 locale.pak 签名调用,显著拉长打包时长。
  616. // 这里仅保留当前产品必需语言,减少签名文件数并缩短 CI 总耗时。
  617. // builder 按语言包文件名精确匹配:Windows/Linux 是 locales/en-US.pak,macOS 见 mac.electronLanguages。
  618. electronLanguages: ["en-US", "zh-CN"],
  619. // builder 的依赖树推导不稳定;显式读取 package.json,避免开发与安装包版本分叉。
  620. electronVersion: desktopElectronVersion,
  621. // 旧 Windows 协议注册可能在应用 JS 重写注册表前注入 --inspect-brk。
  622. // 在签名前关闭原生 Inspector 参数,覆盖升级后首次启动;保留 Agent 所需的 RunAsNode。
  623. ...(targetPlatform.os === "win32"
  624. ? { electronFuses: { enableNodeCliInspectArguments: false } }
  625. : {}),
  626. electronDownload: {
  627. // ELECTRON_MIRROR 是 @electron/get 的全局环境变量,会覆盖 dmg-builder 等
  628. // generic artifact 自己传入的 mirrorOptions,导致 builder 辅助包被错误拼到 Electron runtime 镜像目录。
  629. // 这里改用 electron-builder 的专用配置,只影响 Electron runtime zip 下载。
  630. mirror: resolveElectronDownloadMirror(),
  631. },
  632. productName: desktopProductIdentity.productName,
  633. directories: {
  634. // macOS arm64/x64 CI 可能共享同一个 checkout 并行打包。
  635. // 输出根目录允许按架构隔离,避免一个 job 清理 dist 时删除另一个 job 正在签名的 .app。
  636. output: desktopDistDir,
  637. buildResources: "build",
  638. },
  639. files: [
  640. "out/**/*",
  641. "package.json",
  642. // app.asar 会把桌面端运行时 node_modules 一并打进去,依赖包自带的 .map / README
  643. // 默认也会原样进入安装包。这里统一在主包层做一次裁剪,只移除非运行时文件,LICENSE 继续保留。
  644. ...PACKAGING_PRUNE_PATTERNS,
  645. ...createDesktopNativePackagePrunePatterns(targetPlatform.key),
  646. "!node_modules/@zcode/**",
  647. "!node_modules/react/**",
  648. "!node_modules/react-dom/**",
  649. ],
  650. asarUnpack: [
  651. "node_modules/@napi-rs/keyring-*/**/*.node",
  652. // node-pty 的 target prebuild 还包含 spawn-helper / winpty-agent.exe 等辅助可执行文件,
  653. // 整个目标目录必须 unpack;其他平台目录已由 files 规则裁剪。
  654. `node_modules/node-pty/prebuilds/${targetPlatform.key}/**`,
  655. ],
  656. beforePack: async (context) => {
  657. runTimedSync("beforePack:restoreTargetNodePtyPrebuild", () =>
  658. restoreTargetNodePtyPrebuild({ desktopPackageRoot, targetPlatform }),
  659. );
  660. if (context.electronPlatformName !== "win32" || nsisInstallSectionPatched) {
  661. return;
  662. }
  663. nsisInstallSectionPath = resolve(
  664. dirname(requireFromConfig.resolve("app-builder-lib/package.json")),
  665. "templates",
  666. "nsis",
  667. "installSection.nsh",
  668. );
  669. const patchResult = await runTimedAsync("beforePack:patchNsisInstallSection", () =>
  670. patchNsisInstallSectionFile(nsisInstallSectionPath),
  671. );
  672. nsisInstallSectionOriginalSource = patchResult.originalSource;
  673. if (patchResult.changed) {
  674. // electron-builder 在当前进程内随后才会编译 NSIS;等整个构建进程退出后恢复 node_modules
  675. // 中的上游模板,避免把一次打包的定制内容永久留在开发依赖里。
  676. process.once("exit", () => {
  677. restoreNsisInstallSectionFileSync({
  678. filePath: nsisInstallSectionPath,
  679. originalSource: nsisInstallSectionOriginalSource,
  680. });
  681. });
  682. }
  683. const installUtilPath = resolve(dirname(nsisInstallSectionPath), "include", "installUtil.nsh");
  684. const utilPatch = await patchNsisInstallUtilFile(installUtilPath);
  685. if (utilPatch.changed) {
  686. process.once("exit", () => {
  687. restoreNsisInstallSectionFileSync({
  688. filePath: installUtilPath,
  689. originalSource: utilPatch.originalSource,
  690. });
  691. });
  692. }
  693. nsisInstallSectionPatched = true;
  694. },
  695. afterExtract: async (context) => {
  696. // 修复:macOS 重命名阶段会删除归档顶层许可证,必须在 afterExtract 保留目标平台原文。
  697. const framework = context.packager.info.framework;
  698. const resources =
  699. context.electronPlatformName === "darwin"
  700. ? resolve(context.appOutDir, framework.distMacOsAppName, "Contents", "Resources")
  701. : resolve(context.appOutDir, "resources");
  702. // 26.17.0 在 afterExtract 前已将 macOS 的 LICENSE/Chromium 声明移动到 app Resources;
  703. // Windows/Linux 仍把许可文件保留在 appOutDir 根目录。源目录必须跟随 Builder 的平台布局,
  704. // 否则 macOS 会继续读取已经被移动的 LICENSE.electron.txt 并在签名前失败。
  705. const extractedLicenseRoot =
  706. context.electronPlatformName === "darwin" ? resources : context.appOutDir;
  707. await stageElectronNotices(extractedLicenseRoot, resources, framework.version);
  708. },
  709. afterPack: async (context) => {
  710. const actualWindowsTarget =
  711. context.electronPlatformName === "win32"
  712. ? resolveElectronBuilderWindowsTarget({
  713. electronPlatformName: context.electronPlatformName,
  714. arch: context.arch,
  715. configuredTargetPlatform: targetPlatform,
  716. })
  717. : null;
  718. await runTimedAsync("afterPack:injectHoistedRuntimeModulesIntoAsar", () =>
  719. injectHoistedRuntimeModulesIntoAsar(context),
  720. );
  721. await runTimedAsync("afterPack:stripPackagedSourcemapReferences", () =>
  722. stripPackagedSourcemapReferences(context),
  723. );
  724. runTimedSync("afterPack:assertPackagedNativeResourcePolicy", () =>
  725. assertPackagedNativeResourcePolicy(context),
  726. );
  727. runTimedSync("afterPack:assertPackagedNodePtyPrebuild", () =>
  728. assertPackagedNodePtyPrebuild(context),
  729. );
  730. runTimedSync("afterPack:assertPackagedCuaSharp", () => assertPackagedCuaSharp(context));
  731. runTimedSync("afterPack:assertPackagedCuaKoffi", () => assertPackagedCuaKoffi(context));
  732. runTimedSync("afterPack:assertPackagedCuaHelper", () => assertPackagedCuaHelper(context));
  733. runTimedSync("afterPack:assertPackagedMacElectronLocales", () =>
  734. assertPackagedMacElectronLocales(context),
  735. );
  736. if (actualWindowsTarget && shouldPackageComputerUseHelper) {
  737. await runTimedAsync("afterPack:finalizePackagedWindowsCuaHelper", () =>
  738. finalizePackagedWindowsCuaHelper({
  739. resourcesDir: resolvePackagedResourcesDir(context),
  740. targetPlatform: actualWindowsTarget,
  741. electronVersion: desktopElectronVersion,
  742. }),
  743. );
  744. await runTimedAsync("afterPack:writeWindowsInstallManifest", () =>
  745. writeWindowsInstallManifest(context),
  746. );
  747. }
  748. if (context.electronPlatformName === "win32") {
  749. // 普通打包没有 APP_DIR_* 宏;makensis 前落盘按架构的 helper define(见函数注释)。
  750. await writeInstallerProcessHelperDefine(
  751. context,
  752. actualWindowsTarget?.arch ?? targetPlatform.arch,
  753. );
  754. signWindowsHelper(context, "tools/runtime-host/zcode-runtime-host.exe");
  755. signWindowsHelper(context, "tools/runtime-host/zcode-installer-process-helper.exe");
  756. }
  757. if (shouldPackageWindowsBrowserImportHelper) {
  758. runTimedSync("afterPack:signWindowsBrowserImportHelper", () =>
  759. signWindowsHelper(context, BROWSER_IMPORT_HELPER),
  760. );
  761. }
  762. if (targetPlatform.os === "win32") {
  763. // extraResources 缺源文件时 electron-builder 不报错;没有 shim,Windows 预装入口全部无法写入。
  764. const shimPath = resolve(context.appOutDir, "resources", PREINSTALLED_ENTRY_SHIM);
  765. if (!existsSync(shimPath)) {
  766. throw new Error(`Preinstalled entry shim is missing in the packaged app: ${shimPath}`);
  767. }
  768. runTimedSync("afterPack:signPreinstalledEntryShim", () =>
  769. signWindowsHelper(context, PREINSTALLED_ENTRY_SHIM),
  770. );
  771. }
  772. },
  773. afterSign: async (context) => {
  774. if (context.electronPlatformName === "win32") {
  775. assertSignedWindowsHelper(context, "tools/runtime-host/zcode-runtime-host.exe");
  776. assertSignedWindowsHelper(context, "tools/runtime-host/zcode-installer-process-helper.exe");
  777. runTimedSync("afterSign:assertSignedPreinstalledEntryShim", () =>
  778. assertSignedWindowsHelper(context, PREINSTALLED_ENTRY_SHIM),
  779. );
  780. }
  781. if (shouldPackageWindowsBrowserImportHelper) {
  782. runTimedSync("afterSign:assertSignedWindowsBrowserImportHelper", () =>
  783. assertSignedWindowsHelper(context, BROWSER_IMPORT_HELPER),
  784. );
  785. }
  786. if (context.electronPlatformName === "win32" && shouldEnableWindowsVsign) {
  787. await runTimedAsync("afterSign:writeWindowsUpdatePublisher", () =>
  788. writeWindowsUpdatePublisher({
  789. appOutDir: context.appOutDir,
  790. executableName: context.packager.appInfo.productFilename,
  791. }),
  792. );
  793. }
  794. },
  795. extraResources: [
  796. ...(targetPlatform.os === "win32"
  797. ? [
  798. {
  799. from: `bundled-tools/${targetPlatform.key}/runtime-host/zcode-runtime-host.exe`,
  800. to: "tools/runtime-host/zcode-runtime-host.exe",
  801. },
  802. {
  803. from: `bundled-tools/${targetPlatform.key}/runtime-host/zcode-installer-process-helper.exe`,
  804. to: "tools/runtime-host/zcode-installer-process-helper.exe",
  805. },
  806. ]
  807. : []),
  808. { from: resolve(workspaceRoot, noticesFileName), to: noticesFileName },
  809. ...(targetPlatform.os === "darwin"
  810. ? [
  811. ...(shouldPackageComputerUseHelper
  812. ? [
  813. {
  814. from: bundledCuaHelperSource,
  815. to: `cua-helper/${HELPER_APP_NAME}`,
  816. },
  817. ]
  818. : []),
  819. {
  820. // CUA 权限浮窗的吸附数据源(CGWindowListCopyWindowInfo,不需要任何 TCC 权限)。
  821. // 主进程按 process.resourcesPath 解析;缺失时 watcher fail-open,浮窗仍可用
  822. // 只是不吸附,所以这里不做存在性断言。
  823. from: "resources/macos-window-bounds/zcode-window-bounds",
  824. to: "macos-window-bounds/zcode-window-bounds",
  825. },
  826. ]
  827. : []),
  828. {
  829. // 正式包不能依赖仓库目录读取社区、反馈等内置兜底配置。
  830. // 显式放入 resources/config,与主进程的 process.resourcesPath 解析保持一致。
  831. from: resolve(workspaceRoot, "config/default.json"),
  832. to: "config/default.json",
  833. },
  834. {
  835. // Provider Registry 的 ZCode Built-in Config 是静态 Provider/Model 事实的唯一内置来源。
  836. // 显式随包发布,避免正式 Host 回退到旧 Catalog/Preset hardcode。
  837. from: builtinProviderConfig.sourcePath,
  838. to: "config/provider/zcode-builtin.json",
  839. },
  840. {
  841. // 应用图标:打包后放入 resources 目录,主进程通过 process.resourcesPath 加载
  842. from: "build/icon.png",
  843. to: "icon.png",
  844. },
  845. ...(targetPlatform.os === "linux"
  846. ? [
  847. {
  848. // AppImage 用户级 hicolor 图标安装使用真实 512x512 资源,避免目录标称尺寸和 PNG IHDR 不一致。
  849. from: "build/icons/512x512.png",
  850. to: "icon_512x512.png",
  851. },
  852. ]
  853. : []),
  854. {
  855. // Windows 独立图标:开发态和打包态都统一走同一套任务栏/窗口图标资源。
  856. from: "build/icon_windows.png",
  857. to: "icon_windows.png",
  858. },
  859. ...(targetPlatform.os === "win32"
  860. ? [
  861. {
  862. // Windows 托盘图标:Tray 在打包态只能稳定读取 resources 下的独立资源。
  863. // 这里不复用窗口 PNG,避免通知区域在高 DPI 下退化成模糊缩放图。
  864. from: "build/icon.ico",
  865. to: "tray_icon.ico",
  866. },
  867. ]
  868. : []),
  869. ...(targetPlatform.os === "win32"
  870. ? [
  871. {
  872. // 预装工具入口 shim;Main 按 process.resourcesPath 解析后交给预装进程。
  873. from: `bundled-tools/${targetPlatform.key}/preinstalled-entry-shim/zcode-preinstalled-entry-shim.exe`,
  874. to: PREINSTALLED_ENTRY_SHIM,
  875. },
  876. ]
  877. : []),
  878. ...(targetPlatform.os === "win32" && shouldPackageComputerUseHelper
  879. ? [
  880. {
  881. // 根因:electron-builder 会跳过 from 根目录下的 node_modules;主树与依赖树必须分开映射,
  882. // 否则安装包有 manifest/entry,却会在 Helper 启动时缺 express/Sharp。
  883. from: `bundled-tools/${targetPlatform.key}/cua-helper`,
  884. to: "tools/cua-helper",
  885. filter: ["**/*", "!node_modules{,/**/*}"],
  886. },
  887. {
  888. from: `bundled-tools/${targetPlatform.key}/cua-helper/node_modules`,
  889. to: "tools/cua-helper/node_modules",
  890. filter: ["**/*", "!**/*.map"],
  891. },
  892. ]
  893. : []),
  894. {
  895. // agent 运行时资产,打包到 resources/glm。
  896. // 桌面端内置的是 agent 的 JS bundle(glm/zcode.cjs,由 prepare:agent-bundle 生成),
  897. // Host 进程用 app 自带的 Electron Node runtime(ELECTRON_RUN_AS_NODE)执行 `zcode.cjs app-server --stdio`,
  898. // 不再随包内置独立 Node 二进制。远端 SSH/WSL 仍走原生二进制(无 Electron)。
  899. from: `bundled-agents/${targetPlatform.key}/glm`,
  900. to: "glm",
  901. filter: ["**/*", "!**/*.map"],
  902. },
  903. {
  904. // agent shell 之前完全依赖宿主系统 PATH,GUI 启动时经常拿不到用户自己装的 rg。
  905. // 这里把 ripgrep 作为桌面端内置 runtime tool 打进 resources/tools,
  906. // 后续 host/server 把该目录追加到 PATH;用户版本优先,缺失时再由随包 rg 兜底。
  907. from: `bundled-tools/${targetPlatform.key}/ripgrep`,
  908. to: "tools/ripgrep",
  909. filter: ["**/*"],
  910. },
  911. ...nativeSearchReleasePlan.extraResourceToolIds.map((toolId) => ({
  912. from: `bundled-tools/${targetPlatform.key}/${toolId}`,
  913. to: `tools/${toolId}`,
  914. filter: ["**/*"],
  915. })),
  916. ],
  917. // pnpm 依赖图不完整时禁止仅记录警告并继续生成安装包;afterPack 只能补齐可解析依赖,
  918. // collector 已确认缺失的生产依赖必须在打包阶段停止。
  919. allowMissingDependencies: false,
  920. // postinstall 会先优先复用 node-pty 自带的 Windows 预编译产物,其他平台再按需 electron-rebuild。
  921. // 打包阶段统一复用安装时准备好的原生文件,避免 electron-builder 再触发一轮不受控的本地编译。
  922. npmRebuild: false,
  923. // OAuth deep link 协议注册(macOS 打包后需要 Info.plist 中声明 CFBundleURLTypes)
  924. protocols: [
  925. {
  926. // 协议处理器的展示名之前使用小写 scheme,打包产物里的协议描述无法体现产品名。
  927. // 展示名跟随安装包身份;scheme 仍保持 zcode,因此两个应用中最后注册者会成为默认 handler。
  928. name: desktopProductIdentity.productName,
  929. schemes: ["zcode"],
  930. },
  931. ],
  932. mac: {
  933. minimumSystemVersion: "13.0.0",
  934. target: ["dmg", "zip"],
  935. category: "public.app-category.developer-tools",
  936. artifactName: buildDesktopArtifactName("mac"),
  937. // macOS 语言包是 en.lproj / zh_CN.lproj,沿用顶层 "en-US" 会一个都匹配不上被全部删掉,
  938. // Chromium 自带文案随之丢失(视频控件菜单只剩图标、播放速度子菜单空白)。
  939. electronLanguages: MAC_ELECTRON_LANGUAGES,
  940. extendInfo: {
  941. NSAppleEventsUsageDescription: `${desktopProductIdentity.productName} needs Apple Events access to coordinate local automation workflows with user-approved desktop apps.`,
  942. // 缺失该 key 时 macOS 会静默拒绝 CoreBluetooth 枚举,内置浏览器 Web Bluetooth
  943. // 的设备选择器列表恒为空(实测 Chrome 有蓝牙隐私权限则正常)。
  944. NSBluetoothAlwaysUsageDescription: `${desktopProductIdentity.productName} needs Bluetooth access to list nearby devices when a website you open in the embedded browser requests one.`,
  945. // 语音输入(docs/chat/composer-voice-input.md):缺失该 key 时 askForMediaAccess 直接失败。
  946. NSMicrophoneUsageDescription: `${desktopProductIdentity.productName} needs microphone access to turn your speech into text when you use voice input.`,
  947. },
  948. // 预签名脚本走的是原生 codesign,要求完整的 "Developer ID Application: ..." 身份串;
  949. // 但 electron-builder 的 mac.identity 在 26.x 下会拒绝带此前缀的名字。
  950. // 这里仅对 electron-builder 侧做前缀归一化,避免本地预签名和最终 .app 签名互相打架。
  951. // z-code 之前只有本地未签名打包配置,CI 即使注入了证书变量,
  952. // electron-builder 也不会自动切到 hardened runtime / entitlement 这套发布参数。
  953. // 这里显式收拢到环境开关,保证本地开发不被签名配置绑死,CI 发布时再按需打开。
  954. identity: shouldEnableMacSigning ? macSigningIdentity : null,
  955. // macOS 产物采用“build 阶段签名 + 独立公证阶段”的两段式流水线。
  956. // 如果这里不显式关闭 electron-builder 内置 notarize,它会在 build 阶段读取 Apple 凭据后直接尝试公证,
  957. // 并强制要求 APPLE_APP_SPECIFIC_PASSWORD,导致 build 还没产出 DMG 就提前失败。
  958. notarize: false,
  959. hardenedRuntime: shouldEnableMacSigning,
  960. gatekeeperAssess: false,
  961. entitlements: "build/entitlements.mac.plist",
  962. entitlementsInherit: "build/entitlements.mac.inherit.plist",
  963. // runtime 可执行文件已在打包前的独立预签名阶段完成签名,
  964. // electron-builder 在签主 app 时若继续深度扫描这些目录,会显著拉长 macOS codesign 时长。
  965. // 这里按“任意前缀 + Contents/Resources”匹配绝对路径,避免 ^Contents/... 在 CI 中无法命中。
  966. // 命中后可跳过已预签名目录的重复签名/遍历,同时保留主 app 与框架签名。
  967. // CUA Helper 在独立 job 中已完成 Developer ID 签名和 notarization staple;
  968. // electron-builder 若再次签名嵌套 Helper 会改变 CDHash,使最终用户包中的 staple 失效。
  969. signIgnore: [
  970. "[/\\\\]Contents[/\\\\]Resources[/\\\\]cua-helper([/\\\\]|$)",
  971. "[/\\\\]Contents[/\\\\]Resources[/\\\\]glm([/\\\\]|$)",
  972. "[/\\\\]Contents[/\\\\]Resources[/\\\\]tools([/\\\\]|$)",
  973. ],
  974. },
  975. win: {
  976. target: ["nsis"],
  977. artifactName: buildDesktopArtifactName("win"),
  978. verifyUpdateCodeSignature: true,
  979. signExts: [".node", ".dll"],
  980. // Bugfix: Windows CI 之前完全依赖 electron-builder 内置 signtool.exe,
  981. // 一旦 runner 的证书链路要求改走 vsigntool,打包阶段就会在内置签名环节卡死。
  982. // 这里通过自定义 sign hook 把所有 Windows 可执行文件统一切到仓库内的 vsigntool 封装,
  983. // 既保留 electron-builder 的签名时机,又和 CI 机器上的签名基础设施保持一致。
  984. ...(shouldEnableWindowsVsign
  985. ? {
  986. signtoolOptions: {
  987. sign: "./scripts/sign-windows-hook.cjs",
  988. },
  989. }
  990. : {}),
  991. },
  992. linux: {
  993. target: ["AppImage", "deb", "rpm", "pacman"],
  994. artifactName: buildDesktopArtifactName("linux"),
  995. // desktop 包名是 scoped package(@zcode/desktop),electron-builder 默认会把
  996. // Linux executable/Icon 推成 @zcodedesktop。部分桌面环境无法按这个 icon name 命中
  997. // hicolor 图标,最终回退成系统齿轮。这里固定成稳定的小写名称,让 Icon=zcode
  998. // 与 /usr/share/icons/hicolor/*/apps/zcode.png 保持一致。
  999. executableName: desktopProductIdentity.linuxExecutableName,
  1000. category: "Development",
  1001. maintainer: "ZCode <dev@zcode.z.ai>",
  1002. },
  1003. deb: {
  1004. // 生产版与 Preview 必须是两个 dpkg package;只改可执行名仍会让安装器把另一版本当成升级替换。
  1005. packageName: desktopProductIdentity.linuxPackageName,
  1006. },
  1007. pacman: {
  1008. // 与 deb/rpm 保持相同的 flavor 隔离,避免 Preview/Production 被 pacman 当作同一包覆盖。
  1009. packageName: desktopProductIdentity.linuxPackageName,
  1010. // 显式列出 Arch 官方仓库可解析的 Electron 运行时依赖,替换 electron-builder
  1011. // 陈旧默认集合,避免安装阶段因已移除包名直接失败。
  1012. depends: PACMAN_RUNTIME_DEPENDENCIES,
  1013. // Electron Builder 默认把 pacman target 命名为 .pacman;Arch 原生包的标准扩展名是 .pkg.tar.zst。
  1014. artifactName: buildDesktopArtifactName("linux", "pkg.tar.zst"),
  1015. },
  1016. rpm: {
  1017. // 与 deb 同一约束:生产版与 Preview 必须是两个独立 rpm 包,否则 dnf 会把另一 flavor 当成升级替换。
  1018. // rpm 面向 RHEL 8+(glibc 2.28)分发;整包 glibc 下限由 node-pty prebuild 与 bfs/ugrep 抬到 2.28,
  1019. // Electron 41 主二进制只引用到 2.25,不会更高。fpm 产 rpm 需要构建机提供 rpmbuild 与 xz。
  1020. packageName: desktopProductIdentity.linuxPackageName,
  1021. // electron-builder 的 rpm 默认 Requires(gtk3/nss/libXtst 等)不包含 Electron ELF 实际
  1022. // DT_NEEDED 的 mesa-libgbm 与 alsa-lib;rockylinux:8 最小化容器实测装完后启动报
  1023. // libgbm.so.1 缺失。这里用 fpm 追加 -d(在默认 Requires 之后累积),不能用 depends——
  1024. // depends 会整组替换默认 Requires 集。
  1025. fpm: ["-d", "mesa-libgbm", "-d", "alsa-lib"],
  1026. },
  1027. dmg: {
  1028. // 当前安装包携带的运行时资源(尤其 agent node_modules)体积已超过默认 DMG 估算值。
  1029. // 之前依赖自动容量时,生成的 DMG 挂载卷只有约 1.9Gi,复制 .app 过程中会因为空间耗尽
  1030. // 丢失 Electron Framework 主二进制,安装后启动直接报 DYLD Library missing。
  1031. // 显式放大 DMG 容量,避免拷贝截断导致的“Framework 目录存在但核心文件缺失”。
  1032. size: "3200m",
  1033. // 使用自定义安装背景图。
  1034. background: "build/dmg_background.png",
  1035. // 安装盘图标统一使用安装专用素材,避免复用应用图标导致安装识别度不足。
  1036. icon: "build/icon_installer.icns",
  1037. contents: [
  1038. // dmg-builder@1.2.5 的 dmgbuild 会对每个 type:"file" 条目执行 ditto <path>,
  1039. // path 被当作真实源文件解析。.background.tiff / .VolumeIcon.icns 是 dmgbuild
  1040. // 在镜像内自行生成的隐藏文件,不是源文件;把它们列进 contents 在旧 dmgbuild
  1041. // 上被容忍,在新 dmgbuild 上直接 ditto 报 "Cannot get the real path"(2026-10-23
  1042. // CI x64 DMG 实况)。隐藏文件坐标交给 dmgbuild 默认摆放,不再显式列举。
  1043. { x: 130, y: 220 },
  1044. { x: 410, y: 220, type: "link", path: "/Applications" },
  1045. ],
  1046. },
  1047. nsis: {
  1048. oneClick: false,
  1049. allowToChangeInstallationDirectory: true,
  1050. // Windows 安装流程使用独立安装图标,和应用运行时图标解耦。
  1051. installerIcon: "build/icon_installer.ico",
  1052. uninstallerIcon: "build/icon_installer.ico",
  1053. installerHeaderIcon: "build/icon_installer.ico",
  1054. },
  1055. detectUpdateChannel: false,
  1056. publish: {
  1057. provider: "generic",
  1058. // 当前 OSS/CDN 对多 Range 请求返回 206,但 Content-Type 仍是 application/x-msdownload,
  1059. // electron-updater 会因缺少 multipart/byteranges 直接回退整包下载。关闭 multiple range 后仍走差分,
  1060. // 只是按单 Range 顺序拉取差异块,避免 Windows 用户更新时从约 15MB 退化成 300MB+ 全量包。
  1061. useMultipleRangeRequest: false,
  1062. // 新客户端运行时使用服务端 manifest provider;这里仅保留 electron-builder 必需的
  1063. // generic publish 占位,避免打包产物继续携带可配置的旧 stable feed。
  1064. url: "http://localhost:8081",
  1065. },
  1066. };