<commit_before>/* eslint-disable no-useless-return */
'use strict'

const urlUtil = require('url')
const runHooks = require('fastseries')()
const jsonParser = require('body/json')
const validation = require('./validation')
const validateSchema = validation.validate

function bodyParsed (handle, params, req, res) {
  function parsed (err, body) {
    if (err) {
      res.statusCode = 422
      setImmediate(wrapResEnd, res)
      return
    }
    handler(handle, params, req, res, body, urlUtil.parse(req.url, true).query)
  }

  return parsed
}

function routerHandler (node) {
  return function _routeHanlder (params, req, res) {
    const handle = node[req.method]

    if (!handle) {
      res.statusCode = 404
      setImmediate(wrapResEnd, res)
      return
    }

    // Body not required
    if (req.method === 'GET' || req.method === 'DELETE' || req.method === 'HEAD') {
      return handler(handle, params, req, res, null, urlUtil.parse(req.url, true).query)
    }

    // Optional body
    if (req.method === 'OPTIONS') {
      if (req.headers['content-type']) {
        // application/json content type
        if (req.headers['content-type'].indexOf('application/json') > -1) {
          return jsonParser(req, bodyParsed(handle, params, req, res))
        // custom parser for a given content type
        } else if (handle.contentTypeParser.fastHasHeader(req.headers['content-type'])) {
          return handle.contentTypeParser.run(req.headers['content-type'], handler, handle, params, req, res, urlUtil.parse(req.url, true).query)
        }
        res.statusCode = 415
        setImmediate(wrapResEnd, res)
        return
      }
      return handler(handle, params, req, res, null, urlUtil.parse(req.url, true).query)
    }

    // Body required
    if (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') {
      // application/json content type
      if (req.headers['content-type'] && req.headers['content-type'].indexOf('application/json') > -1) {
        return jsonParser(req, bodyParsed(handle, params, req, res))
      // custom parser fir a given content type
      } else if (handle.contentTypeParser.fastHasHeader(req.headers['content-type'])) {
        return handle.contentTypeParser.run(req.headers['content-type'], handler, handle, params, req, res, urlUtil.parse(req.url, true).query)
      }

      res.statusCode = 415
      setImmediate(wrapResEnd, res)
      return
    }

    res.statusCode = 404
    setImmediate(wrapResEnd, res)
    return
  }
}

function build (url, router) {
  const node = {}
  router.on(url, routerHandler(node))

  return node
}

function handler (handle, params, req, res, body, query) {
  if (!handle) {
    res.statusCode = 404
    setImmediate(wrapResEnd, res)
    return
  }

  const valid = validateSchema(handle, params, body, query)
  if (valid !== true) {
    res.statusCode = 400
    setImmediate(wrapResEnd, res, valid)
    return
  }

  const request = new handle.Request(params, req, body, query, req.log)
  const reply = new handle.Reply(req, res, handle)

  // preHandler hook
  runHooks(
    new State(request, reply, handle),
    hookIterator,
    handle.hooks.preHandler,
    preHandlerCallback
  )
}

function State (request, reply, handle) {
  this.request = request
  this.reply = reply
  this.handle = handle
}

function hookIterator (fn, cb) {
  fn(this.request, this.reply, cb)
}

function preHandlerCallback (err) {
  if (err) {
    this.reply.send(err)
    return
  }
  const result = this.handle.handler(this.request, this.reply)
  if (result && typeof result.then === 'function') {
    this.reply.send(result)
  }
}

function wrapResEnd (res, payload) {
  res.end(payload)
  return
}

module.exports = build
module.exports[Symbol.for('internals')] = { bodyParsed, routerHandler, handler }
<commit_msg>Reordered functions, updated routeHandler params and hook execution<commit_after>/* eslint-disable no-useless-return */
'use strict'

const urlUtil = require('url')
const runHooks = require('fastseries')()
const jsonParser = require('body/json')
const validation = require('./validation')
const validateSchema = validation.validate

function build (url, router) {
  const node = {}
  router.on(url, routerHandler(node))

  return node
}

function routerHandler (node) {
  return function _routerHandler (params, req, res, method) {
    var handle = node[method]
    if (!handle) {
      res.statusCode = 404
      setImmediate(wrapResEnd, res)
      return
    }

    // Body not required
    if (method === 'GET' || method === 'DELETE' || method === 'HEAD') {
      return handler(handle, params, req, res, null, urlUtil.parse(req.url, true).query)
    }

    // Optional body
    if (method === 'OPTIONS') {
      if (req.headers['content-type']) {
        // application/json content type
        if (req.headers['content-type'].indexOf('application/json') > -1) {
          return jsonParser(req, bodyParsed(handle, params, req, res))
        // custom parser for a given content type
        } else if (handle.contentTypeParser.fastHasHeader(req.headers['content-type'])) {
          return handle.contentTypeParser.run(req.headers['content-type'], handler, handle, params, req, res, urlUtil.parse(req.url, true).query)
        }
        res.statusCode = 415
        setImmediate(wrapResEnd, res)
        return
      }
      return handler(handle, params, req, res, null, urlUtil.parse(req.url, true).query)
    }

    // Body required
    if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
      // application/json content type
      if (req.headers['content-type'] && req.headers['content-type'].indexOf('application/json') > -1) {
        return jsonParser(req, bodyParsed(handle, params, req, res))
      // custom parser fir a given content type
      } else if (handle.contentTypeParser.fastHasHeader(req.headers['content-type'])) {
        return handle.contentTypeParser.run(req.headers['content-type'], handler, handle, params, req, res, urlUtil.parse(req.url, true).query)
      }

      res.statusCode = 415
      setImmediate(wrapResEnd, res)
      return
    }

    res.statusCode = 404
    setImmediate(wrapResEnd, res)
    return
  }
}

function bodyParsed (handle, params, req, res) {
  function parsed (err, body) {
    if (err) {
      res.statusCode = 422
      setImmediate(wrapResEnd, res)
      return
    }
    handler(handle, params, req, res, body, urlUtil.parse(req.url, true).query)
  }

  return parsed
}

function handler (handle, params, req, res, body, query) {
  var valid = validateSchema(handle, params, body, query)
  if (valid !== true) {
    res.statusCode = 400
    setImmediate(wrapResEnd, res, valid)
    return
  }

  // preHandler hook
  setImmediate(
    runHooks,
    new State(new handle.Request(params, req, body, query, req.log), new handle.Reply(req, res, handle), handle),
    hookIterator,
    handle.hooks.preHandler,
    preHandlerCallback
  )
}

function State (request, reply, handle) {
  this.request = request
  this.reply = reply
  this.handle = handle
}

function hookIterator (fn, cb) {
  fn(this.request, this.reply, cb)
}

function preHandlerCallback (err) {
  if (err) {
    this.reply.send(err)
    return
  }
  var result = this.handle.handler(this.request, this.reply)
  if (result && typeof result.then === 'function') {
    this.reply.send(result)
  }
}

function wrapResEnd (res, payload) {
  res.end(payload)
  return
}

module.exports = build
module.exports[Symbol.for('internals')] = { bodyParsed, routerHandler, handler }
<|endoftext|>


<commit_before>var EventDate, dayNames, monthNames, pad;

pad = function(num, len) {
  var i, padding, _i, _ref;
  if (typeof num !== 'string') {
    num = '' + num;
  }
  if (!len) {
    len = 2;
  }
  if (num.length >= len) {
    return num;
  }
  padding = '';
  for (i = _i = 0, _ref = len - num.length; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
    padding += '0';
  }
  return padding + num;
};

EventDate = (function() {
  function EventDate() {
    this.date = new Date();
  }

  EventDate.prototype.toString = function() {
    var min;
    min = pad(this.minute, 2);
    return "" + this.dayName + " " + this.day + " " + this.monthName + " " + this.year + " @" + this.hour + ":" + this.minute;
  };

  return EventDate;

})();

Object.defineProperties(EventDate.prototype, {
  minute: {
    get: function() {
      return this.date.getMinutes();
    },
    set: function(val) {
      return this.date.setMinutes(val);
    }
  },
  hour: {
    get: function() {
      return this.date.getHours();
    },
    set: function(val) {
      return this.date.setHours(val);
    }
  },
  day: {
    get: function() {
      return this.date.getDate();
    },
    set: function(val) {
      return this.date.setDate(val);
    }
  },
  dayOfWeek: {
    get: function() {
      return this.date.getDay();
    },
    set: function(val) {
      return this.date.setDay(val);
    }
  },
  dayName: {
    get: function() {
      return dayNames[this.dayOfWeek];
    }
  },
  month: {
    get: function() {
      return this.date.getMonth();
    },
    set: function(val) {
      return this.date.setMonth(val);
    }
  },
  monthName: {
    get: function() {
      return monthNames[this.month];
    }
  },
  year: {
    get: function() {
      return this.date.getFullYear();
    },
    set: function(val) {
      return this.date.setFullYear(val);
    }
  }
});

monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

dayNames = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun'];

(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(function() {
      factory();
    });
  } else if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = factory();
  }
})(function() {
  var Timeously, fn, _INTERVAL_TYPE;
  _INTERVAL_TYPE = {
    MINUTELY: 'minute',
    HOURLY: 'hour',
    DAILY: 'day',
    WEEKLY: 'dayOfWeek',
    MONTHLY: 'month'
  };
  Timeously = (function() {
    function Timeously(options, callback) {
      this.callback = callback;
      this.name = options.name ? ' ' + options.name : '';
      this.interval = options.interval || 1;
      this.intervalType = options.type || _INTERVAL_TYPE.MINUTELY;
      this.modulus = options.start;
      this.timerID = null;
      this.initID = null;
      this.start();
    }

    Timeously.prototype.start = function() {
      var callback, eta, init;
      eta = 60 - new Date().getSeconds();
      callback = (function(_this) {
        return function() {
          var now;
          now = new EventDate();
          if (_this.nextEvent[_this.intervalType] === now[_this.intervalType]) {
            _this.callback();
            return _this.readyNextEvent();
          }
        };
      })(this);
      init = (function(_this) {
        return function() {
          _this.timerID = setInterval(callback, 60000);
          _this.readyNextEvent();
          console.log("Timeously firing " + _this.title + _this.name + " from " + (_this.nextEvent.toString()));
          return callback();
        };
      })(this);
      this.initID = setTimeout(init, eta * 1000);
      return console.log("Timeously starting " + this.title + this.name + " in T - " + eta + "sec and counting");
    };

    Timeously.prototype.stop = function() {
      if (this.initID !== null) {
        clearTimeout(this.initID);
        this.initID = null;
      }
      if (this.timerID !== null) {
        clearTimeout(this.timerID);
        return this.timerID = null;
      }
    };

    Timeously.prototype.readyNextEvent = function() {
      var delta, i, lastPeriod, testPeriod, _i, _ref, _results;
      this.lastEvent = new EventDate();
      this.nextEvent = new EventDate();
      lastPeriod = this.lastEvent[this.intervalType];
      if (this.modulus) {
        _results = [];
        for (i = _i = 0, _ref = this.interval; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
          delta = i + 1;
          testPeriod = lastPeriod + delta;
          if (testPeriod % this.modulus === 0) {
            this.nextEvent[this.intervalType] = lastPeriod + delta;
            break;
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      } else {
        return this.nextEvent[this.intervalType] = lastPeriod + this.interval;
      }
    };

    return Timeously;

  })();
  Object.defineProperty(Timeously.prototype, 'title', {
    get: function() {
      var key, val;
      for (key in _INTERVAL_TYPE) {
        val = _INTERVAL_TYPE[key];
        if (val === this.intervalType) {
          return "" + this.interval + " " + (key.toLowerCase());
        }
      }
    }
  });
  fn = function(options, callback) {
    return new Timeously(options, callback);
  };
  fn.IntervalTypes = _INTERVAL_TYPE;
  return fn;
});
<commit_msg>fixed dayNames / monthNames bug<commit_after>var EventDate, dayNames, monthNames, pad;

pad = function(num, len) {
  var i, padding, _i, _ref;
  if (typeof num !== 'string') {
    num = '' + num;
  }
  if (!len) {
    len = 2;
  }
  if (num.length >= len) {
    return num;
  }
  padding = '';
  for (i = _i = 0, _ref = len - num.length; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
    padding += '0';
  }
  return padding + num;
};

EventDate = (function() {
  function EventDate() {
    this.date = new Date();
  }

  EventDate.prototype.toString = function() {
    var min;
    min = pad(this.minute, 2);
    return "" + this.dayName + " " + this.day + " " + this.monthName + " " + this.year + " @" + this.hour + ":" + this.minute;
  };

  return EventDate;

})();

Object.defineProperties(EventDate.prototype, {
  minute: {
    get: function() {
      return this.date.getMinutes();
    },
    set: function(val) {
      return this.date.setMinutes(val);
    }
  },
  hour: {
    get: function() {
      return this.date.getHours();
    },
    set: function(val) {
      return this.date.setHours(val);
    }
  },
  day: {
    get: function() {
      return this.date.getDate();
    },
    set: function(val) {
      return this.date.setDate(val);
    }
  },
  dayOfWeek: {
    get: function() {
      return this.date.getDay();
    },
    set: function(val) {
      return this.date.setDay(val);
    }
  },
  dayName: {
    get: function() {
      return dayNames[this.dayOfWeek];
    }
  },
  month: {
    get: function() {
      return this.date.getMonth();
    },
    set: function(val) {
      return this.date.setMonth(val);
    }
  },
  monthName: {
    get: function() {
      return monthNames[this.month];
    }
  },
  year: {
    get: function() {
      return this.date.getFullYear();
    },
    set: function(val) {
      return this.date.setFullYear(val);
    }
  }
});

monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

dayNames = ['sun', 'mon', 'tues', 'wed', 'thurs', 'fri', 'sat'];

(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(function() {
      factory();
    });
  } else if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = factory();
  }
})(function() {
  var Timeously, fn, _INTERVAL_TYPE;
  _INTERVAL_TYPE = {
    MINUTELY: 'minute',
    HOURLY: 'hour',
    DAILY: 'day',
    WEEKLY: 'dayOfWeek',
    MONTHLY: 'month'
  };
  Timeously = (function() {
    function Timeously(options, callback) {
      this.callback = callback;
      this.name = options.name ? ' ' + options.name : '';
      this.interval = options.interval || 1;
      this.intervalType = options.type || _INTERVAL_TYPE.MINUTELY;
      this.modulus = options.start;
      this.timerID = null;
      this.initID = null;
      this.start();
    }

    Timeously.prototype.start = function() {
      var callback, eta, init;
      eta = 60 - new Date().getSeconds();
      callback = (function(_this) {
        return function() {
          var now;
          now = new EventDate();
          if (_this.nextEvent[_this.intervalType] === now[_this.intervalType]) {
            _this.callback();
            return _this.readyNextEvent();
          }
        };
      })(this);
      init = (function(_this) {
        return function() {
          _this.timerID = setInterval(callback, 60000);
          _this.readyNextEvent();
          console.log("Timeously firing " + _this.title + _this.name + " from " + (_this.nextEvent.toString()));
          return callback();
        };
      })(this);
      this.initID = setTimeout(init, eta * 1000);
      return console.log("Timeously starting " + this.title + this.name + " in T - " + eta + "sec and counting");
    };

    Timeously.prototype.stop = function() {
      if (this.initID !== null) {
        clearTimeout(this.initID);
        this.initID = null;
      }
      if (this.timerID !== null) {
        clearTimeout(this.timerID);
        return this.timerID = null;
      }
    };

    Timeously.prototype.readyNextEvent = function() {
      var delta, i, lastPeriod, testPeriod, _i, _ref, _results;
      this.lastEvent = new EventDate();
      this.nextEvent = new EventDate();
      lastPeriod = this.lastEvent[this.intervalType];
      if (this.modulus) {
        _results = [];
        for (i = _i = 0, _ref = this.interval; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
          delta = i + 1;
          testPeriod = lastPeriod + delta;
          if (testPeriod % this.modulus === 0) {
            this.nextEvent[this.intervalType] = lastPeriod + delta;
            break;
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      } else {
        return this.nextEvent[this.intervalType] = lastPeriod + this.interval;
      }
    };

    return Timeously;

  })();
  Object.defineProperty(Timeously.prototype, 'title', {
    get: function() {
      var key, val;
      for (key in _INTERVAL_TYPE) {
        val = _INTERVAL_TYPE[key];
        if (val === this.intervalType) {
          return "" + this.interval + " " + (key.toLowerCase());
        }
      }
    }
  });
  fn = function(options, callback) {
    return new Timeously(options, callback);
  };
  fn.IntervalTypes = _INTERVAL_TYPE;
  return fn;
});
<|endoftext|>


<commit_before>var Buffer = require('safe-buffer').Buffer

module.exports = function(thing, encoding, name) {
  if (Buffer.isBuffer(thing)) {
    return thing
  } else if (typeof thing === 'string') {
    return Buffer.from(thing, encoding)
  } else if (ArrayBuffer.isView(thing)) {
    return Buffer.from(thing.buffer)
  } else {
    throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
  }
}
<commit_msg>style nit<commit_after>var Buffer = require('safe-buffer').Buffer

module.exports = function (thing, encoding, name) {
  if (Buffer.isBuffer(thing)) {
    return thing
  } else if (typeof thing === 'string') {
    return Buffer.from(thing, encoding)
  } else if (ArrayBuffer.isView(thing)) {
    return Buffer.from(thing.buffer)
  } else {
    throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
  }
}
<|endoftext|>


<commit_before>'use strict'

const Promise = require('bluebird')
const request = require('request')

const log = require('./log')

/**
 * Parse response headers and return the token.
 *
 * @param {object} response
 * @return {string}
 */
const extractPaywallToken = (response) => {
  let token = response.headers['paywall-token']
  if (token) {
    log.verbose('Got token from the server')
    return token
  } else {
    throw new Error('Can not find a token in the response')
  }
}

class Transport {

  /**
   * @param {function|null} _request
   */
  constructor (_request) {
    this.request = _request
  }

  /**
   * Request URI sending a paywall token.
   * @param {string} uri
   * @param {string} token
   * @return {Promise<object>}
   */
  getWithToken (uri, token) {
    let headers = {
      'authorization': 'Paywall ' + token
    }
    log.verbose(`Getting ${uri} using access token ${token}`)
    return this.get(uri, headers)
  }

  /**
   * @param {string} uri
   * @param {object|null} headers
   * @return {Promise<object>}
   */
  get (uri, headers = null) {
    let options = {
      method: 'GET',
      uri: uri,
      headers: headers
    }
    log.verbose(`Getting ${uri} using headers:`, JSON.stringify(headers))
    log.debug(options)
    return this.request(options)
  }

  /**
   * Request token from the server's gateway
   * @param {string} uri - Full url to the gateway.
   * @param {Payment} payment
   * @return {Promise<string>}
   */
  requestToken (uri, payment) {
    let options = {
      method: 'POST',
      uri: uri,
      json: true,
      body: payment
    }
    log.verbose('Getting request token in exchange for payment')
    log.debug(payment)
    return this.request(options).then(extractPaywallToken)
  }
}

class PaymentRequired {
  constructor (headers) {
    this.receiver = headers['paywall-address']
    this.price = Number(headers['paywall-price'])
    this.gateway = headers['paywall-gateway']
  }
}

/**
 * @param {Object} headers
 * @returns {PaymentRequired}
 */
PaymentRequired.parse = function (headers) {
  return new PaymentRequired(headers)
}

/**
 * Build Transport instance.
 *
 * @param {function} _request
 * @return {Transport}
 */
const build = (_request = null) => {
  return new Transport(_request || Promise.promisify(require('request')))
}

module.exports = {
  Transport: Transport,
  PaymentRequired: PaymentRequired,
  build: build
}
<commit_msg>Transport#requestToken beautification<commit_after>'use strict'

const Promise = require('bluebird')
const request = Promise.promisify(require('request'))

const log = require('./log')

/**
 * Parse response headers and return the token.
 *
 * @param {object} response
 * @return {string}
 */
const extractPaywallToken = (response) => {
  let token = response.headers['paywall-token']
  if (token) {
    log.verbose('Got token from the server')
    return token
  } else {
    throw new Error('Can not find a token in the response')
  }
}

class Transport {

  /**
   * @param {function|null} _request
   */
  constructor (_request) {
    this.request = _request
  }

  /**
   * Request URI sending a paywall token.
   * @param {string} uri
   * @param {string} token
   * @return {Promise<object>}
   */
  getWithToken (uri, token) {
    let headers = {
      'authorization': 'Paywall ' + token
    }
    log.verbose(`Getting ${uri} using access token ${token}`)
    return this.get(uri, headers)
  }

  /**
   * @param {string} uri
   * @param {object|null} headers
   * @return {Promise<object>}
   */
  get (uri, headers = null) {
    let options = {
      method: 'GET',
      uri: uri,
      headers: headers
    }
    log.verbose(`Getting ${uri} using headers:`, JSON.stringify(headers))
    log.debug(options)
    return this.request(options)
  }

  /**
   * Request token from the server's gateway
   * @param {string} uri - Full url to the gateway.
   * @param {Payment} payment
   * @return {Promise<string>}
   */
  requestToken (uri, payment) {
    let options = {
      method: 'POST',
      uri: uri,
      json: true,
      body: payment
    }
    log.verbose('Getting request token in exchange for payment')
    log.debug(payment)
    return this.request(options).then(extractPaywallToken)
  }
}

class PaymentRequired {
  constructor (headers) {
    this.receiver = headers['paywall-address']
    this.price = Number(headers['paywall-price'])
    this.gateway = headers['paywall-gateway']
  }
}

/**
 * @param {Object} headers
 * @returns {PaymentRequired}
 */
PaymentRequired.parse = function (headers) {
  return new PaymentRequired(headers)
}

/**
 * Build Transport instance.
 *
 * @param {function} _request
 * @return {Transport}
 */
const build = (_request = null) => {
  return new Transport(_request || request)
}

module.exports = {
  Transport: Transport,
  PaymentRequired: PaymentRequired,
  build: build
}
<|endoftext|>


<commit_before>
var bitcoin = require('bitcoinjs-lib')
var map = require('map-stream')
var debug = require('debug')('unchainer')
var extend = require('xtend/mutable')
var combine = require('stream-combiner2')
var typeforce = require('typeforce')
var Parser = require('chained-obj').Parser
var Identity = require('midentity').Identity
var Verifier = require('tradle-verifier')
var CONSTANTS = require('tradle-constants')
var currentTime = require('./now')
var errors = require('./errors')
var TYPE = CONSTANTS.TYPE
var ROOT_HASH = CONSTANTS.ROOT_HASH
var plugins = Verifier.plugins
var DEFAULT_PLUGINS = [
  plugins.sigcheck,
  plugins.prev,
  plugins.identity
]

var errToJSON = require('./errToJSON')

/**
 * transactions go in, verified on-chain objects come out (or die inside)
 * @param  {[type]} options [description]
 * @return {[type]}         [description]
 */
module.exports = function chainstream (options) {
  typeforce({
    lookup: 'Function',
    chainloader: 'Object'
  }, options)

  var chainloader = options.chainloader
  var verifier = new Verifier({
    lookup: options.lookup
  })

  var plugins = DEFAULT_PLUGINS.slice()
  if (options.plugins) {
    options.plugins.forEach(function (p) {
      if (plugins.indexOf(p) === -1) {
        plugins.push(p)
      }
    })
  }

  verifier.use(plugins)

  return combine.obj(
    map(function (txEntry, done) {
      var processed = extend({}, txEntry)
      processed.errors = []
      var tx = bitcoin.Transaction.fromBuffer(txEntry.tx)
      chainloader.load(tx)
        .then(function (obj) {
          extend(processed, obj)
        })
        .catch(function (err) {
          debug('unchain failed', err.message, txEntry.txId)
          var typedErr = errors.ChainReadError(err, {
            timestamp: currentTime()
          })

          processed.errors.push(errToJSON(typedErr))
        })
        .done(function () {
          done(null, processed)
        })
    }),
    mkParser(),
    basicIdCheck(),
    verify(verifier)
  )

  // var full = txProcessor
  //   .pipe(map(function (chainedObj, cb) {
  //     if (chainedObj.data) cb(null, chainedObj)
  //     else cb()
  //   }))
  //   .pipe(mkParser())
  //   .pipe(basicIdCheck())
  //   .pipe(verifier)

  // var empty = txProcessor
  //   .pipe(map(function (chainedObj, cb) {
  //     if (chainedObj.data) cb()
  //     else cb(null, chainedObj)
  //   }))

  // var passThrough = new PassThrough({ objectMode: true })
  // full.pipe(passThrough)
  // empty.pipe(passThrough)
  // return combine(
  //   txProcessor,
  //   passThrough
  // )
}

function mkParser () {
  return map(function (chainedObj, done) {
    if (!chainedObj.data) return done(null, chainedObj)

    Parser.parse(chainedObj.data, function (err, parsed) {
      if (err) {
        debug('invalid chained-obj', chainedObj.key)
        chainedObj.errors.push(err)
      } else {
        chainedObj.parsed = parsed
      }

      done(null, chainedObj)
    })

  })
}

function basicIdCheck () {
  return map(function (chainedObj, done) {
    if (!chainedObj.parsed) return done(null, chainedObj)

    var parsed = chainedObj.parsed
    var json = parsed.data
    var isIdentity = json[TYPE] === Identity.TYPE
    var from = chainedObj.from
    // only identities are allowed to be created without an identity
    if (from || isIdentity) {
      if (!from) {
        chainedObj.from = {
          identity: Identity.fromJSON(json)
        }

        chainedObj.from[ROOT_HASH] = chainedObj[ROOT_HASH] || chainedObj.key
      }
    }

    done(null, chainedObj)
  })
}

function verify (verifier) {
  return map(function (chainedObj, cb) {
    if (!chainedObj.parsed) return cb(null, chainedObj)

    verifier.verify(chainedObj, function (err) {
      if (err) {
      debugger
        chainedObj.errors.push(err)
        debug('failed to verify', chainedObj.key, err)
      }

      cb(null, chainedObj)
    })
  })
}
<commit_msg>small code simplification<commit_after>
var bitcoin = require('bitcoinjs-lib')
var map = require('map-stream')
var debug = require('debug')('unchainer')
var extend = require('xtend/mutable')
var combine = require('stream-combiner2')
var typeforce = require('typeforce')
var Parser = require('chained-obj').Parser
var Identity = require('midentity').Identity
var Verifier = require('tradle-verifier')
var CONSTANTS = require('tradle-constants')
var currentTime = require('./now')
var errors = require('./errors')
var TYPE = CONSTANTS.TYPE
var ROOT_HASH = CONSTANTS.ROOT_HASH
var plugins = Verifier.plugins
var DEFAULT_PLUGINS = [
  plugins.sigcheck,
  plugins.prev,
  plugins.identity
]

var errToJSON = require('./errToJSON')

/**
 * transactions go in, verified on-chain objects come out (or die inside)
 * @param  {[type]} options [description]
 * @return {[type]}         [description]
 */
module.exports = function chainstream (options) {
  typeforce({
    lookup: 'Function',
    chainloader: 'Object'
  }, options)

  var chainloader = options.chainloader
  var verifier = new Verifier({
    lookup: options.lookup
  })

  var plugins = DEFAULT_PLUGINS.slice()
  if (options.plugins) {
    options.plugins.forEach(function (p) {
      if (plugins.indexOf(p) === -1) {
        plugins.push(p)
      }
    })
  }

  verifier.use(plugins)

  return combine.obj(
    map(function (txEntry, done) {
      var processed = extend({}, txEntry)
      processed.errors = []
      var tx = bitcoin.Transaction.fromBuffer(txEntry.tx)
      chainloader.load(tx)
        .then(function (obj) {
          extend(processed, obj)
        })
        .catch(function (err) {
          debug('unchain failed', err.message, txEntry.txId)
          var typedErr = errors.ChainReadError(err, {
            timestamp: currentTime()
          })

          processed.errors.push(errToJSON(typedErr))
        })
        .done(function () {
          done(null, processed)
        })
    }),
    mkParser(),
    basicIdCheck(),
    verify(verifier)
  )

  // var full = txProcessor
  //   .pipe(map(function (chainedObj, cb) {
  //     if (chainedObj.data) cb(null, chainedObj)
  //     else cb()
  //   }))
  //   .pipe(mkParser())
  //   .pipe(basicIdCheck())
  //   .pipe(verifier)

  // var empty = txProcessor
  //   .pipe(map(function (chainedObj, cb) {
  //     if (chainedObj.data) cb()
  //     else cb(null, chainedObj)
  //   }))

  // var passThrough = new PassThrough({ objectMode: true })
  // full.pipe(passThrough)
  // empty.pipe(passThrough)
  // return combine(
  //   txProcessor,
  //   passThrough
  // )
}

function mkParser () {
  return map(function (chainedObj, done) {
    if (!chainedObj.data) return done(null, chainedObj)

    Parser.parse(chainedObj.data, function (err, parsed) {
      if (err) {
        debug('invalid chained-obj', chainedObj.key)
        chainedObj.errors.push(err)
      } else {
        chainedObj.parsed = parsed
      }

      done(null, chainedObj)
    })

  })
}

function basicIdCheck () {
  return map(function (chainedObj, done) {
    if (!chainedObj.parsed) return done(null, chainedObj)

    var parsed = chainedObj.parsed
    var json = parsed.data
    var isIdentity = json[TYPE] === Identity.TYPE
    var from = chainedObj.from
    // only identities are allowed to be created without an identity
    if (!from && isIdentity) {
      chainedObj.from = {
        identity: Identity.fromJSON(json)
      }

      chainedObj.from[ROOT_HASH] = chainedObj[ROOT_HASH] || chainedObj.key
    }

    done(null, chainedObj)
  })
}

function verify (verifier) {
  return map(function (chainedObj, cb) {
    if (!chainedObj.parsed) return cb(null, chainedObj)

    verifier.verify(chainedObj, function (err) {
      if (err) {
        chainedObj.errors.push(err)
        debug('failed to verify', chainedObj.key, err)
      }

      cb(null, chainedObj)
    })
  })
}
<|endoftext|>


<commit_before>/*
 *  Copyright 2011 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var sprintf = require('./sprintf');
var log = require('logmagic').local('deploy.helpers.misc');
var spawn = require('child_process').spawn;

/**
 * Get unix timestamp.
 * @param {?Date} date Date object.
 * @return {Number} unix timestamp.
 */
exports.getUnixTimestamp = function getUnixTimestamp(date) {
  date = date || new Date();
  date = date.getTime();
  return Math.round(date / 1000);
};

/** Spawn a subprocess and issue the callback.
 * @param {Array} cmd Command and Arguments.
 * @param {Options} spawnOpts Options object passed to the spawn command.
 * @param {Function} callback Completion callback(err, stdout, stderr).
 */
exports.spawn = function(cmd, spawnOpts, callback) {
  var args,
      diff,
      proc,
      resultString = '',
      errString = '',
      cmdStr,
      stdoutClosed = false,
      stderrClosed = false,
      exitCode,
      timeout = 60 * 1000,
      timedOut = false;

  // Copy command so we don't override the parent
  cmd = cmd.slice();
  args = cmd.splice(1);

  cmdStr = sprintf('%s %s', cmd[0], args.join(' '));
  log.info('Executing Command', {'cmd': cmdStr});

  proc = spawn(cmd[0], args, spawnOpts);
  proc.stdout.on('data', function(data) {
    resultString += data;
  });
  proc.stderr.on('data', function(data) {
    errString += data;
  });

  function closingEvent() {
    var err;

    if (stdoutClosed && stderrClosed && typeof exitCode !== 'undefined') {
      log.info('Command finished', {'cmd': cmdStr, 'code': exitCode, 'stdout': resultString, 'stderr': errString});
    } else if (timedOut) {
      log.info('Command failed %s due to timeout', cmdStr);
      if (!err) {
        err = new Error(sprintf('Failed command %s: Timedout', cmdStr));
      }
    } else {
      log.info('Command failed', {'cmd': cmdStr, 'code': exitCode || null, 'stdout': resultString || null, 'stderr': errString || null});
    }

    if (typeof exitCode !== 'undefined') {
      if (exitCode) {
        err = new Error(sprintf('Failed command %s:\nstderr:\n%s\nstdout:\n%s', cmdStr, errString, resultString));
      }
    }

    callback(err, resultString, errString);
  }
  setTimeout(function() {
    timedOut = true;
    closingEvent();
  }, timeout);
  proc.stdout.on('close', function() {
    stdoutClosed = true;
    closingEvent();
  });
  proc.stderr.on('close', function() {
    stderrClosed = true;
    closingEvent();
  });
  proc.on('exit', function(code) {
    exitCode = code;
    closingEvent();
  });
};

/**
 * Execute a command using a task's baton and args to log and honor dryrun.
 * @param {Object} baton A task's baton with a logger.
 * @param {Object} args A task's args which may contain 'dryrun'.
 * @param {Array} cmd The command and its arguments.
 * @param {Object} options An options object to pass to spawn.
 * @param {Function} callback A callback fired with (err, stdout, stderr).
 */
exports.taskSpawn = function(baton, args, cmd, options, callback) {
  var cmdStr = cmd.join(' '),
      start = Date.now();

  if (args.dryrun) {
    baton.log.infof('dry run, skipping command: ${cmd}', {
      cmd: cmdStr
    });
    callback();
    return;
  }

  baton.log.infof('executing command: ${cmd}', {
    cmd: cmdStr
  });

  exports.spawn(cmd, options, function(err, stdout, stderr) {
    var took = (Date.now() - start) / 1000;

    if (err) {
      baton.log.errorf('error executing command: ${cmd}', {
        cmd: cmdStr,
        err: err,
        stdout: stdout,
        stderr: stderr,
        took: took
      });
    } else {
      baton.log.infof('command successful: ${cmd}', {
        cmd: cmdStr,
        stdout: stdout,
        stderr: stderr,
        took: took
      });
    }
    callback(err, stdout, stderr);
  });
};

exports.randstr = function(len) {
  var chars, r, x;

  chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  r = [];

  for (x = 0; x < len; x++) {
    r.push(chars[exports.getRandomInt(0, chars.length - 1)]);
  }

  return r.join('');
};

exports.getRandomInt = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

exports.merge = function(a, b) {
  var c = {}, attrname;

  for (attrname in a) {
    if (a.hasOwnProperty(attrname)) {
      c[attrname] = a[attrname];
    }
  }
  for (attrname in b) {
    if (b.hasOwnProperty(attrname)) {
      c[attrname] = b[attrname];
    }
  }
  return c;
};

exports.copyEnv = function() {
  var env = {}, key;

  for (key in process.env) {
    env[key] = process.env[key];
  }

  return env;
};
<commit_msg>fix conditional in closingEvent<commit_after>/*
 *  Copyright 2011 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var sprintf = require('./sprintf');
var log = require('logmagic').local('deploy.helpers.misc');
var spawn = require('child_process').spawn;

/**
 * Get unix timestamp.
 * @param {?Date} date Date object.
 * @return {Number} unix timestamp.
 */
exports.getUnixTimestamp = function getUnixTimestamp(date) {
  date = date || new Date();
  date = date.getTime();
  return Math.round(date / 1000);
};

/** Spawn a subprocess and issue the callback.
 * @param {Array} cmd Command and Arguments.
 * @param {Options} spawnOpts Options object passed to the spawn command.
 * @param {Function} callback Completion callback(err, stdout, stderr).
 */
exports.spawn = function(cmd, spawnOpts, callback) {
  var args,
      diff,
      proc,
      resultString = '',
      errString = '',
      cmdStr,
      stdoutClosed = false,
      stderrClosed = false,
      exitCode,
      timeout = 60 * 1000,
      timedOut = false;

  // Copy command so we don't override the parent
  cmd = cmd.slice();
  args = cmd.splice(1);

  cmdStr = sprintf('%s %s', cmd[0], args.join(' '));
  log.info('Executing Command', {'cmd': cmdStr});

  proc = spawn(cmd[0], args, spawnOpts);
  proc.stdout.on('data', function(data) {
    resultString += data;
  });
  proc.stderr.on('data', function(data) {
    errString += data;
  });

  function closingEvent() {
    var err;

    if ((stdoutClosed && stderrClosed && typeof exitCode !== 'undefined') || timedOut) {
      log.info('Command failed', {
        'cmd': cmdStr,
        'code': exitCode || null,
        'stdout': resultString || null,
        'stderr': errString || null,
        'timedOut': timedOut
      });

      if (exitCode) {
        err = new Error(sprintf('Failed command %s:\nstderr:\n%s\nstdout:\n%s', cmdStr, errString, resultString));
      } else if (timedOut) {
        err = new Error(sprintf('Failed command %s: Timedout', cmdStr));
      }
    }

    callback(err, resultString, errString);
  }

  setTimeout(function() {
    timedOut = true;
    closingEvent();
  }, timeout);
  proc.stdout.on('close', function() {
    stdoutClosed = true;
    closingEvent();
  });
  proc.stderr.on('close', function() {
    stderrClosed = true;
    closingEvent();
  });
  proc.on('exit', function(code) {
    exitCode = code;
    closingEvent();
  });
};

/**
 * Execute a command using a task's baton and args to log and honor dryrun.
 * @param {Object} baton A task's baton with a logger.
 * @param {Object} args A task's args which may contain 'dryrun'.
 * @param {Array} cmd The command and its arguments.
 * @param {Object} options An options object to pass to spawn.
 * @param {Function} callback A callback fired with (err, stdout, stderr).
 */
exports.taskSpawn = function(baton, args, cmd, options, callback) {
  var cmdStr = cmd.join(' '),
      start = Date.now();

  if (args.dryrun) {
    baton.log.infof('dry run, skipping command: ${cmd}', {
      cmd: cmdStr
    });
    callback();
    return;
  }

  baton.log.infof('executing command: ${cmd}', {
    cmd: cmdStr
  });

  exports.spawn(cmd, options, function(err, stdout, stderr) {
    var took = (Date.now() - start) / 1000;

    if (err) {
      baton.log.errorf('error executing command: ${cmd}', {
        cmd: cmdStr,
        err: err,
        stdout: stdout,
        stderr: stderr,
        took: took
      });
    } else {
      baton.log.infof('command successful: ${cmd}', {
        cmd: cmdStr,
        stdout: stdout,
        stderr: stderr,
        took: took
      });
    }
    callback(err, stdout, stderr);
  });
};

exports.randstr = function(len) {
  var chars, r, x;

  chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  r = [];

  for (x = 0; x < len; x++) {
    r.push(chars[exports.getRandomInt(0, chars.length - 1)]);
  }

  return r.join('');
};

exports.getRandomInt = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

exports.merge = function(a, b) {
  var c = {}, attrname;

  for (attrname in a) {
    if (a.hasOwnProperty(attrname)) {
      c[attrname] = a[attrname];
    }
  }
  for (attrname in b) {
    if (b.hasOwnProperty(attrname)) {
      c[attrname] = b[attrname];
    }
  }
  return c;
};

exports.copyEnv = function() {
  var env = {}, key;

  for (key in process.env) {
    env[key] = process.env[key];
  }

  return env;
};
<|endoftext|>


<commit_before>/*
 * Iris
 * (c) 2016+ Buenos Aires City Government
 * License: https://opensource.org/licenses/MIT
 *
 */

'use strict';

const fs = require('graceful-fs');
const path = require('path');
const ora = require('ora');
const changeCase = require('change-case');
const npm = require('npm-programmatic');
const utils = require('./utils');

const consoleLog = utils.log;
const irisfile = 'const iris = require(\'iris\');\n';

const checkFile = (fileName) => {
    try {
        return fs.statSync(path.join(process.cwd(), fileName)).isFile();
    } catch (error) {
        if (error.code !== 'ENOENT') throw error;

        return false;
    }
};

const createFile = (fileName, content) => {
    try {
        fs.writeFileSync(path.join(process.cwd(), fileName), content);
    } catch (error) {
        return false;
    }

    return true;
};

const checkFolder = (folder) => {
    try {
        return fs.statSync(path.join(process.cwd(), folder)).isDirectory();
    } catch (error) {
        if (error.code !== 'ENOENT') throw error;

        return false;
    }
};

const createFolder = (folder) => {
    try {
        fs.mkdirSync(path.join(process.cwd(), folder));
    } catch (error) {
        return false;
    }

    return true;
};

const newFolder = (folder, spinner) => {
    if (checkFolder(folder)) {
        spinner.fail();
        consoleLog.error('Directory \'' + folder + '\' already exists');

        process.exit(1);
    }

    if (!createFolder(folder)) {
        spinner.fail();
        consoleLog.error('Could not create directory \'' + folder + '\'');

        process.exit(1);
    }
};

const newFile = (fileName, content, spinner) => {
    if (!createFile(fileName, content)) {
        spinner.fail();
        consoleLog.error('Could not create ' + fileName);

        process.exit(1);
    }
};

const cli = {
    status: () => {

    },
    init: () => {
        var spinner;

        spinner = ora('Checking package.json');
        spinner.start();

        if (checkFile('package.json')) {
            spinner.succeed();
        } else {
            spinner.fail();
            consoleLog.error('package.json not found');
            consoleLog.error('You need to run this command inside a npm module folder');

            process.exit(1);
        }

        spinner = ora('Creating Irisfile');
        spinner.start();

        if (checkFile('irisfile.js')) {
            spinner.fail();
            consoleLog.error('Irisfile already exists');

            process.exit(1);
        }

        newFile('irisfile.js', JSON.stringify(irisfile), spinner);
        spinner.succeed();
        spinner = ora('Running \'npm install gcba-iris/iris --save\'');
        spinner.start();

        npm.install(['gcba-iris/iris'], {
                cwd: process.cwd(),
                save: true
            })
            .then(() => {
                spinner.succeed();
                consoleLog.info('Done!');

                process.exit(0);
            })
            .catch((error) => {
                spinner.fail();
                consoleLog.error('Unable to do \'npm install gcba-iris/iris --save\'');

                process.exit(1);
            });
    },
    new: (name) => {
        const packageTemplate = {
            "name": "",
            "version": "0.1.0",
            "description": "",
            "main": "irisfile.js",
            "dependencies": {
                "iris": "github:gcba-iris/iris"
            },
            "devDependencies": {},
            "scripts": {
                "test": "echo \"Error: no test specified\" && exit 1"
            },
            "keywords": [],
            "author": "",
            "license": "MIT"
        };

        var spinner;

        spinner = ora('Creating directories');
        newFolder(name, spinner);
        process.chdir(path.join(process.cwd(), name));
        newFolder('docks', spinner);
        newFolder('handlers', spinner);
        newFolder('hooks', spinner);
        spinner.succeed();

        spinner = ora('Creating files');
        spinner.start();
        packageTemplate['name'] = changeCase.paramCase(name);

        newFile('package.json', JSON.stringify(packageTemplate, undefined, 4), spinner);
        newFile('irisfile.js', irisfile, spinner);
        spinner.succeed();
        consoleLog.info('Done!');
        consoleLog.info('New iris project created in ' + process.cwd());

        process.exit(0);
    },
    config: () => {

    },
    help: () => {}
};

module.exports = cli;<commit_msg>Refactored to avoid code duplication<commit_after>/*
 * Iris
 * (c) 2016+ Buenos Aires City Government
 * License: https://opensource.org/licenses/MIT
 *
 */

'use strict';

const fs = require('graceful-fs');
const path = require('path');
const ora = require('ora');
const paramCase = require('param-case');
const npm = require('npm-cmd');
const utils = require('./utils');

const consoleLog = utils.log;
const irisfile = 'const iris = require(\'iris\');\n';

const handleErrors = (errors, spinner) => {
    spinner.fail();

    errors.forEach(function (error) {
        consoleLog.error(error);
    }, this);

    process.exit(1);
};

const checkFile = (fileName) => {
    try {
        return fs.statSync(path.join(process.cwd(), fileName)).isFile();
    } catch (error) {
        if (error.code !== 'ENOENT') throw error;

        return false;
    }
};

const createFile = (fileName, content) => {
    try {
        fs.writeFileSync(path.join(process.cwd(), fileName), content);
    } catch (error) {
        return false;
    }

    return true;
};

const newFile = (fileName, content, spinner) => {
    if (!createFile(fileName, content)) {
        handleErrors(['Could not create ' + fileName], spinner);
    }
};

const checkFolder = (folder) => {
    try {
        return fs.statSync(path.join(process.cwd(), folder)).isDirectory();
    } catch (error) {
        if (error.code !== 'ENOENT') throw error;

        return false;
    }
};

const createFolder = (folder) => {
    try {
        fs.mkdirSync(path.join(process.cwd(), folder));
    } catch (error) {
        return false;
    }

    return true;
};

const newFolder = (folder, spinner) => {
    if (checkFolder(folder)) {
        handleErrors(['Directory \'' + folder + '\' already exists'], spinner);
    }

    if (!createFolder(folder)) {
        handleErrors(['Could not create directory \'' + folder + '\''], spinner);
    }
};

const cli = {
    status: () => {

    },
    init: () => {
        var spinner;

        spinner = ora('Checking package.json');
        spinner.start();

        if (checkFile('package.json')) {
            spinner.succeed();
        } else {
            const errors = ['package.json not found', 'You need to run this command inside a npm module folder'];

            handleErrors(errors, spinner);
        }

        spinner = ora('Creating Irisfile');
        spinner.start();

        if (checkFile('irisfile.js')) {
            handleErrors(['Irisfile already exists'], spinner);
        }

        newFile('irisfile.js', JSON.stringify(irisfile), spinner);
        spinner.succeed();
        spinner = ora('Running \'npm install gcba-iris/iris --save\'');
        spinner.start();

        npm.install(['gcba-iris/iris'], {
            cwd: process.cwd(),
            save: true
        }, (error) => {
            if (error) {
                handleErrors(['Unable to do \'npm install gcba-iris/iris --save\''], spinner);
            }

            spinner.succeed();
            consoleLog.info('Done!');

            process.exit(0);
        });
    },
    new: (name) => {
        const packageTemplate = {
            "name": "",
            "version": "0.1.0",
            "description": "",
            "main": "irisfile.js",
            "dependencies": {
                "iris": "github:gcba-iris/iris"
            },
            "devDependencies": {},
            "scripts": {
                "test": "echo \"Error: no test specified\" && exit 1"
            },
            "keywords": [],
            "author": "",
            "license": "MIT"
        };

        var spinner;

        spinner = ora('Creating directories');
        newFolder(name, spinner);
        process.chdir(path.join(process.cwd(), name));
        newFolder('docks', spinner);
        newFolder('handlers', spinner);
        newFolder('hooks', spinner);
        spinner.succeed();

        spinner = ora('Creating files');
        spinner.start();
        packageTemplate['name'] = paramCase(name);

        newFile('package.json', JSON.stringify(packageTemplate, undefined, 4), spinner);
        newFile('irisfile.js', irisfile, spinner);
        spinner.succeed();

        spinner = ora('Running \'npm install\'');
        spinner.start();

        npm.install([], {
            cwd: process.cwd()
        }, (error) => {
            if (error) {
                handleErrors(['Unable to do \'npm install\''], spinner);
            }

            spinner.succeed();
            consoleLog.info('Done!');
            consoleLog.info('New iris project created in ' + process.cwd());
        });
    },
    config: () => {

    },
    help: () => {}
};

module.exports = cli;<|endoftext|>


<commit_before>KeyCodes = (function (exports) {
  "use strict";

  var KeyCodes = Object.create(null);

  var define = function (code) {
    for (var i = 1; i < arguments.length; ++i) {
      var key = arguments[i];
      Object.defineProperty(KeyCodes, key, {
        value: code,
        writable: false,
        enumerable: true,
        configurable: false
      });
    }
  };

  define(  8, 'BACKSPACE'       );
  define(  9, 'TAB'             );
  define( 13, 'ENTER'           );
  define( 16, 'SHIFT'           );
  define( 17, 'CTRL'            );
  define( 18, 'ALT'             );
  define( 19, 'BREAK', 'PAUSE'  );
  define( 20, 'CAPS_LOCK'       );
  define( 27, 'ESCAPE'          );
  define( 32, 'SPACE'           );
  define( 33, 'PAGE_UP'         );
  define( 34, 'PAGE_DOWN'       );
  define( 35, 'END'             );
  define( 36, 'HOME'            );
  define( 37, 'LEFT_ARROW'      );
  define( 38, 'UP_ARROW'        );
  define( 39, 'RIGHT_ARROW'     );
  define( 40, 'DOWN_ARROW'      );
  define( 45, 'INSERT'          );
  define( 46, 'DELETE'          );
  define( 48, '0', 'ZERO'       );
  define( 49, '1', 'ONE'        );
  define( 50, '2', 'TWO'        );
  define( 51, '3', 'THREE'      );
  define( 52, '4', 'FOUR'       );
  define( 53, '5', 'FIVE'       );
  define( 54, '6', 'SIX'        );
  define( 55, '7', 'SEVEN'      );
  define( 56, '8', 'EIGHT'      );
  define( 57, '9', 'NINE'       );
  define( 65, 'A'               );
  define( 66, 'B'               );
  define( 67, 'C'               );
  define( 68, 'D'               );
  define( 69, 'E'               );
  define( 70, 'F'               );
  define( 71, 'G'               );
  define( 72, 'H'               );
  define( 73, 'I'               );
  define( 74, 'J'               );
  define( 75, 'K'               );
  define( 76, 'L'               );
  define( 77, 'M'               );
  define( 78, 'N'               );
  define( 79, 'O'               );
  define( 80, 'P'               );
  define( 81, 'Q'               );
  define( 82, 'R'               );
  define( 83, 'S'               );
  define( 84, 'T'               );
  define( 85, 'U'               );
  define( 86, 'V'               );
  define( 87, 'W'               );
  define( 88, 'X'               );
  define( 89, 'Y'               );
  define( 90, 'Z'               );
  define( 91, 'LEFT_WINDOW_KEY' );
  define( 92, 'RIGHT_WINDOW_KEY');
  define( 93, 'SELECT_KEY'      );
  define( 96, 'NUMPAD_0'        );
  define( 97, 'NUMPAD_1'        );
  define( 98, 'NUMPAD_2'        );
  define( 99, 'NUMPAD_3'        );
  define(100, 'NUMPAD_4'        );
  define(101, 'NUMPAD_5'        );
  define(102, 'NUMPAD_6'        );
  define(103, 'NUMPAD_7'        );
  define(104, 'NUMPAD_8'        );
  define(105, 'NUMPAD_9'        );
  define(106, 'MULTIPLY'        );
  define(107, 'ADD'             );
  define(109, 'SUBTRACT'        );
  define(110, 'DECIMAL_POINT'   );
  define(111, 'DIVIDE'          );
  define(112, 'F1'              );
  define(113, 'F2'              );
  define(114, 'F3'              );
  define(115, 'F4'              );
  define(116, 'F5'              );
  define(117, 'F6'              );
  define(118, 'F7'              );
  define(119, 'F8'              );
  define(120, 'F9'              );
  define(121, 'F10'             );
  define(122, 'F11'             );
  define(123, 'F12'             );
  define(144, 'NUM_LOCK'        );
  define(145, 'SCROLL_LOCK'     );
  define(186, 'SEMICOLON'       );
  define(187, 'EQUAL_SIGN'      );
  define(188, 'COMMA'           );
  define(189, 'DASH'            );
  define(190, 'PERIOD'          );
  define(191, 'FORWARD_SLASH'   );
  define(192, 'GRAVE_ACCENT'    );
  define(219, 'OPEN_BRACKET'    );
  define(220, 'BACK_SLASH'      );
  define(221, 'CLOSE_BRACKET'   );
  define(222, 'SINGLE_QUOTE'    );

  Object.preventExtensions(KeyCodes);

  if (exports) {
    exports.KeyCodes = KeyCodes
  }

  return KeyCodes
}(exports));

<commit_msg>Remove unused export<commit_after>KeyCodes = (function () {
  'use strict';

  var KeyCodes = Object.create(null);

  var define = function (code) {
    for (var i = 1; i < arguments.length; ++i) {
      var key = arguments[i];
      Object.defineProperty(KeyCodes, key, {
        value: code,
        writable: false,
        enumerable: true,
        configurable: false
      });
    }
  };

  define(  8, 'BACKSPACE'       );
  define(  9, 'TAB'             );
  define( 13, 'ENTER'           );
  define( 16, 'SHIFT'           );
  define( 17, 'CTRL'            );
  define( 18, 'ALT'             );
  define( 19, 'BREAK', 'PAUSE'  );
  define( 20, 'CAPS_LOCK'       );
  define( 27, 'ESCAPE'          );
  define( 32, 'SPACE'           );
  define( 33, 'PAGE_UP'         );
  define( 34, 'PAGE_DOWN'       );
  define( 35, 'END'             );
  define( 36, 'HOME'            );
  define( 37, 'LEFT_ARROW'      );
  define( 38, 'UP_ARROW'        );
  define( 39, 'RIGHT_ARROW'     );
  define( 40, 'DOWN_ARROW'      );
  define( 45, 'INSERT'          );
  define( 46, 'DELETE'          );
  define( 48, '0', 'ZERO'       );
  define( 49, '1', 'ONE'        );
  define( 50, '2', 'TWO'        );
  define( 51, '3', 'THREE'      );
  define( 52, '4', 'FOUR'       );
  define( 53, '5', 'FIVE'       );
  define( 54, '6', 'SIX'        );
  define( 55, '7', 'SEVEN'      );
  define( 56, '8', 'EIGHT'      );
  define( 57, '9', 'NINE'       );
  define( 65, 'A'               );
  define( 66, 'B'               );
  define( 67, 'C'               );
  define( 68, 'D'               );
  define( 69, 'E'               );
  define( 70, 'F'               );
  define( 71, 'G'               );
  define( 72, 'H'               );
  define( 73, 'I'               );
  define( 74, 'J'               );
  define( 75, 'K'               );
  define( 76, 'L'               );
  define( 77, 'M'               );
  define( 78, 'N'               );
  define( 79, 'O'               );
  define( 80, 'P'               );
  define( 81, 'Q'               );
  define( 82, 'R'               );
  define( 83, 'S'               );
  define( 84, 'T'               );
  define( 85, 'U'               );
  define( 86, 'V'               );
  define( 87, 'W'               );
  define( 88, 'X'               );
  define( 89, 'Y'               );
  define( 90, 'Z'               );
  define( 91, 'LEFT_WINDOW_KEY' );
  define( 92, 'RIGHT_WINDOW_KEY');
  define( 93, 'SELECT_KEY'      );
  define( 96, 'NUMPAD_0'        );
  define( 97, 'NUMPAD_1'        );
  define( 98, 'NUMPAD_2'        );
  define( 99, 'NUMPAD_3'        );
  define(100, 'NUMPAD_4'        );
  define(101, 'NUMPAD_5'        );
  define(102, 'NUMPAD_6'        );
  define(103, 'NUMPAD_7'        );
  define(104, 'NUMPAD_8'        );
  define(105, 'NUMPAD_9'        );
  define(106, 'MULTIPLY'        );
  define(107, 'ADD'             );
  define(109, 'SUBTRACT'        );
  define(110, 'DECIMAL_POINT'   );
  define(111, 'DIVIDE'          );
  define(112, 'F1'              );
  define(113, 'F2'              );
  define(114, 'F3'              );
  define(115, 'F4'              );
  define(116, 'F5'              );
  define(117, 'F6'              );
  define(118, 'F7'              );
  define(119, 'F8'              );
  define(120, 'F9'              );
  define(121, 'F10'             );
  define(122, 'F11'             );
  define(123, 'F12'             );
  define(144, 'NUM_LOCK'        );
  define(145, 'SCROLL_LOCK'     );
  define(186, 'SEMICOLON'       );
  define(187, 'EQUAL_SIGN'      );
  define(188, 'COMMA'           );
  define(189, 'DASH'            );
  define(190, 'PERIOD'          );
  define(191, 'FORWARD_SLASH'   );
  define(192, 'GRAVE_ACCENT'    );
  define(219, 'OPEN_BRACKET'    );
  define(220, 'BACK_SLASH'      );
  define(221, 'CLOSE_BRACKET'   );
  define(222, 'SINGLE_QUOTE'    );

  return Object.preventExtensions(KeyCodes);
}());

<|endoftext|>


<commit_before>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();

// Initialise New Relic if an app name and license key exists
if (process.env.NEW_RELIC_APP_NAME && process.env.NEW_RELIC_LICENSE_KEY) {
	require('newrelic');
}

// Initialize application
var keystone = require('keystone'),
	handlebars = require('express-handlebars');

keystone.init({

	'name': 'MARE',
	'brand': 'MARE',

	'sass': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',

	'views': 'templates/views',
	'view engine': 'hbs',
	'view cache': false,

	'custom engine': handlebars.create({
		layoutsDir: 'templates/views/layouts',
		partialsDir: 'templates/views/partials',
		defaultLayout: 'default',
		helpers: new require('./templates/views/helpers')(),
		extname: '.hbs'
	}).engine,

	'emails': 'templates/emails',

	'auto update': true,
	'session': true,
	'auth': true,
	'signin url': '/',
	'user model': 'User',

	'wysiwyg override toolbar': false,
	'wysiwyg menubar': true,
	'wysiwyg skin': 'lightgray',
	'wysiwyg additional buttons': 'searchreplace visualchars,' +
	 	' charmap ltr rtl pagebreak paste,' +
	 	' emoticons media image, preview print',
	'wysiwyg additional plugins': 'advlist, anchor,' +
		' autolink, autosave, charmap, contextmenu,' +
		' directionality, emoticons, hr, media, pagebreak,' +
		' paste, preview, print, searchreplace, table, template' +
		' visualblocks, visualchars, wordcount',
	'wysiwyg cloudinary images': true,

	'wysiwyg additional options': {

		extended_valid_elements : '+div[class]',
		content_css: '/keystone/styles/content/editor.min.css',
		templates: [
    		{title: '30/70 Content', description: 'Columns (30% Left, 70% Right)', content: '

Left Content

Right Content

Stuff after...
'},
    		{title: '70/30 Content', description: 'Columns (70% Left, 30% Right)', content: '

Left Content

Right Content

Stuff after...
'},
    		{title: '50/50 Content', description: 'Columns (50% Left, 50% Right)', content: '

Left Content

Right Content

Stuff after...
'}
  		]
  	},

	'cookie secret': process.env.COOKIE_SECRET || '-eRWCqW&S~{bTw-|nG=]av*#2X*u}<?$v44|LV^|K*.q>.a<&rC[A~6%9rVcgh~)'
});

// Cloudinary configuration
// optional, will prefix each image public_id with [{prefix}]/{list.path}/{field.path}/
keystone.set('cloudinary folders', true);
// optional, will force cloudinary to serve images over https
keystone.set('cloudinary secure', true);

// Mandrill configuration
keystone.set('mandrill api key', process.env.MANDRILL_APIKEY);
keystone.set('mandrill username', process.env.MANDRILL_USERNAME);

//Setup stripe tokens
keystone.set('stripe keys',{pubKey: process.env.STRIPE_PUBKEY, privKey: process.env.STRIPE_KEY});

// S3 configuration for hosted file storage
keystone.set('s3 config', { bucket: process.env.S3_BUCKET_NAME, key: process.env.S3_KEY, secret: process.env.S3_SECRET });

// Load project's Models
keystone.import('models');

// Load project Routes
keystone.set('routes', require('./routes'));

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware/middleware.js
keystone.set('locals', {
	_: require('underscore'),
	moment: require('moment'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable
});

// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
keystone.set('email locals', {
	logo_src: '/public/dist/img/mare-logo.png',
	logo_width: 194,
	logo_height: 76,
	theme: {
		email_bg: '#f9f9f9',
		link_color: '#2697de',
		buttons: {
			color: '#fff',
			background_color: '#2697de',
			border_color: '#1a7cb7'
		}
	},
	host: (function() {
		'use strict';

		if (keystone.get('env') === 'development') { return 'http://development.adoptions.io'; }
		if (keystone.get('env') === 'staging') { return 'http://staging.adoptions.io'; }
		if (keystone.get('env') === 'production') { return 'http://adoptions.io'; }
		return (keystone.get('host') || 'http://localhost:') + (keystone.get('port') || '3000');
	})()
});

keystone.set('email rules', [{
	find: '/templates/emails/',
	replace: (function() {
		'use strict';

		if (keystone.get('env') === 'development') { return 'http://development.adoptions.io/templates/emails/'; }
		if (keystone.get('env') === 'staging') { return 'http://staging.adoptions.io/templates/emails/'; }
		if (keystone.get('env') === 'production') { return 'http://adoptions.io/templates/emails/'; }
		return (keystone.get('host') || 'http://localhost:') + (keystone.get('port') || '3000') + '/templates/emails/';
	})()
}, {
	find: '/keystone/',
	replace: (function() {
		'use strict';

		if (keystone.get('env') === 'development') { return 'http://development.adoptions.io/keystone'; }
		if (keystone.get('env') === 'staging') { return 'http://staging.adoptions.io/keystone'; }
		if (keystone.get('env') === 'production') { return 'http://adoptions.io/keystone'; }
		return (keystone.get('host') || 'http://localhost:') + (keystone.get('port') || '3000/keystone');
	})()
}]);

// Load your project's email test routes
keystone.set('email tests', require('./routes/emails'));

// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
	'people'			: [ 'admins', 'site-visitors', 'families', 'social-workers', 'children', 'outside-contacts',
						   'contact-groups' ],
	'other'				: [ 'account-verification-codes', 'agencies', 'inquiries', 'internal-notes', 'media-types',
							'mare-in-the-news' ],
	'events'			: [ 'events' ],
	'mailing lists'		: [ 'mailing-lists' ],
	'relationships'		: [ 'csc-region-contacts', 'staff-email-contacts', 'matches', 'media-features', 'placements' ],
	'change tracking'	: [ 'child-histories', 'family-histories', 'social-worker-histories' ],
	'lists'				: [ 'child-statuses', 'child-types', 'city-or-towns', 'closed-reasons', 'communication-methods',
						    'disabilities', 'event-types', 'family-constellations', 'family-statuses', 'genders', 'inquiry-methods',
						    'inquiry-types', 'languages', 'legal-statuses', 'match-determinations', 'media-eligibilities',
						    'other-considerations', 'other-family-constellation-considerations', 'races', 'regions', 'residences',
							'social-worker-positions', 'sources', 'staff-email-targets', 'states', 'way-to-hear-about-mares' ],
	'donations'			: [ 'donations' ],
	'images'			: [ 'featured-items', 'slideshows', 'slideshow-items' ],
	'content pages'		: [ 'pages' ],
	'content snippets'	: [ 'success-stories' ],

});

// Start Keystone to connect to your database and initialise the web server
keystone.start();
<commit_msg>#25 | removes unnecessary Stripe API variables from keystone scope<commit_after>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();

// Initialise New Relic if an app name and license key exists
if (process.env.NEW_RELIC_APP_NAME && process.env.NEW_RELIC_LICENSE_KEY) {
	require('newrelic');
}

// Initialize application
var keystone = require('keystone'),
	handlebars = require('express-handlebars');

keystone.init({

	'name': 'MARE',
	'brand': 'MARE',

	'sass': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',

	'views': 'templates/views',
	'view engine': 'hbs',
	'view cache': false,

	'custom engine': handlebars.create({
		layoutsDir: 'templates/views/layouts',
		partialsDir: 'templates/views/partials',
		defaultLayout: 'default',
		helpers: new require('./templates/views/helpers')(),
		extname: '.hbs'
	}).engine,

	'emails': 'templates/emails',

	'auto update': true,
	'session': true,
	'auth': true,
	'signin url': '/',
	'user model': 'User',

	'wysiwyg override toolbar': false,
	'wysiwyg menubar': true,
	'wysiwyg skin': 'lightgray',
	'wysiwyg additional buttons': 'searchreplace visualchars,' +
	 	' charmap ltr rtl pagebreak paste,' +
	 	' emoticons media image, preview print',
	'wysiwyg additional plugins': 'advlist, anchor,' +
		' autolink, autosave, charmap, contextmenu,' +
		' directionality, emoticons, hr, media, pagebreak,' +
		' paste, preview, print, searchreplace, table, template' +
		' visualblocks, visualchars, wordcount',
	'wysiwyg cloudinary images': true,

	'wysiwyg additional options': {

		extended_valid_elements : '+div[class]',
		content_css: '/keystone/styles/content/editor.min.css',
		templates: [
    		{title: '30/70 Content', description: 'Columns (30% Left, 70% Right)', content: '

Left Content

Right Content

Stuff after...
'},
    		{title: '70/30 Content', description: 'Columns (70% Left, 30% Right)', content: '

Left Content

Right Content

Stuff after...
'},
    		{title: '50/50 Content', description: 'Columns (50% Left, 50% Right)', content: '

Left Content

Right Content

Stuff after...
'}
  		]
  	},

	'cookie secret': process.env.COOKIE_SECRET || '-eRWCqW&S~{bTw-|nG=]av*#2X*u}<?$v44|LV^|K*.q>.a<&rC[A~6%9rVcgh~)'
});

// Cloudinary configuration
// optional, will prefix each image public_id with [{prefix}]/{list.path}/{field.path}/
keystone.set('cloudinary folders', true);
// optional, will force cloudinary to serve images over https
keystone.set('cloudinary secure', true);

// Mandrill configuration
keystone.set('mandrill api key', process.env.MANDRILL_APIKEY);
keystone.set('mandrill username', process.env.MANDRILL_USERNAME);

// S3 configuration for hosted file storage
keystone.set('s3 config', { bucket: process.env.S3_BUCKET_NAME, key: process.env.S3_KEY, secret: process.env.S3_SECRET });

// Load project's Models
keystone.import('models');

// Load project Routes
keystone.set('routes', require('./routes'));

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware/middleware.js
keystone.set('locals', {
	_: require('underscore'),
	moment: require('moment'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable
});

// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
keystone.set('email locals', {
	logo_src: '/public/dist/img/mare-logo.png',
	logo_width: 194,
	logo_height: 76,
	theme: {
		email_bg: '#f9f9f9',
		link_color: '#2697de',
		buttons: {
			color: '#fff',
			background_color: '#2697de',
			border_color: '#1a7cb7'
		}
	},
	host: (function() {
		'use strict';

		if (keystone.get('env') === 'development') { return 'http://development.adoptions.io'; }
		if (keystone.get('env') === 'staging') { return 'http://staging.adoptions.io'; }
		if (keystone.get('env') === 'production') { return 'http://adoptions.io'; }
		return (keystone.get('host') || 'http://localhost:') + (keystone.get('port') || '3000');
	})()
});

keystone.set('email rules', [{
	find: '/templates/emails/',
	replace: (function() {
		'use strict';

		if (keystone.get('env') === 'development') { return 'http://development.adoptions.io/templates/emails/'; }
		if (keystone.get('env') === 'staging') { return 'http://staging.adoptions.io/templates/emails/'; }
		if (keystone.get('env') === 'production') { return 'http://adoptions.io/templates/emails/'; }
		return (keystone.get('host') || 'http://localhost:') + (keystone.get('port') || '3000') + '/templates/emails/';
	})()
}, {
	find: '/keystone/',
	replace: (function() {
		'use strict';

		if (keystone.get('env') === 'development') { return 'http://development.adoptions.io/keystone'; }
		if (keystone.get('env') === 'staging') { return 'http://staging.adoptions.io/keystone'; }
		if (keystone.get('env') === 'production') { return 'http://adoptions.io/keystone'; }
		return (keystone.get('host') || 'http://localhost:') + (keystone.get('port') || '3000/keystone');
	})()
}]);

// Load your project's email test routes
keystone.set('email tests', require('./routes/emails'));

// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
	'people'			: [ 'admins', 'site-visitors', 'families', 'social-workers', 'children', 'outside-contacts',
						   'contact-groups' ],
	'other'				: [ 'account-verification-codes', 'agencies', 'inquiries', 'internal-notes', 'media-types',
							'mare-in-the-news' ],
	'events'			: [ 'events' ],
	'mailing lists'		: [ 'mailing-lists' ],
	'relationships'		: [ 'csc-region-contacts', 'staff-email-contacts', 'matches', 'media-features', 'placements' ],
	'change tracking'	: [ 'child-histories', 'family-histories', 'social-worker-histories' ],
	'lists'				: [ 'child-statuses', 'child-types', 'city-or-towns', 'closed-reasons', 'communication-methods',
						    'disabilities', 'event-types', 'family-constellations', 'family-statuses', 'genders', 'inquiry-methods',
						    'inquiry-types', 'languages', 'legal-statuses', 'match-determinations', 'media-eligibilities',
						    'other-considerations', 'other-family-constellation-considerations', 'races', 'regions', 'residences',
							'social-worker-positions', 'sources', 'staff-email-targets', 'states', 'way-to-hear-about-mares' ],
	'donations'			: [ 'donations' ],
	'images'			: [ 'featured-items', 'slideshows', 'slideshow-items' ],
	'content pages'		: [ 'pages' ],
	'content snippets'	: [ 'success-stories' ],

});

// Start Keystone to connect to your database and initialise the web server
keystone.start();
<|endoftext|>