dep-refs.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #!/usr/bin/env node
  2. import process from "node:process";
  3. import path from "node:path";
  4. import { Project } from "ts-morph";
  5. const ROOT = process.cwd();
  6. const EXCLUDE_GLOBS = [
  7. "!**/node_modules/**",
  8. "!**/dist/**",
  9. "!**/build/**",
  10. "!**/coverage/**",
  11. "!**/out/**",
  12. ];
  13. const DEFAULT_GLOBS = [
  14. "packages/*/src/**/*.{ts,tsx,mts,cts}",
  15. "packages/*/test/**/*.{ts,tsx,mts,cts}",
  16. "apps/*/src/**/*.{ts,tsx,mts,cts}",
  17. "apps/*/test/**/*.{ts,tsx,mts,cts}",
  18. "harness/**/*.{ts,tsx,mts,cts}",
  19. ...EXCLUDE_GLOBS,
  20. ];
  21. function loadProject(scope) {
  22. const project = new Project({
  23. tsConfigFilePath: path.join(ROOT, "tsconfig.base.json"),
  24. skipAddingFilesFromTsConfig: true,
  25. skipFileDependencyResolution: false,
  26. });
  27. const globs = scope
  28. ? [
  29. `${scope.replace(/\/$/, "")}/**/*.{ts,tsx,mts,cts}`,
  30. ...EXCLUDE_GLOBS,
  31. ]
  32. : DEFAULT_GLOBS;
  33. const added = project.addSourceFilesAtPaths(globs);
  34. return { project, addedCount: added.length };
  35. }
  36. function resolveSourceFile(project, filePath) {
  37. const absolute = path.resolve(ROOT, filePath);
  38. const sourceFile = project.getSourceFile(absolute);
  39. if (!sourceFile) {
  40. throw new Error(`源文件未加载到 project: ${filePath}\n - 确认路径是否正确\n - 如使用了 --scope,检查文件是否在范围内`);
  41. }
  42. return sourceFile;
  43. }
  44. function kindLabel(declaration) {
  45. const kind = declaration.getKindName();
  46. switch (kind) {
  47. case "FunctionDeclaration": return "function";
  48. case "ClassDeclaration": return "class";
  49. case "InterfaceDeclaration": return "interface";
  50. case "TypeAliasDeclaration": return "type";
  51. case "EnumDeclaration": return "enum";
  52. case "VariableDeclaration": return "const";
  53. default: return kind.replace(/Declaration$/, "").toLowerCase();
  54. }
  55. }
  56. function listExports(project, filePath) {
  57. const sourceFile = resolveSourceFile(project, filePath);
  58. const map = sourceFile.getExportedDeclarations();
  59. const rows = [];
  60. for (const [name, declarations] of map) {
  61. for (const decl of declarations) {
  62. rows.push({
  63. name,
  64. kind: kindLabel(decl),
  65. line: decl.getStartLineNumber(),
  66. });
  67. }
  68. }
  69. rows.sort((a, b) => a.line - b.line);
  70. return { file: filePath, exports: rows };
  71. }
  72. function printListExports(result) {
  73. console.log(result.file);
  74. console.log("");
  75. console.log(`Exports (${result.exports.length}):`);
  76. if (result.exports.length === 0) {
  77. console.log(" (none)");
  78. return;
  79. }
  80. const nameWidth = Math.max(...result.exports.map((r) => r.name.length));
  81. const kindWidth = Math.max(...result.exports.map((r) => r.kind.length));
  82. for (const row of result.exports) {
  83. console.log(
  84. ` ${row.name.padEnd(nameWidth)} ${row.kind.padEnd(kindWidth)} line ${row.line}`,
  85. );
  86. }
  87. }
  88. function parseTarget(target) {
  89. const idx = target.lastIndexOf(":");
  90. const filePath = target.slice(0, idx);
  91. const exportName = target.slice(idx + 1);
  92. if (!filePath || !exportName) {
  93. throw new Error(`目标格式错误: ${target}(需 <file>:<exportName>)`);
  94. }
  95. return { filePath, exportName };
  96. }
  97. function toRelative(absolutePath) {
  98. return path.relative(ROOT, absolutePath);
  99. }
  100. function snippetForNode(node) {
  101. const text = node.getSourceFile().getFullText();
  102. const start = node.getStart();
  103. const lineStart = text.lastIndexOf("\n", start - 1) + 1;
  104. let lineEnd = text.indexOf("\n", start);
  105. if (lineEnd === -1) lineEnd = text.length;
  106. return text.slice(lineStart, lineEnd).trim();
  107. }
  108. function isReExportReference(node) {
  109. let current = node.getParent();
  110. while (current) {
  111. const kind = current.getKindName();
  112. if (kind === "ExportSpecifier" || kind === "ExportDeclaration") {
  113. return true;
  114. }
  115. if (kind === "SourceFile") return false;
  116. current = current.getParent();
  117. }
  118. return false;
  119. }
  120. function findReferencesForExport(project, filePath, exportName) {
  121. const sourceFile = resolveSourceFile(project, filePath);
  122. const declarationsMap = sourceFile.getExportedDeclarations();
  123. const declarations = declarationsMap.get(exportName);
  124. if (!declarations || declarations.length === 0) {
  125. const available = [...declarationsMap.keys()].slice(0, 20).join(", ");
  126. throw new Error(
  127. `${filePath} 没有名为 "${exportName}" 的 export\n 可用 export(前 20 个): ${available || "(无)"}`,
  128. );
  129. }
  130. const symbol = {
  131. name: exportName,
  132. kind: kindLabel(declarations[0]),
  133. file: filePath,
  134. line: declarations[0].getStartLineNumber(),
  135. };
  136. const declLocations = new Set(
  137. declarations.map((d) => `${d.getSourceFile().getFilePath()}:${d.getStartLineNumber()}`),
  138. );
  139. const refs = [];
  140. const reExportsTmp = [];
  141. for (const decl of declarations) {
  142. const nameNode = typeof decl.getNameNode === "function" ? decl.getNameNode() : null;
  143. const target = nameNode ?? decl;
  144. const refSymbols = target.findReferences();
  145. for (const refSymbol of refSymbols) {
  146. for (const ref of refSymbol.getReferences()) {
  147. const node = ref.getNode();
  148. const refSourceFile = node.getSourceFile();
  149. const line = node.getStartLineNumber();
  150. const { column } = refSourceFile.getLineAndColumnAtPos(node.getStart());
  151. const col = column;
  152. const filePathAbs = refSourceFile.getFilePath();
  153. const locationKey = `${filePathAbs}:${line}`;
  154. if (declLocations.has(locationKey)) continue;
  155. const entry = {
  156. file: toRelative(filePathAbs),
  157. line,
  158. col,
  159. snippet: snippetForNode(node),
  160. };
  161. if (isReExportReference(node)) {
  162. reExportsTmp.push(entry);
  163. } else {
  164. refs.push(entry);
  165. }
  166. }
  167. }
  168. }
  169. const seen = new Set();
  170. const unique = [];
  171. for (const ref of refs) {
  172. const key = `${ref.file}:${ref.line}:${ref.col}`;
  173. if (seen.has(key)) continue;
  174. seen.add(key);
  175. unique.push(ref);
  176. }
  177. unique.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file.localeCompare(b.file)));
  178. const reExportSeen = new Set();
  179. const reExportsUnique = [];
  180. for (const ref of reExportsTmp) {
  181. const key = `${ref.file}:${ref.line}:${ref.col}`;
  182. if (reExportSeen.has(key)) continue;
  183. reExportSeen.add(key);
  184. reExportsUnique.push(ref);
  185. }
  186. reExportsUnique.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file.localeCompare(b.file)));
  187. return {
  188. symbol,
  189. references: unique,
  190. reExports: reExportsUnique,
  191. notes: ["Static analysis only. Dynamic import() and string-based usage not detected."],
  192. };
  193. }
  194. function truncateSnippet(s, max = 120) {
  195. if (s.length <= max) return s;
  196. return s.slice(0, max - 1) + "…";
  197. }
  198. function printRefs(result) {
  199. const { symbol, references, reExports } = result;
  200. console.log(`${symbol.name} (${symbol.kind}, exported at ${symbol.file}:${symbol.line})`);
  201. console.log("");
  202. console.log(`References (${references.length}):`);
  203. if (references.length === 0 && reExports.length === 0) {
  204. console.log(" Safe to delete (no static references and no re-exports).");
  205. } else if (references.length === 0) {
  206. console.log(" (none — only re-exported)");
  207. } else {
  208. for (const ref of references) {
  209. console.log(` ${ref.file}:${ref.line}:${ref.col}`);
  210. console.log(` > ${truncateSnippet(ref.snippet)}`);
  211. }
  212. }
  213. if (reExports.length > 0) {
  214. console.log("");
  215. console.log(`Re-exports (${reExports.length}):`);
  216. for (const ref of reExports) {
  217. console.log(` ${ref.file}:${ref.line}`);
  218. console.log(` > ${truncateSnippet(ref.snippet)}`);
  219. }
  220. }
  221. console.log("");
  222. for (const note of result.notes) {
  223. console.log(`Note: ${note}`);
  224. }
  225. }
  226. function printHelp() {
  227. console.log(`查询 TypeScript export 的所有引用位置(symbol 级),用于大型重构时安全删代码。
  228. 用法:
  229. pnpm dep:refs <file>:<exportName> 查 export 的所有引用
  230. pnpm dep:refs --list-exports <file> 列出文件的所有 export
  231. pnpm dep:refs <file>:<exportName> --json JSON 输出
  232. pnpm dep:refs --scope <glob> <file>:<sym> 缩小扫描范围加速
  233. 选项:
  234. --list-exports 切换到 list-exports 模式
  235. --json 以 JSON 输出
  236. --scope <glob> 只加载匹配 glob 的源文件(默认加载所有 workspace 源码 + test)
  237. -h, --help 查看帮助
  238. 示例:
  239. pnpm dep:refs packages/services/src/bots/botsService.ts:createBotSession
  240. pnpm dep:refs --list-exports packages/services/src/bots/botsService.ts
  241. 推荐用法:
  242. 1. 先跑 pnpm knip 拿到 unused exports 列表(瞬秒)
  243. 2. 对存疑的 export 用 pnpm dep:refs file:name 看具体引用者
  244. 3. 决定能删 / 要先改调用方
  245. 说明:
  246. - 仅静态分析,不检测 dynamic import() 和字符串路径引用
  247. - 首次启动约 10-30 秒(加载全 workspace);用 --scope 可显著加速
  248. - JSON 管道用 pnpm -s dep:refs ... --json | jq .(pnpm 默认会在 stdout 多打 2 行 banner)
  249. `);
  250. }
  251. function parseArgs(argv) {
  252. const options = {
  253. target: null, // "file:name" for refs query, "file" for list-exports
  254. mode: "refs", // "refs" | "list-exports"
  255. json: false,
  256. scope: null, // glob string, null = default
  257. };
  258. for (let i = 0; i < argv.length; i += 1) {
  259. const arg = argv[i];
  260. if (arg === "-h" || arg === "--help") {
  261. printHelp();
  262. process.exit(0);
  263. }
  264. if (arg === "--json") {
  265. options.json = true;
  266. continue;
  267. }
  268. if (arg === "--list-exports") {
  269. options.mode = "list-exports";
  270. continue;
  271. }
  272. if (arg === "--scope") {
  273. options.scope = argv[i + 1];
  274. i += 1;
  275. if (!options.scope) {
  276. throw new Error("--scope 需要一个 glob 参数");
  277. }
  278. continue;
  279. }
  280. if (arg === "--") {
  281. continue;
  282. }
  283. if (options.target !== null) {
  284. throw new Error(`只能传一个目标参数,已收到 ${options.target},又收到 ${arg}`);
  285. }
  286. options.target = arg;
  287. }
  288. if (options.target === null) {
  289. throw new Error("缺少目标参数。用法: pnpm dep:refs <file>:<exportName> 或 pnpm dep:refs --list-exports <file>");
  290. }
  291. if (options.mode === "refs" && !options.target.includes(":")) {
  292. throw new Error(`refs 模式需要 <file>:<exportName> 格式,收到: ${options.target}`);
  293. }
  294. return options;
  295. }
  296. function main(argv) {
  297. if (argv.length === 0 || argv.includes("-h") || argv.includes("--help")) {
  298. printHelp();
  299. process.exit(0);
  300. }
  301. let options;
  302. try {
  303. options = parseArgs(argv);
  304. } catch (error) {
  305. console.error(`错误: ${error.message}`);
  306. process.exit(1);
  307. }
  308. const { project, addedCount } = loadProject(options.scope);
  309. if (addedCount === 0) {
  310. console.error(`警告: scope 内未加载任何源文件 (scope: ${options.scope})`);
  311. }
  312. try {
  313. if (options.mode === "list-exports") {
  314. const result = listExports(project, options.target);
  315. if (options.json) {
  316. console.log(JSON.stringify(result, null, 2));
  317. } else {
  318. printListExports(result);
  319. }
  320. process.exit(0);
  321. }
  322. if (options.mode === "refs") {
  323. const { filePath, exportName } = parseTarget(options.target);
  324. const result = findReferencesForExport(project, filePath, exportName);
  325. if (options.json) {
  326. console.log(JSON.stringify(result, null, 2));
  327. } else {
  328. printRefs(result);
  329. }
  330. process.exit(0);
  331. }
  332. } catch (error) {
  333. console.error(`错误: ${error.message}`);
  334. process.exit(1);
  335. }
  336. }
  337. main(process.argv.slice(2));