|
| 1 | +import * as ts from 'typescript'; |
| 2 | +import * as fs from 'fs'; |
| 3 | +import {findNodes, insertAfterLastOccurence} from './ast-utils'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Adds provideRouter configuration to the main file (import and bootstrap) if |
| 7 | + * main file hasn't been already configured, else it has no effect. |
| 8 | + * |
| 9 | + * @param (mainFile) path to main.ts in ng project |
| 10 | + * @param (routesName) exported name for the routes array from routesFile |
| 11 | + * @param (routesFile) |
| 12 | + */ |
| 13 | +export function configureMain(mainFile: string, routesName: string, routesFile: string): Promise<void>{ |
| 14 | + return insertImport(mainFile, 'provideRouter', '@angular/router') |
| 15 | + .then(() => { |
| 16 | + return insertImport(mainFile, routesName, routesFile, true); |
| 17 | + }).then(() => { |
| 18 | + let rootNode = ts.createSourceFile(mainFile, fs.readFileSync(mainFile).toString(), |
| 19 | + ts.ScriptTarget.ES6, true); |
| 20 | + // get ExpressionStatements from the top level syntaxList of the sourceFile |
| 21 | + let bootstrapNodes = rootNode.getChildAt(0).getChildren().filter(node => { |
| 22 | + // get bootstrap expressions |
| 23 | + return node.kind === ts.SyntaxKind.ExpressionStatement && |
| 24 | + node.getChildAt(0).getChildAt(0).text.toLowerCase() === 'bootstrap'; |
| 25 | + }); |
| 26 | + // printAll(bootstrapNodes[0].getChildAt(0).getChildAt(2).getChildAt(2)); |
| 27 | + if (bootstrapNodes.length !== 1) { |
| 28 | + return Promise.reject(new Error(`Did not bootstrap provideRouter in ${mainFile} because of multiple or no bootstrap calls`)); |
| 29 | + } |
| 30 | + let bootstrapNode = bootstrapNodes[0].getChildAt(0); |
| 31 | + let isBootstraped = findNodes(bootstrapNode, ts.SyntaxKind.Identifier).map(_ => _.text).indexOf('provideRouter') !== -1; |
| 32 | + |
| 33 | + if (isBootstraped) { |
| 34 | + return Promise.resolve(); |
| 35 | + } |
| 36 | + // if bracket exitst already, add configuration template, |
| 37 | + // otherwise, insert into bootstrap parens |
| 38 | + var fallBackPos: number, configurePathsTemplate: string, separator: string, syntaxListNodes: any; |
| 39 | + let bootstrapProviders = bootstrapNode.getChildAt(2).getChildAt(2); // array of providers |
| 40 | + |
| 41 | + if ( bootstrapProviders ) { |
| 42 | + syntaxListNodes = bootstrapProviders.getChildAt(1).getChildren(); |
| 43 | + fallBackPos = bootstrapProviders.getChildAt(2).pos; // closeBracketLiteral |
| 44 | + separator = syntaxListNodes.length === 0 ? '' : ', '; |
| 45 | + configurePathsTemplate = `provideRouter(${routesName})`; |
| 46 | + } else { |
| 47 | + fallBackPos = bootstrapNode.getChildAt(3).pos; // closeParenLiteral |
| 48 | + syntaxListNodes = bootstrapNode.getChildAt(2).getChildren(); |
| 49 | + configurePathsTemplate = `, [provideRouter(${routesName})]`; |
| 50 | + separator = ''; |
| 51 | + } |
| 52 | + |
| 53 | + return insertAfterLastOccurence(syntaxListNodes, separator, configurePathsTemplate, |
| 54 | + mainFile, fallBackPos); |
| 55 | + }); |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Inserts a path to the new route into src/routes.ts if it doesn't exist |
| 60 | + * @param routesFile |
| 61 | + * @param pathOptions |
| 62 | + * @return Promise |
| 63 | + * @throws Error if routesFile has multiple export default or none. |
| 64 | + */ |
| 65 | +export function addPathToRoutes(routesFile: string, pathOptions: {[key: string]: any}): Promise<void>{ |
| 66 | + let importPath = pathOptions.dir.replace(pathOptions.appRoot, '') + `/+${pathOptions.dasherizedName}`; |
| 67 | + let path: string = pathOptions.path || importPath.replace(/\+/g, ''); |
| 68 | + let isDefault = pathOptions.isDefault ? ', terminal: true' : ''; |
| 69 | + let content = ` { path: '${path}', component: ${pathOptions.component}${isDefault} }`; |
| 70 | + |
| 71 | + let rootNode = ts.createSourceFile(routesFile, fs.readFileSync(routesFile).toString(), |
| 72 | + ts.ScriptTarget.ES6, true); |
| 73 | + let routesNode = rootNode.getChildAt(0).getChildren().filter(n => { |
| 74 | + // get export statement |
| 75 | + return n.kind === ts.SyntaxKind.ExportAssignment && |
| 76 | + n.getFullText().indexOf('export default') !== -1; |
| 77 | + }); |
| 78 | + if (routesNode.length !== 1){ |
| 79 | + return Promise.reject(new Error('Did not insert path in routes.ts because' + |
| 80 | + `there were multiple or no 'export default' statements`)); |
| 81 | + } |
| 82 | + let routesArray = routesNode[0].getChildAt(2).getChildAt(1).getChildren(); // all routes in export route array |
| 83 | + let routeExists = routesArray.map(r => r.getFullText()).indexOf(`\n${content}`) !== -1; |
| 84 | + if (routeExists){ |
| 85 | + // add import in case it hasn't been added already |
| 86 | + return insertImport(routesFile, pathOptions.component, `./app${importPath}`); |
| 87 | + } |
| 88 | + let fallBack = routesNode[0].getChildAt(2).getChildAt(2).pos; // closeBracketLiteral |
| 89 | + let separator = routesArray.length > 0 ? ',\n' : '\n'; |
| 90 | + content = routesArray.length === 0 ? content + '\n' : content; // expand array before inserting path |
| 91 | + return insertAfterLastOccurence(routesArray, separator, content, routesFile, fallBack).then(() => { |
| 92 | + return insertImport(routesFile, pathOptions.component, `./app${importPath}`); |
| 93 | + }); |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | +* Add Import `import { symbolName } from fileName` if the import doesn't exit |
| 98 | +* already. Assumes fileToEdit can be resolved and accessed. |
| 99 | +* @param fileToEdit (file we want to add import to) |
| 100 | +* @param symbolName (item to import) |
| 101 | +* @param fileName (path to the file) |
| 102 | +* @param isDefault (if true, import follows style for importing default exports) |
| 103 | +*/ |
| 104 | + |
| 105 | +export function insertImport(fileToEdit: string, symbolName: string, |
| 106 | + fileName: string, isDefault=false): Promise<void> { |
| 107 | + let rootNode = ts.createSourceFile(fileToEdit, fs.readFileSync(fileToEdit).toString(), |
| 108 | + ts.ScriptTarget.ES6, true); |
| 109 | + let allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration); |
| 110 | + |
| 111 | + // get nodes that map to import statements from the file fileName |
| 112 | + let relevantImports = allImports.filter(node => { |
| 113 | + // StringLiteral of the ImportDeclaration is the import file (fileName in this case). |
| 114 | + let importFiles = node.getChildren().filter(child => child.kind === ts.SyntaxKind.StringLiteral) |
| 115 | + .map(n => (<ts.StringLiteralTypeNode>n).text); |
| 116 | + return importFiles.filter(file => file === fileName).length === 1; |
| 117 | + }); |
| 118 | + |
| 119 | + if (relevantImports.length > 0) { |
| 120 | + |
| 121 | + var importsAsterisk: boolean = false; |
| 122 | + // imports from import file |
| 123 | + let imports: ts.Node[] = []; |
| 124 | + relevantImports.forEach(n => { |
| 125 | + Array.prototype.push.apply(imports, findNodes(n, ts.SyntaxKind.Identifier)); |
| 126 | + if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) { |
| 127 | + importsAsterisk = true; |
| 128 | + } |
| 129 | + }); |
| 130 | + |
| 131 | + // if imports * from fileName, don't add symbolName |
| 132 | + if (importsAsterisk) { |
| 133 | + return Promise.resolve(); |
| 134 | + } |
| 135 | + |
| 136 | + let importTextNodes = imports.filter(n => (<ts.Identifier>n).text === symbolName); |
| 137 | + |
| 138 | + // insert import if it's not there |
| 139 | + if (importTextNodes.length === 0) { |
| 140 | + let fallbackPos = findNodes(relevantImports[0], ts.SyntaxKind.CloseBraceToken)[0].pos || |
| 141 | + findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].pos; |
| 142 | + return insertAfterLastOccurence(imports, ', ', symbolName, fileToEdit, fallbackPos); |
| 143 | + } |
| 144 | + return Promise.resolve(); |
| 145 | + } |
| 146 | + |
| 147 | + // no such import declaration exists |
| 148 | + let useStrict = findNodes(rootNode, ts.SyntaxKind.StringLiteral).filter(n => n.text === 'use strict'); |
| 149 | + let fallbackPos: number = 0; |
| 150 | + if(useStrict.length > 0){ |
| 151 | + fallbackPos = useStrict[0].end; |
| 152 | + } |
| 153 | + let open = isDefault ? '' : '{ '; |
| 154 | + let close = isDefault ? '' : ' }'; |
| 155 | + // if there are no imports or 'use strict' statement, insert import at beginning of file |
| 156 | + let insertAtBeginning = allImports.length === 0 && useStrict.length === 0; |
| 157 | + let separator = insertAtBeginning ? '' : ';\n'; |
| 158 | + return insertAfterLastOccurence(allImports, separator, `import ${open}${symbolName}${close}` + |
| 159 | + ` from '${fileName}'${insertAtBeginning ? ';\n':''}`, |
| 160 | + fileToEdit, fallbackPos, ts.SyntaxKind.StringLiteral); |
| 161 | +}; |
| 162 | + |
0 commit comments