all files / lib/ handlerParser.js

97.44% Statements 76/78
77.78% Branches 14/18
100% Functions 12/12
97.33% Lines 73/75
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157                                  22× 22×   22×       22× 22×         26× 26× 26× 26× 26×   26× 11× 11× 11× 11×   26× 26×   26× 79×       22×             38×           11× 11×       11× 11× 11× 344× 344× 48× 178×   48× 48× 48× 48× 44×   48×               48×     48× 48× 222×     222× 38×   222× 44×   222×       48× 48× 48× 48×           26×       15× 15× 31×         31× 31× 31× 67×     67×   31×     31× 31× 31× 31× 31×        
'use strict'
 
const logger = require("./logger"), 
	fs = require("fs"),
	stripComments = require("strip-json-comments"),
	os = require("os"),
	_ = require("lodash");
 
 
const CONFIG_FILE_PATH = process.cwd() + "/vatican-conf.json";
 
 
const CLASS_HEADER_REGEXP = /class ([a-zA-Z0-9]+ *){/;
 
const ES5endpointRE = /@endpoint\s*\((url:.+)\s*(method:(?:[ \t]*)(?:get|put|post|delete))\s*(name:.+)?\s*\)[\s\n]*([^\s]*)\.prototype\.([^\s]*)/gim
 
const ES6endpointRE = /(?:@endpoint)?\(?((?:[a-z]+:\s*[a-z_:,\.\[\]\/0-9]+)+)[ ]*\)?/gim
const ES6ActionNameRE = /[\t]*([a-z]+)\([a-z, ]+\)/i
 
const ES6classNameRE = /class ([a-zA-Z-0-9_ ]+) *{/;
 
 
module.exports = class HandlerParser {
 
	static parse(dir, cb) {
		var paths = [];
	    fs.readdir(dir, function(err, files) {
 
	        Iif(err) {
	            logger.error("Error reading folder: " + dir);
	            cb("Error reading folder: " + dir);
	        } else {
	        	let fpath = "";
	        	let matches = null,
	        		handlerName = null,
	        		content = null;
 
 
	            _(files).where(function(f) { return f.match(/\.js$/i); }).forEach(function(fname) {
	                fpath = dir + "/" + fname;
	                logger.info("Openning file: " + fpath);
	                content = fs.readFileSync(fpath).toString();
	                let matchesParser = new ES5MatchesParser(fpath);
 
	                if(content.match(CLASS_HEADER_REGEXP)) {
	                	logger.info("ES6 class detected, using ES6 params");
	                	let classNameParts = content.match(ES6classNameRE);
						let handlerClassName = classNameParts[1].trim();
		                matchesParser = new ES6MatchesParser(fpath, handlerClassName);
	                } 
	                content = content.replace(/\/\/\s*@/g, "@") //We allow commenting the line of the endpoint for correct editor syntax coloring
	                content = stripComments(content) //we remove the comments so we don't deal with commented out endpoints
 
	                matchesParser.parse(content, (match) => {
	                	paths.push(matchesParser.getPath(match));
	                })
 
	            });
				cb(null, paths);
	        }
	    });
	}
 
}
 
function parseVersionsMetadata(data) {
	return data.replace(/\[/g, "").replace(/\]/g, "").split(",");
}
 
class ES6MatchesParser {
 
	constructor(fpath, className) {
		this.fpath = fpath;
		this.className = className;
	}
 
	parse(content, matchCB) {
		let lines = content.split(os.EOL);
		let annotationMatches;
		lines.forEach( (line, idx) => {
			let metadata = [];
			if(line.indexOf("@endpoint") != -1) {
				while (annotationMatches = ES6endpointRE.exec(line)){ 
					metadata.push(annotationMatches[1])
				}
				Eif(metadata.length > 0) {
					let nextLine =  lines[idx + 1]
					let actionMetadata = nextLine.match(ES6ActionNameRE)//.exec(nextLine)
					if(actionMetadata){
						metadata.push('action: ' + actionMetadata[1])
					}
					matchCB(metadata);
				}
			}
		})
 
	}
 
	getPath(matches) {
        let currentPath = {
        	versions: []
        };
        let actionStr = "";
        matches.forEach( p => {
            var parts = p.split(":"),
            	key = parts.shift(),
                value = parts.join(":").trim();
            if(key == "versions") {
            	value = parseVersionsMetadata(value);
            }
            if(key == "action") {
            	actionStr = value.trim();
            }
            Eif(value) currentPath[key] = value;
        })
        
        //currentPath['action'] = actionStr.trim();
        currentPath['handlerPath'] = this.fpath;
        currentPath['handlerName'] = this.className;
        currentPath.method = currentPath.method.toUpperCase()
        return currentPath;
	}
}
 
class ES5MatchesParser {
	constructor(fpath) {
		this.fpath = fpath;
	}
 
	parse(content, matchCB) {
		let matches = null;
        while( (matches = ES5endpointRE.exec(content)) !== null) {
        	matchCB(matches);	
        }
	}
 
	getPath(matches) {
        let params = _.compact(matches.slice(1,4))
        let currentPath = {};
        params.forEach(function(p) {
            let parts = p.split(":"),
            	key = parts.shift(),
                value = parts.join(":").trim();
            Eif(value) currentPath[key] = value;
        })
        let actionStr = matches[5],
            handlerName = matches[4]
        
        currentPath['action'] = actionStr.trim();
        currentPath['handlerPath'] = this.fpath;
        currentPath['handlerName'] = handlerName
        currentPath.method = currentPath.method.toUpperCase()
        return currentPath;
	}
}