<commit_before>'use strict';

const

/* node modules */
_     = require( 'lodash' ),
path  = require( 'path' ),
chalk = require( 'chalk' ),
glob  = require( 'glob' ),
fs    = require( 'fs-extra-promise' ),
watch = require( 'node-watch' ),

/* config generation */

defaultConfig = require( './defaultConfig.js' ),

generateIndexConfig = config => ({

  title: !!config.title ? config.title : defaultConfig.title,

  meta: _.union( config.meta, defaultConfig.meta ),
  links: _.union( config.links, defaultConfig.links ),
  scripts: _.union( config.scripts, defaultConfig.scripts ),

}),

/* buffer creation */

buildTitle = title => `<title>${title}</title>`,

buildTag = type => tagObj => {
  console.log( `\t[${chalk.magenta(type)}] ${ _.map( tagObj, ( value, attribute ) => attribute + ': ' + value ).join( ', ' ) }` );
  return `<${type} ${ _.map( tagObj, ( value, attribute ) => attribute + '="' + value + '"' ).join( ' ' ) }>`;
},

buildScriptTag = config => {

  const log = `\t[${chalk.magenta('script')}] `;

  if ( _.isString( config ) ) {

    console.log( log + config );

    return `<script type="application/javascript" src="${config}" ></script>`;

  } else if ( _.isFunction( config ) ) {

    console.log( log + config.toString() );

    return `<script type="application/javascript" >;(${config})();</script>`;

  } else if ( _.isObject( config ) ) {

    console.log( log + _.map( config, ( value, attribute ) => attribute + '="' + value + '"' ).join( ', ' ) )

    if ( !!config.module ) {

      return buildScript( scriptModules[config.module](config) );

    } else {

      return `<script ${ _.map( tagObj, ( value, attribute ) => attribute + '="' + value + '"' ).join( ' ' ) }></script>`;

    }

  } else {

    throw new TypeError( `buildScriptTag( config ) failed, the argument (${ config }) is not of an acceptable type` );

  }

},

getPaths = config => {

  let
    javascriptFiles = glob.sync( `${global.source}/**/*.js`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.js`,`${global.source}/app.js`] ) } ),
    cssFiles = glob.sync( `${global.source}/**/*.css`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.css`] ) } ),
    sassFiles = glob.sync( `${global.source}/**/*.sass`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.sass`] ) } ),
    scssFiles = glob.sync( `${global.source}/**/*.scss`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.scss`] ) } );

  sassFiles       = _.map( sassFiles, sassFile => sassFile.replace( 'sass', 'css' ) );
  scssFiles       = _.map( scssFiles, scssFile => scssFile.replace( 'scss', 'css' ) );
  cssFiles        = _.union( cssFiles, sassFiles, scssFiles );
  cssFiles        = _.map( cssFiles, cssFile => path.relative( global.source, cssfile ) );
  javascriptFiles = _.map( javascriptFiles, javascriptFile => path.relative( global.source, javascriptFile ) );

  return { css: cssFiles, js: javascriptFiles };

},

tab = tabs => _.repeat( '\t', tabs ),

createIndexBuffer = ( config, minify ) => {

  console.log(`Building ${chalk.cyan('index.html')}`)

  minify = !!minify ? 0 : 1;

  const
    index = [],
    paths = getPaths( config );

  index.push( '' );
  index.push( `${tab(1*minify)}<head>` );

  if ( minify === 1 ) { index.push(''); }
  index.push( `${tab(2*minify)}<title>${config.title}</title>` );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( config.meta, tagConfig => index.push( tab(2*minify) + buildTag( 'meta' )( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( config.links, tagConfig => index.push( tab(2*minify) + buildTag( 'link' )( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( paths.css, cssPath => index.push( tab(2*minify) + buildTag( 'links' )({ href: cssPath, rel: 'stylesheet', title: path.basename( cssPath, '.css' ) }) ) );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( config.scripts, tagConfig => index.push( tab(2*minify) + buildScriptTag( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  index.push( `${tab(1*minify)}</head>` );
  index.push( `${tab(1*minify)}<body>` );

  if ( minify === 1 ) { index.push(''); }

  index.push( tab(2*minify) + '

' );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( paths.js, tagConfig => index.push( tab(2*minify) + buildScriptTag( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  index.push( `${tab(1*minify)}</body>` );
  index.push( '' );

  return index.join( minify === 1 ? '\n' : ''  );

},

buildIndexFile = ( destination, configPath, minify, ignore ) => () => {

  delete require.cache[require.resolve(configPath)];

  fs
    .outputFileAsync( `${destination}/index.html`, createIndexBuffer( generateIndexConfig( require(configPath) ), minify ) )
    .catch( error => {

      throw `buildIndexFile failed :  ${error}`;

      if ( ignore ) { process.exit(1); }

    } );

},

index = ( flags, configPath, destination ) => {

  const buildFunction = buildIndexFile( destination, configPath, flags.minify, flags.ignore );

  buildFunction();

  if ( flags.watch ) {

    watch( configPath, buildFunction );

  }

};

module.exports = index;<commit_msg>default css<commit_after>'use strict';

const

/* node modules */
_     = require( 'lodash' ),
path  = require( 'path' ),
chalk = require( 'chalk' ),
glob  = require( 'glob' ),
fs    = require( 'fs-extra-promise' ),
watch = require( 'node-watch' ),

/* config generation */

defaultConfig = require( './defaultConfig.js' ),

generateIndexConfig = config => ({

  title: !!config.title ? config.title : defaultConfig.title,

  meta: _.union( config.meta, defaultConfig.meta ),
  links: _.union( config.links, defaultConfig.links ),
  scripts: _.union( config.scripts, defaultConfig.scripts ),

}),

/* buffer creation */

buildTitle = title => `<title>${title}</title>`,

buildTag = type => tagObj => {
  console.log( `\t[${chalk.magenta(type)}] ${ _.map( tagObj, ( value, attribute ) => attribute + ': ' + value ).join( ', ' ) }` );
  return `<${type} ${ _.map( tagObj, ( value, attribute ) => attribute + '="' + value + '"' ).join( ' ' ) }>`;
},

buildScriptTag = config => {

  const log = `\t[${chalk.magenta('script')}] `;

  if ( _.isString( config ) ) {

    console.log( log + config );

    return `<script type="application/javascript" src="${config}" ></script>`;

  } else if ( _.isFunction( config ) ) {

    console.log( log + config.toString() );

    return `<script type="application/javascript" >;(${config})();</script>`;

  } else if ( _.isObject( config ) ) {

    console.log( log + _.map( config, ( value, attribute ) => attribute + '="' + value + '"' ).join( ', ' ) )

    if ( !!config.module ) {

      return buildScript( scriptModules[config.module](config) );

    } else {

      return `<script ${ _.map( tagObj, ( value, attribute ) => attribute + '="' + value + '"' ).join( ' ' ) }></script>`;

    }

  } else {

    throw new TypeError( `buildScriptTag( config ) failed, the argument (${ config }) is not of an acceptable type` );

  }

},

getPaths = config => {

  let
    javascriptFiles = glob.sync( `${global.source}/**/*.js`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.js`,`${global.source}/app.js`] ) } ),
    cssFiles = glob.sync( `${global.source}/**/*.css`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.css`] ) } ),
    sassFiles = glob.sync( `${global.source}/**/*.sass`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.sass`] ) } ),
    scssFiles = glob.sync( `${global.source}/**/*.scss`, { ignore: _.union( config.ignore, [`${global.source}/**/_*.scss`] ) } );

  sassFiles       = _.map( sassFiles, sassFile => sassFile.replace( 'sass', 'css' ) );
  scssFiles       = _.map( scssFiles, scssFile => scssFile.replace( 'scss', 'css' ) );
  cssFiles        = _.union( cssFiles, sassFiles, scssFiles );
  cssFiles        = _.map( cssFiles, cssFile => path.relative( global.source, cssfile ) );
  javascriptFiles = _.map( javascriptFiles, javascriptFile => path.relative( global.source, javascriptFile ) );

  return { css: cssFiles, js: javascriptFiles };

},

tab = tabs => _.repeat( '\t', tabs ),

createIndexBuffer = ( config, minify ) => {

  console.log(`Building ${chalk.cyan('index.html')}`)

  minify = !!minify ? 0 : 1;

  const
    index = [],
    paths = getPaths( config );

  index.push( '' );
  index.push( `${tab(1*minify)}<head>` );

  if ( minify === 1 ) { index.push(''); }
  index.push( `${tab(2*minify)}<title>${config.title}</title>` );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( config.meta, tagConfig => index.push( tab(2*minify) + buildTag( 'meta' )( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( config.links, tagConfig => index.push( tab(2*minify) + buildTag( 'link' )( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( paths.css, cssPath => index.push( tab(2*minify) + buildTag( 'links' )({ href: cssPath, rel: 'stylesheet', title: path.basename( cssPath, '.css' ) }) ) );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( config.scripts, tagConfig => index.push( tab(2*minify) + buildScriptTag( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  index.push( tab(2*minify) + '' );

  if ( minify === 1 ) { index.push(''); }

  index.push( `${tab(1*minify)}</head>` );
  index.push( `${tab(1*minify)}<body>` );

  if ( minify === 1 ) { index.push(''); }

  index.push( tab(2*minify) + '

' );

  if ( minify === 1 ) { index.push(''); }

  _.forEach( paths.js, tagConfig => index.push( tab(2*minify) + buildScriptTag( tagConfig ) ) );

  if ( minify === 1 ) { index.push(''); }

  index.push( `${tab(1*minify)}</body>` );
  index.push( '' );

  return index.join( minify === 1 ? '\n' : ''  );

},

buildIndexFile = ( destination, configPath, minify, ignore ) => () => {

  delete require.cache[require.resolve(configPath)];

  fs
    .outputFileAsync( `${destination}/index.html`, createIndexBuffer( generateIndexConfig( require(configPath) ), minify ) )
    .catch( error => {

      throw `buildIndexFile failed :  ${error}`;

      if ( ignore ) { process.exit(1); }

    } );

},

index = ( flags, configPath, destination ) => {

  const buildFunction = buildIndexFile( destination, configPath, flags.minify, flags.ignore );

  buildFunction();

  if ( flags.watch ) {

    watch( configPath, buildFunction );

  }

};

module.exports = index;<|endoftext|>


<commit_before>import * as RebelCore from 'rebel-core';

export class RebelRouter {
    constructor() {
        this.paths = {};
        return this;
    }
    add(path, ViewClass) {
        let name = ViewClass.name.replace(/\W+/g, '-').replace(/([a-z\d])([A-Z0-9])/g, '$1-$2').toLowerCase();
        document.registerElement(name, ViewClass);
        if (Array.isArray(path)) {
            path.forEach((item) => {
                this.paths[item] = name;
            });
        } else {
            this.paths[path] = name;
        }
        return this;
    }
    create(name) {
        name = name.toLowerCase();
        if (RebelCore.validElementTag(name) === true) {
            let $constructor = document.registerElement(name, RebelView);
            let $view = new $constructor();
            $view.paths = this.paths;
            return $view;
        } else {
            throw new Error("Invalid router name provided");
        }
    }
    static getPathFromUrl() {
        var result = window.location.href.match(/#(.*)$/);
        if (result !== null) {
            return result[1];
        }
    }
    static getParamsFromUrl(regex, route, path) {
        var result = RebelCore.parseQueryString(path);
        var re = /{(\w+)}/g;
        var results = [];
        let match;
        while (match = re.exec(route)) {
            results.push(match[1]);
        }
        var results2 = regex.exec(path);
        results.forEach(function(item, idx){
            result[item] = results2[idx + 1];
        });
        return result;
    }
}

class RebelView extends HTMLElement {
    createdCallback() {
        this.createShadowRoot();
    }
    attachedCallback() {
        this.render();
        window.onhashchange = (event) => {
            if (event.newURL != event.oldURL) {
                this.render();
            }
        };
    }
    current() {
        const path = RebelRouter.getPathFromUrl();
        for (const route in this._paths) {
            let regexString = "^" + route.replace(/{\w+}\/?/g, "(\\w+)\/?");
            regexString += (regexString.indexOf("\\/?") > -1) ? "" : "\\/?" + "([?=&\\w+]+)?$";
            const regex = new RegExp(regexString);
            if (regex.test(path)) {
                let result = {};
                result.templateName = this._paths[route];
                result.route = route;
                result.path = path;
                result.params = RebelRouter.getParamsFromUrl(regex, route, path);
                return result;
            }
        }
        return null;
    }
    render() {
        this.shadowRoot.innerHTML = "";
        const result = this.current();
        if (result !== null) {
            let $template = document.createElement(result.templateName);
            $template.setAttribute("rbl-url-params", JSON.stringify(result.params));
            this.shadowRoot.appendChild($template);
        }
    }
    set paths(value) {
        this._paths = value;
    }
}<commit_msg>Major changes to how the router works to ensure you can have multiple instances of a router<commit_after>/**
 * Created by Leon Revill on 15/12/2015.
 * Blog: http://www.revilweb.com
 * GitHub: https://github.com/RevillWeb
 * Twitter: @RevillWeb
 */

import * as RebelCore from 'rebel-core';

export class RebelRouter extends HTMLElement {
    attachedCallback() {
        this.createShadowRoot();
        this.render();
        RebelRouter.hashChange(() => {
            this.render();
        });
    }
    current() {
        const path = RebelRouter.getPathFromUrl();
        for (const route in this.paths) {
            let regexString = "^" + route.replace(/{\w+}\/?/g, "(\\w+)\/?");
            regexString += (regexString.indexOf("\\/?") > -1) ? "" : "\\/?" + "([?=&\\w+]+)?$";
            const regex = new RegExp(regexString);
            if (regex.test(path)) {
                let result = {};
                result.templateName = this.paths[route];
                result.route = route;
                result.path = path;
                result.params = RebelRouter.getParamsFromUrl(regex, route, path);
                return result;
            }
        }
        return null;
    }
    render() {
        this.shadowRoot.innerHTML = "";
        const result = this.current();
        if (result !== null) {
            let $template = document.createElement(result.templateName);
            $template.setAttribute("rbl-url-params", JSON.stringify(result.params));
            this.shadowRoot.appendChild($template);
        }
    }
    add(path, ViewClass) {
        if (this.paths === undefined) {
            this.paths = {};
        }
        let name = ViewClass.name.replace(/\W+/g, '-').replace(/([a-z\d])([A-Z0-9])/g, '$1-$2').toLowerCase();
        document.registerElement(name, ViewClass);
        if (Array.isArray(path)) {
            path.forEach((item) => {
                this.paths[item] = name;
            });
        } else {
            this.paths[path] = name;
        }
    }
    static changeCallbacks;
    static hashChange(callback) {
        if (RebelRouter.changeCallbacks === undefined) {
            RebelRouter.changeCallbacks = [];
        }
        RebelRouter.changeCallbacks.push(callback);
        window.onhashchange = (event) => {
            if (event.newURL != event.oldURL) {
                RebelRouter.changeCallbacks.forEach(function(callback){
                    callback();
                });
            }
        };
    }
    static getPathFromUrl() {
        var result = window.location.href.match(/#(.*)$/);
        if (result !== null) {
            return result[1];
        }
    }
    static getParamsFromUrl(regex, route, path) {
        var result = RebelCore.parseQueryString(path);
        var re = /{(\w+)}/g;
        var results = [];
        let match;
        while (match = re.exec(route)) {
            results.push(match[1]);
        }
        var results2 = regex.exec(path);
        results.forEach(function(item, idx){
            result[item] = results2[idx + 1];
        });
        return result;
    }
}<|endoftext|>


<commit_before>// reference all the utility sub-modueles.
exports.StringUtils       		= require('./lib/string-utilities');
exports.ErrorUtils        		= require('./lib/error-utilities');
exports.FormUtils        		= require('./lib/form-utilities');
exports.ResponseUtils     		= require('./lib/response-utilities');
exports.NumberUtils     		= require('./lib/number-utilities');<commit_msg>Adding reference to mongo utilities.<commit_after>// reference all the utility sub-modueles.
exports.StringUtils       		= require('./lib/string-utilities');
exports.ErrorUtils        		= require('./lib/error-utilities');
exports.FormUtils        		= require('./lib/form-utilities');
exports.ResponseUtils     		= require('./lib/response-utilities');
exports.NumberUtils     		= require('./lib/number-utilities');
exports.MongoUtils     		    = require('./lib/mongo-utilities');<|endoftext|>


<commit_before>'use strict';

const PluginError = require('plugin-error');
const rocambole = require('rocambole');
const through = require('through2');

module.exports = () => {
    let out = '';

    return through.obj((file, enc, cb) => {
        if (file.isNull()) {
            return cb(null, file);
        }

        if (file.isStream()) {
            return cb(new PluginError('gulp-debug-finder', 'Streaming not supported.'));
        }

        try {
            const contents = file.contents.toString();

            rocambole.moonwalk(contents, (node) => {
                const expression = node.callee || {};

                if (node.type !== 'CallExpression' || expression.type !== 'MemberExpression') {
                    return;
                }

                const maybeIdent = expression.object || {};

                if (maybeIdent.type === 'Identifier' && maybeIdent.name === 'console' && expression.property) {
                    out = 'There are JavaScript debug statements present.';
                }
            });
        } catch (e) {
            this.emit('error', new PluginError('gulp-debug-finder', e, {
                fileName: file.path
            }));
        }

        return cb();
    }, function (cb) {
        if (out) {
            this.emit('error', new PluginError('gulp-debug-finder', out, {
                showStack: false
            }));
        }

        return cb();
    });
};
<commit_msg>Fix this issue with arrow function<commit_after>'use strict';

const PluginError = require('plugin-error');
const rocambole = require('rocambole');
const through = require('through2');

module.exports = () => {
    let out = '';

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

        if (file.isStream()) {
            return cb(new PluginError('gulp-debug-finder', 'Streaming not supported.'));
        }

        try {
            const contents = file.contents.toString();

            rocambole.moonwalk(contents, (node) => {
                const expression = node.callee || {};

                if (node.type !== 'CallExpression' || expression.type !== 'MemberExpression') {
                    return;
                }

                const maybeIdent = expression.object || {};

                if (maybeIdent.type === 'Identifier' && maybeIdent.name === 'console' && expression.property) {
                    out = 'There are JavaScript debug statements present.';
                }
            });
        } catch (e) {
            this.emit('error', new PluginError('gulp-debug-finder', e, {
                fileName: file.path
            }));
        }

        return cb();
    }, function (cb) {
        if (out) {
            this.emit('error', new PluginError('gulp-debug-finder', out, {
                showStack: false
            }));
        }

        return cb();
    });
};
<|endoftext|>


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

var bind = require('bind');
var type = require('type');
var json = require('json');
var events = require('event');
var qs = require('querystring');
var errors = require('../errors');
var debug = require('debug')('recurly:open');

/**
 * Issues an API request to a popup window.
 *
 * TODO(*): configurable window name?
 * TODO(*): configurable window properties?
 *
 * @param {String} url
 * @param {Object} [data]
 * @param {Function} [done]
 * @throws {Error} If `configure` has not been called.
 * @return {Window}
 * @private
 */

exports.open = function (url, data, done) {
  debug('open');

  if (false === this.configured) {
    throw errors('not-configured');
  }

  if ('function' == type(data)) {
    done = data;
    data = {};
  }

  data = data || {};
  data.version = this.version;
  data.event = 'recurly-open-' + this.id++;
  data.key = this.config.publicKey;
  this.once(data.event, done);

  if (!/^https?:\/\//.test(url)) url = this.url(url);
  url += (~url.indexOf('?') ? '&' : '?') + qs.stringify(data);

  this.relay(function () {
    window.open(url);
  });
};

/**
 * Relay mixin.
 *
 * Inspects the window for intent to relay a message,
 * then attempts to send it off. closes the window once
 * dispatched.
 *
 * @param {Function} done
 * @private
 */

exports.relay = function (done) {
  var self = this;

  if (false === this.configured) {
    throw errors('not-configured');
  }

  events.bind(window, 'message', function listener (event) {
    var data = json.parse(event.data);
    var name = data.recurly_event;
    var body = data.recurly_message;
    var err = body.error ? errors('api-error', body.error) : null;
    events.unbind(window, 'message', listener);
    if (name) self.emit(name, err, body);
    if (frame) document.body.removeChild(frame);
  });

  if ('documentMode' in document) {
    var frame = document.createElement('iframe');
    frame.width = frame.height = 0;
    frame.src = this.url('/relay');
    frame.name = 'recurly-relay';
    frame.style.display = 'none';
    frame.onload = bind(this, done);
    document.body.appendChild(frame);
  } else {
    done();
  }
};
<commit_msg>Fixes relay name<commit_after>
/*!
 * Module dependencies.
 */

var bind = require('bind');
var type = require('type');
var json = require('json');
var events = require('event');
var qs = require('querystring');
var errors = require('../errors');
var debug = require('debug')('recurly:open');

/**
 * Issues an API request to a popup window.
 *
 * TODO(*): configurable window name?
 * TODO(*): configurable window properties?
 *
 * @param {String} url
 * @param {Object} [data]
 * @param {Function} [done]
 * @throws {Error} If `configure` has not been called.
 * @return {Window}
 * @private
 */

exports.open = function (url, data, done) {
  debug('open');

  if (false === this.configured) {
    throw errors('not-configured');
  }

  if ('function' == type(data)) {
    done = data;
    data = {};
  }

  data = data || {};
  data.version = this.version;
  data.event = 'recurly-open-' + this.id++;
  data.key = this.config.publicKey;
  this.once(data.event, done);

  if (!/^https?:\/\//.test(url)) url = this.url(url);
  url += (~url.indexOf('?') ? '&' : '?') + qs.stringify(data);

  this.relay(function () {
    window.open(url);
  });
};

/**
 * Relay mixin.
 *
 * Inspects the window for intent to relay a message,
 * then attempts to send it off. closes the window once
 * dispatched.
 *
 * @param {Function} done
 * @private
 */

exports.relay = function (done) {
  var self = this;

  if (false === this.configured) {
    throw errors('not-configured');
  }

  events.bind(window, 'message', function listener (event) {
    var data = json.parse(event.data);
    var name = data.recurly_event;
    var body = data.recurly_message;
    var err = body.error ? errors('api-error', body.error) : null;
    events.unbind(window, 'message', listener);
    if (name) self.emit(name, err, body);
    if (frame) document.body.removeChild(frame);
  });

  if ('documentMode' in document) {
    var frame = document.createElement('iframe');
    frame.width = frame.height = 0;
    frame.src = this.url('/relay');
    frame.name = 'recurly_relay';
    frame.style.display = 'none';
    frame.onload = bind(this, done);
    document.body.appendChild(frame);
  } else {
    done();
  }
};
<|endoftext|>


<commit_before>/*!
* vdom-virtualize
* Copyright 2014 by Marcel Klehr <mklehr@gmx.net>
*
* (MIT LICENSE)
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var VNode = require("virtual-dom/vnode/vnode")
  , VText = require("virtual-dom/vnode/vtext")
  , VComment = require("./vcomment")

module.exports = createVNode

function createVNode(domNode, key) {
  key = key || null // XXX: Leave out `key` for now... merely used for (re-)ordering

  if(domNode.nodeType == 1) return createFromElement(domNode, key)
  if(domNode.nodeType == 3) return createFromTextNode(domNode, key)
  if(domNode.nodeType == 8) return createFromCommentNode(domNode, key)
  return
}

createVNode.fromHTML = function(html, key) {
  var rootNode = null;

  try {
    // Everything except iOS 7 Safari, IE 8/9, Andriod Browser 4.1/4.3
    var parser = new DOMParser();
    var doc = parser.parseFromString(html, 'text/html');
    rootNode = doc.documentElement;
  } catch(e) {
    // Old browsers
    var ifr = document.createElement('iframe');
    ifr.setAttribute('data-content', html);
    ifr.src = 'javascript: window.frameElement.getAttribute("data-content");';
    document.head.appendChild(ifr);
    rootNode = ifr.contentDocument.documentElement;
    setTimeout(function() {
      ifr.remove(); // Garbage collection
    }, 0);
  }

  return createVNode(rootNode, key);
};

function createFromTextNode(tNode) {
  return new VText(tNode.nodeValue)
}

function createFromCommentNode(cNode) {
  return new VComment(cNode.nodeValue)
}

function createFromElement(el) {
  var tagName = el.tagName
  , namespace = el.namespaceURI == 'http://www.w3.org/1999/xhtml'? null : el.namespaceURI
  , properties = getElementProperties(el)
  , children = []

  for (var i = 0; i < el.childNodes.length; i++) {
    children.push(createVNode(el.childNodes[i]/*, i*/))
  }

  return new VNode(tagName, properties, children, null, namespace)
}

function getElementProperties(el) {
  var obj = {}

  for(var i=0; i<props.length; i++) {
    var propName = props[i]
    if(!el[propName]) continue

    // Special case: style
    // .style is a DOMStyleDeclaration, thus we need to iterate over all
    // rules to create a hash of applied css properties.
    //
    // You can directly set a specific .style[prop] = value so patching with vdom
    // is possible.
    if("style" == propName) {
      var css = {}
        , styleProp
      if ('undefined' !== typeof el.style.length) {
        for(var j=0; j<el.style.length; j++) {
          styleProp = el.style[i]
          css[styleProp] = el.style.getPropertyValue(styleProp) // XXX: add support for "!important" via getPropertyPriority()!
        }
      } else { // IE8
        for (var styleProp in el.style) {
          if (el.style[styleProp] && el.style.hasOwnProperty(styleProp)) {
            css[styleProp] = el.style[styleProp];
          }
        }
      }

      if(Object.keys(css).length) obj[propName] = css
      continue
    }

    // https://msdn.microsoft.com/en-us/library/cc848861%28v=vs.85%29.aspx
    // The img element does not support the HREF content attribute.
    // In addition, the href property is read-only for the img Document Object Model (DOM) object
    if (el.tagName.toLowerCase() === 'img' && propName === 'href') {
      continue;
    }

    // Special case: dataset
    // we can iterate over .dataset with a simple for..in loop.
    // The all-time foo with data-* attribs is the dash-snake to camelCase
    // conversion.
    //
    // *This is compatible with h(), but not with every browser, thus this section was removed in favor
    // of attributes (specified below)!*
    //
    // .dataset properties are directly accessible as transparent getters/setters, so
    // patching with vdom is possible.
    /*if("dataset" == propName) {
      var data = {}
      for(var p in el.dataset) {
        data[p] = el.dataset[p]
      }
      obj[propName] = data
      return
    }*/

    // Special case: attributes
    // these are a NamedNodeMap, but we can just convert them to a hash for vdom,
    // because of https://github.com/Matt-Esch/virtual-dom/blob/master/vdom/apply-properties.js#L57
    if("attributes" == propName){
      var atts = Array.prototype.slice.call(el[propName]);
      var hash = atts.reduce(function(o,a){
        var name = a.name;
        if(obj[name]) return o;
        o[name] = el.getAttribute(a.name);
        return o;
      },{});
      obj[propName] = hash;
      continue
    }
    if("tabIndex" == propName && el.tabIndex === -1) continue

    // Special case: contentEditable
    // browser use 'inherit' by default on all nodes, but does not allow setting it to ''
    // diffing virtualize dom will trigger error
    // ref: https://github.com/Matt-Esch/virtual-dom/issues/176
    if("contentEditable" == propName && el[propName] === 'inherit') continue

    if('object' === typeof el[propName]) continue

    // default: just copy the property
    obj[propName] = el[propName]
  }

  return obj
}

/**
 * DOMNode property white list
 * Taken from https://github.com/Raynos/react/blob/dom-property-config/src/browser/ui/dom/DefaultDOMPropertyConfig.js
 */
var props =

module.exports.properties = [
 "accept"
,"accessKey"
,"action"
,"alt"
,"async"
,"autoComplete"
,"autoPlay"
,"cellPadding"
,"cellSpacing"
,"checked"
,"className"
,"colSpan"
,"content"
,"contentEditable"
,"controls"
,"crossOrigin"
,"data"
//,"dataset" removed since attributes handles data-attributes
,"defer"
,"dir"
,"download"
,"draggable"
,"encType"
,"formNoValidate"
,"href"
,"hrefLang"
,"htmlFor"
,"httpEquiv"
,"icon"
,"id"
,"label"
,"lang"
,"list"
,"loop"
,"max"
,"mediaGroup"
,"method"
,"min"
,"multiple"
,"muted"
,"name"
,"noValidate"
,"pattern"
,"placeholder"
,"poster"
,"preload"
,"radioGroup"
,"readOnly"
,"rel"
,"required"
,"rowSpan"
,"sandbox"
,"scope"
,"scrollLeft"
,"scrolling"
,"scrollTop"
,"selected"
,"span"
,"spellCheck"
,"src"
,"srcDoc"
,"srcSet"
,"start"
,"step"
,"style"
,"tabIndex"
,"target"
,"title"
,"type"
,"value"

// Non-standard Properties
,"autoCapitalize"
,"autoCorrect"
,"property"

, "attributes"
]

var attrs =
module.exports.attrs = [
 "allowFullScreen"
,"allowTransparency"
,"charSet"
,"cols"
,"contextMenu"
,"dateTime"
,"disabled"
,"form"
,"frameBorder"
,"height"
,"hidden"
,"maxLength"
,"role"
,"rows"
,"seamless"
,"size"
,"width"
,"wmode"

// SVG Properties
,"cx"
,"cy"
,"d"
,"dx"
,"dy"
,"fill"
,"fx"
,"fy"
,"gradientTransform"
,"gradientUnits"
,"offset"
,"points"
,"r"
,"rx"
,"ry"
,"spreadMethod"
,"stopColor"
,"stopOpacity"
,"stroke"
,"strokeLinecap"
,"strokeWidth"
,"textAnchor"
,"transform"
,"version"
,"viewBox"
,"x1"
,"x2"
,"x"
,"y1"
,"y2"
,"y"
]
<commit_msg>IE again<commit_after>/*!
* vdom-virtualize
* Copyright 2014 by Marcel Klehr <mklehr@gmx.net>
*
* (MIT LICENSE)
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var VNode = require("virtual-dom/vnode/vnode")
  , VText = require("virtual-dom/vnode/vtext")
  , VComment = require("./vcomment")

module.exports = createVNode

function createVNode(domNode, key) {
  key = key || null // XXX: Leave out `key` for now... merely used for (re-)ordering

  if(domNode.nodeType == 1) return createFromElement(domNode, key)
  if(domNode.nodeType == 3) return createFromTextNode(domNode, key)
  if(domNode.nodeType == 8) return createFromCommentNode(domNode, key)
  return
}

createVNode.fromHTML = function(html, key) {
  var rootNode = null;

  try {
    // Everything except iOS 7 Safari, IE 8/9, Andriod Browser 4.1/4.3
    var parser = new DOMParser();
    var doc = parser.parseFromString(html, 'text/html');
    rootNode = doc.documentElement;
  } catch(e) {
    // Old browsers
    var ifr = document.createElement('iframe');
    ifr.setAttribute('data-content', html);
    ifr.src = 'javascript: window.frameElement.getAttribute("data-content");';
    document.head.appendChild(ifr);
    rootNode = ifr.contentDocument.documentElement;
    setTimeout(function() {
      ifr.remove(); // Garbage collection
    }, 0);
  }

  return createVNode(rootNode, key);
};

function createFromTextNode(tNode) {
  return new VText(tNode.nodeValue)
}

function createFromCommentNode(cNode) {
  return new VComment(cNode.nodeValue)
}

function createFromElement(el) {
  var tagName = el.tagName
  , namespace = el.namespaceURI == 'http://www.w3.org/1999/xhtml'? null : el.namespaceURI
  , properties = getElementProperties(el)
  , children = []

  for (var i = 0; i < el.childNodes.length; i++) {
    children.push(createVNode(el.childNodes[i]/*, i*/))
  }

  return new VNode(tagName, properties, children, null, namespace)
}

function getElementProperties(el) {
  var obj = {}

  for(var i=0; i<props.length; i++) {
    var propName = props[i]
    if(!el[propName]) continue

    // Special case: style
    // .style is a DOMStyleDeclaration, thus we need to iterate over all
    // rules to create a hash of applied css properties.
    //
    // You can directly set a specific .style[prop] = value so patching with vdom
    // is possible.
    if("style" == propName) {
      var css = {}
        , styleProp
      if ('undefined' !== typeof el.style.length) {
        for(var j=0; j<el.style.length; j++) {
          styleProp = el.style[i]
          css[styleProp] = el.style.getPropertyValue(styleProp) // XXX: add support for "!important" via getPropertyPriority()!
        }
      } else { // IE8
        for (var styleProp in el.style) {
          if (el.style[styleProp] && el.style.hasOwnProperty(styleProp)) {
            css[styleProp] = el.style[styleProp];
          }
        }
      }

      if(Object.keys(css).length) obj[propName] = css
      continue
    }

    // https://msdn.microsoft.com/en-us/library/cc848861%28v=vs.85%29.aspx
    // The img element does not support the HREF content attribute.
    // In addition, the href property is read-only for the img Document Object Model (DOM) object
    if (el.tagName.toLowerCase() === 'img' && propName === 'href') {
      continue;
    }

    // Special case: dataset
    // we can iterate over .dataset with a simple for..in loop.
    // The all-time foo with data-* attribs is the dash-snake to camelCase
    // conversion.
    //
    // *This is compatible with h(), but not with every browser, thus this section was removed in favor
    // of attributes (specified below)!*
    //
    // .dataset properties are directly accessible as transparent getters/setters, so
    // patching with vdom is possible.
    /*if("dataset" == propName) {
      var data = {}
      for(var p in el.dataset) {
        data[p] = el.dataset[p]
      }
      obj[propName] = data
      return
    }*/

    // Special case: attributes
    // these are a NamedNodeMap, but we can just convert them to a hash for vdom,
    // because of https://github.com/Matt-Esch/virtual-dom/blob/master/vdom/apply-properties.js#L57
    if("attributes" == propName){
      var atts = Array.prototype.slice.call(el[propName]);
      var hash = {}
      for(var k=0; k<atts.length; k++){
        var name = atts[k].name;
        if(obj[name]) continue;
        hash[name] = el.getAttribute(name);
      }
      obj[propName] = hash;
      continue
    }
    if("tabIndex" == propName && el.tabIndex === -1) continue

    // Special case: contentEditable
    // browser use 'inherit' by default on all nodes, but does not allow setting it to ''
    // diffing virtualize dom will trigger error
    // ref: https://github.com/Matt-Esch/virtual-dom/issues/176
    if("contentEditable" == propName && el[propName] === 'inherit') continue

    if('object' === typeof el[propName]) continue

    // default: just copy the property
    obj[propName] = el[propName]
  }

  return obj
}

/**
 * DOMNode property white list
 * Taken from https://github.com/Raynos/react/blob/dom-property-config/src/browser/ui/dom/DefaultDOMPropertyConfig.js
 */
var props =

module.exports.properties = [
 "accept"
,"accessKey"
,"action"
,"alt"
,"async"
,"autoComplete"
,"autoPlay"
,"cellPadding"
,"cellSpacing"
,"checked"
,"className"
,"colSpan"
,"content"
,"contentEditable"
,"controls"
,"crossOrigin"
,"data"
//,"dataset" removed since attributes handles data-attributes
,"defer"
,"dir"
,"download"
,"draggable"
,"encType"
,"formNoValidate"
,"href"
,"hrefLang"
,"htmlFor"
,"httpEquiv"
,"icon"
,"id"
,"label"
,"lang"
,"list"
,"loop"
,"max"
,"mediaGroup"
,"method"
,"min"
,"multiple"
,"muted"
,"name"
,"noValidate"
,"pattern"
,"placeholder"
,"poster"
,"preload"
,"radioGroup"
,"readOnly"
,"rel"
,"required"
,"rowSpan"
,"sandbox"
,"scope"
,"scrollLeft"
,"scrolling"
,"scrollTop"
,"selected"
,"span"
,"spellCheck"
,"src"
,"srcDoc"
,"srcSet"
,"start"
,"step"
,"style"
,"tabIndex"
,"target"
,"title"
,"type"
,"value"

// Non-standard Properties
,"autoCapitalize"
,"autoCorrect"
,"property"

, "attributes"
]

var attrs =
module.exports.attrs = [
 "allowFullScreen"
,"allowTransparency"
,"charSet"
,"cols"
,"contextMenu"
,"dateTime"
,"disabled"
,"form"
,"frameBorder"
,"height"
,"hidden"
,"maxLength"
,"role"
,"rows"
,"seamless"
,"size"
,"width"
,"wmode"

// SVG Properties
,"cx"
,"cy"
,"d"
,"dx"
,"dy"
,"fill"
,"fx"
,"fy"
,"gradientTransform"
,"gradientUnits"
,"offset"
,"points"
,"r"
,"rx"
,"ry"
,"spreadMethod"
,"stopColor"
,"stopOpacity"
,"stroke"
,"strokeLinecap"
,"strokeWidth"
,"textAnchor"
,"transform"
,"version"
,"viewBox"
,"x1"
,"x2"
,"x"
,"y1"
,"y2"
,"y"
]
<|endoftext|>


<commit_before>'use strict';

const error = Bento.Error;
const API   = Bento.Helpers.Case.toParam(Bento.config.api.name);

/*
 |--------------------------------------------------------------------------------
 | Redis Bucket
 |--------------------------------------------------------------------------------
 |
 | This class is written to simplify the management of redis stores by placing
 | them in categorized buckets. The inspiration for this class was based on
 | the bucket concept presented in AWS S3 file stores.
 |
 | @author Christoffer Rødvik <snapgravy@gmail.com>
 |
 */

class RedisBucket {

  /**
   * Sets up the redis bucket class.
   * @param  {Object} redis
   * @param  {String} store
   * @return {Void}
   */
  constructor(redis, store) {
    this.redis = redis;
    this.store = store;
  }

  /**
   * Registers a new value with the redis store.
   * @param {String} id
   * @param {String} val
   * @param {Number} [expire]
   */
  *set(id, val, expire) {
    yield this.redis.set((this.store + id), val);
    if (expire) {
      yield this.expire(id, expire);
    }
  }

  // The same as above but dealing with lists...
  *lset(id, val, expire) {
    let key = this.store + id;

    yield this.redis.lpush(key, val);

    if (expire) {
      yield this.expire(id, expire);
    }

    // A hygenic lazy garbage collector
    if(Math.floor(Math.random() * 5) === 0) {
      let len = yield this.redis.llen(key);

      // We do some arbitrary cut-off
      if(len > 8) {

        // Drop us down to a smaller amount
        yield this.redis.ltrim(key, 0, len - 5);
      }
    }

  }

  /**
   * Registers a new JSON object with the redis store.
   * @param {String} id
   * @param {Object} val
   * @param {Number} [expire]
   */
  *setJSON(id, val, expire) {
    yield this.set(id, JSON.stringify(val));
    if (expire) {
      yield this.expire(id, expire);
    }
  }

  /**
   * Returns a registered value from the redis store.
   * @param  {String} id
   * @return {String}
   */
  *get(id) {
    return yield this.redis.get(this.store + id);
  }

  *lget(id, val) {
    // our arbitrary cutoff is pretty low, so this should be fine.
    let all = yield this.redis.lrange(this.store + id, 0, 100);

    // we make this backwards compatible with get by returning
    // the value in this case
    if (all.indexOf(val) != -1) {
      return val;
    }
  }

  /**
   * Returns a registered JSON object from the redis store.
   * @param  {String} id
   * @return {Object}
   */
  *getJSON(id) {
    let result = yield this.get(id);
    if (result) {
      return JSON.parse(result);
    }
    return null;
  }

  /**
   * Updates a JSON object with new data.
   * @param {String} id
   * @param {Object} data
   * @param {Number} [expire]
   */
  *putJSON(id, data, expire) {
    let stored = yield this.getJSON(id);
    if (!stored) {
      throw error.parse({
        code    : 'REDIS_BUCKET_NOT_FOUND',
        message : `The redis bucket ${ id } does not exist`
      }, 404);
    }
    yield this.setJSON(id, Object.assign(stored, data), expire);
  }

  /**
   * Deletes a redis key => value pair from the redis store.
   * @param  {String} id
   * @return {Object}
   */
  *del(id) {
    return yield this.redis.del(this.store + id);
  }

  *ldel(id, val) {
    return yield this.redis.lrem(this.store + id, val, 0);
  }

  /**
   * Updates, or sets an expiration timer on a registered key => value pair
   * in the redis store.
   * @param  {String} id
   * @param  {Number} timer
   * @return {Object}
   */
  *expire(id, timer) {
    return yield this.redis.expire((this.store + id), timer);
  }

  /**
   * Removes any expiration timer on the registered key => value pair
   * in the redis store.
   * @param  {String} id
   * @return {Object}
   */
  *persist(id) {
    return yield this.redis.persist(this.store + id);
  }

};

module.exports = function(redis, store) {
  return new RedisBucket(redis, API + ':' + store + ':');
};
<commit_msg>making list trimming more common<commit_after>'use strict';

const error = Bento.Error;
const API   = Bento.Helpers.Case.toParam(Bento.config.api.name);

/*
 |--------------------------------------------------------------------------------
 | Redis Bucket
 |--------------------------------------------------------------------------------
 |
 | This class is written to simplify the management of redis stores by placing
 | them in categorized buckets. The inspiration for this class was based on
 | the bucket concept presented in AWS S3 file stores.
 |
 | @author Christoffer Rødvik <snapgravy@gmail.com>
 |
 */

class RedisBucket {

  /**
   * Sets up the redis bucket class.
   * @param  {Object} redis
   * @param  {String} store
   * @return {Void}
   */
  constructor(redis, store) {
    this.redis = redis;
    this.store = store;
  }

  /**
   * Registers a new value with the redis store.
   * @param {String} id
   * @param {String} val
   * @param {Number} [expire]
   */
  *set(id, val, expire) {
    yield this.redis.set((this.store + id), val);
    if (expire) {
      yield this.expire(id, expire);
    }
  }

  // The same as above but dealing with lists...
  *lset(id, val, expire) {
    let key = this.store + id;

    yield this.redis.lpush(key, val);

    if (expire) {
      yield this.expire(id, expire);
    }

    // A hygenic lazy garbage collector
    if(Math.floor(Math.random() * 3) === 0) {
      let len = yield this.redis.llen(key);

      // We do some arbitrary cut-off
      if(len > 8) {

        // Drop us down to a smaller amount
        yield this.redis.ltrim(key, 0, len - 5);
      }
    }

  }

  /**
   * Registers a new JSON object with the redis store.
   * @param {String} id
   * @param {Object} val
   * @param {Number} [expire]
   */
  *setJSON(id, val, expire) {
    yield this.set(id, JSON.stringify(val));
    if (expire) {
      yield this.expire(id, expire);
    }
  }

  /**
   * Returns a registered value from the redis store.
   * @param  {String} id
   * @return {String}
   */
  *get(id) {
    return yield this.redis.get(this.store + id);
  }

  *lget(id, val) {
    // our arbitrary cutoff is pretty low, so this should be fine.
    let all = yield this.redis.lrange(this.store + id, 0, 100);

    // we make this backwards compatible with get by returning
    // the value in this case
    if (all.indexOf(val) != -1) {
      return val;
    }
  }

  /**
   * Returns a registered JSON object from the redis store.
   * @param  {String} id
   * @return {Object}
   */
  *getJSON(id) {
    let result = yield this.get(id);
    if (result) {
      return JSON.parse(result);
    }
    return null;
  }

  /**
   * Updates a JSON object with new data.
   * @param {String} id
   * @param {Object} data
   * @param {Number} [expire]
   */
  *putJSON(id, data, expire) {
    let stored = yield this.getJSON(id);
    if (!stored) {
      throw error.parse({
        code    : 'REDIS_BUCKET_NOT_FOUND',
        message : `The redis bucket ${ id } does not exist`
      }, 404);
    }
    yield this.setJSON(id, Object.assign(stored, data), expire);
  }

  /**
   * Deletes a redis key => value pair from the redis store.
   * @param  {String} id
   * @return {Object}
   */
  *del(id) {
    return yield this.redis.del(this.store + id);
  }

  *ldel(id, val) {
    return yield this.redis.lrem(this.store + id, val, 0);
  }

  /**
   * Updates, or sets an expiration timer on a registered key => value pair
   * in the redis store.
   * @param  {String} id
   * @param  {Number} timer
   * @return {Object}
   */
  *expire(id, timer) {
    return yield this.redis.expire((this.store + id), timer);
  }

  /**
   * Removes any expiration timer on the registered key => value pair
   * in the redis store.
   * @param  {String} id
   * @return {Object}
   */
  *persist(id) {
    return yield this.redis.persist(this.store + id);
  }

};

module.exports = function(redis, store) {
  return new RedisBucket(redis, API + ':' + store + ':');
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var request = require('request');
var Vow = require('vow');
var extend = require('extend');
var WebSocket = require('ws');
var EventEmitter = require('events').EventEmitter;

class Bot extends EventEmitter {
    /**
     * @param {object} params
     * @constructor
     */

     constructor(params) {
         super(params);
         this.token = params.token;
         this.name = params.name;

         console.assert(params.token, 'token must be defined');
         this.login();
     }

    /**
     * Starts a Real Time Messaging API session
     */
     login() {
         this._api('rtm.start').then((data) => {
             this.wsUrl = data.url;
             this.self = data.self;
             this.team = data.team;
             this.channels = data.channels;
             this.users = data.users;
             this.ims = data.ims;
             this.groups = data.groups;

             this.emit('start');

             this.connect();
         }).fail((data) => {
             this.emit('error', new Error(data.error ? data.error : data));
         }).done();
    }

    /**
     * Establish a WebSocket connection
     */
     connect() {
         this.ws = new WebSocket(this.wsUrl);

         this.ws.on('open', function(data) {
             this.emit('open', data);
         }.bind(this));

         this.ws.on('close', function(data) {
             this.emit('close', data);
         }.bind(this));

         this.ws.on('message', function(data) {
             try {
                 this.emit('message', JSON.parse(data));
             } catch (e) {
                 console.log(e);
             }
         }.bind(this));
     }

    /**
     * Get channels
     * @returns {vow.Promise}
     */
     getChannels() {
         if (this.channels) {
             return Vow.fulfill({ channels: this.channels });
         }
         return this._api('channels.list');
      }

    /**
     * Get users
     * @returns {vow.Promise}
     */
     getUsers() {
          if (this.users) {
              return Vow.fulfill({ members: this.users });
          }

          return this._api('users.list');
     }

    /**
     * Get groups
     * @returns {vow.Promise}
     */
    getGroups() {
        if (this.groups) {
            return Vow.fulfill({ groups: this.groups });
        }

        return this._api('groups.list');
    }

    /**
     * Get user by name
     * @param {string} name
     * @returns {object}
     */
    getUser(name) {
        return this.getUsers().then(function(data) {
            var res = _.find(data.members, { name: name });

            console.assert(res, 'user not found');
            return res;
        });
    }

    /**
     * Get channel by name
     * @param {string} name
     * @returns {object}
     */
    getChannel(name) {
        return this.getChannels().then(function(data) {
            var res = _.find(data.channels, { name: name });

            console.assert(res, 'channel not found');
            return res;
        });
    }

    /**
     * Get group by name
     * @param {string} name
     * @returns {object}
     */
    getGroup(name) {
        return this.getGroups().then(function(data) {
            var res = _.find(data.groups, { name: name });

            console.assert(res, 'group not found');
            return res;
        });
    }

    /**
     * Get user by id
     * @param {string} id
     * @returns {object}
     */
    getUserById(id) {
        return this.getUsers().then(function(data) {
            var res = _.find(data.members, { id: id });

            console.assert(res, 'user not found');
            return res;
        });
    }

     /**
      * Get channel by id
      * @param {string} id
      * @returns {object}
      */
    getChannelById(id) {
        return this.getChannels().then(function(data) {
            var res = _.find(data.channels, { id: id });

            console.assert(res, 'channel not found');
            return res;
        });
    }

     /**
      * Get group by id
      * @param {string} id
      * @returns {object}
     */
    getGroupById(id) {
        return this.getGroups().then(function(data) {
            var res = _.find(data.groups, { id: id });

            console.assert(res, 'group not found');
            return res;
        });
    }

    /**
     * Get channel ID
     * @param {string} name
     * @returns {string}
     */
    getChannelId(name) {
        return this.getChannel(name).then(function(channel) {
            return channel.id;
        });
    }

    /**
     * Get group ID
     * @param {string} name
     * @returns {string}
     */
    getGroupId(name) {
        return this.getGroup(name).then(function(group) {
            return group.id;
        });
    }

    /**
     * Get user ID
     * @param {string} name
     * @returns {string}
     */
    getUserId(name) {
        return this.getUser(name).then(function(user) {
           return user.id;
        });
    }

    /**
     * Get user by email
     * @param {string} email
     * @returns {object}
     */
    getUserByEmail(email) {
        return this.getUsers().then(function(data) {
            return _.find(data.members, { profile: { email: email } });
        });
    }

    /**
     * Get "direct message" channel ID
     * @param {string} name
     * @returns {vow.Promise}
     */
    getChatId(name) {
        return this.getUser(name).then(function(data) {

            var chatId = _.find(this.ims, { user: data.id });

            return (chatId && chatId.id) || this.openIm(data.id);
        }.bind(this)).then(function(data) {
            return typeof data === 'string' ? data : data.channel.id;
        });
    }

    /**
     * Opens a "direct message" channel with another member of your Slack team
     * @param {string} userId
     * @returns {vow.Promise}
     */
    openIm(userId) {
        return this._api('im.open', {user: userId});
    }

    /**
     * Posts an ephemeral message to a channel and user
     * @param {string} id - channel ID
     * @param {string} user - user ID
     * @param {string} text
     * @param {object} params
     * @returns {vow.Promise}
     */
    postEphemeral(id, user, text, params) {
        params = extend({
            text: text,
            channel: id,
            user: user,
            username: this.name
        }, params || {});

        return this._api('chat.postEphemeral', params);
    }

    /**
     * Posts a message to a channel by ID
     * @param {string} id - channel ID
     * @param {string} text
     * @param {object} params
     * @returns {vow.Promise}
     */
    postMessage(id, text, params) {
        params = extend({
            text: text,
            channel: id,
            username: this.name
        }, params || {});

        return this._api('chat.postMessage', params);
    }

     /**
      * Updates a message by timestamp
      * @param {string} id - channel ID
      * @param {string} ts - timestamp
      * @param {string} text
      * @param {object} params
      * @returns {vow.Promise}
      */
    updateMessage(id, ts, text, params) {
        params = extend({
            ts: ts,
            channel: id,
            username: this.name,
            text: text
        }, params || {});

        return this._api('chat.update', params);
    }

    /**
     * Posts a message to user by name
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postMessageToUser(name, text, params, cb) {
        return this._post((params || {}).slackbot ? 'slackbot' : 'user', name, text, params, cb);
    }

    /**
     * Posts a message to channel by name
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postMessageToChannel(name, text, params, cb) {
        return this._post('channel', name, text, params, cb);
    }

    /**
     * Posts a message to group by name
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postMessageToGroup(name, text, params, cb) {
        return this._post('group', name, text, params, cb);
    }

    /**
     * Common method for posting messages
     * @param {string} type
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     * @private
     */
    _post(type, name, text, params, cb) {
        var method = ({
            'group': 'getGroupId',
            'channel': 'getChannelId',
            'user': 'getChatId',
            'slackbot': 'getUserId'
        })[type];

        if (typeof params === 'function') {
            cb = params;
            params = null;
        }

        return this[method](name).then(function(itemId) {
            return this.postMessage(itemId, text, params);
        }.bind(this)).always(function(data) {
            if (cb) {
                cb(data._value);
            }
        });
    }

    /**
     * Posts a message to group | channel | user
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postTo(name, text, params, cb) {
        return Vow.all([this.getChannels(), this.getUsers(), this.getGroups()]).then(function(data) {

            name = this._cleanName(name);

            var all = [].concat(data[0].channels, data[1].members, data[2].groups);
            var result = _.find(all, {name: name});

            console.assert(result, 'wrong name');

            if (result['is_channel']) {
                return this.postMessageToChannel(name, text, params, cb);
            } else if (result['is_group']) {
                return this.postMessageToGroup(name, text, params, cb);
            } else {
                return this.postMessageToUser(name, text, params, cb);
            }
        }.bind(this));
    }

    /**
     * Remove @ or # character from group | channel | user name
     * @param {string} name
     * @returns {string}
     */
    _cleanName (name) {
        if (typeof name !== 'string') {
            return name;
        }

        var firstCharacter = name.charAt(0);
        if (firstCharacter === '#' || firstCharacter === '@') {
            name = name.slice(1);
        }
        return name;
    }

    /**
     * Preprocessing of params
     * @param params
     * @returns {object}
     * @private
     */
    _preprocessParams(params) {
        params = extend(params || {}, {token: this.token});

        Object.keys(params).forEach(function(name) {
            var param = params[name];

            if (param && typeof param === 'object') {
                params[name] = JSON.stringify(param);
            }
        });

        return params;
    }

    /**
     * Send request to API method
     * @param {string} methodName
     * @param {object} params
     * @returns {vow.Promise}
     * @private
     */
    _api(methodName, params) {

        var data = {
            url: 'https://slack.com/api/' + methodName,
            form: this._preprocessParams(params)
        };

        return new Vow.Promise(function(resolve, reject) {

            request.post(data, function(err, request, body) {
                if (err) {
                    reject(err);

                    return false;
                }

                try {
                    body = JSON.parse(body);

                    // Response always contain a top-level boolean property ok,
                    // indicating success or failure
                    if (body.ok) {
                        resolve(body);
                    } else {
                        reject(body);
                    }

                } catch (e) {
                    reject(e);
                }
            });
        });
    }
}

module.exports = Bot;
<commit_msg>Removed whitespace<commit_after>'use strict';

var _ = require('lodash');
var request = require('request');
var Vow = require('vow');
var extend = require('extend');
var WebSocket = require('ws');
var EventEmitter = require('events').EventEmitter;

class Bot extends EventEmitter {
    /**
     * @param {object} params
     * @constructor
     */

     constructor(params) {
         super(params);
         this.token = params.token;
         this.name = params.name;

         console.assert(params.token, 'token must be defined');
         this.login();
     }

    /**
     * Starts a Real Time Messaging API session
     */
     login() {
         this._api('rtm.start').then((data) => {
             this.wsUrl = data.url;
             this.self = data.self;
             this.team = data.team;
             this.channels = data.channels;
             this.users = data.users;
             this.ims = data.ims;
             this.groups = data.groups;

             this.emit('start');

             this.connect();
         }).fail((data) => {
             this.emit('error', new Error(data.error ? data.error : data));
         }).done();
    }

    /**
     * Establish a WebSocket connection
     */
     connect() {
         this.ws = new WebSocket(this.wsUrl);

         this.ws.on('open', function(data) {
             this.emit('open', data);
         }.bind(this));

         this.ws.on('close', function(data) {
             this.emit('close', data);
         }.bind(this));

         this.ws.on('message', function(data) {
             try {
                 this.emit('message', JSON.parse(data));
             } catch (e) {
                 console.log(e);
             }
         }.bind(this));
     }

    /**
     * Get channels
     * @returns {vow.Promise}
     */
     getChannels() {
         if (this.channels) {
             return Vow.fulfill({ channels: this.channels });
         }
         return this._api('channels.list');
      }

    /**
     * Get users
     * @returns {vow.Promise}
     */
     getUsers() {
          if (this.users) {
              return Vow.fulfill({ members: this.users });
          }

          return this._api('users.list');
     }

    /**
     * Get groups
     * @returns {vow.Promise}
     */
    getGroups() {
        if (this.groups) {
            return Vow.fulfill({ groups: this.groups });
        }

        return this._api('groups.list');
    }

    /**
     * Get user by name
     * @param {string} name
     * @returns {object}
     */
    getUser(name) {
        return this.getUsers().then(function(data) {
            var res = _.find(data.members, { name: name });

            console.assert(res, 'user not found');
            return res;
        });
    }

    /**
     * Get channel by name
     * @param {string} name
     * @returns {object}
     */
    getChannel(name) {
        return this.getChannels().then(function(data) {
            var res = _.find(data.channels, { name: name });

            console.assert(res, 'channel not found');
            return res;
        });
    }

    /**
     * Get group by name
     * @param {string} name
     * @returns {object}
     */
    getGroup(name) {
        return this.getGroups().then(function(data) {
            var res = _.find(data.groups, { name: name });

            console.assert(res, 'group not found');
            return res;
        });
    }

    /**
     * Get user by id
     * @param {string} id
     * @returns {object}
     */
    getUserById(id) {
        return this.getUsers().then(function(data) {
            var res = _.find(data.members, { id: id });

            console.assert(res, 'user not found');
            return res;
        });
    }

     /**
      * Get channel by id
      * @param {string} id
      * @returns {object}
      */
    getChannelById(id) {
        return this.getChannels().then(function(data) {
            var res = _.find(data.channels, { id: id });

            console.assert(res, 'channel not found');
            return res;
        });
    }

     /**
      * Get group by id
      * @param {string} id
      * @returns {object}
     */
    getGroupById(id) {
        return this.getGroups().then(function(data) {
            var res = _.find(data.groups, { id: id });

            console.assert(res, 'group not found');
            return res;
        });
    }

    /**
     * Get channel ID
     * @param {string} name
     * @returns {string}
     */
    getChannelId(name) {
        return this.getChannel(name).then(function(channel) {
            return channel.id;
        });
    }

    /**
     * Get group ID
     * @param {string} name
     * @returns {string}
     */
    getGroupId(name) {
        return this.getGroup(name).then(function(group) {
            return group.id;
        });
    }

    /**
     * Get user ID
     * @param {string} name
     * @returns {string}
     */
    getUserId(name) {
        return this.getUser(name).then(function(user) {
           return user.id;
        });
    }

    /**
     * Get user by email
     * @param {string} email
     * @returns {object}
     */
    getUserByEmail(email) {
        return this.getUsers().then(function(data) {
            return _.find(data.members, { profile: { email: email } });
        });
    }

    /**
     * Get "direct message" channel ID
     * @param {string} name
     * @returns {vow.Promise}
     */
    getChatId(name) {
        return this.getUser(name).then(function(data) {

            var chatId = _.find(this.ims, { user: data.id });

            return (chatId && chatId.id) || this.openIm(data.id);
        }.bind(this)).then(function(data) {
            return typeof data === 'string' ? data : data.channel.id;
        });
    }

    /**
     * Opens a "direct message" channel with another member of your Slack team
     * @param {string} userId
     * @returns {vow.Promise}
     */
    openIm(userId) {
        return this._api('im.open', {user: userId});
    }

    /**
     * Posts an ephemeral message to a channel and user
     * @param {string} id - channel ID
     * @param {string} user - user ID
     * @param {string} text
     * @param {object} params
     * @returns {vow.Promise}
     */
    postEphemeral(id, user, text, params) {
        params = extend({
            text: text,
            channel: id,
            user: user,
            username: this.name
        }, params || {});

        return this._api('chat.postEphemeral', params);
    }

    /**
     * Posts a message to a channel by ID
     * @param {string} id - channel ID
     * @param {string} text
     * @param {object} params
     * @returns {vow.Promise}
     */
    postMessage(id, text, params) {
        params = extend({
            text: text,
            channel: id,
            username: this.name
        }, params || {});

        return this._api('chat.postMessage', params);
    }

     /**
      * Updates a message by timestamp
      * @param {string} id - channel ID
      * @param {string} ts - timestamp
      * @param {string} text
      * @param {object} params
      * @returns {vow.Promise}
      */
    updateMessage(id, ts, text, params) {
        params = extend({
            ts: ts,
            channel: id,
            username: this.name,
            text: text
        }, params || {});

        return this._api('chat.update', params);
    }

    /**
     * Posts a message to user by name
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postMessageToUser(name, text, params, cb) {
        return this._post((params || {}).slackbot ? 'slackbot' : 'user', name, text, params, cb);
    }

    /**
     * Posts a message to channel by name
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postMessageToChannel(name, text, params, cb) {
        return this._post('channel', name, text, params, cb);
    }

    /**
     * Posts a message to group by name
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postMessageToGroup(name, text, params, cb) {
        return this._post('group', name, text, params, cb);
    }

    /**
     * Common method for posting messages
     * @param {string} type
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     * @private
     */
    _post(type, name, text, params, cb) {
        var method = ({
            'group': 'getGroupId',
            'channel': 'getChannelId',
            'user': 'getChatId',
            'slackbot': 'getUserId'
        })[type];

        if (typeof params === 'function') {
            cb = params;
            params = null;
        }

        return this[method](name).then(function(itemId) {
            return this.postMessage(itemId, text, params);
        }.bind(this)).always(function(data) {
            if (cb) {
                cb(data._value);
            }
        });
    }

    /**
     * Posts a message to group | channel | user
     * @param {string} name
     * @param {string} text
     * @param {object} params
     * @param {function} cb
     * @returns {vow.Promise}
     */
    postTo(name, text, params, cb) {
        return Vow.all([this.getChannels(), this.getUsers(), this.getGroups()]).then(function(data) {

            name = this._cleanName(name);

            var all = [].concat(data[0].channels, data[1].members, data[2].groups);
            var result = _.find(all, {name: name});

            console.assert(result, 'wrong name');

            if (result['is_channel']) {
                return this.postMessageToChannel(name, text, params, cb);
            } else if (result['is_group']) {
                return this.postMessageToGroup(name, text, params, cb);
            } else {
                return this.postMessageToUser(name, text, params, cb);
            }
        }.bind(this));
    }

    /**
     * Remove @ or # character from group | channel | user name
     * @param {string} name
     * @returns {string}
     */
    _cleanName (name) {
        if (typeof name !== 'string') {
            return name;
        }

        var firstCharacter = name.charAt(0);
        if (firstCharacter === '#' || firstCharacter === '@') {
            name = name.slice(1);
        }
        return name;
    }

    /**
     * Preprocessing of params
     * @param params
     * @returns {object}
     * @private
     */
    _preprocessParams(params) {
        params = extend(params || {}, {token: this.token});

        Object.keys(params).forEach(function(name) {
            var param = params[name];

            if (param && typeof param === 'object') {
                params[name] = JSON.stringify(param);
            }
        });

        return params;
    }

    /**
     * Send request to API method
     * @param {string} methodName
     * @param {object} params
     * @returns {vow.Promise}
     * @private
     */
    _api(methodName, params) {

        var data = {
            url: 'https://slack.com/api/' + methodName,
            form: this._preprocessParams(params)
        };

        return new Vow.Promise(function(resolve, reject) {

            request.post(data, function(err, request, body) {
                if (err) {
                    reject(err);

                    return false;
                }

                try {
                    body = JSON.parse(body);

                    // Response always contain a top-level boolean property ok,
                    // indicating success or failure
                    if (body.ok) {
                        resolve(body);
                    } else {
                        reject(body);
                    }

                } catch (e) {
                    reject(e);
                }
            });
        });
    }
}

module.exports = Bot;
<|endoftext|>


<commit_before>"use strict";

var __slice = [].slice;

function die () {
  console.log.apply(console, __slice.call(arguments, 0));
  process.exit(1);
}

function say () { console.log.apply(console, __slice.call(arguments, 0)) }

function extend (object) {
  __slice.call(arguments, 1).forEach(function (append) {
    for (var key in append) if (append.hasOwnProperty(key)) {
      object[key] = append[key];
    }
  });
  return object;
}

function factory () {
  var options = { context: {} };
  __slice.call(arguments, 0).forEach(function (opts) {
    var context = extend({}, options.context, opts.context || {});
    extend(options, opts).context = context;
  });

  return cadence;

  function cadence () {
    var vargs = __slice.call(arguments, 0)
      , steps = []
      , firstSteps = []
      , timer
      , callback
      , called
      , count
      , exitCode = 0
      , cadences = []
      , methods = { step: async }
      , abended
      , key
      , arg
      , context = {}
      ;

    firstSteps = vargs;

    if (firstSteps.every(function (object) { return typeof object == "object" })) {
      return factory.apply(null, [ options ].concat(firstSteps));
    }

    firstSteps = firstSteps.map(function (step) { return parameterize(step, context) });

    return execute;

    function execute () {
      var vargs = __slice.call(arguments, 0), callbacks = [], callback = exceptional;
      if (vargs.length) {
        callback = vargs.pop();
        callbacks = [{ results: [{ names: [], vargs: vargs }] }];
      }
      steps = firstSteps.slice(0);
      cadences.length = 0;
      abended = false;
      invoke(steps, 0, Object.create(options.context), callbacks, callback);
    }

    function exceptional (error) { if (error) throw error }

    // Set and reset a thirty second timeout between assertions.
    function timeout () {
      if (timer) clearTimeout(timer);
      if (options.timeout) timer = setTimeout(function () { callback(new Error("Timeout")) }, options.timeout);
    }

    var invocation;

    // We give this function to the caller to build control flow. In the
    // debugger, I often want to step into a function that takes a step
    // callback, so I'm often stepping into this function, only to step right
    // back out again. Step out is a two finger chord in the Chrome debugger,
    // but step over is a single function key, so I want to have the option to
    // step over the body of this function, instead of having to find the
    // control key when I'm in it. That is the only reason for the separate
    // async function.

    //
    function async () { return _async.apply(null, arguments) }

    function _async() {
      var vargs = __slice.call(arguments, 0), i = -1, step, original;

      // If we're called with an empty array, we're going to assume that the
      // caller created a cadence programatically, but the conditions were such
      // that no steps were added to the cadence. If we don't skip the empty
      // array, then the next step will flatten the array and we'll end up
      // treating it as a call with no arguments, which generates a callback.

      //
      if (vargs.length == 1 && Array.isArray(vargs[0]) && !vargs[0].length)
        return;

      // The caller as invoked the async function directly as an explicit early
      // return to exit the entire cadence.
      if (vargs.length && (vargs[0] == null || vargs[0] instanceof Error)) {
        invocation.count = Number.MAX_VALUE;
        invocation.callback.apply(null, vargs);
        return;
      }

      // If we're called with a single object argument, we merge the given
      // object into the cadence context.
      if (vargs.length == 1 && typeof vargs[0] == "object" && vargs[0]) {
        extend(invocation.context, vargs[0]);
        return;
      }

      // If our first argument is a function, we check to see if it is a jump
      // instruction. If the function is a member of the current cadence, we
      // will inovke that function with the results of this step.

      // Search for the function in the current cadence.
      if (vargs.length == 1 && typeof vargs[0] == "function") {
        original = vargs[0].original || vargs[0];
        for (i = invocation.arguments[0].length - 1; step = invocation.arguments[0][i]; i--) {
          if (original === step || original === step.original) break;
        }
      }

      // If we find the function in the current cadence, we set the index of
      // next step function to execute; then remove the function argument and
      // procede.
      if (~i) {
        invocation.arguments[1] = i;
        vargs.shift();
      }

      // If we have no arguments, or else if every argument is a string, then
      // we've been asked to build a callback, otherwise, this is a sub-cadence.

      //
      if (vargs.length && vargs.every(function (arg) { return typeof arg == "function" })) {
        cadences.push(vargs);
      } else {
        if (!isNaN(parseFloat(vargs[0])) && isFinite(vargs[0])) {
          var arity = parseInt(vargs.shift(), 10);
        }
        if (Array.isArray(vargs[0]) && vargs[0].length == 0) {
          var arrayed = !! vargs.shift();
        }
        if (!arrayed) invocation.count++;
        if (vargs.length) throw new Error("invalid arguments");
        return createCallback(invocation, arity, arrayed);
      }
    }

    function createCallback (invocation, arity, arrayed) {
      var callback = { results: [] };
      if (arity) callback.arity = arity;
      if (arrayed) callback.arrayed = arrayed;
      invocation.callbacks.push(callback);
      return function (error) {
        var vargs = __slice.call(arguments, 1);
        if (error) {
          thrown(invocation, error);
        } else {
          callback.results.push({ names: [], vargs: vargs });
          // Indicates that the function has completed, so we need create
          // the callbacks for parallel cadences now, the next increment of
          // the called counter, which may be the last.
          if (vargs[0] == invoke) {
            cadences.slice(0).forEach(function (steps) {
              var subtext = Object.create(invocation.context);
              steps = steps.map(function (step) { return parameterize(step, subtext) });
              invoke(steps, 0, subtext, [], async());
            });
          }
        }
        if (!arrayed && ++invocation.called == invocation.count) {
          invoke.apply(null, invocation.arguments);
        }
      }
    }

    function parameterize (step, context) {
      var $ = /^function\s*[^(]*\(([^)]*)\)/.exec(step.toString());
      if (!$) throw new Error("bad function");
      if (step.name) {
        context[step.name] = function () { async(step).apply(null, [ null ].concat(__slice.call(arguments, 0))) }
        context[step.name].original = step;
      }
      step.parameters = $[1].split(/\s*,\s/);
      if (!step.parameters[0].trim()) step.parameters.shift();
      return step;
    }

    // Test if a program name matches one of our special names. We support
    // Streamline.js by also accepting a function whose name has been mangled in a
    // Streamline.js fashion.

    //
    function named (proc, name) {
      return proc.name == name || (proc.name && !proc.name.indexOf(name + '__'));
    }

    // TODO And what if there are many, many errors?

    //
    function thrown (invocation, error) {
      var steps = invocation.arguments[0]
        , next = steps[invocation.index + 1]
        ;
      if (next && /^errors?$/.test(next.parameters[0])) {
        invocation.context.errors.push(error);
      } else {
        if (timer) clearTimeout(timer);
        abended = true;
        invocation.callback(error);
      }
    }

    // Parallel arrays make the most sense, really. If the paralleled function
    // is better off returning a map, it can be shimmed.
    function contextualize (step, callbacks, context, ephemeral) {
      var $, names, name, value, index, vargs = [], arg, callback, arity;

      names = step.parameters.slice(0);
      if (~(index = names.indexOf('step')) || ~(index = names.indexOf(options.alias))) {
        names.length = index;
      }
      // **TODO**: Why? Do I care anymore? Why not callback?
      if (step.name == '_') {
        names.length = 0;
      }

      if (!names.length) return;

      arg = 0;
      while (callbacks.length) {
        callback = callbacks.shift();
        if (arity in callback) {
          arity = callback.arity;
        } else {
          arity = 0;
          callback.results.forEach(function (result) {
            arity = Math.max(arity, result.vargs.length);
          });
        }
        for (index = 0; index < arity; index++) {
          vargs.push({ values: [],
                       arrayed: ('arrayed' in callback) ? callback.arrayed : callback.results.length > 1 });
        }
        callback.results.forEach(function (result) {
          for (var i = 0; i < arity; i++) {
            vargs[arg + i].values.push(result.vargs[i]);
          }
        });
        arg += arity;
      }

      while (names.length) {
        name = names.shift();
        if ($ = /^\$vargs(?:\$(\d+))?$/.exec(name)) {
          ephemeral[name] = vargs.splice(0, vargs.length - (+($[1] || 0)))
                                 .map(function (varg) {
                                    return varg.arrayed ? varg.values : varg.values.shift()
                                 });
        } else {
          if (vargs.length) {
            value = vargs.shift();
            value = value.arrayed ? value.values : value.values.shift();
          } else {
            break;
          }
          (name[0] == '$' ? ephemeral : context)[name] = value;
        }
      }
    }

    // Attempt to organize many callbacks into parallel arrays of values.

    //
    function parallelize (names, callbacks, context, ephemeral) {
      if (callbacks.length == 1) {
        callbacks[0].names.forEach(function (name, i) {
          (names[i][0] == '$' ? ephemeral : context)[name] = callbacks[0].vargs[i];
        });
      } else {
        // Is the result well organized? We have a specific size for names.
        var arrayed = callbacks.every(function (result) {
          return (
            result.vargs.length == names.length
            && (!result.names.length || names.every(function (name, i) { return name == result.names[i] }))
          )
        });
        if (arrayed) {
          names.length = callbacks[0].vargs.length;
          names.forEach(function (name, i) { (name[0] == '$' ? ephemeral : context)[name] = [] });
          callbacks.forEach(function (result) {
            result.vargs.forEach(function (arg, i) {
              (names[i][0] == '$' ? ephemeral : context)[names[i]].push(arg);
            });
          });
        } else {
          throw new Error("Can't infer array assignment.");
        }
      }
    }

    function invoke (steps, index, context, callbacks, callback) {
      var arg
        , args = []
        , match
        , parameter, parameters
        , i, I
        , calledback
        , step, key, next
        , leaked
        , result
        , value
        , names
        , result
        , hold
        , ephemeral = {}
        ;

      if (abended) return;

      timeout();

      invocation = { callbacks: [], count: 0 , called: 0, context: context,
                     index: index, callback: callback };
      invocation.arguments = [ steps, index + 1, context, invocation.callbacks, callback ]

      if (steps[index] && /^errors?$/.test(steps[index].parameters[0]) && !context.errors.length) {
        invoke(steps, index + 1, context, callbacks, callback);
      } else {
        // No callbacks means that we use the function return value, if any.
        if (callbacks.length == 1) {
          if (callbacks[0].results.length && callbacks[0].results[0].vargs[0] == invoke) {
            callbacks[0].results[0].vargs.shift()
          }
        } else {
          callbacks = callbacks.filter(function (callback) {
            return callback.results[0] && callback.results[0].vargs[0] !== invoke
          });
        }

        if (steps.length == index) {
          callback.apply(null, [ null ].concat(callbacks.length == 1 ? callbacks[0].results[0].vargs : []));
          return;
        }

        // Get the next step.
        step = steps[index];

        // Filter out the return value, if there are callbacks left, then
        // `contextualize` will process them.
        if (callbacks.length) {
          contextualize(step, callbacks, context, ephemeral);
        }

        // Give our creator a chance to inspect the step, possibly wrap it.
        Object.keys(options.wrap || {})
          .filter(function (name) { return named(step, name) && name })
          .map(function (name) { return options.wrap[name] })
          .forEach(function (wrapper) {
            var parameters = step.parameters, original = step.original || step;
            step = wrapper(step)
            step.parameters = parameters;
            step.original = original;
          });

        step.parameters.forEach(function (parameter) {
          if (parameter == options.alias) {
            parameter = 'step';
          }
          if (parameter == "error") {
            arg = context.errors[0];
          // Did not know that `/^_|callback$/` means `^_` or `done$`.
          } else if (/^(_|callback)$/.test(parameter)) {
            arg = async();
          } else if ((arg  = context[parameter]) == void(0)) {
            if ((arg = ephemeral[parameter]) == void(0)) arg = methods[parameter];
          }
          args.push(arg);
        });

        cadences.length = 0;
        context.errors = [];

        try {
          hold = async();
          result = step.apply(null, args);
          hold.apply(null, [ null, invoke ].concat(result == void(0) ? [] : [ result ]));
        } catch (error) {
          thrown(invocation, error);
          invoke.apply(null, invocation.arguments);
        }
      }
    }
  }
}

module.exports = factory();
<commit_msg>Remove `parallelize`.<commit_after>"use strict";

var __slice = [].slice;

function die () {
  console.log.apply(console, __slice.call(arguments, 0));
  process.exit(1);
}

function say () { console.log.apply(console, __slice.call(arguments, 0)) }

function extend (object) {
  __slice.call(arguments, 1).forEach(function (append) {
    for (var key in append) if (append.hasOwnProperty(key)) {
      object[key] = append[key];
    }
  });
  return object;
}

function factory () {
  var options = { context: {} };
  __slice.call(arguments, 0).forEach(function (opts) {
    var context = extend({}, options.context, opts.context || {});
    extend(options, opts).context = context;
  });

  return cadence;

  function cadence () {
    var vargs = __slice.call(arguments, 0)
      , steps = []
      , firstSteps = []
      , timer
      , callback
      , called
      , count
      , exitCode = 0
      , cadences = []
      , methods = { step: async }
      , abended
      , key
      , arg
      , context = {}
      ;

    firstSteps = vargs;

    if (firstSteps.every(function (object) { return typeof object == "object" })) {
      return factory.apply(null, [ options ].concat(firstSteps));
    }

    firstSteps = firstSteps.map(function (step) { return parameterize(step, context) });

    return execute;

    function execute () {
      var vargs = __slice.call(arguments, 0), callbacks = [], callback = exceptional;
      if (vargs.length) {
        callback = vargs.pop();
        callbacks = [{ results: [{ names: [], vargs: vargs }] }];
      }
      steps = firstSteps.slice(0);
      cadences.length = 0;
      abended = false;
      invoke(steps, 0, Object.create(options.context), callbacks, callback);
    }

    function exceptional (error) { if (error) throw error }

    // Set and reset a thirty second timeout between assertions.
    function timeout () {
      if (timer) clearTimeout(timer);
      if (options.timeout) timer = setTimeout(function () { callback(new Error("Timeout")) }, options.timeout);
    }

    var invocation;

    // We give this function to the caller to build control flow. In the
    // debugger, I often want to step into a function that takes a step
    // callback, so I'm often stepping into this function, only to step right
    // back out again. Step out is a two finger chord in the Chrome debugger,
    // but step over is a single function key, so I want to have the option to
    // step over the body of this function, instead of having to find the
    // control key when I'm in it. That is the only reason for the separate
    // async function.

    //
    function async () { return _async.apply(null, arguments) }

    function _async() {
      var vargs = __slice.call(arguments, 0), i = -1, step, original;

      // If we're called with an empty array, we're going to assume that the
      // caller created a cadence programatically, but the conditions were such
      // that no steps were added to the cadence. If we don't skip the empty
      // array, then the next step will flatten the array and we'll end up
      // treating it as a call with no arguments, which generates a callback.

      //
      if (vargs.length == 1 && Array.isArray(vargs[0]) && !vargs[0].length)
        return;

      // The caller as invoked the async function directly as an explicit early
      // return to exit the entire cadence.
      if (vargs.length && (vargs[0] == null || vargs[0] instanceof Error)) {
        invocation.count = Number.MAX_VALUE;
        invocation.callback.apply(null, vargs);
        return;
      }

      // If we're called with a single object argument, we merge the given
      // object into the cadence context.
      if (vargs.length == 1 && typeof vargs[0] == "object" && vargs[0]) {
        extend(invocation.context, vargs[0]);
        return;
      }

      // If our first argument is a function, we check to see if it is a jump
      // instruction. If the function is a member of the current cadence, we
      // will inovke that function with the results of this step.

      // Search for the function in the current cadence.
      if (vargs.length == 1 && typeof vargs[0] == "function") {
        original = vargs[0].original || vargs[0];
        for (i = invocation.arguments[0].length - 1; step = invocation.arguments[0][i]; i--) {
          if (original === step || original === step.original) break;
        }
      }

      // If we find the function in the current cadence, we set the index of
      // next step function to execute; then remove the function argument and
      // procede.
      if (~i) {
        invocation.arguments[1] = i;
        vargs.shift();
      }

      // If we have no arguments, or else if every argument is a string, then
      // we've been asked to build a callback, otherwise, this is a sub-cadence.

      //
      if (vargs.length && vargs.every(function (arg) { return typeof arg == "function" })) {
        cadences.push(vargs);
      } else {
        if (!isNaN(parseFloat(vargs[0])) && isFinite(vargs[0])) {
          var arity = parseInt(vargs.shift(), 10);
        }
        if (Array.isArray(vargs[0]) && vargs[0].length == 0) {
          var arrayed = !! vargs.shift();
        }
        if (!arrayed) invocation.count++;
        if (vargs.length) throw new Error("invalid arguments");
        return createCallback(invocation, arity, arrayed);
      }
    }

    function createCallback (invocation, arity, arrayed) {
      var callback = { results: [] };
      if (arity) callback.arity = arity;
      if (arrayed) callback.arrayed = arrayed;
      invocation.callbacks.push(callback);
      return function (error) {
        var vargs = __slice.call(arguments, 1);
        if (error) {
          thrown(invocation, error);
        } else {
          callback.results.push({ names: [], vargs: vargs });
          // Indicates that the function has completed, so we need create
          // the callbacks for parallel cadences now, the next increment of
          // the called counter, which may be the last.
          if (vargs[0] == invoke) {
            cadences.slice(0).forEach(function (steps) {
              var subtext = Object.create(invocation.context);
              steps = steps.map(function (step) { return parameterize(step, subtext) });
              invoke(steps, 0, subtext, [], async());
            });
          }
        }
        if (!arrayed && ++invocation.called == invocation.count) {
          invoke.apply(null, invocation.arguments);
        }
      }
    }

    function parameterize (step, context) {
      var $ = /^function\s*[^(]*\(([^)]*)\)/.exec(step.toString());
      if (!$) throw new Error("bad function");
      if (step.name) {
        context[step.name] = function () { async(step).apply(null, [ null ].concat(__slice.call(arguments, 0))) }
        context[step.name].original = step;
      }
      step.parameters = $[1].split(/\s*,\s/);
      if (!step.parameters[0].trim()) step.parameters.shift();
      return step;
    }

    // Test if a program name matches one of our special names. We support
    // Streamline.js by also accepting a function whose name has been mangled in a
    // Streamline.js fashion.

    //
    function named (proc, name) {
      return proc.name == name || (proc.name && !proc.name.indexOf(name + '__'));
    }

    // TODO And what if there are many, many errors?

    //
    function thrown (invocation, error) {
      var steps = invocation.arguments[0]
        , next = steps[invocation.index + 1]
        ;
      if (next && /^errors?$/.test(next.parameters[0])) {
        invocation.context.errors.push(error);
      } else {
        if (timer) clearTimeout(timer);
        abended = true;
        invocation.callback(error);
      }
    }

    // Parallel arrays make the most sense, really. If the paralleled function
    // is better off returning a map, it can be shimmed.
    function contextualize (step, callbacks, context, ephemeral) {
      var $, names, name, value, index, vargs = [], arg, callback, arity;

      names = step.parameters.slice(0);
      if (~(index = names.indexOf('step')) || ~(index = names.indexOf(options.alias))) {
        names.length = index;
      }
      // **TODO**: Why? Do I care anymore? Why not callback?
      if (step.name == '_') {
        names.length = 0;
      }

      if (!names.length) return;

      arg = 0;
      while (callbacks.length) {
        callback = callbacks.shift();
        if (arity in callback) {
          arity = callback.arity;
        } else {
          arity = 0;
          callback.results.forEach(function (result) {
            arity = Math.max(arity, result.vargs.length);
          });
        }
        for (index = 0; index < arity; index++) {
          vargs.push({ values: [],
                       arrayed: ('arrayed' in callback) ? callback.arrayed : callback.results.length > 1 });
        }
        callback.results.forEach(function (result) {
          for (var i = 0; i < arity; i++) {
            vargs[arg + i].values.push(result.vargs[i]);
          }
        });
        arg += arity;
      }

      while (names.length) {
        name = names.shift();
        if ($ = /^\$vargs(?:\$(\d+))?$/.exec(name)) {
          ephemeral[name] = vargs.splice(0, vargs.length - (+($[1] || 0)))
                                 .map(function (varg) {
                                    return varg.arrayed ? varg.values : varg.values.shift()
                                 });
        } else {
          if (vargs.length) {
            value = vargs.shift();
            value = value.arrayed ? value.values : value.values.shift();
          } else {
            break;
          }
          (name[0] == '$' ? ephemeral : context)[name] = value;
        }
      }
    }

    function invoke (steps, index, context, callbacks, callback) {
      var arg
        , args = []
        , match
        , parameter, parameters
        , i, I
        , calledback
        , step, key, next
        , leaked
        , result
        , value
        , names
        , result
        , hold
        , ephemeral = {}
        ;

      if (abended) return;

      timeout();

      invocation = { callbacks: [], count: 0 , called: 0, context: context,
                     index: index, callback: callback };
      invocation.arguments = [ steps, index + 1, context, invocation.callbacks, callback ]

      if (steps[index] && /^errors?$/.test(steps[index].parameters[0]) && !context.errors.length) {
        invoke(steps, index + 1, context, callbacks, callback);
      } else {
        // No callbacks means that we use the function return value, if any.
        if (callbacks.length == 1) {
          if (callbacks[0].results.length && callbacks[0].results[0].vargs[0] == invoke) {
            callbacks[0].results[0].vargs.shift()
          }
        } else {
          callbacks = callbacks.filter(function (callback) {
            return callback.results[0] && callback.results[0].vargs[0] !== invoke
          });
        }

        if (steps.length == index) {
          callback.apply(null, [ null ].concat(callbacks.length == 1 ? callbacks[0].results[0].vargs : []));
          return;
        }

        // Get the next step.
        step = steps[index];

        // Filter out the return value, if there are callbacks left, then
        // `contextualize` will process them.
        if (callbacks.length) {
          contextualize(step, callbacks, context, ephemeral);
        }

        // Give our creator a chance to inspect the step, possibly wrap it.
        Object.keys(options.wrap || {})
          .filter(function (name) { return named(step, name) && name })
          .map(function (name) { return options.wrap[name] })
          .forEach(function (wrapper) {
            var parameters = step.parameters, original = step.original || step;
            step = wrapper(step)
            step.parameters = parameters;
            step.original = original;
          });

        step.parameters.forEach(function (parameter) {
          if (parameter == options.alias) {
            parameter = 'step';
          }
          if (parameter == "error") {
            arg = context.errors[0];
          // Did not know that `/^_|callback$/` means `^_` or `done$`.
          } else if (/^(_|callback)$/.test(parameter)) {
            arg = async();
          } else if ((arg  = context[parameter]) == void(0)) {
            if ((arg = ephemeral[parameter]) == void(0)) arg = methods[parameter];
          }
          args.push(arg);
        });

        cadences.length = 0;
        context.errors = [];

        try {
          hold = async();
          result = step.apply(null, args);
          hold.apply(null, [ null, invoke ].concat(result == void(0) ? [] : [ result ]));
        } catch (error) {
          thrown(invocation, error);
          invoke.apply(null, invocation.arguments);
        }
      }
    }
  }
}

module.exports = factory();
<|endoftext|>