-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathenforce-module-boundaries.ts
More file actions
777 lines (734 loc) · 25.5 KB
/
enforce-module-boundaries.ts
File metadata and controls
777 lines (734 loc) · 25.5 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
import {
joinPathFragments,
normalizePath,
NX_VERSION,
ProjectGraphExternalNode,
ProjectGraphProjectNode,
workspaceRoot,
} from '@nx/devkit';
import {
AST_NODE_TYPES,
ESLintUtils,
TSESTree,
} from '@typescript-eslint/utils';
import { isBuiltinModuleImport } from '@nx/js/src/internal';
import { isRelativePath } from 'nx/src/utils/fileutils';
import { basename, dirname, join, relative } from 'path';
import {
getBarrelEntryPointByImportScope,
getBarrelEntryPointProjectNode,
getRelativeImportPath,
} from '../utils/ast-utils';
import {
checkCircularPath,
circularPathHasPair,
expandIgnoredCircularDependencies,
findFilesInCircularPath,
findFilesWithDynamicImports,
} from '../utils/graph-utils';
import { readProjectGraph } from '../utils/project-graph-utils';
import {
appIsMFERemote,
belongsToDifferentEntryPoint,
DepConstraint,
findConstraintsFor,
findDependenciesWithTags,
findProject,
findProjectUsingImport,
findTransitiveExternalDependencies,
getSourceFilePath,
getTargetProjectBasedOnRelativeImport,
groupImports,
hasBannedDependencies,
hasBannedImport,
hasBuildExecutor,
hasNoneOfTheseTags,
hasStaticImportOfDynamicResource,
isAbsoluteImportIntoAnotherProject,
isComboDepConstraint,
isDirectDependency,
matchImportWithWildcard,
stringifyTags,
} from '../utils/runtime-lint-utils';
import { isProjectGraphProjectNode } from 'nx/src/config/project-graph';
export type Options = [
{
allow: string[];
buildTargets: string[];
depConstraints: DepConstraint[];
enforceBuildableLibDependency: boolean;
allowCircularSelfDependency: boolean;
ignoredCircularDependencies: Array<[string, string]>;
checkDynamicDependenciesExceptions: string[];
banTransitiveDependencies: boolean;
checkNestedExternalImports: boolean;
},
];
export type MessageIds =
| 'noRelativeOrAbsoluteImportsAcrossLibraries'
| 'noRelativeOrAbsoluteExternals'
| 'noSelfCircularDependencies'
| 'noCircularDependencies'
| 'noImportsOfApps'
| 'noImportsOfE2e'
| 'noImportOfNonBuildableLibraries'
| 'noImportsOfLazyLoadedLibraries'
| 'projectWithoutTagsCannotHaveDependencies'
| 'bannedExternalImportsViolation'
| 'nestedBannedExternalImportsViolation'
| 'noTransitiveDependencies'
| 'onlyTagsConstraintViolation'
| 'emptyOnlyTagsConstraintViolation'
| 'notTagsConstraintViolation';
export const RULE_NAME = 'enforce-module-boundaries';
export default ESLintUtils.RuleCreator(
() =>
`https://github.com/nrwl/nx/blob/${NX_VERSION}/docs/generated/packages/eslint-plugin/documents/enforce-module-boundaries.md`
)<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description: `Ensure that module boundaries are respected within the monorepo`,
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
enforceBuildableLibDependency: { type: 'boolean' },
allowCircularSelfDependency: { type: 'boolean' },
checkDynamicDependenciesExceptions: {
type: 'array',
items: { type: 'string' },
},
ignoredCircularDependencies: {
type: 'array',
items: {
type: 'array',
items: { type: 'string' },
minItems: 2,
maxItems: 2,
},
},
banTransitiveDependencies: { type: 'boolean' },
checkNestedExternalImports: { type: 'boolean' },
allow: { type: 'array', items: { type: 'string' } },
buildTargets: { type: 'array', items: { type: 'string' } },
depConstraints: {
type: 'array',
items: {
oneOf: [
{
type: 'object',
properties: {
sourceTag: { type: 'string' },
onlyDependOnLibsWithTags: {
type: 'array',
items: { type: 'string' },
},
allowedExternalImports: {
type: 'array',
items: { type: 'string' },
},
bannedExternalImports: {
type: 'array',
items: { type: 'string' },
},
notDependOnLibsWithTags: {
type: 'array',
items: { type: 'string' },
},
},
additionalProperties: false,
},
{
type: 'object',
properties: {
allSourceTags: {
type: 'array',
items: { type: 'string' },
minItems: 2,
},
onlyDependOnLibsWithTags: {
type: 'array',
items: { type: 'string' },
},
allowedExternalImports: {
type: 'array',
items: { type: 'string' },
},
bannedExternalImports: {
type: 'array',
items: { type: 'string' },
},
notDependOnLibsWithTags: {
type: 'array',
items: { type: 'string' },
},
},
additionalProperties: false,
},
],
},
},
},
additionalProperties: false,
},
],
messages: {
noRelativeOrAbsoluteImportsAcrossLibraries: `Projects cannot be imported by a relative or absolute path, and must begin with a npm scope`,
noRelativeOrAbsoluteExternals: `External resources cannot be imported using a relative or absolute path`,
noCircularDependencies: `Circular dependency between "{{sourceProjectName}}" and "{{targetProjectName}}" detected: {{path}}\n\nCircular file chain:\n{{filePaths}}`,
noSelfCircularDependencies: `Projects should use relative imports to import from other files within the same project. Use "./path/to/file" instead of import from "{{imp}}"`,
noImportsOfApps: 'Imports of apps are forbidden',
noImportsOfE2e: 'Imports of e2e projects are forbidden',
noImportOfNonBuildableLibraries:
'Buildable libraries cannot import or export from non-buildable libraries',
noImportsOfLazyLoadedLibraries: `Static imports of lazy-loaded libraries are forbidden.\n\nLibrary "{{targetProjectName}}" is lazy-loaded in these files:\n{{filePaths}}`,
projectWithoutTagsCannotHaveDependencies: `A project without tags matching at least one constraint cannot depend on any libraries`,
bannedExternalImportsViolation: `A project tagged with "{{sourceTag}}" is not allowed to import "{{imp}}"`,
nestedBannedExternalImportsViolation: `A project tagged with "{{sourceTag}}" is not allowed to import "{{imp}}". Nested import found at {{childProjectName}}`,
noTransitiveDependencies: `Only packages defined in the "package.json" can be imported. Transitive or unresolvable dependencies are not allowed.`,
onlyTagsConstraintViolation: `A project tagged with "{{sourceTag}}" can only depend on libs tagged with {{tags}}`,
emptyOnlyTagsConstraintViolation:
'A project tagged with "{{sourceTag}}" cannot depend on any libs with tags',
notTagsConstraintViolation: `A project tagged with "{{sourceTag}}" can not depend on libs tagged with {{tags}}\n\nViolation detected in:\n{{projects}}`,
},
},
defaultOptions: [
{
allow: [],
buildTargets: ['build'],
depConstraints: [],
enforceBuildableLibDependency: false,
allowCircularSelfDependency: false,
checkDynamicDependenciesExceptions: [],
ignoredCircularDependencies: [],
banTransitiveDependencies: false,
checkNestedExternalImports: false,
},
],
create(
context,
[
{
allow,
buildTargets,
depConstraints,
enforceBuildableLibDependency,
allowCircularSelfDependency,
checkDynamicDependenciesExceptions,
ignoredCircularDependencies,
banTransitiveDependencies,
checkNestedExternalImports,
},
]
) {
/**
* Globally cached info about workspace
*/
const projectPath = normalizePath(
(global as any).projectPath || workspaceRoot
);
const fileName = normalizePath(context.filename ?? context.getFilename());
const {
projectGraph,
projectRootMappings,
projectFileMap,
targetProjectLocator,
} = readProjectGraph(RULE_NAME);
if (!projectGraph) {
return {};
}
const workspaceLayout = (global as any).workspaceLayout;
const expandedIgnoreCircularDependencies =
expandIgnoredCircularDependencies(
ignoredCircularDependencies,
projectGraph
);
function run(
node:
| TSESTree.ImportDeclaration
| TSESTree.ImportExpression
| TSESTree.ExportAllDeclaration
| TSESTree.ExportNamedDeclaration
) {
// Ignoring ExportNamedDeclarations like:
// export class Foo {}
if (!node.source) {
return;
}
// accept only literals because template literals have no value
if (node.source.type !== AST_NODE_TYPES.Literal) {
return;
}
const imp = node.source.value as string;
// whitelisted import
if (allow.some((a) => matchImportWithWildcard(a, imp))) {
return;
}
const sourceFilePath = getSourceFilePath(fileName, projectPath);
const sourceProject = findProject(
projectGraph,
projectRootMappings,
sourceFilePath
);
// If source is not part of an nx workspace, return.
if (!sourceProject) {
return;
}
// check for relative and absolute imports
const isAbsoluteImportIntoAnotherProj =
isAbsoluteImportIntoAnotherProject(imp, workspaceLayout);
let targetProject: ProjectGraphProjectNode | ProjectGraphExternalNode;
if (isAbsoluteImportIntoAnotherProj) {
targetProject = findProject(projectGraph, projectRootMappings, imp);
} else {
targetProject = getTargetProjectBasedOnRelativeImport(
imp,
projectPath,
projectGraph,
projectRootMappings,
sourceFilePath
);
}
if (
(targetProject && sourceProject !== targetProject) ||
isAbsoluteImportIntoAnotherProj
) {
context.report({
node,
messageId: 'noRelativeOrAbsoluteImportsAcrossLibraries',
fix(fixer) {
if (targetProject) {
const indexTsPaths = getBarrelEntryPointProjectNode(
targetProject as ProjectGraphProjectNode
);
if (indexTsPaths && indexTsPaths.length > 0) {
const specifiers = (node as any).specifiers;
if (!specifiers || specifiers.length === 0) {
return;
}
const imports = specifiers
.filter((s) => s.type === 'ImportSpecifier')
.map((s) => s.imported.name);
// process each potential entry point and try to find the imports
const importsToRemap = [];
for (const entryPointPath of indexTsPaths) {
for (const importMember of imports) {
const importPath = getRelativeImportPath(
importMember,
join(workspaceRoot, entryPointPath.path)
);
// we cannot remap, so leave it as is
if (importPath) {
importsToRemap.push({
member: importMember,
importPath: entryPointPath.importScope,
});
}
}
}
const adjustedRelativeImports = groupImports(importsToRemap);
if (adjustedRelativeImports !== '') {
return fixer.replaceTextRange(
node.range,
adjustedRelativeImports
);
}
}
}
},
});
return;
}
targetProject =
targetProject ||
findProjectUsingImport(
projectGraph,
targetProjectLocator,
sourceFilePath,
imp
);
if (!targetProject) {
// non-project imports cannot use relative or absolute paths
if (isRelativePath(imp) || imp.startsWith('/')) {
context.report({
node,
messageId: 'noRelativeOrAbsoluteExternals',
});
} else if (banTransitiveDependencies && !isBuiltinModuleImport(imp)) {
/**
* At this point, the target project could not be found in the project graph, and it is not a relative or absolute import.
* Therefore it could be an external/npm package dependency (but not a node built in module) which has not yet been installed
* in the workspace.
*
* If the banTransitiveDependencies option is enabled, we should flag this case as an error because the user is trying to
* depend on something which is not explicitly defined/resolvable on disk for their project.
*/
context.report({
node,
messageId: 'noTransitiveDependencies',
});
}
// If target is not found (including node internals) we bail early
return;
}
// we only allow relative paths within the same project
// and if it's not a secondary entrypoint in an angular lib
if (
sourceProject === targetProject &&
!circularPathHasPair(
[sourceProject, targetProject],
expandedIgnoreCircularDependencies
)
) {
if (
!allowCircularSelfDependency &&
!isRelativePath(imp) &&
!belongsToDifferentEntryPoint(
imp,
sourceFilePath,
sourceProject.data.root
)
) {
context.report({
node,
messageId: 'noSelfCircularDependencies',
data: {
imp,
},
fix(fixer) {
// imp has form of @myorg/someproject/some/path
const indexTsPaths = getBarrelEntryPointByImportScope(imp);
if (indexTsPaths.length > 0) {
const specifiers = (node as any).specifiers;
if (!specifiers || specifiers.length === 0) {
return;
}
// imported JS functions to remap
const imports = specifiers
.filter((s) => s.type === 'ImportSpecifier')
.map((s) => s.imported.name);
// process each potential entry point and try to find the imports
const importsToRemap = [];
for (const entryPointPath of indexTsPaths) {
for (const importMember of imports) {
const importPath = getRelativeImportPath(
importMember,
join(workspaceRoot, entryPointPath)
);
if (importPath) {
// resolve the import path
const relativePath = relative(
dirname(fileName),
dirname(importPath)
);
// the string we receive from elsewhere might not have a leading './' here despite still being a relative path
// we'd like to ensure it's a normalized relative form starting from ./ or ../
const ensureRelativeForm = (path: string): string =>
path.startsWith('./') || path.startsWith('../')
? path
: `./${path}`;
// if the string is empty, it's the current file
const importPathResolved =
relativePath === ''
? `./${basename(importPath)}`
: ensureRelativeForm(
joinPathFragments(
relativePath,
basename(importPath)
)
);
importsToRemap.push({
member: importMember,
// remove .ts or .tsx from the end of the file path
importPath: importPathResolved.replace(/.tsx?$/, ''),
});
}
}
}
const adjustedRelativeImports = groupImports(importsToRemap);
if (adjustedRelativeImports !== '') {
return fixer.replaceTextRange(
node.range,
adjustedRelativeImports
);
}
}
},
});
}
return;
}
// project => npm package
if (targetProject.type === 'npm') {
if (
banTransitiveDependencies &&
!isDirectDependency(sourceProject, targetProject)
) {
context.report({
node,
messageId: 'noTransitiveDependencies',
});
}
const constraint = hasBannedImport(
sourceProject,
targetProject,
depConstraints,
imp
);
if (constraint) {
context.report({
node,
messageId: 'bannedExternalImportsViolation',
data: {
sourceTag: isComboDepConstraint(constraint)
? constraint.allSourceTags.join('" and "')
: constraint.sourceTag,
imp,
},
});
}
return;
}
if (!isProjectGraphProjectNode(targetProject)) {
return;
}
targetProject = targetProject as ProjectGraphProjectNode;
// check constraints between libs and apps
// check for circular dependency
const circularPath = checkCircularPath(
projectGraph,
sourceProject,
targetProject
);
if (
circularPath.length !== 0 &&
!circularPathHasPair(circularPath, expandedIgnoreCircularDependencies)
) {
const circularFilePath = findFilesInCircularPath(
projectFileMap,
circularPath
);
// spacer text used for indirect dependencies when printing one line per file.
// without this, we can end up with a very long line that does not display well in the terminal.
const spacer = ' ';
context.report({
node,
messageId: 'noCircularDependencies',
data: {
sourceProjectName: sourceProject.name,
targetProjectName: targetProject.name,
path: circularPath.reduce(
(acc, v) => `${acc} -> ${v.name}`,
sourceProject.name
),
filePaths: circularFilePath
.map((files) =>
files.length > 1
? `[${files
.map((f) => `\n${spacer}${spacer}${f}`)
.join(',')}\n${spacer}]`
: files[0]
)
.reduce(
(acc, files) => `${acc}\n- ${files}`,
`- ${sourceFilePath}`
),
},
});
return;
}
// cannot import apps
if (targetProject.type === 'app' && !appIsMFERemote(targetProject)) {
context.report({
node,
messageId: 'noImportsOfApps',
});
return;
}
// cannot import e2e projects
if (targetProject.type === 'e2e') {
context.report({
node,
messageId: 'noImportsOfE2e',
});
return;
}
// buildable-lib is not allowed to import non-buildable-lib
if (
enforceBuildableLibDependency === true &&
sourceProject.type === 'lib' &&
targetProject.type === 'lib'
) {
if (
hasBuildExecutor(sourceProject, buildTargets) &&
!hasBuildExecutor(targetProject, buildTargets)
) {
context.report({
node,
messageId: 'noImportOfNonBuildableLibraries',
});
return;
}
}
// if we import a library using loadChildren, we should not import it using es6imports
if (
!checkDynamicDependenciesExceptions.some((a) =>
matchImportWithWildcard(a, imp)
) &&
hasStaticImportOfDynamicResource(
node,
projectGraph,
sourceProject.name,
targetProject.name,
imp,
sourceFilePath
)
) {
const filesWithLazyImports = findFilesWithDynamicImports(
projectFileMap,
sourceProject.name,
targetProject.name
);
context.report({
data: {
filePaths: filesWithLazyImports
.map(({ file }) => `- ${file}`)
.join('\n'),
targetProjectName: targetProject.name,
},
node,
messageId: 'noImportsOfLazyLoadedLibraries',
});
return;
}
// check that dependency constraints are satisfied
if (depConstraints.length > 0) {
const constraints = findConstraintsFor(depConstraints, sourceProject);
// when no constrains found => error. Force the user to provision them.
if (constraints.length === 0) {
context.report({
node,
messageId: 'projectWithoutTagsCannotHaveDependencies',
});
return;
}
const transitiveExternalDeps = checkNestedExternalImports
? findTransitiveExternalDependencies(projectGraph, targetProject)
: [];
for (let constraint of constraints) {
if (
constraint.onlyDependOnLibsWithTags &&
constraint.onlyDependOnLibsWithTags.length &&
hasNoneOfTheseTags(
targetProject,
constraint.onlyDependOnLibsWithTags
)
) {
context.report({
node,
messageId: 'onlyTagsConstraintViolation',
data: {
sourceTag: isComboDepConstraint(constraint)
? constraint.allSourceTags.join('" and "')
: constraint.sourceTag,
tags: stringifyTags(constraint.onlyDependOnLibsWithTags),
},
});
return;
}
if (
constraint.onlyDependOnLibsWithTags &&
constraint.onlyDependOnLibsWithTags.length === 0 &&
targetProject.data.tags.length !== 0
) {
context.report({
node,
messageId: 'emptyOnlyTagsConstraintViolation',
data: {
sourceTag: isComboDepConstraint(constraint)
? constraint.allSourceTags.join('" and "')
: constraint.sourceTag,
},
});
return;
}
if (
constraint.notDependOnLibsWithTags &&
constraint.notDependOnLibsWithTags.length
) {
const projectPaths = findDependenciesWithTags(
targetProject,
constraint.notDependOnLibsWithTags,
projectGraph
);
if (projectPaths.length > 0) {
context.report({
node,
messageId: 'notTagsConstraintViolation',
data: {
sourceTag: isComboDepConstraint(constraint)
? constraint.allSourceTags.join('" and "')
: constraint.sourceTag,
tags: stringifyTags(constraint.notDependOnLibsWithTags),
projects: projectPaths
.map(
(projectPath) =>
`- ${projectPath.map((p) => p.name).join(' -> ')}`
)
.join('\n'),
},
});
return;
}
}
if (
checkNestedExternalImports &&
constraint.bannedExternalImports &&
constraint.bannedExternalImports.length
) {
const matches = hasBannedDependencies(
transitiveExternalDeps,
projectGraph,
constraint,
imp
);
if (matches.length > 0) {
matches.forEach(([target, violatingSource, constraint]) => {
context.report({
node,
messageId: 'nestedBannedExternalImportsViolation',
data: {
sourceTag: isComboDepConstraint(constraint)
? constraint.allSourceTags.join('" and "')
: constraint.sourceTag,
childProjectName: violatingSource.name,
imp,
},
});
});
return;
}
}
}
}
}
return {
ImportDeclaration(node: TSESTree.ImportDeclaration) {
run(node);
},
ImportExpression(node: TSESTree.ImportExpression) {
run(node);
},
ExportAllDeclaration(node: TSESTree.ExportAllDeclaration) {
run(node);
},
ExportNamedDeclaration(node: TSESTree.ExportNamedDeclaration) {
run(node);
},
};
},
});