<commit_before>
/**
 * As our first step, we'll pull in the user's webpack.mix.js
 * file. Based on what the user requests in that file,
 * a generic config object will be constructed for us.
 */

const path = require('path');
const currentPath = path.resolve(__dirname);
const mixPath = path.resolve(currentPath, 'node_modules/laravel-mix');
const { spawnSync } = require('child_process');
const Watchpack = require('watchpack');
const spawnOptions = { stdio: 'inherit' };

require(path.resolve(mixPath, 'src/index'));

Mix.paths.setRootPath(currentPath);

let ComponentFactory = require(path.resolve(mixPath, 'src/components/ComponentFactory'));
new ComponentFactory().installAll();

require(Mix.paths.mix());

/**
 * Just in case the user needs to hook into this point
 * in the build process, we'll make an announcement.
 */

Mix.dispatch('init', Mix);

/**
 * Now that we know which build tasks are required by the
 * user, we can dynamically create a configuration object
 * for Webpack. And that's all there is to it. Simple!
 */

let WebpackConfig = require(path.resolve(mixPath, 'src/builder/WebpackConfig'));
const config = new WebpackConfig().build();

const routesFile = path.resolve(__dirname, 'routes/web.php');
const langDir = path.resolve(__dirname, 'resources/lang');

let resolved = false;

const watches = [
  {
    callback: () => {
      spawnSync('php', ['artisan', 'ziggy:generate'], spawnOptions);
    },
    path: routesFile,
    type: 'file',
  },
  {
    callback: () => {
      spawnSync('yarn', ['generate-localizations'], spawnOptions);
      // touching the file on first build might cause karma's watchers to fire after tests start.
      if (resolved) {
        spawnSync('touch', [path.resolve(__dirname, 'resources/assets/coffee/main.coffee')], spawnOptions);
      }
    },
    path: langDir,
    type: 'dir',
  },
]

function configPromise(env, argv) {
  return new Promise((resolve) => {
    const options = {
      // fire an aggregated event after 200ms on changes.
      aggregateTimeout: 200,
    };
    // same as webpack-cli's handling
    if (argv['watch-poll'] === 'true' || argv['watch-poll'] === '') options.poll = true;

    if (!argv.watch) {
      watches.forEach((watched) => {
        watched.callback();
      })

      return resolve(config);
    }

    const wp = new Watchpack(options);
    wp.watch(
      watches.filter(x => x.type === 'file').map(x => x.path),
      watches.filter(x => x.type === 'dir').map(x => x.path)
    ); // files and directories are different arguments.

    // directory watchers cause change events on start, file watchers don't;
    // run the callback for each file watcher once.
    watches.filter(x => x.type === 'file').forEach((watched) => {
      watched.callback();
      watched.ranOnce = true;
    })

    wp.on('aggregated', (changes, removals) => {
      watches.forEach((watched) => {
        if (changes.includes(watched.path) || removals.includes(watched.path)) {
          watched.callback();
          watched.ranOnce = true;
        }
      });

      // let webpack run after the first build.
      if (!resolved && watches.reduce((value, watched) => value && watched.ranOnce, true)) {
        resolved = true;
        resolve(config);
      }
    });
  });
}

module.exports = configPromise;
<commit_msg>delay resolving and building mix config.<commit_after>
/**
 * As our first step, we'll pull in the user's webpack.mix.js
 * file. Based on what the user requests in that file,
 * a generic config object will be constructed for us.
 */

const path = require('path');
const currentPath = path.resolve(__dirname);
const mixPath = path.resolve(currentPath, 'node_modules/laravel-mix');
const { spawnSync } = require('child_process');
const Watchpack = require('watchpack');
const spawnOptions = { stdio: 'inherit' };

require(path.resolve(mixPath, 'src/index'));

Mix.paths.setRootPath(currentPath);

let ComponentFactory = require(path.resolve(mixPath, 'src/components/ComponentFactory'));
new ComponentFactory().installAll();

const routesFile = path.resolve(__dirname, 'routes/web.php');
const langDir = path.resolve(__dirname, 'resources/lang');

let resolved = false;

const watches = [
  {
    callback: () => {
      spawnSync('php', ['artisan', 'ziggy:generate'], spawnOptions);
    },
    path: routesFile,
    type: 'file',
  },
  {
    callback: () => {
      spawnSync('yarn', ['generate-localizations'], spawnOptions);
      // touching the file on first build might cause karma's watchers to fire after tests start.
      if (resolved) {
        spawnSync('touch', [path.resolve(__dirname, 'resources/assets/coffee/main.coffee')], spawnOptions);
      }
    },
    path: langDir,
    type: 'dir',
  },
]

function buildConfig() {
  require(Mix.paths.mix());
  Mix.dispatch('init', Mix);
  const WebpackConfig = require(path.resolve(mixPath, 'src/builder/WebpackConfig'));

  return new WebpackConfig().build();
}

function configPromise(env, argv) {
  return new Promise((resolve) => {
    const options = {
      // fire an aggregated event after 200ms on changes.
      aggregateTimeout: 200,
    };
    // same as webpack-cli's handling
    if (argv['watch-poll'] === 'true' || argv['watch-poll'] === '') options.poll = true;

    if (!argv.watch) {
      watches.forEach((watched) => {
        watched.callback();
      })

      return resolve(buildConfig());
    }

    const wp = new Watchpack(options);
    wp.watch(
      watches.filter(x => x.type === 'file').map(x => x.path),
      watches.filter(x => x.type === 'dir').map(x => x.path)
    ); // files and directories are different arguments.

    // directory watchers cause change events on start, file watchers don't;
    // run the callback for each file watcher once.
    watches.filter(x => x.type === 'file').forEach((watched) => {
      watched.callback();
      watched.ranOnce = true;
    })

    wp.on('aggregated', (changes, removals) => {
      watches.forEach((watched) => {
        if (changes.includes(watched.path) || removals.includes(watched.path)) {
          watched.callback();
          watched.ranOnce = true;
        }
      });

      // let webpack run after the first build.
      if (!resolved && watches.reduce((value, watched) => value && watched.ranOnce, true)) {
        resolved = true;
        resolve(buildConfig());
      }
    });
  });
}

module.exports = configPromise;
<|endoftext|>


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

module.exports = {
	mode: 'development',
    target: 'web',
    context: path.resolve(__dirname, 'src'),
    plugins: [
    ],
    entry: {
        'ractive-modal': './ractive-modal.ractive.html'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        library: 'RactiveModal',
        libraryTarget: 'umd'
    },
    externals: {
    	ractive: {
    		commonjs: 'Ractive',
    		commonjs2: 'Ractive',
    		amd: 'Ractive',
    		root: 'Ractive'
    	}
    },
    module: {
        rules: [
            {
                test: /\.ractive\.html$/,
                exclude: /(node_modules|bower_components)/,
                use: [
                    {
                        loader: 'ractive-bin-loader'
                    }
                ]
            }
        ]
    }
}<commit_msg>Added node false to the config<commit_after>const webpack = require('webpack');
const path = require('path');

module.exports = {
	node: false,
	mode: 'development',
    target: 'web',
    context: path.resolve(__dirname, 'src'),
    plugins: [
    ],
    entry: {
        'ractive-modal': './ractive-modal.ractive.html'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        library: 'RactiveModal',
        libraryTarget: 'umd'
    },
    externals: {
    	ractive: {
    		commonjs: 'Ractive',
    		commonjs2: 'Ractive',
    		amd: 'Ractive',
    		root: 'Ractive'
    	}
    },
    module: {
        rules: [
            {
                test: /\.ractive\.html$/,
                exclude: /(node_modules|bower_components)/,
                use: [
                    {
                        loader: 'ractive-bin-loader'
                    }
                ]
            }
        ]
    }
}<|endoftext|>


<commit_before>const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const precss = require('precss');
const autoprefixer = require('autoprefixer');

module.exports = {
    context: `${__dirname}/src`,
    devtool: 'source-map',
    entry: ['babel-polyfill', './entry.js'],
    output: {
        path: `${__dirname}/dist`,
        filename: 'cheese-burger.js'
    },
    externals: {
        'react/addons': true,
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': true
    },
    module: {
        preLoaders: [
            {test: /\.js$/, loaders: ['eslint'], include: `${__dirname}/src`}
        ],
        loaders: [
            {test: /\.js$/, loaders: ['babel'], exclude: /node_modules/},
            {test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass'], exclude: /node_modules/}
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            {from: './index.html', to: './index.html'}
        ])
    ],
    postcss() {
        return [precss, autoprefixer];
    },
};
<commit_msg>Changed Webpack to use white listing not blacklisting<commit_after>const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const precss = require('precss');
const autoprefixer = require('autoprefixer');

module.exports = {
    context: `${__dirname}/src`,
    devtool: 'source-map',
    entry: ['babel-polyfill', './entry.js'],
    output: {
        path: `${__dirname}/dist`,
        filename: 'cheese-burger.js'
    },
    externals: {
        'react/addons': true,
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': true
    },
    module: {
        preLoaders: [
            {test: /\.js$/, loaders: ['eslint'], include: `${__dirname}/src`}
        ],
        loaders: [
            {test: /\.js$/, loaders: ['babel'], include: `${__dirname}/src`},
            {test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass'], include: `${__dirname}/src`}
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            {from: './index.html', to: './index.html'}
        ])
    ],
    postcss() {
        return [precss, autoprefixer];
    },
};
<|endoftext|>


<commit_before>/*
 * Moksha javascript library
 *
 * Copyright (c) 2008 Red Hat, Inc.
 *
 * GPLv2+ license.
 *
 * Depends:
 *      jquery.js
 */

(function(){

True = true
False = false
// prevent double loading
if (!(typeof(moksha) === 'undefined'))
    return;

var _moksha_page_scripts_cache = {};

var _moksha_init = false;
// preload cache

$(document).ready(function(){
  _moksha_init = true;
  var $s = $('script[src]');

  $.each($s, function(i, a) {
                var $a = $(a);
                var src = $a.attr('src');
                // for right now just compare exact source values
                // later we will want to be a bit smarter
                if(!_moksha_page_scripts_cache[src]) {
                    _moksha_page_scripts_cache[src] = true;
                }
             }
         );

});

moksha = {
    /******************************************************************
     * Filter the script tags in a fragment of HTML or jQuery DOM
     * so that they aren't double loaded.  You should send in HTML
     * if possible because placing script tags in a jQuery DOM can
     * cause them to load if not done correctly
     ******************************************************************/
    filter_scripts: function(fragment) {
        // don't append to a tag, doing so will cause scripts to load
        if (!fragment.jquery)
            fragment = $(fragment);

        var $stripped = [];
        $.each(fragment, function(i, s) {
            var $s = $(s)
            if ($s.is('script[src]')){
                var src = $s.attr('src');
                //strip query string
                src = src.split('?')[0];

                if(!_moksha_page_scripts_cache[src]) {
                    // we can add more attributes later
                    // right now just set to true
                    _moksha_page_scripts_cache[src] = true;
                    $stripped.push(s);
                }
            } else {
                $stripped.push(s);
            }
        });

        return $stripped;
    },

    /******************************************************************
     * Filter resources in a fragment of HTML or jQuery DOM
     * so that they aren't double loaded.  Right now this is only
     * scripts but could be expanded to css and other loaded
     * resource types. You should send in HTML
     * if possible since loading into a jQuery DOM can cause them
     * to load if not done correctly
     ******************************************************************/
    filter_resources: function(fragment) {
        if (!fragment.jquery)
            fragment = $(fragment);

        var $f = moksha.filter_scripts(fragment);

        return $f;
    },

    /********************************************************************
     * Take a url and attach the csrf hash if available
     ********************************************************************/
    csrf_rewrite_url: function(url, params) {
        var ourl = moksha.parseUri(url);

        if (typeof(params) == 'undefined')
            params = {};

        if (typeof(moksha_csrf_token) != 'undefined' && moksha_csrf_token)
            params['_csrf_token'] = moksha_csrf_token;

        ourl.update_query_string(params);

        return ourl.toString();

    },

    /*********************************************************************
     * Take a form element and add or update a hidden field for the
     * csrf token
     *
     * Example:
     *   <form action="/process_form/"
     *         onSubmit="moksha.csrf_add_form_field(this)">
     *********************************************************************/
    csrf_add_form_field: function(form_element) {
        // do nothing if we don't actually have a token
        if (typeof(moksha_csrf_token) === 'undefined' || !moksha_csrf_token)
            return;

        var $fe = $(form_element);
        var $csrf_field = $("input[name=_csrf_token]", form_element);

        // create a field if it doens't already exist
        if ($csrf_field.length < 1) {
            $csrf_field = $("<input type='hidden'></input>").attr("name", "_csrf_token");

            $fe.append($csrf_field);
        }

        $csrf_field.attr("value", moksha_csrf_token);
    },

    /********************************************************************
     * Take a url and target, attach the csrf hash if available and load
     *
     * FIXME: target is ignored for now
     *
     * TODO: Fast loading where we just switch tabs
     ********************************************************************/
    goto: function(url, params, target) {
        if (typeof(params) != 'object')
            params = {}

        window.location.href = moksha.csrf_rewrite_url(url, params);
    },

    /*
     * modified from parseUri 1.2.1 Steven Levithan <stevenlevithan.com>
     */
    parseUri: function (str) {
        var options = {
            strictMode: false,
            key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
            q:   {
                name:   "queryKey",
                parser: /(?:^|&)([^&=]*)=?([^&]*)/g
            },
            parser: {
                strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
                loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
            }
        };

        var uriClass = function(){};
        uriClass.prototype = {
            update_query_string :function(params) {
               for (p in params)
                   this.queryKey[p] = params[p];
            },

            toString: function() {
                var proto = this.protocol;
                if (proto)
                    proto += '://';

                var url = proto + this.authority + this.path;
                var qlist = []

                for (q in this.queryKey) {
                    qlist.push(q + '=' + this.queryKey[q]);
                }

                var query = qlist.join('&')
                url += '?'+ query;

                if (this.anchor)
                    url += '#' + this.anchor;

                return url;
           }
        };

        var o   = options,
            m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
            uri = new uriClass,
            i   = 14;

        while (i--) uri[o.key[i]] = m[i] || "";

        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
            if ($1) uri[o.q.name][$1] = $2;
        });

        return uri;
    },

    json_load: function(path, params, callback, $overlay_div) {
       return moksha.ajax_load(path, params, callback, $overlay_div, 'json')
    },

    xml_load: function(path, params, callback, $overlay_div) {
       return moksha.ajax_load(path, params, callback, $overlay_div, 'xml')
    },

    html_load: function(path, params, callback, $overlay_div) {
       return moksha.ajax_load(path, params, callback, $overlay_div, 'html')
    },

    ajax_load: function(path, params, callback, $overlay_div, data_type) {
       self = this;

       var success = function(data, status) {
         if (typeof($overlay_div) == 'object')
             $overlay_div.hide();

         callback(data);
       }

       var error = function(XMLHttpRequest, status, err) {
         // TODO: provide a reload link in the overlay
         if (typeof($overlay_div) == 'object') {
             var $msg = $('.message', $overlay_div);
             if (moksha_debug)
               console.log(err);

             $msg.html(error);
         }
       }

       // show loading
       if (typeof($overlay_div) == 'object') {
           var $msg = $('.message', $overlay_div);
           // FIXME: make this globally configurable
           $msg.html('');

           var $parent = $overlay_div.parent();
           $overlay_div.css({'height': $parent.height(),
                             'width': $parent.width()})
           $overlay_div.show();
       }

       o = {
            'url': path,
            'data': params,
            'success': success,
            'error': error,
            'dataType': data_type
           }

       return $.ajax(o);
    }
}

})();
<commit_msg>send an error message back if a page section can no load<commit_after>/*
 * Moksha javascript library
 *
 * Copyright (c) 2008 Red Hat, Inc.
 *
 * GPLv2+ license.
 *
 * Depends:
 *      jquery.js
 */

(function(){

True = true
False = false
// prevent double loading
if (!(typeof(moksha) === 'undefined'))
    return;

var _moksha_page_scripts_cache = {};

var _moksha_init = false;
// preload cache

$(document).ready(function(){
  _moksha_init = true;
  var $s = $('script[src]');

  $.each($s, function(i, a) {
                var $a = $(a);
                var src = $a.attr('src');
                // for right now just compare exact source values
                // later we will want to be a bit smarter
                if(!_moksha_page_scripts_cache[src]) {
                    _moksha_page_scripts_cache[src] = true;
                }
             }
         );

});

moksha = {
    /******************************************************************
     * Filter the script tags in a fragment of HTML or jQuery DOM
     * so that they aren't double loaded.  You should send in HTML
     * if possible because placing script tags in a jQuery DOM can
     * cause them to load if not done correctly
     ******************************************************************/
    filter_scripts: function(fragment) {
        // don't append to a tag, doing so will cause scripts to load
        if (!fragment.jquery)
            fragment = $(fragment);

        var $stripped = [];
        $.each(fragment, function(i, s) {
            var $s = $(s)
            if ($s.is('script[src]')){
                var src = $s.attr('src');
                //strip query string
                src = src.split('?')[0];

                if(!_moksha_page_scripts_cache[src]) {
                    // we can add more attributes later
                    // right now just set to true
                    _moksha_page_scripts_cache[src] = true;
                    $stripped.push(s);
                }
            } else {
                $stripped.push(s);
            }
        });

        return $stripped;
    },

    /******************************************************************
     * Filter resources in a fragment of HTML or jQuery DOM
     * so that they aren't double loaded.  Right now this is only
     * scripts but could be expanded to css and other loaded
     * resource types. You should send in HTML
     * if possible since loading into a jQuery DOM can cause them
     * to load if not done correctly
     ******************************************************************/
    filter_resources: function(fragment) {
        if (!fragment.jquery)
            fragment = $(fragment);

        var $f = moksha.filter_scripts(fragment);

        return $f;
    },

    /********************************************************************
     * Take a url and attach the csrf hash if available
     ********************************************************************/
    csrf_rewrite_url: function(url, params) {
        var ourl = moksha.parseUri(url);

        if (typeof(params) == 'undefined')
            params = {};

        if (typeof(moksha_csrf_token) != 'undefined' && moksha_csrf_token)
            params['_csrf_token'] = moksha_csrf_token;

        ourl.update_query_string(params);

        return ourl.toString();

    },

    /*********************************************************************
     * Take a form element and add or update a hidden field for the
     * csrf token
     *
     * Example:
     *   <form action="/process_form/"
     *         onSubmit="moksha.csrf_add_form_field(this)">
     *********************************************************************/
    csrf_add_form_field: function(form_element) {
        // do nothing if we don't actually have a token
        if (typeof(moksha_csrf_token) === 'undefined' || !moksha_csrf_token)
            return;

        var $fe = $(form_element);
        var $csrf_field = $("input[name=_csrf_token]", form_element);

        // create a field if it doens't already exist
        if ($csrf_field.length < 1) {
            $csrf_field = $("<input type='hidden'></input>").attr("name", "_csrf_token");

            $fe.append($csrf_field);
        }

        $csrf_field.attr("value", moksha_csrf_token);
    },

    /********************************************************************
     * Take a url and target, attach the csrf hash if available and load
     *
     * FIXME: target is ignored for now
     *
     * TODO: Fast loading where we just switch tabs
     ********************************************************************/
    goto: function(url, params, target) {
        if (typeof(params) != 'object')
            params = {}

        window.location.href = moksha.csrf_rewrite_url(url, params);
    },

    /*
     * modified from parseUri 1.2.1 Steven Levithan <stevenlevithan.com>
     */
    parseUri: function (str) {
        var options = {
            strictMode: false,
            key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
            q:   {
                name:   "queryKey",
                parser: /(?:^|&)([^&=]*)=?([^&]*)/g
            },
            parser: {
                strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
                loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
            }
        };

        var uriClass = function(){};
        uriClass.prototype = {
            update_query_string :function(params) {
               for (p in params)
                   this.queryKey[p] = params[p];
            },

            toString: function() {
                var proto = this.protocol;
                if (proto)
                    proto += '://';

                var url = proto + this.authority + this.path;
                var qlist = []

                for (q in this.queryKey) {
                    qlist.push(q + '=' + this.queryKey[q]);
                }

                var query = qlist.join('&')
                url += '?'+ query;

                if (this.anchor)
                    url += '#' + this.anchor;

                return url;
           }
        };

        var o   = options,
            m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
            uri = new uriClass,
            i   = 14;

        while (i--) uri[o.key[i]] = m[i] || "";

        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
            if ($1) uri[o.q.name][$1] = $2;
        });

        return uri;
    },

    json_load: function(path, params, callback, $overlay_div) {
       return moksha.ajax_load(path, params, callback, $overlay_div, 'json')
    },

    xml_load: function(path, params, callback, $overlay_div) {
       return moksha.ajax_load(path, params, callback, $overlay_div, 'xml')
    },

    html_load: function(path, params, callback, $overlay_div) {
       return moksha.ajax_load(path, params, callback, $overlay_div, 'html')
    },

    ajax_load: function(path, params, callback, $overlay_div, data_type) {
       self = this;

       var success = function(data, status) {
         if (typeof($overlay_div) == 'object')
             $overlay_div.hide();

         callback(data);
       }

       var error = function(XMLHttpRequest, status, err) {
         // TODO: provide a reload link in the overlay
         if (typeof($overlay_div) == 'object') {
             var $msg = $('.message', $overlay_div);
             if (moksha_debug)
               console.log(err);

             $msg.html('Error loading the data for this page element');
         }
       }

       // show loading
       if (typeof($overlay_div) == 'object') {
           var $msg = $('.message', $overlay_div);
           // FIXME: make this globally configurable
           $msg.html('');

           var $parent = $overlay_div.parent();
           $overlay_div.css({'height': $parent.height(),
                             'width': $parent.width()})
           $overlay_div.show();
       }

       o = {
            'url': path,
            'data': params,
            'success': success,
            'error': error,
            'dataType': data_type
           }

       return $.ajax(o);
    }
}

})();
<|endoftext|>


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

module.exports = {
    entry: [
        __dirname + '/app/scripts/index.js'
    ],
    output: {
        filename: 'bundle.js'
    },
    resolve: {
        modulesDirectories: [
            __dirname + '/app/vendors',
            __dirname + '/node_modules'
        ]
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('.bower.json', ['main'])
        ),
        new webpack.ProvidePlugin({
            //'angular': 'exports?window.angular!angular',
            $: "jquery"
        })
    ]
};
<commit_msg>add comments<commit_after>var webpack = require('webpack');

module.exports = {
    entry: [
        __dirname + '/app/scripts/index.js'
    ],
    output: {
        filename: 'bundle.js'
    },
    resolve: {
        modulesDirectories: [
            __dirname + '/app/vendors',
            __dirname + '/node_modules'
        ]
    },
    plugins: [

    /**
     * minify js
     */

        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),

    /**
     * resolver plugin, for using bower components
     */

        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('.bower.json', ['main'])
        ),

    /**
     * provide plugin, load the component the first time
     */

        new webpack.ProvidePlugin({
            //'angular': 'exports?window.angular!angular',
            $: "jquery"
        })
    ]
};
<|endoftext|>


<commit_before>/* eslint prefer-rest-params:0, default-case:0, no-console: 0 func-names:0 */
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
require('babel-polyfill');
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const NPMInstallPlugin = require('npm-install-webpack-plugin');
const HTMLPlugin = require('html-webpack-plugin');
const chalk = require('chalk');

// ===========================================================================
// CONSTANTS
// ===========================================================================

const PATHS = { // :off
  src: unipath('src'),
  build: unipath('build'),
  modules: unipath('node_modules'),
  base: unipath('.'),
}; // :on
const LOADER_INCLUDES = [PATHS.src(), PATHS.base('tests.webpack.js')];

const DEVELOPMENT = 'development';
const PRODUCTION = 'production';
const TEST = 'test';

// ===========================================================================
// SETUP ENV
// ===========================================================================

const TARGET = process.env.npm_lifecycle_event;
const ENV = getEnv(TARGET);
const DEBUG = !process.argv.includes('release');
const VERBOSE = process.argv.includes('verbose');
const WATCH = global.watch || process.argv.includes('--auto-watch');

// ===========================================================================
// NOTIFY
// ===========================================================================

log('ENV', ENV);
log('DEBUG', DEBUG);
log('VERBOSE', VERBOSE);
log('WATCH', WATCH);

// ===========================================================================
// CONFIG EXPORT
// ===========================================================================

module.exports = {
  entry: getEntry(ENV),

  output: { // :off
    path: PATHS.build(),
    publicPath: DEBUG ? '/' : '/2048/',
    filename: DEBUG ? '[name].js?[hash]' : '[name].[chunkhash].js',
    chunkFilename: DEBUG ? '[name].js?[chunkhash]' : '[name].[chunkhash].js',
    sourceMapFilename: '[file].map',
    sourcePrefix: '  ',
  }, // :on

  module: {
    preLoaders: getPreLoaders(ENV),

    loaders: getLoaders(ENV),
  },

  resolve: {
    extensions: ['', '.json', '.js', '.jsx'],
  },

  cache: DEBUG,

  debug: DEBUG,

  devtool: getDevtool(ENV),

  plugins: getPlugins(ENV),

  target: 'web',

  progress: true,

  watch: WATCH,

  noInfo: !VERBOSE,

  stats: {
    colors: true,
    reasons: DEBUG,
    hash: VERBOSE,
    version: VERBOSE,
    timings: true,
    chunks: VERBOSE,
    chunkModules: VERBOSE,
    cached: VERBOSE,
    cachedAssets: VERBOSE,
    children: VERBOSE,
  },

  postcss(bundler) {
    return [
      /*require('colorguard')(),*/
      require('postcss-import')({ addDependencyTo: bundler }),
      require('precss')(),
      require('autoprefixer')({ browsers: ['last 2 versions'] }),
    ];
  },
};

// ===========================================================================
// CONFIG ENV DEFINITIONS
// ===========================================================================

function getEntry(env) {
  const entry = { main: [] };

  switch (env) {
    case DEVELOPMENT:
      entry.main.push('babel-polyfill');
      entry.main.push('webpack-hot-middleware/client?http://localhost:3000');
      entry.main.push('webpack/hot/only-dev-server'); // TODO ??
      entry.main.push(PATHS.src('index.jsx'));
      break;

    case PRODUCTION:
      entry.main.push('babel-polyfill');
      entry.main.push(PATHS.src('index.jsx'));
      entry.vendor = Object.keys(require('./package.json').dependencies);
      break;

    case TEST:
      break;

  }

  return entry;
}

function getPreLoaders(env) {
  const preLoaders = [];

  switch (env) {
    case PRODUCTION:
      preLoaders.push({
        test: /\.jsx?$/, include: LOADER_INCLUDES, loaders: ['eslint', 'jscs'],
      });
      break;

    case DEVELOPMENT:
      preLoaders.push({
        test: /\.jsx?$/, include: LOADER_INCLUDES, loaders: ['eslint', 'jscs'],
      });
      break;

    case TEST:
      preLoaders.push({
        test: /\.jsx?$/, include: LOADER_INCLUDES, loader: 'babel-istanbul',
      });
      break;

  }
  return preLoaders;
}

function getDevtool(env) {
  switch (env) {
    case PRODUCTION:
      return 'source-map';

    case DEVELOPMENT:
      return 'inline-source-map';

    case TEST:
      return 'inline-source-map';

    default:
      return false;
  }
}

function getLoaders(env) {
  const JS_LOADER = { // :off
    test: /\.jsx?$/,
    include: LOADER_INCLUDES,
    loader: 'babel',
    query: {
      cacheDirectory: true,
      presets: [],
    },
  }; // :on
  const loaders = [
    JS_LOADER,
    {
      test: /\.json$/,
      include: LOADER_INCLUDES,
      loader: 'json',
    },
    {
      test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=application/font-woff',
    },
    {
      test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=application/font-woff',
    },
    {
      test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=application/octet-stream',
    },
    {
      test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'file',
    },
    {
      test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=image/svg+xml',
    },
    {
      test: /\.(png|jpg|jpeg|gif)$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000',
    },
    {
      test: /\.(wav|mp3)$/,
      include: LOADER_INCLUDES,
      loader: 'file',
    },
  ];

  switch (env) {
    case PRODUCTION:
      loaders.push({// :off
        test: /\.s?css$/,
        include: LOADER_INCLUDES,
        loader: ExtractTextPlugin.extract((
          ''
          + 'css'
          + '?minimize'
          + '&sourceMap'
          + '&modules'
          + '&localIdentName=[hash:base64]'
          + '&importLoaders=2'
          + '!'
          + 'postcss'
          + '?sourceMap'
          + '!'
          + 'sass'
          + '?sourceMap'
        )),
      });// :on
      break;

    case DEVELOPMENT:
      loaders.push({ // :off
        test: /\.s?css$/,
        includes: LOADER_INCLUDES,
        loaders: [
          'style'
          + '?sourceMap',
          'css'
          + '?sourceMap'
          + '&modules'
          + '&localIdentName=[name]__[local]__[hash:base64:3]'
          + '&importLoaders=2',
          'postcss'
          + '?sourceMap',
          'sass'
          + '?sourceMap',
        ],
      }); // :on
      JS_LOADER.query.presets.push('react-hmre');
      break;

    case TEST:
      loaders.push({ // :off
        test: /\.s?css$/,
        include: LOADER_INCLUDES,
        loaders: [
          'style'
          + '?sourceMap',
          'css'
          + '?sourceMap'
          + '&modules'
          + '&localIdentName=[name]__[local]__[hash:base64:5]'
          + '&importLoaders=2',
          'postcss'
          + '?sourceMap',
          'sass'
          + '?sourceMap',
        ],
      }); // :on
      break;

  }

  return loaders;
}

function getPlugins(env) {
  const plugins = [ // :off
    new HTMLPlugin({
      inject: false,
      template: PATHS.modules('html-webpack-template', 'index.ejs'),
      appMountId: 'app',
      minify: DEBUG ? false : {
        removeComments: true,
        collapseWhitespace: true,
        conservativeCollapse: true,
        collapseInlineTagWhitespace: true,
        collapseBooleanAttributes: true,
        removeTagWhitespace: true,
        removeAttributeQuotes: true,
        useShortDoctype: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        caseSensitive: true,
      },
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env),
      __DEV__: env === DEVELOPMENT,
      __DEVTOOLS__: DEBUG,
    }),
  ]; // :on

  switch (env) {
    case PRODUCTION:
      plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: { warnings: false },
      }));
      plugins.push(new ExtractTextPlugin(DEBUG ? 'main.css?[chunkhash]' : 'main.[chunkhash].css'));
      plugins.push(new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest'],
      }));
      plugins.push(new webpack.optimize.DedupePlugin());
      break;

    case DEVELOPMENT:
      plugins.push(new NPMInstallPlugin({ save: true }));
      plugins.push(new webpack.HotModuleReplacementPlugin());
      plugins.push(new webpack.NoErrorsPlugin());
      break;

    case TEST:
      plugins.push(new NPMInstallPlugin({ save: true }));
      break;
  }

  plugins.push(new webpack.PrefetchPlugin('lodash/merge'));

  return plugins;
}

// ===========================================================================
// UTILS
// ===========================================================================

/**
 * Get env from npm script target.
 *
 * @param {string} target
 * @returns {string}
 */
function getEnv(target) {
  if (global.test) {return TEST;}

  switch (target) {
    case 'test':
      return TEST;

    case 'start':
      return DEVELOPMENT;

    case 'build':
      return PRODUCTION;

    case 'stats':
      return PRODUCTION;

    default:
      throw Error('unknown target', target);
  }
}

/**
 * Log a colorful message to the console.
 *
 * @param {string} description - Name of the variable to log
 * @param {*} data - Variable
 * @returns {void}
 */
function log(description, data) {
  console.error(chalk.bold.white.bgBlue(` ${description}: %s `), data);
}

/**
 * Create a path -> resolve -> join partial.
 *
 * @param {string} base - Base path
 * @returns {Function}
 */
function unipath(base) {
  return join;

  /**
   * Get fully resolved path from arguments.
   *
   * @param {...string} paths - Paths to join
   * @returns {*|{extensions}|{filePath}|{filePath, configName}}
   */
  function join(paths/* ...paths */) { // eslint-disable-line no-unused-vars
    const _paths = [base].concat(Array.from(arguments));
    return path.resolve(path.join.apply(null, _paths));
  }
}
<commit_msg>fix missing favicon<commit_after>/* eslint prefer-rest-params:0, default-case:0, no-console: 0 func-names:0 */
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
require('babel-polyfill');
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const NPMInstallPlugin = require('npm-install-webpack-plugin');
const HTMLPlugin = require('html-webpack-plugin');
const chalk = require('chalk');

// ===========================================================================
// CONSTANTS
// ===========================================================================

const PATHS = { // :off
  src: unipath('src'),
  build: unipath('build'),
  modules: unipath('node_modules'),
  static: unipath('static'),
  base: unipath('.'),
}; // :on
const LOADER_INCLUDES = [PATHS.src(), PATHS.base('tests.webpack.js')];

const DEVELOPMENT = 'development';
const PRODUCTION = 'production';
const TEST = 'test';

// ===========================================================================
// SETUP ENV
// ===========================================================================

const TARGET = process.env.npm_lifecycle_event;
const ENV = getEnv(TARGET);
const DEBUG = !process.argv.includes('release');
const VERBOSE = process.argv.includes('verbose');
const WATCH = global.watch || process.argv.includes('--auto-watch');

// ===========================================================================
// NOTIFY
// ===========================================================================

log('ENV', ENV);
log('DEBUG', DEBUG);
log('VERBOSE', VERBOSE);
log('WATCH', WATCH);

// ===========================================================================
// CONFIG EXPORT
// ===========================================================================

module.exports = {
  entry: getEntry(ENV),

  output: { // :off
    path: PATHS.build(),
    publicPath: DEBUG ? '/' : '/2048/',
    filename: DEBUG ? '[name].js?[hash]' : '[name].[chunkhash].js',
    chunkFilename: DEBUG ? '[name].js?[chunkhash]' : '[name].[chunkhash].js',
    sourceMapFilename: '[file].map',
    sourcePrefix: '  ',
  }, // :on

  module: {
    preLoaders: getPreLoaders(ENV),

    loaders: getLoaders(ENV),
  },

  resolve: {
    extensions: ['', '.json', '.js', '.jsx'],
  },

  cache: DEBUG,

  debug: DEBUG,

  devtool: getDevtool(ENV),

  plugins: getPlugins(ENV),

  target: 'web',

  progress: true,

  watch: WATCH,

  noInfo: !VERBOSE,

  stats: {
    colors: true,
    reasons: DEBUG,
    hash: VERBOSE,
    version: VERBOSE,
    timings: true,
    chunks: VERBOSE,
    chunkModules: VERBOSE,
    cached: VERBOSE,
    cachedAssets: VERBOSE,
    children: VERBOSE,
  },

  postcss(bundler) {
    return [
      /*require('colorguard')(),*/
      require('postcss-import')({ addDependencyTo: bundler }),
      require('precss')(),
      require('autoprefixer')({ browsers: ['last 2 versions'] }),
    ];
  },
};

// ===========================================================================
// CONFIG ENV DEFINITIONS
// ===========================================================================

function getEntry(env) {
  const entry = { main: [] };

  switch (env) {
    case DEVELOPMENT:
      entry.main.push('babel-polyfill');
      entry.main.push('webpack-hot-middleware/client?http://localhost:3000');
      entry.main.push('webpack/hot/only-dev-server'); // TODO ??
      entry.main.push(PATHS.src('index.jsx'));
      break;

    case PRODUCTION:
      entry.main.push('babel-polyfill');
      entry.main.push(PATHS.src('index.jsx'));
      entry.vendor = Object.keys(require('./package.json').dependencies);
      break;

    case TEST:
      break;

  }

  return entry;
}

function getPreLoaders(env) {
  const preLoaders = [];

  switch (env) {
    case PRODUCTION:
      preLoaders.push({
        test: /\.jsx?$/, include: LOADER_INCLUDES, loaders: ['eslint', 'jscs'],
      });
      break;

    case DEVELOPMENT:
      preLoaders.push({
        test: /\.jsx?$/, include: LOADER_INCLUDES, loaders: ['eslint', 'jscs'],
      });
      break;

    case TEST:
      preLoaders.push({
        test: /\.jsx?$/, include: LOADER_INCLUDES, loader: 'babel-istanbul',
      });
      break;

  }
  return preLoaders;
}

function getDevtool(env) {
  switch (env) {
    case PRODUCTION:
      return 'source-map';

    case DEVELOPMENT:
      return 'inline-source-map';

    case TEST:
      return 'inline-source-map';

    default:
      return false;
  }
}

function getLoaders(env) {
  const JS_LOADER = { // :off
    test: /\.jsx?$/,
    include: LOADER_INCLUDES,
    loader: 'babel',
    query: {
      cacheDirectory: true,
      presets: [],
    },
  }; // :on
  const loaders = [
    JS_LOADER,
    {
      test: /\.json$/,
      include: LOADER_INCLUDES,
      loader: 'json',
    },
    {
      test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=application/font-woff',
    },
    {
      test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=application/font-woff',
    },
    {
      test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=application/octet-stream',
    },
    {
      test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'file',
    },
    {
      test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000&mimetype=image/svg+xml',
    },
    {
      test: /\.(png|jpg|jpeg|gif)$/,
      include: LOADER_INCLUDES,
      loader: 'url?limit=10000',
    },
    {
      test: /\.(wav|mp3)$/,
      include: LOADER_INCLUDES,
      loader: 'file',
    },
  ];

  switch (env) {
    case PRODUCTION:
      loaders.push({// :off
        test: /\.s?css$/,
        include: LOADER_INCLUDES,
        loader: ExtractTextPlugin.extract((
          ''
          + 'css'
          + '?minimize'
          + '&sourceMap'
          + '&modules'
          + '&localIdentName=[hash:base64]'
          + '&importLoaders=2'
          + '!'
          + 'postcss'
          + '?sourceMap'
          + '!'
          + 'sass'
          + '?sourceMap'
        )),
      });// :on
      break;

    case DEVELOPMENT:
      loaders.push({ // :off
        test: /\.s?css$/,
        includes: LOADER_INCLUDES,
        loaders: [
          'style'
          + '?sourceMap',
          'css'
          + '?sourceMap'
          + '&modules'
          + '&localIdentName=[name]__[local]__[hash:base64:3]'
          + '&importLoaders=2',
          'postcss'
          + '?sourceMap',
          'sass'
          + '?sourceMap',
        ],
      }); // :on
      JS_LOADER.query.presets.push('react-hmre');
      break;

    case TEST:
      loaders.push({ // :off
        test: /\.s?css$/,
        include: LOADER_INCLUDES,
        loaders: [
          'style'
          + '?sourceMap',
          'css'
          + '?sourceMap'
          + '&modules'
          + '&localIdentName=[name]__[local]__[hash:base64:5]'
          + '&importLoaders=2',
          'postcss'
          + '?sourceMap',
          'sass'
          + '?sourceMap',
        ],
      }); // :on
      break;

  }

  return loaders;
}

function getPlugins(env) {
  const plugins = [ // :off
    new HTMLPlugin({
      inject: false,
      template: PATHS.modules('html-webpack-template', 'index.ejs'),
      appMountId: 'app',
      favicon: PATHS.static('favicon.ico'),
      minify: DEBUG ? false : {
        removeComments: true,
        collapseWhitespace: true,
        conservativeCollapse: true,
        collapseInlineTagWhitespace: true,
        collapseBooleanAttributes: true,
        removeTagWhitespace: true,
        removeAttributeQuotes: true,
        useShortDoctype: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        caseSensitive: true,
      },
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env),
      __DEV__: env === DEVELOPMENT,
      __DEVTOOLS__: DEBUG,
    }),
  ]; // :on

  switch (env) {
    case PRODUCTION:
      plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: { warnings: false },
      }));
      plugins.push(new ExtractTextPlugin(DEBUG ? 'main.css?[chunkhash]' : 'main.[chunkhash].css'));
      plugins.push(new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest'],
      }));
      plugins.push(new webpack.optimize.DedupePlugin());
      break;

    case DEVELOPMENT:
      plugins.push(new NPMInstallPlugin({ save: true }));
      plugins.push(new webpack.HotModuleReplacementPlugin());
      plugins.push(new webpack.NoErrorsPlugin());
      break;

    case TEST:
      plugins.push(new NPMInstallPlugin({ save: true }));
      break;
  }

  plugins.push(new webpack.PrefetchPlugin('lodash/merge'));

  return plugins;
}

// ===========================================================================
// UTILS
// ===========================================================================

/**
 * Get env from npm script target.
 *
 * @param {string} target
 * @returns {string}
 */
function getEnv(target) {
  if (global.test) {return TEST;}

  switch (target) {
    case 'test':
      return TEST;

    case 'start':
      return DEVELOPMENT;

    case 'build':
      return PRODUCTION;

    case 'stats':
      return PRODUCTION;

    default:
      throw Error('unknown target', target);
  }
}

/**
 * Log a colorful message to the console.
 *
 * @param {string} description - Name of the variable to log
 * @param {*} data - Variable
 * @returns {void}
 */
function log(description, data) {
  console.error(chalk.bold.white.bgBlue(` ${description}: %s `), data);
}

/**
 * Create a path -> resolve -> join partial.
 *
 * @param {string} base - Base path
 * @returns {Function}
 */
function unipath(base) {
  return join;

  /**
   * Get fully resolved path from arguments.
   *
   * @param {...string} paths - Paths to join
   * @returns {*|{extensions}|{filePath}|{filePath, configName}}
   */
  function join(paths/* ...paths */) { // eslint-disable-line no-unused-vars
    const _paths = [base].concat(Array.from(arguments));
    return path.resolve(path.join.apply(null, _paths));
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2020 Google LLC
 *
 * 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.
 */

// This function's role is to enable smooth transition to the brave new world of
// User-Agent Client Hints. If you have legacy code that relies on
// `navigator.userAgent` and which relies on entropy that will go away by
// default, you *need* to refactor it to use UA-CH. This function is to be used
// as a stop gap, to enable smooth transition during that period.

/**
* @param {string[]} hints
* @return {Promise<string|undefined>} A Promise that resolves to a string if a
*   UA could be synthesized from client hints, otherwise undefined.
*/
async function getUserAgentUsingClientHints(hints) {
  // Helper functions for platform specific strings
  const GetCrosSpecificString = values => {
    let osCPUFragment = '';
    if (values.bitness == '64') {
      if (values.architecture == 'x86') {
        osCPUFragment = 'x86_64'
      } else if (values.architecture == 'arm') {
        osCPUFragment = 'aarch64';
      }
    } else if (values.architecture == 'arm' && values.bitness == '32') {
      osCPUFragment = 'armv7l';
    }
    return `X11; CrOS ${osCPUFragment} ${values.platformVersion}`;
  }

  const GetWindowsSpecificString = values => {
    let osCPUFragment = '';
    if (values.architecture == 'x86' && values.bitness == '64') {
      osCPUFragment = '; Win64; x64';
    } else if (values.architecture == 'arm'){
      osCPUFragment = '; ARM';
    }
    return `Windows NT ${values.platformVersion}${osCPUFragment}`;
  }

  const GetMacSpecificString = values => {
    let newUA = 'Macintosh; Intel Mac OS X ';
    newUA += values.platformVersion;
    return newUA;
  }

  const GetAndroidSpecificString = values => {
    let newUA = 'Linux; Android ';
    newUA += values.platformVersion;
    if (values.model) {
      newUA += '; ';
      newUA += values.model;
    }
    return newUA;
  }

  const Initialize = (values) => {
    if (!values.architecture) {
      values.architecture = 'x86';
    }
    if (!values.bitness) {
      values.bitness = '64';
    }
    if (!values.model) {
      values.model = '';
    }
    if (!values.platform) {
      values.platform = 'Windows';
    }
    if (!values.platformVersion) {
      values.platformVersion = '10.0';
    }
    return values;
  }

  if (!navigator.userAgentData || Date.now() > 1640995199000) {
    return Promise.resolve();
  }

  // Verify that this is a Chromium
  let is_chromium = false;
  let is_edge = false
  let chromium_version;
  navigator.userAgentData.brands.forEach(value => {
    if (value.brand == 'Chromium') {
      is_chromium = true;
      chromium_version = value.version;
    } else if (value.brand == 'Microsoft Edge') {
      is_edge = true;
    }
  });
  if (!is_chromium) {
    // If this is not a Chromium based browser, the UA string should be very different. So bailing...
    return Promise.resolve();
  }

  // Main logic
  return new Promise(resolve => {
    navigator.userAgentData.getHighEntropyValues(hints).then(values => {
      let initialValues = {
        platform: navigator.userAgentData?.platform,
        uaFullVersion: `${chromium_version}.0.0.0`,
      };
      values = Object.assign(initialValues, values);
      values = Initialize(values);
      let newUA = 'Mozilla/5.0 (';
      if (['Chrome OS', 'Chromium OS'].includes(values.platform)) {
        newUA += GetCrosSpecificString(values);
      } else if (values.platform == 'Windows') {
        newUA += GetWindowsSpecificString(values);
      } else if (values.platform == 'macOS') {
        newUA += GetMacSpecificString(values);
      } else if (values.platform == 'Android') {
        newUA += GetAndroidSpecificString(values);
      } else {
        newUA += 'X11; Linux x86_64';
      }
      newUA += ') AppleWebKit/537.36 (KHTML, like Gecko) Chrome/';
      newUA += values.uaFullVersion;
      if (navigator.userAgentData.mobile) {
        newUA += ' Mobile';
      }
      newUA += ' Safari/537.36';

      if (is_edge) {
        newUA += ' Edg/';
        // Note: The full version Edge includes is not the same as the equivalent Chrome full version
        newUA += values.uaFullVersion;
      }
      resolve(newUA);
    })
  })
}

/**
* @param {string[]} hints
* @return {Promise<string|undefined>} A Promise that resolves on overriding the
*   navigator.userAgent string.
*/
async function overrideUserAgentUsingClientHints(hints) {
  return new Promise(resolve => {
    getUserAgentUsingClientHints(hints).then(newUA => {
      // Got a new UA value. Now override `navigator.userAgent`.
      Object.defineProperty(navigator, 'userAgent', {
        value: newUA,
        writable: false,
        configurable: true
      });
      resolve();
    })
  });
}

export { getUserAgentUsingClientHints, overrideUserAgentUsingClientHints };
<commit_msg>Issue #22 - Support macOS version delimited by "."<commit_after>/**
 * Copyright 2020 Google LLC
 *
 * 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.
 */

// This function's role is to enable smooth transition to the brave new world of
// User-Agent Client Hints. If you have legacy code that relies on
// `navigator.userAgent` and which relies on entropy that will go away by
// default, you *need* to refactor it to use UA-CH. This function is to be used
// as a stop gap, to enable smooth transition during that period.

/**
* @param {string[]} hints
* @return {Promise<string|undefined>} A Promise that resolves to a string if a
*   UA could be synthesized from client hints, otherwise undefined.
*/
async function getUserAgentUsingClientHints(hints) {
  // Helper functions for platform specific strings
  const GetCrosSpecificString = values => {
    let osCPUFragment = '';
    if (values.bitness == '64') {
      if (values.architecture == 'x86') {
        osCPUFragment = 'x86_64'
      } else if (values.architecture == 'arm') {
        osCPUFragment = 'aarch64';
      }
    } else if (values.architecture == 'arm' && values.bitness == '32') {
      osCPUFragment = 'armv7l';
    }
    return `X11; CrOS ${osCPUFragment} ${values.platformVersion}`;
  }

  const GetWindowsSpecificString = values => {
    let osCPUFragment = '';
    if (values.architecture == 'x86' && values.bitness == '64') {
      osCPUFragment = '; Win64; x64';
    } else if (values.architecture == 'arm'){
      osCPUFragment = '; ARM';
    }
    return `Windows NT ${values.platformVersion}${osCPUFragment}`;
  }

  const GetMacSpecificString = values => {
    let newUA = 'Macintosh; Intel Mac OS X ';
    let macVersion = values.platformVersion;
    if (macVersion.indexOf('.') > -1) {
      macVersion = macVersion.split('.').join('_');
    }
    newUA += macVersion;
    return newUA;
  }

  const GetAndroidSpecificString = values => {
    let newUA = 'Linux; Android ';
    newUA += values.platformVersion;
    if (values.model) {
      newUA += '; ';
      newUA += values.model;
    }
    return newUA;
  }

  const Initialize = (values) => {
    if (!values.architecture) {
      values.architecture = 'x86';
    }
    if (!values.bitness) {
      values.bitness = '64';
    }
    if (!values.model) {
      values.model = '';
    }
    if (!values.platform) {
      values.platform = 'Windows';
    }
    if (!values.platformVersion) {
      values.platformVersion = '10.0';
    }
    return values;
  }

  if (!navigator.userAgentData || Date.now() > 1640995199000) {
    return Promise.resolve();
  }

  // Verify that this is a Chromium
  let is_chromium = false;
  let is_edge = false
  let chromium_version;
  navigator.userAgentData.brands.forEach(value => {
    if (value.brand == 'Chromium') {
      is_chromium = true;
      chromium_version = value.version;
    } else if (value.brand == 'Microsoft Edge') {
      is_edge = true;
    }
  });
  if (!is_chromium) {
    // If this is not a Chromium based browser, the UA string should be very different. So bailing...
    return Promise.resolve();
  }

  // Main logic
  return new Promise(resolve => {
    navigator.userAgentData.getHighEntropyValues(hints).then(values => {
      let initialValues = {
        platform: navigator.userAgentData?.platform,
        uaFullVersion: `${chromium_version}.0.0.0`,
      };
      values = Object.assign(initialValues, values);
      values = Initialize(values);
      let newUA = 'Mozilla/5.0 (';
      if (['Chrome OS', 'Chromium OS'].includes(values.platform)) {
        newUA += GetCrosSpecificString(values);
      } else if (values.platform == 'Windows') {
        newUA += GetWindowsSpecificString(values);
      } else if (values.platform == 'macOS') {
        newUA += GetMacSpecificString(values);
      } else if (values.platform == 'Android') {
        newUA += GetAndroidSpecificString(values);
      } else {
        newUA += 'X11; Linux x86_64';
      }
      newUA += ') AppleWebKit/537.36 (KHTML, like Gecko) Chrome/';
      newUA += values.uaFullVersion;
      if (navigator.userAgentData.mobile) {
        newUA += ' Mobile';
      }
      newUA += ' Safari/537.36';

      if (is_edge) {
        newUA += ' Edg/';
        // Note: The full version Edge includes is not the same as the equivalent Chrome full version
        newUA += values.uaFullVersion;
      }
      resolve(newUA);
    })
  })
}

/**
* @param {string[]} hints
* @return {Promise<string|undefined>} A Promise that resolves on overriding the
*   navigator.userAgent string.
*/
async function overrideUserAgentUsingClientHints(hints) {
  return new Promise(resolve => {
    getUserAgentUsingClientHints(hints).then(newUA => {
      // Got a new UA value. Now override `navigator.userAgent`.
      Object.defineProperty(navigator, 'userAgent', {
        value: newUA,
        writable: false,
        configurable: true
      });
      resolve();
    })
  });
}

export { getUserAgentUsingClientHints, overrideUserAgentUsingClientHints };
<|endoftext|>


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

const PATHS = {
  app: path.resolve(__dirname, './client'),
  dist: path.resolve(__dirname, './dist'),
  style: [path.resolve(__dirname, './client/styles')],
  vendor: path.resolve(__dirname, './vendor.jsx')
};

const VENDOR_LIBS = ['lodash', 'react', 'react-dom', 'react-redux', 'react-router', 'react-router-bootstrap', 'react-router-redux', 'redux', 'redux-form', 'redux-thunk'];

module.exports = {
  entry: {
    app: PATHS.app + '/app.jsx',
    vendor: VENDOR_LIBS
  },
  output: {
    path: PATHS.dist,
    filename: '[name].[chunkhash].js',
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.jsx$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'BelwoodBakeryCafe',
      template: PATHS.app + '/index.html'
    }),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    })
  ],
  externals: {
    'react/addons': true,
    'react/lib/ExecutionEnvironment': true,
    'react/lib/ReactContext': true
  }
};
<commit_msg>[ DEV ] add webpack devserver<commit_after>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const PATHS = {
  app: path.resolve(__dirname, './client'),
  dist: path.resolve(__dirname, './dist'),
  style: [path.resolve(__dirname, './client/styles')],
  vendor: path.resolve(__dirname, './vendor.jsx')
};

const VENDOR_LIBS = ['lodash', 'react', 'react-dom', 'react-redux', 'react-router', 'react-router-bootstrap', 'react-router-redux', 'redux', 'redux-form', 'redux-thunk'];

module.exports = {
  entry: {
    app: PATHS.app + '/app.jsx',
    vendor: VENDOR_LIBS
  },
  output: {
    path: PATHS.dist,
    filename: '[name].[chunkhash].js',
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.jsx$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'BelwoodBakeryCafe',
      template: PATHS.app + '/index.html'
    }),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
  ],
  externals: {
    'react/addons': true,
    'react/lib/ExecutionEnvironment': true,
    'react/lib/ReactContext': true
  }
};
<|endoftext|>


<commit_before>/* eslint-env node */

const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');

const COMMON_CONFIG = {
  devtool: 'cheap-module-source-map',
  entry: {
    background: './app/background.js',
    popup: './app/popup.js',
  },
  mode: 'development',
  module: {
    rules: [
      {
        exclude: /node_modules/,
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: ['file-loader'],
      },
    ],
  },
  optimization: {
    splitChunks: {
      name: 'commons',
    },
  },
  plugins: [
    new CopyWebpackPlugin([
      { from: '_locales/**' },
      { from: 'app/img/', to: 'img/' },
      { from: 'app/manifest.json' },
      { from: 'MIT-LICENSE.txt' },
      { from: 'README.md' },
    ]),
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
    new HtmlWebpackPlugin({
      cache: false, // Disable cache to ensure file is always created in multi-compiler build
      chunks: ['commons', 'popup'],
      filename: 'popup.html',
      template: './app/popup.template.html',
    }),
    new HtmlWebpackPlugin({
      cache: false, // Disable cache to ensure file is always created in multi-compiler build
      chunks: ['commons', 'background'],
      filename: 'background.html',
      template: './app/background.template.html',
    }),
  ],
};

module.exports = [
  Object.assign({}, COMMON_CONFIG, {
    name: 'chrome',
    output: {
      path: path.join(__dirname, 'dist', 'chrome'),
      filename: '[name].entry.js',
    },
    plugins: COMMON_CONFIG.plugins.concat([
      new webpack.DefinePlugin({
        EXTENSION_URL: JSON.stringify(
          'https://chrome.google.com/webstore/detail/egnjhciaieeiiohknchakcodbpgjnchh/'
        ),
      }),
    ]),
  }),
  Object.assign({}, COMMON_CONFIG, {
    name: 'firefox',
    output: {
      path: path.join(__dirname, 'dist', 'firefox'),
      filename: '[name].entry.js',
    },
    plugins: COMMON_CONFIG.plugins.concat([
      new webpack.DefinePlugin({
        EXTENSION_URL: JSON.stringify(
          'https://addons.mozilla.org/en-US/firefox/addon/tabwrangler/'
        ),
      }),
    ]),
  }),
];
<commit_msg>Configure commons chunk for popup + background<commit_after>/* eslint-env node */

const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');

const COMMON_CONFIG = {
  devtool: 'cheap-module-source-map',
  entry: {
    background: './app/background.js',
    popup: './app/popup.js',
  },
  mode: 'development',
  module: {
    rules: [
      {
        exclude: /node_modules/,
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: ['file-loader'],
      },
    ],
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          minChunks: 2,
          name: 'commons',
        },
      },
    },
  },
  plugins: [
    new CopyWebpackPlugin([
      { from: '_locales/**' },
      { from: 'app/img/', to: 'img/' },
      { from: 'app/manifest.json' },
      { from: 'MIT-LICENSE.txt' },
      { from: 'README.md' },
    ]),
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
    new HtmlWebpackPlugin({
      cache: false, // Disable cache to ensure file is always created in multi-compiler build
      chunks: ['commons', 'popup'],
      filename: 'popup.html',
      template: './app/popup.template.html',
    }),
    new HtmlWebpackPlugin({
      cache: false, // Disable cache to ensure file is always created in multi-compiler build
      chunks: ['commons', 'background'],
      filename: 'background.html',
      template: './app/background.template.html',
    }),
  ],
};

module.exports = [
  Object.assign({}, COMMON_CONFIG, {
    name: 'chrome',
    output: {
      path: path.join(__dirname, 'dist', 'chrome'),
      filename: '[name].entry.js',
    },
    plugins: COMMON_CONFIG.plugins.concat([
      new webpack.DefinePlugin({
        EXTENSION_URL: JSON.stringify(
          'https://chrome.google.com/webstore/detail/egnjhciaieeiiohknchakcodbpgjnchh/'
        ),
      }),
    ]),
  }),
  Object.assign({}, COMMON_CONFIG, {
    name: 'firefox',
    output: {
      path: path.join(__dirname, 'dist', 'firefox'),
      filename: '[name].entry.js',
    },
    plugins: COMMON_CONFIG.plugins.concat([
      new webpack.DefinePlugin({
        EXTENSION_URL: JSON.stringify(
          'https://addons.mozilla.org/en-US/firefox/addon/tabwrangler/'
        ),
      }),
    ]),
  }),
];
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementsByTagName("BODY")[0]);
registerServiceWorker();
<commit_msg>Testing travis<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementsByTagName('BODY')[0]);
registerServiceWorker();
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');

var pluginArray = [];

var sourceMapType = 'source-map';

if (process.env.NODE_ENV !== 'development') {

  /*
   console.log('Development environment detected, enabling Bundle Analyzer');

   var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

   pluginArray.push(new BundleAnalyzerPlugin({
   // Can be `server`, `static` or `disabled`.
   // In `server` mode analyzer will start HTTP server to show bundle report.
   // In `static` mode single HTML file with bundle report will be generated.
   // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting
   // `generateStatsFile` to `true`.
   analyzerMode: 'static',
   // Host that will be used in `server` mode to start HTTP server.
   analyzerHost: '127.0.0.1',
   // Port that will be used in `server` mode to start HTTP server.
   analyzerPort: 8888,
   // Path to bundle report file that will be generated in `static` mode.
   // Relative to bundles output directory.
   reportFilename: 'bundle_report.html',
   // Module sizes to show in report by default.
   // Should be one of `stat`, `parsed` or `gzip`.
   // See "Definitions" section for more information.
   defaultSizes: 'parsed',
   // Automatically open report in default browser
   openAnalyzer: true,
   // If `true`, Webpack Stats JSON file will be generated in bundles output directory
   generateStatsFile: false,
   // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
   // Relative to bundles output directory.
   statsFilename: 'stats.json',
   // Options for `stats.toJson()` method.
   // For example you can exclude sources of your modules from stats file with `source: false` option.
   // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
   statsOptions: null,
   // Log level. Can be 'info', 'warn', 'error' or 'silent'.
   logLevel: 'info'
   }));
   */
}

var jq = new webpack.ProvidePlugin({
  $: "jquery",
  jQuery: "jquery",
  "window.jQuery": "jquery'",
  "window.$": "jquery"
});

pluginArray.push(jq);

// Strip all locales except the ones defined in lib/language.js
// (“en” is built into Moment and can’t be removed, 'dk' is not defined in moment)
var momentLocales = new MomentLocalesPlugin({
  localesToKeep: ['bg', 'cs', 'de', 'el', 'es', 'fi', 'fr', 'he', 'hr', 'it', 'ko', 'nb', 'nl', 'pl', 'pt', 'ro', 'ru',
    'sk', 'sv', 'zh_cn', 'zh_tw'],
});
pluginArray.push(momentLocales);

module.exports = {
  context: path.resolve(__dirname, '.'),
  entry: {
    app: './bundle/bundle.source.js'
  },
  output: {
    path: path.resolve(__dirname, './tmp'),
    publicPath: '/',
    filename: 'js/bundle.js',
    sourceMapFilename: "js/bundle.js.map",
  },
  devtool: sourceMapType,
  plugins: pluginArray,
  module: {
    rules: [{
      test: /\.(jpe?g|png|gif)$/i,
      loader: "file-loader",
      query: {
        name: '[name].[ext]',
        outputPath: 'images/'
        //the images will be emmited to public/assets/images/ folder
        //the images will be put in the DOM <style> tag as eg. background: url(assets/images/image.png);
      },
      exclude: /node_modules/
    },
      {
        test: /\.css$/,
        loaders: ["style-loader", "css-loader"],
        exclude: /node_modules/
      }, {
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: '$'
        }]
      }
    ]
  }
};<commit_msg>reimplement changes from https://github.com/nightscout/cgm-remote-monitor/pull/3819 with indent=2<commit_after>const path = require('path');
const webpack = require('webpack');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const pluginArray = [];
const sourceMapType = 'source-map';

/*if (process.env.NODE_ENV !== 'development') {
 console.log('Development environment detected, enabling Bundle Analyzer');
 const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

 pluginArray.push(new BundleAnalyzerPlugin({
 // Can be `server`, `static` or `disabled`.
 // In `server` mode analyzer will start HTTP server to show bundle report.
 // In `static` mode single HTML file with bundle report will be generated.
 // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting
 // `generateStatsFile` to `true`.
 analyzerMode: 'static',
 // Host that will be used in `server` mode to start HTTP server.
 analyzerHost: '127.0.0.1',
 // Port that will be used in `server` mode to start HTTP server.
 analyzerPort: 8888,
 // Path to bundle report file that will be generated in `static` mode.
 // Relative to bundles output directory.
 reportFilename: 'bundle_report.html',
 // Module sizes to show in report by default.
 // Should be one of `stat`, `parsed` or `gzip`.
 // See "Definitions" section for more information.
 defaultSizes: 'parsed',
 // Automatically open report in default browser
 openAnalyzer: true,
 // If `true`, Webpack Stats JSON file will be generated in bundles output directory
 generateStatsFile: false,
 // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
 // Relative to bundles output directory.
 statsFilename: 'stats.json',
 // Options for `stats.toJson()` method.
 // For example you can exclude sources of your modules from stats file with `source: false` option.
 // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
 statsOptions: null,
 // Log level. Can be 'info', 'warn', 'error' or 'silent'.
 logLevel: 'info'
 }));
 }*/

pluginArray.push(new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  'window.jQuery': 'jquery',
  'window.$': 'jquery'
}));

// Strip all locales except the ones defined in lib/language.js
// (“en” is built into Moment and can’t be removed, 'dk' is not defined in moment)
pluginArray.push(new MomentLocalesPlugin({
  localesToKeep: ['bg', 'cs', 'de', 'el', 'es', 'fi', 'fr', 'he', 'hr', 'it', 'ko', 'nb', 'nl', 'pl', 'pt', 'ro', 'ru',
    'sk', 'sv', 'zh_cn', 'zh_tw'],
}));

module.exports = {
  context: path.resolve(__dirname, '.'),
  entry: {
    app: './bundle/bundle.source.js'
  },
  output: {
    path: path.resolve(__dirname, './tmp'),
    publicPath: '/',
    filename: 'js/bundle.js',
    sourceMapFilename: 'js/bundle.js.map',
  },
  devtool: sourceMapType,
  plugins: pluginArray,
  module: {
    rules: [{
      test: /\.(jpe?g|png|gif)$/i,
      loader: 'file-loader',
      query: {
        name: '[name].[ext]',
        outputPath: 'images/'
        //the images will be emmited to public/assets/images/ folder
        //the images will be put in the DOM <style> tag as eg. background: url(assets/images/image.png);
      },
      exclude: /node_modules/
    },
      {
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader'],
        exclude: /node_modules/
      },
      {
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: '$'
        }]
      }
    ]
  }
};<|endoftext|>


<commit_before>'use strict';
const path = require('path'),
  webpack = require('webpack'),
  LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
  target: 'web',
  entry: {
    browser: './client.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    library: 'nymag-handlebars',
    libraryTarget: 'commonjs2'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        plugins: ['lodash'],
        presets: ['es2015'],
      }
    }, {
      // allows us to require() partials
      test: /\.hbs$/,
      loader: 'handlebars-template-loader'
    }]
  },
  plugins: [
    new LodashModuleReplacementPlugin,
    new webpack.optimize.OccurrenceOrderPlugin,
    new webpack.optimize.UglifyJsPlugin,
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/)
  ]
};
<commit_msg>uglify option for inline scripts<commit_after>'use strict';
const path = require('path'),
  webpack = require('webpack'),
  LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = {
  target: 'web',
  entry: {
    browser: './client.js'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    library: 'nymag-handlebars',
    libraryTarget: 'commonjs2'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        plugins: ['lodash'],
        presets: ['es2015'],
      }
    }, {
      // allows us to require() partials
      test: /\.hbs$/,
      loader: 'handlebars-template-loader'
    }]
  },
  plugins: [
    new LodashModuleReplacementPlugin,
    new webpack.optimize.OccurrenceOrderPlugin,
    new webpack.optimize.UglifyJsPlugin({ output: {inline_script: true} }),
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/)
  ]
};
<|endoftext|>


<commit_before>var webpack = require('webpack');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var path = require('path');
var helpers = require('./helpers');

var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var appConfig = require(process.cwd() + '/app.config.js')(helpers.getEnv(), helpers.getPkg());

var ENV = process.env.ENV = process.env.NODE_ENV = 'development';

var metadata = {
  title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV
};
/*
 * Config
 */
module.exports = helpers.validate({
  // static data for index.html
  metadata: metadata,
  // for faster builds use 'eval'
  devtool: 'source-map',
  debug: true,
  // cache: false,

  // our angular app
  entry: {
    app: './src/boot.ts',
    vendor: './src/vendor.ts'
  },

  // Config for our build files
  output: {
    path: helpers.root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
    //    path: './dist',
    //  filename: 'bundle.js'
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  module: {
    preLoaders: [
      {
        test: /\.ts$/,
        loader: 'tslint'
      }
    ],
    loaders: [
      // Support for .ts files.
      {test: /\.ts$/, loader: 'ts-loader', exclude: [/\.(spec|e2e)\.ts$/]},

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

      // Allows compiling sass into css
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass')
      },

      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*$|$)/,
        loader: 'file'
      },

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

      // support for .html as raw text
      {test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')]}

    ],
    noParse: [path.join(__dirname, 'node_modules', 'angular2', 'bundles')]
  },

  plugins: [
    new webpack.DefinePlugin(appConfig),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    // generating html
    new HtmlWebpackPlugin({template: 'src/index.html', inject: 'body'}),
    // replace
    new webpack.DefinePlugin({
      'process.env': {
        'ENV': JSON.stringify(metadata.ENV),
        'NODE_ENV': JSON.stringify(metadata.ENV)
      }
    }),
    new ExtractTextPlugin(
      '[name].[hash].css', {
        disable: true
      }
    )
  ],

  postcss: [
    autoprefixer({
      browsers: ['last 2 version']
    })
  ],

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

  // our Webpack Development Server config
  devServer: {
    port: metadata.port,
    host: metadata.host,
    // contentBase: 'src/',
    historyApiFallback: true,
    watchOptions: {aggregateTimeout: 300, poll: 1000}
  },
  // we need this due to problems with es6-shim
  node: {global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false}
});
<commit_msg>refactors the webpack config<commit_after>var webpack = require('webpack');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var path = require('path');
var helpers = require('./helpers');

var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BuildConfigPlugin = require('./build-config');

var ENV = process.env.ENV = process.env.NODE_ENV = 'development';

var metadata = {
  title: helpers.getPkg().name,
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV
};
/*
 * Config
 */
module.exports = helpers.validate({
  // static data for index.html
  metadata: metadata,
  // for faster builds use 'eval'
  devtool: 'source-map',
  debug: true,

  // our angular app
  entry: {
    app: './src/boot.ts',
    vendor: './src/vendor.ts'
  },

  // Config for our build files
  output: {
    path: helpers.root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map'
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  module: {
    preLoaders: [
      {
        test: /\.ts$/,
        loader: 'tslint'
      }
    ],
    loaders: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      //Support for *.json files.
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      // Allows compiling sass into css
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass')
      },
      //
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*$|$)/,
        loader: 'file'
      },
      // Support for CSS as raw text
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },
      // support for .html as raw text
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      }

    ],
    noParse: [path.join(__dirname, 'node_modules', 'angular2', 'bundles')]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    new BuildConfigPlugin({
      env: 'dev',
      from: './src/assets/configs/[env].json',
      to: './src/config.json'
    })
  ],

  postcss: [
    autoprefixer({
      browsers: ['last 2 version']
    })
  ],

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

  // our Webpack Development Server config
  devServer: {
    port: metadata.port,
    host: metadata.host,
    historyApiFallback: true,
    watchOptions: {aggregateTimeout: 300, poll: 1000}
  },
  // we need this due to problems with es6-shim
  node: {global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false}
});
<|endoftext|>