Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decide a ReferenceType's package name by looking for a package.json file #2017

Merged
merged 2 commits into from Apr 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
56 changes: 46 additions & 10 deletions src/lib/models/types.ts
@@ -1,3 +1,6 @@
import * as fs from "fs";
import * as path from "path";

import type * as ts from "typescript";
import type { Context } from "../converter";
import { Reflection } from "./reflections/abstract";
Expand Down Expand Up @@ -847,18 +850,22 @@ export class ReferenceType extends Type {
.fileName.replace(/\\/g, "/");
if (!symbolPath) return ref;

let startIndex = symbolPath.indexOf("node_modules/");
if (startIndex === -1) return ref;
startIndex += "node_modules/".length;
let stopIndex = symbolPath.indexOf("/", startIndex);
// Scoped package, e.g. `@types/node`
if (symbolPath[startIndex] === "@") {
stopIndex = symbolPath.indexOf("/", stopIndex + 1);
// Attempt to decide package name from path if it contains "node_modules"
let startIndex = symbolPath.lastIndexOf("node_modules/");
if (startIndex !== -1) {
startIndex += "node_modules/".length;
let stopIndex = symbolPath.indexOf("/", startIndex);
// Scoped package, e.g. `@types/node`
if (symbolPath[startIndex] === "@") {
stopIndex = symbolPath.indexOf("/", stopIndex + 1);
}
const packageName = symbolPath.substring(startIndex, stopIndex);
ref.package = packageName;
return ref;
}

const packageName = symbolPath.substring(startIndex, stopIndex);
ref.package = packageName;

// Otherwise, look for a "package.json" file in a parent path
ref.package = findPackageForPath(symbolPath);
return ref;
}

Expand Down Expand Up @@ -1287,3 +1294,32 @@ export class UnknownType extends Type {
};
}
}

const packageJsonLookupCache: Record<string, string> = {};

function findPackageForPath(sourcePath: string): string | undefined {
if (packageJsonLookupCache[sourcePath] !== undefined) {
return packageJsonLookupCache[sourcePath];
}
let basePath = sourcePath;
for (;;) {
const nextPath = path.dirname(basePath);
if (nextPath === basePath) {
return;
}
basePath = nextPath;
const projectPath = path.join(basePath, "package.json");
try {
const packageJsonData = fs.readFileSync(projectPath, {
encoding: "utf8",
});
const packageJson = JSON.parse(packageJsonData);
if (packageJson.name !== undefined) {
packageJsonLookupCache[sourcePath] = packageJson.name;
}
return packageJson.name;
} catch (err) {
continue;
}
}
}