@abp/ng.schematics 5.0.1 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +3 -3
  2. package/collection.json +29 -29
  3. package/commands/api/files-enum/proxy/__namespace@dir__/__name@kebab__.enum.ts.template +8 -8
  4. package/commands/api/files-model/proxy/__namespace@dir__/models.ts.template +9 -9
  5. package/commands/api/files-service/proxy/__namespace@dir__/__name@kebab__.service.ts.template +25 -25
  6. package/commands/api/index.d.ts +2 -2
  7. package/commands/api/index.js +112 -112
  8. package/commands/api/schema.json +45 -45
  9. package/commands/proxy-add/index.d.ts +2 -2
  10. package/commands/proxy-add/index.js +41 -41
  11. package/commands/proxy-add/schema.json +45 -45
  12. package/commands/proxy-index/index.d.ts +4 -4
  13. package/commands/proxy-index/index.js +14 -14
  14. package/commands/proxy-index/schema.json +18 -18
  15. package/commands/proxy-refresh/index.d.ts +3 -3
  16. package/commands/proxy-refresh/index.js +27 -27
  17. package/commands/proxy-refresh/schema.json +45 -45
  18. package/commands/proxy-remove/index.d.ts +3 -3
  19. package/commands/proxy-remove/index.js +33 -33
  20. package/commands/proxy-remove/schema.json +45 -45
  21. package/constants/api.d.ts +1 -1
  22. package/constants/api.js +4 -4
  23. package/constants/index.d.ts +4 -4
  24. package/constants/index.js +16 -16
  25. package/constants/proxy.d.ts +4 -4
  26. package/constants/proxy.js +24 -24
  27. package/constants/system-types.d.ts +1 -1
  28. package/constants/system-types.js +27 -27
  29. package/constants/volo.d.ts +1 -1
  30. package/constants/volo.js +4 -4
  31. package/enums/binding-source-id.d.ts +6 -6
  32. package/enums/binding-source-id.js +10 -10
  33. package/enums/exception.d.ts +16 -16
  34. package/enums/exception.js +2 -2
  35. package/enums/import-keyword.d.ts +4 -4
  36. package/enums/import-keyword.js +8 -8
  37. package/enums/index.d.ts +4 -4
  38. package/enums/index.js +16 -16
  39. package/enums/method-modifier.d.ts +6 -6
  40. package/enums/method-modifier.js +10 -10
  41. package/index.d.ts +1 -1
  42. package/index.js +2 -2
  43. package/models/api-definition.d.ts +72 -72
  44. package/models/api-definition.js +2 -2
  45. package/models/generate-proxy-schema.d.ts +18 -18
  46. package/models/generate-proxy-schema.js +2 -2
  47. package/models/import.d.ts +11 -11
  48. package/models/import.js +13 -13
  49. package/models/index.d.ts +10 -10
  50. package/models/index.js +22 -22
  51. package/models/method.d.ts +31 -31
  52. package/models/method.js +61 -61
  53. package/models/model.d.ts +48 -48
  54. package/models/model.js +71 -71
  55. package/models/project.d.ts +5 -5
  56. package/models/project.js +2 -2
  57. package/models/proxy-config.d.ts +4 -4
  58. package/models/proxy-config.js +2 -2
  59. package/models/service.d.ts +21 -21
  60. package/models/service.js +11 -11
  61. package/models/tree.d.ts +1 -1
  62. package/models/tree.js +2 -2
  63. package/models/util.d.ts +7 -7
  64. package/models/util.js +2 -2
  65. package/package.json +1 -1
  66. package/test-setup.d.ts +1 -1
  67. package/test-setup.js +3 -3
  68. package/utils/angular/ast-utils.d.ts +115 -115
  69. package/utils/angular/ast-utils.js +598 -598
  70. package/utils/angular/change.d.ts +66 -66
  71. package/utils/angular/change.js +96 -96
  72. package/utils/angular/config.d.ts +455 -455
  73. package/utils/angular/config.js +70 -70
  74. package/utils/angular/dependencies.d.ts +23 -23
  75. package/utils/angular/dependencies.js +58 -58
  76. package/utils/angular/find-module.d.ts +35 -35
  77. package/utils/angular/find-module.js +105 -105
  78. package/utils/angular/index.d.ts +17 -17
  79. package/utils/angular/index.js +29 -29
  80. package/utils/angular/json-file.d.ts +23 -23
  81. package/utils/angular/json-file.js +61 -61
  82. package/utils/angular/json-utils.d.ts +14 -14
  83. package/utils/angular/json-utils.js +158 -158
  84. package/utils/angular/latest-versions.d.ts +18 -18
  85. package/utils/angular/latest-versions.js +26 -26
  86. package/utils/angular/lint-fix.d.ts +9 -9
  87. package/utils/angular/lint-fix.js +41 -41
  88. package/utils/angular/ng-ast-utils.d.ts +5 -5
  89. package/utils/angular/ng-ast-utils.js +75 -75
  90. package/utils/angular/parse-name.d.ts +13 -13
  91. package/utils/angular/parse-name.js +21 -21
  92. package/utils/angular/paths.d.ts +8 -8
  93. package/utils/angular/paths.js +21 -21
  94. package/utils/angular/project-targets.d.ts +9 -9
  95. package/utils/angular/project-targets.js +15 -15
  96. package/utils/angular/tsconfig.d.ts +16 -16
  97. package/utils/angular/tsconfig.js +62 -62
  98. package/utils/angular/validation.d.ts +4 -4
  99. package/utils/angular/validation.js +73 -73
  100. package/utils/angular/workspace-models.d.ts +159 -159
  101. package/utils/angular/workspace-models.js +29 -29
  102. package/utils/angular/workspace.d.ts +18 -18
  103. package/utils/angular/workspace.js +75 -75
  104. package/utils/api.d.ts +2 -2
  105. package/utils/api.js +8 -8
  106. package/utils/ast.d.ts +4 -4
  107. package/utils/ast.js +23 -23
  108. package/utils/barrel.d.ts +4 -4
  109. package/utils/barrel.js +92 -92
  110. package/utils/common.d.ts +6 -6
  111. package/utils/common.js +33 -33
  112. package/utils/enum.d.ts +18 -18
  113. package/utils/enum.js +40 -40
  114. package/utils/file.d.ts +2 -2
  115. package/utils/file.js +9 -9
  116. package/utils/generics.d.ts +24 -24
  117. package/utils/generics.js +87 -87
  118. package/utils/import.d.ts +3 -3
  119. package/utils/import.js +11 -11
  120. package/utils/index.d.ts +19 -19
  121. package/utils/index.js +31 -31
  122. package/utils/model.d.ts +11 -11
  123. package/utils/model.js +141 -141
  124. package/utils/namespace.d.ts +1 -1
  125. package/utils/namespace.js +18 -18
  126. package/utils/path.d.ts +2 -2
  127. package/utils/path.js +36 -36
  128. package/utils/rule.d.ts +4 -4
  129. package/utils/rule.js +27 -27
  130. package/utils/service.d.ts +6 -6
  131. package/utils/service.js +82 -82
  132. package/utils/source.d.ts +13 -13
  133. package/utils/source.js +162 -162
  134. package/utils/text.d.ts +9 -9
  135. package/utils/text.js +46 -46
  136. package/utils/tree.d.ts +13 -13
  137. package/utils/tree.js +56 -56
  138. package/utils/type.d.ts +12 -12
  139. package/utils/type.js +102 -102
  140. package/utils/workspace.d.ts +8 -8
  141. package/utils/workspace.js +66 -66
@@ -1,599 +1,599 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.addRouteDeclarationToModule = exports.getRouterModuleDeclaration = exports.getEnvironmentExportName = exports.isImported = exports.addEntryComponentToModule = exports.addBootstrapToModule = exports.addExportToModule = exports.addProviderToModule = exports.addImportToModule = exports.addDeclarationToModule = exports.addSymbolToNgModuleMetadata = exports.getMetadataField = exports.getFirstNgModuleName = exports.getDecoratorMetadata = exports.getContentOfKeyLiteral = exports.insertAfterLastOccurrence = exports.findNode = exports.getSourceNodes = exports.findNodes = exports.insertImport = void 0;
4
- /**
5
- * @license
6
- * Copyright Google Inc. All Rights Reserved.
7
- *
8
- * Use of this source code is governed by an MIT-style license that can be
9
- * found in the LICENSE file at https://angular.io/license
10
- */
11
- const ts = require("typescript");
12
- const change_1 = require("./change");
13
- /**
14
- * Add Import `import { symbolName } from fileName` if the import doesn't exit
15
- * already. Assumes fileToEdit can be resolved and accessed.
16
- * @param fileToEdit (file we want to add import to)
17
- * @param symbolName (item to import)
18
- * @param fileName (path to the file)
19
- * @param isDefault (if true, import follows style for importing default exports)
20
- * @return Change
21
- */
22
- function insertImport(source, fileToEdit, symbolName, fileName, isDefault = false) {
23
- const rootNode = source;
24
- const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
25
- // get nodes that map to import statements from the file fileName
26
- const relevantImports = allImports.filter(node => {
27
- // StringLiteral of the ImportDeclaration is the import file (fileName in this case).
28
- const importFiles = node
29
- .getChildren()
30
- .filter(ts.isStringLiteral)
31
- .map(n => n.text);
32
- return importFiles.filter(file => file === fileName).length === 1;
33
- });
34
- if (relevantImports.length > 0) {
35
- let importsAsterisk = false;
36
- // imports from import file
37
- const imports = [];
38
- relevantImports.forEach(n => {
39
- Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier));
40
- if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) {
41
- importsAsterisk = true;
42
- }
43
- });
44
- // if imports * from fileName, don't add symbolName
45
- if (importsAsterisk) {
46
- return new change_1.NoopChange();
47
- }
48
- const importTextNodes = imports.filter(n => n.text === symbolName);
49
- // insert import if it's not there
50
- if (importTextNodes.length === 0) {
51
- const fallbackPos = findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
52
- findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();
53
- return insertAfterLastOccurrence(imports, `, ${symbolName}`, fileToEdit, fallbackPos);
54
- }
55
- return new change_1.NoopChange();
56
- }
57
- // no such import declaration exists
58
- const useStrict = findNodes(rootNode, ts.isStringLiteral).filter(n => n.text === 'use strict');
59
- let fallbackPos = 0;
60
- if (useStrict.length > 0) {
61
- fallbackPos = useStrict[0].end;
62
- }
63
- const open = isDefault ? '' : '{ ';
64
- const close = isDefault ? '' : ' }';
65
- // if there are no imports or 'use strict' statement, insert import at beginning of file
66
- const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
67
- const separator = insertAtBeginning ? '' : ';\n';
68
- const toInsert = `${separator}import ${open}${symbolName}${close}` +
69
- ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`;
70
- return insertAfterLastOccurrence(allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral);
71
- }
72
- exports.insertImport = insertImport;
73
- function findNodes(node, kindOrGuard, max = Infinity, recursive = false) {
74
- if (!node || max == 0) {
75
- return [];
76
- }
77
- const test = typeof kindOrGuard === 'function'
78
- ? kindOrGuard
79
- : (node) => node.kind === kindOrGuard;
80
- const arr = [];
81
- if (test(node)) {
82
- arr.push(node);
83
- max--;
84
- }
85
- if (max > 0 && (recursive || !test(node))) {
86
- for (const child of node.getChildren()) {
87
- findNodes(child, test, max).forEach(node => {
88
- if (max > 0) {
89
- arr.push(node);
90
- }
91
- max--;
92
- });
93
- if (max <= 0) {
94
- break;
95
- }
96
- }
97
- }
98
- return arr;
99
- }
100
- exports.findNodes = findNodes;
101
- /**
102
- * Get all the nodes from a source.
103
- * @param sourceFile The source file object.
104
- * @returns {Array<ts.Node>} An array of all the nodes in the source.
105
- */
106
- function getSourceNodes(sourceFile) {
107
- const nodes = [sourceFile];
108
- const result = [];
109
- while (nodes.length > 0) {
110
- const node = nodes.shift();
111
- if (node) {
112
- result.push(node);
113
- if (node.getChildCount(sourceFile) >= 0) {
114
- nodes.unshift(...node.getChildren());
115
- }
116
- }
117
- }
118
- return result;
119
- }
120
- exports.getSourceNodes = getSourceNodes;
121
- function findNode(node, kind, text) {
122
- if (node.kind === kind && node.getText() === text) {
123
- // throw new Error(node.getText());
124
- return node;
125
- }
126
- let foundNode = null;
127
- ts.forEachChild(node, childNode => {
128
- foundNode = foundNode || findNode(childNode, kind, text);
129
- });
130
- return foundNode;
131
- }
132
- exports.findNode = findNode;
133
- /**
134
- * Helper for sorting nodes.
135
- * @return function to sort nodes in increasing order of position in sourceFile
136
- */
137
- function nodesByPosition(first, second) {
138
- return first.getStart() - second.getStart();
139
- }
140
- /**
141
- * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
142
- * or after the last of occurence of `syntaxKind` if the last occurence is a sub child
143
- * of ts.SyntaxKind[nodes[i].kind] and save the changes in file.
144
- *
145
- * @param nodes insert after the last occurence of nodes
146
- * @param toInsert string to insert
147
- * @param file file to insert changes into
148
- * @param fallbackPos position to insert if toInsert happens to be the first occurence
149
- * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after
150
- * @return Change instance
151
- * @throw Error if toInsert is first occurence but fall back is not set
152
- */
153
- function insertAfterLastOccurrence(nodes, toInsert, file, fallbackPos, syntaxKind) {
154
- let lastItem;
155
- for (const node of nodes) {
156
- if (!lastItem || lastItem.getStart() < node.getStart()) {
157
- lastItem = node;
158
- }
159
- }
160
- if (syntaxKind && lastItem) {
161
- lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop();
162
- }
163
- if (!lastItem && fallbackPos == undefined) {
164
- throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`);
165
- }
166
- const lastItemPosition = lastItem ? lastItem.getEnd() : fallbackPos;
167
- return new change_1.InsertChange(file, lastItemPosition, toInsert);
168
- }
169
- exports.insertAfterLastOccurrence = insertAfterLastOccurrence;
170
- function getContentOfKeyLiteral(_source, node) {
171
- if (node.kind == ts.SyntaxKind.Identifier) {
172
- return node.text;
173
- }
174
- else if (node.kind == ts.SyntaxKind.StringLiteral) {
175
- return node.text;
176
- }
177
- else {
178
- return null;
179
- }
180
- }
181
- exports.getContentOfKeyLiteral = getContentOfKeyLiteral;
182
- function _angularImportsFromNode(node, _sourceFile) {
183
- const ms = node.moduleSpecifier;
184
- let modulePath;
185
- switch (ms.kind) {
186
- case ts.SyntaxKind.StringLiteral:
187
- modulePath = ms.text;
188
- break;
189
- default:
190
- return {};
191
- }
192
- if (!modulePath.startsWith('@angular/')) {
193
- return {};
194
- }
195
- if (node.importClause) {
196
- if (node.importClause.name) {
197
- // This is of the form `import Name from 'path'`. Ignore.
198
- return {};
199
- }
200
- else if (node.importClause.namedBindings) {
201
- const nb = node.importClause.namedBindings;
202
- if (nb.kind == ts.SyntaxKind.NamespaceImport) {
203
- // This is of the form `import * as name from 'path'`. Return `name.`.
204
- return {
205
- [nb.name.text + '.']: modulePath,
206
- };
207
- }
208
- else {
209
- // This is of the form `import {a,b,c} from 'path'`
210
- const namedImports = nb;
211
- return namedImports.elements
212
- .map((is) => (is.propertyName ? is.propertyName.text : is.name.text))
213
- .reduce((acc, curr) => {
214
- acc[curr] = modulePath;
215
- return acc;
216
- }, {});
217
- }
218
- }
219
- return {};
220
- }
221
- else {
222
- // This is of the form `import 'path';`. Nothing to do.
223
- return {};
224
- }
225
- }
226
- function getDecoratorMetadata(source, identifier, module) {
227
- const angularImports = findNodes(source, ts.isImportDeclaration)
228
- .map(node => _angularImportsFromNode(node, source))
229
- .reduce((acc, current) => {
230
- for (const key of Object.keys(current)) {
231
- acc[key] = current[key];
232
- }
233
- return acc;
234
- }, {});
235
- return getSourceNodes(source)
236
- .filter(node => {
237
- return (node.kind == ts.SyntaxKind.Decorator &&
238
- node.expression.kind == ts.SyntaxKind.CallExpression);
239
- })
240
- .map(node => node.expression)
241
- .filter(expr => {
242
- if (expr.expression.kind == ts.SyntaxKind.Identifier) {
243
- const id = expr.expression;
244
- return id.text == identifier && angularImports[id.text] === module;
245
- }
246
- else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
247
- // This covers foo.NgModule when importing * as foo.
248
- const paExpr = expr.expression;
249
- // If the left expression is not an identifier, just give up at that point.
250
- if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
251
- return false;
252
- }
253
- const id = paExpr.name.text;
254
- const moduleId = paExpr.expression.text;
255
- return id === identifier && angularImports[moduleId + '.'] === module;
256
- }
257
- return false;
258
- })
259
- .filter(expr => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
260
- .map(expr => expr.arguments[0]);
261
- }
262
- exports.getDecoratorMetadata = getDecoratorMetadata;
263
- function findClassDeclarationParent(node) {
264
- if (ts.isClassDeclaration(node)) {
265
- return node;
266
- }
267
- return node.parent && findClassDeclarationParent(node.parent);
268
- }
269
- /**
270
- * Given a source file with @NgModule class(es), find the name of the first @NgModule class.
271
- *
272
- * @param source source file containing one or more @NgModule
273
- * @returns the name of the first @NgModule, or `undefined` if none is found
274
- */
275
- function getFirstNgModuleName(source) {
276
- // First, find the @NgModule decorators.
277
- const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core');
278
- if (ngModulesMetadata.length === 0) {
279
- return undefined;
280
- }
281
- // Then walk parent pointers up the AST, looking for the ClassDeclaration parent of the NgModule
282
- // metadata.
283
- const moduleClass = findClassDeclarationParent(ngModulesMetadata[0]);
284
- if (!moduleClass || !moduleClass.name) {
285
- return undefined;
286
- }
287
- // Get the class name of the module ClassDeclaration.
288
- return moduleClass.name.text;
289
- }
290
- exports.getFirstNgModuleName = getFirstNgModuleName;
291
- function getMetadataField(node, metadataField) {
292
- return (node.properties
293
- .filter(ts.isPropertyAssignment)
294
- // Filter out every fields that's not "metadataField". Also handles string literals
295
- // (but not expressions).
296
- .filter(({ name }) => {
297
- return ((ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.getText() === metadataField);
298
- }));
299
- }
300
- exports.getMetadataField = getMetadataField;
301
- function addSymbolToNgModuleMetadata(source, ngModulePath, metadataField, symbolName, importPath = null) {
302
- const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
303
- let node = nodes[0];
304
- // Find the decorator declaration.
305
- if (!node) {
306
- return [];
307
- }
308
- // Get all the children property assignment of object literals.
309
- const matchingProperties = getMetadataField(node, metadataField);
310
- // Get the last node of the array literal.
311
- if (!matchingProperties) {
312
- return [];
313
- }
314
- if (matchingProperties.length == 0) {
315
- // We haven't found the field in the metadata declaration. Insert a new field.
316
- const expr = node;
317
- let position;
318
- let toInsert;
319
- if (expr.properties.length == 0) {
320
- position = expr.getEnd() - 1;
321
- toInsert = ` ${metadataField}: [${symbolName}]\n`;
322
- }
323
- else {
324
- node = expr.properties[expr.properties.length - 1];
325
- position = node.getEnd();
326
- // Get the indentation of the last element, if any.
327
- const text = node.getFullText(source);
328
- const matches = text.match(/^\r?\n\s*/);
329
- if (matches && matches.length > 0) {
330
- toInsert = `,${matches[0]}${metadataField}: [${symbolName}]`;
331
- }
332
- else {
333
- toInsert = `, ${metadataField}: [${symbolName}]`;
334
- }
335
- }
336
- if (importPath !== null) {
337
- return [
338
- new change_1.InsertChange(ngModulePath, position, toInsert),
339
- insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
340
- ];
341
- }
342
- else {
343
- return [new change_1.InsertChange(ngModulePath, position, toInsert)];
344
- }
345
- }
346
- const assignment = matchingProperties[0];
347
- // If it's not an array, nothing we can do really.
348
- if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
349
- return [];
350
- }
351
- const arrLiteral = assignment.initializer;
352
- if (arrLiteral.elements.length == 0) {
353
- // Forward the property.
354
- node = arrLiteral;
355
- }
356
- else {
357
- node = arrLiteral.elements;
358
- }
359
- if (!node) {
360
- console.error('No app module found. Please add your new class to your component.');
361
- return [];
362
- }
363
- if (Array.isArray(node)) {
364
- // eslint-disable-next-line @typescript-eslint/ban-types
365
- const nodeArray = node;
366
- const symbolsArray = nodeArray.map(node => node.getText());
367
- if (symbolsArray.includes(symbolName)) {
368
- return [];
369
- }
370
- node = node[node.length - 1];
371
- }
372
- let toInsert;
373
- let position = node.getEnd();
374
- if (node.kind == ts.SyntaxKind.ObjectLiteralExpression) {
375
- // We haven't found the field in the metadata declaration. Insert a new
376
- // field.
377
- const expr = node;
378
- if (expr.properties.length == 0) {
379
- position = expr.getEnd() - 1;
380
- toInsert = ` ${symbolName}\n`;
381
- }
382
- else {
383
- // Get the indentation of the last element, if any.
384
- const text = node.getFullText(source);
385
- if (text.match(/^\r?\r?\n/)) {
386
- toInsert = `,${text.match(/^\r?\n\s*/)[0]}${symbolName}`;
387
- }
388
- else {
389
- toInsert = `, ${symbolName}`;
390
- }
391
- }
392
- }
393
- else if (node.kind == ts.SyntaxKind.ArrayLiteralExpression) {
394
- // We found the field but it's empty. Insert it just before the `]`.
395
- position--;
396
- toInsert = `${symbolName}`;
397
- }
398
- else {
399
- // Get the indentation of the last element, if any.
400
- const text = node.getFullText(source);
401
- if (text.match(/^\r?\n/)) {
402
- toInsert = `,${text.match(/^\r?\n(\r?)\s*/)[0]}${symbolName}`;
403
- }
404
- else {
405
- toInsert = `, ${symbolName}`;
406
- }
407
- }
408
- if (importPath !== null) {
409
- return [
410
- new change_1.InsertChange(ngModulePath, position, toInsert),
411
- insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
412
- ];
413
- }
414
- return [new change_1.InsertChange(ngModulePath, position, toInsert)];
415
- }
416
- exports.addSymbolToNgModuleMetadata = addSymbolToNgModuleMetadata;
417
- /**
418
- * Custom function to insert a declaration (component, pipe, directive)
419
- * into NgModule declarations. It also imports the component.
420
- */
421
- function addDeclarationToModule(source, modulePath, classifiedName, importPath) {
422
- return addSymbolToNgModuleMetadata(source, modulePath, 'declarations', classifiedName, importPath);
423
- }
424
- exports.addDeclarationToModule = addDeclarationToModule;
425
- /**
426
- * Custom function to insert an NgModule into NgModule imports. It also imports the module.
427
- */
428
- function addImportToModule(source, modulePath, classifiedName, importPath) {
429
- return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
430
- }
431
- exports.addImportToModule = addImportToModule;
432
- /**
433
- * Custom function to insert a provider into NgModule. It also imports it.
434
- */
435
- function addProviderToModule(source, modulePath, classifiedName, importPath) {
436
- return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
437
- }
438
- exports.addProviderToModule = addProviderToModule;
439
- /**
440
- * Custom function to insert an export into NgModule. It also imports it.
441
- */
442
- function addExportToModule(source, modulePath, classifiedName, importPath) {
443
- return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
444
- }
445
- exports.addExportToModule = addExportToModule;
446
- /**
447
- * Custom function to insert an export into NgModule. It also imports it.
448
- */
449
- function addBootstrapToModule(source, modulePath, classifiedName, importPath) {
450
- return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
451
- }
452
- exports.addBootstrapToModule = addBootstrapToModule;
453
- /**
454
- * Custom function to insert an entryComponent into NgModule. It also imports it.
455
- * @deprecated - Since version 9.0.0 with Ivy, entryComponents is no longer necessary.
456
- */
457
- function addEntryComponentToModule(source, modulePath, classifiedName, importPath) {
458
- return addSymbolToNgModuleMetadata(source, modulePath, 'entryComponents', classifiedName, importPath);
459
- }
460
- exports.addEntryComponentToModule = addEntryComponentToModule;
461
- /**
462
- * Determine if an import already exists.
463
- */
464
- function isImported(source, classifiedName, importPath) {
465
- const allNodes = getSourceNodes(source);
466
- const matchingNodes = allNodes
467
- .filter(ts.isImportDeclaration)
468
- .filter(imp => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath)
469
- .filter(imp => {
470
- if (!imp.importClause) {
471
- return false;
472
- }
473
- const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter(n => n.getText() === classifiedName);
474
- return nodes.length > 0;
475
- });
476
- return matchingNodes.length > 0;
477
- }
478
- exports.isImported = isImported;
479
- /**
480
- * This function returns the name of the environment export
481
- * whether this export is aliased or not. If the environment file
482
- * is not imported, then it will return `null`.
483
- */
484
- function getEnvironmentExportName(source) {
485
- // Initial value is `null` as we don't know yet if the user
486
- // has imported `environment` into the root module or not.
487
- let environmentExportName = null;
488
- const allNodes = getSourceNodes(source);
489
- allNodes
490
- .filter(ts.isImportDeclaration)
491
- .filter(declaration => declaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral &&
492
- declaration.importClause !== undefined)
493
- .map(declaration =>
494
- // If `importClause` property is defined then the first
495
- // child will be `NamedImports` object (or `namedBindings`).
496
- declaration.importClause.getChildAt(0))
497
- // Find those `NamedImports` object that contains `environment` keyword
498
- // in its text. E.g. `{ environment as env }`.
499
- .filter(ts.isNamedImports)
500
- .filter(namedImports => namedImports.getText().includes('environment'))
501
- .forEach(namedImports => {
502
- for (const specifier of namedImports.elements) {
503
- // `propertyName` is defined if the specifier
504
- // has an aliased import.
505
- const name = specifier.propertyName || specifier.name;
506
- // Find specifier that contains `environment` keyword in its text.
507
- // Whether it's `environment` or `environment as env`.
508
- if (name.text.includes('environment')) {
509
- environmentExportName = specifier.name.text;
510
- }
511
- }
512
- });
513
- return environmentExportName;
514
- }
515
- exports.getEnvironmentExportName = getEnvironmentExportName;
516
- /**
517
- * Returns the RouterModule declaration from NgModule metadata, if any.
518
- */
519
- function getRouterModuleDeclaration(source) {
520
- const result = getDecoratorMetadata(source, 'NgModule', '@angular/core');
521
- const node = result[0];
522
- const matchingProperties = getMetadataField(node, 'imports');
523
- if (!matchingProperties) {
524
- return;
525
- }
526
- const assignment = matchingProperties[0];
527
- if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
528
- return;
529
- }
530
- const arrLiteral = assignment.initializer;
531
- return arrLiteral.elements
532
- .filter(el => el.kind === ts.SyntaxKind.CallExpression)
533
- .find(el => el.getText().startsWith('RouterModule'));
534
- }
535
- exports.getRouterModuleDeclaration = getRouterModuleDeclaration;
536
- /**
537
- * Adds a new route declaration to a router module (i.e. has a RouterModule declaration)
538
- */
539
- function addRouteDeclarationToModule(source, fileToAdd, routeLiteral) {
540
- const routerModuleExpr = getRouterModuleDeclaration(source);
541
- if (!routerModuleExpr) {
542
- throw new Error(`Couldn't find a route declaration in ${fileToAdd}.`);
543
- }
544
- const scopeConfigMethodArgs = routerModuleExpr.arguments;
545
- if (!scopeConfigMethodArgs.length) {
546
- const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart());
547
- throw new Error(`The router module method doesn't have arguments ` + `at line ${line} in ${fileToAdd}`);
548
- }
549
- let routesArr;
550
- const routesArg = scopeConfigMethodArgs[0];
551
- // Check if the route declarations array is
552
- // an inlined argument of RouterModule or a standalone variable
553
- if (ts.isArrayLiteralExpression(routesArg)) {
554
- routesArr = routesArg;
555
- }
556
- else {
557
- const routesVarName = routesArg.getText();
558
- let routesVar;
559
- if (routesArg.kind === ts.SyntaxKind.Identifier) {
560
- routesVar = source.statements.filter(ts.isVariableStatement).find(v => {
561
- return v.declarationList.declarations[0].name.getText() === routesVarName;
562
- });
563
- }
564
- if (!routesVar) {
565
- const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart());
566
- throw new Error(`No route declaration array was found that corresponds ` +
567
- `to router module at line ${line} in ${fileToAdd}`);
568
- }
569
- routesArr = findNodes(routesVar, ts.SyntaxKind.ArrayLiteralExpression, 1)[0];
570
- }
571
- const occurrencesCount = routesArr.elements.length;
572
- const text = routesArr.getFullText(source);
573
- let route = routeLiteral;
574
- let insertPos = routesArr.elements.pos;
575
- if (occurrencesCount > 0) {
576
- const lastRouteLiteral = [...routesArr.elements].pop();
577
- const lastRouteIsWildcard = ts.isObjectLiteralExpression(lastRouteLiteral) &&
578
- lastRouteLiteral.properties.some(n => ts.isPropertyAssignment(n) &&
579
- ts.isIdentifier(n.name) &&
580
- n.name.text === 'path' &&
581
- ts.isStringLiteral(n.initializer) &&
582
- n.initializer.text === '**');
583
- const indentation = text.match(/\r?\n(\r?)\s*/) || [];
584
- const routeText = `${indentation[0] || ' '}${routeLiteral}`;
585
- // Add the new route before the wildcard route
586
- // otherwise we'll always redirect to the wildcard route
587
- if (lastRouteIsWildcard) {
588
- insertPos = lastRouteLiteral.pos;
589
- route = `${routeText},`;
590
- }
591
- else {
592
- insertPos = lastRouteLiteral.end;
593
- route = `,${routeText}`;
594
- }
595
- }
596
- return new change_1.InsertChange(fileToAdd, insertPos, route);
597
- }
598
- exports.addRouteDeclarationToModule = addRouteDeclarationToModule;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addRouteDeclarationToModule = exports.getRouterModuleDeclaration = exports.getEnvironmentExportName = exports.isImported = exports.addEntryComponentToModule = exports.addBootstrapToModule = exports.addExportToModule = exports.addProviderToModule = exports.addImportToModule = exports.addDeclarationToModule = exports.addSymbolToNgModuleMetadata = exports.getMetadataField = exports.getFirstNgModuleName = exports.getDecoratorMetadata = exports.getContentOfKeyLiteral = exports.insertAfterLastOccurrence = exports.findNode = exports.getSourceNodes = exports.findNodes = exports.insertImport = void 0;
4
+ /**
5
+ * @license
6
+ * Copyright Google Inc. All Rights Reserved.
7
+ *
8
+ * Use of this source code is governed by an MIT-style license that can be
9
+ * found in the LICENSE file at https://angular.io/license
10
+ */
11
+ const ts = require("typescript");
12
+ const change_1 = require("./change");
13
+ /**
14
+ * Add Import `import { symbolName } from fileName` if the import doesn't exit
15
+ * already. Assumes fileToEdit can be resolved and accessed.
16
+ * @param fileToEdit (file we want to add import to)
17
+ * @param symbolName (item to import)
18
+ * @param fileName (path to the file)
19
+ * @param isDefault (if true, import follows style for importing default exports)
20
+ * @return Change
21
+ */
22
+ function insertImport(source, fileToEdit, symbolName, fileName, isDefault = false) {
23
+ const rootNode = source;
24
+ const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
25
+ // get nodes that map to import statements from the file fileName
26
+ const relevantImports = allImports.filter(node => {
27
+ // StringLiteral of the ImportDeclaration is the import file (fileName in this case).
28
+ const importFiles = node
29
+ .getChildren()
30
+ .filter(ts.isStringLiteral)
31
+ .map(n => n.text);
32
+ return importFiles.filter(file => file === fileName).length === 1;
33
+ });
34
+ if (relevantImports.length > 0) {
35
+ let importsAsterisk = false;
36
+ // imports from import file
37
+ const imports = [];
38
+ relevantImports.forEach(n => {
39
+ Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier));
40
+ if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) {
41
+ importsAsterisk = true;
42
+ }
43
+ });
44
+ // if imports * from fileName, don't add symbolName
45
+ if (importsAsterisk) {
46
+ return new change_1.NoopChange();
47
+ }
48
+ const importTextNodes = imports.filter(n => n.text === symbolName);
49
+ // insert import if it's not there
50
+ if (importTextNodes.length === 0) {
51
+ const fallbackPos = findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
52
+ findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();
53
+ return insertAfterLastOccurrence(imports, `, ${symbolName}`, fileToEdit, fallbackPos);
54
+ }
55
+ return new change_1.NoopChange();
56
+ }
57
+ // no such import declaration exists
58
+ const useStrict = findNodes(rootNode, ts.isStringLiteral).filter(n => n.text === 'use strict');
59
+ let fallbackPos = 0;
60
+ if (useStrict.length > 0) {
61
+ fallbackPos = useStrict[0].end;
62
+ }
63
+ const open = isDefault ? '' : '{ ';
64
+ const close = isDefault ? '' : ' }';
65
+ // if there are no imports or 'use strict' statement, insert import at beginning of file
66
+ const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
67
+ const separator = insertAtBeginning ? '' : ';\n';
68
+ const toInsert = `${separator}import ${open}${symbolName}${close}` +
69
+ ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`;
70
+ return insertAfterLastOccurrence(allImports, toInsert, fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral);
71
+ }
72
+ exports.insertImport = insertImport;
73
+ function findNodes(node, kindOrGuard, max = Infinity, recursive = false) {
74
+ if (!node || max == 0) {
75
+ return [];
76
+ }
77
+ const test = typeof kindOrGuard === 'function'
78
+ ? kindOrGuard
79
+ : (node) => node.kind === kindOrGuard;
80
+ const arr = [];
81
+ if (test(node)) {
82
+ arr.push(node);
83
+ max--;
84
+ }
85
+ if (max > 0 && (recursive || !test(node))) {
86
+ for (const child of node.getChildren()) {
87
+ findNodes(child, test, max).forEach(node => {
88
+ if (max > 0) {
89
+ arr.push(node);
90
+ }
91
+ max--;
92
+ });
93
+ if (max <= 0) {
94
+ break;
95
+ }
96
+ }
97
+ }
98
+ return arr;
99
+ }
100
+ exports.findNodes = findNodes;
101
+ /**
102
+ * Get all the nodes from a source.
103
+ * @param sourceFile The source file object.
104
+ * @returns {Array<ts.Node>} An array of all the nodes in the source.
105
+ */
106
+ function getSourceNodes(sourceFile) {
107
+ const nodes = [sourceFile];
108
+ const result = [];
109
+ while (nodes.length > 0) {
110
+ const node = nodes.shift();
111
+ if (node) {
112
+ result.push(node);
113
+ if (node.getChildCount(sourceFile) >= 0) {
114
+ nodes.unshift(...node.getChildren());
115
+ }
116
+ }
117
+ }
118
+ return result;
119
+ }
120
+ exports.getSourceNodes = getSourceNodes;
121
+ function findNode(node, kind, text) {
122
+ if (node.kind === kind && node.getText() === text) {
123
+ // throw new Error(node.getText());
124
+ return node;
125
+ }
126
+ let foundNode = null;
127
+ ts.forEachChild(node, childNode => {
128
+ foundNode = foundNode || findNode(childNode, kind, text);
129
+ });
130
+ return foundNode;
131
+ }
132
+ exports.findNode = findNode;
133
+ /**
134
+ * Helper for sorting nodes.
135
+ * @return function to sort nodes in increasing order of position in sourceFile
136
+ */
137
+ function nodesByPosition(first, second) {
138
+ return first.getStart() - second.getStart();
139
+ }
140
+ /**
141
+ * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
142
+ * or after the last of occurence of `syntaxKind` if the last occurence is a sub child
143
+ * of ts.SyntaxKind[nodes[i].kind] and save the changes in file.
144
+ *
145
+ * @param nodes insert after the last occurence of nodes
146
+ * @param toInsert string to insert
147
+ * @param file file to insert changes into
148
+ * @param fallbackPos position to insert if toInsert happens to be the first occurence
149
+ * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after
150
+ * @return Change instance
151
+ * @throw Error if toInsert is first occurence but fall back is not set
152
+ */
153
+ function insertAfterLastOccurrence(nodes, toInsert, file, fallbackPos, syntaxKind) {
154
+ let lastItem;
155
+ for (const node of nodes) {
156
+ if (!lastItem || lastItem.getStart() < node.getStart()) {
157
+ lastItem = node;
158
+ }
159
+ }
160
+ if (syntaxKind && lastItem) {
161
+ lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop();
162
+ }
163
+ if (!lastItem && fallbackPos == undefined) {
164
+ throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`);
165
+ }
166
+ const lastItemPosition = lastItem ? lastItem.getEnd() : fallbackPos;
167
+ return new change_1.InsertChange(file, lastItemPosition, toInsert);
168
+ }
169
+ exports.insertAfterLastOccurrence = insertAfterLastOccurrence;
170
+ function getContentOfKeyLiteral(_source, node) {
171
+ if (node.kind == ts.SyntaxKind.Identifier) {
172
+ return node.text;
173
+ }
174
+ else if (node.kind == ts.SyntaxKind.StringLiteral) {
175
+ return node.text;
176
+ }
177
+ else {
178
+ return null;
179
+ }
180
+ }
181
+ exports.getContentOfKeyLiteral = getContentOfKeyLiteral;
182
+ function _angularImportsFromNode(node, _sourceFile) {
183
+ const ms = node.moduleSpecifier;
184
+ let modulePath;
185
+ switch (ms.kind) {
186
+ case ts.SyntaxKind.StringLiteral:
187
+ modulePath = ms.text;
188
+ break;
189
+ default:
190
+ return {};
191
+ }
192
+ if (!modulePath.startsWith('@angular/')) {
193
+ return {};
194
+ }
195
+ if (node.importClause) {
196
+ if (node.importClause.name) {
197
+ // This is of the form `import Name from 'path'`. Ignore.
198
+ return {};
199
+ }
200
+ else if (node.importClause.namedBindings) {
201
+ const nb = node.importClause.namedBindings;
202
+ if (nb.kind == ts.SyntaxKind.NamespaceImport) {
203
+ // This is of the form `import * as name from 'path'`. Return `name.`.
204
+ return {
205
+ [nb.name.text + '.']: modulePath,
206
+ };
207
+ }
208
+ else {
209
+ // This is of the form `import {a,b,c} from 'path'`
210
+ const namedImports = nb;
211
+ return namedImports.elements
212
+ .map((is) => (is.propertyName ? is.propertyName.text : is.name.text))
213
+ .reduce((acc, curr) => {
214
+ acc[curr] = modulePath;
215
+ return acc;
216
+ }, {});
217
+ }
218
+ }
219
+ return {};
220
+ }
221
+ else {
222
+ // This is of the form `import 'path';`. Nothing to do.
223
+ return {};
224
+ }
225
+ }
226
+ function getDecoratorMetadata(source, identifier, module) {
227
+ const angularImports = findNodes(source, ts.isImportDeclaration)
228
+ .map(node => _angularImportsFromNode(node, source))
229
+ .reduce((acc, current) => {
230
+ for (const key of Object.keys(current)) {
231
+ acc[key] = current[key];
232
+ }
233
+ return acc;
234
+ }, {});
235
+ return getSourceNodes(source)
236
+ .filter(node => {
237
+ return (node.kind == ts.SyntaxKind.Decorator &&
238
+ node.expression.kind == ts.SyntaxKind.CallExpression);
239
+ })
240
+ .map(node => node.expression)
241
+ .filter(expr => {
242
+ if (expr.expression.kind == ts.SyntaxKind.Identifier) {
243
+ const id = expr.expression;
244
+ return id.text == identifier && angularImports[id.text] === module;
245
+ }
246
+ else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
247
+ // This covers foo.NgModule when importing * as foo.
248
+ const paExpr = expr.expression;
249
+ // If the left expression is not an identifier, just give up at that point.
250
+ if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
251
+ return false;
252
+ }
253
+ const id = paExpr.name.text;
254
+ const moduleId = paExpr.expression.text;
255
+ return id === identifier && angularImports[moduleId + '.'] === module;
256
+ }
257
+ return false;
258
+ })
259
+ .filter(expr => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
260
+ .map(expr => expr.arguments[0]);
261
+ }
262
+ exports.getDecoratorMetadata = getDecoratorMetadata;
263
+ function findClassDeclarationParent(node) {
264
+ if (ts.isClassDeclaration(node)) {
265
+ return node;
266
+ }
267
+ return node.parent && findClassDeclarationParent(node.parent);
268
+ }
269
+ /**
270
+ * Given a source file with @NgModule class(es), find the name of the first @NgModule class.
271
+ *
272
+ * @param source source file containing one or more @NgModule
273
+ * @returns the name of the first @NgModule, or `undefined` if none is found
274
+ */
275
+ function getFirstNgModuleName(source) {
276
+ // First, find the @NgModule decorators.
277
+ const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core');
278
+ if (ngModulesMetadata.length === 0) {
279
+ return undefined;
280
+ }
281
+ // Then walk parent pointers up the AST, looking for the ClassDeclaration parent of the NgModule
282
+ // metadata.
283
+ const moduleClass = findClassDeclarationParent(ngModulesMetadata[0]);
284
+ if (!moduleClass || !moduleClass.name) {
285
+ return undefined;
286
+ }
287
+ // Get the class name of the module ClassDeclaration.
288
+ return moduleClass.name.text;
289
+ }
290
+ exports.getFirstNgModuleName = getFirstNgModuleName;
291
+ function getMetadataField(node, metadataField) {
292
+ return (node.properties
293
+ .filter(ts.isPropertyAssignment)
294
+ // Filter out every fields that's not "metadataField". Also handles string literals
295
+ // (but not expressions).
296
+ .filter(({ name }) => {
297
+ return ((ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.getText() === metadataField);
298
+ }));
299
+ }
300
+ exports.getMetadataField = getMetadataField;
301
+ function addSymbolToNgModuleMetadata(source, ngModulePath, metadataField, symbolName, importPath = null) {
302
+ const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
303
+ let node = nodes[0];
304
+ // Find the decorator declaration.
305
+ if (!node) {
306
+ return [];
307
+ }
308
+ // Get all the children property assignment of object literals.
309
+ const matchingProperties = getMetadataField(node, metadataField);
310
+ // Get the last node of the array literal.
311
+ if (!matchingProperties) {
312
+ return [];
313
+ }
314
+ if (matchingProperties.length == 0) {
315
+ // We haven't found the field in the metadata declaration. Insert a new field.
316
+ const expr = node;
317
+ let position;
318
+ let toInsert;
319
+ if (expr.properties.length == 0) {
320
+ position = expr.getEnd() - 1;
321
+ toInsert = ` ${metadataField}: [${symbolName}]\n`;
322
+ }
323
+ else {
324
+ node = expr.properties[expr.properties.length - 1];
325
+ position = node.getEnd();
326
+ // Get the indentation of the last element, if any.
327
+ const text = node.getFullText(source);
328
+ const matches = text.match(/^\r?\n\s*/);
329
+ if (matches && matches.length > 0) {
330
+ toInsert = `,${matches[0]}${metadataField}: [${symbolName}]`;
331
+ }
332
+ else {
333
+ toInsert = `, ${metadataField}: [${symbolName}]`;
334
+ }
335
+ }
336
+ if (importPath !== null) {
337
+ return [
338
+ new change_1.InsertChange(ngModulePath, position, toInsert),
339
+ insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
340
+ ];
341
+ }
342
+ else {
343
+ return [new change_1.InsertChange(ngModulePath, position, toInsert)];
344
+ }
345
+ }
346
+ const assignment = matchingProperties[0];
347
+ // If it's not an array, nothing we can do really.
348
+ if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
349
+ return [];
350
+ }
351
+ const arrLiteral = assignment.initializer;
352
+ if (arrLiteral.elements.length == 0) {
353
+ // Forward the property.
354
+ node = arrLiteral;
355
+ }
356
+ else {
357
+ node = arrLiteral.elements;
358
+ }
359
+ if (!node) {
360
+ console.error('No app module found. Please add your new class to your component.');
361
+ return [];
362
+ }
363
+ if (Array.isArray(node)) {
364
+ // eslint-disable-next-line @typescript-eslint/ban-types
365
+ const nodeArray = node;
366
+ const symbolsArray = nodeArray.map(node => node.getText());
367
+ if (symbolsArray.includes(symbolName)) {
368
+ return [];
369
+ }
370
+ node = node[node.length - 1];
371
+ }
372
+ let toInsert;
373
+ let position = node.getEnd();
374
+ if (node.kind == ts.SyntaxKind.ObjectLiteralExpression) {
375
+ // We haven't found the field in the metadata declaration. Insert a new
376
+ // field.
377
+ const expr = node;
378
+ if (expr.properties.length == 0) {
379
+ position = expr.getEnd() - 1;
380
+ toInsert = ` ${symbolName}\n`;
381
+ }
382
+ else {
383
+ // Get the indentation of the last element, if any.
384
+ const text = node.getFullText(source);
385
+ if (text.match(/^\r?\r?\n/)) {
386
+ toInsert = `,${text.match(/^\r?\n\s*/)[0]}${symbolName}`;
387
+ }
388
+ else {
389
+ toInsert = `, ${symbolName}`;
390
+ }
391
+ }
392
+ }
393
+ else if (node.kind == ts.SyntaxKind.ArrayLiteralExpression) {
394
+ // We found the field but it's empty. Insert it just before the `]`.
395
+ position--;
396
+ toInsert = `${symbolName}`;
397
+ }
398
+ else {
399
+ // Get the indentation of the last element, if any.
400
+ const text = node.getFullText(source);
401
+ if (text.match(/^\r?\n/)) {
402
+ toInsert = `,${text.match(/^\r?\n(\r?)\s*/)[0]}${symbolName}`;
403
+ }
404
+ else {
405
+ toInsert = `, ${symbolName}`;
406
+ }
407
+ }
408
+ if (importPath !== null) {
409
+ return [
410
+ new change_1.InsertChange(ngModulePath, position, toInsert),
411
+ insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
412
+ ];
413
+ }
414
+ return [new change_1.InsertChange(ngModulePath, position, toInsert)];
415
+ }
416
+ exports.addSymbolToNgModuleMetadata = addSymbolToNgModuleMetadata;
417
+ /**
418
+ * Custom function to insert a declaration (component, pipe, directive)
419
+ * into NgModule declarations. It also imports the component.
420
+ */
421
+ function addDeclarationToModule(source, modulePath, classifiedName, importPath) {
422
+ return addSymbolToNgModuleMetadata(source, modulePath, 'declarations', classifiedName, importPath);
423
+ }
424
+ exports.addDeclarationToModule = addDeclarationToModule;
425
+ /**
426
+ * Custom function to insert an NgModule into NgModule imports. It also imports the module.
427
+ */
428
+ function addImportToModule(source, modulePath, classifiedName, importPath) {
429
+ return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
430
+ }
431
+ exports.addImportToModule = addImportToModule;
432
+ /**
433
+ * Custom function to insert a provider into NgModule. It also imports it.
434
+ */
435
+ function addProviderToModule(source, modulePath, classifiedName, importPath) {
436
+ return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
437
+ }
438
+ exports.addProviderToModule = addProviderToModule;
439
+ /**
440
+ * Custom function to insert an export into NgModule. It also imports it.
441
+ */
442
+ function addExportToModule(source, modulePath, classifiedName, importPath) {
443
+ return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
444
+ }
445
+ exports.addExportToModule = addExportToModule;
446
+ /**
447
+ * Custom function to insert an export into NgModule. It also imports it.
448
+ */
449
+ function addBootstrapToModule(source, modulePath, classifiedName, importPath) {
450
+ return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
451
+ }
452
+ exports.addBootstrapToModule = addBootstrapToModule;
453
+ /**
454
+ * Custom function to insert an entryComponent into NgModule. It also imports it.
455
+ * @deprecated - Since version 9.0.0 with Ivy, entryComponents is no longer necessary.
456
+ */
457
+ function addEntryComponentToModule(source, modulePath, classifiedName, importPath) {
458
+ return addSymbolToNgModuleMetadata(source, modulePath, 'entryComponents', classifiedName, importPath);
459
+ }
460
+ exports.addEntryComponentToModule = addEntryComponentToModule;
461
+ /**
462
+ * Determine if an import already exists.
463
+ */
464
+ function isImported(source, classifiedName, importPath) {
465
+ const allNodes = getSourceNodes(source);
466
+ const matchingNodes = allNodes
467
+ .filter(ts.isImportDeclaration)
468
+ .filter(imp => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath)
469
+ .filter(imp => {
470
+ if (!imp.importClause) {
471
+ return false;
472
+ }
473
+ const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter(n => n.getText() === classifiedName);
474
+ return nodes.length > 0;
475
+ });
476
+ return matchingNodes.length > 0;
477
+ }
478
+ exports.isImported = isImported;
479
+ /**
480
+ * This function returns the name of the environment export
481
+ * whether this export is aliased or not. If the environment file
482
+ * is not imported, then it will return `null`.
483
+ */
484
+ function getEnvironmentExportName(source) {
485
+ // Initial value is `null` as we don't know yet if the user
486
+ // has imported `environment` into the root module or not.
487
+ let environmentExportName = null;
488
+ const allNodes = getSourceNodes(source);
489
+ allNodes
490
+ .filter(ts.isImportDeclaration)
491
+ .filter(declaration => declaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral &&
492
+ declaration.importClause !== undefined)
493
+ .map(declaration =>
494
+ // If `importClause` property is defined then the first
495
+ // child will be `NamedImports` object (or `namedBindings`).
496
+ declaration.importClause.getChildAt(0))
497
+ // Find those `NamedImports` object that contains `environment` keyword
498
+ // in its text. E.g. `{ environment as env }`.
499
+ .filter(ts.isNamedImports)
500
+ .filter(namedImports => namedImports.getText().includes('environment'))
501
+ .forEach(namedImports => {
502
+ for (const specifier of namedImports.elements) {
503
+ // `propertyName` is defined if the specifier
504
+ // has an aliased import.
505
+ const name = specifier.propertyName || specifier.name;
506
+ // Find specifier that contains `environment` keyword in its text.
507
+ // Whether it's `environment` or `environment as env`.
508
+ if (name.text.includes('environment')) {
509
+ environmentExportName = specifier.name.text;
510
+ }
511
+ }
512
+ });
513
+ return environmentExportName;
514
+ }
515
+ exports.getEnvironmentExportName = getEnvironmentExportName;
516
+ /**
517
+ * Returns the RouterModule declaration from NgModule metadata, if any.
518
+ */
519
+ function getRouterModuleDeclaration(source) {
520
+ const result = getDecoratorMetadata(source, 'NgModule', '@angular/core');
521
+ const node = result[0];
522
+ const matchingProperties = getMetadataField(node, 'imports');
523
+ if (!matchingProperties) {
524
+ return;
525
+ }
526
+ const assignment = matchingProperties[0];
527
+ if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
528
+ return;
529
+ }
530
+ const arrLiteral = assignment.initializer;
531
+ return arrLiteral.elements
532
+ .filter(el => el.kind === ts.SyntaxKind.CallExpression)
533
+ .find(el => el.getText().startsWith('RouterModule'));
534
+ }
535
+ exports.getRouterModuleDeclaration = getRouterModuleDeclaration;
536
+ /**
537
+ * Adds a new route declaration to a router module (i.e. has a RouterModule declaration)
538
+ */
539
+ function addRouteDeclarationToModule(source, fileToAdd, routeLiteral) {
540
+ const routerModuleExpr = getRouterModuleDeclaration(source);
541
+ if (!routerModuleExpr) {
542
+ throw new Error(`Couldn't find a route declaration in ${fileToAdd}.`);
543
+ }
544
+ const scopeConfigMethodArgs = routerModuleExpr.arguments;
545
+ if (!scopeConfigMethodArgs.length) {
546
+ const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart());
547
+ throw new Error(`The router module method doesn't have arguments ` + `at line ${line} in ${fileToAdd}`);
548
+ }
549
+ let routesArr;
550
+ const routesArg = scopeConfigMethodArgs[0];
551
+ // Check if the route declarations array is
552
+ // an inlined argument of RouterModule or a standalone variable
553
+ if (ts.isArrayLiteralExpression(routesArg)) {
554
+ routesArr = routesArg;
555
+ }
556
+ else {
557
+ const routesVarName = routesArg.getText();
558
+ let routesVar;
559
+ if (routesArg.kind === ts.SyntaxKind.Identifier) {
560
+ routesVar = source.statements.filter(ts.isVariableStatement).find(v => {
561
+ return v.declarationList.declarations[0].name.getText() === routesVarName;
562
+ });
563
+ }
564
+ if (!routesVar) {
565
+ const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart());
566
+ throw new Error(`No route declaration array was found that corresponds ` +
567
+ `to router module at line ${line} in ${fileToAdd}`);
568
+ }
569
+ routesArr = findNodes(routesVar, ts.SyntaxKind.ArrayLiteralExpression, 1)[0];
570
+ }
571
+ const occurrencesCount = routesArr.elements.length;
572
+ const text = routesArr.getFullText(source);
573
+ let route = routeLiteral;
574
+ let insertPos = routesArr.elements.pos;
575
+ if (occurrencesCount > 0) {
576
+ const lastRouteLiteral = [...routesArr.elements].pop();
577
+ const lastRouteIsWildcard = ts.isObjectLiteralExpression(lastRouteLiteral) &&
578
+ lastRouteLiteral.properties.some(n => ts.isPropertyAssignment(n) &&
579
+ ts.isIdentifier(n.name) &&
580
+ n.name.text === 'path' &&
581
+ ts.isStringLiteral(n.initializer) &&
582
+ n.initializer.text === '**');
583
+ const indentation = text.match(/\r?\n(\r?)\s*/) || [];
584
+ const routeText = `${indentation[0] || ' '}${routeLiteral}`;
585
+ // Add the new route before the wildcard route
586
+ // otherwise we'll always redirect to the wildcard route
587
+ if (lastRouteIsWildcard) {
588
+ insertPos = lastRouteLiteral.pos;
589
+ route = `${routeText},`;
590
+ }
591
+ else {
592
+ insertPos = lastRouteLiteral.end;
593
+ route = `,${routeText}`;
594
+ }
595
+ }
596
+ return new change_1.InsertChange(fileToAdd, insertPos, route);
597
+ }
598
+ exports.addRouteDeclarationToModule = addRouteDeclarationToModule;
599
599
  //# sourceMappingURL=ast-utils.js.map