dep-refs.mjs 11 KB

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