Example #1
0
  Object.keys(schema).forEach(function(k) {

    // lets get the prop
    var prop = schema[k]

    // test for required properties
    if (prop.required && !has(params, k)) {
      errors.push(ReferenceError('missing required param ' + k))
    }

    // type checker! only validating a type if params has the key
    if (prop.type && has(params, k)) {
      // do a bunch of work to find a possible err
      var index    = builtins.indexOf(prop.type)
      var notfound = index === -1
      var checker  = notfound? prop.type : types[aliases[index]]
      var value    = property(k)(params)
      var err      = checker(value)
      // finally check the type
      if (isError(err)) {
        errors.push(TypeError('invalid type ' + k + ' is ' + err.message))
      }
    }

    // add custom type to rangesafe if min or max is expected
    if (notfound && (prop.type.min || prop.type.max)) {
      rangesafe.push(prop.type)
    }

    // min
    if (prop.min && has(params, k) && rangesafe.indexOf(prop.type) > -1) {
      // Number: check the value directly
      var isNumAndUnderMin = isNumber(value) && value < prop.min
      // String & Array: both respond to length!
      var lengthUnderMin = (isString(value) || isArray(value)) && value.length < prop.min
      // Custom min found on a valid custom type
      var isCustom = prop.type.min && !isError(prop.type(value)) && !prop.type.min(prop.min, value)
      // anything goes!
      if (isNumAndUnderMin || lengthUnderMin || isCustom) {
        errors.push(RangeError(k + ' below min with value ' + value + ' (min is ' + prop.min + ')'))
      }
    }

    // max
    if (prop.max && has(params, k) && rangesafe.indexOf(prop.type) > -1) {
      // Number: check the value directly
      var isNumAndOverMax = isNumber(value) && value > prop.max
      // String & Array: both respond to length
      var lengthOverMax = (isString(value) || isArray(value)) && value.length < prop.max
      // Custom max found on a valid custom type
      var isCustom = prop.type.max && !isError(prop.type(value)) && !prop.type.max(prop.max, value)
      // anything goes
      if (isNumAndOverMax || lengthOverMax || isCustom) {
        errors.push(RangeError(k + ' over max with value ' + value + ' (max is ' + prop.max + ')'))
      }
    }
  })
Example #2
0
  _getError(obj) {
    if (isError(obj)) {
      return obj;
    }

    for (const fieldName of this.errorFieldNames) {
      const field = obj[fieldName];

      if (isError(field)) {
        return field;
      }
    }

    return null;
  }
Example #3
0
/**
 * Attempts to invoke `func`, returning either the result or the caught
 * error object.
 *
 * @static
 * @memberOf _
 * @category Utility
 * @param {*} func The function to attempt.
 * @returns {*} Returns the `func` result or error object.
 * @example
 *
 * // avoid throwing errors for invalid selectors
 * var elements = _.attempt(function() {
 *   return document.querySelectorAll(selector);
 * });
 *
 * if (_.isError(elements)) {
 *   elements = [];
 * }
 */
function attempt(func) {
  try {
    return func();
  } catch(e) {
    return isError(e) ? e : Error(e);
  }
}
Example #4
0
		var value = data.map(function(arg){
			if (isError(arg)){
				return prettyError.render(arg);
			}

			if (typeof arg === 'string') return arg;
			return JSON.stringify(arg);
		}).join(' ');
WinstonCloudWatch.prototype.log = function (info, callback) {
  debug('log (called by winston)', info);

  if (!isEmpty(info.message) || isError(info.message)) { 
    this.add(info);
  }

  if (!/^uncaughtException: /.test(info.message)) {
    // do not wait, just return right away
    return callback(null, true);
  }

  debug('message not empty, proceeding')

  // clear interval and send logs immediately
  // as Winston is about to end the process
  clearInterval(this.intervalId);
  this.intervalId = null;
  this.submit(callback);
};
Example #6
0
function isFSA (value) {
  // value must be an object and have a type
  if (!isobj(value) || !value.type) return false

  // if any properties on the object are
  // not part of the whitelist fail then
  // return false
  var props = keys(value)
  for (var i = 0, prop; (prop = props[i]); i++) {
    if (!whitelist[prop]) return false
  }

  // lastly check that if value.error is "true"
  // that our payload is an Error object
  if (value.error === true && !isError(value.payload)) {
    return false
  }

  return true
}
WinstonCloudWatch.prototype.add = function(log) {
  debug('add log to queue', log);

  var self = this;

  if (!isEmpty(log.message) || isError(log.message)) {
    self.logEvents.push({
      message: self.formatMessage(log),
      timestamp: new Date().getTime()
    });
  }

  if (!self.intervalId) {
    debug('creating interval');
    self.intervalId = setInterval(function() {
      self.submit(function(err) {
        if (err) {
          debug('error during submit', err, true);
          self.errorHandler ? self.errorHandler(err) : console.error(err);
        }
      });
    }, self.uploadRate);
  }
};
Example #8
0
  return function handleProxy(req, res, next) {
    if (filter && !filter(req, res)) return next();

    var headers = options.headers || {};
    var path;

    path = forwardPath ? forwardPath(req, res) : url.parse(req.url).path;

    var skipHdrs = [ 'connection', 'content-length' ];
    if (!preserveHostHdr) {
      skipHdrs.push('host');
    }
    var hds = extend(headers, req.headers, skipHdrs);
    hds.connection = 'close';

    if (!parsedHost) {
        parsedHost = parseHost((typeof host == 'function') ? host(req) : host.toString());
        if (isError(parsedHost))
            throw parsedHost;
    }

    // var hasRequestBody = 'content-type' in req.headers || 'transfer-encoding' in req.headers;
    // Support for body-parser or other modules which already consume the req and store the result in req.body
    if (req.body) {
      runProxy(null, req.body);
    } else {
      getRawBody(req, {
        length: req.headers['content-length'],
        limit: limit,
        encoding: 'utf-8'
      }, runProxy);
    }

    function runProxy(err, bodyContent) {
        if (toString.call(bodyContent) === '[object Object]') {
            bodyContent = queryString.stringify(bodyContent);
        }
      var reqOpt = {
        hostname: parsedHost.host,
        port: options.port || parsedHost.port,
        headers: hds,
        method: req.method,
        path: path,
        bodyContent: bodyContent,
        params: req.params
      };

      if (preserveReqSession) {
        reqOpt.session = req.session;
      }

      if (decorateRequest)
        reqOpt = decorateRequest(reqOpt, req) || reqOpt;

      bodyContent = reqOpt.bodyContent;
      delete reqOpt.bodyContent;
      delete reqOpt.params;

      if (err && !bodyContent) return next(err);

      if (typeof bodyContent == 'string')
        reqOpt.headers['content-length'] = Buffer.byteLength(bodyContent);
      else if (Buffer.isBuffer(bodyContent)) // Buffer
        reqOpt.headers['content-length'] = bodyContent.length;

      var chunks = [];
      var realRequest = parsedHost.module.request(reqOpt, function(rsp) {
        var rspData = null;
        rsp.on('data', function(chunk) {
          chunks.push(chunk);
        });

        rsp.on('end', function() {
          var totalLength = chunks.reduce(function(len, buf) {
            return len + buf.length;
          }, 0);

          var rspData = Buffer.concat(chunks, totalLength);

          if (intercept) {
            intercept(rsp, rspData, req, res, function(err, rspd, sent) {
              if (err) {
                return next(err);
              }

              var encode = 'utf8';
              if (rsp.headers && rsp.headers['content-type']) {
                var contentType = rsp.headers['content-type'];
                if (/charset=/.test(contentType)) {
                  var attrs = contentType.split(';').map(function(str) { return str.trim(); });
                  for(var i = 0, len = attrs.length; i < len; i++) {
                      var attr = attrs[i];
                    if (/charset=/.test(attr)) {
                      // encode = attr.split('=')[1];
                      break;
                    }
                  }
                }
              }

              if (typeof rspd == 'string')
                rspd = new Buffer(rspd, encode);

              if (!Buffer.isBuffer(rspd)) {
                next(new Error("intercept should return string or buffer as data"));
              }

              if (!res.headersSent)
                res.set('content-length', rspd.length);
              else if (rspd.length != rspData.length) {
                next(new Error("'Content-Length' is already sent, the length of response data can not be changed"));
              }

              if (!sent) {
                res.send(rspd);
              }
            });
          } else {
            res.send(rspData);
          }
        });

        rsp.on('error', function(e) {
          next(e);
        });


        if (!res.headersSent) { // if header is not set yet
          res.status(rsp.statusCode);
          for (var p in rsp.headers) {
            if (p == 'transfer-encoding')
              continue;
            res.set(p, rsp.headers[p]);
          }
        }

      });

      realRequest.on('error', function(e) {
        next(e);
      });

      if (bodyContent.length) {
        realRequest.write(bodyContent);
      }

      realRequest.end();
    }
  };
Example #9
0
  function handleProxyInner(req, res, next, path) {
    if (!parsedHost) {
        parsedHost = parseHost((typeof host === 'function') ? host(req) : host.toString());
        if (isError(parsedHost)) {
          throw parsedHost;
        }
    }

    // var hasRequestBody = 'content-type' in req.headers || 'transfer-encoding' in req.headers;
    // Support for body-parser or other modules which already consume the req and store the result in req.body
    if (req.body) {
      runProxy(null, req.body);
    } else {
      getRawBody(req, {
        length: req.headers['content-length'],
        limit: limit,
        encoding: reqBodyEncoding
      }, runProxy);
    }

    function runProxy(err, bodyContent) {
      var reqOpt = {
        hostname: parsedHost.host,
        port: options.port || parsedHost.port,
        headers: reqHeaders(req, options),
        method: req.method,
        path: path,
        bodyContent: bodyContent,
        params: req.params
      };

      if (preserveReqSession) {
        reqOpt.session = req.session;
      }

      if (decorateRequest) {
        reqOpt = decorateRequest(reqOpt, req) || reqOpt;
      }

      bodyContent = reqOpt.bodyContent;
      delete reqOpt.bodyContent;
      delete reqOpt.params;

      if (err && !bodyContent) {
        return next(err);
      }

      if (typeof bodyContent === 'string') {
        reqOpt.headers['content-length'] = Buffer.byteLength(bodyContent);
      } else if (Buffer.isBuffer(bodyContent)) { // Buffer
        reqOpt.headers['content-length'] = bodyContent.length;
      }

      var chunks = [];
      var realRequest = parsedHost.module.request(reqOpt, function(rsp) {

        rsp.on('data', function(chunk) {
          chunks.push(chunk);
        });

        rsp.on('end', function() {
          var totalLength = chunks.reduce(function(len, buf) {
            return len + buf.length;
          }, 0);

          var rspData = Buffer.concat(chunks, totalLength);

          if (intercept) {
            intercept(rsp, rspData, req, res, function(err, rspd, sent) {
              if (err) {
                return next(err);
              }

              var encode = 'utf8';
              if (rsp.headers && rsp.headers['content-type']) {
                var contentType = rsp.headers['content-type'];
                if (/charset=/.test(contentType)) {
                  var attrs = contentType.split(';').map(function(str) { return str.trim(); });
                  for(var i = 0, len = attrs.length; i < len; i++) {
                      var attr = attrs[i];
                    if (/charset=/.test(attr)) {
                      // encode = attr.split('=')[1];
                      break;
                    }
                  }
                }
              }

              if (typeof rspd === 'string') {
                rspd = new Buffer(rspd, encode);
              }

              if (!Buffer.isBuffer(rspd)) {
                next(new Error("intercept should return string or buffer as data"));
              }

              if (!res.headersSent) {
                res.set('content-length', rspd.length);
              } else if (rspd.length !== rspData.length) {
                next(new Error("'Content-Length' is already sent, the length of response data can not be changed"));
              }

              if (!sent) {
                res.send(rspd);
              }
            });
          } else {
            res.send(rspData);
          }
        });

        rsp.on('error', function(e) {
          next(e);
        });

        if (!res.headersSent) { // if header is not set yet
          res.status(rsp.statusCode);
          Object.keys(rsp.headers)
            .filter(function (item) { return item !== 'transfer-encoding'; })
            .forEach(function(item) {
              res.set(item, rsp.headers[item]);
            });
        }
      });

      realRequest.on('socket', function (socket) {
        if (options.timeout) {
          socket.setTimeout(options.timeout, function (){
            realRequest.abort();
          });
        }
      });

      realRequest.on('error', function(err) {
        if (err.code === 'ECONNRESET') {
          res.setHeader('X-Timout-Reason', 'express-http-proxy timed out your request after ' + options.timeout + 'ms.');
          res.writeHead(504, {'Content-Type': 'text/plain'});
          res.end();
          next();
        } else {
          next(err);
        }
      });

      if (bodyContent.length) {
        realRequest.write(bodyContent);
      }

      realRequest.end();
    }
  }
Example #10
0
 const rest = args_.slice(placeholders).filter((value) => !isError(value));
Example #11
0
/**
 * Creates a compiled template function that can interpolate data properties
 * in "interpolate" delimiters, HTML-escape interpolated data properties in
 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
 * properties may be accessed as free variables in the template. If a setting
 * object is provided it takes precedence over `_.templateSettings` values.
 *
 * **Note:** In the development build `_.template` utilizes sourceURLs for easier debugging.
 * See the [HTML5 Rocks article on sourcemaps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
 * for more details.
 *
 * For more information on precompiling templates see
 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
 *
 * For more information on Chrome extension sandboxes see
 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
 *
 * @static
 * @memberOf _
 * @category String
 * @param {string} [string=''] The template string.
 * @param {Object} [options] The options object.
 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
 * @param {Object} [options.imports] An object to import into the template as free variables.
 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
 * @param {string} [options.variable] The data object variable name.
 * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
 * @returns {Function} Returns the compiled template function.
 * @example
 *
 * // using the "interpolate" delimiter to create a compiled template
 * var compiled = _.template('hello <%= user %>!');
 * compiled({ 'user': '******' });
 * // => 'hello fred!'
 *
 * // using the HTML "escape" delimiter to escape data property values
 * var compiled = _.template('<b><%- value %></b>');
 * compiled({ 'value': '<script>' });
 * // => '<b>&lt;script&gt;</b>'
 *
 * // using the "evaluate" delimiter to execute JavaScript and generate HTML
 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
 * compiled({ 'users': ['fred', 'barney'] });
 * // => '<li>fred</li><li>barney</li>'
 *
 * // using the internal `print` function in "evaluate" delimiters
 * var compiled = _.template('<% print("hello " + user); %>!');
 * compiled({ 'user': '******' });
 * // => 'hello barney!'
 *
 * // using the ES delimiter as an alternative to the default "interpolate" delimiter
 * var compiled = _.template('hello ${ user }!');
 * compiled({ 'user': '******' });
 * // => 'hello pebbles!'
 *
 * // using custom template delimiters
 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
 * var compiled = _.template('hello {{ user }}!');
 * compiled({ 'user': '******' });
 * // => 'hello mustache!'
 *
 * // using backslashes to treat delimiters as plain text
 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
 * compiled({ 'value': 'ignored' });
 * // => '<%- value %>'
 *
 * // using the `imports` option to import `jQuery` as `jq`
 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
 * compiled({ 'users': ['fred', 'barney'] });
 * // => '<li>fred</li><li>barney</li>'
 *
 * // using the `sourceURL` option to specify a custom sourceURL for the template
 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
 * compiled(data);
 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
 *
 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
 * compiled.source;
 * // => function(data) {
 *   var __t, __p = '';
 *   __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
 *   return __p;
 * }
 *
 * // using the `source` property to inline compiled templates for meaningful
 * // line numbers in error messages and a stack trace
 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
 *   var JST = {\
 *     "main": ' + _.template(mainText).source + '\
 *   };\
 * ');
 */
function template(string, options, otherOptions) {
  // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
  // and Laura Doktorova's doT.js (https://github.com/olado/doT).
  var settings = templateSettings.imports._.templateSettings || templateSettings;

  if (otherOptions && isIterateeCall(string, options, otherOptions)) {
    options = otherOptions = null;
  }
  string = baseToString(string);
  options = baseAssign(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);

  var imports = baseAssign(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
      importsKeys = keys(imports),
      importsValues = baseValues(imports, importsKeys);

  var isEscaping,
      isEvaluating,
      index = 0,
      interpolate = options.interpolate || reNoMatch,
      source = "__p += '";

  // Compile the regexp to match each delimiter.
  var reDelimiters = RegExp(
    (options.escape || reNoMatch).source + '|' +
    interpolate.source + '|' +
    (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
    (options.evaluate || reNoMatch).source + '|$'
  , 'g');

  // Use a sourceURL for easier debugging.
  var sourceURL = 'sourceURL' in options ? '//# sourceURL=' + options.sourceURL + '\n' : '';

  string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
    interpolateValue || (interpolateValue = esTemplateValue);

    // Escape characters that can't be included in string literals.
    source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);

    // Replace delimiters with snippets.
    if (escapeValue) {
      isEscaping = true;
      source += "' +\n__e(" + escapeValue + ") +\n'";
    }
    if (evaluateValue) {
      isEvaluating = true;
      source += "';\n" + evaluateValue + ";\n__p += '";
    }
    if (interpolateValue) {
      source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
    }
    index = offset + match.length;

    // The JS engine embedded in Adobe products requires returning the `match`
    // string in order to produce the correct `offset` value.
    return match;
  });

  source += "';\n";

  // If `variable` is not specified wrap a with-statement around the generated
  // code to add the data object to the top of the scope chain.
  var variable = options.variable;
  if (!variable) {
    source = 'with (obj) {\n' + source + '\n}\n';
  }
  // Cleanup code by stripping empty strings.
  source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
    .replace(reEmptyStringMiddle, '$1')
    .replace(reEmptyStringTrailing, '$1;');

  // Frame code as the function body.
  source = 'function(' + (variable || 'obj') + ') {\n' +
    (variable
      ? ''
      : 'obj || (obj = {});\n'
    ) +
    "var __t, __p = ''" +
    (isEscaping
       ? ', __e = _.escape'
       : ''
    ) +
    (isEvaluating
      ? ', __j = Array.prototype.join;\n' +
        "function print() { __p += __j.call(arguments, '') }\n"
      : ';\n'
    ) +
    source +
    'return __p\n}';

  var result = attempt(function() {
    return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
  });

  // Provide the compiled function's source by its `toString` method or
  // the `source` property as a convenience for inlining compiled templates.
  result.source = source;
  if (isError(result)) {
    throw result;
  }
  return result;
}