import ts from "typescript"; import type { CollectedExport } from "./exportCollector"; import { normalizePath } from "./project"; export function collectImportReferences( program: ts.Program, checker: ts.TypeChecker, targetFilePath: string, exports: CollectedExport[], ): void { const exportByName = new Map(exports.map((item) => [item.summary.exportName, item])); const defaultExport = exportByName.get("default"); for (const sourceFile of program.getSourceFiles()) { if (sourceFile.isDeclarationFile || normalizePath(sourceFile.fileName) === targetFilePath) { continue; } for (const statement of sourceFile.statements) { if (ts.isImportDeclaration(statement)) { collectImportDeclaration(statement, checker, targetFilePath, exportByName, defaultExport); } else if (ts.isExportDeclaration(statement)) { collectExportDeclaration(statement, checker, targetFilePath, exports, exportByName); } } } } function collectImportDeclaration( statement: ts.ImportDeclaration, checker: ts.TypeChecker, targetFilePath: string, exportByName: Map, defaultExport: CollectedExport | undefined, ): void { if (!moduleSpecifierTargetsFile(statement.moduleSpecifier, checker, targetFilePath)) { return; } if (statement.importClause?.name && defaultExport) { incrementExternal(defaultExport); } const namedBindings = statement.importClause?.namedBindings; if (!namedBindings) { return; } if (ts.isNamespaceImport(namedBindings)) { for (const item of exportByName.values()) { incrementExternal(item); } return; } for (const specifier of namedBindings.elements) { const exportName = (specifier.propertyName ?? specifier.name).text; const item = exportByName.get(exportName); if (item) { incrementExternal(item); } } } function collectExportDeclaration( statement: ts.ExportDeclaration, checker: ts.TypeChecker, targetFilePath: string, exports: CollectedExport[], exportByName: Map, ): void { if ( !statement.moduleSpecifier || !moduleSpecifierTargetsFile(statement.moduleSpecifier, checker, targetFilePath) ) { return; } if (!statement.exportClause) { for (const item of exports) { incrementExternal(item); } return; } if (!ts.isNamedExports(statement.exportClause)) { return; } for (const specifier of statement.exportClause.elements) { const exportName = (specifier.propertyName ?? specifier.name).text; const item = exportByName.get(exportName); if (item) { incrementExternal(item); } } } function moduleSpecifierTargetsFile( moduleSpecifier: ts.Expression, checker: ts.TypeChecker, targetFilePath: string, ): boolean { if (!ts.isStringLiteralLike(moduleSpecifier)) { return false; } const symbol = checker.getSymbolAtLocation(moduleSpecifier); return (symbol?.declarations ?? []).some( (declaration) => normalizePath(declaration.getSourceFile().fileName) === targetFilePath, ); } function incrementExternal(item: CollectedExport): void { item.summary.externalReferenceCount = (item.summary.externalReferenceCount ?? 0) + 1; }