electron-builder.config.js 46 KB

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