<commit_before>require('babel-register')

const webpack = require('webpack')
const cssnano = require('cssnano')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OfflinePlugin = require('offline-plugin')
const config = require('../config/')
const _debug = require('debug')
const postcssImport = require('postcss-import')
const precss = require('precss')
const paths = config.utils_paths

const debug = _debug('app:webpack:config')
const {__DEV__, __PROD__, __TEST__} = config.globals

debug('Create configuration.')
const webpackConfig = {
  name: 'client',
  target: 'web',
  devtool: 'cheap-source-map',
  resolve: {
    root: paths.client(),
    extensions: ['', '.js', '.jsx', '.json']
  },
  module: {},
  modulesDirectories: ['src', 'node_modules'],
  colors: true,
  stats: {
    colors: true,
    reasons: true
  }
}

const APP_ENTRY_PATHS = [
  'babel-polyfill',
  paths.client('main.jsx')
]

webpackConfig.entry = {
  app: __DEV__
    ? APP_ENTRY_PATHS.concat(`webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`)
    : APP_ENTRY_PATHS,
  vendor: config.vendor_packages
}

webpackConfig.output = {
  filename: '[name].[hash].js',
  path: paths.base(config.dir_dist),
  publicPath: config.compiler_public_path
}

webpackConfig.plugins = [
  new webpack.DefinePlugin(config.globals),
  new HtmlWebpackPlugin({
    template: paths.client('index.html'),
    hash: false,
    // Uncomment if you want a favicon
    // favicon: path.resolve(__dirname, '../src/static') + '/favicon.ico',
    filename: 'index.html',
    inject: 'body',
    minify: {
      collapseWhitespace: true
    }
  }),
  new OfflinePlugin()
]

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
}
else if (__PROD__) {
  debug('Apply UglifyJS plugin.')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        unused: true,
        dead_code: true,
        drop_console: true,
        screw_ie8: true,
        drop_debugger: true,
        hoist_funs: true,
        evaluate: true,
        comparisons: true,
        properties: true,
        warnings: false
      }
    }),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    })
  )
}

if (!__TEST__) {
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({
    names: ['vendor']
  }))
}

if (!__PROD__) {
  webpackConfig.module.preLoaders = [{
    test: /\.(js|jsx)$/,
    loader: 'eslint',
    exclude: /node_modules/
  }]

  webpackConfig.eslint = {
    configFile: './.eslintrc',
    emitWarning: __DEV__
  }
}

webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime'],
    presets: __DEV__
      ? ['es2015', 'react', 'stage-0']
      : ['es2015', 'react', 'stage-0', 'react-optimize'],
    env: {
      development: {
        plugins: [
          ['react-transform', {
            'transforms': [{
              'transform': 'react-transform-hmr',
              'imports': ['react'],
              'locals': ['module']
            }, {
              'transform': 'react-transform-catch-errors',
              'imports': ['react', 'redbox-react']
            }]
          }],
          'transform-runtime'
        ]
      }
    }
  }
},
{
  test: /\.json$/,
  loader: 'json'
}]

// Styles
const cssLoader = [
  'css?modules',
  'sourceMap',
  'importLoaders=1',
  'localIdentName=[name]__[local]___[hash:base64:5]'
].join('&')

webpackConfig.module.loaders.push({
  test: /\.pcss/,
  include: /src/,
  loaders: [
    'style',
    cssLoader,
    'postcss'
  ]
})

webpackConfig.module.loaders.push({
  test: /\.pcss/,
  exclude: /src/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss'
  ]
})

webpackConfig.module.loaders.push({
  test: /\.*.global.css/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss'
  ]
})

webpackConfig.postcss = [
  postcssImport({
    root: process.cwd(),
    path: `${process.cwd()}/node_modules`
  }),
  precss(),
  cssnano({
    sourcemap: !__PROD__,
    compress: __PROD__,
    autoprefixer: {
      add: true,
      remove: true,
      browsers: ['last 2 versions']
    },
    safe: true,
    discardComments: {
      removeAll: true
    }
  })
]

// File loaders
webpackConfig.module.loaders.push({
  test: /\.(jpe?g|png|gif|svg)$/i,
  loaders: [
    'file?hash=sha512&digest=hex&name=[hash].[ext]',
    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
  ]
})

if (!__DEV__) {
  debug('Apply ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter(loader =>
    loader.loaders && loader.loaders.find(name => /css/.test(name.split('?')[0]))
  ).forEach(loader => {
    const [first, ...rest] = loader.loaders
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].[contenthash].css', {
      allChunks: true
    })
  )
}

module.exports = webpackConfig
<commit_msg>Use chunkhash for prod builds<commit_after>require('babel-register')

const webpack = require('webpack')
const cssnano = require('cssnano')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OfflinePlugin = require('offline-plugin')
const config = require('../config/')
const _debug = require('debug')
const postcssImport = require('postcss-import')
const precss = require('precss')
const paths = config.utils_paths

const debug = _debug('app:webpack:config')
const {__DEV__, __PROD__, __TEST__} = config.globals

debug('Create configuration.')
const webpackConfig = {
  name: 'client',
  target: 'web',
  devtool: 'cheap-source-map',
  resolve: {
    root: paths.client(),
    extensions: ['', '.js', '.jsx', '.json']
  },
  module: {},
  modulesDirectories: ['src', 'node_modules'],
  colors: true,
  stats: {
    colors: true,
    reasons: true
  }
}

const APP_ENTRY_PATHS = [
  'babel-polyfill',
  paths.client('main.jsx')
]

webpackConfig.entry = {
  app: __DEV__
    ? APP_ENTRY_PATHS.concat(`webpack-hot-middleware/client?path=${config.compiler_public_path}__webpack_hmr`)
    : APP_ENTRY_PATHS,
  vendor: config.vendor_packages
}

const filename = __PROD__ ? '[name].[chunkhash].js' : '[name].[hash].js'

webpackConfig.output = {
  filename,
  path: paths.base(config.dir_dist),
  publicPath: config.compiler_public_path
}

webpackConfig.plugins = [
  new webpack.DefinePlugin(config.globals),
  new HtmlWebpackPlugin({
    template: paths.client('index.html'),
    hash: false,
    // Uncomment if you want a favicon
    // favicon: path.resolve(__dirname, '../src/static') + '/favicon.ico',
    filename: 'index.html',
    inject: 'body',
    minify: {
      collapseWhitespace: true
    }
  }),
  new OfflinePlugin()
]

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
}
else if (__PROD__) {
  debug('Apply UglifyJS plugin.')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        unused: true,
        dead_code: true,
        drop_console: true,
        screw_ie8: true,
        drop_debugger: true,
        hoist_funs: true,
        evaluate: true,
        comparisons: true,
        properties: true,
        warnings: false
      }
    }),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    })
  )
}

if (!__TEST__) {
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin({
    names: ['vendor']
  }))
}

if (!__PROD__) {
  webpackConfig.module.preLoaders = [{
    test: /\.(js|jsx)$/,
    loader: 'eslint',
    exclude: /node_modules/
  }]

  webpackConfig.eslint = {
    configFile: './.eslintrc',
    emitWarning: __DEV__
  }
}

webpackConfig.module.loaders = [{
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-runtime'],
    presets: __DEV__
      ? ['es2015', 'react', 'stage-0']
      : ['es2015', 'react', 'stage-0', 'react-optimize'],
    env: {
      development: {
        plugins: [
          ['react-transform', {
            'transforms': [{
              'transform': 'react-transform-hmr',
              'imports': ['react'],
              'locals': ['module']
            }, {
              'transform': 'react-transform-catch-errors',
              'imports': ['react', 'redbox-react']
            }]
          }],
          'transform-runtime'
        ]
      }
    }
  }
},
{
  test: /\.json$/,
  loader: 'json'
}]

// Styles
const cssLoader = [
  'css?modules',
  'sourceMap',
  'importLoaders=1',
  'localIdentName=[name]__[local]___[hash:base64:5]'
].join('&')

webpackConfig.module.loaders.push({
  test: /\.pcss/,
  include: /src/,
  loaders: [
    'style',
    cssLoader,
    'postcss'
  ]
})

webpackConfig.module.loaders.push({
  test: /\.pcss/,
  exclude: /src/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss'
  ]
})

webpackConfig.module.loaders.push({
  test: /\.*.global.css/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss'
  ]
})

webpackConfig.postcss = [
  postcssImport({
    root: process.cwd(),
    path: `${process.cwd()}/node_modules`
  }),
  precss(),
  cssnano({
    sourcemap: !__PROD__,
    compress: __PROD__,
    autoprefixer: {
      add: true,
      remove: true,
      browsers: ['last 2 versions']
    },
    safe: true,
    discardComments: {
      removeAll: true
    }
  })
]

// File loaders
webpackConfig.module.loaders.push({
  test: /\.(jpe?g|png|gif|svg)$/i,
  loaders: [
    'file?hash=sha512&digest=hex&name=[hash].[ext]',
    'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
  ]
})

if (!__DEV__) {
  debug('Apply ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter(loader =>
    loader.loaders && loader.loaders.find(name => /css/.test(name.split('?')[0]))
  ).forEach(loader => {
    const [first, ...rest] = loader.loaders
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].[contenthash].css', {
      allChunks: true
    })
  )
}

module.exports = webpackConfig
<|endoftext|>


<commit_before>/**
 *
 * This wait command is your universal weapon if you want to wait on
 * something. It expects a condition and waits until that condition
 * is fulfilled with an truthy value. A condition can be either a promise
 * or a command that returns a promise.
 *
 * A common example is to wait until a certain element contains a certain
 * text.
 *
 * <example>
 :example.html

I am some text

 :waitUntil.js
 client.waitUntil(function() {
      return this.getText('#someText').then(function(text) {
        return text === 'I am now different'
      });
    });
 * </example>
 *
 *
 * @param {Function|Promise} condition  condition to wait on
 * @param {Number=}          timeout    timeout in ms (default: 500)
 * @param {Number=}          interval   interval between condition checks (default: 250)
 *
 * @uses utility/pause
 * @type utility
 *
 */

var q = require('q'),
    ErrorHandler = require('webdriverio/lib/utils/ErrorHandler.js'),
    reject = function(d) {
        d.reject(new ErrorHandler.CommandError('Promise never resolved with an truthy value'));
    };
var AbortedWaitError = require('../abortedWaitError')

function waitUntilPrivate(condition, timeout, interval, starttime) {
    var self = this,
        defer = q.defer(),
        promise;

    if(typeof condition === 'function') {
        promise = condition.call(this);
    } else if(q.isPromiseAlike(condition)) {
        promise = condition;
    } else {
        throw new ErrorHandler.CommandError('waitUntil condition needs to be a promise or a function that returns a promise');
    }

    var now = new Date().getTime();
    var timeLeft = timeout - (now - starttime);
    timeLeft = timeLeft < 0 ? 0 : timeLeft;

    var abortWait = this.getAbortWait()
    console.log("abortWait", abortWait)
    if (abortWait === true) {
        // Abort the waitUntil and signal it with an AbortedWaitError
        defer.reject(new AbortedWaitError())
        return defer.promise;
    }

    if(!timeLeft) {
        console.log("!timeLeft")
        reject(defer);
        return defer.promise;
    }

    var timeoutId = setTimeout(function() {
        console.log("timeout")
        reject(defer);
    }, timeLeft < 0 ? 0 : timeLeft);

    promise.then(function(res) {
        clearTimeout(timeoutId);

        if(!res) {
            if(q.isPromiseAlike(condition)) {
                defer.reject(new ErrorHandler.CommandError('Promise was fulfilled with a falsy value'));
            }
            return defer.resolve(self.pause(interval)
                .then(waitUntilPrivate.bind(self, condition, timeout, interval, starttime)));
        }

        defer.resolve(res);

    }, function(err) {
        clearTimeout(timeoutId);

        defer.reject(new ErrorHandler.CommandError('Promise was fulfilled but got rejected with the following reason: ' + err));

    });

    return defer.promise;

}

module.exports = function waitUntil(condition, timeout, interval) {
    /*!
     * ensure that timeout and interval are set properly
     */
    if (typeof timeout !== 'number') {
        timeout = this.options.waitforTimeout;
    }

    console.log("called custom waitUntil")

    if (typeof interval !== 'number') {
        interval = this.options.waitforInterval;
    }

    var startTime = new Date().getTime();

    return waitUntilPrivate.call(this, condition, timeout, interval, startTime);
};
<commit_msg>Remove debug output<commit_after>/**
 *
 * This wait command is your universal weapon if you want to wait on
 * something. It expects a condition and waits until that condition
 * is fulfilled with an truthy value. A condition can be either a promise
 * or a command that returns a promise.
 *
 * A common example is to wait until a certain element contains a certain
 * text.
 *
 * <example>
 :example.html

I am some text

 :waitUntil.js
 client.waitUntil(function() {
      return this.getText('#someText').then(function(text) {
        return text === 'I am now different'
      });
    });
 * </example>
 *
 *
 * @param {Function|Promise} condition  condition to wait on
 * @param {Number=}          timeout    timeout in ms (default: 500)
 * @param {Number=}          interval   interval between condition checks (default: 250)
 *
 * @uses utility/pause
 * @type utility
 *
 */

var q = require('q'),
    ErrorHandler = require('webdriverio/lib/utils/ErrorHandler.js'),
    reject = function(d) {
        d.reject(new ErrorHandler.CommandError('Promise never resolved with an truthy value'));
    };
var AbortedWaitError = require('../abortedWaitError')

function waitUntilPrivate(condition, timeout, interval, starttime) {
    var self = this,
        defer = q.defer(),
        promise;

    if(typeof condition === 'function') {
        promise = condition.call(this);
    } else if(q.isPromiseAlike(condition)) {
        promise = condition;
    } else {
        throw new ErrorHandler.CommandError('waitUntil condition needs to be a promise or a function that returns a promise');
    }

    var now = new Date().getTime();
    var timeLeft = timeout - (now - starttime);
    timeLeft = timeLeft < 0 ? 0 : timeLeft;

    var abortWait = this.getAbortWait()
    if (abortWait === true) {
        // Abort the waitUntil and signal it with an AbortedWaitError
        defer.reject(new AbortedWaitError())
        return defer.promise;
    }

    if(!timeLeft) {
        reject(defer);
        return defer.promise;
    }

    var timeoutId = setTimeout(function() {
        reject(defer);
    }, timeLeft < 0 ? 0 : timeLeft);

    promise.then(function(res) {
        clearTimeout(timeoutId);

        if(!res) {
            if(q.isPromiseAlike(condition)) {
                defer.reject(new ErrorHandler.CommandError('Promise was fulfilled with a falsy value'));
            }
            return defer.resolve(self.pause(interval)
                .then(waitUntilPrivate.bind(self, condition, timeout, interval, starttime)));
        }

        defer.resolve(res);

    }, function(err) {
        clearTimeout(timeoutId);

        defer.reject(new ErrorHandler.CommandError('Promise was fulfilled but got rejected with the following reason: ' + err));

    });

    return defer.promise;

}

module.exports = function waitUntil(condition, timeout, interval) {
    /*!
     * ensure that timeout and interval are set properly
     */
    if (typeof timeout !== 'number') {
        timeout = this.options.waitforTimeout;
    }

    if (typeof interval !== 'number') {
        interval = this.options.waitforInterval;
    }

    var startTime = new Date().getTime();

    return waitUntilPrivate.call(this, condition, timeout, interval, startTime);
};
<|endoftext|>


<commit_before>const { RedisClient, createClient, Multi } = require('redis')
const bluebird = require('bluebird')

bluebird.promisifyAll(RedisClient.prototype)
bluebird.promisifyAll(Multi.prototype)

module.exports = class Botact {
  constructor (settings) {
    const { confirmation, token, flowTimeout: timeout, redis = false, redisConfig = {} } = settings

    if (!confirmation) {
      throw new Error('confirmation is required')
    } else if (!token) {
      throw new Error('token is required')
    }

    this.flow = { scenes: {}, session: {}, timeout }
    this.actions = { commands: [], hears: [], events: [], on: [], middlewares: [] }
    this.methods = []
    this.settings = settings
    this.redis = redis && createClient(redisConfig)

    this.api = require('./api')
    this.getOptions = require('./methods/options/get').bind(this)
    this.setOptions = require('./methods/options/set').bind(this)
    this.deleteOptions = require('./methods/options/delete').bind(this)
    this.before = require('./methods/before').bind(this)
    this.use = require('./methods/use').bind(this)
    this.command = require('./methods/command').bind(this)
    this.hears = require('./methods/hears').bind(this)
    this.on = require('./methods/on').bind(this)
    this.event = require('./methods/event').bind(this)
    this.reply = require('./methods/reply').bind(this)
    this.handler = require('./methods/handler').bind(this)
    this.uploadDocument = require('./methods/upload/document').bind(this)
    this.uploadPhoto = require('./methods/upload/photo').bind(this)
    this.uploadCover = require('./methods/upload/cover').bind(this)
    this.addScene = require('./methods/flow/add').bind(this)
    this.joinScene = require('./methods/flow/join').bind(this)
    this.nextScene = require('./methods/flow/next').bind(this)
    this.leaveScene = require('./methods/flow/leave').bind(this)
    this.listen = require('./methods/listen').bind(this)
    this.execute = require('./methods/execute').bind(this)
    this.executeHandler = require('./utils/executeHandler')
    this.getLastMessage = require('./utils/getLastMessage')

    setInterval(() => {
      this.executeHandler(this.methods)
      this.methods = []
    }, (1000 / 20))
  }

  get options () {
    return this.getOptions()
  }

  set options (settings) {
    return this.setOptions(settings)
  }

  static execute (method, settings, callback) {
    return this.execute(method, settings, callback)
  }

  async before (callback) {
    return await this.before(callback)
  }

  deleteOptions (keys) {
    return this.deleteOptions(keys)
  }

  use (callback) {
    return this.use(callback)
  }

  command (command, callback) {
    return this.command(command, callback)
  }

  hears (command, callback) {
    return this.hears(command, callback)
  }

  on (callback) {
    return this.on(callback)
  }

  event (event, callback) {
    return this.event(event, callback)
  }

  reply (userId, message, attachment, callback) {
    return this.reply(userId, message, attachment, callback)
  }

  handler (ctx) {
    return this.handler(ctx)
  }

  uploadDocument (file) {
    return this.uploadDocument(file)
  }

  uploadPhoto (file, peer_id) {
    return this.uploadPhoto(file, peer_id)
  }

  uploadCover (file, settings) {
    return this.uploadCover(file, settings)
  }

  addScene (name, ...callbacks) {
    return this.addScene(name, callbacks)
  }

  joinScene (ctx, scene, session, step, now) {
    return this.joinScene(ctx, scene, session, step, now)
  }

  leaveScene (ctx) {
    return this.leaveScene(ctx)
  }

  nextScene (ctx, session) {
    return this.nextScene(ctx, session)
  }

  listen (req, res) {
    return this.listen(req, res)
  }

  callback (methods, body) {
    return this.callback(methods, body)
  }
}
<commit_msg>delete async/await from class<commit_after>const { RedisClient, createClient, Multi } = require('redis')
const bluebird = require('bluebird')

bluebird.promisifyAll(RedisClient.prototype)
bluebird.promisifyAll(Multi.prototype)

module.exports = class Botact {
  constructor (settings) {
    const { confirmation, token, flowTimeout: timeout, redis = false, redisConfig = {} } = settings

    if (!confirmation) {
      throw new Error('confirmation is required')
    } else if (!token) {
      throw new Error('token is required')
    }

    this.flow = { scenes: {}, session: {}, timeout }
    this.actions = { commands: [], hears: [], events: [], on: [], middlewares: [] }
    this.methods = []
    this.settings = settings
    this.redis = redis && createClient(redisConfig)

    this.api = require('./api')
    this.getOptions = require('./methods/options/get').bind(this)
    this.setOptions = require('./methods/options/set').bind(this)
    this.deleteOptions = require('./methods/options/delete').bind(this)
    this.before = require('./methods/before').bind(this)
    this.use = require('./methods/use').bind(this)
    this.command = require('./methods/command').bind(this)
    this.hears = require('./methods/hears').bind(this)
    this.on = require('./methods/on').bind(this)
    this.event = require('./methods/event').bind(this)
    this.reply = require('./methods/reply').bind(this)
    this.handler = require('./methods/handler').bind(this)
    this.uploadDocument = require('./methods/upload/document').bind(this)
    this.uploadPhoto = require('./methods/upload/photo').bind(this)
    this.uploadCover = require('./methods/upload/cover').bind(this)
    this.addScene = require('./methods/flow/add').bind(this)
    this.joinScene = require('./methods/flow/join').bind(this)
    this.nextScene = require('./methods/flow/next').bind(this)
    this.leaveScene = require('./methods/flow/leave').bind(this)
    this.listen = require('./methods/listen').bind(this)
    this.execute = require('./methods/execute').bind(this)
    this.executeHandler = require('./utils/executeHandler')
    this.getLastMessage = require('./utils/getLastMessage')

    setInterval(() => {
      this.executeHandler(this.methods)
      this.methods = []
    }, (1000 / 20))
  }

  get options () {
    return this.getOptions()
  }

  set options (settings) {
    return this.setOptions(settings)
  }

  static execute (method, settings, callback) {
    return this.execute(method, settings, callback)
  }

  before (callback) {
    return this.before(callback)
  }

  deleteOptions (keys) {
    return this.deleteOptions(keys)
  }

  use (callback) {
    return this.use(callback)
  }

  command (command, callback) {
    return this.command(command, callback)
  }

  hears (command, callback) {
    return this.hears(command, callback)
  }

  on (callback) {
    return this.on(callback)
  }

  event (event, callback) {
    return this.event(event, callback)
  }

  reply (userId, message, attachment, callback) {
    return this.reply(userId, message, attachment, callback)
  }

  handler (ctx) {
    return this.handler(ctx)
  }

  uploadDocument (file) {
    return this.uploadDocument(file)
  }

  uploadPhoto (file, peer_id) {
    return this.uploadPhoto(file, peer_id)
  }

  uploadCover (file, settings) {
    return this.uploadCover(file, settings)
  }

  addScene (name, ...callbacks) {
    return this.addScene(name, callbacks)
  }

  joinScene (ctx, scene, session, step, now) {
    return this.joinScene(ctx, scene, session, step, now)
  }

  leaveScene (ctx) {
    return this.leaveScene(ctx)
  }

  nextScene (ctx, session) {
    return this.nextScene(ctx, session)
  }

  listen (req, res) {
    return this.listen(req, res)
  }

  callback (methods, body) {
    return this.callback(methods, body)
  }
}
<|endoftext|>


<commit_before>// This object is imported into the documentation site. An example for the documentation site should be part of the pull request for the component. The object key is the kabob case of the "URL folder". In the case of `http://localhost:8080/components/app-launcher/`, `app-launcher` is the `key`. The folder name is created by `components.component` value in `package.json`. The following uses webpack's raw-loader plugin to get "text files" that will be eval()'d by CodeMirror within the documentation site on page load.

/* eslint-env node */
/* eslint-disable global-require */

const siteStories = [
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/image-text.jsx'),
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/heading-message.jsx'),
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/heading-only.jsx'),
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/message-only.jsx'),
];

module.exports = siteStories;
<commit_msg>update site-stories<commit_after>// This object is imported into the documentation site. An example for the documentation site should be part of the pull request for the component. The object key is the kabob case of the "URL folder". In the case of `http://localhost:8080/components/app-launcher/`, `app-launcher` is the `key`. The folder name is created by `components.component` value in `package.json`. The following uses webpack's raw-loader plugin to get "text files" that will be eval()'d by CodeMirror within the documentation site on page load.

/* eslint-env node */
/* eslint-disable global-require */

const siteStories = [
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/small-image-text.jsx'),
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/large-image-text.jsx'),
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/heading-message.jsx'),
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/heading-only.jsx'),
	require('raw-loader!@salesforce/design-system-react/components/illustration/__examples__/message-only.jsx'),
];

module.exports = siteStories;
<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const project = require('../project.config')

const inProject = path.resolve.bind(path, project.basePath)
const inProjectSrc = (file) => inProject(project.srcDir, file)

const __DEV__ = project.env === 'development'
const __STAGE__ = project.env === 'stage'
const __TEST__ = project.env === 'test'
const __PROD__ = project.env === 'production'

const config = {
  entry: {
    normalize: [
      inProjectSrc('normalize'),
    ],
    main: [
      inProjectSrc(project.main),
    ],
  },
  devtool: project.sourcemaps ? 'source-map' : false,
  output: {
    path: inProject(project.outDir),
    filename: __DEV__ ? '[name].js' : '[name].[chunkhash].js',
    publicPath: project.publicPath,
  },
  resolve: {
    modules: [
      inProject(project.srcDir),
      'node_modules',
    ],
    extensions: ['*', '.js', '.jsx', '.json'],
  },
  externals: project.externals,
  module: {
    rules: [],
  },
  plugins: [
    new webpack.DefinePlugin(Object.assign({
      'process.env': { NODE_ENV: JSON.stringify(project.env) },
      __DEV__,
      __STAGE__,
      __TEST__,
      __PROD__,
    }, project.globals))
  ],
}

// JavaScript
// ------------------------------------
config.module.rules.push({
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: [{
    loader: 'babel-loader',
    query: {
      cacheDirectory: true,
      plugins: [
        'babel-plugin-transform-class-properties',
        'babel-plugin-syntax-dynamic-import',
        [
          'babel-plugin-transform-runtime',
          {
            helpers: true,
            polyfill: false, // we polyfill needed features in src/normalize.js
            regenerator: true,
          },
        ],
        [
          'babel-plugin-transform-object-rest-spread',
          {
            useBuiltIns: true // we polyfill Object.assign in src/normalize.js
          },
        ],
        ['import', { libraryName: 'antd', style: 'css' }],
        [
          'babel-plugin-js-logger',
          {
            "format": {
              'project': false,
              'separator': '.',
            },
          },
        ],
      ],
      presets: [
        'babel-preset-react',
        ['babel-preset-env', {
          modules: false,
          targets: {
            ie9: true,
          },
          uglify: true,
        }],
      ]
    },
  }],
})

// Styles
// ------------------------------------
const extractStyles = new ExtractTextPlugin({
  filename: 'styles/[name].[contenthash].css',
  allChunks: true,
  disable: __DEV__,
})

// local style, with '.module.sass/scss/css' suffix
config.module.rules.push({
  test: /\.module.(sass|scss|css)$/,
  loader: extractStyles.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          modules: true,
          localIdentName: "[name]__[local]___[hash:base64:5]",
          sourceMap: project.sourcemaps,
          minimize: {
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions'],
            },
            discardComments: {
              removeAll : true,
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: project.sourcemaps,
          },
        },
      },
      {
        loader: 'sass-loader',
        options: {
          sourceMap: project.sourcemaps,
          includePaths: [
            inProjectSrc('styles'),
          ],
        },
      }
    ],
  })
})

// global style
config.module.rules.push({
  test: /^((?!\.module).)*(sass|scss|css)$/,
  loader: extractStyles.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          sourceMap: project.sourcemaps,
          minimize: {
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions'],
            },
            discardComments: {
              removeAll : true,
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: project.sourcemaps,
          },
        },
      },
      {
        loader: 'sass-loader',
        options: {
          sourceMap: project.sourcemaps,
          includePaths: [
            inProjectSrc('styles'),
          ],
        },
      }
    ],
  })
})
config.plugins.push(extractStyles)

// Images
// ------------------------------------
config.module.rules.push({
  test    : /\.(png|jpg|gif)$/,
  loader  : 'url-loader',
  options : {
    limit : 8192,
  },
})

// Fonts
// ------------------------------------
;[
  ['woff', 'application/font-woff'],
  ['woff2', 'application/font-woff2'],
  ['otf', 'font/opentype'],
  ['ttf', 'application/octet-stream'],
  ['eot', 'application/vnd.ms-fontobject'],
  ['svg', 'image/svg+xml'],
].forEach((font) => {
  const extension = font[0]
  const mimetype = font[1]

  config.module.rules.push({
    test    : new RegExp(`\\.${extension}$`),
    loader  : 'url-loader',
    options : {
      name  : 'fonts/[name].[ext]',
      limit : 10000,
      mimetype,
    },
  })
})

// HTML Template
// ------------------------------------
config.plugins.push(new HtmlWebpackPlugin({
  template: inProjectSrc('index.html'),
  inject: true,
  minify: {
    collapseWhitespace: true,
  },
}))

// Development Tools
// ------------------------------------
if (__DEV__) {
  config.entry.main.push(
    `webpack-hot-middleware/client.js?path=${config.output.publicPath}__webpack_hmr`
  )
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin()
  )
}

// Bundle Splitting
// ------------------------------------
if (!__TEST__) {
  const bundles = ['normalize', 'manifest']

  if (project.vendors && project.vendors.length) {
    bundles.unshift('vendor')
    config.entry.vendor = project.vendors
  }
  config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ names: bundles }))
}

// Production Optimizations
// ------------------------------------
if (__PROD__ || __STAGE__) {
  config.plugins.push(
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: !!config.devtool,
      comments: false,
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
      },
    })
  )
}

module.exports = config
<commit_msg>webpack: add less support<commit_after>const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const project = require('../project.config')

const inProject = path.resolve.bind(path, project.basePath)
const inProjectSrc = (file) => inProject(project.srcDir, file)

const __DEV__ = project.env === 'development'
const __STAGE__ = project.env === 'stage'
const __TEST__ = project.env === 'test'
const __PROD__ = project.env === 'production'

const config = {
  entry: {
    normalize: [
      inProjectSrc('normalize'),
    ],
    main: [
      inProjectSrc(project.main),
    ],
  },
  devtool: project.sourcemaps ? 'source-map' : false,
  output: {
    path: inProject(project.outDir),
    filename: __DEV__ ? '[name].js' : '[name].[chunkhash].js',
    publicPath: project.publicPath,
  },
  resolve: {
    modules: [
      inProject(project.srcDir),
      'node_modules',
    ],
    extensions: ['*', '.js', '.jsx', '.json'],
  },
  externals: project.externals,
  module: {
    rules: [],
  },
  plugins: [
    new webpack.DefinePlugin(Object.assign({
      'process.env': { NODE_ENV: JSON.stringify(project.env) },
      __DEV__,
      __STAGE__,
      __TEST__,
      __PROD__,
    }, project.globals))
  ],
}

// JavaScript
// ------------------------------------
config.module.rules.push({
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: [{
    loader: 'babel-loader',
    query: {
      cacheDirectory: true,
      plugins: [
        'babel-plugin-transform-class-properties',
        'babel-plugin-syntax-dynamic-import',
        [
          'babel-plugin-transform-runtime',
          {
            helpers: true,
            polyfill: false, // we polyfill needed features in src/normalize.js
            regenerator: true,
          },
        ],
        [
          'babel-plugin-transform-object-rest-spread',
          {
            useBuiltIns: true // we polyfill Object.assign in src/normalize.js
          },
        ],
        ['import', { libraryName: 'antd', style: 'css' }],
        [
          'babel-plugin-js-logger',
          {
            "format": {
              'project': false,
              'separator': '.',
            },
          },
        ],
      ],
      presets: [
        'babel-preset-react',
        ['babel-preset-env', {
          modules: false,
          targets: {
            ie9: true,
          },
          uglify: true,
        }],
      ]
    },
  }],
})

// Styles
// ------------------------------------
const extractStyles = new ExtractTextPlugin({
  filename: 'styles/[name].[contenthash].css',
  allChunks: true,
  disable: __DEV__,
})

// local style, with '.module.sass/scss/css' suffix
config.module.rules.push({
  test: /\.module.(sass|scss|css)$/,
  loader: extractStyles.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          modules: true,
          localIdentName: "[name]__[local]___[hash:base64:5]",
          sourceMap: project.sourcemaps,
          minimize: {
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions'],
            },
            discardComments: {
              removeAll : true,
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: project.sourcemaps,
          },
        },
      },
      {
        loader: 'sass-loader',
        options: {
          sourceMap: project.sourcemaps,
          includePaths: [
            inProjectSrc('styles'),
          ],
        },
      }
    ],
  })
})

config.module.rules.push({
  test: /\.module.(less)$/,
  loader: extractStyles.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          modules: true,
          localIdentName: "[name]__[local]___[hash:base64:5]",
          sourceMap: project.sourcemaps,
          minimize: {
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions'],
            },
            discardComments: {
              removeAll : true,
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: project.sourcemaps,
          },
        },
      },
      {
        loader: 'less-loader',
        options: {
        },
      }
    ],
  })
})

// global style
config.module.rules.push({
  test: /^((?!\.module).)*(sass|scss|css)$/,
  loader: extractStyles.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          sourceMap: project.sourcemaps,
          minimize: {
            autoprefixer: {
              add: true,
              remove: true,
              browsers: ['last 2 versions'],
            },
            discardComments: {
              removeAll : true,
            },
            discardUnused: false,
            mergeIdents: false,
            reduceIdents: false,
            safe: true,
            sourcemap: project.sourcemaps,
          },
        },
      },
      {
        loader: 'sass-loader',
        options: {
          sourceMap: project.sourcemaps,
          includePaths: [
            inProjectSrc('styles'),
          ],
        },
      }
    ],
  })
})
config.plugins.push(extractStyles)

// Images
// ------------------------------------
config.module.rules.push({
  test    : /\.(png|jpg|gif)$/,
  loader  : 'url-loader',
  options : {
    limit : 8192,
  },
})

// Fonts
// ------------------------------------
;[
  ['woff', 'application/font-woff'],
  ['woff2', 'application/font-woff2'],
  ['otf', 'font/opentype'],
  ['ttf', 'application/octet-stream'],
  ['eot', 'application/vnd.ms-fontobject'],
  ['svg', 'image/svg+xml'],
].forEach((font) => {
  const extension = font[0]
  const mimetype = font[1]

  config.module.rules.push({
    test    : new RegExp(`\\.${extension}$`),
    loader  : 'url-loader',
    options : {
      name  : 'fonts/[name].[ext]',
      limit : 10000,
      mimetype,
    },
  })
})

// HTML Template
// ------------------------------------
config.plugins.push(new HtmlWebpackPlugin({
  template: inProjectSrc('index.html'),
  inject: true,
  minify: {
    collapseWhitespace: true,
  },
}))

// Development Tools
// ------------------------------------
if (__DEV__) {
  config.entry.main.push(
    `webpack-hot-middleware/client.js?path=${config.output.publicPath}__webpack_hmr`
  )
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin()
  )
}

// Bundle Splitting
// ------------------------------------
if (!__TEST__) {
  const bundles = ['normalize', 'manifest']

  if (project.vendors && project.vendors.length) {
    bundles.unshift('vendor')
    config.entry.vendor = project.vendors
  }
  config.plugins.push(new webpack.optimize.CommonsChunkPlugin({ names: bundles }))
}

// Production Optimizations
// ------------------------------------
if (__PROD__ || __STAGE__) {
  config.plugins.push(
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: !!config.devtool,
      comments: false,
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
      },
    })
  )
}

module.exports = config
<|endoftext|>


<commit_before>'use babel'
/* globals atom */

import kd from 'kd.js'
import debug from 'debug'
import KD from './kd-states'
import PromptView from './views/prompt-view'
import TeamSelector from './views/team-selector'
import MachineSettings from './views/machine-settings'
import MountSettings from './views/mount-settings'
import getTeams from './utils/get-teams'
import getMachines from './utils/get-machines'
import getMounts from './utils/get-mounts'
import showTreeView from './utils/show-tree-view'
import StatusBarIcon from './views/statusbar-icon'
import kdRun from './utils/kd-run'
import setMountIcons from './utils/set-mount-icons'

const log = debug('kd-controller:log')
const error = debug('kd:err')

export default class KDController extends kd.Object {
  constructor (serializedState = {}) {
    super({}, serializedState)
    KD.init()

    this.machinePanel = null
    this.mountPanel = null
  }

  showLoading (message, duration) {
    KD.emitter.emit('kd-state-loading', message)
    if (duration) {
      setTimeout(this.bound('hideLoading'), duration)
    }
  }

  hideLoading () {
    KD.emitter.emit('kd-state-loading-finished')
  }

  showPrompt (prompts, callback) {
    let view = new PromptView(prompts)

    let panel = atom.workspace.addModalPanel({
      className: 'kd-loading-modal',
      item: view,
      visible: true,
      priority: 201
    })
    view.emitter.on('prompt-given', userInputs => {
      callback(null, userInputs)
    })
    view.emitter.on('prompt-cancelled', () => {
      callback(true)
    })
    return panel
  }

  _err (e) {
    this.hideLoading()

    atom.notifications.addFatalError(`kd: ${e}`, {
      dismissable: true,
      stack: e.stack
    })

    error(e)
  }

  _showSelector (items, selector) {
    this.hideLoading()
    selector.getItem().setItems(items)
    selector.getItem().attached()
    selector.show()
  }

  hideSelectors () {
    this.teamSelector && this.teamSelector.hide()
    this.machineSelector && this.machineSelector.hide()
    this.mountSelector && this.mountSelector.hide()
  }

  showTeamsSelector (teams, options = {}) {
    if (this.teamSelector) {
      return this._showSelector(teams, this.teamSelector)
    }

    let view = new TeamSelector({ items: teams, label: 'team' })
    this.teamSelector = atom.workspace.addModalPanel({
      className: 'kd-team-selector',
      item: view,
      visible: true,
      priority: 201
    })
    view.emitter.on('teamSelector-cancelled', event => {
      this.teamSelector.hide()
      options.onCancel && options.onCancel()
    })
    view.emitter.on('teamSelector-confirmed', team => {
      this.teamSelector.hide()
      options.onConfirm && options.onConfirm(team)
    })

    return teams
  }

  async showTeams () {
    log('showTeams')
    this.showLoading('Loading teams…')

    let teams
    try {
      teams = await getTeams()
      this.getData().teams = teams
    } catch (e) { return this._err(e) }

    this.showLoading('Selecting team…')
    this.showTeamsSelector(teams, {
      onConfirm: team => {
        this.getData().team = team
        this.showMachines(team.slug)
      },
      onCancel: this.bound('hideLoading')
    })
  }

  destroyPanel (type) {
    const panel = this[`${type}Panel`]

    panel && panel.destroy()

    this[`${type}Panel`] = null
  }

  showMachineSettingsView (machines, options = {}) {
    const {
      filterValue,
      onMount,
      onAlwaysOnChange,
      onPowerChange,
      onShowLogs,
    } = options

    const view = new MachineSettings({ machines, filterValue })

    this.machinePanel = atom.workspace.addBottomPanel({
      className: 'kd-machine-selector',
      item: view,
      visible: true,
      priority: 201
    })

    view.emitter.on('machine-settings:close', () => {
      this.destroyPanel('machine')
    })

    view.emitter.on('machine-settings:open-terminal', ({ machine }) => {
      this.openTerminal({ machine })
    })

    view.emitter.on('machine-settings:reload', () => {
      this.showMachines(null, true)
      this.destroyPanel('machine')
    })

    if (onMount) {
      view.emitter.on('machine-settings:mount', onMount)
    }
    if (onAlwaysOnChange) {
      view.emitter.on('machine-settings:always-on-change', onAlwaysOnChange)
    }
    if (onPowerChange) {
      view.emitter.on('machine-settings:power-change', onPowerChange)
    }
    if (onShowLogs) {
      view.emitter.on('machine-settings:show-logs', onShowLogs)
    }
  }

  async showMachines (team = null, reload = false, filterValue = '') {
    log('show machine settings')
    this.showLoading('Loading machines…')

    let machines = this.getData().machines
    if (!machines || reload) {
      try {
        machines = await getMachines(team)
        this.getData().machines = machines
      } catch (e) { return this._err(e) }
    }

    this.hideLoading()

    this.showMachineSettingsView(machines, {
      filterValue,
      onAlwaysOnChange: this.bound('setAlwaysOn'),
      onPowerChange: this.bound('setPowerState'),
      onShowLogs: this.bound('showBuildLogs'),
      onMount: this.bound('onMount'),
      onCancel: this.bound('hideLoading')
    })
  }

  setAlwaysOn ({ machine, state }) {
    log('set always on not implemented yet', { state })
  }

  setPowerState ({ machine, state }) {
    const cmd = state ? 'start' : 'stop'

    this.showLoading(`${state ? 'Starting' : 'Stopping'} machine…`)

    kdRun(`machine ${cmd} ${machine.alias}`)
      .then(() => {
        this.hideLoading()
        this.showMachines(null, true)
        this.destroyPanel('machine')
      })
      .catch(err => {
        this.hideLoading()
        atom.notifications.addError(err.message, {
          stack: err.stack ? err.stack : null
        })
      })

    log('set power state not implemented yet', { state })
  }

  showBuildLogs ({ machine }) {
    log('show build logs not implemented yet', { machine })
  }

  onMount ({ machine }) {
    this.getData().machine = machine
    this.showMountPrompt(machine)
  }

  openTerminal ({ machine }) {
    // implement initial command based on machine
    let activeEditor = atom.views.getView(
      atom.workspace.getActiveTextEditor()
    )
    atom.commands.dispatch(activeEditor, 'atom-terminal:open')
  }

  runMountCmd (machine, options = {}) {
    const { remote, local, onConfirm, onError } = options

    kdRun(['machine', 'mount', remote, local])
      .then(result => {
        onConfirm && onConfirm()
      }).catch(e => {
        onError && onError(e)
      })
  }

  showMountPrompt (machine) {
    const localBasePath = atom.config.get('kd.localBasePath')
    const localPath = `${localBasePath}/${machine.team}/${machine.label}`
    const remotePath = `/home/${machine.owner || machine.username}`

    this.showLoading('Selecting folders…')
    const panel = this.showPrompt({
      prompts: makePrompts(remotePath, localPath),
      callback: (err, inputs) => {
        panel.destroy()
        this.hideLoading()

        if (err) { return }

        const { localPath, remotePath } = inputs
        const remoteAddress = `${machine.id}:${remotePath}`

        this.showLoading('Mounting…')

        this.runMountCmd(machine, {
          remote: remoteAddress,
          local: localPath,
          onConfirm: () => {
            this.hideLoading()
            atom.notifications.addSuccess(getMountedMessage())
            atom.workspace.project.addPath(localPath)
            showTreeView()
          },
          onError: err => {
            this.hideLoading()
            atom.notifications.addError(getMountError(), {
              stack: err.stack
            })
          }
        })
      }
    })
  }

  showMountSettingsView (mounts, machines, options = {}) {
    this.mountPanel = atom.workspace.addBottomPanel({
      className: 'kd-machine-selector',
      item: new MountSettings({
        mounts,
        machines,
        options: {
          ...options,
          onClose: () => this.destroyPanel('mount')
        }
      }),
      visible: true,
      priority: 201
    })
  }

  async showMounts () {
    log('show mounts settings')
    this.showLoading('Loading mounts…')

    let mounts, machines
    try {
      mounts = await getMounts()
      machines = await getMachines()
      this.getData().mounts = mounts
      this.getData().machines = machines
      setMountIcons(mounts)
    } catch (e) { return this._err(e) }

    this.hideLoading()

    const { workspace, notifications } = atom

    this.showMountSettingsView(mounts, machines, {
      onClose: () => {
        this.hideLoading()
        this.destroyPanel('mount')
      },
      onReload: () => {
        this.showMounts()
        this.destroyPanel('mount')
      },
      onShowMachine: ({ machine }) => {
        log('on show machine', machine)
        this.hideLoading()
        this.destroyPanel('mount')
        this.showMachines(null, false, machine.alias)
      },
      onOpen: ({ mount }) => {
        log('on open mount', mount)
        this.getData().mount = mount
        workspace.project.addPath(mount.mount.path)
        showTreeView()
        setMountIcons(mounts)
      },
      onNewWindow: ({ mount }) => {
        log('on open mount in new window', mount)
        atom.open({ pathsToOpen: mount.mount.path, newWindow: true })
      },
      onUnmount: ({ mount }) => {
        log('on unmount', mount)
        this.showLoading('Unmounting…')
        kdRun(['umount', mount.id])
          .then(() => {
            this.hideLoading()
            notifications.addSuccess(`${mount.label} unmounted successfully`)
            this.destroyPanel('mount')
          })
          .catch(err => {
            this.hideLoading()
            notifications.addError(
              `Error while trying to unmount ${mount.label}`,
              { stack: err.stack }
            )
          })
      }
    })
  }

  consumeStatusBar (statusBar) {
    this.statusBarItem = new StatusBarIcon({
      callback: (method) => { this[method] && this[method]() }
    })
    this.statusBarTile = statusBar.addRightTile({
      item: this.statusBarItem,
      priority: 100
    })
  }

  destroy () {
    this.statusBarTile.destroy()
    this.statusBarItem.destroy()
    this.statusBarTile = null
    this.statusBarItem = null

    this.destroyPanel('machine')
    this.destroyPanel('mount')

    super.destroy()
  }
}

const getMountedMessage = () =>
  `Machine mounted, preparing the mount please wait…`

const getMountError = () => `Machine could not be mounted, rolling back…`

const makePrompts = (remote, local) => (
  [
    {
      name: 'localPath',
      title: 'Local path:',
      defaultValue: local,
      placeholder: local
    },
    {
      name: 'remotePath',
      title: 'Remote path:',
      defaultValue: remote,
      placeholder: remote
    }
  ]
)
<commit_msg>destroy panels before showing them<commit_after>'use babel'
/* globals atom */

import kd from 'kd.js'
import debug from 'debug'
import KD from './kd-states'
import PromptView from './views/prompt-view'
import TeamSelector from './views/team-selector'
import MachineSettings from './views/machine-settings'
import MountSettings from './views/mount-settings'
import getTeams from './utils/get-teams'
import getMachines from './utils/get-machines'
import getMounts from './utils/get-mounts'
import showTreeView from './utils/show-tree-view'
import StatusBarIcon from './views/statusbar-icon'
import kdRun from './utils/kd-run'
import setMountIcons from './utils/set-mount-icons'

const log = debug('kd-controller:log')
const error = debug('kd:err')

export default class KDController extends kd.Object {
  constructor (serializedState = {}) {
    super({}, serializedState)
    KD.init()

    this.machinePanel = null
    this.mountPanel = null
  }

  showLoading (message, duration) {
    KD.emitter.emit('kd-state-loading', message)
    if (duration) {
      setTimeout(this.bound('hideLoading'), duration)
    }
  }

  hideLoading () {
    KD.emitter.emit('kd-state-loading-finished')
  }

  showPrompt (prompts, callback) {
    let view = new PromptView(prompts)

    let panel = atom.workspace.addModalPanel({
      className: 'kd-loading-modal',
      item: view,
      visible: true,
      priority: 201
    })
    view.emitter.on('prompt-given', userInputs => {
      callback(null, userInputs)
    })
    view.emitter.on('prompt-cancelled', () => {
      callback(true)
    })
    return panel
  }

  _err (e) {
    this.hideLoading()

    atom.notifications.addFatalError(`kd: ${e}`, {
      dismissable: true,
      stack: e.stack
    })

    error(e)
  }

  _showSelector (items, selector) {
    this.hideLoading()
    selector.getItem().setItems(items)
    selector.getItem().attached()
    selector.show()
  }

  hideSelectors () {
    this.teamSelector && this.teamSelector.hide()
    this.machineSelector && this.machineSelector.hide()
    this.mountSelector && this.mountSelector.hide()
  }

  showTeamsSelector (teams, options = {}) {
    if (this.teamSelector) {
      return this._showSelector(teams, this.teamSelector)
    }

    let view = new TeamSelector({ items: teams, label: 'team' })
    this.teamSelector = atom.workspace.addModalPanel({
      className: 'kd-team-selector',
      item: view,
      visible: true,
      priority: 201
    })
    view.emitter.on('teamSelector-cancelled', event => {
      this.teamSelector.hide()
      options.onCancel && options.onCancel()
    })
    view.emitter.on('teamSelector-confirmed', team => {
      this.teamSelector.hide()
      options.onConfirm && options.onConfirm(team)
    })

    return teams
  }

  async showTeams () {
    log('showTeams')
    this.showLoading('Loading teams…')

    let teams
    try {
      teams = await getTeams()
      this.getData().teams = teams
    } catch (e) { return this._err(e) }

    this.showLoading('Selecting team…')
    this.showTeamsSelector(teams, {
      onConfirm: team => {
        this.getData().team = team
        this.showMachines(team.slug)
      },
      onCancel: this.bound('hideLoading')
    })
  }

  destroyPanel (type) {
    const panel = this[`${type}Panel`]

    panel && panel.destroy()

    this[`${type}Panel`] = null
  }

  showMachineSettingsView (machines, options = {}) {
    const {
      filterValue,
      onMount,
      onAlwaysOnChange,
      onPowerChange,
      onShowLogs,
    } = options

    const view = new MachineSettings({ machines, filterValue })

    this.destroyPanel('machine')

    this.machinePanel = atom.workspace.addBottomPanel({
      className: 'kd-machine-selector',
      item: view,
      visible: true,
      priority: 201
    })

    view.emitter.on('machine-settings:close', () => {
      this.destroyPanel('machine')
    })

    view.emitter.on('machine-settings:open-terminal', ({ machine }) => {
      this.openTerminal({ machine })
    })

    view.emitter.on('machine-settings:reload', () => {
      this.showMachines(null, true)
      this.destroyPanel('machine')
    })

    if (onMount) {
      view.emitter.on('machine-settings:mount', onMount)
    }
    if (onAlwaysOnChange) {
      view.emitter.on('machine-settings:always-on-change', onAlwaysOnChange)
    }
    if (onPowerChange) {
      view.emitter.on('machine-settings:power-change', onPowerChange)
    }
    if (onShowLogs) {
      view.emitter.on('machine-settings:show-logs', onShowLogs)
    }
  }

  async showMachines (team = null, reload = false, filterValue = '') {
    log('show machine settings')
    this.showLoading('Loading machines…')

    let machines = this.getData().machines
    if (!machines || reload) {
      try {
        machines = await getMachines(team)
        this.getData().machines = machines
      } catch (e) { return this._err(e) }
    }

    this.hideLoading()

    this.showMachineSettingsView(machines, {
      filterValue,
      onAlwaysOnChange: this.bound('setAlwaysOn'),
      onPowerChange: this.bound('setPowerState'),
      onShowLogs: this.bound('showBuildLogs'),
      onMount: this.bound('onMount'),
      onCancel: this.bound('hideLoading')
    })
  }

  setAlwaysOn ({ machine, state }) {
    log('set always on not implemented yet', { state })
  }

  setPowerState ({ machine, state }) {
    const cmd = state ? 'start' : 'stop'

    this.showLoading(`${state ? 'Starting' : 'Stopping'} machine…`)

    kdRun(`machine ${cmd} ${machine.alias}`)
      .then(() => {
        this.hideLoading()
        this.showMachines(null, true)
        this.destroyPanel('machine')
      })
      .catch(err => {
        this.hideLoading()
        atom.notifications.addError(err.message, {
          stack: err.stack ? err.stack : null
        })
      })

    log('set power state not implemented yet', { state })
  }

  showBuildLogs ({ machine }) {
    log('show build logs not implemented yet', { machine })
  }

  onMount ({ machine }) {
    this.getData().machine = machine
    this.showMountPrompt(machine)
  }

  openTerminal ({ machine }) {
    // implement initial command based on machine
    let activeEditor = atom.views.getView(
      atom.workspace.getActiveTextEditor()
    )
    atom.commands.dispatch(activeEditor, 'atom-terminal:open')
  }

  runMountCmd (machine, options = {}) {
    const { remote, local, onConfirm, onError } = options

    kdRun(['machine', 'mount', remote, local])
      .then(result => {
        onConfirm && onConfirm()
      }).catch(e => {
        onError && onError(e)
      })
  }

  showMountPrompt (machine) {
    const localBasePath = atom.config.get('kd.localBasePath')
    const localPath = `${localBasePath}/${machine.team}/${machine.label}`
    const remotePath = `/home/${machine.owner || machine.username}`

    this.showLoading('Selecting folders…')
    const panel = this.showPrompt({
      prompts: makePrompts(remotePath, localPath),
      callback: (err, inputs) => {
        panel.destroy()
        this.hideLoading()

        if (err) { return }

        const { localPath, remotePath } = inputs
        const remoteAddress = `${machine.id}:${remotePath}`

        this.showLoading('Mounting…')

        this.runMountCmd(machine, {
          remote: remoteAddress,
          local: localPath,
          onConfirm: () => {
            this.hideLoading()
            atom.notifications.addSuccess(getMountedMessage())
            atom.workspace.project.addPath(localPath)
            showTreeView()
          },
          onError: err => {
            this.hideLoading()
            atom.notifications.addError(getMountError(), {
              stack: err.stack
            })
          }
        })
      }
    })
  }

  showMountSettingsView (mounts, machines, options = {}) {
    this.destroyPanel('mount')
    this.mountPanel = atom.workspace.addBottomPanel({
      className: 'kd-machine-selector',
      item: new MountSettings({
        mounts,
        machines,
        options: {
          ...options,
          onClose: () => this.destroyPanel('mount')
        }
      }),
      visible: true,
      priority: 201
    })
  }

  async showMounts () {
    log('show mounts settings')
    this.showLoading('Loading mounts…')

    let mounts, machines
    try {
      mounts = await getMounts()
      machines = await getMachines()
      this.getData().mounts = mounts
      this.getData().machines = machines
      setMountIcons(mounts)
    } catch (e) { return this._err(e) }

    this.hideLoading()

    const { workspace, notifications } = atom

    this.showMountSettingsView(mounts, machines, {
      onClose: () => {
        this.hideLoading()
        this.destroyPanel('mount')
      },
      onReload: () => {
        this.showMounts()
        this.destroyPanel('mount')
      },
      onShowMachine: ({ machine }) => {
        log('on show machine', machine)
        this.hideLoading()
        this.destroyPanel('mount')
        this.showMachines(null, false, machine.alias)
      },
      onOpen: ({ mount }) => {
        log('on open mount', mount)
        this.getData().mount = mount
        workspace.project.addPath(mount.mount.path)
        showTreeView()
        setMountIcons(mounts)
      },
      onNewWindow: ({ mount }) => {
        log('on open mount in new window', mount)
        atom.open({ pathsToOpen: mount.mount.path, newWindow: true })
      },
      onUnmount: ({ mount }) => {
        log('on unmount', mount)
        this.showLoading('Unmounting…')
        kdRun(['umount', mount.id])
          .then(() => {
            this.hideLoading()
            notifications.addSuccess(`${mount.label} unmounted successfully`)
            this.destroyPanel('mount')
          })
          .catch(err => {
            this.hideLoading()
            notifications.addError(
              `Error while trying to unmount ${mount.label}`,
              { stack: err.stack }
            )
          })
      }
    })
  }

  consumeStatusBar (statusBar) {
    this.statusBarItem = new StatusBarIcon({
      callback: (method) => { this[method] && this[method]() }
    })
    this.statusBarTile = statusBar.addRightTile({
      item: this.statusBarItem,
      priority: 100
    })
  }

  destroy () {
    this.statusBarTile.destroy()
    this.statusBarItem.destroy()
    this.statusBarTile = null
    this.statusBarItem = null

    this.destroyPanel('machine')
    this.destroyPanel('mount')

    super.destroy()
  }
}

const getMountedMessage = () =>
  `Machine mounted, preparing the mount please wait…`

const getMountError = () => `Machine could not be mounted, rolling back…`

const makePrompts = (remote, local) => (
  [
    {
      name: 'localPath',
      title: 'Local path:',
      defaultValue: local,
      placeholder: local
    },
    {
      name: 'remotePath',
      title: 'Remote path:',
      defaultValue: remote,
      placeholder: remote
    }
  ]
)
<|endoftext|>


<commit_before>// Contains the "demo framework", along with some of the more simple demos.

(function(exports) {
    "use strict";

    // Creates a server instance for each demo, and sets up "demo things".
    // It sizes each server according to the containing element, adds the
    // stipple pattern, and (optionally) adds the inspector as well.
    function bootstrapDemo(demo, elem) {
        var demoSlot = document.createElement("div");
        demoSlot.style = demo.style;
        demoSlot.classList.add('demo-' + demo.name);
        elem.insertBefore(demoSlot, elem.firstChild);
        return demoSlot;
    }

    var demos = {};

    var ArticleDemos = {};
    ArticleDemos.registerDemo = function(name, style, func) {
        demos[name] = { name: name, func: func, style: style };
    };

    function findDemo(demoName) {
        var demo = demos[demoName];
        if (!demo)
            console.error("Unknown demo: " + demoName);
        return demo;
    }
    ArticleDemos.runServerDemo = function(elem) {
        var demoName = elem.dataset.demo;
        var demo = findDemo(demoName);
        var demoFunc = demo.func;
        var demoSlot = bootstrapDemo(demo, elem);
        var server = new Server();
        server.resize(demoSlot.clientWidth, demoSlot.clientHeight);
        demoSlot.appendChild(server.elem);
        var res = { server: server, elem: elem };
        demoFunc(res);
    };
    ArticleDemos.runCanvasDemo = function(elem) {
        var demoName = elem.dataset.demo;
        var demo = findDemo(demoName);
        if (!demo)
            return;
        var demoFunc = demo.func;
        var demoSlot = bootstrapDemo(demo, elem);
        var canvas = document.createElement('canvas');
        canvas.width = demoSlot.clientWidth;
        canvas.height = demoSlot.clientHeight;
        demoSlot.appendChild(canvas);
        var res = { canvas: canvas, elem: elem, demoSlot: demoSlot };
        demoFunc(res);
    };

    // The "main" function of the article. Goes over all the demo elements
    // the article's source code and runs the according demo for them.
    ArticleDemos.runAllDemos = function() {
        var elems;
        elems = document.querySelectorAll(".demo-server");
        [].forEach.call(elems, ArticleDemos.runServerDemo);
        elems = document.querySelectorAll(".demo-canvas");
        [].forEach.call(elems, ArticleDemos.runCanvasDemo);
    };

    exports.ArticleDemos = ArticleDemos;

})(window);
<commit_msg>demos: You aren't allowed to set style directly<commit_after>// Contains the "demo framework", along with some of the more simple demos.

(function(exports) {
    "use strict";

    // Creates a server instance for each demo, and sets up "demo things".
    // It sizes each server according to the containing element, adds the
    // stipple pattern, and (optionally) adds the inspector as well.
    function bootstrapDemo(demo, elem) {
        var demoSlot = document.createElement("div");
        demoSlot.setAttribute('style', demo.style);
        demoSlot.classList.add('demo-' + demo.name);
        elem.insertBefore(demoSlot, elem.firstChild);
        return demoSlot;
    }

    var demos = {};

    var ArticleDemos = {};
    ArticleDemos.registerDemo = function(name, style, func) {
        demos[name] = { name: name, func: func, style: style };
    };

    function findDemo(demoName) {
        var demo = demos[demoName];
        if (!demo)
            console.error("Unknown demo: " + demoName);
        return demo;
    }
    ArticleDemos.runServerDemo = function(elem) {
        var demoName = elem.dataset.demo;
        var demo = findDemo(demoName);
        var demoFunc = demo.func;
        var demoSlot = bootstrapDemo(demo, elem);
        var server = new Server();
        server.resize(demoSlot.clientWidth, demoSlot.clientHeight);
        demoSlot.appendChild(server.elem);
        var res = { server: server, elem: elem };
        demoFunc(res);
    };
    ArticleDemos.runCanvasDemo = function(elem) {
        var demoName = elem.dataset.demo;
        var demo = findDemo(demoName);
        if (!demo)
            return;
        var demoFunc = demo.func;
        var demoSlot = bootstrapDemo(demo, elem);
        var canvas = document.createElement('canvas');
        canvas.width = demoSlot.clientWidth;
        canvas.height = demoSlot.clientHeight;
        demoSlot.appendChild(canvas);
        var res = { canvas: canvas, elem: elem, demoSlot: demoSlot };
        demoFunc(res);
    };

    // The "main" function of the article. Goes over all the demo elements
    // the article's source code and runs the according demo for them.
    ArticleDemos.runAllDemos = function() {
        var elems;
        elems = document.querySelectorAll(".demo-server");
        [].forEach.call(elems, ArticleDemos.runServerDemo);
        elems = document.querySelectorAll(".demo-canvas");
        [].forEach.call(elems, ArticleDemos.runCanvasDemo);
    };

    exports.ArticleDemos = ArticleDemos;

})(window);
<|endoftext|>


<commit_before>//= wrapped

angular.module('streama').controller('adminReportsCtrl', [
  'apiService', '$state', '$rootScope', '$filter', function (apiService, $state, $rootScope, $filter) {
    var vm = this;
    var selectedReports = [];

    vm.maxPerPage = 15;
    vm.pagination = {};
    vm.sortAndOrderBy = {
      sort: 'dateCreated',
      order: 'DESC'
    };

    var currentOffset = 0;

    vm.resolveMultiple = resolveMultiple;
    vm.resolve = resolve;
    vm.unresolve = unresolve;
    vm.pageChanged = pageChanged;
    vm.refreshList = refreshList;
    vm.addOrRemoveFromSelection = addOrRemoveFromSelection;

    function pageChanged () {

      currentOffset = vm.maxPerPage*(vm.pagination.currentPage-1);
      loadReports({max: vm.maxPerPage, filter: vm.listFilter, offset: currentOffset, sort: vm.sortAndOrderBy.sort, order: vm.sortAndOrderBy.order});
    }

    function refreshList (filter) {
      if (filter) {
        vm.listFilter = filter;
      }
      loadReports({max: vm.maxPerPage, filter: vm.listFilter, offset: currentOffset, sort: vm.sortAndOrderBy.sort, order: vm.sortAndOrderBy.order});
    }

    function loadReports (params) {
      vm.reports = [];
      vm.reportsCount = 0;
      apiService.report.list(params)
        .then(function (response) {
          vm.reports = response.data.reports;
          vm.reportsCount = response.data.count;
        }, function () {
          alertify.error('An error occurred.');
        });
    }

    function addOrRemoveFromSelection($event, report) {
      if($event.target.checked && report.resolved === false) {
        selectedReports.push(report.id);
      } else {
        _.remove(selectedReports, function(id) {
          return id === report.id;
        });
      }
    }

    function resolve(oldReport) {
      apiService.report.resolve(oldReport.id).then
      (function (response) {
        var newReport = response.data;
        oldReport.resolved = newReport.resolved;
        oldReport.lastUpdated = newReport.lastUpdated;
        alertify.success('Selected report has been resolved.');
      }, function () {
        alertify.error('Report could not be resolved.');
      });
      }

    function unresolve(oldReport) {
      apiService.report.unresolve(oldReport.id).then
      (function (response) {
        var newReport = response.data;
        oldReport.resolved = newReport.resolved;
        oldReport.lastUpdated = newReport.lastUpdated;
        alertify.success('Selected report has been unresolved.');
      }, function () {
        alertify.error('Report could not be unresolved.');
      });
    }

    function resolveMultiple() {
      if(selectedReports.length > 0) {
        var confirmText = "This will resolve all selected reports. Do you want to proceed?";
        alertify.set({ buttonReverse: true, labels: {ok: "Yes", cancel : "Cancel"}});
        alertify.confirm(confirmText, function (confirmed) {
          if(confirmed){
            apiService.report.resolveMultiple(selectedReports).then
            (function (response) {
              var newReports = response.data;
              _.forEach(newReports, function (newReport) {
                _.forEach(vm.reports, function (oldReport) {
                  if (newReport.id === oldReport.id) {
                    oldReport.resolved = newReport.resolved;
                    oldReport.lastUpdated = newReport.lastUpdated;
                  }
                });
              });
              selectedReports = [];
              alertify.success('Selected reports have been resolved.');
            }, function () {
              alertify.error('Reports could not be resolved.');
            });
          }
        });
      } else alertify.error('No reports selected.');
    }
    refreshList('all');
  }]);

<commit_msg>reset page to 1 when changing filter to fix bug<commit_after>//= wrapped

angular.module('streama').controller('adminReportsCtrl', [
  'apiService', '$state', '$rootScope', '$filter', function (apiService, $state, $rootScope, $filter) {
    var vm = this;
    var selectedReports = [];

    vm.maxPerPage = 15;
    vm.pagination = {};
    vm.sortAndOrderBy = {
      sort: 'dateCreated',
      order: 'DESC'
    };

    var currentOffset = 0;

    vm.resolveMultiple = resolveMultiple;
    vm.resolve = resolve;
    vm.unresolve = unresolve;
    vm.pageChanged = pageChanged;
    vm.refreshList = refreshList;
    vm.addOrRemoveFromSelection = addOrRemoveFromSelection;

    function pageChanged () {

      currentOffset = vm.maxPerPage*(vm.pagination.currentPage-1);
      loadReports({max: vm.maxPerPage, filter: vm.listFilter, offset: currentOffset, sort: vm.sortAndOrderBy.sort, order: vm.sortAndOrderBy.order});
    }

    function refreshList (filter) {
      if (filter) {
        vm.listFilter = filter;
        vm.pagination.currentPage = 1;
        currentOffset = 0;
      }
      loadReports({max: vm.maxPerPage, filter: vm.listFilter, offset: currentOffset, sort: vm.sortAndOrderBy.sort, order: vm.sortAndOrderBy.order});
    }

    function loadReports (params) {
      vm.reports = [];
      vm.reportsCount = 0;
      apiService.report.list(params)
        .then(function (response) {
          vm.reports = response.data.reports;
          vm.reportsCount = response.data.count;
        }, function () {
          alertify.error('An error occurred.');
        });
    }

    function addOrRemoveFromSelection($event, report) {
      if($event.target.checked && report.resolved === false) {
        selectedReports.push(report.id);
      } else {
        _.remove(selectedReports, function(id) {
          return id === report.id;
        });
      }
    }

    function resolve(oldReport) {
      apiService.report.resolve(oldReport.id).then
      (function (response) {
        var newReport = response.data;
        oldReport.resolved = newReport.resolved;
        oldReport.lastUpdated = newReport.lastUpdated;
        alertify.success('Selected report has been resolved.');
      }, function () {
        alertify.error('Report could not be resolved.');
      });
      }

    function unresolve(oldReport) {
      apiService.report.unresolve(oldReport.id).then
      (function (response) {
        var newReport = response.data;
        oldReport.resolved = newReport.resolved;
        oldReport.lastUpdated = newReport.lastUpdated;
        alertify.success('Selected report has been unresolved.');
      }, function () {
        alertify.error('Report could not be unresolved.');
      });
    }

    function resolveMultiple() {
      if(selectedReports.length > 0) {
        var confirmText = "This will resolve all selected reports. Do you want to proceed?";
        alertify.set({ buttonReverse: true, labels: {ok: "Yes", cancel : "Cancel"}});
        alertify.confirm(confirmText, function (confirmed) {
          if(confirmed){
            apiService.report.resolveMultiple(selectedReports).then
            (function (response) {
              var newReports = response.data;
              _.forEach(newReports, function (newReport) {
                _.forEach(vm.reports, function (oldReport) {
                  if (newReport.id === oldReport.id) {
                    oldReport.resolved = newReport.resolved;
                    oldReport.lastUpdated = newReport.lastUpdated;
                  }
                });
              });
              selectedReports = [];
              alertify.success('Selected reports have been resolved.');
            }, function () {
              alertify.error('Reports could not be resolved.');
            });
          }
        });
      } else alertify.error('No reports selected.');
    }
    refreshList('all');
  }]);

<|endoftext|>


<commit_before>console.warn('`resolve/lib/core` is deprecated; please use `is-core-module` directly');

var current = (process.versions && process.versions.node && process.versions.node.split('.')) || [];

function specifierIncluded(specifier) {
    var parts = specifier.split(' ');
    var op = parts.length > 1 ? parts[0] : '=';
    var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');

    for (var i = 0; i < 3; ++i) {
        var cur = parseInt(current[i] || 0, 10);
        var ver = parseInt(versionParts[i] || 0, 10);
        if (cur === ver) {
            continue; // eslint-disable-line no-restricted-syntax, no-continue
        }
        if (op === '<') {
            return cur < ver;
        } else if (op === '>=') {
            return cur >= ver;
        } else {
            return false;
        }
    }
    return op === '>=';
}

function matchesRange(range) {
    var specifiers = range.split(/ ?&& ?/);
    if (specifiers.length === 0) { return false; }
    for (var i = 0; i < specifiers.length; ++i) {
        if (!specifierIncluded(specifiers[i])) { return false; }
    }
    return true;
}

function versionIncluded(specifierValue) {
    if (typeof specifierValue === 'boolean') { return specifierValue; }
    if (specifierValue && typeof specifierValue === 'object') {
        for (var i = 0; i < specifierValue.length; ++i) {
            if (matchesRange(specifierValue[i])) { return true; }
        }
        return false;
    }
    return matchesRange(specifierValue);
}

var data = require('./core.json');

var core = {};
for (var mod in data) { // eslint-disable-line no-restricted-syntax
    if (Object.prototype.hasOwnProperty.call(data, mod)) {
        core[mod] = versionIncluded(data[mod]);
    }
}
module.exports = core;
<commit_msg>[Fix] `core`: remove console warning on require, since the main entry point requires it<commit_after>var current = (process.versions && process.versions.node && process.versions.node.split('.')) || [];

function specifierIncluded(specifier) {
    var parts = specifier.split(' ');
    var op = parts.length > 1 ? parts[0] : '=';
    var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');

    for (var i = 0; i < 3; ++i) {
        var cur = parseInt(current[i] || 0, 10);
        var ver = parseInt(versionParts[i] || 0, 10);
        if (cur === ver) {
            continue; // eslint-disable-line no-restricted-syntax, no-continue
        }
        if (op === '<') {
            return cur < ver;
        } else if (op === '>=') {
            return cur >= ver;
        } else {
            return false;
        }
    }
    return op === '>=';
}

function matchesRange(range) {
    var specifiers = range.split(/ ?&& ?/);
    if (specifiers.length === 0) { return false; }
    for (var i = 0; i < specifiers.length; ++i) {
        if (!specifierIncluded(specifiers[i])) { return false; }
    }
    return true;
}

function versionIncluded(specifierValue) {
    if (typeof specifierValue === 'boolean') { return specifierValue; }
    if (specifierValue && typeof specifierValue === 'object') {
        for (var i = 0; i < specifierValue.length; ++i) {
            if (matchesRange(specifierValue[i])) { return true; }
        }
        return false;
    }
    return matchesRange(specifierValue);
}

var data = require('./core.json');

var core = {};
for (var mod in data) { // eslint-disable-line no-restricted-syntax
    if (Object.prototype.hasOwnProperty.call(data, mod)) {
        core[mod] = versionIncluded(data[mod]);
    }
}
module.exports = core;
<|endoftext|>


<commit_before>// Enable expanding/folding folders in TracBrowser

(function($){
  var FOLDERID_COUNTER = 0;
  var SUBFOLDER_INDENT = 20;

  // enableExpandDir adds the capability to ''folder'' rows in a table
  // to be expanded and folded.
  //
  // It also teach the rows about their ancestors. It expects:
  //  - `parent_tr`, the logical parent row (`null` if there's no ancestor)
  //  - a `rows` jQuery object matching the newly created entry rows
  //  - `qargs`, additional parameters to send to the server when expanding
  //  - `autoexpand`, an optional array corresponding to a splitted sub-path
  //    of entries that will be expanded automatically.

  window.enableExpandDir = function(parent_tr, rows, qargs, autoexpand) {
    // the ancestors folder ids are present in the parent_tr class attribute
    var ancestor_folderids = [];

    if (parent_tr) // rows are logical children of the parent_tr row
      ancestor_folderids = $.grep(parent_tr.attr("class").split(" "),
                                  function(c) { return c.match(/^f\d+$/)});
    else { // rows are toplevel rows, this is the initial call
      var anchor = window.location.hash.substr(1);
      if (anchor)
        autoexpand = anchor.split("/");
    }

    var autoexpand_expander = null;
    rows.each(function () {
      var a = $(this).find("a.dir");

      if (a.length) { // then the entry is a folder
        // create new folder id
        var folderid = "f" + FOLDERID_COUNTER++;
        this.id = folderid;
        $(this).addClass(folderid);

        // add the expander icon
        var expander = $(' ')
          .attr("title", _("Expand sub-directory in place"))
          .click(function() { toggleDir($(this), qargs); })
        a.wrap('

').before(expander);
        if (autoexpand && a.text() == autoexpand[0])
          autoexpand_expander = expander;
      }

      // tie that row to ancestor folders
      if (parent_tr)
        $(this).addClass(ancestor_folderids.join(" "));
    });

    if ( autoexpand_expander )
      toggleDir(autoexpand_expander, qargs, autoexpand.slice(1));
  }

  // handler for click event on the expander icons
  window.toggleDir = function(expander, qargs, autoexpand) {
    var tr = expander.parents("tr:first");
    var folderid = tr.get(0).id;

    if ( tr.hasClass("expanded") ) { // then *fold*
      tr.removeClass("expanded");
      if (tr.next().hasClass("error")) {
        tr.next().remove();
      } else {
        tr.addClass("collapsed");
        tr.siblings("tr."+folderid).hide();
      }
      expander.attr("title", _("Re-expand directory"));
      return;
    }

    // update location, unless autoexpand in progress
    var a = expander.next("a");
    if ( !autoexpand )
      window.location.hash = a.attr("href")
        .substr(window.location.pathname.length+1)
        .replace(/([^?]*)(\?.*)?$/, '$1');

    // update sort links in column headers
    tr.parents("table:first").find("thead tr:first").find("a").each(function(){
      var href = $(this).attr("href").replace(/#.*$/, '');
      $(this).attr("href", href+window.location.hash);
     });

    if ( tr.hasClass("collapsed") ) { // then *expand*
      tr.removeClass("collapsed").addClass("expanded");
      tr.siblings("tr."+folderid).show();
      // Note that the above will show all the already fetched subtrees,
      // so we have to fold again the folders which were already collapsed.
      tr.siblings("tr.collapsed").each(function() {
        tr.siblings("tr."+this.id).not(this).hide();
      });
    } else {                                // then *fetch*
      var td = expander.parents("td:first");
      var td_class = td.attr("class");
      var depth =
        parseFloat(td.css("padding-left").replace(/^(\d*\.\d*).*$/, "$1")) +
        SUBFOLDER_INDENT;

      tr.addClass("expanded");
      // insert "Loading ..." row
      var loading_row = $($.htmlFormat(
        '
' +
        ' ' +
        '  ${loading}' +
        ' 	' +
        '
', {
        td_class: td_class,
        colspan: tr.children("td").length,
        depth: depth,
        loading: babel.format(_("Loading %(entry)s..."), {entry: a.text()})
      }));
      tr.after(loading_row);

      // XHR for getting the rows corresponding to the folder entries
      $.ajax({
        type: "GET",
        url: a.attr("href"),
        data: qargs,
        dataType: "html",
        success: function(data) {
          // Safari 3.1.1 has some trouble reconstructing HTML snippets
          // bigger than 50k - splitting in rows before building DOM nodes
          var rows = data.replace(/^<!DOCTYPE[^>]+>/, "").split("
");
          if (rows.length) {
            // insert entry rows
            $(rows).each(function() {
              row = $(this+"
");
              row.children("td."+td_class).css("padding-left", depth);
              // make all entry rows collapsible but only subdir rows expandable
              loading_row.before(row);
              enableExpandDir(tr, row, qargs, autoexpand);
            });
            // remove "Loading ..." row
            loading_row.remove();
          } else {
            loading_row.find("span.loading")
              .text("")
              .append("" + _("(empty)") + "")
              .removeClass("loading");
            enableExpandDir(tr, loading_row, qargs); // make it collapsible
          }
        },
        error: function(req, err, exc) {
          loading_row.find("span.loading")
            .text("")
            .append("" + _("(error)") + "")
            .removeClass("loading");
          loading_row.addClass("error");
          enableExpandDir(tr, loading_row, qargs); // make it collapsible
        }
      });
    }
    expander.attr("title", _("Fold directory"));
  }

})(jQuery);
<commit_msg>0.12.1dev: Fixed the update of the page location when expanding a directory in the source browser, in the case where the URL has trailing slashes.<commit_after>// Enable expanding/folding folders in TracBrowser

(function($){
  var FOLDERID_COUNTER = 0;
  var SUBFOLDER_INDENT = 20;

  // enableExpandDir adds the capability to ''folder'' rows in a table
  // to be expanded and folded.
  //
  // It also teach the rows about their ancestors. It expects:
  //  - `parent_tr`, the logical parent row (`null` if there's no ancestor)
  //  - a `rows` jQuery object matching the newly created entry rows
  //  - `qargs`, additional parameters to send to the server when expanding
  //  - `autoexpand`, an optional array corresponding to a splitted sub-path
  //    of entries that will be expanded automatically.

  window.enableExpandDir = function(parent_tr, rows, qargs, autoexpand) {
    // the ancestors folder ids are present in the parent_tr class attribute
    var ancestor_folderids = [];

    if (parent_tr) // rows are logical children of the parent_tr row
      ancestor_folderids = $.grep(parent_tr.attr("class").split(" "),
                                  function(c) { return c.match(/^f\d+$/)});
    else { // rows are toplevel rows, this is the initial call
      var anchor = window.location.hash.substr(1);
      if (anchor)
        autoexpand = anchor.split("/");
    }

    var autoexpand_expander = null;
    rows.each(function () {
      var a = $(this).find("a.dir");

      if (a.length) { // then the entry is a folder
        // create new folder id
        var folderid = "f" + FOLDERID_COUNTER++;
        this.id = folderid;
        $(this).addClass(folderid);

        // add the expander icon
        var expander = $(' ')
          .attr("title", _("Expand sub-directory in place"))
          .click(function() { toggleDir($(this), qargs); })
        a.wrap('

').before(expander);
        if (autoexpand && a.text() == autoexpand[0])
          autoexpand_expander = expander;
      }

      // tie that row to ancestor folders
      if (parent_tr)
        $(this).addClass(ancestor_folderids.join(" "));
    });

    if ( autoexpand_expander )
      toggleDir(autoexpand_expander, qargs, autoexpand.slice(1));
  }

  // handler for click event on the expander icons
  window.toggleDir = function(expander, qargs, autoexpand) {
    var tr = expander.parents("tr:first");
    var folderid = tr.get(0).id;

    if ( tr.hasClass("expanded") ) { // then *fold*
      tr.removeClass("expanded");
      if (tr.next().hasClass("error")) {
        tr.next().remove();
      } else {
        tr.addClass("collapsed");
        tr.siblings("tr."+folderid).hide();
      }
      expander.attr("title", _("Re-expand directory"));
      return;
    }

    // update location, unless autoexpand in progress
    var a = expander.next("a");
    if ( !autoexpand )
      window.location.hash = a.attr("href")
        .substr(window.location.pathname.replace(/\/+$/, '').length + 1)
        .replace(/([^?]*)(\?.*)?$/, '$1');

    // update sort links in column headers
    tr.parents("table:first").find("thead tr:first").find("a").each(function(){
      var href = $(this).attr("href").replace(/#.*$/, '');
      $(this).attr("href", href+window.location.hash);
     });

    if ( tr.hasClass("collapsed") ) { // then *expand*
      tr.removeClass("collapsed").addClass("expanded");
      tr.siblings("tr."+folderid).show();
      // Note that the above will show all the already fetched subtrees,
      // so we have to fold again the folders which were already collapsed.
      tr.siblings("tr.collapsed").each(function() {
        tr.siblings("tr."+this.id).not(this).hide();
      });
    } else {                                // then *fetch*
      var td = expander.parents("td:first");
      var td_class = td.attr("class");
      var depth =
        parseFloat(td.css("padding-left").replace(/^(\d*\.\d*).*$/, "$1")) +
        SUBFOLDER_INDENT;

      tr.addClass("expanded");
      // insert "Loading ..." row
      var loading_row = $($.htmlFormat(
        '
' +
        ' ' +
        '  ${loading}' +
        ' 	' +
        '
', {
        td_class: td_class,
        colspan: tr.children("td").length,
        depth: depth,
        loading: babel.format(_("Loading %(entry)s..."), {entry: a.text()})
      }));
      tr.after(loading_row);

      // XHR for getting the rows corresponding to the folder entries
      $.ajax({
        type: "GET",
        url: a.attr("href"),
        data: qargs,
        dataType: "html",
        success: function(data) {
          // Safari 3.1.1 has some trouble reconstructing HTML snippets
          // bigger than 50k - splitting in rows before building DOM nodes
          var rows = data.replace(/^<!DOCTYPE[^>]+>/, "").split("
");
          if (rows.length) {
            // insert entry rows
            $(rows).each(function() {
              row = $(this+"
");
              row.children("td."+td_class).css("padding-left", depth);
              // make all entry rows collapsible but only subdir rows expandable
              loading_row.before(row);
              enableExpandDir(tr, row, qargs, autoexpand);
            });
            // remove "Loading ..." row
            loading_row.remove();
          } else {
            loading_row.find("span.loading")
              .text("")
              .append("" + _("(empty)") + "")
              .removeClass("loading");
            enableExpandDir(tr, loading_row, qargs); // make it collapsible
          }
        },
        error: function(req, err, exc) {
          loading_row.find("span.loading")
            .text("")
            .append("" + _("(error)") + "")
            .removeClass("loading");
          loading_row.addClass("error");
          enableExpandDir(tr, loading_row, qargs); // make it collapsible
        }
      });
    }
    expander.attr("title", _("Fold directory"));
  }

})(jQuery);
<|endoftext|>


<commit_before>module("Bio.Alphabet Tests");
test("instantiation", function(){
    var a = null;
    ok(a == null);
    a = new Bio.Alphabet();
    ok(a instanceof Bio.Alphabet);
});

test("letters", function(){
    var a = new Bio.Alphabet();
    ok(a.letters == null);
});

test("size", function(){
    var a = new Bio.Alphabet();
    ok(a.size == null);
});

test("Bio.generic_alphabet instance", function(){
    ok(Bio.generic_alphabet instanceof Bio.Alphabet);
});

module("Bio.SingleLetterAlphabet Tests");
test("instantiation", function(){
    var a = null;
    ok(a == null);
    a = new Bio.SingleLetterAlphabet();
    ok(a instanceof Bio.SingleLetterAlphabet);
    ok(a instanceof Bio.Alphabet);
});

test("letters", function(){
    var a = new Bio.SingleLetterAlphabet();
    ok(a.letters == null);
});

test("size", function(assert){
    var a = new Bio.SingleLetterAlphabet();
    assert.equal(a.size, 1);
});

test("instantiation", function(){
    var a = null;
    ok(a == null);
    a = new Bio.ProteinAlphabet();
    ok(a instanceof Bio.ProteinAlphabet);
    ok(a instanceof Bio.SingleLetterAlphabet);
    ok(a instanceof Bio.Alphabet);
});
<commit_msg>Bio.Alphabet tests: Unify and clarify test names<commit_after>module("Bio.Alphabet Tests");
test("Alphabet instantiation", function(){
    var a = null;
    ok(a == null);
    a = new Bio.Alphabet();
    ok(a instanceof Bio.Alphabet);
});

test("Alphabet letters", function(){
    var a = new Bio.Alphabet();
    ok(a.letters == null);
});

test("Alphabet size", function(){
    var a = new Bio.Alphabet();
    ok(a.size == null);
});

test("Bio.generic_alphabet instance", function(){
    ok(Bio.generic_alphabet instanceof Bio.Alphabet);
});

test("SingleLetterAlphabet instantiation", function(){
    var a = null;
    ok(a == null);
    a = new Bio.SingleLetterAlphabet();
    ok(a instanceof Bio.SingleLetterAlphabet);
    ok(a instanceof Bio.Alphabet);
});

test("SingleLetterAlphabet letters", function(){
    var a = new Bio.SingleLetterAlphabet();
    ok(a.letters == null);
});

test("SingleLetterAlphabet size", function(assert){
    var a = new Bio.SingleLetterAlphabet();
    assert.equal(a.size, 1);
});

test("ProteinAlphabet instantiation", function(){
    var a = null;
    ok(a == null);
    a = new Bio.ProteinAlphabet();
    ok(a instanceof Bio.ProteinAlphabet);
    ok(a instanceof Bio.SingleLetterAlphabet);
    ok(a instanceof Bio.Alphabet);
});
<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
  var fileLocation = determinFileRequested(req.url);

  if (fs.existsSync(fileLocation)) //lets get that file
    {
      serveContent(fileLocation, res, 200);
    }
  else //my 404 message
    {
      serveContent('static/404.html', res, 404);
    }

}).listen(3000, '0.0.0.0');
console.log('Server running at http://0.0.0.0:3000/');

function determinFileRequested(requestedURL) {
  if ((requestedURL.indexOf('.html') + requestedURL.indexOf('.jpg') + requestedURL.indexOf('.css')) ==-3) {
    return 'static' + requestedURL + '.html';
  }
  return 'static' + requestedURL;
}

function serveContent(fileLocation, response, statusCode) {
  fs.readFile(fileLocation, function (err, data) {
    if (err) throw err;
    response.writeHead(statusCode, {'Content-Type': 'text/html'});
    response.end(data);
    console.log('SERVED: ' + fileLocation);
  })
}<commit_msg>now supporting css & jpg<commit_after>var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
  var fileLocation = determinFileRequested(req.url);
  var contentType = selectContentType(req.url);
  if (fs.existsSync(fileLocation)) //lets get that file
    {
      serveContent(fileLocation, res, 200, contentType);
    }
  else //my 404 message
    {
      serveContent('static/404.html', res, 404, contentType);
    }

}).listen(3000, '0.0.0.0');
console.log('Server running at http://0.0.0.0:3000/');

function determinFileRequested(requestedURL) {
  if ((requestedURL.indexOf('.html') + requestedURL.indexOf('.jpg') + requestedURL.indexOf('.css')) ==-3) {
    return 'static' + requestedURL + '.html';
  }
  return 'static' + requestedURL;
}

function selectContentType(requestedURL){
  if (requestedURL.indexOf('.html')) return 'text/html';
  if (requestedURL.indexOf('.css')) return 'text/css';
  if (requestedURL.indexOf('.jpg')) return 'image/jpeg';
}

function serveContent(fileLocation, response, statusCode, contentType) {
  fs.readFile(fileLocation, function (err, data) {
    if (err) throw err;
    response.writeHead(statusCode, {'Content-Type': contentType});
    response.end(data);
    console.log('SERVED: ' + fileLocation);
  })
}<|endoftext|>