<commit_before>/**
 * Module dependencies.
 */

var _ = require('underscore');
var bind = require('../bind');
var regex = require('../regex');
var stop = require('../stop-event');
var $ = require('../bonzo-augmented');
var template = require('./signin.ejs');
var create = require('../object-create');
var Emitter = require('events').EventEmitter;
var buttonTmpl = require('../html/zocial-button.ejs');
var loginActionsTmpl = require('./login_actions.ejs');
var gravatar = require('../gravatar');

/**
 * Expose SigninPanel
 */

module.exports = SigninPanel;

/**
 * Create `SigninPanel`
 *
 * @param {Auth0Lock} widget
 * @param {Object} options
 * @constructor
 */

function SigninPanel(widget, options) {
  if (!(this instanceof SigninPanel)) {
    return new SigninPanel(widget, options);
  }

  // Both `widget` and `options` are required
  if (2 !== arguments.length) {
    throw new Error('Missing parameters for SigninPanel');
  }

  this.name = 'signin';
  this.widget = widget;
  this.options = this.resolveOptions(options);
  this.el = null;

  Emitter.call(this);
}

/**
 * Inherit from `EventEmitter`
 */

SigninPanel.prototype = create(Emitter.prototype);

/**
 * Query for elements at `this.el` context
 *
 * @param {String} selector
 * @return {BonzoAugmented}
 * @public
 */

SigninPanel.prototype.query = function(selector) {
  if (!this.el) { throw new Error('Can\'t get element since no `el` is set to local context'); }
  return $(selector, this.el);
};

/**
 * Create `el`
 *
 * @param {Object} options
 * @return {NodeElement}
 * @public
 */

SigninPanel.prototype.create = function(options) {
  var opts = this.resolveOptions(options);
  var widget = this.widget;

  this.el = $.create(widget.render(template, opts))[0];
  this.bindAll();
  return this.el;
};

/**
 * Return `el` or create it
 *
 * @param {Object} options
 * @return {NodeElement}
 * @public
 */

SigninPanel.prototype.render = function() {
  return null != this.el
    ? this.el
    : this.create.apply(this, arguments);
};

/**
 * Resolves login options passed to template
 *
 * @param {Object} options
 * @return {Object}
 * @private
 */

SigninPanel.prototype.resolveOptions = function(options) {
  return _.extend({}, this.widget.options,  this.options, options);
};

/*
 * Render and bind social strategies
 *
 *@private
 */
SigninPanel.prototype.renderAndBindSocialStrategies = function () {
  var options = this.options;

  // load social buttons
  var list = this.query('.a0-iconlist');

  var socialStrategies = _.chain(options.$client.strategies).where({ social: true });

  if (options.connections) {
    // sort social strategies based on options.connections array order
    var connections = options.connections;
    socialStrategies = socialStrategies.map(function (s) {
      var n = connections.indexOf(s.connections[0].name);
      connections[n] = '';
      return [n, s];
    }).sort().map(function (x) { return x[1]; });
  }

  socialStrategies
    .map(function (s) {
      var e = {
        use_big_buttons: options._useBigSocialButtons(),
        title: options.i18n.t('loginSocialButton').replace('{connection:title}', s.title)
      };
      return  _.extend({}, s, e);
    })
    .each(function (s) { return list.append(buttonTmpl(s)); });

  if (options._getSocialStrategies().length > 0) {
    this.query('.a0-separator, .a0-iconlist').toggleClass('a0-hide', false);
  }

  this.query('.a0-zocial[data-strategy]', list).a0_on('click', bind(this.onsocialclick, this));
};

/**
 * Bind events to `this.el`, like submit
 *
 * @return {SigninPanel}
 * @private
 */

SigninPanel.prototype.bindAll = function() {
  var widget = this.widget;
  var options = this.options;

  this.renderAndBindSocialStrategies();

  this.query('.a0-email input').a0_on('input', _.debounce(bind(this.onemailinput, this), 300));
  this.query('form').a0_on('submit', bind(this.onsubmit, this));

  var actions = $.create(widget.render(loginActionsTmpl, options));
  this.query('.a0-db-actions').append(actions);

  // set username mode
  if (options.usernameStyle === 'username') {
    var placeholder = options.i18n.t('signin:usernamePlaceholder');

    this.query('.a0-email input')
      .attr('type', 'text')
      .attr('title', placeholder)
      .attr('placeholder', placeholder);

    this.query('.a0-email label').text(placeholder);
  }

  var signup_btn = this.query('.a0-sign-up');
  if (!options.signupLink && signup_btn.length > 0) {
    signup_btn.a0_on('click', bind(this.onsignupclick, this));
  }

  if (!options.resetLink) {
    this.query('.a0-forgot-pass').a0_on('click', bind(this.onresetclick, this));
  }

  this.query('input').val('');

  // show email, password, separator and button if there are enterprise/db connections
  var anyEnterpriseOrDbConnection = options._isThereAnyEnterpriseOrDbConnection();
  var anySocialConnection = options._isThereAnySocialConnection();
  var anyDBConnection = options._isThereAnyDBConnection();

  this.query('.a0-email input').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);
  this.query('.a0-zocial.a0-primary').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);
  this.query('.a0-password').toggleClass('a0-hide', !anyDBConnection);
  this.query('.a0-separator').toggleClass('a0-hide', !(anyEnterpriseOrDbConnection && anySocialConnection));

  this.query('.a0-inputs').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);
  this.query('.a0-action').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);

};

/**
 * Show or hide password input whether it is or is not
 * an enterprise connection
 * XXX: This should be moved to `SigninPanel` view
 *
 * @param {Event} e
 * @private
 */
// TODO Debounce me
SigninPanel.prototype.onemailinput = function (e) {
  stop(e);
  var mailField   = this.query('.a0-email input');
  var pwdField    = this.query('.a0-password input').first();
  var nextButton  = this.query('.a0-action > button.a0-next');

  var emailDomain = this.options._extractEmailDomain(mailField.val() || '');

  var isEnterpriseConnection = this.options._isEnterpriseConnection(mailField.val() || '');
  var adConnection = this.options._findConnectionByADDomain(emailDomain);
  var msg;

  if ('username' !== this.options.usernameStyle && this.options.gravatar) {
    gravatar(this.widget, mailField.val());
  }

  // TODO Refactor
  if (adConnection) {
    this.hrd = true;
    this.currentADConnection = adConnection;
    this.currentADConnectionDomain = emailDomain;

    this.query('.a0-sso-notice-container').removeClass('a0-hide');
    this.query('.a0-password').addClass('a0-hide');
    this.oldText = nextButton.text();

    msg = this.options.i18n.t('signin:actionDomain');
    msg = msg.replace('{domain}', emailDomain);

    nextButton.text(msg);
    nextButton.attr('title', msg);

    return pwdField.attr('disabled', true);
  }

  this.hrd = undefined;
  this.currentADConnection = undefined;
  if (this.oldText) {
    nextButton.text(this.oldText);
    nextButton.attr('title', this.oldText);
    this.oldText = undefined;
  }

  if (isEnterpriseConnection) {
    this.query('.a0-sso-notice-container').removeClass('a0-hide');
    this.query('.a0-password').addClass('a0-hide');
    this.oldText = nextButton.text();

    msg = this.options.i18n.t('signin:actionDomain');
    msg = msg.replace('{domain}', emailDomain);

    nextButton.text(msg);
    nextButton.attr('title', msg);

    return pwdField.attr('disabled', true);
  }

  this.query('.a0-sso-notice-container').addClass('a0-hide');
  this.query('.a0-password').removeClass('a0-hide');

  return pwdField.removeAttr('disabled');
};

/**
 * Validate form and continue with signin
 *
 * @param {Event} e
 * @private
 */
SigninPanel.prototype.onsubmit = function(e) {
  stop(e);
  var widget = this.widget;
  var options = this.options;

  var ok = true;
  var password_input = this.query('input[name=password]');
  var password_empty = regex.empty.test(password_input.val());
  var password_disabled = password_input.attr('disabled');
  var password_required = options._isThereAnyDBConnection();
  var email_input = this.query('input[name=email]');
  var email_parsed = regex.email_parser.exec(email_input.val().toLowerCase());
  var email_empty = regex.empty.test(email_input.val());

  // Clean error container
  widget._showError();
  widget._focusError();

  if (email_empty) {
    widget._focusError(email_input);
    ok = false;
  }

  if (!widget._ignoreEmailValidations(email_input)) {
    if (!email_parsed && !email_empty) {
      widget._focusError(email_input, options.i18n.t('invalid'));
      ok = false;
    }
  }

  if (password_empty && password_required && !password_disabled) {
    widget._focusError(password_input);
    ok = false;
  }

  if (this.hrd) {
    return this.enableHRD(this.currentADConnection, this.currentADConnectionDomain);

  }

  if (ok && this.currentADConnection) {
    var conn_obj = this.options._findConnectionByADDomain(
      this.currentADConnection.domain,
      widget.$client.strategies
    );
    return widget._signinWithAuth0(this, conn_obj);
  }

  if (ok) { return widget._signin(this); }
};

/**
 * Handle `e` for social connections button click
 *
 * @param {Event} e
 * @private
 */

SigninPanel.prototype.onsocialclick = function(e) {
    stop(e);
    this.widget._signinSocial(e, null, null, this);
};

/**
 * Handle `e` for reset button action click
 *
 * @param {Event} e
 * @private
 */

SigninPanel.prototype.onresetclick = function(e) {
  stop(e);
  this.widget._resetPanel(this.options);
};

/**
 * Handle `e` for signup button action click
 *
 * @param {Event} e
 * @private
 */

SigninPanel.prototype.onsignupclick = function(e) {
  stop(e);
  this.widget._signupPanel(this.options);
};

/**
 * Enables Home Realm Discovery in signin
 *
 * @param {Connection} conn
 * @private
 */
// TODO Refactor
SigninPanel.prototype.enableHRD = function (adConnection, emailDomain) {
  this.hrd = undefined;

  var emailField = this.query('.a0-email input').first();
  var pwdField   = this.query('.a0-password input').first();
  var nextButton = this.query('.a0-action > button.a0-next');

  var emailParsed = regex.email_parser.exec(emailField.val());

  this.query('.a0-password').removeClass('a0-hide');
  this.query('.a0-sso-notice-container').addClass('a0-hide');
  nextButton.text(this.oldText);
  pwdField.removeAttr('disabled');

  this.widget.setPanel(this);

  var placeholder = this.options.i18n.t('signin:usernamePlaceholder');

  this._oldPlaceholder = emailField.attr('title');

  emailField
  .attr('type', 'text')
  .attr('title', placeholder)
  .attr('placeholder', placeholder);

  this.query('.a0-email label').text(placeholder);
  emailField.focus();
  if (emailParsed.length > 1) {
    emailField.val(emailParsed[1]);
  } else {
    emailField.val('');
  }

  this.query('.a0-corporate-credentials').toggleClass('a0-hide');
  this.query('.a0-domain').text(emailDomain);

  // Hide other actions buttons
  var actions = $.create(this.widget.render(loginActionsTmpl, {
    showSignupAction: false,
    showResetAction: false,
    showCancel: true
  }));

  this.query('.a0-db-actions').first().deepEach(function (child) {
    $(child).hide();
  });
  this.query('.a0-db-actions').append(actions);
  this.query('.a0-db-actions').show();

  this.query('.a0-cancel').a0_on('click', bind(this.oncancel, this));
  this.currentADConnection = adConnection;
  emailField.a0_off('input');
};

/**
 * Handle `e` for cancel button action click (when doing HRD)
 *
 * @param {Event} e
 * @private
 */
// TODO Refactor
SigninPanel.prototype.oncancel = function (e) {
  stop(e);

  this.currentADConnection = undefined;

  var widget = this.widget;
  // Clean error container
  widget._showError();
  widget._focusError();
  widget.setPanel(this);

  var emailField = this.query('.a0-email input').first();
  var pwdField   = this.query('.a0-password input').first();

  this.query('.a0-db-actions').first().deepEach(function (child) {
    $(child).show();
  });

  var oldPlaceholder = this._oldPlaceholder;
  this._oldPlaceholder = undefined;

  this.query('.a0-db-actions .a0-cancel').remove();
  emailField
    .attr('type', 'text')
    .attr('title', oldPlaceholder)
    .attr('placeholder', oldPlaceholder);

  emailField.val('');
  pwdField.val('');

  this.query('.a0-email label').text(oldPlaceholder);

  this.query('.a0-corporate-credentials').toggleClass('a0-hide');
  emailField.a0_on('input', bind(this.onemailinput, this));
  emailField.focus();
};

<commit_msg>Not entering HRD in `username` mode.<commit_after>/**
 * Module dependencies.
 */

var _ = require('underscore');
var bind = require('../bind');
var regex = require('../regex');
var stop = require('../stop-event');
var $ = require('../bonzo-augmented');
var template = require('./signin.ejs');
var create = require('../object-create');
var Emitter = require('events').EventEmitter;
var buttonTmpl = require('../html/zocial-button.ejs');
var loginActionsTmpl = require('./login_actions.ejs');
var gravatar = require('../gravatar');

/**
 * Expose SigninPanel
 */

module.exports = SigninPanel;

/**
 * Create `SigninPanel`
 *
 * @param {Auth0Lock} widget
 * @param {Object} options
 * @constructor
 */

function SigninPanel(widget, options) {
  if (!(this instanceof SigninPanel)) {
    return new SigninPanel(widget, options);
  }

  // Both `widget` and `options` are required
  if (2 !== arguments.length) {
    throw new Error('Missing parameters for SigninPanel');
  }

  this.name = 'signin';
  this.widget = widget;
  this.options = this.resolveOptions(options);
  this.el = null;

  Emitter.call(this);
}

/**
 * Inherit from `EventEmitter`
 */

SigninPanel.prototype = create(Emitter.prototype);

/**
 * Query for elements at `this.el` context
 *
 * @param {String} selector
 * @return {BonzoAugmented}
 * @public
 */

SigninPanel.prototype.query = function(selector) {
  if (!this.el) { throw new Error('Can\'t get element since no `el` is set to local context'); }
  return $(selector, this.el);
};

/**
 * Create `el`
 *
 * @param {Object} options
 * @return {NodeElement}
 * @public
 */

SigninPanel.prototype.create = function(options) {
  var opts = this.resolveOptions(options);
  var widget = this.widget;

  this.el = $.create(widget.render(template, opts))[0];
  this.bindAll();
  return this.el;
};

/**
 * Return `el` or create it
 *
 * @param {Object} options
 * @return {NodeElement}
 * @public
 */

SigninPanel.prototype.render = function() {
  return null != this.el
    ? this.el
    : this.create.apply(this, arguments);
};

/**
 * Resolves login options passed to template
 *
 * @param {Object} options
 * @return {Object}
 * @private
 */

SigninPanel.prototype.resolveOptions = function(options) {
  return _.extend({}, this.widget.options,  this.options, options);
};

/*
 * Render and bind social strategies
 *
 *@private
 */
SigninPanel.prototype.renderAndBindSocialStrategies = function () {
  var options = this.options;

  // load social buttons
  var list = this.query('.a0-iconlist');

  var socialStrategies = _.chain(options.$client.strategies).where({ social: true });

  if (options.connections) {
    // sort social strategies based on options.connections array order
    var connections = options.connections;
    socialStrategies = socialStrategies.map(function (s) {
      var n = connections.indexOf(s.connections[0].name);
      connections[n] = '';
      return [n, s];
    }).sort().map(function (x) { return x[1]; });
  }

  socialStrategies
    .map(function (s) {
      var e = {
        use_big_buttons: options._useBigSocialButtons(),
        title: options.i18n.t('loginSocialButton').replace('{connection:title}', s.title)
      };
      return  _.extend({}, s, e);
    })
    .each(function (s) { return list.append(buttonTmpl(s)); });

  if (options._getSocialStrategies().length > 0) {
    this.query('.a0-separator, .a0-iconlist').toggleClass('a0-hide', false);
  }

  this.query('.a0-zocial[data-strategy]', list).a0_on('click', bind(this.onsocialclick, this));
};

/**
 * Bind events to `this.el`, like submit
 *
 * @return {SigninPanel}
 * @private
 */

SigninPanel.prototype.bindAll = function() {
  var widget = this.widget;
  var options = this.options;

  this.renderAndBindSocialStrategies();

  this.query('.a0-email input').a0_on('input', _.debounce(bind(this.onemailinput, this), 300));
  this.query('form').a0_on('submit', bind(this.onsubmit, this));

  var actions = $.create(widget.render(loginActionsTmpl, options));
  this.query('.a0-db-actions').append(actions);

  // set username mode
  if (options.usernameStyle === 'username') {
    var placeholder = options.i18n.t('signin:usernamePlaceholder');

    this.query('.a0-email input')
      .attr('type', 'text')
      .attr('title', placeholder)
      .attr('placeholder', placeholder);

    this.query('.a0-email label').text(placeholder);
  }

  var signup_btn = this.query('.a0-sign-up');
  if (!options.signupLink && signup_btn.length > 0) {
    signup_btn.a0_on('click', bind(this.onsignupclick, this));
  }

  if (!options.resetLink) {
    this.query('.a0-forgot-pass').a0_on('click', bind(this.onresetclick, this));
  }

  this.query('input').val('');

  // show email, password, separator and button if there are enterprise/db connections
  var anyEnterpriseOrDbConnection = options._isThereAnyEnterpriseOrDbConnection();
  var anySocialConnection = options._isThereAnySocialConnection();
  var anyDBConnection = options._isThereAnyDBConnection();

  this.query('.a0-email input').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);
  this.query('.a0-zocial.a0-primary').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);
  this.query('.a0-password').toggleClass('a0-hide', !anyDBConnection);
  this.query('.a0-separator').toggleClass('a0-hide', !(anyEnterpriseOrDbConnection && anySocialConnection));

  this.query('.a0-inputs').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);
  this.query('.a0-action').toggleClass('a0-hide', !anyEnterpriseOrDbConnection);

};

/**
 * Show or hide password input whether it is or is not
 * an enterprise connection
 * XXX: This should be moved to `SigninPanel` view
 *
 * @param {Event} e
 * @private
 */
// TODO Debounce me
SigninPanel.prototype.onemailinput = function (e) {
  stop(e);
  var mailField   = this.query('.a0-email input');
  var pwdField    = this.query('.a0-password input').first();
  var nextButton  = this.query('.a0-action > button.a0-next');

  var emailDomain = this.options._extractEmailDomain(mailField.val() || '');

  var isEnterpriseConnection = this.options._isEnterpriseConnection(mailField.val() || '');
  var adConnection = this.options._findConnectionByADDomain(emailDomain);
  var msg;

  if ('username' !== this.options.usernameStyle && this.options.gravatar) {
    gravatar(this.widget, mailField.val());
  }

  // TODO Refactor
  if ('username' !== this.options.usernameStyle && adConnection) {
    this.hrd = true;
    this.currentADConnection = adConnection;
    this.currentADConnectionDomain = emailDomain;

    this.query('.a0-sso-notice-container').removeClass('a0-hide');
    this.query('.a0-password').addClass('a0-hide');
    this.oldText = nextButton.text();

    msg = this.options.i18n.t('signin:actionDomain');
    msg = msg.replace('{domain}', emailDomain);

    nextButton.text(msg);
    nextButton.attr('title', msg);

    return pwdField.attr('disabled', true);
  }

  this.hrd = undefined;
  this.currentADConnection = undefined;
  if (this.oldText) {
    nextButton.text(this.oldText);
    nextButton.attr('title', this.oldText);
    this.oldText = undefined;
  }

  if (isEnterpriseConnection) {
    this.query('.a0-sso-notice-container').removeClass('a0-hide');
    this.query('.a0-password').addClass('a0-hide');
    this.oldText = nextButton.text();

    msg = this.options.i18n.t('signin:actionDomain');
    msg = msg.replace('{domain}', emailDomain);

    nextButton.text(msg);
    nextButton.attr('title', msg);

    return pwdField.attr('disabled', true);
  }

  this.query('.a0-sso-notice-container').addClass('a0-hide');
  this.query('.a0-password').removeClass('a0-hide');

  return pwdField.removeAttr('disabled');
};

/**
 * Validate form and continue with signin
 *
 * @param {Event} e
 * @private
 */
SigninPanel.prototype.onsubmit = function(e) {
  stop(e);
  var widget = this.widget;
  var options = this.options;

  var ok = true;
  var password_input = this.query('input[name=password]');
  var password_empty = regex.empty.test(password_input.val());
  var password_disabled = password_input.attr('disabled');
  var password_required = options._isThereAnyDBConnection();
  var email_input = this.query('input[name=email]');
  var email_parsed = regex.email_parser.exec(email_input.val().toLowerCase());
  var email_empty = regex.empty.test(email_input.val());

  // Clean error container
  widget._showError();
  widget._focusError();

  if (email_empty) {
    widget._focusError(email_input);
    ok = false;
  }

  if (!widget._ignoreEmailValidations(email_input)) {
    if (!email_parsed && !email_empty) {
      widget._focusError(email_input, options.i18n.t('invalid'));
      ok = false;
    }
  }

  if (password_empty && password_required && !password_disabled) {
    widget._focusError(password_input);
    ok = false;
  }

  if (this.hrd) {
    return this.enableHRD(this.currentADConnection, this.currentADConnectionDomain);

  }

  if (ok && this.currentADConnection) {
    var conn_obj = this.options._findConnectionByADDomain(
      this.currentADConnection.domain,
      widget.$client.strategies
    );
    return widget._signinWithAuth0(this, conn_obj);
  }

  if (ok) { return widget._signin(this); }
};

/**
 * Handle `e` for social connections button click
 *
 * @param {Event} e
 * @private
 */

SigninPanel.prototype.onsocialclick = function(e) {
    stop(e);
    this.widget._signinSocial(e, null, null, this);
};

/**
 * Handle `e` for reset button action click
 *
 * @param {Event} e
 * @private
 */

SigninPanel.prototype.onresetclick = function(e) {
  stop(e);
  this.widget._resetPanel(this.options);
};

/**
 * Handle `e` for signup button action click
 *
 * @param {Event} e
 * @private
 */

SigninPanel.prototype.onsignupclick = function(e) {
  stop(e);
  this.widget._signupPanel(this.options);
};

/**
 * Enables Home Realm Discovery in signin
 *
 * @param {Connection} conn
 * @private
 */
// TODO Refactor
SigninPanel.prototype.enableHRD = function (adConnection, emailDomain) {
  this.hrd = undefined;

  var emailField = this.query('.a0-email input').first();
  var pwdField   = this.query('.a0-password input').first();
  var nextButton = this.query('.a0-action > button.a0-next');

  var emailParsed = regex.email_parser.exec(emailField.val());

  this.query('.a0-password').removeClass('a0-hide');
  this.query('.a0-sso-notice-container').addClass('a0-hide');
  nextButton.text(this.oldText);
  pwdField.removeAttr('disabled');

  this.widget.setPanel(this);

  var placeholder = this.options.i18n.t('signin:usernamePlaceholder');

  this._oldPlaceholder = emailField.attr('title');

  emailField
  .attr('type', 'text')
  .attr('title', placeholder)
  .attr('placeholder', placeholder);

  this.query('.a0-email label').text(placeholder);
  emailField.focus();
  if (emailParsed.length > 1) {
    emailField.val(emailParsed[1]);
  } else {
    emailField.val('');
  }

  this.query('.a0-corporate-credentials').toggleClass('a0-hide');
  this.query('.a0-domain').text(emailDomain);

  // Hide other actions buttons
  var actions = $.create(this.widget.render(loginActionsTmpl, {
    showSignupAction: false,
    showResetAction: false,
    showCancel: true
  }));

  this.query('.a0-db-actions').first().deepEach(function (child) {
    $(child).hide();
  });
  this.query('.a0-db-actions').append(actions);
  this.query('.a0-db-actions').show();

  this.query('.a0-cancel').a0_on('click', bind(this.oncancel, this));
  this.currentADConnection = adConnection;
  emailField.a0_off('input');
};

/**
 * Handle `e` for cancel button action click (when doing HRD)
 *
 * @param {Event} e
 * @private
 */
// TODO Refactor
SigninPanel.prototype.oncancel = function (e) {
  stop(e);

  this.currentADConnection = undefined;

  var widget = this.widget;
  // Clean error container
  widget._showError();
  widget._focusError();
  widget.setPanel(this);

  var emailField = this.query('.a0-email input').first();
  var pwdField   = this.query('.a0-password input').first();

  this.query('.a0-db-actions').first().deepEach(function (child) {
    $(child).show();
  });

  var oldPlaceholder = this._oldPlaceholder;
  this._oldPlaceholder = undefined;

  this.query('.a0-db-actions .a0-cancel').remove();
  emailField
    .attr('type', 'text')
    .attr('title', oldPlaceholder)
    .attr('placeholder', oldPlaceholder);

  emailField.val('');
  pwdField.val('');

  this.query('.a0-email label').text(oldPlaceholder);

  this.query('.a0-corporate-credentials').toggleClass('a0-hide');
  emailField.a0_on('input', bind(this.onemailinput, this));
  emailField.focus();
};

<|endoftext|>


<commit_before>import test from 'ava';
import { create } from '../lib';
<commit_msg>Add lib/create.js test<commit_after>import test from 'ava';
import { create } from '../lib';

test('"create" function.', ({is, true: isTrue}) => {
  // Create object.
  let Test = create(function(a){
    this.a = a;
  }, {
    foo: function(a){ this.a = a; }
  });

  // Initialize object.
  let foo = new Test('baz');

  // Check construction value.
  is(foo.a, 'baz');

  // Change value
  foo.foo('qux'); // Haha, foofoo

  // Test new value
  is(foo.a, 'qux');

  // Construction without "new"
  // jshint newcap: false
  let bar = Test('qux');
  isTrue(bar instanceof Test);
});
<|endoftext|>


<commit_before>'use strict';

const supertest = require( 'supertest' );
const should    = require( 'should' );

const request   = supertest( 'localhost:' + ( process.env.INTERNAL_PORT || '3030' ) );

module.exports = function() {
	describe( 'events', function() {
		it( 'fails if requested over insecure port' );

		it( 'fails if no body is provided' );

		let props = [ 'userId', 'service', 'message', 'occurredAt' ];
		props.forEach( prop => {
			it( `fails if missing param ${prop}` );
		});

		it( 'returns success on valid body' );

		it( 'saves an event in the database' );

		it( 'saves a reference in the database' );

		after( 'cleanup', function( done ) {
			done();
		});
	});
};
<commit_msg>Adds create tests.<commit_after>'use strict';

const supertest = require( 'supertest' );
const should    = require( 'should' );
const Promise   = require( 'bluebird' );

const Event     = require( '../models/event' );
const Reference = require( '../models/reference' );

const request   = supertest( 'localhost:' + ( process.env.INTERNAL_PORT || '3030' ) );

module.exports = function() {
	describe( 'events', function() {
		it( 'fails if requested over insecure port', function( done ) {
			supertest( 'localhost:' + ( process.env.PORT || '3000' ) )
			.post( '/v1/events' )
			.expect( 403, done );
		});

		it( 'fails if no body is provided', function( done ) {
			request
			.post( '/v1/events' )
			.expect( 400, done );
		});

		let props = [ 'userId', 'service', 'message', 'occurredAt' ];
		props.forEach( prop => {
			it( `fails if missing param ${prop}`, function( done ) {
				let body = {
					userId: 1,
					service: 'audit-test',
					message: 'Test',
					occurredAt: Date.now()
				};
				delete body[ prop ];

				request
				.post( '/v1/events' )
				.send( body )
				.expect( 400, done );
			});
		});

		it( 'returns success on valid body', function( done ) {
			request
			.post( '/v1/events' )
			.send({
				userId: 1,
				service: 'audit-test',
				message: 'Test',
				occurredAt: Date.now()
			})
			.expect( 200 )
			.end( ( err, res ) => {
				if ( err ) {
					done( err );
				}
				res.body.should.be.an.Object();
				res.body.should.have.property( 'success', true );
				done();
			});
		});

		it( 'saves an event in the database', function( done ) {
			request
			.post( '/v1/events' )
			.send({
				userId: 2,
				service: 'audit-test',
				message: 'Test',
				occurredAt: Date.now()
			})
			.expect( 200 )
			.end( ( err, res ) => {
				if ( err ) {
					done( err );
				}

				new Event({ userId: 2, service: 'audit-test' })
				.fetch()
				.then( row => {
					let data = row.toJSON();
					data.should.have.properties([
						'userId',
						'service',
						'id',
						'officeId',
						'message',
						'delta',
						'createdAt',
						'occurredAt'
					]);
					done();
				})
				.catch( err => done( err ) );
			});
		});

		it( 'saves a reference in the database', function( done ) {
			request
			.post( '/v1/events' )
			.send({
				userId: 3,
				service: 'audit-test',
				message: 'Test',
				occurredAt: Date.now(),
				references: [{
					service: 'audit-test',
					object: 'test',
					objectId: 1
				}]
			})
			.expect( 200 )
			.end( ( err, res ) => {
				if ( err ) {
					done( err );
				}

				// Delay, as saving the references takes a bit longer.
				Promise.delay( 100 ).then( () => {
					new Reference({ service: 'audit-test' })
					.fetch({ require: true })
					.then( row => {
						let data = row.toJSON();
						data.should.have.properties([
							'id',
							'service',
							'eventId',
							'object',
							'objectId'
						]);
						done();
					})
				 	.catch( err => done( err ) );
				});
			});
		} );

		after( 'cleanup', function( done ) {
			Promise.join(
				Event.where({ service: 'audit-test' }).destroy(),
				Reference.where({ service: 'audit-test' }).destroy(),
				() => done()
			);
		});
	});
};
<|endoftext|>


<commit_before>const fs = require('../../core/fs.js');
const utils = require('../../utils/utils.js');
const namehash = require('eth-ens-namehash');
const async = require('async');
const embarkJsUtils = require('embarkjs').Utils;
const reverseAddrSuffix = '.addr.reverse';

class ENS {
  constructor(embark, _options) {
    this.env = embark.env;
    this.isDev = embark.config.blockchainConfig.isDev;
    this.logger = embark.logger;
    this.events = embark.events;
    this.namesConfig = embark.config.namesystemConfig;
    this.registration = this.namesConfig.register || {};
    this.embark = embark;

    if (this.namesConfig === {} ||
      this.namesConfig.enabled !== true ||
      this.namesConfig.available_providers.indexOf('ens') < 0) {
      return;
    }
    this.doSetENSProvider = this.namesConfig.provider === 'ens';

    this.addENSToEmbarkJS();
    this.configureContracts();
    this.registerEvents();
  }

  registerEvents() {
    this.events.once("contracts:deploy:afterAll", this.setProviderAndRegisterDomains.bind(this));

    this.events.setCommandHandler("storage:ens:associate", this.associateStorageToEns.bind(this));
  }

  setProviderAndRegisterDomains(cb = (() => {})) {
    const self = this;
    async.parallel([
      function getENSRegistry(paraCb) {
        self.events.request('contracts:contract', "ENSRegistry", (contract) => {
          paraCb(null, contract);
        });
      },
      function getRegistrar(paraCb) {
        self.events.request('contracts:contract', "FIFSRegistrar", (contract) => {
          paraCb(null, contract);
        });
      },
      function getResolver(paraCb) {
        self.events.request('contracts:contract', "Resolver", (contract) => {
          paraCb(null, contract);
        });
      }
    ], (err, results) => {
      if (err) {
        return cb(err);
      }
      if (!results[0] || !results[1] || !results[2]) {
        return cb(__('Aborting ENS setup as some of the contracts did not deploy properly'));
      }
      // result[0] => ENSRegistry; result[1] => FIFSRegistrar; result[2] => FIFSRegistrar
      let config = {
        env: self.env,
        registration: self.registration,
        registryAbi: results[0].abiDefinition,
        registryAddress: results[0].deployedAddress,
        registrarAbi: results[1].abiDefinition,
        registrarAddress: results[1].deployedAddress,
        resolverAbi: results[2].abiDefinition,
        resolverAddress: results[2].deployedAddress
      };

      if (self.doSetENSProvider) {
        self.addSetProvider(config);
      }

      if ((!self.isDev && self.env !== 'privatenet') || !self.registration || !self.registration.subdomains || !Object.keys(self.registration.subdomains).length) {
        return cb();
      }
      self.registerConfigDomains(config, cb);
    });
  }

  associateStorageToEns(options, cb) {
    const self = this;
    // Code inspired by https://github.com/monkybrain/ipfs-to-ens
    const {name, storageHash} = options;

    if (!utils.isValidEthDomain(name)) {
      return cb('Invalid domain name ' + name);
    }

    let hashedName = namehash.hash(name);
    let contentHash;
    try {
      contentHash = utils.hashTo32ByteHexString(storageHash);
    } catch (e) {
      return cb('Invalid IPFS hash');
    }

    // Set content
    async.waterfall([
      function getRegistryABI(next) {
        self.events.request('contracts:contract', "ENSRegistry", (contract) => {
          next(null, contract);
        });
      },
      function createRegistryContract(contract, next) {
        self.events.request("blockchain:contract:create",
          {abi: contract.abiDefinition, address: contract.deployedAddress},
          (resolver) => {
            next(null, resolver);
          });
      },
      function getResolverForName(registry, next) {
        registry.methods.resolver(hashedName).call((err, resolverAddress) => {
          if (err) {
            return cb(err);
          }
          if (resolverAddress === '0x0000000000000000000000000000000000000000') {
            return cb('Name not yet registered');
          }
          next(null, resolverAddress);
        });
      },
      function getResolverABI(resolverAddress, next) {
        self.events.request('contracts:contract', "Resolver", (contract) => {
          next(null, resolverAddress, contract);
        });
      },
      function createResolverContract(resolverAddress, contract, next) {
        self.events.request("blockchain:contract:create",
          {abi: contract.abiDefinition, address: resolverAddress},
          (resolver) => {
            next(null, resolver);
          });
      },
      function getDefaultAccount(resolver, next) {
        self.events.request("blockchain:defaultAccount:get", (defaultAccount) => {
          next(null, resolver, defaultAccount);
        });
      },
      function setContent(resolver, defaultAccount, next) {
        resolver.methods.setContent(hashedName, contentHash).send({from: defaultAccount}).then((transaction) => {
          if (transaction.status !== "0x1" && transaction.status !== "0x01" && transaction.status !== true) {
            return next('Association failed. Status: ' + transaction.status);
          }
          next();
        }).catch(next);
      }
    ], cb);
  }

  registerConfigDomains(config, cb) {
    const self = this;
    const register = require('./register');
    const secureSend = embarkJsUtils.secureSend;
    self.events.request("blockchain:defaultAccount:get", (defaultAccount) => {
      async.parallel([
        function createRegistryContract(paraCb) {
          self.events.request("blockchain:contract:create",
            {abi: config.registryAbi, address: config.registryAddress},
            (registry) => {
              paraCb(null, registry);
            });
        },
        function createRegistrarContract(paraCb) {
          self.events.request("blockchain:contract:create",
            {abi: config.registrarAbi, address: config.registrarAddress},
            (registrar) => {
              paraCb(null, registrar);
            });
        },
        function createResolverContract(paraCb) {
          self.events.request("blockchain:contract:create",
            {abi: config.resolverAbi, address: config.resolverAddress},
            (resolver) => {
              paraCb(null, resolver);
            });
        }
      ], function(err, contracts) {
        if (err) {
          return cb(err);
        }
        const [ens, registrar, resolver] = contracts;

        async.each(Object.keys(self.registration.subdomains), (subDomainName, eachCb) => {
          const address = self.registration.subdomains[subDomainName];
          const reverseNode = utils.soliditySha3(address.toLowerCase().substr(2) + reverseAddrSuffix);
          register(ens, registrar, resolver, defaultAccount, subDomainName, self.registration.rootDomain,
            reverseNode, address, self.logger, secureSend, eachCb);
        }, cb);

      });
    });
  }

  addENSToEmbarkJS() {
    const self = this;

    // get namehash, import it into file
    self.events.request("version:get:eth-ens-namehash", function(EnsNamehashVersion) {
      let currentEnsNamehashVersion = require('../../../package.json').dependencies["eth-ens-namehash"];
      if (EnsNamehashVersion !== currentEnsNamehashVersion) {
        self.events.request("version:getPackageLocation", "eth-ens-namehash", EnsNamehashVersion, function(err, location) {
          self.embark.registerImportFile("eth-ens-namehash", fs.dappPath(location));
        });
      }
    });

    let code = fs.readFileSync(utils.joinPath(__dirname, 'register.js')).toString();
    code += "\n" + fs.readFileSync(utils.joinPath(__dirname, 'embarkjs.js')).toString();
    code += "\nEmbarkJS.Names.registerProvider('ens', __embarkENS);";

    this.embark.addCodeToEmbarkJS(code);
  }

  configureContracts() {
    const config = {
      "default": {
        "gas": "auto",
        "contracts": {
          "ENS": {
            "deploy": false,
            "silent": true
          },
          "ENSRegistry": {
            "deploy": true,
            "silent": true,
            "args": []
          },
          "Resolver": {
            "deploy": true,
            "silent": true,
            "args": ["$ENSRegistry"]
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      },
      "ropsten": {
        "contracts": {
          "ENSRegistry": {
            "address": "0x112234455c3a32fd11230c42e7bccd4a84e02010",
            "silent": true
          },
          "Resolver": {
            "deploy": false
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      },
      "rinkeby": {
        "contracts": {
          "ENSRegistry": {
            "address": "0xe7410170f87102DF0055eB195163A03B7F2Bff4A",
            "silent": true
          },
          "Resolver": {
            "deploy": false
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      },
      "livenet": {
        "contracts": {
          "ENSRegistry": {
            "address": "0x314159265dd8dbb310642f98f50c066173c1259b",
            "silent": true
          },
          "Resolver": {
            "deploy": false
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      }
    };
    config.testnet = config.ropsten;

    if (this.registration && this.registration.rootDomain) {
      // Register root domain if it is defined
      const rootNode = namehash.hash(this.registration.rootDomain);
      config.default.contracts['FIFSRegistrar'] = {
        "deploy": true,
        "silent": true,
        "args": ["$ENSRegistry", rootNode],
        "onDeploy": [
          `ENSRegistry.methods.setOwner('${rootNode}', web3.eth.defaultAccount).send({from: web3.eth.defaultAccount}).then(() => {
            ENSRegistry.methods.setResolver('${rootNode}', "$Resolver").send({from: web3.eth.defaultAccount});
            var reverseNode = web3.utils.soliditySha3(web3.eth.defaultAccount.toLowerCase().substr(2) + '${reverseAddrSuffix}');
            ENSRegistry.methods.setResolver(reverseNode, "$Resolver").send({from: web3.eth.defaultAccount});
            Resolver.methods.setAddr('${rootNode}', web3.eth.defaultAccount).send({from: web3.eth.defaultAccount});
            Resolver.methods.setName(reverseNode, '${this.registration.rootDomain}').send({from: web3.eth.defaultAccount});
          })`
        ]
      };
    }
    config.privatenet = config.development;
    this.embark.registerContractConfiguration(config);

    if (this.isDev || this.env === 'privatenet') {
      this.embark.events.request("config:contractsFiles:add", this.embark.pathToFile('./contracts/ENSRegistry.sol'));
      this.embark.events.request("config:contractsFiles:add", this.embark.pathToFile('./contracts/FIFSRegistrar.sol'));
      this.embark.events.request("config:contractsFiles:add", this.embark.pathToFile('./contracts/Resolver.sol'));
    }
  }

  addSetProvider(config) {
    let code = "\nEmbarkJS.Names.setProvider('ens'," + JSON.stringify(config) + ");";

    let shouldInit = (namesConfig) => {
      return (namesConfig.provider === 'ens' && namesConfig.enabled === true);
    };

    this.embark.addProviderInit('names', code, shouldInit);
    this.embark.addConsoleProviderInit('names', code, shouldInit);
  }
}

module.exports = ENS;
<commit_msg>only add & deploy fifs register if it's actually a non live env<commit_after>const fs = require('../../core/fs.js');
const utils = require('../../utils/utils.js');
const namehash = require('eth-ens-namehash');
const async = require('async');
const embarkJsUtils = require('embarkjs').Utils;
const reverseAddrSuffix = '.addr.reverse';

class ENS {
  constructor(embark, _options) {
    this.env = embark.env;
    this.isDev = embark.config.blockchainConfig.isDev;
    this.logger = embark.logger;
    this.events = embark.events;
    this.namesConfig = embark.config.namesystemConfig;
    this.registration = this.namesConfig.register || {};
    this.embark = embark;

    if (this.namesConfig === {} ||
      this.namesConfig.enabled !== true ||
      this.namesConfig.available_providers.indexOf('ens') < 0) {
      return;
    }
    this.doSetENSProvider = this.namesConfig.provider === 'ens';

    this.addENSToEmbarkJS();
    this.configureContracts();
    this.registerEvents();
  }

  registerEvents() {
    this.events.once("contracts:deploy:afterAll", this.setProviderAndRegisterDomains.bind(this));

    this.events.setCommandHandler("storage:ens:associate", this.associateStorageToEns.bind(this));
  }

  setProviderAndRegisterDomains(cb = (() => {})) {
    const self = this;
    async.parallel([
      function getENSRegistry(paraCb) {
        self.events.request('contracts:contract', "ENSRegistry", (contract) => {
          paraCb(null, contract);
        });
      },
      function getRegistrar(paraCb) {
        self.events.request('contracts:contract', "FIFSRegistrar", (contract) => {
          paraCb(null, contract);
        });
      },
      function getResolver(paraCb) {
        self.events.request('contracts:contract', "Resolver", (contract) => {
          paraCb(null, contract);
        });
      }
    ], (err, results) => {
      if (err) {
        return cb(err);
      }
      if (!results[0] || !results[1] || !results[2]) {
        return cb(__('Aborting ENS setup as some of the contracts did not deploy properly'));
      }
      // result[0] => ENSRegistry; result[1] => FIFSRegistrar; result[2] => FIFSRegistrar
      let config = {
        env: self.env,
        registration: self.registration,
        registryAbi: results[0].abiDefinition,
        registryAddress: results[0].deployedAddress,
        registrarAbi: results[1].abiDefinition,
        registrarAddress: results[1].deployedAddress,
        resolverAbi: results[2].abiDefinition,
        resolverAddress: results[2].deployedAddress
      };

      if (self.doSetENSProvider) {
        self.addSetProvider(config);
      }

      if ((!self.isDev && self.env !== 'privatenet') || !self.registration || !self.registration.subdomains || !Object.keys(self.registration.subdomains).length) {
        return cb();
      }
      self.registerConfigDomains(config, cb);
    });
  }

  associateStorageToEns(options, cb) {
    const self = this;
    // Code inspired by https://github.com/monkybrain/ipfs-to-ens
    const {name, storageHash} = options;

    if (!utils.isValidEthDomain(name)) {
      return cb('Invalid domain name ' + name);
    }

    let hashedName = namehash.hash(name);
    let contentHash;
    try {
      contentHash = utils.hashTo32ByteHexString(storageHash);
    } catch (e) {
      return cb('Invalid IPFS hash');
    }

    // Set content
    async.waterfall([
      function getRegistryABI(next) {
        self.events.request('contracts:contract', "ENSRegistry", (contract) => {
          next(null, contract);
        });
      },
      function createRegistryContract(contract, next) {
        self.events.request("blockchain:contract:create",
          {abi: contract.abiDefinition, address: contract.deployedAddress},
          (resolver) => {
            next(null, resolver);
          });
      },
      function getResolverForName(registry, next) {
        registry.methods.resolver(hashedName).call((err, resolverAddress) => {
          if (err) {
            return cb(err);
          }
          if (resolverAddress === '0x0000000000000000000000000000000000000000') {
            return cb('Name not yet registered');
          }
          next(null, resolverAddress);
        });
      },
      function getResolverABI(resolverAddress, next) {
        self.events.request('contracts:contract', "Resolver", (contract) => {
          next(null, resolverAddress, contract);
        });
      },
      function createResolverContract(resolverAddress, contract, next) {
        self.events.request("blockchain:contract:create",
          {abi: contract.abiDefinition, address: resolverAddress},
          (resolver) => {
            next(null, resolver);
          });
      },
      function getDefaultAccount(resolver, next) {
        self.events.request("blockchain:defaultAccount:get", (defaultAccount) => {
          next(null, resolver, defaultAccount);
        });
      },
      function setContent(resolver, defaultAccount, next) {
        resolver.methods.setContent(hashedName, contentHash).send({from: defaultAccount}).then((transaction) => {
          if (transaction.status !== "0x1" && transaction.status !== "0x01" && transaction.status !== true) {
            return next('Association failed. Status: ' + transaction.status);
          }
          next();
        }).catch(next);
      }
    ], cb);
  }

  registerConfigDomains(config, cb) {
    const self = this;
    const register = require('./register');
    const secureSend = embarkJsUtils.secureSend;
    self.events.request("blockchain:defaultAccount:get", (defaultAccount) => {
      async.parallel([
        function createRegistryContract(paraCb) {
          self.events.request("blockchain:contract:create",
            {abi: config.registryAbi, address: config.registryAddress},
            (registry) => {
              paraCb(null, registry);
            });
        },
        function createRegistrarContract(paraCb) {
          self.events.request("blockchain:contract:create",
            {abi: config.registrarAbi, address: config.registrarAddress},
            (registrar) => {
              paraCb(null, registrar);
            });
        },
        function createResolverContract(paraCb) {
          self.events.request("blockchain:contract:create",
            {abi: config.resolverAbi, address: config.resolverAddress},
            (resolver) => {
              paraCb(null, resolver);
            });
        }
      ], function(err, contracts) {
        if (err) {
          return cb(err);
        }
        const [ens, registrar, resolver] = contracts;

        async.each(Object.keys(self.registration.subdomains), (subDomainName, eachCb) => {
          const address = self.registration.subdomains[subDomainName];
          const reverseNode = utils.soliditySha3(address.toLowerCase().substr(2) + reverseAddrSuffix);
          register(ens, registrar, resolver, defaultAccount, subDomainName, self.registration.rootDomain,
            reverseNode, address, self.logger, secureSend, eachCb);
        }, cb);

      });
    });
  }

  addENSToEmbarkJS() {
    const self = this;

    // get namehash, import it into file
    self.events.request("version:get:eth-ens-namehash", function(EnsNamehashVersion) {
      let currentEnsNamehashVersion = require('../../../package.json').dependencies["eth-ens-namehash"];
      if (EnsNamehashVersion !== currentEnsNamehashVersion) {
        self.events.request("version:getPackageLocation", "eth-ens-namehash", EnsNamehashVersion, function(err, location) {
          self.embark.registerImportFile("eth-ens-namehash", fs.dappPath(location));
        });
      }
    });

    let code = fs.readFileSync(utils.joinPath(__dirname, 'register.js')).toString();
    code += "\n" + fs.readFileSync(utils.joinPath(__dirname, 'embarkjs.js')).toString();
    code += "\nEmbarkJS.Names.registerProvider('ens', __embarkENS);";

    this.embark.addCodeToEmbarkJS(code);
  }

  configureContracts() {
    const config = {
      "default": {
        "gas": "auto",
        "contracts": {
          "ENS": {
            "deploy": false,
            "silent": true
          },
          "ENSRegistry": {
            "deploy": true,
            "silent": true,
            "args": []
          },
          "Resolver": {
            "deploy": true,
            "silent": true,
            "args": ["$ENSRegistry"]
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      },
      "ropsten": {
        "contracts": {
          "ENSRegistry": {
            "address": "0x112234455c3a32fd11230c42e7bccd4a84e02010",
            "silent": true
          },
          "Resolver": {
            "deploy": false
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      },
      "rinkeby": {
        "contracts": {
          "ENSRegistry": {
            "address": "0xe7410170f87102DF0055eB195163A03B7F2Bff4A",
            "silent": true
          },
          "Resolver": {
            "deploy": false
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      },
      "livenet": {
        "contracts": {
          "ENSRegistry": {
            "address": "0x314159265dd8dbb310642f98f50c066173c1259b",
            "silent": true
          },
          "Resolver": {
            "deploy": false
          },
          "FIFSRegistrar": {
            "deploy": false
          }
        }
      }
    };
    config.testnet = config.ropsten;

    if (this.registration && this.registration.rootDomain) {
      // Register root domain if it is defined
      if (this.isDev || this.env === 'privatenet' || this.env ==='development') {
        const rootNode = namehash.hash(this.registration.rootDomain);
        config.default.contracts['FIFSRegistrar'] = {
          "deploy": true,
          "silent": true,
          "args": ["$ENSRegistry", rootNode],
          "onDeploy": [
            `ENSRegistry.methods.setOwner('${rootNode}', web3.eth.defaultAccount).send({from: web3.eth.defaultAccount}).then(() => {
            ENSRegistry.methods.setResolver('${rootNode}', "$Resolver").send({from: web3.eth.defaultAccount});
            var reverseNode = web3.utils.soliditySha3(web3.eth.defaultAccount.toLowerCase().substr(2) + '${reverseAddrSuffix}');
            ENSRegistry.methods.setResolver(reverseNode, "$Resolver").send({from: web3.eth.defaultAccount});
            Resolver.methods.setAddr('${rootNode}', web3.eth.defaultAccount).send({from: web3.eth.defaultAccount});
            Resolver.methods.setName(reverseNode, '${this.registration.rootDomain}').send({from: web3.eth.defaultAccount});
          })`
          ]
        };
      }
    }
    config.privatenet = config.development;
    this.embark.registerContractConfiguration(config);

    if (this.isDev || this.env === 'privatenet') {
      this.embark.events.request("config:contractsFiles:add", this.embark.pathToFile('./contracts/ENSRegistry.sol'));
      this.embark.events.request("config:contractsFiles:add", this.embark.pathToFile('./contracts/FIFSRegistrar.sol'));
      this.embark.events.request("config:contractsFiles:add", this.embark.pathToFile('./contracts/Resolver.sol'));
    }
  }

  addSetProvider(config) {
    let code = "\nEmbarkJS.Names.setProvider('ens'," + JSON.stringify(config) + ");";

    let shouldInit = (namesConfig) => {
      return (namesConfig.provider === 'ens' && namesConfig.enabled === true);
    };

    this.embark.addProviderInit('names', code, shouldInit);
    this.embark.addConsoleProviderInit('names', code, shouldInit);
  }
}

module.exports = ENS;
<|endoftext|>


<commit_before>"use strict";

describe("define", function () {

    var test = {};

    before(function () {
        // Defines a namespace root
        gpf.context().test = test;
    });

    after(function () {
        delete gpf.context().test;
    });

    function _generateNamesValidation (typeName, Exception, names) {

        Object.keys(names).filter(function (name) {
            return !names[name];
        }).forEach(function (invalidName) {
            it("rejects invalid " + typeName + " name (" + invalidName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = invalidName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof Exception);
            });
        });

        Object.keys(names).filter(function (name) {
            return names[name];
        }).forEach(function (validName) {
            it("accepts valid " + typeName + " name (" + validName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = validName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(undefined === exceptionCaught);
            });
        });

    }

    function _generateBasicValidations (descriptor) {
        it(descriptor.it, function () {
            var exceptionCaught;
            try {
                gpf.define(descriptor.definition);
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof descriptor.exception);
        });
    }

    describe("gpf.define", function () {

        it("accepts only one parameter", function () {
            assert("function" === typeof gpf.define);
            assert(1 === gpf.define.length);
        });

        describe("Common validation", function () {

            _generateBasicValidations({
                it: "checks that he entity type is specified",
                definition: {},
                exception: gpf.Error.InvalidEntityType
            });

        });

        describe("Class definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("class", gpf.Error.InvalidClassName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "A": true,
                    "$B": true,
                    "_C": true,
                    "Test123": true
                });

                [{
                    it: "rejects invalid $ property names",
                    definition: {
                        $class: "Test",
                        $test: false
                    },
                    exception: gpf.Error.InvalidEntity$Property

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $class: "Test",
                        "super": false
                    },
                    exception: gpf.Error.InvalidClassProperty

                }, {
                    it: "rejects constructor property if not a method",
                    definition: {
                        $class: "Test",
                        constructor: false
                    },
                    exception: gpf.Error.InvalidClassConstructor

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var A, a;

                before(function () {
                    A = gpf.define({
                        $class: "A",
                        _member: "defaultValue",
                        getMember: function () {
                            return this._member;
                        },
                        "constructor": function (memberValue) {
                            if (memberValue) {
                                this._member = memberValue;
                            }
                            this._constructorOfA = true;
                        },
                        funcWith3params: function (p1, p2, p3) {
                            return p1 + p2 + p3;
                        },
                        throwError: function () {
                            throw new Error("error");
                        }
                    });

                    a = new A();
                });

                it("prevents constructor functions to be used without new", function () {
                    var exceptionCaught;
                    try {
                        A(); // eslint-disable-line new-cap
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.ClassConstructorFunction);
                });

                it("creates a constructor with the same signature than the constructor property", function () {
                    assert(A.length === 1);
                });

                it("handles instanceof", function () {
                    assert(a instanceof A);
                });

                it("calls constructor property", function () {
                    assert(a._constructorOfA);
                });

                it("exposes methods", function () {
                    assert("function" === typeof a.getMember);
                    assert("defaultValue" === a.getMember());
                });

                describe("Subclassing", function () {

                    it("prevents invalid override", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: A,
                                getMember: false
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassOverride);
                    });

                    var B, b;

                    before(function () {
                        B = gpf.define({
                            $class: "test.B",
                            $extend: A,
                            "constructor": function (initialValue) {
                                this.$super("valueOfB");
                                this._constructorOfB = initialValue;
                            },
                            getMember: function () {
                                return this.$super() + "-inB";
                            },
                            setMember: function (newValue) {
                                this._member = newValue;
                            },
                            baseTest: function () {
                                return this.$super.getMember();
                            },
                            invalidSuperMember: function () {
                                return this.$super.doesntExist();
                            },
                            noSuperMember: function () {
                                return this.$super();
                            },
                            differentBinding: function () {
                                return this.$super.getMember.call({
                                    _member: "different"
                                });
                            },
                            checkSignature: function () {
                                assert(this.$super.funcWith3params.length === 3);
                            },
                            throwError: function () {
                                this.$super();
                            }
                        });

                        b = new B(3475);
                    });

                    it("handles instanceof", function () {
                        assert(b instanceof A);
                        assert(b instanceof B);
                    });

                    it("handles namespace", function () {
                        assert(test.B === B);
                    });

                    it("calls the constructor function", function () {
                        assert(b._constructorOfB === 3475);
                    });

                    it("calls the proper $super()", function () {
                        assert(b._constructorOfA);
                        assert(b.getMember() === "valueOfB-inB");
                    });

                    it("offers a way to call named base method", function () {
                        assert(b.baseTest() === "valueOfB");
                    });

                    it("fails when accessing an unknown $super member", function () {
                        var exceptionCaught;
                        try {
                            b.invalidSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuperMember);
                    });

                    it("fails when accessing inexistent $super", function () {
                        var exceptionCaught;
                        try {
                            b.noSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuper);
                    });

                    it("allows calling $super member with a different binding", function () {
                        assert(b.differentBinding() === "different");
                    });

                    it("respects methods signature", function () {
                        b.checkSignature();
                    });

                    it("does not leak $super", function () {
                        assert(undefined === b.$super);
                    });

                    it("does not leak $super on exception", function () {
                        try {
                            b.throwError();
                        } catch (e) {
                            // ignore
                        }
                        assert(undefined === b.$super);
                    });

                    it("handles several versions of $super", function () {
                        var C = gpf.define({
                                $class: "C",
                                $extend: B,
                                testMethod: function () {
                                    return this.$super.getMember();
                                }
                            }),
                            c = new C();
                        assert("valueOfB-inB" === c.testMethod());
                    });
                });

            });

        });

        if (gpf.interfaces) {

            describe("Interface definition", function () {

                describe("Validation", function () {

                    _generateNamesValidation("interface", gpf.Error.InvalidInterfaceName, {
                        "1NumberAtTheBeginningIsNotOK": false,
                        "noUppercaseFirstLetterIsNotOK": false,
                        "DollarSignAnywhereIsNotOK$": false,
                        "NotStartingWithUppercaseI": false,
                        "A": false,
                        "$B": false,
                        "_C": false,
                        "Test123": false,
                        "ISample": true,
                        "IS": true
                    });

                    [{
                        it: "rejects interface if all members are not methods",
                        definition: {
                            $interface: "ITest",
                            member: false
                        },
                        exception: gpf.Error.InvalidInterfaceMember

                    }, {
                        it: "rejects invalid property names (reserved keywords)",
                        definition: {
                            $interface: "ITest",
                            "super": function () {}
                        },
                        exception: gpf.Error.InvalidInterfaceMember

                    }, {
                        it: "rejects constructor property",
                        definition: {
                            $class: "Test",
                            constructor: function () {}
                        },
                        exception: gpf.Error.InvalidInterfaceMember

                    }].forEach(_generateBasicValidations);

                });

                describe("Implementation", function () {

                    var ITest = gpf.define({
                        $interface: "ITest",
                        test: function (value) {
                            return value;
                        }
                    });

                    it("can't be used as a class extend", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: ITest
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassExtend);
                    });

                });

            });

        }

    });

});
<commit_msg>Fix error<commit_after>"use strict";

describe("define", function () {

    var test = {};

    before(function () {
        // Defines a namespace root
        gpf.context().test = test;
    });

    after(function () {
        delete gpf.context().test;
    });

    function _generateNamesValidation (typeName, Exception, names) {

        Object.keys(names).filter(function (name) {
            return !names[name];
        }).forEach(function (invalidName) {
            it("rejects invalid " + typeName + " name (" + invalidName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = invalidName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof Exception);
            });
        });

        Object.keys(names).filter(function (name) {
            return names[name];
        }).forEach(function (validName) {
            it("accepts valid " + typeName + " name (" + validName + ")", function () {
                var exceptionCaught,
                    definition = {};
                definition["$" + typeName] = validName;
                try {
                    gpf.define(definition);
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(undefined === exceptionCaught);
            });
        });

    }

    function _generateBasicValidations (descriptor) {
        it(descriptor.it, function () {
            var exceptionCaught;
            try {
                gpf.define(descriptor.definition);
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof descriptor.exception);
        });
    }

    describe("gpf.define", function () {

        it("accepts only one parameter", function () {
            assert("function" === typeof gpf.define);
            assert(1 === gpf.define.length);
        });

        describe("Common validation", function () {

            _generateBasicValidations({
                it: "checks that he entity type is specified",
                definition: {},
                exception: gpf.Error.InvalidEntityType
            });

        });

        describe("Class definition", function () {

            describe("Validation", function () {

                _generateNamesValidation("class", gpf.Error.InvalidClassName, {
                    "1NumberAtTheBeginningIsNotOK": false,
                    "noUppercaseFirstLetterIsNotOK": false,
                    "DollarSignAnywhereIsNotOK$": false,
                    "A": true,
                    "$B": true,
                    "_C": true,
                    "Test123": true
                });

                [{
                    it: "rejects invalid $ property names",
                    definition: {
                        $class: "Test",
                        $test: false
                    },
                    exception: gpf.Error.InvalidEntity$Property

                }, {
                    it: "rejects invalid property names (reserved keywords)",
                    definition: {
                        $class: "Test",
                        "super": false
                    },
                    exception: gpf.Error.InvalidClassProperty

                }, {
                    it: "rejects constructor property if not a method",
                    definition: {
                        $class: "Test",
                        constructor: false
                    },
                    exception: gpf.Error.InvalidClassConstructor

                }].forEach(_generateBasicValidations);

            });

            describe("Implementation", function () {

                var A, a;

                before(function () {
                    A = gpf.define({
                        $class: "A",
                        _member: "defaultValue",
                        getMember: function () {
                            return this._member;
                        },
                        "constructor": function (memberValue) {
                            if (memberValue) {
                                this._member = memberValue;
                            }
                            this._constructorOfA = true;
                        },
                        funcWith3params: function (p1, p2, p3) {
                            return p1 + p2 + p3;
                        },
                        throwError: function () {
                            throw new Error("error");
                        }
                    });

                    a = new A();
                });

                it("prevents constructor functions to be used without new", function () {
                    var exceptionCaught;
                    try {
                        A(); // eslint-disable-line new-cap
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.ClassConstructorFunction);
                });

                it("creates a constructor with the same signature than the constructor property", function () {
                    assert(A.length === 1);
                });

                it("handles instanceof", function () {
                    assert(a instanceof A);
                });

                it("calls constructor property", function () {
                    assert(a._constructorOfA);
                });

                it("exposes methods", function () {
                    assert("function" === typeof a.getMember);
                    assert("defaultValue" === a.getMember());
                });

                describe("Subclassing", function () {

                    it("prevents invalid override", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: A,
                                getMember: false
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassOverride);
                    });

                    var B, b;

                    before(function () {
                        B = gpf.define({
                            $class: "test.B",
                            $extend: A,
                            "constructor": function (initialValue) {
                                this.$super("valueOfB");
                                this._constructorOfB = initialValue;
                            },
                            getMember: function () {
                                return this.$super() + "-inB";
                            },
                            setMember: function (newValue) {
                                this._member = newValue;
                            },
                            baseTest: function () {
                                return this.$super.getMember();
                            },
                            invalidSuperMember: function () {
                                return this.$super.doesntExist();
                            },
                            noSuperMember: function () {
                                return this.$super();
                            },
                            differentBinding: function () {
                                return this.$super.getMember.call({
                                    _member: "different"
                                });
                            },
                            checkSignature: function () {
                                assert(this.$super.funcWith3params.length === 3);
                            },
                            throwError: function () {
                                this.$super();
                            }
                        });

                        b = new B(3475);
                    });

                    it("handles instanceof", function () {
                        assert(b instanceof A);
                        assert(b instanceof B);
                    });

                    it("handles namespace", function () {
                        assert(test.B === B);
                    });

                    it("calls the constructor function", function () {
                        assert(b._constructorOfB === 3475);
                    });

                    it("calls the proper $super()", function () {
                        assert(b._constructorOfA);
                        assert(b.getMember() === "valueOfB-inB");
                    });

                    it("offers a way to call named base method", function () {
                        assert(b.baseTest() === "valueOfB");
                    });

                    it("fails when accessing an unknown $super member", function () {
                        var exceptionCaught;
                        try {
                            b.invalidSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuperMember);
                    });

                    it("fails when accessing inexistent $super", function () {
                        var exceptionCaught;
                        try {
                            b.noSuperMember();
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassSuper);
                    });

                    it("allows calling $super member with a different binding", function () {
                        assert(b.differentBinding() === "different");
                    });

                    it("respects methods signature", function () {
                        b.checkSignature();
                    });

                    it("does not leak $super", function () {
                        assert(undefined === b.$super);
                    });

                    it("does not leak $super on exception", function () {
                        try {
                            b.throwError();
                        } catch (e) {
                            // ignore
                        }
                        assert(undefined === b.$super);
                    });

                    it("handles several versions of $super", function () {
                        var C = gpf.define({
                                $class: "C",
                                $extend: B,
                                testMethod: function () {
                                    return this.$super.getMember();
                                }
                            }),
                            c = new C();
                        assert("valueOfB-inB" === c.testMethod());
                    });
                });

            });

        });

        if (gpf.interfaces) {

            describe("Interface definition", function () {

                describe("Validation", function () {

                    _generateNamesValidation("interface", gpf.Error.InvalidInterfaceName, {
                        "1NumberAtTheBeginningIsNotOK": false,
                        "noUppercaseFirstLetterIsNotOK": false,
                        "DollarSignAnywhereIsNotOK$": false,
                        "NotStartingWithUppercaseI": false,
                        "A": false,
                        "$B": false,
                        "_C": false,
                        "Test123": false,
                        "ISample": true,
                        "IS": true
                    });

                    [{
                        it: "rejects interface if all members are not methods",
                        definition: {
                            $interface: "ITest",
                            member: false
                        },
                        exception: gpf.Error.InvalidInterfaceProperty

                    }, {
                        it: "rejects invalid property names (reserved keywords)",
                        definition: {
                            $interface: "ITest",
                            "super": function () {}
                        },
                        exception: gpf.Error.InvalidInterfaceProperty

                    }, {
                        it: "rejects constructor property",
                        definition: {
                            $class: "Test",
                            constructor: function () {}
                        },
                        exception: gpf.Error.InvalidInterfaceProperty

                    }].forEach(_generateBasicValidations);

                });

                describe("Implementation", function () {

                    var ITest = gpf.define({
                        $interface: "ITest",
                        test: function (value) {
                            return value;
                        }
                    });

                    it("can't be used as a class extend", function () {
                        var exceptionCaught;
                        try {
                            gpf.define({
                                $class: "Test",
                                $extend: ITest
                            });
                        } catch (e) {
                            exceptionCaught = e;
                        }
                        assert(exceptionCaught instanceof gpf.Error.InvalidClassExtend);
                    });

                });

            });

        }

    });

});
<|endoftext|>


<commit_before>var expect = chai.expect;

describe('fixDefine()', function () {
  it('the main fixDefine function', function () {
    expect(fixDefine).to.be.a('function');
  });

  var testGlobal = {};

  fixDefine(testGlobal);

  describe('global.define and global.require', function () {
    it('global.define', function () {
      expect(testGlobal.define).to.be.a('function');
    });

    it('global.require', function () {
      expect(testGlobal.require).to.be.a('function');
    });

  });
});
<commit_msg>fix the test reference to definejs<commit_after>var expect = chai.expect;

describe('definejs()', function () {
  it('the main definejs function', function () {
    expect(definejs).to.be.a('function');
  });

  var testGlobal = {};

  definejs(testGlobal);

  describe('global.define and global.require', function () {
    it('global.define', function () {
      expect(testGlobal.define).to.be.a('function');
    });

    it('global.require', function () {
      expect(testGlobal.require).to.be.a('function');
    });

  });
});
<|endoftext|>


<commit_before>
/*
 * @list dependencies
 */

var async = require('async');

/*
 * @method paginate
 * @param {Object} query Mongoose Query Object
 * @param {Number} pageNumber
 * @param {Number} resultsPerPage
 * Extend Mongoose Models to paginate queries
 */

function paginate(q, pageNumber, resultsPerPage, callback, options) {
  var model = this;
  options = options || {};
  columns = options.columns || null;
  sortBy = options.sortBy || {
    _id : 1
  };
  populate = options.populate || null;
  callback = callback || function() {};
  skipFrom = (pageNumber * resultsPerPage) - resultsPerPage;
  query = model.find(q);
  if (columns !== null) {
    query = query.select(options.columns);
  }
  query = query.skip(skipFrom).limit(resultsPerPage).sort(sortBy);
  if (populate) {
    query = query.populate(populate);
  }
  async.parallel({
    results: function(callback) {
      query.exec(callback);
    },
    count: function(callback) {
      model.count(q, function(err, count) {
        callback(err, count);
      })
    }
  }, function(error, data) {
    if (error) {
      return callback(error);
    }
    callback(null, Math.ceil(data.count / resultsPerPage) || 1, data.results, data.count);
  });
}

module.exports = function(schema) {
  schema.statics.paginate = paginate;
}
<commit_msg>[minor] format shit<commit_after>
/*
 * @list dependencies
 */

var async = require('async');

/*
 * @method paginate
 * @param {Object} query Mongoose Query Object
 * @param {Number} pageNumber
 * @param {Number} resultsPerPage
 * Extend Mongoose Models to paginate queries
 */

function paginate(q, pageNumber, resultsPerPage, callback, options) {
  var query, skipFrom, sortBy, columns, populate, model = this;
  options = options || {};
  columns = options.columns || null;
  sortBy = options.sortBy || {
    _id : 1
  };
  populate = options.populate || null;
  callback = callback || function() {};
  skipFrom = (pageNumber * resultsPerPage) - resultsPerPage;
  query = model.find(q);
  if (columns !== null) {
    query = query.select(options.columns);
  }
  query = query.skip(skipFrom).limit(resultsPerPage).sort(sortBy);
  if (populate) {
    query = query.populate(populate);
  }
  async.parallel({
    results: function(callback) {
      query.exec(callback);
    },
    count: function(callback) {
      model.count(q, function(err, count) {
        callback(err, count);
      })
    }
  }, function(error, data) {
    if (error) {
      return callback(error);
    }
    callback(null, Math.ceil(data.count / resultsPerPage) || 1, data.results, data.count);
  });
}

module.exports = function(schema) {
  schema.statics.paginate = paginate;
}
<|endoftext|>


<commit_before>/* global describe it beforeEach */
'use strict'

const chai = require('chai')
const requireInject = require('require-inject')
const sinon = require('sinon')

const expect = chai.expect

describe('getSemverTags', function () {
  let stubs
  let exec

  beforeEach('create stubs', function () {
    exec = sinon.stub()
    stubs = {}
    stubs[require.resolve('../lib/util')] = { exec }
  })

  it('returns semver tags only in an array', function () {
    exec.returns(new Buffer('v1.0.0\nnot-semver\nv0.2.1\nv0.2.0\nv0.1.0\n'))
    const github = requireInject('../lib/github', stubs)

    const tags = github.getSemverTags()
    expect(tags).to.deep.equal(['v1.0.0', 'v0.2.1', 'v0.2.0', 'v0.1.0'])
  })

  it('returns empty array when no tags found', function () {
    exec.returns(new Buffer('not-semver\n'))
    const github = requireInject('../lib/github', stubs)

    const tags = github.getSemverTags()
    expect(tags).to.deep.equal([])
  })
})

describe('getMergeCommits', function () {
  let stubs
  let exec

  beforeEach('create stubs', function () {
    exec = sinon.stub()
    stubs = {}
    stubs[require.resolve('../lib/util')] = { exec }
  })

  it('returns one commit per line', function () {
    exec.returns(new Buffer('commit 1\ncommit 2\n'))
    const github = requireInject('../lib/github', stubs)

    expect(github.getMergeCommits('a..b'))
      .to.deep.equal(['commit 1', 'commit 2'])
  })

  it('returns empty array when no commits are found', function () {
    exec.returns(new Buffer(''))
    const github = requireInject('../lib/github', stubs)

    expect(github.getMergeCommits('a..b')).to.deep.equal([])
  })
})

describe('getPRs', function () {
  const getPRs = require('../lib/github').getPRs

  it('filters commits with PRs', function () {
    const prs = getPRs([
      'this is a commit',
      'Merge pull request #42 from ',
      'this is another commit'
    ])
    expect(prs).to.deep.equal([42])
  })

  it('return empty array when no commits have been passed', function () {
    const prs = getPRs([])
    expect(prs).to.deep.equal([])
  })
})

describe('writeComment', function () {
  let stubs
  let createComment
  let logger
  const pr = 42

  beforeEach('create stubs', function () {
    createComment = sinon.stub()
    logger = {
      debug: sinon.stub(),
      error: sinon.stub()
    }
    stubs = {
      ghissues: {
        createComment
      }
    }
    stubs[require.resolve('../lib/logging')] = {
      logger
    }
  })

  it('writes comment object to log on success', function () {
    createComment.callsArgWith(5, undefined, '<comment object>')
    const github = requireInject('../lib/github', stubs)

    github.writeComment('auth data', 'user', 'project', pr, 'comment')
    expect(logger.debug).to.have.been.calledWith('Comment: %s', '<comment object>')
  })

  it('writes error to log on failure', function () {
    const expectedError = new Error('some error')
    createComment.callsArgWith(5, expectedError, undefined)
    const github = requireInject('../lib/github', stubs)

    github.writeComment('auth data', 'user', 'project', pr, 'comment')
    expect(logger.error).to.have.been.calledWith(
      'Error adding comment to PR#%d: %s', pr, expectedError)
  })
})
<commit_msg>Update writeComment test cases<commit_after>/* global describe it beforeEach */
'use strict'

const chai = require('chai')
const requireInject = require('require-inject')
const sinon = require('sinon')

const expect = chai.expect

describe('getSemverTags', function () {
  let stubs
  let exec

  beforeEach('create stubs', function () {
    exec = sinon.stub()
    stubs = {}
    stubs[require.resolve('../lib/util')] = { exec }
  })

  it('returns semver tags only in an array', function () {
    exec.returns(new Buffer('v1.0.0\nnot-semver\nv0.2.1\nv0.2.0\nv0.1.0\n'))
    const github = requireInject('../lib/github', stubs)

    const tags = github.getSemverTags()
    expect(tags).to.deep.equal(['v1.0.0', 'v0.2.1', 'v0.2.0', 'v0.1.0'])
  })

  it('returns empty array when no tags found', function () {
    exec.returns(new Buffer('not-semver\n'))
    const github = requireInject('../lib/github', stubs)

    const tags = github.getSemverTags()
    expect(tags).to.deep.equal([])
  })
})

describe('getMergeCommits', function () {
  let stubs
  let exec

  beforeEach('create stubs', function () {
    exec = sinon.stub()
    stubs = {}
    stubs[require.resolve('../lib/util')] = { exec }
  })

  it('returns one commit per line', function () {
    exec.returns(new Buffer('commit 1\ncommit 2\n'))
    const github = requireInject('../lib/github', stubs)

    expect(github.getMergeCommits('a..b'))
      .to.deep.equal(['commit 1', 'commit 2'])
  })

  it('returns empty array when no commits are found', function () {
    exec.returns(new Buffer(''))
    const github = requireInject('../lib/github', stubs)

    expect(github.getMergeCommits('a..b')).to.deep.equal([])
  })
})

describe('getPRs', function () {
  const getPRs = require('../lib/github').getPRs

  it('filters commits with PRs', function () {
    const prs = getPRs([
      'this is a commit',
      'Merge pull request #42 from ',
      'this is another commit'
    ])
    expect(prs).to.deep.equal([42])
  })

  it('return empty array when no commits have been passed', function () {
    const prs = getPRs([])
    expect(prs).to.deep.equal([])
  })
})

describe('writeComment', function () {
  let stubs
  let logger
  const pr = 42

  beforeEach('create stubs', function () {
    logger = {
      debug: sinon.stub(),
      error: sinon.stub()
    }
    stubs = {
      ghissues: {}
    }
    stubs[require.resolve('../lib/logging')] = {
      logger
    }
  })

  it('writes comment object to log on success', function (done) {
    const expected = '<comment object>'
    stubs.ghissues.createComment = function (
        authData, user, project, pr, comment, cb) {
      cb(null, expected)
    }
    const github = requireInject('../lib/github', stubs)

    github.writeComment('auth data', 'user', 'project', pr, 'comment').then(
      function () {
        expect(logger.debug).to.have.been.calledWith('Comment: %s', expected)
        done()
      })
  })

  it('writes error to log on failure', function (done) {
    const expected = new Error('some error')
    stubs.ghissues.createComment = function (
        authData, user, project, pr, comment, cb) {
      cb(expected, null)
    }
    const github = requireInject('../lib/github', stubs)

    github.writeComment('auth data', 'user', 'project', pr, 'comment').then(
      function () {
        expect(logger.error).to.have.been.calledWith(
          'Error adding comment to PR#%d: %s', pr, expected)
        done()
      })
  })
})
<|endoftext|>


<commit_before>// test globals
assert = require('assert');
debug = require('debug')('strong-supervisor:test');
fs = require('fs');
path = require('path');
shell = require('shelljs/global');
util = require('util');

// module locals
var child = require('child_process');
var dgram = require('dgram');

// Skip when run by mocha
exports.skip = function skip() {
  if ('describe' in global) {
    describe(module.parent.filename, function() {
      it.skip('run test with tap, not mocha', function(){});
    });
    return true;
  }
}

// Assert if test does not explicitly say it passed, guards against accidental
// exit with `0`.
exports.pass = false;

process.on('exit', function(status) {
  if (status === 0) {
    assert(exports.pass);
    console.log('PASS');
  }
});

// Utility functions

exports.statsd = function statsd(callback) {
  var server = dgram.createSocket('udp4');
  server.reported = [];

  server.on('message', function(data) {
    console.log('statsd receives metric: %s', data);
    server.reported.push(data.toString());
  });

  server.bind(listening);

  server.waitfor = function(regex, callback) {
    waitForStats();

    function waitForStats() {
      function found(stat) {
        return regex.test(stat);
      }

      if (server.reported.some(found)) {
        return callback();
      }

      setTimeout(waitForStats, 2000);
    }
  };

  function listening(er) {
    console.log('statsd listening:', er || server.address());
    assert.ifError(er);
    server.port = server.address().port;
    return callback(server);
  }
}

exports.runCtl = {
  supervise: supervise,
  waiton: waiton,
  expect: expect,
  failon: failon,
};

// run supervisor
function supervise(app, args) {
  var run = require.resolve('../bin/sl-run');
  var ctl = path.join(app, '..', 'runctl');
  try {
    fs.unlinkSync(ctl);
  } catch(er) {
    console.log('no `%s` to cleanup: %s', ctl, er);
  }

  args = ['--cluster=0'].concat(args || []).concat([app]);

  console.log('supervise %s with %j', run, args);

  var c = child.fork(run, args);

  // don't let it live longer than us!
  // XXX(sam) once sl-runctl et. al. self-exit on loss of parent, we
  // won't need this, but until then...
  process.on('exit', c.kill.bind(c));
  function die() {
    c.kill();
    process.kill(process.pid, 'SIGTERM');
  }
  process.once('SIGTERM', die);
  process.once('SIGINT', die);

  return c;
}

// Wait on cmd to write specific output
function waiton(cmd, output) {
  while (true) {
    try {
      expect(cmd, output);
      return;
    } catch(er) {
      pause();
    }
  }
}

// Expect cmd to succeed and write specific output
function expect(cmd, output) {
  var out = runctl(cmd);

  assert.equal(out.code, 0);

  if (output) {
    assert(output.test(out.output), output);
  }
}

// Expect cmd to fail and write specific output
function failon(cmd, output) {
  var out = runctl(cmd);

  assert.notEqual(out.code, 0);

  if (output) {
    assert(output.test(out.output), output);
  }
}

function runctl(cmd) {
  var out = exec(util.format(
    '%s %s',
    require.resolve('../bin/sl-runctl'),
    cmd || ''
  ));
  console.log('runctl %s =>', cmd, out);
  return out;
}

function pause(secs) {
  var secs = secs || 1;
  var start = process.hrtime();
  while (true) {
    var ts = process.hrtime(start);
    if (ts[0] >= secs)
      return;
  }
}

global.pause = pause;
<commit_msg>test: don't let tap guard kill mocha<commit_after>// test globals
assert = require('assert');
debug = require('debug')('strong-supervisor:test');
fs = require('fs');
path = require('path');
shell = require('shelljs/global');
util = require('util');

// module locals
var child = require('child_process');
var dgram = require('dgram');

// Skip when run by mocha
exports.skip = function skip() {
  if ('describe' in global) {
    describe(module.parent.filename, function() {
      it.skip('run test with tap, not mocha', function(){});
    });
    return true;
  }
}

// Assert if test does not explicitly say it passed, guards against accidental
// exit with `0`.
exports.pass = false;

process.on('exit', function(status) {
  if (require.main == module && status === 0) {
    assert(exports.pass);
    console.log('PASS');
  }
});

// Utility functions

exports.statsd = function statsd(callback) {
  var server = dgram.createSocket('udp4');
  server.reported = [];

  server.on('message', function(data) {
    console.log('statsd receives metric: %s', data);
    server.reported.push(data.toString());
  });

  server.bind(listening);

  server.waitfor = function(regex, callback) {
    waitForStats();

    function waitForStats() {
      function found(stat) {
        return regex.test(stat);
      }

      if (server.reported.some(found)) {
        return callback();
      }

      setTimeout(waitForStats, 2000);
    }
  };

  function listening(er) {
    console.log('statsd listening:', er || server.address());
    assert.ifError(er);
    server.port = server.address().port;
    return callback(server);
  }
}

exports.runCtl = {
  supervise: supervise,
  waiton: waiton,
  expect: expect,
  failon: failon,
};

// run supervisor
function supervise(app, args) {
  var run = require.resolve('../bin/sl-run');
  var ctl = path.join(app, '..', 'runctl');
  try {
    fs.unlinkSync(ctl);
  } catch(er) {
    console.log('no `%s` to cleanup: %s', ctl, er);
  }

  args = ['--cluster=0'].concat(args || []).concat([app]);

  console.log('supervise %s with %j', run, args);

  var c = child.fork(run, args);

  // don't let it live longer than us!
  // XXX(sam) once sl-runctl et. al. self-exit on loss of parent, we
  // won't need this, but until then...
  process.on('exit', c.kill.bind(c));
  function die() {
    c.kill();
    process.kill(process.pid, 'SIGTERM');
  }
  process.once('SIGTERM', die);
  process.once('SIGINT', die);

  return c;
}

// Wait on cmd to write specific output
function waiton(cmd, output) {
  while (true) {
    try {
      expect(cmd, output);
      return;
    } catch(er) {
      pause();
    }
  }
}

// Expect cmd to succeed and write specific output
function expect(cmd, output) {
  var out = runctl(cmd);

  assert.equal(out.code, 0);

  if (output) {
    assert(output.test(out.output), output);
  }
}

// Expect cmd to fail and write specific output
function failon(cmd, output) {
  var out = runctl(cmd);

  assert.notEqual(out.code, 0);

  if (output) {
    assert(output.test(out.output), output);
  }
}

function runctl(cmd) {
  var out = exec(util.format(
    '%s %s',
    require.resolve('../bin/sl-runctl'),
    cmd || ''
  ));
  console.log('runctl %s =>', cmd, out);
  return out;
}

function pause(secs) {
  var secs = secs || 1;
  var start = process.hrtime();
  while (true) {
    var ts = process.hrtime(start);
    if (ts[0] >= secs)
      return;
  }
}

global.pause = pause;
<|endoftext|>


<commit_before>"use strict";

function _getDb() {
    return new Promise((resolve, reject) => {
        let factory = require('mongo-factory');
        factory.getConnection(process.env.DB_CONNECTIONSTRING)
            .then(dbInstance => {
                resolve(dbInstance);
            })
            .catch(e => {
                reject(e);
            });
    });
}

module.exports = {
    getDb: _getDb,

    getManager: function (ManagerType) {
        return _getDb()
            .then(db => {
                return Promise.resolve(new ManagerType(db, {
                    username: "dev"
                }));
            })
    }
}<commit_msg>update helper<commit_after>"use strict";

function _getDb() {
    return new Promise((resolve, reject) => {
        let factory = require('mongo-factory');
        factory.getConnection(process.env.DB_CONNECTIONSTRING)
            .then(dbInstance => {
                dbInstance.use = dbInstance.use ||((collectionName) => {
                    return dbInstance.collection(collectionName)
                });
                resolve(dbInstance);
            })
            .catch(e => {
                reject(e);
            });
    });
}

module.exports = {
    getDb: _getDb,

    getManager: function (ManagerType) {
        return _getDb()
            .then(db => {
                return Promise.resolve(new ManagerType(db, {
                    username: "dev"
                }));
            })
    }
}<|endoftext|>