Skip to content

Commit

Permalink
fix(type-utils): treat custom type roots as external (#6870)
Browse files Browse the repository at this point in the history
* fix(type-utils): use typescript's `isSourceFileFromExternalLibrary`

* style: fix linting issues

* Undo merge conflict-y change

---------

Co-authored-by: Josh Goldberg <git@joshuakgoldberg.com>
  • Loading branch information
RebeccaStevens and JoshuaKGoldberg committed Oct 17, 2023
1 parent 6398d3f commit b85f744
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
26 changes: 17 additions & 9 deletions packages/type-utils/src/TypeOrValueSpecifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,16 +155,20 @@ function typeDeclaredInFile(
function typeDeclaredInPackage(
packageName: string,
declarationFiles: ts.SourceFile[],
program: ts.Program,
): boolean {
// Handle scoped packages - if the name starts with @, remove it and replace / with __
const typesPackageName =
'@types/' + packageName.replace(/^@([^/]+)\//, '$1__');
const matcher = new RegExp(
`node_modules/(?:${packageName}|${typesPackageName})/`,
);
return declarationFiles.some(declaration =>
matcher.test(declaration.fileName),
);
const typesPackageName = packageName.replace(/^@([^/]+)\//, '$1__');

const matcher = new RegExp(`${packageName}|${typesPackageName}`);
return declarationFiles.some(declaration => {
const packageIdName = program.sourceFileToPackageName.get(declaration.path);
return (
packageIdName !== undefined &&
matcher.test(packageIdName) &&
program.isSourceFileFromExternalLibrary(declaration)
);
});
}

function typeDeclaredInLib(
Expand Down Expand Up @@ -207,6 +211,10 @@ export function typeMatchesSpecifier(
case 'lib':
return typeDeclaredInLib(declarationFiles, program);
case 'package':
return typeDeclaredInPackage(specifier.package, declarationFiles);
return typeDeclaredInPackage(
specifier.package,
declarationFiles,
program,
);
}
}
11 changes: 11 additions & 0 deletions packages/type-utils/typings/typescript.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,15 @@ declare module 'typescript' {
*/
intrinsicName?: string;
}

interface Program {
/**
* Maps from a SourceFile's `.path` to the name of the package it was imported with.
*/
readonly sourceFileToPackageName: ReadonlyMap<Path, string>;
}

interface SourceFile extends Declaration, LocalsContainer {
path: Path;
}
}

0 comments on commit b85f744

Please sign in to comment.