import ts from "typescript"; import type { CollectedExport, CollectedMember } from "./exportCollector"; import { normalizePath } from "./project"; import { classifyReference, isDeclarationName } from "./referenceClassifier"; import type { ReferenceKind, ReferenceRecord, SourceLocation } from "./types"; interface SymbolTarget { exportItem?: CollectedExport; memberItem?: CollectedMember; } export interface ReferenceCollectionContext { languageService: ts.LanguageService; locationCache: Map>; nodeCache: Map>; } export function createReferenceCollectionContext(program: ts.Program): ReferenceCollectionContext { return { languageService: createLanguageService(program), locationCache: new Map(), nodeCache: new Map(), }; } export interface ReferenceCollectionOptions { countOnly?: boolean; includeImports?: boolean; } export function collectReferences( program: ts.Program, checker: ts.TypeChecker, targetFilePath: string, exports: CollectedExport[], context = createReferenceCollectionContext(program), options: ReferenceCollectionOptions = {}, ): void { const includeImports = options.includeImports ?? true; const symbolTargets = new Map(); for (const exportItem of exports) { for (const symbol of exportItem.symbols) { addSymbolTarget(symbolTargets, symbol, { exportItem }); } for (const memberItem of exportItem.members) { for (const symbol of memberItem.symbols) { addSymbolTarget(symbolTargets, symbol, { memberItem }); } } } const seen = new Set(); for (const [symbol, targets] of symbolTargets) { for (const declaration of symbol.declarations ?? []) { const nameNode = getDeclarationNameNode(declaration); if (!nameNode) { continue; } const sourceFile = declaration.getSourceFile(); const references = context.languageService.findReferences(sourceFile.fileName, nameNode.getStart(sourceFile)) ?? []; for (const referencedSymbol of references) { for (const reference of referencedSymbol.references) { recordReference( reference, program, targets, targetFilePath, seen, context, { countOnly: options.countOnly, includeImports }, ); } } } } } function recordReference( reference: ts.ReferencedSymbolEntry, program: ts.Program, targets: SymbolTarget[], targetFilePath: string, seen: Set, context: ReferenceCollectionContext, options: Required> & Pick, ): void { if (reference.isDefinition) { return; } const sourceFile = program.getSourceFile(reference.fileName); if (!sourceFile || sourceFile.isDeclarationFile) { return; } const isInternal = normalizePath(sourceFile.fileName) === targetFilePath; if (options.countOnly && options.includeImports) { for (const target of targets) { const key = [ target.exportItem?.summary.exportName ?? "", target.memberItem?.summary.name ?? "", normalizePath(reference.fileName), reference.textSpan.start, ].join("\0"); if (seen.has(key)) { continue; } seen.add(key); if (target.exportItem) { addReferenceCount(target.exportItem.summary, isInternal); } if (target.memberItem) { addReferenceCount(target.memberItem.summary, isInternal); } } return; } const node = getCachedNodeAtPosition(context, sourceFile, reference.textSpan.start); if (!node) { return; } const kind = classifyReference(node); if (!options.includeImports && kind === "import") { return; } if (isInternal && isDeclarationName(node) && kind !== "import" && kind !== "re-export") { return; } const location = getCachedLocation(context, reference.textSpan.start, sourceFile); for (const target of targets) { const key = [ target.exportItem?.summary.exportName ?? "", target.memberItem?.summary.name ?? "", location.filePath, location.line, location.column, kind, ].join("\0"); if (seen.has(key)) { continue; } seen.add(key); if (target.exportItem) { addReference(target.exportItem.summary, kind, location, isInternal, options.countOnly); } if (target.memberItem) { addReference(target.memberItem.summary, kind, location, isInternal, options.countOnly); } } } function addReferenceCount( target: CollectedExport["summary"] | CollectedMember["summary"], isInternal: boolean, ): void { if (isInternal) { target.internalReferenceCount = (target.internalReferenceCount ?? 0) + 1; } else { target.externalReferenceCount = (target.externalReferenceCount ?? 0) + 1; } } function addReference( target: CollectedExport["summary"] | CollectedMember["summary"], kind: ReferenceKind, location: SourceLocation, isInternal: boolean, countOnly: boolean | undefined, ): void { if (isInternal) { target.internalReferenceCount = (target.internalReferenceCount ?? 0) + 1; } else { target.externalReferenceCount = (target.externalReferenceCount ?? 0) + 1; } if (countOnly) { return; } target.references.push({ kind, location, isInternal, }); } function addSymbolTarget( symbolTargets: Map, symbol: ts.Symbol, target: SymbolTarget, ): void { const existing = symbolTargets.get(symbol); if (existing) { existing.push(target); return; } symbolTargets.set(symbol, [target]); } function getLocation(positionIndex: number, sourceFile: ts.SourceFile): SourceLocation { const position = sourceFile.getLineAndCharacterOfPosition(positionIndex); return { filePath: normalizePath(sourceFile.fileName), line: position.line + 1, column: position.character + 1, }; } function getCachedLocation( context: ReferenceCollectionContext, positionIndex: number, sourceFile: ts.SourceFile, ): SourceLocation { const filePath = normalizePath(sourceFile.fileName); let fileCache = context.locationCache.get(filePath); if (!fileCache) { fileCache = new Map(); context.locationCache.set(filePath, fileCache); } let location = fileCache.get(positionIndex); if (!location) { location = getLocation(positionIndex, sourceFile); fileCache.set(positionIndex, location); } return location; } function getCachedNodeAtPosition( context: ReferenceCollectionContext, sourceFile: ts.SourceFile, position: number, ): ts.Node | undefined { const filePath = normalizePath(sourceFile.fileName); let fileCache = context.nodeCache.get(filePath); if (!fileCache) { fileCache = new Map(); context.nodeCache.set(filePath, fileCache); } if (!fileCache.has(position)) { fileCache.set(position, findNodeAtPosition(sourceFile, position)); } return fileCache.get(position); } function createLanguageService(program: ts.Program): ts.LanguageService { const sourceFiles = new Map( program .getSourceFiles() .filter((sourceFile) => !sourceFile.isDeclarationFile) .map((sourceFile) => [normalizePath(sourceFile.fileName), sourceFile.text]), ); const compilerOptions = program.getCompilerOptions(); return ts.createLanguageService({ getScriptFileNames: () => [...sourceFiles.keys()], getScriptVersion: () => "0", getScriptSnapshot: (fileName) => { const text = sourceFiles.get(normalizePath(fileName)) ?? ts.sys.readFile(fileName); return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text); }, getCurrentDirectory: () => process.cwd(), getCompilationSettings: () => compilerOptions, getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options), fileExists: ts.sys.fileExists, readFile: ts.sys.readFile, readDirectory: ts.sys.readDirectory, }); } function getDeclarationNameNode(declaration: ts.Declaration): ts.Node | undefined { if ( (ts.isFunctionDeclaration(declaration) || ts.isClassDeclaration(declaration) || ts.isInterfaceDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration) || ts.isEnumDeclaration(declaration) || ts.isModuleDeclaration(declaration) || ts.isMethodDeclaration(declaration) || ts.isMethodSignature(declaration) || ts.isPropertyDeclaration(declaration) || ts.isPropertySignature(declaration) || ts.isGetAccessorDeclaration(declaration) || ts.isSetAccessorDeclaration(declaration)) && declaration.name ) { return declaration.name; } if (ts.isVariableDeclaration(declaration)) { return declaration.name; } if (ts.isExportSpecifier(declaration)) { return declaration.name; } if (ts.isImportSpecifier(declaration)) { return declaration.name; } if (ts.isImportClause(declaration) && declaration.name) { return declaration.name; } return undefined; } function findNodeAtPosition(sourceFile: ts.SourceFile, position: number): ts.Node | undefined { let best: ts.Node | undefined; function visit(node: ts.Node): void { const start = node.getStart(sourceFile); const end = node.getEnd(); if (position < start || position >= end) { return; } if (!best || node.getWidth(sourceFile) <= best.getWidth(sourceFile)) { best = node; } ts.forEachChild(node, visit); } visit(sourceFile); return best; } export function sortReferences(references: ReferenceRecord[]): ReferenceRecord[] { return references.sort((left, right) => { const file = left.location.filePath.localeCompare(right.location.filePath); if (file !== 0) return file; const line = left.location.line - right.location.line; if (line !== 0) return line; const column = left.location.column - right.location.column; if (column !== 0) return column; return referenceKindOrder(left.kind) - referenceKindOrder(right.kind); }); } function referenceKindOrder(kind: ReferenceKind): number { const order: ReferenceKind[] = [ "import", "re-export", "construct", "call", "write", "read", "type", "jsx", "unknown", ]; return order.indexOf(kind); }