build-desktop-agent-bytecode.mjs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { execFile } from "node:child_process";
  2. import { createHash, randomUUID } from "node:crypto";
  3. import { readFile, rename, rm, writeFile } from "node:fs/promises";
  4. import { createRequire } from "node:module";
  5. import { basename, dirname, join, resolve } from "node:path";
  6. import { pathToFileURL } from "node:url";
  7. import { promisify } from "node:util";
  8. const execFileAsync = promisify(execFile);
  9. const repoRoot = resolve(import.meta.dirname, "..");
  10. const defaultEntryPath = join(repoRoot, "apps/zcode-cli/packages/cli/dist/zcode.cjs");
  11. const runtimeSourcePath = join(import.meta.dirname, "desktop-agent-bytecode-runtime.cjs");
  12. const compilerPath = join(import.meta.dirname, "compile-desktop-agent-bytecode.cjs");
  13. async function publishImmutable(path, contents) {
  14. try {
  15. await writeFile(path, contents, { flag: "wx" });
  16. } catch (error) {
  17. if (error.code !== "EEXIST") throw error;
  18. if (!(await readFile(path)).equals(contents)) {
  19. throw new Error(`已有字节码资源损坏: ${path}`);
  20. }
  21. }
  22. }
  23. export async function buildDesktopAgentBytecode({
  24. entryPath = defaultEntryPath,
  25. electronPath = createRequire(import.meta.url)("electron"),
  26. env = process.env,
  27. } = {}) {
  28. if (env.ZCODE_E2E_COVERAGE === "1") throw new Error("coverage 构建不能启用字节码试验");
  29. const directory = dirname(entryPath);
  30. const temporary = join(directory, `.bytecode-${randomUUID()}`);
  31. const loaderPath = join(directory, "zcode.bytecode.cjs");
  32. try {
  33. const { stdout } = await execFileAsync(electronPath, [compilerPath, entryPath, temporary], {
  34. env: { ...env, ELECTRON_RUN_AS_NODE: "1", NODE_OPTIONS: "" },
  35. maxBuffer: 1024 * 1024,
  36. });
  37. const metadata = JSON.parse(stdout);
  38. const bytecodeFile = `zcode.bytecode-${metadata.bytecodeSha256}.jsc`;
  39. const bytecodePath = join(directory, bytecodeFile);
  40. const runtimeSource = await readFile(runtimeSourcePath);
  41. const runtimeHash = createHash("sha256").update(runtimeSource).digest("hex");
  42. const runtimeFile = `zcode.bytecode-runtime-${runtimeHash}.cjs`;
  43. metadata.bytecodeFile = bytecodeFile;
  44. metadata.sourceFile = basename(entryPath);
  45. // 先写不可变依赖,最后原子替换入口;失败时上次可用的加载器仍能找到自己的字节码。
  46. await publishImmutable(bytecodePath, await readFile(temporary));
  47. await publishImmutable(join(directory, runtimeFile), runtimeSource);
  48. const loader = `#!/usr/bin/env node\n"use strict";\nconst metadata = ${JSON.stringify(metadata)};\nrequire(${JSON.stringify(`./${runtimeFile}`)}).loadBytecode(metadata, module, require).catch(error => {\n process.stderr.write(String(error.stack ?? error) + "\\n");\n process.exitCode = 1;\n});\n`;
  49. await writeFile(`${temporary}.cjs`, loader, { mode: 0o755 });
  50. await rename(`${temporary}.cjs`, loaderPath);
  51. return { loaderPath, bytecodePath, metadata };
  52. } finally {
  53. await Promise.all([temporary, `${temporary}.cjs`].map((file) => rm(file, { force: true })));
  54. }
  55. }
  56. if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  57. const artifact = await buildDesktopAgentBytecode();
  58. console.log(JSON.stringify(artifact, null, 2));
  59. }