Open History to see the last commit
1#!/usr/bin/env node
2β
3import { existsSync, readFileSync } from 'node:fs'
4import { dirname, relative, resolve } from 'node:path'
5import ts from 'typescript'
6β
7const usage = `Usage:
8 pnpm ts:symbol-references -- --project <tsconfig> --file <file> --symbol <name> [--line <line> --column <column>]
9β
10Example:
11 pnpm ts:symbol-references -- --project packages/router-core/tsconfig.json --file packages/router-core/src/utils.ts --symbol last
12`
13β
14const args = parseArgs(process.argv.slice(2))
15β
16if (args.help) {
17 console.log(usage)
18 process.exit(0)
19}
20β
21if (!args.project || !args.file || !args.symbol) {
22 fail(usage)
23}
24β
25const cwd = process.cwd()
26const projectPath = resolve(cwd, args.project)
27const targetFile = resolve(cwd, args.file)
28β
29if (!existsSync(projectPath)) {
30 fail(`Project not found: ${args.project}`)
31}
32β
33if (!existsSync(targetFile)) {
34 fail(`File not found: ${args.file}`)
35}
36β
37const configFile = ts.readConfigFile(projectPath, ts.sys.readFile)
38if (configFile.error) {
39 fail(formatDiagnostics([configFile.error]))
40}
41β
42const parsedConfig = ts.parseJsonConfigFileContent(
43 configFile.config,
44 ts.sys,
45 dirname(projectPath),
46 undefined,
47 projectPath,
48)
49β
50if (parsedConfig.errors.length) {
51 fail(formatDiagnostics(parsedConfig.errors))
52}
53β
54const fileNames = Array.from(new Set([...parsedConfig.fileNames, targetFile]))
55const fileTextCache = new Map()
56const service = ts.createLanguageService({
57 getCompilationSettings: () => parsedConfig.options,
58 getCurrentDirectory: () => dirname(projectPath),
59 getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
60 getDirectories: ts.sys.getDirectories,
61 getNewLine: () => ts.sys.newLine,
62 getScriptFileNames: () => fileNames,
63 getScriptSnapshot(fileName) {
64 const text = getFileText(fileName)
65 return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text)
66 },
67 getScriptVersion: () => '0',
68 readDirectory: ts.sys.readDirectory,
69 readFile: ts.sys.readFile,
70 fileExists: ts.sys.fileExists,
71 directoryExists: ts.sys.directoryExists,
72 useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
73 realpath: ts.sys.realpath,
74})
75β
76const program = service.getProgram()
77const sourceFile = program
78 ?.getSourceFiles()
79 .find((source) => resolve(source.fileName) === targetFile)
80β
81if (!sourceFile) {
82 fail(`File is not in the TypeScript program: ${args.file}`)
83}
84β
85const symbolNode = findSymbolNode(
86 sourceFile,
87 args.symbol,
88 args.line,
89 args.column,
90)
91const refs = service.findReferences(
92 sourceFile.fileName,
93 symbolNode.getStart(sourceFile),
94)
95β
96if (!refs?.length) {
97 fail(`No references found for ${args.symbol}`)
98}
99β
100const rows = dedupeReferences(refs)
101console.log(
102 `Found ${rows.length} references for ${args.symbol} at ${formatLocation(sourceFile, symbolNode.getStart(sourceFile))}`,
103)
104β
105for (const row of rows) {
106 const source = program?.getSourceFile(row.fileName)
107 if (!source) continue
108β
109 const location = formatLocation(source, row.textSpan.start)
110 const line = getLineText(row.fileName, source, row.textSpan.start)
111 const marker = row.isDefinition ? ' [definition]' : ''
112 console.log(`${location}${marker} ${line}`)
113}
114β
115function parseArgs(rawArgs) {
116 const parsed = {}
117 for (let index = 0; index < rawArgs.length; index++) {
118 const arg = rawArgs[index]
119β
120 if (arg === '--') {
121 continue
122 }
123β
124 if (arg === '--help' || arg === '-h') {
125 parsed.help = true
126 continue
127 }
128β
129 if (!arg.startsWith('--')) {
130 fail(`Unexpected argument: ${arg}\n\n${usage}`)
131 }
132β
133 const key = arg.slice(2)
134 const value = rawArgs[index + 1]
135 if (!value || value.startsWith('--')) {
136 fail(`Missing value for --${key}\n\n${usage}`)
137 }
138β
139 parsed[key] = value
140 index++
141 }
142β
143 return parsed
144}
145β
146function findSymbolNode(sourceFile, symbol, line, column) {
147 if (line !== undefined || column !== undefined) {
148 if (line === undefined || column === undefined) {
149 fail('Pass both --line and --column, or neither.')
150 }
151β
152 const lineNumber = Number(line)
153 const columnNumber = Number(column)
154 if (!Number.isInteger(lineNumber) || !Number.isInteger(columnNumber)) {
155 fail('--line and --column must be integers.')
156 }
157β
158 const position = sourceFile.getPositionOfLineAndCharacter(
159 lineNumber - 1,
160 columnNumber - 1,
161 )
162 const node = findIdentifierAtPosition(sourceFile, position)
163 if (!node) {
164 fail(`No identifier at ${line}:${column}`)
165 }
166β
167 if (node.text !== symbol) {
168 fail(`Identifier at ${line}:${column} is ${node.text}, not ${symbol}`)
169 }
170β
171 return node
172 }
173β
174 const candidates = []
175 visitIdentifiers(sourceFile, (node) => {
176 if (node.text === symbol) candidates.push(node)
177 })
178β
179 if (!candidates.length) {
180 fail(`Symbol not found in ${relative(cwd, sourceFile.fileName)}: ${symbol}`)
181 }
182β
183 const declarations = candidates.filter(isDeclarationName)
184 if (declarations.length === 1) {
185 return declarations[0]
186 }
187β
188 const options = (declarations.length ? declarations : candidates)
189 .map((node) => ` ${formatLocation(sourceFile, node.getStart(sourceFile))}`)
190 .join('\n')
191β
192 fail(`Symbol is ambiguous. Pass --line and --column for one of:\n${options}`)
193}
194β
195function visitIdentifiers(node, onIdentifier) {
196 if (ts.isIdentifier(node)) {
197 onIdentifier(node)
198 }
199 ts.forEachChild(node, (child) => visitIdentifiers(child, onIdentifier))
200}
201β
202function findIdentifierAtPosition(sourceFile, position) {
203 let match
204 visitIdentifiers(sourceFile, (node) => {
205 const start = node.getStart(sourceFile)
206 const end = node.getEnd()
207 if (start <= position && position <= end) {
208 match = node
209 }
210 })
211 return match
212}
213β
214function isDeclarationName(node) {
215 const parent = node.parent
216 if (!parent || parent.name !== node) return false
217β
218 return (
219 ts.isClassDeclaration(parent) ||
220 ts.isEnumDeclaration(parent) ||
221 ts.isFunctionDeclaration(parent) ||
222 ts.isGetAccessorDeclaration(parent) ||
223 ts.isInterfaceDeclaration(parent) ||
224 ts.isMethodDeclaration(parent) ||
225 ts.isModuleDeclaration(parent) ||
226 ts.isParameter(parent) ||
227 ts.isPropertyDeclaration(parent) ||
228 ts.isSetAccessorDeclaration(parent) ||
229 ts.isTypeAliasDeclaration(parent) ||
230 ts.isVariableDeclaration(parent)
231 )
232}
233β
234function dedupeReferences(refs) {
235 const seen = new Set()
236 const rows = []
237β
238 for (const group of refs) {
239 for (const reference of group.references) {
240 const key = `${resolve(reference.fileName)}:${reference.textSpan.start}:${reference.textSpan.length}`
241 if (seen.has(key)) continue
242β
243 seen.add(key)
244 rows.push(reference)
245 }
246 }
247β
248 rows.sort((left, right) => {
249 const fileCompare = relative(cwd, left.fileName).localeCompare(
250 relative(cwd, right.fileName),
251 )
252 return fileCompare || left.textSpan.start - right.textSpan.start
253 })
254β
255 return rows
256}
257β
258function getFileText(fileName) {
259 if (fileTextCache.has(fileName)) return fileTextCache.get(fileName)
260 if (!existsSync(fileName)) return undefined
261β
262 const text = readFileSync(fileName, 'utf8')
263 fileTextCache.set(fileName, text)
264 return text
265}
266β
267function getLineText(fileName, sourceFile, position) {
268 const { line } = sourceFile.getLineAndCharacterOfPosition(position)
269 return getFileText(fileName)?.split(/\r?\n/)[line]?.trim() ?? ''
270}
271β
272function formatLocation(sourceFile, position) {
273 const { line, character } = sourceFile.getLineAndCharacterOfPosition(position)
274 return `${relative(cwd, sourceFile.fileName)}:${line + 1}:${character + 1}`
275}
276β
277function formatDiagnostics(diagnostics) {
278 return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
279 getCanonicalFileName: (fileName) => fileName,
280 getCurrentDirectory: () => cwd,
281 getNewLine: () => ts.sys.newLine,
282 })
283}
284β
285function fail(message) {
286 console.error(message)
287 process.exit(1)
288}