<commit_before>const getPromptInfos = function (prompts, data) {
  let result;
  prompts.forEach(prompt => {
    if (result || !prompt.pattern || prompt.pattern.length === 0) {
      return;
    }
    const pattern = new RegExp(prompt.pattern, 'gm');
    const matches = pattern.exec(data);
    if (matches && matches.length > 0) {
      // Pattern has matched, now extract infos
      const {username, hostname, path} = prompt;
      result = {
        username: username ? matches[username] : undefined,
        hostname: hostname ? matches[hostname] : undefined,
        path: path ? matches[path] : undefined
      };
    }
  });
  return result;
};

const getProfile = function (profiles, infos) {
  let result;
  profiles.forEach(profile => {
    if (result || !profile.triggers || profile.triggers.length === 0) {
      return;
    }
    let match = false;
    profile.triggers.forEach(trigger => {
      if (match) {
        return;
      }
      const keys = Object.keys(trigger);
      for (let i = 0; i < keys.length; i += 1) {
        let key = keys[i];
        if (key === 'path') {
          if (infos[key].indexOf(trigger[key]) === -1) {
            return;
          }
        } else if (trigger[key] !== infos[key]) {
          return;
        }
      }
      match = true;
    });
    if (match) {
      result = profile;
    }
  });

  return result;
};

const newline = {};

exports.middleware = store => next => action => {
  if (action.type === 'SESSION_PTY_DATA') {
    let {data, uid} = action;
    data = data.replace(/[\n\r]?.*\033\[2J/mg,''); // Remove all char before ANSI sequence to erase line 'ESC[2J'
    data = data.replace(/.*\033\[[12]K/mg,''); // Remove all char before ANSI sequence to erase line 'ESC[2K'
    data = data.replace(/\033\[K.*/mg,''); //Remove all char after ANSI sequence to erase end on line
    data = data.replace(/\033\]0.*?\007/mg,''); // Remove ANSI sequence trick to set xterm title

    // Parse data only if it is a new line or if it contains a line beginning
    if (!newline[uid] &&
        data.indexOf('\n') === -1 &&
        data.indexOf('\r') === -1 &&
        data.indexOf('\033[?1034h') === -1 && // After a sudo
        data.indexOf('\033[K') === -1 && // ANSI sequence to erase a line
        data.indexOf('\033[2J') === -1) { // ANSI sequence to erase display
      return next(action);
    }

    // If there is a '\n' or '\r' at the end of line, next data is a newline
    const lastChar = data.charAt(data.length - 1);
    newline[uid] = (lastChar === '\n' ||
                    lastChar === '\r');

    const config = store.getState().ui.autoProfile ? store.getState().ui.autoProfile.config : {};
    if (!config || !config.prompts || config.prompts.length === 0) {
      console.warn('hyper-autoprofile enabled but no prompt config found');
      return next(action);
    }

    if (config.stripAnsiSequences !== false) {
      data = data.replace(/\033\[[0-9;]*m/mg,''); //Color ESC[0;1m
      data = data.replace(/\033[\(\)][AB0-2;]/mg,''); //Font ESC(B and ESC)B
    }
    const promptInfos = getPromptInfos(config.prompts, data);
    if (!promptInfos) {
      return next(action);
    }
    const profile = getProfile(config.profiles, promptInfos);
    store.dispatch({
      type: 'AUTOPROFILE_SET',
      uid,
      profile: profile ? profile.style : undefined
    });
  }
  next(action);
};

const parseTrigger = function (trigger) {
  const result = {};
  const idxAt = trigger.indexOf('@');
  const idxColon = trigger.indexOf(':');

  // username
  if (idxAt > 0) {
    result.username = trigger.substr(0, idxAt);
  }
  // hostname
  if (idxAt >= 0 && idxAt < trigger.length - 1) {
    result.hostname = trigger.substr(idxAt + 1, ((idxColon >= 0) ? idxColon : trigger.length) - idxAt - 1);
  }
  // path
  if (idxAt === -1 || (idxColon >= 0 && idxColon < trigger.length - 1)) {
    result.path = trigger.substr(idxColon + 1, trigger.length - idxColon - 1);
  }

  return result;
};

function formatConfiguration(autoProfileConfig) {
  const formattedConfig = {};

  if (!autoProfileConfig || !autoProfileConfig.prompts || !autoProfileConfig.profiles) {
    return formattedConfig;
  }
  formattedConfig.prompts = autoProfileConfig.prompts;
  const profiles = [];
  autoProfileConfig.profiles.forEach(profile => {
    const formattedProfile = {triggers:[], style:{}};
    if (!profile.triggers || profile.triggers.length === 0) {
      return;
    }
    profile.triggers.forEach(trigger => {
      const criteria = parseTrigger(trigger);
      if (!criteria || criteria.length === 0) {
        return;
      }
      formattedProfile.triggers.push(criteria);

    });
    formattedProfile.style = Object.assign({},profile);
    delete formattedProfile.style.triggers;
    profiles.push(formattedProfile);
  });
  formattedConfig.profiles = profiles;
  return formattedConfig;
}

exports.reduceUI = (state, action) => {
  switch (action.type) {
    case 'CONFIG_LOAD':
    case 'CONFIG_RELOAD': {
      const config = formatConfiguration(action.config.autoProfile);
      return state.set('autoProfile', {config: config, sessions: {}});
    }
    case 'AUTOPROFILE_SET': {
      return state.setIn(['autoProfile', 'sessions', action.uid], action.profile);
    }
    default:
      return state;
  }
};

exports.mapTermsState = (state, map) => {
  if (!state.ui.autoProfile || !state.ui.autoProfile.sessions) {
    return map;
  }
  return Object.assign({}, map, {profiles: state.ui.autoProfile.sessions});
};

exports.getTermGroupProps = (uid, parentProps, props) => {
  return Object.assign({}, props, {profiles: parentProps.profiles});
};

exports.getTermProps = (uid, parentProps, props) => {
  const {profiles} = parentProps;
  if (!profiles) {
    return props;
  }
  const profileProps = Object.assign({}, profiles[uid]);

  if (profileProps.backgroundColor) {
    // Weird trick because backgroundColor property is explicitly not forwarded to Term in Hyper.app
    profileProps.customCSS = `body { background-color: ${profileProps.backgroundColor}; }`;
  }
  return Object.assign({}, props, profileProps);
};
<commit_msg>Fix crash when a prompt config doesn't specify a path and a trigger use path part of a prompt<commit_after>const getPromptInfos = function (prompts, data) {
  let result;
  prompts.forEach(prompt => {
    if (result || !prompt.pattern || prompt.pattern.length === 0) {
      return;
    }
    const pattern = new RegExp(prompt.pattern, 'gm');
    const matches = pattern.exec(data);
    if (matches && matches.length > 0) {
      // Pattern has matched, now extract infos
      const {username, hostname, path} = prompt;
      result = {
        username: username ? matches[username] : undefined,
        hostname: hostname ? matches[hostname] : undefined,
        path: path ? matches[path] : undefined
      };
    }
  });
  return result;
};

const getProfile = function (profiles, infos) {
  let result;
  profiles.forEach(profile => {
    if (result || !profile.triggers || profile.triggers.length === 0) {
      return;
    }
    let match = false;
    profile.triggers.forEach(trigger => {
      if (match) {
        return;
      }
      const keys = Object.keys(trigger);
      for (let i = 0; i < keys.length; i += 1) {
        let key = keys[i];
        if (key === 'path' && infos[key]) {
          if (infos[key].indexOf(trigger[key]) === -1) {
            return;
          }
        } else if (trigger[key] !== infos[key]) {
          return;
        }
      }
      match = true;
    });
    if (match) {
      result = profile;
    }
  });

  return result;
};

const newline = {};

exports.middleware = store => next => action => {
  if (action.type === 'SESSION_PTY_DATA') {
    let {data, uid} = action;
    data = data.replace(/[\n\r]?.*\033\[2J/mg,''); // Remove all char before ANSI sequence to erase line 'ESC[2J'
    data = data.replace(/.*\033\[[12]K/mg,''); // Remove all char before ANSI sequence to erase line 'ESC[2K'
    data = data.replace(/\033\[K.*/mg,''); //Remove all char after ANSI sequence to erase end on line
    data = data.replace(/\033\]0.*?\007/mg,''); // Remove ANSI sequence trick to set xterm title

    // Parse data only if it is a new line or if it contains a line beginning
    if (!newline[uid] &&
        data.indexOf('\n') === -1 &&
        data.indexOf('\r') === -1 &&
        data.indexOf('\033[?1034h') === -1 && // After a sudo
        data.indexOf('\033[K') === -1 && // ANSI sequence to erase a line
        data.indexOf('\033[2J') === -1) { // ANSI sequence to erase display
      return next(action);
    }

    // If there is a '\n' or '\r' at the end of line, next data is a newline
    const lastChar = data.charAt(data.length - 1);
    newline[uid] = (lastChar === '\n' ||
                    lastChar === '\r');

    const config = store.getState().ui.autoProfile ? store.getState().ui.autoProfile.config : {};
    if (!config || !config.prompts || config.prompts.length === 0) {
      console.warn('hyper-autoprofile enabled but no prompt config found');
      return next(action);
    }

    if (config.stripAnsiSequences !== false) {
      data = data.replace(/\033\[[0-9;]*m/mg,''); //Color ESC[0;1m
      data = data.replace(/\033[\(\)][AB0-2;]/mg,''); //Font ESC(B and ESC)B
    }
    const promptInfos = getPromptInfos(config.prompts, data);
    if (!promptInfos) {
      return next(action);
    }
    const profile = getProfile(config.profiles, promptInfos);
    store.dispatch({
      type: 'AUTOPROFILE_SET',
      uid,
      profile: profile ? profile.style : undefined
    });
  }
  next(action);
};

const parseTrigger = function (trigger) {
  const result = {};
  const idxAt = trigger.indexOf('@');
  const idxColon = trigger.indexOf(':');

  // username
  if (idxAt > 0) {
    result.username = trigger.substr(0, idxAt);
  }
  // hostname
  if (idxAt >= 0 && idxAt < trigger.length - 1) {
    result.hostname = trigger.substr(idxAt + 1, ((idxColon >= 0) ? idxColon : trigger.length) - idxAt - 1);
  }
  // path
  if (idxAt === -1 || (idxColon >= 0 && idxColon < trigger.length - 1)) {
    result.path = trigger.substr(idxColon + 1, trigger.length - idxColon - 1);
  }

  return result;
};

function formatConfiguration(autoProfileConfig) {
  const formattedConfig = {};

  if (!autoProfileConfig || !autoProfileConfig.prompts || !autoProfileConfig.profiles) {
    return formattedConfig;
  }
  formattedConfig.prompts = autoProfileConfig.prompts;
  const profiles = [];
  autoProfileConfig.profiles.forEach(profile => {
    const formattedProfile = {triggers:[], style:{}};
    if (!profile.triggers || profile.triggers.length === 0) {
      return;
    }
    profile.triggers.forEach(trigger => {
      const criteria = parseTrigger(trigger);
      if (!criteria || criteria.length === 0) {
        return;
      }
      formattedProfile.triggers.push(criteria);

    });
    formattedProfile.style = Object.assign({},profile);
    delete formattedProfile.style.triggers;
    profiles.push(formattedProfile);
  });
  formattedConfig.profiles = profiles;
  return formattedConfig;
}

exports.reduceUI = (state, action) => {
  switch (action.type) {
    case 'CONFIG_LOAD':
    case 'CONFIG_RELOAD': {
      const config = formatConfiguration(action.config.autoProfile);
      return state.set('autoProfile', {config: config, sessions: {}});
    }
    case 'AUTOPROFILE_SET': {
      return state.setIn(['autoProfile', 'sessions', action.uid], action.profile);
    }
    default:
      return state;
  }
};

exports.mapTermsState = (state, map) => {
  if (!state.ui.autoProfile || !state.ui.autoProfile.sessions) {
    return map;
  }
  return Object.assign({}, map, {profiles: state.ui.autoProfile.sessions});
};

exports.getTermGroupProps = (uid, parentProps, props) => {
  return Object.assign({}, props, {profiles: parentProps.profiles});
};

exports.getTermProps = (uid, parentProps, props) => {
  const {profiles} = parentProps;
  if (!profiles) {
    return props;
  }
  const profileProps = Object.assign({}, profiles[uid]);

  if (profileProps.backgroundColor) {
    // Weird trick because backgroundColor property is explicitly not forwarded to Term in Hyper.app
    profileProps.customCSS = `body { background-color: ${profileProps.backgroundColor}; }`;
  }
  return Object.assign({}, props, profileProps);
};
<|endoftext|>


<commit_before>
const path       = require('path');
const express    = require('express');
const mongoose   = require('mongoose');
const helmet     = require('helmet');
const bodyParser = require('body-parser');
const morgan     = require('morgan');
const bluebird   = require('bluebird');
const config = require('./config');
const routes = require('./routes');
const cors = require('cors');
const enforce = require('express-sslify');
const corsOptions =
{ origin: JSON.parse(process.env.AllowUrl).urls,
  credentials: true,
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
const app  = express();

/* istanbul ignore if */
if (process.env.NODE_ENV === 'production') {
  app.use(enforce.HTTPS({ trustProtoHeader: true }));
}

app.use(express.static(path.normalize(path.join(__dirname, 'frontend/dist'))));

// Handle rejected promises globally
app.use((req, res, next) => {
  process.on('unhandledRejection', (reason, promise) => {
    /* istanbul ignore next */
    next(new Error(reason));
  });
  next();
});

app.use(cors(corsOptions));
mongoose.Promise = bluebird;
mongoose.connect(process.env.MONGO_DB_URI);
app.use(helmet());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('tiny'));
routes(app);

app.get('*', (request, response) => {
  response.sendFile(path.normalize(path.join(__dirname, 'frontend/dist/index.html')));
});

app.listen(config.server.port, () => {
  console.log(`Magic happens on port ${config.server.port}`);
});

module.exports = app;
<commit_msg>fixed mongoose warning<commit_after>
const path       = require('path');
const express    = require('express');
const mongoose   = require('mongoose');
const helmet     = require('helmet');
const bodyParser = require('body-parser');
const morgan     = require('morgan');
const bluebird   = require('bluebird');
const config = require('./config');
const routes = require('./routes');
const cors = require('cors');
const enforce = require('express-sslify');
const corsOptions =
{ origin: JSON.parse(process.env.AllowUrl).urls,
  credentials: true,
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
const app  = express();

/* istanbul ignore if */
if (process.env.NODE_ENV === 'production') {
  app.use(enforce.HTTPS({ trustProtoHeader: true }));
}

app.use(express.static(path.normalize(path.join(__dirname, 'frontend/dist'))));

// Handle rejected promises globally
app.use((req, res, next) => {
  process.on('unhandledRejection', (reason, promise) => {
    /* istanbul ignore next */
    next(new Error(reason));
  });
  next();
});

app.use(cors(corsOptions));
mongoose.Promise = bluebird;
// mongoose.connect(process.env.MONGO_DB_URI);
mongoose.connect(process.env.MONGO_DB_URI, {
  useMongoClient: true
  /* other options */
});
app.use(helmet());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('tiny'));
routes(app);

app.get('*', (request, response) => {
  response.sendFile(path.normalize(path.join(__dirname, 'frontend/dist/index.html')));
});

app.listen(config.server.port, () => {
  console.log(`Magic happens on port ${config.server.port}`);
});

module.exports = app;
<|endoftext|>


<commit_before>var postcss = require('postcss');
var config = {
    suit: {
        separators: {
            namespace: '-',
            descendent: '-',
            modifier: '--',
            state: '.is-'
        }
    },
    bem: {
        separators: {
            namespace: '--',
            descendent: '__',
            modifier: '_'
        }
    }
};

module.exports = postcss.plugin('postcss-bem', function (opts) {
    opts = opts || {};

    if (!opts.style) {
        opts.style = 'suit';
    }

    if (opts.style !== 'suit' && opts.style !== 'bem') {
        throw new Error('postcss-bem: opts.style may only be "suit" or "bem"');
    }

    var currentConfig = config[opts.style];

    function processComponent (component, namespace) {
        var name = component.params;

        if (namespace) {
            name = namespace + currentConfig.separators.namespace + name;
        }

        var last = component;
        var newComponent = postcss.rule({
            selector: '.' + name,
            source: component.source
        });
        component.each(function (rule) {
            var separator;
            var newRule;

            if (rule.type === 'atrule') {
                if (rule.name === 'modifier') {
                    separator = currentConfig.separators.modifier;
                } else if (rule.name === 'descendent') {
                    separator = currentConfig.separators.descendent;
                }

                if(separator) {
                    newRule = postcss.rule({
                        selector: '.' + name + separator + rule.params,
                        source: rule.source
                    });
                    rule.each(function (node) {
                        node.moveTo(newRule);
                    });
                    component.parent.insertAfter(last, newRule);
                    last = newRule;
                    rule.removeSelf();
                }
            }
            if (!separator) {
                rule.moveTo(newComponent);
            }
        });

        component.replaceWith(newComponent);
    }

    return function (css, result) {
        var namespaces = {};

        if (opts.style === 'suit') {
            css.eachAtRule('utility', function (utility) {
                if (!utility.params) {
                    throw utility.error('No names supplied to @utility');
                }

                var utilityNames = postcss.list.comma(utility.params);

                var selector = utilityNames.map(function (params) {
                    params = postcss.list.space(params);
                    var variant;
                    var name;

                    if (params.length > 2) {
                        result.warn('Too many parameters for @utility', {
                            node: utility
                        });
                    }

                    name = 'u-';
                    if (params.length > 1) {
                        variant = params[1];

                        if (variant === 'small') {
                            name += 'sm';
                        } else if (variant === 'medium') {
                            name += 'md';
                        } else if (variant === 'large') {
                            name += 'lg';
                        } else {
                            result.warn('Unknown variant: ' + variant, {
                                node: utility
                            });
                        }
                        name += '-';
                    }
                    name += params[0];
                    return '.' + name;
                }).join(', ');

                var newUtility = postcss.rule({
                    selector: selector,
                    source: utility.source
                });

                utility.each(function (node) {
                    node.moveTo(newUtility);
                });
                utility.replaceWith(newUtility);
            });
        }

        css.eachAtRule('component-namespace', function (namespace) {
            var name = namespace.params;

            if (!namespace.nodes) {
                namespaces[namespace.source.input.file || namespace.source.input.id] = name;
                namespace.removeSelf();
                return;
            }

            namespace.eachAtRule('component', function (component) {
                processComponent(component, name);
            });

            var node = namespace.last;
            while (node) {
                node.moveAfter(namespace);
                node = namespace.last;
            }
            namespace.removeSelf();
        });

        css.eachAtRule('component', function (component) {
            var namespace = opts.defaultNamespace;
            var id = component.source.input.file || component.source.input.id;
            if (id in namespaces) {
                namespace = namespaces[id];
            }

            processComponent(component, namespace);
        });

        if (opts.style === 'suit') {
            css.eachAtRule('when', function (when) {
                var parent = when.parent;

                if (parent === css || parent.type !== 'rule') {
                    throw when.error('@when can only be used in rules which are not the root node');
                }

                var states = when.params;
                var newSelector = postcss.list.comma(parent.selector).map(function (selector) {
                    return postcss.list.comma(states).map(function (state) {
                        return selector + currentConfig.separators.state + state;
                    }).join(', ');
                }).join(', ');

                var newWhen = postcss.rule({
                    selector: newSelector,
                    source: when.source
                });

                when.each(function (node) {
                    node.moveTo(newWhen);
                });
                newWhen.moveAfter(parent);
                when.removeSelf();
            });
        }
    };
});
<commit_msg>allow separator overrides<commit_after>var postcss = require('postcss');
var config = {
    suit: {
        separators: {
            namespace: '-',
            descendent: '-',
            modifier: '--',
            state: '.is-'
        }
    },
    bem: {
        separators: {
            namespace: '--',
            descendent: '__',
            modifier: '_'
        }
    }
};

module.exports = postcss.plugin('postcss-bem', function (opts) {
    opts = opts || {};

    if (!opts.style) {
        opts.style = 'suit';
    }

    if (opts.style !== 'suit' && opts.style !== 'bem') {
        throw new Error('postcss-bem: opts.style may only be "suit" or "bem"');
    }

    var currentConfig = config[opts.style];

    if (opts.separators) {
        for (var separator in opts.separators) {
            if (!opts.separators.hasOwnProperty(separator)) continue;

            var separatorValue = opts.separators[separator];
            if (typeof separatorValue === 'string') {
                currentConfig.separators[separator] = separatorValue;
            } else {
                throw new Error('postcss-bem: opts.separators.' + separator + ' must be a string');
            }
        }
    }

    function processComponent (component, namespace) {
        var name = component.params;

        if (namespace) {
            name = namespace + currentConfig.separators.namespace + name;
        }

        var last = component;
        var newComponent = postcss.rule({
            selector: '.' + name,
            source: component.source
        });
        component.each(function (rule) {
            var separator;
            var newRule;

            if (rule.type === 'atrule') {
                if (rule.name === 'modifier') {
                    separator = currentConfig.separators.modifier;
                } else if (rule.name === 'descendent') {
                    separator = currentConfig.separators.descendent;
                }

                if(separator) {
                    newRule = postcss.rule({
                        selector: '.' + name + separator + rule.params,
                        source: rule.source
                    });
                    rule.each(function (node) {
                        node.moveTo(newRule);
                    });
                    component.parent.insertAfter(last, newRule);
                    last = newRule;
                    rule.removeSelf();
                }
            }
            if (!separator) {
                rule.moveTo(newComponent);
            }
        });

        component.replaceWith(newComponent);
    }

    return function (css, result) {
        var namespaces = {};

        if (opts.style === 'suit') {
            css.eachAtRule('utility', function (utility) {
                if (!utility.params) {
                    throw utility.error('No names supplied to @utility');
                }

                var utilityNames = postcss.list.comma(utility.params);

                var selector = utilityNames.map(function (params) {
                    params = postcss.list.space(params);
                    var variant;
                    var name;

                    if (params.length > 2) {
                        result.warn('Too many parameters for @utility', {
                            node: utility
                        });
                    }

                    name = 'u-';
                    if (params.length > 1) {
                        variant = params[1];

                        if (variant === 'small') {
                            name += 'sm';
                        } else if (variant === 'medium') {
                            name += 'md';
                        } else if (variant === 'large') {
                            name += 'lg';
                        } else {
                            result.warn('Unknown variant: ' + variant, {
                                node: utility
                            });
                        }
                        name += '-';
                    }
                    name += params[0];
                    return '.' + name;
                }).join(', ');

                var newUtility = postcss.rule({
                    selector: selector,
                    source: utility.source
                });

                utility.each(function (node) {
                    node.moveTo(newUtility);
                });
                utility.replaceWith(newUtility);
            });
        }

        css.eachAtRule('component-namespace', function (namespace) {
            var name = namespace.params;

            if (!namespace.nodes) {
                namespaces[namespace.source.input.file || namespace.source.input.id] = name;
                namespace.removeSelf();
                return;
            }

            namespace.eachAtRule('component', function (component) {
                processComponent(component, name);
            });

            var node = namespace.last;
            while (node) {
                node.moveAfter(namespace);
                node = namespace.last;
            }
            namespace.removeSelf();
        });

        css.eachAtRule('component', function (component) {
            var namespace = opts.defaultNamespace;
            var id = component.source.input.file || component.source.input.id;
            if (id in namespaces) {
                namespace = namespaces[id];
            }

            processComponent(component, namespace);
        });

        if (opts.style === 'suit') {
            css.eachAtRule('when', function (when) {
                var parent = when.parent;

                if (parent === css || parent.type !== 'rule') {
                    throw when.error('@when can only be used in rules which are not the root node');
                }

                var states = when.params;
                var newSelector = postcss.list.comma(parent.selector).map(function (selector) {
                    return postcss.list.comma(states).map(function (state) {
                        return selector + currentConfig.separators.state + state;
                    }).join(', ');
                }).join(', ');

                var newWhen = postcss.rule({
                    selector: newSelector,
                    source: when.source
                });

                when.each(function (node) {
                    node.moveTo(newWhen);
                });
                newWhen.moveAfter(parent);
                when.removeSelf();
            });
        }
    };
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var Time = require('time-diff');
var debug = require('debug')('base:runner');
var Liftoff = require('liftoff');
var utils = require('./utils');

/**
 * Create a `runner` with the given `constructor`, [liftoff][] `config` object,
 * `argv` object and `callback` function.
 *
 * ```js
 * var Base = require('base');
 * var argv = require('minimist')(process.argv.slice(2));
 * var config = {
 *   name: 'foo',
 *   cwd: process.cwd(),
 *   extensions: {'.js': null}
 * };
 *
 * runner(Base, config, argv, function(err, app, runnerContext) {
 *   if (err) throw err;
 *   // do stuff with `app` and `runnerContext`
 *   process.exit();
 * });
 * ```
 * @param {Function} `Ctor` Constructor to use, must inherit [base][].
 * @param {Object} `config` The config object to pass to [liftoff][].
 * @param {Object} `argv` Argv object, optionally pre-parsed.
 * @param {Function} `cb` Callback function, which exposes `err`, `app` (base application instance) and `runnerContext`
 * @return {Object}
 * @api public
 */

function runner(Ctor, config, argv, cb) {
  debug('initializing <%s>, called from <%s>', __filename, module.parent.id);

  /**
   * handle runner arguments errors
   */

  var err = validateRunnerArgs(Ctor, config, argv, cb);
  if (err) {
    cb(err);
    return;
  }

  /**
   * Start timings
   */

  var time = new Time(argv);
  var diff = time.diff('init', argv);
  diff('modules loaded');

  /**
   * Shallow clone options
   */

  argv = utils.merge({_: []}, argv);
  config = utils.merge({cwd: process.cwd(), extensions: {'.js': null}}, config);
  config.processTitle = config.processTitle || config.name;
  config.moduleName = config.moduleName || config.name;
  config.configName = config.configName || config.name + 'file';

  /**
   * Set cwd (if not defined)
   *
   *   $ verb --cwd="lib"
   *
   */

  if (typeof argv.cwd === 'undefined') {
    argv.cwd = config.cwd;
  }

  /**
   * Custom config file
   *
   *   $ verb --verbfile="docs/foo.js"
   *
   */

  var customFile = argv[config.configName];
  if (customFile) {
    argv.configPath = path.resolve(config.cwd, customFile);
  }

  /**
   * Initialize liftoff
   */

  var CLI = new Liftoff(config);
  utils.timestamp('initializing ' + config.name);
  diff('config loaded');

  /**
   * Load environment
   */

  CLI.launch(argv, function(env) {
    debug('launching CLI');
    diff('environment loaded');

    env.name = config.name;
    env.configName = config.configName;
    env.configFile = env.configName + '.js';

    /**
     * Create `runnerContext`
     */

    var ctx = new RunnerContext(argv, config, env);
    diff('runnerContext initialized');

    /**
     * Get the `Base` constructor to use
     */

    try {
      var Base = env.modulePath ? require(env.modulePath) : Ctor;
      ctx.Base = Base;

      var emit = emitRunnerEvents(Base);
      emit('preInit', ctx);

      /**
       * Create our `base` instance
       */

      var base = new Base(argv);
      base.cwd = env.cwd;
      handleTaskErrors(base, env);

      emit('init', base, ctx);
      diff('application initialized');

      /**
       * Load plugins onto the `base` instance
       */

      base.use(utils.project());
      base.use(utils.runtimes());
      base.use(utils.config());
      base.use(utils.cli(argv));
      diff('plugins loaded');

      /**
       * Set `runnerContext`
       */

      base.set('cache.runnerContext', ctx);

      /**
       * Resolve configfile in the user's cwd (`assemblefile.js`, etc)
       */

      runner.resolveConfig(base, config, env);
      diff('initialized ' + config.name);
      emit('postInit', base, ctx);

      /**
       * Emit `finished`, callback
       */

      process.nextTick(function() {
        emit('finished', base, ctx);
        diff('finished');
        cb(null, base, ctx);
      });
    } catch (err) {
      cb(err);
    }
  });
}

/**
 * Resolve the config file to use
 */

runner.resolveConfig = function(app, config, env) {
  var filepath = path.resolve(config.cwd, env.configName);
  if (env.configPath && ~env.configPath.indexOf(filepath)) {
    utils.configPath('using ' + env.configName, env.configPath);
    app.generator('default', env.configPath);
  }
};

/**
 * Create runner context
 */

function RunnerContext(argv, config, env) {
  argv.tasks = argv._.length ? argv._ : ['default'];
  this.argv = argv;
  this.config = config;
  this.env = env;
}

/**
 * Handle task errors
 * TODO: should this be moved to implementations?
 * (e.g. "verb/lib/commands/tasks.js")
 */

function handleTaskErrors(app, env) {
  app.on('error', function(err) {
    if (err.message === 'no default task defined') {
      var fp = path.relative(app.cwd, env.configPath);
      console.warn('No tasks or generators defined in ' + fp + ', stopping.');
      process.exit();
    }
    console.error(err.stack);
    process.exit(1);
  });
}

/**
 * Handle invalid arguments
 */

function validateRunnerArgs(Ctor, config, argv, cb) {
  if (typeof cb !== 'function') {
    throw new Error('expected a callback function');
  }
  if (argv == null || typeof argv !== 'object') {
    return new Error('expected the third argument to be an options object');
  }

  if (config == null || typeof config !== 'object') {
    return new Error('expected the second argument to be a liftoff config object');
  }

  if (typeof Ctor !== 'function' || typeof Ctor.namespace !== 'function') {
    return new Error('expected the first argument to be a Base constructor');
  }
}

/**
 * Emit `runner`
 */

function emitRunnerEvents(Base) {
  return function(name) {
    var args = [].slice.call(arguments, 1);
    args.unshift();
    Base.emit.bind(Base, 'runner:' + name).apply(Base, args);
    Base.emit.bind(Base, 'runner').apply(Base, arguments);
  };
}

/**
 * Expose `runner`
 */

module.exports = runner;
<commit_msg>temporarily log out err.stack<commit_after>'use strict';

var path = require('path');
var Time = require('time-diff');
var debug = require('debug')('base:runner');
var Liftoff = require('liftoff');
var utils = require('./utils');

/**
 * Create a `runner` with the given `constructor`, [liftoff][] `config` object,
 * `argv` object and `callback` function.
 *
 * ```js
 * var Base = require('base');
 * var argv = require('minimist')(process.argv.slice(2));
 * var config = {
 *   name: 'foo',
 *   cwd: process.cwd(),
 *   extensions: {'.js': null}
 * };
 *
 * runner(Base, config, argv, function(err, app, runnerContext) {
 *   if (err) throw err;
 *   // do stuff with `app` and `runnerContext`
 *   process.exit();
 * });
 * ```
 * @param {Function} `Ctor` Constructor to use, must inherit [base][].
 * @param {Object} `config` The config object to pass to [liftoff][].
 * @param {Object} `argv` Argv object, optionally pre-parsed.
 * @param {Function} `cb` Callback function, which exposes `err`, `app` (base application instance) and `runnerContext`
 * @return {Object}
 * @api public
 */

function runner(Ctor, config, argv, cb) {
  debug('initializing <%s>, called from <%s>', __filename, module.parent.id);

  /**
   * handle runner arguments errors
   */

  var err = validateRunnerArgs(Ctor, config, argv, cb);
  if (err) {
    cb(err);
    return;
  }

  /**
   * Start timings
   */

  var time = new Time(argv);
  var diff = time.diff('init', argv);
  diff('modules loaded');

  /**
   * Shallow clone options
   */

  argv = utils.merge({_: []}, argv);
  config = utils.merge({cwd: process.cwd(), extensions: {'.js': null}}, config);
  config.processTitle = config.processTitle || config.name;
  config.moduleName = config.moduleName || config.name;
  config.configName = config.configName || config.name + 'file';

  /**
   * Set cwd (if not defined)
   *
   *   $ verb --cwd="lib"
   *
   */

  if (typeof argv.cwd === 'undefined') {
    argv.cwd = config.cwd;
  }

  /**
   * Custom config file
   *
   *   $ verb --verbfile="docs/foo.js"
   *
   */

  var customFile = argv[config.configName];
  if (customFile) {
    argv.configPath = path.resolve(config.cwd, customFile);
  }

  /**
   * Initialize liftoff
   */

  var CLI = new Liftoff(config);
  utils.timestamp('initializing ' + config.name);
  diff('config loaded');

  /**
   * Load environment
   */

  CLI.launch(argv, function(env) {
    debug('launching CLI');
    diff('environment loaded');

    env.name = config.name;
    env.configName = config.configName;
    env.configFile = env.configName + '.js';

    /**
     * Create `runnerContext`
     */

    var ctx = new RunnerContext(argv, config, env);
    diff('runnerContext initialized');

    /**
     * Get the `Base` constructor to use
     */

    try {
      var Base = env.modulePath ? require(env.modulePath) : Ctor;
      ctx.Base = Base;

      var emit = emitRunnerEvents(Base);
      emit('preInit', ctx);

      /**
       * Create our `base` instance
       */

      var base = new Base(argv);
      base.cwd = env.cwd;
      handleTaskErrors(base, env);

      emit('init', base, ctx);
      diff('application initialized');

      /**
       * Load plugins onto the `base` instance
       */

      base.use(utils.project());
      base.use(utils.runtimes());
      base.use(utils.config());
      base.use(utils.cli(argv));
      diff('plugins loaded');

      /**
       * Set `runnerContext`
       */

      base.set('cache.runnerContext', ctx);

      /**
       * Resolve configfile in the user's cwd (`assemblefile.js`, etc)
       */

      runner.resolveConfig(base, config, env);
      diff('initialized ' + config.name);
      emit('postInit', base, ctx);

      /**
       * Emit `finished`, callback
       */

      process.nextTick(function() {
        emit('finished', base, ctx);
        diff('finished');
        cb(null, base, ctx);
      });
    } catch (err) {
      console.log(err.stack);
      cb(err);
    }
  });
}

/**
 * Resolve the config file to use
 */

runner.resolveConfig = function(app, config, env) {
  var filepath = path.resolve(config.cwd, env.configName);
  if (env.configPath && ~env.configPath.indexOf(filepath)) {
    utils.configPath('using ' + env.configName, env.configPath);
    app.generator('default', env.configPath);
  }
};

/**
 * Create runner context
 */

function RunnerContext(argv, config, env) {
  argv.tasks = argv._.length ? argv._ : ['default'];
  this.argv = argv;
  this.config = config;
  this.env = env;
}

/**
 * Handle task errors
 * TODO: should this be moved to implementations?
 * (e.g. "verb/lib/commands/tasks.js")
 */

function handleTaskErrors(app, env) {
  app.on('error', function(err) {
    if (err.message === 'no default task defined') {
      var fp = path.relative(app.cwd, env.configPath);
      console.warn('No tasks or generators defined in ' + fp + ', stopping.');
      process.exit();
    }
    console.error(err.stack);
    process.exit(1);
  });
}

/**
 * Handle invalid arguments
 */

function validateRunnerArgs(Ctor, config, argv, cb) {
  if (typeof cb !== 'function') {
    throw new Error('expected a callback function');
  }
  if (argv == null || typeof argv !== 'object') {
    return new Error('expected the third argument to be an options object');
  }

  if (config == null || typeof config !== 'object') {
    return new Error('expected the second argument to be a liftoff config object');
  }

  if (typeof Ctor !== 'function' || typeof Ctor.namespace !== 'function') {
    return new Error('expected the first argument to be a Base constructor');
  }
}

/**
 * Emit `runner`
 */

function emitRunnerEvents(Base) {
  return function(name) {
    var args = [].slice.call(arguments, 1);
    args.unshift();
    Base.emit.bind(Base, 'runner:' + name).apply(Base, args);
    Base.emit.bind(Base, 'runner').apply(Base, arguments);
  };
}

/**
 * Expose `runner`
 */

module.exports = runner;
<|endoftext|>


<commit_before>var traj = require('voxel-trajectory');
var tic = require('tic')();

function Sky(opts) {
  var self = this;
  if (opts.THREE) opts = {game:opts};
  this.game   = opts.game;
  this.time   = opts.time  || 0;
  this.size   = opts.size  || this.game.worldWidth() * 3;
  this._color = opts.color || new this.game.THREE.Color(0, 0, 0);
  this._speed = opts.speed || 0.1;
}

module.exports = function(opts) {
  var sky = new Sky(opts || {});
  sky.createBox();
  sky.createLights();
  return function(fn) {
    if (typeof fn === 'function') sky.fn = fn;
    else if (typeof fn === 'number') {
      // move to the specific time of day
      sky.time = fn;
      for (var i = 0; i <= 2400; i += sky._speed) sky.tick.call(sky);
    }
    return sky.tick.bind(sky);
  }
};
module.exports.Sky = Sky;

Sky.prototype.tick = function(dt) {
  tic.tick(dt);
  this.fn.call(this, this.time);
  var pos = this.game.cameraPosition();
  var vec = new this.game.THREE.Vector3(pos[0], pos[1], pos[2]);
  this.outer.position.copy(vec);
  this.inner.position.copy(vec);
  this.ambient.position.copy(vec);
  this.time += this._speed;
  if (this.time > 2400) this.time = 0;
  return this;
};

Sky.prototype.createBox = function() {
  var game = this.game;
  var size = this.size;

  var mat = new game.THREE.MeshBasicMaterial({
    side: game.THREE.BackSide,
    fog: false,
  });
  this.outer = new game.THREE.Mesh(
    new game.THREE.CubeGeometry(size, size, size),
    new game.THREE.MeshFaceMaterial([
      mat, mat, mat, mat, mat, mat
    ])
  );
  game.scene.add(this.outer);

  var materials = [];
  for (var i = 0; i < 6; i++) {
    materials.push(this.createCanvas());
  }
  this.inner = new game.THREE.Mesh(
    new game.THREE.CubeGeometry(size-10, size-10, size-10),
    new game.THREE.MeshFaceMaterial(materials)
  );
  game.scene.add(this.inner);
};

Sky.prototype.createLights = function() {
  var game = this.game;
  this.ambient = new game.THREE.HemisphereLight(0x408CFF, 0xFFC880, 0.6);
  game.scene.add(this.ambient);
  this.sunlight = new game.THREE.DirectionalLight(0xffffff, 0.5);
  game.scene.add(this.sunlight);
};

Sky.prototype.color = function(end, time) {
  var self = this;
  if (self._colorInterval) self._colorInterval();
  var i = 0;
  var start = self._color.clone().getHSL();
  var color = self._color.clone().getHSL();
  self._colorInterval = tic.interval(function() {
    var dt = i / time;
    for (var p in color) color[p] = start[p] + (end[p] - start[p]) * dt;
    self._color.setHSL(color.h, color.s, color.l);
    self.outer.material.materials.forEach(function(mat) {
      mat.color.setHSL(color.h, color.s, color.l);
    });
    self.ambient.color.setHSL(color.h, color.s, color.l);
    if (self.game.scene.fog) self.game.scene.fog.color.setHSL(color.h, color.s, color.l);
    if (dt === 1) self._colorInterval();
    i += self._speed;
  }, self._speed);
};

Sky.prototype.speed = function(speed) {
  if (speed != null) this._speed = speed;
  return this._speed;
};

Sky.prototype.paint = function(faces, fn) {
  var self = this;
  var args = Array.prototype.slice.call(arguments, 2);
  var index = ['back', 'front', 'top', 'bottom', 'left', 'right'];
  if (faces === 'all') faces = index;
  if (faces === 'sides') faces = ['back', 'front', 'left', 'right'];
  if (!isArray(faces)) faces = [faces];
  faces.forEach(function(face) {
    if (typeof face === 'string') {
      face = index.indexOf(String(face).toLowerCase());
      if (face === -1) return;
    }
    self.material = self.inner.material.materials[face];
    self.canvas = self.material.map.image;
    self.context = self.canvas.getContext('2d');
    fn.apply(self, args);
    self.inner.material.materials[face].map.needsUpdate = true;
  });
  self.material = self.canvas = self.context = false;
};

Sky.prototype.sun   = require('./lib/sun.js');
Sky.prototype.moon  = require('./lib/moon.js');
Sky.prototype.stars = require('./lib/stars.js');

Sky.prototype.createCanvas = function() {
  var game = this.game;

  var canvas = document.createElement('canvas');
  canvas.height = canvas.width = 512;
  var context = canvas.getContext('2d');

  var material = new game.THREE.MeshBasicMaterial({
    side: game.THREE.BackSide,
    map: new game.THREE.Texture(canvas),
    transparent: true,
    fog: false,
  });
  material.magFilter = game.THREE.NearestFilter;
  material.minFilter = game.THREE.LinearMipMapLinearFilter;
  material.wrapS = material.wrapT = game.THREE.RepeatWrapping;
  material.map.needsUpdate = true;

  return material;
};

Sky.prototype.spin = function(r) {
  this.inner.rotation.x = this.outer.rotation.x = r;
  this.ambient.rotation.x = r + Math.PI;
  var t = traj(this.size/2, this.ambient.rotation);
  this.sunlight.position.set(t[0], t[1], t[2]);
  this.sunlight.lookAt(0, 0, 0);
};

Sky.prototype.clear = function() {
  if (!this.canvas) return false;
  this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
};

// default sky
Sky.prototype._default = {
  hours: {
       0: {color: {h: 230/360, s: 0.3, l: 0}},
     300: {color: {h: 26/360, s: 0.3, l: 0.5}},
     500: {color: {h: 230/360, s: 0.3, l: 0.7}},
    1400: {color: {h: 26/360, s: 0.3, l: 0.5}},
    1600: {color: {h: 230/360, s: 0.3, l: 0}}
  },
  init: function() {
    // add a sun on the bottom
    this.paint('bottom', this.sun);
    // add some stars
    this.paint(['top', 'left', 'right', 'front', 'back'], this.stars, 500);
    // add full moon to the top
    this.paint('top', this.moon, 0);
    // no sunlight at startup
    this.sunlight.intensity = 0;
  },
  day: 0,
  moonCycle: 29.5305882,
  until: false,
  last: 0
};

// default sky fn
Sky.prototype.fn = function(time) {
  var my = this._default;
  var hour = Math.round(time / 100) * 100;
  var speed = Math.abs(my.last - time);
  my.last = time;

  // run initialization once
  if (my.init) { my.init.call(this); delete my.init; }

  // switch color based on time of day
  // maybe make this next part into a helper function
  if (my.hours[hour]) {
    if (!my.until) {
      this.color(my.hours[hour].color, speed > 9 ? 100 : 1000);
      my.until = hour + 100;
    }
  }
  if (my.until === hour) my.until = false;

  // change moon phase
  if (time === 1200) {
    this.paint('top', this.clear);
    this.paint('top', this.moon, Math.floor(my.day % my.moonCycle) / my.moonCycle);
    this.paint('top', this.stars, 500);
  }

  // fade stars in and out
  if (time === 500) {
    this.paint(['top', 'left', 'right', 'front', 'back'], function() {
      this.material.transparent = true;
      var i = tic.interval(function(mat) {
        mat.opacity -= 0.1;
        if (mat.opacity <= 0) i();
      }, 100, this.material);
    });
  }
  if (time === 1800) {
    this.paint(['top', 'left', 'right', 'front', 'back'], function() {
      this.material.transparent = true;
      var i = tic.interval(function(mat) {
        mat.opacity += 0.1;
        if (mat.opacity >= 1) i();
      }, 100, this.material);
    });
  }

  // turn on sunlight
  if (time === 400) {
    (function(sunlight) {
      var i = tic.interval(function() {
        sunlight.intensity += 0.1;
        if (sunlight.intensity <= 1) i();
      }, 100);
    }(this.sunlight));
  }

  // turn off sunlight
  if (time === 1800) {
    (function(sunlight) {
      var i = tic.interval(function() {
        sunlight.intensity -= 0.1;
        if (sunlight.intensity <= 0) i();
      }, 100);
    }(this.sunlight));
  }

  // spin the sky 1 revolution per day
  this.spin(Math.PI * 2 * (time / 2400));

  // keep track of days
  if (time === 2400) my.day++;
};

Sky.prototype.rgba = function(c, o) {
  if (arguments.length === 4) {
    c = {r: arguments[0], g: arguments[1], b: arguments[2]};
    o = arguments[3];
  }
  return 'rgba(' + (c.r*255) + ', ' + (c.g*255) + ', ' + (c.b*255) + ', ' + o + ')';
};

function isArray(ar) {
  return Array.isArray(ar)
    || (typeof ar === 'object' && Object.prototype.toString.call(ar) === '[object Array]');
}
<commit_msg>spin accepts axis as a param and defaults to z<commit_after>var traj = require('voxel-trajectory');
var tic = require('tic')();

function Sky(opts) {
  var self = this;
  if (opts.THREE) opts = {game:opts};
  this.game   = opts.game;
  this.time   = opts.time  || 0;
  this.size   = opts.size  || this.game.worldWidth() * 3;
  this._color = opts.color || new this.game.THREE.Color(0, 0, 0);
  this._speed = opts.speed || 0.1;
}

module.exports = function(opts) {
  var sky = new Sky(opts || {});
  sky.createBox();
  sky.createLights();
  return function(fn) {
    if (typeof fn === 'function') sky.fn = fn;
    else if (typeof fn === 'number') {
      // move to the specific time of day
      sky.time = fn;
      for (var i = 0; i <= 2400; i += sky._speed) sky.tick.call(sky);
    }
    return sky.tick.bind(sky);
  }
};
module.exports.Sky = Sky;

Sky.prototype.tick = function(dt) {
  tic.tick(dt);
  this.fn.call(this, this.time);
  var pos = this.game.cameraPosition();
  var vec = new this.game.THREE.Vector3(pos[0], pos[1], pos[2]);
  this.outer.position.copy(vec);
  this.inner.position.copy(vec);
  this.ambient.position.copy(vec);
  this.time += this._speed;
  if (this.time > 2400) this.time = 0;
  return this;
};

Sky.prototype.createBox = function() {
  var game = this.game;
  var size = this.size;

  var mat = new game.THREE.MeshBasicMaterial({
    side: game.THREE.BackSide,
    fog: false,
  });
  this.outer = new game.THREE.Mesh(
    new game.THREE.CubeGeometry(size, size, size),
    new game.THREE.MeshFaceMaterial([
      mat, mat, mat, mat, mat, mat
    ])
  );
  game.scene.add(this.outer);

  var materials = [];
  for (var i = 0; i < 6; i++) {
    materials.push(this.createCanvas());
  }
  this.inner = new game.THREE.Mesh(
    new game.THREE.CubeGeometry(size-10, size-10, size-10),
    new game.THREE.MeshFaceMaterial(materials)
  );
  game.scene.add(this.inner);
};

Sky.prototype.createLights = function() {
  var game = this.game;
  this.ambient = new game.THREE.HemisphereLight(0x408CFF, 0xFFC880, 0.6);
  game.scene.add(this.ambient);
  this.sunlight = new game.THREE.DirectionalLight(0xffffff, 0.5);
  game.scene.add(this.sunlight);
};

Sky.prototype.color = function(end, time) {
  var self = this;
  if (self._colorInterval) self._colorInterval();
  var i = 0;
  var start = self._color.clone().getHSL();
  var color = self._color.clone().getHSL();
  self._colorInterval = tic.interval(function() {
    var dt = i / time;
    for (var p in color) color[p] = start[p] + (end[p] - start[p]) * dt;
    self._color.setHSL(color.h, color.s, color.l);
    self.outer.material.materials.forEach(function(mat) {
      mat.color.setHSL(color.h, color.s, color.l);
    });
    self.ambient.color.setHSL(color.h, color.s, color.l);
    if (self.game.scene.fog) self.game.scene.fog.color.setHSL(color.h, color.s, color.l);
    if (dt === 1) self._colorInterval();
    i += self._speed;
  }, self._speed);
};

Sky.prototype.speed = function(speed) {
  if (speed != null) this._speed = speed;
  return this._speed;
};

Sky.prototype.paint = function(faces, fn) {
  var self = this;
  var args = Array.prototype.slice.call(arguments, 2);
  var index = ['back', 'front', 'top', 'bottom', 'left', 'right'];
  if (faces === 'all') faces = index;
  if (faces === 'sides') faces = ['back', 'front', 'left', 'right'];
  if (!isArray(faces)) faces = [faces];
  faces.forEach(function(face) {
    if (typeof face === 'string') {
      face = index.indexOf(String(face).toLowerCase());
      if (face === -1) return;
    }
    self.material = self.inner.material.materials[face];
    self.canvas = self.material.map.image;
    self.context = self.canvas.getContext('2d');
    fn.apply(self, args);
    self.inner.material.materials[face].map.needsUpdate = true;
  });
  self.material = self.canvas = self.context = false;
};

Sky.prototype.sun   = require('./lib/sun.js');
Sky.prototype.moon  = require('./lib/moon.js');
Sky.prototype.stars = require('./lib/stars.js');

Sky.prototype.createCanvas = function() {
  var game = this.game;

  var canvas = document.createElement('canvas');
  canvas.height = canvas.width = 512;
  var context = canvas.getContext('2d');

  var material = new game.THREE.MeshBasicMaterial({
    side: game.THREE.BackSide,
    map: new game.THREE.Texture(canvas),
    transparent: true,
    fog: false,
  });
  material.magFilter = game.THREE.NearestFilter;
  material.minFilter = game.THREE.LinearMipMapLinearFilter;
  material.wrapS = material.wrapT = game.THREE.RepeatWrapping;
  material.map.needsUpdate = true;

  return material;
};

Sky.prototype.spin = function(r, axis) {
  axis = axis || 'z';
  this.inner.rotation[axis] = this.outer.rotation[axis] = r;
  this.ambient.rotation[axis] = r + Math.PI;
  var t = traj(this.size/2, this.ambient.rotation);
  this.sunlight.position.set(t[0], t[1], t[2]);
  this.sunlight.lookAt(0, 0, 0);
};

Sky.prototype.clear = function() {
  if (!this.canvas) return false;
  this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
};

// default sky
Sky.prototype._default = {
  hours: {
       0: {color: {h: 230/360, s: 0.3, l: 0}},
     300: {color: {h: 26/360, s: 0.3, l: 0.5}},
     500: {color: {h: 230/360, s: 0.3, l: 0.7}},
    1400: {color: {h: 26/360, s: 0.3, l: 0.5}},
    1600: {color: {h: 230/360, s: 0.3, l: 0}}
  },
  init: function() {
    // add a sun on the bottom
    this.paint('bottom', this.sun);
    // add some stars
    this.paint(['top', 'left', 'right', 'front', 'back'], this.stars, 500);
    // add full moon to the top
    this.paint('top', this.moon, 0);
    // no sunlight at startup
    this.sunlight.intensity = 0;
  },
  day: 0,
  moonCycle: 29.5305882,
  until: false,
  last: 0
};

// default sky fn
Sky.prototype.fn = function(time) {
  var my = this._default;
  var hour = Math.round(time / 100) * 100;
  var speed = Math.abs(my.last - time);
  my.last = time;

  // run initialization once
  if (my.init) { my.init.call(this); delete my.init; }

  // switch color based on time of day
  // maybe make this next part into a helper function
  if (my.hours[hour]) {
    if (!my.until) {
      this.color(my.hours[hour].color, speed > 9 ? 100 : 1000);
      my.until = hour + 100;
    }
  }
  if (my.until === hour) my.until = false;

  // change moon phase
  if (time === 1200) {
    this.paint('top', this.clear);
    this.paint('top', this.moon, Math.floor(my.day % my.moonCycle) / my.moonCycle);
    this.paint('top', this.stars, 500);
  }

  // fade stars in and out
  if (time === 500) {
    this.paint(['top', 'left', 'right', 'front', 'back'], function() {
      this.material.transparent = true;
      var i = tic.interval(function(mat) {
        mat.opacity -= 0.1;
        if (mat.opacity <= 0) i();
      }, 100, this.material);
    });
  }
  if (time === 1800) {
    this.paint(['top', 'left', 'right', 'front', 'back'], function() {
      this.material.transparent = true;
      var i = tic.interval(function(mat) {
        mat.opacity += 0.1;
        if (mat.opacity >= 1) i();
      }, 100, this.material);
    });
  }

  // turn on sunlight
  if (time === 400) {
    (function(sunlight) {
      var i = tic.interval(function() {
        sunlight.intensity += 0.1;
        if (sunlight.intensity <= 1) i();
      }, 100);
    }(this.sunlight));
  }

  // turn off sunlight
  if (time === 1800) {
    (function(sunlight) {
      var i = tic.interval(function() {
        sunlight.intensity -= 0.1;
        if (sunlight.intensity <= 0) i();
      }, 100);
    }(this.sunlight));
  }

  // spin the sky 1 revolution per day
  this.spin(Math.PI * 2 * (time / 2400));

  // keep track of days
  if (time === 2400) my.day++;
};

Sky.prototype.rgba = function(c, o) {
  if (arguments.length === 4) {
    c = {r: arguments[0], g: arguments[1], b: arguments[2]};
    o = arguments[3];
  }
  return 'rgba(' + (c.r*255) + ', ' + (c.g*255) + ', ' + (c.b*255) + ', ' + o + ')';
};

function isArray(ar) {
  return Array.isArray(ar)
    || (typeof ar === 'object' && Object.prototype.toString.call(ar) === '[object Array]');
}
<|endoftext|>


<commit_before><commit_msg>Cleanup index.js<commit_after><|endoftext|>


<commit_before>module.exports = ignore
ignore.extension = extension

function extension (path) {
  if (path.lastIndexOf('.') > path.lastIndexOf('/')) {
    return true
  }

  return false
}

function ignore (paths, ignores) {
  let result = []
  let edge = String.prototype

  for (let ignore of ignores) {
    if (extension(ignore)) {
      edge = edge.endsWith
    } else {
      edge = edge.startsWith
    }

    for (let path of paths) {
      if (!edge.call(path, ignore)) {
        result[result.length] = path
      }
    }
  }

  return result
}
<commit_msg>Remove extension function<commit_after>module.exports = ignore

function ignore (paths, ignores) {
  let result = []
  let edge = String.prototype

  for (let ignore of ignores) {
    if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) {
      edge = edge.endsWith
    } else {
      edge = edge.startsWith
    }

    for (let path of paths) {
      if (!edge.call(path, ignore)) {
        result[result.length] = path
      }
    }
  }

  return result
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*!
 * -----------
 * ASPDB®-Data
 * -----------
 * Data of ASPDB — A manually curated dedicated acid shock proteins database.
 * ___________________________________________________________________________
 *
 * CCPE ——————— Centre for Computational Protein Engineering.
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 10-Dec-2016
 * @license   : Apache, version 2.0
 * @purpose   : To create Data System(s) with Node.js® and NPM.
 * @require   : Node.js®
 * @require   : NPM
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Data System/-- of "ASPDB®-Data".
 * ___________________________________________________________________________
 */

// global __dirname: true
// global require: true

// # Usage: $ node -v
// # Usage: $ npm -v

// Invoking strict mode.
"use strict";

// To load required Node module.
// -----------------------------
var os         = require('os');
var fs         = require('fs');
var path       = require('path');

// To load required NPM modules.
// -----------------------------
var chalk      = require('chalk');
var semver     = require('semver');

// Default color defined.
// ----------------------
var noop       = chalk.red;
var yeep       = chalk.green;
var okay       = chalk.blue;
var boop       = chalk.cyan;
var goop       = chalk.gray;
<commit_msg>Initial commit<commit_after>#!/usr/bin/env node
/*!
 * -----------
 * ASPDB®-Data
 * -----------
 * Data of ASPDB — A manually curated dedicated acid shock proteins database.
 * ___________________________________________________________________________
 *
 * CCPE ——————— Centre for Computational Protein Engineering.
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 10-Dec-2016
 * @license   : Apache, version 2.0
 * @purpose   : To create Data System(s) with Node.js® and NPM.
 * @require   : Node.js®
 * @require   : NPM
 * @build     : SEED™ — Skövde
 *              └────── A Sequømics Product — http://seed.sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Data System/-- of "ASPDB®-Data".
 * ___________________________________________________________________________
 */

// global __dirname: true
// global require: true

// # Usage: $ node -v
// # Usage: $ npm -v

// Invoking strict mode.
"use strict";

// To load required Node module.
// -----------------------------
var os         = require('os');
var fs         = require('fs');
var path       = require('path');

// To load required NPM modules.
// -----------------------------
var chalk      = require('chalk');
var semver     = require('semver');

// Default color defined.
// ----------------------
var noop       = chalk.red;
var yeep       = chalk.green;
var okay       = chalk.blue;
var boop       = chalk.cyan;
var goop       = chalk.gray;

///-------------------
// An object literals.
///-------------------
var build = {
  // Non-identifier property names are quoted.
  "system"     : "SEED™",
  "name"       : "Skövde",
  "year"       : "2016",
  "audience"   : "for all scientist and computational biologist."
};
<|endoftext|>


<commit_before>/**
 * main lib of lark
 */
var Application = require('./lib/application')
/**
 * promise helper
 */
var promisify = require('./lib/promisify');

/**
 * lark interfaces
 */
Application.promisify = promisify.promisify;
Application.promisifyAll = promisify.promisifyAll;
Application.http = promisify.http;
Application.mvc = require('lark-mvc');
Application.router = require('lark-router');
Application.logging = require('lark-log');

module.exports = Application;
<commit_msg>fix code<commit_after>/**
 * main lib of lark
 */
var Application = require('./lib/application')
/**
 * promise helper
 */
var promisify = require('./lib/promisify');

/**
 * lark interfaces
 */
Application.promisify = promisify.promisify;
Application.promisifyAll = promisify.promisifyAll;
Application.http = promisify.http;
Application.mvc = require('lark-mvc');
Application.router = require('lark-router');
Application.logging = require('lark-log').logging;

module.exports = Application;
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var envs = require('envs');
var write = require('fs').writeFileSync;
var list = require('fs').readdirSync;
var join = require('path').join;
var resolve = require('path').resolve;
var Path = require('path');
var glob = require('glob');
var byExtension = require('./lib/loaders-by-extension');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
// polyfill Promises
require('es6-promise').polyfill();
var OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
var ResolveSelf = require('./lib/resolve-self');
// remove this once webpack releases it
// WatchIgnorePlugin = webpack.WatchIgnorePlugin
var WatchIgnorePlugin = require('./lib/watch-ignore');
var EnvifyPlugin = require('./lib/envify-plugin');

var DISABLE_MIN = !!envs('DISABLE_MIN');
var NODE_ENV = envs('ASSET_ENV', envs('NODE_ENV', 'production'));
var DEVELOPMENT = NODE_ENV === 'development';
var HASH = typeof envs('DISABLE_HASH') === 'undefined';
var MANIFEST = envs('MANIFEST');
var BUILD_TARGET = envs('BUILD_TARGET', 'web');
var EXTRACT_STYLE = !DEVELOPMENT && envs('EXTRACT_STYLE', BUILD_TARGET === 'node') !== '0';
var OUTPUT_PATTERN = envs('OUTPUT_PATTERN', '[name]');
var MAIN_ENTRY = DEVELOPMENT ? 'app' : envs('MAIN_ENTRY', 'main');
var COMPILE_ENV = envs('COMPILE_ENV', '1') !== '0';

module.exports = function(dirname, webpack) {
  var config = {
    sourcedir: dirname,
    cache: true
  };

  /**
   * Configure the entries
   */

  var target = config.target = BUILD_TARGET;

  // Autoload all of the modules
  config.entry = {};
  config.entry[MAIN_ENTRY] = dirname + '/index.js';

  if (target === 'node') {
    config.entry = {
      server: dirname + '/server'
    };
  }

  config.output = {
    path: Path.dirname(dirname) + '/build',
    filename: (DEVELOPMENT || !HASH) ?
      OUTPUT_PATTERN + '.js' :
      OUTPUT_PATTERN + (DISABLE_MIN ? '' : '.min') + '.js?[chunkhash]',
    libraryTarget: 'this'
  };

  if (DEVELOPMENT) {
    config.output.pathinfo = true;
    config.output.publicPath = '/build/';

    if (config.target === 'web') {
      // use the eval builder for optimal speed in development
      config.devtool = 'eval';

      var entries = [config.entry.app];
      // append the hot reload entries
      entries.push('webpack-dev-server/client?http://localhost:' + envs('PORT', '3000'));
      entries.push('webpack/hot/dev-server');
      config.entry = entries;
    }
  }

  /**
   * Configure plugins
   */

  config.plugins = [
    new webpack.IgnorePlugin(/vertx/),
    envify(webpack),
    new webpack.DefinePlugin({
      'browser.env': '__env__',
      'process.BUILD_TARGET': JSON.stringify(target)
    }),
    new webpack.ResolverPlugin([
      new ResolveSelf()
    ], ['normal'])
  ];

  var extractPlugin = new ExtractTextPlugin('style', OUTPUT_PATTERN + (DISABLE_MIN ? '' : '.min') + '.css?[chunkhash]');

  if (EXTRACT_STYLE) {
    config.plugins.push(extractPlugin);
    config.plugins.push(new OptimizeCssPlugin({
      canPrint: false
    }));
  }

  if (!DEVELOPMENT) {
    config.plugins.push(
      new webpack.optimize.AggressiveMergingPlugin({
        moveToParents: true
      })
    );

    if (!envs('DISABLE_MIN')) config.plugins.push(
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.optimize.UglifyJsPlugin({output: {comments: false}, sourceMap: false})
    );

    if (MANIFEST) config.plugins.push(createManifest(MANIFEST));
  } else {
    // append the hot reload plugin
    if (config.target === 'web') config.plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  /**
   * configure resolution
   */

  config.resolve = {
    extensions: ['', '.js'],
    modulesDirectories: ['web_modules', 'node_modules', 'src/modules'],
    fallback: [process.cwd(), process.cwd() + '/node_modules']
  };

  config.resolveLoader = {
    fallback: [process.cwd(), process.cwd() + '/node_modules']
  };

  /**
   * Configure loaders
   */

  config.module = {
    loaders: []
  };

  config.addLoader = function(ext, loader) {
    if (ext instanceof RegExp) return config.module.loaders.push({test: ext, loader: loader, loaders: loader});
    var obj = {};
    obj[ext] = loader;
    return config.module.loaders.push.apply(config.module.loaders, byExtension(obj));
  };

  /**
   * Setup style loading
   */

  config.addStyle = function(ext, loader, styleLoader) {
    styleLoader = styleLoader || 'style-loader';
    config.addLoader(ext, !EXTRACT_STYLE ? styleLoader + '!' + loader : extractPlugin.extract(loader));
  };

  /**
   * Configure development stuff
   */

  var watchIgnores = [];

  config.load = function() {
    if (watchIgnores.length) config.plugins.push(new WatchIgnorePlugin(watchIgnores));
    return webpack(config);
  };

  config.watchIgnore = function() {
    watchIgnores.push.apply(watchIgnores, arguments);
  };

  config.prefetchWildcard = function(pattern, opts, ignore) {
    glob.sync(pattern, opts).forEach(function(file) {
      if (ignore && file.match(ignore)) return;
      config.prefetchModule(resolve(process.cwd(), file));
    });
  };

  config.prefetchModule = function(context, request) {
    config.plugins.push(new webpack.PrefetchPlugin(context, request));
  };

  return config;
};

function envify(webpack) {
  var env = COMPILE_ENV ? null : function(name) {
    return '___POE_UI_BUILDER_ENV_BEGIN___' + name + '___POE_UI_BUILDER_ENV_END___';
  };
  return new EnvifyPlugin(env, webpack);
}

function createManifest(manifest) {
  return function() {
    this.plugin('done', function(stats) {
      var json = stats.toJson();
      var byChunkName = json.assetsByChunkName;
      var out = json.assets.reduce(function(acc, asset) {
        if (!asset.chunkNames.length) {
          if (~asset.name.indexOf('.js')) acc.chunks.push(asset.name);
          return acc;
        }
        if (~asset.name.indexOf('.css')) acc.styles.push(asset.name);
        if (~asset.name.indexOf('.js')) acc.scripts.push(asset.name);
        return acc;
      }, {
        styles: [],
        scripts: [],
        chunks: []
      });

      write(manifest, JSON.stringify(out, null, '  '));
    });
  };
}
<commit_msg>Added way to set hostname for web pack via environment variable for docker compatibility.<commit_after>/**
 * Module dependencies
 */

var envs = require('envs');
var write = require('fs').writeFileSync;
var list = require('fs').readdirSync;
var join = require('path').join;
var resolve = require('path').resolve;
var Path = require('path');
var glob = require('glob');
var byExtension = require('./lib/loaders-by-extension');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
// polyfill Promises
require('es6-promise').polyfill();
var OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
var ResolveSelf = require('./lib/resolve-self');
// remove this once webpack releases it
// WatchIgnorePlugin = webpack.WatchIgnorePlugin
var WatchIgnorePlugin = require('./lib/watch-ignore');
var EnvifyPlugin = require('./lib/envify-plugin');

var DISABLE_MIN = !!envs('DISABLE_MIN');
var NODE_ENV = envs('ASSET_ENV', envs('NODE_ENV', 'production'));
var DEVELOPMENT = NODE_ENV === 'development';
var HASH = typeof envs('DISABLE_HASH') === 'undefined';
var MANIFEST = envs('MANIFEST');
var BUILD_TARGET = envs('BUILD_TARGET', 'web');
var EXTRACT_STYLE = !DEVELOPMENT && envs('EXTRACT_STYLE', BUILD_TARGET === 'node') !== '0';
var OUTPUT_PATTERN = envs('OUTPUT_PATTERN', '[name]');
var MAIN_ENTRY = DEVELOPMENT ? 'app' : envs('MAIN_ENTRY', 'main');
var COMPILE_ENV = envs('COMPILE_ENV', '1') !== '0';

module.exports = function(dirname, webpack) {
  var config = {
    sourcedir: dirname,
    cache: true
  };

  /**
   * Configure the entries
   */

  var target = config.target = BUILD_TARGET;

  // Autoload all of the modules
  config.entry = {};
  config.entry[MAIN_ENTRY] = dirname + '/index.js';

  if (target === 'node') {
    config.entry = {
      server: dirname + '/server'
    };
  }

  config.output = {
    path: Path.dirname(dirname) + '/build',
    filename: (DEVELOPMENT || !HASH) ?
      OUTPUT_PATTERN + '.js' :
      OUTPUT_PATTERN + (DISABLE_MIN ? '' : '.min') + '.js?[chunkhash]',
    libraryTarget: 'this'
  };

  if (DEVELOPMENT) {
    config.output.pathinfo = true;
    config.output.publicPath = '/build/';

    if (config.target === 'web') {
      // use the eval builder for optimal speed in development
      config.devtool = 'eval';

      var entries = [config.entry.app];
      // append the hot reload entries
      entries.push('webpack-dev-server/client?' + envs('WEBPACK_DEV_SERVER_URL', 'http://localhost:' + envs('PORT', '3000')));
      entries.push('webpack/hot/dev-server');
      config.entry = entries;
    }
  }

  /**
   * Configure plugins
   */

  config.plugins = [
    new webpack.IgnorePlugin(/vertx/),
    envify(webpack),
    new webpack.DefinePlugin({
      'browser.env': '__env__',
      'process.BUILD_TARGET': JSON.stringify(target)
    }),
    new webpack.ResolverPlugin([
      new ResolveSelf()
    ], ['normal'])
  ];

  var extractPlugin = new ExtractTextPlugin('style', OUTPUT_PATTERN + (DISABLE_MIN ? '' : '.min') + '.css?[chunkhash]');

  if (EXTRACT_STYLE) {
    config.plugins.push(extractPlugin);
    config.plugins.push(new OptimizeCssPlugin({
      canPrint: false
    }));
  }

  if (!DEVELOPMENT) {
    config.plugins.push(
      new webpack.optimize.AggressiveMergingPlugin({
        moveToParents: true
      })
    );

    if (!envs('DISABLE_MIN')) config.plugins.push(
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.optimize.UglifyJsPlugin({output: {comments: false}, sourceMap: false})
    );

    if (MANIFEST) config.plugins.push(createManifest(MANIFEST));
  } else {
    // append the hot reload plugin
    if (config.target === 'web') config.plugins.push(new webpack.HotModuleReplacementPlugin());
  }

  /**
   * configure resolution
   */

  config.resolve = {
    extensions: ['', '.js'],
    modulesDirectories: ['web_modules', 'node_modules', 'src/modules'],
    fallback: [process.cwd(), process.cwd() + '/node_modules']
  };

  config.resolveLoader = {
    fallback: [process.cwd(), process.cwd() + '/node_modules']
  };

  /**
   * Configure loaders
   */

  config.module = {
    loaders: []
  };

  config.addLoader = function(ext, loader) {
    if (ext instanceof RegExp) return config.module.loaders.push({test: ext, loader: loader, loaders: loader});
    var obj = {};
    obj[ext] = loader;
    return config.module.loaders.push.apply(config.module.loaders, byExtension(obj));
  };

  /**
   * Setup style loading
   */

  config.addStyle = function(ext, loader, styleLoader) {
    styleLoader = styleLoader || 'style-loader';
    config.addLoader(ext, !EXTRACT_STYLE ? styleLoader + '!' + loader : extractPlugin.extract(loader));
  };

  /**
   * Configure development stuff
   */

  var watchIgnores = [];

  config.load = function() {
    if (watchIgnores.length) config.plugins.push(new WatchIgnorePlugin(watchIgnores));
    return webpack(config);
  };

  config.watchIgnore = function() {
    watchIgnores.push.apply(watchIgnores, arguments);
  };

  config.prefetchWildcard = function(pattern, opts, ignore) {
    glob.sync(pattern, opts).forEach(function(file) {
      if (ignore && file.match(ignore)) return;
      config.prefetchModule(resolve(process.cwd(), file));
    });
  };

  config.prefetchModule = function(context, request) {
    config.plugins.push(new webpack.PrefetchPlugin(context, request));
  };

  return config;
};

function envify(webpack) {
  var env = COMPILE_ENV ? null : function(name) {
    return '___POE_UI_BUILDER_ENV_BEGIN___' + name + '___POE_UI_BUILDER_ENV_END___';
  };
  return new EnvifyPlugin(env, webpack);
}

function createManifest(manifest) {
  return function() {
    this.plugin('done', function(stats) {
      var json = stats.toJson();
      var byChunkName = json.assetsByChunkName;
      var out = json.assets.reduce(function(acc, asset) {
        if (!asset.chunkNames.length) {
          if (~asset.name.indexOf('.js')) acc.chunks.push(asset.name);
          return acc;
        }
        if (~asset.name.indexOf('.css')) acc.styles.push(asset.name);
        if (~asset.name.indexOf('.js')) acc.scripts.push(asset.name);
        return acc;
      }, {
        styles: [],
        scripts: [],
        chunks: []
      });

      write(manifest, JSON.stringify(out, null, '  '));
    });
  };
}
<|endoftext|>


<commit_before>var createCharm = require('charm')
var EventEmitter = require('events').EventEmitter
var through = require('through2')
var duplexer = require('duplexer2')
var wcstring = require('wcstring')
const color = require('color-convert')
const supportsColor = require('supports-color')

module.exports = function (opts) {
  return new Menu(opts || {})
}

const keywordLookup = supportsColor.supportsColor().has256 ? color.keyword.ansi256 : color.keyword.ansi16

class Menu extends EventEmitter {
  constructor (opts) {
    super()
    this.width = opts.width || 50
    this.x = opts.x || 1
    this.y = opts.y || 1
    this.init = { x: this.x, y: this.y }
    this.items = []
    this.lines = {}
    this.selected = opts.selected || 0
    this.colors = {
      fg: typeof opts.fg === 'number' ? opts.fg : keywordLookup(opts.fg || 'white'),
      bg: typeof opts.bg === 'number' ? opts.bg : keywordLookup(opts.bg || 'blue')
    }

    this.padding = opts.padding || {
      left: 2,
      right: 2,
      top: 1,
      bottom: 1
    }
    if (typeof this.padding === 'number') {
      this.padding = {
        left: this.padding,
        right: this.padding,
        top: this.padding,
        bottom: this.padding
      }
    }
    this.x += this.padding.left
    this.y += this.padding.top
    this.size = {
      x: this.width + this.padding.left + this.padding.right
    }

    this._input = through(
      (buf, _, next) => {
        this._ondata(buf)
        next()
      },
      () => { this.emit('close') }
    )
    this._output = through()
    this.charm = opts.charm || createCharm({
      input: this._input
    })
    this.charm.on('error', function () {})
    this.charm.pipe(this._output)

    this.stream = this.charm.pipe(through())
    try {
      this.charm.display('reset')
      this.charm.display('bright')
    } catch (e) {}

    process.nextTick(() => {
      this._ticked = true
      this.charm.cursor(false)
      this._draw()
    })
  }

  createStream () {
    return duplexer(this._input, this._output)
  }

  add (label, cb) {
    var index = this.items.length
    if (cb) {
      this.on('select', function (x, ix) {
        if (ix === index) cb(x, ix)
      })
    }

    this.items.push({
      x: this.x,
      y: this.y,
      label: label
    })
    this._fillLine(this.y)
    this.y++
  }

  _fillLine (y) {
    if (!this.lines[y]) {
      this.charm.position(this.init.x, y)
      this.charm.write(Array(1 + this.size.x).join(' '))
      this.lines[y] = true
    }
  }

  jump (name) {
    var index = typeof name === 'number'
      ? name
      : this.items
        .findIndex(item => item.label === name)

    if (index < 0) return
    var prev = this.selected
    this.selected = index
    if (this._ticked) {
      this._drawRow(prev)
      this._drawRow(index)
    }
  }

  close () {
    this._input.end()
    this.charm.cursor(true)
    this.charm.display('reset')
    this.charm.position(1, this.y + 1)
    this.charm.end()
  }

  reset () {
    this.charm.reset()
  }

  write (msg) {
    this.charm.background(this.colors.bg)
    this.charm.foreground(this.colors.fg)
    this._fillLine(this.y)

    var parts = msg.split('\n')

    for (var i = 0; i < parts.length; i++) {
      if (parts[i].length) {
        this.charm.position(this.x, this.y)
        this.charm.write(parts[i])
      }
      if (i !== parts.length - 1) {
        this.x = this.init.x + this.padding.left
        this._fillLine(this.y)
        this.y++
      }
    }
  }

  _draw () {
    for (let i = 0; i < this.padding.top; i++) {
      this._fillLine(this.init.y + i)
    }
    for (let i = 0; i < this.items.length; i++) this._drawRow(i)

    // reset foreground and background colors
    this.charm.background(this.colors.bg)
    this.charm.foreground(this.colors.fg)

    for (let i = 0; i < this.padding.bottom; i++) {
      this._fillLine(this.y + i)
    }
  }

  _drawRow (index) {
    index = (index + this.items.length) % this.items.length
    var item = this.items[index]
    this.charm.position(item.x, item.y)

    if (this.selected === index) {
      this.charm.background(this.colors.fg)
      this.charm.foreground(this.colors.bg)
    } else {
      this.charm.background(this.colors.bg)
      this.charm.foreground(this.colors.fg)
    }

    var len = this.width - wcstring(item.label).size() + 1

    this.charm.write(item.label + Array(Math.max(0, len)).join(' '))
  }

  _ondata (buf) {
    var bytes = [].slice.call(buf)
    while (bytes.length) {
      var codes = [].join.call(bytes, '.')
      if (/^(27.91.65|27,79.65|107|16)\b/.test(codes)) { // up or k
        this.selected = (this.selected - 1 + this.items.length) %
                    this.items.length

        this._drawRow(this.selected + 1)
        this._drawRow(this.selected)
        if (/^107\b/.test(codes)) bytes.shift()
        else bytes.splice(0, 3)
      }
      if (/^(27.91.66|27.79.66|106|14)\b/.test(codes)) { // down or j
        this.selected = (this.selected + 1) % this.items.length
        this._drawRow(this.selected - 1)
        this._drawRow(this.selected)
        if (/^106\b/.test(codes)) bytes.shift()
        else bytes.splice(0, 3)
      } else if (/^(3|113)/.test(codes)) { // ^C or q
        this.charm.reset()
        this._input.end()
        this._output.end()
        bytes.shift()
      } else if (/^(13|10)\b/.test(codes)) { // enter
        this.charm.position(1, this.items[this.items.length - 1].y + 2)
        this.charm.display('reset')
        this.emit('select', this.items[this.selected].label, this.selected)
        bytes.shift()
      } else bytes.shift()
    }
  }
}
<commit_msg>Breaking change: emitting items instead of labels for easier handling of events<commit_after>var createCharm = require('charm')
var EventEmitter = require('events').EventEmitter
var through = require('through2')
var duplexer = require('duplexer2')
var wcstring = require('wcstring')
const color = require('color-convert')
const supportsColor = require('supports-color')

module.exports = function (opts) {
  return new Menu(opts || {})
}

const keywordLookup = supportsColor.supportsColor().has256 ? color.keyword.ansi256 : color.keyword.ansi16

function preparePadding (input) {
  if (typeof input === 'number') {
    return {
      left: input,
      right: input,
      top: input,
      bottom: input
    }
  }
  return input || {
    left: 2,
    right: 2,
    top: 1,
    bottom: 1
  }
}

class Menu extends EventEmitter {
  constructor (opts) {
    super()
    this.width = opts.width || 50
    this.x = opts.x || 1
    this.y = opts.y || 1
    this.init = { x: this.x, y: this.y }
    this.entries = []
    this.lines = {}
    this.selected = opts.selected || 0
    this.colors = {
      fg: typeof opts.fg === 'number' ? opts.fg : keywordLookup(opts.fg || 'white'),
      bg: typeof opts.bg === 'number' ? opts.bg : keywordLookup(opts.bg || 'blue')
    }

    this.padding = preparePadding(opts.padding)
    this.x += this.padding.left
    this.y += this.padding.top
    this.size = {
      x: this.width + this.padding.left + this.padding.right
    }

    this._input = through(
      (buf, _, next) => {
        this._ondata(buf)
        next()
      },
      () => { this.emit('close') }
    )
    this._output = through()
    this.charm = opts.charm || createCharm({
      input: this._input
    })
    this.charm.on('error', function () {})
    this.charm.pipe(this._output)

    this.stream = this.charm.pipe(through())
    try {
      this.charm.display('reset')
      this.charm.display('bright')
    } catch (e) {}

    process.nextTick(() => {
      this._ticked = true
      this.charm.cursor(false)
      this._draw()
    })
  }

  createStream () {
    return duplexer(this._input, this._output)
  }

  add (item, cb) {
    if (typeof item === 'string') {
      item = { label: item }
    }
    if (typeof cb === 'function') {
      item.handler = cb
    }
    if (item.handler) {
      this.on('select', (selectedItem, index) => {
        if (selectedItem === item) item.handler(item, index)
      })
    }

    this.entries.push({
      x: this.x,
      y: this.y,
      item: item
    })
    this._fillLine(this.y)
    this.y++
  }

  _fillLine (y) {
    if (!this.lines[y]) {
      this.charm.position(this.init.x, y)
      this.charm.write(Array(1 + this.size.x).join(' '))
      this.lines[y] = true
    }
  }

  jump (label) {
    var index = typeof label === 'number'
      ? label
      : this.entries
        .findIndex(entry => entry.label === label)

    if (index < 0) return
    var prev = this.selected
    this.selected = index
    if (this._ticked) {
      this._drawRow(prev)
      this._drawRow(index)
    }
  }

  close () {
    this._input.end()
    this.charm.cursor(true)
    this.charm.display('reset')
    this.charm.position(1, this.y + 1)
    this.charm.end()
  }

  reset () {
    this.charm.reset()
  }

  write (msg) {
    this.charm.background(this.colors.bg)
    this.charm.foreground(this.colors.fg)
    this._fillLine(this.y)

    var parts = msg.split('\n')

    for (var i = 0; i < parts.length; i++) {
      if (parts[i].length) {
        this.charm.position(this.x, this.y)
        this.charm.write(parts[i])
      }
      if (i !== parts.length - 1) {
        this.x = this.init.x + this.padding.left
        this._fillLine(this.y)
        this.y++
      }
    }
  }

  _draw () {
    for (let i = 0; i < this.padding.top; i++) {
      this._fillLine(this.init.y + i)
    }
    for (let i = 0; i < this.entries.length; i++) this._drawRow(i)

    // reset foreground and background colors
    this.charm.background(this.colors.bg)
    this.charm.foreground(this.colors.fg)

    for (let i = 0; i < this.padding.bottom; i++) {
      this._fillLine(this.y + i)
    }
  }

  _drawRow (index) {
    index = (index + this.entries.length) % this.entries.length
    const entry = this.entries[index]
    this.charm.position(entry.x, entry.y)

    if (this.selected === index) {
      this.charm.background(this.colors.fg)
      this.charm.foreground(this.colors.bg)
    } else {
      this.charm.background(this.colors.bg)
      this.charm.foreground(this.colors.fg)
    }

    var len = this.width - wcstring(entry.item.label).size() + 1

    this.charm.write(entry.item.label + Array(Math.max(0, len)).join(' '))
  }

  _ondata (buf) {
    var bytes = [].slice.call(buf)
    while (bytes.length) {
      var codes = [].join.call(bytes, '.')
      if (/^(27.91.65|27,79.65|107|16)\b/.test(codes)) { // up or k
        this.selected = (this.selected - 1 + this.entries.length) % this.entries.length

        this._drawRow(this.selected + 1)
        this._drawRow(this.selected)
        if (/^107\b/.test(codes)) bytes.shift()
        else bytes.splice(0, 3)
      }
      if (/^(27.91.66|27.79.66|106|14)\b/.test(codes)) { // down or j
        this.selected = (this.selected + 1) % this.entries.length
        this._drawRow(this.selected - 1)
        this._drawRow(this.selected)
        if (/^106\b/.test(codes)) bytes.shift()
        else bytes.splice(0, 3)
      } else if (/^(3|113)/.test(codes)) { // ^C or q
        this.charm.reset()
        this._input.end()
        this._output.end()
        bytes.shift()
      } else if (/^(13|10)\b/.test(codes)) { // enter
        this.charm.position(1, this.entries[this.entries.length - 1].y + 2)
        this.charm.display('reset')
        const item = this.entries[this.selected].item
        this.emit('select', item.label, this.selected, item)
        bytes.shift()
      } else bytes.shift()
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var through = require('through2');
var PluginError = require('gulp-util').PluginError;
var objectAssign = require('object-assign');
var esperanto = require('esperanto');

var defaultOptions = {
  type: 'amd'
};

function compile (contents, opts) {
  if(opts.moduleRoot) {
    var name = path.relative(opts.moduleRoot, file.path).slice(0, -path.extname(file.path).length);
    // platform agnostic for file path definition
    name = name.split(path.sep).join('/');
    var prefix = opts.modulePrefix.indexOf('/') > -1 ? opts.modulePrefix : opts.modulePrefix + '/';
    opts.amdName = prefix + name;
  }

  var fileOpts = objectAssign(defaultOptions, opts);
  var fn = 'to' + opts.type.charAt(0).toUpperCase() + opts.type.slice(1).toLowerCase();

  var code = esperanto[fn](file.contents.toString(), fileOpts).code;
  return new BUffer(code);
}

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

  function EsperantoRocks (file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);  // return an empty file
      return;
    }

    // Do not do streams by gulp design
    if (file.isStream()) {
      cb(new PluginError('gulp-esperanto-rocks', 'Streaming not supported', {fileName: file.path}));
      return;
    }

    // `file.contents` type should always be the same going out as it was when it came in
    try {
      file.contents = compile(file.contents, options);
      this.push(file);
    } catch (err) {
      this.emit('error', new PluginError('gulp-esperanto-rocks', err, {fileName: file.path}));
    }

    cb();
  }

  return through.obj(EsperantoRocks);
};
<commit_msg>update typo and pass the right argument<commit_after>'use strict';

var through = require('through2');
var PluginError = require('gulp-util').PluginError;
var objectAssign = require('object-assign');
var esperanto = require('esperanto');
var path = require('path');

var defaultOptions = {
  type: 'amd'
};

function compile (file, opts) {
  if(opts.moduleRoot) {
    var name = path.relative(opts.moduleRoot, file.path).slice(0, -path.extname(file.path).length);
    // platform agnostic for file path definition
    name = name.split(path.sep).join('/');
    var prefix = opts.modulePrefix.indexOf('/') > -1 ? opts.modulePrefix : opts.modulePrefix + '/';
    opts.amdName = prefix + name;
  }

  var fileOpts = objectAssign(defaultOptions, opts);
  var fn = 'to' + opts.type.charAt(0).toUpperCase() + opts.type.slice(1).toLowerCase();

  var code = esperanto[fn](file.contents.toString(), fileOpts).code;
  return new Buffer(code);
}

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

  function EsperantoRocks (file, enc, cb) {
    if (file.isNull()) {
      cb(null, file);  // return an empty file
      return;
    }

    // Do not do streams by gulp design
    if (file.isStream()) {
      cb(new PluginError('gulp-esperanto-rocks', 'Streaming not supported', {fileName: file.path}));
      return;
    }

    // `file.contents` type should always be the same going out as it was when it came in
    try {
      file.contents = compile(file, options);
      this.push(file);
    } catch (err) {
      this.emit('error', new PluginError('gulp-esperanto-rocks', err, {fileName: file.path}));
    }

    cb();
  }

  return through.obj(EsperantoRocks);
};
<|endoftext|>


<commit_before>var querystring = require('querystring');
var debug = require('debug')('connect-login');

module.exports = function (options){

    options = options || {};

    var loginManager = function (req, res, next){

        if (req.session === undefined){
            return next(new Error("session middleware is required to use connect-login"));
        }

        if (loginManager._userLoader === undefined){
            return next(new Error("The connect-login module requires a user loader function"));
        }

        if (loginManager._userSaver === undefined){
            return next(new Error("The connect-login module requires a user serializer function"));
        }

        req.loginManager = loginManager;

        req.login = function(user, rememberMe){
            debug("req.login username: " + user.username);

            req.user = user;
            var userid = loginManager._userSaver(user);

            if (!userid){
                throw Error("serializeUser() returned an empty value");
            }

            req.session.userid = userid;
            req.session.fresh = true;

            if (rememberMe){

                if (rememberMe === true){
                    rememberMe = {};
                }

                rememberMe.signed = true;

                if (rememberMe.maxAge === undefined){
                    rememberMe.maxAge = 360 * 24 * 60 * 60 * 1000;
                }
                if (rememberMe.httpOnly === undefined){
                    rememberMe.httpOnly = true;
                }
                if (rememberMe.path === undefined){
                    rememberMe.path = '/';
                }

                res.cookie('userid', userid, rememberMe);
            }
        };

        var signedCookies = req.signedCookies || {};

        req.logout = function(){

            delete req.session.userid;
            if (signedCookies.userid){
                debug("logoug username:", signedCookies.userid);
                res.clearCookie('userid');
            }

        };

        var userid = req.session.userid || signedCookies.userid;
        if (userid){
            debug("Load User user_id: " + userid);
            loginManager._userLoader(userid, function(err, user){
                res.locals.user = req.user = user;
                next(err);
            });
        } else {
            if (loginManager._userCreator){
                debug("Load Anonymous User");
                res.locals.user = req.user = loginManager._userCreator();
            }
            next();
        }
    };

    loginManager.loadUser = loginManager.userLoader = function(userLoader){
        loginManager._userLoader = userLoader;
        debug("userLoader was set");
    };

    loginManager.serializeUser = loginManager.userSerializer = function(userSaver){
        loginManager._userSaver = userSaver;
        debug("userSerializer was set");
    };
    loginManager.anonymousUser = function(userCreator){
        loginManager._userCreator = userCreator;
        debug("anonymousUser creator was set");
    };

    loginManager.loginPath = options.loginPath || '/login';
    return loginManager;
};

module.exports.loginRequired = function(req, res, next){
    var user  = req.user;
    if (!user || !user.username) {
        var url = req.loginManager.loginPath + '?' + querystring.stringify({next: req.path});
        return res.redirect(url);
    } else {
        next();
    }
};

module.exports.loginRequiredWS = function(req, res, next){
    var user  = req.user;
    if (!user || !user.username) {
        next(new Error("Login is required for this websocked upgrade"));
        return;
    } else {
        next();
    }
};
<commit_msg>fixes<commit_after>var querystring = require('querystring');
var debug = require('debug')('connect-login');

module.exports = function (options){

    options = options || {};

    var loginManager = function (req, res, next){

        if (req.session === undefined){
            return next(new Error("session middleware is required to use connect-login"));
        }

        if (loginManager._userLoader === undefined){
            return next(new Error("The connect-login module requires a user loader function"));
        }

        if (loginManager._userSaver === undefined){
            return next(new Error("The connect-login module requires a user serializer function"));
        }

        req.loginManager = loginManager;

        req.login = function(user, rememberMe){
            debug("req.login username: " + user.username);

            req.user = user;
            var userid = loginManager._userSaver(user);

            if (!userid){
                throw Error("serializeUser() returned an empty value");
            }

            req.session.userid = userid;
            req.session.fresh = true;

            if (rememberMe){

                if (rememberMe === true){
                    rememberMe = {};
                }

                rememberMe.signed = true;

                if (rememberMe.maxAge === undefined){
                    rememberMe.maxAge = 360 * 24 * 60 * 60 * 1000;
                }
                if (rememberMe.httpOnly === undefined){
                    rememberMe.httpOnly = true;
                }
                if (rememberMe.path === undefined){
                    rememberMe.path = '/';
                }

                res.cookie('userid', userid, rememberMe);
            }
        };

        var signedCookies = req.signedCookies || {};

        req.logout = function(){

            delete req.session.userid;
            delete req.session.fresh;

            if (signedCookies.userid){
                debug("logoug username:", signedCookies.userid);
                res.clearCookie('userid');
            }

        };

        var userid = req.session.userid || signedCookies.userid;
        if (userid){
            debug("Load User user_id: " + userid);
            loginManager._userLoader(userid, function(err, user){
                res.locals.user = req.user = user;
                next(err);
            });
        } else {
            if (loginManager._userCreator){
                debug("Load Anonymous User");
                res.locals.user = req.user = loginManager._userCreator();
            } else {
                res.locals.user = req.user = null;
            }
            next();
        }
    };

    loginManager.loadUser = loginManager.userLoader = function(userLoader){
        loginManager._userLoader = userLoader;
        debug("userLoader was set");
    };

    loginManager.serializeUser = loginManager.userSerializer = function(userSaver){
        loginManager._userSaver = userSaver;
        debug("userSerializer was set");
    };
    loginManager.anonymousUser = function(userCreator){
        loginManager._userCreator = userCreator;
        debug("anonymousUser creator was set");
    };

    loginManager.loginPath = options.loginPath || '/login';
    return loginManager;
};

module.exports.loginRequired = function(req, res, next){

    if (!req.loginManager){
        next(new Error("connect-login middleware must be used before loginRequired"));
    }

    var user  = req.user;
    if (!user || !user.username) {
        var url = req.loginManager.loginPath + '?' + querystring.stringify({next: req.path});
        return res.redirect(url);
    } else {
        next();
    }
};

module.exports.loginRequiredWS = function(req, res, next){
    var user  = req.user;
    if (!user || !user.username) {
        next(new Error("Login is required for this websocked upgrade"));
        return;
    } else {
        next();
    }
};
<|endoftext|>