Skip to content

Commit d248684

Browse files
committed
Decide a ReferenceType's package name by looking for a package.json.
1 parent 5687934 commit d248684

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

src/lib/models/types.ts

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import * as fs from "fs";
2+
import * as path from "path";
3+
14
import type * as ts from "typescript";
25
import type { Context } from "../converter";
36
import { Reflection } from "./reflections/abstract";
@@ -847,18 +850,28 @@ export class ReferenceType extends Type {
847850
.fileName.replace(/\\/g, "/");
848851
if (!symbolPath) return ref;
849852

850-
let startIndex = symbolPath.indexOf("node_modules/");
851-
if (startIndex === -1) return ref;
852-
startIndex += "node_modules/".length;
853-
let stopIndex = symbolPath.indexOf("/", startIndex);
854-
// Scoped package, e.g. `@types/node`
855-
if (symbolPath[startIndex] === "@") {
856-
stopIndex = symbolPath.indexOf("/", stopIndex + 1);
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+
}
871+
}
857872
}
858873

859-
const packageName = symbolPath.substring(startIndex, stopIndex);
860-
ref.package = packageName;
861-
874+
ref.package = findPackageForPath(symbolPath);
862875
return ref;
863876
}
864877

0 commit comments

Comments
 (0)