build-sea.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import { spawnSync } from "node:child_process";
  2. import { existsSync } from "node:fs";
  3. import { chmod, copyFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join, resolve } from "node:path";
  6. import { pathToFileURL } from "node:url";
  7. import { resolveSpawnRuntimeOptions } from "../../../../../scripts/spawn-command.mjs";
  8. import { resolveDownloadedNodeBinary } from "./sea-node-download.mjs";
  9. import { stageNodeNotices } from "../../../../../scripts/third-party-notices.mjs";
  10. import {
  11. adHocCodesignArgs,
  12. hostTarget,
  13. isHostTarget,
  14. nodeReleaseArtifact,
  15. nodeReleaseUrl,
  16. outputBinaryName,
  17. parseBuildSeaArgs,
  18. postjectArgsForTarget,
  19. shouldAdHocSignMacTarget,
  20. supportedTargets,
  21. targetParts,
  22. } from "./sea-targets.mjs";
  23. import { removeWindowsAuthenticodeSignature } from "./windows-authenticode.mjs";
  24. import { collectSeaTuiAssets } from "./sea-tui-assets.mjs";
  25. import { collectSeaOfficialPluginAssets } from "./sea-official-plugin-assets.mjs";
  26. import { collectSeaRuntimeToolAssets } from "./sea-runtime-tool-assets.mjs";
  27. import { prepareSeaRuntimeToolAssets } from "./sea-runtime-tool-prepare.mjs";
  28. import { collectSeaPlaywrightAssets } from "./sea-playwright-assets.mjs";
  29. import { collectSeaProviderConfigAssets } from "./sea-provider-config-assets.mjs";
  30. export {
  31. adHocCodesignArgs,
  32. hostTarget,
  33. isHostTarget,
  34. nodeReleaseArtifact,
  35. nodeReleaseUrl,
  36. outputBinaryName,
  37. parseBuildSeaArgs,
  38. postjectArgsForTarget,
  39. shouldAdHocSignMacTarget,
  40. supportedTargets,
  41. };
  42. const usage = `Usage:
  43. node scripts/build-sea.mjs
  44. node scripts/build-sea.mjs --target linux-x64 --target win-x64
  45. node scripts/build-sea.mjs --targets linux-x64,win-x64
  46. node scripts/build-sea.mjs --all
  47. node scripts/build-sea.mjs --node-binary linux-x64=/abs/path/node
  48. Supported targets:
  49. ${supportedTargets.join(", ")}
  50. `;
  51. const root = resolve(import.meta.dirname, "../../..");
  52. const repositoryRoot = resolve(root, "../..");
  53. const cliRoot = resolve(import.meta.dirname, "..");
  54. const dist = resolve(cliRoot, "dist");
  55. const cliBundle = resolve(dist, "zcode.cjs");
  56. const seaBlobForTarget = (target) => resolve(dist, `zcode-${target}.sea.blob`);
  57. const seaConfigForTarget = (target) => resolve(dist, `sea-config-${target}.json`);
  58. const seaAssetStagingForTarget = (target) => resolve(dist, "sea-assets", target);
  59. const nodeCache = resolve(dist, "sea-node-cache");
  60. const sentinelFusePrefix = "NODE_SEA_FUSE_";
  61. export const resolvePostjectBin = ({
  62. platform = process.platform,
  63. startDirectory = cliRoot,
  64. } = {}) => {
  65. const executable = platform === "win32" ? "postject.cmd" : "postject";
  66. let directory = startDirectory;
  67. // pnpm hoisted 布局会把 postject 放到仓库根 node_modules,而不是 CLI 子包下。
  68. // 从 CLI 包目录逐级向上找,避免 SEA 构建依赖某一种安装布局。
  69. while (true) {
  70. const candidate = resolve(directory, "node_modules", ".bin", executable);
  71. if (existsSync(candidate)) return candidate;
  72. const parent = dirname(directory);
  73. if (parent === directory) return undefined;
  74. directory = parent;
  75. }
  76. };
  77. const commandText = (command, args) => [command, ...args].join(" ");
  78. const run = (command, args, options = {}) => {
  79. const result = spawnSync(command, args, {
  80. cwd: cliRoot,
  81. encoding: "utf8",
  82. stdio: "inherit",
  83. ...options,
  84. ...resolveSpawnRuntimeOptions(command),
  85. });
  86. if (result.error) {
  87. throw new Error(`${commandText(command, args)} failed: ${result.error.message}`, {
  88. cause: result.error,
  89. });
  90. }
  91. if (result.status !== 0) {
  92. throw new Error(`${commandText(command, args)} failed`);
  93. }
  94. };
  95. const findSeaFuse = async (binary) => {
  96. const contents = await readFile(binary, "latin1");
  97. const match = contents.match(/NODE_SEA_FUSE_[a-z0-9]+:0/i);
  98. if (!match) {
  99. throw new Error(
  100. `Could not find a NODE_SEA_FUSE marker in ${binary}. ` +
  101. "Use an official Node.js binary with SEA support, or fall back to `pnpm build`.",
  102. );
  103. }
  104. return match[0].replace(/:0$/, "");
  105. };
  106. const resolveNodeBinary = async ({ nodeBinaries, nodeVersion, target }) => {
  107. const explicitBinary = nodeBinaries[target];
  108. if (explicitBinary) {
  109. if (!existsSync(explicitBinary)) {
  110. throw new Error(`Configured Node.js binary for ${target} does not exist: ${explicitBinary}`);
  111. }
  112. console.log(`[sea] using ${target} Node.js binary ${explicitBinary}`);
  113. return explicitBinary;
  114. }
  115. return resolveDownloadedNodeBinary({
  116. nodeCache,
  117. nodeVersion,
  118. target,
  119. });
  120. };
  121. const prepareSeaBlob = async (target, nodeVersion) => {
  122. const seaBlob = seaBlobForTarget(target);
  123. const seaConfig = seaConfigForTarget(target);
  124. await prepareSeaRuntimeToolAssets({
  125. root: repositoryRoot,
  126. target,
  127. });
  128. const { assets: tuiAssets, manifest: tuiManifest } = await collectSeaTuiAssets({
  129. root,
  130. stagingDirectory: seaAssetStagingForTarget(target),
  131. target,
  132. });
  133. const { assets: pluginAssets, manifest: pluginManifest } = await collectSeaOfficialPluginAssets({
  134. requireRuntime: true,
  135. root,
  136. stagingDirectory: seaAssetStagingForTarget(`${target}-official-plugins`),
  137. });
  138. const { assets: runtimeToolAssets, manifest: runtimeToolManifest } =
  139. await collectSeaRuntimeToolAssets({
  140. root: repositoryRoot,
  141. stagingDirectory: seaAssetStagingForTarget(`${target}-runtime-tools`),
  142. target,
  143. });
  144. const { assets: playwrightAssets, manifest: playwrightManifest } =
  145. await collectSeaPlaywrightAssets({
  146. root,
  147. stagingDirectory: seaAssetStagingForTarget(`${target}-playwright`),
  148. target,
  149. });
  150. const providerConfigAssets = await collectSeaProviderConfigAssets({ root: repositoryRoot });
  151. const nodeLicensePath = await stageNodeNotices(seaAssetStagingForTarget(`${target}-node`), nodeVersion, repositoryRoot);
  152. await writeFile(
  153. seaConfig,
  154. JSON.stringify(
  155. {
  156. assets: {
  157. ...tuiAssets,
  158. ...pluginAssets,
  159. ...runtimeToolAssets,
  160. ...playwrightAssets,
  161. ...providerConfigAssets,
  162. "zcode-node-license": nodeLicensePath,
  163. },
  164. disableExperimentalSEAWarning: true,
  165. main: "dist/zcode.cjs",
  166. output: `dist/zcode-${target}.sea.blob`,
  167. useCodeCache: false,
  168. useSnapshot: false,
  169. },
  170. null,
  171. 2,
  172. ),
  173. );
  174. console.log(
  175. `[sea] generating SEA blob for ${target} with ${tuiManifest.files.length} TUI assets, ${pluginManifest.plugins.length} official plugins, ${runtimeToolManifest.tools.length} runtime tools, and ${playwrightManifest.files.length} Playwright assets`,
  176. );
  177. run(process.execPath, ["--experimental-sea-config", seaConfig]);
  178. return seaBlob;
  179. };
  180. const removeMacSignatureForInjection = (target, binaryPath) => {
  181. if (!shouldAdHocSignMacTarget(target)) return;
  182. console.log("[sea] removing macOS signature before injection");
  183. run("codesign", ["--remove-signature", binaryPath]);
  184. };
  185. const removeWindowsSignatureForInjection = async (target, binaryPath) => {
  186. const { releasePlatform } = targetParts(target);
  187. if (releasePlatform !== "win") return;
  188. // postject invalidates Node's original Authenticode signature; a stale PE
  189. // Security Directory can make downstream signing reject the SEA as bad Win32.
  190. const result = await removeWindowsAuthenticodeSignature(binaryPath);
  191. if (!result.removed) return;
  192. const action = result.truncated ? "removed and truncated" : "removed";
  193. console.log(
  194. `[sea] ${action} Windows Authenticode signature at offset ${result.certificateOffset}`,
  195. );
  196. };
  197. const adHocSignMacBinary = (target, binaryPath) => {
  198. if (!shouldAdHocSignMacTarget(target)) return;
  199. console.log("[sea] ad-hoc signing macOS binary after injection");
  200. run("codesign", adHocCodesignArgs(binaryPath));
  201. };
  202. const smokeTestHostTarget = async (target, binaryPath) => {
  203. if (isHostTarget(target)) {
  204. const storageRoot = await mkdtemp(join(tmpdir(), "zcode-sea-smoke-"));
  205. try {
  206. const env = {
  207. ...process.env,
  208. ZCODE_STORAGE_DIR: storageRoot,
  209. };
  210. delete env.ZCODE_BFS_BINARY;
  211. delete env.ZCODE_RG_BINARY;
  212. delete env.ZCODE_UGREP_BINARY;
  213. run(binaryPath, ["--version"], {
  214. env,
  215. });
  216. } finally {
  217. await rm(storageRoot, {
  218. force: true,
  219. recursive: true,
  220. });
  221. }
  222. return;
  223. }
  224. console.log(`[sea] skipping smoke test for foreign target ${target}`);
  225. };
  226. const buildTarget = async ({ nodeBinaries, nodeVersion, postjectBin, target }) => {
  227. const binaryPath = resolve(dist, outputBinaryName(target));
  228. const seaBlob = await prepareSeaBlob(target, nodeVersion);
  229. const targetNodeBinary = await resolveNodeBinary({
  230. nodeBinaries,
  231. nodeVersion,
  232. target,
  233. });
  234. console.log(`[sea] building ${target} -> ${binaryPath}`);
  235. await copyFile(targetNodeBinary, binaryPath);
  236. await chmod(binaryPath, 0o755);
  237. // 同一原文既内嵌到 --licenses,也随 dist 提供,单文件上传仍可取到完整材料。
  238. await stageNodeNotices(dist, nodeVersion, repositoryRoot);
  239. const sentinelFuse = await findSeaFuse(binaryPath);
  240. if (!sentinelFuse.startsWith(sentinelFusePrefix)) {
  241. throw new Error(`Unexpected SEA fuse marker in ${binaryPath}: ${sentinelFuse}`);
  242. }
  243. removeMacSignatureForInjection(target, binaryPath);
  244. await removeWindowsSignatureForInjection(target, binaryPath);
  245. run(postjectBin, postjectArgsForTarget({ binaryPath, seaBlob, sentinelFuse, target }));
  246. adHocSignMacBinary(target, binaryPath);
  247. await smokeTestHostTarget(target, binaryPath);
  248. console.log(`[sea] binary written to ${binaryPath}`);
  249. };
  250. export const main = async (argv = process.argv.slice(2)) => {
  251. const options = parseBuildSeaArgs(argv);
  252. if (options.help) {
  253. console.log(usage);
  254. return;
  255. }
  256. if (!existsSync(cliBundle)) {
  257. throw new Error("Missing dist/zcode.cjs. Run `pnpm build` first.");
  258. }
  259. const postjectBin = resolvePostjectBin();
  260. if (!postjectBin) {
  261. throw new Error("Missing postject. Run `pnpm install` before `pnpm sea`.");
  262. }
  263. const nodeVersion = process.versions.node;
  264. for (const target of options.targets) {
  265. await buildTarget({
  266. nodeBinaries: options.nodeBinaries,
  267. nodeVersion,
  268. postjectBin,
  269. target,
  270. });
  271. }
  272. };
  273. const entryPath = process.argv[1];
  274. if (entryPath && import.meta.url === pathToFileURL(entryPath).href) {
  275. try {
  276. await main();
  277. } catch (error) {
  278. console.error(error instanceof Error ? error.message : String(error));
  279. process.exitCode = 1;
  280. }
  281. }