compile-desktop-agent-bytecode.cjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. const { readFile, writeFile } = require("node:fs/promises");
  3. const Module = require("node:module");
  4. const vm = require("node:vm");
  5. const {
  6. configureBytecodeRuntime,
  7. bytecodeDigest,
  8. } = require("./desktop-agent-bytecode-runtime.cjs");
  9. async function compile() {
  10. const [entryPath, outputPath] = process.argv.slice(2);
  11. const runtime = configureBytecodeRuntime();
  12. if (!runtime.electron) throw new Error("桌面 Agent 字节码必须由 Electron Node 模式编译");
  13. const source = await readFile(entryPath, "utf8");
  14. const wrapped = Module.wrap(source.replace(/^#![^\r\n]*/, ""));
  15. const script = new vm.Script(wrapped, {
  16. filename: entryPath,
  17. importModuleDynamically: vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
  18. });
  19. // 仅编译,不调用模块;不能为了预热缓存触发 CLI 的存储、网络或进程副作用。
  20. const cachedData = script.createCachedData();
  21. await writeFile(outputPath, cachedData);
  22. process.stdout.write(
  23. JSON.stringify({
  24. runtime,
  25. sourceLength: wrapped.length,
  26. sourceSha256: bytecodeDigest(Buffer.from(source)),
  27. bytecodeSha256: bytecodeDigest(cachedData),
  28. bytecodeBytes: cachedData.length,
  29. }),
  30. );
  31. }
  32. compile().catch((error) => {
  33. process.stderr.write(`${error.stack ?? error}\n`);
  34. process.exitCode = 1;
  35. });