build-sea.test.mjs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. import assert from "node:assert/strict";
  2. import { execFile, spawnSync } from "node:child_process";
  3. import { createHash } from "node:crypto";
  4. import { createReadStream } from "node:fs";
  5. import { chmod, copyFile, cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  6. import { createServer } from "node:http";
  7. import { tmpdir } from "node:os";
  8. import { dirname, join } from "node:path";
  9. import { fileURLToPath, pathToFileURL } from "node:url";
  10. import test from "node:test";
  11. import { promisify } from "node:util";
  12. import {
  13. adHocCodesignArgs,
  14. hostTarget,
  15. isHostTarget,
  16. nodeReleaseArtifact,
  17. nodeReleaseUrl,
  18. outputBinaryName,
  19. parseBuildSeaArgs,
  20. postjectArgsForTarget,
  21. resolvePostjectBin,
  22. shouldAdHocSignMacTarget,
  23. supportedTargets,
  24. } from "../scripts/build-sea.mjs";
  25. import {
  26. readWindowsAuthenticodeDirectory,
  27. removeWindowsAuthenticodeSignature,
  28. removeWindowsAuthenticodeSignatureFromBuffer,
  29. } from "../scripts/windows-authenticode.mjs";
  30. import {
  31. collectSeaOfficialPluginAssets,
  32. officialSeaPlugins,
  33. } from "../scripts/sea-official-plugin-assets.mjs";
  34. import {
  35. bundledSkillPackRequiredPaths,
  36. collectSeaBundledSkillAssets,
  37. seaBundledSkillAssetPrefix,
  38. seaBundledSkillManifestAssetKey,
  39. } from "../scripts/sea-bundled-skill-assets.mjs";
  40. import {
  41. collectSeaTuiAssets,
  42. opentuiNativePackageForTarget,
  43. seaTuiAssetPrefix,
  44. } from "../scripts/sea-tui-assets.mjs";
  45. import { placeRuntimePackage } from "../scripts/sea-runtime-package-resolution.mjs";
  46. import {
  47. collectSeaRuntimeToolAssets,
  48. seaRuntimeToolManifestAssetKey,
  49. } from "../scripts/sea-runtime-tool-assets.mjs";
  50. import {
  51. prepareSeaRuntimeToolAssets,
  52. resolveSeaRuntimeToolPreparationPlan,
  53. } from "../scripts/sea-runtime-tool-prepare.mjs";
  54. import { packSourceAsDeterministicTarGzip } from "../../../../../scripts/deterministic-tar-archive.mjs";
  55. import { writeNativeSearchBundleMeta } from "../../../../../scripts/native-search-tools-bundle-meta.mjs";
  56. import { resolveNativeSearchPrebuiltPlan } from "../../../../../scripts/native-search-tools-config.mjs";
  57. import {
  58. collectSeaPlaywrightAssets,
  59. seaPlaywrightManifestAssetKey,
  60. } from "../scripts/sea-playwright-assets.mjs";
  61. import {
  62. collectSeaProviderConfigAssets,
  63. SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY,
  64. } from "../scripts/sea-provider-config-assets.mjs";
  65. const PE_FIXTURE_OFFSET = 0x80;
  66. const PE_SIGNATURE_SIZE = 4;
  67. const COFF_HEADER_SIZE = 20;
  68. const COFF_OPTIONAL_HEADER_SIZE_OFFSET = 16;
  69. const PE32_MAGIC = 0x10b;
  70. const PE32_PLUS_MAGIC = 0x20b;
  71. const PE32_OPTIONAL_HEADER_SIZE = 0xe0;
  72. const PE32_PLUS_OPTIONAL_HEADER_SIZE = 0xf0;
  73. const PE32_NUMBER_OF_DIRECTORIES_OFFSET = 92;
  74. const PE32_DATA_DIRECTORIES_OFFSET = 96;
  75. const PE32_PLUS_NUMBER_OF_DIRECTORIES_OFFSET = 108;
  76. const PE32_PLUS_DATA_DIRECTORIES_OFFSET = 112;
  77. const SECURITY_DIRECTORY_INDEX = 4;
  78. const DATA_DIRECTORY_ENTRY_SIZE = 8;
  79. const CERTIFICATE_OFFSET = 0x200;
  80. const CERTIFICATE_SIZE = 0x20;
  81. const DATA_DIRECTORY_COUNT = 16;
  82. const PE_SIGNATURE = 0x00004550;
  83. const DOS_MAGIC = 0x5a4d;
  84. test("includes the production ZCode Built-in Provider Config as a SEA asset", async () => {
  85. const root = fileURLToPath(new URL("../../../../..", import.meta.url));
  86. const assets = await collectSeaProviderConfigAssets({ root, env: { ZCODE_ENV: "production" } });
  87. const zcodeBuiltinFilePath = assets[SEA_ZCODE_BUILTIN_PROVIDER_CONFIG_ASSET_KEY];
  88. assert.ok(zcodeBuiltinFilePath);
  89. assert.deepEqual(
  90. JSON.parse(await readFile(zcodeBuiltinFilePath, "utf8")),
  91. JSON.parse(
  92. await readFile(
  93. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  94. "utf8",
  95. ),
  96. ),
  97. );
  98. });
  99. const createMachOExecutableFixture = (label) => {
  100. const labelBytes = Buffer.from(label);
  101. const contents = Buffer.alloc(32 + labelBytes.length);
  102. contents.writeUInt32LE(0xfeedfacf, 0);
  103. contents.writeUInt32LE(0x0100000c, 4);
  104. contents.writeUInt32LE(2, 12);
  105. labelBytes.copy(contents, 32);
  106. return contents;
  107. };
  108. const createPeFixture = ({ pe32Plus = true, signed = true, trailingBytes = 0 } = {}) => {
  109. const optionalHeaderSize = pe32Plus ? PE32_PLUS_OPTIONAL_HEADER_SIZE : PE32_OPTIONAL_HEADER_SIZE;
  110. const magic = pe32Plus ? PE32_PLUS_MAGIC : PE32_MAGIC;
  111. const dataDirectoriesOffset = pe32Plus
  112. ? PE32_PLUS_DATA_DIRECTORIES_OFFSET
  113. : PE32_DATA_DIRECTORIES_OFFSET;
  114. const numberOfDirectoriesOffset = pe32Plus
  115. ? PE32_PLUS_NUMBER_OF_DIRECTORIES_OFFSET
  116. : PE32_NUMBER_OF_DIRECTORIES_OFFSET;
  117. const optionalHeaderOffset = PE_FIXTURE_OFFSET + PE_SIGNATURE_SIZE + COFF_HEADER_SIZE;
  118. const securityDirectoryEntryOffset =
  119. optionalHeaderOffset +
  120. dataDirectoriesOffset +
  121. SECURITY_DIRECTORY_INDEX * DATA_DIRECTORY_ENTRY_SIZE;
  122. const length = signed
  123. ? CERTIFICATE_OFFSET + CERTIFICATE_SIZE + trailingBytes
  124. : CERTIFICATE_OFFSET;
  125. const contents = Buffer.alloc(length);
  126. contents.writeUInt16LE(DOS_MAGIC, 0);
  127. contents.writeUInt32LE(PE_FIXTURE_OFFSET, 0x3c);
  128. contents.writeUInt32LE(PE_SIGNATURE, PE_FIXTURE_OFFSET);
  129. contents.writeUInt16LE(
  130. optionalHeaderSize,
  131. PE_FIXTURE_OFFSET + PE_SIGNATURE_SIZE + COFF_OPTIONAL_HEADER_SIZE_OFFSET,
  132. );
  133. contents.writeUInt16LE(magic, optionalHeaderOffset);
  134. contents.writeUInt32LE(DATA_DIRECTORY_COUNT, optionalHeaderOffset + numberOfDirectoriesOffset);
  135. if (signed) {
  136. contents.writeUInt32LE(CERTIFICATE_OFFSET, securityDirectoryEntryOffset);
  137. contents.writeUInt32LE(CERTIFICATE_SIZE, securityDirectoryEntryOffset + 4);
  138. contents.fill(0xa5, CERTIFICATE_OFFSET, CERTIFICATE_OFFSET + CERTIFICATE_SIZE);
  139. }
  140. return {
  141. contents,
  142. securityDirectoryEntryOffset,
  143. };
  144. };
  145. test("defaults SEA target to the current host platform and arch", () => {
  146. assert.deepEqual(
  147. parseBuildSeaArgs([], {
  148. hostArch: "arm64",
  149. hostPlatform: "darwin",
  150. }),
  151. {
  152. help: false,
  153. nodeBinaries: {},
  154. targets: ["darwin-arm64"],
  155. },
  156. );
  157. });
  158. test("keeps package SEA build scripts aligned with the existing all-target contract", async () => {
  159. const cliPackage = JSON.parse(
  160. await readFile(join(import.meta.dirname, "..", "package.json"), "utf8"),
  161. );
  162. const cliWorkspacePackage = JSON.parse(
  163. await readFile(join(import.meta.dirname, "..", "..", "..", "package.json"), "utf8"),
  164. );
  165. const rootPackage = JSON.parse(
  166. await readFile(join(import.meta.dirname, "..", "..", "..", "..", "..", "package.json"), "utf8"),
  167. );
  168. assert.equal(
  169. cliPackage.scripts["build:sea"],
  170. "pnpm --dir ../../../.. build:sea:prepare && node scripts/build-sea.mjs --all",
  171. );
  172. assert.equal(cliPackage.scripts["build:sea:all"], undefined);
  173. assert.equal(cliWorkspacePackage.scripts["build:sea"], "pnpm --filter @zcode/cli build:sea");
  174. assert.equal(cliWorkspacePackage.scripts["build:sea:all"], undefined);
  175. assert.equal(rootPackage.scripts["build:sea"], "pnpm --dir apps/zcode-cli build:sea");
  176. assert.equal(
  177. rootPackage.scripts["build:sea:all"],
  178. "pnpm install && pnpm --dir apps/zcode-cli build:sea",
  179. );
  180. });
  181. test("parses repeated and comma-separated SEA targets", () => {
  182. const parsed = parseBuildSeaArgs([
  183. "--",
  184. "--target",
  185. "linux-x64",
  186. "--targets=win-x64,darwin-x64",
  187. "--target",
  188. "linux-x64",
  189. ]);
  190. assert.deepEqual(parsed.targets, ["linux-x64", "win-x64", "darwin-x64"]);
  191. });
  192. test("parses all supported SEA targets", () => {
  193. assert.deepEqual(parseBuildSeaArgs(["--all"]).targets, supportedTargets);
  194. });
  195. test("platform flags narrow the SEA target set", () => {
  196. // `pnpm build:sea --linux` 让 build-sea.mjs 收到 `--all --linux`;`pnpm run build:sea -- --linux` 多一个 `--`。
  197. assert.deepEqual(parseBuildSeaArgs(["--all", "--linux"]).targets, ["linux-arm64", "linux-x64"]);
  198. assert.deepEqual(parseBuildSeaArgs(["--all", "--", "--linux"]).targets, [
  199. "linux-arm64",
  200. "linux-x64",
  201. ]);
  202. assert.deepEqual(parseBuildSeaArgs(["--all", "--darwin", "--linux"]).targets, [
  203. "darwin-arm64",
  204. "darwin-x64",
  205. "linux-arm64",
  206. "linux-x64",
  207. ]);
  208. assert.deepEqual(parseBuildSeaArgs(["--win"]).targets, ["win-arm64", "win-x64"]);
  209. assert.deepEqual(parseBuildSeaArgs(["--targets=linux-x64,win-x64", "--linux"]).targets, [
  210. "linux-x64",
  211. ]);
  212. });
  213. test("rejects platform flags that leave no SEA target", () => {
  214. assert.throws(
  215. () => parseBuildSeaArgs(["--target", "darwin-x64", "--linux"]),
  216. /No SEA target left after --linux/,
  217. );
  218. });
  219. test("uses node-binary targets when no explicit target selector is provided", () => {
  220. // Windows 会按宿主路径规则解析 binary 路径,不能硬编码 POSIX 绝对路径作为预期。
  221. const linuxBinary = join(tmpdir(), "node binaries", "linux", "node");
  222. const windowsBinary = join(tmpdir(), "node binaries", "win", "node.exe");
  223. const parsed = parseBuildSeaArgs([
  224. "--node-binary",
  225. `linux-x64=${linuxBinary}`,
  226. `--node-binary=win32-x64=${windowsBinary}`,
  227. ]);
  228. assert.deepEqual(parsed.targets, ["linux-x64", "win-x64"]);
  229. assert.equal(parsed.nodeBinaries["linux-x64"], linuxBinary);
  230. assert.equal(parsed.nodeBinaries["win-x64"], windowsBinary);
  231. });
  232. test("rejects unsupported SEA targets", () => {
  233. assert.throws(
  234. () => parseBuildSeaArgs(["--target", "linux-s390x"]),
  235. /Unsupported SEA target "linux-s390x"/,
  236. );
  237. });
  238. test("rejects empty SEA target selectors", () => {
  239. assert.throws(() => parseBuildSeaArgs(["--target="]), /Missing SEA target value/);
  240. });
  241. test("maps SEA targets to output binary names", () => {
  242. assert.equal(outputBinaryName("darwin-arm64"), "zcode-darwin-arm64");
  243. assert.equal(outputBinaryName("linux-x64"), "zcode-linux-x64");
  244. assert.equal(outputBinaryName("win-arm64"), "zcode-windows-arm64.exe");
  245. assert.equal(outputBinaryName("win-x64"), "zcode-windows-x64.exe");
  246. });
  247. test("prepares every SEA target in the desktop bundled-tools layout", () => {
  248. assert.deepEqual(
  249. supportedTargets.map((target) => {
  250. const plan = resolveSeaRuntimeToolPreparationPlan({ root: "/repo", target });
  251. return [target, plan.platformKey, plan.enabled];
  252. }),
  253. [
  254. ["darwin-arm64", "darwin-arm64", true],
  255. ["darwin-x64", "darwin-x64", true],
  256. ["linux-arm64", "linux-arm64", true],
  257. ["linux-x64", "linux-x64", true],
  258. ["win-arm64", "win32-arm64", true],
  259. ["win-x64", "win32-x64", true],
  260. ],
  261. );
  262. });
  263. test("downloads the complete SEA runtime tool set before asset collection", async () => {
  264. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-prepare-"));
  265. const archives = new Map();
  266. let requestCount = 0;
  267. const server = createServer((request, response) => {
  268. requestCount += 1;
  269. const archivePath = archives.get(request.url ?? "");
  270. if (!archivePath) {
  271. response.writeHead(404).end();
  272. return;
  273. }
  274. response.writeHead(200, { "content-type": "application/gzip" });
  275. createReadStream(archivePath).pipe(response);
  276. });
  277. await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
  278. try {
  279. const address = server.address();
  280. assert.ok(address && typeof address !== "string");
  281. const baseUrl = `http://127.0.0.1:${address.port}`;
  282. const nativeBaseUrl = `${baseUrl}/native`;
  283. const env = {
  284. NATIVE_SEARCH_RIPGREP_DOWNLOAD_BASE_URL: `${baseUrl}/microsoft-ripgrep`,
  285. NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: nativeBaseUrl,
  286. };
  287. const outputDir = join(directory, "root/packages/desktop/bundled-tools/darwin-arm64");
  288. const nativePlan = resolveNativeSearchPrebuiltPlan({
  289. platform: "darwin",
  290. arch: "arm64",
  291. outputDir,
  292. env,
  293. });
  294. const fixtures = nativePlan.artifacts.map((artifact) => ({
  295. artifact,
  296. binaryName: artifact.binaryName,
  297. downloadUrl: artifact.downloadUrl,
  298. contents: createMachOExecutableFixture(`${artifact.toolId}-fixture`),
  299. toolId: artifact.toolId,
  300. }));
  301. for (const [index, fixture] of fixtures.entries()) {
  302. if (fixture.artifact.source === "official") {
  303. await mkdir(dirname(fixture.artifact.binaryPath), { recursive: true });
  304. await writeFile(fixture.artifact.binaryPath, fixture.contents);
  305. await chmod(fixture.artifact.binaryPath, 0o755);
  306. writeNativeSearchBundleMeta(fixture.artifact, nativePlan.platformKey);
  307. continue;
  308. }
  309. const sourcePath = join(directory, `source-${index}`, fixture.binaryName);
  310. const archivePath = join(directory, `archive-${index}.tar.gz`);
  311. await mkdir(dirname(sourcePath), { recursive: true });
  312. await writeFile(sourcePath, fixture.contents);
  313. await chmod(sourcePath, 0o755);
  314. packSourceAsDeterministicTarGzip(sourcePath, archivePath);
  315. fixture.artifact.archiveSha256 = createHash("sha256")
  316. .update(await readFile(archivePath))
  317. .digest("hex");
  318. archives.set(new URL(fixture.downloadUrl).pathname, archivePath);
  319. }
  320. await prepareSeaRuntimeToolAssets({
  321. root: join(directory, "root"),
  322. target: "darwin-arm64",
  323. env,
  324. prebuiltPlan: nativePlan,
  325. });
  326. const fixtureByToolId = new Map(fixtures.map((fixture) => [fixture.toolId, fixture.contents]));
  327. assert.deepEqual(await readFile(nativePlan.bfsPath), fixtureByToolId.get("bfs"));
  328. assert.deepEqual(await readFile(nativePlan.ugrepPath), fixtureByToolId.get("ugrep"));
  329. assert.deepEqual(await readFile(nativePlan.rgPath), fixtureByToolId.get("ripgrep"));
  330. assert.equal(requestCount, 2);
  331. } finally {
  332. await new Promise((resolvePromise, rejectPromise) => {
  333. server.close((error) => (error ? rejectPromise(error) : resolvePromise()));
  334. });
  335. await rm(directory, { force: true, recursive: true });
  336. }
  337. });
  338. test("maps SEA targets to OpenTUI native package names", () => {
  339. assert.equal(opentuiNativePackageForTarget("darwin-arm64"), "@mbears/opentui-core-darwin-arm64");
  340. assert.equal(opentuiNativePackageForTarget("linux-x64"), "@mbears/opentui-core-linux-x64");
  341. assert.equal(opentuiNativePackageForTarget("win-arm64"), "@mbears/opentui-core-win32-arm64");
  342. assert.equal(opentuiNativePackageForTarget("win-x64"), "@mbears/opentui-core-win32-x64");
  343. });
  344. for (const fixture of [
  345. {
  346. expectedTools: [
  347. ["bfs", "4.1.1", "bfs"],
  348. ["ripgrep", "14.1.1", "rg"],
  349. ["ugrep", "7.8.4", "ugrep"],
  350. ],
  351. platformKey: "darwin-arm64",
  352. target: "darwin-arm64",
  353. },
  354. {
  355. expectedTools: [
  356. ["bfs", "4.1.1", "bfs"],
  357. ["ripgrep", "14.1.1", "rg"],
  358. ["ugrep", "7.8.4", "ugrep"],
  359. ],
  360. platformKey: "darwin-x64",
  361. target: "darwin-x64",
  362. },
  363. {
  364. expectedTools: [
  365. ["bfs", "4.1.1", "bfs"],
  366. ["ripgrep", "14.1.1", "rg"],
  367. ["ugrep", "7.8.4", "ugrep"],
  368. ],
  369. platformKey: "linux-arm64",
  370. target: "linux-arm64",
  371. },
  372. {
  373. expectedTools: [
  374. ["bfs", "4.1.1", "bfs"],
  375. ["ripgrep", "14.1.1", "rg"],
  376. ["ugrep", "7.8.4", "ugrep"],
  377. ],
  378. platformKey: "linux-x64",
  379. target: "linux-x64",
  380. },
  381. {
  382. expectedTools: [
  383. ["ripgrep", "14.1.1", "rg.exe"],
  384. ["ugrep", "7.8.4", "ugrep.exe"],
  385. ],
  386. platformKey: "win32-arm64",
  387. target: "win-arm64",
  388. },
  389. {
  390. expectedTools: [
  391. ["ripgrep", "14.1.1", "rg.exe"],
  392. ["ugrep", "7.8.4", "ugrep.exe"],
  393. ],
  394. platformKey: "win32-x64",
  395. target: "win-x64",
  396. },
  397. ]) {
  398. test(`includes target runtime tools for ${fixture.target}`, async () => {
  399. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-tools-"));
  400. const root = join(directory, "root");
  401. const stagingDirectory = join(directory, "staging");
  402. try {
  403. for (const [toolId, , binaryName] of fixture.expectedTools) {
  404. await writeTestFile(
  405. root,
  406. `packages/desktop/bundled-tools/${fixture.platformKey}/${toolId}/${binaryName}`,
  407. `${fixture.target}:${toolId}`,
  408. );
  409. }
  410. // SEA 内嵌原生工具的许可声明与来源清单;材料取自仓库登记,fixture 根目录需带上同一份。
  411. const repositoryRoot = fileURLToPath(new URL("../../../../..", import.meta.url));
  412. await cp(
  413. join(repositoryRoot, "third-party/native-search"),
  414. join(root, "third-party/native-search"),
  415. { recursive: true },
  416. );
  417. const { assets, manifest } = await collectSeaRuntimeToolAssets({
  418. root,
  419. stagingDirectory,
  420. target: fixture.target,
  421. });
  422. assert.deepEqual(
  423. manifest.tools.map(({ id, version, binaryName }) => [id, version, binaryName]),
  424. fixture.expectedTools,
  425. );
  426. assert.equal(typeof assets[seaRuntimeToolManifestAssetKey], "string");
  427. for (const tool of manifest.tools) {
  428. const expectedBytes = Buffer.from(`${fixture.target}:${tool.id}`);
  429. assert.equal(tool.size, expectedBytes.byteLength);
  430. assert.equal(tool.sha256, createHash("sha256").update(expectedBytes).digest("hex"));
  431. const assetKey = `zcode-runtime-tools/${tool.id}/${tool.sha256}/${tool.binaryName}`;
  432. assert.equal(assets[assetKey].endsWith(tool.binaryName), true);
  433. }
  434. const notices = await readFile(assets["zcode-runtime-tools/THIRD-PARTY-NOTICES.txt"], "utf8");
  435. assert.ok(notices.startsWith("NATIVE SEARCH THIRD-PARTY NOTICES"));
  436. assert.deepEqual(
  437. await readFile(assets["zcode-runtime-tools/SOURCES.json"]),
  438. await readFile(join(root, "third-party/native-search/sources.json")),
  439. );
  440. } finally {
  441. await rm(directory, {
  442. force: true,
  443. recursive: true,
  444. });
  445. }
  446. });
  447. }
  448. test("fails SEA packaging when a target runtime tool is missing", async () => {
  449. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-tools-missing-"));
  450. try {
  451. await assert.rejects(
  452. collectSeaRuntimeToolAssets({
  453. root: directory,
  454. stagingDirectory: join(directory, "staging"),
  455. target: "darwin-arm64",
  456. }),
  457. /Missing SEA runtime tool bfs for darwin-arm64/,
  458. );
  459. } finally {
  460. await rm(directory, {
  461. force: true,
  462. recursive: true,
  463. });
  464. }
  465. });
  466. test("places conflicting versions of one runtime package under their consumer", () => {
  467. // TUI 闭包里已经只有一个 Zod 版本;同名不同版本的放置规则用合成数据单独覆盖。
  468. const placements = new Map();
  469. const place = (packageDirectory, fromAssetPath) =>
  470. placeRuntimePackage({ packageName: "zod", packageDirectory, fromAssetPath, placements });
  471. assert.equal(place("/store/zod@4", "node_modules/@zcode/shared"), "node_modules/zod");
  472. assert.equal(place("/store/zod@4", "node_modules/@zcode/tui"), undefined);
  473. assert.equal(
  474. place("/store/zod@3", "node_modules/legacy"),
  475. "node_modules/legacy/node_modules/zod",
  476. );
  477. });
  478. test("includes TUI workspace runtime package assets", async () => {
  479. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-tui-assets-"));
  480. const root = join(import.meta.dirname, "../../..");
  481. try {
  482. const { manifest, assets } = await collectSeaTuiAssets({
  483. root,
  484. stagingDirectory: directory,
  485. target: "linux-x64",
  486. });
  487. const paths = new Set(manifest.files.map((file) => file.path));
  488. // SEA 从缓存目录导入 TUI 时无法回退到 workspace 链接,运行时 workspace
  489. // 依赖必须和第三方依赖一样完整进入 node_modules 形状的资产闭包。
  490. assert.equal(paths.has("node_modules/@zcode/tui/package.json"), true);
  491. assert.equal(paths.has("node_modules/@zcode/tui/dist/index.js"), true);
  492. assert.equal(paths.has("node_modules/@zcode/i18n/package.json"), true);
  493. assert.equal(paths.has("node_modules/@zcode/i18n/dist/index.js"), true);
  494. assert.equal(paths.has("node_modules/@zcode/contracts/package.json"), true);
  495. assert.equal(paths.has("node_modules/@zcode/contracts/dist/index.js"), true);
  496. assert.equal(paths.has("node_modules/@zcode/shared/package.json"), true);
  497. assert.equal(paths.has("node_modules/@zcode/shared/dist/index.js"), true);
  498. assert.equal(
  499. paths.has("node_modules/@zcode/shared/dist/workspace-hook-trust-store-file.js"),
  500. true,
  501. );
  502. assert.equal(paths.has("node_modules/@zcode/i18n/src/index.ts"), false);
  503. assert.equal(paths.has("node_modules/@zcode/contracts/src/index.ts"), false);
  504. assert.equal(paths.has("node_modules/@zcode/shared/src/index.ts"), false);
  505. // session-control 只有子路径导出,没有 dist/index.js,仍须随 shared 打入 SEA。
  506. assert.equal(paths.has("node_modules/@zcode/session-control/dist/contract.js"), true);
  507. const zodPackages = manifest.files.filter((file) => file.path.endsWith("/zod/package.json"));
  508. const zodVersions = await Promise.all(
  509. zodPackages.map(async (file) => {
  510. const metadata = JSON.parse(
  511. await readFile(assets[`${seaTuiAssetPrefix}${file.path}`], "utf8"),
  512. );
  513. return metadata.version.split(".")[0];
  514. }),
  515. );
  516. assert.deepEqual([...new Set(zodVersions)].sort(), ["4"]);
  517. // 根 workspace 的源码 exports 不能原样进入只包含 dist 的 SEA runtime。
  518. for (const packageName of ["@zcode/shared", "@zcode/model-option-map"]) {
  519. const assetKey = `${seaTuiAssetPrefix}node_modules/${packageName}/package.json`;
  520. const stagedPackage = JSON.parse(await readFile(assets[assetKey], "utf8"));
  521. assert.equal(stagedPackage.exports["."], "./dist/index.js");
  522. const sourcePackage = JSON.parse(
  523. await readFile(
  524. join(root, "../..", "packages", packageName.split("/")[1], "package.json"),
  525. "utf8",
  526. ),
  527. );
  528. assert.equal(sourcePackage.exports["."], "./src/index.ts");
  529. }
  530. } finally {
  531. await rm(directory, {
  532. force: true,
  533. recursive: true,
  534. });
  535. }
  536. });
  537. test("loads TUI from an extracted SEA runtime dependency closure", async () => {
  538. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-tui-runtime-"));
  539. const root = join(import.meta.dirname, "../../..");
  540. const stagingDirectory = join(directory, "staging");
  541. const runtimeDirectory = join(directory, "runtime");
  542. try {
  543. const { assets, manifest } = await collectSeaTuiAssets({
  544. root,
  545. stagingDirectory,
  546. target: hostTarget(),
  547. });
  548. for (const file of manifest.files) {
  549. const sourcePath = assets[`${seaTuiAssetPrefix}${file.path}`];
  550. assert.equal(typeof sourcePath, "string");
  551. const outputPath = join(runtimeDirectory, file.path);
  552. await mkdir(dirname(outputPath), {
  553. recursive: true,
  554. });
  555. await copyFile(sourcePath, outputPath);
  556. }
  557. // Windows 锁定进程已加载的 opentui.dll;子进程退出释放 DLL 后,父进程才能清理目录。
  558. const entryUrl = pathToFileURL(
  559. join(runtimeDirectory, "node_modules/@zcode/tui/dist/index.js"),
  560. ).href;
  561. await promisify(execFile)(
  562. process.execPath,
  563. [
  564. "--input-type=module",
  565. "--eval",
  566. 'import assert from "node:assert/strict"; const tui = await import(process.argv[1]); assert.equal(typeof tui.runTui, "function");',
  567. entryUrl,
  568. ],
  569. { cwd: runtimeDirectory, timeout: 30000 },
  570. );
  571. } finally {
  572. await rm(directory, {
  573. force: true,
  574. recursive: true,
  575. });
  576. }
  577. });
  578. test("includes the pinned Playwright runtime required by headless Browser Use", async () => {
  579. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-playwright-assets-"));
  580. const root = join(import.meta.dirname, "../../..");
  581. try {
  582. const { assets, manifest } = await collectSeaPlaywrightAssets({
  583. root,
  584. stagingDirectory: directory,
  585. target: "linux-x64",
  586. });
  587. const paths = new Set(manifest.files.map((file) => file.path));
  588. assert.equal(manifest.packageVersion, "1.59.1");
  589. assert.equal(typeof assets[seaPlaywrightManifestAssetKey], "string");
  590. assert.equal(paths.has("node_modules/playwright-core/package.json"), true);
  591. assert.equal(paths.has("node_modules/playwright-core/index.js"), true);
  592. assert.equal(paths.has("node_modules/playwright-core/lib/server/browserType.js"), true);
  593. } finally {
  594. await rm(directory, { force: true, recursive: true });
  595. }
  596. });
  597. test("keeps the Browser Use SEA release at 0.5.2 with complete runtime assets", async () => {
  598. const root = join(import.meta.dirname, "../../..");
  599. const browserUsePlugin = officialSeaPlugins.find((plugin) => plugin.name === "browser-use");
  600. assert.equal(browserUsePlugin?.version, "0.5.2");
  601. assert.deepEqual(browserUsePlugin?.requiredRuntimePaths, [
  602. "scripts/browser-client.mjs",
  603. "docs/api.json",
  604. "docs/documents.json",
  605. "docs/overview.md",
  606. "docs/recording.md",
  607. "docs/workflow.md",
  608. "skills/control-browser/SKILL.md",
  609. "skills/web-gui-tester/SKILL.md",
  610. ]);
  611. const packageJson = JSON.parse(
  612. await readFile(join(root, browserUsePlugin.rootPath, "package.json"), "utf8"),
  613. );
  614. const pluginManifest = JSON.parse(
  615. await readFile(join(root, browserUsePlugin.rootPath, ".zcode-plugin", "plugin.json"), "utf8"),
  616. );
  617. assert.deepEqual(
  618. {
  619. manifest: pluginManifest.version,
  620. package: packageJson.version,
  621. sea: browserUsePlugin.version,
  622. },
  623. {
  624. manifest: "0.5.2",
  625. package: "0.5.2",
  626. sea: "0.5.2",
  627. },
  628. );
  629. // Bug 原因:新增录屏能力时重写了整段插件描述,并把原生 WebM 误写成 MP4。
  630. assert.equal(
  631. pluginManifest.description,
  632. "Built-in browser automation runtime and guidance for Desktop IAB and explicitly enabled CLI-managed headless CDP: open, navigate, inspect, click, type, screenshot, record workspace WebM videos, and verify web pages and local dev targets.",
  633. );
  634. });
  635. test("keeps SEA official plugin versions aligned with package and plugin manifests", async () => {
  636. const root = join(import.meta.dirname, "../../..");
  637. for (const plugin of officialSeaPlugins) {
  638. const packageJson = JSON.parse(
  639. await readFile(join(root, plugin.rootPath, "package.json"), "utf8"),
  640. );
  641. const pluginManifest = JSON.parse(
  642. await readFile(join(root, plugin.rootPath, ".zcode-plugin", "plugin.json"), "utf8"),
  643. );
  644. assert.deepEqual(
  645. {
  646. manifest: pluginManifest.version,
  647. package: packageJson.version,
  648. sea: plugin.version,
  649. },
  650. {
  651. manifest: plugin.version,
  652. package: plugin.version,
  653. sea: plugin.version,
  654. },
  655. plugin.name,
  656. );
  657. }
  658. });
  659. test("includes the bundled skill pack as content-hashed SEA assets", async () => {
  660. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-assets-"));
  661. const root = join(import.meta.dirname, "../../..");
  662. try {
  663. const { assets, manifest } = await collectSeaBundledSkillAssets({
  664. root,
  665. stagingDirectory: directory,
  666. });
  667. const paths = new Set(manifest.files.map((file) => file.path));
  668. assert.equal(manifest.version, 1);
  669. assert.match(manifest.hash, /^[0-9a-f]{64}$/u);
  670. assert.equal(typeof assets[seaBundledSkillManifestAssetKey], "string");
  671. for (const requiredPath of bundledSkillPackRequiredPaths) {
  672. assert.equal(paths.has(requiredPath), true, requiredPath);
  673. assert.equal(typeof assets[`${seaBundledSkillAssetPrefix}${requiredPath}`], "string");
  674. }
  675. // 资产只来自 skills/:README 之类的包元数据不进二进制。
  676. assert.equal(
  677. [...paths].every((path) => path.startsWith("skills/")),
  678. true,
  679. );
  680. for (const file of manifest.files) {
  681. assert.match(file.sha256, /^[0-9a-f]{64}$/u);
  682. }
  683. } finally {
  684. await rm(directory, { force: true, recursive: true });
  685. }
  686. });
  687. test("rejects a bundled skill pack that lost a required file", async () => {
  688. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-incomplete-"));
  689. const root = join(directory, "root");
  690. try {
  691. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/SKILL.md", "# s");
  692. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/patterns.md", "#");
  693. await assert.rejects(
  694. collectSeaBundledSkillAssets({ root, stagingDirectory: join(directory, "staging") }),
  695. /Missing bundled skill pack required asset/u,
  696. );
  697. } finally {
  698. await rm(directory, { force: true, recursive: true });
  699. }
  700. });
  701. test("allows skill-only official plugins when SEA runtime assets are required", async () => {
  702. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-runtime-assets-"));
  703. const root = join(directory, "root");
  704. const stagingDirectory = join(directory, "staging");
  705. try {
  706. await writeVisualizePluginFixture(root);
  707. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  708. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  709. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  710. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  711. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  712. await writeTestFile(root, "packages/browser-use-plugin/skills/control-browser/SKILL.md", "");
  713. await writeTestFile(root, "packages/browser-use-plugin/skills/web-gui-tester/SKILL.md", "");
  714. await writeTestFile(root, "packages/browser-use-plugin/docs/api.json", "{}");
  715. await writeTestFile(root, "packages/browser-use-plugin/docs/documents.json", "[]");
  716. await writeTestFile(root, "packages/browser-use-plugin/docs/overview.md", "");
  717. await writeTestFile(root, "packages/browser-use-plugin/docs/recording.md", "");
  718. await writeTestFile(root, "packages/browser-use-plugin/docs/workflow.md", "");
  719. await writeTestFile(root, "packages/browser-use-plugin/scripts/browser-client.mjs", "");
  720. await writeDocumentPluginFixtures(root);
  721. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  722. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  723. await writeTestFile(
  724. root,
  725. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  726. "{}",
  727. );
  728. await writeTestFile(
  729. root,
  730. "packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md",
  731. "",
  732. );
  733. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  734. await writeTestFile(root, "packages/skill-creator-plugin/skills/skill-creator/SKILL.md", "");
  735. // 新增官方内容插件后也要提供 fixture,否则采集会先报 manifest 缺失,无法验证免运行时资源。
  736. await writeTestFile(root, "packages/plugin-creator-plugin/.zcode-plugin/plugin.json", "{}");
  737. await writeTestFile(root, "packages/plugin-creator-plugin/skills/plugin-creator/SKILL.md", "");
  738. // skill-creator 用作「带可执行 hook 的 skill-only 官方插件」载体(原先由 superpowers 覆盖)。
  739. // collector 按 officialSeaPlugins 登记 + 伪造目录采集,真实 skill-creator 是否带 hook 无关紧要。
  740. await writeTestFile(root, "packages/skill-creator-plugin/hooks/hooks.json", "{}");
  741. await writeTestFile(root, "packages/skill-creator-plugin/hooks/run-hook.cmd", "");
  742. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  743. await writeTestFile(
  744. root,
  745. "packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md",
  746. "",
  747. );
  748. await writeTestFile(root, "packages/zcode-site-plugin/.zcode-plugin/plugin.json", "{}");
  749. await writeTestFile(
  750. root,
  751. "packages/zcode-site-plugin/skills/site-deploy/scripts/zcode-site.mjs",
  752. "",
  753. );
  754. await writeTestFile(root, "packages/zcode-site-plugin/skills/site-deploy/SKILL.md", "");
  755. await writeTestFile(
  756. root,
  757. "packages/zcode-site-plugin/skills/site-deploy/scripts/stage.mjs",
  758. "",
  759. );
  760. await writeTestFile(
  761. root,
  762. "packages/zcode-site-plugin/skills/site-deploy/scripts/errors.mjs",
  763. "",
  764. );
  765. // 0.4.0 起带 Sites 面板:插件自己构建的 server 与面板页面是必需运行时产物。
  766. await writeTestFile(root, "packages/zcode-site-plugin/dist/server.mjs", "");
  767. await writeTestFile(root, "packages/zcode-site-plugin/dist/ui/panel.html", "");
  768. // design 是带 hook 的纯内容型插件:requiresRuntime:false,只需 seed 必需文件。
  769. const designPlugin = officialSeaPlugins.find((plugin) => plugin.name === "design");
  770. await writeTestFile(root, "packages/design-plugin/.zcode-plugin/plugin.json", "{}");
  771. for (const seedPath of designPlugin?.requiredSeedPaths ?? [])
  772. await writeTestFile(root, join("packages/design-plugin", seedPath), "");
  773. const { manifest } = await collectSeaOfficialPluginAssets({
  774. requireRuntime: true,
  775. root,
  776. stagingDirectory,
  777. });
  778. const documentPlugin = manifest.plugins.find((item) => item.name === "documents");
  779. const browserUsePlugin = manifest.plugins.find((item) => item.name === "browser-use");
  780. const restorePlugin = manifest.plugins.find((item) => item.name === "restore-legacy-sessions");
  781. const skillCreatorPlugin = manifest.plugins.find((item) => item.name === "skill-creator");
  782. const pluginCreatorPlugin = manifest.plugins.find((item) => item.name === "plugin-creator");
  783. const designSeaPlugin = manifest.plugins.find((item) => item.name === "design");
  784. assert.equal(
  785. designSeaPlugin?.files.find((file) => file.path === "hooks/design-rules")?.mode,
  786. 0o755,
  787. );
  788. assert.equal(
  789. designSeaPlugin?.files.some((file) => file.path === "dist/mcp/server.js"),
  790. false,
  791. );
  792. const documentPaths = new Set(
  793. manifest.plugins
  794. .filter((plugin) =>
  795. ["documents", "pdf", "presentations", "spreadsheets"].includes(plugin.name),
  796. )
  797. .flatMap((plugin) => plugin.files.map((file) => file.path)),
  798. );
  799. const browserUsePaths = new Set(browserUsePlugin?.files.map((file) => file.path));
  800. const restorePaths = new Set(restorePlugin?.files.map((file) => file.path));
  801. const skillCreatorPaths = new Set(skillCreatorPlugin?.files.map((file) => file.path));
  802. const skillCreatorRunHook = skillCreatorPlugin?.files.find(
  803. (file) => file.path === "hooks/run-hook.cmd",
  804. );
  805. assert.ok(pluginCreatorPlugin);
  806. assert.equal(
  807. pluginCreatorPlugin.files.some((file) => file.path === "skills/plugin-creator/SKILL.md"),
  808. true,
  809. );
  810. assert.equal(
  811. pluginCreatorPlugin.files.some((file) => file.path === "dist/mcp/server.js"),
  812. false,
  813. );
  814. assert.equal(documentPaths.has("skills/docx/SKILL.md"), true);
  815. assert.equal(documentPaths.has("skills/pdf/SKILL.md"), true);
  816. assert.equal(documentPaths.has("skills/pptx/SKILL.md"), true);
  817. assert.equal(documentPaths.has("dist/mcp/server.js"), false);
  818. assert.equal(browserUsePaths.has("skills/control-browser/SKILL.md"), true);
  819. assert.equal(browserUsePaths.has("skills/web-gui-tester/SKILL.md"), true);
  820. assert.equal(browserUsePaths.has("docs/api.json"), true);
  821. assert.equal(browserUsePaths.has("docs/overview.md"), true);
  822. assert.equal(browserUsePaths.has("docs/workflow.md"), true);
  823. // 宿主产物已搬到独立的 node-repl-host seed 单元;browser-use 不再携带它。
  824. assert.equal(browserUsePaths.has("dist/mcp/server.js"), false);
  825. const hostPlugin = manifest.plugins.find((item) => item.name === "node-repl-host");
  826. assert.ok(hostPlugin, "the shared node_repl host must be embedded");
  827. assert.equal(
  828. new Set(hostPlugin.files.map((file) => file.path)).has("dist/mcp/server.js"),
  829. true,
  830. );
  831. assert.equal(browserUsePaths.has("scripts/browser-client.mjs"), true);
  832. // CUA 的 client 只有一份,属于 computer-use 插件;browser-use 不再镜像它。
  833. assert.equal(browserUsePaths.has("scripts/computer-use-client.mjs"), false);
  834. // CUA 的文档同理:唯一那份属于 computer-use 插件。
  835. assert.equal(browserUsePaths.has("docs/computer-use.md"), false);
  836. assert.equal(restorePaths.has("skills/restore-legacy-sessions/SKILL.md"), true);
  837. assert.equal(restorePaths.has("dist/mcp/server.js"), false);
  838. assert.equal(skillCreatorPaths.has("skills/skill-creator/SKILL.md"), true);
  839. assert.equal(skillCreatorPaths.has("hooks/hooks.json"), true);
  840. assert.equal(skillCreatorPaths.has("hooks/run-hook.cmd"), true);
  841. assert.equal(skillCreatorRunHook?.mode, 0o755);
  842. assert.equal(skillCreatorPaths.has("dist/mcp/server.js"), false);
  843. } finally {
  844. await rm(directory, {
  845. force: true,
  846. recursive: true,
  847. });
  848. }
  849. });
  850. test("requires SEA runtime assets for runtime-backed official plugins", async () => {
  851. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-missing-runtime-"));
  852. const root = join(directory, "root");
  853. const stagingDirectory = join(directory, "staging");
  854. try {
  855. await writeVisualizePluginFixture(root);
  856. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  857. // 宿主要先齐备,这条测试隔离的是 android-emulator 缺 runtime 这一种情况。
  858. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  859. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  860. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  861. await writeTestFile(root, "packages/documents-plugin/.zcode-plugin/plugin.json", "{}");
  862. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  863. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  864. await writeTestFile(
  865. root,
  866. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  867. "{}",
  868. );
  869. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  870. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  871. await assert.rejects(
  872. collectSeaOfficialPluginAssets({
  873. requireRuntime: true,
  874. root,
  875. stagingDirectory,
  876. }),
  877. /Missing android-emulator MCP runtime/,
  878. );
  879. } finally {
  880. await rm(directory, {
  881. force: true,
  882. recursive: true,
  883. });
  884. }
  885. });
  886. test("requires the Browser Use client alongside the SEA MCP runtime", async () => {
  887. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-browser-client-missing-"));
  888. const root = join(directory, "root");
  889. const stagingDirectory = join(directory, "staging");
  890. try {
  891. await writeVisualizePluginFixture(root);
  892. for (const pluginName of [
  893. "android-emulator-plugin",
  894. "browser-use-plugin",
  895. "documents-plugin",
  896. "ios-simulator-plugin",
  897. "restore-legacy-sessions-plugin",
  898. "skill-creator-plugin",
  899. "zcode-guide-plugin",
  900. ]) {
  901. await writeTestFile(root, `packages/${pluginName}/.zcode-plugin/plugin.json`, "{}");
  902. }
  903. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  904. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  905. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  906. await writeDocumentPluginFixtures(root);
  907. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  908. await assert.rejects(
  909. collectSeaOfficialPluginAssets({
  910. requireRuntime: true,
  911. root,
  912. stagingDirectory,
  913. }),
  914. /Missing browser-use runtime asset.*browser-client\.mjs/u,
  915. );
  916. } finally {
  917. await rm(directory, {
  918. force: true,
  919. recursive: true,
  920. });
  921. }
  922. });
  923. test("maps SEA targets to Node.js release artifacts and URLs", () => {
  924. assert.equal(nodeReleaseArtifact("darwin-arm64", "24.14.0"), "node-v24.14.0-darwin-arm64.tar.gz");
  925. assert.equal(nodeReleaseArtifact("linux-x64", "24.14.0"), "node-v24.14.0-linux-x64.tar.xz");
  926. assert.equal(nodeReleaseArtifact("win-arm64", "24.14.0"), "win-arm64/node.exe");
  927. assert.equal(nodeReleaseArtifact("win-x64", "24.14.0"), "win-x64/node.exe");
  928. assert.equal(
  929. nodeReleaseUrl("win-arm64", "24.14.0"),
  930. "https://nodejs.org/dist/v24.14.0/win-arm64/node.exe",
  931. );
  932. assert.equal(
  933. nodeReleaseUrl("win-x64", "24.14.0"),
  934. "https://nodejs.org/dist/v24.14.0/win-x64/node.exe",
  935. );
  936. });
  937. async function writeTestFile(root, relativePath, contents) {
  938. const filePath = join(root, relativePath);
  939. await mkdir(dirname(filePath), {
  940. recursive: true,
  941. });
  942. await writeFile(filePath, contents);
  943. }
  944. test("adds the Mach-O segment argument only for macOS targets", () => {
  945. assert.deepEqual(
  946. postjectArgsForTarget({
  947. binaryPath: "/tmp/zcode-darwin-arm64",
  948. seaBlob: "/tmp/zcode.sea.blob",
  949. sentinelFuse: "NODE_SEA_FUSE_test",
  950. target: "darwin-arm64",
  951. }),
  952. [
  953. "/tmp/zcode-darwin-arm64",
  954. "NODE_SEA_BLOB",
  955. "/tmp/zcode.sea.blob",
  956. "--sentinel-fuse",
  957. "NODE_SEA_FUSE_test",
  958. "--macho-segment-name",
  959. "NODE_SEA",
  960. ],
  961. );
  962. assert.deepEqual(
  963. postjectArgsForTarget({
  964. binaryPath: "/tmp/zcode-linux-x64",
  965. seaBlob: "/tmp/zcode.sea.blob",
  966. sentinelFuse: "NODE_SEA_FUSE_test",
  967. target: "linux-x64",
  968. }),
  969. [
  970. "/tmp/zcode-linux-x64",
  971. "NODE_SEA_BLOB",
  972. "/tmp/zcode.sea.blob",
  973. "--sentinel-fuse",
  974. "NODE_SEA_FUSE_test",
  975. ],
  976. );
  977. });
  978. test("ad-hoc signs only macOS targets built on macOS hosts", () => {
  979. assert.deepEqual(adHocCodesignArgs("/tmp/zcode-darwin-arm64"), [
  980. "--force",
  981. "--sign",
  982. "-",
  983. "/tmp/zcode-darwin-arm64",
  984. ]);
  985. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "darwin" }), true);
  986. assert.equal(shouldAdHocSignMacTarget("darwin-x64", { platform: "darwin" }), true);
  987. assert.equal(shouldAdHocSignMacTarget("linux-x64", { platform: "darwin" }), false);
  988. assert.equal(shouldAdHocSignMacTarget("win-x64", { platform: "darwin" }), false);
  989. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "linux" }), false);
  990. });
  991. test("resolves postject from a hoisted ancestor node_modules", async () => {
  992. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-postject-"));
  993. const cliDirectory = join(directory, "apps", "zcode-cli", "packages", "cli");
  994. const binDirectory = join(directory, "node_modules", ".bin");
  995. const postjectPath = join(binDirectory, "postject");
  996. try {
  997. await mkdir(cliDirectory, { recursive: true });
  998. await mkdir(binDirectory, { recursive: true });
  999. await writeFile(postjectPath, "");
  1000. assert.equal(
  1001. resolvePostjectBin({
  1002. platform: "linux",
  1003. startDirectory: cliDirectory,
  1004. }),
  1005. postjectPath,
  1006. );
  1007. } finally {
  1008. await rm(directory, {
  1009. force: true,
  1010. recursive: true,
  1011. });
  1012. }
  1013. });
  1014. test("removes and truncates a trailing Windows Authenticode certificate table", () => {
  1015. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1016. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1017. assert.equal(result.removed, true);
  1018. assert.equal(result.truncated, true);
  1019. assert.equal(result.certificateOffset, CERTIFICATE_OFFSET);
  1020. assert.equal(result.certificateSize, CERTIFICATE_SIZE);
  1021. assert.equal(result.buffer.length, CERTIFICATE_OFFSET);
  1022. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1023. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1024. assert.deepEqual(readWindowsAuthenticodeDirectory(result.buffer), {
  1025. certificateOffset: 0,
  1026. certificateSize: 0,
  1027. securityDirectoryEntryOffset,
  1028. signed: false,
  1029. });
  1030. });
  1031. test("removes a PE32 Authenticode directory without truncating non-certificate trailing data", () => {
  1032. const trailingBytes = 16;
  1033. const { contents, securityDirectoryEntryOffset } = createPeFixture({
  1034. pe32Plus: false,
  1035. trailingBytes,
  1036. });
  1037. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1038. assert.equal(result.removed, true);
  1039. assert.equal(result.truncated, false);
  1040. assert.equal(result.buffer.length, CERTIFICATE_OFFSET + CERTIFICATE_SIZE + trailingBytes);
  1041. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1042. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1043. });
  1044. test("leaves unsigned Windows PE binaries unchanged", () => {
  1045. const { contents } = createPeFixture({
  1046. signed: false,
  1047. });
  1048. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1049. assert.equal(result.removed, false);
  1050. assert.equal(result.truncated, false);
  1051. assert.equal(result.buffer, contents);
  1052. });
  1053. test("rejects Windows Authenticode directories outside the file range", () => {
  1054. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1055. contents.writeUInt32LE(contents.length + CERTIFICATE_SIZE, securityDirectoryEntryOffset);
  1056. assert.throws(
  1057. () => removeWindowsAuthenticodeSignatureFromBuffer(contents),
  1058. /Invalid PE certificate table/,
  1059. );
  1060. });
  1061. test("removes Windows Authenticode signatures from files", async () => {
  1062. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-authenticode-"));
  1063. const binaryPath = join(directory, "zcode-windows-x64.exe");
  1064. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1065. try {
  1066. await writeFile(binaryPath, contents);
  1067. const result = await removeWindowsAuthenticodeSignature(binaryPath);
  1068. const updated = await readFile(binaryPath);
  1069. assert.deepEqual(result, {
  1070. certificateOffset: CERTIFICATE_OFFSET,
  1071. certificateSize: CERTIFICATE_SIZE,
  1072. removed: true,
  1073. truncated: true,
  1074. });
  1075. assert.equal(updated.length, CERTIFICATE_OFFSET);
  1076. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset), 0);
  1077. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1078. } finally {
  1079. await rm(directory, {
  1080. force: true,
  1081. recursive: true,
  1082. });
  1083. }
  1084. });
  1085. test("matches host targets using Node.js platform names", () => {
  1086. assert.equal(
  1087. hostTarget({
  1088. arch: "x64",
  1089. platform: "win32",
  1090. }),
  1091. "win-x64",
  1092. );
  1093. assert.equal(
  1094. isHostTarget("win32-x64", {
  1095. arch: "x64",
  1096. platform: "win32",
  1097. }),
  1098. true,
  1099. );
  1100. assert.equal(
  1101. isHostTarget("linux-x64", {
  1102. arch: "arm64",
  1103. platform: "darwin",
  1104. }),
  1105. false,
  1106. );
  1107. });
  1108. test("builds SEA dependencies from the root workspace graph", async () => {
  1109. const repositoryRoot = new URL("../../../../../", import.meta.url);
  1110. const rootPackage = JSON.parse(await readFile(new URL("package.json", repositoryRoot), "utf8"));
  1111. const filters = [...rootPackage.scripts["build:sea:prepare"].matchAll(/--filter=("[^"]+"|\S+)/gu)]
  1112. .map((match) => match[1].replaceAll('"', ""))
  1113. .flatMap((filter) => ["--filter", filter]);
  1114. // 回归原因:CLI 子 workspace 的 Turbo 图看不到根 session-control,build:sea 不会生成其 dist。
  1115. const result = spawnSync("pnpm", [...filters, "list", "--depth", "-1", "--json"], {
  1116. cwd: repositoryRoot,
  1117. encoding: "utf8",
  1118. shell: process.platform === "win32",
  1119. });
  1120. assert.equal(result.status, 0, result.stderr || result.stdout);
  1121. const names = JSON.parse(result.stdout).map((pkg) => pkg.name);
  1122. assert.ok(names.includes("@zcode/session-control"));
  1123. assert.ok(!names.includes("@zcode/cli"));
  1124. });
  1125. test("can be dynamically imported when argv[1] is missing", () => {
  1126. const scriptUrl = new URL("../scripts/build-sea.mjs", import.meta.url).href;
  1127. const result = spawnSync(
  1128. process.execPath,
  1129. [
  1130. "-e",
  1131. `import(${JSON.stringify(scriptUrl)}).then((m) => console.log(m.outputBinaryName("win-x64")))`,
  1132. ],
  1133. {
  1134. encoding: "utf8",
  1135. },
  1136. );
  1137. assert.equal(result.status, 0, result.stderr);
  1138. assert.equal(result.stdout.trim(), "zcode-windows-x64.exe");
  1139. });
  1140. async function writeDocumentPluginFixtures(root) {
  1141. for (const [name, skill] of [
  1142. ["documents", "docx"],
  1143. ["pdf", "pdf"],
  1144. ["presentations", "pptx"],
  1145. ["spreadsheets", "xlsx"],
  1146. ]) {
  1147. await writeTestFile(root, `packages/${name}-plugin/.zcode-plugin/plugin.json`, "{}");
  1148. await writeTestFile(root, `packages/${name}-plugin/skills/${skill}/SKILL.md`, "");
  1149. for (const path of [
  1150. "scripts/zcode_libreoffice.py",
  1151. "scripts/libreoffice-profile/user/registrymodifications.xcu",
  1152. "scripts/libreoffice-profile/user/basic/script.xlc",
  1153. "scripts/libreoffice-profile/user/basic/dialog.xlc",
  1154. "scripts/libreoffice-profile/user/basic/Standard/script.xlb",
  1155. "scripts/libreoffice-profile/user/basic/Standard/dialog.xlb",
  1156. "scripts/libreoffice-profile/user/basic/Standard/ZCode.xba",
  1157. ]) {
  1158. await writeTestFile(root, `packages/${name}-plugin/${path}`, "fixture");
  1159. }
  1160. // 0.2.0 起文档插件带查看面板:viewer skill 与 office-runtime 构建产物都是必需资产。
  1161. await writeTestFile(root, `packages/${name}-plugin/skills/${skill}-viewer/SKILL.md`, "");
  1162. for (const runtimePath of ["dist/server.mjs", "dist/ui/assets.json", "dist/ui/panel.html"]) {
  1163. await writeTestFile(root, `packages/${name}-plugin/${runtimePath}`, "");
  1164. }
  1165. }
  1166. await writeTestFile(root, "packages/image-search-plugin/.zcode-plugin/plugin.json", "{}");
  1167. await writeTestFile(root, "packages/image-search-plugin/.mcp.json", "{}");
  1168. }
  1169. async function writeVisualizePluginFixture(root) {
  1170. // 官方清单新增静态插件后,运行时缺失用例也必须先准备其内容,避免提前失败。
  1171. const plugin = officialSeaPlugins.find((item) => item.name === "visualize");
  1172. assert.ok(plugin);
  1173. await writeTestFile(root, "packages/visualize-plugin/.zcode-plugin/plugin.json", "{}");
  1174. for (const path of plugin.requiredSeedPaths) {
  1175. await writeTestFile(root, `packages/visualize-plugin/${path}`, "");
  1176. }
  1177. }