build-remote.ts 2.6 KB

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