electron-builder.config.js 49 KB

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