/
runtime-lint-utils.ts
365 lines (332 loc) · 10.3 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
import * as path from 'path';
import { FileData, readFileIfExisting } from '../core/file-utils';
import {
ProjectGraph,
ProjectGraphDependency,
ProjectGraphProjectNode,
normalizePath,
DependencyType,
parseJson,
ProjectGraphExternalNode,
joinPathFragments,
} from '@nrwl/devkit';
import { TargetProjectLocator } from '../core/target-project-locator';
import { join } from 'path';
import { appRootPath } from './app-root';
import { getPath, pathExists } from './graph-utils';
import { existsSync } from 'fs';
export type MappedProjectGraphNode<T = any> = ProjectGraphProjectNode<T> & {
data: {
files: Record<string, FileData>;
};
};
export type MappedProjectGraph<T = any> = ProjectGraph<T> & {
nodes: Record<string, MappedProjectGraphNode<T>>;
};
export type Deps = { [projectName: string]: ProjectGraphDependency[] };
export type DepConstraint = {
sourceTag: string;
onlyDependOnLibsWithTags: string[];
notDependOnLibsWithTags: string[];
bannedExternalImports?: string[];
};
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;
}
/**
* 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)
);
}
function hasTag(proj: ProjectGraphProjectNode, tag: string) {
return tag === '*' || (proj.data.tags || []).indexOf(tag) > -1;
}
function removeExt(file: string): string {
return file.replace(/(?<!(^|\/))\.[^/.]+$/, '');
}
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('.');
}
export function getTargetProjectBasedOnRelativeImport(
imp: string,
projectPath: string,
projectGraph: MappedProjectGraph,
sourceFilePath: string
): MappedProjectGraphNode<any> | undefined {
if (!isRelative(imp)) {
return undefined;
}
const targetFile = normalizePath(
path.resolve(path.join(projectPath, path.dirname(sourceFilePath)), imp)
).substring(projectPath.length + 1);
return findTargetProject(projectGraph, targetFile);
}
export function findProjectUsingFile<T>(
projectGraph: MappedProjectGraph<T>,
file: string
): MappedProjectGraphNode {
return Object.values(projectGraph.nodes).find((n) => n.data.files[file]);
}
export function findSourceProject(
projectGraph: MappedProjectGraph,
sourceFilePath: string
) {
const targetFile = removeExt(sourceFilePath);
return findProjectUsingFile(projectGraph, targetFile);
}
export function findTargetProject(
projectGraph: MappedProjectGraph,
targetFile: string
) {
let targetProject = findProjectUsingFile(projectGraph, targetFile);
if (!targetProject) {
targetProject = findProjectUsingFile(
projectGraph,
normalizePath(path.join(targetFile, 'index'))
);
}
if (!targetProject) {
targetProject = findProjectUsingFile(
projectGraph,
normalizePath(path.join(targetFile, 'src', 'index'))
);
}
return targetProject;
}
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: MappedProjectGraph,
targetProjectLocator: TargetProjectLocator,
filePath: string,
imp: string,
npmScope: string
): MappedProjectGraphNode | ProjectGraphExternalNode {
const target = targetProjectLocator.findProjectWithImport(
imp,
filePath,
npmScope
);
return projectGraph.nodes[target] || projectGraph.externalNodes?.[target];
}
export function findConstraintsFor(
depConstraints: DepConstraint[],
sourceProject: ProjectGraphProjectNode
) {
return depConstraints.filter((f) => 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) {
return normalizePath(sourceFileName).substring(projectPath.length + 1);
}
export function hasBannedImport(
source: ProjectGraphProjectNode,
target: ProjectGraphProjectNode | ProjectGraphExternalNode,
depConstraints: DepConstraint[]
): DepConstraint | null {
// return those constraints that match source projec and have `bannedExternalImports` defined
depConstraints = depConstraints.filter(
(c) =>
(source.data.tags || []).includes(c.sourceTag) &&
c.bannedExternalImports &&
c.bannedExternalImports.length
);
return depConstraints.find((constraint) =>
constraint.bannedExternalImports.some((importDefinition) =>
parseImportWildcards(importDefinition).test(target.data.packageName)
)
);
}
export function isDirectDependency(target: ProjectGraphExternalNode): boolean {
const fileName = 'package.json';
const content = readFileIfExisting(join(appRootPath, fileName));
if (content) {
const { dependencies, devDependencies, peerDependencies } =
parseJson(content);
if (dependencies && dependencies[target.data.packageName]) {
return true;
}
if (peerDependencies && peerDependencies[target.data.packageName]) {
return true;
}
if (devDependencies && devDependencies[target.data.packageName]) {
return true;
}
return false;
}
return true;
}
/**
* Maps import with wildcards to regex pattern
* @param importDefinition
* @returns
*/
function parseImportWildcards(importDefinition: string): RegExp {
const mappedWildcards = importDefinition.split('*').join('.*');
return new RegExp(`^${new RegExp(mappedWildcards).source}$`);
}
/**
* Verifies whether the given node has an architect builder attached
* @param projectGraph the node to verify
*/
export function hasBuildExecutor(
projectGraph: ProjectGraphProjectNode
): boolean {
return (
// can the architect not be defined? real use case?
projectGraph.data.targets &&
projectGraph.data.targets.build &&
projectGraph.data.targets.build.executor !== ''
);
}
export function mapProjectGraphFiles<T>(
projectGraph: ProjectGraph<T>
): MappedProjectGraph | null {
if (!projectGraph) {
return null;
}
const nodes: Record<string, MappedProjectGraphNode> = {};
Object.entries(
projectGraph.nodes as Record<string, ProjectGraphProjectNode>
).forEach(([name, node]) => {
const files: Record<string, FileData> = {};
node.data.files.forEach(({ file, hash, deps }) => {
files[removeExt(file)] = { file, hash, ...(deps && { deps }) };
});
const data = { ...node.data, files };
nodes[name] = { ...node, data };
});
return {
...projectGraph,
nodes,
};
}
export function isTerminalRun(): boolean {
return (
process.argv.length > 1 &&
!!process.argv[1].match(/@nrwl\/cli\/lib\/run-cli\.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(
targetProjectLocator: TargetProjectLocator,
importExpr: string
): boolean {
const targetFiles = targetProjectLocator.findPaths(importExpr);
return (
targetFiles &&
targetFiles.some(
(file) =>
file.endsWith('src/index.ts') &&
existsSync(joinPathFragments(file, '../../', 'ng-package.json'))
)
);
}