Skip to content

Commit 65dfba3

Browse files
committed
Try looking for a node_modules path first, and cache expensive lookups.
1 parent d248684 commit 65dfba3

File tree

1 file changed

+41
-18
lines changed

1 file changed

+41
-18
lines changed

src/lib/models/types.ts

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -850,27 +850,21 @@ export class ReferenceType extends Type {
850850
.fileName.replace(/\\/g, "/");
851851
if (!symbolPath) return ref;
852852

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);
871861
}
862+
const packageName = symbolPath.substring(startIndex, stopIndex);
863+
ref.package = packageName;
864+
return ref;
872865
}
873866

867+
// Otherwise, look for a "package.json" file in a parent path
874868
ref.package = findPackageForPath(symbolPath);
875869
return ref;
876870
}
@@ -1300,3 +1294,32 @@ export class UnknownType extends Type {
13001294
};
13011295
}
13021296
}
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

Comments
 (0)