electron-builder.config.js 47 KB

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