third-party-npm.mjs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 unsupportedCanvas = new Set([
  10. "@napi-rs/canvas-android-arm64",
  11. "@napi-rs/canvas-linux-arm-gnueabihf",
  12. "@napi-rs/canvas-linux-riscv64-gnu",
  13. ]);
  14. const noticeName =
  15. /(?:^|[._-])(?:licen[sc]es?|copying|notice|copyright|unlicense|third.party|ofl)(?:[._-]|$)/iu;
  16. export async function readPackageNotices(directory) {
  17. const files = [];
  18. async function visit(path) {
  19. for (const entry of await readdir(path, { withFileTypes: true })) {
  20. if (["node_modules", ".git", "test", "tests", "fixtures"].includes(entry.name)) continue;
  21. // Chromium 聚合许可由打包流程经 resources/licenses/electron 单独分发,不进 npm 通知。
  22. if (entry.isFile() && entry.name === "LICENSES.chromium.html") continue;
  23. const full = join(path, entry.name);
  24. if (entry.isDirectory()) await visit(full);
  25. else if (entry.isFile() && noticeName.test(entry.name)) {
  26. const bytes = await readFile(full);
  27. if (bytes.includes(0) || bytes.length === 0) continue;
  28. files.push({ member: relative(directory, full).replaceAll("\\", "/"), bytes });
  29. } else if (entry.isFile() && /^readme(?:\.[^/]*)?$/iu.test(entry.name)) {
  30. const text = await readFile(full, "utf8");
  31. const match = /^(?:#{1,6}\s+licen[sc]e[^\n]*\n|licen[sc]e\s*\n[=-]+\n)/imu.exec(text);
  32. if (match) {
  33. const section = text.slice(match.index).split(/\n(?=#{1,6}\s)/u)[0];
  34. files.push({
  35. member: `${relative(directory, full).replaceAll("\\", "/")} (license section)`,
  36. bytes: Buffer.from(section),
  37. });
  38. }
  39. }
  40. }
  41. }
  42. await visit(directory);
  43. return files.sort((a, b) => a.member.localeCompare(b.member, "en"));
  44. }
  45. function productionPackages(projects) {
  46. const own = new Set(projects.map((project) => project.name));
  47. const required = new Map();
  48. function dependencies(deps) {
  49. for (const [alias, info] of Object.entries(deps ?? {})) {
  50. const name = info.name ?? alias;
  51. if (!own.has(name) && !name.startsWith("@zcode/") && !info.version.startsWith("link:")) {
  52. required.set(`${name}@${info.version}`, { name, version: info.version });
  53. }
  54. dependencies(info.dependencies);
  55. dependencies(info.optionalDependencies);
  56. }
  57. }
  58. for (const project of projects) {
  59. dependencies(project.dependencies);
  60. dependencies(project.optionalDependencies);
  61. }
  62. return required;
  63. }
  64. export function assertProductionGraphs(lockedProjects, installedProjects) {
  65. const locked = productionPackages(lockedProjects);
  66. const installed = productionPackages(installedProjects);
  67. const missing = [...locked].filter(
  68. ([key, item]) => !installed.has(key) && !unsupportedCanvas.has(item.name),
  69. );
  70. const stale = [...installed.keys()].filter((key) => !locked.has(key));
  71. if (missing.length || stale.length) {
  72. throw new Error(
  73. `Installed production graph differs from pnpm-lock.yaml. Run pnpm install --frozen-lockfile.\nMissing: ${missing.map(([key]) => key).join(", ")}\nStale: ${stale.join(", ")}`,
  74. );
  75. }
  76. return locked;
  77. }
  78. export async function readWorkspaceProductionGraph(root) {
  79. root = await realpath(root);
  80. // 修复:pnpm ls 默认读取安装快照,不能把旧图与当前锁文件哈希拼成有效声明。
  81. const [locked, actual] = await Promise.all(
  82. [true, false].map(async (lockfileOnly) => {
  83. const { stdout } = await exec(
  84. "pnpm",
  85. [
  86. "-r",
  87. "ls",
  88. "--prod",
  89. "--json",
  90. "--depth",
  91. "Infinity",
  92. ...(lockfileOnly ? ["--lockfile-only"] : []),
  93. ],
  94. {
  95. cwd: root,
  96. maxBuffer: 256 * 1024 * 1024,
  97. ...resolveSpawnRuntimeOptions("pnpm"),
  98. },
  99. );
  100. return JSON.parse(stdout);
  101. }),
  102. );
  103. const required = assertProductionGraphs(locked, actual);
  104. return { required, projects: actual };
  105. }
  106. export async function scanInstalledPackages(root, projects) {
  107. // pnpm hoisted 布局的 ls.path 仍可能指向不存在的 .pnpm 路径;按真实安装目录和精确版本匹配。
  108. const installed = new Map();
  109. const visited = new Set();
  110. async function scanNodeModules(directory) {
  111. let actual;
  112. try {
  113. actual = await realpath(directory);
  114. } catch (error) {
  115. if (error.code === "ENOENT") return;
  116. throw error;
  117. }
  118. if (visited.has(actual)) return;
  119. visited.add(actual);
  120. const entries = await readdir(directory, { withFileTypes: true });
  121. for (const entry of entries) {
  122. if (entry.name.startsWith(".")) continue;
  123. const path = join(directory, entry.name);
  124. if (entry.name.startsWith("@")) {
  125. for (const scoped of await readdir(path)) await scanPackage(join(path, scoped));
  126. } else await scanPackage(path);
  127. }
  128. }
  129. async function scanPackage(directory) {
  130. let pkg;
  131. try {
  132. pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
  133. } catch (error) {
  134. if (["ENOENT", "ENOTDIR"].includes(error.code)) return;
  135. throw error;
  136. }
  137. if (pkg.name && pkg.version) installed.set(`${pkg.name}@${pkg.version}`, { pkg, directory });
  138. await scanNodeModules(join(directory, "node_modules"));
  139. }
  140. for (const project of projects) await scanNodeModules(join(project.path, "node_modules"));
  141. await scanNodeModules(join(root, "node_modules"));
  142. await scanNodeModules(join(root, "apps/zcode-cli/node_modules"));
  143. return installed;
  144. }
  145. export function missingProductionPackages(required, installed) {
  146. const missing = [...required].filter(([key]) => !installed.has(key)).map(([, item]) => item);
  147. for (const item of missing) {
  148. if (!unsupportedCanvas.has(item.name))
  149. throw new Error(`Missing installed dependency: ${item.name}@${item.version}`);
  150. }
  151. return missing;
  152. }
  153. export async function collectNpmNotices(root, overrides) {
  154. root = await realpath(root);
  155. const { required, projects } = await readWorkspaceProductionGraph(root);
  156. // 修复:标识门禁和声明生成必须扫描同一安装集合,避免嵌套版本只进声明、不进门禁。
  157. const installed = await scanInstalledPackages(root, projects);
  158. const packages = [];
  159. const missing = [];
  160. const notInstalled = missingProductionPackages(required, installed);
  161. for (const [key, item] of [...required].sort(([a], [b]) => a.localeCompare(b, "en"))) {
  162. const installedPackage = installed.get(key);
  163. if (!installedPackage) {
  164. continue;
  165. }
  166. const { pkg, directory } = installedPackage;
  167. const notices = await readPackageNotices(directory);
  168. const override = overrides.find((record) => record.package === key);
  169. if (override?.file) {
  170. const bytes = await readFile(join(root, override.file));
  171. if (hashBytes(bytes) !== override.sha256) throw new Error(`Changed upstream notice: ${key}`);
  172. notices.push({ member: override.source, bytes });
  173. }
  174. // README 中仅有 MIT 等标签不能冒充完整许可文件;这种包仍需要版本固定的补充材料。
  175. if (
  176. !notices.some(({ member }) => !member.endsWith(" (license section)")) &&
  177. !override?.acceptedMissingNotice
  178. )
  179. missing.push(key);
  180. packages.push({
  181. ...item,
  182. license:
  183. pkg.license ??
  184. pkg.licenses?.map((item) => (typeof item === "string" ? item : item.type)).join(" OR ") ??
  185. override?.license ??
  186. "(not declared)",
  187. repository: typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url,
  188. ...(override?.acceptedMissingNotice
  189. ? { acceptedMissingNotice: override.acceptedMissingNotice }
  190. : {}),
  191. notices,
  192. });
  193. }
  194. if (missing.length) throw new Error(`Missing complete upstream notices:\n${missing.join("\n")}`);
  195. return {
  196. packages,
  197. notInstalled,
  198. workspaceManifests: projects.map((project) =>
  199. relative(root, join(project.path, "package.json")).replaceAll("\\", "/"),
  200. ),
  201. };
  202. }