@@ -850,27 +850,21 @@ export class ReferenceType extends Type {
850
850
. fileName . replace ( / \\ / g, "/" ) ;
851
851
if ( ! symbolPath ) return ref ;
852
852
853
- function findPackageForPath ( sourcePath : string ) : string | undefined {
854
- let basePath = sourcePath ;
855
- for ( ; ; ) {
856
- const nextPath = path . dirname ( basePath ) ;
857
- if ( nextPath === basePath ) {
858
- return ;
859
- }
860
- basePath = nextPath ;
861
- const projectPath = path . join ( basePath , "package.json" ) ;
862
- try {
863
- const packageJsonData = fs . readFileSync ( projectPath , {
864
- encoding : "utf8" ,
865
- } ) ;
866
- const packageJson = JSON . parse ( packageJsonData ) ;
867
- return packageJson . name ;
868
- } catch ( err ) {
869
- continue ;
870
- }
853
+ // Attempt to decide package name from path if it contains "node_modules"
854
+ let startIndex = symbolPath . lastIndexOf ( "node_modules/" ) ;
855
+ if ( startIndex !== - 1 ) {
856
+ startIndex += "node_modules/" . length ;
857
+ let stopIndex = symbolPath . indexOf ( "/" , startIndex ) ;
858
+ // Scoped package, e.g. `@types/node`
859
+ if ( symbolPath [ startIndex ] === "@" ) {
860
+ stopIndex = symbolPath . indexOf ( "/" , stopIndex + 1 ) ;
871
861
}
862
+ const packageName = symbolPath . substring ( startIndex , stopIndex ) ;
863
+ ref . package = packageName ;
864
+ return ref ;
872
865
}
873
866
867
+ // Otherwise, look for a "package.json" file in a parent path
874
868
ref . package = findPackageForPath ( symbolPath ) ;
875
869
return ref ;
876
870
}
@@ -1300,3 +1294,32 @@ export class UnknownType extends Type {
1300
1294
} ;
1301
1295
}
1302
1296
}
1297
+
1298
+ const packageJsonLookupCache : Record < string , string > = { } ;
1299
+
1300
+ function findPackageForPath ( sourcePath : string ) : string | undefined {
1301
+ if ( packageJsonLookupCache [ sourcePath ] !== undefined ) {
1302
+ return packageJsonLookupCache [ sourcePath ] ;
1303
+ }
1304
+ let basePath = sourcePath ;
1305
+ for ( ; ; ) {
1306
+ const nextPath = path . dirname ( basePath ) ;
1307
+ if ( nextPath === basePath ) {
1308
+ return ;
1309
+ }
1310
+ basePath = nextPath ;
1311
+ const projectPath = path . join ( basePath , "package.json" ) ;
1312
+ try {
1313
+ const packageJsonData = fs . readFileSync ( projectPath , {
1314
+ encoding : "utf8" ,
1315
+ } ) ;
1316
+ const packageJson = JSON . parse ( packageJsonData ) ;
1317
+ if ( packageJson . name !== undefined ) {
1318
+ packageJsonLookupCache [ sourcePath ] = packageJson . name ;
1319
+ }
1320
+ return packageJson . name ;
1321
+ } catch ( err ) {
1322
+ continue ;
1323
+ }
1324
+ }
1325
+ }
0 commit comments