build.mjs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { chmod, mkdir } from "node:fs/promises";
  2. import { dirname, resolve } from "node:path";
  3. import { pathToFileURL } from "node:url";
  4. import { build } from "esbuild";
  5. const defaultPackageRoot = resolve(import.meta.dirname, "..");
  6. const executableFileMode = 0o755;
  7. // esbuild 以 format: "esm" 打包时,会把 CJS 依赖里的 require() 替换成一个 __require shim:
  8. // typeof require !== "undefined" ? require : (name) => { throw Error('Dynamic require of "' + name + '" is not supported') }
  9. // ESM 模块作用域里没有 require,于是这个 shim 永远走抛错分支。
  10. // @zcode/core 从 tool/handlers/write.js -> memory/origin-session.js eager import 了 CJS 的
  11. // yaml,yaml 内部 require("process") 正好命中 shim,导致 dist/mcp/server.js 在**模块求值阶段**
  12. // 就抛 `Dynamic require of "process" is not supported`;plugin host 的 await import() 直接失败,
  13. // 表现为 mcp.server.closed / mcp.server.failed、注册 0 个工具,模型侧彻底看不到 mcp__node_repl__js。
  14. // 这里注入真实的 createRequire,让 shim 落到可用的 require 上(产物仍是 ESM)。
  15. // 两个 bundle 都加:browser-client 目前没有 CJS 依赖,但同样是 ESM 产物,后续被拖进一个
  16. // CJS 依赖就会以同样的方式在加载期炸掉。
  17. const nodeRequireBanner = `import { createRequire as __zcodeCreateRequire } from "node:module";
  18. const require = __zcodeCreateRequire(import.meta.url);`;
  19. const createBundleOptions = ({ entryPoint, outfile }) => ({
  20. banner: {
  21. js: nodeRequireBanner,
  22. },
  23. bundle: true,
  24. entryPoints: [entryPoint],
  25. format: "esm",
  26. legalComments: "none",
  27. outfile,
  28. platform: "node",
  29. target: "node24",
  30. });
  31. /**
  32. * 供 scripts 直跑与 smoke test 复用的构建入口,保证测试校验的产物与发布产物同一套 esbuild 选项。
  33. */
  34. export const buildBrowserUsePluginBundles = async ({
  35. packageRoot = defaultPackageRoot,
  36. browserClientOutfile = resolve(packageRoot, "scripts", "browser-client.mjs"),
  37. } = {}) => {
  38. // node_repl 宿主的产物由 @zcode/node-repl-host 自己构建与携带;这个包只出 browser-client。
  39. await mkdir(dirname(browserClientOutfile), { recursive: true });
  40. await build(
  41. createBundleOptions({
  42. entryPoint: resolve(packageRoot, "src", "browser-client.ts"),
  43. outfile: browserClientOutfile,
  44. }),
  45. );
  46. await chmod(browserClientOutfile, executableFileMode);
  47. return { browserClientOutfile };
  48. };
  49. const entryPath = process.argv[1];
  50. if (entryPath && import.meta.url === pathToFileURL(entryPath).href) {
  51. await buildBrowserUsePluginBundles();
  52. }