<commit_before>var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
var toString  = Function.prototype.call.bind(Object.prototype.toString);
var path = require('path');
var webpack = require('webpack');
// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;

module.exports = {
  devtool: 'source-map',
  // devtool: 'eval',

  //
  entry: {
    'vendor': [
      // Polyfills
      'es6-shim',
      'es6-promise',
      'reflect-metadata',
      'zone.js/dist/zone-microtask',
      'zone.js/dist/long-stack-trace-zone',
      // Angular2
      'angular2/platform/browser',
      'angular2/platform/common_dom',
      'angular2/core',
      'angular2/router',
      'angular2/http',
      // RxJS
      'rxjs',
      // Other
      'angular2-jwt'
    ],
    'app': [
      './src/index'
    ]
  },

  // Config for our build files
  output: {
    path: root('build'),
    filename: '[name].js',
    // filename: '[name].[hash].js',
    sourceMapFilename: '[name].js.map',
    chunkFilename: '[id].chunk.js'
    // publicPath: 'http://mycdn.com/'
  },

  resolve: {
    root: __dirname,
    extensions: [
      '',
      '.ts',
      '.js',
      '.json',
      '.css',
      '.html'
    ]
  },

  module: {
    preLoaders: [ { test: /\.ts$/, loader: 'tslint-loader' } ],
    loaders: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        query: {
          'ignoreDiagnostics': [
            2403, // 2403 -> Subsequent variable declarations
            2300, // 2300 Duplicate identifier
            2374, // 2374 -> Duplicate number index signature
            2375  // 2375 -> Duplicate string index signature
          ]
        },
        exclude: [ /\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/ ]
      },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,  loader: 'raw-loader' },
    ],
    noParse: [
     /zone\.js\/dist\/.+/,
     /reflect-metadata/,
     /es(6|7)-.+/,
    ]
  },

  plugins: [
    new CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
    new CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] })
  ],

  // Other module loader config
  tslint: {
    emitErrors: false,
    failOnHint: false
  },

  // our Development Server configs
  // our Webpack Development Server config
  devServer: {
    historyApiFallback: true,
    publicPath: '/build'
  }
};

function getBanner() {
  return 'This is a sample that shows how to add authentication to an Angular 2 (ng2) app by @auth0';
}

function root(args) {
  args = sliceArgs(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
  args = sliceArgs(arguments, 0);
  return root.apply(path, ['node_modules'].concat(args));
}

<commit_msg>supress pre-built javascript message<commit_after>var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
var toString  = Function.prototype.call.bind(Object.prototype.toString);
var path = require('path');
var webpack = require('webpack');
// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;

module.exports = {
  devtool: 'source-map',
  // devtool: 'eval',

  //
  entry: {
    'vendor': [
      // Polyfills
      'es6-shim',
      'es6-promise',
      'reflect-metadata',
      'zone.js/dist/zone-microtask',
      'zone.js/dist/long-stack-trace-zone',
      // Angular2
      'angular2/platform/browser',
      'angular2/platform/common_dom',
      'angular2/core',
      'angular2/router',
      'angular2/http',
      // RxJS
      'rxjs',
      // Other
      'angular2-jwt'
    ],
    'app': [
      './src/index'
    ]
  },

  // Config for our build files
  output: {
    path: root('build'),
    filename: '[name].js',
    // filename: '[name].[hash].js',
    sourceMapFilename: '[name].js.map',
    chunkFilename: '[id].chunk.js'
    // publicPath: 'http://mycdn.com/'
  },

  resolve: {
    root: __dirname,
    extensions: [
      '',
      '.ts',
      '.js',
      '.json',
      '.css',
      '.html'
    ]
  },

  module: {
    preLoaders: [ { test: /\.ts$/, loader: 'tslint-loader' } ],
    loaders: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        query: {
          'ignoreDiagnostics': [
            2403, // 2403 -> Subsequent variable declarations
            2300, // 2300 Duplicate identifier
            2374, // 2374 -> Duplicate number index signature
            2375  // 2375 -> Duplicate string index signature
          ]
        },
        exclude: [ /\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/ ]
      },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,  loader: 'raw-loader' },
    ],
    noParse: [
     /zone\.js\/dist\/.+/,
     /reflect-metadata/,
     /es(6|7)-.+/,
     /.zone-microtask/,
     /.long-stack-trace-zone/
    ]
  },

  plugins: [
    new CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
    new CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] })
  ],

  // Other module loader config
  tslint: {
    emitErrors: false,
    failOnHint: false
  },

  // our Development Server configs
  // our Webpack Development Server config
  devServer: {
    historyApiFallback: true,
    publicPath: '/build'
  }
};

function getBanner() {
  return 'This is a sample that shows how to add authentication to an Angular 2 (ng2) app by @auth0';
}

function root(args) {
  args = sliceArgs(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
  args = sliceArgs(arguments, 0);
  return root.apply(path, ['node_modules'].concat(args));
}

<|endoftext|>


<commit_before>/* global __dirname */

const process = require('process');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');

/**
 * The URL of the Jitsi Meet deployment to be proxy to in the context of
 * development with webpack-dev-server.
 */
const devServerProxyTarget
    = process.env.WEBPACK_DEV_SERVER_PROXY_TARGET || 'https://beta.meet.jit.si';

const minimize
    = process.argv.indexOf('-p') !== -1
        || process.argv.indexOf('--optimize-minimize') !== -1;

const plugins = [
    new webpack.LoaderOptionsPlugin({
        debug: !minimize,
        minimize
    })
];

if (minimize) {
    // XXX Webpack's command line argument -p is not enough. Further
    // optimizations are made possible by the use of DefinePlugin and NODE_ENV
    // with value 'production'. For example, React takes advantage of these.
    plugins.push(new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    }));
    plugins.push(new webpack.optimize.ModuleConcatenationPlugin());
    plugins.push(new UglifyJsPlugin({
        cache: true,
        extractComments: true,
        parallel: true,
        sourceMap: true
    }));
}

// The base Webpack configuration to bundle the JavaScript artifacts of
// jitsi-meet such as app.bundle.js and external_api.js.
const config = {
    devServer: {
        https: true,
        inline: true,
        proxy: {
            '/': {
                bypass: devServerProxyBypass,
                secure: false,
                target: devServerProxyTarget
            }
        }
    },
    devtool: 'source-map',
    module: {
        rules: [ {
            // Transpile ES2015 (aka ES6) to ES5. Accept the JSX syntax by React
            // as well.

            exclude: [
                new RegExp(`${__dirname}/node_modules/(?!js-utils)`)
            ],
            loader: 'babel-loader',
            options: {
                // XXX The require.resolve bellow solves failures to locate the
                // presets when lib-jitsi-meet, for example, is npm linked in
                // jitsi-meet.
                plugins: [
                    require.resolve('@babel/plugin-transform-flow-strip-types'),
                    require.resolve('@babel/plugin-proposal-class-properties'),
                    require.resolve(
                        '@babel/plugin-proposal-export-default-from'),
                    require.resolve(
                        '@babel/plugin-proposal-export-namespace-from')
                ],
                presets: [
                    [
                        require.resolve('@babel/preset-env'),

                        // Tell babel to avoid compiling imports into CommonJS
                        // so that webpack may do tree shaking.
                        { modules: false }
                    ],
                    require.resolve('@babel/preset-flow'),
                    require.resolve('@babel/preset-react')
                ]
            },
            test: /\.jsx?$/
        }, {
            // Expose jquery as the globals $ and jQuery because it is expected
            // to be available in such a form by multiple jitsi-meet
            // dependencies including lib-jitsi-meet.

            loader: 'expose-loader?$!expose-loader?jQuery',
            test: /\/node_modules\/jquery\/.*\.js$/
        }, {
            // Allow CSS to be imported into JavaScript.

            test: /\.css$/,
            use: [
                'style-loader',
                'css-loader'
            ]
        } ]
    },
    node: {
        // Allow the use of the real filename of the module being executed. By
        // default Webpack does not leak path-related information and provides a
        // value that is a mock (/index.js).
        __filename: true
    },
    output: {
        filename: `[name]${minimize ? '.min' : ''}.js`,
        path: `${__dirname}/build`,
        publicPath: '/libs/',
        sourceMapFilename: `[name].${minimize ? 'min' : 'js'}.map`
    },
    plugins,
    resolve: {
        alias: {
            jquery: `jquery/dist/jquery${minimize ? '.min' : ''}.js`
        },
        aliasFields: [
            'browser'
        ],
        extensions: [
            '.web.js',

            // Webpack defaults:
            '.js',
            '.json'
        ]
    }
};

module.exports = [
    Object.assign({}, config, {
        entry: {
            'app.bundle': './app.js',

            'device_selection_popup_bundle':
                './react/features/settings/popup.js',

            'alwaysontop':
                './react/features/always-on-top/index.js',

            'dial_in_info_bundle': [

                // atlaskit does not support React 16 prop-types
                './react/features/base/react/prop-types-polyfill.js',

                './react/features/invite/components/dial-in-info-page'
            ],

            'do_external_connect':
                './connection_optimization/do_external_connect.js',

            'flacEncodeWorker':
                './react/features/local-recording/'
                    + 'recording/flac/flacEncodeWorker.js'
        }
    }),

    // The Webpack configuration to bundle external_api.js (aka
    // JitsiMeetExternalAPI).
    Object.assign({}, config, {
        entry: {
            'external_api': './modules/API/external/index.js'
        },
        output: Object.assign({}, config.output, {
            library: 'JitsiMeetExternalAPI',
            libraryTarget: 'umd'
        })
    })
];

/**
 * Determines whether a specific (HTTP) request is to bypass the proxy of
 * webpack-dev-server (i.e. is to be handled by the proxy target) and, if not,
 * which local file is to be served in response to the request.
 *
 * @param {Object} request - The (HTTP) request received by the proxy.
 * @returns {string|undefined} If the request is to be served by the proxy
 * target, undefined; otherwise, the path to the local file to be served.
 */
function devServerProxyBypass({ path }) {
    if (path.startsWith('/css/') || path.startsWith('/doc/')) {
        return path;
    }

    const configs = module.exports;

    /* eslint-disable array-callback-return, indent */

    if ((Array.isArray(configs) ? configs : Array(configs)).some(c => {
                if (path.startsWith(c.output.publicPath)) {
                    if (!minimize) {
                        // Since webpack-dev-server is serving non-minimized
                        // artifacts, serve them even if the minimized ones are
                        // requested.
                        Object.keys(c.entry).some(e => {
                            const name = `${e}.min.js`;

                            if (path.indexOf(name) !== -1) {
                                // eslint-disable-next-line no-param-reassign
                                path = path.replace(name, `${e}.js`);

                                return true;
                            }
                        });
                    }

                    return true;
                }
            })) {
        return path;
    }

    /* eslint-enable array-callback-return, indent */
}
<commit_msg>feat(dev): don't proxy fonts<commit_after>/* global __dirname */

const process = require('process');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');

/**
 * The URL of the Jitsi Meet deployment to be proxy to in the context of
 * development with webpack-dev-server.
 */
const devServerProxyTarget
    = process.env.WEBPACK_DEV_SERVER_PROXY_TARGET || 'https://beta.meet.jit.si';

const minimize
    = process.argv.indexOf('-p') !== -1
        || process.argv.indexOf('--optimize-minimize') !== -1;

const plugins = [
    new webpack.LoaderOptionsPlugin({
        debug: !minimize,
        minimize
    })
];

if (minimize) {
    // XXX Webpack's command line argument -p is not enough. Further
    // optimizations are made possible by the use of DefinePlugin and NODE_ENV
    // with value 'production'. For example, React takes advantage of these.
    plugins.push(new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    }));
    plugins.push(new webpack.optimize.ModuleConcatenationPlugin());
    plugins.push(new UglifyJsPlugin({
        cache: true,
        extractComments: true,
        parallel: true,
        sourceMap: true
    }));
}

// The base Webpack configuration to bundle the JavaScript artifacts of
// jitsi-meet such as app.bundle.js and external_api.js.
const config = {
    devServer: {
        https: true,
        inline: true,
        proxy: {
            '/': {
                bypass: devServerProxyBypass,
                secure: false,
                target: devServerProxyTarget
            }
        }
    },
    devtool: 'source-map',
    module: {
        rules: [ {
            // Transpile ES2015 (aka ES6) to ES5. Accept the JSX syntax by React
            // as well.

            exclude: [
                new RegExp(`${__dirname}/node_modules/(?!js-utils)`)
            ],
            loader: 'babel-loader',
            options: {
                // XXX The require.resolve bellow solves failures to locate the
                // presets when lib-jitsi-meet, for example, is npm linked in
                // jitsi-meet.
                plugins: [
                    require.resolve('@babel/plugin-transform-flow-strip-types'),
                    require.resolve('@babel/plugin-proposal-class-properties'),
                    require.resolve(
                        '@babel/plugin-proposal-export-default-from'),
                    require.resolve(
                        '@babel/plugin-proposal-export-namespace-from')
                ],
                presets: [
                    [
                        require.resolve('@babel/preset-env'),

                        // Tell babel to avoid compiling imports into CommonJS
                        // so that webpack may do tree shaking.
                        { modules: false }
                    ],
                    require.resolve('@babel/preset-flow'),
                    require.resolve('@babel/preset-react')
                ]
            },
            test: /\.jsx?$/
        }, {
            // Expose jquery as the globals $ and jQuery because it is expected
            // to be available in such a form by multiple jitsi-meet
            // dependencies including lib-jitsi-meet.

            loader: 'expose-loader?$!expose-loader?jQuery',
            test: /\/node_modules\/jquery\/.*\.js$/
        }, {
            // Allow CSS to be imported into JavaScript.

            test: /\.css$/,
            use: [
                'style-loader',
                'css-loader'
            ]
        } ]
    },
    node: {
        // Allow the use of the real filename of the module being executed. By
        // default Webpack does not leak path-related information and provides a
        // value that is a mock (/index.js).
        __filename: true
    },
    output: {
        filename: `[name]${minimize ? '.min' : ''}.js`,
        path: `${__dirname}/build`,
        publicPath: '/libs/',
        sourceMapFilename: `[name].${minimize ? 'min' : 'js'}.map`
    },
    plugins,
    resolve: {
        alias: {
            jquery: `jquery/dist/jquery${minimize ? '.min' : ''}.js`
        },
        aliasFields: [
            'browser'
        ],
        extensions: [
            '.web.js',

            // Webpack defaults:
            '.js',
            '.json'
        ]
    }
};

module.exports = [
    Object.assign({}, config, {
        entry: {
            'app.bundle': './app.js',

            'device_selection_popup_bundle':
                './react/features/settings/popup.js',

            'alwaysontop':
                './react/features/always-on-top/index.js',

            'dial_in_info_bundle': [

                // atlaskit does not support React 16 prop-types
                './react/features/base/react/prop-types-polyfill.js',

                './react/features/invite/components/dial-in-info-page'
            ],

            'do_external_connect':
                './connection_optimization/do_external_connect.js',

            'flacEncodeWorker':
                './react/features/local-recording/'
                    + 'recording/flac/flacEncodeWorker.js'
        }
    }),

    // The Webpack configuration to bundle external_api.js (aka
    // JitsiMeetExternalAPI).
    Object.assign({}, config, {
        entry: {
            'external_api': './modules/API/external/index.js'
        },
        output: Object.assign({}, config.output, {
            library: 'JitsiMeetExternalAPI',
            libraryTarget: 'umd'
        })
    })
];

/**
 * Determines whether a specific (HTTP) request is to bypass the proxy of
 * webpack-dev-server (i.e. is to be handled by the proxy target) and, if not,
 * which local file is to be served in response to the request.
 *
 * @param {Object} request - The (HTTP) request received by the proxy.
 * @returns {string|undefined} If the request is to be served by the proxy
 * target, undefined; otherwise, the path to the local file to be served.
 */
function devServerProxyBypass({ path }) {
    if (path.startsWith('/css/') || path.startsWith('/doc/')
            || path.startsWith('/fonts/')) {
        return path;
    }

    const configs = module.exports;

    /* eslint-disable array-callback-return, indent */

    if ((Array.isArray(configs) ? configs : Array(configs)).some(c => {
                if (path.startsWith(c.output.publicPath)) {
                    if (!minimize) {
                        // Since webpack-dev-server is serving non-minimized
                        // artifacts, serve them even if the minimized ones are
                        // requested.
                        Object.keys(c.entry).some(e => {
                            const name = `${e}.min.js`;

                            if (path.indexOf(name) !== -1) {
                                // eslint-disable-next-line no-param-reassign
                                path = path.replace(name, `${e}.js`);

                                return true;
                            }
                        });
                    }

                    return true;
                }
            })) {
        return path;
    }

    /* eslint-enable array-callback-return, indent */
}
<|endoftext|>


<commit_before>module.exports = {
    entry: "./example/src/index.js",
    output: {
        path: "example/dist",
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: "babel"},
            { test: /\.css$/, loader: "style!css" },
            { test: /\.scss$/, loader: "style!css!autoprefixer!sass" }
        ]
    }
};
<commit_msg>update webpack.config.js<commit_after>module.exports = {
    entry: "./example/src/index.js",
    output: {
        path: "example/dist",
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: "babel",
                query: {
                    presets: ['es2015', 'react'],
                }
            },
            { test: /\.css$/, loader: "style!css" },
            { test: /\.scss$/, loader: "style!css!autoprefixer!sass" }
        ]
    }
};
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var pkg = require(process.cwd() + '/package.json');

var release = (process.env.NODE_ENV === 'production');
var testing = (process.env.NODE_ENV === 'testing');

var plugins = [
  new webpack.IgnorePlugin(/vertx/),
  new webpack.NormalModuleReplacementPlugin(/^react$/, 'react/addons'),
];

if (!testing) {
  plugins.push(new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'));
  plugins.push(function() { // emit stats.json here because shell scripting is hard
    this.plugin('done', function(stats) {
      var jsonStats = stats.toJson({
        chunkModules: true,
      });
      require('fs').writeFileSync(
        path.join(process.cwd(), 'dist', 'assets.json'),
        JSON.stringify(jsonStats.assetsByChunkName)
      );
      require('fs').writeFileSync(
        path.join(process.cwd(), 'dist', 'stats.json'),
        JSON.stringify(jsonStats)
      );
    });
  });
}

var jsxLoader = ['babel?experimental&optional=runtime'];

if (release)  {
  plugins.push(new webpack.DefinePlugin({
    'process.env': {
      // This has effect on the react lib size
      'NODE_ENV': JSON.stringify('production'),
    },
  }));

  plugins.push(new webpack.optimize.DedupePlugin());
  plugins.push(new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}}));
  plugins.push(new webpack.NoErrorsPlugin()); // cause failed production builds to fail faster
} else if (!testing) {
  jsxLoader.unshift('react-hot-loader');
}

if (testing) {
  var entry = null;
} else {
  var entry = {
    app: './app',
    vendor: Object.keys(pkg.dependencies).filter(function(e) {
      return [
        'macropod-components',
        'react-components', //TODO: make this finer
        'open-sans',
      ].indexOf(e) === -1;
    }),
  };
}

var config = module.exports = {
  debug: !release,
  cache: !release,
  devtool: !release && 'eval',
  entry: entry,
  output: {
    path: process.cwd() + '/dist',
    filename: '[name].js',
  },
  plugins: plugins,
  resolveLoader: {
    modulesDirectories: ['node_modules', 'node_modules/macropod-tools/node_modules']
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.scss', '.css'],
    modulesDirectories: ['node_modules', 'node_modules/macropod-tools/node_modules'],
    packageMains: ['browser', 'main', 'style'],
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: jsxLoader,
      },
      {
        test: /\.(js|jsx)$/,
        include: /node_modules[\\\/]macropod-components/,
        loaders: jsxLoader,
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'autoprefixer-loader',
          'sass-loader?includePaths[]=./app/base/style,includePaths[]=./node_modules,includePaths[]=./style,includePaths[]=./node_modules/macropod-components/style,includePaths[]=./app/base/style,includePaths[]=./app/base/components,includePaths[]=./node_modules,includePaths[]=./node_modules/bootstrap-sass/assets/fonts'
        ],
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
      },
      {
        test: /\.png$/,
        loader: 'url-loader?limit=100000&mimetype=image/png',
      },
      {
        test: /\.jpg$/,
        loader: 'url-loader?limit=100000&mimetype=image/jpeg',
      },
      {
        test: /\.woff$/,
        loader: 'url-loader?mimetype=application/font-woff',
      },
      {
        test: /\.ttf$/,
        loader: 'url-loader?',
      },
      {
        test: /\.eot$/,
        loader: 'url-loader?',
      },
      {
        test: /\.svg$/,
        loader: 'url-loader',
      },
      {
        test: /\.pdf$/,
        loader: 'file-loader',
      },
      {
        test: /\.raw.svg$/,
        loader: 'raw-loader?',
      },
    ],
  },
};
<commit_msg>Make pouch load correctly when included in another project<commit_after>var webpack = require('webpack');
var path = require('path');
var pkg = require(process.cwd() + '/package.json');

var release = (process.env.NODE_ENV === 'production');
var testing = (process.env.NODE_ENV === 'testing');

var plugins = [
  new webpack.IgnorePlugin(/vertx/),
  new webpack.NormalModuleReplacementPlugin(/^react$/, 'react/addons'),
];

if (!testing) {
  plugins.push(new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'));
  plugins.push(function() { // emit stats.json here because shell scripting is hard
    this.plugin('done', function(stats) {
      var jsonStats = stats.toJson({
        chunkModules: true,
      });
      require('fs').writeFileSync(
        path.join(process.cwd(), 'dist', 'assets.json'),
        JSON.stringify(jsonStats.assetsByChunkName)
      );
      require('fs').writeFileSync(
        path.join(process.cwd(), 'dist', 'stats.json'),
        JSON.stringify(jsonStats)
      );
    });
  });
}

var jsxLoader = ['babel?experimental&optional=runtime'];

if (release)  {
  plugins.push(new webpack.DefinePlugin({
    'process.env': {
      // This has effect on the react lib size
      'NODE_ENV': JSON.stringify('production'),
    },
  }));

  plugins.push(new webpack.optimize.DedupePlugin());
  plugins.push(new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}}));
  plugins.push(new webpack.NoErrorsPlugin()); // cause failed production builds to fail faster
} else if (!testing) {
  jsxLoader.unshift('react-hot-loader');
}

if (testing) {
  var entry = null;
} else {
  var entry = {
    app: './app',
    vendor: Object.keys(pkg.dependencies).filter(function(e) {
      return [
        'macropod-components',
        'react-components', //TODO: make this finer
        'open-sans',
        'pouch-client',
      ].indexOf(e) === -1;
    }),
  };
}

var config = module.exports = {
  debug: !release,
  cache: !release,
  devtool: !release && 'eval',
  entry: entry,
  output: {
    path: process.cwd() + '/dist',
    filename: '[name].js',
  },
  plugins: plugins,
  resolveLoader: {
    modulesDirectories: ['node_modules', 'node_modules/macropod-tools/node_modules']
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.scss', '.css'],
    modulesDirectories: ['node_modules', 'node_modules/macropod-tools/node_modules'],
    packageMains: ['browser', 'main', 'style'],
  },
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: jsxLoader,
      },
      {
        test: /\.(js|jsx)$/,
        include: /node_modules[\\\/]macropod-components/,
        loaders: jsxLoader,
      },
      {
        test: /\.(js|jsx)$/,
        include: /pouch-client/,
        loaders: jsxLoader,
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'autoprefixer-loader',
          'sass-loader?includePaths[]=./app/base/style,includePaths[]=./node_modules,includePaths[]=./style,includePaths[]=./node_modules/macropod-components/style,includePaths[]=./app/base/style,includePaths[]=./app/base/components,includePaths[]=./node_modules,includePaths[]=./node_modules/bootstrap-sass/assets/fonts'
        ],
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
      },
      {
        test: /\.png$/,
        loader: 'url-loader?limit=100000&mimetype=image/png',
      },
      {
        test: /\.jpg$/,
        loader: 'url-loader?limit=100000&mimetype=image/jpeg',
      },
      {
        test: /\.woff$/,
        loader: 'url-loader?mimetype=application/font-woff',
      },
      {
        test: /\.ttf$/,
        loader: 'url-loader?',
      },
      {
        test: /\.eot$/,
        loader: 'url-loader?',
      },
      {
        test: /\.svg$/,
        loader: 'url-loader',
      },
      {
        test: /\.pdf$/,
        loader: 'file-loader',
      },
      {
        test: /\.raw.svg$/,
        loader: 'raw-loader?',
      },
    ],
  },
};
<|endoftext|>


<commit_before>var path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
   context : __dirname,
   entry : './src/main/js/index.js',
   devtool : 'inline-source-map',
   cache : true,
   debug : true,
   output : {
      path : __dirname,
      filename : './target/generated-ui/bundle.js'
   },
   resolve : {
      extensions : [ '', '.scss', '.css', '.js', '.json' ],
      modulesDirectories : [
         'src/main/js',
         path.resolve(__dirname, './src/main/js'),
         'node_modules',
         path.resolve(__dirname, './node_modules')
      ]
   },
   module : {
      loaders : [
            {
               test : /(\.js|\.jsx)$/,
               exclude : /(node_modules)/,
               loader : 'babel',
               query : {
                  cacheDirectory : true,
                  presets : [ 'es2015', 'stage-0', 'react' ]
               }
            },
            {
               test : /(\.scss|\.css)$/,
               loader : ExtractTextPlugin
                     .extract(
                           'style',
                           'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass')
            } ]
   },
   postcss : [ autoprefixer ],
   sassLoader : {
      data : '@import "theme/style.scss";',
      includePaths : [ path.resolve(__dirname, './src/main/js') ]
   },
   plugins : [
      new ExtractTextPlugin('./target/generated-ui/style.css', {
         allChunks : true
      }),
      new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.optimize.CommonsChunkPlugin({
         name : 'vendor',
         filename : './target/generated-ui/vendor.bundle.js',
         minChunks : Infinity
      }),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.DefinePlugin({
         'process.env': {
            'NODE_ENV': JSON.stringify('development')
         },
         ROUTE_BASE : JSON.stringify('/dreadball')
      })
   ]
};
<commit_msg>Set environment configuration to allow easy overriding<commit_after>var path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

const env = process.env.NODE_ENV || 'development';

module.exports = {
   context : __dirname,
   entry : './src/main/js/index.js',
   devtool : 'inline-source-map',
   cache : true,
   debug : true,
   output : {
      path : __dirname,
      filename : './target/generated-ui/bundle.js'
   },
   resolve : {
      extensions : [ '', '.scss', '.css', '.js', '.json' ],
      modulesDirectories : [
         'src/main/js',
         path.resolve(__dirname, './src/main/js'),
         'node_modules',
         path.resolve(__dirname, './node_modules')
      ]
   },
   module : {
      loaders : [
            {
               test : /(\.js|\.jsx)$/,
               exclude : /(node_modules)/,
               loader : 'babel',
               query : {
                  cacheDirectory : true,
                  presets : [ 'es2015', 'stage-0', 'react' ]
               }
            },
            {
               test : /(\.scss|\.css)$/,
               loader : ExtractTextPlugin
                     .extract(
                           'style',
                           'css?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass')
            } ]
   },
   postcss : [ autoprefixer ],
   sassLoader : {
      data : '@import "theme/style.scss";',
      includePaths : [ path.resolve(__dirname, './src/main/js') ]
   },
   plugins : [
      new ExtractTextPlugin('./target/generated-ui/style.css', {
         allChunks : true
      }),
      new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.optimize.CommonsChunkPlugin({
         name : 'vendor',
         filename : './target/generated-ui/vendor.bundle.js',
         minChunks : Infinity
      }),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.DefinePlugin({
         'process.env': {
            NODE_ENV: JSON.stringify(env)
         },
         ROUTE_BASE : JSON.stringify('/dreadball')
      })
   ]
};
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const ExtraWatchWebpackPlugin = require('extra-watch-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// const CircularDependencyPlugin = require('circular-dependency-plugin');

const sharedConfig = {
    module: {
        rules: [
            {
                test: /\.(woff2?|ttf|otf|eot|svg|html)$/,
                include: [path.resolve(__dirname, 'build/src/')],
                use: [{
                    loader: 'file-loader',
                    options: { name: '[name].[ext]' }
                }]
            },
            {
                test: /\.(s*)css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader', 'resolve-url-loader', 'sass-loader'
                ]
            }
        ]
    },
    plugins: [
        // new CircularDependencyPlugin({
        //     include: [ path.resolve(__dirname, 'lib/') ],
        //     failOnError: false,
        //     cwd: process.cwd(),
        // }),
        new ExtraWatchWebpackPlugin({
            files: [
                './lib/**/*.scss',
                './lib/**/*.html'
            ],
        }),
        new webpack.DefinePlugin({
            __PLUGIN_VERSION_TIMESTAMP__: webpack.DefinePlugin.runtimeValue(() => `${new Date().valueOf()}`, true),
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
            'process.env.DEBUG': JSON.stringify(process.env.DEBUG)
        }),
        new MiniCssExtractPlugin({ filename: 'app.css' })
    ],
    resolve: {
        modules: [
            'node_modules',
            path.resolve(__dirname, 'lib/')
        ],
    }
}

function createEntry(src, outFolder, outFilename, isNode) {
    return {
        node: isNode ? void 0 : { fs: 'empty' }, // TODO find better solution? Currently used in file-handle.ts
        target: isNode ? 'node' : void 0,
        entry: path.resolve(__dirname, `lib/${src}.js`),
        output: { filename: `${outFilename}.js`, path: path.resolve(__dirname, `build/${outFolder}`) },
        ...sharedConfig
    }
}

function createEntryPoint(name, dir, out) {
    return {
        node: { fs: 'empty' }, // TODO find better solution? Currently used in file-handle.ts
        entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
        output: { filename: `${name}.js`, path: path.resolve(__dirname, `build/${out}`) },
        ...sharedConfig
    }
}

function createNodeEntryPoint(name, dir, out) {
    return {
        target: 'node',
        entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
        output: { filename: `${name}.js`, path: path.resolve(__dirname, `build/${out}`) },
        externals: {
            argparse: 'require("argparse")',
            'node-fetch': 'require("node-fetch")',
            'util.promisify': 'require("util.promisify")',
            xhr2: 'require("xhr2")',
        },
        ...sharedConfig
    }
}

function createApp(name) { return createEntryPoint('index', `apps/${name}`, name) }
function createBrowserTest(name) { return createEntryPoint(name, 'tests/browser', 'tests') }
function createNodeApp(name) { return createNodeEntryPoint('index', `apps/${name}`, name) }

module.exports = [
    createApp('viewer'),
    createApp('basic-wrapper'),
    createEntry('examples/proteopedia-wrapper/index', 'examples/proteopedia-wrapper', 'index'),
    createNodeApp('state-docs'),
    createNodeEntryPoint('preprocess', 'servers/model', 'model-server'),
    createApp('model-server-query'),

    createBrowserTest('font-atlas'),
    createBrowserTest('render-asa'),
    createBrowserTest('marching-cubes'),
    createBrowserTest('render-lines'),
    createBrowserTest('render-mesh'),
    createBrowserTest('render-shape'),
    createBrowserTest('render-spheres'),
    createBrowserTest('render-structure'),
    createBrowserTest('render-text'),
]<commit_msg>fix webpack config<commit_after>const path = require('path');
const webpack = require('webpack');
const ExtraWatchWebpackPlugin = require('extra-watch-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// const CircularDependencyPlugin = require('circular-dependency-plugin');

const sharedConfig = {
    module: {
        rules: [
            {
                test: /\.(woff2?|ttf|otf|eot|svg|html)$/,
                use: [{
                    loader: 'file-loader',
                    options: { name: '[name].[ext]' }
                }]
            },
            {
                test: /\.(s*)css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader', 'resolve-url-loader', 'sass-loader'
                ]
            }
        ]
    },
    plugins: [
        // new CircularDependencyPlugin({
        //     include: [ path.resolve(__dirname, 'lib/') ],
        //     failOnError: false,
        //     cwd: process.cwd(),
        // }),
        new ExtraWatchWebpackPlugin({
            files: [
                './lib/**/*.scss',
                './lib/**/*.html'
            ],
        }),
        new webpack.DefinePlugin({
            __PLUGIN_VERSION_TIMESTAMP__: webpack.DefinePlugin.runtimeValue(() => `${new Date().valueOf()}`, true),
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
            'process.env.DEBUG': JSON.stringify(process.env.DEBUG)
        }),
        new MiniCssExtractPlugin({ filename: 'app.css' })
    ],
    resolve: {
        modules: [
            'node_modules',
            path.resolve(__dirname, 'lib/')
        ],
    }
}

function createEntry(src, outFolder, outFilename, isNode) {
    return {
        node: isNode ? void 0 : { fs: 'empty' }, // TODO find better solution? Currently used in file-handle.ts
        target: isNode ? 'node' : void 0,
        entry: path.resolve(__dirname, `lib/${src}.js`),
        output: { filename: `${outFilename}.js`, path: path.resolve(__dirname, `build/${outFolder}`) },
        ...sharedConfig
    }
}

function createEntryPoint(name, dir, out) {
    return {
        node: { fs: 'empty' }, // TODO find better solution? Currently used in file-handle.ts
        entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
        output: { filename: `${name}.js`, path: path.resolve(__dirname, `build/${out}`) },
        ...sharedConfig
    }
}

function createNodeEntryPoint(name, dir, out) {
    return {
        target: 'node',
        entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
        output: { filename: `${name}.js`, path: path.resolve(__dirname, `build/${out}`) },
        externals: {
            argparse: 'require("argparse")',
            'node-fetch': 'require("node-fetch")',
            'util.promisify': 'require("util.promisify")',
            xhr2: 'require("xhr2")',
        },
        ...sharedConfig
    }
}

function createApp(name) { return createEntryPoint('index', `apps/${name}`, name) }
function createBrowserTest(name) { return createEntryPoint(name, 'tests/browser', 'tests') }
function createNodeApp(name) { return createNodeEntryPoint('index', `apps/${name}`, name) }

module.exports = [
    createApp('viewer'),
    createApp('basic-wrapper'),
    createEntry('examples/proteopedia-wrapper/index', 'examples/proteopedia-wrapper', 'index'),
    createNodeApp('state-docs'),
    createNodeEntryPoint('preprocess', 'servers/model', 'model-server'),
    createApp('model-server-query'),

    createBrowserTest('font-atlas'),
    createBrowserTest('render-asa'),
    createBrowserTest('marching-cubes'),
    createBrowserTest('render-lines'),
    createBrowserTest('render-mesh'),
    createBrowserTest('render-shape'),
    createBrowserTest('render-spheres'),
    createBrowserTest('render-structure'),
    createBrowserTest('render-text'),
]<|endoftext|>


<commit_before>// Look in ./config folder for webpack.dev.js
var webpack = require('./config/webpack.prod.js');

var config = {
	module: {

    loaders: [
    	{
		  test: /\.(jpe?g|png|jpg|gif|svg)$/i,
		  loader:'file'
		}
    ]
  }
}<commit_msg>webpack config adjust<commit_after>// Look in ./config folder for webpack.dev.js
var webpack = require('./config/webpack.prod.js');

var config = {
	module: {
	    loaders: [
	    	{
			  test: /\.(jpe?g|png|jpg|gif|svg)$/i,
			  loader:'file'
			}
	    ]
  	}
}

module.exports = config;<|endoftext|>


<commit_before>module.exports = {
  module: {
    noParse: [
      /node_modules\/sinon/,
    ],

    resolve: {
      alias: {
        sinon: 'sinon/pkg/sinon.js'
      }
    },

    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
        //include: [
          //path.resolve(__dirname, 'lib')
        //]
      }
    ]
  }
};<commit_msg>Fixed the incorrect webpack structure.<commit_after>module.exports = {
  resolve: {
    alias: {
      sinon: 'sinon/pkg/sinon.js'
    }
  },
  module: {
    noParse: [
      /node_modules\/sinon/,
    ],
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
        //include: [
          //path.resolve(__dirname, 'lib')
        //]
      }
    ]
  }
};<|endoftext|>


<commit_before>import webpack from 'webpack';
import path from 'path';

/*
  conditionally set webpack env variable
  used to differntiate production / development / demo builds
  values are: `dev`, `dist` or `demo`
*/
const ENV = process.env.WEBPACK_ENV;

/*
  Define `entry` array.
  Based on `ENV`, we will conditionally extend it properly.
*/
let entry = [];
const devAndDistEntry = [
  path.resolve(__dirname, 'src/index.js')
];
const devEntry = [
  'webpack-hot-middleware/client?reload=true'
];
const demoEntry = [
  path.resolve(__dirname, 'demo/src/index')
];

/*
  Define `output` object.
  Based on `ENV`, we will conditionally extend it properly.
*/
let output = {
  publicPath: '/'
};
const devAndDistOutput = {
  path: path.resolve(__dirname, 'dist'),
  library: 'diffy',
  libraryTarget: 'umd'
};
const devOutput = {
  filename: 'diffy.js'
};
const distOutput = {
  filename: 'diffy.min.js' //todo minify dist output
};
const demoOutput = {
  filename: 'demo.min.js',//todo minify demo output
  path: path.resolve(__dirname, 'demo/dist')
};

/*
  Define the es6 loader configuration object.
  Based on `ENV`, we will conditionally extend it properly.
*/
let es6LoaderConfig = {
  test: /\.js$/,
  loaders: ['babel']
};
const devAndDistEs6LoaderConfig = {
  include: path.resolve(__dirname, 'src'),
};
const demoEs6LoaderConfig = {
  exclude: [/node_modules/, /bower_components/]
};

/*
  Define `plugins` array.
  Based on ENV, we will conditionally extend it properly.
*/
let plugins = [];
const devPlugins = [
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NoErrorsPlugin()
];
const distPlugins = [
  // new webpack.optimize.UglifyJsPlugin({
  //   compress: {
  //     warnings: false
  //   }
  // })
];

/*
  Read the `ENV` and construct webpack configurations accordingly.
*/
switch(ENV) {
  case 'dev':
    entry = [...entry, ...devEntry, ...devAndDistEntry];
    output = Object.assign(output, devAndDistOutput, devOutput);
    plugins = [...plugins, ...devPlugins];
    es6LoaderConfig = Object.assign(es6LoaderConfig, devAndDistEs6LoaderConfig);
    break;
  case 'dist':
    entry = [...entry, ...devAndDistEntry];
    output = Object.assign(output, devAndDistOutput, distOutput);
    plugins = [...plugins, ...distPlugins];
    es6LoaderConfig = Object.assign(es6LoaderConfig, devAndDistEs6LoaderConfig);
    break;
  case 'demo':
    entry = [...entry, ...demoEntry];
    output = Object.assign(output, demoOutput);
    es6LoaderConfig = Object.assign(es6LoaderConfig, demoEs6LoaderConfig);
    break;
  default:
    // Use `dist` case by default
    entry = [...entry, ...devAndDistEntry];
    output = Object.assign(output, devAndDistOutput);
    es6LoaderConfig = Object.assign(es6LoaderConfig, devAndDistEs6LoaderConfig);
}

export default {
  debug: true,
  devtool: 'source-map',
  noInfo: false,
  entry,
  target: 'web',
  output,
  devServer: {
    contentBase: path.resolve(__dirname, 'src')
  },
  plugins,
  module: {
    loaders: [
      es6LoaderConfig
    ]
  },

};
<commit_msg>Remove trailing comma<commit_after>import webpack from 'webpack';
import path from 'path';

/*
  conditionally set webpack env variable
  used to differntiate production / development / demo builds
  values are: `dev`, `dist` or `demo`
*/
const ENV = process.env.WEBPACK_ENV;

/*
  Define `entry` array.
  Based on `ENV`, we will conditionally extend it properly.
*/
let entry = [];
const devAndDistEntry = [
  path.resolve(__dirname, 'src/index.js')
];
const devEntry = [
  'webpack-hot-middleware/client?reload=true'
];
const demoEntry = [
  path.resolve(__dirname, 'demo/src/index')
];

/*
  Define `output` object.
  Based on `ENV`, we will conditionally extend it properly.
*/
let output = {
  publicPath: '/'
};
const devAndDistOutput = {
  path: path.resolve(__dirname, 'dist'),
  library: 'diffy',
  libraryTarget: 'umd'
};
const devOutput = {
  filename: 'diffy.js'
};
const distOutput = {
  filename: 'diffy.min.js' //todo minify dist output
};
const demoOutput = {
  filename: 'demo.min.js',//todo minify demo output
  path: path.resolve(__dirname, 'demo/dist')
};

/*
  Define the es6 loader configuration object.
  Based on `ENV`, we will conditionally extend it properly.
*/
let es6LoaderConfig = {
  test: /\.js$/,
  loaders: ['babel']
};
const devAndDistEs6LoaderConfig = {
  include: path.resolve(__dirname, 'src'),
};
const demoEs6LoaderConfig = {
  exclude: [/node_modules/, /bower_components/]
};

/*
  Define `plugins` array.
  Based on ENV, we will conditionally extend it properly.
*/
let plugins = [];
const devPlugins = [
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NoErrorsPlugin()
];
const distPlugins = [
  // new webpack.optimize.UglifyJsPlugin({
  //   compress: {
  //     warnings: false
  //   }
  // })
];

/*
  Read the `ENV` and construct webpack configurations accordingly.
*/
switch(ENV) {
  case 'dev':
    entry = [...entry, ...devEntry, ...devAndDistEntry];
    output = Object.assign(output, devAndDistOutput, devOutput);
    plugins = [...plugins, ...devPlugins];
    es6LoaderConfig = Object.assign(es6LoaderConfig, devAndDistEs6LoaderConfig);
    break;
  case 'dist':
    entry = [...entry, ...devAndDistEntry];
    output = Object.assign(output, devAndDistOutput, distOutput);
    plugins = [...plugins, ...distPlugins];
    es6LoaderConfig = Object.assign(es6LoaderConfig, devAndDistEs6LoaderConfig);
    break;
  case 'demo':
    entry = [...entry, ...demoEntry];
    output = Object.assign(output, demoOutput);
    es6LoaderConfig = Object.assign(es6LoaderConfig, demoEs6LoaderConfig);
    break;
  default:
    // Use `dist` case by default
    entry = [...entry, ...devAndDistEntry];
    output = Object.assign(output, devAndDistOutput);
    es6LoaderConfig = Object.assign(es6LoaderConfig, devAndDistEs6LoaderConfig);
}

export default {
  debug: true,
  devtool: 'source-map',
  noInfo: false,
  entry,
  target: 'web',
  output,
  devServer: {
    contentBase: path.resolve(__dirname, 'src')
  },
  plugins,
  module: {
    loaders: [
      es6LoaderConfig
    ]
  }
};
<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  mode: 'development',
  entry: {
    app: './src/index.js',
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
    hot: true
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Passgen',
      hash: true,
      template: './src/index.html',
      filename: './index.html',
      favicon: './src/favicon.ico'
    }),
    new CopyWebpackPlugin([
        {from: 'src/images', to: 'images'}
    ]),
    new webpack.HotModuleReplacementPlugin()
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  }
};
<commit_msg>copies all other files over to dist<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  mode: 'development',
  entry: {
    app: './src/index.js',
  },
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist',
    hot: true
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Passgen',
      hash: true,
      template: './src/index.html',
      filename: './index.html',
      favicon: './src/favicon.ico'
    }),
    new CopyWebpackPlugin([
        {from: 'src/images', to: 'images'},
        {from: 'src/robots.txt', to: '.'},
        {from: 'src/404.html', to: '.'}
    ]),
    new webpack.HotModuleReplacementPlugin()
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  }
};
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'cheap-module-source-map',
    entry: [
        'react-hot-loader/patch',
        'webpack-hot-middleware/client',
        './src/app/index'
    ],
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/static/'
    },
    plugins: [
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.ProvidePlugin({
            $: "jquery",
            jquery: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "window.jquery": "jquery"
        })
    ],
    eslint: {
        configFile: '.eslintrc',
        failOnWarning: false,
        failOnError: false
    },
    module: {
        preLoaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'eslint'
            }
        ],
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel'],
                include: path.join(__dirname, 'src')
            }
            ,{
                test: /\.css$/, loader: "style!css"
            }
            ,{
                test: /\.woff(2)?(\?[a-z0-9#=&.]+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'
            }
            ,{
                test: /\.(ttf|eot|svg)(\?[a-z0-9#=&.]+)?$/, loader: 'file'
            }
        ]
    }
};
<commit_msg>New steps<commit_after>var path = require('path');
var webpack = require('webpack');
var FlowtypePlugin = require('flowtype-loader/plugin');
//var GlobalizePlugin = require('globalize-webpack-plugin');

module.exports = {
    devtool: 'cheap-module-source-map',
    entry: [
        'react-hot-loader/patch',
        'webpack-hot-middleware/client',
        './src/app/index'
    ],
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/static/'
    },
    plugins: [
        // new GlobalizePlugin({
        //     production: false,
        //     developmentLocale: "en",
        //     supportedLocales: [ "ar", "de", "en", "es", "pt", "ru", "zh" ],
        //     messages: "messages/[locale].json",
        //     output: "i18n/[locale].[hash].js"
        // }),
        new FlowtypePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.ProvidePlugin({
            $: "jquery",
            jquery: "jquery",
            jQuery: "jquery",
            "window.jQuery": "jquery",
            "window.jquery": "jquery"
        }),
    ],
    eslint: {
        configFile: '.eslintrc',
        failOnWarning: false,
        failOnError: false
    },
    module: {
        preLoaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'eslint'
            }
            , {
                test: /\.js$/
                , loader: "flowtype"
                , exclude: /node_modules/
            }
        ],
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel'],
                include: path.join(__dirname, 'src')
            }
            , {
                test: /\.css$/, loader: "style!css"
            }
            , {test: /\.less$/, loader: "style-loader!css-loader!less-loader"}
            , {test: /\.gif$/, loader: "url-loader?mimetype=image/png"}
            , {
                test: /\.woff(2)?(\?[a-z0-9#=&.]+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff'
            }
            , {
                test: /\.(ttf|eot|svg)(\?[a-z0-9#=&.]+)?$/, loader: 'file'
            }
        ]

    }
};
<|endoftext|>


<commit_before>const webpack = require('webpack');

const path = require('path');
const merge = require('webpack-merge');

const TARGET = process.env.npm_lifecycle_event;
const DEFAULT_PORT = process.env.PORT || 3000;
const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build')
};

const common = {
  entry: PATHS.app,
  output: {
    path: PATHS.build,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loader: 'style!css?sourceMap&modules!postcss!sass?sourceMap',
        include: PATHS.app
      },
      {
        test: /\.js$/,
        loaders: ['babel?cacheDirectory'],
        include: PATHS.app
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin()
  ]
};

module.exports = merge(common, {
  start: {
    devtool: 'eval-source-map',
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      stats: 'errors-only',
      host: process.env.HOST,
      port: process.env.PORT || DEFAULT_PORT
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin()
    ]
  },
  build: {

  }
}[TARGET]);
<commit_msg>default port<commit_after>const webpack = require('webpack');

const path = require('path');
const merge = require('webpack-merge');

const TARGET = process.env.npm_lifecycle_event;
const DEFAULT_PORT = process.env.PORT || 3000;
const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build')
};

const common = {
  entry: PATHS.app,
  output: {
    path: PATHS.build,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        loader: 'style!css?sourceMap&modules!postcss!sass?sourceMap',
        include: PATHS.app
      },
      {
        test: /\.js$/,
        loaders: ['babel?cacheDirectory'],
        include: PATHS.app
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin()
  ]
};

module.exports = merge(common, {
  start: {
    devtool: 'eval-source-map',
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      stats: 'errors-only',
      host: process.env.HOST,
      port: DEFAULT_PORT
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin()
    ]
  },
  build: {

  }
}[TARGET]);
<|endoftext|>


<commit_before>var _ = require('underscore');
var roll20 = require('./roll20');

/**
 * @constructor
 */
function Command(root, handler) {
    'use strict';
    this.root = root;
    this.handler = handler;
    this.parsers = [];
}

Command.prototype.option = function (optionString, validator) {
    'use strict';
    this.parsers.push(function (arg, errors, options) {
        var argParts = arg.split(/\s+/);
        if (argParts[0].toLowerCase() === optionString.toLowerCase()) {
            if (argParts.length <= 2) {
                //Allow for bare switches
                var value = argParts.length === 2 ? argParts[1] : true;
                var result = validator(value);
                if (result.valid) {
                    options[argParts[0]] = result.converted;
                    return options;
                }
                else {
                    errors.push('Invalid value [' + value + '] for option [' + argParts[0] + ']');
                }
            }
            return true;
        }
        return false;
    });
    return this;
};

Command.prototype.options = function (optsSpec) {
    'use strict';
    var self = this;
    _.each(optsSpec, function (validator, key) {
        self.option(key, validator);
    });
    return this;
};

Command.prototype.optionLookup = function (groupName, lookupFunction) {
    'use strict';
    this.parsers.push(function (arg, errors, options) {
        options[groupName] = options[groupName] || [];
        var name = arg.toLowerCase();
        var resolved = lookupFunction(name);
        if (resolved) {
            options[groupName].push(resolved);
            return true;
        }
        return false;
    });
    return this;
};

Command.prototype.handle = function (args, selection) {
    'use strict';
    var self = this;
    var options = _.reduce(args, function (options, arg) {
        var parser = _.find(self.parsers, function (parser) {
            return parser(arg, options.errors, options);
        });
        if (!parser) {
            options.errors.push('Unrecognised or poorly formed option [$$$]', arg);
        }

        return options;
    }, {errors: []});
    if (options.errors.length > 0) {
        throw options.errors.join('\n');
    }
    delete options.errors;
    options.selected = this.selectionSpec && processSelection(selection || [], this.selectionSpec);
    this.handler(options);
};

Command.prototype.withSelection = function (selectionSpec) {
    'use strict';
    this.selectionSpec = selectionSpec;
    return this;
};

Command.prototype.addCommand = function (cmdString, handler) {
    'use strict';
    return this.root.addCommand(cmdString, handler);
};

Command.prototype.end = function () {
    'use strict';
    return this.root;
};

function processSelection(selection, constraints) {
    'use strict';
    return _.reduce(constraints, function (result, constraintDetails, type) {

        var objects = _.chain(selection)
          .where({_type: type === 'character' ? 'graphic' : type})
          .map(function (selected) {
              return roll20.getObj(selected._type, selected._id);
          })
          .map(function (object) {
              if (type === 'character' && object) {
                  var represents = object.get('represents');
                  if (represents) {
                      return roll20.getObj('character', represents);
                  }
              }
              return object;
          })
          .compact()
          .value();
        if (_.size(objects) < constraintDetails.min || _.size(objects) > constraintDetails.max) {
            throw 'Wrong number of objects of type [' + type + '] selected, should be between ' + constraintDetails.min + ' and ' + constraintDetails.max;
        }
        switch (_.size(objects)) {
            case 0:
                break;
            case 1:
                if (constraintDetails.max === 1) {
                    result[type] = objects[0];
                }
                else {
                    result[type] = objects;
                }
                break;
            default:
                result[type] = objects;
        }
        return result;
    }, {});
}

module.exports = function (rootCommand) {
    'use strict';

    var commands = {};
    return {
        addCommand: function (cmdString, handler) {
            var command = new Command(this, handler);
            commands[cmdString] = command;
            return command;
        },

        processCommand: function (msg) {
            var prefix = '!' + rootCommand + '-';
            if (msg.type === 'api' && msg.content.indexOf(prefix) === 0) {
                var cmdString = msg.content.slice(prefix.length);
                var parts = cmdString.split(/\s+--/);
                var cmdName = parts.shift();
                var cmd = commands[cmdName];
                if (!cmd) {
                    throw new Error('Unrecognised command ' + prefix + cmdName);
                }
                cmd.handle(parts, msg.selected);
            }
        }

    };

};
<commit_msg>Improve error message for incorrect commands<commit_after>var _ = require('underscore');
var roll20 = require('./roll20');

/**
 * @constructor
 */
function Command(root, handler) {
    'use strict';
    this.root = root;
    this.handler = handler;
    this.parsers = [];
}

Command.prototype.option = function (optionString, validator) {
    'use strict';
    this.parsers.push(function (arg, errors, options) {
        var argParts = arg.split(/\s+/);
        if (argParts[0].toLowerCase() === optionString.toLowerCase()) {
            if (argParts.length <= 2) {
                //Allow for bare switches
                var value = argParts.length === 2 ? argParts[1] : true;
                var result = validator(value);
                if (result.valid) {
                    options[argParts[0]] = result.converted;
                    return options;
                }
                else {
                    errors.push('Invalid value [' + value + '] for option [' + argParts[0] + ']');
                }
            }
            return true;
        }
        return false;
    });
    return this;
};

Command.prototype.options = function (optsSpec) {
    'use strict';
    var self = this;
    _.each(optsSpec, function (validator, key) {
        self.option(key, validator);
    });
    return this;
};

Command.prototype.optionLookup = function (groupName, lookupFunction) {
    'use strict';
    this.parsers.push(function (arg, errors, options) {
        options[groupName] = options[groupName] || [];
        var name = arg.toLowerCase();
        var resolved = lookupFunction(name);
        if (resolved) {
            options[groupName].push(resolved);
            return true;
        }
        return false;
    });
    return this;
};

Command.prototype.handle = function (args, selection) {
    'use strict';
    var self = this;
    var options = _.reduce(args, function (options, arg) {
        var parser = _.find(self.parsers, function (parser) {
            return parser(arg, options.errors, options);
        });
        if (!parser) {
            options.errors.push('Unrecognised or poorly formed option [$$$]', arg);
        }

        return options;
    }, {errors: []});
    if (options.errors.length > 0) {
        throw options.errors.join('\n');
    }
    delete options.errors;
    options.selected = this.selectionSpec && processSelection(selection || [], this.selectionSpec);
    this.handler(options);
};

Command.prototype.withSelection = function (selectionSpec) {
    'use strict';
    this.selectionSpec = selectionSpec;
    return this;
};

Command.prototype.addCommand = function (cmdString, handler) {
    'use strict';
    return this.root.addCommand(cmdString, handler);
};

Command.prototype.end = function () {
    'use strict';
    return this.root;
};

function processSelection(selection, constraints) {
    'use strict';
    return _.reduce(constraints, function (result, constraintDetails, type) {

        var objects = _.chain(selection)
          .where({_type: type === 'character' ? 'graphic' : type})
          .map(function (selected) {
              return roll20.getObj(selected._type, selected._id);
          })
          .map(function (object) {
              if (type === 'character' && object) {
                  var represents = object.get('represents');
                  if (represents) {
                      return roll20.getObj('character', represents);
                  }
              }
              return object;
          })
          .compact()
          .value();
        if (_.size(objects) < constraintDetails.min || _.size(objects) > constraintDetails.max) {
            throw 'Wrong number of objects of type [' + type + '] selected, should be between ' + constraintDetails.min + ' and ' + constraintDetails.max;
        }
        switch (_.size(objects)) {
            case 0:
                break;
            case 1:
                if (constraintDetails.max === 1) {
                    result[type] = objects[0];
                }
                else {
                    result[type] = objects;
                }
                break;
            default:
                result[type] = objects;
        }
        return result;
    }, {});
}

module.exports = function (rootCommand) {
    'use strict';

    var commands = {};
    return {
        addCommand: function (cmdString, handler) {
            var command = new Command(this, handler);
            commands[cmdString] = command;
            return command;
        },

        processCommand: function (msg) {
            var prefix = '!' + rootCommand + '-';
            if (msg.type === 'api' && msg.content.indexOf(prefix) === 0) {
                var cmdString = msg.content.slice(prefix.length);
                var parts = cmdString.split(/\s+--/);
                var cmdName = parts.shift();
                var cmd = commands[cmdName];
                if (!cmd) {
                    throw 'Unrecognised command ' + prefix + cmdName;
                }
                cmd.handle(parts, msg.selected);
            }
        }

    };

};
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const packageJSON = require('../package.json');

const getBanner = function (compressing) {
  return packageJSON.name + (compressing ? ' (compressed)' : ' (uncompressed)') + '\n' +
    packageJSON.homepage + '\n' +
    'Version: ' + packageJSON.version + ' -- ' + (new Date()).toISOString() + '\n' +
    'License: ' + packageJSON.license;
};

const ENV = (process.env.npm_lifecycle_event.indexOf('dev') === 0) ? 'development' : 'production';
console.log('********** webpack runs in ' + ENV + ' environment **********\n');

let configEnv = {};

const arrTestFiles = fs.readdirSync('test')
  .map(e => (e.indexOf('Spec.js') !== -1) ?
    {[e.replace(/\.js/, '')]: path.resolve(__dirname, '../test/' + e)} : null
  )
  .filter(e => e !== null);

let testFiles = {};
arrTestFiles.forEach(e => testFiles[Object.keys(e)[0]] = e[Object.keys(e)[0]]);

if (ENV === 'development') {
  configEnv = {
    output: {
      filename: '[name].js'
    },

    rules: [{
      enforce: 'pre',
      test: /Spec\.js$/,
      include: path.resolve(__dirname, '../test'),
      use: [{
        loader: 'jshint-loader'
      }]
    }],

    devtool: 'inline-source-map',

    entry: testFiles,

    plugins: [],

    devServer: {
      contentBase: path.join(__dirname, '../demo/'),
      inline: true,
      quiet: false,
      hot: true,
      port: 5005,
      publicPath: path.join(__dirname, '../')
    },

    watch: true
  }
}

if (ENV === 'production') {
  configEnv = {
    output: {
      path: path.join(__dirname, '../dist'),
      filename: '[name].js'
    },

    rules: [],

    devtool: 'source-map',

    entry: {
      'ui-scroll.min': path.resolve(__dirname, '../src/ui-scroll.js'),
      'ui-scroll-grid.min': path.resolve(__dirname, '../src/ui-scroll-grid.js')
    },

    plugins: [
      new CleanWebpackPlugin('dist', {
        root: path.join(__dirname, '..')
      }),
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          warnings: true,
        },
        output: {
          comments: false,
        },
        include: /\.min\.js$/
      }),
      new CopyWebpackPlugin([
        {from: 'src/ui-scroll-jqlite.js', to: 'ui-scroll-jqlite.min.js'},
        {from: 'src/ui-scroll-jqlite.js', to: 'ui-scroll-jqlite.js'}
      ], {copyUnmodified: true}),
      new webpack.BannerPlugin(getBanner(true))
    ],

    devServer: {},

    watch: false
  }
}

module.exports = {
  entry: Object.assign({
    'ui-scroll': path.resolve(__dirname, '../src/ui-scroll.js'),
    'ui-scroll-grid': path.resolve(__dirname, '../src/ui-scroll-grid.js')
  }, configEnv.entry),

  output: configEnv.output,

  cache: false,

  devtool: configEnv.devtool,

  module: {
    rules: [...configEnv.rules,
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: ['es2015']
        }
      },
      {
        enforce: 'pre',
        test: /\.js$/,
        include: path.resolve(__dirname, '../src'),
        use: [{
          loader: 'jshint-loader'
        }]
      }
    ]
  },

  plugins: configEnv.plugins,

  devServer: configEnv.devServer,

  watch: configEnv.watch
};
<commit_msg>WebpackDevServer and including .js-files<commit_after>const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const packageJSON = require('../package.json');

const getBanner = function (compressing) {
  return packageJSON.name + (compressing ? ' (compressed)' : ' (uncompressed)') + '\n' +
    packageJSON.homepage + '\n' +
    'Version: ' + packageJSON.version + ' -- ' + (new Date()).toISOString() + '\n' +
    'License: ' + packageJSON.license;
};

const ENV = (process.env.npm_lifecycle_event.indexOf('dev') === 0) ? 'development' : 'production';
console.log('********** webpack runs in ' + ENV + ' environment **********\n');

let configEnv = {};

const arrTestFiles = fs.readdirSync('test')
  .map(e => (e.indexOf('Spec.js') !== -1) ?
    {[e.replace(/\.js/, '')]: path.resolve(__dirname, '../test/' + e)} : null
  )
  .filter(e => e !== null);

let testFiles = {};
arrTestFiles.forEach(e => testFiles[Object.keys(e)[0]] = e[Object.keys(e)[0]]);

if (ENV === 'development') {
  configEnv = {
    output: {
      filename: '[name].js'
    },

    rules: [{
      enforce: 'pre',
      test: /Spec\.js$/,
      include: path.resolve(__dirname, '../test'),
      use: [{
        loader: 'jshint-loader'
      }]
    }],

    devtool: 'inline-source-map',

    entry: testFiles,

    plugins: [],

    devServer: {
      // contentBase: path.join(__dirname, '../demo/'),
      historyApiFallback: {
        rewrites: [
          { from: /^\/$/, to: '/demo/index.html' },
          { from: /\/index\.html$/, to: '/demo/index.html' },
          { from: /\/css\/style\.css$/, to: '/demo/css/style.css' },
          { from: /\/css\/bootstrap\.css$/, to: '/demo/css/bootstrap.css' },
          { from: /\/serviceDatasource\/serviceDatasource\.html$/, to: '/demo/serviceDatasource/serviceDatasource.html' },
          { from: /\/serviceDatasource\/serviceDatasource\.js$/, to: '/demo/serviceDatasource/serviceDatasource.js' }
        ]
      },
      inline: true,
      quiet: false,
      hot: true,
      port: 5005,
      publicPath: path.join(__dirname, '../')
    },

    watch: true
  }
}

if (ENV === 'production') {
  configEnv = {
    output: {
      path: path.join(__dirname, '../dist'),
      filename: '[name].js'
    },

    rules: [],

    devtool: 'source-map',

    entry: {
      'ui-scroll.min': path.resolve(__dirname, '../src/ui-scroll.js'),
      'ui-scroll-grid.min': path.resolve(__dirname, '../src/ui-scroll-grid.js')
    },

    plugins: [
      new CleanWebpackPlugin('dist', {
        root: path.join(__dirname, '..')
      }),
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          warnings: true,
        },
        output: {
          comments: false,
        },
        include: /\.min\.js$/
      }),
      new CopyWebpackPlugin([
        {from: 'src/ui-scroll-jqlite.js', to: 'ui-scroll-jqlite.min.js'},
        {from: 'src/ui-scroll-jqlite.js', to: 'ui-scroll-jqlite.js'}
      ], {copyUnmodified: true}),
      new webpack.BannerPlugin(getBanner(true))
    ],

    devServer: {},

    watch: false
  }
}

module.exports = {
  entry: Object.assign({
    'ui-scroll': path.resolve(__dirname, '../src/ui-scroll.js'),
    'ui-scroll-grid': path.resolve(__dirname, '../src/ui-scroll-grid.js')
  }, configEnv.entry),

  output: configEnv.output,

  cache: false,

  devtool: configEnv.devtool,

  module: {
    rules: [...configEnv.rules,
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: ['es2015']
        }
      },
      {
        enforce: 'pre',
        test: /\.js$/,
        include: path.resolve(__dirname, '../src'),
        use: [{
          loader: 'jshint-loader'
        }]
      }
    ]
  },

  plugins: configEnv.plugins,

  devServer: configEnv.devServer,

  watch: configEnv.watch
};
<|endoftext|>


<commit_before>/**
 * External dependencies
 */
import { render } from '@testing-library/react';
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { RegistryProvider } from '@wordpress/data';

/**
 * Internal dependencies
 */
import { createTestRegistry } from 'tests/js/utils';

// Override `@testing-library/react`'s render method with one that includes
// our data store.
const customRender = ( children, options = {} ) => {
	const {
		registry = createTestRegistry(),
		...renderOptions
	} = options;
	return {
		...render( (
			<RegistryProvider value={ registry }>
				{ children }
			</RegistryProvider>
		), renderOptions ),
		registry,
	};
};

// Export our own test utils from this file.
export * from 'tests/js/utils';

// Export @testing-library/react as normal.
export * from '@testing-library/react';

// Override @testing-library/react's render method with our own.
export { customRender as render };
<commit_msg>Remove unused import.<commit_after>/**
 * External dependencies
 */
import { render } from '@testing-library/react';

/**
 * WordPress dependencies
 */
import { RegistryProvider } from '@wordpress/data';

/**
 * Internal dependencies
 */
import { createTestRegistry } from 'tests/js/utils';

// Override `@testing-library/react`'s render method with one that includes
// our data store.
const customRender = ( children, options = {} ) => {
	const {
		registry = createTestRegistry(),
		...renderOptions
	} = options;
	return {
		...render( (
			<RegistryProvider value={ registry }>
				{ children }
			</RegistryProvider>
		), renderOptions ),
		registry,
	};
};

// Export our own test utils from this file.
export * from 'tests/js/utils';

// Export @testing-library/react as normal.
export * from '@testing-library/react';

// Override @testing-library/react's render method with our own.
export { customRender as render };
<|endoftext|>


<commit_before>/*
   Copyright 2010 Ephox Corporation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
(function() {
	if (window.robot) {
		// Don't load if there's already a version of robot loaded.
		return;
	}

	window.robot = {

		onload: function(userCallback) {
			if (this.ready) {
				userCallback();
			} else {
				this.userCallback = userCallback;
			}
		},

		init: function(useDocumentWrite) {
			var jarUrl = "JSRobot.jar";
			var scripts = document.getElementsByTagName('script');
			for (var i = 0; i < scripts.length; i++) {
				var src = scripts[i].src;
				var regex = /^(.*\/?)robot.js(\?|$)/;
				if (src && regex.test(src)) {
					jarUrl = regex.exec(src)[1] + "JSRobot.jar";
				}
			}
			var appletTag = '<applet archive="' + jarUrl + '" code="com.ephox.jsrobot.JSRobot" id="robotApplet" width="10" height="10" mayscript="true" initial_focus="false"><param name="initial_focus" value="false" /><param name="mayscript" value="true" /></applet>';
			if (useDocumentWrite) {
				document.write(appletTag);
			} else {
				var div = document.createElement('div');
				document.body.appendChild(div);
				div.innerHTML = appletTag;
			}
			this.appletInstance = document.getElementById('robotApplet');
		},

		callback: function() {
			if (window.robotUsesSymbols){
				this.initSymbols();
			}
			if (this.userCallback) {
				setTimeout(this.userCallback, 100);
			}
			return "Callback received.";
		},

		initSymbols: function(){
			var input = document.createElement("input");
			document.body.appendChild(input);
			input.focus();
			var t = this;
			function loadSymbolsFromInput(){
				t.symbols = input.value;
				t.ready = true;
				document.body.removeChild(input);
			}

		  	this.appletAction(input, loadSymbolsFromInput, function() {
				  return this.getApplet().typeSymbolsAboveNumberKeys();
			});
		},

		type: function(key, shiftKey, callback, focusElement) {
			var keycode = this.getKeycode(key);
			shiftKey = !!shiftKey;
			this.appletAction(focusElement, callback, function() {
				return this.getApplet().typeKey(keycode, shiftKey);
			});
		},

		typeSymbol: function(symbol, callback, focusElement) {
			if (!window.robotUsesSymbols) {
				alert("need to define the attribute\nwindow.robotUsesSymbols\nbefore using the typeSymbol function.");
			}
			var t = this;

			var symbolNumber = t.symbols.search("\\"+symbol);
			if (symbolNumber <0) {
				throw new Error("The symbol "+ symbol + " could not be located on your keyboard.  Unable to press key");
			}
			return t.type(symbolNumber+48, true, callback, focusElement);
		},

		forwardDelete: function(callback, focusElement) {
			this.type(0x7F, false, callback, focusElement);
		},

		cut: function(callback, focusElement) {
			this.typeAsShortcut('x', callback, focusElement, 'cut');
		},

		copy: function(callback, focusElement) {
			this.typeAsShortcut('c', callback, focusElement, 'copy');
		},

		paste: function(callback, focusElement) {
			this.typeAsShortcut('v', callback, focusElement, 'paste');
		},

		pasteText: function(content, callback, focusElement) {
			var actionResult = this.getApplet().setClipboard(content);
			if (actionResult) {
				throw { message: "JSRobot error: " + actionResult };
			}
			this.paste(callback, focusElement);
		},

		typeAsShortcut: function(key, callback, focusElement, event) {
			var keycode = this.getKeycode(key);
			this.appletAction(focusElement, callback, function() {
				return this.getApplet().typeAsShortcut(keycode);
			}, event);
		},

		getKeycode: function(key) {
			if (key.toUpperCase && key.charCodeAt) {
				if (/^[a-zA-Z\n\b\t]$/.test(key)) {
					return key.toUpperCase().charCodeAt(0);
				} else {
					throw { message: 'Invalid character to type. Must be a-z or A-Z, otherwise use the key code directly.' };
				}
			}
			return key;
		},

		captureScreenShot: function() {
			return this.getApplet().captureScreenShot();
		},

		setScreenShotDirectory: function(dir) {
			this.getApplet().setScreenShotDirectory(dir);
		},

		getApplet: function() {
			return this.appletInstance;
		},

		appletAction: function(focusElement, continueCallback, action, event) {
			var actionResult, listenerActivated = false, listenerType = event || 'keyup', timeout, curEl, toFocus = [], t = this;

			// Make sure the focus change has taken effect.
			var afterFocused = function() {
				timeout = setTimeout(function() {
					if (listenerActivated) return false;
					doListeners(false);
					if (continueCallback) {
						setTimeout(continueCallback, 0);
					}
				}, 10000);
				actionResult = action.apply(t);
				if (actionResult) {
					throw { message: "JSRobot error: " + actionResult };
				}
				if (!focusElement && continueCallback) {
					setTimeout(continueCallback, 100);
				}
			};

			var listener = function() {
				if (listenerActivated) return;
				listenerActivated = true;
				clearTimeout(timeout);
				doListeners(false);
				if (continueCallback) {
					setTimeout(continueCallback, 100);
				}
			};
			var doListeners = function(add) {
				// Listen as high up in the hierarchy as possible to give us the best chance of getting the event before any JS listeners cancel it.
				var target = focusElement.defaultView || focusElement.ownerDocument || focusElement;
				if (focusElement.addEventListener) {
					target[add ? 'addEventListener' : 'removeEventListener'](listenerType, listener, true);
				} else {
					focusElement[add ? 'attachEvent' : 'detachEvent']('on' + listenerType, listener);
					target[add ? 'attachEvent' : 'detachEvent']('on' + listenerType, listener);
				}
			};

			if (!focusElement) {
				focusElement = document.activeElement;
				while (focusElement && (focusElement.contentDocument || focusElement.contentWindow)) {
					if (focusElement.contentDocument) {
						focusElement = focusElement.contentDocument.activeElement;
					} else {
						focusElement = focusElement.contentWindow.document.activeElement;
					}
				}
			}
			if (navigator.userAgent.indexOf('MSIE') < 0) {
				curEl = focusElement;
				while (curEl) {
					if (curEl.frameElement) {
						toFocus.push(curEl);
						toFocus.push(curEl.frameElement);
						curEl = curEl.frameElement;
					} else if (curEl.parent && curEl.parent !== curEl) {
						toFocus.push(curEl.parent);
						curEl = curEl.parent;
					} else if (curEl.defaultView) {
						toFocus.push(curEl.defaultView);
						curEl = curEl.defaultView;
					} else if (curEl.ownerDocument) {
						toFocus.push(curEl.ownerDocument.body);
						curEl = curEl.ownerDocument;
					} else {
						curEl = null;
					}
				}
			}

			var focused = [];
			var focusNext = function() {
				if (toFocus.length > 0) {
					curEl = toFocus.pop();
					focused.push(curEl);
					if (curEl.focus) curEl.focus();
					setTimeout(focusNext, 0);
				} else {
					doListeners(true);
					focusElement.focus();

					setTimeout(afterFocused, 0);
				}
			};
			if (focusElement) {
				focusNext();
			} else {
				afterFocused();
			}
		}
	};

	function robotOnload() {
		window.robot.init();
	}
	if (document.addEventListener) {
		window.addEventListener('load', robotOnload, true);
	} else {
		// If you don't init straight away on IE, it gets the applet context wrong.
		window.robot.init(true);
	}
})();
<commit_msg>Modified robot.js to call the userCallback once the initSymbols is done.<commit_after>/*
   Copyright 2010 Ephox Corporation

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
(function() {
	if (window.robot) {
		// Don't load if there's already a version of robot loaded.
		return;
	}

	window.robot = {

		onload: function(userCallback) {
			if (this.ready) {
				userCallback();
			} else {
				this.userCallback = userCallback;
			}
		},

		init: function(useDocumentWrite) {
			var jarUrl = "JSRobot.jar";
			var scripts = document.getElementsByTagName('script');
			for (var i = 0; i < scripts.length; i++) {
				var src = scripts[i].src;
				var regex = /^(.*\/?)robot.js(\?|$)/;
				if (src && regex.test(src)) {
					jarUrl = regex.exec(src)[1] + "JSRobot.jar";
				}
			}
			var appletTag = '<applet archive="' + jarUrl + '" code="com.ephox.jsrobot.JSRobot" id="robotApplet" width="10" height="10" mayscript="true" initial_focus="false"><param name="initial_focus" value="false" /><param name="mayscript" value="true" /></applet>';
			if (useDocumentWrite) {
				document.write(appletTag);
			} else {
				var div = document.createElement('div');
				document.body.appendChild(div);
				div.innerHTML = appletTag;
			}
			this.appletInstance = document.getElementById('robotApplet');
		},

		callback: function() {
			if (window.robotUsesSymbols){
				this.initSymbols();
			} else if (this.userCallback) {
				setTimeout(this.userCallback, 100);
			}

			return "Callback received.";
		},

		initSymbols: function(){
			var input = document.createElement("input");
			document.body.appendChild(input);
			input.focus();
			var t = this;
			function loadSymbolsFromInput(){
				t.symbols = input.value;
				t.ready = true;
				document.body.removeChild(input);

				if (t.userCallback) {
					setTimeout(t.userCallback, 100);
				}
			}

		  	this.appletAction(input, loadSymbolsFromInput, function() {
				  return this.getApplet().typeSymbolsAboveNumberKeys();
			});
		},

		type: function(key, shiftKey, callback, focusElement) {
			var keycode = this.getKeycode(key);
			shiftKey = !!shiftKey;
			this.appletAction(focusElement, callback, function() {
				return this.getApplet().typeKey(keycode, shiftKey);
			});
		},

		typeSymbol: function(symbol, callback, focusElement) {
			if (!window.robotUsesSymbols) {
				alert("need to define the attribute\nwindow.robotUsesSymbols\nbefore using the typeSymbol function.");
			}
			var t = this;

			var symbolNumber = t.symbols.search("\\"+symbol);
			if (symbolNumber <0) {
				throw new Error("The symbol "+ symbol + " could not be located on your keyboard.  Unable to press key");
			}
			return t.type(symbolNumber+48, true, callback, focusElement);
		},

		forwardDelete: function(callback, focusElement) {
			this.type(0x7F, false, callback, focusElement);
		},

		cut: function(callback, focusElement) {
			this.typeAsShortcut('x', callback, focusElement, 'cut');
		},

		copy: function(callback, focusElement) {
			this.typeAsShortcut('c', callback, focusElement, 'copy');
		},

		paste: function(callback, focusElement) {
			this.typeAsShortcut('v', callback, focusElement, 'paste');
		},

		pasteText: function(content, callback, focusElement) {
			var actionResult = this.getApplet().setClipboard(content);
			if (actionResult) {
				throw { message: "JSRobot error: " + actionResult };
			}
			this.paste(callback, focusElement);
		},

		typeAsShortcut: function(key, callback, focusElement, event) {
			var keycode = this.getKeycode(key);
			this.appletAction(focusElement, callback, function() {
				return this.getApplet().typeAsShortcut(keycode);
			}, event);
		},

		getKeycode: function(key) {
			if (key.toUpperCase && key.charCodeAt) {
				if (/^[a-zA-Z\n\b\t]$/.test(key)) {
					return key.toUpperCase().charCodeAt(0);
				} else {
					throw { message: 'Invalid character to type. Must be a-z or A-Z, otherwise use the key code directly.' };
				}
			}
			return key;
		},

		captureScreenShot: function() {
			return this.getApplet().captureScreenShot();
		},

		setScreenShotDirectory: function(dir) {
			this.getApplet().setScreenShotDirectory(dir);
		},

		getApplet: function() {
			return this.appletInstance;
		},

		appletAction: function(focusElement, continueCallback, action, event) {
			var actionResult, listenerActivated = false, listenerType = event || 'keyup', timeout, curEl, toFocus = [], t = this;

			// Make sure the focus change has taken effect.
			var afterFocused = function() {
				timeout = setTimeout(function() {
					if (listenerActivated) return false;
					doListeners(false);
					if (continueCallback) {
						setTimeout(continueCallback, 0);
					}
				}, 10000);
				actionResult = action.apply(t);
				if (actionResult) {
					throw { message: "JSRobot error: " + actionResult };
				}
				if (!focusElement && continueCallback) {
					setTimeout(continueCallback, 100);
				}
			};

			var listener = function() {
				if (listenerActivated) return;
				listenerActivated = true;
				clearTimeout(timeout);
				doListeners(false);
				if (continueCallback) {
					setTimeout(continueCallback, 100);
				}
			};
			var doListeners = function(add) {
				// Listen as high up in the hierarchy as possible to give us the best chance of getting the event before any JS listeners cancel it.
				var target = focusElement.defaultView || focusElement.ownerDocument || focusElement;
				if (focusElement.addEventListener) {
					target[add ? 'addEventListener' : 'removeEventListener'](listenerType, listener, true);
				} else {
					focusElement[add ? 'attachEvent' : 'detachEvent']('on' + listenerType, listener);
					target[add ? 'attachEvent' : 'detachEvent']('on' + listenerType, listener);
				}
			};

			if (!focusElement) {
				focusElement = document.activeElement;
				while (focusElement && (focusElement.contentDocument || focusElement.contentWindow)) {
					if (focusElement.contentDocument) {
						focusElement = focusElement.contentDocument.activeElement;
					} else {
						focusElement = focusElement.contentWindow.document.activeElement;
					}
				}
			}
			if (navigator.userAgent.indexOf('MSIE') < 0) {
				curEl = focusElement;
				while (curEl) {
					if (curEl.frameElement) {
						toFocus.push(curEl);
						toFocus.push(curEl.frameElement);
						curEl = curEl.frameElement;
					} else if (curEl.parent && curEl.parent !== curEl) {
						toFocus.push(curEl.parent);
						curEl = curEl.parent;
					} else if (curEl.defaultView) {
						toFocus.push(curEl.defaultView);
						curEl = curEl.defaultView;
					} else if (curEl.ownerDocument) {
						toFocus.push(curEl.ownerDocument.body);
						curEl = curEl.ownerDocument;
					} else {
						curEl = null;
					}
				}
			}

			var focused = [];
			var focusNext = function() {
				if (toFocus.length > 0) {
					curEl = toFocus.pop();
					focused.push(curEl);
					if (curEl.focus) curEl.focus();
					setTimeout(focusNext, 0);
				} else {
					doListeners(true);
					focusElement.focus();

					setTimeout(afterFocused, 0);
				}
			};
			if (focusElement) {
				focusNext();
			} else {
				afterFocused();
			}
		}
	};

	function robotOnload() {
		window.robot.init();
	}
	if (document.addEventListener) {
		window.addEventListener('load', robotOnload, true);
	} else {
		// If you don't init straight away on IE, it gets the applet context wrong.
		window.robot.init(true);
	}
})();
<|endoftext|>


<commit_before>import test from 'tape'

import {shortname, longname} from '../src/language'

function check (t, lang, short, long) {
  t.equal(shortname(lang), short)
  t.equal(longname(shortname(lang)), long)
  t.equal(shortname(short), short)
  t.equal(longname(long), long)
}

test('pack works for primitive types', function (t) {
  check(t, 'Javascript', 'js', 'JavaScript')
  check(t, 'Julia', 'jl', 'Julia')
  check(t, 'Python', 'py', 'Python')
  check(t, 'R', 'r', 'R')
  check(t, 'SQL', 'sql', 'SQL')

  t.end()
})
<commit_msg>Fix name<commit_after>import test from 'tape'

import {shortname, longname} from '../src/language'

function check (t, lang, short, long) {
  t.equal(shortname(lang), short)
  t.equal(longname(shortname(lang)), long)
  t.equal(shortname(short), short)
  t.equal(longname(long), long)
}

test('language.{shortname|longname}', function (t) {
  check(t, 'Javascript', 'js', 'JavaScript')
  check(t, 'Julia', 'jl', 'Julia')
  check(t, 'Python', 'py', 'Python')
  check(t, 'R', 'r', 'R')
  check(t, 'SQL', 'sql', 'SQL')

  t.end()
})
<|endoftext|>


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

const fs = require("fs");
const { spawn } = require("child_process");
const path = require("path");

const share_dir_9p = fs.mkdtempSync("/tmp/v86-test-qemu-9p");

fs.copyFileSync(path.join(__dirname, "/test-i386"), path.join(share_dir_9p, "/test-i386"));

const qemu = spawn("qemu-system-x86_64",
    [
        "-serial", "stdio",
        "-cdrom", path.join(__dirname, "/../../images/linux3.iso"),
        "-device", "virtio-9p-pci,fsdev=fs9p,mount_tag=host9p",
        "-fsdev", `local,id=fs9p,path=${share_dir_9p},security_model=none`,
        "-display", "none",
        "-cpu", "max", // default doesn't support popcnt

        //"-monitor", "telnet:127.0.0.1:1235,server,nowait",
    ]
);

let qemu_output = "";
let ran_command = false;
let finished = false;

qemu.stdout.on("data", data => {
    process.stderr.write(data);
    qemu_output += data.toString().replace(/\r/, "");

    if(!ran_command && qemu_output.endsWith("~% "))
    {
        ran_command = true;
        qemu.stdin.write("chmod +x /mnt/test-i386\n");
        qemu.stdin.write("/mnt/test-i386 > /mnt/result\n");
        qemu.stdin.write("echo test fini''shed\n");
    }

    if(ran_command && !finished && qemu_output.endsWith("test finished\n"))
    {
        const result_file = path.join(share_dir_9p, "result");

        finished = true;
        console.error("Finished");
        process.stdout.write(fs.readFileSync(result_file));

        fs.unlinkSync(result_file);
        fs.unlinkSync(path.join(share_dir_9p, "test-i386"));
        fs.rmdirSync(share_dir_9p);

        qemu.kill();
    }
});

qemu.stderr.on("data", data => {
    process.stderr.write(data);
});
<commit_msg>Use Westmere instead of max cpu for qemu (max is not available on older qemu versions)<commit_after>#!/usr/bin/env node
"use strict";

const fs = require("fs");
const { spawn } = require("child_process");
const path = require("path");

const share_dir_9p = fs.mkdtempSync("/tmp/v86-test-qemu-9p");

fs.copyFileSync(path.join(__dirname, "/test-i386"), path.join(share_dir_9p, "/test-i386"));

const qemu = spawn("qemu-system-x86_64",
    [
        "-serial", "stdio",
        "-cdrom", path.join(__dirname, "/../../images/linux3.iso"),
        "-device", "virtio-9p-pci,fsdev=fs9p,mount_tag=host9p",
        "-fsdev", `local,id=fs9p,path=${share_dir_9p},security_model=none`,
        "-display", "none",
        "-cpu", "Westmere", // default doesn't support popcnt

        //"-monitor", "telnet:127.0.0.1:1235,server,nowait",
    ]
);

let qemu_output = "";
let ran_command = false;
let finished = false;

qemu.stdout.on("data", data => {
    process.stderr.write(data);
    qemu_output += data.toString().replace(/\r/, "");

    if(!ran_command && qemu_output.endsWith("~% "))
    {
        ran_command = true;
        qemu.stdin.write("chmod +x /mnt/test-i386\n");
        qemu.stdin.write("/mnt/test-i386 > /mnt/result\n");
        qemu.stdin.write("echo test fini''shed\n");
    }

    if(ran_command && !finished && qemu_output.endsWith("test finished\n"))
    {
        const result_file = path.join(share_dir_9p, "result");

        finished = true;
        console.error("Finished");
        process.stdout.write(fs.readFileSync(result_file));

        fs.unlinkSync(result_file);
        fs.unlinkSync(path.join(share_dir_9p, "test-i386"));
        fs.rmdirSync(share_dir_9p);

        qemu.kill();
    }
});

qemu.stderr.on("data", data => {
    process.stderr.write(data);
});
<|endoftext|>