<commit_before>var loaderUtils = require('loader-utils');
var postcss     = require('postcss');

module.exports = function (source, map) {
    if ( this.cacheable ) this.cacheable();

    var file    = loaderUtils.getRemainingRequest(this);
    var params  = loaderUtils.parseQuery(this.query);

    var opts = {
        from: file,
        to:   file,
        map:  {
            inline:     false,
            annotation: false
        }
    };

    if ( typeof map === 'string' ) {
        map = JSON.parse(map);
    }

    if ( map && map.mappings ) opts.map.prev = map;

    if ( params.syntax )      opts.syntax      = require(params.syntax);
    if ( params.parser )      opts.parser      = require(params.parser);
    if ( params.stringifier ) opts.stringifier = require(params.stringifier);

    var plugins = this.options.postcss;
    if ( typeof plugins === 'function' ) {
        plugins = plugins.call(this);
    }

    if ( typeof plugins === 'undefined' ) {
        plugins = [];
    } else if ( params.pack ) {
        plugins = plugins[params.pack];
    } else if ( !Array.isArray(plugins) ) {
        plugins = plugins.defaults;
    }

    var loader   = this;
    var callback = this.async();

    postcss(plugins)
        .process(source, opts).then(function (result) {
            result.warnings().forEach(function (msg) {
                loader.emitWarning(msg.toString());
            });
            callback(null, result.css, result.map);
        })
        .catch(function (error) {
            if ( error.name === 'CssSyntaxError' ) {
                loader.emitError(error.message + error.showSourceCode());
                callback();
            } else {
                callback(error);
            }
        });
};
<commit_msg>Other code clean up<commit_after>var loaderUtils = require('loader-utils');
var postcss     = require('postcss');

module.exports = function (source, map) {
    if ( this.cacheable ) this.cacheable();

    var file    = loaderUtils.getRemainingRequest(this);
    var params  = loaderUtils.parseQuery(this.query);

    var opts = {
        from: file,
        to:   file,
        map:  {
            inline:     false,
            annotation: false
        }
    };

    if ( typeof map === 'string' ) map = JSON.parse(map);
    if ( map && map.mappings ) opts.map.prev = map;

    if ( params.syntax )      opts.syntax      = require(params.syntax);
    if ( params.parser )      opts.parser      = require(params.parser);
    if ( params.stringifier ) opts.stringifier = require(params.stringifier);

    var plugins = this.options.postcss;
    if ( typeof plugins === 'function' ) {
        plugins = plugins.call(this);
    }

    if ( typeof plugins === 'undefined' ) {
        plugins = [];
    } else if ( params.pack ) {
        plugins = plugins[params.pack];
    } else if ( !Array.isArray(plugins) ) {
        plugins = plugins.defaults;
    }

    var loader   = this;
    var callback = this.async();

    postcss(plugins)
        .process(source, opts).then(function (result) {
            result.warnings().forEach(function (msg) {
                loader.emitWarning(msg.toString());
            });
            callback(null, result.css, result.map);
        })
        .catch(function (error) {
            if ( error.name === 'CssSyntaxError' ) {
                loader.emitError(error.message + error.showSourceCode());
                callback();
            } else {
                callback(error);
            }
        });
};
<|endoftext|>


<commit_before>/*!
 * base-runner <https://github.com/jonschlinkert/base-runner>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var utils = require('./utils');

/**
 * Create a customized `Runner` constructor with the given `config`.
 *
 * ```js
 * var runner = require('base-runner');
 * var Generate = require('generate');
 *
 * // register `runner` as a mixin
 * Generate.mixin(runner('generate', 'generator'));
 *
 * // get the `base` instance
 * var base = Generate.getConfig('generator.js')
 *   .resolve('generator.js', {
 *     cwd: __dirname
 *   });
 * ```
 *
 * @param {String} `moduleName` The name of the "parent" module, ex: `generate`
 * @param {String} `appName` The name of the "child" apps, ex: `generator`
 * @return {Function}
 */

function runner(moduleName, appName, preload) {
  if (typeof moduleName !== 'string') {
    throw new TypeError('expected "moduleName" to be a string');
  }
  if (typeof appName !== 'string') {
    throw new TypeError('expected "appName" to be a string');
  }

  var toSingular = utils.inflection.singularize;
  var toPlural = utils.inflection.pluralize;

  appName = toSingular(appName);

  // create property and method names
  var parent = utils.pascal(appName);
  var plural = toPlural(appName);
  var isName = 'is' + utils.pascal(moduleName);
  var method = function(prop) {
    return prop + parent;
  };

  return function runnerPlugin(proto) {
    var Ctor = proto.constructor;

    if (proto instanceof Ctor) {
      throw new Error('base-runner must be used as a mixin, not as an instance plugin.');
    }

    /**
     * Ensure CLI and config plugins are loaded as early as possible
     */

    if (typeof proto.config !== 'function') {
      Ctor.use(utils.config());
    }

    if (typeof proto.cli !== 'function') {
      Ctor.use(utils.cli());
    }

    if (typeof proto.runtimes !== 'function') {
      Ctor.use(function() {
        var name = this.name || this.options.name || 'base';

        this.use(utils.runtimes({
          displayName: function (key) {
            return name !== key ? (name + ':' + key) : key;
          }
        }));
      });
    }

    /**
     * Static method for getting the very first instance to be used
     * as the `base` instance. The first instance will either be defined
     * by the user, like in local `node_modules`, or a globally installed
     * module that serves as a default/fallback.
     *
     * ```js
     * var base = Base.getConfig('generator.js');
     * ```
     * @name .getConfig
     * @param {String} `filename` Then name of the config file to lookup.
     * @return {Object} Returns the "base" instance.
     * @api public
     */

    Ctor.getConfig = function(filename, fallback) {
      var base = getConfig(filename, moduleName, {
        Ctor: Ctor,
        preload: preload,
        fallback: fallback,
        appName: appName,
        isModule: function(app) {
          if (app) return app[isName];
          throw new Error('verbfile.js should return an instance of verb or a function');
        }
      });

      base.initRunner(base);
      return base;
    };

    /**
     * Private method for initializing runner defaults and listening for config
     * objects to be emitted.
     *
     * @return {Object}
     */

    proto.initRunner = function() {
      if (this.runnerInitialized) return;
      this.runnerInitialized = true;

      this.emit('plugin', 'runner', this);
      this.env = this.env || {};

      this[plural] = this[plural] || {};
      this[isName] = true;

      this
        .use(utils.argv({prop: plural}))
        .use(utils.resolver(moduleName))

      initListeners(this);
      proxyArgv(this);
    };

    /**
     * Ensure argv is parsed for the `base-cli` and
     * `base-argv` plugins at the same time.
     */

    function proxyArgv(app) {
      var processFn = app.cli.process;
      var argvFn = app.argv;

      app.cli.process = function(argv) {
        var args = argvFn.call(app, argv);
        utils.extend(args, args.commands);
        processFn.call(app.cli, args);
        app.set('env.argv', args);
        app.emit('argv', args);
        return args;
      };
    }

    /**
     * Add a `config` listener to `app`, and register
     * a `fn` each time a config is emitted
     */

    function initListeners(app) {
      app.on('config', function(name, env) {
        env.module.path = env.module.path || app.path;
        var config = env.config;
        var alias = config.alias;
        var fn = config.fn;

        if (alias === moduleName) {
          alias = 'base';
        }
        app.register(alias, fn, app, env);
      });
    }

    /**
     * Get task `name` from the `runner.tasks` object.
     *
     * ```js
     * runner.getTask('abc');
     *
     * // get a task from app `foo`
     * runner.getTask('foo:abc');
     *
     * // get a task from sub-app `foo.bar`
     * runner.getTask('foo.bar:abc');
     * ```
     * @name .getTask
     * @param {String} `name`
     * @return {Object}
     * @api public
     */

    proto.getTask = function(name) {
      var segments = name.split(':');
      if (segments.length === 1) {
        return this.tasks[name];
      }
      var app = this[method('get')](segments[0]);
      return app.getTask(segments[1]);
    };

    /**
     * Register `app` with the given `name`.
     *
     * ```js
     * runner.register('foo', function(app, base, env) {
     *   app.task('foo-a', function() {});
     *   app.task('foo-b', function() {});
     *   app.task('foo-c', function() {});
     *
     *   // sub-app
     *   app.register('bar', function(sub) {
     *     sub.task('bar-a', function() {});
     *     sub.task('bar-b', function() {});
     *     sub.task('bar-c', function() {});
     *   });
     * });
     *  ```
     * @name .register
     * @param {String} `name` The app's name.
     * @param {Object|Function} `app` Generator can be an instance of runner or a function. Generator functions are invoked with a new instance of `Runner`, a `base` instance that is used for storing all apps, and `env`, an object with user environment details, such as `cwd`.
     * @return {String}
     */

    proto.register = function(name, app, base, env) {
      if (typeof this[plural] === 'undefined') {
        var ctor = this.constructor.name;
        throw new Error('object "' + plural + '" is not defined on ' + ctor);
      }
      if (!app) {
        throw new Error('expected ' + app + ' to be a function or object');
      }

      app = this.invoke(name, app, base, env);
      this.emit('register', name, app);
      this[plural][name] = app;
      return this;
    };

    /**
     * Alias for `register`. Adds an `app` with the given `name`
     * to the `runner.apps` object.
     *
     * @name .addApp
     * @param {String} `name` The name of the config object to register
     * @param {Object|Function} `config` The config object or function
     * @api public
     */

    proto[method('add')] = function(name, config) {
      return this.register.apply(this, arguments);
    };

    /**
     * Return true if app `name` is registered. Dot-notation
     * may be used to check for [sub-apps](#sub-apps).
     *
     * ```js
     * base.hasApp('foo.bar.baz');
     * ```
     * @name .hasApp
     * @param {String} `name`
     * @return {Boolean}
     * @api public
     */

    proto[method('has')] = function(name) {
      if (this[plural].hasOwnProperty(name)) {
        return true;
      }
      name = name.split('.').join('.' + plural + '.');
      return this.has([plural, name]);
    };

    /**
     * Return app `name` is registered. Dot-notation
     * may be used to get [sub-apps](#sub-apps).
     *
     * ```js
     * base.getApp('foo');
     * // or
     * base.getApp('foo.bar.baz');
     * ```
     * @name .getApp
     * @param {String} `name`
     * @return {Boolean}
     * @api public
     */

    proto[method('get')] = function(name) {
      if (this[plural].hasOwnProperty(name)) {
        return this[plural][name];
      }
      name = name.split('.').join('.' + plural + '.');
      return this.get([plural, name]);
    };

    /**
     * Extend an app.
     *
     * ```js
     * var foo = base.getApp('foo');
     * foo.extendApp(app);
     * ```
     * @name .extendApp
     * @param {Object} `app`
     * @return {Object} Returns the instance for chaining.
     * @api public
     */

    proto[method('extend')] = function(app) {
      if (typeof this.fn !== 'function') {
        throw new Error('base-runner expected `fn` to be a function');
      }

      this.fn.call(app, app, this.base, this.env);
      return this;
    };

    /**
     * Run one or more apps and the specified tasks for each.
     *
     * ```js
     * // run the default tasks for apps `foo` and `bar`
     * foo.runApps(['foo', 'bar'], function(err) {
     *   if (err) return console.log(err);
     *   console.log('done!');
     * });
     *
     * // run the specified tasks for apps `foo` and `bar`
     * var apps = {
     *   foo: ['a', 'b', 'c'],
     *   bar: ['x', 'y', 'z']
     * };
     *
     * base.runApps(apps, function(err) {
     *   if (err) return console.log(err);
     *   console.log('done!');
     * });
     * ```
     * @param {Object} `apps`
     * @param {Function} `done`
     * @api public
     */

    proto[toPlural(method('run'))] = function(apps, done) {
      if (!Array.isArray(apps) || !utils.isObject(apps[0])) {
        apps = this.argv(apps)[plural];
      }

      this.emit(toPlural(method('run')), apps, this);

      utils.async.each(apps, function(app, cb) {
        utils.async.eachOf(app, function(tasks, name, next) {
          var instance = this[method('get')](name) || this;
          if (!instance) {
            return cb(new Error('cannot find ' + appName + ' "' + name + '"'));
          }
          this.emit('prebuild', name, tasks, instance);
          instance.build(tasks, cb);
        }.bind(this), cb);
      }.bind(this), done);
    };

    /**
     * Invoke app `fn` with the given `base` instance.
     *
     * ```js
     * runner.invoke(app.fn, app);
     * ```
     * @name .invoke
     * @param {Function} `fn` The app function.
     * @param {Object} `app` The "base" instance to use with the app.
     * @return {Object}
     * @api public
     */

    proto.invoke = function(name, app, base, env) {
      env = env || this.env;
      if (typeof app === 'function') {
        var fn = app;
        app = new this.constructor({name: name});
        app.fn = fn;
        init(app, this);
        fn.call(app, app, base || app.base, app.env);
      } else {
        // `parent` is used to get the base instance
        init(app, this);
      }

      function init(inst, parent) {
        inst.name = name;
        inst.env = env || inst.env;
        inst.define('parent', parent);
        inst.initRunner();
      }
      return app;
    };

    /**
     * Get the `base` instance
     */

    Object.defineProperty(proto, 'base', {
      configurable: true,
      get: function() {
        this.calledParent = true;
        return this.parent ? this.parent.base : this;
      }
    });

  };
}

/**
 * Expose `runner`
 */

module.exports = runner;

/**
 * If necessary, this static method will resolve the _first instance_
 * to be used as the `base` instance for caching any additional resolved configs.
 *
 * ```js
 * var Generate = require('generate');
 * var resolver = require('base-resolver');
 *
 * var generate = resolver.first('generator.js', 'generate', {
 *   Ctor: Generate,
 *   isModule: function(app) {
 *     return app.isGenerate;
 *   }
 * });
 * ```
 * @param {String} `configfile` The name of the config file, ex: `assemblefile.js`
 * @param {String} `moduleName` The name of the module to lookup, ex: `assemble`
 * @param {Object} `options`
 *   @option {Function} `options.isModule` Optionally pass a function that will be used to verify that the correct instance was created.
 * @return {Object}
 * @api public
 */

function getConfig(configfile, moduleName, options) {
  var opts = utils.extend({ cwd: process.cwd() }, options);
  var fp = path.resolve(opts.cwd, configfile);

  var User = utils.resolver.Resolver.User;
  var createEnv = utils.resolver.Resolver.createEnv;
  var fallback = opts.fallback;
  var Ctor = opts.Ctor;

  if (!utils.isAbsolute(fallback)) {
    fallback = utils.resolveModule(opts.fallback);
  }

  if (typeof Ctor !== 'function') {
    throw new TypeError('expected options.Ctor to be a function');
  }

  var validate = function() {
    return false;
  };

  if (typeof opts.isModule === 'function') {
    validate = opts.isModule;
  }

  // if a "configfile.js" is in the user's cwd, we'll try to
  // require it in and use it to get (or create) the instance
  if (fs.existsSync(fp)) {
    opts.module = moduleName;
    var env = createEnv(fp, opts.cwd, opts);
    Ctor = env.module.fn;

    if (typeof Ctor.create === 'function' && typeof opts.preload === 'function') {
      Ctor = Ctor.create(function(app, base) {
        return opts.preload(app, base, env);
      });
      Ctor.mixin(runner(moduleName, opts.appName));
    }

    // `fn` is whatever the "configfile" returns
    var fn = env.config.fn;

    // if the "configfile" returns a function, we need to
    // call the function, and pass an instance of our
    // application to it
    if (typeof fn === 'function') {
      var app = new Ctor();
      if (!env.user) {
        env.user = new User(env.config.cwd);
      }
      return app.invoke('base', fn, app, env);
    }

    // Otherwise, if the "configfile" returns an instance
    // of our application we'll use that as our `base`
    if (validate(fn)) {
      return fn;
    }
  }

  // if we haven't resolved a user-specified config file by now,
  // try the fallback dir, if passed on the options
  if (fallback && fallback !== opts.cwd) {
    opts.cwd = fallback;
    return getConfig(configfile, moduleName, opts);
  }

  // create a new, bare instance as a last resort
  return new Ctor();
};

<commit_msg>fix processArgv<commit_after>/*!
 * base-runner <https://github.com/jonschlinkert/base-runner>
 *
 * Copyright (c) 2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var fs = require('fs');
var path = require('path');
var utils = require('./utils');

/**
 * Create a customized `Runner` constructor with the given `config`.
 *
 * ```js
 * var runner = require('base-runner');
 * var Generate = require('generate');
 *
 * // register `runner` as a mixin
 * Generate.mixin(runner('generate', 'generator'));
 *
 * // get the `base` instance
 * var base = Generate.getConfig('generator.js')
 *   .resolve('generator.js', {
 *     cwd: __dirname
 *   });
 * ```
 *
 * @param {String} `moduleName` The name of the "parent" module, ex: `generate`
 * @param {String} `appName` The name of the "child" apps, ex: `generator`
 * @return {Function}
 */

function runner(moduleName, appName, preload) {
  if (typeof moduleName !== 'string') {
    throw new TypeError('expected "moduleName" to be a string');
  }
  if (typeof appName !== 'string') {
    throw new TypeError('expected "appName" to be a string');
  }

  var toSingular = utils.inflection.singularize;
  var toPlural = utils.inflection.pluralize;

  appName = toSingular(appName);

  // create property and method names
  var parent = utils.pascal(appName);
  var plural = toPlural(appName);
  var isName = 'is' + utils.pascal(moduleName);
  var method = function(prop) {
    return prop + parent;
  };

  return function runnerPlugin(proto) {
    var Ctor = proto.constructor;

    if (proto instanceof Ctor) {
      throw new Error('base-runner must be used as a mixin, not as an instance plugin.');
    }

    /**
     * Ensure CLI and config plugins are loaded as early as possible
     */

    if (typeof proto.config !== 'function') {
      Ctor.use(utils.config());
    }

    if (typeof proto.cli !== 'function') {
      Ctor.use(utils.cli());
    }

    if (typeof proto.runtimes !== 'function') {
      Ctor.use(function() {
        var name = this.name || this.options.name || 'base';

        this.use(utils.runtimes({
          displayName: function (key) {
            return name !== key ? (name + ':' + key) : key;
          }
        }));
      });
    }

    /**
     * Static method for getting the very first instance to be used
     * as the `base` instance. The first instance will either be defined
     * by the user, like in local `node_modules`, or a globally installed
     * module that serves as a default/fallback.
     *
     * ```js
     * var base = Base.getConfig('generator.js');
     * ```
     * @name .getConfig
     * @param {String} `filename` Then name of the config file to lookup.
     * @return {Object} Returns the "base" instance.
     * @api public
     */

    Ctor.getConfig = function(filename, fallback) {
      var base = getConfig(filename, moduleName, {
        Ctor: Ctor,
        preload: preload,
        fallback: fallback,
        appName: appName,
        isModule: function(app) {
          if (app) return app[isName];
          throw new Error('verbfile.js should return an instance of verb or a function');
        }
      });

      base.initRunner(base);
      return base;
    };

    /**
     * Private method for initializing runner defaults and listening for config
     * objects to be emitted.
     *
     * @return {Object}
     */

    proto.initRunner = function() {
      if (this.runnerInitialized) return;
      this.runnerInitialized = true;

      this.emit('plugin', 'runner', this);
      this.env = this.env || {};

      this[plural] = this[plural] || {};
      this[isName] = true;

      this
        .use(utils.argv({prop: plural}))
        .use(utils.resolver(moduleName))

      initListeners(this);
      proxyArgv(this);
    };

    /**
     * Ensure argv is parsed for the `base-cli` and
     * `base-argv` plugins at the same time.
     */

    function proxyArgv(app) {
      var processFn = app.cli.process;
      var argvFn = app.processArgv;

      app.cli.process = function(argv) {
        var args = argvFn.call(app, argv);
        utils.extend(args, args.commands);
        processFn.call(app.cli, args);
        app.set('env.argv', args);
        app.emit('argv', args);
        return args;
      };
    }

    /**
     * Add a `config` listener to `app`, and register
     * a `fn` each time a config is emitted
     */

    function initListeners(app) {
      app.on('config', function(name, env) {
        env.module.path = env.module.path || app.path;
        var config = env.config;
        var alias = config.alias;
        var fn = config.fn;

        if (alias === moduleName) {
          alias = 'base';
        }
        app.register(alias, fn, app, env);
      });
    }

    /**
     * Get task `name` from the `runner.tasks` object.
     *
     * ```js
     * runner.getTask('abc');
     *
     * // get a task from app `foo`
     * runner.getTask('foo:abc');
     *
     * // get a task from sub-app `foo.bar`
     * runner.getTask('foo.bar:abc');
     * ```
     * @name .getTask
     * @param {String} `name`
     * @return {Object}
     * @api public
     */

    proto.getTask = function(name) {
      var segments = name.split(':');
      if (segments.length === 1) {
        return this.tasks[name];
      }
      var app = this[method('get')](segments[0]);
      return app.getTask(segments[1]);
    };

    /**
     * Register `app` with the given `name`.
     *
     * ```js
     * runner.register('foo', function(app, base, env) {
     *   app.task('foo-a', function() {});
     *   app.task('foo-b', function() {});
     *   app.task('foo-c', function() {});
     *
     *   // sub-app
     *   app.register('bar', function(sub) {
     *     sub.task('bar-a', function() {});
     *     sub.task('bar-b', function() {});
     *     sub.task('bar-c', function() {});
     *   });
     * });
     *  ```
     * @name .register
     * @param {String} `name` The app's name.
     * @param {Object|Function} `app` Generator can be an instance of runner or a function. Generator functions are invoked with a new instance of `Runner`, a `base` instance that is used for storing all apps, and `env`, an object with user environment details, such as `cwd`.
     * @return {String}
     */

    proto.register = function(name, app, base, env) {
      if (typeof this[plural] === 'undefined') {
        var ctor = this.constructor.name;
        throw new Error('object "' + plural + '" is not defined on ' + ctor);
      }
      if (!app) {
        throw new Error('expected ' + app + ' to be a function or object');
      }

      app = this.invoke(name, app, base, env);
      this.emit('register', name, app);
      this[plural][name] = app;
      return this;
    };

    /**
     * Alias for `register`. Adds an `app` with the given `name`
     * to the `runner.apps` object.
     *
     * @name .addApp
     * @param {String} `name` The name of the config object to register
     * @param {Object|Function} `config` The config object or function
     * @api public
     */

    proto[method('add')] = function(name, config) {
      return this.register.apply(this, arguments);
    };

    /**
     * Return true if app `name` is registered. Dot-notation
     * may be used to check for [sub-apps](#sub-apps).
     *
     * ```js
     * base.hasApp('foo.bar.baz');
     * ```
     * @name .hasApp
     * @param {String} `name`
     * @return {Boolean}
     * @api public
     */

    proto[method('has')] = function(name) {
      if (this[plural].hasOwnProperty(name)) {
        return true;
      }
      name = name.split('.').join('.' + plural + '.');
      return this.has([plural, name]);
    };

    /**
     * Return app `name` is registered. Dot-notation
     * may be used to get [sub-apps](#sub-apps).
     *
     * ```js
     * base.getApp('foo');
     * // or
     * base.getApp('foo.bar.baz');
     * ```
     * @name .getApp
     * @param {String} `name`
     * @return {Boolean}
     * @api public
     */

    proto[method('get')] = function(name) {
      if (this[plural].hasOwnProperty(name)) {
        return this[plural][name];
      }
      name = name.split('.').join('.' + plural + '.');
      return this.get([plural, name]);
    };

    /**
     * Extend an app.
     *
     * ```js
     * var foo = base.getApp('foo');
     * foo.extendApp(app);
     * ```
     * @name .extendApp
     * @param {Object} `app`
     * @return {Object} Returns the instance for chaining.
     * @api public
     */

    proto[method('extend')] = function(app) {
      if (typeof this.fn !== 'function') {
        throw new Error('base-runner expected `fn` to be a function');
      }

      this.fn.call(app, app, this.base, this.env);
      return this;
    };

    /**
     * Run one or more apps and the specified tasks for each.
     *
     * ```js
     * // run the default tasks for apps `foo` and `bar`
     * foo.runApps(['foo', 'bar'], function(err) {
     *   if (err) return console.log(err);
     *   console.log('done!');
     * });
     *
     * // run the specified tasks for apps `foo` and `bar`
     * var apps = {
     *   foo: ['a', 'b', 'c'],
     *   bar: ['x', 'y', 'z']
     * };
     *
     * base.runApps(apps, function(err) {
     *   if (err) return console.log(err);
     *   console.log('done!');
     * });
     * ```
     * @param {Object} `apps`
     * @param {Function} `done`
     * @api public
     */

    proto[toPlural(method('run'))] = function(apps, done) {
      if (!Array.isArray(apps) || !utils.isObject(apps[0])) {
        apps = this.argv(apps)[plural];
      }

      this.emit(toPlural(method('run')), apps, this);

      utils.async.each(apps, function(app, cb) {
        utils.async.eachOf(app, function(tasks, name, next) {
          var instance = this[method('get')](name) || this;
          if (!instance) {
            return cb(new Error('cannot find ' + appName + ' "' + name + '"'));
          }
          this.emit('prebuild', name, tasks, instance);
          instance.build(tasks, cb);
        }.bind(this), cb);
      }.bind(this), done);
    };

    /**
     * Invoke app `fn` with the given `base` instance.
     *
     * ```js
     * runner.invoke(app.fn, app);
     * ```
     * @name .invoke
     * @param {Function} `fn` The app function.
     * @param {Object} `app` The "base" instance to use with the app.
     * @return {Object}
     * @api public
     */

    proto.invoke = function(name, app, base, env) {
      env = env || this.env;
      if (typeof app === 'function') {
        var fn = app;
        app = new this.constructor({name: name});
        app.fn = fn;
        init(app, this);
        fn.call(app, app, base || app.base, app.env);
      } else {
        // `parent` is used to get the base instance
        init(app, this);
      }

      function init(inst, parent) {
        inst.name = name;
        inst.env = env || inst.env;
        inst.define('parent', parent);
        inst.initRunner();
      }
      return app;
    };

    /**
     * Get the `base` instance
     */

    Object.defineProperty(proto, 'base', {
      configurable: true,
      get: function() {
        this.calledParent = true;
        return this.parent ? this.parent.base : this;
      }
    });

  };
}

/**
 * Expose `runner`
 */

module.exports = runner;

/**
 * If necessary, this static method will resolve the _first instance_
 * to be used as the `base` instance for caching any additional resolved configs.
 *
 * ```js
 * var Generate = require('generate');
 * var resolver = require('base-resolver');
 *
 * var generate = resolver.first('generator.js', 'generate', {
 *   Ctor: Generate,
 *   isModule: function(app) {
 *     return app.isGenerate;
 *   }
 * });
 * ```
 * @param {String} `configfile` The name of the config file, ex: `assemblefile.js`
 * @param {String} `moduleName` The name of the module to lookup, ex: `assemble`
 * @param {Object} `options`
 *   @option {Function} `options.isModule` Optionally pass a function that will be used to verify that the correct instance was created.
 * @return {Object}
 * @api public
 */

function getConfig(configfile, moduleName, options) {
  var opts = utils.extend({ cwd: process.cwd() }, options);
  var fp = path.resolve(opts.cwd, configfile);

  var User = utils.resolver.Resolver.User;
  var createEnv = utils.resolver.Resolver.createEnv;
  var fallback = opts.fallback;
  var Ctor = opts.Ctor;

  if (!utils.isAbsolute(fallback)) {
    fallback = utils.resolveModule(opts.fallback);
  }

  if (typeof Ctor !== 'function') {
    throw new TypeError('expected options.Ctor to be a function');
  }

  var validate = function() {
    return false;
  };

  if (typeof opts.isModule === 'function') {
    validate = opts.isModule;
  }

  // if a "configfile.js" is in the user's cwd, we'll try to
  // require it in and use it to get (or create) the instance
  if (fs.existsSync(fp)) {
    opts.module = moduleName;
    var env = createEnv(fp, opts.cwd, opts);
    Ctor = env.module.fn;

    if (typeof Ctor.create === 'function' && typeof opts.preload === 'function') {
      Ctor = Ctor.create(function(app, base) {
        return opts.preload(app, base, env);
      });
      Ctor.mixin(runner(moduleName, opts.appName));
    }

    // `fn` is whatever the "configfile" returns
    var fn = env.config.fn;

    // if the "configfile" returns a function, we need to
    // call the function, and pass an instance of our
    // application to it
    if (typeof fn === 'function') {
      var app = new Ctor();
      if (!env.user) {
        env.user = new User(env.config.cwd);
      }
      return app.invoke('base', fn, app, env);
    }

    // Otherwise, if the "configfile" returns an instance
    // of our application we'll use that as our `base`
    if (validate(fn)) {
      return fn;
    }
  }

  // if we haven't resolved a user-specified config file by now,
  // try the fallback dir, if passed on the options
  if (fallback && fallback !== opts.cwd) {
    opts.cwd = fallback;
    return getConfig(configfile, moduleName, opts);
  }

  // create a new, bare instance as a last resort
  return new Ctor();
};

<|endoftext|>


<commit_before>'use strict';

var fancyLog = require('fancy-log');
var PluginError = require('plugin-error');
var supportsColor = require('supports-color');
var File = require('vinyl');
var MemoryFileSystem = require('memory-fs');
var nodePath = require('path');
var through = require('through');
var ProgressPlugin = require('webpack/lib/ProgressPlugin');
var clone = require('lodash.clone');

var defaultStatsOptions = {
  colors: supportsColor.stdout.hasBasic,
  hash: false,
  timings: false,
  chunks: false,
  chunkModules: false,
  modules: false,
  children: true,
  version: true,
  cached: false,
  cachedAssets: false,
  reasons: false,
  source: false,
  errorDetails: false
};

var cache = {};

module.exports = function (options, wp, done) {
  if (cache.wp !== wp || cache.options !== options) {
    cache = {};
  }

  cache.options = options;
  cache.wp = wp;

  options = clone(options) || {};
  var config = options.config || options;

  /**
   * Webpack 4 doesn't support the `quiet` attribute, however supports
   * setting `stats` to a string within an array of configurations
   * (errors-only|minimal|none|normal|verbose)
   */
  const isSilent = options.quiet || (options.stats && (options.stats.match(/^(errors-only|minimal|none)$/)));

  if (typeof done !== 'function') {
    var callingDone = false;
    done = function (err, stats) {
      if (err) {
        // The err is here just to match the API but isnt used
        return;
      }
      stats = stats || {};
      if (isSilent || callingDone) {
        return;
      }

      // Debounce output a little for when in watch mode
      if (options.watch) {
        callingDone = true;
        setTimeout(function () {
          callingDone = false;
        }, 500);
      }

      if (options.verbose) {
        fancyLog(stats.toString({
          colors: supportsColor.stdout.hasBasic
        }));
      } else {
        var statsOptions = (options && options.stats) || {};

        if (typeof statsOptions === 'object') {
          Object.keys(defaultStatsOptions).forEach(function (key) {
            if (typeof statsOptions[key] === 'undefined') {
              statsOptions[key] = defaultStatsOptions[key];
            }
          });
        }
        var statusLog = stats.toString(statsOptions);
        if (statusLog) {
          fancyLog(statusLog);
        }
      }
    };
  }

  var webpack = wp || require('webpack');
  var entry = [];
  var entries = Object.create(null);

  var stream = through(function (file) {
    if (file.isNull()) {
      return;
    }
    if ('named' in file) {
      if (!Array.isArray(entries[file.named])) {
        entries[file.named] = [];
      }
      entries[file.named].push(file.path);
    } else {
      entry = entry || [];
      entry.push(file.path);
    }
  }, function () {
    var self = this;
    var handleConfig = function (config) {
      config.output = config.output || {};
      config.watch = !!options.watch;

      // Determine pipe'd in entry
      if (Object.keys(entries).length > 0) {
        entry = entries;
        if (!config.output.filename) {
          // Better output default for multiple chunks
          config.output.filename = '[name].js';
        }
      } else if (entry.length < 2) {
        entry = entry[0] || entry;
      }

      config.entry = config.entry || entry;
      config.output.path = config.output.path || process.cwd();
      config.output.filename = config.output.filename || '[hash].js';
      config.watch = options.watch;
      entry = [];

      if (!config.entry || config.entry.length < 1) {
        fancyLog('webpack-stream - No files given; aborting compilation');
        self.emit('end');
        return false;
      }
      return true;
    };

    var succeeded;
    if (Array.isArray(config)) {
      for (var i = 0; i < config.length; i++) {
        succeeded = handleConfig(config[i]);
        if (!succeeded) {
          return false;
        }
      }
    } else {
      succeeded = handleConfig(config);
      if (!succeeded) {
        return false;
      }
    }

    // Cache compiler for future use
    var compiler = cache.compiler || webpack(config);
    cache.compiler = compiler;

    const callback = function (err, stats) {
      if (err) {
        self.emit('error', new PluginError('webpack-stream', err));
        return;
      }
      var jsonStats = stats ? stats.toJson() || {} : {};
      var errors = jsonStats.errors || [];
      if (errors.length) {
        var errorMessage = errors.join('\n');
        var compilationError = new PluginError('webpack-stream', errorMessage);
        if (!options.watch) {
          self.emit('error', compilationError);
        }
        self.emit('compilation-error', compilationError);
      }
      if (!options.watch) {
        self.queue(null);
      }
      done(err, stats);
      if (options.watch && !isSilent) {
        fancyLog('webpack is watching for changes');
      }
    };

    if (options.watch) {
      const watchOptions = options.watchOptions || {};
      compiler.watch(watchOptions, callback);
    } else {
      compiler.run(callback);
    }

    var handleCompiler = function (compiler) {
      if (options.progress) {
        (new ProgressPlugin(function (percentage, msg) {
          percentage = Math.floor(percentage * 100);
          msg = percentage + '% ' + msg;
          if (percentage < 10) msg = ' ' + msg;
          fancyLog('webpack', msg);
        })).apply(compiler);
      }

      cache.mfs = cache.mfs || new MemoryFileSystem();

      var fs = compiler.outputFileSystem = cache.mfs;

      var afterEmitPlugin = compiler.hooks
        // Webpack 4
        ? function (callback) { compiler.hooks.afterEmit.tapAsync('WebpackStream', callback); }
        // Webpack 2/3
        : function (callback) { compiler.plugin('after-emit', callback); };

      afterEmitPlugin(function (compilation, callback) {
        Object.keys(compilation.assets).forEach(function (outname) {
          if (compilation.assets[outname].emitted) {
            var file = prepareFile(fs, compiler, outname);
            self.queue(file);
          }
        });
        callback();
      });
    };

    if (Array.isArray(options.config)) {
      compiler.compilers.forEach(function (compiler) {
        handleCompiler(compiler);
      });
    } else {
      handleCompiler(compiler);
    }
  });

  // If entry point manually specified, trigger that
  var hasEntry = Array.isArray(config)
    ? config.some(function (c) { return c.entry; })
    : config.entry;
  if (hasEntry) {
    stream.end();
  }

  return stream;
};

function prepareFile (fs, compiler, outname) {
  var path = fs.join(compiler.outputPath, outname);
  if (path.indexOf('?') !== -1) {
    path = path.split('?')[0];
  }

  var contents = fs.readFileSync(path);

  var file = new File({
    base: compiler.outputPath,
    path: nodePath.join(compiler.outputPath, outname),
    contents: contents
  });
  return file;
}

// Expose webpack if asked
Object.defineProperty(module.exports, 'webpack', {
  get: function () {
    return require('webpack');
  }
});
<commit_msg>Check if options.stats is a string before calling match. Fixes GH-211<commit_after>'use strict';

var fancyLog = require('fancy-log');
var PluginError = require('plugin-error');
var supportsColor = require('supports-color');
var File = require('vinyl');
var MemoryFileSystem = require('memory-fs');
var nodePath = require('path');
var through = require('through');
var ProgressPlugin = require('webpack/lib/ProgressPlugin');
var clone = require('lodash.clone');

var defaultStatsOptions = {
  colors: supportsColor.stdout.hasBasic,
  hash: false,
  timings: false,
  chunks: false,
  chunkModules: false,
  modules: false,
  children: true,
  version: true,
  cached: false,
  cachedAssets: false,
  reasons: false,
  source: false,
  errorDetails: false
};

var cache = {};

module.exports = function (options, wp, done) {
  if (cache.wp !== wp || cache.options !== options) {
    cache = {};
  }

  cache.options = options;
  cache.wp = wp;

  options = clone(options) || {};
  var config = options.config || options;

  // Webpack 4 doesn't support the `quiet` attribute, however supports
  // setting `stats` to a string within an array of configurations
  // (errors-only|minimal|none|normal|verbose) or an object with an absurd
  // amount of config
  const isSilent = options.quiet || (typeof options.stats === 'string' && (options.stats.match(/^(errors-only|minimal|none)$/)));

  if (typeof done !== 'function') {
    var callingDone = false;
    done = function (err, stats) {
      if (err) {
        // The err is here just to match the API but isnt used
        return;
      }
      stats = stats || {};
      if (isSilent || callingDone) {
        return;
      }

      // Debounce output a little for when in watch mode
      if (options.watch) {
        callingDone = true;
        setTimeout(function () {
          callingDone = false;
        }, 500);
      }

      if (options.verbose) {
        fancyLog(stats.toString({
          colors: supportsColor.stdout.hasBasic
        }));
      } else {
        var statsOptions = (options && options.stats) || {};

        if (typeof statsOptions === 'object') {
          Object.keys(defaultStatsOptions).forEach(function (key) {
            if (typeof statsOptions[key] === 'undefined') {
              statsOptions[key] = defaultStatsOptions[key];
            }
          });
        }
        var statusLog = stats.toString(statsOptions);
        if (statusLog) {
          fancyLog(statusLog);
        }
      }
    };
  }

  var webpack = wp || require('webpack');
  var entry = [];
  var entries = Object.create(null);

  var stream = through(function (file) {
    if (file.isNull()) {
      return;
    }
    if ('named' in file) {
      if (!Array.isArray(entries[file.named])) {
        entries[file.named] = [];
      }
      entries[file.named].push(file.path);
    } else {
      entry = entry || [];
      entry.push(file.path);
    }
  }, function () {
    var self = this;
    var handleConfig = function (config) {
      config.output = config.output || {};
      config.watch = !!options.watch;

      // Determine pipe'd in entry
      if (Object.keys(entries).length > 0) {
        entry = entries;
        if (!config.output.filename) {
          // Better output default for multiple chunks
          config.output.filename = '[name].js';
        }
      } else if (entry.length < 2) {
        entry = entry[0] || entry;
      }

      config.entry = config.entry || entry;
      config.output.path = config.output.path || process.cwd();
      config.output.filename = config.output.filename || '[hash].js';
      config.watch = options.watch;
      entry = [];

      if (!config.entry || config.entry.length < 1) {
        fancyLog('webpack-stream - No files given; aborting compilation');
        self.emit('end');
        return false;
      }
      return true;
    };

    var succeeded;
    if (Array.isArray(config)) {
      for (var i = 0; i < config.length; i++) {
        succeeded = handleConfig(config[i]);
        if (!succeeded) {
          return false;
        }
      }
    } else {
      succeeded = handleConfig(config);
      if (!succeeded) {
        return false;
      }
    }

    // Cache compiler for future use
    var compiler = cache.compiler || webpack(config);
    cache.compiler = compiler;

    const callback = function (err, stats) {
      if (err) {
        self.emit('error', new PluginError('webpack-stream', err));
        return;
      }
      var jsonStats = stats ? stats.toJson() || {} : {};
      var errors = jsonStats.errors || [];
      if (errors.length) {
        var errorMessage = errors.join('\n');
        var compilationError = new PluginError('webpack-stream', errorMessage);
        if (!options.watch) {
          self.emit('error', compilationError);
        }
        self.emit('compilation-error', compilationError);
      }
      if (!options.watch) {
        self.queue(null);
      }
      done(err, stats);
      if (options.watch && !isSilent) {
        fancyLog('webpack is watching for changes');
      }
    };

    if (options.watch) {
      const watchOptions = options.watchOptions || {};
      compiler.watch(watchOptions, callback);
    } else {
      compiler.run(callback);
    }

    var handleCompiler = function (compiler) {
      if (options.progress) {
        (new ProgressPlugin(function (percentage, msg) {
          percentage = Math.floor(percentage * 100);
          msg = percentage + '% ' + msg;
          if (percentage < 10) msg = ' ' + msg;
          fancyLog('webpack', msg);
        })).apply(compiler);
      }

      cache.mfs = cache.mfs || new MemoryFileSystem();

      var fs = compiler.outputFileSystem = cache.mfs;

      var afterEmitPlugin = compiler.hooks
        // Webpack 4
        ? function (callback) { compiler.hooks.afterEmit.tapAsync('WebpackStream', callback); }
        // Webpack 2/3
        : function (callback) { compiler.plugin('after-emit', callback); };

      afterEmitPlugin(function (compilation, callback) {
        Object.keys(compilation.assets).forEach(function (outname) {
          if (compilation.assets[outname].emitted) {
            var file = prepareFile(fs, compiler, outname);
            self.queue(file);
          }
        });
        callback();
      });
    };

    if (Array.isArray(options.config)) {
      compiler.compilers.forEach(function (compiler) {
        handleCompiler(compiler);
      });
    } else {
      handleCompiler(compiler);
    }
  });

  // If entry point manually specified, trigger that
  var hasEntry = Array.isArray(config)
    ? config.some(function (c) { return c.entry; })
    : config.entry;
  if (hasEntry) {
    stream.end();
  }

  return stream;
};

function prepareFile (fs, compiler, outname) {
  var path = fs.join(compiler.outputPath, outname);
  if (path.indexOf('?') !== -1) {
    path = path.split('?')[0];
  }

  var contents = fs.readFileSync(path);

  var file = new File({
    base: compiler.outputPath,
    path: nodePath.join(compiler.outputPath, outname),
    contents: contents
  });
  return file;
}

// Expose webpack if asked
Object.defineProperty(module.exports, 'webpack', {
  get: function () {
    return require('webpack');
  }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var repl = require('repl');
var fs = require('fs');
var path = require('path');
var xtend = require('xtend');
var camelCase = require('camel-case');
var pkginfo = require('pkginfo');

function getPrefix(cb){
  try {
    var prefix = path.resolve(pkginfo.find(null, process.cwd()), '..');
    return cb(null, prefix);
  }
  catch (err) {
    return cb(err);
  }
}

function readPackage(prefix, cb){
  var pkg = path.join(prefix, 'package.json');
  fs.readFile(pkg, 'utf8', function(err, data){
    if(err){
      return cb(err);
    }
    var packages;

    try {
      data = JSON.parse(data);
      packages = Object.keys(xtend(data.devDependencies, data.dependencies));
    } catch (e) {
      return cb(e);
    }

    cb(null, packages, data.name, data.main || 'index.js');
  });
}

function loadPackage(pkg, pkgPath, loadedPackages) {
  if(pkg.indexOf('.') > -1){
    console.log('Naming', pkg, 'as', pkg.replace(/\./g, '-'), 'in repl for ease of use');
    pkg = pkg.replace(/\./g, '-');
  }
  pkg = camelCase(pkg);
  loadedPackages[pkg] = require(pkgPath);
}

function loadPackages(prefix, packages, cb){
  var loadedPackages = {};
  packages.forEach(function(pkg){
    var pkgPath = path.resolve(prefix, 'node_modules', pkg);
    try {
      loadPackage(pkg, pkgPath, loadedPackages);
    } catch(e) {
      return cb(e);
    }

  });
  cb(null, loadedPackages);
}

function handleError(err){
  if (err) {
    console.log(err);
    process.exit(1);
  }
}

var replit = module.exports = function(){
  var loadMain = process.argv[2] == '--load-main';

  getPrefix(function (err, prefix) {
    handleError(err);

    readPackage(prefix, function(err, packages, projectName, projectMain){
      handleError(err);

      loadPackages(prefix, packages, function(err, pkgs){
        handleError(err);

        if (loadMain) {
          // Load main package.
          var main = path.resolve(prefix, projectMain);
          loadPackage(projectName, main, pkgs);
        }

        var r = repl.start({
          prompt: projectName+'> '
        });
        Object.keys(pkgs).forEach(function(p){
          r.context[p] = pkgs[p];
        });
      });
    });
  });
};

if(!module.parent){
  replit();
}<commit_msg>Add .loadmain REPL command<commit_after>#!/usr/bin/env node
'use strict';

var repl = require('repl');
var fs = require('fs');
var path = require('path');
var xtend = require('xtend');
var camelCase = require('camel-case');
var pkginfo = require('pkginfo');

function getPrefix(cb){
  try {
    var prefix = path.resolve(pkginfo.find(null, process.cwd()), '..');
    return cb(null, prefix);
  }
  catch (err) {
    return cb(err);
  }
}

function readPackage(prefix, cb){
  var pkg = path.join(prefix, 'package.json');
  fs.readFile(pkg, 'utf8', function(err, data){
    if(err){
      return cb(err);
    }
    var packages;

    try {
      data = JSON.parse(data);
      packages = Object.keys(xtend(data.devDependencies, data.dependencies));
    } catch (e) {
      return cb(e);
    }

    cb(null, packages, data.name, data.main || 'index.js');
  });
}

function getPackageDisplayName(pkg){
  if(pkg.indexOf('.') > -1){
    console.log('Naming', pkg, 'as', pkg.replace(/\./g, '-'), 'in repl for ease of use');
    pkg = pkg.replace(/\./g, '-');
  }
  pkg = camelCase(pkg);
  return pkg;
}

function loadPackages(prefix, packages, cb){
  var loadedPackages = {};
  packages.forEach(function(pkg){
    var pkgPath = path.resolve(prefix, 'node_modules', pkg);
    try {
      pkg = getPackageDisplayName(pkg);
      loadedPackages[pkg] = require(pkgPath);
    } catch(e) {
      return cb(e);
    }
  });
  cb(null, loadedPackages);
}

function handleError(err){
  if (err) {
    console.log(err);
    process.exit(1);
  }
}

var replit = module.exports = function(){
  var shouldLoadMain = process.argv[2] == '--load-main';

  getPrefix(function (err, prefix) {
    handleError(err);

    readPackage(prefix, function(err, packages, projectName, projectMain){
      handleError(err);

      loadPackages(prefix, packages, function(err, pkgs){
        handleError(err);

        var mainPackageLoaded = false;

        var loadMain = function (context) {
          var displayName = getPackageDisplayName(projectName);
          var pkgPath = path.resolve(prefix, projectMain);
          context[displayName] = require(pkgPath);

          console.log('Main package loaded as ' + displayName);
          mainPackageLoaded = true;
        };

        if (shouldLoadMain) {
          loadMain(pkgs);
        }

        var r = repl.start({
          prompt: projectName+'> '
        });

        Object.keys(pkgs).forEach(function(p){
          r.context[p] = pkgs[p];
        });

        r.defineCommand('loadmain', {
          help: 'Load the main entry from your package.json into the repl context',
          action: function() {
            if (mainPackageLoaded) {
              console.log('Main package already loaded!');
            }
            else {
              loadMain(r.context);
            }
            this.displayPrompt();
          }
        });
      });
    });
  });
};

if(!module.parent){
  replit();
}<|endoftext|>


<commit_before>var zlib = require('zlib')
var peek = require('peek-stream')
var through = require('through2')
var pumpify = require('pumpify')
var isGzip = require('is-gzip')
var isDeflate = require('is-deflate')

var isCompressed = function (data) {
  if (isGzip(data)) return 1
  if (isDeflate(data)) return 2
  return 0
}

var gunzip = function (maxRecursion) {
  if (!(0 <= maxRecursion)) maxRecursion = 3

  return peek({newline: false, maxBuffer: 10}, function (data, swap) {
    if (maxRecursion < 0) return swap(new Error('Maximum recursion reached'))
    switch (isCompressed(data)) {
      case 1:
        swap(null, pumpify(zlib.createGunzip(), gunzip(maxRecursion - 1)))
        break
      case 2:
        swap(null, pumpify(zlib.createInflate(), gunzip(maxRecursion - 1)))
        break
      default:
        swap(null, through())
    }
  })
}

module.exports = gunzip
<commit_msg>standard<commit_after>var zlib = require('zlib')
var peek = require('peek-stream')
var through = require('through2')
var pumpify = require('pumpify')
var isGzip = require('is-gzip')
var isDeflate = require('is-deflate')

var isCompressed = function (data) {
  if (isGzip(data)) return 1
  if (isDeflate(data)) return 2
  return 0
}

var gunzip = function (maxRecursion) {
  if (!(maxRecursion >= 0)) maxRecursion = 3

  return peek({newline: false, maxBuffer: 10}, function (data, swap) {
    if (maxRecursion < 0) return swap(new Error('Maximum recursion reached'))
    switch (isCompressed(data)) {
      case 1:
        swap(null, pumpify(zlib.createGunzip(), gunzip(maxRecursion - 1)))
        break
      case 2:
        swap(null, pumpify(zlib.createInflate(), gunzip(maxRecursion - 1)))
        break
      default:
        swap(null, through())
    }
  })
}

module.exports = gunzip
<|endoftext|>


<commit_before>'use strict';

//This file contains then/promise specific extensions to the core promise API

var Promise = require('./core.js')
var asap = require('asap')

module.exports = Promise

/* Static Functions */

function ValuePromise(value) {
  this.then = function (onFulfilled) {
    if (typeof onFulfilled !== 'function') return this
    return new Promise(function (resolve, reject) {
      asap(function () {
        try {
          resolve(onFulfilled(value))
        } catch (ex) {
          reject(ex);
        }
      })
    })
  }
}
ValuePromise.prototype = Object.create(Promise.prototype)

var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')

Promise.from = function (value) {
  if (value instanceof Promise) return value

  if (value === null) return NULL
  if (value === undefined) return UNDEFINED
  if (value === true) return TRUE
  if (value === false) return FALSE
  if (value === 0) return ZERO
  if (value === '') return EMPTYSTRING

  if (typeof value === 'object' || typeof value === 'function') {
    try {
      var then = value.then
      if (typeof then === 'function') {
        return new Promise(then.bind(value))
      }
    } catch (ex) {
      return new Promise(function (resolve, reject) {
        reject(ex)
      })
    }
  }

  return new ValuePromise(value)
}
Promise.denodeify = function (fn) {
  return function () {
    var self = this
    var args = Array.prototype.slice.call(arguments)
    return new Promise(function (resolve, reject) {
      args.push(function (err, res) {
        if (err) reject(err)
        else resolve(res)
      })
      fn.apply(self, args)
    })
  }
}
Promise.nodeify = function (fn) {
  return function () {
    var args = Array.prototype.slice.call(arguments)
    var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
    try {
      return fn.apply(this, arguments).nodeify(callback)
    } catch (ex) {
      if (callback === null || typeof callback == 'undefined') {
        return new Promise(function (resolve, reject) { reject(ex) })
      } else {
        asap(function () {
          callback(ex)
        })
      }
    }
  }
}

Promise.all = function () {
  var args = Array.prototype.slice.call(arguments.length === 1 && Array.isArray(arguments[0]) ? arguments[0] : arguments)

  return new Promise(function (resolve, reject) {
    if (args.length === 0) return resolve([])
    var remaining = args.length
    function res(i, val) {
      try {
        if (val && (typeof val === 'object' || typeof val === 'function')) {
          var then = val.then
          if (typeof then === 'function') {
            then.call(val, function (val) { res(i, val) }, reject)
            return
          }
        }
        args[i] = val
        if (--remaining === 0) {
          resolve(args);
        }
      } catch (ex) {
        reject(ex)
      }
    }
    for (var i = 0; i < args.length; i++) {
      res(i, args[i])
    }
  })
}

/* Prototype Methods */

Promise.prototype.done = function (onFulfilled, onRejected) {
  var self = arguments.length ? this.then.apply(this, arguments) : this
  self.then(null, function (err) {
    asap(function () {
      throw err
    })
  })
}
Promise.prototype.nodeify = function (callback) {
  if (callback === null || typeof callback == 'undefined') return this

  this.then(function (value) {
    asap(function () {
      callback(null, value)
    })
  }, function (err) {
    asap(function () {
      callback(err)
    })
  })
}
<commit_msg>fixes #23 by adding resolve, reject, cast, race, and prototype.catch<commit_after>'use strict';

//This file contains then/promise specific extensions to the core promise API

var Promise = require('./core.js')
var asap = require('asap')

module.exports = Promise

/* Static Functions */

function ValuePromise(value) {
  this.then = function (onFulfilled) {
    if (typeof onFulfilled !== 'function') return this
    return new Promise(function (resolve, reject) {
      asap(function () {
        try {
          resolve(onFulfilled(value))
        } catch (ex) {
          reject(ex);
        }
      })
    })
  }
}
ValuePromise.prototype = Object.create(Promise.prototype)

var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')

Promise.from = function (value) {
  if (value instanceof Promise) return value

  if (value === null) return NULL
  if (value === undefined) return UNDEFINED
  if (value === true) return TRUE
  if (value === false) return FALSE
  if (value === 0) return ZERO
  if (value === '') return EMPTYSTRING

  if (typeof value === 'object' || typeof value === 'function') {
    try {
      var then = value.then
      if (typeof then === 'function') {
        return new Promise(then.bind(value))
      }
    } catch (ex) {
      return new Promise(function (resolve, reject) {
        reject(ex)
      })
    }
  }

  return new ValuePromise(value)
}
Promise.denodeify = function (fn) {
  return function () {
    var self = this
    var args = Array.prototype.slice.call(arguments)
    return new Promise(function (resolve, reject) {
      args.push(function (err, res) {
        if (err) reject(err)
        else resolve(res)
      })
      fn.apply(self, args)
    })
  }
}
Promise.nodeify = function (fn) {
  return function () {
    var args = Array.prototype.slice.call(arguments)
    var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
    try {
      return fn.apply(this, arguments).nodeify(callback)
    } catch (ex) {
      if (callback === null || typeof callback == 'undefined') {
        return new Promise(function (resolve, reject) { reject(ex) })
      } else {
        asap(function () {
          callback(ex)
        })
      }
    }
  }
}

Promise.all = function () {
  var args = Array.prototype.slice.call(arguments.length === 1 && Array.isArray(arguments[0]) ? arguments[0] : arguments)

  return new Promise(function (resolve, reject) {
    if (args.length === 0) return resolve([])
    var remaining = args.length
    function res(i, val) {
      try {
        if (val && (typeof val === 'object' || typeof val === 'function')) {
          var then = val.then
          if (typeof then === 'function') {
            then.call(val, function (val) { res(i, val) }, reject)
            return
          }
        }
        args[i] = val
        if (--remaining === 0) {
          resolve(args);
        }
      } catch (ex) {
        reject(ex)
      }
    }
    for (var i = 0; i < args.length; i++) {
      res(i, args[i])
    }
  })
}

/* Prototype Methods */

Promise.prototype.done = function (onFulfilled, onRejected) {
  var self = arguments.length ? this.then.apply(this, arguments) : this
  self.then(null, function (err) {
    asap(function () {
      throw err
    })
  })
}

Promise.prototype.nodeify = function (callback) {
  if (callback === null || typeof callback == 'undefined') return this

  this.then(function (value) {
    asap(function () {
      callback(null, value)
    })
  }, function (err) {
    asap(function () {
      callback(err)
    })
  })
}

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

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

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

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

Promise.race = function (values) {
  return new Promise(function (resolve, reject) {
    values.map(function(value){
      Promise.cast(value).then(resolve, reject);
    })
  });
}<|endoftext|>


<commit_before>module.exports = Batch

function Batch(ready, all) {
  if(!(this instanceof Batch)) {
    return new Batch(ready, all)
  }

  this.jobs = []
  this.all = all
  this.ready = ready
  this.queud = false
  this.run = this.run.bind(this)
}

Batch.prototype.queue = queue
Batch.prototype.add = add
Batch.prototype.run = run

function add(fn) {
  var queued = false
    , batch = this
    , self
    , args

  return queue

  function queue() {
    args = [].slice.call(arguments)
    self = this

    if(queued) {
      return batch.all && batch.ready()
    }

    queued = true
    batch.queue(run)
  }

  function run() {
    queued = false
    fn.apply(self, args)
  }
}

function queue(fn) {
  this.jobs.push(fn)

  if(this.all || !this.queued) {
    this.queued = true
    this.ready(this)
  }
}

function run() {
  var jobs = this.jobs

  this.jobs = []
  this.queued = false

  for(var i = 0, l = jobs.length; i < l; ++i) {
    jobs[i]()
  }

  return !!this.jobs.length
}
<commit_msg>return correctly<commit_after>module.exports = Batch

function Batch(ready, all) {
  if(!(this instanceof Batch)) {
    return new Batch(ready, all)
  }

  this.jobs = []
  this.all = all
  this.ready = ready
  this.queud = false
  this.run = this.run.bind(this)
}

Batch.prototype.queue = queue
Batch.prototype.add = add
Batch.prototype.run = run

function add(fn) {
  var queued = false
    , batch = this
    , self
    , args

  return queue

  function queue() {
    args = [].slice.call(arguments)
    self = this

    if(queued) {
      return batch.all && batch.ready()
    }

    queued = true
    batch.queue(run)
  }

  function run() {
    queued = false
    fn.apply(self, args)
  }
}

function queue(fn) {
  this.jobs.push(fn)

  if(this.all || !this.queued) {
    this.queued = true
    this.ready(this)
  }
}

function run() {
  var jobs = this.jobs

  this.jobs = []
  this.queued = false

  for(var i = 0, l = jobs.length; i < l; ++i) {
    jobs[i]()
  }

  return !!jobs.length
}
<|endoftext|>


<commit_before>'use strict';

const memoryStreams = require('memory-streams');

function resolve(context, path) {
	function r(data, path) {
		if (!data) return;
		if (path.length === 0) return data;
		return r(data[path[0]], path.slice(1));
	}

	if (path.length === 0) return context.data;
	return r(context.get(path[0]), path.slice(1));
}

function stringify(value) {
	return "" + (value || "");
}

function Literal(str) { this.str = str; }
Literal.prototype.render = function* (_context) { yield this.str; }

function Interpolation(path, verbatim) {
	this.path = path;
	this.verbatim = verbatim;
}

Interpolation.prototype.render = function* (context) {
	const resolved = stringify(resolve(context, this.path));
	if (this.verbatim) yield resolved;
	else yield* escape(resolved);
}

function Sequence(seq) { this.seq = seq; }

Sequence.prototype.render = function* (context) {
	for (var i = 0; i < this.seq.length; ++i) {
		yield* this.seq[i].render(context);
	}
};

function Section(path, nested) {
	this.path = path;
	this.nested = nested;
}
Section.prototype.render = function* (context) {
	const value = resolve(context, this.path);

	if (!value) return;

	if (Array.isArray(value)) {
		for (var i = 0; i < value.length; ++i) {
			yield* this.nested.render(context.subcontext(value[i]));
		}
	} else if (typeof value === 'object') {
		yield* this.nested.render(context.subcontext(value));
	} else {
		yield* this.nested.render(context.subcontext({ ".": value }));
	}
};

function NegativeSection(path, nested) {
	this.path = path;
	this.nested = nested;
}
NegativeSection.prototype.render = function* (context) {
	const value = resolve(context, this.path);

	if (Array.isArray(value) && value.length) return;
	if (!Array.isArray(value) && value) return;

	yield* this.nested.render(context);
};

function Partial(partialName) {
	this.partialName = partialName;
}
Partial.prototype.render = function* (context) {
	var partial = context.getPartial(this.partialName);
	if (!partial) return;

	yield* parse(partial).render(context);
};

function Context(data, parent, partials) {
	this.data = data;
	this.parent = parent;
	this.partials = partials;
}
Context.prototype.get = function (id) {
	if (this.data.hasOwnProperty(id)) return this.data[id];
	else if (this.parent) return this.parent.get(id);
};
Context.prototype.getPartial = function (id) {
	if (this.partials && this.partials.hasOwnProperty(id)) return this.partials[id];
	else if (this.parent) return this.parent.getPartial(id);
};
Context.prototype.subcontext = function (data) {
	return new Context(data, this);
};

function* escape(str) {
	var i = 0;
	while (i < str.length) {
		var j = str.slice(i).search(/[&<>"']/);
		if (j === -1) {
			yield str.slice(i);
			return;
		}
		j += i;
		if (j !== i) yield str.slice(i, j);
		switch (str[j]) {
			case '&': yield '&'; break;
			case '<': yield '<'; break;
			case '>': yield '>'; break;
			case '"': yield '"'; break;
			case "'": yield '''; break;
		}
		i = j+1;
	}
}

function getSequence(ctx, str) {
	var i = 0;
	var seq = [];

	while (i < str.length) {
		const openPos = str.indexOf(ctx.openDelimiter, i);

		if (openPos === -1) {
			seq.push(new Literal(str.slice(i)));
			i = str.length;
			break;
		}

		if (openPos > i) {
			seq.push(new Literal(str.slice(i, openPos)));
		}

		i = openPos + ctx.openDelimiter.length;

		if (i >= str.length) throw new Error("Mustache tag opened without being closed");

		var expectedCloseDelimiter = ctx.closeDelimiter;

		var fn = str[i];

		switch (str[i]) {
		case '{': expectedCloseDelimiter = '}' + ctx.closeDelimiter; break;
		case '=': expectedCloseDelimiter = '=' + ctx.closeDelimiter; break;
		}

		if (fn.match(/[{&=>#/^!]/)) i++;
		else fn = '';

		const closePos = str.indexOf(expectedCloseDelimiter, i);
		if (closePos === -1) throw new Error("Mustache tag opened without being closed");

		const tagContents = str.slice(i, closePos).trim();

		i = closePos + expectedCloseDelimiter.length;

		switch (fn) {
		case '': seq.push(new Interpolation(tagContents === '.' ? [] : tagContents.split('.'))); break;
		case '{':
		case '&':
			seq.push(new Interpolation(tagContents === '.' ? [] : tagContents.split('.'), true)); break;
		case '=':
			const delimiters = tagContents.split(/\s+/);
			if (delimiters.length !== 2) throw new Error(`Invalid delimiter specification: ${JSON.stringify(tagContents)}`);
			ctx.openDelimiter = delimiters[0];
			ctx.closeDelimiter = delimiters[1];
			break;
		case '#': {
			const nested = getSequence(ctx, str.slice(i));
			i += nested.len;
			seq.push(new Section(tagContents === '.' ? [] : tagContents.split('.'), nested.ast));
			break;
		}
		case '^': {
			const nested = getSequence(ctx, str.slice(i));
			i += nested.len;
			seq.push(new NegativeSection(tagContents === '.' ? [] : tagContents.split('.'), nested.ast));
			break;
		}
		case '/':
			// TODO Check closing tag
			return {
				ast: new Sequence(seq),
				len: i
			};
		case '>': seq.push(new Partial(tagContents));
		case '!': break;
		}
	}

	return {
		ast: new Sequence(seq),
		len: i
	};
}

function parse(str) {
	const ctx = {
		openDelimiter: '{{',
		closeDelimiter: '}}'
	};

	const result = getSequence(ctx, str);

	if (result.len !== str.length) throw new Error('Unable to fully parse input');
	return result.ast;
}

var Readable = require('readable-stream').Readable;

function GeneratorStream(source) {
    if (!source.next) throw new TypeError('source must be an iterator');

    Readable.call(this, {objectMode: true});
    this._source = source;
}
GeneratorStream.prototype = Object.create(Readable.prototype, {constructor: {value: GeneratorStream}});

GeneratorStream.prototype._read = function(size) {
    try {
        do {
            var r = this._source.next();

            if (r.done) {
                this.push(null);
                break;
            }
        } while (this.push(r.value));
    } catch (e) {
        this.emit('error', e);
    }
};

function render(template, data, partials) {
	return string(template).render(data, partials).string();
}

function Template(templateAST) {
	this.template = templateAST;
}
Template.prototype.render = function (data, partials) {
	const r = this.template.render(new Context(data, null, partials));
	const reader = new GeneratorStream(r);

	return {
		string: () => new Promise((resolve, reject) => {
			const writer = new memoryStreams.WritableStream();

			reader.pipe(writer);
			reader.on('end', function () {
				resolve(writer.toString());
			});

			reader.on('error', reject);
			writer.on('error', reject);
		}),
		stream: () => reader
	};
};

function string(templateString) {
	return new Template(parse(templateString));
}

module.exports = {
	render,
	string
};
<commit_msg>Use Readable stream from the standard library<commit_after>'use strict';

const memoryStreams = require('memory-streams');

function resolve(context, path) {
	function r(data, path) {
		if (!data) return;
		if (path.length === 0) return data;
		return r(data[path[0]], path.slice(1));
	}

	if (path.length === 0) return context.data;
	return r(context.get(path[0]), path.slice(1));
}

function stringify(value) {
	return "" + (value || "");
}

function Literal(str) { this.str = str; }
Literal.prototype.render = function* (_context) { yield this.str; }

function Interpolation(path, verbatim) {
	this.path = path;
	this.verbatim = verbatim;
}

Interpolation.prototype.render = function* (context) {
	const resolved = stringify(resolve(context, this.path));
	if (this.verbatim) yield resolved;
	else yield* escape(resolved);
}

function Sequence(seq) { this.seq = seq; }

Sequence.prototype.render = function* (context) {
	for (var i = 0; i < this.seq.length; ++i) {
		yield* this.seq[i].render(context);
	}
};

function Section(path, nested) {
	this.path = path;
	this.nested = nested;
}
Section.prototype.render = function* (context) {
	const value = resolve(context, this.path);

	if (!value) return;

	if (Array.isArray(value)) {
		for (var i = 0; i < value.length; ++i) {
			yield* this.nested.render(context.subcontext(value[i]));
		}
	} else if (typeof value === 'object') {
		yield* this.nested.render(context.subcontext(value));
	} else {
		yield* this.nested.render(context.subcontext({ ".": value }));
	}
};

function NegativeSection(path, nested) {
	this.path = path;
	this.nested = nested;
}
NegativeSection.prototype.render = function* (context) {
	const value = resolve(context, this.path);

	if (Array.isArray(value) && value.length) return;
	if (!Array.isArray(value) && value) return;

	yield* this.nested.render(context);
};

function Partial(partialName) {
	this.partialName = partialName;
}
Partial.prototype.render = function* (context) {
	var partial = context.getPartial(this.partialName);
	if (!partial) return;

	yield* parse(partial).render(context);
};

function Context(data, parent, partials) {
	this.data = data;
	this.parent = parent;
	this.partials = partials;
}
Context.prototype.get = function (id) {
	if (this.data.hasOwnProperty(id)) return this.data[id];
	else if (this.parent) return this.parent.get(id);
};
Context.prototype.getPartial = function (id) {
	if (this.partials && this.partials.hasOwnProperty(id)) return this.partials[id];
	else if (this.parent) return this.parent.getPartial(id);
};
Context.prototype.subcontext = function (data) {
	return new Context(data, this);
};

function* escape(str) {
	var i = 0;
	while (i < str.length) {
		var j = str.slice(i).search(/[&<>"']/);
		if (j === -1) {
			yield str.slice(i);
			return;
		}
		j += i;
		if (j !== i) yield str.slice(i, j);
		switch (str[j]) {
			case '&': yield '&'; break;
			case '<': yield '<'; break;
			case '>': yield '>'; break;
			case '"': yield '"'; break;
			case "'": yield '''; break;
		}
		i = j+1;
	}
}

function getSequence(ctx, str) {
	var i = 0;
	var seq = [];

	while (i < str.length) {
		const openPos = str.indexOf(ctx.openDelimiter, i);

		if (openPos === -1) {
			seq.push(new Literal(str.slice(i)));
			i = str.length;
			break;
		}

		if (openPos > i) {
			seq.push(new Literal(str.slice(i, openPos)));
		}

		i = openPos + ctx.openDelimiter.length;

		if (i >= str.length) throw new Error("Mustache tag opened without being closed");

		var expectedCloseDelimiter = ctx.closeDelimiter;

		var fn = str[i];

		switch (str[i]) {
		case '{': expectedCloseDelimiter = '}' + ctx.closeDelimiter; break;
		case '=': expectedCloseDelimiter = '=' + ctx.closeDelimiter; break;
		}

		if (fn.match(/[{&=>#/^!]/)) i++;
		else fn = '';

		const closePos = str.indexOf(expectedCloseDelimiter, i);
		if (closePos === -1) throw new Error("Mustache tag opened without being closed");

		const tagContents = str.slice(i, closePos).trim();

		i = closePos + expectedCloseDelimiter.length;

		switch (fn) {
		case '': seq.push(new Interpolation(tagContents === '.' ? [] : tagContents.split('.'))); break;
		case '{':
		case '&':
			seq.push(new Interpolation(tagContents === '.' ? [] : tagContents.split('.'), true)); break;
		case '=':
			const delimiters = tagContents.split(/\s+/);
			if (delimiters.length !== 2) throw new Error(`Invalid delimiter specification: ${JSON.stringify(tagContents)}`);
			ctx.openDelimiter = delimiters[0];
			ctx.closeDelimiter = delimiters[1];
			break;
		case '#': {
			const nested = getSequence(ctx, str.slice(i));
			i += nested.len;
			seq.push(new Section(tagContents === '.' ? [] : tagContents.split('.'), nested.ast));
			break;
		}
		case '^': {
			const nested = getSequence(ctx, str.slice(i));
			i += nested.len;
			seq.push(new NegativeSection(tagContents === '.' ? [] : tagContents.split('.'), nested.ast));
			break;
		}
		case '/':
			// TODO Check closing tag
			return {
				ast: new Sequence(seq),
				len: i
			};
		case '>': seq.push(new Partial(tagContents));
		case '!': break;
		}
	}

	return {
		ast: new Sequence(seq),
		len: i
	};
}

function parse(str) {
	const ctx = {
		openDelimiter: '{{',
		closeDelimiter: '}}'
	};

	const result = getSequence(ctx, str);

	if (result.len !== str.length) throw new Error('Unable to fully parse input');
	return result.ast;
}

var Readable = require('stream').Readable;

function GeneratorStream(source) {
    if (!source.next) throw new TypeError('source must be an iterator');

    Readable.call(this, {objectMode: true});
    this._source = source;
}
GeneratorStream.prototype = Object.create(Readable.prototype, {constructor: {value: GeneratorStream}});

GeneratorStream.prototype._read = function(size) {
    try {
        do {
            var r = this._source.next();

            if (r.done) {
                this.push(null);
                break;
            }
        } while (this.push(r.value));
    } catch (e) {
        this.emit('error', e);
    }
};

function render(template, data, partials) {
	return string(template).render(data, partials).string();
}

function Template(templateAST) {
	this.template = templateAST;
}
Template.prototype.render = function (data, partials) {
	const r = this.template.render(new Context(data, null, partials));
	const reader = new GeneratorStream(r);

	return {
		string: () => new Promise((resolve, reject) => {
			const writer = new memoryStreams.WritableStream();

			reader.pipe(writer);
			reader.on('end', function () {
				resolve(writer.toString());
			});

			reader.on('error', reject);
			writer.on('error', reject);
		}),
		stream: () => reader
	};
};

function string(templateString) {
	return new Template(parse(templateString));
}

module.exports = {
	render,
	string
};
<|endoftext|>


<commit_before>var docpadConfig,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

var imgBaseUrl = '/images/';
var sponsorsImgBaseUrl = imgBaseUrl + 'sponsors/';
var speakersImgBaseUrl = imgBaseUrl + 'speakers/';
var partnersImgBaseUrl = imgBaseUrl + 'partners/';

docpadConfig = {
  outPath: '../2015.mobilization.pl-gh-pages/',
  templateData: {
    site: {
      url: "http://mobilization.pl",
      oldUrls: ['www.mobilization.pl'],
      title: "Mobilization 2015",
      description: "Mobilization is a conference dedicated to mobile technologies. The main scope is development of mobile solutions aimed at smartphones and tablets, with particular interest in Android, iOS and Windows Phone platforms.",
      keywords: "mobilization, conference, mobile conference, Łódź",
      styles: [],
      scripts: [],

      event: {
      	title: 'Mobilization 2015',
      	location: {
      		lat: 51.7505458,
      		lng: 19.4501351,
      		place: 'Expo-Łódź Sp. z o.o.',
      		street: 'al. Politechniki 4',
      		city: 'Łódź',
      		zip: '93-590',
      		country: 'Polska'
      	},
      	data: '17th Oct 2015',
      	time: '07:30-17:30'
      },
      sponsors: {
      	platinum: [
			{"name":"Seamless","logo_url":"/images/sponsors/seamless.png","link":"http://seamless.se/"},{"name":"TomTom","logo_url":"/images/sponsors/tomtom.png","link":"http://www.tomtom.com/pl_pl/"}
      	],
      	gold: [
			{"name":"Ericpol","logo_url":"/images/sponsors/ericpol.jpg","link":"http://www.ericpol.pl/"}
      	],
      	silver: [

      	],
      },
      partners: {
      	organizers: [
      		{
      			name: 'Java User Group Łódź',
      			logo_url: partnersImgBaseUrl + 'juglodz.png',
      			description_html: 'Łódź JUG is an association of Java developers, architects and enthusiasts of Java technology from Łódź, the city in the centre of Poland. The aim of the association is to promote exchange of knowledge and competence growth among Java professionals in the Łódźarea. The main activity towards this goal is organisation of IT-related seminars and meetings that usually involve a presentation about chosen topic and then follow-up discussion. LJUG cooperates with other JUGs in Poland, like Polish JUG and Warsaw JUG. We encourage everyone interested in Java technologies to join and start participating in our expertise-sharing activities! Java User Group Łódź is main organizer of Mobilization event since 2011'
      		}
      	],
      	supporters: [
			{"name":"Upmenu","logo_url":"/images/partners/upmenu.png","description_html":"Upmenu had created new layout for Mobilization 2014! which is used for Mobilization 2015. Besides creating mobile and responsive layouts they work in Horeca business and help restaurants with online orders. Check out more on their webpage"},
      	],
      	community: [
			// {"name":"Łódź WiOSłuje","logo_url":"/images/partners/lodz-wiosluje.png","description_html":"The best place for iOS developers based in Łódź. A group with monthly meetings with tech talks, fantastic speakers and unbeatable atmosphere! Join us on facebook: www.facebook.com/lodzwiosluje"},
			// {"name":"Toruń JUG","logo_url":"/images/partners/jugtorun.png","description_html":"Toruń JUG is a group of JVM technologies developers and enthusiasts. The main goal of the group is to gather people interested in JVM languages both professionally and personally. Our group contains programmers from many companies, scientists working on Toruń university, students and other technology passionates. We are encouraging knowledge sharing and collaboration in open source projects. Although we are the youngest JUG in Poland we are growing fast already having several big partners supporting us. More about Toruń JUG you can find at: torun.jug.pl"},
			// {"name":"Polish Java User Group","logo_url":"/images/partners/polish-jug.png","description_html":"Polish Java User Group is a group of Java technology developers and enthusiasts. The main goal of the group is to popularize Java and modern software development methodologies. Since the beginning in 1999, the group had great impact on the Polish Java community growth. They main activity are meetings with students, programmers and project managers as well as conferences with famous professionals."},
			// {"name":"Mobile Central Europe 2015","logo_url":"/images/partners/mce2015.png","description_html":"We put our best effort into creating a stimulating experience for everyone involved. Help us make it one of the best mobile events in Europe! MCE is about bringing together the greatest minds in tech to exchange groundbreaking ideas. For Mobilization attendees promo-code will be offered giving 20% discount. Code will be visible during Mobilization event so you have to be on Mobilization! With this discount and early bird the ticket for MCE is really good price."},
			{"name":"GDG Kraków","logo_url":"/images/partners/gdgkrakow.png","link":"http://www.meetup.com/GDG-Krakow/"},
			// {"name":"MIT Łódź","logo_url":"/images/partners/mit.png","link":"http://mitlodz.pl"}
      	],
      	media: [
			// {"name":"AK74","logo_url":"/images/partners/ak74.png","description_html":"Cześć! Nazywam się Artur Kurasiński i jestem autorem tego bloga. Na co dzień zajmuję się Fokusem. Jestem współtwórcą cyklu spotkań dla przedsiębiorców Aula Polska oraz konkursu Aulery. Jako vloger prowadzę program „Seria z AK74″. Czasami udzielam się jako mentor na imprezach z cyklu Seedcamp, Labstar, DemoCamp, Intel Challenge, i StartupFest. Więcej znajdziesz tutaj: LinkedIn.com czy Facebooku lub Twitterze Chcesz się ze mną skontaktować?: Wyślij maila na adres: artur@revolver.pl"},
			// {"name":"Marketing Mobilny","logo_url":"/images/partners/marketing-mobilny.jpg","link":"http://marketingmobilny.pl"},
			// {"name":"Dworzynska","logo_url":"/images/partners/dworzynska.png","link":"http://dworzynska.com"},
			// {"name":"Praca IT","logo_url":"/images/partners/pracait.png","link":"http://pracait.com"},
			// {"name":"Software Developer's Journal","logo_url":"/images/partners/sdj.png","link":"http://sdjournal.pl"},
			{"name":"GoMobi","logo_url":"/images/partners/gomobi.jpg","link":"http://gomobi.pl"},
			// {"name":"Programista Magazine","logo_url":"/images/partners/programistamag.png","link":"http://programistamag.pl"},
			// {"name":"MyApple","logo_url":"/images/partners/myapple.jpg","link":"http://myapple.pl"},
			// {"name":"4tech.tv","logo_url":"/images/partners/4techmobile.png","link":"http://testytelefonow.pl"},
			// {"name":"StartUpTV","logo_url":"/images/partners/startuptv.png","link":"http://startuptv.pl"},
			{"name":"Linux Magazine","logo_url":"/images/partners/linuxmag.png","link":"http://www.linux-magazine.pl"},
			// {"name":"Kariera Plus","logo_url":"/images/partners/karieraplus.png","link":"http://karieraplus.pl"},
			// {"name":"Młodzi w Łodzi","logo_url":"/images/partners/mlodzi-w-lodzi.jpg","link":"http://mlodziwlodzi.pl"},
			{"name":"Helion","logo_url":"/images/partners/helionpl.png","link":"http://helion.pl"},
			// {"name":"Manning Publications","logo_url":"/images/partners/manning.png","link":"http://www.manning.com"}
      	]
      },
      slots: {
      	'slot-registration': {
      		from: '7:30',
      		to:   '9:00'
      	},
      	'slot-hello-world': {
      		from: '9:00',
      		to:   '9:10'
      	},
      	'slot-1': {
      		from: '9:10',
      		to:   '9:55'
      	},
      	'slot-coffee-1': {
      	   	from: '9:55',
      		to:   '10:15'
      	},
      	'slot-2': {
      		from: '10:15',
      		to:   '11:00'
      	},
      	'slot-coffee-2': {
      	   	from: '11:00',
      		to:   '11:20'
      	},
      	'slot-3': {
      		from: '11:20',
      		to:   '12:05'
      	},
      	'slot-coffee-3': {
      	   	from: '12:05',
      		to:   '12:25'
      	},
       	'slot-4': {
      		from: '12:25',
      		to:   '13:10'
      	},
      	'slot-lunch': {
      	   	from: '13:10',
      		to:   '14:30'
      	},
        'slot-5': {
      		from: '14:30',
      		to:   '15:15'
      	},
        'slot-coffee-4': {
      	   	from: '15:15',
      		to:   '15:30'
      	},
        'slot-6': {
      		from: '15:30',
      		to:   '16:15'
      	},
        'slot-coffee-5': {
      	   	from: '16:15',
      		to:   '16:30'
      	},
        'slot-7': {
      		from: '16:30',
      		to:   '17:15'
      	},
      	'slot-finally': {
      		from: '17:15',
      		to:   '18:00'
      	},
      },
      speakers: {

   	  },
   	  talks: {

   	  },
   	  breaks: {
   	  	'break-registration': {
   	  		title: 'Registration',
   	  		description_html: 'If you do not want to miss any presentation please register between 7:30-9:10. However, registration will be opened all day!'
   	  	},
   	  	'break-hello-world': {
   	  		title: 'Hello World',
   	  		description_html: 'This is couple of words about Mobilization. For community by community.'
   	  	},
   	  	'break-coffee': {
   	  	 	title: 'Coffee Break',
   	  		description_html: ''
   	  	},
   	  	'break-lunch': {
   	  		title: 'Lunch Break',
   	  		description_html: 'There is Solider soup - "Grochówka" for everyone! VIPs (Speakers, Sponsors) have lunch in Congresowa Restaurant on base floor.'
   	  	},
   	  	'break-finally': {
   	  		title: 'Finally',
   	  		description_html: ''
   	  	}
   	  },
   	  venues: {

   	  },
   	  schedule: {

   	  }
    },
    getPreparedTitle: function() {
      if (this.document.title) {
        return this.document.title + " | " + this.site.title;
      } else {
        return this.site.title;
      }
    },
    getPreparedDescription: function() {
      return this.document.description || this.site.description;
    },
    getPreparedKeywords: function() {
      return this.site.keywords.concat(this.document.keywords || []).join(', ');
    }
  },
  collections: {
    posts: function() {
      return this.getCollection('documents').findAllLive({
        relativeOutDirPath: 'posts'
      });
    }
  },
  environments: {
    development: {
      templateData: {
        site: {
          url: false
        }
      }
    }
  },
  events: {
    serverExtend: function(opts) {
      var docpad, latestConfig, newUrl, oldUrls, server;
      server = opts.server;
      docpad = this.docpad;
      latestConfig = docpad.getConfig();
      oldUrls = latestConfig.templateData.site.oldUrls || [];
      newUrl = latestConfig.templateData.site.url;
      return server.use(function(req, res, next) {
        var ref;
        if (ref = req.headers.host, indexOf.call(oldUrls, ref) >= 0) {
          return res.redirect(newUrl + req.url, 301);
        } else {
          return next();
        }
      });
    }
  }
};

module.exports = docpadConfig;

// ---
// generated by coffee-script 1.9.2
<commit_msg>Removed linux magazine<commit_after>var docpadConfig,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

var imgBaseUrl = '/images/';
var sponsorsImgBaseUrl = imgBaseUrl + 'sponsors/';
var speakersImgBaseUrl = imgBaseUrl + 'speakers/';
var partnersImgBaseUrl = imgBaseUrl + 'partners/';

docpadConfig = {
  outPath: '../2015.mobilization.pl-gh-pages/',
  templateData: {
    site: {
      url: "http://mobilization.pl",
      oldUrls: ['www.mobilization.pl'],
      title: "Mobilization 2015",
      description: "Mobilization is a conference dedicated to mobile technologies. The main scope is development of mobile solutions aimed at smartphones and tablets, with particular interest in Android, iOS and Windows Phone platforms.",
      keywords: "mobilization, conference, mobile conference, Łódź",
      styles: [],
      scripts: [],

      event: {
      	title: 'Mobilization 2015',
      	location: {
      		lat: 51.7505458,
      		lng: 19.4501351,
      		place: 'Expo-Łódź Sp. z o.o.',
      		street: 'al. Politechniki 4',
      		city: 'Łódź',
      		zip: '93-590',
      		country: 'Polska'
      	},
      	data: '17th Oct 2015',
      	time: '07:30-17:30'
      },
      sponsors: {
      	platinum: [
			{"name":"Seamless","logo_url":"/images/sponsors/seamless.png","link":"http://seamless.se/"},{"name":"TomTom","logo_url":"/images/sponsors/tomtom.png","link":"http://www.tomtom.com/pl_pl/"}
      	],
      	gold: [
			{"name":"Ericpol","logo_url":"/images/sponsors/ericpol.jpg","link":"http://www.ericpol.pl/"}
      	],
      	silver: [

      	],
      },
      partners: {
      	organizers: [
      		{
      			name: 'Java User Group Łódź',
      			logo_url: partnersImgBaseUrl + 'juglodz.png',
      			description_html: 'Łódź JUG is an association of Java developers, architects and enthusiasts of Java technology from Łódź, the city in the centre of Poland. The aim of the association is to promote exchange of knowledge and competence growth among Java professionals in the Łódźarea. The main activity towards this goal is organisation of IT-related seminars and meetings that usually involve a presentation about chosen topic and then follow-up discussion. LJUG cooperates with other JUGs in Poland, like Polish JUG and Warsaw JUG. We encourage everyone interested in Java technologies to join and start participating in our expertise-sharing activities! Java User Group Łódź is main organizer of Mobilization event since 2011'
      		}
      	],
      	supporters: [
			{"name":"Upmenu","logo_url":"/images/partners/upmenu.png","description_html":"Upmenu had created new layout for Mobilization 2014! which is used for Mobilization 2015. Besides creating mobile and responsive layouts they work in Horeca business and help restaurants with online orders. Check out more on their webpage"},
      	],
      	community: [
			// {"name":"Łódź WiOSłuje","logo_url":"/images/partners/lodz-wiosluje.png","description_html":"The best place for iOS developers based in Łódź. A group with monthly meetings with tech talks, fantastic speakers and unbeatable atmosphere! Join us on facebook: www.facebook.com/lodzwiosluje"},
			// {"name":"Toruń JUG","logo_url":"/images/partners/jugtorun.png","description_html":"Toruń JUG is a group of JVM technologies developers and enthusiasts. The main goal of the group is to gather people interested in JVM languages both professionally and personally. Our group contains programmers from many companies, scientists working on Toruń university, students and other technology passionates. We are encouraging knowledge sharing and collaboration in open source projects. Although we are the youngest JUG in Poland we are growing fast already having several big partners supporting us. More about Toruń JUG you can find at: torun.jug.pl"},
			// {"name":"Polish Java User Group","logo_url":"/images/partners/polish-jug.png","description_html":"Polish Java User Group is a group of Java technology developers and enthusiasts. The main goal of the group is to popularize Java and modern software development methodologies. Since the beginning in 1999, the group had great impact on the Polish Java community growth. They main activity are meetings with students, programmers and project managers as well as conferences with famous professionals."},
			// {"name":"Mobile Central Europe 2015","logo_url":"/images/partners/mce2015.png","description_html":"We put our best effort into creating a stimulating experience for everyone involved. Help us make it one of the best mobile events in Europe! MCE is about bringing together the greatest minds in tech to exchange groundbreaking ideas. For Mobilization attendees promo-code will be offered giving 20% discount. Code will be visible during Mobilization event so you have to be on Mobilization! With this discount and early bird the ticket for MCE is really good price."},
			{"name":"GDG Kraków","logo_url":"/images/partners/gdgkrakow.png","link":"http://www.meetup.com/GDG-Krakow/"},
			// {"name":"MIT Łódź","logo_url":"/images/partners/mit.png","link":"http://mitlodz.pl"},
			{"name":"Dev Day 2015","logo_url":"/images/partners/abb-dev-day.svg","link":"http://devday.pl"},
      	],
      	media: [
			// {"name":"AK74","logo_url":"/images/partners/ak74.png","description_html":"Cześć! Nazywam się Artur Kurasiński i jestem autorem tego bloga. Na co dzień zajmuję się Fokusem. Jestem współtwórcą cyklu spotkań dla przedsiębiorców Aula Polska oraz konkursu Aulery. Jako vloger prowadzę program „Seria z AK74″. Czasami udzielam się jako mentor na imprezach z cyklu Seedcamp, Labstar, DemoCamp, Intel Challenge, i StartupFest. Więcej znajdziesz tutaj: LinkedIn.com czy Facebooku lub Twitterze Chcesz się ze mną skontaktować?: Wyślij maila na adres: artur@revolver.pl"},
			// {"name":"Marketing Mobilny","logo_url":"/images/partners/marketing-mobilny.jpg","link":"http://marketingmobilny.pl"},
			// {"name":"Dworzynska","logo_url":"/images/partners/dworzynska.png","link":"http://dworzynska.com"},
			// {"name":"Praca IT","logo_url":"/images/partners/pracait.png","link":"http://pracait.com"},
			// {"name":"Software Developer's Journal","logo_url":"/images/partners/sdj.png","link":"http://sdjournal.pl"},
			{"name":"GoMobi","logo_url":"/images/partners/gomobi.jpg","link":"http://gomobi.pl"},
			// {"name":"Programista Magazine","logo_url":"/images/partners/programistamag.png","link":"http://programistamag.pl"},
			// {"name":"MyApple","logo_url":"/images/partners/myapple.jpg","link":"http://myapple.pl"},
			// {"name":"4tech.tv","logo_url":"/images/partners/4techmobile.png","link":"http://testytelefonow.pl"},
			// {"name":"StartUpTV","logo_url":"/images/partners/startuptv.png","link":"http://startuptv.pl"},
//			{"name":"Linux Magazine","logo_url":"/images/partners/linuxmag.png","link":"http://www.linux-magazine.pl"},
			// {"name":"Kariera Plus","logo_url":"/images/partners/karieraplus.png","link":"http://karieraplus.pl"},
			// {"name":"Młodzi w Łodzi","logo_url":"/images/partners/mlodzi-w-lodzi.jpg","link":"http://mlodziwlodzi.pl"},
			{"name":"Helion","logo_url":"/images/partners/helionpl.png","link":"http://helion.pl"},
			// {"name":"Manning Publications","logo_url":"/images/partners/manning.png","link":"http://www.manning.com"}
      	]
      },
      slots: {
      	'slot-registration': {
      		from: '7:30',
      		to:   '9:00'
      	},
      	'slot-hello-world': {
      		from: '9:00',
      		to:   '9:10'
      	},
      	'slot-1': {
      		from: '9:10',
      		to:   '9:55'
      	},
      	'slot-coffee-1': {
      	   	from: '9:55',
      		to:   '10:15'
      	},
      	'slot-2': {
      		from: '10:15',
      		to:   '11:00'
      	},
      	'slot-coffee-2': {
      	   	from: '11:00',
      		to:   '11:20'
      	},
      	'slot-3': {
      		from: '11:20',
      		to:   '12:05'
      	},
      	'slot-coffee-3': {
      	   	from: '12:05',
      		to:   '12:25'
      	},
       	'slot-4': {
      		from: '12:25',
      		to:   '13:10'
      	},
      	'slot-lunch': {
      	   	from: '13:10',
      		to:   '14:30'
      	},
        'slot-5': {
      		from: '14:30',
      		to:   '15:15'
      	},
        'slot-coffee-4': {
      	   	from: '15:15',
      		to:   '15:30'
      	},
        'slot-6': {
      		from: '15:30',
      		to:   '16:15'
      	},
        'slot-coffee-5': {
      	   	from: '16:15',
      		to:   '16:30'
      	},
        'slot-7': {
      		from: '16:30',
      		to:   '17:15'
      	},
      	'slot-finally': {
      		from: '17:15',
      		to:   '18:00'
      	},
      },
      speakers: {

   	  },
   	  talks: {

   	  },
   	  breaks: {
   	  	'break-registration': {
   	  		title: 'Registration',
   	  		description_html: 'If you do not want to miss any presentation please register between 7:30-9:10. However, registration will be opened all day!'
   	  	},
   	  	'break-hello-world': {
   	  		title: 'Hello World',
   	  		description_html: 'This is couple of words about Mobilization. For community by community.'
   	  	},
   	  	'break-coffee': {
   	  	 	title: 'Coffee Break',
   	  		description_html: ''
   	  	},
   	  	'break-lunch': {
   	  		title: 'Lunch Break',
   	  		description_html: 'There is Solider soup - "Grochówka" for everyone! VIPs (Speakers, Sponsors) have lunch in Congresowa Restaurant on base floor.'
   	  	},
   	  	'break-finally': {
   	  		title: 'Finally',
   	  		description_html: ''
   	  	}
   	  },
   	  venues: {

   	  },
   	  schedule: {

   	  }
    },
    getPreparedTitle: function() {
      if (this.document.title) {
        return this.document.title + " | " + this.site.title;
      } else {
        return this.site.title;
      }
    },
    getPreparedDescription: function() {
      return this.document.description || this.site.description;
    },
    getPreparedKeywords: function() {
      return this.site.keywords.concat(this.document.keywords || []).join(', ');
    }
  },
  collections: {
    posts: function() {
      return this.getCollection('documents').findAllLive({
        relativeOutDirPath: 'posts'
      });
    }
  },
  environments: {
    development: {
      templateData: {
        site: {
          url: false
        }
      }
    }
  },
  events: {
    serverExtend: function(opts) {
      var docpad, latestConfig, newUrl, oldUrls, server;
      server = opts.server;
      docpad = this.docpad;
      latestConfig = docpad.getConfig();
      oldUrls = latestConfig.templateData.site.oldUrls || [];
      newUrl = latestConfig.templateData.site.url;
      return server.use(function(req, res, next) {
        var ref;
        if (ref = req.headers.host, indexOf.call(oldUrls, ref) >= 0) {
          return res.redirect(newUrl + req.url, 301);
        } else {
          return next();
        }
      });
    }
  }
};

module.exports = docpadConfig;

// ---
// generated by coffee-script 1.9.2
<|endoftext|>