-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
dependency-checks.ts
364 lines (335 loc) · 11.1 KB
/
dependency-checks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { NX_VERSION, normalizePath, workspaceRoot } from '@nx/devkit';
import { findNpmDependencies } from '@nx/js/src/utils/find-npm-dependencies';
import { ESLintUtils } from '@typescript-eslint/utils';
import { AST } from 'jsonc-eslint-parser';
import { type JSONLiteral } from 'jsonc-eslint-parser/lib/parser/ast';
import { join } from 'path';
import { satisfies } from 'semver';
import {
getAllDependencies,
getPackageJson,
getProductionDependencies,
} from '../utils/package-json-utils';
import { readProjectGraph } from '../utils/project-graph-utils';
import {
findProject,
getParserServices,
getSourceFilePath,
} from '../utils/runtime-lint-utils';
export type Options = [
{
buildTargets?: string[];
checkMissingDependencies?: boolean;
checkObsoleteDependencies?: boolean;
checkVersionMismatches?: boolean;
ignoredDependencies?: string[];
ignoredFiles?: string[];
includeTransitiveDependencies?: boolean;
useLocalPathsForWorkspaceDependencies?: boolean;
}
];
export type MessageIds =
| 'missingDependency'
| 'obsoleteDependency'
| 'versionMismatch'
| 'missingDependencySection';
export const RULE_NAME = 'dependency-checks';
export default ESLintUtils.RuleCreator(
() =>
`https://github.com/nrwl/nx/blob/${NX_VERSION}/docs/generated/packages/eslint-plugin/documents/dependency-checks.md`
)<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description: `Checks dependencies in project's package.json for version mismatches`,
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
buildTargets: { type: 'array', items: { type: 'string' } },
ignoredDependencies: { type: 'array', items: { type: 'string' } },
ignoredFiles: { type: 'array', items: { type: 'string' } },
checkMissingDependencies: { type: 'boolean' },
checkObsoleteDependencies: { type: 'boolean' },
checkVersionMismatches: { type: 'boolean' },
includeTransitiveDependencies: { type: 'boolean' },
useLocalPathsForWorkspaceDependencies: { type: 'boolean' },
},
additionalProperties: false,
},
],
messages: {
missingDependency: `The "{{projectName}}" project uses the following packages, but they are missing from "{{section}}":{{packageNames}}`,
obsoleteDependency: `The "{{packageName}}" package is not used by "{{projectName}}" project.`,
versionMismatch: `The version specifier does not contain the installed version of "{{packageName}}" package: {{version}}.`,
missingDependencySection: `Dependency sections are missing from the "package.json" but following dependencies were detected:{{dependencies}}`,
},
},
defaultOptions: [
{
buildTargets: ['build'],
checkMissingDependencies: true,
checkObsoleteDependencies: true,
checkVersionMismatches: true,
ignoredDependencies: [],
ignoredFiles: [],
includeTransitiveDependencies: false,
useLocalPathsForWorkspaceDependencies: false,
},
],
create(
context,
[
{
buildTargets,
ignoredDependencies,
ignoredFiles,
checkMissingDependencies,
checkObsoleteDependencies,
checkVersionMismatches,
includeTransitiveDependencies,
useLocalPathsForWorkspaceDependencies,
},
]
) {
if (!getParserServices(context).isJSON) {
return {};
}
const fileName = normalizePath(context.filename ?? context.getFilename());
// support only package.json
if (!fileName.endsWith('/package.json')) {
return {};
}
const sourceFilePath = getSourceFilePath(fileName, workspaceRoot);
const { projectGraph, projectRootMappings, projectFileMap } =
readProjectGraph(RULE_NAME);
if (!projectGraph) {
return {};
}
const sourceProject = findProject(
projectGraph,
projectRootMappings,
sourceFilePath
);
// check if source project exists
if (!sourceProject) {
return {};
}
// check if library has a build target
const buildTarget = buildTargets.find(
(t) => sourceProject.data.targets?.[t]
);
if (!buildTarget) {
return {};
}
const rootPackageJson = getPackageJson(join(workspaceRoot, 'package.json'));
const npmDependencies = findNpmDependencies(
workspaceRoot,
sourceProject,
projectGraph,
projectFileMap,
buildTarget, // TODO: What if child library has a build target different from the parent?
{
includeTransitiveDependencies,
ignoredFiles,
useLocalPathsForWorkspaceDependencies,
}
);
const expectedDependencyNames = Object.keys(npmDependencies);
const packageJson = JSON.parse(context.sourceCode.getText());
const projPackageJsonDeps = getProductionDependencies(packageJson);
const rootPackageJsonDeps = getAllDependencies(rootPackageJson);
function validateMissingDependencies(node: AST.JSONProperty) {
if (!checkMissingDependencies) {
return;
}
const missingDeps = expectedDependencyNames.filter(
(d) => !projPackageJsonDeps[d] && !ignoredDependencies.includes(d)
);
if (missingDeps.length) {
context.report({
node: node as any,
messageId: 'missingDependency',
data: {
packageNames: missingDeps.map((d) => `\n - ${d}`).join(''),
section: (node.key as JSONLiteral).value,
projectName: sourceProject.name,
},
fix(fixer) {
missingDeps.forEach((d) => {
projPackageJsonDeps[d] =
rootPackageJsonDeps[d] || npmDependencies[d];
});
const deps = (node.value as AST.JSONObjectExpression).properties;
const mappedDeps = missingDeps
.map((d) => `\n "${d}": "${projPackageJsonDeps[d]}"`)
.join(',');
if (deps.length) {
return fixer.insertTextAfter(
deps[deps.length - 1] as any,
`,${mappedDeps}`
);
} else {
return fixer.insertTextAfterRange(
[node.value.range[0] + 1, node.value.range[1] - 1],
`${mappedDeps}\n `
);
}
},
});
}
}
function validateVersionMatchesInstalled(
node: AST.JSONProperty,
packageName: string,
packageRange: string
) {
if (!checkVersionMismatches) {
return;
}
if (
npmDependencies[packageName].startsWith('file:') ||
packageRange.startsWith('file:') ||
npmDependencies[packageName] === '*' ||
packageRange === '*' ||
packageRange === 'workspace:*' ||
satisfies(npmDependencies[packageName], packageRange, {
includePrerelease: true,
})
) {
return;
}
context.report({
node: node as any,
messageId: 'versionMismatch',
data: {
packageName: packageName,
version: npmDependencies[packageName],
},
fix: (fixer) =>
fixer.replaceText(
node as any,
`"${packageName}": "${
rootPackageJsonDeps[packageName] || npmDependencies[packageName]
}"`
),
});
}
function reportObsoleteDependency(
node: AST.JSONProperty,
packageName: string
) {
if (!checkObsoleteDependencies) {
return;
}
context.report({
node: node as any,
messageId: 'obsoleteDependency',
data: { packageName: packageName, projectName: sourceProject.name },
fix: (fixer) => {
const isLastProperty =
node.parent.properties[node.parent.properties.length - 1] === node;
const index = node.parent.properties.findIndex((n) => n === node);
if (index > 0) {
const previousNode = node.parent.properties[index - 1];
return fixer.removeRange([
previousNode.range[1] + (isLastProperty ? 0 : 1),
node.range[1] + (isLastProperty ? 0 : 1),
]);
} else {
const parent = node.parent;
// it's the only property
if (isLastProperty) {
return fixer.removeRange([
parent.range[0] + 1,
parent.range[1] - 1,
]);
} else {
return fixer.removeRange([
parent.range[0] + 1,
node.range[1] + 1,
]);
}
}
},
});
}
function validateDependenciesSectionExistance(
node: AST.JSONObjectExpression
) {
if (
!expectedDependencyNames.length ||
!expectedDependencyNames.some((d) => !ignoredDependencies.includes(d))
) {
return;
}
if (
!node.properties ||
!node.properties.some((p) =>
['dependencies', 'peerDependencies', 'optionalDependencies'].includes(
(p.key as any).value
)
)
) {
context.report({
node: node as any,
messageId: 'missingDependencySection',
data: {
dependencies: expectedDependencyNames
.map((d) => `\n- "${d}"`)
.join(),
},
fix: (fixer) => {
expectedDependencyNames.sort().reduce((acc, d) => {
acc[d] = rootPackageJsonDeps[d] || npmDependencies[d];
return acc;
}, projPackageJsonDeps);
const dependencies = Object.keys(projPackageJsonDeps)
.map((d) => `\n "${d}": "${projPackageJsonDeps[d]}"`)
.join(',');
if (!node.properties.length) {
return fixer.replaceText(
node as any,
`{\n "dependencies": {${dependencies}\n }\n}`
);
} else {
return fixer.insertTextAfter(
node.properties[node.properties.length - 1] as any,
`,\n "dependencies": {${dependencies}\n }`
);
}
},
});
}
}
return {
['JSONExpressionStatement > JSONObjectExpression > JSONProperty[key.value=/^(peer|optional)?dependencies$/i]'](
node: AST.JSONProperty
) {
validateMissingDependencies(node);
},
['JSONExpressionStatement > JSONObjectExpression > JSONProperty[key.value=/^(peer|optional)?dependencies$/i] > JSONObjectExpression > JSONProperty'](
node: AST.JSONProperty
) {
const packageName = (node.key as any).value;
const packageRange = (node.value as any).value;
if (ignoredDependencies.includes(packageName)) {
return;
}
if (expectedDependencyNames.includes(packageName)) {
validateVersionMatchesInstalled(node, packageName, packageRange);
} else {
reportObsoleteDependency(node, packageName);
}
},
['JSONExpressionStatement > JSONObjectExpression'](
node: AST.JSONObjectExpression
) {
validateDependenciesSectionExistance(node);
},
};
},
});