devElectronAppBundle.mjs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import { access, cp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
  2. import { dirname, posix } from "node:path";
  3. import { execFile } from "node:child_process";
  4. import { promisify } from "node:util";
  5. export const DEV_ELECTRON_PROTOCOL_SCHEME = "zcode";
  6. export const DEV_ELECTRON_APP_NAME = "ZCode Dev";
  7. export const DEV_ELECTRON_APP_BUNDLE_ID = "dev.zcode.app.development";
  8. // 副本布局版本,见 prepareDevElectronAppBundle 中的指纹说明。
  9. export const DEV_ELECTRON_BUNDLE_FORMAT = 3;
  10. const execFileAsync = promisify(execFile);
  11. async function signDevElectronApp(appPath) {
  12. // Electron 42 起通知要求有效签名;原 npm runtime 签名可能不完整,修改身份后也必须重签。
  13. // 仅对 ignored 的开发副本做 ad-hoc 签名,正式发布仍走现有证书、公证流程。
  14. await execFileAsync("/usr/bin/codesign", [
  15. "--deep",
  16. "--force",
  17. "--sign",
  18. "-",
  19. "--preserve-metadata=entitlements,flags,runtime",
  20. appPath,
  21. ]);
  22. }
  23. function escapeXml(value) {
  24. return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll('"', "&quot;");
  25. }
  26. function replacePlistString(plist, key, value) {
  27. const pattern = new RegExp(`(<key>${key}</key>\\s*<string>)[^<]*(</string>)`, "u");
  28. if (!pattern.test(plist)) {
  29. throw new Error(`Dev Electron Info.plist is missing ${key}`);
  30. }
  31. return plist.replace(
  32. pattern,
  33. (_match, prefix, suffix) => `${prefix}${escapeXml(value)}${suffix}`,
  34. );
  35. }
  36. function appendProtocolDeclaration(plist) {
  37. if (plist.includes(`<string>${DEV_ELECTRON_PROTOCOL_SCHEME}</string>`)) {
  38. return plist;
  39. }
  40. const closingDictIndex = plist.lastIndexOf("</dict>");
  41. if (closingDictIndex < 0) {
  42. throw new Error("Dev Electron Info.plist is missing its root dict");
  43. }
  44. const protocolDeclaration = `\n\t<key>CFBundleURLTypes</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>CFBundleURLName</key>\n\t\t\t<string>${DEV_ELECTRON_APP_NAME}</string>\n\t\t\t<key>CFBundleURLSchemes</key>\n\t\t\t<array>\n\t\t\t\t<string>${DEV_ELECTRON_PROTOCOL_SCHEME}</string>\n\t\t\t</array>\n\t\t</dict>\n\t</array>\n`;
  45. return `${plist.slice(0, closingDictIndex)}${protocolDeclaration}${plist.slice(closingDictIndex)}`;
  46. }
  47. /**
  48. * 为 macOS 本地 Dev runtime 写入产品身份和 zcode URL scheme。
  49. * raw Electron 的 Info.plist 没有 CFBundleURLTypes,系统只能把 zcode 交给
  50. * com.github.Electron;这里仅修改启动副本,避免污染 node_modules 中的 Electron。
  51. */
  52. export function patchDevElectronInfoPlist(plist) {
  53. let patched = replacePlistString(plist, "CFBundleDisplayName", DEV_ELECTRON_APP_NAME);
  54. patched = replacePlistString(patched, "CFBundleIdentifier", DEV_ELECTRON_APP_BUNDLE_ID);
  55. patched = replacePlistString(patched, "CFBundleName", DEV_ELECTRON_APP_NAME);
  56. return appendProtocolDeclaration(patched);
  57. }
  58. export function resolveDevElectronAppBundlePath({ runtimeRoot, electronVersion, arch }) {
  59. return posix.join(runtimeRoot, `${electronVersion}-${arch}`, `${DEV_ELECTRON_APP_NAME}.app`);
  60. }
  61. export async function prepareDevElectronAppBundle({
  62. electronAppPath,
  63. runtimeRoot,
  64. electronVersion,
  65. arch,
  66. signApp = signDevElectronApp,
  67. }) {
  68. const appPath = resolveDevElectronAppBundlePath({ runtimeRoot, electronVersion, arch });
  69. const infoPlistPath = posix.join(appPath, "Contents", "Info.plist");
  70. const sourceExecutablePath = posix.join(electronAppPath, "Contents", "MacOS", "Electron");
  71. const existingExecutablePath = posix.join(appPath, "Contents", "MacOS", "Electron");
  72. // 源二进制的身份指纹,写在 .app 外面:放进 Contents 会污染 bundle 结构。
  73. const sourceStampPath = posix.join(dirname(appPath), ".zcode-dev-electron-source.json");
  74. // 修复原因:这里原本把两个 Electron 可执行文件(各 ~100MB+)整份读进内存做 equals,
  75. // 每次 dev 启动都要付一次全量读盘。源二进制由 npm 包解压产出,记录它的 size+mtime
  76. // 即可判定是否需要重拷,语义等价而开销是常数级。
  77. //
  78. // 不直接比较「源与副本」的 mtime:cp 即使开 preserveTimestamps 也会把 mtime
  79. // 四舍五入到毫秒,源的亚毫秒精度必然丢失,两边永远不相等 —— 那等于没有缓存。
  80. //
  81. // format 字段记录副本的布局版本:布局修复(例如符号链接策略变更)时递增,
  82. // 让已存在的旧副本在源二进制没变的情况下也能被判定为需要重拷。
  83. const sourceStats = await stat(sourceExecutablePath).catch(() => undefined);
  84. const sourceStamp = sourceStats
  85. ? JSON.stringify({
  86. format: DEV_ELECTRON_BUNDLE_FORMAT,
  87. size: sourceStats.size,
  88. mtimeMs: sourceStats.mtimeMs,
  89. })
  90. : undefined;
  91. let needsCopy = true;
  92. try {
  93. const existingInfoPlist = await readFile(infoPlistPath, "utf8");
  94. await access(existingExecutablePath);
  95. const existingStamp = await readFile(sourceStampPath, "utf8");
  96. needsCopy =
  97. !existingInfoPlist.includes(`<string>${DEV_ELECTRON_APP_BUNDLE_ID}</string>`) ||
  98. !existingInfoPlist.includes(`<string>${DEV_ELECTRON_PROTOCOL_SCHEME}</string>`) ||
  99. sourceStamp === undefined ||
  100. existingStamp !== sourceStamp;
  101. } catch {
  102. // 目录不存在、来源不是本工具生成的 bundle,下面走一次完整复制。
  103. }
  104. if (needsCopy) {
  105. // 只删除本次生成的 ignored runtime 目录,绝不触碰 node_modules 或用户数据。
  106. await rm(appPath, { recursive: true, force: true });
  107. await rm(sourceStampPath, { force: true });
  108. await mkdir(dirname(appPath), { recursive: true });
  109. // verbatimSymlinks 必须开:Electron Framework.framework 内部靠相对符号链接
  110. // (Resources -> Versions/Current/Resources、Current -> A)组织。fs.cp 默认会把
  111. // 相对链接改写成指向 node_modules 的绝对路径,主进程仍能读到,但 GPU / network
  112. // 等 macOS 沙箱子进程只允许读本 bundle 目录,顺链接出去会被拦,表现为
  113. // "icudtl.dat not found in bundle" 然后 "GPU process isn't usable. Goodbye."。
  114. await cp(electronAppPath, appPath, { recursive: true, verbatimSymlinks: true });
  115. const patchedInfoPlist = patchDevElectronInfoPlist(await readFile(infoPlistPath, "utf8"));
  116. await writeFile(infoPlistPath, patchedInfoPlist, "utf8");
  117. await signApp(appPath);
  118. // 指纹最后写:中途失败时下次仍会判定为需要重拷,不会留下半成品缓存。
  119. if (sourceStamp !== undefined) await writeFile(sourceStampPath, sourceStamp, "utf8");
  120. }
  121. return {
  122. appPath,
  123. executablePath: posix.join(appPath, "Contents", "MacOS", "Electron"),
  124. };
  125. }