node-pty-package-assets.mjs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { cpSync, existsSync, mkdirSync } from "node:fs";
  2. import { createRequire } from "node:module";
  3. import { dirname, resolve } from "node:path";
  4. const require = createRequire(import.meta.url);
  5. export function restoreTargetNodePtyPrebuild({ desktopPackageRoot, targetPlatform }) {
  6. if (targetPlatform.os !== "linux") {
  7. console.log(`[beforePack] node-pty prebuild restore skipped for ${targetPlatform.key}`);
  8. return;
  9. }
  10. const platformKey = targetPlatform.key;
  11. const sourcePackageName = `@lydell/node-pty-${platformKey}`;
  12. let sourceBinaryPath;
  13. try {
  14. sourceBinaryPath = resolveSourceNodePtyPrebuildPath({ sourcePackageName, platformKey });
  15. } catch (error) {
  16. const message = error instanceof Error ? error.message : String(error);
  17. throw new Error(`缺少 ${sourcePackageName},无法为 ${platformKey} 打包 node-pty: ${message}`);
  18. }
  19. const nodePtyPackageRoot = dirname(
  20. require.resolve("node-pty/package.json", { paths: [desktopPackageRoot] }),
  21. );
  22. const targetPrebuildDir = resolve(nodePtyPackageRoot, "prebuilds", platformKey);
  23. const targetBinaryPath = resolve(targetPrebuildDir, "pty.node");
  24. // Linux 包中 node-pty 本体只会查自己的 prebuilds/linux-*/pty.node,
  25. // 但 Linux 预编译文件实际来自 @lydell/node-pty-linux-* 平台包;若排除该平台包,
  26. // 而 node-pty 自身目录没有 linux prebuild,最终安装包里会缺 pty.node,终端启动失败。
  27. // 这里在 beforePack 阶段恢复依赖资产,让后续 asarUnpack 按标准链路处理 native addon。
  28. mkdirSync(targetPrebuildDir, { recursive: true });
  29. cpSync(sourceBinaryPath, targetBinaryPath);
  30. if (!existsSync(targetBinaryPath))
  31. throw new Error(`node-pty 预编译产物恢复失败: ${targetBinaryPath}`);
  32. console.log(`[beforePack] node-pty prebuild restored: ${targetBinaryPath}`);
  33. }
  34. export function resolveSourceNodePtyPrebuildPath({ sourcePackageName, platformKey }) {
  35. const sourcePackageEntry = require.resolve(sourcePackageName);
  36. let currentDir = dirname(sourcePackageEntry);
  37. while (currentDir !== dirname(currentDir)) {
  38. const candidatePath = resolve(currentDir, "prebuilds", platformKey, "pty.node");
  39. if (existsSync(candidatePath)) return candidatePath;
  40. currentDir = dirname(currentDir);
  41. }
  42. // @lydell/node-pty-linux-* 通过 package exports 只暴露 lib/index.js,
  43. // 不能再解析 package.json。这里从公开入口向上寻找 prebuilds,兼容 exports 限制。
  44. throw new Error(
  45. `缺少 node-pty 预编译产物: ${sourcePackageName}/prebuilds/${platformKey}/pty.node`,
  46. );
  47. }
  48. export function resolvePackagedNodePtyPrebuildPath({ resourcesDir, platformKey }) {
  49. return resolve(
  50. resourcesDir,
  51. "app.asar.unpacked",
  52. "node_modules",
  53. "node-pty",
  54. "prebuilds",
  55. platformKey,
  56. "pty.node",
  57. );
  58. }