build-sea.mjs 11 KB

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