build-sea.test.mjs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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. seaOfficialPluginManifestAssetKey,
  34. } from "../scripts/sea-official-plugin-assets.mjs";
  35. import {
  36. bundledSkillPackRequiredPaths,
  37. collectSeaBundledSkillAssets,
  38. seaBundledSkillAssetPrefix,
  39. seaBundledSkillManifestAssetKey,
  40. } from "../scripts/sea-bundled-skill-assets.mjs";
  41. import {
  42. collectSeaTuiAssets,
  43. opentuiNativePackageForTarget,
  44. seaTuiAssetPrefix,
  45. } from "../scripts/sea-tui-assets.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 ../../../.. exec turbo --skip-infer --cwd apps/zcode-cli run build --filter=!@zcode/cli --force && pnpm build && 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("uses node-binary targets when no explicit target selector is provided", () => {
  196. // Windows 会按宿主路径规则解析 binary 路径,不能硬编码 POSIX 绝对路径作为预期。
  197. const linuxBinary = join(tmpdir(), "node binaries", "linux", "node");
  198. const windowsBinary = join(tmpdir(), "node binaries", "win", "node.exe");
  199. const parsed = parseBuildSeaArgs([
  200. "--node-binary",
  201. `linux-x64=${linuxBinary}`,
  202. `--node-binary=win32-x64=${windowsBinary}`,
  203. ]);
  204. assert.deepEqual(parsed.targets, ["linux-x64", "win-x64"]);
  205. assert.equal(parsed.nodeBinaries["linux-x64"], linuxBinary);
  206. assert.equal(parsed.nodeBinaries["win-x64"], windowsBinary);
  207. });
  208. test("rejects unsupported SEA targets", () => {
  209. assert.throws(
  210. () => parseBuildSeaArgs(["--target", "linux-s390x"]),
  211. /Unsupported SEA target "linux-s390x"/,
  212. );
  213. });
  214. test("rejects empty SEA target selectors", () => {
  215. assert.throws(() => parseBuildSeaArgs(["--target="]), /Missing SEA target value/);
  216. });
  217. test("maps SEA targets to output binary names", () => {
  218. assert.equal(outputBinaryName("darwin-arm64"), "zcode-darwin-arm64");
  219. assert.equal(outputBinaryName("linux-x64"), "zcode-linux-x64");
  220. assert.equal(outputBinaryName("win-arm64"), "zcode-windows-arm64.exe");
  221. assert.equal(outputBinaryName("win-x64"), "zcode-windows-x64.exe");
  222. });
  223. test("prepares every SEA target in the desktop bundled-tools layout", () => {
  224. assert.deepEqual(
  225. supportedTargets.map((target) => {
  226. const plan = resolveSeaRuntimeToolPreparationPlan({ root: "/repo", target });
  227. return [target, plan.platformKey, plan.enabled];
  228. }),
  229. [
  230. ["darwin-arm64", "darwin-arm64", true],
  231. ["darwin-x64", "darwin-x64", true],
  232. ["linux-arm64", "linux-arm64", true],
  233. ["linux-x64", "linux-x64", true],
  234. ["win-arm64", "win32-arm64", true],
  235. ["win-x64", "win32-x64", true],
  236. ],
  237. );
  238. });
  239. test("downloads the complete SEA runtime tool set before asset collection", async () => {
  240. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-prepare-"));
  241. const archives = new Map();
  242. let requestCount = 0;
  243. const server = createServer((request, response) => {
  244. requestCount += 1;
  245. const archivePath = archives.get(request.url ?? "");
  246. if (!archivePath) {
  247. response.writeHead(404).end();
  248. return;
  249. }
  250. response.writeHead(200, { "content-type": "application/gzip" });
  251. createReadStream(archivePath).pipe(response);
  252. });
  253. await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
  254. try {
  255. const address = server.address();
  256. assert.ok(address && typeof address !== "string");
  257. const baseUrl = `http://127.0.0.1:${address.port}`;
  258. const nativeBaseUrl = `${baseUrl}/native`;
  259. const env = {
  260. NATIVE_SEARCH_RIPGREP_DOWNLOAD_BASE_URL: `${baseUrl}/microsoft-ripgrep`,
  261. NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: nativeBaseUrl,
  262. };
  263. const outputDir = join(directory, "root/packages/desktop/bundled-tools/darwin-arm64");
  264. const nativePlan = resolveNativeSearchPrebuiltPlan({
  265. platform: "darwin",
  266. arch: "arm64",
  267. outputDir,
  268. env,
  269. });
  270. const fixtures = nativePlan.artifacts.map((artifact) => ({
  271. artifact,
  272. binaryName: artifact.binaryName,
  273. downloadUrl: artifact.downloadUrl,
  274. contents: createMachOExecutableFixture(`${artifact.toolId}-fixture`),
  275. toolId: artifact.toolId,
  276. }));
  277. for (const [index, fixture] of fixtures.entries()) {
  278. if (fixture.artifact.source === "official") {
  279. await mkdir(dirname(fixture.artifact.binaryPath), { recursive: true });
  280. await writeFile(fixture.artifact.binaryPath, fixture.contents);
  281. await chmod(fixture.artifact.binaryPath, 0o755);
  282. writeNativeSearchBundleMeta(fixture.artifact, nativePlan.platformKey);
  283. continue;
  284. }
  285. const sourcePath = join(directory, `source-${index}`, fixture.binaryName);
  286. const archivePath = join(directory, `archive-${index}.tar.gz`);
  287. await mkdir(dirname(sourcePath), { recursive: true });
  288. await writeFile(sourcePath, fixture.contents);
  289. await chmod(sourcePath, 0o755);
  290. packSourceAsDeterministicTarGzip(sourcePath, archivePath);
  291. fixture.artifact.archiveSha256 = createHash("sha256")
  292. .update(await readFile(archivePath))
  293. .digest("hex");
  294. archives.set(new URL(fixture.downloadUrl).pathname, archivePath);
  295. }
  296. await prepareSeaRuntimeToolAssets({
  297. root: join(directory, "root"),
  298. target: "darwin-arm64",
  299. env,
  300. prebuiltPlan: nativePlan,
  301. });
  302. const fixtureByToolId = new Map(fixtures.map((fixture) => [fixture.toolId, fixture.contents]));
  303. assert.deepEqual(await readFile(nativePlan.bfsPath), fixtureByToolId.get("bfs"));
  304. assert.deepEqual(await readFile(nativePlan.ugrepPath), fixtureByToolId.get("ugrep"));
  305. assert.deepEqual(await readFile(nativePlan.rgPath), fixtureByToolId.get("ripgrep"));
  306. assert.equal(requestCount, 2);
  307. } finally {
  308. await new Promise((resolvePromise, rejectPromise) => {
  309. server.close((error) => (error ? rejectPromise(error) : resolvePromise()));
  310. });
  311. await rm(directory, { force: true, recursive: true });
  312. }
  313. });
  314. test("maps SEA targets to OpenTUI native package names", () => {
  315. assert.equal(opentuiNativePackageForTarget("darwin-arm64"), "@mbears/opentui-core-darwin-arm64");
  316. assert.equal(opentuiNativePackageForTarget("linux-x64"), "@mbears/opentui-core-linux-x64");
  317. assert.equal(opentuiNativePackageForTarget("win-arm64"), "@mbears/opentui-core-win32-arm64");
  318. assert.equal(opentuiNativePackageForTarget("win-x64"), "@mbears/opentui-core-win32-x64");
  319. });
  320. for (const fixture of [
  321. {
  322. expectedTools: [
  323. ["bfs", "4.1.1", "bfs"],
  324. ["ripgrep", "14.1.1", "rg"],
  325. ["ugrep", "7.8.4", "ugrep"],
  326. ],
  327. platformKey: "darwin-arm64",
  328. target: "darwin-arm64",
  329. },
  330. {
  331. expectedTools: [
  332. ["bfs", "4.1.1", "bfs"],
  333. ["ripgrep", "14.1.1", "rg"],
  334. ["ugrep", "7.8.4", "ugrep"],
  335. ],
  336. platformKey: "darwin-x64",
  337. target: "darwin-x64",
  338. },
  339. {
  340. expectedTools: [
  341. ["bfs", "4.1.1", "bfs"],
  342. ["ripgrep", "14.1.1", "rg"],
  343. ["ugrep", "7.8.4", "ugrep"],
  344. ],
  345. platformKey: "linux-arm64",
  346. target: "linux-arm64",
  347. },
  348. {
  349. expectedTools: [
  350. ["bfs", "4.1.1", "bfs"],
  351. ["ripgrep", "14.1.1", "rg"],
  352. ["ugrep", "7.8.4", "ugrep"],
  353. ],
  354. platformKey: "linux-x64",
  355. target: "linux-x64",
  356. },
  357. {
  358. expectedTools: [
  359. ["ripgrep", "14.1.1", "rg.exe"],
  360. ["ugrep", "7.8.4", "ugrep.exe"],
  361. ],
  362. platformKey: "win32-arm64",
  363. target: "win-arm64",
  364. },
  365. {
  366. expectedTools: [
  367. ["ripgrep", "14.1.1", "rg.exe"],
  368. ["ugrep", "7.8.4", "ugrep.exe"],
  369. ],
  370. platformKey: "win32-x64",
  371. target: "win-x64",
  372. },
  373. ]) {
  374. test(`includes target runtime tools for ${fixture.target}`, async () => {
  375. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-tools-"));
  376. const root = join(directory, "root");
  377. const stagingDirectory = join(directory, "staging");
  378. try {
  379. for (const [toolId, , binaryName] of fixture.expectedTools) {
  380. await writeTestFile(
  381. root,
  382. `packages/desktop/bundled-tools/${fixture.platformKey}/${toolId}/${binaryName}`,
  383. `${fixture.target}:${toolId}`,
  384. );
  385. }
  386. // SEA 内嵌原生工具的许可声明与来源清单;材料取自仓库登记,fixture 根目录需带上同一份。
  387. const repositoryRoot = fileURLToPath(new URL("../../../../..", import.meta.url));
  388. await cp(
  389. join(repositoryRoot, "third-party/native-search"),
  390. join(root, "third-party/native-search"),
  391. { recursive: true },
  392. );
  393. const { assets, manifest } = await collectSeaRuntimeToolAssets({
  394. root,
  395. stagingDirectory,
  396. target: fixture.target,
  397. });
  398. assert.deepEqual(
  399. manifest.tools.map(({ id, version, binaryName }) => [id, version, binaryName]),
  400. fixture.expectedTools,
  401. );
  402. assert.equal(typeof assets[seaRuntimeToolManifestAssetKey], "string");
  403. for (const tool of manifest.tools) {
  404. const expectedBytes = Buffer.from(`${fixture.target}:${tool.id}`);
  405. assert.equal(tool.size, expectedBytes.byteLength);
  406. assert.equal(tool.sha256, createHash("sha256").update(expectedBytes).digest("hex"));
  407. const assetKey = `zcode-runtime-tools/${tool.id}/${tool.sha256}/${tool.binaryName}`;
  408. assert.equal(assets[assetKey].endsWith(tool.binaryName), true);
  409. }
  410. const notices = await readFile(assets["zcode-runtime-tools/THIRD-PARTY-NOTICES.txt"], "utf8");
  411. assert.ok(notices.startsWith("NATIVE SEARCH THIRD-PARTY NOTICES"));
  412. assert.deepEqual(
  413. await readFile(assets["zcode-runtime-tools/SOURCES.json"]),
  414. await readFile(join(root, "third-party/native-search/sources.json")),
  415. );
  416. } finally {
  417. await rm(directory, {
  418. force: true,
  419. recursive: true,
  420. });
  421. }
  422. });
  423. }
  424. test("fails SEA packaging when a target runtime tool is missing", async () => {
  425. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-runtime-tools-missing-"));
  426. try {
  427. await assert.rejects(
  428. collectSeaRuntimeToolAssets({
  429. root: directory,
  430. stagingDirectory: join(directory, "staging"),
  431. target: "darwin-arm64",
  432. }),
  433. /Missing SEA runtime tool bfs for darwin-arm64/,
  434. );
  435. } finally {
  436. await rm(directory, {
  437. force: true,
  438. recursive: true,
  439. });
  440. }
  441. });
  442. test("includes TUI workspace runtime package assets", async () => {
  443. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-tui-assets-"));
  444. const root = join(import.meta.dirname, "../../..");
  445. try {
  446. const { manifest, assets } = await collectSeaTuiAssets({
  447. root,
  448. stagingDirectory: directory,
  449. target: "linux-x64",
  450. });
  451. const paths = new Set(manifest.files.map((file) => file.path));
  452. // SEA 从缓存目录导入 TUI 时无法回退到 workspace 链接,运行时 workspace
  453. // 依赖必须和第三方依赖一样完整进入 node_modules 形状的资产闭包。
  454. assert.equal(paths.has("node_modules/@zcode/tui/package.json"), true);
  455. assert.equal(paths.has("node_modules/@zcode/tui/dist/index.js"), true);
  456. assert.equal(paths.has("node_modules/@zcode/i18n/package.json"), true);
  457. assert.equal(paths.has("node_modules/@zcode/i18n/dist/index.js"), true);
  458. assert.equal(paths.has("node_modules/@zcode/contracts/package.json"), true);
  459. assert.equal(paths.has("node_modules/@zcode/contracts/dist/index.js"), true);
  460. assert.equal(paths.has("node_modules/@zcode/shared/package.json"), true);
  461. assert.equal(paths.has("node_modules/@zcode/shared/dist/index.js"), true);
  462. assert.equal(
  463. paths.has("node_modules/@zcode/shared/dist/workspace-hook-trust-store-file.js"),
  464. true,
  465. );
  466. assert.equal(paths.has("node_modules/@zcode/i18n/src/index.ts"), false);
  467. assert.equal(paths.has("node_modules/@zcode/contracts/src/index.ts"), false);
  468. assert.equal(paths.has("node_modules/@zcode/shared/src/index.ts"), false);
  469. const zodPackages = manifest.files.filter((file) => file.path.endsWith("/zod/package.json"));
  470. const zodVersions = await Promise.all(
  471. zodPackages.map(async (file) => {
  472. const metadata = JSON.parse(
  473. await readFile(assets[`${seaTuiAssetPrefix}${file.path}`], "utf8"),
  474. );
  475. return metadata.version.split(".")[0];
  476. }),
  477. );
  478. assert.deepEqual([...new Set(zodVersions)].sort(), ["3", "4"]);
  479. // 根 workspace 的源码 exports 不能原样进入只包含 dist 的 SEA runtime。
  480. for (const packageName of ["@zcode/shared", "@zcode/model-option-map"]) {
  481. const assetKey = `${seaTuiAssetPrefix}node_modules/${packageName}/package.json`;
  482. const stagedPackage = JSON.parse(await readFile(assets[assetKey], "utf8"));
  483. assert.equal(stagedPackage.exports["."], "./dist/index.js");
  484. const sourcePackage = JSON.parse(
  485. await readFile(
  486. join(root, "../..", "packages", packageName.split("/")[1], "package.json"),
  487. "utf8",
  488. ),
  489. );
  490. assert.equal(sourcePackage.exports["."], "./src/index.ts");
  491. }
  492. } finally {
  493. await rm(directory, {
  494. force: true,
  495. recursive: true,
  496. });
  497. }
  498. });
  499. test("loads TUI from an extracted SEA runtime dependency closure", async () => {
  500. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-tui-runtime-"));
  501. const root = join(import.meta.dirname, "../../..");
  502. const stagingDirectory = join(directory, "staging");
  503. const runtimeDirectory = join(directory, "runtime");
  504. try {
  505. const { assets, manifest } = await collectSeaTuiAssets({
  506. root,
  507. stagingDirectory,
  508. target: hostTarget(),
  509. });
  510. for (const file of manifest.files) {
  511. const sourcePath = assets[`${seaTuiAssetPrefix}${file.path}`];
  512. assert.equal(typeof sourcePath, "string");
  513. const outputPath = join(runtimeDirectory, file.path);
  514. await mkdir(dirname(outputPath), {
  515. recursive: true,
  516. });
  517. await copyFile(sourcePath, outputPath);
  518. }
  519. // Windows 锁定进程已加载的 opentui.dll;子进程退出释放 DLL 后,父进程才能清理目录。
  520. const entryUrl = pathToFileURL(
  521. join(runtimeDirectory, "node_modules/@zcode/tui/dist/index.js"),
  522. ).href;
  523. await promisify(execFile)(
  524. process.execPath,
  525. [
  526. "--input-type=module",
  527. "--eval",
  528. 'import assert from "node:assert/strict"; const tui = await import(process.argv[1]); assert.equal(typeof tui.runTui, "function");',
  529. entryUrl,
  530. ],
  531. { cwd: runtimeDirectory, timeout: 30000 },
  532. );
  533. } finally {
  534. await rm(directory, {
  535. force: true,
  536. recursive: true,
  537. });
  538. }
  539. });
  540. test("includes the pinned Playwright runtime required by headless Browser Use", async () => {
  541. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-playwright-assets-"));
  542. const root = join(import.meta.dirname, "../../..");
  543. try {
  544. const { assets, manifest } = await collectSeaPlaywrightAssets({
  545. root,
  546. stagingDirectory: directory,
  547. target: "linux-x64",
  548. });
  549. const paths = new Set(manifest.files.map((file) => file.path));
  550. assert.equal(manifest.packageVersion, "1.59.1");
  551. assert.equal(typeof assets[seaPlaywrightManifestAssetKey], "string");
  552. assert.equal(paths.has("node_modules/playwright-core/package.json"), true);
  553. assert.equal(paths.has("node_modules/playwright-core/index.js"), true);
  554. assert.equal(paths.has("node_modules/playwright-core/lib/server/browserType.js"), true);
  555. } finally {
  556. await rm(directory, { force: true, recursive: true });
  557. }
  558. });
  559. test("keeps the Browser Use SEA release at 0.5.1 with complete runtime assets", async () => {
  560. const root = join(import.meta.dirname, "../../..");
  561. const browserUsePlugin = officialSeaPlugins.find((plugin) => plugin.name === "browser-use");
  562. assert.equal(browserUsePlugin?.version, "0.5.1");
  563. assert.deepEqual(browserUsePlugin?.requiredRuntimePaths, [
  564. "scripts/browser-client.mjs",
  565. "docs/api.json",
  566. "docs/documents.json",
  567. "docs/overview.md",
  568. "docs/recording.md",
  569. "docs/workflow.md",
  570. "skills/control-browser/SKILL.md",
  571. "skills/web-gui-tester/SKILL.md",
  572. ]);
  573. const packageJson = JSON.parse(
  574. await readFile(join(root, browserUsePlugin.rootPath, "package.json"), "utf8"),
  575. );
  576. const pluginManifest = JSON.parse(
  577. await readFile(join(root, browserUsePlugin.rootPath, ".zcode-plugin", "plugin.json"), "utf8"),
  578. );
  579. assert.deepEqual(
  580. {
  581. manifest: pluginManifest.version,
  582. package: packageJson.version,
  583. sea: browserUsePlugin.version,
  584. },
  585. {
  586. manifest: "0.5.1",
  587. package: "0.5.1",
  588. sea: "0.5.1",
  589. },
  590. );
  591. // Bug 原因:新增录屏能力时重写了整段插件描述,并把原生 WebM 误写成 MP4。
  592. assert.equal(
  593. pluginManifest.description,
  594. "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.",
  595. );
  596. });
  597. test("keeps SEA official plugin versions aligned with package and plugin manifests", async () => {
  598. const root = join(import.meta.dirname, "../../..");
  599. for (const plugin of officialSeaPlugins) {
  600. const packageJson = JSON.parse(
  601. await readFile(join(root, plugin.rootPath, "package.json"), "utf8"),
  602. );
  603. const pluginManifest = JSON.parse(
  604. await readFile(join(root, plugin.rootPath, ".zcode-plugin", "plugin.json"), "utf8"),
  605. );
  606. assert.deepEqual(
  607. {
  608. manifest: pluginManifest.version,
  609. package: packageJson.version,
  610. sea: plugin.version,
  611. },
  612. {
  613. manifest: plugin.version,
  614. package: plugin.version,
  615. sea: plugin.version,
  616. },
  617. plugin.name,
  618. );
  619. }
  620. });
  621. test("includes bundled official plugin assets", async () => {
  622. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-assets-"));
  623. const root = join(import.meta.dirname, "../../..");
  624. try {
  625. const { assets, manifest } = await collectSeaOfficialPluginAssets({
  626. root,
  627. stagingDirectory: directory,
  628. });
  629. const iosPlugin = manifest.plugins.find((item) => item.name === "ios-simulator");
  630. const androidPlugin = manifest.plugins.find((item) => item.name === "android-emulator");
  631. const browserUsePlugin = manifest.plugins.find((item) => item.name === "browser-use");
  632. const documentPlugin = manifest.plugins.find((item) => item.name === "documents");
  633. const restorePlugin = manifest.plugins.find((item) => item.name === "restore-legacy-sessions");
  634. const skillCreatorPlugin = manifest.plugins.find((item) => item.name === "skill-creator");
  635. const zcodeGuidePlugin = manifest.plugins.find((item) => item.name === "zcode-guide");
  636. const iosPaths = new Set(iosPlugin?.files.map((file) => file.path));
  637. const androidPaths = new Set(androidPlugin?.files.map((file) => file.path));
  638. const browserUsePaths = new Set(browserUsePlugin?.files.map((file) => file.path));
  639. const documentPaths = new Set(
  640. manifest.plugins
  641. .filter((plugin) =>
  642. ["documents", "pdf", "presentations", "spreadsheets"].includes(plugin.name),
  643. )
  644. .flatMap((plugin) => plugin.files.map((file) => file.path)),
  645. );
  646. const restorePaths = new Set(restorePlugin?.files.map((file) => file.path));
  647. const skillCreatorPaths = new Set(skillCreatorPlugin?.files.map((file) => file.path));
  648. const zcodeGuidePaths = new Set(zcodeGuidePlugin?.files.map((file) => file.path));
  649. assert.equal(typeof assets[seaOfficialPluginManifestAssetKey], "string");
  650. assert.equal(iosPlugin?.marketplace, "zcode-plugins-official");
  651. assert.equal(androidPlugin?.marketplace, "zcode-plugins-official");
  652. assert.equal(browserUsePlugin?.marketplace, "zcode-plugins-official");
  653. assert.equal(documentPlugin?.marketplace, "zcode-plugins-official");
  654. assert.equal(restorePlugin?.marketplace, "zcode-plugins-official");
  655. assert.equal(skillCreatorPlugin?.marketplace, "zcode-plugins-official");
  656. assert.equal(zcodeGuidePlugin?.marketplace, "zcode-plugins-official");
  657. // superpowers 已从内置 SEA 清单移除,断言它不再出现在 manifest 里。
  658. assert.equal(
  659. manifest.plugins.some((item) => item.name === "superpowers"),
  660. false,
  661. );
  662. assert.equal(iosPaths.has(".zcode-plugin/plugin.json"), true);
  663. assert.equal(iosPaths.has("commands/ios-dev.md"), true);
  664. assert.equal(iosPaths.has("skills/ios-dev/SKILL.md"), true);
  665. assert.equal(iosPaths.has("src/mcp/server.ts"), false);
  666. assert.equal(androidPaths.has(".zcode-plugin/plugin.json"), true);
  667. assert.equal(androidPaths.has("commands/android-dev.md"), true);
  668. assert.equal(androidPaths.has("skills/android-dev/SKILL.md"), true);
  669. assert.equal(androidPaths.has("skills/android-dev/scripts/setup-windows.ps1"), false);
  670. assert.equal(androidPaths.has("src/mcp/server.ts"), false);
  671. assert.equal(browserUsePaths.has(".zcode-plugin/plugin.json"), true);
  672. assert.equal(browserUsePaths.has("skills/control-browser/SKILL.md"), true);
  673. assert.equal(browserUsePaths.has("skills/web-gui-tester/SKILL.md"), true);
  674. assert.equal(browserUsePaths.has("docs/api.json"), true);
  675. assert.equal(browserUsePaths.has("docs/documents.json"), true);
  676. assert.equal(browserUsePaths.has("docs/overview.md"), true);
  677. assert.equal(browserUsePaths.has("docs/workflow.md"), true);
  678. // 宿主产物已搬到独立的 node-repl-host seed 单元;browser-use 不再携带它。
  679. assert.equal(browserUsePaths.has("dist/mcp/server.js"), false);
  680. const hostPlugin = manifest.plugins.find((item) => item.name === "node-repl-host");
  681. assert.ok(hostPlugin, "the shared node_repl host must be embedded");
  682. assert.equal(
  683. new Set(hostPlugin.files.map((file) => file.path)).has("dist/mcp/server.js"),
  684. true,
  685. );
  686. assert.equal(browserUsePaths.has("scripts/browser-client.mjs"), true);
  687. // CUA 的 client 只有一份,属于 computer-use 插件;browser-use 不再镜像它。
  688. assert.equal(browserUsePaths.has("scripts/computer-use-client.mjs"), false);
  689. // CUA 的文档同理:唯一那份属于 computer-use 插件。
  690. assert.equal(browserUsePaths.has("docs/computer-use.md"), false);
  691. assert.equal(documentPaths.has(".zcode-plugin/plugin.json"), true);
  692. assert.equal(documentPaths.has("skills/docx/SKILL.md"), true);
  693. assert.equal(documentPaths.has("skills/pdf/SKILL.md"), true);
  694. assert.equal(documentPaths.has("skills/pdf/scripts/pdf.py"), true);
  695. assert.equal(documentPaths.has("skills/pptx/SKILL.md"), true);
  696. assert.equal(documentPaths.has("agents/visual-judge.md"), true);
  697. assert.equal(documentPaths.has("skills/pptx/scripts/general_judge.py"), false);
  698. assert.equal(documentPaths.has("skills/xlsx/SKILL.md"), true);
  699. assert.equal(documentPaths.has("skills/xlsx/xlsx.py"), true);
  700. assert.equal(
  701. [...documentPaths].some((path) =>
  702. /(?:^|\/)(?:\.venv|__pycache__|\.DS_Store)(?:\/|$)/u.test(path),
  703. ),
  704. false,
  705. );
  706. assert.equal(restorePaths.has(".zcode-plugin/plugin.json"), true);
  707. assert.equal(restorePaths.has("commands/restore-legacy-sessions.md"), true);
  708. assert.equal(restorePaths.has("skills/restore-legacy-sessions/SKILL.md"), true);
  709. assert.equal(
  710. restorePaths.has("skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs"),
  711. true,
  712. );
  713. assert.equal(
  714. restorePaths.has("skills/restore-legacy-sessions/scripts/restore-conversation.mjs"),
  715. true,
  716. );
  717. assert.equal(restorePaths.has("dist/mcp/server.js"), false);
  718. assert.equal(skillCreatorPaths.has(".zcode-plugin/plugin.json"), true);
  719. assert.equal(skillCreatorPaths.has("skills/skill-creator/SKILL.md"), true);
  720. assert.equal(zcodeGuidePaths.has(".zcode-plugin/plugin.json"), true);
  721. assert.equal(zcodeGuidePaths.has("skills/zcode-configuration-guide/SKILL.md"), true);
  722. assert.equal(zcodeGuidePaths.has("skills/diagnosing-mcp/SKILL.md"), true);
  723. assert.equal(zcodeGuidePaths.has("skills/diagnosing-skills/SKILL.md"), true);
  724. assert.equal(zcodeGuidePaths.has("skills/diagnosing-commands/SKILL.md"), true);
  725. assert.equal(zcodeGuidePaths.has("skills/diagnosing-hooks/SKILL.md"), true);
  726. assert.equal(zcodeGuidePaths.has("skills/diagnosing-plugins/SKILL.md"), true);
  727. // 0.3.0:/workflow 与 dynamic-workflows 不再随 zcode-guide 发布(见 bundled skill pack 用例)。
  728. assert.equal(zcodeGuidePaths.has("commands/workflow.md"), false);
  729. assert.equal(zcodeGuidePaths.has("skills/dynamic-workflows/SKILL.md"), false);
  730. } finally {
  731. await rm(directory, {
  732. force: true,
  733. recursive: true,
  734. });
  735. }
  736. });
  737. test("includes the bundled skill pack as content-hashed SEA assets", async () => {
  738. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-assets-"));
  739. const root = join(import.meta.dirname, "../../..");
  740. try {
  741. const { assets, manifest } = await collectSeaBundledSkillAssets({
  742. root,
  743. stagingDirectory: directory,
  744. });
  745. const paths = new Set(manifest.files.map((file) => file.path));
  746. assert.equal(manifest.version, 1);
  747. assert.match(manifest.hash, /^[0-9a-f]{64}$/u);
  748. assert.equal(typeof assets[seaBundledSkillManifestAssetKey], "string");
  749. for (const requiredPath of bundledSkillPackRequiredPaths) {
  750. assert.equal(paths.has(requiredPath), true, requiredPath);
  751. assert.equal(typeof assets[`${seaBundledSkillAssetPrefix}${requiredPath}`], "string");
  752. }
  753. // 资产只来自 skills/:README 之类的包元数据不进二进制。
  754. assert.equal(
  755. [...paths].every((path) => path.startsWith("skills/")),
  756. true,
  757. );
  758. for (const file of manifest.files) {
  759. assert.match(file.sha256, /^[0-9a-f]{64}$/u);
  760. }
  761. } finally {
  762. await rm(directory, { force: true, recursive: true });
  763. }
  764. });
  765. test("rejects a bundled skill pack that lost a required file", async () => {
  766. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-bundled-skill-incomplete-"));
  767. const root = join(directory, "root");
  768. try {
  769. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/SKILL.md", "# s");
  770. await writeTestFile(root, "packages/bundled-skills/skills/dynamic-workflows/patterns.md", "#");
  771. await assert.rejects(
  772. collectSeaBundledSkillAssets({ root, stagingDirectory: join(directory, "staging") }),
  773. /Missing bundled skill pack required asset/u,
  774. );
  775. } finally {
  776. await rm(directory, { force: true, recursive: true });
  777. }
  778. });
  779. test("allows skill-only official plugins when SEA runtime assets are required", async () => {
  780. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-runtime-assets-"));
  781. const root = join(directory, "root");
  782. const stagingDirectory = join(directory, "staging");
  783. try {
  784. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  785. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  786. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  787. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  788. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  789. await writeTestFile(root, "packages/browser-use-plugin/skills/control-browser/SKILL.md", "");
  790. await writeTestFile(root, "packages/browser-use-plugin/skills/web-gui-tester/SKILL.md", "");
  791. await writeTestFile(root, "packages/browser-use-plugin/docs/api.json", "{}");
  792. await writeTestFile(root, "packages/browser-use-plugin/docs/documents.json", "[]");
  793. await writeTestFile(root, "packages/browser-use-plugin/docs/overview.md", "");
  794. await writeTestFile(root, "packages/browser-use-plugin/docs/recording.md", "");
  795. await writeTestFile(root, "packages/browser-use-plugin/docs/workflow.md", "");
  796. await writeTestFile(root, "packages/browser-use-plugin/scripts/browser-client.mjs", "");
  797. await writeDocumentPluginFixtures(root);
  798. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  799. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  800. await writeTestFile(
  801. root,
  802. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  803. "{}",
  804. );
  805. await writeTestFile(
  806. root,
  807. "packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md",
  808. "",
  809. );
  810. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  811. await writeTestFile(root, "packages/skill-creator-plugin/skills/skill-creator/SKILL.md", "");
  812. // 新增官方内容插件后也要提供 fixture,否则采集会先报 manifest 缺失,无法验证免运行时资源。
  813. await writeTestFile(root, "packages/plugin-creator-plugin/.zcode-plugin/plugin.json", "{}");
  814. await writeTestFile(root, "packages/plugin-creator-plugin/skills/plugin-creator/SKILL.md", "");
  815. // skill-creator 用作「带可执行 hook 的 skill-only 官方插件」载体(原先由 superpowers 覆盖)。
  816. // collector 按 officialSeaPlugins 登记 + 伪造目录采集,真实 skill-creator 是否带 hook 无关紧要。
  817. await writeTestFile(root, "packages/skill-creator-plugin/hooks/hooks.json", "{}");
  818. await writeTestFile(root, "packages/skill-creator-plugin/hooks/run-hook.cmd", "");
  819. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  820. await writeTestFile(
  821. root,
  822. "packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md",
  823. "",
  824. );
  825. const { manifest } = await collectSeaOfficialPluginAssets({
  826. requireRuntime: true,
  827. root,
  828. stagingDirectory,
  829. });
  830. const documentPlugin = manifest.plugins.find((item) => item.name === "documents");
  831. const browserUsePlugin = manifest.plugins.find((item) => item.name === "browser-use");
  832. const restorePlugin = manifest.plugins.find((item) => item.name === "restore-legacy-sessions");
  833. const skillCreatorPlugin = manifest.plugins.find((item) => item.name === "skill-creator");
  834. const pluginCreatorPlugin = manifest.plugins.find((item) => item.name === "plugin-creator");
  835. const documentPaths = new Set(
  836. manifest.plugins
  837. .filter((plugin) =>
  838. ["documents", "pdf", "presentations", "spreadsheets"].includes(plugin.name),
  839. )
  840. .flatMap((plugin) => plugin.files.map((file) => file.path)),
  841. );
  842. const browserUsePaths = new Set(browserUsePlugin?.files.map((file) => file.path));
  843. const restorePaths = new Set(restorePlugin?.files.map((file) => file.path));
  844. const skillCreatorPaths = new Set(skillCreatorPlugin?.files.map((file) => file.path));
  845. const skillCreatorRunHook = skillCreatorPlugin?.files.find(
  846. (file) => file.path === "hooks/run-hook.cmd",
  847. );
  848. assert.ok(pluginCreatorPlugin);
  849. assert.equal(
  850. pluginCreatorPlugin.files.some((file) => file.path === "skills/plugin-creator/SKILL.md"),
  851. true,
  852. );
  853. assert.equal(
  854. pluginCreatorPlugin.files.some((file) => file.path === "dist/mcp/server.js"),
  855. false,
  856. );
  857. assert.equal(documentPaths.has("skills/docx/SKILL.md"), true);
  858. assert.equal(documentPaths.has("skills/pdf/SKILL.md"), true);
  859. assert.equal(documentPaths.has("skills/pptx/SKILL.md"), true);
  860. assert.equal(documentPaths.has("dist/mcp/server.js"), false);
  861. assert.equal(browserUsePaths.has("skills/control-browser/SKILL.md"), true);
  862. assert.equal(browserUsePaths.has("skills/web-gui-tester/SKILL.md"), true);
  863. assert.equal(browserUsePaths.has("docs/api.json"), true);
  864. assert.equal(browserUsePaths.has("docs/overview.md"), true);
  865. assert.equal(browserUsePaths.has("docs/workflow.md"), true);
  866. // 宿主产物已搬到独立的 node-repl-host seed 单元;browser-use 不再携带它。
  867. assert.equal(browserUsePaths.has("dist/mcp/server.js"), false);
  868. const hostPlugin = manifest.plugins.find((item) => item.name === "node-repl-host");
  869. assert.ok(hostPlugin, "the shared node_repl host must be embedded");
  870. assert.equal(
  871. new Set(hostPlugin.files.map((file) => file.path)).has("dist/mcp/server.js"),
  872. true,
  873. );
  874. assert.equal(browserUsePaths.has("scripts/browser-client.mjs"), true);
  875. // CUA 的 client 只有一份,属于 computer-use 插件;browser-use 不再镜像它。
  876. assert.equal(browserUsePaths.has("scripts/computer-use-client.mjs"), false);
  877. // CUA 的文档同理:唯一那份属于 computer-use 插件。
  878. assert.equal(browserUsePaths.has("docs/computer-use.md"), false);
  879. assert.equal(restorePaths.has("skills/restore-legacy-sessions/SKILL.md"), true);
  880. assert.equal(restorePaths.has("dist/mcp/server.js"), false);
  881. assert.equal(skillCreatorPaths.has("skills/skill-creator/SKILL.md"), true);
  882. assert.equal(skillCreatorPaths.has("hooks/hooks.json"), true);
  883. assert.equal(skillCreatorPaths.has("hooks/run-hook.cmd"), true);
  884. assert.equal(skillCreatorRunHook?.mode, 0o755);
  885. assert.equal(skillCreatorPaths.has("dist/mcp/server.js"), false);
  886. } finally {
  887. await rm(directory, {
  888. force: true,
  889. recursive: true,
  890. });
  891. }
  892. });
  893. test("requires SEA runtime assets for runtime-backed official plugins", async () => {
  894. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-plugin-missing-runtime-"));
  895. const root = join(directory, "root");
  896. const stagingDirectory = join(directory, "staging");
  897. try {
  898. await writeTestFile(root, "packages/android-emulator-plugin/.zcode-plugin/plugin.json", "{}");
  899. // 宿主要先齐备,这条测试隔离的是 android-emulator 缺 runtime 这一种情况。
  900. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  901. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  902. await writeTestFile(root, "packages/browser-use-plugin/.zcode-plugin/plugin.json", "{}");
  903. await writeTestFile(root, "packages/documents-plugin/.zcode-plugin/plugin.json", "{}");
  904. await writeTestFile(root, "packages/ios-simulator-plugin/.zcode-plugin/plugin.json", "{}");
  905. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  906. await writeTestFile(
  907. root,
  908. "packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json",
  909. "{}",
  910. );
  911. await writeTestFile(root, "packages/skill-creator-plugin/.zcode-plugin/plugin.json", "{}");
  912. await writeTestFile(root, "packages/zcode-guide-plugin/.zcode-plugin/plugin.json", "{}");
  913. await assert.rejects(
  914. collectSeaOfficialPluginAssets({
  915. requireRuntime: true,
  916. root,
  917. stagingDirectory,
  918. }),
  919. /Missing android-emulator MCP runtime/,
  920. );
  921. } finally {
  922. await rm(directory, {
  923. force: true,
  924. recursive: true,
  925. });
  926. }
  927. });
  928. test("requires the Browser Use client alongside the SEA MCP runtime", async () => {
  929. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-browser-client-missing-"));
  930. const root = join(directory, "root");
  931. const stagingDirectory = join(directory, "staging");
  932. try {
  933. for (const pluginName of [
  934. "android-emulator-plugin",
  935. "browser-use-plugin",
  936. "documents-plugin",
  937. "ios-simulator-plugin",
  938. "restore-legacy-sessions-plugin",
  939. "skill-creator-plugin",
  940. "zcode-guide-plugin",
  941. ]) {
  942. await writeTestFile(root, `packages/${pluginName}/.zcode-plugin/plugin.json`, "{}");
  943. }
  944. await writeTestFile(root, "packages/android-emulator-plugin/dist/mcp/server.js", "");
  945. await writeTestFile(root, "packages/node-repl-host/.zcode-plugin/plugin.json", "{}");
  946. await writeTestFile(root, "packages/node-repl-host/dist/mcp/server.js", "");
  947. await writeDocumentPluginFixtures(root);
  948. await writeTestFile(root, "packages/ios-simulator-plugin/dist/mcp/server.js", "");
  949. await assert.rejects(
  950. collectSeaOfficialPluginAssets({
  951. requireRuntime: true,
  952. root,
  953. stagingDirectory,
  954. }),
  955. /Missing browser-use runtime asset.*browser-client\.mjs/u,
  956. );
  957. } finally {
  958. await rm(directory, {
  959. force: true,
  960. recursive: true,
  961. });
  962. }
  963. });
  964. test("maps SEA targets to Node.js release artifacts and URLs", () => {
  965. assert.equal(nodeReleaseArtifact("darwin-arm64", "24.14.0"), "node-v24.14.0-darwin-arm64.tar.gz");
  966. assert.equal(nodeReleaseArtifact("linux-x64", "24.14.0"), "node-v24.14.0-linux-x64.tar.xz");
  967. assert.equal(nodeReleaseArtifact("win-arm64", "24.14.0"), "win-arm64/node.exe");
  968. assert.equal(nodeReleaseArtifact("win-x64", "24.14.0"), "win-x64/node.exe");
  969. assert.equal(
  970. nodeReleaseUrl("win-arm64", "24.14.0"),
  971. "https://nodejs.org/dist/v24.14.0/win-arm64/node.exe",
  972. );
  973. assert.equal(
  974. nodeReleaseUrl("win-x64", "24.14.0"),
  975. "https://nodejs.org/dist/v24.14.0/win-x64/node.exe",
  976. );
  977. });
  978. async function writeTestFile(root, relativePath, contents) {
  979. const filePath = join(root, relativePath);
  980. await mkdir(dirname(filePath), {
  981. recursive: true,
  982. });
  983. await writeFile(filePath, contents);
  984. }
  985. test("adds the Mach-O segment argument only for macOS targets", () => {
  986. assert.deepEqual(
  987. postjectArgsForTarget({
  988. binaryPath: "/tmp/zcode-darwin-arm64",
  989. seaBlob: "/tmp/zcode.sea.blob",
  990. sentinelFuse: "NODE_SEA_FUSE_test",
  991. target: "darwin-arm64",
  992. }),
  993. [
  994. "/tmp/zcode-darwin-arm64",
  995. "NODE_SEA_BLOB",
  996. "/tmp/zcode.sea.blob",
  997. "--sentinel-fuse",
  998. "NODE_SEA_FUSE_test",
  999. "--macho-segment-name",
  1000. "NODE_SEA",
  1001. ],
  1002. );
  1003. assert.deepEqual(
  1004. postjectArgsForTarget({
  1005. binaryPath: "/tmp/zcode-linux-x64",
  1006. seaBlob: "/tmp/zcode.sea.blob",
  1007. sentinelFuse: "NODE_SEA_FUSE_test",
  1008. target: "linux-x64",
  1009. }),
  1010. [
  1011. "/tmp/zcode-linux-x64",
  1012. "NODE_SEA_BLOB",
  1013. "/tmp/zcode.sea.blob",
  1014. "--sentinel-fuse",
  1015. "NODE_SEA_FUSE_test",
  1016. ],
  1017. );
  1018. });
  1019. test("ad-hoc signs only macOS targets built on macOS hosts", () => {
  1020. assert.deepEqual(adHocCodesignArgs("/tmp/zcode-darwin-arm64"), [
  1021. "--force",
  1022. "--sign",
  1023. "-",
  1024. "/tmp/zcode-darwin-arm64",
  1025. ]);
  1026. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "darwin" }), true);
  1027. assert.equal(shouldAdHocSignMacTarget("darwin-x64", { platform: "darwin" }), true);
  1028. assert.equal(shouldAdHocSignMacTarget("linux-x64", { platform: "darwin" }), false);
  1029. assert.equal(shouldAdHocSignMacTarget("win-x64", { platform: "darwin" }), false);
  1030. assert.equal(shouldAdHocSignMacTarget("darwin-arm64", { platform: "linux" }), false);
  1031. });
  1032. test("resolves postject from a hoisted ancestor node_modules", async () => {
  1033. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-postject-"));
  1034. const cliDirectory = join(directory, "apps", "zcode-cli", "packages", "cli");
  1035. const binDirectory = join(directory, "node_modules", ".bin");
  1036. const postjectPath = join(binDirectory, "postject");
  1037. try {
  1038. await mkdir(cliDirectory, { recursive: true });
  1039. await mkdir(binDirectory, { recursive: true });
  1040. await writeFile(postjectPath, "");
  1041. assert.equal(
  1042. resolvePostjectBin({
  1043. platform: "linux",
  1044. startDirectory: cliDirectory,
  1045. }),
  1046. postjectPath,
  1047. );
  1048. } finally {
  1049. await rm(directory, {
  1050. force: true,
  1051. recursive: true,
  1052. });
  1053. }
  1054. });
  1055. test("removes and truncates a trailing Windows Authenticode certificate table", () => {
  1056. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1057. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1058. assert.equal(result.removed, true);
  1059. assert.equal(result.truncated, true);
  1060. assert.equal(result.certificateOffset, CERTIFICATE_OFFSET);
  1061. assert.equal(result.certificateSize, CERTIFICATE_SIZE);
  1062. assert.equal(result.buffer.length, CERTIFICATE_OFFSET);
  1063. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1064. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1065. assert.deepEqual(readWindowsAuthenticodeDirectory(result.buffer), {
  1066. certificateOffset: 0,
  1067. certificateSize: 0,
  1068. securityDirectoryEntryOffset,
  1069. signed: false,
  1070. });
  1071. });
  1072. test("removes a PE32 Authenticode directory without truncating non-certificate trailing data", () => {
  1073. const trailingBytes = 16;
  1074. const { contents, securityDirectoryEntryOffset } = createPeFixture({
  1075. pe32Plus: false,
  1076. trailingBytes,
  1077. });
  1078. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1079. assert.equal(result.removed, true);
  1080. assert.equal(result.truncated, false);
  1081. assert.equal(result.buffer.length, CERTIFICATE_OFFSET + CERTIFICATE_SIZE + trailingBytes);
  1082. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset), 0);
  1083. assert.equal(result.buffer.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1084. });
  1085. test("leaves unsigned Windows PE binaries unchanged", () => {
  1086. const { contents } = createPeFixture({
  1087. signed: false,
  1088. });
  1089. const result = removeWindowsAuthenticodeSignatureFromBuffer(contents);
  1090. assert.equal(result.removed, false);
  1091. assert.equal(result.truncated, false);
  1092. assert.equal(result.buffer, contents);
  1093. });
  1094. test("rejects Windows Authenticode directories outside the file range", () => {
  1095. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1096. contents.writeUInt32LE(contents.length + CERTIFICATE_SIZE, securityDirectoryEntryOffset);
  1097. assert.throws(
  1098. () => removeWindowsAuthenticodeSignatureFromBuffer(contents),
  1099. /Invalid PE certificate table/,
  1100. );
  1101. });
  1102. test("removes Windows Authenticode signatures from files", async () => {
  1103. const directory = await mkdtemp(join(tmpdir(), "zcode-sea-authenticode-"));
  1104. const binaryPath = join(directory, "zcode-windows-x64.exe");
  1105. const { contents, securityDirectoryEntryOffset } = createPeFixture();
  1106. try {
  1107. await writeFile(binaryPath, contents);
  1108. const result = await removeWindowsAuthenticodeSignature(binaryPath);
  1109. const updated = await readFile(binaryPath);
  1110. assert.deepEqual(result, {
  1111. certificateOffset: CERTIFICATE_OFFSET,
  1112. certificateSize: CERTIFICATE_SIZE,
  1113. removed: true,
  1114. truncated: true,
  1115. });
  1116. assert.equal(updated.length, CERTIFICATE_OFFSET);
  1117. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset), 0);
  1118. assert.equal(updated.readUInt32LE(securityDirectoryEntryOffset + 4), 0);
  1119. } finally {
  1120. await rm(directory, {
  1121. force: true,
  1122. recursive: true,
  1123. });
  1124. }
  1125. });
  1126. test("matches host targets using Node.js platform names", () => {
  1127. assert.equal(
  1128. hostTarget({
  1129. arch: "x64",
  1130. platform: "win32",
  1131. }),
  1132. "win-x64",
  1133. );
  1134. assert.equal(
  1135. isHostTarget("win32-x64", {
  1136. arch: "x64",
  1137. platform: "win32",
  1138. }),
  1139. true,
  1140. );
  1141. assert.equal(
  1142. isHostTarget("linux-x64", {
  1143. arch: "arm64",
  1144. platform: "darwin",
  1145. }),
  1146. false,
  1147. );
  1148. });
  1149. test("rebuilds workspace dependencies without caching SEA outputs before packaging", async () => {
  1150. const packageJson = JSON.parse(
  1151. await readFile(new URL("../package.json", import.meta.url), "utf8"),
  1152. );
  1153. assert.equal(
  1154. packageJson.scripts?.["build:sea"],
  1155. "pnpm --dir ../../../.. exec turbo --skip-infer --cwd apps/zcode-cli run build --filter=!@zcode/cli --force && pnpm build && node scripts/build-sea.mjs --all",
  1156. );
  1157. });
  1158. test("resolves Turbo from the repository while retaining the CLI workspace graph", () => {
  1159. const cliPackageRoot = new URL("..", import.meta.url);
  1160. // 回归原因:CLI 是嵌套 workspace,--workspace-root 会把 Turbo 限定到未安装 binary 的内层 node_modules。
  1161. const result = spawnSync(
  1162. "pnpm",
  1163. [
  1164. "--dir",
  1165. "../../../..",
  1166. "exec",
  1167. "turbo",
  1168. "--skip-infer",
  1169. "--cwd",
  1170. "apps/zcode-cli",
  1171. "run",
  1172. "build",
  1173. "--filter=!@zcode/cli",
  1174. "--force",
  1175. "--dry=json",
  1176. ],
  1177. {
  1178. cwd: cliPackageRoot,
  1179. encoding: "utf8",
  1180. shell: process.platform === "win32",
  1181. },
  1182. );
  1183. assert.equal(result.status, 0, result.stderr || result.stdout);
  1184. assert.match(result.stdout, /"taskId":/u);
  1185. assert.doesNotMatch(result.stdout, /"package": "@zcode\/cli"/u);
  1186. });
  1187. test("can be dynamically imported when argv[1] is missing", () => {
  1188. const scriptUrl = new URL("../scripts/build-sea.mjs", import.meta.url).href;
  1189. const result = spawnSync(
  1190. process.execPath,
  1191. [
  1192. "-e",
  1193. `import(${JSON.stringify(scriptUrl)}).then((m) => console.log(m.outputBinaryName("win-x64")))`,
  1194. ],
  1195. {
  1196. encoding: "utf8",
  1197. },
  1198. );
  1199. assert.equal(result.status, 0, result.stderr);
  1200. assert.equal(result.stdout.trim(), "zcode-windows-x64.exe");
  1201. });
  1202. async function writeDocumentPluginFixtures(root) {
  1203. for (const [name, skill] of [
  1204. ["documents", "docx"],
  1205. ["pdf", "pdf"],
  1206. ["presentations", "pptx"],
  1207. ["spreadsheets", "xlsx"],
  1208. ]) {
  1209. await writeTestFile(root, `packages/${name}-plugin/.zcode-plugin/plugin.json`, "{}");
  1210. await writeTestFile(root, `packages/${name}-plugin/agents/visual-judge.md`, "");
  1211. await writeTestFile(root, `packages/${name}-plugin/skills/${skill}/SKILL.md`, "");
  1212. }
  1213. await writeTestFile(root, "packages/image-search-plugin/.zcode-plugin/plugin.json", "{}");
  1214. await writeTestFile(root, "packages/image-search-plugin/.mcp.json", "{}");
  1215. }