build-remote.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { readFileSync } from "node:fs";
  2. import { build, type Plugin } from "esbuild";
  3. import { validateRemoteServerBundle } from "./buildRemoteValidation.js";
  4. import { loadBuiltinProviderConfig } from "../../scripts/builtin-provider-config.mjs";
  5. import { stageThirdPartyNotices } from "../../scripts/third-party-notices.mjs";
  6. const { version } = JSON.parse(readFileSync("../../package.json", "utf-8"));
  7. const { content: zcodeBuiltinProviderConfigJson } = await loadBuiltinProviderConfig();
  8. /**
  9. * Let esbuild bundle node-pty's JS code normally, but keep .node native
  10. * addon files as external requires. node-pty's loadNativeModule() searches
  11. * for `./build/Release/pty.node` relative to itself, which matches our
  12. * deploy layout on the remote.
  13. *
  14. * CJS 格式而非 ESM:node-pty 内部大量使用 __dirname,ESM 里没有这个变量,
  15. * 用 CJS 输出可以直接原生支持,不需要任何 polyfill。
  16. */
  17. const nativeAddonPlugin: Plugin = {
  18. name: "native-addon",
  19. setup(build) {
  20. // Mark all .node files as external — they can't be bundled
  21. build.onResolve({ filter: /\.node$/ }, (args) => ({
  22. path: args.path,
  23. external: true,
  24. }));
  25. },
  26. };
  27. const buildResult = await build({
  28. entryPoints: ["src/entry-stdio.ts"],
  29. bundle: true,
  30. outfile: "dist/remote/zcode-server.cjs",
  31. platform: "node",
  32. format: "cjs",
  33. target: "node22",
  34. plugins: [nativeAddonPlugin],
  35. // CJS 环境没有 import.meta.url,通过 banner 注入等价变量,
  36. // 再用 define 全局替换,这样源码无需关心最终打包格式。
  37. banner: {
  38. js: 'var __import_meta_url = require("url").pathToFileURL(__filename).href; var __import_meta_dirname = __dirname;',
  39. },
  40. define: {
  41. "import.meta.url": "__import_meta_url",
  42. "import.meta.dirname": "__import_meta_dirname",
  43. __ZCODE_VERSION__: JSON.stringify(version),
  44. __ZCODE_BUILTIN_PROVIDER_CONFIG_JSON__: JSON.stringify(zcodeBuiltinProviderConfigJson),
  45. },
  46. metafile: true,
  47. });
  48. const remoteBundleSource = readFileSync("dist/remote/zcode-server.cjs", "utf-8");
  49. const bundledInputs = Object.keys(buildResult.metafile.inputs);
  50. validateRemoteServerBundle({ bundledInputs, source: remoteBundleSource });
  51. // 修复:remote 单文件 bundle 内联第三方代码,dist/remote 也必须附完整声明。
  52. await stageThirdPartyNotices("dist/remote");
  53. console.log("Built dist/remote/zcode-server.cjs");