|
| 1 | + |
| 2 | +const fs = require('fs'); |
| 3 | +const path = require('path'); |
| 4 | +//The Flow Parser is a JavaScript parser written in OCaml. It produces an AST that conforms to the ESTree spec and that mostly matches what esprima produces. |
| 5 | +const flowParser = require('flow-parser'); |
| 6 | + |
| 7 | +/** |
| 8 | + * Iterates through AST Object and returns the entry point for the Class or Function Block; |
| 9 | + * @param {Object} obj AST JSON Object |
| 10 | + */ |
| 11 | +function getClassEntry(obj) { |
| 12 | + let entry = null; |
| 13 | + // Start lookup if Program body has ClassDeclaration or inside ExportDefaultDeclaration has ClassDeclaration |
| 14 | + for (let elem of obj.body) { |
| 15 | + if (elem.type === 'ClassDeclaration') { |
| 16 | + return entry = elem.body; |
| 17 | + } |
| 18 | + else if (elem.type === 'ExportDefaultDeclaration' && elem.declaration.type === 'ClassDeclaration') { |
| 19 | + return entry = elem.declaration.body; |
| 20 | + } |
| 21 | + } |
| 22 | + return entry; |
| 23 | +} |
| 24 | +/** |
| 25 | + * grabs state of stateful Component if available; |
| 26 | + * @param {Object} obj AST object created from file at Class Block |
| 27 | + */ |
| 28 | +function grabState(obj) { |
| 29 | + let ret = []; |
| 30 | + let entry = getClassEntry(obj); |
| 31 | + if (entry) ret = digStateInClassBody(entry); |
| 32 | + return ret; |
| 33 | +} |
| 34 | +/** |
| 35 | + * traverses through AST object and returns entry point for constructor Object; |
| 36 | + * @param {Object} obj - classBody object from AST |
| 37 | + */ |
| 38 | +function digStateInClassBody(obj) { |
| 39 | + if (obj.type !== 'ClassBody') |
| 40 | + return; |
| 41 | + let ret = []; |
| 42 | + obj.body.forEach((elem) => { |
| 43 | + if (elem.type = "MethodDefinition" && elem.key.name === "constructor") { |
| 44 | + ret = digStateInBlockStatement(elem.value.body); |
| 45 | + } |
| 46 | + }); |
| 47 | + return ret; |
| 48 | +} |
| 49 | + |
| 50 | +function parseNestedObjects(stateValue, nested=false){ |
| 51 | + //check if the array is nested. Only use for arrays |
| 52 | + const curr = nested ? stateValue : stateValue.value; |
| 53 | + if(curr.type === 'ObjectExpression'){ |
| 54 | + //iterate through object properties and store them in values |
| 55 | + let values = {} |
| 56 | + for(let key in stateValue.value.properties){ |
| 57 | + values[key] = parseNestedObjects(stateValue.value.properties[key]) |
| 58 | + } |
| 59 | + return values |
| 60 | + } |
| 61 | + else if(curr.type === 'ArrayExpression'){ |
| 62 | + let values = [] |
| 63 | + let currObj = curr.elements; |
| 64 | + for(let key in currObj){ |
| 65 | + values.push(parseNestedObjects(currObj[key],true)) |
| 66 | + } |
| 67 | + return values |
| 68 | + } |
| 69 | + else { |
| 70 | + return curr.value; |
| 71 | + } |
| 72 | +} |
| 73 | +/** |
| 74 | + * traverses through AST BlockStatement object and returns the state of Component; |
| 75 | + * @param {*} obj |
| 76 | + */ |
| 77 | +function digStateInBlockStatement(obj) { |
| 78 | + if (obj.type !== 'BlockStatement') return; |
| 79 | + let ret = {}; |
| 80 | + obj.body.forEach((element) => { |
| 81 | + if (element.type === "ExpressionStatement" && element.expression.type === "AssignmentExpression") |
| 82 | + if (element.expression.left.property.name === 'state') { |
| 83 | + if (element.expression.right.type === "ObjectExpression"){ |
| 84 | + element.expression.right.properties.forEach(elem => { |
| 85 | + // ret[elem.key.name] = elem.value.value; |
| 86 | + ret[elem.key.name] = parseNestedObjects(elem) |
| 87 | + // console.log('parseNestedObjects return value', parseNestedObjects(elem)) |
| 88 | + }); |
| 89 | + } |
| 90 | + } |
| 91 | + }); |
| 92 | + // console.log('return' ,ret) |
| 93 | + return ret; |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * parses through AST Object and returns an object of props |
| 98 | + * @param {Array} arrOfAttr - Array of AST Object attributes |
| 99 | + */ |
| 100 | +function grabAttr(arrOfAttr) { |
| 101 | + return arrOfAttr.reduce((acc, curr) => { |
| 102 | + if (curr.value.type === 'JSXExpressionContainer') { |
| 103 | + if (curr.value.expression.type === 'ArrowFunctionExpression' || curr.value.expression.type === 'FunctionExpression') { |
| 104 | + if(curr.value.expression.body.body) { |
| 105 | + acc[curr.name.name] = curr.value.expression.body.body[0].expression.callee.name |
| 106 | + } else { |
| 107 | + acc[curr.name.name] = curr.value.expression.body.callee.name |
| 108 | + } |
| 109 | + } else if (curr.value.expression.type === 'Literal') { |
| 110 | + acc[curr.name.name] = curr.value.expression.value; |
| 111 | + } else if (curr.value.expression.type === 'MemberExpression') { |
| 112 | + acc[curr.name.name] = curr.value.expression.property.name; |
| 113 | + } else if (curr.value.expression.type === 'ConditionalExpression') { |
| 114 | + let condition, consequent, alternate; |
| 115 | + if(curr.value.expression.test.type === 'MemberExpression') { |
| 116 | + condition = curr.value.expression.test.property.name; |
| 117 | + } else{ |
| 118 | + condition = curr.value.expression.test.name; |
| 119 | + } |
| 120 | + if(curr.value.expression.consequent.type === 'MemberExpression') { |
| 121 | + consequent = curr.value.expression.consequent.property.name; |
| 122 | + } else { |
| 123 | + consequent = curr.value.expression.consequent.name; |
| 124 | + } |
| 125 | + if(curr.value.expression.alternate.type === 'MemberExpression') { |
| 126 | + alternate = curr.value.expression.alternate.property.name; |
| 127 | + } else{ |
| 128 | + alternate = curr.value.expression.consequent.name; |
| 129 | + } |
| 130 | + acc[curr.name.name + 'True'] = {condition: condition, value:consequent}; |
| 131 | + |
| 132 | + acc[curr.name.name + 'False'] = {condition: condition, value: alternate} |
| 133 | + } else { |
| 134 | + acc[curr.name.name] = curr.value.expression.name; |
| 135 | + } |
| 136 | + } else { |
| 137 | + acc[curr.name.name] = curr.value.value; |
| 138 | + } |
| 139 | + return acc; |
| 140 | + },{}) |
| 141 | +}; |
| 142 | +/** |
| 143 | + * returns an Array of Objects with the name and path of IMPORT objects |
| 144 | + * @param {Object} json- AST Object |
| 145 | + */ |
| 146 | +function grabImportNameAndPath(json) { |
| 147 | + let output; |
| 148 | + //inputted AST has a property named body that is an array of objects |
| 149 | + //importObjectArr is filtered |
| 150 | + const importObjectArr = json.body.filter((importObj) => { |
| 151 | + //whatever importObjs have a 'type' value of 'ImportDeclaration' are what are returned |
| 152 | + if (importObj.type === 'ImportDeclaration') { |
| 153 | + return { |
| 154 | + importObj |
| 155 | + } |
| 156 | + } |
| 157 | + }) |
| 158 | + //importObjectArr is mappped over and if the importObj.specifiers[0] is true/truthy, a new object is returned |
| 159 | + // console.log(importObjectArr, 'XXX'); |
| 160 | + output = importObjectArr.map((importObj) => { |
| 161 | + if (importObj.specifiers[0]) { |
| 162 | + return { |
| 163 | + name: importObj.specifiers[0].local.name, |
| 164 | + path: importObj.source.value, |
| 165 | + } |
| 166 | + } |
| 167 | + }) |
| 168 | + // output is reassigned to the array returned by filtering anything that isn't true/truthy |
| 169 | + // console.log(output, '***'); |
| 170 | + output = output.filter((obj) => { |
| 171 | + if (obj) { |
| 172 | + return obj; |
| 173 | + } |
| 174 | + }) |
| 175 | + // console.log(output, 'SSS'); |
| 176 | + //an array of imported objects is returned |
| 177 | + return output; |
| 178 | +} |
| 179 | +/** |
| 180 | + * returns an Object with Component name and props from AST Object; |
| 181 | + * @param {Object} returnObj - AST object |
| 182 | + */ |
| 183 | +const constructComponentProps = (returnObj) => { |
| 184 | + const output = {}; |
| 185 | + output[returnObj.openingElement.name.name] = grabAttr(returnObj.openingElement.attributes) |
| 186 | + return output; |
| 187 | +} |
| 188 | +/** |
| 189 | + * returns Object with name and props of current Component; |
| 190 | + * @param {String} jsxPath - Path of file to convert into a AST object |
| 191 | + */ |
| 192 | +function constructSingleLevel(jsxPath) { |
| 193 | + let reactObj = {}; |
| 194 | + // fileContent stores the file at the jsxPath |
| 195 | + const fileContent = fs.readFileSync(jsxPath, { encoding: 'utf-8' }); |
| 196 | + //jsonObj uses flowParser to turn the file into an AST |
| 197 | + let jsonObj = flowParser.parse(fileContent); |
| 198 | + // checks for Components in imports section |
| 199 | + let imports = grabImportNameAndPath(jsonObj); |
| 200 | + let componentTags = grabChildComponents(imports, fileContent); |
| 201 | + // checks if component is Stateful and grabs state; |
| 202 | + let state = grabState(jsonObj); |
| 203 | + // iterates through components array and creates object with Component name, props and path; |
| 204 | + if (componentTags !== null){ |
| 205 | + componentTags.forEach(elem => { |
| 206 | + let ast = flowParser.parse(elem).body[0].expression |
| 207 | + reactObj = Object.assign(reactObj, constructComponentProps(ast)); |
| 208 | + }); |
| 209 | + imports = imports.filter(comp => { |
| 210 | + comp.props = reactObj[comp.name] |
| 211 | + return Object.keys(reactObj).includes(comp.name); |
| 212 | + }); |
| 213 | + } else { |
| 214 | + imports = []; |
| 215 | + } |
| 216 | + let outputObj = { |
| 217 | + name: path.basename(jsxPath).split('.')[0], |
| 218 | + childProps: imports, |
| 219 | + stateProps: state, |
| 220 | + children: [] |
| 221 | + } |
| 222 | + return outputObj; |
| 223 | +} |
| 224 | +/** |
| 225 | + * recursively traverses through all folders given from filePath and creates JSON Object; |
| 226 | + * @param {String} filePath Path to Component folder |
| 227 | + * @param {String} rootPath - name of File |
| 228 | + */ |
| 229 | +function constructComponentTree(filePath, rootPath) { |
| 230 | + // create object at current level; |
| 231 | + let result = constructSingleLevel(path.join(rootPath, filePath)); |
| 232 | + // checks if current Object has children and traverses through children to create Object; |
| 233 | + if(result && Object.keys(result.childProps).length > 0){ |
| 234 | + for(let childProp of result.childProps) { |
| 235 | + //creates new path for children components - if girootPath doesnt have an extension adds .js extension |
| 236 | + let fullPath = path.join(rootPath, childProp.path); |
| 237 | + let newRootPath = path.dirname(fullPath); |
| 238 | + let newFileName = path.basename(fullPath); |
| 239 | + let childPathSplit = newFileName.split('.'); |
| 240 | + if (childPathSplit.length === 1) |
| 241 | + newFileName += '.js'; |
| 242 | + let newFullPath = path.join(newRootPath, newFileName); |
| 243 | + //traverses through children |
| 244 | + result.children.push(constructComponentTree(newFileName, newRootPath)); |
| 245 | + } |
| 246 | + } |
| 247 | + return result; |
| 248 | +} |
| 249 | +/** |
| 250 | + * returns an array of React Components in String Format, checks imports array and filters fileContent to find Components; |
| 251 | + * @param {Array} imports - Array of Objects with name and path of all Import Objects; |
| 252 | + * @param {String} fileContent - String of File Content; |
| 253 | + */ |
| 254 | +function grabChildComponents(imports, fileContent) { |
| 255 | + // console.log(imports, fileContent, '***'); |
| 256 | + // grab all import object name from import array; |
| 257 | + let compNames = imports.reduce((arr, cur) => { |
| 258 | + // skips <Provider/> component from redux |
| 259 | + if (cur.name !== 'Provider') { |
| 260 | + arr.push(cur.name); |
| 261 | + } |
| 262 | + return arr; |
| 263 | + }, []); |
| 264 | + // console.log(compNames, 'XXX'); |
| 265 | + // format all import names for regex |
| 266 | + compNames = compNames.join('|'); |
| 267 | + let pattern = '<\s*(' + compNames + ')(>|(.|[\r\n])*?[^?]>)' |
| 268 | + const regExp = new RegExp(pattern, 'g'); |
| 269 | + // finds all components that match imports; |
| 270 | + let matchedComponents = fileContent.match(regExp); |
| 271 | + |
| 272 | + return matchedComponents; |
| 273 | +} |
| 274 | + |
| 275 | +module.exports = {grabChildComponents, constructComponentTree, constructSingleLevel, constructComponentProps, grabImportNameAndPath, grabAttr, digStateInBlockStatement, digStateInClassBody, grabState, getClassEntry} |
0 commit comments