/
nxEnforceModuleBoundariesRule.ts
328 lines (300 loc) · 10.2 KB
/
nxEnforceModuleBoundariesRule.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
import * as Lint from 'tslint';
import { IOptions } from 'tslint';
import * as ts from 'typescript';
import type {
NxJsonConfiguration,
ProjectGraphExternalNode,
} from '@nrwl/devkit';
import { ProjectType, readCachedProjectGraph } from '../core/project-graph';
import { appRootPath } from '@nrwl/tao/src/utils/app-root';
import {
DepConstraint,
findConstraintsFor,
findProjectUsingImport,
findSourceProject,
getSourceFilePath,
getTargetProjectBasedOnRelativeImport,
hasBuildExecutor,
findDependenciesWithTags,
isAbsoluteImportIntoAnotherProject,
MappedProjectGraph,
mapProjectGraphFiles,
matchImportWithWildcard,
onlyLoadChildren,
stringifyTags,
hasNoneOfTheseTags,
MappedProjectGraphNode,
} from '../utils/runtime-lint-utils';
import { normalize } from 'path';
import { readNxJson } from '../core/file-utils';
import { TargetProjectLocator } from '../core/target-project-locator';
import {
checkCircularPath,
findFilesInCircularPath,
} from '../utils/graph-utils';
import { isRelativePath } from '../utilities/fileutils';
export class Rule extends Lint.Rules.AbstractRule {
constructor(
options: IOptions,
private readonly projectPath?: string,
private readonly npmScope?: string,
private readonly projectGraph?: MappedProjectGraph,
private readonly targetProjectLocator?: TargetProjectLocator,
private readonly workspaceLayout?: NxJsonConfiguration['workspaceLayout']
) {
super(options);
if (!projectPath) {
this.projectPath = normalize(appRootPath);
if (!(global as any).projectGraph) {
const nxJson = readNxJson();
(global as any).npmScope = nxJson.npmScope;
(global as any).workspaceLayout = nxJson.workspaceLayout;
/**
* Because there are a number of ways in which the rule can be invoked (executor vs TSLint CLI vs IDE Plugin),
* the ProjectGraph may or may not exist by the time the lint rule is invoked for the first time.
*/
try {
(global as any).projectGraph = mapProjectGraphFiles(
readCachedProjectGraph()
);
} catch {}
}
this.npmScope = (global as any).npmScope;
this.workspaceLayout = (global as any).workspaceLayout;
this.projectGraph = (global as any).projectGraph as MappedProjectGraph;
if (!(global as any).targetProjectLocator && this.projectGraph) {
(global as any).targetProjectLocator = new TargetProjectLocator(
this.projectGraph.nodes,
this.projectGraph.externalNodes
);
}
this.targetProjectLocator = (global as any).targetProjectLocator;
}
}
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
if (!this.projectGraph) return [];
return this.applyWithWalker(
new EnforceModuleBoundariesWalker(
sourceFile,
this.getOptions(),
this.projectPath,
this.npmScope,
this.projectGraph,
this.targetProjectLocator,
this.workspaceLayout
)
);
}
}
class EnforceModuleBoundariesWalker extends Lint.RuleWalker {
private readonly allow: string[];
private readonly enforceBuildableLibDependency: boolean = false; // for backwards compat
private readonly depConstraints: DepConstraint[];
private readonly allowCircularSelfDependency: boolean = false;
constructor(
sourceFile: ts.SourceFile,
options: IOptions,
private readonly projectPath: string,
private readonly npmScope: string,
private readonly projectGraph: MappedProjectGraph,
private readonly targetProjectLocator: TargetProjectLocator,
private readonly workspaceLayout: NxJsonConfiguration['workspaceLayout']
) {
super(sourceFile, options);
this.allow = Array.isArray(this.getOptions()[0].allow)
? this.getOptions()[0].allow.map((a) => `${a}`)
: [];
this.depConstraints = Array.isArray(this.getOptions()[0].depConstraints)
? this.getOptions()[0].depConstraints
: [];
this.enforceBuildableLibDependency =
this.getOptions()[0].enforceBuildableLibDependency === true;
this.allowCircularSelfDependency =
this.getOptions()[0].allowCircularSelfDependency === true;
}
public visitImportDeclaration(node: ts.ImportDeclaration) {
const imp = node.moduleSpecifier
.getText()
.substring(1, node.moduleSpecifier.getText().length - 1);
// whitelisted import
if (this.allow.some((a) => matchImportWithWildcard(a, imp))) {
super.visitImportDeclaration(node);
return;
}
const filePath = getSourceFilePath(
this.getSourceFile().fileName,
this.projectPath
);
const sourceProject = findSourceProject(this.projectGraph, filePath);
if (!sourceProject) {
super.visitImportDeclaration(node);
return;
}
let targetProject: MappedProjectGraphNode | ProjectGraphExternalNode =
getTargetProjectBasedOnRelativeImport(
imp,
this.projectPath,
this.projectGraph,
filePath
);
// check for relative and absolute imports
if (
(targetProject && sourceProject !== targetProject) ||
isAbsoluteImportIntoAnotherProject(imp, this.workspaceLayout)
) {
this.addFailureAt(
node.getStart(),
node.getWidth(),
`libraries cannot be imported by a relative or absolute path, and must begin with a npm scope`
);
return;
}
targetProject =
targetProject ||
findProjectUsingImport(
this.projectGraph,
this.targetProjectLocator,
filePath,
imp,
this.npmScope
);
// If source or target are not part of an nx workspace, return.
if (!targetProject || targetProject.type === 'npm') {
super.visitImportDeclaration(node);
return;
}
// same project => allow
if (sourceProject === targetProject) {
if (!this.allowCircularSelfDependency && !isRelativePath(imp)) {
const error = `Projects should use relative imports to import from other files within the same project. Use "./path/to/file" instead of import from "${imp}"`;
this.addFailureAt(node.getStart(), node.getWidth(), error);
} else {
super.visitImportDeclaration(node);
}
return;
}
// check for circular dependency
const circularPath = checkCircularPath(
this.projectGraph,
sourceProject,
targetProject
);
if (circularPath.length !== 0) {
const path = circularPath.reduce(
(acc, v) => `${acc} -> ${v.name}`,
sourceProject.name
);
const circularFilePath = findFilesInCircularPath(circularPath);
const filePaths = circularFilePath
.map((files) => (files.length > 1 ? `[${files.join(',')}]` : files[0]))
.reduce((acc, files) => `${acc}\n- ${files}`, `- ${filePath}`);
const error = `Circular dependency between "${sourceProject.name}" and "${targetProject.name}" detected: ${path}\n\nCircular file chain:\n${filePaths}`;
this.addFailureAt(node.getStart(), node.getWidth(), error);
return;
}
// cannot import apps
if (targetProject.type === ProjectType.app) {
this.addFailureAt(
node.getStart(),
node.getWidth(),
'imports of apps are forbidden'
);
return;
}
// cannot import e2e projects
if (targetProject.type === ProjectType.e2e) {
this.addFailureAt(
node.getStart(),
node.getWidth(),
'imports of e2e projects are forbidden'
);
return;
}
// buildable-lib is not allowed to import non-buildable-lib
if (
this.enforceBuildableLibDependency === true &&
sourceProject.type === ProjectType.lib &&
targetProject.type === ProjectType.lib
) {
if (hasBuildExecutor(sourceProject) && !hasBuildExecutor(targetProject)) {
this.addFailureAt(
node.getStart(),
node.getWidth(),
'buildable libraries cannot import non-buildable libraries'
);
return;
}
}
// if we import a library using loadChildren, we should not import it using es6imports
if (
onlyLoadChildren(
this.projectGraph,
sourceProject.name,
targetProject.name,
[]
)
) {
this.addFailureAt(
node.getStart(),
node.getWidth(),
'imports of lazy-loaded libraries are forbidden'
);
return;
}
// check that dependency constraints are satisfied
if (this.depConstraints.length > 0) {
const constraints = findConstraintsFor(
this.depConstraints,
sourceProject
);
// when no constrains found => error. Force the user to provision them.
if (constraints.length === 0) {
this.addFailureAt(
node.getStart(),
node.getWidth(),
`A project without tags matching at least one constraint cannot depend on any libraries`
);
return;
}
for (let constraint of constraints) {
if (
constraint.onlyDependOnLibsWithTags &&
hasNoneOfTheseTags(targetProject, constraint.onlyDependOnLibsWithTags)
) {
const error = `A project tagged with "${
constraint.sourceTag
}" can only depend on libs tagged with ${stringifyTags(
constraint.onlyDependOnLibsWithTags
)}`;
this.addFailureAt(node.getStart(), node.getWidth(), error);
return;
}
if (
constraint.notDependOnLibsWithTags &&
constraint.notDependOnLibsWithTags.length
) {
const projectPaths = findDependenciesWithTags(
targetProject,
constraint.notDependOnLibsWithTags,
this.projectGraph
);
if (projectPaths.length > 0) {
const error = `A project tagged with "${
constraint.sourceTag
}" can not depend on libs tagged with ${stringifyTags(
constraint.notDependOnLibsWithTags
)}\n\nViolation detected in:\n${projectPaths
.map(
(projectPath) =>
`- ${projectPath.map((p) => p.name).join(' -> ')}`
)
.join('\n')}`;
this.addFailureAt(node.getStart(), node.getWidth(), error);
return;
}
}
}
}
super.visitImportDeclaration(node);
}
}