@magic-xpa/cli 4.1201.0-dev4121.254 → 4.1201.0-dev4121.263

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 (183) hide show
  1. package/README.md +28 -28
  2. package/index.js.map +1 -1
  3. package/index.ts +1 -1
  4. package/package.json +1 -1
  5. package/src/collection.json +75 -75
  6. package/src/public_api.js.map +1 -1
  7. package/src/public_api.ts +5 -5
  8. package/src/schematics/magic-utils/config.js.map +1 -1
  9. package/src/schematics/magic-utils/config.ts +68 -68
  10. package/src/schematics/magic-utils/env.js.map +1 -1
  11. package/src/schematics/magic-utils/env.ts +50 -50
  12. package/src/schematics/magic-utils/manifest.js.map +1 -1
  13. package/src/schematics/magic-utils/manifest.ts +46 -46
  14. package/src/schematics/magic-utils/metadata.class.js.map +1 -1
  15. package/src/schematics/magic-utils/metadata.class.ts +159 -159
  16. package/src/schematics/magic-utils/rules/generate.rule.js.map +1 -1
  17. package/src/schematics/magic-utils/rules/generate.rule.ts +61 -61
  18. package/src/schematics/magic-utils/rules/init-add-modules.rule.js.map +1 -1
  19. package/src/schematics/magic-utils/rules/init-add-modules.rule.ts +360 -360
  20. package/src/schematics/magic-utils/rules/init-magic-metadata.rule.js.map +1 -1
  21. package/src/schematics/magic-utils/rules/init-magic-metadata.rule.ts +19 -19
  22. package/src/schematics/magic-utils/rules/magic-option.scheme.js.map +1 -1
  23. package/src/schematics/magic-utils/rules/magic-option.scheme.ts +24 -24
  24. package/src/schematics/magic-utils/utils.js.map +1 -1
  25. package/src/schematics/magic-utils/utils.ts +134 -134
  26. package/src/schematics/mg-Install-prerequisites/index.js.map +1 -1
  27. package/src/schematics/mg-Install-prerequisites/index.ts +30 -30
  28. package/src/schematics/mg-Install-prerequisites/schema.json +14 -14
  29. package/src/schematics/mg-add/files/src/app/app.component.html +17 -17
  30. package/src/schematics/mg-add/files/src/app/app.routes.ts +14 -14
  31. package/src/schematics/mg-add/files/src/app/magic/component-list.g.ts +9 -9
  32. package/src/schematics/mg-add/files/src/magic-styles.css +131 -131
  33. package/src/schematics/mg-add/schema.json +29 -29
  34. package/src/schematics/mg-add/utils/add-declaration-to-root-module.js.map +1 -1
  35. package/src/schematics/mg-add/utils/add-declaration-to-root-module.ts +12 -12
  36. package/src/schematics/mg-add/webModule/app.routes.ts +14 -14
  37. package/src/schematics/mg-add-tasks/index.js.map +1 -1
  38. package/src/schematics/mg-add-tasks/index.ts +53 -53
  39. package/src/schematics/mg-add-tasks/schema.json +41 -41
  40. package/src/schematics/mg-delete-files/index.js.map +1 -1
  41. package/src/schematics/mg-delete-files/index.ts +12 -12
  42. package/src/schematics/mg-delete-files/schema.json +14 -14
  43. package/src/schematics/mg-gen-module/index.js.map +1 -1
  44. package/src/schematics/mg-gen-module/index.ts +14 -14
  45. package/src/schematics/mg-gen-module/schema.json +24 -24
  46. package/src/schematics/mg-generate/index.js.map +1 -1
  47. package/src/schematics/mg-generate/index.ts +12 -12
  48. package/src/schematics/mg-generate/schema.json +34 -34
  49. package/src/schematics/mg-install/index.js.map +1 -1
  50. package/src/schematics/mg-install/index.ts +37 -37
  51. package/src/schematics/mg-install/schema.json +24 -24
  52. package/src/schematics/mg-routes/schema.json +14 -14
  53. package/src/schematics/mg-single-control/schema.json +24 -24
  54. package/src/schematics/utils/ast.js.map +1 -1
  55. package/src/schematics/utils/ast.ts +103 -103
  56. package/src/schematics/utils/devkit-utils/README.md +1 -1
  57. package/src/schematics/utils/devkit-utils/ast-utils.js.map +1 -1
  58. package/src/schematics/utils/devkit-utils/ast-utils.ts +570 -570
  59. package/src/schematics/utils/devkit-utils/ast-utils_old.js.map +1 -1
  60. package/src/schematics/utils/devkit-utils/ast-utils_old.ts +478 -478
  61. package/src/schematics/utils/devkit-utils/change.js.map +1 -1
  62. package/src/schematics/utils/devkit-utils/change.ts +127 -127
  63. package/src/schematics/utils/devkit-utils/component.js.map +1 -1
  64. package/src/schematics/utils/devkit-utils/component.ts +136 -136
  65. package/src/schematics/utils/devkit-utils/config.js.map +1 -1
  66. package/src/schematics/utils/devkit-utils/config.ts +120 -120
  67. package/src/schematics/utils/devkit-utils/find-module.js.map +1 -1
  68. package/src/schematics/utils/devkit-utils/find-module.ts +108 -108
  69. package/src/schematics/utils/devkit-utils/ng-ast-utils.js.map +1 -1
  70. package/src/schematics/utils/devkit-utils/ng-ast-utils.ts +84 -84
  71. package/src/schematics/utils/devkit-utils/parse-name.js.map +1 -1
  72. package/src/schematics/utils/devkit-utils/parse-name.ts +24 -24
  73. package/src/schematics/utils/devkit-utils/route-utils.js.map +1 -1
  74. package/src/schematics/utils/devkit-utils/route-utils.ts +180 -180
  75. package/src/schematics/utils/devkit-utils/validation.js +1 -1
  76. package/src/schematics/utils/devkit-utils/validation.js.map +1 -1
  77. package/src/schematics/utils/devkit-utils/validation.ts +16 -16
  78. package/src/schematics/utils/html.js.map +1 -1
  79. package/src/schematics/utils/html.ts +63 -63
  80. package/src/schematics/utils/lib-versions.js.map +1 -1
  81. package/src/schematics/utils/lib-versions.ts +3 -3
  82. package/src/schematics/utils/package.js.map +1 -1
  83. package/src/schematics/utils/package.ts +22 -22
  84. package/src/schematics/utils/testing.js.map +1 -1
  85. package/src/schematics/utils/testing.ts +25 -25
  86. package/src/types/enums/Enums.js.map +1 -1
  87. package/src/types/enums/Enums.ts +2063 -2063
  88. package/src/types/enums/generated-file-types.enum.js.map +1 -1
  89. package/src/types/enums/generated-file-types.enum.ts +6 -6
  90. package/src/types/enums/horizontal-alignments.enum.js.map +1 -1
  91. package/src/types/enums/horizontal-alignments.enum.ts +6 -6
  92. package/src/types/enums/themes.enum.js.map +1 -1
  93. package/src/types/enums/themes.enum.ts +6 -6
  94. package/src/types/index.js.map +1 -1
  95. package/src/types/index.ts +8 -8
  96. package/src/types/interfaces/app.js.map +1 -1
  97. package/src/types/interfaces/app.ts +89 -89
  98. package/src/types/interfaces/control.js.map +1 -1
  99. package/src/types/interfaces/control.ts +106 -106
  100. package/src/types/interfaces/template.config.js.map +1 -1
  101. package/src/types/interfaces/template.config.ts +11 -11
  102. package/templates/angular/src/app/app.component.html.ejs +17 -17
  103. package/templates/angular/src/app/cmp-array.ejs +3 -3
  104. package/templates/angular/src/app/cmp-hash.ejs +3 -3
  105. package/templates/angular/src/app/component-list.g.ts +21 -21
  106. package/templates/angular/src/app.component.ts +16 -16
  107. package/templates/angular/src/app.module.ts +70 -70
  108. package/templates/angular/src/app.routes.ts +73 -73
  109. package/templates/angular/src/styles/app.css +5 -5
  110. package/templates/attributes/button_attributes.ejs +2 -2
  111. package/templates/attributes/common/base/class.ejs +6 -6
  112. package/templates/attributes/common/base/control_type.ejs +53 -53
  113. package/templates/attributes/common/base/enabled.ejs +9 -9
  114. package/templates/attributes/common/base/imageFileName.ejs +3 -3
  115. package/templates/attributes/common/base/no_control_class.ejs +3 -3
  116. package/templates/attributes/common/base/rtol.ejs +3 -3
  117. package/templates/attributes/common/base/tabindex.ejs +11 -11
  118. package/templates/attributes/common/base/testingId.ejs +8 -8
  119. package/templates/attributes/common/base/tooltip.ejs +7 -7
  120. package/templates/attributes/common/base/visible.ejs +6 -6
  121. package/templates/attributes/common/base/wallpaper.ejs +3 -3
  122. package/templates/attributes/common/base_attributes.ejs +10 -10
  123. package/templates/attributes/common/container_attributes.ejs +6 -6
  124. package/templates/attributes/common/control_attributes.ejs +3 -3
  125. package/templates/attributes/common/format.ejs +5 -5
  126. package/templates/attributes/common/input/hint.ejs +13 -13
  127. package/templates/attributes/common/input/multiline_edit.ejs +3 -3
  128. package/templates/attributes/common/input/must_input.ejs +8 -8
  129. package/templates/attributes/common/input/password_edit.ejs +7 -7
  130. package/templates/attributes/common/input/row_editing_input_attributes.ejs +6 -6
  131. package/templates/attributes/common/input/validation.ejs +5 -5
  132. package/templates/attributes/common/input_attributes.ejs +4 -4
  133. package/templates/attributes/common/no_control_base_attributes.ejs +4 -4
  134. package/templates/attributes/common/row_editing_button_attributes.ejs +10 -10
  135. package/templates/component/view.component.html +14 -14
  136. package/templates/component/view.component.ts +136 -136
  137. package/templates/themes/basicHTML/Code/theme.module.ts +10 -10
  138. package/templates/themes/basicHTML/combobox.ejs +37 -37
  139. package/templates/themes/basicHTML/edit.ejs +169 -169
  140. package/templates/themes/basicHTML/form.ejs +4 -4
  141. package/templates/themes/basicHTML/group.ejs +4 -4
  142. package/templates/themes/basicHTML/image.ejs +6 -6
  143. package/templates/themes/basicHTML/label.ejs +11 -11
  144. package/templates/themes/basicHTML/listbox.ejs +21 -21
  145. package/templates/themes/basicHTML/push-button.ejs +28 -28
  146. package/templates/themes/basicHTML/radio.ejs +20 -20
  147. package/templates/themes/basicHTML/subform.ejs +6 -6
  148. package/templates/themes/basicHTML/tab.ejs +31 -31
  149. package/templates/themes/basicHTML/tabpage.ejs +5 -5
  150. package/templates/themes/basicHiddenHTML/Code/theme.module.ts +10 -10
  151. package/templates/themes/basicHiddenHTML/combobox.ejs +5 -5
  152. package/templates/themes/basicHiddenHTML/form.ejs +3 -3
  153. package/templates/themes/basicHiddenHTML/group.ejs +2 -2
  154. package/templates/themes/basicHiddenHTML/image.ejs +4 -4
  155. package/templates/themes/basicHiddenHTML/label.ejs +1 -1
  156. package/templates/themes/basicHiddenHTML/listbox.ejs +8 -8
  157. package/templates/themes/basicHiddenHTML/push-button.ejs +26 -26
  158. package/templates/themes/basicHiddenHTML/radio.ejs +17 -17
  159. package/templates/themes/basicHiddenHTML/tab.ejs +13 -13
  160. package/templates/themes/basicHiddenHTML/table.ejs +18 -18
  161. package/templates/themes/basicHiddenHTML/tabpage.ejs +2 -2
  162. package/templates/themes/container.ejs +26 -26
  163. package/templates/themes/control.ejs +52 -52
  164. package/templates/themes/editTypeSelector.ejs +1 -1
  165. package/templates/themes/material/Code/theme.module.ts +68 -68
  166. package/templates/themes/material/base_attributes_date.ejs +8 -8
  167. package/templates/themes/material/combobox.ejs +58 -58
  168. package/templates/themes/material/edit.ejs +204 -204
  169. package/templates/themes/material/group.ejs +3 -3
  170. package/templates/themes/material/listbox.ejs +22 -22
  171. package/templates/themes/material/push-button.ejs +28 -28
  172. package/templates/themes/material/radio.ejs +22 -22
  173. package/templates/themes/material/subform.ejs +8 -8
  174. package/templates/themes/material/tab.ejs +19 -19
  175. package/templates/themes/router_outlet.ejs +5 -5
  176. package/templates/themes/table/HTMLTable/table.ejs +37 -37
  177. package/templates/themes/table/grid/additionalComponentCode.ejs +26 -26
  178. package/templates/themes/table/grid/additionalIncludes.ejs +1 -1
  179. package/templates/themes/table/grid/table.ejs +37 -37
  180. package/templates/themes/table/repeatable/column.ejs +11 -11
  181. package/templates/themes/table/repeatable/table.ejs +28 -28
  182. package/templates/themes/tableTypeSelector.ejs +21 -21
  183. package/tsconfig.json +36 -36
@@ -1,570 +1,570 @@
1
- /**
2
- * @license
3
- * Copyright Google Inc. All Rights Reserved.
4
- *
5
- * Use of this source code is governed by an MIT-style license that can be
6
- * found in the LICENSE file at https://angular.io/license
7
- */
8
- import * as ts from 'typescript';
9
- import { Change, InsertChange, NoopChange } from './change';
10
-
11
-
12
- /**
13
- * Add Import `import { symbolName } from fileName` if the import doesn't exit
14
- * already. Assumes fileToEdit can be resolved and accessed.
15
- * @param fileToEdit (file we want to add import to)
16
- * @param symbolName (item to import)
17
- * @param fileName (path to the file)
18
- * @param isDefault (if true, import follows style for importing default exports)
19
- * @return Change
20
- */
21
- export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolName: string,
22
- fileName: string, isDefault = false): Change {
23
- const rootNode = source;
24
- const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
25
-
26
- // get nodes that map to import statements from the file fileName
27
- const relevantImports = allImports.filter(node => {
28
- // StringLiteral of the ImportDeclaration is the import file (fileName in this case).
29
- const importFiles = node.getChildren()
30
- .filter(child => child.kind === ts.SyntaxKind.StringLiteral)
31
- .map(n => (n as ts.StringLiteral).text);
32
-
33
- return importFiles.filter(file => file === fileName).length === 1;
34
- });
35
-
36
- if (relevantImports.length > 0) {
37
- let importsAsterisk = false;
38
- // imports from import file
39
- const imports: ts.Node[] = [];
40
- relevantImports.forEach(n => {
41
- Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier));
42
- if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) {
43
- importsAsterisk = true;
44
- }
45
- });
46
-
47
- // if imports * from fileName, don't add symbolName
48
- if (importsAsterisk) {
49
- return new NoopChange();
50
- }
51
-
52
- const importTextNodes = imports.filter(n => (n as ts.Identifier).text === symbolName);
53
-
54
- // insert import if it's not there
55
- if (importTextNodes.length === 0) {
56
- const fallbackPos =
57
- findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
58
- findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();
59
-
60
- return insertAfterLastOccurrence(imports, `, ${symbolName}`, fileToEdit, fallbackPos);
61
- }
62
-
63
- return new NoopChange();
64
- }
65
-
66
- // no such import declaration exists
67
- const useStrict = findNodes(rootNode, ts.SyntaxKind.StringLiteral)
68
- .filter((n: ts.StringLiteral) => n.text === 'use strict');
69
- let fallbackPos = 0;
70
- if (useStrict.length > 0) {
71
- fallbackPos = useStrict[0].end;
72
- }
73
- const open = isDefault ? '' : '{ ';
74
- const close = isDefault ? '' : ' }';
75
- // if there are no imports or 'use strict' statement, insert import at beginning of file
76
- const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
77
- const separator = insertAtBeginning ? '' : ';\n';
78
- const toInsert = `${separator}import ${open}${symbolName}${close}` +
79
- ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`;
80
-
81
- return insertAfterLastOccurrence(
82
- allImports,
83
- toInsert,
84
- fileToEdit,
85
- fallbackPos,
86
- ts.SyntaxKind.StringLiteral,
87
- );
88
- }
89
-
90
-
91
- /**
92
- * Find all nodes from the AST in the subtree of node of SyntaxKind kind.
93
- * @param node
94
- * @param kind
95
- * @param max The maximum number of items to return.
96
- * @return all nodes of kind, or [] if none is found
97
- */
98
- export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max = Infinity): ts.Node[] {
99
- if (!node || max == 0) {
100
- return [];
101
- }
102
-
103
- const arr: ts.Node[] = [];
104
- if (node.kind === kind) {
105
- arr.push(node);
106
- max--;
107
- }
108
- if (max > 0) {
109
- for (const child of node.getChildren()) {
110
- findNodes(child, kind, max).forEach(node => {
111
- if (max > 0) {
112
- arr.push(node);
113
- }
114
- max--;
115
- });
116
-
117
- if (max <= 0) {
118
- break;
119
- }
120
- }
121
- }
122
-
123
- return arr;
124
- }
125
-
126
-
127
- /**
128
- * Get all the nodes from a source.
129
- * @param sourceFile The source file object.
130
- * @returns {Observable<ts.Node>} An observable of all the nodes in the source.
131
- */
132
- export function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[] {
133
- const nodes: ts.Node[] = [sourceFile];
134
- const result = [];
135
-
136
- while (nodes.length > 0) {
137
- const node = nodes.shift();
138
-
139
- if (node) {
140
- result.push(node);
141
- if (node.getChildCount(sourceFile) >= 0) {
142
- nodes.unshift(...node.getChildren());
143
- }
144
- }
145
- }
146
-
147
- return result;
148
- }
149
-
150
- export function findNode(node: ts.Node, kind: ts.SyntaxKind, text: string): ts.Node | null {
151
- if (node.kind === kind && node.getText() === text) {
152
- // throw new Error(node.getText());
153
- return node;
154
- }
155
-
156
- let foundNode: ts.Node | null = null;
157
- ts.forEachChild(node, childNode => {
158
- foundNode = foundNode || findNode(childNode, kind, text);
159
- });
160
-
161
- return foundNode;
162
- }
163
-
164
-
165
- /**
166
- * Helper for sorting nodes.
167
- * @return function to sort nodes in increasing order of position in sourceFile
168
- */
169
- function nodesByPosition(first: ts.Node, second: ts.Node): number {
170
- return first.getStart() - second.getStart();
171
- }
172
-
173
-
174
- /**
175
- * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
176
- * or after the last of occurence of `syntaxKind` if the last occurence is a sub child
177
- * of ts.SyntaxKind[nodes[i].kind] and save the changes in file.
178
- *
179
- * @param nodes insert after the last occurence of nodes
180
- * @param toInsert string to insert
181
- * @param file file to insert changes into
182
- * @param fallbackPos position to insert if toInsert happens to be the first occurence
183
- * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after
184
- * @return Change instance
185
- * @throw Error if toInsert is first occurence but fall back is not set
186
- */
187
- export function insertAfterLastOccurrence(nodes: ts.Node[],
188
- toInsert: string,
189
- file: string,
190
- fallbackPos: number,
191
- syntaxKind?: ts.SyntaxKind): Change {
192
- let lastItem = nodes.sort(nodesByPosition).pop();
193
- if (!lastItem) {
194
- //throw new Error();
195
- new InsertChange(file, 0, toInsert); // Eyal Vardi Fix when no import at all.
196
- }
197
- if (syntaxKind) {
198
- lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop();
199
- }
200
- if (!lastItem && fallbackPos == undefined) {
201
- throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`);
202
- }
203
- const lastItemPosition: number = lastItem ? lastItem.getEnd() : fallbackPos;
204
-
205
- return new InsertChange(file, lastItemPosition, toInsert);
206
- }
207
-
208
-
209
- export function getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): string | null {
210
- if (node.kind == ts.SyntaxKind.Identifier) {
211
- return (node as ts.Identifier).text;
212
- } else if (node.kind == ts.SyntaxKind.StringLiteral) {
213
- return (node as ts.StringLiteral).text;
214
- } else {
215
- return null;
216
- }
217
- }
218
-
219
-
220
- function _angularImportsFromNode(node: ts.ImportDeclaration,
221
- _sourceFile: ts.SourceFile): {[name: string]: string} {
222
- const ms = node.moduleSpecifier;
223
- let modulePath: string;
224
- switch (ms.kind) {
225
- case ts.SyntaxKind.StringLiteral:
226
- modulePath = (ms as ts.StringLiteral).text;
227
- break;
228
- default:
229
- return {};
230
- }
231
-
232
- if (!modulePath.startsWith('@angular/')) {
233
- return {};
234
- }
235
-
236
- if (node.importClause) {
237
- if (node.importClause.name) {
238
- // This is of the form `import Name from 'path'`. Ignore.
239
- return {};
240
- } else if (node.importClause.namedBindings) {
241
- const nb = node.importClause.namedBindings;
242
- if (nb.kind == ts.SyntaxKind.NamespaceImport) {
243
- // This is of the form `import * as name from 'path'`. Return `name.`.
244
- return {
245
- [(nb as ts.NamespaceImport).name.text + '.']: modulePath,
246
- };
247
- } else {
248
- // This is of the form `import {a,b,c} from 'path'`
249
- const namedImports = nb as ts.NamedImports;
250
-
251
- return namedImports.elements
252
- .map((is: ts.ImportSpecifier) => is.propertyName ? is.propertyName.text : is.name.text)
253
- .reduce((acc: {[name: string]: string}, curr: string) => {
254
- acc[curr] = modulePath;
255
-
256
- return acc;
257
- }, {});
258
- }
259
- }
260
-
261
- return {};
262
- } else {
263
- // This is of the form `import 'path';`. Nothing to do.
264
- return {};
265
- }
266
- }
267
-
268
-
269
- export function getDecoratorMetadata(source: ts.SourceFile, identifier: string,
270
- module: string): ts.Node[] {
271
- const angularImports: {[name: string]: string}
272
- = findNodes(source, ts.SyntaxKind.ImportDeclaration)
273
- .map((node: ts.ImportDeclaration) => _angularImportsFromNode(node, source))
274
- .reduce((acc: {[name: string]: string}, current: {[name: string]: string}) => {
275
- for (const key of Object.keys(current)) {
276
- acc[key] = current[key];
277
- }
278
-
279
- return acc;
280
- }, {});
281
-
282
- return getSourceNodes(source)
283
- .filter(node => {
284
- return node.kind == ts.SyntaxKind.Decorator
285
- && (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression;
286
- })
287
- .map(node => (node as ts.Decorator).expression as ts.CallExpression)
288
- .filter(expr => {
289
- if (expr.expression.kind == ts.SyntaxKind.Identifier) {
290
- const id = expr.expression as ts.Identifier;
291
-
292
- return id.getFullText(source) == identifier
293
- && angularImports[id.getFullText(source)] === module;
294
- } else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
295
- // This covers foo.NgModule when importing * as foo.
296
- const paExpr = expr.expression as ts.PropertyAccessExpression;
297
- // If the left expression is not an identifier, just give up at that point.
298
- if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
299
- return false;
300
- }
301
-
302
- const id = paExpr.name.text;
303
- const moduleId = (paExpr.expression as ts.Identifier).getText(source);
304
-
305
- return id === identifier && (angularImports[moduleId + '.'] === module);
306
- }
307
-
308
- return false;
309
- })
310
- .filter(expr => expr.arguments[0]
311
- && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
312
- .map(expr => expr.arguments[0] as ts.ObjectLiteralExpression);
313
- }
314
-
315
- function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration|undefined {
316
- if (ts.isClassDeclaration(node)) {
317
- return node;
318
- }
319
-
320
- return node.parent && findClassDeclarationParent(node.parent);
321
- }
322
-
323
- /**
324
- * Given a source file with @NgModule class(es), find the name of the first @NgModule class.
325
- *
326
- * @param source source file containing one or more @NgModule
327
- * @returns the name of the first @NgModule, or `undefined` if none is found
328
- */
329
- export function getFirstNgModuleName(source: ts.SourceFile): string|undefined {
330
- // First, find the @NgModule decorators.
331
- const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core');
332
- if (ngModulesMetadata.length === 0) {
333
- return undefined;
334
- }
335
-
336
- // Then walk parent pointers up the AST, looking for the ClassDeclaration parent of the NgModule
337
- // metadata.
338
- const moduleClass = findClassDeclarationParent(ngModulesMetadata[0]);
339
- if (!moduleClass || !moduleClass.name) {
340
- return undefined;
341
- }
342
-
343
- // Get the class name of the module ClassDeclaration.
344
- return moduleClass.name.text;
345
- }
346
-
347
- export function addSymbolToNgModuleMetadata(
348
- source: ts.SourceFile,
349
- ngModulePath: string,
350
- metadataField: string,
351
- symbolName: string,
352
- importPath: string | null = null,
353
- ): Change[] {
354
- const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
355
- let node: any = nodes[0]; // tslint:disable-line:no-any
356
- // Find the decorator declaration.
357
- if (!node) {
358
- return [];
359
- }
360
-
361
- // Get all the children property assignment of object literals.
362
- const matchingProperties: ts.ObjectLiteralElement[] =
363
- (node as ts.ObjectLiteralExpression).properties
364
- .filter(prop => prop.kind == ts.SyntaxKind.PropertyAssignment)
365
- // Filter out every fields that's not "metadataField". Also handles string literals
366
- // (but not expressions).
367
- .filter((prop: ts.PropertyAssignment) => {
368
- const name = prop.name;
369
- switch (name.kind) {
370
- case ts.SyntaxKind.Identifier:
371
- return (name as ts.Identifier).getText(source) == metadataField;
372
- case ts.SyntaxKind.StringLiteral:
373
- return (name as ts.StringLiteral).text == metadataField;
374
- }
375
-
376
- return false;
377
- });
378
-
379
- // Get the last node of the array literal.
380
- if (!matchingProperties) {
381
- return [];
382
- }
383
- if (matchingProperties.length == 0) {
384
- // We haven't found the field in the metadata declaration. Insert a new field.
385
- const expr = node as ts.ObjectLiteralExpression;
386
- let position: number;
387
- let toInsert: string;
388
- if (expr.properties.length == 0) {
389
- position = expr.getEnd() - 1;
390
- toInsert = ` ${metadataField}: [${symbolName}]\n`;
391
- } else {
392
- node = expr.properties[expr.properties.length - 1];
393
- position = node.getEnd();
394
- // Get the indentation of the last element, if any.
395
- const text = node.getFullText(source);
396
- const matches = text.match(/^\r?\n\s*/);
397
- if (matches.length > 0) {
398
- toInsert = `,${matches[0]}${metadataField}: [${symbolName}]`;
399
- } else {
400
- toInsert = `, ${metadataField}: [${symbolName}]`;
401
- }
402
- }
403
- if (importPath !== null) {
404
- return [
405
- new InsertChange(ngModulePath, position, toInsert),
406
- insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
407
- ];
408
- } else {
409
- return [new InsertChange(ngModulePath, position, toInsert)];
410
- }
411
- }
412
- const assignment = matchingProperties[0] as ts.PropertyAssignment;
413
-
414
- // If it's not an array, nothing we can do really.
415
- if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
416
- return [];
417
- }
418
-
419
- const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression;
420
- if (arrLiteral.elements.length == 0) {
421
- // Forward the property.
422
- node = arrLiteral;
423
- } else {
424
- node = arrLiteral.elements;
425
- }
426
-
427
- if (!node) {
428
- console.log('No app module found. Please add your new class to your component.');
429
-
430
- return [];
431
- }
432
-
433
- if (Array.isArray(node)) {
434
- const nodeArray = node as {} as Array<ts.Node>;
435
- const symbolsArray = nodeArray.map(node => node.getText());
436
- if (symbolsArray.includes(symbolName)) {
437
- return [];
438
- }
439
-
440
- node = node[node.length - 1];
441
- }
442
-
443
- let toInsert: string;
444
- let position = node.getEnd();
445
- if (node.kind == ts.SyntaxKind.ObjectLiteralExpression) {
446
- // We haven't found the field in the metadata declaration. Insert a new
447
- // field.
448
- const expr = node as ts.ObjectLiteralExpression;
449
- if (expr.properties.length == 0) {
450
- position = expr.getEnd() - 1;
451
- toInsert = ` ${metadataField}: [${symbolName}]\n`;
452
- } else {
453
- node = expr.properties[expr.properties.length - 1];
454
- position = node.getEnd();
455
- // Get the indentation of the last element, if any.
456
- const text = node.getFullText(source);
457
- if (text.match('^\r?\r?\n')) {
458
- toInsert = `,${text.match(/^\r?\n\s+/)[0]}${metadataField}: [${symbolName}]`;
459
- } else {
460
- toInsert = `, ${metadataField}: [${symbolName}]`;
461
- }
462
- }
463
- } else if (node.kind == ts.SyntaxKind.ArrayLiteralExpression) {
464
- // We found the field but it's empty. Insert it just before the `]`.
465
- position--;
466
- toInsert = `${symbolName}`;
467
- } else {
468
- // Get the indentation of the last element, if any.
469
- const text = node.getFullText(source);
470
- if (text.match(/^\r?\n/)) {
471
- toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${symbolName}`;
472
- } else {
473
- toInsert = `, ${symbolName}`;
474
- }
475
- }
476
- if (importPath !== null) {
477
- return [
478
- new InsertChange(ngModulePath, position, toInsert),
479
- insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
480
- ];
481
- }
482
-
483
- return [new InsertChange(ngModulePath, position, toInsert)];
484
- }
485
-
486
- /**
487
- * Custom function to insert a declaration (component, pipe, directive)
488
- * into NgModule declarations. It also imports the component.
489
- */
490
- export function addDeclarationToModule(source: ts.SourceFile,
491
- modulePath: string, classifiedName: string,
492
- importPath: string): Change[] {
493
- return addSymbolToNgModuleMetadata(
494
- source, modulePath, 'declarations', classifiedName, importPath);
495
- }
496
-
497
- /**
498
- * Custom function to insert an NgModule into NgModule imports. It also imports the module.
499
- */
500
- export function addImportToModule(source: ts.SourceFile,
501
- modulePath: string, classifiedName: string,
502
- importPath: string): Change[] {
503
-
504
- return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
505
- }
506
-
507
- /**
508
- * Custom function to insert a provider into NgModule. It also imports it.
509
- */
510
- export function addProviderToModule(source: ts.SourceFile,
511
- modulePath: string, classifiedName: string,
512
- importPath: string): Change[] {
513
- return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
514
- }
515
-
516
- /**
517
- * Custom function to insert an export into NgModule. It also imports it.
518
- */
519
- export function addExportToModule(source: ts.SourceFile,
520
- modulePath: string, classifiedName: string,
521
- importPath: string): Change[] {
522
- return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
523
- }
524
-
525
- /**
526
- * Custom function to insert an export into NgModule. It also imports it.
527
- */
528
- export function addBootstrapToModule(source: ts.SourceFile,
529
- modulePath: string, classifiedName: string,
530
- importPath: string): Change[] {
531
- return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
532
- }
533
-
534
- /**
535
- * Custom function to insert an entryComponent into NgModule. It also imports it.
536
- */
537
- export function addEntryComponentToModule(source: ts.SourceFile,
538
- modulePath: string, classifiedName: string,
539
- importPath: string): Change[] {
540
- return addSymbolToNgModuleMetadata(
541
- source, modulePath,
542
- 'entryComponents', classifiedName, importPath,
543
- );
544
- }
545
-
546
- /**
547
- * Determine if an import already exists.
548
- */
549
- export function isImported(source: ts.SourceFile,
550
- classifiedName: string,
551
- importPath: string): boolean {
552
- const allNodes = getSourceNodes(source);
553
- const matchingNodes = allNodes
554
- .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration)
555
- .filter((imp: ts.ImportDeclaration) => imp.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral)
556
- .filter((imp: ts.ImportDeclaration) => {
557
- return (<ts.StringLiteral> imp.moduleSpecifier).text === importPath;
558
- })
559
- .filter((imp: ts.ImportDeclaration) => {
560
- if (!imp.importClause) {
561
- return false;
562
- }
563
- const nodes = findNodes(imp.importClause, ts.SyntaxKind.ImportSpecifier)
564
- .filter(n => n.getText() === classifiedName);
565
-
566
- return nodes.length > 0;
567
- });
568
-
569
- return matchingNodes.length > 0;
570
- }
1
+ /**
2
+ * @license
3
+ * Copyright Google Inc. All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by an MIT-style license that can be
6
+ * found in the LICENSE file at https://angular.io/license
7
+ */
8
+ import * as ts from 'typescript';
9
+ import { Change, InsertChange, NoopChange } from './change';
10
+
11
+
12
+ /**
13
+ * Add Import `import { symbolName } from fileName` if the import doesn't exit
14
+ * already. Assumes fileToEdit can be resolved and accessed.
15
+ * @param fileToEdit (file we want to add import to)
16
+ * @param symbolName (item to import)
17
+ * @param fileName (path to the file)
18
+ * @param isDefault (if true, import follows style for importing default exports)
19
+ * @return Change
20
+ */
21
+ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolName: string,
22
+ fileName: string, isDefault = false): Change {
23
+ const rootNode = source;
24
+ const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
25
+
26
+ // get nodes that map to import statements from the file fileName
27
+ const relevantImports = allImports.filter(node => {
28
+ // StringLiteral of the ImportDeclaration is the import file (fileName in this case).
29
+ const importFiles = node.getChildren()
30
+ .filter(child => child.kind === ts.SyntaxKind.StringLiteral)
31
+ .map(n => (n as ts.StringLiteral).text);
32
+
33
+ return importFiles.filter(file => file === fileName).length === 1;
34
+ });
35
+
36
+ if (relevantImports.length > 0) {
37
+ let importsAsterisk = false;
38
+ // imports from import file
39
+ const imports: ts.Node[] = [];
40
+ relevantImports.forEach(n => {
41
+ Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier));
42
+ if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) {
43
+ importsAsterisk = true;
44
+ }
45
+ });
46
+
47
+ // if imports * from fileName, don't add symbolName
48
+ if (importsAsterisk) {
49
+ return new NoopChange();
50
+ }
51
+
52
+ const importTextNodes = imports.filter(n => (n as ts.Identifier).text === symbolName);
53
+
54
+ // insert import if it's not there
55
+ if (importTextNodes.length === 0) {
56
+ const fallbackPos =
57
+ findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].getStart() ||
58
+ findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();
59
+
60
+ return insertAfterLastOccurrence(imports, `, ${symbolName}`, fileToEdit, fallbackPos);
61
+ }
62
+
63
+ return new NoopChange();
64
+ }
65
+
66
+ // no such import declaration exists
67
+ const useStrict = findNodes(rootNode, ts.SyntaxKind.StringLiteral)
68
+ .filter((n: ts.StringLiteral) => n.text === 'use strict');
69
+ let fallbackPos = 0;
70
+ if (useStrict.length > 0) {
71
+ fallbackPos = useStrict[0].end;
72
+ }
73
+ const open = isDefault ? '' : '{ ';
74
+ const close = isDefault ? '' : ' }';
75
+ // if there are no imports or 'use strict' statement, insert import at beginning of file
76
+ const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
77
+ const separator = insertAtBeginning ? '' : ';\n';
78
+ const toInsert = `${separator}import ${open}${symbolName}${close}` +
79
+ ` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`;
80
+
81
+ return insertAfterLastOccurrence(
82
+ allImports,
83
+ toInsert,
84
+ fileToEdit,
85
+ fallbackPos,
86
+ ts.SyntaxKind.StringLiteral,
87
+ );
88
+ }
89
+
90
+
91
+ /**
92
+ * Find all nodes from the AST in the subtree of node of SyntaxKind kind.
93
+ * @param node
94
+ * @param kind
95
+ * @param max The maximum number of items to return.
96
+ * @return all nodes of kind, or [] if none is found
97
+ */
98
+ export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max = Infinity): ts.Node[] {
99
+ if (!node || max == 0) {
100
+ return [];
101
+ }
102
+
103
+ const arr: ts.Node[] = [];
104
+ if (node.kind === kind) {
105
+ arr.push(node);
106
+ max--;
107
+ }
108
+ if (max > 0) {
109
+ for (const child of node.getChildren()) {
110
+ findNodes(child, kind, max).forEach(node => {
111
+ if (max > 0) {
112
+ arr.push(node);
113
+ }
114
+ max--;
115
+ });
116
+
117
+ if (max <= 0) {
118
+ break;
119
+ }
120
+ }
121
+ }
122
+
123
+ return arr;
124
+ }
125
+
126
+
127
+ /**
128
+ * Get all the nodes from a source.
129
+ * @param sourceFile The source file object.
130
+ * @returns {Observable<ts.Node>} An observable of all the nodes in the source.
131
+ */
132
+ export function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[] {
133
+ const nodes: ts.Node[] = [sourceFile];
134
+ const result = [];
135
+
136
+ while (nodes.length > 0) {
137
+ const node = nodes.shift();
138
+
139
+ if (node) {
140
+ result.push(node);
141
+ if (node.getChildCount(sourceFile) >= 0) {
142
+ nodes.unshift(...node.getChildren());
143
+ }
144
+ }
145
+ }
146
+
147
+ return result;
148
+ }
149
+
150
+ export function findNode(node: ts.Node, kind: ts.SyntaxKind, text: string): ts.Node | null {
151
+ if (node.kind === kind && node.getText() === text) {
152
+ // throw new Error(node.getText());
153
+ return node;
154
+ }
155
+
156
+ let foundNode: ts.Node | null = null;
157
+ ts.forEachChild(node, childNode => {
158
+ foundNode = foundNode || findNode(childNode, kind, text);
159
+ });
160
+
161
+ return foundNode;
162
+ }
163
+
164
+
165
+ /**
166
+ * Helper for sorting nodes.
167
+ * @return function to sort nodes in increasing order of position in sourceFile
168
+ */
169
+ function nodesByPosition(first: ts.Node, second: ts.Node): number {
170
+ return first.getStart() - second.getStart();
171
+ }
172
+
173
+
174
+ /**
175
+ * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
176
+ * or after the last of occurence of `syntaxKind` if the last occurence is a sub child
177
+ * of ts.SyntaxKind[nodes[i].kind] and save the changes in file.
178
+ *
179
+ * @param nodes insert after the last occurence of nodes
180
+ * @param toInsert string to insert
181
+ * @param file file to insert changes into
182
+ * @param fallbackPos position to insert if toInsert happens to be the first occurence
183
+ * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after
184
+ * @return Change instance
185
+ * @throw Error if toInsert is first occurence but fall back is not set
186
+ */
187
+ export function insertAfterLastOccurrence(nodes: ts.Node[],
188
+ toInsert: string,
189
+ file: string,
190
+ fallbackPos: number,
191
+ syntaxKind?: ts.SyntaxKind): Change {
192
+ let lastItem = nodes.sort(nodesByPosition).pop();
193
+ if (!lastItem) {
194
+ //throw new Error();
195
+ new InsertChange(file, 0, toInsert); // Eyal Vardi Fix when no import at all.
196
+ }
197
+ if (syntaxKind) {
198
+ lastItem = findNodes(lastItem, syntaxKind).sort(nodesByPosition).pop();
199
+ }
200
+ if (!lastItem && fallbackPos == undefined) {
201
+ throw new Error(`tried to insert ${toInsert} as first occurence with no fallback position`);
202
+ }
203
+ const lastItemPosition: number = lastItem ? lastItem.getEnd() : fallbackPos;
204
+
205
+ return new InsertChange(file, lastItemPosition, toInsert);
206
+ }
207
+
208
+
209
+ export function getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): string | null {
210
+ if (node.kind == ts.SyntaxKind.Identifier) {
211
+ return (node as ts.Identifier).text;
212
+ } else if (node.kind == ts.SyntaxKind.StringLiteral) {
213
+ return (node as ts.StringLiteral).text;
214
+ } else {
215
+ return null;
216
+ }
217
+ }
218
+
219
+
220
+ function _angularImportsFromNode(node: ts.ImportDeclaration,
221
+ _sourceFile: ts.SourceFile): {[name: string]: string} {
222
+ const ms = node.moduleSpecifier;
223
+ let modulePath: string;
224
+ switch (ms.kind) {
225
+ case ts.SyntaxKind.StringLiteral:
226
+ modulePath = (ms as ts.StringLiteral).text;
227
+ break;
228
+ default:
229
+ return {};
230
+ }
231
+
232
+ if (!modulePath.startsWith('@angular/')) {
233
+ return {};
234
+ }
235
+
236
+ if (node.importClause) {
237
+ if (node.importClause.name) {
238
+ // This is of the form `import Name from 'path'`. Ignore.
239
+ return {};
240
+ } else if (node.importClause.namedBindings) {
241
+ const nb = node.importClause.namedBindings;
242
+ if (nb.kind == ts.SyntaxKind.NamespaceImport) {
243
+ // This is of the form `import * as name from 'path'`. Return `name.`.
244
+ return {
245
+ [(nb as ts.NamespaceImport).name.text + '.']: modulePath,
246
+ };
247
+ } else {
248
+ // This is of the form `import {a,b,c} from 'path'`
249
+ const namedImports = nb as ts.NamedImports;
250
+
251
+ return namedImports.elements
252
+ .map((is: ts.ImportSpecifier) => is.propertyName ? is.propertyName.text : is.name.text)
253
+ .reduce((acc: {[name: string]: string}, curr: string) => {
254
+ acc[curr] = modulePath;
255
+
256
+ return acc;
257
+ }, {});
258
+ }
259
+ }
260
+
261
+ return {};
262
+ } else {
263
+ // This is of the form `import 'path';`. Nothing to do.
264
+ return {};
265
+ }
266
+ }
267
+
268
+
269
+ export function getDecoratorMetadata(source: ts.SourceFile, identifier: string,
270
+ module: string): ts.Node[] {
271
+ const angularImports: {[name: string]: string}
272
+ = findNodes(source, ts.SyntaxKind.ImportDeclaration)
273
+ .map((node: ts.ImportDeclaration) => _angularImportsFromNode(node, source))
274
+ .reduce((acc: {[name: string]: string}, current: {[name: string]: string}) => {
275
+ for (const key of Object.keys(current)) {
276
+ acc[key] = current[key];
277
+ }
278
+
279
+ return acc;
280
+ }, {});
281
+
282
+ return getSourceNodes(source)
283
+ .filter(node => {
284
+ return node.kind == ts.SyntaxKind.Decorator
285
+ && (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression;
286
+ })
287
+ .map(node => (node as ts.Decorator).expression as ts.CallExpression)
288
+ .filter(expr => {
289
+ if (expr.expression.kind == ts.SyntaxKind.Identifier) {
290
+ const id = expr.expression as ts.Identifier;
291
+
292
+ return id.getFullText(source) == identifier
293
+ && angularImports[id.getFullText(source)] === module;
294
+ } else if (expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression) {
295
+ // This covers foo.NgModule when importing * as foo.
296
+ const paExpr = expr.expression as ts.PropertyAccessExpression;
297
+ // If the left expression is not an identifier, just give up at that point.
298
+ if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {
299
+ return false;
300
+ }
301
+
302
+ const id = paExpr.name.text;
303
+ const moduleId = (paExpr.expression as ts.Identifier).getText(source);
304
+
305
+ return id === identifier && (angularImports[moduleId + '.'] === module);
306
+ }
307
+
308
+ return false;
309
+ })
310
+ .filter(expr => expr.arguments[0]
311
+ && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
312
+ .map(expr => expr.arguments[0] as ts.ObjectLiteralExpression);
313
+ }
314
+
315
+ function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration|undefined {
316
+ if (ts.isClassDeclaration(node)) {
317
+ return node;
318
+ }
319
+
320
+ return node.parent && findClassDeclarationParent(node.parent);
321
+ }
322
+
323
+ /**
324
+ * Given a source file with @NgModule class(es), find the name of the first @NgModule class.
325
+ *
326
+ * @param source source file containing one or more @NgModule
327
+ * @returns the name of the first @NgModule, or `undefined` if none is found
328
+ */
329
+ export function getFirstNgModuleName(source: ts.SourceFile): string|undefined {
330
+ // First, find the @NgModule decorators.
331
+ const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core');
332
+ if (ngModulesMetadata.length === 0) {
333
+ return undefined;
334
+ }
335
+
336
+ // Then walk parent pointers up the AST, looking for the ClassDeclaration parent of the NgModule
337
+ // metadata.
338
+ const moduleClass = findClassDeclarationParent(ngModulesMetadata[0]);
339
+ if (!moduleClass || !moduleClass.name) {
340
+ return undefined;
341
+ }
342
+
343
+ // Get the class name of the module ClassDeclaration.
344
+ return moduleClass.name.text;
345
+ }
346
+
347
+ export function addSymbolToNgModuleMetadata(
348
+ source: ts.SourceFile,
349
+ ngModulePath: string,
350
+ metadataField: string,
351
+ symbolName: string,
352
+ importPath: string | null = null,
353
+ ): Change[] {
354
+ const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
355
+ let node: any = nodes[0]; // tslint:disable-line:no-any
356
+ // Find the decorator declaration.
357
+ if (!node) {
358
+ return [];
359
+ }
360
+
361
+ // Get all the children property assignment of object literals.
362
+ const matchingProperties: ts.ObjectLiteralElement[] =
363
+ (node as ts.ObjectLiteralExpression).properties
364
+ .filter(prop => prop.kind == ts.SyntaxKind.PropertyAssignment)
365
+ // Filter out every fields that's not "metadataField". Also handles string literals
366
+ // (but not expressions).
367
+ .filter((prop: ts.PropertyAssignment) => {
368
+ const name = prop.name;
369
+ switch (name.kind) {
370
+ case ts.SyntaxKind.Identifier:
371
+ return (name as ts.Identifier).getText(source) == metadataField;
372
+ case ts.SyntaxKind.StringLiteral:
373
+ return (name as ts.StringLiteral).text == metadataField;
374
+ }
375
+
376
+ return false;
377
+ });
378
+
379
+ // Get the last node of the array literal.
380
+ if (!matchingProperties) {
381
+ return [];
382
+ }
383
+ if (matchingProperties.length == 0) {
384
+ // We haven't found the field in the metadata declaration. Insert a new field.
385
+ const expr = node as ts.ObjectLiteralExpression;
386
+ let position: number;
387
+ let toInsert: string;
388
+ if (expr.properties.length == 0) {
389
+ position = expr.getEnd() - 1;
390
+ toInsert = ` ${metadataField}: [${symbolName}]\n`;
391
+ } else {
392
+ node = expr.properties[expr.properties.length - 1];
393
+ position = node.getEnd();
394
+ // Get the indentation of the last element, if any.
395
+ const text = node.getFullText(source);
396
+ const matches = text.match(/^\r?\n\s*/);
397
+ if (matches.length > 0) {
398
+ toInsert = `,${matches[0]}${metadataField}: [${symbolName}]`;
399
+ } else {
400
+ toInsert = `, ${metadataField}: [${symbolName}]`;
401
+ }
402
+ }
403
+ if (importPath !== null) {
404
+ return [
405
+ new InsertChange(ngModulePath, position, toInsert),
406
+ insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
407
+ ];
408
+ } else {
409
+ return [new InsertChange(ngModulePath, position, toInsert)];
410
+ }
411
+ }
412
+ const assignment = matchingProperties[0] as ts.PropertyAssignment;
413
+
414
+ // If it's not an array, nothing we can do really.
415
+ if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
416
+ return [];
417
+ }
418
+
419
+ const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression;
420
+ if (arrLiteral.elements.length == 0) {
421
+ // Forward the property.
422
+ node = arrLiteral;
423
+ } else {
424
+ node = arrLiteral.elements;
425
+ }
426
+
427
+ if (!node) {
428
+ console.log('No app module found. Please add your new class to your component.');
429
+
430
+ return [];
431
+ }
432
+
433
+ if (Array.isArray(node)) {
434
+ const nodeArray = node as {} as Array<ts.Node>;
435
+ const symbolsArray = nodeArray.map(node => node.getText());
436
+ if (symbolsArray.includes(symbolName)) {
437
+ return [];
438
+ }
439
+
440
+ node = node[node.length - 1];
441
+ }
442
+
443
+ let toInsert: string;
444
+ let position = node.getEnd();
445
+ if (node.kind == ts.SyntaxKind.ObjectLiteralExpression) {
446
+ // We haven't found the field in the metadata declaration. Insert a new
447
+ // field.
448
+ const expr = node as ts.ObjectLiteralExpression;
449
+ if (expr.properties.length == 0) {
450
+ position = expr.getEnd() - 1;
451
+ toInsert = ` ${metadataField}: [${symbolName}]\n`;
452
+ } else {
453
+ node = expr.properties[expr.properties.length - 1];
454
+ position = node.getEnd();
455
+ // Get the indentation of the last element, if any.
456
+ const text = node.getFullText(source);
457
+ if (text.match('^\r?\r?\n')) {
458
+ toInsert = `,${text.match(/^\r?\n\s+/)[0]}${metadataField}: [${symbolName}]`;
459
+ } else {
460
+ toInsert = `, ${metadataField}: [${symbolName}]`;
461
+ }
462
+ }
463
+ } else if (node.kind == ts.SyntaxKind.ArrayLiteralExpression) {
464
+ // We found the field but it's empty. Insert it just before the `]`.
465
+ position--;
466
+ toInsert = `${symbolName}`;
467
+ } else {
468
+ // Get the indentation of the last element, if any.
469
+ const text = node.getFullText(source);
470
+ if (text.match(/^\r?\n/)) {
471
+ toInsert = `,${text.match(/^\r?\n(\r?)\s+/)[0]}${symbolName}`;
472
+ } else {
473
+ toInsert = `, ${symbolName}`;
474
+ }
475
+ }
476
+ if (importPath !== null) {
477
+ return [
478
+ new InsertChange(ngModulePath, position, toInsert),
479
+ insertImport(source, ngModulePath, symbolName.replace(/\..*$/, ''), importPath),
480
+ ];
481
+ }
482
+
483
+ return [new InsertChange(ngModulePath, position, toInsert)];
484
+ }
485
+
486
+ /**
487
+ * Custom function to insert a declaration (component, pipe, directive)
488
+ * into NgModule declarations. It also imports the component.
489
+ */
490
+ export function addDeclarationToModule(source: ts.SourceFile,
491
+ modulePath: string, classifiedName: string,
492
+ importPath: string): Change[] {
493
+ return addSymbolToNgModuleMetadata(
494
+ source, modulePath, 'declarations', classifiedName, importPath);
495
+ }
496
+
497
+ /**
498
+ * Custom function to insert an NgModule into NgModule imports. It also imports the module.
499
+ */
500
+ export function addImportToModule(source: ts.SourceFile,
501
+ modulePath: string, classifiedName: string,
502
+ importPath: string): Change[] {
503
+
504
+ return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
505
+ }
506
+
507
+ /**
508
+ * Custom function to insert a provider into NgModule. It also imports it.
509
+ */
510
+ export function addProviderToModule(source: ts.SourceFile,
511
+ modulePath: string, classifiedName: string,
512
+ importPath: string): Change[] {
513
+ return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
514
+ }
515
+
516
+ /**
517
+ * Custom function to insert an export into NgModule. It also imports it.
518
+ */
519
+ export function addExportToModule(source: ts.SourceFile,
520
+ modulePath: string, classifiedName: string,
521
+ importPath: string): Change[] {
522
+ return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
523
+ }
524
+
525
+ /**
526
+ * Custom function to insert an export into NgModule. It also imports it.
527
+ */
528
+ export function addBootstrapToModule(source: ts.SourceFile,
529
+ modulePath: string, classifiedName: string,
530
+ importPath: string): Change[] {
531
+ return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
532
+ }
533
+
534
+ /**
535
+ * Custom function to insert an entryComponent into NgModule. It also imports it.
536
+ */
537
+ export function addEntryComponentToModule(source: ts.SourceFile,
538
+ modulePath: string, classifiedName: string,
539
+ importPath: string): Change[] {
540
+ return addSymbolToNgModuleMetadata(
541
+ source, modulePath,
542
+ 'entryComponents', classifiedName, importPath,
543
+ );
544
+ }
545
+
546
+ /**
547
+ * Determine if an import already exists.
548
+ */
549
+ export function isImported(source: ts.SourceFile,
550
+ classifiedName: string,
551
+ importPath: string): boolean {
552
+ const allNodes = getSourceNodes(source);
553
+ const matchingNodes = allNodes
554
+ .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration)
555
+ .filter((imp: ts.ImportDeclaration) => imp.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral)
556
+ .filter((imp: ts.ImportDeclaration) => {
557
+ return (<ts.StringLiteral> imp.moduleSpecifier).text === importPath;
558
+ })
559
+ .filter((imp: ts.ImportDeclaration) => {
560
+ if (!imp.importClause) {
561
+ return false;
562
+ }
563
+ const nodes = findNodes(imp.importClause, ts.SyntaxKind.ImportSpecifier)
564
+ .filter(n => n.getText() === classifiedName);
565
+
566
+ return nodes.length > 0;
567
+ });
568
+
569
+ return matchingNodes.length > 0;
570
+ }