desktopAgentBytecode.test.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import { execFile } from "node:child_process";
  2. import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { promisify } from "node:util";
  7. import { afterEach, expect, it } from "vitest";
  8. import { buildDesktopAgentBytecode } from "../../../scripts/build-desktop-agent-bytecode.mjs";
  9. const execFileAsync = promisify(execFile);
  10. const electronPath = createRequire(import.meta.url)("electron") as string;
  11. const directories: string[] = [];
  12. const runtimeEnv = { ...process.env, ELECTRON_RUN_AS_NODE: "1", NODE_OPTIONS: "" };
  13. afterEach(async () => {
  14. await Promise.all(directories.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
  15. });
  16. async function fixture(source: string) {
  17. const dir = await mkdtemp(join(tmpdir(), "zcode bytecode 中文 "));
  18. directories.push(dir);
  19. const entryPath = join(dir, "zcode.cjs");
  20. await writeFile(entryPath, source);
  21. return { dir, entryPath };
  22. }
  23. it("实际 Electron 字节码保留 CommonJS、argv、资源路径和动态函数源码", async () => {
  24. const { dir, entryPath } = await fixture(`#!/usr/bin/env node
  25. // 不应出现在字节码产物中的源码注释
  26. const path = require('node:path');
  27. const value = require('./value.cjs');
  28. const dynamic = new Function('return 7');
  29. process.stdout.write(JSON.stringify({value, args:process.argv.slice(2),
  30. filename:path.basename(__filename), directory:__dirname, dynamic:dynamic(),
  31. hasDynamicSource:dynamic.toString().includes('return 7')}));
  32. `);
  33. await writeFile(join(dir, "value.cjs"), "module.exports = 42;");
  34. const artifact = await buildDesktopAgentBytecode({ entryPath, electronPath });
  35. const result = await execFileAsync(electronPath, [artifact.loaderPath, "app-server", "--stdio"], {
  36. env: runtimeEnv,
  37. });
  38. expect(JSON.parse(result.stdout)).toEqual({
  39. value: 42,
  40. args: ["app-server", "--stdio"],
  41. filename: "zcode.cjs",
  42. directory: await realpath(dir),
  43. dynamic: 7,
  44. hasDynamicSource: true,
  45. });
  46. expect(result.stderr).toBe("");
  47. expect(await readFile(entryPath, "utf8")).toContain("不应出现在字节码产物中的源码注释");
  48. expect(
  49. (await readFile(artifact.bytecodePath)).includes(
  50. Buffer.from("不应出现在字节码产物中的源码注释"),
  51. ),
  52. ).toBe(false);
  53. });
  54. it.each(["0", "1"])(
  55. "字节码内动态 import 按原 bundle 目录加载 ESM(FORCE_COLOR=%s)",
  56. async (forceColor) => {
  57. // 只验证导入值,直接写 stdout,避免 console.log 按 FORCE_COLOR 给数字着色。
  58. const { dir, entryPath } = await fixture(
  59. "import('./value.mjs').then(m => process.stdout.write(String(m.default)));",
  60. );
  61. await writeFile(join(dir, "value.mjs"), "export default 43;");
  62. const artifact = await buildDesktopAgentBytecode({ entryPath, electronPath });
  63. const result = await execFileAsync(electronPath, [artifact.loaderPath], {
  64. env: { ...runtimeEnv, FORCE_COLOR: forceColor },
  65. });
  66. expect(result.stdout).toBe("43");
  67. },
  68. );
  69. it("损坏字节码在 CLI 执行前失败且不污染 stdout", async () => {
  70. const { entryPath } = await fixture("console.log('SHOULD_NOT_EXECUTE');");
  71. const artifact = await buildDesktopAgentBytecode({ entryPath, electronPath });
  72. await writeFile(artifact.bytecodePath, "corrupt");
  73. await expect(
  74. execFileAsync(electronPath, [artifact.loaderPath], { env: runtimeEnv }),
  75. ).rejects.toMatchObject({
  76. code: 1,
  77. stdout: "",
  78. stderr: expect.stringContaining("字节码摘要不匹配"),
  79. });
  80. });
  81. it("不同 V8 运行时在反序列化前失败", async () => {
  82. const { entryPath } = await fixture("console.log('SHOULD_NOT_EXECUTE');");
  83. const artifact = await buildDesktopAgentBytecode({ entryPath, electronPath });
  84. await expect(
  85. execFileAsync(process.execPath, [artifact.loaderPath], {
  86. env: { ...process.env, NODE_OPTIONS: "" },
  87. }),
  88. ).rejects.toMatchObject({
  89. code: 1,
  90. stdout: "",
  91. stderr: expect.stringContaining("字节码运行时不匹配"),
  92. });
  93. });
  94. it("编译函数报错保留错误消息与函数名,诊断只写 stderr", async () => {
  95. const { entryPath } = await fixture(
  96. "function bytecodeFailure() { throw new Error('EXPECTED_BYTECODE_FAILURE'); } bytecodeFailure();",
  97. );
  98. const artifact = await buildDesktopAgentBytecode({ entryPath, electronPath });
  99. await expect(
  100. execFileAsync(electronPath, [artifact.loaderPath], { env: runtimeEnv }),
  101. ).rejects.toMatchObject({
  102. code: 1,
  103. stdout: "",
  104. stderr: expect.stringMatching(/EXPECTED_BYTECODE_FAILURE[\s\S]*bytecodeFailure/),
  105. });
  106. });
  107. it("编译失败保留上次可运行的加载器,编译阶段不执行 CLI", async () => {
  108. const { dir, entryPath } = await fixture(
  109. "require('node:fs').writeFileSync(__dirname+'/executed', 'yes');",
  110. );
  111. const artifact = await buildDesktopAgentBytecode({ entryPath, electronPath });
  112. await expect(readFile(join(dir, "executed"))).rejects.toMatchObject({ code: "ENOENT" });
  113. const loader = await readFile(artifact.loaderPath);
  114. await writeFile(entryPath, "function {");
  115. await expect(buildDesktopAgentBytecode({ entryPath, electronPath })).rejects.toThrow();
  116. expect(await readFile(artifact.loaderPath)).toEqual(loader);
  117. });
  118. it("拒绝 coverage 构建混用字节码", async () => {
  119. const { entryPath } = await fixture("42;");
  120. await expect(
  121. buildDesktopAgentBytecode({ entryPath, electronPath, env: { ZCODE_E2E_COVERAGE: "1" } }),
  122. ).rejects.toThrow(/coverage/);
  123. });