<commit_before>var FULFILLED = 'fulfilled'
  , REJECTED = 'rejected'
  , PENDING = 'pending'

function Promise(block) {
  ifInstanceOf(this, Promise, noop, function () {
    throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")
  });

  ifFunction(block, noop, function () {
    throw new TypeError("You must pass a resolver function as the first argument to the promise constructor.");
  });

  var deferred = newDeferred(this);

  this.then = function (onFulfilled, onRejected) {
    var resolveNext
      , rejectNext

    var promise = new Promise(function (resolve, reject) {
      resolveNext = resolve;
      rejectNext = reject;
    });

    function addFulfillmentHandler() {
      return deferred.onFulfilled(wrapHandler(onFulfilled));
    }

    function proxyFulfillment() {
      return deferred.onFulfilled(resolveNext);
    }

    ifFunction(onFulfilled, addFulfillmentHandler, proxyFulfillment);

    function addRejectionHandler() {
      return deferred.onRejected(wrapHandler(onRejected));
    }

    function proxyRejection() {
      return deferred.onRejected(rejectNext);
    }

    ifFunction(onRejected, addRejectionHandler, proxyRejection);

    function wrapHandler(handler) {
      return tryCatch(handler, resolveNext, rejectNext);
    }

    return promise;
  };

  this.catch = function (onRejected) {
    return this.then(null, onRejected);
  };

  this._proxy = function (resolve, reject) {
    deferred.onFulfilled(resolve);
    deferred.onRejected(reject);
  };

  try {
    block(deferred.resolve, deferred.reject);
  } catch (err) {
    deferred.reject(err);
  }
}

Promise.cast = function (value) {
  if (value instanceof Promise) {
    return value;
  }
  return Promise.resolve(value);
};

Promise.resolve = function (value) {
  return new Promise(function (resolve, reject) {
    resolve(value);
  });
};

Promise.reject = function (error) {
  return new Promise(function (resolve, reject) {
    reject(error);
  });
};

Promise.all = function (promises) {
  if (!Array.isArray(promises)) {
    promises = Array.prototype.slice.call(arguments);
  }

  var promise
    , values = []
    , count = 0
    , expected = promises.length

  promise = new Promise(function (resolve, reject) {
    promises.forEach(function (promise, index) {

      function maybeResolve(val) {
        values[index] = val;
        if ((count += 1) === expected) {
          resolve(values);
        }
      }

      Promise.cast(promise)._proxy(maybeResolve, reject);
    })
  });

  return promise;
};

exports.Promise = Promise;

function newDeferred(promise) {
  var self = Object.create(null)
    , status = PENDING
    , knownFate
    , fulfillmentHandlers = []
    , rejectionHandlers = []

  self.resolve = function (value) {
    var resolve = commit(fulfillmentHandlers, FULFILLED)
    resolveValue(value, promise, resolve, self.reject);
    return self;
  };
  self.resolve;

  self.reject = function (reason) {
    commit(rejectionHandlers, REJECTED)(reason);
    return self;
  };

  self.onFulfilled = addHandler(fulfillmentHandlers, FULFILLED);

  self.onRejected = addHandler(rejectionHandlers, REJECTED);

  function addHandler(handlers, expect) {
    return function (handler) {
      if (status === PENDING) {
        handlers.push(handler);
      } else if (status === expect) {
        queue(handler);
      }
    };
  }

  function queue(handler) {
    process.nextTick(function () {
      handler(knownFate);
    });
  }

  function commit(handlers, committedStatus) {
    return function (fate) {
      return process.nextTick(function () {
        if (status !== PENDING) return;
        status = committedStatus;
        knownFate = fate;
        handlers.forEach(function (handler) {
          handler(knownFate);
        });
      });
    };
  }

  return self;
}

function resolveValue(x, promise, resolve, reject) {
  var invokeResolve = invoke(resolve, [x])

  function rejectWithSameObject() {
    return reject(new TypeError("promise === value"));
  }

  function checkIsPromise() {
    return ifInstanceOf(x, Promise, inheritState, checkIsThenable);
  }

  function inheritState() {
    x._proxy(resolve, reject);
  }

  function checkIsThenable() {
    return ifObjectOrFunction(x, dereferenceThenable, invokeResolve);
  }

  function dereferenceThenable() {
    return dereference(x, 'then', checkThenIsFunction, reject);
  }

  function checkThenIsFunction(then) {
    return ifFunction(then, invoke(resolveThenable, [then]), invokeResolve);
  }

  function resolveThenable(then) {
    var resolved = false

    try {
      then.call(x, function (y) {
        if (resolved) return;
        resolved = true;
        resolveValue(y, promise, resolve, reject);
      }, function (r) {
        if (resolved) return;
        resolved = true;
        reject(r);
      });
    } catch (err) {
      if (!resolved) reject(err);
    }
  }

  ifInstanceOf(x, Error, function () {
    return reject(x);
  }, function () {
    return ifSameObject(x, promise, rejectWithSameObject, checkIsPromise);
  });
}

function ifIsPromise(x, success, reject) {
  return ifInstanceOf(x, Promise, success, reject);
}

function tryCatch(func, resolve, reject) {
  return function (val) {
    var x
    try {
      x = func(val);
    } catch (err) {
      reject(err);
      return;
    }
    resolve(x);
  }
}

function ifInstanceOf(x, y, success, reject) {
  return ifCondition(x instanceof y, success, reject);
}

function ifSameObject(x, y, success, reject) {
  return ifCondition(x === y, success, reject);
}

function ifFunction(x, success, reject) {
  return ifCondition(typeof x === 'function', success, reject);
}

function ifObjectOrFunction(x, success, reject) {
  var guard = (x && (typeof x === 'object' || typeof x === 'function'))
  return ifCondition(guard, success, reject);
}

function ifCondition(guard, success, reject) {
  if (guard) {
    return success();
  }
  return reject();
}

function dereference(x, name, success, reject) {
  var ref
  try {
    ref = x[name];
  } catch (err) {
    return reject(err);
  }
  return success(ref);
}

function invoke(func, args, context) {
  return function () {
    return func.apply(context || null, args);
  };
}

function noop() {}
<commit_msg>Work around ECMA5+ features.<commit_after>var FULFILLED = 'fulfilled'
  , REJECTED = 'rejected'
  , PENDING = 'pending'

function Promise(block) {
  ifInstanceOf(this, Promise, noop, function () {
    throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")
  });

  ifFunction(block, noop, function () {
    throw new TypeError("You must pass a resolver function as the first argument to the promise constructor.");
  });

  var deferred = newDeferred(this);

  this.then = function (onFulfilled, onRejected) {
    var resolveNext
      , rejectNext

    var promise = new Promise(function (resolve, reject) {
      resolveNext = resolve;
      rejectNext = reject;
    });

    function addFulfillmentHandler() {
      return deferred.onFulfilled(wrapHandler(onFulfilled));
    }

    function proxyFulfillment() {
      return deferred.onFulfilled(resolveNext);
    }

    ifFunction(onFulfilled, addFulfillmentHandler, proxyFulfillment);

    function addRejectionHandler() {
      return deferred.onRejected(wrapHandler(onRejected));
    }

    function proxyRejection() {
      return deferred.onRejected(rejectNext);
    }

    ifFunction(onRejected, addRejectionHandler, proxyRejection);

    function wrapHandler(handler) {
      return tryCatch(handler, resolveNext, rejectNext);
    }

    return promise;
  };

  this.catch = function (onRejected) {
    return this.then(null, onRejected);
  };

  this._proxy = function (resolve, reject) {
    deferred.onFulfilled(resolve);
    deferred.onRejected(reject);
  };

  try {
    block(deferred.resolve, deferred.reject);
  } catch (err) {
    deferred.reject(err);
  }
}

Promise.cast = function (value) {
  if (value instanceof Promise) {
    return value;
  }
  return Promise.resolve(value);
};

Promise.resolve = function (value) {
  return new Promise(function (resolve, reject) {
    resolve(value);
  });
};

Promise.reject = function (error) {
  return new Promise(function (resolve, reject) {
    reject(error);
  });
};

Promise.all = function (promises) {
  if (!isArray(promises)) {
    promises = Array.prototype.slice.call(arguments);
  }

  var promise
    , values = []
    , count = 0
    , expected = promises.length

  promise = new Promise(function (resolve, reject) {
    var i = 0, len = promises.length

    function resolver(index) {
      return function (val) {
        values[index] = val;
        if ((count += 1) === expected) {
          resolve(values);
        }
      };
    }

    for (; i < len; i += 1) {
      Promise.cast(promises[i])._proxy(resolver(i), reject);
    }
  });

  return promise;
};

exports.Promise = Promise;

function newDeferred(promise) {
  var self = Object.create(null)
    , status = PENDING
    , knownFate
    , fulfillmentHandlers = []
    , rejectionHandlers = []

  self.resolve = function (value) {
    var resolve = commit(fulfillmentHandlers, FULFILLED)
    resolveValue(value, promise, resolve, self.reject);
    return self;
  };
  self.resolve;

  self.reject = function (reason) {
    commit(rejectionHandlers, REJECTED)(reason);
    return self;
  };

  self.onFulfilled = addHandler(fulfillmentHandlers, FULFILLED);

  self.onRejected = addHandler(rejectionHandlers, REJECTED);

  function addHandler(handlers, expect) {
    return function (handler) {
      if (status === PENDING) {
        handlers.push(handler);
      } else if (status === expect) {
        queue(handler);
      }
    };
  }

  function queue(handler) {
    setTimeout(function () {
      handler(knownFate);
    }, 1);
  }

  function commit(handlers, committedStatus) {
    return function (fate) {
      setTimeout(function () {
        if (status !== PENDING) return;
        status = committedStatus;
        knownFate = fate;
        handlers.forEach(function (handler) {
          handler(knownFate);
        });
      }, 1);
    };
  }

  return self;
}

function resolveValue(x, promise, resolve, reject) {
  var invokeResolve = invoke(resolve, [x])

  function rejectWithSameObject() {
    return reject(new TypeError("promise === value"));
  }

  function checkIsPromise() {
    return ifInstanceOf(x, Promise, inheritState, checkIsThenable);
  }

  function inheritState() {
    x._proxy(resolve, reject);
  }

  function checkIsThenable() {
    return ifObjectOrFunction(x, dereferenceThenable, invokeResolve);
  }

  function dereferenceThenable() {
    return dereference(x, 'then', checkThenIsFunction, reject);
  }

  function checkThenIsFunction(then) {
    return ifFunction(then, invoke(resolveThenable, [then]), invokeResolve);
  }

  function resolveThenable(then) {
    var resolved = false

    try {
      then.call(x, function (y) {
        if (resolved) return;
        resolved = true;
        resolveValue(y, promise, resolve, reject);
      }, function (r) {
        if (resolved) return;
        resolved = true;
        reject(r);
      });
    } catch (err) {
      if (!resolved) reject(err);
    }
  }

  ifInstanceOf(x, Error, function () {
    return reject(x);
  }, function () {
    return ifSameObject(x, promise, rejectWithSameObject, checkIsPromise);
  });
}

function ifIsPromise(x, success, reject) {
  return ifInstanceOf(x, Promise, success, reject);
}

var isArray = (function () {
  var isArray

  if (typeof Array.isArray === 'function') {
    isArray = Array.isArray;
  } else {
    isArray = function (x) {
      return Object.prototype.toString.call(x) === '[object Array]';
    }
  }

  return isArray;
}());

function tryCatch(func, resolve, reject) {
  return function (val) {
    var x
    try {
      x = func(val);
    } catch (err) {
      reject(err);
      return;
    }
    resolve(x);
  }
}

function ifInstanceOf(x, y, success, reject) {
  return ifCondition(x instanceof y, success, reject);
}

function ifSameObject(x, y, success, reject) {
  return ifCondition(x === y, success, reject);
}

function ifFunction(x, success, reject) {
  return ifCondition(typeof x === 'function', success, reject);
}

function ifObjectOrFunction(x, success, reject) {
  var guard = (x && (typeof x === 'object' || typeof x === 'function'))
  return ifCondition(guard, success, reject);
}

function ifCondition(guard, success, reject) {
  if (guard) {
    return success();
  }
  return reject();
}

function dereference(x, name, success, reject) {
  var ref
  try {
    ref = x[name];
  } catch (err) {
    return reject(err);
  }
  return success(ref);
}

function invoke(func, args, context) {
  return function () {
    return func.apply(context || null, args);
  };
}

function noop() {}
<|endoftext|>


<commit_before>var plugin = require("../.././plugin/extend");
var responseinterceptor=require('responseinterceptor');
var async=require('async');
var fs = require('fs');

function LoadParams(params,req){
    var values={};
    params.forEach(function(element,index){
        values[element]=req[element];
    });

    return values;
}

function writeParams(params,req){

    if((typeof  params) ==="object"){
        async.eachOf(params, function(value,key, callback) {
            req[key]=value;
        });
    }else{
        req.before=params;
    }
}

function extendGet(app,method,ext) {
    method=method.toLocaleLowerCase();
    app[method](ext.resource, function(req,res,next) {
        var params= LoadParams(ext.params,req);

        if(ext.mode=="override") {
            ext.extender(params,null,null,function (err, val) {
                if(!err) {
                    res.send(val);
                }
                else{
                    res.status(err.error_code).send(err.error_message);
                }
            });
        } else if(ext.mode=="before") {
            ext.extender(params,null,null,function (err, val) {
                if(!err){
                    writeParams(val, req);
                    next();
                }else{
                    res.status(err.error_code).send(err.error_message);
                }
            });
        }else if(ext.mode=="after") {
            responseinterceptor.interceptOnFly(req,res,function(body,cType, request, clb){
                ext.extender(params,body,cType,function (err, val) {
                    if(!err) {
                        clb(val);
                    }else{
                        res.status(err.error_code).send(err.error_message);
                    }
                });
            });
            next();
        } else if(ext.mode=="before_after") {

            ext.extender.before(params,null,null,function (err, val) {
                if(!err) {
                    writeParams(val, req);
                }else{
                    res.status(err.error_code).send(err.error_message);
                }
            });

            responseinterceptor.interceptOnFly(req,res,function(body,cType, request, clb){
                ext.extender.after(params,body,cType,function (err, val) {
                    if(!err) {
                        clb(val);
                    }else{
                        res.status(err.error_code).send(err.error_message);
                    }
                });
            });

            next();

        }else next(); // do nothing
    });
}

exports.extend=function(app){
    async.eachSeries(plugin, function(ext, callback) {
        extendGet(app,ext.method,ext);
        callback();
    });
};

function getErrorHandlers(app,error_map) {
    var route, stack;

    stack = app._router.stack;

    async.eachOfSeries(stack, function(layer,key, callback) {
        if (layer && layer.name == '<anonymous>' &&  layer.route == undefined)
            callback(key);
        else callback();

    }, function(err_map) {
        var error_handlers=null;
        if(err_map){
            error_handlers = stack.splice(err_map);
            app._router.stack=stack;
        }
        error_map(error_handlers);
    });
}

exports.install=function(app,extender,save){
    getErrorHandlers(app,function(error_handlers){
        extendGet(app,extender.method,extender);

        if(error_handlers)
            app._router.stack.push.apply(app._router.stack, error_handlers);

        if(save){
            plugin.push(extender);
            var functionToString="[\n";
            async.eachSeries(plugin,function(obj,callback){
                functionToString += "   {\n";
                functionToString += ("      \"resource\":\"") + obj.resource.toString() + "\",\n";
                functionToString += ("      \"method\":\"") + obj.method.toString() + "\",\n";
                functionToString += ("      \"mode\":\"") + obj.mode.toString() + "\",\n";
                functionToString += ("      \"params\":\"") + obj.params.toString() + "\",\n";
                if(obj.extender && obj.extender.before) {
                    functionToString += ("      \"extender\":{\n");
                    functionToString += ("          \"before\":") + obj.extender.before.toString() + ",\n";
                    functionToString += ("          \"after\":") + obj.extender.after.toString() + "\n";
                    functionToString += ("      }\n");
                }else{
                    functionToString += ("      \"extender\":") + obj.extender.toString() + "\n";
                }
                functionToString += "   },\n";
                callback();
            },function(err){
                functionToString=functionToString.slice(0,-2); // remove , and \n
                functionToString+="\n]";
                var nfile='var express = require(\'express\');\n\r' +
                    '\n\r' +
                    'var plugins=' + functionToString + ';\n\r' +
                    'module.exports = plugins;';

                fs.writeFile("./plugin/extend.js", nfile, function(err) {
                    console.log("DONE:" + err);
                });
            });
        }
    });
};
<commit_msg>install on the fly bugs fixed on save<commit_after>var plugin = require("../.././plugin/extend");
var responseinterceptor=require('responseinterceptor');
var async=require('async');
var fs = require('fs');

function LoadParams(params,req){
    var values={};
    params.forEach(function(element,index){
        values[element]=req[element];
    });

    return values;
}

function writeParams(params,req){

    if((typeof  params) ==="object"){
        async.eachOf(params, function(value,key, callback) {
            req[key]=value;
        });
    }else{
        req.before=params;
    }
}

function extendGet(app,method,ext) {
    method=method.toLocaleLowerCase();
    app[method](ext.resource, function(req,res,next) {
        var params= LoadParams(ext.params,req);

        if(ext.mode=="override") {
            ext.extender(params,null,null,function (err, val) {
                if(!err) {
                    res.send(val);
                }
                else{
                    res.status(err.error_code).send(err.error_message);
                }
            });
        } else if(ext.mode=="before") {
            ext.extender(params,null,null,function (err, val) {
                if(!err){
                    writeParams(val, req);
                    next();
                }else{
                    res.status(err.error_code).send(err.error_message);
                }
            });
        }else if(ext.mode=="after") {
            responseinterceptor.interceptOnFly(req,res,function(body,cType, request, clb){
                ext.extender(params,body,cType,function (err, val) {
                    if(!err) {
                        clb(val);
                    }else{
                        res.status(err.error_code).send(err.error_message);
                    }
                });
            });
            next();
        } else if(ext.mode=="before_after") {

            ext.extender.before(params,null,null,function (err, val) {
                if(!err) {
                    writeParams(val, req);
                }else{
                    res.status(err.error_code).send(err.error_message);
                }
            });

            responseinterceptor.interceptOnFly(req,res,function(body,cType, request, clb){
                ext.extender.after(params,body,cType,function (err, val) {
                    if(!err) {
                        clb(val);
                    }else{
                        res.status(err.error_code).send(err.error_message);
                    }
                });
            });

            next();

        }else next(); // do nothing
    });
}

exports.extend=function(app){
    async.eachSeries(plugin, function(ext, callback) {
        extendGet(app,ext.method,ext);
        callback();
    });
};

function getErrorHandlers(app,error_map) {
    var route, stack;

    stack = app._router.stack;

    async.eachOfSeries(stack, function(layer,key, callback) {
        if (layer && layer.name == '<anonymous>' &&  layer.route == undefined)
            callback(key);
        else callback();

    }, function(err_map) {
        var error_handlers=null;
        if(err_map){
            error_handlers = stack.splice(err_map);
            app._router.stack=stack;
        }
        error_map(error_handlers);
    });
}

exports.install=function(app,extender,save){
    getErrorHandlers(app,function(error_handlers){
        extendGet(app,extender.method,extender);

        if(error_handlers)
            app._router.stack.push.apply(app._router.stack, error_handlers);

        if(save){
            plugin.push(extender);
            var functionToString="[\n";
            async.eachSeries(plugin,function(obj,callback){
                functionToString += "   {\n";
                functionToString += ("      \"resource\":\"") + obj.resource.toString() + "\",\n";
                functionToString += ("      \"method\":\"") + obj.method.toString() + "\",\n";
                functionToString += ("      \"mode\":\"") + obj.mode.toString() + "\",\n";
                functionToString += ("      \"params\":\"[") + obj.params.toString() + "\"],\n";
                if(obj.extender && obj.extender.before) {
                    functionToString += ("      \"extender\":{\n");
                    functionToString += ("          \"before\":") + obj.extender.before.toString() + ",\n";
                    functionToString += ("          \"after\":") + obj.extender.after.toString() + "\n";
                    functionToString += ("      }\n");
                }else{
                    functionToString += ("      \"extender\":") + obj.extender.toString() + "\n";
                }
                functionToString += "   },\n";
                callback();
            },function(err){
                functionToString=functionToString.slice(0,-2); // remove , and \n
                functionToString+="\n]";
                var nfile='var express = require(\'express\');\n\r' +
                    '\n\r' +
                    'var plugins=' + functionToString + ';\n\r' +
                    'module.exports = plugins;';

                fs.writeFile("./plugin/extend.js", nfile, function(err) {
                    console.log("DONE:" + err);
                });
            });
        }
    });
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Expose customs
 */

module.exports = exports = customs;

/**
 * Init 'customs'
 *
 *  customs('string', 'hi', function(err) {
 *    // handle error if any
 *  });
 *
 * @params {String} type
 * @params {any} target
 * @return {bool}
 * @api public
 */

function customs (type, target) {
  switch (type) {

    case 'array':
      if ('[object Array]' == Object.prototype.toString.call(target)){
        return true;
      }
      return false;

    case 'string':
      if ('string' == typeof(target)) {
        return true;
      }
      return false;

    case 'number':
      if ('number' == typeof(target)) {
        return true
      };
      return false;

    case 'boolean':
      if ('boolean' == typeof(target)) {
        return true;
      }
      return false;

    case 'object':
      if ('object' == typeof(target)) {
        return true;
      }
      return false;

    case 'email':
      var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regex.test(target)) {
        return true;
      }

    default:
      // check and evaluate regex
      if (type instanceof RegExp && type.test(target)) {
        return true;
      }
      return false;
  }
}<commit_msg>Update usage example<commit_after>'use strict';

/**
 * Expose customs
 */

module.exports = exports = customs;

/**
 * Init 'customs'
 *
 *  var validate = require('customs');
 *  validate('string', 'hi');
 *  // -> 'true'
 *
 * @params {String} type
 * @params {any} target
 * @return {bool}
 * @api public
 */

function customs (type, target) {
  switch (type) {

    case 'array':
      if ('[object Array]' == Object.prototype.toString.call(target)){
        return true;
      }
      return false;

    case 'string':
      if ('string' == typeof(target)) {
        return true;
      }
      return false;

    case 'number':
      if ('number' == typeof(target)) {
        return true
      };
      return false;

    case 'boolean':
      if ('boolean' == typeof(target)) {
        return true;
      }
      return false;

    case 'object':
      if ('object' == typeof(target)) {
        return true;
      }
      return false;

    case 'email':
      var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regex.test(target)) {
        return true;
      }

    default:
      // check and evaluate regex
      if (type instanceof RegExp && type.test(target)) {
        return true;
      }
      return false;
  }
}<|endoftext|>


<commit_before>'use strict';

const util = require('util');

const stringifyEntity = require('bem-naming').stringify;

/**
 * Enum for types of BEM entities.
 *
 * @readonly
 * @enum {String}
 */
const TYPES = {
    BLOCK:     'block',
    BLOCK_MOD: 'blockMod',
    ELEM:      'elem',
    ELEM_MOD:  'elemMod'
};

module.exports = class BemEntityName {
    /**
     * @param {object} obj — representation of entity name.
     * @param {string} obj.block  — the block name of entity.
     * @param {string} [obj.elem] — the element name of entity.
     * @param {object} [obj.mod]  — the modifier of entity.
     * @param {string} [obj.mod.name] — the modifier name of entity.
     * @param {string} [obj.mod.val]  — the modifier value of entity.
     */
    constructor(obj) {
        if (!obj.block) {
             throw new Error('This is not valid BEM entity: the field `block` is undefined.');
        }

        const data = this._data = { block: obj.block };
        const modName = (typeof obj.mod === 'string' ? obj.mod : obj.mod && obj.mod.name) || obj.modName;

        obj.elem && (data.elem = obj.elem);

        if (modName) {
            const modVal = obj.hasOwnProperty('modVal') || obj.mod && obj.mod.hasOwnProperty('val')
                ? obj.mod && obj.mod.val || obj.modVal
                : true;

            data.mod = {
                name: modName,
                val: modVal
            };
        }
    }

    /**
     * Returns the name of block to which this entity belongs.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button' });
     *
     * name.block; // button
     *
     * @returns {string} name of entity block.
     */
    get block() { return this._data.block; }

    /**
     * Returns the element name of this entity.
     *
     * If entity is not element or modifier of element then returns empty string.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', elem: 'text' });
     *
     * name.elem; // text
     *
     * @returns {string} name of entity element.
     */
    get elem() { return this._data.elem; }

    /**
     * Returns the modifier of this entity.
     *
     * Important: If entity is not a modifier then returns `undefined`.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     *
     * const blockName = new BemEntityName({ block: 'button' });
     * const modName = new BemEntityName({ block: 'button', mod: 'disabled' });
     *
     * modName.mod;   // { name: 'disabled', val: true }
     * blockName.mod; // undefined
     *
     * @returns {{mod: string, val: *}} entity modifier.
     */
    get mod() { return this._data.mod; }

    /**
     * Returns the modifier name of this entity.
     *
     * If entity is not modifier then returns `undefined`.
     *
     * @returns {string} entity modifier name.
     * @deprecated use `mod.name` instead.
     */
    get modName() { return this.mod && this.mod.name; }

    /**
     * Returns the modifier value of this entity.
     *
     * If entity is not modifier then returns `undefined`.
     *
     * @returns {string} entity modifier name.
     * @deprecated use `mod.val` instead.
     */
    get modVal() { return this.mod && this.mod.val; }

    /**
     * Returns id for this entity.
     *
     * Important: should only be used to determine uniqueness of entity.
     *
     * If you want to get string representation in accordance with the provisions naming convention
     * you should use `bem-naming` package.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', mod: 'disabled' });
     *
     * name.id; // button_disabled
     *
     * @returns {string} id of entity.
     */
    get id() {
        if (this._id) { return this._id; }

        const entity = { block: this._data.block };

        this.elem && (entity.elem = this.elem);
        this.modName && (entity.modName = this.modName);
        this.modVal && (entity.modVal = this.modVal);

        this._id = stringifyEntity(entity);

        return this._id;
    }

    /**
     * Returns type for this entity.
     *
     * @example
type of element

     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', elem: 'text' });
     *
     * name.type; // elem
     *
     * @example
type of element modifier

     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'menu', elem: 'item', mod: 'current' });
     *
     * name.type; // elemMod
     *
     * @returns {string} type of entity.
     */
    get type() {
        if (this._type) { return this._type; }

        const data = this._data;
        const isMod = data.mod;

        this._type = data.elem
            ? isMod ? TYPES.ELEM_MOD : TYPES.ELEM
            : isMod ? TYPES.BLOCK_MOD : TYPES.BLOCK;

        return this._type;
    }
    /**
     * Returns string representing the entity name.
     *
     * Important: If you want to get string representation in accordance with the provisions naming convention
     * you should use `bem-naming` package.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button' });
     *
     * name.toString(); // button_focused
     *
     * @returns {string}
     */
    toString() { return this.id; }

    /**
     * Returns object representing the entity name. Is needed for debug in Node.js.
     *
     * In some browsers `console.log()` calls `valueOf()` on each argument.
     * This method will be called to get custom string representation of the object.
     *
     * The representation object contains only `block`, `elem` and `mod` fields
     * without private and deprecated fields (`modName` and `modVal`).
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button' });
     *
     * name.valueOf();
     *
     * // ➜ { block: 'button', mod: { name: 'focused', value: true } }
     *
     * @returns {{block: string, elem: ?string, mod: ?{name: ?string, val: *}}}
     */
    valueOf() { return this._data; }

    /**
     * Returns object representing the entity name. Is needed for debug in Node.js.
     *
     * In Node.js, `console.log()` calls `util.inspect()` on each argument without a formatting placeholder.
     * This method will be called to get custom string representation of the object.
     *
     * The representation object contains only `block`, `elem` and `mod` fields
     * without private and deprecated fields (`modName` and `modVal`).
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button' });
     *
     * console.log(name); // BemEntityName { block: 'button' }
     *
     * @param {integer} depth — tells inspect how many times to recurse while formatting the object.
     * @param {object} options — An optional `options` object may be passed
     *                         	 that alters certain aspects of the formatted string.
     *
     * @returns {string}
     */
    inspect(depth, options) {
        const stringRepresentation = util.inspect(this._data, options);

        return `BemEntityName ${stringRepresentation}`;
    }

    /**
     * Determines whether specified entity is the deepEqual entity.
     *
     * @param {BemEntityName} entityName - the entity to compare.
     *
     * @returns {boolean} A Boolean indicating whether or not specified entity is the deepEqual entity.
     * @example
     * const BemEntityName = require('bem-entity-name');
     *
     * const inputName = new BemEntityName({ block: 'input' });
     * const buttonName = new BemEntityName({ block: 'button' });
     *
     * console.log(inputName.isEqual(buttonName)); // false
     * console.log(buttonName.isEqual(buttonName)); // true
     */
    isEqual(entityName) {
        return entityName && (this.id === entityName.id);
    }
};
<commit_msg>docs(examples): fix typo<commit_after>'use strict';

const util = require('util');

const stringifyEntity = require('bem-naming').stringify;

/**
 * Enum for types of BEM entities.
 *
 * @readonly
 * @enum {String}
 */
const TYPES = {
    BLOCK:     'block',
    BLOCK_MOD: 'blockMod',
    ELEM:      'elem',
    ELEM_MOD:  'elemMod'
};

module.exports = class BemEntityName {
    /**
     * @param {object} obj — representation of entity name.
     * @param {string} obj.block  — the block name of entity.
     * @param {string} [obj.elem] — the element name of entity.
     * @param {object} [obj.mod]  — the modifier of entity.
     * @param {string} [obj.mod.name] — the modifier name of entity.
     * @param {string} [obj.mod.val]  — the modifier value of entity.
     */
    constructor(obj) {
        if (!obj.block) {
             throw new Error('This is not valid BEM entity: the field `block` is undefined.');
        }

        const data = this._data = { block: obj.block };
        const modName = (typeof obj.mod === 'string' ? obj.mod : obj.mod && obj.mod.name) || obj.modName;

        obj.elem && (data.elem = obj.elem);

        if (modName) {
            const modVal = obj.hasOwnProperty('modVal') || obj.mod && obj.mod.hasOwnProperty('val')
                ? obj.mod && obj.mod.val || obj.modVal
                : true;

            data.mod = {
                name: modName,
                val: modVal
            };
        }
    }

    /**
     * Returns the name of block to which this entity belongs.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button' });
     *
     * name.block; // button
     *
     * @returns {string} name of entity block.
     */
    get block() { return this._data.block; }

    /**
     * Returns the element name of this entity.
     *
     * If entity is not element or modifier of element then returns empty string.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', elem: 'text' });
     *
     * name.elem; // text
     *
     * @returns {string} name of entity element.
     */
    get elem() { return this._data.elem; }

    /**
     * Returns the modifier of this entity.
     *
     * Important: If entity is not a modifier then returns `undefined`.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     *
     * const blockName = new BemEntityName({ block: 'button' });
     * const modName = new BemEntityName({ block: 'button', mod: 'disabled' });
     *
     * modName.mod;   // { name: 'disabled', val: true }
     * blockName.mod; // undefined
     *
     * @returns {{mod: string, val: *}} entity modifier.
     */
    get mod() { return this._data.mod; }

    /**
     * Returns the modifier name of this entity.
     *
     * If entity is not modifier then returns `undefined`.
     *
     * @returns {string} entity modifier name.
     * @deprecated use `mod.name` instead.
     */
    get modName() { return this.mod && this.mod.name; }

    /**
     * Returns the modifier value of this entity.
     *
     * If entity is not modifier then returns `undefined`.
     *
     * @returns {string} entity modifier name.
     * @deprecated use `mod.val` instead.
     */
    get modVal() { return this.mod && this.mod.val; }

    /**
     * Returns id for this entity.
     *
     * Important: should only be used to determine uniqueness of entity.
     *
     * If you want to get string representation in accordance with the provisions naming convention
     * you should use `bem-naming` package.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', mod: 'disabled' });
     *
     * name.id; // button_disabled
     *
     * @returns {string} id of entity.
     */
    get id() {
        if (this._id) { return this._id; }

        const entity = { block: this._data.block };

        this.elem && (entity.elem = this.elem);
        this.modName && (entity.modName = this.modName);
        this.modVal && (entity.modVal = this.modVal);

        this._id = stringifyEntity(entity);

        return this._id;
    }

    /**
     * Returns type for this entity.
     *
     * @example
type of element

     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', elem: 'text' });
     *
     * name.type; // elem
     *
     * @example
type of element modifier

     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'menu', elem: 'item', mod: 'current' });
     *
     * name.type; // elemMod
     *
     * @returns {string} type of entity.
     */
    get type() {
        if (this._type) { return this._type; }

        const data = this._data;
        const isMod = data.mod;

        this._type = data.elem
            ? isMod ? TYPES.ELEM_MOD : TYPES.ELEM
            : isMod ? TYPES.BLOCK_MOD : TYPES.BLOCK;

        return this._type;
    }
    /**
     * Returns string representing the entity name.
     *
     * Important: If you want to get string representation in accordance with the provisions naming convention
     * you should use `bem-naming` package.
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', mod: 'focused' });
     *
     * name.toString(); // button_focused
     *
     * @returns {string}
     */
    toString() { return this.id; }

    /**
     * Returns object representing the entity name. Is needed for debug in Node.js.
     *
     * In some browsers `console.log()` calls `valueOf()` on each argument.
     * This method will be called to get custom string representation of the object.
     *
     * The representation object contains only `block`, `elem` and `mod` fields
     * without private and deprecated fields (`modName` and `modVal`).
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button', mod: 'focused' });
     *
     * name.valueOf();
     *
     * // ➜ { block: 'button', mod: { name: 'focused', value: true } }
     *
     * @returns {{block: string, elem: ?string, mod: ?{name: ?string, val: *}}}
     */
    valueOf() { return this._data; }

    /**
     * Returns object representing the entity name. Is needed for debug in Node.js.
     *
     * In Node.js, `console.log()` calls `util.inspect()` on each argument without a formatting placeholder.
     * This method will be called to get custom string representation of the object.
     *
     * The representation object contains only `block`, `elem` and `mod` fields
     * without private and deprecated fields (`modName` and `modVal`).
     *
     * @example
     * const BemEntityName = require('bem-entity-name');
     * const name = new BemEntityName({ block: 'button' });
     *
     * console.log(name); // BemEntityName { block: 'button' }
     *
     * @param {integer} depth — tells inspect how many times to recurse while formatting the object.
     * @param {object} options — An optional `options` object may be passed
     *                         	 that alters certain aspects of the formatted string.
     *
     * @returns {string}
     */
    inspect(depth, options) {
        const stringRepresentation = util.inspect(this._data, options);

        return `BemEntityName ${stringRepresentation}`;
    }

    /**
     * Determines whether specified entity is the deepEqual entity.
     *
     * @param {BemEntityName} entityName - the entity to compare.
     *
     * @returns {boolean} A Boolean indicating whether or not specified entity is the deepEqual entity.
     * @example
     * const BemEntityName = require('bem-entity-name');
     *
     * const inputName = new BemEntityName({ block: 'input' });
     * const buttonName = new BemEntityName({ block: 'button' });
     *
     * console.log(inputName.isEqual(buttonName)); // false
     * console.log(buttonName.isEqual(buttonName)); // true
     */
    isEqual(entityName) {
        return entityName && (this.id === entityName.id);
    }
};
<|endoftext|>


<commit_before>var Parsimmon = {};

Parsimmon.Parser = (function() {
  "use strict";

  // The Parser object is a wrapper for a parser function.
  // Externally, you use one to parse a string by calling
  //   var result = SomeParser.parse('Me Me Me! Parse Me!');
  // You should never call the constructor, rather you should
  // construct your Parser from the base parsers and the
  // parser combinator methods.
  function Parser(action) {
    if (!(this instanceof Parser)) return new Parser(action);
    this._ = action;
  };

  var _ = Parser.prototype;

  function makeSuccess(index, value) {
    return {
      status: true,
      index: index,
      value: value,
      furthest: -1,
      expected: []
    };
  }

  function makeFailure(index, expected) {
    return {
      status: false,
      index: -1,
      value: null,
      furthest: index,
      expected: [expected]
    };
  }

  function mergeReplies(result, last) {
    if (!last) return result;
    if (result.furthest > last.furthest) return result;

    var expected = (result.furthest === last.furthest)
      ? result.expected.concat(last.expected)
      : last.expected;

    return {
      status: result.status,
      index: result.index,
      value: result.value,
      furthest: last.furthest,
      expected: expected
    }
  }

  // For ensuring we have the right argument types
  function assertParser(p) {
    if (!(p instanceof Parser)) throw new Error('not a parser: '+p);
  }
  function assertNumber(x) {
    if (typeof x !== 'number') throw new Error('not a number: '+x);
  }
  function assertRegexp(x) {
    if (!(x instanceof RegExp)) throw new Error('not a regex: '+x);
  }
  function assertFunction(x) {
    if (typeof x !== 'function') throw new Error('not a function: '+x);
  }
  function assertString(x) {
    if (typeof x !== 'string') throw new Error('not a string: '+x)
  }

  function formatExpected(expected) {
    if (expected.length === 1) return expected[0];

    return 'one of ' + expected.join(', ')
  }

  function formatGot(stream, error) {
    var i = error.index;

    if (i === stream.length) return ', got the end of the stream'

    var prefix = (i > 0 ? "'..." : "'");
    var suffix = (stream.length - i > 12 ? "...'" : "'");

    return ' at character ' + i + ', got ' + prefix + stream.slice(i, i+12) + suffix
  }

  var formatError = Parsimmon.formatError = function(stream, error) {
    return 'expected ' + formatExpected(error.expected) + formatGot(stream, error)
  };

  _.parse = function(stream) {
    if (typeof stream !== 'string') {
      throw new Error('.parse must be called with a string as its argument');
    }
    var result = this.skip(eof)._(stream, 0);

    return result.status ? {
      status: true,
      value: result.value
    } : {
      status: false,
      index: result.furthest,
      expected: result.expected
    };
  };

  // [Parser a] -> Parser [a]
  var seq = Parsimmon.seq = function() {
    var parsers = [].slice.call(arguments);
    var numParsers = parsers.length;

    for (var j = 0; j < numParsers; j += 1) {
      assertParser(parsers[j]);
    }

    return Parser(function(stream, i) {
      var result;
      var accum = new Array(numParsers);

      for (var j = 0; j < numParsers; j += 1) {
        result = mergeReplies(parsers[j]._(stream, i), result);
        if (!result.status) return result;
        accum[j] = result.value
        i = result.index;
      }

      return mergeReplies(makeSuccess(i, accum), result);
    });
  };

  var seqMap = Parsimmon.seqMap = function() {
    var args = [].slice.call(arguments);
    var mapper = args.pop();
    return seq.apply(null, args).map(function(results) {
      return mapper.apply(null, results);
    });
  };

  /**
   * Allows to add custom primitive parsers
   */
  var custom = Parsimmon.custom = function(parsingFunction) {
    return Parser(parsingFunction(makeSuccess, makeFailure));
  };

  var alt = Parsimmon.alt = function() {
    var parsers = [].slice.call(arguments);
    var numParsers = parsers.length;
    if (numParsers === 0) return fail('zero alternates')

    for (var j = 0; j < numParsers; j += 1) {
      assertParser(parsers[j]);
    }

    return Parser(function(stream, i) {
      var result;
      for (var j = 0; j < parsers.length; j += 1) {
        result = mergeReplies(parsers[j]._(stream, i), result);
        if (result.status) return result;
      }
      return result;
    });
  };

  var sepBy = Parsimmon.sepBy = function(parser, separator) {
    // Argument asserted by sepBy1
    return sepBy1(parser, separator).or(Parsimmon.of([]));
  };

  var sepBy1 = Parsimmon.sepBy1 = function(parser, separator) {
    assertParser(parser);
    assertParser(separator);

    var pairs = separator.then(parser).many();

    return parser.chain(function(r) {
      return pairs.map(function(rs) {
        return [r].concat(rs);
      })
    })
  };

  // -*- primitive combinators -*- //
  _.or = function(alternative) {
    return alt(this, alternative);
  };

  _.then = function(next) {
    if (typeof next === 'function') {
      throw new Error('chaining features of .then are no longer supported, use .chain instead');
    }

    assertParser(next);
    return seq(this, next).map(function(results) { return results[1]; });
  };

  // -*- optimized iterative combinators -*- //
  // equivalent to:
  // _.many = function() {
  //   return this.times(0, Infinity);
  // };
  // or, more explicitly:
  // _.many = function() {
  //   var self = this;
  //   return self.then(function(x) {
  //     return self.many().then(function(xs) {
  //       return [x].concat(xs);
  //     });
  //   }).or(succeed([]));
  // };
  _.many = function() {
    var self = this;

    return Parser(function(stream, i) {
      var accum = [];
      var result;
      var prevResult;

      for (;;) {
        result = mergeReplies(self._(stream, i), result);

        if (result.status) {
          i = result.index;
          accum.push(result.value);
        }
        else {
          return mergeReplies(makeSuccess(i, accum), result);
        }
      }
    });
  };

  // equivalent to:
  // _.times = function(min, max) {
  //   if (arguments.length < 2) max = min;
  //   var self = this;
  //   if (min > 0) {
  //     return self.then(function(x) {
  //       return self.times(min - 1, max - 1).then(function(xs) {
  //         return [x].concat(xs);
  //       });
  //     });
  //   }
  //   else if (max > 0) {
  //     return self.then(function(x) {
  //       return self.times(0, max - 1).then(function(xs) {
  //         return [x].concat(xs);
  //       });
  //     }).or(succeed([]));
  //   }
  //   else return succeed([]);
  // };
  _.times = function(min, max) {
    if (arguments.length < 2) max = min;
    var self = this;

    assertNumber(min);
    assertNumber(max);

    return Parser(function(stream, i) {
      var accum = [];
      var start = i;
      var result;
      var prevResult;

      for (var times = 0; times < min; times += 1) {
        result = self._(stream, i);
        prevResult = mergeReplies(result, prevResult);
        if (result.status) {
          i = result.index;
          accum.push(result.value);
        }
        else return prevResult;
      }

      for (; times < max; times += 1) {
        result = self._(stream, i);
        prevResult = mergeReplies(result, prevResult);
        if (result.status) {
          i = result.index;
          accum.push(result.value);
        }
        else break;
      }

      return mergeReplies(makeSuccess(i, accum), prevResult);
    });
  };

  // -*- higher-level combinators -*- //
  _.result = function(res) { return this.map(function(_) { return res; }); };
  _.atMost = function(n) { return this.times(0, n); };
  _.atLeast = function(n) {
    var self = this;
    return seqMap(this.times(n), this.many(), function(init, rest) {
      return init.concat(rest);
    });
  };

  _.map = function(fn) {

    assertFunction(fn);

    var self = this;
    return Parser(function(stream, i) {
      var result = self._(stream, i);
      if (!result.status) return result;
      return mergeReplies(makeSuccess(result.index, fn(result.value)), result);
    });
  };

  _.skip = function(next) {
    return seq(this, next).map(function(results) { return results[0]; });
  };

  _.mark = function() {
    return seqMap(index, this, index, function(start, value, end) {
      return { start: start, value: value, end: end };
    });
  };

  _.desc = function(expected) {
    var self = this;
    return Parser(function(stream, i) {
      var reply = self._(stream, i);
      if (!reply.status) reply.expected = [expected];
      return reply;
    });
  };

  // -*- primitive parsers -*- //
  var string = Parsimmon.string = function(str) {
    var len = str.length;
    var expected = "'"+str+"'";

    assertString(str);

    return Parser(function(stream, i) {
      var head = stream.slice(i, i+len);

      if (head === str) {
        return makeSuccess(i+len, head);
      }
      else {
        return makeFailure(i, expected);
      }
    });
  };

  var regex = Parsimmon.regex = function(re, group) {

    assertRegexp(re);
    if (group) assertNumber(group);

    var anchored = RegExp('^(?:'+re.source+')', (''+re).slice((''+re).lastIndexOf('/')+1));
    var expected = '' + re;
    if (group == null) group = 0;

    return Parser(function(stream, i) {
      var match = anchored.exec(stream.slice(i));

      if (match) {
        var fullMatch = match[0];
        var groupMatch = match[group];
        if (groupMatch != null) return makeSuccess(i+fullMatch.length, groupMatch);
      }

      return makeFailure(i, expected);
    });
  };

  var succeed = Parsimmon.succeed = function(value) {
    return Parser(function(stream, i) {
      return makeSuccess(i, value);
    });
  };

  var fail = Parsimmon.fail = function(expected) {
    return Parser(function(stream, i) { return makeFailure(i, expected); });
  };

  var letter = Parsimmon.letter = regex(/[a-z]/i).desc('a letter')
  var letters = Parsimmon.letters = regex(/[a-z]*/i)
  var digit = Parsimmon.digit = regex(/[0-9]/).desc('a digit');
  var digits = Parsimmon.digits = regex(/[0-9]*/)
  var whitespace = Parsimmon.whitespace = regex(/\s+/).desc('whitespace');
  var optWhitespace = Parsimmon.optWhitespace = regex(/\s*/);

  var any = Parsimmon.any = Parser(function(stream, i) {
    if (i >= stream.length) return makeFailure(i, 'any character');

    return makeSuccess(i+1, stream.charAt(i));
  });

  var all = Parsimmon.all = Parser(function(stream, i) {
    return makeSuccess(stream.length, stream.slice(i));
  });

  var eof = Parsimmon.eof = Parser(function(stream, i) {
    if (i < stream.length) return makeFailure(i, 'EOF');

    return makeSuccess(i, null);
  });

  var test = Parsimmon.test = function(predicate) {
    assertFunction(predicate);

    return Parser(function(stream, i) {
      var char = stream.charAt(i);
      if (i < stream.length && predicate(char)) {
        return makeSuccess(i+1, char);
      }
      else {
        return makeFailure(i, 'a character matching '+predicate);
      }
    });
  };

  var oneOf = Parsimmon.oneOf = function(str) {
    return test(function(ch) { return str.indexOf(ch) >= 0; });
  };

  var noneOf = Parsimmon.noneOf = function(str) {
    return test(function(ch) { return str.indexOf(ch) < 0; });
  };

  var takeWhile = Parsimmon.takeWhile = function(predicate) {
    assertFunction(predicate);

    return Parser(function(stream, i) {
      var j = i;
      while (j < stream.length && predicate(stream.charAt(j))) j += 1;
      return makeSuccess(j, stream.slice(i, j));
    });
  };

  var lazy = Parsimmon.lazy = function(desc, f) {
    if (arguments.length < 2) {
      f = desc;
      desc = undefined;
    }

    var parser = Parser(function(stream, i) {
      parser._ = f()._;
      return parser._(stream, i);
    });

    if (desc) parser = parser.desc(desc)

    return parser;
  };

  var index = Parsimmon.index = Parser(function(stream, i) {
    return makeSuccess(i, i);
  });

  //- fantasyland compat

  //- Monoid (Alternative, really)
  _.concat = _.or;
  _.empty = fail('empty')

  //- Applicative
  _.of = Parser.of = Parsimmon.of = succeed

  _.ap = function(other) {
    return seqMap(this, other, function(f, x) { return f(x); })
  };

  //- Monad
  _.chain = function(f) {
    var self = this;
    return Parser(function(stream, i) {
      var result = self._(stream, i);
      if (!result.status) return result;
      var nextParser = f(result.value);
      return mergeReplies(nextParser._(stream, result.index), result);
    });
  };

  return Parser;
})();
module.exports = Parsimmon;
<commit_msg>Use neater forEach for asserting parsers array<commit_after>var Parsimmon = {};

Parsimmon.Parser = (function() {
  "use strict";

  // The Parser object is a wrapper for a parser function.
  // Externally, you use one to parse a string by calling
  //   var result = SomeParser.parse('Me Me Me! Parse Me!');
  // You should never call the constructor, rather you should
  // construct your Parser from the base parsers and the
  // parser combinator methods.
  function Parser(action) {
    if (!(this instanceof Parser)) return new Parser(action);
    this._ = action;
  };

  var _ = Parser.prototype;

  function makeSuccess(index, value) {
    return {
      status: true,
      index: index,
      value: value,
      furthest: -1,
      expected: []
    };
  }

  function makeFailure(index, expected) {
    return {
      status: false,
      index: -1,
      value: null,
      furthest: index,
      expected: [expected]
    };
  }

  function mergeReplies(result, last) {
    if (!last) return result;
    if (result.furthest > last.furthest) return result;

    var expected = (result.furthest === last.furthest)
      ? result.expected.concat(last.expected)
      : last.expected;

    return {
      status: result.status,
      index: result.index,
      value: result.value,
      furthest: last.furthest,
      expected: expected
    }
  }

  // For ensuring we have the right argument types
  function assertParser(p) {
    if (!(p instanceof Parser)) throw new Error('not a parser: '+p);
  }
  function assertNumber(x) {
    if (typeof x !== 'number') throw new Error('not a number: '+x);
  }
  function assertRegexp(x) {
    if (!(x instanceof RegExp)) throw new Error('not a regex: '+x);
  }
  function assertFunction(x) {
    if (typeof x !== 'function') throw new Error('not a function: '+x);
  }
  function assertString(x) {
    if (typeof x !== 'string') throw new Error('not a string: '+x)
  }

  function formatExpected(expected) {
    if (expected.length === 1) return expected[0];

    return 'one of ' + expected.join(', ')
  }

  function formatGot(stream, error) {
    var i = error.index;

    if (i === stream.length) return ', got the end of the stream'

    var prefix = (i > 0 ? "'..." : "'");
    var suffix = (stream.length - i > 12 ? "...'" : "'");

    return ' at character ' + i + ', got ' + prefix + stream.slice(i, i+12) + suffix
  }

  var formatError = Parsimmon.formatError = function(stream, error) {
    return 'expected ' + formatExpected(error.expected) + formatGot(stream, error)
  };

  _.parse = function(stream) {
    if (typeof stream !== 'string') {
      throw new Error('.parse must be called with a string as its argument');
    }
    var result = this.skip(eof)._(stream, 0);

    return result.status ? {
      status: true,
      value: result.value
    } : {
      status: false,
      index: result.furthest,
      expected: result.expected
    };
  };

  // [Parser a] -> Parser [a]
  var seq = Parsimmon.seq = function() {
    var parsers = [].slice.call(arguments);
    var numParsers = parsers.length;

    parsers.forEach(assertParser)

    return Parser(function(stream, i) {
      var result;
      var accum = new Array(numParsers);

      for (var j = 0; j < numParsers; j += 1) {
        result = mergeReplies(parsers[j]._(stream, i), result);
        if (!result.status) return result;
        accum[j] = result.value
        i = result.index;
      }

      return mergeReplies(makeSuccess(i, accum), result);
    });
  };

  var seqMap = Parsimmon.seqMap = function() {
    var args = [].slice.call(arguments);
    var mapper = args.pop();
    return seq.apply(null, args).map(function(results) {
      return mapper.apply(null, results);
    });
  };

  /**
   * Allows to add custom primitive parsers
   */
  var custom = Parsimmon.custom = function(parsingFunction) {
    return Parser(parsingFunction(makeSuccess, makeFailure));
  };

  var alt = Parsimmon.alt = function() {
    var parsers = [].slice.call(arguments);
    var numParsers = parsers.length;
    if (numParsers === 0) return fail('zero alternates')

    parsers.forEach(assertParser)

    return Parser(function(stream, i) {
      var result;
      for (var j = 0; j < parsers.length; j += 1) {
        result = mergeReplies(parsers[j]._(stream, i), result);
        if (result.status) return result;
      }
      return result;
    });
  };

  var sepBy = Parsimmon.sepBy = function(parser, separator) {
    // Argument asserted by sepBy1
    return sepBy1(parser, separator).or(Parsimmon.of([]));
  };

  var sepBy1 = Parsimmon.sepBy1 = function(parser, separator) {
    assertParser(parser);
    assertParser(separator);

    var pairs = separator.then(parser).many();

    return parser.chain(function(r) {
      return pairs.map(function(rs) {
        return [r].concat(rs);
      })
    })
  };

  // -*- primitive combinators -*- //
  _.or = function(alternative) {
    return alt(this, alternative);
  };

  _.then = function(next) {
    if (typeof next === 'function') {
      throw new Error('chaining features of .then are no longer supported, use .chain instead');
    }

    assertParser(next);
    return seq(this, next).map(function(results) { return results[1]; });
  };

  // -*- optimized iterative combinators -*- //
  // equivalent to:
  // _.many = function() {
  //   return this.times(0, Infinity);
  // };
  // or, more explicitly:
  // _.many = function() {
  //   var self = this;
  //   return self.then(function(x) {
  //     return self.many().then(function(xs) {
  //       return [x].concat(xs);
  //     });
  //   }).or(succeed([]));
  // };
  _.many = function() {
    var self = this;

    return Parser(function(stream, i) {
      var accum = [];
      var result;
      var prevResult;

      for (;;) {
        result = mergeReplies(self._(stream, i), result);

        if (result.status) {
          i = result.index;
          accum.push(result.value);
        }
        else {
          return mergeReplies(makeSuccess(i, accum), result);
        }
      }
    });
  };

  // equivalent to:
  // _.times = function(min, max) {
  //   if (arguments.length < 2) max = min;
  //   var self = this;
  //   if (min > 0) {
  //     return self.then(function(x) {
  //       return self.times(min - 1, max - 1).then(function(xs) {
  //         return [x].concat(xs);
  //       });
  //     });
  //   }
  //   else if (max > 0) {
  //     return self.then(function(x) {
  //       return self.times(0, max - 1).then(function(xs) {
  //         return [x].concat(xs);
  //       });
  //     }).or(succeed([]));
  //   }
  //   else return succeed([]);
  // };
  _.times = function(min, max) {
    if (arguments.length < 2) max = min;
    var self = this;

    assertNumber(min);
    assertNumber(max);

    return Parser(function(stream, i) {
      var accum = [];
      var start = i;
      var result;
      var prevResult;

      for (var times = 0; times < min; times += 1) {
        result = self._(stream, i);
        prevResult = mergeReplies(result, prevResult);
        if (result.status) {
          i = result.index;
          accum.push(result.value);
        }
        else return prevResult;
      }

      for (; times < max; times += 1) {
        result = self._(stream, i);
        prevResult = mergeReplies(result, prevResult);
        if (result.status) {
          i = result.index;
          accum.push(result.value);
        }
        else break;
      }

      return mergeReplies(makeSuccess(i, accum), prevResult);
    });
  };

  // -*- higher-level combinators -*- //
  _.result = function(res) { return this.map(function(_) { return res; }); };
  _.atMost = function(n) { return this.times(0, n); };
  _.atLeast = function(n) {
    var self = this;
    return seqMap(this.times(n), this.many(), function(init, rest) {
      return init.concat(rest);
    });
  };

  _.map = function(fn) {

    assertFunction(fn);

    var self = this;
    return Parser(function(stream, i) {
      var result = self._(stream, i);
      if (!result.status) return result;
      return mergeReplies(makeSuccess(result.index, fn(result.value)), result);
    });
  };

  _.skip = function(next) {
    return seq(this, next).map(function(results) { return results[0]; });
  };

  _.mark = function() {
    return seqMap(index, this, index, function(start, value, end) {
      return { start: start, value: value, end: end };
    });
  };

  _.desc = function(expected) {
    var self = this;
    return Parser(function(stream, i) {
      var reply = self._(stream, i);
      if (!reply.status) reply.expected = [expected];
      return reply;
    });
  };

  // -*- primitive parsers -*- //
  var string = Parsimmon.string = function(str) {
    var len = str.length;
    var expected = "'"+str+"'";

    assertString(str);

    return Parser(function(stream, i) {
      var head = stream.slice(i, i+len);

      if (head === str) {
        return makeSuccess(i+len, head);
      }
      else {
        return makeFailure(i, expected);
      }
    });
  };

  var regex = Parsimmon.regex = function(re, group) {

    assertRegexp(re);
    if (group) assertNumber(group);

    var anchored = RegExp('^(?:'+re.source+')', (''+re).slice((''+re).lastIndexOf('/')+1));
    var expected = '' + re;
    if (group == null) group = 0;

    return Parser(function(stream, i) {
      var match = anchored.exec(stream.slice(i));

      if (match) {
        var fullMatch = match[0];
        var groupMatch = match[group];
        if (groupMatch != null) return makeSuccess(i+fullMatch.length, groupMatch);
      }

      return makeFailure(i, expected);
    });
  };

  var succeed = Parsimmon.succeed = function(value) {
    return Parser(function(stream, i) {
      return makeSuccess(i, value);
    });
  };

  var fail = Parsimmon.fail = function(expected) {
    return Parser(function(stream, i) { return makeFailure(i, expected); });
  };

  var letter = Parsimmon.letter = regex(/[a-z]/i).desc('a letter')
  var letters = Parsimmon.letters = regex(/[a-z]*/i)
  var digit = Parsimmon.digit = regex(/[0-9]/).desc('a digit');
  var digits = Parsimmon.digits = regex(/[0-9]*/)
  var whitespace = Parsimmon.whitespace = regex(/\s+/).desc('whitespace');
  var optWhitespace = Parsimmon.optWhitespace = regex(/\s*/);

  var any = Parsimmon.any = Parser(function(stream, i) {
    if (i >= stream.length) return makeFailure(i, 'any character');

    return makeSuccess(i+1, stream.charAt(i));
  });

  var all = Parsimmon.all = Parser(function(stream, i) {
    return makeSuccess(stream.length, stream.slice(i));
  });

  var eof = Parsimmon.eof = Parser(function(stream, i) {
    if (i < stream.length) return makeFailure(i, 'EOF');

    return makeSuccess(i, null);
  });

  var test = Parsimmon.test = function(predicate) {
    assertFunction(predicate);

    return Parser(function(stream, i) {
      var char = stream.charAt(i);
      if (i < stream.length && predicate(char)) {
        return makeSuccess(i+1, char);
      }
      else {
        return makeFailure(i, 'a character matching '+predicate);
      }
    });
  };

  var oneOf = Parsimmon.oneOf = function(str) {
    return test(function(ch) { return str.indexOf(ch) >= 0; });
  };

  var noneOf = Parsimmon.noneOf = function(str) {
    return test(function(ch) { return str.indexOf(ch) < 0; });
  };

  var takeWhile = Parsimmon.takeWhile = function(predicate) {
    assertFunction(predicate);

    return Parser(function(stream, i) {
      var j = i;
      while (j < stream.length && predicate(stream.charAt(j))) j += 1;
      return makeSuccess(j, stream.slice(i, j));
    });
  };

  var lazy = Parsimmon.lazy = function(desc, f) {
    if (arguments.length < 2) {
      f = desc;
      desc = undefined;
    }

    var parser = Parser(function(stream, i) {
      parser._ = f()._;
      return parser._(stream, i);
    });

    if (desc) parser = parser.desc(desc)

    return parser;
  };

  var index = Parsimmon.index = Parser(function(stream, i) {
    return makeSuccess(i, i);
  });

  //- fantasyland compat

  //- Monoid (Alternative, really)
  _.concat = _.or;
  _.empty = fail('empty')

  //- Applicative
  _.of = Parser.of = Parsimmon.of = succeed

  _.ap = function(other) {
    return seqMap(this, other, function(f, x) { return f(x); })
  };

  //- Monad
  _.chain = function(f) {
    var self = this;
    return Parser(function(stream, i) {
      var result = self._(stream, i);
      if (!result.status) return result;
      var nextParser = f(result.value);
      return mergeReplies(nextParser._(stream, result.index), result);
    });
  };

  return Parser;
})();
module.exports = Parsimmon;
<|endoftext|>


<commit_before>/*
Name:         pastecapi
Description:  Lightweight module for Pastec image recognition API
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.com/fvdm/nodejs-pastecapi
Feedback:     https://github.com/fvdm/nodejs-pastecapi/issues
License:      Unlicense (Public Domain, see LICENSE file)
*/

var httpreq = require ('httpreq');
var fs = require ('fs');

var config = {};

/**
 * Communicate with API
 *
 * @callback callback
 * @param {object} options
 * @param {string} options.method=GET - HTTP method
 * @param {string} options.path=/ - Request path, i.e. /index/searcher
 * @param {object} options.parameters - Request query parameters
 * @param {object} options.json - POST JSON data
 * @param {object} options.files - Upload files paths
 * @param {number} options.timeout=5000 - Override request timeout in ms
 * @param {function} callback - Callback function
 * @returns {void}
 */

function talk (options, callback) {
  options.url = config.endpoint + options.path;
  options.method = options.method || 'GET';
  options.timeout = config.timeout;
  options.headers = options.headers || {};
  options.headers ['User-Agent'] = 'pastecapi node/' + process.versions.node;

  httpreq.doRequest (options, function (err, res) {
    var data = res && res.body || '';
    var error = null;

    if (err) {
      error = new Error ('request failed');
      error.error = err;
      callback (error);
      return;
    }

    try {
      data = JSON.parse (data);
    } catch (e) {
      error = new Error ('request failed');
      error.error = e;
      callback (error);
      return;
    }

    callback (null, data);
  });
}

/**
 * Test API access
 *
 * @callback callback
 * @param {function} callback - Process result
 * @returns {void}
 */

function ping (callback) {
  var options = {
    method: 'POST',
    path: '/',
    json: {
      type: 'PING'
    }
  };

  talk (options, callback);
}

/**
 * Load index from file on server
 *
 * @param {string} indexPath - Path to .dat file on server
 * @param {function} callback - Process result
 * @returns {void}
 */

function loadIndex (indexPath, callback) {
  var options = {
    method: 'POST',
    path: '/index/io',
    json: {
      type: 'LOAD',
      index_path: indexPath
    }
  };

  talk (options, callback);
}

/**
 * Write index to file on server
 *
 * @callback callback
 * @param {string} indexPath - Path of .dat file on server
 * @param {function} callback - Process result
 * @returns {void}
 */

function writeIndex (indexPath, callback) {
  var options = {
    method: 'POST',
    path: '/index/io',
    json: {
      type: 'WRITE',
      index_path: indexPath
    }
  };

  talk (options, callback);
}

/**
 * Clear index on server
 *
 * @callback callback
 * @param {function} callback - Process result
 * @returns {void}
 */

function clearIndex (callback) {
  var options = {
    method: 'POST',
    path: '/index/io',
    json: {
      type: 'CLEAR'
    }
  };

  talk (options, callback);
}

/**
 * Match image against index
 *
 * @callback callback
 * @param {string} image - Buffer or local path to image
 * @param {function} callback - Process result
 * @returns {void}
 */

function searchIndex (image, callback) {
  var options = {
    method: 'POST',
    path: '/index/searcher',
    binary: true
  };

  // Binary pass through
  if (image instanceof Buffer) {
    options.body = image;
    options.headers = {
      'Content-Length': image.length,
      'Content-Type': 'image/jpeg'
    };
    talk (options, callback);
    return;
  }

  // Read file to buffer
  fs.readFile (image, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    options.body = data;
    options.headers = {
      'Content-Length': data.length,
      'Content-Type': 'image/jpeg'
    };

    talk (options, callback);
  });
}

/**
 * Remove image signature from index
 *
 * @callback callback
 * @param {number} imageId - Index ID of image signature
 * @param {function} callback - Process result
 * @returns {void}
 */

function deleteImage (imageId, callback) {
  var options = {
    method: 'DELETE',
    path: '/index/images/' + imageId
  };

  talk (options, callback);
}

/**
 * Add image signature to index
 *
 * @callback callback
 * @param {string} image - Buffer or local path to image
 * @param {number} imageId - Index ID for image
 * @param {function} callback - Process result
 * @returns {void}
 */

function addImage (image, imageId, callback) {
  var options = {
    method: 'PUT',
    path: '/index/images/' + imageId,
    binary: true
  };

  // Binary pass through
  if (image instanceof Buffer) {
    options.body = image;
    options.headers = {
      'Content-Length': image.length,
      'Content-Type': 'image/jpeg'
    };
    talk (options, callback);
    return;
  }

  // Read file to buffer
  fs.readFile (image, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    options.body = data;
    options.headers = {
      'Content-Length': data.length,
      'Content-Type': 'image/jpeg'
    };
    talk (options, callback);
  });
}

/**
 * Module setup
 *
 * @param {string} endpoint - REST API base URL
 * @param {integer} timeout - Request wait timeout in ms
 * @returns {object} - Module methods
 */

module.exports = function (endpoint, timeout) {
  config.endpoint = endpoint || 'http://localhost:4121';
  config.timeout = timeout || 5000;

  return {
    ping,
    loadIndex,
    writeIndex,
    clearIndex,
    searchIndex,
    addImage,
    deleteImage
  };
};
<commit_msg>Allow timeout override in talk()<commit_after>/*
Name:         pastecapi
Description:  Lightweight module for Pastec image recognition API
Author:       Franklin van de Meent (https://frankl.in)
Source code:  https://github.com/fvdm/nodejs-pastecapi
Feedback:     https://github.com/fvdm/nodejs-pastecapi/issues
License:      Unlicense (Public Domain, see LICENSE file)
*/

var httpreq = require ('httpreq');
var fs = require ('fs');

var config = {};

/**
 * Communicate with API
 *
 * @callback callback
 * @param {object} options
 * @param {string} options.method=GET - HTTP method
 * @param {string} options.path=/ - Request path, i.e. /index/searcher
 * @param {object} options.parameters - Request query parameters
 * @param {object} options.json - POST JSON data
 * @param {object} options.files - Upload files paths
 * @param {number} options.timeout=5000 - Override request timeout in ms
 * @param {function} callback - Callback function
 * @returns {void}
 */

function talk (options, callback) {
  options.url = config.endpoint + options.path;
  options.method = options.method || 'GET';
  options.timeout = options.timeout || config.timeout;
  options.headers = options.headers || {};
  options.headers ['User-Agent'] = 'pastecapi node/' + process.versions.node;

  httpreq.doRequest (options, function (err, res) {
    var data = res && res.body || '';
    var error = null;

    if (err) {
      error = new Error ('request failed');
      error.error = err;
      callback (error);
      return;
    }

    try {
      data = JSON.parse (data);
    } catch (e) {
      error = new Error ('request failed');
      error.error = e;
      callback (error);
      return;
    }

    callback (null, data);
  });
}

/**
 * Test API access
 *
 * @callback callback
 * @param {function} callback - Process result
 * @returns {void}
 */

function ping (callback) {
  var options = {
    method: 'POST',
    path: '/',
    json: {
      type: 'PING'
    }
  };

  talk (options, callback);
}

/**
 * Load index from file on server
 *
 * @param {string} indexPath - Path to .dat file on server
 * @param {function} callback - Process result
 * @returns {void}
 */

function loadIndex (indexPath, callback) {
  var options = {
    method: 'POST',
    path: '/index/io',
    json: {
      type: 'LOAD',
      index_path: indexPath
    }
  };

  talk (options, callback);
}

/**
 * Write index to file on server
 *
 * @callback callback
 * @param {string} indexPath - Path of .dat file on server
 * @param {function} callback - Process result
 * @returns {void}
 */

function writeIndex (indexPath, callback) {
  var options = {
    method: 'POST',
    path: '/index/io',
    json: {
      type: 'WRITE',
      index_path: indexPath
    }
  };

  talk (options, callback);
}

/**
 * Clear index on server
 *
 * @callback callback
 * @param {function} callback - Process result
 * @returns {void}
 */

function clearIndex (callback) {
  var options = {
    method: 'POST',
    path: '/index/io',
    json: {
      type: 'CLEAR'
    }
  };

  talk (options, callback);
}

/**
 * Match image against index
 *
 * @callback callback
 * @param {string} image - Buffer or local path to image
 * @param {function} callback - Process result
 * @returns {void}
 */

function searchIndex (image, callback) {
  var options = {
    method: 'POST',
    path: '/index/searcher',
    binary: true
  };

  // Binary pass through
  if (image instanceof Buffer) {
    options.body = image;
    options.headers = {
      'Content-Length': image.length,
      'Content-Type': 'image/jpeg'
    };
    talk (options, callback);
    return;
  }

  // Read file to buffer
  fs.readFile (image, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    options.body = data;
    options.headers = {
      'Content-Length': data.length,
      'Content-Type': 'image/jpeg'
    };

    talk (options, callback);
  });
}

/**
 * Remove image signature from index
 *
 * @callback callback
 * @param {number} imageId - Index ID of image signature
 * @param {function} callback - Process result
 * @returns {void}
 */

function deleteImage (imageId, callback) {
  var options = {
    method: 'DELETE',
    path: '/index/images/' + imageId
  };

  talk (options, callback);
}

/**
 * Add image signature to index
 *
 * @callback callback
 * @param {string} image - Buffer or local path to image
 * @param {number} imageId - Index ID for image
 * @param {function} callback - Process result
 * @returns {void}
 */

function addImage (image, imageId, callback) {
  var options = {
    method: 'PUT',
    path: '/index/images/' + imageId,
    binary: true
  };

  // Binary pass through
  if (image instanceof Buffer) {
    options.body = image;
    options.headers = {
      'Content-Length': image.length,
      'Content-Type': 'image/jpeg'
    };
    talk (options, callback);
    return;
  }

  // Read file to buffer
  fs.readFile (image, function (err, data) {
    if (err) {
      callback (err);
      return;
    }

    options.body = data;
    options.headers = {
      'Content-Length': data.length,
      'Content-Type': 'image/jpeg'
    };
    talk (options, callback);
  });
}

/**
 * Module setup
 *
 * @param {string} endpoint - REST API base URL
 * @param {integer} timeout - Request wait timeout in ms
 * @returns {object} - Module methods
 */

module.exports = function (endpoint, timeout) {
  config.endpoint = endpoint || 'http://localhost:4121';
  config.timeout = timeout || 5000;

  return {
    ping,
    loadIndex,
    writeIndex,
    clearIndex,
    searchIndex,
    addImage,
    deleteImage
  };
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var measure = require('./src/metrics');
var sourceFiles = require('./src/sourceFiles');
var complexityInfo = require('./src/reporter').getComplexityInfo;
var program = require('commander');
var package = require('./package.json');
var check = require('check-types');
var path = require('path');

var repoRevision = require('ggit').repoRevision;
var repoRoot = require('ggit').repoRoot;

program.version(package.version);
program._name = package.name;

program.command('help')
.description('show help and exit')
.action(function () {
	console.log('Complexity metrics:\n\n' + complexityInfo());
	program.help();
});

program.command('changes [filename]')
.description('analyze file complexity against Git repo version')
.option('-f, --filename [filename]', 'filename to analyze')
.action(function (filename, options) {
	filename = filename || options.filename;
	check.verifyString(filename, 'missing filename');
	var files = sourceFiles(filename);
	check.verifyArray(files, 'should get full filenames');
	if (!files.length) {
		console.log('not files found matching', filename);
		process.exit(0);
	}

	repoRoot(function (rootFolder) {
		var relativePaths = files.map(path.relative.bind(this, rootFolder));
		relativePaths.forEach(reportChange);
	});
});

if (process.argv.length === 2) {
	process.argv.push('help');
}
program.parse(process.argv);

function reportChange(filename) {
	check.verifyString(filename, 'missing filename');
	repoRevision(filename, function (contents) {
		check.verifyString(contents, 'could not get repo for', filename);
		var repoComplexity = measure.getSourceComplexity(contents, filename);
		var diskComplexity = measure.getFileComplexity(filename);
		diskComplexity.compare(repoComplexity, filename);
	});
}<commit_msg>updated index<commit_after>#!/usr/bin/env node

var measure = require('./src/metrics');
var sourceFiles = require('./src/sourceFiles');
var complexityInfo = require('./src/reporter').getComplexityInfo;
var program = require('commander');
var package = require('./package.json');
var check = require('check-types');
var path = require('path');

var repoRevision = require('ggit').repoRevision;
var repoRoot = require('ggit').repoRoot;

program.version(package.version);
program._name = package.name;

program.command('help')
.description('show help and exit')
.action(function () {
	console.log('Complexity metrics:\n\n' + complexityInfo());
	program.help();
});

program.command('changes [filename]')
.description('analyze file complexity against Git repo version')
.option('-f, --filename [filename]', 'filename to analyze')
.action(function (filename, options) {
	filename = filename || options.filename;
	check.verifyString(filename, 'missing filename');
	var files = sourceFiles(filename);
	check.verifyArray(files, 'should get full filenames');
	if (!files.length) {
		console.log('not files found matching', filename);
		process.exit(0);
	}

	repoRoot(function (rootFolder) {
		var relativePaths = files.map(path.relative.bind(this, rootFolder));
		relativePaths.forEach(reportChange);
	});
});

if (process.argv.length === 2) {
	process.argv.push('help');
}
program.parse(process.argv);

function reportChange(filename) {
	check.verifyString(filename, 'missing filename');
	repoRevision(filename, function (contents) {
		check.verifyString(contents, 'could not get repo for', filename);
		var repoComplexity = measure.getSourceComplexity(contents, filename);
		var diskComplexity = measure.getFileComplexity(filename);
		diskComplexity.compare(repoComplexity, filename);
	});
}<|endoftext|>


<commit_before>const os = require('os');
const fs = require('fs');
const path = require('path');
const execFile = require('child_process').execFile;

const tmpfile = path.join(os.tmpdir(), process.versions.v8+'.flags.json');
const exclusions = ['--help'];

module.exports = function (cb) {
  try {
    cb(null, require(tmpfile));
  } catch (e) {
    execFile(process.execPath, ['--v8-options'], function (execErr, result) {
      var flags;
      if (execErr) {
        return cb(execErr);
      }
      flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
        return match.substring(2);
      }).filter(function (name) {
        return exclusions.indexOf(name) === -1;
      });
      fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
        function (writeErr) {
          if (writeErr) {
            return cb(writeErr);
          }
          cb(null, flags);
        }
      );
    });
  }
};
<commit_msg>Fix: Ensure callback is always called async<commit_after>const os = require('os');
const fs = require('fs');
const path = require('path');
const execFile = require('child_process').execFile;

const tmpfile = path.join(os.tmpdir(), process.versions.v8+'.flags.json');
const exclusions = ['--help'];

module.exports = function (cb) {
  try {
    var flags = require(tmpfile);
    process.nextTick(function(){
      cb(null, flags);
    });
  } catch (e) {
    execFile(process.execPath, ['--v8-options'], function (execErr, result) {
      var flags;
      if (execErr) {
        return cb(execErr);
      }
      flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
        return match.substring(2);
      }).filter(function (name) {
        return exclusions.indexOf(name) === -1;
      });
      fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
        function (writeErr) {
          if (writeErr) {
            return cb(writeErr);
          }
          cb(null, flags);
        }
      );
    });
  }
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var merge = require('merge');
var mergeTrees = require('broccoli-merge-trees');
var flatiron = require('broccoli-flatiron');
var Funnel = require('broccoli-funnel');
var SVGOptmizer = require('./svg-optimizer');

module.exports = {
  name: require('./package').name,

  included: function (app) {
    if (app.app) {
      app = app.app;
    }
    this.app = app;
  },

  options: function () {
    return merge(
      true,
      {},
      {
        paths: ['public'],
        optimize: {
          /* svgo defaults */
        },
      },
      (this.app && this.app.options && this.app.options.svg) || {}
    );
  },

  svgPaths: function () {
    if (this.isDevelopingAddon()) {
      return ['tests/dummy/public'];
    }
    return this.options().paths;
  },

  optimizeSVGs: function (tree) {
    var config = this.options().optimize;
    if (!config) {
      return tree;
    }

    return new SVGOptmizer([tree], { svgoConfig: config });
  },

  treeForApp: function (tree) {
    var existingPaths = this.svgPaths().filter(function (path) {
      return fs.existsSync(path);
    });

    var svgTrees = existingPaths.map(function (path) {
      return new Funnel(path, {
        include: [new RegExp(/\.svg$/)],
      });
    });

    var svgs = mergeTrees(svgTrees, {
      overwrite: true,
    });

    var optimized = this.optimizeSVGs(svgs);

    var manifest = flatiron(optimized, {
      outputFile: 'svgs.js',
      trimExtensions: true,
    });

    return mergeTrees([tree, manifest]);
  },
};
<commit_msg>Use shorthand function definition in index.js<commit_after>'use strict';

var fs = require('fs');
var merge = require('merge');
var mergeTrees = require('broccoli-merge-trees');
var flatiron = require('broccoli-flatiron');
var Funnel = require('broccoli-funnel');
var SVGOptmizer = require('./svg-optimizer');

module.exports = {
  name: require('./package').name,

  included(app) {
    if (app.app) {
      app = app.app;
    }
    this.app = app;
  },

  options() {
    return merge(
      true,
      {},
      {
        paths: ['public'],
        optimize: {
          /* svgo defaults */
        },
      },
      (this.app && this.app.options && this.app.options.svg) || {}
    );
  },

  svgPaths() {
    if (this.isDevelopingAddon()) {
      return ['tests/dummy/public'];
    }
    return this.options().paths;
  },

  optimizeSVGs(tree) {
    var config = this.options().optimize;
    if (!config) {
      return tree;
    }

    return new SVGOptmizer([tree], { svgoConfig: config });
  },

  treeForApp(tree) {
    var existingPaths = this.svgPaths().filter(function (path) {
      return fs.existsSync(path);
    });

    var svgTrees = existingPaths.map(function (path) {
      return new Funnel(path, {
        include: [new RegExp(/\.svg$/)],
      });
    });

    var svgs = mergeTrees(svgTrees, {
      overwrite: true,
    });

    var optimized = this.optimizeSVGs(svgs);

    var manifest = flatiron(optimized, {
      outputFile: 'svgs.js',
      trimExtensions: true,
    });

    return mergeTrees([tree, manifest]);
  },
};
<|endoftext|>


<commit_before>/* @flow */

/* eslint
  no-underscore-dangle:
    ["error", { "allow": ["_onDidScan", "_onSettingsDidChange", "_activity"] }]
  no-console:
    0
*/

import React, { PropTypes } from 'react';
import {
  NativeModules,
  Platform,
  requireNativeComponent,
  UIManager,
  View,
  Event,
} from 'react-native';

import NativeComponent from './SGNativeComponent';

import type {
  ScanditPointType as PointType,
  ScanditSizeType as SizeType,
  ScanditRectType as RectType,
  ScanditScanAreaType as ScanAreaType,
  ScanditSymbologyType as SymbologyType,
  ScanditSettingsType as SettingsType,
} from './SGScanditTypes';

const { SGScandit, SGScanditPicker } = NativeModules;

const iOS = Platform.OS === 'ios';

const Commands = iOS
  ? SGScanditPicker
  : UIManager.SGScanditPicker.Commands;

type ScanditPickerPropsType = {

}

type ScanditPickerActivityType = 'active' | 'paused' | 'stopped';

export class ScanditPicker extends NativeComponent {
  _onDidScan: Function;
  _onSettingsDidChange: Function;
  _activity: ScanditPickerActivityType;

  constructor(props: ScanditPickerPropsType) {
    super(props);

    this._onDidScan = this._onDidScan.bind(this);
    this._onSettingsDidChange = this._onSettingsDidChange.bind(this);
    this._activity = 'stopped';
  }

  _onDidScan(event: Event) {
    if (this.props.onScan) {
      this.props.onScan(event.nativeEvent);
    }
  }

  _onSettingsDidChange(event: Event) {
    if (!this.props.onSettingsChange) {
      return;
    }
    console.log(JSON.stringify(event.nativeEvent, null, 2));
    this.props.onSettingsChange(event.nativeEvent);
  }

  componentDidMount() {
    this.startScanning();
  }

  getSettings(): Promise<*> {
    return this.dispatchCommand(Commands.getSettings);
  }

  setSettings(settings: SettingsType): Promise<*> {
    return this.dispatchCommand(Commands.setSettings, [settings]);
  }

  startScanning(): Promise<*> {
    return this.dispatchCommand(Commands.startScanning);
  }

  startScanningInPausedState() {
    this.dispatchCommand(Commands.startScanningInPausedState);
  }

  stopScanning() {
    this.dispatchCommand(Commands.stopScanning);
  }

  pauseScanning() {
    this.dispatchCommand(Commands.pauseScanning);
  }

  resumeScanning() {
    this.dispatchCommand(Commands.resumeScanning);
  }

  activity(): string {
    return this._activity;
  }

  render() {
    return (<SGScanditPickerComponent
      {...this.props}
      onDidScan={this._onDidScan}
      onSettingsDidChange={this._onSettingsDidChange}
    />);
  }
}

ScanditPicker.propTypes = {
  settings: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  onScan: PropTypes.func,
  onSettingsChange: PropTypes.func,
  ...View.propTypes,
};

const SGScanditPickerComponent = requireNativeComponent(
  'SGScanditPicker',
  ScanditPicker,
  {
    nativeOnly: {
      onDidScan: true,
      onSettingsDidChange: true,
    },
  },
);

export default SGScandit;

export type ScanditPointType = PointType;
export type ScanditSizeType = SizeType;
export type ScanditRectType = RectType;
export type ScanditScanAreaType = ScanAreaType;
export type ScanditSymbologyType = SymbologyType;
export type ScanditSettingsType = SettingsType;
export const ScanditSDKVersion = SGScandit.SDK_VERSION;
<commit_msg>Added onCodeScan prop<commit_after>/* @flow */

/* eslint
  no-underscore-dangle:
    ["error", { "allow": ["_onDidScan", "_onSettingsDidChange", "_activity"] }]
  no-console:
    0
*/

import React, { PropTypes } from 'react';
import {
  NativeModules,
  Platform,
  requireNativeComponent,
  UIManager,
  View,
  Event,
} from 'react-native';

import NativeComponent from './SGNativeComponent';

import type {
  ScanditPointType as PointType,
  ScanditSizeType as SizeType,
  ScanditRectType as RectType,
  ScanditScanAreaType as ScanAreaType,
  ScanditSymbologyType as SymbologyType,
  ScanditSettingsType as SettingsType,
} from './SGScanditTypes';

const { SGScandit, SGScanditPicker } = NativeModules;

const iOS = Platform.OS === 'ios';

const Commands = iOS
  ? SGScanditPicker
  : UIManager.SGScanditPicker.Commands;

type ScanditPickerPropsType = {

}

type ScanditPickerActivityType = 'active' | 'paused' | 'stopped';

export class ScanditPicker extends NativeComponent {
  _onDidScan: Function;
  _onSettingsDidChange: Function;
  _activity: ScanditPickerActivityType;

  constructor(props: ScanditPickerPropsType) {
    super(props);

    this._onDidScan = this._onDidScan.bind(this);
    this._onSettingsDidChange = this._onSettingsDidChange.bind(this);
    this._activity = 'stopped';
  }

  _onDidScan(event: Event) {
    if (this.props.onScan) {
      this.props.onScan(event.nativeEvent);
    }
    if (this.props.onCodeScan) {
      const codes = event.nativeEvent.newlyRecognizedCodes;
      if (codes && codes.length) {
        this.props.onCodeScan(codes[0]);
      }
    }
  }

  _onSettingsDidChange(event: Event) {
    if (!this.props.onSettingsChange) {
      return;
    }
    console.log(JSON.stringify(event.nativeEvent, null, 2));
    this.props.onSettingsChange(event.nativeEvent);
  }

  componentDidMount() {
    this.startScanning();
  }

  getSettings(): Promise<*> {
    return this.dispatchCommand(Commands.getSettings);
  }

  setSettings(settings: SettingsType): Promise<*> {
    return this.dispatchCommand(Commands.setSettings, [settings]);
  }

  startScanning(): Promise<*> {
    return this.dispatchCommand(Commands.startScanning);
  }

  startScanningInPausedState() {
    this.dispatchCommand(Commands.startScanningInPausedState);
  }

  stopScanning() {
    this.dispatchCommand(Commands.stopScanning);
  }

  pauseScanning() {
    this.dispatchCommand(Commands.pauseScanning);
  }

  resumeScanning() {
    this.dispatchCommand(Commands.resumeScanning);
  }

  activity(): string {
    return this._activity;
  }

  render() {
    return (<SGScanditPickerComponent
      {...this.props}
      onDidScan={this._onDidScan}
      onSettingsDidChange={this._onSettingsDidChange}
    />);
  }
}

ScanditPicker.propTypes = {
  settings: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  onScan: PropTypes.func,
  onCodeScan: PropTypes.func,
  onSettingsChange: PropTypes.func,
  ...View.propTypes,
};

const SGScanditPickerComponent = requireNativeComponent(
  'SGScanditPicker',
  ScanditPicker,
  {
    nativeOnly: {
      onDidScan: true,
      onSettingsDidChange: true,
    },
  },
);

export default SGScandit;

export type ScanditPointType = PointType;
export type ScanditSizeType = SizeType;
export type ScanditRectType = RectType;
export type ScanditScanAreaType = ScanAreaType;
export type ScanditSymbologyType = SymbologyType;
export type ScanditSettingsType = SettingsType;
export const ScanditSDKVersion = SGScandit.SDK_VERSION;
<|endoftext|>


<commit_before>var semver = require('semver');
var packageJson = require('../../package.json');

checkVersion = function(customExpectedVersion) {
  var version = process.version;
  var expectedVersion = version; // Default: always satisfied
  if (typeof customExpectedVersion !== "undefined" && customExpectedVersion !== null) {
    expectedVersion = customExpectedVersion;
  } else {
    var packageJson;
    try {
      packageJson = require('../../package.json');
    } catch (e) { return; }

    engines = packageJson.engines;
    if (typeof engines !== "undefined" && engines !== null) {
      expectedVersion = engines.node;
    }
  }

  if (!semver.satisfies(version, expectedVersion)){
    throw new Error('Node ' + expectedVersion + ' required.');
  }
};

module.exports = checkVersion
<commit_msg>remove duplicate require<commit_after>var semver = require('semver');

checkVersion = function(customExpectedVersion) {
  var version = process.version;
  var expectedVersion = version; // Default: always satisfied
  if (typeof customExpectedVersion !== "undefined" && customExpectedVersion !== null) {
    expectedVersion = customExpectedVersion;
  } else {
    var packageJson;
    try {
      packageJson = require('../../package.json');
    } catch (e) { return; }

    engines = packageJson.engines;
    if (typeof engines !== "undefined" && engines !== null) {
      expectedVersion = engines.node;
    }
  }

  if (!semver.satisfies(version, expectedVersion)){
    throw new Error('Node ' + expectedVersion + ' required.');
  }
};

module.exports = checkVersion
<|endoftext|>


<commit_before>'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var swfBuild = require('swf-build');
var path = require('path');
var fs = require('fs');
var isdir = require('isdir');

module.exports = function (output,params) {
	var done;
	function flashBuild(file, enc, callback) {
		if (file.isNull() || path.extname(file.path)!='.as') return callback(null, file);
		if (file.isStream()) return callback(new gutil.PluginError('gulp-flash', 'Streaming not supported'));

		var self = this;

		var args = [file.path]; // input

		if(typeof output==='string') { // if string are output path
			args.push((isdir(path.resolve(output)) ? path.resolve(output,path.basename(file.path,'.as')+'.swf') : path.resolve(output)));
		}

		if(typeof output==='object') { //params
			args.push(output);
		} else {
			if(params) args.push(params);
		}

		args.push(function(err, stdout, stderr){ // callback
			callback(err, file);
		});

		swfBuild.bind.apply(swfBuild, [null].concat(args))();
	}

	return through.obj(flashBuild)
};
<commit_msg>try travis<commit_after>'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var swfBuild = require('swf-build');
var path = require('path');
var fs = require('fs');
var isdir = require('isdir');

module.exports = function (output,params) {
	function flashBuild(file, enc, callback) {
		if (file.isNull() || path.extname(file.path)!='.as') return callback(null, file);
		if (file.isStream()) return callback(new gutil.PluginError('gulp-flash', 'Streaming not supported'));

		var self = this;

		var args = [file.path]; // input

		if(typeof output==='string') { // if string are output path
			if (!fs.existsSync(path.dirname(path.resolve(output)))) fs.mkdirSync(path.resolve(output));
			args.push((fs.lstatSync(path.resolve(output)).isDirectory() ? path.resolve(output,path.basename(file.path,'.as')+'.swf') : path.resolve(output)));
		}

		if(typeof output==='object') { //params
			args.push(output);
		} else {
			if(params) args.push(params);
		}

		args.push(function(err, stdout, stderr){ // callback
			callback(err, file);
		});

		swfBuild.bind.apply(swfBuild, [null].concat(args))();
	}

	return through.obj(flashBuild)
};
<|endoftext|>