-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
runtime-lint-utils.ts
503 lines (458 loc) · 14.2 KB
/
runtime-lint-utils.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
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
import * as path from 'path';
import { join } from 'path';
import {
DependencyType,
joinPathFragments,
normalizePath,
parseJson,
ProjectGraph,
ProjectGraphDependency,
ProjectGraphExternalNode,
ProjectGraphProjectNode,
workspaceRoot,
} from '@nx/devkit';
import { getPath, pathExists } from './graph-utils';
import { readFileIfExisting } from 'nx/src/utils/fileutils';
import {
findProjectForPath,
ProjectRootMappings,
} from 'nx/src/project-graph/utils/find-project-for-path';
import { getRootTsConfigFileName } from '@nx/js';
import {
resolveModuleByImport,
TargetProjectLocator,
} from '@nx/js/src/internal';
export type Deps = { [projectName: string]: ProjectGraphDependency[] };
type SingleSourceTagConstraint = {
sourceTag: string;
onlyDependOnLibsWithTags?: string[];
notDependOnLibsWithTags?: string[];
allowedExternalImports?: string[];
bannedExternalImports?: string[];
};
type ComboSourceTagConstraint = {
allSourceTags: string[];
onlyDependOnLibsWithTags?: string[];
notDependOnLibsWithTags?: string[];
allowedExternalImports?: string[];
bannedExternalImports?: string[];
};
export type DepConstraint =
| SingleSourceTagConstraint
| ComboSourceTagConstraint;
export function stringifyTags(tags: string[]): string {
return tags.map((t) => `"${t}"`).join(', ');
}
export function hasNoneOfTheseTags(
proj: ProjectGraphProjectNode,
tags: string[]
): boolean {
return tags.filter((tag) => hasTag(proj, tag)).length === 0;
}
export function isComboDepConstraint(
depConstraint: DepConstraint
): depConstraint is ComboSourceTagConstraint {
return !!(depConstraint as ComboSourceTagConstraint).allSourceTags;
}
/**
* Check if any of the given tags is included in the project
* @param proj ProjectGraphProjectNode
* @param tags
* @returns
*/
export function findDependenciesWithTags(
targetProject: ProjectGraphProjectNode,
tags: string[],
graph: ProjectGraph
): ProjectGraphProjectNode[][] {
// find all reachable projects that have one of the tags and
// are reacheable from the targetProject (including self)
const allReachableProjects = Object.keys(graph.nodes).filter(
(projectName) =>
pathExists(graph, targetProject.name, projectName) &&
tags.some((tag) => hasTag(graph.nodes[projectName], tag))
);
// return path from targetProject to reachable project
return allReachableProjects.map((project) =>
targetProject.name === project
? [targetProject]
: getPath(graph, targetProject.name, project)
);
}
const regexMap = new Map<string, RegExp>();
function hasTag(proj: ProjectGraphProjectNode, tag: string): boolean {
if (tag === '*') return true;
// if the tag is a regex, check if the project matches the regex
if (tag.startsWith('/') && tag.endsWith('/')) {
let regex;
if (regexMap.has(tag)) {
regex = regexMap.get(tag);
} else {
regex = new RegExp(tag.substring(1, tag.length - 1));
regexMap.set(tag, regex);
}
return (proj.data.tags || []).some((t) => regex.test(t));
}
// if the tag is a glob, check if the project matches the glob prefix
if (tag.includes('*')) {
const regex = mapGlobToRegExp(tag);
return (proj.data.tags || []).some((t) => regex.test(t));
}
return (proj.data.tags || []).indexOf(tag) > -1;
}
export function matchImportWithWildcard(
// This may or may not contain wildcards ("*")
allowableImport: string,
extractedImport: string
): boolean {
if (allowableImport.endsWith('/**')) {
const prefix = allowableImport.substring(0, allowableImport.length - 2);
return extractedImport.startsWith(prefix);
} else if (allowableImport.endsWith('/*')) {
const prefix = allowableImport.substring(0, allowableImport.length - 1);
if (!extractedImport.startsWith(prefix)) return false;
return extractedImport.substring(prefix.length).indexOf('/') === -1;
} else if (allowableImport.indexOf('/**/') > -1) {
const [prefix, suffix] = allowableImport.split('/**/');
return (
extractedImport.startsWith(prefix) && extractedImport.endsWith(suffix)
);
} else {
return new RegExp(allowableImport).test(extractedImport);
}
}
export function isRelative(s: string) {
return s.startsWith('./') || s.startsWith('../');
}
export function getTargetProjectBasedOnRelativeImport(
imp: string,
projectPath: string,
projectGraph: ProjectGraph,
projectRootMappings: ProjectRootMappings,
sourceFilePath: string
): ProjectGraphProjectNode | undefined {
if (!isRelative(imp)) {
return undefined;
}
const sourceDir = path.join(projectPath, path.dirname(sourceFilePath));
const targetFile = normalizePath(path.resolve(sourceDir, imp)).substring(
projectPath.length + 1
);
return findProject(projectGraph, projectRootMappings, targetFile);
}
export function findProject(
projectGraph: ProjectGraph,
projectRootMappings: ProjectRootMappings,
sourceFilePath: string
) {
return projectGraph.nodes[
findProjectForPath(sourceFilePath, projectRootMappings)
];
}
export function isAbsoluteImportIntoAnotherProject(
imp: string,
workspaceLayout = { libsDir: 'libs', appsDir: 'apps' }
) {
return (
imp.startsWith(`${workspaceLayout.libsDir}/`) ||
imp.startsWith(`/${workspaceLayout.libsDir}/`) ||
imp.startsWith(`${workspaceLayout.appsDir}/`) ||
imp.startsWith(`/${workspaceLayout.appsDir}/`)
);
}
export function findProjectUsingImport(
projectGraph: ProjectGraph,
targetProjectLocator: TargetProjectLocator,
filePath: string,
imp: string
): ProjectGraphProjectNode | ProjectGraphExternalNode {
const target = targetProjectLocator.findProjectWithImport(imp, filePath);
return projectGraph.nodes[target] || projectGraph.externalNodes?.[target];
}
export function findConstraintsFor(
depConstraints: DepConstraint[],
sourceProject: ProjectGraphProjectNode
) {
return depConstraints.filter((f) => {
if (isComboDepConstraint(f)) {
return f.allSourceTags.every((tag) => hasTag(sourceProject, tag));
} else {
return hasTag(sourceProject, f.sourceTag);
}
});
}
export function onlyLoadChildren(
graph: ProjectGraph,
sourceProjectName: string,
targetProjectName: string,
visited: string[]
) {
if (visited.indexOf(sourceProjectName) > -1) return false;
return (
(graph.dependencies[sourceProjectName] || []).filter((d) => {
if (d.type !== DependencyType.dynamic) return false;
if (d.target === targetProjectName) return true;
return onlyLoadChildren(graph, d.target, targetProjectName, [
...visited,
sourceProjectName,
]);
}).length > 0
);
}
export function getSourceFilePath(sourceFileName: string, projectPath: string) {
const normalizedProjectPath = normalizePath(projectPath);
const normalizedSourceFileName = normalizePath(sourceFileName);
return normalizedSourceFileName.slice(normalizedProjectPath.length + 1);
}
/**
* Find constraint (if any) that explicitly banns the given target npm project
* @param externalProject
* @param depConstraints
* @returns
*/
function isConstraintBanningProject(
externalProject: ProjectGraphExternalNode,
constraint: DepConstraint,
imp: string
): boolean {
const { allowedExternalImports, bannedExternalImports } = constraint;
const { packageName } = externalProject.data;
if (imp !== packageName && !imp.startsWith(`${packageName}/`)) {
return false;
}
/* Check if import is banned... */
if (
bannedExternalImports?.some((importDefinition) =>
mapGlobToRegExp(importDefinition).test(imp)
)
) {
return true;
}
/* ... then check if there is a whitelist and if there is a match in the whitelist. */
return allowedExternalImports?.every(
(importDefinition) =>
!imp.startsWith(packageName) ||
!mapGlobToRegExp(importDefinition).test(imp)
);
}
export function hasBannedImport(
source: ProjectGraphProjectNode,
target: ProjectGraphExternalNode,
depConstraints: DepConstraint[],
imp: string
): DepConstraint | undefined {
// return those constraints that match source project
depConstraints = depConstraints.filter((c) => {
let tags = [];
if (isComboDepConstraint(c)) {
tags = c.allSourceTags;
} else {
tags = [c.sourceTag];
}
return tags.every((t) => hasTag(source, t));
});
return depConstraints.find((constraint) =>
isConstraintBanningProject(target, constraint, imp)
);
}
/**
* Find all unique (transitive) external dependencies of given project
* @param graph
* @param source
* @returns
*/
export function findTransitiveExternalDependencies(
graph: ProjectGraph,
source: ProjectGraphProjectNode
): ProjectGraphDependency[] {
if (!graph.externalNodes) {
return [];
}
const allReachableProjects = [];
const allProjects = Object.keys(graph.nodes);
for (let i = 0; i < allProjects.length; i++) {
if (pathExists(graph, source.name, allProjects[i])) {
allReachableProjects.push(allProjects[i]);
}
}
const externalDependencies = [];
for (let i = 0; i < allReachableProjects.length; i++) {
const dependencies = graph.dependencies[allReachableProjects[i]];
if (dependencies) {
for (let d = 0; d < dependencies.length; d++) {
const dependency = dependencies[d];
if (graph.externalNodes[dependency.target]) {
externalDependencies.push(dependency);
}
}
}
}
return externalDependencies;
}
/**
* Check if
* @param externalDependencies
* @param graph
* @param depConstraint
* @returns
*/
export function hasBannedDependencies(
externalDependencies: ProjectGraphDependency[],
graph: ProjectGraph,
depConstraint: DepConstraint,
imp: string
):
| Array<[ProjectGraphExternalNode, ProjectGraphProjectNode, DepConstraint]>
| undefined {
return externalDependencies
.filter((dependency) =>
isConstraintBanningProject(
graph.externalNodes[dependency.target],
depConstraint,
imp
)
)
.map((dep) => [
graph.externalNodes[dep.target],
graph.nodes[dep.source],
depConstraint,
]);
}
export function isDirectDependency(
source: ProjectGraphProjectNode,
target: ProjectGraphExternalNode
): boolean {
return (
packageExistsInPackageJson(target.data.packageName, '.') ||
packageExistsInPackageJson(target.data.packageName, source.data.root)
);
}
function packageExistsInPackageJson(
packageName: string,
projectRoot: string
): boolean {
const content = readFileIfExisting(
join(workspaceRoot, projectRoot, 'package.json')
);
if (content) {
const { dependencies, devDependencies, peerDependencies } =
parseJson(content);
if (dependencies && dependencies[packageName]) {
return true;
}
if (peerDependencies && peerDependencies[packageName]) {
return true;
}
if (devDependencies && devDependencies[packageName]) {
return true;
}
}
return false;
}
/**
* Maps import with wildcards to regex pattern
* @param importDefinition
* @returns
*/
function mapGlobToRegExp(importDefinition: string): RegExp {
// we replace all instances of `*`, `**..*` and `.*` with `.*`
const mappedWildcards = importDefinition.split(/(?:\.\*)|\*+/).join('.*');
return new RegExp(`^${new RegExp(mappedWildcards).source}$`);
}
/**
* Verifies whether the given node has a builder target
* @param projectGraph the node to verify
* @param buildTargets the list of targets to check for
*/
export function hasBuildExecutor(
projectGraph: ProjectGraphProjectNode,
buildTargets = ['build']
): boolean {
return (
projectGraph.data.targets &&
buildTargets.some(
(target) =>
projectGraph.data.targets[target] &&
projectGraph.data.targets[target].executor !== ''
)
);
}
const ESLINT_REGEX = /node_modules.*[\/\\]eslint$/;
const JEST_REGEX = /node_modules\/.bin\/jest$/; // when we run unit tests in jest
const NRWL_CLI_REGEX = /nx[\/\\]bin[\/\\]run-executor\.js$/;
export function isTerminalRun(): boolean {
return (
process.argv.length > 1 &&
(!!process.argv[1].match(NRWL_CLI_REGEX) ||
!!process.argv[1].match(JEST_REGEX) ||
!!process.argv[1].match(ESLINT_REGEX) ||
!!process.argv[1].endsWith('/bin/jest.js'))
);
}
/**
* Takes an array of imports and tries to group them, so rather than having
* `import { A } from './some-location'` and `import { B } from './some-location'` you get
* `import { A, B } from './some-location'`
* @param importsToRemap
* @returns
*/
export function groupImports(
importsToRemap: { member: string; importPath: string }[]
): string {
const importsToRemapGrouped = importsToRemap.reduce((acc, curr) => {
const existing = acc.find(
(i) => i.importPath === curr.importPath && i.member !== curr.member
);
if (existing) {
if (existing.member) {
existing.member += `, ${curr.member}`;
}
} else {
acc.push({
importPath: curr.importPath,
member: curr.member,
});
}
return acc;
}, []);
return importsToRemapGrouped
.map((entry) => `import { ${entry.member} } from '${entry.importPath}';`)
.join('\n');
}
/**
* Checks if import points to a secondary entry point in Angular project
* @param targetProjectLocator
* @param importExpr
* @returns
*/
export function isAngularSecondaryEntrypoint(
importExpr: string,
filePath: string,
projectRoot: string
): boolean {
const resolvedModule = resolveModuleByImport(
importExpr,
filePath,
join(workspaceRoot, getRootTsConfigFileName())
);
return (
!!resolvedModule && fileIsSecondaryEntryPoint(resolvedModule, projectRoot)
);
}
function fileIsSecondaryEntryPoint(file: string, projectRoot: string): boolean {
let parent = joinPathFragments(file, '../');
while (parent !== `${projectRoot}/`) {
// we need to find closest existing ng-package.json
// in order to determine if the file matches the secondary entry point
const ngPackageContent = readFileIfExisting(
joinPathFragments(workspaceRoot, parent, 'ng-package.json')
);
if (ngPackageContent) {
// https://github.com/ng-packagr/ng-packagr/blob/23c718d04eea85e015b4c261310b7bd0c39e5311/src/ng-package.schema.json#L54
const entryFile = parseJson(ngPackageContent)?.lib?.entryFile;
return entryFile && file === joinPathFragments(parent, entryFile);
}
parent = joinPathFragments(parent, '../');
}
return false;
}