third-party-npm.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import { execFile } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { readFile, readdir, realpath } from "node:fs/promises";
  4. import { join, relative } from "node:path";
  5. import { promisify } from "node:util";
  6. import { resolveSpawnRuntimeOptions } from "./spawn-command.mjs";
  7. const exec = promisify(execFile);
  8. export const hashBytes = (bytes) => createHash("sha256").update(bytes).digest("hex");
  9. const noticeName =
  10. /(?:^|[._-])(?:licen[sc]es?|copying|notice|copyright|unlicense|third.party|ofl)(?:[._-]|$)/iu;
  11. export async function readPackageNotices(directory) {
  12. const files = [];
  13. async function visit(path) {
  14. for (const entry of await readdir(path, { withFileTypes: true })) {
  15. if (["node_modules", ".git", "test", "tests", "fixtures"].includes(entry.name)) continue;
  16. // Chromium 聚合许可由打包流程经 resources/licenses/electron 单独分发,不进 npm 通知。
  17. if (entry.isFile() && entry.name === "LICENSES.chromium.html") continue;
  18. const full = join(path, entry.name);
  19. if (entry.isDirectory()) await visit(full);
  20. else if (entry.isFile() && noticeName.test(entry.name)) {
  21. const bytes = await readFile(full);
  22. if (bytes.includes(0) || bytes.length === 0) continue;
  23. files.push({ member: relative(directory, full).replaceAll("\\", "/"), bytes });
  24. } else if (entry.isFile() && /^readme(?:\.[^/]*)?$/iu.test(entry.name)) {
  25. const text = await readFile(full, "utf8");
  26. const match = /^(?:#{1,6}\s+licen[sc]e[^\n]*\n|licen[sc]e\s*\n[=-]+\n)/imu.exec(text);
  27. if (match) {
  28. const section = text.slice(match.index).split(/\n(?=#{1,6}\s)/u)[0];
  29. files.push({
  30. member: `${relative(directory, full).replaceAll("\\", "/")} (license section)`,
  31. bytes: Buffer.from(section),
  32. });
  33. }
  34. }
  35. }
  36. }
  37. await visit(directory);
  38. return files.sort((a, b) => a.member.localeCompare(b.member, "en"));
  39. }
  40. // 解析锁文件(v9)packages 段的平台约束:` 'name@version':` 下的 ` os/cpu/libc: [..]` 行。
  41. export function readLockfilePlatformConstraints(lockfileText) {
  42. const constraints = new Map();
  43. let inPackages = false;
  44. let key = null;
  45. for (const line of lockfileText.split(/\r?\n/u)) {
  46. if (/^\S/u.test(line)) {
  47. inPackages = line === "packages:";
  48. key = null;
  49. continue;
  50. }
  51. if (!inPackages) continue;
  52. const header = /^ {2}(?:'([^']+)'|([^\s'][^:]*)):$/u.exec(line);
  53. if (header) {
  54. key = header[1] ?? header[2];
  55. continue;
  56. }
  57. const field = key && /^ {4}(os|cpu|libc): \[(.*)\]$/u.exec(line);
  58. if (field) {
  59. const values = field[2]
  60. .split(",")
  61. .map((value) => value.trim().replace(/^'(.*)'$/u, "$1"))
  62. .filter(Boolean);
  63. constraints.set(key, { ...constraints.get(key), [field[1]]: values });
  64. }
  65. }
  66. return constraints;
  67. }
  68. // 照搬 pnpm package-is-installable 的 checkList,保证与实际安装结果一致(含否定项语义)。
  69. function pnpmCheckList(values, list) {
  70. if (list.length === 1 && list[0] === "any") return true;
  71. let match = false;
  72. let blc = 0;
  73. for (const value of values) {
  74. for (const item of list) {
  75. if (item[0] === "!") {
  76. if (item.slice(1) === value) return false;
  77. ++blc;
  78. } else {
  79. match = match || item === value;
  80. }
  81. }
  82. }
  83. return match || blc === list.length;
  84. }
  85. // targets.libc 为 null 表示宿主 libc 未知(非 Linux),pnpm 此时不检查 libc。
  86. export function createInstallablePackageFilter(constraints, targets) {
  87. return (name, version) => {
  88. const wanted = constraints.get(`${name}@${version.split("(")[0]}`);
  89. if (!wanted) return true;
  90. if (wanted.os && !pnpmCheckList(targets.os, wanted.os)) return false;
  91. if (wanted.cpu && !pnpmCheckList(targets.cpu, wanted.cpu)) return false;
  92. if (wanted.libc && targets.libc && !pnpmCheckList(targets.libc, wanted.libc)) return false;
  93. return true;
  94. };
  95. }
  96. function hostLibc() {
  97. if (process.platform !== "linux") return null;
  98. return process.report?.getReport?.()?.header?.glibcVersionRuntime ? "glibc" : "musl";
  99. }
  100. // 与 pnpm checkPlatform 相同:supportedArchitectures 未配置时只取宿主,`current` 替换为宿主值。
  101. export async function readInstallTargets(root) {
  102. const { parse } = await import("yaml");
  103. const workspace = parse(await readFile(join(root, "pnpm-workspace.yaml"), "utf8")) ?? {};
  104. const supported = workspace.supportedArchitectures ?? {};
  105. const resolveCurrent = (list, current) =>
  106. (list ?? ["current"]).map((value) => (value === "current" ? current : value));
  107. const libc = hostLibc();
  108. return {
  109. os: resolveCurrent(supported.os, process.platform),
  110. cpu: resolveCurrent(supported.cpu, process.arch),
  111. libc: libc ? resolveCurrent(supported.libc, libc) : null,
  112. };
  113. }
  114. // 修复:pnpm 按 supportedArchitectures 跳过的平台包(如 sharp 的 s390x/wasm32 构建)从不安装、不分发,
  115. // 此前靠按包名的例外名单放行,新依赖一引入就会误报缺失;现在按锁文件平台约束整棵子树跳过。
  116. export function productionPackages(projects, isInstallable = () => true) {
  117. const own = new Set(projects.map((project) => project.name));
  118. const required = new Map();
  119. function dependencies(deps) {
  120. for (const [alias, info] of Object.entries(deps ?? {})) {
  121. const name = info.name ?? alias;
  122. if (!isInstallable(name, info.version)) continue;
  123. if (!own.has(name) && !name.startsWith("@zcode/") && !info.version.startsWith("link:")) {
  124. required.set(`${name}@${info.version}`, { name, version: info.version });
  125. }
  126. dependencies(info.dependencies);
  127. dependencies(info.optionalDependencies);
  128. }
  129. }
  130. for (const project of projects) {
  131. dependencies(project.dependencies);
  132. dependencies(project.optionalDependencies);
  133. }
  134. return required;
  135. }
  136. export function assertInstalledLockfileSnapshot(rootLockfile, installedLockfile) {
  137. // Windows autocrlf 工作区的根 lockfile 可能是 CRLF,而 pnpm 安装快照始终写 LF;
  138. // 换行风格不改变依赖图,归一化后比较(评审 CR-03:原始字符串比较会把
  139. // 依赖图一致的 CRLF 工作区误判为安装快照过期,且重装无法消除差异)。
  140. const normalize = (value) => value.replaceAll("\r\n", "\n");
  141. if (normalize(rootLockfile) !== normalize(installedLockfile)) {
  142. throw new Error(
  143. "Installed dependency snapshot differs from pnpm-lock.yaml. Run pnpm install --frozen-lockfile.",
  144. );
  145. }
  146. }
  147. async function readWorkspaceProjects(root) {
  148. const { stdout } = await exec("pnpm", ["-r", "list", "--depth", "-1", "--json"], {
  149. cwd: root,
  150. maxBuffer: 64 * 1024 * 1024,
  151. ...resolveSpawnRuntimeOptions("pnpm"),
  152. });
  153. return JSON.parse(stdout);
  154. }
  155. export function createPnpmLockfileOnlyEnv(env = process.env) {
  156. return { ...env, NPM_CONFIG_LOCKFILE_ONLY: "true" };
  157. }
  158. async function readLockedWorkspaceProductionGraph(root, workspaceProjects) {
  159. const projects = [];
  160. // pnpm 10.33.2 的递归 list 在 Windows 会一次打开整个 workspace,超过句柄上限。
  161. // 固定根 lockfile 后按唯一 workspace 名称逐项过滤,保留完整 deduped 子树并限制峰值句柄数。
  162. for (const project of workspaceProjects) {
  163. const { stdout } = await exec(
  164. "pnpm",
  165. ["--filter", project.name, "list", "--prod", "--json", "--depth", "Infinity"],
  166. {
  167. cwd: root,
  168. env: createPnpmLockfileOnlyEnv(),
  169. maxBuffer: 64 * 1024 * 1024,
  170. ...resolveSpawnRuntimeOptions("pnpm"),
  171. },
  172. );
  173. const rows = JSON.parse(stdout);
  174. if (rows.length !== 1) {
  175. throw new Error(`Unexpected pnpm production graph rows for ${project.name}: ${rows.length}`);
  176. }
  177. projects.push(rows[0]);
  178. }
  179. return projects;
  180. }
  181. export async function readWorkspaceProductionGraph(root) {
  182. root = await realpath(root);
  183. const rootLockfile = await readFile(join(root, "pnpm-lock.yaml"), "utf8");
  184. let installedLockfile;
  185. try {
  186. installedLockfile = await readFile(join(root, "node_modules/.pnpm/lock.yaml"), "utf8");
  187. } catch (error) {
  188. if (error.code !== "ENOENT") throw error;
  189. throw new Error(
  190. "Installed dependency snapshot is missing. Run pnpm install --frozen-lockfile.",
  191. { cause: error },
  192. );
  193. }
  194. assertInstalledLockfileSnapshot(rootLockfile, installedLockfile);
  195. const workspaceProjects = await readWorkspaceProjects(root);
  196. const lockedProjects = await readLockedWorkspaceProductionGraph(root, workspaceProjects);
  197. const isInstallable = createInstallablePackageFilter(
  198. readLockfilePlatformConstraints(rootLockfile),
  199. await readInstallTargets(root),
  200. );
  201. const required = productionPackages(lockedProjects, isInstallable);
  202. return { required, projects: workspaceProjects };
  203. }
  204. export async function scanInstalledPackages(root, projects) {
  205. // pnpm hoisted 布局的 ls.path 仍可能指向不存在的 .pnpm 路径;按真实安装目录和精确版本匹配。
  206. const installed = new Map();
  207. const visited = new Set();
  208. async function scanNodeModules(directory) {
  209. let actual;
  210. try {
  211. actual = await realpath(directory);
  212. } catch (error) {
  213. if (error.code === "ENOENT") return;
  214. throw error;
  215. }
  216. if (visited.has(actual)) return;
  217. visited.add(actual);
  218. const entries = await readdir(directory, { withFileTypes: true });
  219. for (const entry of entries) {
  220. if (entry.name.startsWith(".")) continue;
  221. const path = join(directory, entry.name);
  222. if (entry.name.startsWith("@")) {
  223. for (const scoped of await readdir(path)) await scanPackage(join(path, scoped));
  224. } else await scanPackage(path);
  225. }
  226. }
  227. async function scanPackage(directory) {
  228. let pkg;
  229. try {
  230. pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
  231. } catch (error) {
  232. if (["ENOENT", "ENOTDIR"].includes(error.code)) return;
  233. throw error;
  234. }
  235. if (pkg.name && pkg.version) installed.set(`${pkg.name}@${pkg.version}`, { pkg, directory });
  236. await scanNodeModules(join(directory, "node_modules"));
  237. }
  238. for (const project of projects) await scanNodeModules(join(project.path, "node_modules"));
  239. await scanNodeModules(join(root, "node_modules"));
  240. await scanNodeModules(join(root, "apps/zcode-cli/node_modules"));
  241. return installed;
  242. }
  243. export function missingProductionPackages(required, installed) {
  244. const missing = [...required].filter(([key]) => !installed.has(key)).map(([, item]) => item);
  245. for (const item of missing) {
  246. throw new Error(`Missing installed dependency: ${item.name}@${item.version}`);
  247. }
  248. return missing;
  249. }
  250. export async function collectNpmNotices(root, overrides) {
  251. root = await realpath(root);
  252. const { required, projects } = await readWorkspaceProductionGraph(root);
  253. // 修复:标识门禁和声明生成必须扫描同一安装集合,避免嵌套版本只进声明、不进门禁。
  254. const installed = await scanInstalledPackages(root, projects);
  255. const packages = [];
  256. const missing = [];
  257. const notInstalled = missingProductionPackages(required, installed);
  258. for (const [key, item] of [...required].sort(([a], [b]) => a.localeCompare(b, "en"))) {
  259. const installedPackage = installed.get(key);
  260. if (!installedPackage) {
  261. continue;
  262. }
  263. const { pkg, directory } = installedPackage;
  264. const notices = await readPackageNotices(directory);
  265. const override = overrides.find((record) => record.package === key);
  266. if (override?.file) {
  267. const bytes = await readFile(join(root, override.file));
  268. if (hashBytes(bytes) !== override.sha256) throw new Error(`Changed upstream notice: ${key}`);
  269. notices.push({ member: override.source, bytes });
  270. }
  271. // README 中仅有 MIT 等标签不能冒充完整许可文件;这种包仍需要版本固定的补充材料。
  272. if (
  273. !notices.some(({ member }) => !member.endsWith(" (license section)")) &&
  274. !override?.acceptedMissingNotice
  275. )
  276. missing.push(key);
  277. packages.push({
  278. ...item,
  279. license:
  280. pkg.license ??
  281. pkg.licenses?.map((item) => (typeof item === "string" ? item : item.type)).join(" OR ") ??
  282. override?.license ??
  283. "(not declared)",
  284. repository: typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url,
  285. ...(override?.acceptedMissingNotice
  286. ? { acceptedMissingNotice: override.acceptedMissingNotice }
  287. : {}),
  288. notices,
  289. });
  290. }
  291. if (missing.length) throw new Error(`Missing complete upstream notices:\n${missing.join("\n")}`);
  292. return {
  293. packages,
  294. notInstalled,
  295. workspaceManifests: projects.map((project) =>
  296. relative(root, join(project.path, "package.json")).replaceAll("\\", "/"),
  297. ),
  298. };
  299. }