bundled-npm-assets.mjs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. // 随包 npm:桌面 agent 跑在 Electron Node 上,用户机器没装 Node 时,stdio MCP 的 npm/npx
  2. // 回退到这里 stage 的 npm(规格:apps/zcode-cli/docs/design/v2/mcp-node-fallback.md)。
  3. //
  4. // 为什么下载 registry tarball 而不是加 pnpm 依赖:仓库用 node-linker=hoisted,npm 包的
  5. // npm/npx bin 会被链接进根 node_modules/.bin,覆盖开发者自己的 npm(新 npm 还不支持仓库
  6. // 锁定的 Node 小版本)。这里按固定版本 + registry sha512 下载并缓存,开发工具链不受影响。
  7. import { createHash, randomUUID } from "node:crypto";
  8. import { createReadStream } from "node:fs";
  9. import { access, cp, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
  10. import { tmpdir } from "node:os";
  11. import { basename, join, relative, sep } from "node:path";
  12. import { downloadPrebuiltArchive } from "../../../scripts/prebuilt-binary-download.mjs";
  13. import { extractPrebuiltArchive } from "../../../scripts/prebuilt-binary-extract.mjs";
  14. // engines.node 必须接受 Electron 自带的 Node(Electron 44 = Node 24.21);升级时同步更新摘要。
  15. export const BUNDLED_NPM_VERSION = "12.2.0";
  16. export const BUNDLED_NPM_INTEGRITY =
  17. "sha512-ZsJjKpTnlmSXOLLXiU1xDCzC4Wlok4IwZmh/aw2KUuXytU7q6qMv/cUT7MoeSf95Slwuw/lRXYefGzGCspHPNQ==";
  18. /** 相对 glm 目录(zcode.cjs 所在目录)的位置;与 bootstrap mcp-node-fallback.ts 同一约定。 */
  19. export const BUNDLED_NPM_STAGED_SEGMENTS = ["node-runtime", "npm"];
  20. const NPM_REGISTRY_TARBALL_BASE = "https://registry.npmjs.org/npm/-/";
  21. const NPM_TARBALL_PACKAGE_DIR = "package";
  22. const NPM_REQUIRED_ENTRIES = ["bin/npm-cli.js", "bin/npx-cli.js"];
  23. const NPM_RUN_SCRIPT_SPAWN_ARGS = [
  24. "node_modules",
  25. "@npmcli",
  26. "run-script",
  27. "lib",
  28. "make-spawn-args.js",
  29. ];
  30. const NPM_RUN_SCRIPT_SPAWN_OPTIONS = ` const spawnOpts = {
  31. env: spawnEnv,
  32. stdioString,
  33. stdio,
  34. cwd: path,
  35. shell: scriptShell,
  36. }`;
  37. const NPM_RUN_SCRIPT_HIDDEN_SPAWN_OPTIONS = ` const spawnOpts = {
  38. env: spawnEnv,
  39. stdioString,
  40. stdio,
  41. cwd: path,
  42. shell: scriptShell,
  43. // ZCode 修改:外层隐藏参数不递归;Electron Node 的 npm 子 shell 需单独隐藏空白窗口。
  44. windowsHide: process.platform === 'win32' && process.versions.electron !== undefined,
  45. }`;
  46. // npm help 不受支持;去掉文档与 man 页省下约 3MB。
  47. const EXCLUDED_TOP_LEVEL_ENTRIES = new Set(["docs", "man"]);
  48. const SHA512_PREFIX = "sha512-";
  49. export function bundledNpmTarballUrl(version) {
  50. return `${NPM_REGISTRY_TARBALL_BASE}npm-${version}.tgz`;
  51. }
  52. /**
  53. * 校验并缓存 tarball,解包后拷进 `<glmDir>/node-runtime/npm`。返回 stage 后的 npm 根目录。
  54. * download / extract 可注入,测试无需网络。
  55. */
  56. export async function stageBundledNpm({
  57. cacheDir,
  58. download = downloadPrebuiltArchive,
  59. extract = extractPrebuiltArchive,
  60. glmDir,
  61. integrity = BUNDLED_NPM_INTEGRITY,
  62. version = BUNDLED_NPM_VERSION,
  63. }) {
  64. const tarballPath = await ensureVerifiedTarball({ cacheDir, download, integrity, version });
  65. const workDir = await mkdtemp(join(tmpdir(), "zcode-bundled-npm-"));
  66. try {
  67. extract({ archiveExt: "tgz", archivePath: tarballPath, cwd: workDir, extractDir: workDir });
  68. const packageRoot = join(workDir, NPM_TARBALL_PACKAGE_DIR);
  69. await assertNpmEntries(packageRoot);
  70. await patchNpmRunScriptWindowsHide(packageRoot);
  71. const targetRoot = join(glmDir, ...BUNDLED_NPM_STAGED_SEGMENTS);
  72. await rm(targetRoot, { force: true, recursive: true });
  73. await cp(packageRoot, targetRoot, {
  74. filter: (source) => !isExcludedTopLevelEntry(packageRoot, source),
  75. recursive: true,
  76. });
  77. return targetRoot;
  78. } finally {
  79. await rm(workDir, { force: true, recursive: true });
  80. }
  81. }
  82. async function ensureVerifiedTarball({ cacheDir, download, integrity, version }) {
  83. const tarballPath = join(cacheDir, `npm-${version}.tgz`);
  84. if (await isTarballValid(tarballPath, integrity)) return tarballPath;
  85. await mkdir(cacheDir, { recursive: true });
  86. const temporaryPath = `${tarballPath}.tmp-${process.pid}-${randomUUID()}`;
  87. try {
  88. await download(bundledNpmTarballUrl(version), temporaryPath);
  89. if (!(await isTarballValid(temporaryPath, integrity))) {
  90. throw new Error(`[bundled-npm] sha512 mismatch for npm@${version}`);
  91. }
  92. await rename(temporaryPath, tarballPath);
  93. return tarballPath;
  94. } finally {
  95. await rm(temporaryPath, { force: true });
  96. }
  97. }
  98. async function isTarballValid(tarballPath, integrity) {
  99. try {
  100. return (await sha512Integrity(tarballPath)) === integrity;
  101. } catch {
  102. return false;
  103. }
  104. }
  105. function sha512Integrity(path) {
  106. return new Promise((resolvePromise, rejectPromise) => {
  107. const hash = createHash("sha512");
  108. createReadStream(path)
  109. .on("error", rejectPromise)
  110. .on("data", (chunk) => hash.update(chunk))
  111. .on("end", () => resolvePromise(`${SHA512_PREFIX}${hash.digest("base64")}`));
  112. });
  113. }
  114. async function assertNpmEntries(packageRoot) {
  115. for (const entry of NPM_REQUIRED_ENTRIES) {
  116. const entryPath = join(packageRoot, ...entry.split("/"));
  117. try {
  118. await access(entryPath);
  119. } catch (error) {
  120. throw new Error(`[bundled-npm] missing npm entry ${entry} in ${packageRoot}`, {
  121. cause: error,
  122. });
  123. }
  124. }
  125. }
  126. async function patchNpmRunScriptWindowsHide(packageRoot) {
  127. const sourcePath = join(packageRoot, ...NPM_RUN_SCRIPT_SPAWN_ARGS);
  128. const source = await readFile(sourcePath, "utf8");
  129. if (source.split(NPM_RUN_SCRIPT_SPAWN_OPTIONS).length !== 2) {
  130. throw new Error(
  131. "[bundled-npm] expected one run-script spawn-options block; review the npm patch",
  132. );
  133. }
  134. await writeFile(
  135. sourcePath,
  136. source.replace(NPM_RUN_SCRIPT_SPAWN_OPTIONS, NPM_RUN_SCRIPT_HIDDEN_SPAWN_OPTIONS),
  137. );
  138. }
  139. function isExcludedTopLevelEntry(packageRoot, source) {
  140. const relativePath = relative(packageRoot, source);
  141. return !relativePath.includes(sep) && EXCLUDED_TOP_LEVEL_ENTRIES.has(basename(source));
  142. }