<commit_before>var oo = require('../utils/oo');

var Helpers = {};

/******************************************************************************
 * DEFINITIONS
 */

var SELECT_DEF          = { type: 'select', container: true }
  , LABEL_DEF           = { type: 'label', container: true }
  , TEXT_AREA_DEF       = { type: 'textaarea', container: true, attributes : { class: 'input' } }
  , TEXT_FIELD_DEF      = { type: 'input', attributes: { type: 'text', class: 'text-field input' } }
  , PASSWORD_FIELD_DEF  = { type: 'input', attributes: { type: 'password', class: 'input password-field'  } }
  , HIDDEN_FIELD_DEF    = { type: 'input', noId: true, attributes: { type: 'hidden' } }
  , RADIO_BUTTON_DEF    = { type: 'input', attributes: { type: 'radio', class: 'input radio-button'  } }
  , CHECK_BOX_DEF       = { type: 'input', attributes: { type: 'checkbox', class: 'input check-box'  } }
  , FILE_FIELD_DEF      = { type: 'input', attributes: { type: 'file', class: 'input file-field' } }
  , SUBMIT_DEF          = { type: 'input', noName: true, attributes: { type: 'submit', name: 'commit', class: 'submit' } }
  , LINK_DEF            = { type: 'a', noName: true, container: true}
  ;

var schemaToForm = {
    Boolean:      {type: 'check_box'      , attributes: {class: ['Boolean']}}
  , String:       {type: 'text_field'}
  , Email:        {type: 'text_field'     , attributes: {class: ['Email'], placeholder: 'Email Address'}}
  , Password:     {type: 'password_field' , attributes: {class: ['Password'], placeholder: 'Password'}}
  , AlphaNumeric: {type: 'text_field'     , attributes: {class: ['AlphaNumeric']}}
  , Number:       {type: 'text_field'     , attributes: {class: ['Number']}}
  , Float:        {type: 'text_field'     , attributes: {class: ['Number', 'Float']}}
  , Integer:      {type: 'text_field'     , attributes: {class: ['Number', 'Integer']}}
  , Date:         {type: 'text_field'     , attributes: {class: ['Date']}}
  , DateTime:     {type: 'text_field'     , attributes: {class: ['Date','DateTime']}}
  , Time:         {type: 'text_field'     , attributes: {class: ['Time']}}
  , Text:         {type: 'text_area'      , attributes: {class: ['Text']}}
  , Url:          {type: 'text_field'     , attributes: {class: ['Url']}}
  };

/******************************************************************************
 * MODEL FORM TAGS FACTORY
 */

var createModelFormTags = function(model) {

  var modelFormTags = {  /* ALL functions except `input` are lazy wrapped for optimizations */
      select          : function(){ return (createTaghelper(oo.__extends( SELECT_DEF          , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , label           : function(){ return (createTagHelper(oo.__extends( LABEL_DEF           , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , text_field      : function(){ return (createTagHelper(oo.__extends( TEXT_FIELD_DEF      , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , text_area       : function(){ return (createTagHelper(oo.__extends( TEXT_AREA_DEF       , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , password_field  : function(){ return (createTagHelper(oo.__extends( PASSWORD_FIELD_DEF  , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , hidden_field    : function(){ return (createTagHelper(oo.__extends( HIDDEN_FIELD_DEF    , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , radio_button    : function(){ return (createTagHelper(oo.__extends( RADIO_BUTTON_DEF    , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , check_box       : function(){ return (createTagHelper(oo.__extends( CHECK_BOX_DEF       , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , file_field      : function(){ return (createTagHelper(oo.__extends( FILE_FIELD_DEF      , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , input           : function input_form_for_helper(name, attributes) {
        var schema = model.schema
          , field_type = undefined
          ;

        if(typeof schema[name] !== 'undefined' && schema[name] !== null) {
          if(typeof schema[name] === 'string') {
            field_type = schema[name];
          }else if(typeof schema[name] === 'object' && typeof schema[name].validate === 'string') {
            field_type = schema[name].validate;
          }
        }else{
          throw 'Unable to find field `' + name + '` in model `' + model.name + '.schema`';
        }

        var field_def = schemaToForm[field_type] || {type: 'text_field', attributes: {class: 'unknownModelField'}};

        return modelFormTags[field_def.type](oo.__deepExtends(attributes, '', field_def.attributes, {copyOnWrite: true}));
      }
    };
  oo.__extends(modelFormTags, formTags);

};

/******************************************************************************
 * FORM TAGS HELPERS
 */

var formTags = {
    link_tag            : createTagHelper(LINK_DEF)
  , select_tag          : createTagHelper(SELECT_DEF)
  , label_tag           : createTagHelper(LABEL_DEF)
  , text_field_tag      : createTagHelper(TEXT_FIELD_DEF)
  , text_area_tag       : createTagHelper(TEXT_AREA_DEF)
  , password_field_tag  : createTagHelper(PASSWORD_FIELD_DEF)
  , hidden_field_tag    : createTagHelper(HIDDEN_FIELD_DEF)
  , radio_button_tag    : createTagHelper(RADIO_BUTTON_DEF)
  , check_box_tag       : createTagHelper(CHECK_BOX_DEF)
  , file_field_tag      : createTagHelper(FILE_FIELD_DEF)
  , submit_tag          : createTagHelper(SUBMIT_DEF)
  , options_for_select  : function options_for_select(options, selected_idx) {
      var html = '';
      for(var i = 0, len = options.length; i < len; i++) {

        text += '<option value="' + options[i][1] + '"';

        if(typeof selected_idx !== 'undefined' && selected_idx !== null) {
          text += ' selected="selected"';
        }

        text += '>' + options[i][0] + '</option>';
      }
      return html;
    }
  };

oo.__extends(this, formTags);

/******************************************************************************
 * FORM TAGS HELPERS FACTORY
 */

function createTagHelper(options) {
  return function(/*name, content | value , attributes*/) {
    var tag_type = options.type
      , tag = ''
      , all_attributes = {}
      , content = ''
      , attributes = {}
      ;

    //if the tag_type is 'label' put attributes.for = name
    if(tag_type === 'label'){
      all_attributes['for'] = (options.model_name ? model_name + '_' + arguments[0] : arguments[0]);
      all_attributes['class'] = all_attributes['for'];
      content = arguments[1] || content;
      attributes =  arguments[2] || attributes;
    }else{
    //else set attr.id = attr.name attr = name (in the attributes obj)
      if(!options.noName) {

        all_attributes['name'] = (options.model_name ? model_name + '[' + arguments[0] + ']' : arguments[0]);

        if(!options.noId) {
          attributes['id'] = (options.model_name ? model_name + '_' + arguments[0] : arguments[0]);
          attributes['class'] += ' ' + (options.model_name ? model_name + '_' + arguments[0] : arguments[0]);
        }

        content = arguments[1] || content;
        attributes =  arguments[2] || attributes;

      }else{
        content = arguments[0] || content;
        attributes =  arguments[1] || attributes;
      }
    }

    if(options.attributes) {
      oo.__extends(all_attributes, options.attributes, {overwrite: true});
    }

    if(options.attributes &&  options.attributes['class'] && attributes['class']) {
      all_attributes['class'] += ' ' + attributes['class'];
      delete attributes['class'];
    }

    if(attributes) {
      oo.__extends(all_attributes, attributes, {overwrite: true});
    }

    if(!options.container) {
      all_attributes['value'] = content;
    }

    tag += '<' + tag_type;

    //add all attributes to the (opening) tag
    for(var attr in all_attributes) {
      tag += ' ' + attr + '="' + all_attributes[attr].toString() + '"';
    }

    if(options.container) {
      //close opening tag
      tag += '>';

      //add content
      tag += content;

      //add closing tag
      tag += '</' + tag_type + '>';

    }else{
      //close tag
      tag += ' />';
    }
    //return tag
    this.content = (this.content ? this.content : '') + tag;
  };
}

/******************************************************************************
 * form_tag helper
 */

var __form_tag = createTagHelper({type: 'form', noName: true, container: true});

function ContentObj() {}
oo.__extends(ContentObj.prototype, formTags);

Helpers.form_tag = function form_tag(/* route, (attributes,) content_fun */) {

  var route = arguments[0]
    , attributes = (arguments.length === 3 ? arguments[1] : {})|| {}/* OPTIONAL */
    , content_fun = (arguments.length === 3 ? arguments[2] : arguments[1])
    , contentObj = new ContentObj();
    ;

  attributes.method = attributes.method || 'POST';
  attributes.action = (typeof route === 'string' ? route : link_to(route));

  content_fun.toString();
  content_fun.call(contentObj);
  return (new __form_tag(contentObj.content, attributes)).content;
};

/******************************************************************************
 * form_for helper
 */
Helpers.form_for = function form_for(/* model, route, (attributes,) content_fun */) {

  var model = arguments[0]
    , route = arguments[1]
    , attributes = (arguments.length === 4 ? arguments[2] : {}) /* OPTIONAL */
    , content_fun = (arguments.length === 4 ? arguments[3] : arguments[2])
    /***/
    , modelFormTags = createModelFormTags(model)
    , model_content_fun = function() { return content_fun(modelFormTags); }
    ;

  return form_tag(route, attributes, model_content_fun);
};

//export Helpers;
module.exports = Helpers;
<commit_msg>removed unused toString()<commit_after>var oo = require('../utils/oo');

var Helpers = {};

/******************************************************************************
 * DEFINITIONS
 */

var SELECT_DEF          = { type: 'select', container: true }
  , LABEL_DEF           = { type: 'label', container: true }
  , TEXT_AREA_DEF       = { type: 'textaarea', container: true, attributes : { class: 'input' } }
  , TEXT_FIELD_DEF      = { type: 'input', attributes: { type: 'text', class: 'text-field input' } }
  , PASSWORD_FIELD_DEF  = { type: 'input', attributes: { type: 'password', class: 'input password-field'  } }
  , HIDDEN_FIELD_DEF    = { type: 'input', noId: true, attributes: { type: 'hidden' } }
  , RADIO_BUTTON_DEF    = { type: 'input', attributes: { type: 'radio', class: 'input radio-button'  } }
  , CHECK_BOX_DEF       = { type: 'input', attributes: { type: 'checkbox', class: 'input check-box'  } }
  , FILE_FIELD_DEF      = { type: 'input', attributes: { type: 'file', class: 'input file-field' } }
  , SUBMIT_DEF          = { type: 'input', noName: true, attributes: { type: 'submit', name: 'commit', class: 'submit' } }
  , LINK_DEF            = { type: 'a', noName: true, container: true}
  ;

var schemaToForm = {
    Boolean:      {type: 'check_box'      , attributes: {class: ['Boolean']}}
  , String:       {type: 'text_field'}
  , Email:        {type: 'text_field'     , attributes: {class: ['Email'], placeholder: 'Email Address'}}
  , Password:     {type: 'password_field' , attributes: {class: ['Password'], placeholder: 'Password'}}
  , AlphaNumeric: {type: 'text_field'     , attributes: {class: ['AlphaNumeric']}}
  , Number:       {type: 'text_field'     , attributes: {class: ['Number']}}
  , Float:        {type: 'text_field'     , attributes: {class: ['Number', 'Float']}}
  , Integer:      {type: 'text_field'     , attributes: {class: ['Number', 'Integer']}}
  , Date:         {type: 'text_field'     , attributes: {class: ['Date']}}
  , DateTime:     {type: 'text_field'     , attributes: {class: ['Date','DateTime']}}
  , Time:         {type: 'text_field'     , attributes: {class: ['Time']}}
  , Text:         {type: 'text_area'      , attributes: {class: ['Text']}}
  , Url:          {type: 'text_field'     , attributes: {class: ['Url']}}
  };

/******************************************************************************
 * MODEL FORM TAGS FACTORY
 */

var createModelFormTags = function(model) {

  var modelFormTags = {  /* ALL functions except `input` are lazy wrapped for optimizations */
      select          : function(){ return (createTaghelper(oo.__extends( SELECT_DEF          , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , label           : function(){ return (createTagHelper(oo.__extends( LABEL_DEF           , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , text_field      : function(){ return (createTagHelper(oo.__extends( TEXT_FIELD_DEF      , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , text_area       : function(){ return (createTagHelper(oo.__extends( TEXT_AREA_DEF       , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , password_field  : function(){ return (createTagHelper(oo.__extends( PASSWORD_FIELD_DEF  , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , hidden_field    : function(){ return (createTagHelper(oo.__extends( HIDDEN_FIELD_DEF    , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , radio_button    : function(){ return (createTagHelper(oo.__extends( RADIO_BUTTON_DEF    , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , check_box       : function(){ return (createTagHelper(oo.__extends( CHECK_BOX_DEF       , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , file_field      : function(){ return (createTagHelper(oo.__extends( FILE_FIELD_DEF      , {model_name: model.name}  , {copyOnWrite: true}))).apply(this, arguments); }
    , input           : function input_form_for_helper(name, attributes) {
        var schema = model.schema
          , field_type = undefined
          ;

        if(typeof schema[name] !== 'undefined' && schema[name] !== null) {
          if(typeof schema[name] === 'string') {
            field_type = schema[name];
          }else if(typeof schema[name] === 'object' && typeof schema[name].validate === 'string') {
            field_type = schema[name].validate;
          }
        }else{
          throw 'Unable to find field `' + name + '` in model `' + model.name + '.schema`';
        }

        var field_def = schemaToForm[field_type] || {type: 'text_field', attributes: {class: 'unknownModelField'}};

        return modelFormTags[field_def.type](oo.__deepExtends(attributes, '', field_def.attributes, {copyOnWrite: true}));
      }
    };
  oo.__extends(modelFormTags, formTags);

};

/******************************************************************************
 * FORM TAGS HELPERS
 */

var formTags = {
    link_tag            : createTagHelper(LINK_DEF)
  , select_tag          : createTagHelper(SELECT_DEF)
  , label_tag           : createTagHelper(LABEL_DEF)
  , text_field_tag      : createTagHelper(TEXT_FIELD_DEF)
  , text_area_tag       : createTagHelper(TEXT_AREA_DEF)
  , password_field_tag  : createTagHelper(PASSWORD_FIELD_DEF)
  , hidden_field_tag    : createTagHelper(HIDDEN_FIELD_DEF)
  , radio_button_tag    : createTagHelper(RADIO_BUTTON_DEF)
  , check_box_tag       : createTagHelper(CHECK_BOX_DEF)
  , file_field_tag      : createTagHelper(FILE_FIELD_DEF)
  , submit_tag          : createTagHelper(SUBMIT_DEF)
  , options_for_select  : function options_for_select(options, selected_idx) {
      var html = '';
      for(var i = 0, len = options.length; i < len; i++) {

        text += '<option value="' + options[i][1] + '"';

        if(typeof selected_idx !== 'undefined' && selected_idx !== null) {
          text += ' selected="selected"';
        }

        text += '>' + options[i][0] + '</option>';
      }
      return html;
    }
  };

oo.__extends(this, formTags);

/******************************************************************************
 * FORM TAGS HELPERS FACTORY
 */

function createTagHelper(options) {
  return function(/*name, content | value , attributes*/) {
    var tag_type = options.type
      , tag = ''
      , all_attributes = {}
      , content = ''
      , attributes = {}
      ;

    //if the tag_type is 'label' put attributes.for = name
    if(tag_type === 'label'){
      all_attributes['for'] = (options.model_name ? model_name + '_' + arguments[0] : arguments[0]);
      all_attributes['class'] = all_attributes['for'];
      content = arguments[1] || content;
      attributes =  arguments[2] || attributes;
    }else{
    //else set attr.id = attr.name attr = name (in the attributes obj)
      if(!options.noName) {

        all_attributes['name'] = (options.model_name ? model_name + '[' + arguments[0] + ']' : arguments[0]);

        if(!options.noId) {
          attributes['id'] = (options.model_name ? model_name + '_' + arguments[0] : arguments[0]);
          attributes['class'] += ' ' + (options.model_name ? model_name + '_' + arguments[0] : arguments[0]);
        }

        content = arguments[1] || content;
        attributes =  arguments[2] || attributes;

      }else{
        content = arguments[0] || content;
        attributes =  arguments[1] || attributes;
      }
    }

    if(options.attributes) {
      oo.__extends(all_attributes, options.attributes, {overwrite: true});
    }

    if(options.attributes &&  options.attributes['class'] && attributes['class']) {
      all_attributes['class'] += ' ' + attributes['class'];
      delete attributes['class'];
    }

    if(attributes) {
      oo.__extends(all_attributes, attributes, {overwrite: true});
    }

    if(!options.container) {
      all_attributes['value'] = content;
    }

    tag += '<' + tag_type;

    //add all attributes to the (opening) tag
    for(var attr in all_attributes) {
      tag += ' ' + attr + '="' + all_attributes[attr].toString() + '"';
    }

    if(options.container) {
      //close opening tag
      tag += '>';

      //add content
      tag += content;

      //add closing tag
      tag += '</' + tag_type + '>';

    }else{
      //close tag
      tag += ' />';
    }
    //return tag
    this.content = (this.content ? this.content : '') + tag;
  };
}

/******************************************************************************
 * form_tag helper
 */

var __form_tag = createTagHelper({type: 'form', noName: true, container: true});

function ContentObj() {}
oo.__extends(ContentObj.prototype, formTags);

Helpers.form_tag = function form_tag(/* route, (attributes,) content_fun */) {

  var route = arguments[0]
    , attributes = (arguments.length === 3 ? arguments[1] : {})|| {}/* OPTIONAL */
    , content_fun = (arguments.length === 3 ? arguments[2] : arguments[1])
    , contentObj = new ContentObj();
    ;

  attributes.method = attributes.method || 'POST';
  attributes.action = (typeof route === 'string' ? route : link_to(route));

  content_fun.call(contentObj, contentObj);

  return (new __form_tag(contentObj.content, attributes)).content;

};

/******************************************************************************
 * form_for helper
 */
Helpers.form_for = function form_for(/* model, route, (attributes,) content_fun */) {

  var model = arguments[0]
    , route = arguments[1]
    , attributes = (arguments.length === 4 ? arguments[2] : {}) /* OPTIONAL */
    , content_fun = (arguments.length === 4 ? arguments[3] : arguments[2])
    /***/
    , modelFormTags = createModelFormTags(model)
    , model_content_fun = function() { return content_fun(modelFormTags); }
    ;

  return form_tag(route, attributes, model_content_fun);
};

//export Helpers;
module.exports = Helpers;
<|endoftext|>


<commit_before>var {NativeModules} = require('react-native');
var ReactCBLite = NativeModules.ReactCBLite;

var base64 = require('base-64')
  , events = require('events');

var CHANGE_EVENT_TYPE = 'changes';

var manager = function (databaseUrl, databaseName) {
  this.authHeader = "Basic " + base64.encode(databaseUrl.split("//")[1].split('@')[0]);
  this.databaseUrl = databaseUrl;
  this.databaseName = databaseName;
  this.changesEventEmitter = new events.EventEmitter();
};

/**
 * Wrapper around the CBL rest API.
 *
 * See: http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/database/index.html
 */
manager.prototype = {

  /**
   * Construct a new Couchbase object given a database URL and database name
   *
   * @returns {*|promise}
   */
  createDatabase: function () {
    return this.makeRequest("PUT", this.databaseUrl + this.databaseName, null, null);
  },

  /**
   * Delete the database
   *
   * @returns {*|promise}
   */
  deleteDatabase: function () {
    return this.makeRequest("DELETE", this.databaseUrl + this.databaseName, null, null);
  },

  /**
   * Get the changes feed.
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/database/get-changes/index.html
   *
   * @returns {*|promise}
   */
  getChanges: function (options) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_changes", options);
  },

  /**
   * Get the latest revision
   *
   * @returns {*|promise}
   */
  latestRevision: function () {
    return this.getInfo()
      .then((res) => {
        return res.update_seq;
      });
  },

  /**
   * Get the meta-information
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/server/get--/index.html
   *
   * @returns {*|promise}
   */
  getInfo: function () {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName)
  },

  /**
   * Get the active tasks
   *
   * @returns {*|promise}
   */
  activeTasks: function () {
    return this.makeRequest("GET", this.databaseUrl + "_active_tasks")
  },

  /**
   * Get the databases
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/server/get-all-dbs/index.html
   *
   * @returns {*|promise}
   */
  getAllDatabases: function () {
    return this.makeRequest("GET", this.databaseUrl + "_all_dbs")
  },

  /**
   * Create a new design document with views
   *
   * @param    string designDocumentName
   * @param    object designDocumentViews
   * @return   promise
   */
  createDesignDocument: function (designDocumentName, designDocumentBody) {
    return this.makeRequest("PUT", this.databaseUrl + this.databaseName + "/_design/" + designDocumentName, null, designDocumentBody);
  },

  /**
   * Get a design document and all views associated to insert
   *
   * @param    string designDocumentName
   * @return   promise
   */
  getDesignDocument: function (designDocumentName) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_design/" + designDocumentName);
  },

  /**
   * Delete a particular design document based on its id and revision
   *
   * @param designDocumentName
   * @param documentRevision
   * @return promise
   */
  deleteDesignDocument: function (designDocumentName, documentRevision) {
    var documentId = "_design/" + designDocumentName;
    return this.deleteDocument(documentId, documentRevision);
  },

  /**
   * Query a particular database view. Options for the query ('descending', 'limit', 'startkey', 'endkey' etc.)
   * can be specified using query string parameters.  Query string values are json objects and are URL encoded within,
   * for example:
   *
   *  var options = {
   *    descending: true,
   *    startkey: [docId, {}],
   *    endkey: [docId]
   *  };
   *
   *  return queryView('design_doc_name', 'view_name', options);
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/design-document/get---db--design--design-doc--view--view-name-/index.html
   *
   * @param    string designDocumentName
   * @param    string viewName
   * @param    object queryStringParameters
   * @return   promise
   */
  queryView: function (designDocumentName, viewName, options) {
    var url = this.databaseUrl + this.databaseName + "/_design/" + designDocumentName + "/_view/" + viewName;

    var queryStringParameters = {};
    if (options) {
      for (var key in options) {
        var value = options[key];
        queryStringParameters[key] = JSON.stringify(value);
      }
    }

    return this.makeRequest("GET", url, queryStringParameters);
  },

  /**
   * Create a new database document
   *
   * @param object jsonDocument
   * @returns {*|promise}
   */
  createDocument: function (jsonDocument) {
    return this.makeRequest("POST", this.databaseUrl + this.databaseName, null, jsonDocument);
  },

  /**
   * Add, update, or delete multiple documents to a database in a single request
   *
   * @param object jsonDocuments array
   * @returns {*|promise}
   */
  modifyDocuments: function (jsonDocuments) {
    return this.makeRequest("POST", this.databaseUrl + this.databaseName + '/_bulk_docs', null, {docs: jsonDocuments});
  },

  /**
   * Creates a new document or creates a new revision of an existing document
   *
   * @param object jsonDocument
   * @param string documentId
   * @param string documentRevision (required if updating an existing document)
   * @returns {*|promise}
   */
  updateDocument: function (jsonDocument, documentId, documentRevision) {
    var options = {};

    if (documentRevision) {
      options.rev = documentRevision;
    }

    return this.makeRequest("PUT", this.databaseUrl + this.databaseName + "/" + documentId, options, jsonDocument);
  },

  /**
   * Delete a particular document based on its id and revision
   *
   * @param documentId
   * @param documentRevision
   * @return promise
   */
  deleteDocument: function (documentId, documentRevision) {
    return this.makeRequest("DELETE", this.databaseUrl + this.databaseName + "/" + documentId, {rev: documentRevision});
  },

  /**
   * Delete a named attachment of a particular document
   *
   * @param documentId
   * @param attachmentName
   * @param documentRevision
   * @return promise
   */
  deleteAttachment: function (documentId, documentRevision, attachmentName) {
    return this.makeRequest("DELETE", this.databaseUrl + this.databaseName + "/" + documentId + "/" + attachmentName, {rev: documentRevision});
  },

  /**
   * Get a document with optional revision from the database
   *
   * @param    string documentId
   * @param    object options
   * @return   promise
   */
  getDocument: function (documentId, options) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/" + documentId, options);
  },

  /**
   * Get documents from the database using the _all_docs endpoint
   *
   * see http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/database/get-all-docs/index.html
   *
   * @param   options
   * @returns {*|promise}
   */
  getDocuments: function (options) {
    var queryStringParameters = {};

    if (options) {
      for (var key in options) {
        var value = options[key];
        queryStringParameters[key] = JSON.stringify(value);
      }
    }

    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_all_docs", queryStringParameters);
  },

  /**
   * Get all documents from the database
   *
   * @param object options
   *
   * @returns {*|promise}
   */
  getAllDocuments: function (options) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_all_docs", options);
  },

  /**
   * Get all conflicts
   *
   * @returns {*|promise}
   */
  getAllDocumentConflicts: function () {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_all_docs", {only_conflicts: true});
  },

  /**
   * Replicate in a single direction whether that be remote from local or local to remote.
   *
   * @param string source
   * @param string target
   * @param boolean continuous
   * @param boolean createTarget
   * @returns {*|promise}
   */
  replicate: function (source, target, continuous, createTarget) {
    var replicateUrl = this.databaseUrl + "_replicate";

    return this.makeRequest("POST", replicateUrl, {}, {
      source: source,
      target: target,
      continuous: continuous,
      create_target: createTarget
    });
  },

  /**
   * Listen for database changes
   */
  listen: function (queryStringParams) {
    var poller = function (databaseUrl, databaseName, params) {
      var request = new XMLHttpRequest();
      var self = this;
      request.onload = (e) => {
        var data = JSON.parse(request.responseText);
        self.changesEventEmitter.emit(CHANGE_EVENT_TYPE, data);
        params.since = data.last_seq;
        poller(databaseUrl, databaseName, params);
      };
      request.open('GET', databaseUrl + databaseName + '/_changes' + this._encodeParams(params));
      request.setRequestHeader('Authorization', this.authHeader);
      request.send();
    }.bind(this);
    poller(this.databaseUrl, this.databaseName, queryStringParams);
  },

  /**
   * Construct a URI for retrieving attachments
   *
   * @param    string documentId
   * @param    string attachmentName
   * @param    string documentRevision (optional)
   *
   * @returns string
   */
  getAttachmentUri: function (documentId, name, documentRevision) {
    var url = encodeURI(this.databaseUrl + this.databaseName + "/" + documentId + "/" + name);

    if (documentRevision) {
      url += "?rev=" + encodeURIComponent(documentRevision);
    }

    return url;
  },

  /**
   * Save an attachment using a uri OR file path as input
   *
   * @param    string documentId
   * @param    string documentRevision
   * @param    string name
   * @param    string path
   * @param    string contentType
   *
   * @returns {*|promise}
   */
  saveAttachment: function (documentId, documentRevision, name, path, contentType) {
    var uploadUrl = encodeURI(this.databaseUrl + this.databaseName + "/" + documentId + "/" + name) + "?rev=" + encodeURIComponent(documentRevision);

    return new Promise((resolve, reject) => {
      ReactCBLite.upload("PUT", this.authHeader, path, uploadUrl, contentType,
        (err, success) => {
          if (err) {
            reject(err);
          } else {
            resolve(success);
          }
        }
      );
    });
  },

  /**
   * Make a RESTful request to an endpoint while providing parameters or data or both
   *
   * @param string method
   * @param string url
   * @param object params
   * @param object data
   * @returns {*|promise}
   */
  makeRequest: function (method, url, queryStringParameters, data) {
    var body;
    if (data) {
      body = JSON.stringify(data);
    }

    var settings = {
      method: method,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': this.authHeader
      }
    };

    if (data) {
      settings.body = body;
    }

    return this._makeRequest(settings, url, queryStringParameters, body)
      .then((res) => {
        return res.json()
      });
  },

  _makeRequest: function (settings, url, queryStringParameters, attemptNumber) {

    var fullUrl = encodeURI(url) + this._encodeParams(queryStringParameters);

//    console.log("fullUrl", fullUrl);
    var self = this;

    return fetch(fullUrl, settings).then((res) => {
      if (res.status == 401) {
        console.log("cbl request failed", settings.method, fullUrl, JSON.stringify(res));

        // work-around for a bug in CBL that erroneously sends back a 401
        if (attemptNumber > 1) {
          throw new Error("Not authorized to " + settings.method + " to '" + fullUrl + "' [" + res.status + "]");
        } else {
          var attempt = attemptNumber ? attemptNumber++ : 1;
          return self._makeRequest(settings, url, queryStringParameters, attempt)
        }
      }
      return res
    }).catch((err) => {
      throw new Error("http error for " + settings.method + " '" + fullUrl + "', caused by => " + err);
    });
  },

  _encodeParams: function (queryStringParameters) {
    var queryString = "";

    if (queryStringParameters) {
      var parts = [];

      for (var key in queryStringParameters) {
        var value = queryStringParameters[key];
        var part = key + "=" + encodeURIComponent(value);
        parts.push(part);
      }

      if (parts.length > 0) {
        queryString = "?" + parts.join("&");
      }
    }

    return queryString;
  }
};

module.exports = {manager, ReactCBLite};<commit_msg>added cancelReplicate function, and removed the JSON.stringify code - its not valid for all parameter types so this task needs to be done by the user<commit_after>var {NativeModules} = require('react-native');
var ReactCBLite = NativeModules.ReactCBLite;

var base64 = require('base-64')
  , events = require('events');

var CHANGE_EVENT_TYPE = 'changes';

var manager = function (databaseUrl, databaseName) {
  this.authHeader = "Basic " + base64.encode(databaseUrl.split("//")[1].split('@')[0]);
  this.databaseUrl = databaseUrl;
  this.databaseName = databaseName;
  this.changesEventEmitter = new events.EventEmitter();
};

/**
 * Wrapper around the CBL rest API.
 *
 * See: http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/database/index.html
 */
manager.prototype = {

  /**
   * Construct a new Couchbase object given a database URL and database name
   *
   * @returns {*|promise}
   */
  createDatabase: function () {
    return this.makeRequest("PUT", this.databaseUrl + this.databaseName, null, null);
  },

  /**
   * Delete the database
   *
   * @returns {*|promise}
   */
  deleteDatabase: function () {
    return this.makeRequest("DELETE", this.databaseUrl + this.databaseName, null, null);
  },

  /**
   * Get the changes feed.
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/database/get-changes/index.html
   *
   * @returns {*|promise}
   */
  getChanges: function (options) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_changes", options);
  },

  /**
   * Get the latest revision
   *
   * @returns {*|promise}
   */
  latestRevision: function () {
    return this.getInfo()
      .then((res) => {
        return res.update_seq;
      });
  },

  /**
   * Get the meta-information
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/server/get--/index.html
   *
   * @returns {*|promise}
   */
  getInfo: function () {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName)
  },

  /**
   * Get the active tasks
   *
   * @returns {*|promise}
   */
  activeTasks: function () {
    return this.makeRequest("GET", this.databaseUrl + "_active_tasks")
  },

  /**
   * Get the databases
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/server/get-all-dbs/index.html
   *
   * @returns {*|promise}
   */
  getAllDatabases: function () {
    return this.makeRequest("GET", this.databaseUrl + "_all_dbs")
  },

  /**
   * Create a new design document with views
   *
   * @param    string designDocumentName
   * @param    object designDocumentViews
   * @return   promise
   */
  createDesignDocument: function (designDocumentName, designDocumentBody) {
    return this.makeRequest("PUT", this.databaseUrl + this.databaseName + "/_design/" + designDocumentName, null, designDocumentBody);
  },

  /**
   * Get a design document and all views associated to insert
   *
   * @param    string designDocumentName
   * @return   promise
   */
  getDesignDocument: function (designDocumentName) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_design/" + designDocumentName);
  },

  /**
   * Delete a particular design document based on its id and revision
   *
   * @param designDocumentName
   * @param documentRevision
   * @return promise
   */
  deleteDesignDocument: function (designDocumentName, documentRevision) {
    var documentId = "_design/" + designDocumentName;
    return this.deleteDocument(documentId, documentRevision);
  },

  /**
   * Query a particular database view. Options for the query ('descending', 'limit', 'startkey', 'endkey' etc.)
   * can be specified using query string parameters.  Query string values are json objects and are URL encoded within,
   * for example:
   *
   *  var options = {
   *    descending: true,
   *    startkey: [docId, {}],
   *    endkey: [docId]
   *  };
   *
   *  return queryView('design_doc_name', 'view_name', options);
   *
   * See http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/design-document/get---db--design--design-doc--view--view-name-/index.html
   *
   * @param    string designDocumentName
   * @param    string viewName
   * @param    object queryStringParameters
   * @return   promise
   */
  queryView: function (designDocumentName, viewName, options) {
    var url = this.databaseUrl + this.databaseName + "/_design/" + designDocumentName + "/_view/" + viewName;

    return this.makeRequest("GET", url, options);
  },

  /**
   * Create a new database document
   *
   * @param object jsonDocument
   * @returns {*|promise}
   */
  createDocument: function (jsonDocument) {
    return this.makeRequest("POST", this.databaseUrl + this.databaseName, null, jsonDocument);
  },

  /**
   * Add, update, or delete multiple documents to a database in a single request
   *
   * @param object jsonDocuments array
   * @returns {*|promise}
   */
  modifyDocuments: function (jsonDocuments) {
    return this.makeRequest("POST", this.databaseUrl + this.databaseName + '/_bulk_docs', null, {docs: jsonDocuments});
  },

  /**
   * Creates a new document or creates a new revision of an existing document
   *
   * @param object jsonDocument
   * @param string documentId
   * @param string documentRevision (required if updating an existing document)
   * @returns {*|promise}
   */
  updateDocument: function (jsonDocument, documentId, documentRevision) {
    var options = {};

    if (documentRevision) {
      options.rev = documentRevision;
    }

    return this.makeRequest("PUT", this.databaseUrl + this.databaseName + "/" + documentId, options, jsonDocument);
  },

  /**
   * Delete a particular document based on its id and revision
   *
   * @param documentId
   * @param documentRevision
   * @return promise
   */
  deleteDocument: function (documentId, documentRevision) {
    return this.makeRequest("DELETE", this.databaseUrl + this.databaseName + "/" + documentId, {rev: documentRevision});
  },

  /**
   * Delete a named attachment of a particular document
   *
   * @param documentId
   * @param attachmentName
   * @param documentRevision
   * @return promise
   */
  deleteAttachment: function (documentId, documentRevision, attachmentName) {
    return this.makeRequest("DELETE", this.databaseUrl + this.databaseName + "/" + documentId + "/" + attachmentName, {rev: documentRevision});
  },

  /**
   * Get a document with optional revision from the database
   *
   * @param    string documentId
   * @param    object options
   * @return   promise
   */
  getDocument: function (documentId, options) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/" + documentId, options);
  },

  /**
   * Get documents from the database using the _all_docs endpoint
   *
   * see http://developer.couchbase.com/documentation/mobile/1.2/develop/references/couchbase-lite/rest-api/database/get-all-docs/index.html
   *
   * @param   options
   * @returns {*|promise}
   */
  getDocuments: function (options) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_all_docs", options);
  },

  /**
   * Get all documents from the database
   *
   * @param object options
   *
   * @returns {*|promise}
   */
  getAllDocuments: function (options) {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_all_docs", options);
  },

  /**
   * Get all conflicts
   *
   * @returns {*|promise}
   */
  getAllDocumentConflicts: function () {
    return this.makeRequest("GET", this.databaseUrl + this.databaseName + "/_all_docs", {only_conflicts: true});
  },

  /**
   * Replicate in a single direction whether that be remote from local or local to remote.
   *
   * @param string source
   * @param string target
   * @param boolean continuous
   * @param boolean createTarget
   * @returns {*|promise}
   */
  replicate: function (source, target, continuous, createTarget) {
    var replicateUrl = this.databaseUrl + "_replicate";

    return this.makeRequest("POST", replicateUrl, {}, {
      source: source,
      target: target,
      continuous: continuous,
      create_target: createTarget
    });
  },

  /**
   * Cancel a replication task
   *
   * @param object task
   * @returns {*|promise}
   */
  cancelReplicate: function (task) {
    var replicateUrl = this.databaseUrl + "_replicate";

    task.cancel = true;

    return this.makeRequest("POST", replicateUrl, {}, task);
  },

  /**
   * Listen for database changes
   */
  listen: function (queryStringParams) {
    var poller = function (databaseUrl, databaseName, params) {
      var request = new XMLHttpRequest();
      var self = this;
      request.onload = (e) => {
        var data = JSON.parse(request.responseText);
        self.changesEventEmitter.emit(CHANGE_EVENT_TYPE, data);
        params.since = data.last_seq;
        poller(databaseUrl, databaseName, params);
      };
      request.open('GET', databaseUrl + databaseName + '/_changes' + this._encodeParams(params));
      request.setRequestHeader('Authorization', this.authHeader);
      request.send();
    }.bind(this);
    poller(this.databaseUrl, this.databaseName, queryStringParams);
  },

  /**
   * Construct a URI for retrieving attachments
   *
   * @param    string documentId
   * @param    string attachmentName
   * @param    string documentRevision (optional)
   *
   * @returns string
   */
  getAttachmentUri: function (documentId, name, documentRevision) {
    var url = encodeURI(this.databaseUrl + this.databaseName + "/" + documentId + "/" + name);

    if (documentRevision) {
      url += "?rev=" + encodeURIComponent(documentRevision);
    }

    return url;
  },

  /**
   * Save an attachment using a uri OR file path as input
   *
   * @param    string documentId
   * @param    string documentRevision
   * @param    string name
   * @param    string path
   * @param    string contentType
   *
   * @returns {*|promise}
   */
  saveAttachment: function (documentId, documentRevision, name, path, contentType) {
    var uploadUrl = encodeURI(this.databaseUrl + this.databaseName + "/" + documentId + "/" + name) + "?rev=" + encodeURIComponent(documentRevision);

    return new Promise((resolve, reject) => {
      ReactCBLite.upload("PUT", this.authHeader, path, uploadUrl, contentType,
        (err, success) => {
          if (err) {
            reject(err);
          } else {
            resolve(success);
          }
        }
      );
    });
  },

  /**
   * Make a RESTful request to an endpoint while providing parameters or data or both
   *
   * @param string method
   * @param string url
   * @param object params
   * @param object data
   * @returns {*|promise}
   */
  makeRequest: function (method, url, queryStringParameters, data) {
    var body;
    if (data) {
      body = JSON.stringify(data);
    }

    var settings = {
      method: method,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': this.authHeader
      }
    };

    if (data) {
      settings.body = body;
    }

    return this._makeRequest(settings, url, queryStringParameters, body)
      .then((res) => {
        return res.json()
      });
  },

  _makeRequest: function (settings, url, queryStringParameters, attemptNumber) {

    var fullUrl = encodeURI(url) + this._encodeParams(queryStringParameters);

//    console.log("fullUrl", fullUrl);
    var self = this;

    return fetch(fullUrl, settings).then((res) => {
      if (res.status == 401) {
        console.log("cbl request failed auth", settings, fullUrl, res);

        // work-around for a bug in CBL that erroneously sends back a 401
        if (attemptNumber > 1) {
          throw new Error("Not authorized to " + settings + " to '" + fullUrl + "' [" + res.status + "]");
        } else {
          var attempt = attemptNumber ? attemptNumber++ : 1;
          return self._makeRequest(settings, url, queryStringParameters, attempt)
        }
      }

      return res
    }).catch((err) => {
      throw new Error("http error for " + settings.method + " '" + fullUrl + "', caused by => " + err);
    });
  },

  _encodeParams: function (queryStringParameters) {
    var queryString = "";

    if (queryStringParameters) {
      var parts = [];

      for (var key in queryStringParameters) {
        var value = queryStringParameters[key];
        var part = key + "=" + encodeURIComponent(value);
        parts.push(part);
      }

      if (parts.length > 0) {
        queryString = "?" + parts.join("&");
      }
    }

    return queryString;
  }
};

module.exports = {manager, ReactCBLite};<|endoftext|>


<commit_before>require('coffee-script');
module.exports = require('./lib');
<commit_msg>fix: require of coffeescript<commit_after>require('coffee-script/register');
module.exports = require('./lib');
<|endoftext|>


<commit_before>'use strict';

let mergeTrees = require('broccoli-merge-trees');
let StyleLinter = require('broccoli-stylelint');
let Funnel = require('broccoli-funnel');
const escapeString = require('js-string-escape');

module.exports = {
  name: 'ember-cli-stylelint',

  init(){
    this._super.init && this._super.init.apply(this, arguments);

    let VersionChecker = require('ember-cli-version-checker');
    let checker = new VersionChecker(this);

    if (checker.for('ember-qunit', 'npm').exists() || checker.for('ember-cli-qunit', 'npm').exists()) {
      this._testGenerator = 'qunit';
    } else if (checker.for('ember-mocha', 'npm').exists() || checker.for('ember-cli-mocha', 'npm').exists()) {
      this._testGenerator = 'mocha';
    }
  },

  included() {
    //shared
    //guard see https://github.com/ember-cli/ember-cli/issues/3718
    let app;

    // If the addon has the _findHost() method (in ember-cli >= 2.7.0), we'll just
    // use that.
    if (typeof this._findHost === 'function') {
     app = this._findHost();
    } else {
     // Otherwise, we'll use this implementation borrowed from the _findHost()
     // method in ember-cli.
     let current = this;
     do {
       app = current.app || app;
     } while (current.parent.parent && (current = current.parent));
    }
    this.styleLintOptions = app.options.stylelint || {};
    this.styleLintOptions.console = console;

    //used in real app only
    if (!app.isTestingStyleLintAddon) {
      this._super.included(app);
    } else {
      //Testing only
      this.project = {
        generateTestFile: function(){}
      }
    }

    this.app = app;
  },

  lintTree(type) {

    if (type === 'app') {
      this.styleLintOptions.testingFramework = this._testGenerator;

      let toBeLinted = [ this.app.trees.app ];
      if (this.styleLintOptions.includePaths) {
        toBeLinted.push.apply(toBeLinted, this.styleLintOptions.includePaths);
      }

      let linted = toBeLinted.map(function(tree) {
        let filteredTreeToBeLinted = new Funnel(tree, {
          exclude: ['**/*.js']
        });
        return StyleLinter.create(filteredTreeToBeLinted, this.styleLintOptions)
      }, this);

      return mergeTrees(linted);
    }
  }
};
<commit_msg>force lint tree to behave as if it is calle once<commit_after>'use strict';

let mergeTrees = require('broccoli-merge-trees');
let StyleLinter = require('broccoli-stylelint');
let Funnel = require('broccoli-funnel');
const escapeString = require('js-string-escape');

module.exports = {
  name: 'ember-cli-stylelint',

  init(){
    this._super.init && this._super.init.apply(this, arguments);

    let VersionChecker = require('ember-cli-version-checker');
    let checker = new VersionChecker(this);

    if (checker.for('ember-qunit', 'npm').exists() || checker.for('ember-cli-qunit', 'npm').exists()) {
      this._testGenerator = 'qunit';
    } else if (checker.for('ember-mocha', 'npm').exists() || checker.for('ember-cli-mocha', 'npm').exists()) {
      this._testGenerator = 'mocha';
    }
  },

  included() {
    //shared
    //guard see https://github.com/ember-cli/ember-cli/issues/3718
    let app;

    // If the addon has the _findHost() method (in ember-cli >= 2.7.0), we'll just
    // use that.
    if (typeof this._findHost === 'function') {
     app = this._findHost();
    } else {
     // Otherwise, we'll use this implementation borrowed from the _findHost()
     // method in ember-cli.
     let current = this;
     do {
       app = current.app || app;
     } while (current.parent.parent && (current = current.parent));
    }
    this.styleLintOptions = app.options.stylelint || {};
    this.styleLintOptions.console = console;

    //used in real app only
    if (!app.isTestingStyleLintAddon) {
      this._super.included(app);
    } else {
      //Testing only
      this.project = {
        generateTestFile: function(){}
      }
    }

    this.app = app;
  },

  lintTree() {
    if (!this.linted) {
      this.styleLintOptions.testingFramework = this._testGenerator;

      let toBeLinted = [ this.app.trees.app ];
      if (this.styleLintOptions.includePaths) {
        toBeLinted.push.apply(toBeLinted, this.styleLintOptions.includePaths);
      }

      let linted = toBeLinted.map(function(tree) {
        let filteredTreeToBeLinted = new Funnel(tree, {
          exclude: ['**/*.js']
        });
        return StyleLinter.create(filteredTreeToBeLinted, this.styleLintOptions)
      }, this);
      this.linted = true;
      return mergeTrees(linted);
    }
  }
};
<|endoftext|>


<commit_before>// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.

var Buffer = require('safe-buffer').Buffer

module.exports = function base (ALPHABET) {
  if (ALPHABET.length >= 255) throw new TypeError('Alphabet too long')

  const BASE_MAP = new Uint8Array(256)
  BASE_MAP.fill(255)

  for (let i = 0; i < ALPHABET.length; i++) {
    const x = ALPHABET.charAt(i)
    const xc = x.charCodeAt(0)

    BASE_MAP[xc] = i
  }

  const BASE = ALPHABET.length
  const LEADER = ALPHABET.charAt(0)
  const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
  const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up

  function encode (source) {
    if (!Buffer.isBuffer(source)) throw new TypeError('Expected Buffer')

    // Skip & count leading zeroes.
    let zeroes = 0
    let length = 0
    let pbegin = 0
    const pend = source.length

    while (pbegin !== pend && source[pbegin] === 0) {
      pbegin++
      zeroes++
    }

    // Allocate enough space in big-endian base58 representation.
    const size = ((pend - pbegin) * iFACTOR + 1) >>> 0
    const b58 = new Uint8Array(size)

    // Process the bytes.
    while (pbegin !== pend) {
      let carry = source[pbegin]

      // Apply "b58 = b58 * 256 + ch".
      let i = 0
      for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) {
        carry += (256 * b58[it]) >>> 0
        b58[it] = (carry % BASE) >>> 0
        carry = (carry / BASE) >>> 0
      }

      if (carry !== 0) throw new Error('Non-zero carry')
      length = i
      pbegin++
    }

    // Skip leading zeroes in base58 result.
    let it = size - length
    while (it !== size && b58[it] === 0) {
      it++
    }

    // Translate the result into a string.
    let str = ''
    for (let j = 0; j < zeroes; ++j) str += LEADER
    for (; it < size; ++it) str += ALPHABET.charAt(b58[it])

    return str
  }

  function decodeUnsafe (source) {
    if (typeof source !== 'string') throw new TypeError('Expected String')

    let psz = 0

    // Skip leading spaces.
    if (source[psz] === ' ') return

    // Skip and count leading '1's.
    let zeroes = 0
    let length = 0
    while (source[psz] === LEADER) {
      zeroes++
      psz++
    }

    // Allocate enough space in big-endian base256 representation.
    const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.
    const b256 = new Uint8Array(size)

    // Process the characters.
    while (source[psz]) {
      // Decode character
      let carry = BASE_MAP[source.charCodeAt(psz)]

      // Invalid character
      if (carry === 255) return

      let i = 0
      for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) {
        carry += (BASE * b256[it]) >>> 0
        b256[it] = (carry % 256) >>> 0
        carry = (carry / 256) >>> 0
      }

      if (carry !== 0) throw new Error('Non-zero carry')
      length = i
      psz++
    }

    // Skip trailing spaces.
    if (source[psz] === ' ') return

    // Skip leading zeroes in b256.
    let it = size - length
    while (it !== size && b256[it] === 0) {
      it++
    }

    let vch = Buffer.allocUnsafe(zeroes + (size - it))
    let j = 0
    for (; j < zeroes; ++j) {
      vch[j] = 0x00
    }

    while (it !== size) {
      vch[j++] = b256[it++]
    }

    return vch
  }

  function decode (string) {
    var buffer = decodeUnsafe(string)
    if (buffer) return buffer

    throw new Error('Non-base' + BASE + ' character')
  }

  return {
    encode: encode,
    decodeUnsafe: decodeUnsafe,
    decode: decode
  }
}
<commit_msg>throw for poorly formed alphabet<commit_after>// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.

var Buffer = require('safe-buffer').Buffer

module.exports = function base (ALPHABET) {
  if (ALPHABET.length >= 255) throw new TypeError('Alphabet too long')

  const BASE_MAP = new Uint8Array(256)
  BASE_MAP.fill(255)

  for (let i = 0; i < ALPHABET.length; i++) {
    const x = ALPHABET.charAt(i)
    const xc = x.charCodeAt(0)

    if (BASE_MAP[xc] !== 255) throw new TypeError(x + ' is ambiguous')
    BASE_MAP[xc] = i
  }

  const BASE = ALPHABET.length
  const LEADER = ALPHABET.charAt(0)
  const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
  const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up

  function encode (source) {
    if (!Buffer.isBuffer(source)) throw new TypeError('Expected Buffer')

    // Skip & count leading zeroes.
    let zeroes = 0
    let length = 0
    let pbegin = 0
    const pend = source.length

    while (pbegin !== pend && source[pbegin] === 0) {
      pbegin++
      zeroes++
    }

    // Allocate enough space in big-endian base58 representation.
    const size = ((pend - pbegin) * iFACTOR + 1) >>> 0
    const b58 = new Uint8Array(size)

    // Process the bytes.
    while (pbegin !== pend) {
      let carry = source[pbegin]

      // Apply "b58 = b58 * 256 + ch".
      let i = 0
      for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) {
        carry += (256 * b58[it]) >>> 0
        b58[it] = (carry % BASE) >>> 0
        carry = (carry / BASE) >>> 0
      }

      if (carry !== 0) throw new Error('Non-zero carry')
      length = i
      pbegin++
    }

    // Skip leading zeroes in base58 result.
    let it = size - length
    while (it !== size && b58[it] === 0) {
      it++
    }

    // Translate the result into a string.
    let str = ''
    for (let j = 0; j < zeroes; ++j) str += LEADER
    for (; it < size; ++it) str += ALPHABET.charAt(b58[it])

    return str
  }

  function decodeUnsafe (source) {
    if (typeof source !== 'string') throw new TypeError('Expected String')

    let psz = 0

    // Skip leading spaces.
    if (source[psz] === ' ') return

    // Skip and count leading '1's.
    let zeroes = 0
    let length = 0
    while (source[psz] === LEADER) {
      zeroes++
      psz++
    }

    // Allocate enough space in big-endian base256 representation.
    const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.
    const b256 = new Uint8Array(size)

    // Process the characters.
    while (source[psz]) {
      // Decode character
      let carry = BASE_MAP[source.charCodeAt(psz)]

      // Invalid character
      if (carry === 255) return

      let i = 0
      for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) {
        carry += (BASE * b256[it]) >>> 0
        b256[it] = (carry % 256) >>> 0
        carry = (carry / 256) >>> 0
      }

      if (carry !== 0) throw new Error('Non-zero carry')
      length = i
      psz++
    }

    // Skip trailing spaces.
    if (source[psz] === ' ') return

    // Skip leading zeroes in b256.
    let it = size - length
    while (it !== size && b256[it] === 0) {
      it++
    }

    let vch = Buffer.allocUnsafe(zeroes + (size - it))
    let j = 0
    for (; j < zeroes; ++j) {
      vch[j] = 0x00
    }

    while (it !== size) {
      vch[j++] = b256[it++]
    }

    return vch
  }

  function decode (string) {
    var buffer = decodeUnsafe(string)
    if (buffer) return buffer

    throw new Error('Non-base' + BASE + ' character')
  }

  return {
    encode: encode,
    decodeUnsafe: decodeUnsafe,
    decode: decode
  }
}
<|endoftext|>


<commit_before>'use strict';

var define = require('define-properties');
var isSymbol = require('is-symbol');

var globalKey = '__ global cache key __';
if (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') {
	globalKey = Symbol['for'](globalKey);
}
if (!global[globalKey]) {
	var properties = {};
	properties[globalKey] = {};
	define(global, properties);
}

var cache = global[globalKey];

var isPrimitive = function isPrimitive(val) {
	return val === null || (typeof val !== 'object' && typeof val !== 'function');
};

var getPrimitiveKey = function getPrimitiveKey(val) {
	if (isSymbol(val)) {
		return Symbol.prototype.valueOf.call(val);
	}
	return typeof val + ' | ' + String(val);
};

var requirePrimitiveKey = function requirePrimitiveKey(val) {
	if (!isPrimitive(val)) {
		throw new TypeError('key must not be an object');
	}
};

var globalCache = {
	'delete': function deleteKey(key) {
		requirePrimitiveKey(key);
		delete cache[getPrimitiveKey(key)];
		return !globalCache.has(key);
	},

	get: function get(key) {
		requirePrimitiveKey(key);
		return cache[getPrimitiveKey(key)];
	},

	has: function has(key) {
		requirePrimitiveKey(key);
		return getPrimitiveKey(key) in cache;
	},

	set: function set(key, value) {
		requirePrimitiveKey(key);
		var props = {};
		props[getPrimitiveKey(key)] = value;
		define(cache, props);
		return globalCache.has(key);
	}
};

module.exports = globalCache;
<commit_msg>Ensure that when `Symbol` and `Symbol.for` are available, they're real Symbols and not gross fake ones.<commit_after>'use strict';

var define = require('define-properties');
var isSymbol = require('is-symbol');

var globalKey = '__ global cache key __';
if (typeof Symbol === 'function' && isSymbol(Symbol()) && typeof Symbol['for'] === 'function') {
	globalKey = Symbol['for'](globalKey);
}
if (!global[globalKey]) {
	var properties = {};
	properties[globalKey] = {};
	define(global, properties);
}

var cache = global[globalKey];

var isPrimitive = function isPrimitive(val) {
	return val === null || (typeof val !== 'object' && typeof val !== 'function');
};

var getPrimitiveKey = function getPrimitiveKey(val) {
	if (isSymbol(val)) {
		return Symbol.prototype.valueOf.call(val);
	}
	return typeof val + ' | ' + String(val);
};

var requirePrimitiveKey = function requirePrimitiveKey(val) {
	if (!isPrimitive(val)) {
		throw new TypeError('key must not be an object');
	}
};

var globalCache = {
	'delete': function deleteKey(key) {
		requirePrimitiveKey(key);
		delete cache[getPrimitiveKey(key)];
		return !globalCache.has(key);
	},

	get: function get(key) {
		requirePrimitiveKey(key);
		return cache[getPrimitiveKey(key)];
	},

	has: function has(key) {
		requirePrimitiveKey(key);
		return getPrimitiveKey(key) in cache;
	},

	set: function set(key, value) {
		requirePrimitiveKey(key);
		var props = {};
		props[getPrimitiveKey(key)] = value;
		define(cache, props);
		return globalCache.has(key);
	}
};

module.exports = globalCache;
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');
const wtf = e => console.log("wtf", e);

function go(star, args) {
  return new Promise((resolve, reject) => {
    const gen = star.apply(null, args);
    gen.resolve = resolve;
    gen.reject = reject;
    bounce(gen);
  });
}

function bounce(gen, input) {
  let output;
  try { output = gen.next(input); }
  catch (e) { return gen.reject(e); }
  if (output.done) return gen.resolve(output.value);
  next(gen, output.value);
}

function toss(gen, error) {
  let output;
  try { output = gen.throw(error); }
  catch (e) { return gen.reject(e); }
  if (output.done) return gen.resolve(output.value);
  next(gen, output.value);
}

function next(gen, instr) {
  if (isPromise(instr)) {
    return instr.then(i => bounce(gen, i), e => toss(gen, e));
  }

  if (instr instanceof Unbuffered) {
    return instr.take(gen).then(i => bounce(gen, i), wtf);
  }

  if (instr instanceof Put) {
    return instr.ch.put(gen, instr.val).then(() => bounce(gen), wtf);
  }

  if (instr instanceof Alts) {
    const alt = { isLive: true };
    for (let op of instr.ops) {
      if (isPromise(op)) {
        op.then(i => {
          if (alt.isLive) {
            alt.isLive = false;
            bounce(gen, i);
          }
        }, e => {
          if (alt.isLive) {
            alt.isLive = false;
            toss(gen, e);
          }
        });
      }

      if (op instanceof Unbuffered) {
        op.take(alt).then(i => {
          alt.isLive = false;
          bounce(gen, { value: i, channel: op })
        }, wtf);
      }

      if (op instanceof Put) {
        op.ch.put(alt, instr.val).then(() => {
          alt.isLive = false;
          bounce(gen, { channel: op });
        }, wtf);
      }
    }
    return;
  }

  gen.reject(new Error("Invalid yield instruction: " + instr + "."));
}

class Put {
  constructor(ch, val) {
    this.ch = ch;
    this.val = val;
  }
}
const put = (ch, val) => new Put(ch, val);

class Alts {
  constructor(ops) {
    this.ops = ops;
  }
}
const alts = ops => new Alts(ops);

const isPromise = x => typeof x.then === 'function';
const isGen = x => typeof x.next === 'function' && typeof x.throw === 'function';
const isLive = x => {
  const alive = x.isLive || x.isLive === undefined;
  if (!alive) console.log("Found something dead!", x);
  return alive;
}

class Unbuffered {

  constructor() {
    this.takings = [];
    this.putings = [];
  }

  put(puter, val) {
    this.takings = this.takings.filter(isLive);
    const takings = this.takings;
    const putings = this.putings;
    return new Promise((resolve, reject) => {
      if (!takings.length) {
        return putings.push({
          val: val,
          resolve: resolve,
          reject: reject,
          isLive: puter.isLive
        });
      }
      const taking = takings.shift();
      taking.resolve(val);
      resolve();
    });
  }

  take(taker) {
    this.putings = this.putings.filter(isLive);
    const takings = this.takings;
    const putings = this.putings;
    return new Promise((resolve, reject) => {
      if (!putings.length) {
        return takings.push({
          resolve: resolve,
          reject: reject,
          isLive: taker.isLive
        });
      }
      const puting = putings.shift();
      puting.resolve();
      resolve(puting.val);
    });
  }
}

const chan = () => new Unbuffered();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

module.exports = {
  go: go,
  put: put,
  alts: alts,
  sleep: sleep,
  chan: chan
};
<commit_msg>Clean things up a bit.<commit_after>'use strict';

const assert = require('assert');
const wtf = e => console.log("wtf", e);

function go(star, args) {
  return new Promise((resolve, reject) => {
    const gen = star.apply(null, args);
    gen.resolve = resolve;
    gen.reject = reject;
    bounce(gen);
  });
}

function bounce(gen, input) {
  let output;
  try { output = gen.next(input); }
  catch (e) { return gen.reject(e); }
  if (output.done) return gen.resolve(output.value);
  next(gen, output.value);
}

function toss(gen, error) {
  let output;
  try { output = gen.throw(error); }
  catch (e) { return gen.reject(e); }
  if (output.done) return gen.resolve(output.value);
  next(gen, output.value);
}

function next(gen, instr) {
  if (isPromise(instr)) {
    return instr.then(i => bounce(gen, i), e => toss(gen, e));
  }
  if (instr instanceof Unbuffered) {
    return instr.take(gen).then(i => bounce(gen, i), wtf);
  }
  if (instr instanceof Put) {
    return instr.ch.put(gen, instr.val).then(() => bounce(gen), wtf);
  }
  if (instr instanceof Alts) {
    const alt = { isLive: true };
    return instr.ops.forEach(op => {
      if (isPromise(op)) {
        op.then(i => { if (alt.isLive) { alt.isLive = false; bounce(gen, i); } },
                e => { if (alt.isLive) { alt.isLive = false; toss(gen, e); } });
      }

      if (op instanceof Unbuffered) {
        op.take(alt).then(i => bounce(gen, { value: i, channel: op }), wtf);
      }

      if (op instanceof Put) {
        op.ch.put(alt, instr.val).then(() => bounce(gen, { channel: op }), wtf);
      }
    });
  }

  gen.reject(new Error("Invalid yield instruction: " + instr + "."));
}

class Put {
  constructor(ch, val) {
    this.ch = ch;
    this.val = val;
  }
}
const put = (ch, val) => new Put(ch, val);

class Alts {
  constructor(ops) {
    this.ops = ops;
  }
}
const alts = ops => new Alts(ops);

const isPromise = x => typeof x.then === 'function';
const isAlt = x => x.isLive != undefined;
const isLive = x => x.isLive || x.isLive === undefined;

class Unbuffered {

  constructor() {
    this.takings = [];
    this.putings = [];
  }

  put(puter, val) {
    this.takings = this.takings.filter(t => isLive(t.er));
    const takings = this.takings;
    const putings = this.putings;
    return new Promise((resolve, reject) => {
      if (!takings.length) {
        return putings.push({
          val: val,
          er: puter,
          resolve: resolve,
          reject: reject
        });
      }
      const taking = takings.shift();
      if (isAlt(taking.er)) taking.er.isLive = false;
      taking.resolve(val);

      if (isAlt(puter)) puter.isLive = false;
      resolve();
    });
  }

  take(taker) {
    this.putings = this.putings.filter(p => isLive(p.er));
    const takings = this.takings;
    const putings = this.putings;
    return new Promise((resolve, reject) => {
      if (!putings.length) {
        return takings.push({
          er: taker,
          resolve: resolve,
          reject: reject,
        });
      }
      const puting = putings.shift();
      if (isAlt(puting.er)) puting.er.isLive = false;
      puting.resolve();

      if (isAlt(taker)) taker.isLive = false;
      resolve(puting.val);
    });
  }
}

const chan = () => new Unbuffered();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

module.exports = {
  go: go,
  put: put,
  alts: alts,
  sleep: sleep,
  chan: chan
};
<|endoftext|>


<commit_before>var http = require('http'),
	url = require('url');

module.exports = function(opts, done) {
	var u = url.parse(opts.url);

	var info = {
		hostname: u.hostname,
		port: u.port,
		path: u.path,
		method: opts.method,
		// TODO
		headers: null
	};

	var responses = {}, errors = {};
	var report = {
		url: opts.url,
		ok: 0,
		fail: 0,
		completed: 0,
		ongoing: 0,
		pending: opts.amount,
		total: opts.amount,
		start: new Date()
	};

	while (opts.concurrent--) {
		request();
	}

	function request() {
		if (report.pending <= 0) return;
		report.pending--;
		report.ongoing++;

		var req = http.request(info, function(res) {
			var status = res.statusCode;
			if (status >= 400) {
				error(status);
			} else {
				success(status);
			}
		});

		// FIXME: Doesn't seem to be working
		req.setTimeout(opts.timeout);
		req.on('error', function(e) {
			error(e.code);
		});
		req.end(opts.data);
	}

	function success(status) {
		if (responses[status]) {
			responses[status].amount++;
		} else {
			responses[status] = { status:status, amount:1 }
		}

		report.ok++;
		completed();
	}

	function error(code) {
		if (errors[code]) {
			errors[code].amount++;
		} else {
			errors[code] = {code:code, amount:1};
		}

		report.fail++;
		completed();
	}

	function completed() {
		report.ongoing--;
		report.completed++;
		request();

		if (opts.progress) {
			opts.progress(report);
		}

		if (report.completed < report.total) return;

		report.end = new Date();
		report.responses = values(responses);
		report.errors = values(errors);
		done(report);
	}
};

function values(obj) {
	var arr = [];
	for (var key in obj) {
		arr.push(obj[key]);
	}
	return arr;
}<commit_msg>Fixed concurrent setting limited by node maxSockets<commit_after>var http = require('http'),
	url = require('url');

module.exports = function(opts, done) {
	var u = url.parse(opts.url);

	var info = {
		hostname: u.hostname,
		port: u.port,
		path: u.path,
		method: opts.method,
		agent: new http.Agent(),
		// TODO
		headers: null
	};
	// WARNING: if you get EMFILE errors, you're reaching the limit
	// https://github.com/joyent/node/issues/793
	info.agent.maxSockets = opts.concurrent;

	var responses = {}, errors = {};
	var report = {
		url: opts.url,
		ok: 0,
		fail: 0,
		completed: 0,
		ongoing: 0,
		pending: opts.amount,
		total: opts.amount,
		start: new Date()
	};

	while (opts.concurrent--) {
		request();
	}

	function request() {
		if (report.pending <= 0) return;
		report.pending--;
		report.ongoing++;

		var req = http.request(info, function(res) {
			var status = res.statusCode;
			if (status >= 400) {
				error(status);
			} else {
				success(status);
			}
		});

		// FIXME: Doesn't seem to be working
		req.setTimeout(opts.timeout);
		req.on('error', function(e) {
			error(e.code);
		});

		req.end(opts.data);
	}

	function success(status) {
		if (responses[status]) {
			responses[status].amount++;
		} else {
			responses[status] = { status:status, amount:1 }
		}

		report.ok++;
		completed();
	}

	function error(code) {
		if (errors[code]) {
			errors[code].amount++;
		} else {
			errors[code] = {code:code, amount:1};
		}

		report.fail++;
		completed();
	}

	function completed() {
		report.ongoing--;
		report.completed++;
		request();

		if (opts.progress) {
			opts.progress(report);
		}

		if (report.completed < report.total) return;

		report.end = new Date();
		report.responses = values(responses);
		report.errors = values(errors);
		done(report);
	}
};

function values(obj) {
	var arr = [];
	for (var key in obj) {
		arr.push(obj[key]);
	}
	return arr;
}<|endoftext|>


<commit_before>import React from 'react-native';
import { EventEmitter } from 'fbemitter';

import NavBarContainer from './components/NavBarContainer';

const {
  StyleSheet,
  Navigator,
  StatusBarIOS,
  View,
  Platform,
} = React;

class Router extends React.Component {
  constructor(props) {
    super(props);

    this.onForward = this.onForward.bind(this);
    this.onBack = this.onBack.bind(this);
    this.customAction = this.customAction.bind(this);
    this.renderScene = this.renderScene.bind(this);
    this.onDidFocus = this.onDidFocus.bind(this);
    this.onWillFocus = this.onWillFocus.bind(this);

    this.state = {
      route: {
        name: null,
        index: null,
      },
    };
    this.emitter = new EventEmitter();
  }

  onWillFocus(route) {
    this.setState({ route });
    this.emitter.emit('willFocus', route.name);
  }

  onDidFocus(route) {
    this.emitter.emit('didFocus', route.name);
  }

  onBack(navigator) {
    if (this.state.route.index > 0) {
      navigator.pop();
    }
  }

  onForward(nextRoute, navigator) {
    navigator.push(
      Object.assign(nextRoute, { index: this.state.route.index + 1 || 1 })
    );
  }

  setRightProps(props) {
    this.setState({ rightProps: props });
  }

  setLeftProps(props) {
    this.setState({ leftProps: props });
  }

  setTitleProps(props) {
    this.setState({ titleProps: props });
  }

  customAction(opts) {
    this.props.customAction(opts);
  }

  configureScene(route) {
    return route.sceneConfig || Navigator.SceneConfigs.FloatFromRight;
  }

  renderScene(route, navigator) {
    const goForward = function goForward(nextRoute) {
      navigator.push(
        Object.assign(nextRoute, { index: this.state.route.index + 1 || 1 })
      );
    }.bind(this);

    const replaceRoute = function replaceRoute(nextRoute) {
      navigator.replace(
        Object.assign(nextRoute, { index: this.state.route.index || 0 })
      );
    }.bind(this);

    const resetToRoute = function resetToRoute(nextRoute) {
      navigator.resetTo(
        Object.assign(nextRoute, { index: 0 })
      );
    };

    const goBackwards = function goBackwards() {
      this.onBack(navigator);
    }.bind(this);

    const goToFirstRoute = function goToFirstRoute() {
      navigator.popToTop();
    };

    const setRightProps = function setRightProps(props) {
      this.setState({ rightProps: props });
    }.bind(this);

    const setLeftProps = function setLeftProps(props) {
      this.setState({ leftProps: props });
    }.bind(this);

    const setTitleProps = function setTitleProps(props) {
      this.setState({ titleProps: props });
    }.bind(this);

    const customAction = function customAction(opts) {
      this.customAction(opts);
    }.bind(this);

    const Content = route.component;

    // Remove the margin of the navigation bar if not using navigation bar
    const extraStyling = {};
    if (this.props.hideNavigationBar) {
      extraStyling.marginTop = 0;
    }

    let margin;
    if (route.trans) {
      margin = 0;
    } else if (this.props.hideNavigationBar || route.hideNavigationBar) {
      margin = this.props.noStatusBar ? 0 : 20;
    } else {
      margin = 64;
    }

    return (
      <View
        style={[styles.container, this.props.bgStyle, extraStyling, { marginTop: margin }]}>
        <Content
          name={route.name}
          index={route.index}
          data={route.data}
          toRoute={goForward}
          toBack={goBackwards}
          routeEmitter={this.emitter}
          replaceRoute={replaceRoute}
          resetToRoute={resetToRoute}
          reset={goToFirstRoute}
          setRightProps={setRightProps}
          setLeftProps={setLeftProps}
          setTitleProps={setTitleProps}
          customAction={customAction}
          {...route.passProps}
        />
      </View>
    );
  }

  render() {
    let navigationBar;
    // Status bar color
    if (Platform.OS === 'ios') {
      if (this.props.statusBarColor === 'black') {
        StatusBarIOS.setStyle(0);
      } else {
        StatusBarIOS.setStyle(1);
      }
    } else if (Platform.OS === 'android') {
      // no android version yet
    }

    if (!this.props.hideNavigationBar) {
      navigationBar = (
        <NavBarContainer
          style={this.props.headerStyle}
          navigator={navigator}
          currentRoute={this.state.route}
          backButtonComponent={this.props.backButtonComponent}
          rightCorner={this.props.rightCorner}
          titleStyle={this.props.titleStyle}
          borderBottomWidth={this.props.borderBottomWidth}
          borderColor={this.props.borderColor}
          toRoute={this.onForward}
          toBack={this.onBack}
          leftProps={this.state.leftProps}
          rightProps={this.state.rightProps}
          titleProps={this.state.titleProps}
          customAction={this.customAction}
        />
      );
    }

    return (
      <Navigator
        ref="navigator"
        initialRoute={this.props.firstRoute}
        navigationBar={navigationBar}
        renderScene={this.renderScene}
        onDidFocus={this.onDidFocus}
        onWillFocus={this.onWillFocus}
        configureScene={this.configureScene}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
});

export default Router;
<commit_msg>broadcasting events based on navigator actions<commit_after>import React from 'react-native';
import { EventEmitter } from 'fbemitter';

import NavBarContainer from './components/NavBarContainer';

const {
  StyleSheet,
  Navigator,
  StatusBarIOS,
  View,
  Platform,
} = React;

class Router extends React.Component {
  constructor(props) {
    super(props);

    this.onForward = this.onForward.bind(this);
    this.onBack = this.onBack.bind(this);
    this.customAction = this.customAction.bind(this);
    this.renderScene = this.renderScene.bind(this);
    this.onDidFocus = this.onDidFocus.bind(this);
    this.onWillFocus = this.onWillFocus.bind(this);

    this.state = {
      route: {
        name: null,
        index: null,
      },
    };
    this.emitter = new EventEmitter();
  }

  onWillFocus(route) {
    this.setState({ route });
    this.emitter.emit('willFocus', route.name);
  }

  onDidFocus(route) {
    this.emitter.emit('didFocus', route.name);
  }

  onBack(navigator) {
    if (this.state.route.index > 0) {
      navigator.pop();
      this.emitter.emit('pop');
    }
  }

  onForward(nextRoute, navigator) {
    navigator.push(
      Object.assign(nextRoute, { index: this.state.route.index + 1 || 1 })
    );
    this.emitter.emit('push', nextRoute);
  }

  setRightProps(props) {
    this.setState({ rightProps: props });
  }

  setLeftProps(props) {
    this.setState({ leftProps: props });
  }

  setTitleProps(props) {
    this.setState({ titleProps: props });
  }

  customAction(opts) {
    this.props.customAction(opts);
  }

  configureScene(route) {
    return route.sceneConfig || Navigator.SceneConfigs.FloatFromRight;
  }

  renderScene(route, navigator) {
    const goForward = function goForward(nextRoute) {
      navigator.push(
        Object.assign(nextRoute, { index: this.state.route.index + 1 || 1 })
      );
      this.emitter.emit('push', nextRoute);
    }.bind(this);

    const replaceRoute = function replaceRoute(nextRoute) {
      navigator.replace(
        Object.assign(nextRoute, { index: this.state.route.index || 0 })
      );
      this.emitter.emit('replace', nextRoute);
    }.bind(this);

    const resetToRoute = function resetToRoute(nextRoute) {
      navigator.resetTo(
        Object.assign(nextRoute, { index: 0 })
      );
      this.emitter.emit('resetTo', nextRoute);
    }.bind(this);

    const goBackwards = function goBackwards() {
      this.onBack(navigator);
    }.bind(this);

    const goToFirstRoute = function goToFirstRoute() {
      navigator.popToTop();
      this.emitter.emit('popToTop');
    }.bind(this);

    const setRightProps = function setRightProps(props) {
      this.setState({ rightProps: props });
    }.bind(this);

    const setLeftProps = function setLeftProps(props) {
      this.setState({ leftProps: props });
    }.bind(this);

    const setTitleProps = function setTitleProps(props) {
      this.setState({ titleProps: props });
    }.bind(this);

    const customAction = function customAction(opts) {
      this.customAction(opts);
    }.bind(this);

    const Content = route.component;

    // Remove the margin of the navigation bar if not using navigation bar
    const extraStyling = {};
    if (this.props.hideNavigationBar) {
      extraStyling.marginTop = 0;
    }

    let margin;
    if (route.trans) {
      margin = 0;
    } else if (this.props.hideNavigationBar || route.hideNavigationBar) {
      margin = this.props.noStatusBar ? 0 : 20;
    } else {
      margin = 64;
    }

    return (
      <View
        style={[styles.container, this.props.bgStyle, extraStyling, { marginTop: margin }]}>
        <Content
          name={route.name}
          index={route.index}
          data={route.data}
          toRoute={goForward}
          toBack={goBackwards}
          routeEmitter={this.emitter}
          replaceRoute={replaceRoute}
          resetToRoute={resetToRoute}
          reset={goToFirstRoute}
          setRightProps={setRightProps}
          setLeftProps={setLeftProps}
          setTitleProps={setTitleProps}
          customAction={customAction}
          {...route.passProps}
        />
      </View>
    );
  }

  render() {
    let navigationBar;
    // Status bar color
    if (Platform.OS === 'ios') {
      if (this.props.statusBarColor === 'black') {
        StatusBarIOS.setStyle(0);
      } else {
        StatusBarIOS.setStyle(1);
      }
    } else if (Platform.OS === 'android') {
      // no android version yet
    }

    if (!this.props.hideNavigationBar) {
      navigationBar = (
        <NavBarContainer
          style={this.props.headerStyle}
          navigator={navigator}
          currentRoute={this.state.route}
          backButtonComponent={this.props.backButtonComponent}
          rightCorner={this.props.rightCorner}
          titleStyle={this.props.titleStyle}
          borderBottomWidth={this.props.borderBottomWidth}
          borderColor={this.props.borderColor}
          toRoute={this.onForward}
          toBack={this.onBack}
          leftProps={this.state.leftProps}
          rightProps={this.state.rightProps}
          titleProps={this.state.titleProps}
          customAction={this.customAction}
        />
      );
    }

    return (
      <Navigator
        ref="navigator"
        initialRoute={this.props.firstRoute}
        navigationBar={navigationBar}
        renderScene={this.renderScene}
        onDidFocus={this.onDidFocus}
        onWillFocus={this.onWillFocus}
        configureScene={this.configureScene}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
  },
});

export default Router;
<|endoftext|>


<commit_before>'use strict';

var through = require('through2');
var w3cjs = require('w3cjs');
var gutil = require('gulp-util');

/**
 * Handles messages.
 *
 * @param file The file array.
 * @param messages Array of messages returned by w3cjs.
 * @return boolean Return false if errors have occurred.
 */
function handleMessages(file, messages, options) {
	var success = true;
	var errorText = gutil.colors.red.bold('HTML Error:');
	var warningText = gutil.colors.yellow.bold('HTML Warning:');
	var infoText = gutil.colors.green.bold('HTML Info:');
	var lines = file.contents.toString().split(/\r\n|\r|\n/g);

	if (!Array.isArray(messages)) {
		gutil.log(warningText, 'Failed to run validation on', file.relative);

		// Not sure whether this should be true or false
		return true;
	}

	messages.forEach(function (message) {
		if (message.type === 'info' && !options.showInfo) {
			return;
		}

		if (message.type === 'error') {
			success = false;
		}

		var type = (message.type === 'error') ? errorText : ((message.type === 'info') ? infoText : warningText);

		var location = 'Line ' + (message.lastLine || 0) + ', Column ' + (message.lastColumn || 0) + ':';

		var erroredLine = lines[message.lastLine - 1];

		// If this is false, stream was changed since validation
		if (erroredLine) {
			var errorColumn = message.lastColumn;

			// Trim before if the error is too late in the line
			if (errorColumn > 60) {
				erroredLine = erroredLine.slice(errorColumn - 50);
				errorColumn = 50;
			}

			// Trim after so the line is not too long
			erroredLine = erroredLine.slice(0, 60);

			// Highlight character with error
			erroredLine =
				gutil.colors.grey(erroredLine.substring(0, errorColumn - 1)) +
				gutil.colors.red.bold(erroredLine[ errorColumn - 1 ]) +
				gutil.colors.grey(erroredLine.substring(errorColumn));
		}

		if (typeof(message.lastLine) !== 'undefined' || typeof(lastColumn) !== 'undefined') {
			gutil.log(type, file.relative, location, message.message);
		} else {
			gutil.log(type, file.relative, message.message);
		}

		if (erroredLine) {
			gutil.log(erroredLine);
		}
	});

	return success;
}

module.exports = function (options) {
	options = options || {};

	// I typo'd this and didn't want to break BC
	if (typeof options.uri === 'string') {
		options.url = options.uri;
	}

	if (typeof options.url === 'string') {
		w3cjs.setW3cCheckUrl(options.url);
	}

	return through.obj(function (file, enc, callback) {
		if (file.isNull()) {
			return callback(null, file);
		}

		if (file.isStream()) {
			return callback(new gutil.PluginError('gulp-w3cjs', 'Streaming not supported'));
		}

		w3cjs.validate({
			proxy: options.proxy ? options.proxy : undefined,
			input: file.contents,
			callback: function (res) {
				file.w3cjs = {
					success: handleMessages(file, res.messages, options),
					messages: res.messages
				};

				callback(null, file);
			}
		});
	});
};

module.exports.setW3cCheckUrl = w3cjs.setW3cCheckUrl;
<commit_msg>Add optional reporter like CoffeeLint<commit_after>'use strict';

var through = require('through2');
var w3cjs = require('w3cjs');
var gutil = require('gulp-util');

/**
 * Handles messages.
 *
 * @param file The file array.
 * @param messages Array of messages returned by w3cjs.
 * @return boolean Return false if errors have occurred.
 */
function handleMessages(file, messages, options) {
	var success = true;
	var errorText = gutil.colors.red.bold('HTML Error:');
	var warningText = gutil.colors.yellow.bold('HTML Warning:');
	var infoText = gutil.colors.green.bold('HTML Info:');
	var lines = file.contents.toString().split(/\r\n|\r|\n/g);

	if (!Array.isArray(messages)) {
		gutil.log(warningText, 'Failed to run validation on', file.relative);

		// Not sure whether this should be true or false
		return true;
	}

	messages.forEach(function (message) {
		if (message.type === 'info' && !options.showInfo) {
			return;
		}

		if (message.type === 'error') {
			success = false;
		}

		var type = (message.type === 'error') ? errorText : ((message.type === 'info') ? infoText : warningText);

		var location = 'Line ' + (message.lastLine || 0) + ', Column ' + (message.lastColumn || 0) + ':';

		var erroredLine = lines[message.lastLine - 1];

		// If this is false, stream was changed since validation
		if (erroredLine) {
			var errorColumn = message.lastColumn;

			// Trim before if the error is too late in the line
			if (errorColumn > 60) {
				erroredLine = erroredLine.slice(errorColumn - 50);
				errorColumn = 50;
			}

			// Trim after so the line is not too long
			erroredLine = erroredLine.slice(0, 60);

			// Highlight character with error
			erroredLine =
				gutil.colors.grey(erroredLine.substring(0, errorColumn - 1)) +
				gutil.colors.red.bold(erroredLine[ errorColumn - 1 ]) +
				gutil.colors.grey(erroredLine.substring(errorColumn));
		}

		if (typeof(message.lastLine) !== 'undefined' || typeof(lastColumn) !== 'undefined') {
			gutil.log(type, file.relative, location, message.message);
		} else {
			gutil.log(type, file.relative, message.message);
		}

		if (erroredLine) {
			gutil.log(erroredLine);
		}
	});

	return success;
}

function reporter (message) {
	through2.obj(function(file, enc, cb) {
        cb(null, file);
        if (!file.w3cjs.success) {
            throw new gutil.PluginError('gulp-w3cjs', 'HTML validation error(s) found');
        }
    });
}

module.exports = function (options) {
	options = options || {};

	// I typo'd this and didn't want to break BC
	if (typeof options.uri === 'string') {
		options.url = options.uri;
	}

	if (typeof options.url === 'string') {
		w3cjs.setW3cCheckUrl(options.url);
	}

	return through.obj(function (file, enc, callback) {
		if (file.isNull()) {
			return callback(null, file);
		}

		if (file.isStream()) {
			return callback(new gutil.PluginError('gulp-w3cjs', 'Streaming not supported'));
		}

		w3cjs.validate({
			proxy: options.proxy ? options.proxy : undefined,
			input: file.contents,
			callback: function (res) {
				file.w3cjs = {
					success: handleMessages(file, res.messages, options),
					messages: res.messages
				};

				callback(null, file);
			}
		});
	});
};

module.exports.reporter = reporter;
module.exports.setW3cCheckUrl = w3cjs.setW3cCheckUrl;
<|endoftext|>


<commit_before>var fs = require('fs')
var parse = require('css-parse')
var deepEqual = require('deep-equal')

var pkg = require('./package.json')

module.exports = Tecsst

function Tecsst (cssPath) {
    if (!(this instanceof Tecsst)) return new Tecsst(cssPath);

    this.cssPath = cssPath
    this.css = fs.readFileSync(cssPath, 'utf-8').trim()
    this.ast = parse(this.css)
    this.okCount = 0
    this.failedCount = 0
    this.testNum = this.okCount + this.failedCount

    console.log("Tecsst version: " + pkg.version + "\n")
}

Tecsst.prototype.parse = function (s) {
    this.selector = s

    var re = new RegExp(s)
    var properties = []
    var values = []
    var ret = []

    this.ast.stylesheet.rules.forEach(function (rule) {
        rule.selectors.forEach(function (selector) {
            if (selector.match(re)) {
                rule.declarations.forEach(function (declaration) {
                    properties.push(declaration.property)
                    values.push(declaration.value)
                })
            }
        })
    })

    for (var i = 0; i < properties.length; i++) {
        ret.push(properties[i] + ": " + values[i]);
    }

    return ret
}

Tecsst.prototype.equal = function (expected, result, desc) {
    if (!desc) desc = this.selector

    if (deepEqual(expected, result)) {
        console.log("# " + desc + ": " + '\033[32m' + "\nok" + '\033[39m')
        this.okCount++
        return "ok"
    } else {
        console.log("# " + desc + ": " + '\033[31m' + "\nnot ok" + '\033[39m')
        this.failedCount++
        return "not ok"
    }
}

Tecsst.prototype.end = function () {
    if (this.failedCount) {
        console.log('\n\033[31m' + "test failed" + '\033[39m')
    }
    else {
        console.log('\n\033[32m' + "all green, test clear!" + '\033[39m')
    }
}
<commit_msg>view all tests and pass test number<commit_after>var fs = require('fs')
var parse = require('css-parse')
var deepEqual = require('deep-equal')

var pkg = require('./package.json')

module.exports = Tecsst

function Tecsst (cssPath) {
    if (!(this instanceof Tecsst)) return new Tecsst(cssPath);

    this.cssPath = cssPath
    this.css = fs.readFileSync(cssPath, 'utf-8').trim()
    this.ast = parse(this.css)
    this.okCount = 0
    this.failedCount = 0
    this.testNum = 0

    console.log("Tecsst version: " + pkg.version + "\n")
}

Tecsst.prototype.parse = function (s) {
    this.selector = s

    var re = new RegExp(s)
    var properties = []
    var values = []
    var ret = []

    this.ast.stylesheet.rules.forEach(function (rule) {
        rule.selectors.forEach(function (selector) {
            if (selector.match(re)) {
                rule.declarations.forEach(function (declaration) {
                    properties.push(declaration.property)
                    values.push(declaration.value)
                })
            }
        })
    })

    for (var i = 0; i < properties.length; i++) {
        ret.push(properties[i] + ": " + values[i]);
    }

    return ret
}

Tecsst.prototype.equal = function (expected, result, desc) {
    if (!desc) desc = this.selector

    if (deepEqual(expected, result)) {
        console.log("# " + desc + ": " + '\033[32m' + "\nok" + '\033[39m')
        this.okCount++
        this.testNum++

        return "ok"
    } else {
        console.log("# " + desc + ": " + '\033[31m' + "\nnot ok" + '\033[39m')
        this.failedCount++
        this.testNum++

        return "not ok"
    }
}

Tecsst.prototype.end = function () {
    console.log("\n# tests " + this.testNum)
    console.log('\033[32m' + "# pass " + this.okCount + '\033[39m')

    if (this.failedCount) {
        console.log('\n\033[31m' + "test failed" + '\033[39m')
    }
    else {
        console.log('\n\033[32m' + "all green, test clear!" + '\033[39m')
    }
}
<|endoftext|>


<commit_before>import CircularProgress from './src/CircularProgress';
import AnimatedCircularProgress from './src/AnimatedCircularProgress';

exports.CircularProgress = CircularProgress;
exports.AnimatedCircularProgress = AnimatedCircularProgress;
<commit_msg>Update index.js<commit_after>export { default as CircularProgress } from './src/CircularProgress';
export { default as AnimatedCircularProgress } from './src/AnimatedCircularProgress';
<|endoftext|>