Skip to content

Commit

Permalink
fix(type-utils): use typescript's isSourceFileFromExternalLibrary
Browse files Browse the repository at this point in the history
  • Loading branch information
RebeccaStevens committed Jun 15, 2023
1 parent e6235bf commit 58728a8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
22 changes: 14 additions & 8 deletions packages/type-utils/src/TypeOrValueSpecifier.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { JSONSchema4 } from '@typescript-eslint/utils/json-schema';
import path from 'path';
import type * as ts from 'typescript';
import * as ts from 'typescript';

Check failure on line 3 in packages/type-utils/src/TypeOrValueSpecifier.ts

View workflow job for this annotation

GitHub Actions / Lint (lint)

All imports in the declaration are only used as types. Use `import type`

interface FileSpecifier {
from: 'file';
Expand Down Expand Up @@ -150,16 +150,18 @@ 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 typesPackageName = packageName.replace(/^@([^/]+)\//, '$1__');

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

export function typeMatchesSpecifier(
Expand All @@ -186,6 +188,10 @@ export function typeMatchesSpecifier(
program.isSourceFileDefaultLibrary(declaration),
);
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 58728a8

Please sign in to comment.