Something went wrong. Try again.
tsref is a Bun CLI for finding references to exported TypeScript APIs.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import { existsSync } from "node:fs";import path from "node:path";import ts from "typescript";
export interface LoadedProject { program: ts.Program; checker: ts.TypeChecker; targetFile: ts.SourceFile; targetFilePath: string; projectFilePath: string; diagnostics: () => string[];}
export function normalizePath(filePath: string): string { return path.resolve(filePath).replaceAll(path.sep, "/");}
export function loadProject(targetFileInput: string, projectInput?: string): LoadedProject { const targetFilePath = normalizePath(targetFileInput);
if (!existsSync(targetFilePath)) { throw new Error(`Target file not found: ${targetFileInput}`); }
const projectFilePath = resolveProjectFile(projectInput); const config = ts.readConfigFile(projectFilePath, ts.sys.readFile);
if (config.error) { throw new Error(formatDiagnostic(config.error)); }
const parsed = ts.parseJsonConfigFileContent( config.config, ts.sys, path.dirname(projectFilePath), undefined, projectFilePath, );
if (parsed.errors.length > 0) { throw new Error(parsed.errors.map(formatDiagnostic).join("\n")); }
const program = ts.createProgram({ rootNames: parsed.fileNames, options: parsed.options, }); const checker = program.getTypeChecker(); const targetFile = program .getSourceFiles() .find((sourceFile) => normalizePath(sourceFile.fileName) === targetFilePath);
if (!targetFile) { throw new Error( `Target file is not included by ${projectFilePath}: ${targetFileInput}`, ); }
let diagnosticsCache: string[] | undefined;
return { program, checker, targetFile, targetFilePath, projectFilePath, diagnostics: () => { diagnosticsCache ??= ts .getPreEmitDiagnostics(program) .map(formatDiagnostic) .filter(Boolean);
return diagnosticsCache; }, };}
function resolveProjectFile(projectInput?: string): string { if (projectInput) { const projectFilePath = normalizePath(projectInput);
if (!existsSync(projectFilePath)) { throw new Error(`tsconfig.json not found: ${projectInput}`); }
return projectFilePath; }
const found = ts.findConfigFile(process.cwd(), ts.sys.fileExists, "tsconfig.json");
if (!found) { throw new Error("tsconfig.json not found from current directory"); }
return normalizePath(found);}
function formatDiagnostic(diagnostic: ts.Diagnostic): string { return ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");}