Code coverage report for lib/config.js

Statements: 96.5% (138 / 143)      Branches: 91.82% (101 / 110)      Functions: 100% (22 / 22)      Lines: 96.5% (138 / 143)      Ignored: none     

All files » lib/ » config.js
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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314    1       1 9     9     9     9     9     9     9 9     9     1 9                           1 9 9   9 8 8 6       9 8 8 6       9 8     9           1 9   9     9 4 4 4 4     4 4               9       1 13 13   13 5     13 13     13 13 13 13 13 13   13       1 26   26 12     14 37 37       14       1 9   2 2     2 1     2 6     2 2     2 4 4   4 8 2 2       4 2       2 4 4   4 4 2 2       4 2         9         1 12     12 6 14     6 5         1 15   15 15 15   15 7       15     1 13       1 32     32       32       32 32 32         32       1 47       47 2   47 47       47 35           47 37     47                   1 45     45 37 37 37     8   8 8     8 8 8     8    
'use strict';
 
var fs      = require('fs'),
    path    = require('path'),
    url     = require('url');
 
module.exports = function configParser(options) {
  var config = createDefaultConfig(),
      temp;
 
  options = options || {};
 
  // read environmental variables first
  config = parseEnv(config);
 
  // read a config file next
  config = parseFile(options.file, config);
 
  // process any command line arguments
  config = parseCommandLine(options.argv, config);
 
  // process the hard code values
  temp = parseConfig(options, config);
 
  // normalize the path to config.server.webroot
  Eif (config.server.webroot && config.server.webroot.length > 0) {
    config.server.webroot = path.normalize(config.server.webroot);
  }
 
  return config;
};
 
function createDefaultConfig() {
  return {
    server: {
      port: 8080,
      webroot: process.cwd(),
      html5mode: false
    },
    proxy: {
      gateway: null,
      forward: [],
      headers: []
    }
  };
}
 
function parseEnv(config) {
  var env = process.env;
  var temp;
 
  if (env['JSON_PROXY_PORT']) {
    temp = parseInt(env['JSON_PROXY_PORT'], 10);
    if (temp && !isNaN(temp)) {
      config.server.port = temp;
    }
  }
 
  if (env['JSON_PROXY_WEBROOT']) {
    temp = path.normalize(env['JSON_PROXY_WEBROOT']);
    if (temp && fs.existsSync(temp)) {
      config.server.webroot = temp;
    }
  }
 
  if (env['JSON_PROXY_GATEWAY']) {
    config.proxy.gateway = parseGateway(env['JSON_PROXY_GATEWAY'], env['JSON_PROXY_GATEWAY_AUTH']);
  }
 
  return config;
}
 
// reads a config file from either the config file specified on the command line, 
// or fallback to a file name json-proxy.config in the working directory
// return true if the file can be read, otherwise return false
function parseFile(filepath, config) {
  var contents;
 
  filepath = filepath || path.join(process.cwd(), '/json-proxy.json');
 
  // if we were passed a config file, read and parse it
  if (fs.existsSync(filepath)) {
    try {
      var data = fs.readFileSync(filepath);
      contents = JSON.parse(data.toString());
      config = parseConfig(contents, config);
 
      // replace the token $config_dir in the webroot arg
      Eif (config.server.webroot && config.server.webroot.length > 0) {
        config.server.webroot = config.server.webroot.replace("$config_dir", path.dirname(filepath));
      }
    } catch (ex) {
      throw new Error('Cannot parse the config file "' + filepath + '": ' + ex);
    }
 
  }
 
  return config;
}
 
// parse a config structure, overriding any values in config
function parseConfig(contents, config) {
  contents.server = contents.server || {};
  contents.proxy = contents.proxy || {};
 
  if (contents.proxy.gateway && typeof(contents.proxy.gateway) === "string" && contents.proxy.gateway.length > 0) {
    contents.proxy.gateway = parseGateway(contents.proxy.gateway);
  }
 
  contents.proxy.forward = parseConfigMap(contents.proxy.forward, parseForwardRule);
  contents.proxy.headers = parseConfigMap(contents.proxy.headers, parseHeaderRule);
 
  // override any values in the config object with values specified in the file;
  config.server.port = contents.server.port || config.server.port;
  config.server.webroot = contents.server.webroot || config.server.webroot;
  config.server.html5mode = contents.server.html5mode || config.server.html5mode;
  config.proxy.gateway = contents.proxy.gateway || config.proxy.gateway;
  config.proxy.forward = contents.proxy.forward || config.proxy.forward;
  config.proxy.headers = contents.proxy.headers || config.proxy.headers;
 
  return config;
}
 
// transform a config hash object into an array
function parseConfigMap(map, callback) {
  var result = [];
 
  if (!(map instanceof Object)) {
    return map;
  }
 
  for(var property in map) {
    Eif (map.hasOwnProperty(property)) {
      result.push(callback(property, map[property]));
    }
  }
 
  return result;
}
 
// reads command line parameters
function parseCommandLine(argv, config) {
  if (argv) {
    // read the command line arguments if no config file was given
    parseCommandLineArgument(argv.port, function(item){
      config.server.port = item;
    });
 
    parseCommandLineArgument(argv.html5mode, function(item){
      config.server.html5mode = item;
    });
 
    parseCommandLineArgument(argv._, function(item){
      config.server.webroot = path.normalize(item);
    });
 
    parseCommandLineArgument(argv.gateway, function(item){
      config.proxy.gateway = parseGateway(item);
    });
 
    parseCommandLineArgument(argv.forward, function(item){
      var rule = parseForwardRule(item);
      var match = false;
 
      config.proxy.forward.forEach(function(item) {
        if (item.regexp.source === rule.regexp.source) {
          item.target = rule.target;
          match = true;
        }
      });
 
      if (!match) {
        config.proxy.forward.push(rule);
      }
    });
 
    parseCommandLineArgument(argv.header, function(item){
      var rule = parseHeaderRule(item);
      var match = false;
 
      config.proxy.headers.forEach(function(item) {
        if (item.name === rule.name) {
          item.value = rule.value;
          match = true;
        }
      });
 
      if (!match) {
        config.proxy.headers.push(rule);
      }
    });
  }
 
  return config;
}
 
// argv.X will be an array if multiple -X options are provided
// otherwise argv.X will just be a scalar value
function parseCommandLineArgument(arg, fn) {
  Iif (typeof(fn) !== 'function')
    return;
 
  if (Array.isArray(arg)) {
    arg.forEach(function(item) {
      fn.call(null, item);
    });
  } else {
    if (arg !== null && arg !== undefined) {
      fn.call(null, arg);
    }
  }
}
 
function parseGateway(gateway, auth) {
  var config = null;
 
  Eif (gateway !== undefined && gateway !== null && typeof(gateway) === 'string' && gateway.length > 0) {
    config = parseTargetServer(gateway);
    config.auth = url.parse(gateway).auth;
 
    if (auth && typeof(auth) === "string" && auth.length > 0) {
      config.auth  = auth;
    }
  }
 
  return config;
}
 
function parseHeaderRule() {
  return tokenize.apply(null, arguments);
}
 
// parses rule syntax to create forwarding rules
function parseForwardRule() {
  var token,
      rule;
 
  Iif (arguments[0] === undefined || arguments[0] === null) {
    return;
  }
 
  Iif (typeof(arguments[0]) === "object") {
    return arguments[0];
  }
 
  try {
    token = tokenize.apply(null, arguments);
    rule = { regexp: new RegExp('^' + token.name, 'i'), target: parseTargetServer(token.value) };
  } catch (e) {
    throw new Error('cannot parse the forwarding rule ' + arguments[0] + ' - ' + e);
  }
 
  return rule;
}
 
// parses a simple hostname:port argument, defaulting to port 80 if not specified
function parseTargetServer(value) {
  var target,
      path;
 
  // insert a http protocol handler if not found in the string
  if (value.indexOf('http://') !== 0 && value.indexOf('https://') !== 0) {
    value = 'http://' + value + '/';
  }
  target = url.parse(value);
  path = target.path;
 
  // url.parse() will default to '/' as the path
  // we can safely strip this for regexp matches to function properly
  if (path === '/') {
    path = '';
  }
 
  // support an explict set of regexp unnamed captures (prefixed with `$`)
  // if the pattern doesn't include a match operator like '$1', '$2', '$3',
  // then use the RegExp lastMatch operator `$&` if the rewrite rule
  if (/\$\d/.test(path) === false) {
    path = [path ,'$&'].join('');
  }
 
  return {
    host: target.hostname,
    // inject a default port if one wasn't specified
    port: target.port || ((target.protocol === 'https:') ? 443 : 80),
    protocol: target.protocol,
    path: path
  };
}
 
// reads name/value tokens for command line parameters
function tokenize() {
  var token = { name: null, value: null },
      temp = null;
 
  if (arguments.length !== 1) {
    token.name = arguments[0];
    token.value = arguments[1];
    return token;
  }
 
  temp = arguments[0];
 
  Eif (undefined !== temp && null !== temp) {
    temp = temp.split('=');
  }
 
  Eif (Array.isArray(temp) && temp.length > 1) {
    token.name = temp[0];
    token.value = temp[1];
  }
 
  return token;
}