e2e-electron-binary.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import { execFileSync } from "node:child_process";
  2. import { existsSync, readFileSync } from "node:fs";
  3. import { resolve } from "node:path";
  4. export const DEFAULT_E2E_ELECTRON_INSTALL_TIMEOUT_MS = 5 * 60_000;
  5. const MAX_CHILD_PROCESS_TIMEOUT_MS = 2_147_483_647;
  6. interface ElectronPackageInstallInput {
  7. environment: NodeJS.ProcessEnv;
  8. installScriptPath: string;
  9. packageRoot: string;
  10. timeoutMs: number;
  11. }
  12. interface ResolveE2EElectronBinaryOptions {
  13. desktopDir: string;
  14. environment?: NodeJS.ProcessEnv;
  15. installTimeoutMs?: number;
  16. installElectronPackage?: (input: ElectronPackageInstallInput) => void;
  17. repoRoot: string;
  18. }
  19. export function resolveE2EElectronBinary({
  20. desktopDir,
  21. environment = process.env,
  22. installTimeoutMs = DEFAULT_E2E_ELECTRON_INSTALL_TIMEOUT_MS,
  23. installElectronPackage = runElectronPackageInstall,
  24. repoRoot,
  25. }: ResolveE2EElectronBinaryOptions) {
  26. const packageRoots = [
  27. ...new Set([
  28. resolve(desktopDir, "node_modules", "electron"),
  29. resolve(repoRoot, "node_modules", "electron"),
  30. ]),
  31. ];
  32. const installedBinary = resolveInstalledElectronBinary(packageRoots);
  33. if (installedBinary) {
  34. return installedBinary;
  35. }
  36. const packageRoot = packageRoots.find(
  37. (candidate) =>
  38. existsSync(resolve(candidate, "package.json")) &&
  39. existsSync(resolve(candidate, "install.js")),
  40. );
  41. if (!packageRoot) {
  42. throw createElectronBinaryUnavailableError(packageRoots, "Electron package/install.js 不存在");
  43. }
  44. assertValidInstallTimeout(installTimeoutMs);
  45. const installScriptPath = resolve(packageRoot, "install.js");
  46. const mirrorForDiagnostics = formatElectronMirrorForDiagnostics(environment.ELECTRON_MIRROR);
  47. console.warn(
  48. `[e2e] Electron 可执行文件缺失,正在运行安装脚本: ${installScriptPath} ` +
  49. `(timeout=${installTimeoutMs}ms, ELECTRON_MIRROR=${mirrorForDiagnostics})`,
  50. );
  51. try {
  52. installElectronPackage({
  53. environment,
  54. installScriptPath,
  55. packageRoot,
  56. timeoutMs: installTimeoutMs,
  57. });
  58. } catch (error) {
  59. // Bug 根因:旧 WDIO 只检查 .bin/electron 包装脚本,Electron postinstall 被跳过时
  60. // 会继续交给 ChromeDriver;同时安装下载无超时,网络半开时会在配置加载阶段永久阻塞。
  61. const failureKind = isElectronInstallTimeoutError(error) ? "安装超时" : "执行失败";
  62. throw createElectronBinaryUnavailableError(
  63. packageRoots,
  64. `Electron install.js ${failureKind}(timeout=${installTimeoutMs}ms, ELECTRON_MIRROR=${mirrorForDiagnostics}, child=${formatElectronInstallError(error)})`,
  65. error,
  66. );
  67. }
  68. const repairedBinary = resolveInstalledElectronBinary(packageRoots);
  69. if (repairedBinary) {
  70. console.log(`[e2e] Electron 可执行文件已就绪: ${repairedBinary}`);
  71. return repairedBinary;
  72. }
  73. throw createElectronBinaryUnavailableError(
  74. packageRoots,
  75. "Electron install.js 已结束,但 path.txt 或其指向的可执行文件仍然缺失;请确认未设置 ELECTRON_SKIP_BINARY_DOWNLOAD",
  76. );
  77. }
  78. function resolveInstalledElectronBinary(packageRoots: string[]) {
  79. for (const packageRoot of packageRoots) {
  80. const pathFile = resolve(packageRoot, "path.txt");
  81. if (!existsSync(pathFile)) {
  82. continue;
  83. }
  84. const executableRelativePath = readFileSync(pathFile, "utf-8").trim();
  85. if (!executableRelativePath) {
  86. continue;
  87. }
  88. const executablePath = resolve(packageRoot, "dist", executableRelativePath);
  89. if (existsSync(executablePath)) {
  90. return executablePath;
  91. }
  92. }
  93. return null;
  94. }
  95. function runElectronPackageInstall({
  96. environment,
  97. installScriptPath,
  98. packageRoot,
  99. timeoutMs,
  100. }: ElectronPackageInstallInput) {
  101. execFileSync(process.execPath, [installScriptPath], {
  102. cwd: packageRoot,
  103. env: environment,
  104. // 安装脚本可能阻塞在 DNS、代理或镜像连接;SIGKILL 保证超时边界不被子进程忽略。
  105. killSignal: "SIGKILL",
  106. stdio: "inherit",
  107. timeout: timeoutMs,
  108. });
  109. }
  110. function assertValidInstallTimeout(timeoutMs: number) {
  111. if (
  112. !Number.isSafeInteger(timeoutMs) ||
  113. timeoutMs <= 0 ||
  114. timeoutMs > MAX_CHILD_PROCESS_TIMEOUT_MS
  115. ) {
  116. throw new Error(
  117. `ZCODE_E2E_ELECTRON_INSTALL_TIMEOUT_MS must be an integer between 1 and ${MAX_CHILD_PROCESS_TIMEOUT_MS}, got: ${timeoutMs}`,
  118. );
  119. }
  120. }
  121. function isElectronInstallTimeoutError(error: unknown) {
  122. if (!(error instanceof Error)) {
  123. return false;
  124. }
  125. const processError = error as Error & {
  126. code?: unknown;
  127. killed?: unknown;
  128. signal?: unknown;
  129. };
  130. return (
  131. processError.code === "ETIMEDOUT" ||
  132. (processError.killed === true && processError.signal === "SIGKILL") ||
  133. error.message.includes("ETIMEDOUT")
  134. );
  135. }
  136. function formatElectronInstallError(error: unknown) {
  137. if (!(error instanceof Error)) {
  138. return String(error);
  139. }
  140. const processError = error as Error & { code?: unknown; signal?: unknown };
  141. const details = [error.message];
  142. if (typeof processError.code === "string") {
  143. details.push(`code=${processError.code}`);
  144. }
  145. if (typeof processError.signal === "string") {
  146. details.push(`signal=${processError.signal}`);
  147. }
  148. return details.join(", ");
  149. }
  150. function formatElectronMirrorForDiagnostics(rawMirror: string | undefined) {
  151. const mirror = rawMirror?.trim();
  152. if (!mirror) {
  153. return "<default>";
  154. }
  155. try {
  156. const url = new URL(mirror);
  157. url.username = "";
  158. url.password = "";
  159. url.search = "";
  160. url.hash = "";
  161. return url.toString();
  162. } catch {
  163. return "<configured non-URL>";
  164. }
  165. }
  166. function createElectronBinaryUnavailableError(
  167. packageRoots: string[],
  168. reason: string,
  169. cause?: unknown,
  170. ) {
  171. return new Error(
  172. `[e2e] Electron binary unavailable: ${reason}. Checked package roots: ${packageRoots.join(
  173. ", ",
  174. )}`,
  175. cause === undefined ? undefined : { cause },
  176. );
  177. }