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

[New] no extraneous type-only dependencies #2234

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"escope": "^3.6.0",
"eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8",
"eslint-import-resolver-node": "file:./resolvers/node",
"eslint-import-resolver-typescript": "^1.0.2 || ^1.1.1",
"eslint-import-resolver-typescript": "^1.0.2 || ^2.5.0",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eslint-import-resolver-typescript handles @types packages since version 2.0.0.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'd prefer to continue testing on v1.1.1

Suggested change
"eslint-import-resolver-typescript": "^1.0.2 || ^2.5.0",
"eslint-import-resolver-typescript": "^1.0.2 || ^1.1.1 || ^2.5.0",

"eslint-import-resolver-webpack": "file:./resolvers/webpack",
"eslint-import-test-order-redirect": "file:./tests/files/order-redirect",
"eslint-module-utils": "file:./utils",
Expand Down
46 changes: 37 additions & 9 deletions src/rules/no-extraneous-dependencies.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import path from 'path';
import fs from 'fs';
import readPkgUp from 'eslint-module-utils/readPkgUp';
import minimatch from 'minimatch';
import resolve from 'eslint-module-utils/resolve';
import resolve, {
requireResolver,
resolverReducer,
} from 'eslint-module-utils/resolve';
import moduleVisitor from 'eslint-module-utils/moduleVisitor';
import importType from '../core/importType';
import { getFilePackageName } from '../core/packagePath';
Expand Down Expand Up @@ -117,6 +120,27 @@ function optDepErrorMessage(packageName) {
`not optionalDependencies.`;
}

function resolveTypeOnly(modulePath, context) {
const sourceFile = context.getPhysicalFilename
? context.getPhysicalFilename()
: context.getFilename();
const configResolvers = context.settings['import/resolver'];
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copied from:

const configResolvers = (settings['import/resolver']
|| { 'node': settings['import/resolve'] }); // backward compatibility
const resolvers = resolverReducer(configResolvers, new Map());
for (const pair of resolvers) {
const name = pair[0];
const config = pair[1];
const resolver = requireResolver(name, sourceFile);
const resolved = withResolver(resolver, config);

if (!configResolvers) return;
const resolvers = resolverReducer(configResolvers, new Map());
for (const [name, config] of resolvers) {
switch (name) {
case 'typescript':
case 'eslint-import-resolver-typescript': {
const resolver = requireResolver(name, sourceFile);
const resolved = resolver.resolve(modulePath, sourceFile, config);
if (resolved.found) {
return resolved.path;
}
}
}
}
}

function getModuleOriginalName(name) {
const [first, second] = name.split('/');
return first.startsWith('@') ? `${first}/${second}` : first;
Expand Down Expand Up @@ -160,22 +184,25 @@ function checkDependencyDeclaration(deps, packageName, declarationStatus) {

function reportIfMissing(context, deps, depsOptions, node, name) {
// Do not report when importing types
if (
node.importKind === 'type' ||
node.importKind === 'typeof'
) {
if (node.importKind === 'typeof') {
return;
}

if (importType(name, context) !== 'external') {
return;
}

const resolved = resolve(name, context);
const isTypeOnly = node.importKind === 'type';
const resolved = (isTypeOnly ? resolveTypeOnly : resolve)(name, context);
if (!resolved) { return; }

const importPackageName = getModuleOriginalName(name);
let declarationStatus = checkDependencyDeclaration(deps, importPackageName);
// If this is type-only, only check realPackageName, because if you
// e.g. import type { JSONSchema7Type } from 'json-schema',
// realPackageName could be @types/json-schema but importPackageName
// will be json-schema and that package could be untyped.
const importPackageName = !isTypeOnly && getModuleOriginalName(name);
let declarationStatus =
!isTypeOnly && checkDependencyDeclaration(deps, importPackageName);

if (
declarationStatus.isInDeps ||
Expand All @@ -195,7 +222,8 @@ function reportIfMissing(context, deps, depsOptions, node, name) {

if (
declarationStatus.isInDeps ||
(depsOptions.allowDevDeps && declarationStatus.isInDevDeps) ||
((depsOptions.allowDevDeps || isTypeOnly) &&
declarationStatus.isInDevDeps) ||
(depsOptions.allowPeerDeps && declarationStatus.isInPeerDeps) ||
(depsOptions.allowOptDeps && declarationStatus.isInOptDeps) ||
(depsOptions.allowBundledDeps && declarationStatus.isInBundledDeps)
Expand Down
Empty file.
3 changes: 3 additions & 0 deletions tests/files/node_modules/@types/a/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 42 additions & 1 deletion tests/src/core/resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { expect } from 'chai';
import eslintPkg from 'eslint/package.json';
import semver from 'semver';

import resolve, { CASE_SENSITIVE_FS, fileExistsWithCaseSync } from 'eslint-module-utils/resolve';
import resolve, {
CASE_SENSITIVE_FS,
fileExistsWithCaseSync,
requireResolver,
resolverReducer,
} from 'eslint-module-utils/resolve';

import * as path from 'path';
import * as fs from 'fs';
Expand Down Expand Up @@ -433,3 +438,39 @@ describe('resolve', function () {
});

});

describe('resolverReducer', () => {
it('accepts a string', () => {
expect([...resolverReducer('node', new Map())]).to.deep.equal([
['node', null],
]);
});

it('accepts an array', () => {
expect([
...resolverReducer(['node', 'typescript'], new Map()),
]).to.deep.equal([
['node', null],
['typescript', null],
]);
});

it('accepts an object', () => {
expect([
...resolverReducer({ node: null, typescript: null }, new Map()),
]).to.deep.equal([
['node', null],
['typescript', null],
]);
});
});

describe('requireResolver', () => {
it('accepts a conventional resolver name', () => {
requireResolver('node');
});

it('accepts a full package name', () => {
requireResolver('eslint-import-resolver-node');
});
});
99 changes: 69 additions & 30 deletions tests/src/rules/no-extraneous-dependencies.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { getTSParsers, test, testFilePath } from '../utils';
import typescriptConfig from '../../../config/typescript';
import path from 'path';
import typescriptResolverPkg from 'eslint-import-resolver-typescript/package.json';
import fs from 'fs';
import semver from 'semver';

import { RuleTester } from 'eslint';
import flatMap from 'array.prototype.flatmap';
Expand Down Expand Up @@ -378,38 +380,75 @@ ruleTester.run('no-extraneous-dependencies', rule, {
],
});

describe('TypeScript', () => {
getTSParsers()
// Type-only imports were added in TypeScript ESTree 2.23.0
.filter((parser) => parser !== require.resolve('typescript-eslint-parser'))
.forEach((parser) => {
const parserConfig = {
parser,
settings: {
'import/parsers': { [parser]: ['.ts'] },
'import/resolver': ['node', 'typescript'],
},
};
if (semver.satisfies(typescriptResolverPkg.version, '>=2.1.0')) {
describe('TypeScript', () => {
getTSParsers()
// Type-only imports were added in TypeScript ESTree 2.23.0
.filter((parser) => parser !== require.resolve('typescript-eslint-parser'))
.forEach((parser) => {
const parserConfig = {
parser,
settings: {
'import/parsers': { [parser]: ['.ts'] },
'import/resolver': ['node', 'typescript'],
},
};

ruleTester.run('no-extraneous-dependencies', rule, {
valid: [
test(Object.assign({
code: 'import type T from "a";',
options: [{ packageDir: packageDirWithTypescriptDevDependencies, devDependencies: false }],
}, parserConfig)),
],
invalid: [
test(Object.assign({
code: 'import T from "a";',
options: [{ packageDir: packageDirWithTypescriptDevDependencies, devDependencies: false }],
errors: [{
message: "'a' should be listed in the project's dependencies, not devDependencies.",
}],
}, parserConfig)),
],
ruleTester.run('no-extraneous-dependencies', rule, {
valid: [],
invalid: [
test(Object.assign({
code: 'import T from "a";',
options: [{ packageDir: packageDirWithTypescriptDevDependencies, devDependencies: false }],
errors: [{
message: "'a' should be listed in the project's dependencies, not devDependencies.",
}],
}, parserConfig)),
test(Object.assign({
code: 'import type T from "a";',
options: [{ packageDir: packageDirWithTypescriptDevDependencies, devDependencies: false }],
errors: [{
message: "'@types/a' should be listed in the project's dependencies. Run 'npm i -S @types/a' to add it",
}],
}, parserConfig)),
],
});
});
});
});
});
} else {
describe('Legacy TypeScript resolver', () => {
getTSParsers()
// Type-only imports were added in TypeScript ESTree 2.23.0
.filter((parser) => parser !== require.resolve('typescript-eslint-parser'))
.forEach((parser) => {
const parserConfig = {
parser,
settings: {
'import/parsers': { [parser]: ['.ts'] },
'import/resolver': ['node', 'typescript'],
},
};

ruleTester.run('no-extraneous-dependencies', rule, {
valid: [
test(Object.assign({
code: 'import type T from "a";',
options: [{ packageDir: packageDirWithTypescriptDevDependencies, devDependencies: false }],
}, parserConfig)),
],
invalid: [
test(Object.assign({
code: 'import T from "a";',
options: [{ packageDir: packageDirWithTypescriptDevDependencies, devDependencies: false }],
errors: [{
message: "'a' should be listed in the project's dependencies, not devDependencies.",
}],
}, parserConfig)),
],
});
});
});
}

typescriptRuleTester.run('no-extraneous-dependencies typescript type imports', rule, {
valid: [
Expand Down
2 changes: 2 additions & 0 deletions utils/resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ function resolverReducer(resolvers, map) {
err.name = ERROR_NAME;
throw err;
}
exports.resolverReducer = resolverReducer;

function getBaseDir(sourceFile) {
return pkgDir.sync(sourceFile) || process.cwd();
Expand All @@ -196,6 +197,7 @@ function requireResolver(name, sourceFile) {

return resolver;
}
exports.requireResolver = requireResolver;

function isResolverValid(resolver) {
if (resolver.interfaceVersion === 2) {
Expand Down