app-asar-repack.mjs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { access, rename, rm } from "node:fs/promises";
  2. export const ASAR_UNPACK_NATIVE_GLOB = "*.{node,dll,dylib,exe}";
  3. async function pathExists(path) {
  4. try {
  5. await access(path);
  6. return true;
  7. } catch {
  8. return false;
  9. }
  10. }
  11. export function createAppAsarPackArgs({ sourceDir, destinationPath, targetPlatformKey }) {
  12. return [
  13. "pack",
  14. sourceDir,
  15. destinationPath,
  16. "--unpack",
  17. ASAR_UNPACK_NATIVE_GLOB,
  18. "--unpack-dir",
  19. `node_modules/node-pty/prebuilds/${targetPlatformKey}`,
  20. ];
  21. }
  22. export async function replaceAppAsarFromStaging({
  23. sourceDir,
  24. appAsarPath,
  25. targetPlatformKey,
  26. runAsarCommand,
  27. }) {
  28. const candidateAsarPath = `${appAsarPath}.next`;
  29. const candidateUnpackedPath = `${candidateAsarPath}.unpacked`;
  30. const unpackedPath = `${appAsarPath}.unpacked`;
  31. await Promise.all([
  32. rm(candidateAsarPath, { force: true, recursive: true }),
  33. rm(candidateUnpackedPath, { force: true, recursive: true }),
  34. ]);
  35. try {
  36. runAsarCommand(
  37. createAppAsarPackArgs({
  38. sourceDir,
  39. destinationPath: candidateAsarPath,
  40. targetPlatformKey,
  41. }),
  42. );
  43. if (!(await pathExists(candidateAsarPath)) || !(await pathExists(candidateUnpackedPath))) {
  44. // CI 的 TMPDIR 位于隐藏目录 `.tmp`。旧 glob 含 `**/`,@electron/asar 用绝对路径
  45. // 匹配时不会跨过隐藏目录,导致 native 被写回 asar,同时遗留旧 unpacked 形成物理双份。
  46. throw new Error(`重打包结果缺少 app.asar 或 app.asar.unpacked: ${candidateAsarPath}`);
  47. }
  48. // 先完整生成候选文件,再替换旧 archive 和 sidecar;不会把上一次打包的跨平台 native 留在 unpacked。
  49. await rm(unpackedPath, { force: true, recursive: true });
  50. await rename(candidateUnpackedPath, unpackedPath);
  51. await rm(appAsarPath, { force: true });
  52. await rename(candidateAsarPath, appAsarPath);
  53. } finally {
  54. await Promise.all([
  55. rm(candidateAsarPath, { force: true, recursive: true }),
  56. rm(candidateUnpackedPath, { force: true, recursive: true }),
  57. ]);
  58. }
  59. }