<commit_before>var net = require('net')
  , x_types = require('./x_types');

net.createServer(function (socket) {
  new XServerClient(socket);
}).listen(6041);

var windows = {
    0x00000026: new x_types.Window(0x00000026)
}

var atoms = [];

function XServerClient (socket) {
  this.socket = socket;
  this.state = 0;
  this.endian = null;
  this.release = 11300000;
  this.resource_id_mask = 0x001fffff;
  this.resource_id_base = 0x00200000;
  this.vendor = 'JavaScript X';
  this.motion_buffer_size = 0xff;
  this.maximum_request_length = 0xffff;
  this.formats = [
      new x_types.Format(0x01, 0x01, 0x20)
    , new x_types.Format(0x04, 0x08, 0x20)
    , new x_types.Format(0x08, 0x08, 0x20)
    , new x_types.Format(0x0f, 0x10, 0x20)
    , new x_types.Format(0x10, 0x10, 0x20)
    , new x_types.Format(0x18, 0x20, 0x20)
    , new x_types.Format(0x20, 0x20, 0x20)
  ];
  this.screens = [
      new x_types.Screen(
          0x00000026 // root
        , 0x00000022 // def colormap
        , 0x00ffffff // white
        , 0x00000000 // black
        , 0x00000000 // current input masks
        , 400 // width px
        , 400 // height px
        , 400 // width mm
        , 400 // height mm
        , 0x0001 // min maps
        , 0x0001 // max maps
        , 0x20 // root visual
        , 0 // backing stores
        , 0 // save unders
        , 0x18 //24 default depth
        , [ // depths
              new x_types.Depth(
                  0x01 // depth 1
              )
            , new x_types.Depth(
                  0x18 // depth 24
                , [ // visualtypes
                      new x_types.VisualType(
                          0x00000020 // id
                        , 0x04 // class
                        , 0x08 // bits per rgb
                        , 0x0100 // colormap entries
                        , 0x00ff0000 // red mask
                        , 0x0000ff00 // green mask
                        , 0x000000ff // blue mask
                      )
                    , new x_types.VisualType(
                          0x00000021 // id
                        , 0x05 // class
                        , 0x08 // bits per rgb
                        , 0x0100 // colormap entries
                        , 0x00ff0000 // red mask
                        , 0x0000ff00 // green mask
                        , 0x000000ff // blue mask
                      )
                  ]
              )
          ]
      )
  ];
  socket.on('data', this.processData.bind(this));
}

XServerClient.prototype.processData = function (data) {
  console.log('DATA');
  data.endian = this.endian;
  switch (this.state) {
    case 0:
      return this.setup(data);
    case 1:
      var req = { length: 0 }
      while (data.length > req.length) {
        var req = new x_types.Request(data);
        console.log('NEW REQ', req.opcode);
        var func = this[XServerClient.opcodes[req.opcode]];
        func && func.call(this, req);
        if (data.length > req.length) {
          data = data.slice(req.length);
          data.endian = this.endian;
        }
      }
  }
}

XServerClient.prototype.setup = function (data) {
  data.endian = this.endian = data[0] !== 'B' ? 'LE' : 'BE';
  this.protocol_major = data.readUInt16(2);
  this.protocol_minor = data.readUInt16(4);

  this.auth_name = data.toString(
      'ascii'
    , 12
    , 12 + data.readUInt16(6)
  );

  this.auth_data = data.toString(
      'ascii'
    , 12 + data.readUInt16(6) + 2
    , 12 + data.readUInt16(6) + 2 + data.readUInt16(8)
  );
  console.log(this.auth_name, this.auth_data);

  /* Deny connection
  var reason = 'No Way'
    , pad = 4 - ((reason.length % 4) || 4);

  var res = new Buffer(8 + reason.length + pad);
  res.fill(0);
  res.writeUInt8(reason.length, 1); // 2 (0: 0, 1: reason.length)
  this.writeUInt16(res, this.protocol_major, 2); // 2
  this.writeUInt16(res, this.protocol_minor, 4); // 2
  this.writeUInt16(res, (reason.length + pad) / 4, 6);
  res.write(reason, 8, reason.length, 'ascii');
  this.socket.write(res);
  */
  // Allow connection

  var res = new Buffer(500);
  res.endian = this.endian;
  res.fill(0);
  res.writeUInt8(1, 0);
  res.writeUInt16(this.protocol_major, 2);
  res.writeUInt16(this.protocol_minor, 4);
  res.writeUInt16((32 + (this.formats.byteLength()) + stringPad(this.vendor) + this.screens.byteLength()) / 4, 6);
  res.writeUInt32(this.release, 8);
  res.writeUInt32(this.resource_id_base, 12);
  res.writeUInt32(this.resource_id_mask, 16);
  res.writeUInt32(this.motion_buffer_size, 20);
  res.writeUInt16(this.vendor.length, 24);
  res.writeUInt16(this.maximum_request_length, 26);
  res.writeUInt8(this.screens.length, 28); // Number screens
  res.writeUInt8(this.formats.length, 29); // Number formats
  res.writeUInt8(0, 30); // image lsb first
  res.writeUInt8(0, 31); // pixmap lsb first
  res.writeUInt8(32, 32); // pixmap scanline unit
  res.writeUInt8(32, 33); // pixmap scanline pad
  res.writeUInt8(8, 34); // min keycode
  res.writeUInt8(255, 35); // max keycode
  // 4 unused
  res.write(this.vendor, 40, this.vendor.length, 'ascii');
  var base = 40 + stringPad(this.vendor);
  base = this.formats.writeBuffer(res, base);
  base = this.screens.writeBuffer(res, base);
  var _res = new Buffer(base);
  _res.fill(0);
  res.copy(_res, 0, 0, base);
  this.socket.write(_res);
  console.log('Finished setup');
  this.state = 1;
}

XServerClient.opcodes = {
    98: 'QueryExtension'
}

XServerClient.prototype.QueryExtension = function (req) {
  console.log('QE');
  var res = new x_types.Reply(req);
  res.data.writeUInt8(0, 0);
  res.data.writeUInt8(req.opcode, 1);
  res.data.writeUInt8(0, 2);
  res.data.writeUInt8(0, 3);
  var _res = new Buffer(res.length);
  _res.endian = this.endian;
  res.writeBuffer(_res, 0);
  this.socket.write(_res);
}

function stringPad (string) {
  return string.length + (4 - ((string.length % 4) || 4));
}
<commit_msg>Added stub for CreateGC<commit_after>var net = require('net')
  , x_types = require('./x_types');

net.createServer(function (socket) {
  new XServerClient(socket);
}).listen(6041);

var windows = {
    0x00000026: new x_types.Window(0x00000026)
}

var atoms = [];

function XServerClient (socket) {
  this.socket = socket;
  this.state = 0;
  this.endian = null;
  this.release = 11300000;
  this.resource_id_mask = 0x001fffff;
  this.resource_id_base = 0x00200000;
  this.vendor = 'JavaScript X';
  this.motion_buffer_size = 0xff;
  this.maximum_request_length = 0xffff;
  this.formats = [
      new x_types.Format(0x01, 0x01, 0x20)
    , new x_types.Format(0x04, 0x08, 0x20)
    , new x_types.Format(0x08, 0x08, 0x20)
    , new x_types.Format(0x0f, 0x10, 0x20)
    , new x_types.Format(0x10, 0x10, 0x20)
    , new x_types.Format(0x18, 0x20, 0x20)
    , new x_types.Format(0x20, 0x20, 0x20)
  ];
  this.screens = [
      new x_types.Screen(
          0x00000026 // root
        , 0x00000022 // def colormap
        , 0x00ffffff // white
        , 0x00000000 // black
        , 0x00000000 // current input masks
        , 400 // width px
        , 400 // height px
        , 400 // width mm
        , 400 // height mm
        , 0x0001 // min maps
        , 0x0001 // max maps
        , 0x20 // root visual
        , 0 // backing stores
        , 0 // save unders
        , 0x18 //24 default depth
        , [ // depths
              new x_types.Depth(
                  0x01 // depth 1
              )
            , new x_types.Depth(
                  0x18 // depth 24
                , [ // visualtypes
                      new x_types.VisualType(
                          0x00000020 // id
                        , 0x04 // class
                        , 0x08 // bits per rgb
                        , 0x0100 // colormap entries
                        , 0x00ff0000 // red mask
                        , 0x0000ff00 // green mask
                        , 0x000000ff // blue mask
                      )
                    , new x_types.VisualType(
                          0x00000021 // id
                        , 0x05 // class
                        , 0x08 // bits per rgb
                        , 0x0100 // colormap entries
                        , 0x00ff0000 // red mask
                        , 0x0000ff00 // green mask
                        , 0x000000ff // blue mask
                      )
                  ]
              )
          ]
      )
  ];
  socket.on('data', this.processData.bind(this));
}

XServerClient.prototype.processData = function (data) {
  console.log('DATA');
  data.endian = this.endian;
  switch (this.state) {
    case 0:
      return this.setup(data);
    case 1:
      var req = { length: 0 }
      while (data.length > req.length) {
        var req = new x_types.Request(data);
        console.log('NEW REQ', req.opcode);
        var func = this[XServerClient.opcodes[req.opcode]];
        func && func.call(this, req);
        if (data.length > req.length) {
          data = data.slice(req.length);
          data.endian = this.endian;
        }
      }
  }
}

XServerClient.prototype.setup = function (data) {
  data.endian = this.endian = data[0] !== 'B' ? 'LE' : 'BE';
  this.protocol_major = data.readUInt16(2);
  this.protocol_minor = data.readUInt16(4);

  this.auth_name = data.toString(
      'ascii'
    , 12
    , 12 + data.readUInt16(6)
  );

  this.auth_data = data.toString(
      'ascii'
    , 12 + data.readUInt16(6) + 2
    , 12 + data.readUInt16(6) + 2 + data.readUInt16(8)
  );
  console.log(this.auth_name, this.auth_data);

  /* Deny connection
  var reason = 'No Way'
    , pad = 4 - ((reason.length % 4) || 4);

  var res = new Buffer(8 + reason.length + pad);
  res.fill(0);
  res.writeUInt8(reason.length, 1); // 2 (0: 0, 1: reason.length)
  this.writeUInt16(res, this.protocol_major, 2); // 2
  this.writeUInt16(res, this.protocol_minor, 4); // 2
  this.writeUInt16(res, (reason.length + pad) / 4, 6);
  res.write(reason, 8, reason.length, 'ascii');
  this.socket.write(res);
  */
  // Allow connection

  var res = new Buffer(500);
  res.endian = this.endian;
  res.fill(0);
  res.writeUInt8(1, 0);
  res.writeUInt16(this.protocol_major, 2);
  res.writeUInt16(this.protocol_minor, 4);
  res.writeUInt16((32 + (this.formats.byteLength()) + stringPad(this.vendor) + this.screens.byteLength()) / 4, 6);
  res.writeUInt32(this.release, 8);
  res.writeUInt32(this.resource_id_base, 12);
  res.writeUInt32(this.resource_id_mask, 16);
  res.writeUInt32(this.motion_buffer_size, 20);
  res.writeUInt16(this.vendor.length, 24);
  res.writeUInt16(this.maximum_request_length, 26);
  res.writeUInt8(this.screens.length, 28); // Number screens
  res.writeUInt8(this.formats.length, 29); // Number formats
  res.writeUInt8(0, 30); // image lsb first
  res.writeUInt8(0, 31); // pixmap lsb first
  res.writeUInt8(32, 32); // pixmap scanline unit
  res.writeUInt8(32, 33); // pixmap scanline pad
  res.writeUInt8(8, 34); // min keycode
  res.writeUInt8(255, 35); // max keycode
  // 4 unused
  res.write(this.vendor, 40, this.vendor.length, 'ascii');
  var base = 40 + stringPad(this.vendor);
  base = this.formats.writeBuffer(res, base);
  base = this.screens.writeBuffer(res, base);
  var _res = new Buffer(base);
  _res.fill(0);
  res.copy(_res, 0, 0, base);
  this.socket.write(_res);
  console.log('Finished setup');
  this.state = 1;
}

XServerClient.opcodes = {
  , 55: 'CreateGC'
  , 98: 'QueryExtension'
}

XServerClient.prototype.CreateGC = function (req) {
  console.log('CGC');
  console.log(req);
}

XServerClient.prototype.QueryExtension = function (req) {
  console.log('QE');
  var res = new x_types.Reply(req);
  res.data.writeUInt8(0, 0);
  res.data.writeUInt8(req.opcode, 1);
  res.data.writeUInt8(0, 2);
  res.data.writeUInt8(0, 3);
  var _res = new Buffer(res.length);
  _res.endian = this.endian;
  res.writeBuffer(_res, 0);
  this.socket.write(_res);
}

function stringPad (string) {
  return string.length + (4 - ((string.length % 4) || 4));
}
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'main':      AOT ? './src/main.browser.aot.ts' :
                  './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            { // MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json'
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          use: 'json-loader'
        },

        /*
         * to string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * to string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['to-string-loader', 'css-loader', 'sass-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /*
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        }

      ],

    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      // This enables tree shaking of the vendor modules
      new CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['main'],
        minChunks: module => /node_modules/.test(module.resource)
      }),
      // Specify the correct order the scripts will be injected in
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },
        { from: 'src/meta'}
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'head'
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // Fix Angular 2
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)async/,
        helpers.root('node_modules/@angular/core/src/facade/async.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)collection/,
        helpers.root('node_modules/@angular/core/src/facade/collection.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)errors/,
        helpers.root('node_modules/@angular/core/src/facade/errors.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)lang/,
        helpers.root('node_modules/@angular/core/src/facade/lang.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)math/,
        helpers.root('node_modules/@angular/core/src/facade/math.js')
      ),

      new ngcWebpack.NgcWebpackPlugin({
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
        resourceOverride: helpers.root('config/resource-override.js')
      })

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}
<commit_msg>check git<commit_after>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Angular2 Webpack Starter Y3',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function (options) {
  isProd = options.env === 'production';
  return {

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
    //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'main':      AOT ? './src/main.browser.aot.ts' :
                  './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['.ts', '.js', '.json'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), helpers.root('node_modules')],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      rules: [

        /*
         * Typescript loader support for .ts
         *
         * Component Template/Style integration using `angular2-template-loader`
         * Angular 2 lazy loading (async routes) via `ng-router-loader`
         *
         * `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
         * order of the loader matter.
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         * See: https://github.com/shlomiassaf/ng-router-loader
         */
        {
          test: /\.ts$/,
          use: [
            {
              loader: '@angularclass/hmr-loader',
              options: {
                pretty: !isProd,
                prod: isProd
              }
            },
            { // MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
              loader: 'ng-router-loader',
              options: {
                loader: 'async-import',
                genDir: 'compiled',
                aot: AOT
              }
            },
            {
              loader: 'awesome-typescript-loader',
              options: {
                configFileName: 'tsconfig.webpack.json'
              }
            },
            {
              loader: 'angular2-template-loader'
            }
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          use: 'json-loader'
        },

        /*
         * to string and css loader support for *.css files (from Angular components)
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          use: ['to-string-loader', 'css-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /*
         * to string and sass loader support for *.scss files (from Angular components)
         * Returns compiled css content as string
         *
         */
        {
          test: /\.scss$/,
          use: ['to-string-loader', 'css-loader', 'sass-loader'],
          exclude: [helpers.root('src', 'styles')]
        },

        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          use: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /*
         * File loader for supporting images, for example, in CSS files.
         */
        {
          test: /\.(jpg|png|gif)$/,
          use: 'file-loader'
        },

        /* File loader for supporting fonts, for example, in CSS files.
        */
        {
          test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
          use: 'file-loader'
        }

      ],

    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new CheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new CommonsChunkPlugin({
        name: 'polyfills',
        chunks: ['polyfills']
      }),
      // This enables tree shaking of the vendor modules
      new CommonsChunkPlugin({
        name: 'vendor',
        chunks: ['main'],
        minChunks: module => /node_modules/.test(module.resource)
      }),
      // Specify the correct order the scripts will be injected in
      new CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
        helpers.root('src'), // location of your src
        {
          // your Angular Async Route paths relative to this root directory
        }
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([
        { from: 'src/assets', to: 'assets' },
        { from: 'src/meta'}
      ]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'head'
      }),

      /*
       * Plugin: ScriptExtHtmlWebpackPlugin
       * Description: Enhances html-webpack-plugin functionality
       * with different deployment options for your scripts including:
       *
       * See: https://github.com/numical/script-ext-html-webpack-plugin
       */
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),

      /*
       * Plugin: HtmlElementsPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

      /**
       * Plugin LoaderOptionsPlugin (experimental)
       *
       * See: https://gist.github.com/sokra/27b24881210b56bbaff7
       */
      new LoaderOptionsPlugin({}),

      // Fix Angular 2
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)async/,
        helpers.root('node_modules/@angular/core/src/facade/async.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)collection/,
        helpers.root('node_modules/@angular/core/src/facade/collection.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)errors/,
        helpers.root('node_modules/@angular/core/src/facade/errors.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)lang/,
        helpers.root('node_modules/@angular/core/src/facade/lang.js')
      ),
      new NormalModuleReplacementPlugin(
        /facade(\\|\/)math/,
        helpers.root('node_modules/@angular/core/src/facade/math.js')
      ),

      new ngcWebpack.NgcWebpackPlugin({
        disabled: !AOT,
        tsConfig: helpers.root('tsconfig.webpack.json'),
        resourceOverride: helpers.root('config/resource-override.js')
      })

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: true,
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}
<|endoftext|>


<commit_before>/*
  ___ usage ___ en_US ___
  name:

    executable - my executable

  synopsis:

    executable [--name <name>] [--bind <port|interface:port>]
               [--help] [--] <files>

  options:

    -n, --name <name> [string:required]
        named argument

    -b, --bind <port|interface:port> [bindable]
        bind to the interface

    --status

    --no-status [negate("never-")]
        do not display a status

    --never-status [negate("never-")]
        alias for `--no-status`

    -h
        show this help message
  ___ . ___
*/
require('./es6')(module, { $stdout: process.stdout }, async (arguable) => {
    if (arguable.complete) {
        return [ "foo", "bar", "baz" ]
    } else {
        arguable.options.$stdout.write('hello, world\n')
        return 0
    }
})
<commit_msg>Remove scrap code.<commit_after><|endoftext|>


<commit_before>var $carousels = [];
var loadedCarousels = {};
var css = {
    'containers': '.carousel__js',
    'handles': '.carousel__link--next, .carousel__link--prev'
};

export function init() {
    $carousels = $(css.containers);

    // prevent flicker effect on page load
    $carousels.on('init', function () {
        $(css.containers).css("visibility", "visible");
    });

    // img carousels
    $.each($carousels, function (i, carousel) {
        var $carousel = $(carousel),
            id = $carousel.attr("id");
        loadedCarousels[id] = false;

        $carousel.slick({
            speed: 300,
            slidesToShow: 1,
            infinite: false,
            appendArrows: "#" + id + " .slick-list",
            prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
            nextArrow: '<button class="carousel__link--next carousel__link--waggle">Nächstes Bild</button>',
            slide: ".carousel__item"
        });
        registerListener($carousel);
    });

    // video carousels
    $(".video_carousel__js").on("init", function (slick) {
        $(this).css("visibility", "visible");
        // triggering a "recalculation of dots" (via "setPosition" below)
        $(window).trigger('resize');
    });

    // video carousel:
    $.each($('.video_carousel__js'), function (i, carousel) {
        let $carousel = $(carousel),
            id = $carousel.attr("id");

        loadedCarousels[id] = false;

        $carousel.slick({
            infinite: false,
            slide: ".carousel__item",
            slidesToShow: 1, // we need all dots - initially
            slidesToScroll: 1,
            accessibility: false,
            focusOnSelect: true, // let's try this
            appendArrows: "#" + id + " .slick-list",
            dots: true,
            centerPadding: 0,
            variableWidth: true,
            prevArrow: '<button class="carousel__link--prev">Vorhergehender Slide</button>',
            nextArrow: '<button class="carousel__link--next">Nächster Slide</button>'
        });
    });

    // "position change" (resize page or "activate" slider in any way)
    $('.video_carousel__js').on('setPosition', function (slick) {
        let slidesToShow = getNumberOfSlidesPerScreen(1), // mobile : 1
            $carousel = $(this),
            currentSlide = $carousel.slick("slickCurrentSlide");
        // if previous num. of slides shown != the num. we'll see now
        if ($carousel.slick("slickGetOption", "slidesToShow") != slidesToShow) {
            // if slider not at initial pos. && arrows displayed
            if (currentSlide > 0 && slidesToShow != 1) {
                // move it to 0 - so the "arrows" don't get "confused"
                currentSlide = 0;
                $carousel.slick("slickGoTo", currentSlide, true);
            }

            if (slidesToShow > 1) { // this option is terrible for screen sizes showing more than 1 elm
                $carousel.slick("focusOnSelect", false);
            }

            // and adjust num. of slides...
            $carousel.slick("slickSetOption", "slidesToShow", slidesToShow, false);
            $carousel.slick("slickSetOption", "slidesToScroll", slidesToShow, false);

            let screensToShow = Math.ceil($carousel.find(".carousel__item").length / slidesToShow);

            (slidesToShow >= screensToShow) // are there more slides than elements?
                ? $(".slick-dots").removeClass(".h-element--hide")  // show dots
                : $(".slick-dots").addClass(".h-element--hide");    // else hide them

            // and adjust num. of dots
            rePaintDots($carousel, screensToShow);

            // if we're at the rightmost position within the carousel - we don't want the right arrow
            handleRightArrow($carousel, currentSlide, screensToShow);
        }
    });
}

function registerListener($carousel) {
    // load all images after user starts interacting with carousel
    $carousel.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        if (loadedCarousels[$carousel.attr("id")] === false) {
            loadedCarousels[$carousel.attr("id")] = true;
            loadLazyImages(slick.$slides.find(".image-figure__js"));
        }
    });

    $carousel.on('swipe', function (event, slick, direction) {
        // on "interacting" with the carousel => no more animation
        $(this).find(".carousel__link--next").removeClass("carousel__link--waggle");
    });

    $carousel.find(css.handles).on("touchstart mousedown mouseenter", function () {
        $(this).removeClass("untouched");
        // if the handles are clicked / touched: stop the animation
        $(this).removeClass("carousel__link--waggle");
    }).on("touchend touchcancel", function () {
        $(this).addClass("untouched");
    });
}

function loadLazyImages(images) {
    images.each(function (i, image) {
        var $image = $(image);
        if ($image.data("src")) {
            $image.attr("srcset", $image.data("srcset"));
            $image.attr("src", $image.data("src"));
        }
    });
}

function rePaintDots($carousel, screensToShow) {
    let x = screensToShow + 1;
    $carousel.find(".slick-dots li").removeClass("h-element--hide");
    $carousel.find(".slick-dots li:nth-child(1n + " + x + ")").addClass("h-element--hide");
}

function handleRightArrow($carousel, currentSlide, screensToShow) {
    if ((currentSlide + 1) == screensToShow) {
        $carousel.find(".carousel__link--next").addClass("h-element--hide").attr("aria-disabled", true);
    } else {
        $carousel.find(".carousel__link--next").removeClass("h-element--hide").attr("aria-disabled", false);
    }
}

function getNumberOfSlidesPerScreen(slidesToShow = 1) {
    // let slidesToShow = 1; // mobile

    if (matchMedia('screen and (min-width: 720px) and (max-width: 1023px)').matches) {
        slidesToShow = 2; // tablet
    } else if (matchMedia('screen and (min-width: 1024px)').matches) {
        slidesToShow = 3; // larger
    }

    return slidesToShow
}
<commit_msg>correction (that was silly!)<commit_after>var $carousels = [];
var loadedCarousels = {};
var css = {
    'containers': '.carousel__js',
    'handles': '.carousel__link--next, .carousel__link--prev'
};

export function init() {
    $carousels = $(css.containers);

    // prevent flicker effect on page load
    $carousels.on('init', function () {
        $(css.containers).css("visibility", "visible");
    });

    // img carousels
    $.each($carousels, function (i, carousel) {
        var $carousel = $(carousel),
            id = $carousel.attr("id");
        loadedCarousels[id] = false;

        $carousel.slick({
            speed: 300,
            slidesToShow: 1,
            infinite: false,
            appendArrows: "#" + id + " .slick-list",
            prevArrow: '<button class="carousel__link--prev">Vorhergehendes Bild</button>',
            nextArrow: '<button class="carousel__link--next carousel__link--waggle">Nächstes Bild</button>',
            slide: ".carousel__item"
        });
        registerListener($carousel);
    });

    // video carousels
    $(".video_carousel__js").on("init", function (slick) {
        $(this).css("visibility", "visible");
        // triggering a "recalculation of dots" (via "setPosition" below)
        $(window).trigger('resize');
    });

    // video carousel:
    $.each($('.video_carousel__js'), function (i, carousel) {
        let $carousel = $(carousel),
            id = $carousel.attr("id");

        loadedCarousels[id] = false;

        $carousel.slick({
            infinite: false,
            slide: ".carousel__item",
            slidesToShow: 1, // we need all dots - initially
            slidesToScroll: 1,
            accessibility: false,
            focusOnSelect: true, // let's try this
            appendArrows: "#" + id + " .slick-list",
            dots: true,
            centerPadding: 0,
            variableWidth: true,
            prevArrow: '<button class="carousel__link--prev">Vorhergehender Slide</button>',
            nextArrow: '<button class="carousel__link--next">Nächster Slide</button>'
        });
    });

    // "position change" (resize page or "activate" slider in any way)
    $('.video_carousel__js').on('setPosition', function (slick) {
        let slidesToShow = getNumberOfSlidesPerScreen(1), // mobile : 1
            $carousel = $(this),
            currentSlide = $carousel.slick("slickCurrentSlide");
        // if previous num. of slides shown != the num. we'll see now
        if ($carousel.slick("slickGetOption", "slidesToShow") != slidesToShow) {
            // if slider not at initial pos. && arrows displayed
            if (currentSlide > 0 && slidesToShow != 1) {
                // move it to 0 - so the "arrows" don't get "confused"
                currentSlide = 0;
                $carousel.slick("slickGoTo", currentSlide, true);
            }

            if (slidesToShow > 1) { // this option is terrible for screen sizes showing more than 1 elm
                $carousel.slick("slickSetOption", "focusOnSelect", false);
            }

            // and adjust num. of slides...
            $carousel.slick("slickSetOption", "slidesToShow", slidesToShow, false);
            $carousel.slick("slickSetOption", "slidesToScroll", slidesToShow, false);

            let screensToShow = Math.ceil($carousel.find(".carousel__item").length / slidesToShow);

            (slidesToShow >= screensToShow) // are there more slides than elements?
                ? $(".slick-dots").removeClass(".h-element--hide")  // show dots
                : $(".slick-dots").addClass(".h-element--hide");    // else hide them

            // and adjust num. of dots
            rePaintDots($carousel, screensToShow);

            // if we're at the rightmost position within the carousel - we don't want the right arrow
            handleRightArrow($carousel, currentSlide, screensToShow);
        }
    });
}

function registerListener($carousel) {
    // load all images after user starts interacting with carousel
    $carousel.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
        if (loadedCarousels[$carousel.attr("id")] === false) {
            loadedCarousels[$carousel.attr("id")] = true;
            loadLazyImages(slick.$slides.find(".image-figure__js"));
        }
    });

    $carousel.on('swipe', function (event, slick, direction) {
        // on "interacting" with the carousel => no more animation
        $(this).find(".carousel__link--next").removeClass("carousel__link--waggle");
    });

    $carousel.find(css.handles).on("touchstart mousedown mouseenter", function () {
        $(this).removeClass("untouched");
        // if the handles are clicked / touched: stop the animation
        $(this).removeClass("carousel__link--waggle");
    }).on("touchend touchcancel", function () {
        $(this).addClass("untouched");
    });
}

function loadLazyImages(images) {
    images.each(function (i, image) {
        var $image = $(image);
        if ($image.data("src")) {
            $image.attr("srcset", $image.data("srcset"));
            $image.attr("src", $image.data("src"));
        }
    });
}

function rePaintDots($carousel, screensToShow) {
    let x = screensToShow + 1;
    $carousel.find(".slick-dots li").removeClass("h-element--hide");
    $carousel.find(".slick-dots li:nth-child(1n + " + x + ")").addClass("h-element--hide");
}

function handleRightArrow($carousel, currentSlide, screensToShow) {
    if ((currentSlide + 1) == screensToShow) {
        $carousel.find(".carousel__link--next").addClass("h-element--hide").attr("aria-disabled", true);
    } else {
        $carousel.find(".carousel__link--next").removeClass("h-element--hide").attr("aria-disabled", false);
    }
}

function getNumberOfSlidesPerScreen(slidesToShow = 1) {
    // let slidesToShow = 1; // mobile

    if (matchMedia('screen and (min-width: 720px) and (max-width: 1023px)').matches) {
        slidesToShow = 2; // tablet
    } else if (matchMedia('screen and (min-width: 1024px)').matches) {
        slidesToShow = 3; // larger
    }

    return slidesToShow
}
<|endoftext|>


<commit_before>const webpack = require('webpack');
const helpers = require('./helpers');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const AssetsPlugin = require('assets-webpack-plugin');
const autoprefixer = require('autoprefixer');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ngcWebpack = require('ngc-webpack');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const sassLintPlugin = require('sasslint-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');

const precss = require('precss');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Fabric8 Planner',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

module.exports = {

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

    // An array of directory names to be resolved to the current directory
    modules: [helpers.root('src'), helpers.root('node_modules')],
  },

  stats: {
    colors: true,
    reasons: true
  },

  module: {
    rules: [
      // {
      //   enforce: 'pre',
      //   test: /\.ts$/,
      //   use: 'tslint-loader',
      //   exclude: [helpers.root('node_modules')]
      // },
      {
        test: /\.ts$/,
        use: [
          {
            loader: 'awesome-typescript-loader',
          },
          {
            loader: 'angular2-template-loader'
          }
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: 'file-loader'
      },

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

      {
        test: /\.css$/,
        use: [
          {
            loader: 'to-string-loader'
          },
          // Commented out as causing CSS ot load twice
          /*{
           loader: 'style-loader'
           },*/
          {
            loader: 'css-loader'
          },
        ]
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: 'css-to-string-loader'
          },
          // Commented out as causing CSS ot load twice
          /*{
           loader: 'style-loader'
           },*/
          {
            loader: 'css-loader',
            options: {sourceMap: true}
          },
          {
            loader: 'sass-loader',
            options: {sourceMap: true}
          }
        ]
      },
      {
        test: /\.html$/,
        use: 'raw-loader'
      }
    ]
  },

  plugins: [
    new AssetsPlugin({
      path: helpers.root('dist'),
      filename: 'webpack-assets.json',
      prettyPrint: true
    }),

    /*
     * Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new CheckerPlugin(),

    // new sassLintPlugin({
    //   configFile: '.sass-lint.yml',
    //   context: ['inherits from webpack'],
    //   ignoreFiles: [],
    //   ignorePlugins: [],
    //   glob: '**/*.s?(a|c)ss',
    //   quiet: false,
    //   failOnWarning: false,
    //   failOnError: false,
    //   testing: false
    // }),
    /**
     * Plugin: ContextReplacementPlugin
     * Description: Provides context to Angular's use of System.import
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
     * See: https://github.com/angular/angular/issues/11580
     */
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
      helpers.root('src') // location of your src
    ),

    /**
     * Webpack plugin to optimize a JavaScript file for faster initial load
     * by wrapping eagerly-invoked functions.
     *
     * See: https://github.com/vigneshshanmugam/optimize-js-plugin
     */

    new OptimizeJsPlugin({
      sourceMap: false
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html',
      title: METADATA.title,
      chunksSortMode: 'dependency',
      metadata: METADATA,
      inject: 'head'
    }),

    /**
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([
      {
        from: 'src/assets',
        to: 'assets'
      }
    ]),

    /*
     * Plugin: HtmlElementsPlugin
     * Description: Generate html tags based on javascript maps.
     *
     * If a publicPath is set in the webpack output configuration, it will be automatically added to
     * href attributes, you can disable that by adding a "=href": false property.
     * You can also enable it to other attribute by settings "=attName": true.
     *
     * The configuration supplied is map between a location (key) and an element definition object (value)
     * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
     *
     * Example:
     *  Adding this plugin configuration
     *  new HtmlElementsPlugin({
     *    headTags: { ... }
     *  })
     *
     *  Means we can use it in the template like this:
     *  <%= webpackConfig.htmlElements.headTags %>
     *
     * Dependencies: HtmlWebpackPlugin
     */
    new HtmlElementsPlugin({
      headTags: require('./head-config.common')
    }),

    /*
     * Plugin: ScriptExtHtmlWebpackPlugin
     * Description: Enhances html-webpack-plugin functionality
     * with different deployment options for your scripts including:
     *
     * See: https://github.com/numical/script-ext-html-webpack-plugin
     */
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: 'defer'
    }),

    /**
     * Plugin: ExtractTextPlugin
     * Description: Extracts imported CSS files into external stylesheet
     *
     * See: https://github.com/webpack/extract-text-webpack-plugin
     */
    // new ExtractTextPlugin('[name].[contenthash].css'),
    // new ExtractTextPlugin('[name].css'),

    new webpack.LoaderOptionsPlugin({
      // debug: true,
      // options: {
      //   /**
      //    * Html loader advanced options
      //    *
      //    * See: https://github.com/webpack/html-loader#advanced-options
      //    */
      //   // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
      //   htmlLoader: {
      //     minimize: true,
      //     removeAttributeQuotes: false,
      //     caseSensitive: true,
      //     customAttrSurround: [
      //       [/#/, /(?:)/],
      //       [/\*/, /(?:)/],
      //       [/\[?\(?/, /(?:)/]
      //     ],
      //     customAttrAssign: [/\)?\]?=/]
      //   },
      //
      //   context: helpers.root(),
      //   // output: {
      //   //   path: helpers.root('dist')
      //   // },
      //   tslintLoader: {
      //     emitErrors: false,
      //     failOnHint: false,
      //     resourcePath: 'src'
      //   },
      //   /**
      //    * Sass
      //    * Reference: https://github.com/jtangelder/sass-loader
      //    * Transforms .scss files to .css
      //    */
      //   sassLoader: {
      //     //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
      //   }
      // }
    }),
    // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
    // Only emit files when there are no errors
    new webpack.NoEmitOnErrorsPlugin(),

    // // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
    // // Dedupe modules in the output
    // new webpack.optimize.DedupePlugin(),

    // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
    // Minify all javascript, switch loaders to minimizing mode
    // new webpack.optimize.UglifyJsPlugin({sourceMap: true, mangle: { keep_fnames: true }}),

    // Copy assets from the public folder
    // Reference: https://github.com/kevlened/copy-webpack-plugin
    // new CopyWebpackPlugin([{
    //   from: helpers.root('src/public')
    // }]),

    // Reference: https://github.com/johnagan/clean-webpack-plugin
    // Removes the bundle folder before the build
    new CleanWebpackPlugin(['bundles'], {
      root: helpers.root(),
      verbose: false,
      dry: false
    }),

    // Fix Angular 2
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)async/,
      helpers.root('node_modules/@angular/core/src/facade/async.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)collection/,
      helpers.root('node_modules/@angular/core/src/facade/collection.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)errors/,
      helpers.root('node_modules/@angular/core/src/facade/errors.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)lang/,
      helpers.root('node_modules/@angular/core/src/facade/lang.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)math/,
      helpers.root('node_modules/@angular/core/src/facade/math.js')
    ),

    // new ngcWebpack.NgcWebpackPlugin({
    //   disabled: !AOT,
    //   tsConfig: helpers.root('tsconfig.webpack.json'),
    //   resourceOverride: helpers.root('config/resource-override.js')
    // })

  ]
};
<commit_msg>fix(build): add CleanWebpackPlugin to webpack commons<commit_after>const webpack = require('webpack');
const helpers = require('./helpers');

const AssetsPlugin = require('assets-webpack-plugin');
const autoprefixer = require('autoprefixer');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ngcWebpack = require('ngc-webpack');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const sassLintPlugin = require('sasslint-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');

const precss = require('precss');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const AOT = helpers.hasNpmFlag('aot');
const METADATA = {
  title: 'Fabric8 Planner',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

module.exports = {

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

    // An array of directory names to be resolved to the current directory
    modules: [helpers.root('src'), helpers.root('node_modules')],
  },

  stats: {
    colors: true,
    reasons: true
  },

  module: {
    rules: [
      // {
      //   enforce: 'pre',
      //   test: /\.ts$/,
      //   use: 'tslint-loader',
      //   exclude: [helpers.root('node_modules')]
      // },
      {
        test: /\.ts$/,
        use: [
          {
            loader: 'awesome-typescript-loader',
          },
          {
            loader: 'angular2-template-loader'
          }
        ],
        exclude: [/\.(spec|e2e)\.ts$/]
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: 'file-loader'
      },

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

      {
        test: /\.css$/,
        use: [
          {
            loader: 'to-string-loader'
          },
          // Commented out as causing CSS ot load twice
          /*{
           loader: 'style-loader'
           },*/
          {
            loader: 'css-loader'
          },
        ]
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: 'css-to-string-loader'
          },
          // Commented out as causing CSS ot load twice
          /*{
           loader: 'style-loader'
           },*/
          {
            loader: 'css-loader',
            options: {sourceMap: true}
          },
          {
            loader: 'sass-loader',
            options: {sourceMap: true}
          }
        ]
      },
      {
        test: /\.html$/,
        use: 'raw-loader'
      }
    ]
  },

  plugins: [
    new AssetsPlugin({
      path: helpers.root('dist'),
      filename: 'webpack-assets.json',
      prettyPrint: true
    }),

    /*
     * Plugin: ForkCheckerPlugin
     * Description: Do type checking in a separate process, so webpack don't need to wait.
     *
     * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
     */
    new CheckerPlugin(),

    // new sassLintPlugin({
    //   configFile: '.sass-lint.yml',
    //   context: ['inherits from webpack'],
    //   ignoreFiles: [],
    //   ignorePlugins: [],
    //   glob: '**/*.s?(a|c)ss',
    //   quiet: false,
    //   failOnWarning: false,
    //   failOnError: false,
    //   testing: false
    // }),
    /**
     * Plugin: ContextReplacementPlugin
     * Description: Provides context to Angular's use of System.import
     *
     * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
     * See: https://github.com/angular/angular/issues/11580
     */
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
      helpers.root('src') // location of your src
    ),

    /**
     * Webpack plugin to optimize a JavaScript file for faster initial load
     * by wrapping eagerly-invoked functions.
     *
     * See: https://github.com/vigneshshanmugam/optimize-js-plugin
     */

    new OptimizeJsPlugin({
      sourceMap: false
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html',
      title: METADATA.title,
      chunksSortMode: 'dependency',
      metadata: METADATA,
      inject: 'head'
    }),

    /**
     * Plugin: CopyWebpackPlugin
     * Description: Copy files and directories in webpack.
     *
     * Copies project static assets.
     *
     * See: https://www.npmjs.com/package/copy-webpack-plugin
     */
    new CopyWebpackPlugin([
      {
        from: 'src/assets',
        to: 'assets'
      }
    ]),

    /*
     * Plugin: HtmlElementsPlugin
     * Description: Generate html tags based on javascript maps.
     *
     * If a publicPath is set in the webpack output configuration, it will be automatically added to
     * href attributes, you can disable that by adding a "=href": false property.
     * You can also enable it to other attribute by settings "=attName": true.
     *
     * The configuration supplied is map between a location (key) and an element definition object (value)
     * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
     *
     * Example:
     *  Adding this plugin configuration
     *  new HtmlElementsPlugin({
     *    headTags: { ... }
     *  })
     *
     *  Means we can use it in the template like this:
     *  <%= webpackConfig.htmlElements.headTags %>
     *
     * Dependencies: HtmlWebpackPlugin
     */
    new HtmlElementsPlugin({
      headTags: require('./head-config.common')
    }),

    /*
     * Plugin: ScriptExtHtmlWebpackPlugin
     * Description: Enhances html-webpack-plugin functionality
     * with different deployment options for your scripts including:
     *
     * See: https://github.com/numical/script-ext-html-webpack-plugin
     */
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: 'defer'
    }),

    /**
     * Plugin: ExtractTextPlugin
     * Description: Extracts imported CSS files into external stylesheet
     *
     * See: https://github.com/webpack/extract-text-webpack-plugin
     */
    // new ExtractTextPlugin('[name].[contenthash].css'),
    // new ExtractTextPlugin('[name].css'),

    new webpack.LoaderOptionsPlugin({
      // debug: true,
      // options: {
      //   /**
      //    * Html loader advanced options
      //    *
      //    * See: https://github.com/webpack/html-loader#advanced-options
      //    */
      //   // TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
      //   htmlLoader: {
      //     minimize: true,
      //     removeAttributeQuotes: false,
      //     caseSensitive: true,
      //     customAttrSurround: [
      //       [/#/, /(?:)/],
      //       [/\*/, /(?:)/],
      //       [/\[?\(?/, /(?:)/]
      //     ],
      //     customAttrAssign: [/\)?\]?=/]
      //   },
      //
      //   context: helpers.root(),
      //   // output: {
      //   //   path: helpers.root('dist')
      //   // },
      //   tslintLoader: {
      //     emitErrors: false,
      //     failOnHint: false,
      //     resourcePath: 'src'
      //   },
      //   /**
      //    * Sass
      //    * Reference: https://github.com/jtangelder/sass-loader
      //    * Transforms .scss files to .css
      //    */
      //   sassLoader: {
      //     //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
      //   }
      // }
    }),
    // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
    // Only emit files when there are no errors
    new webpack.NoEmitOnErrorsPlugin(),

    // // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
    // // Dedupe modules in the output
    // new webpack.optimize.DedupePlugin(),

    // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
    // Minify all javascript, switch loaders to minimizing mode
    // new webpack.optimize.UglifyJsPlugin({sourceMap: true, mangle: { keep_fnames: true }}),

    // Copy assets from the public folder
    // Reference: https://github.com/kevlened/copy-webpack-plugin
    // new CopyWebpackPlugin([{
    //   from: helpers.root('src/public')
    // }]),

    // Reference: https://github.com/johnagan/clean-webpack-plugin
    // Removes the bundle folder before the build
    new CleanWebpackPlugin(['bundles'], {
      root: helpers.root(),
      verbose: false,
      dry: false
    }),

    // Fix Angular 2
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)async/,
      helpers.root('node_modules/@angular/core/src/facade/async.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)collection/,
      helpers.root('node_modules/@angular/core/src/facade/collection.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)errors/,
      helpers.root('node_modules/@angular/core/src/facade/errors.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)lang/,
      helpers.root('node_modules/@angular/core/src/facade/lang.js')
    ),
    new NormalModuleReplacementPlugin(
      /facade(\\|\/)math/,
      helpers.root('node_modules/@angular/core/src/facade/math.js')
    ),

    // new ngcWebpack.NgcWebpackPlugin({
    //   disabled: !AOT,
    //   tsConfig: helpers.root('tsconfig.webpack.json'),
    //   resourceOverride: helpers.root('config/resource-override.js')
    // })

  ]
};
<|endoftext|>


<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

core.Class("core.mvc.view.Dom",
{
  include : [core.mvc.view.Abstract],
  implement : [core.mvc.view.IView],

  construct: function(presenter) {
    core.mvc.view.Abstract.call(this, presenter);
  },

  properties :
  {
    /** Instance of compiled template to produce final data / text for output e.g. HTML, JSON, ... */
    template :
    {
      type: core.template.Template,
      nullable : true,
      apply : function() {
        this.render();
      }
    },

    /** The root element to render into */
    root :
    {
      type: "Node",
      nullable : true,
      apply : function(value, old) {
        this.render();
      }
    }
  },

  members :
  {
    // Interface implementation
    render : function()
    {
      if (this.__renderScheduled != null) {
        return;
      }

      /** #require(ext.RequestAnimationFrame) */
      this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
    },

    __renderRequest : function()
    {
      if (this._shouldRender())
      {
        this.__render();
        this.__renderScheduled = null;
      }
      else
      {
        this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
      }
    },

    /**
     * Internal render method which is called in buffered mode
     * so that only one rendering happens per frame.
     */
    __render : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      var template = this.getTemplate();
      if (!template) {
        return;
      }

      var presenter = this.getPresenter() || {};
      if (this.getPresenter() == null) {
        this.warn("Missing presenter!");
      }

      this._beforeRender();

      this.log("Rendering view...");
      elem.innerHTML = template.render(presenter);

      this._afterRender();
    },

    _shouldRender : function() {
      return this.__isLoading == 0;
    },

    _beforeRender : function() {
      // placeholder
    },

    _afterRender : function() {
      // placeholder
    },

    // Interface implementation
    show : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "";
      this.fireEvent("show");
    },

    // Interface implementation
    hide : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "none";
      this.fireEvent("hide");
    },

    __isLoading : 0,

    /**
     * Loads the given @tmpl {Uri} via the text loader (XHR) and creates
     * a new template instance which is auto applied to the #text property afterwards.
     */
    loadTemplate : function(tmpl, nocache)
    {
      this.__isLoading++;
      core.io.Text.load(jasy.Asset.toUri(tmpl), this.__loadTemplateCallback, this, nocache);
    },

    __loadTemplateCallback : function(uri, errornous, data)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load template: " + uri + "!");
      }

      this.setTemplate(core.template.Compiler.compile(data.text));
    },

    loadStyleSheet : function(sheet, nocache)
    {
      this.__isLoading++;
      core.io.StyleSheet.load(jasy.Asset.toUri(sheet), this.__loadStyleSheetCallback, this, nocache);
    },

    __loadStyleSheetCallback : function(uri, errornous)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load style sheet: " + uri + "!");
      }
    }
  }
});
<commit_msg>Cleanup<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

core.Class("core.mvc.view.Dom",
{
  include : [core.mvc.view.Abstract],
  implement : [core.mvc.view.IView],

  construct: function(presenter) {
    core.mvc.view.Abstract.call(this, presenter);
  },

  properties :
  {
    /** Instance of compiled template to produce final data / text for output e.g. HTML, JSON, ... */
    template :
    {
      type: core.template.Template,
      nullable : true,
      apply : function() {
        this.render();
      }
    },

    /** The root element to render into */
    root :
    {
      type: "Node",
      nullable : true,
      apply : function(value, old) {
        this.render();
      }
    }
  },

  members :
  {
    // Interface implementation
    render : function()
    {
      if (this.__renderScheduled != null) {
        return;
      }

      /** #require(ext.RequestAnimationFrame) */
      this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
    },

    __renderRequest : function()
    {
      if (this._shouldRender())
      {
        this.__render();
        this.__renderScheduled = null;
      }
      else
      {
        this.__renderScheduled = requestAnimationFrame(core.util.Function.bind(this.__renderRequest, this));
      }
    },

    /**
     * Internal render method which is called in buffered mode
     * so that only one rendering happens per frame.
     */
    __render : function()
    {
      var presenter = this.getPresenter();
      if (!presenter) {
        return;
      }

      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      var template = this.getTemplate();
      if (!template) {
        return;
      }

      this._beforeRender();
      elem.innerHTML = template.render(presenter);
      this._afterRender();
    },

    _shouldRender : function() {
      return this.__isLoading == 0;
    },

    _beforeRender : function() {
      // placeholder
    },

    _afterRender : function() {
      // placeholder
    },

    // Interface implementation
    show : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "";
      this.fireEvent("show");
    },

    // Interface implementation
    hide : function()
    {
      var elem = this.getRoot();
      if (!elem) {
        return;
      }

      elem.style.display = "none";
      this.fireEvent("hide");
    },

    __isLoading : 0,

    /**
     * Loads the given @tmpl {Uri} via the text loader (XHR) and creates
     * a new template instance which is auto applied to the #text property afterwards.
     */
    loadTemplate : function(tmpl, nocache)
    {
      this.__isLoading++;
      core.io.Text.load(jasy.Asset.toUri(tmpl), this.__loadTemplateCallback, this, nocache);
    },

    __loadTemplateCallback : function(uri, errornous, data)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load template: " + uri + "!");
      }

      this.setTemplate(core.template.Compiler.compile(data.text));
    },

    loadStyleSheet : function(sheet, nocache)
    {
      this.__isLoading++;
      core.io.StyleSheet.load(jasy.Asset.toUri(sheet), this.__loadStyleSheetCallback, this, nocache);
    },

    __loadStyleSheetCallback : function(uri, errornous)
    {
      this.__isLoading--;

      if (errornous) {
        throw new Error("Could not load style sheet: " + uri + "!");
      }
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var webpack = require('webpack');
var StatsPlugin = require('stats-webpack-plugin');

var IS_PRODUCTION = process.env.NODE_ENV === 'production';
var ROOT_PATH = path.resolve(__dirname, '..');

// must match config.webpack.dev_server.port
var DEV_SERVER_PORT = 3808;

var config = {
  context: ROOT_PATH,
  entry: {
    bundle: './app/assets/javascripts/webpack/bundle.js'
  },

  output: {
    path: path.join(ROOT_PATH, 'public/assets/webpack'),
    publicPath: '/assets/webpack/',
    filename: IS_PRODUCTION ? '[name]-[chunkhash].js' : '[name].js'
  },

  module: {
    loaders: [
      {
        test: /\.es6$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        }
      }
    ]
  },

  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    })
  ],

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

if (!IS_PRODUCTION) {
  config.devServer = {
    port: DEV_SERVER_PORT,
    headers: { 'Access-Control-Allow-Origin': '*' }
  };
  config.output.publicPath = '//localhost:' + DEV_SERVER_PORT + config.output.publicPath;
}

module.exports = config;
<commit_msg>optimize production output and generate sourcemaps<commit_after>'use strict';

var path = require('path');
var webpack = require('webpack');
var StatsPlugin = require('stats-webpack-plugin');

var IS_PRODUCTION = process.env.NODE_ENV === 'production';
var ROOT_PATH = path.resolve(__dirname, '..');

// must match config.webpack.dev_server.port
var DEV_SERVER_PORT = 3808;

var config = {
  context: ROOT_PATH,
  entry: {
    bundle: './app/assets/javascripts/webpack/bundle.js'
  },

  output: {
    path: path.join(ROOT_PATH, 'public/assets/webpack'),
    publicPath: '/assets/webpack/',
    filename: IS_PRODUCTION ? '[name]-[chunkhash].js' : '[name].js'
  },

  devtool: 'source-map',

  module: {
    loaders: [
      {
        test: /\.es6$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        }
      }
    ]
  },

  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    })
  ],

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

if (IS_PRODUCTION) {
  config.plugins.push(
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false }
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') }
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurrenceOrderPlugin()
  );
} else {
  config.devServer = {
    port: DEV_SERVER_PORT,
    headers: { 'Access-Control-Allow-Origin': '*' }
  };
  config.output.publicPath = '//localhost:' + DEV_SERVER_PORT + config.output.publicPath;
}

module.exports = config;
<|endoftext|>


<commit_before>// Staging config. Also the default config that prod and dev are based off of.

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const bourbon = require('bourbon').includePaths;
const neat = require('bourbon-neat').includePaths;
const path = require('path');
const webpack = require('webpack');
const _ = require('lodash');

require('babel-polyfill');

const entryFiles = {
  'disability-benefits': './src/js/disability-benefits/disability-benefits-entry.jsx',
  'edu-benefits': './src/js/edu-benefits/edu-benefits-entry.jsx',
  facilities: './src/js/facility-locator/facility-locator-entry.jsx',
  hca: './src/js/hca/hca-entry.jsx',
  messaging: './src/js/messaging/messaging-entry.jsx',
  rx: './src/js/rx/rx-entry.jsx',
  'no-react': './src/js/no-react-entry.js',
  'user-profile': './src/js/user-profile/user-profile-entry.jsx',
  auth: './src/js/auth/auth-entry.jsx'
};

const configGenerator = (options) => {
  var filesToBuild = entryFiles; // eslint-disable-line no-var
  if (options.entry) {
    filesToBuild = _.pick(entryFiles, options.entry.split(',').map(x => x.trim()));
  }
  filesToBuild.vendor = [
    'core-js',
    'history',
    'lodash',
    'jquery',
    'react',
    'react-dom',
    'react-redux',
    'react-router',
    'redux',
    'redux-thunk'
  ];
  const baseConfig = {
    entry: filesToBuild,
    output: {
      path: path.join(__dirname, `../build/${options.buildtype}/generated`),
      publicPath: '/generated/',
      filename: (options.buildtype === 'development') ? '[name].entry.js' : '[name].entry.[chunkhash].js'
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel',
          query: {
            // Speed up compilation.
            cacheDirectory: '.babelcache'

            // Also see .babelrc
          }
        },
        {
          test: /\.jsx$/,
          exclude: /node_modules/,
          loader: 'babel',
          query: {
            presets: ['react'],
            // Speed up compilation.
            cacheDirectory: '.babelcache'

            // Also see .babelrc
          }
        },
        {
          // components.js is effectively a hand-rolled bundle.js. Break it apart.
          test: /components\.js$/,
          loader: 'imports?this=>window'
        },
        {
          test: /foundation\.js$/,
          loader: 'imports?this=>window'
        },
        {
          test: /modernizrrc/,
          loader: 'modernizr'
        },
        {
          test: /\.scss$/,
          loader: ExtractTextPlugin.extract('style-loader', `css!resolve-url!sass?includePaths[]=${bourbon}&includePaths[]=${neat}&includePaths[]=~/uswds/src/stylesheets&sourceMap`)
        },
        {
          test: /\.(jpe?g|png|gif)$/i,
          loader: 'url?limit=10000!img?progressive=true&-minimize'
        },
        {
          test: /\.svg/,
          loader: 'svg-url'
        },
        {
          test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          loader: 'url-loader?limit=10000&minetype=application/font-woff'
        },
        {
          test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          loader: 'file-loader'
        }
      ],
      noParse: [/mapbox\/vendor\/promise.js$/],
    },
    resolve: {
      alias: {
        modernizr$: path.resolve(__dirname, './modernizrrc'),
        jquery: 'jquery/src/jquery'
      },
      extensions: ['', '.js', '.jsx']
    },
    plugins: [
      new webpack.DefinePlugin({
        __BUILDTYPE__: JSON.stringify(options.buildtype),
        __ALL_CLAIMS_ENABLED__: (options.buildtype === 'development' || process.env.ALL_CLAIMS_ENABLED === 'true'),
        __SAMPLE_ENABLED__: (process.env.SAMPLE_ENABLED === 'true'),
        'process.env': {
          NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
          API_PORT: (process.env.API_PORT || 4000),
          WEB_PORT: (process.env.WEB_PORT || 3333),
        }
      }),

      // See http://stackoverflow.com/questions/28969861/managing-jquery-plugin-dependency-in-webpack
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      }),

      new ExtractTextPlugin((options.buildtype === 'development') ? '[name].css' : '[name].[chunkhash].css'),
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new ManifestPlugin({
        fileName: 'file-manifest.json'
      }),
      new webpack.optimize.CommonsChunkPlugin(
        'vendor',
        (options.buildtype === 'development') ? 'vendor.js' : 'vendor.[chunkhash].js'
      )
    ],
  };

  if (options.buildtype === 'production' || options.buildtype === 'staging') {
    baseConfig.devtool = '#source-map';
    baseConfig.module.loaders.push({
      test: /debug\/PopulateVeteranButton/,
      loader: 'null'
    });
    baseConfig.module.loaders.push({
      test: /debug\/PerfPanel/,
      loader: 'null'
    });
    baseConfig.module.loaders.push({
      test: /debug\/RoutesDropdown/,
      loader: 'null'
    });

    baseConfig.plugins.push(new webpack.optimize.DedupePlugin());
    baseConfig.plugins.push(new webpack.optimize.OccurrenceOrderPlugin(true));
    baseConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
      beautify: false,
      compress: { warnings: false },
      comments: false
    }));
  } else {
    baseConfig.devtool = '#eval-source-map';
  }

  return baseConfig;
};

module.exports = configGenerator;
<commit_msg>remove lodash from vendor<commit_after>// Staging config. Also the default config that prod and dev are based off of.

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const bourbon = require('bourbon').includePaths;
const neat = require('bourbon-neat').includePaths;
const path = require('path');
const webpack = require('webpack');
const _ = require('lodash');

require('babel-polyfill');

const entryFiles = {
  'disability-benefits': './src/js/disability-benefits/disability-benefits-entry.jsx',
  'edu-benefits': './src/js/edu-benefits/edu-benefits-entry.jsx',
  facilities: './src/js/facility-locator/facility-locator-entry.jsx',
  hca: './src/js/hca/hca-entry.jsx',
  messaging: './src/js/messaging/messaging-entry.jsx',
  rx: './src/js/rx/rx-entry.jsx',
  'no-react': './src/js/no-react-entry.js',
  'user-profile': './src/js/user-profile/user-profile-entry.jsx',
  auth: './src/js/auth/auth-entry.jsx'
};

const configGenerator = (options) => {
  var filesToBuild = entryFiles; // eslint-disable-line no-var
  if (options.entry) {
    filesToBuild = _.pick(entryFiles, options.entry.split(',').map(x => x.trim()));
  }
  filesToBuild.vendor = [
    'core-js',
    'history',
    'jquery',
    'react',
    'react-dom',
    'react-redux',
    'react-router',
    'redux',
    'redux-thunk'
  ];
  const baseConfig = {
    entry: filesToBuild,
    output: {
      path: path.join(__dirname, `../build/${options.buildtype}/generated`),
      publicPath: '/generated/',
      filename: (options.buildtype === 'development') ? '[name].entry.js' : '[name].entry.[chunkhash].js'
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel',
          query: {
            // Speed up compilation.
            cacheDirectory: '.babelcache'

            // Also see .babelrc
          }
        },
        {
          test: /\.jsx$/,
          exclude: /node_modules/,
          loader: 'babel',
          query: {
            presets: ['react'],
            // Speed up compilation.
            cacheDirectory: '.babelcache'

            // Also see .babelrc
          }
        },
        {
          // components.js is effectively a hand-rolled bundle.js. Break it apart.
          test: /components\.js$/,
          loader: 'imports?this=>window'
        },
        {
          test: /foundation\.js$/,
          loader: 'imports?this=>window'
        },
        {
          test: /modernizrrc/,
          loader: 'modernizr'
        },
        {
          test: /\.scss$/,
          loader: ExtractTextPlugin.extract('style-loader', `css!resolve-url!sass?includePaths[]=${bourbon}&includePaths[]=${neat}&includePaths[]=~/uswds/src/stylesheets&sourceMap`)
        },
        {
          test: /\.(jpe?g|png|gif)$/i,
          loader: 'url?limit=10000!img?progressive=true&-minimize'
        },
        {
          test: /\.svg/,
          loader: 'svg-url'
        },
        {
          test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          loader: 'url-loader?limit=10000&minetype=application/font-woff'
        },
        {
          test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          loader: 'file-loader'
        }
      ],
      noParse: [/mapbox\/vendor\/promise.js$/],
    },
    resolve: {
      alias: {
        modernizr$: path.resolve(__dirname, './modernizrrc'),
        jquery: 'jquery/src/jquery'
      },
      extensions: ['', '.js', '.jsx']
    },
    plugins: [
      new webpack.DefinePlugin({
        __BUILDTYPE__: JSON.stringify(options.buildtype),
        __ALL_CLAIMS_ENABLED__: (options.buildtype === 'development' || process.env.ALL_CLAIMS_ENABLED === 'true'),
        __SAMPLE_ENABLED__: (process.env.SAMPLE_ENABLED === 'true'),
        'process.env': {
          NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
          API_PORT: (process.env.API_PORT || 4000),
          WEB_PORT: (process.env.WEB_PORT || 3333),
        }
      }),

      // See http://stackoverflow.com/questions/28969861/managing-jquery-plugin-dependency-in-webpack
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      }),

      new ExtractTextPlugin((options.buildtype === 'development') ? '[name].css' : '[name].[chunkhash].css'),
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new ManifestPlugin({
        fileName: 'file-manifest.json'
      }),
      new webpack.optimize.CommonsChunkPlugin(
        'vendor',
        (options.buildtype === 'development') ? 'vendor.js' : 'vendor.[chunkhash].js'
      )
    ],
  };

  if (options.buildtype === 'production' || options.buildtype === 'staging') {
    baseConfig.devtool = '#source-map';
    baseConfig.module.loaders.push({
      test: /debug\/PopulateVeteranButton/,
      loader: 'null'
    });
    baseConfig.module.loaders.push({
      test: /debug\/PerfPanel/,
      loader: 'null'
    });
    baseConfig.module.loaders.push({
      test: /debug\/RoutesDropdown/,
      loader: 'null'
    });

    baseConfig.plugins.push(new webpack.optimize.DedupePlugin());
    baseConfig.plugins.push(new webpack.optimize.OccurrenceOrderPlugin(true));
    baseConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
      beautify: false,
      compress: { warnings: false },
      comments: false
    }));
  } else {
    baseConfig.devtool = '#eval-source-map';
  }

  return baseConfig;
};

module.exports = configGenerator;
<|endoftext|>


<commit_before>require('dotenv').config()
const autoprefixer = require('autoprefixer')

const paths = require('config/paths')

const Env = process.env.NODE_ENV || 'development'
const DEV = Env === 'development'
const STAGING = Env === 'staging'
const PROD = Env === 'production'

console.log('Running webpack in ' + Env + ' environment')

const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const Webpack_isomorphic_tools_plugin = require('webpack-isomorphic-tools/plugin')

var webpack_isomorphic_tools_plugin = new Webpack_isomorphic_tools_plugin(
  require('./isomorphic-tools.config.js')
)

if (DEV) webpack_isomorphic_tools_plugin = webpack_isomorphic_tools_plugin.development()

const preloaders = []

if (DEV) {
  preloaders.push({
    test: /\.jsx?$/,
    loader: 'eslint-loader',
    exclude: /node_modules/
  })
}

const plugins = [
  new webpack.DefinePlugin({
    'process.env.API_URL': JSON.stringify(process.env.API_URL)
  }),
  new ExtractTextPlugin('bundle.css'),
  webpack_isomorphic_tools_plugin
]

const UGLIFY = STAGING || PROD

if (UGLIFY) {
  plugins.push(new webpack.optimize.UglifyJsPlugin({
    mangle: true,
    sourceMap: true
  }))
}

const loaders = [
  {
    test: /\.jsx?$/,
    loader: 'babel'
  },
  {
    test: /\.scss$/,
    loader: ExtractTextPlugin.extract(
      'style',
      [
        UGLIFY ? 'css?minimize!' : 'css',
        'postcss',
        'sass'
      ]
    )
  },
  {
    test: /\.svg$/,
    loader: 'svg-inline'
  },
  {
    test: /\.ttf$/,
    loader: 'url?limit=10000'
  },
  {
    test: /\.json$/,
    loader: 'json'
  }
]

const config = {
  context: paths.ROOT,
  entry: 'src/browser.jsx',
  output: {
    path: paths.BUNDLES,
    filename: UGLIFY ? 'bundle.min.js' : 'bundle.js'
  },
  devtool: DEV ? 'eval-source-map' : 'source-map',
  resolve: {
    extensions: ['', '.js', '.jsx', '.scss', '.svg'],
    root: [ paths.ROOT ]
  },
  stats: {
    colors: true,
    reasons: true,
    chunks: true
  },
  module: {
    preLoaders: preloaders,
    loaders: loaders
  },
  postcss: [ autoprefixer({ browsers: [ '> 1%' ]}) ],
  plugins: plugins
}

console.log('CONFIG IS: ', config)

module.exports = config
<commit_msg>Put webpack loaders directly into webpack config.<commit_after>require('dotenv').config()
const autoprefixer = require('autoprefixer')

const paths = require('config/paths')

const Env = process.env.NODE_ENV || 'development'
const DEV = Env === 'development'
const STAGING = Env === 'staging'
const PROD = Env === 'production'
const UGLIFY = STAGING || PROD

console.log('Running webpack in ' + Env + ' environment')

const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const Webpack_isomorphic_tools_plugin = require('webpack-isomorphic-tools/plugin')

var webpack_isomorphic_tools_plugin = new Webpack_isomorphic_tools_plugin(
  require('./isomorphic-tools.config.js')
)

if (DEV) webpack_isomorphic_tools_plugin = webpack_isomorphic_tools_plugin.development()

const preloaders = []

if (DEV) {
  preloaders.push({
    test: /\.jsx?$/,
    loader: 'eslint-loader',
    exclude: /node_modules/
  })
}

const plugins = [
  new webpack.DefinePlugin({
    'process.env.API_URL': JSON.stringify(process.env.API_URL)
  }),
  new ExtractTextPlugin('bundle.css'),
  webpack_isomorphic_tools_plugin
]

if (UGLIFY) {
  plugins.push(new webpack.optimize.UglifyJsPlugin({
    mangle: true,
    sourceMap: true
  }))
}

const config = {
  context: paths.ROOT,
  entry: 'src/browser.jsx',
  output: {
    path: paths.BUNDLES,
    filename: UGLIFY ? 'bundle.min.js' : 'bundle.js'
  },
  devtool: DEV ? 'eval-source-map' : 'source-map',
  resolve: {
    extensions: ['', '.js', '.jsx', '.scss', '.svg'],
    root: [ paths.ROOT ]
  },
  stats: {
    colors: true,
    reasons: true,
    chunks: true
  },
  module: {
    preLoaders: preloaders,
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel'
      },
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(
          'style',
          [
            UGLIFY ? 'css?minimize!' : 'css',
            'postcss',
            'sass'
          ]
        )
      },
      {
        test: /\.svg$/,
        loader: 'svg-inline'
      },
      {
        test: /\.ttf$/,
        loader: 'url?limit=10000'
      },
      {
        test: /\.json$/,
        loader: 'json'
      }
    ]
  },
  postcss: [ autoprefixer({ browsers: [ '> 1%' ]}) ],
  plugins: plugins
}

console.log('CONFIG IS: ', config)

module.exports = config
<|endoftext|>


<commit_before>import React, { PureComponent} from 'react'
import PropTypes from 'prop-types';
import classnames from 'classnames';
import scrollTo from '../lib/scroll';
import throttle from 'lodash.throttle';

class PageNav extends PureComponent {
	static propTypes = {
		reduceOnMobile : PropTypes.bool,
		name : PropTypes.string.isRequired,
		isActive: PropTypes.bool.isRequired,
		isScrollTriggered: PropTypes.bool.isRequired,
		backgroundColor: PropTypes.string
	};

	shouldComponentUpdate(nextProps) {
		return this.props.isActive !== nextProps.isActive
			|| this.props.isScrollTriggered !== nextProps.isScrollTriggered;
	}

	componentDidMount(){
		global.addEventListener('scroll', throttle(()=> this.activateOnScroll(), 100))
	}

	activateOnScroll(){
		const {pageYOffset, innerHeight} = global;
		if(!this.props.isScrollTriggered
			&& pageYOffset > this.elem.offsetTop - innerHeight/3 && pageYOffset < this.elem.offsetTop + this.elem.offsetHeight - innerHeight/3) {
			this.props.setActiveSection(this.props.name);
		}
	}

	componentWillUpdate(newProps){
		if(newProps.isActive && newProps.isScrollTriggered)	{
			scrollTo(this.elem.offsetTop, 300, this.props.unsetScrollTriggered)
		}
	}

    render(){
    	const {children, reduceOnMobile, backgroundColor} = this.props;
    	const classNames = classnames({
			'c-homepage-section': true,
			'c-homepage-section--reduce-on-mobile' : reduceOnMobile,
			'c-homepage-section--pale-green': backgroundColor === 'pale-green'
		});

        return (

 this.elem = elem}
					 className={classNames}
					 data-js-animate-on-view>
				{children}

		)
    }
}

export default PageNav<commit_msg>Fixing warning<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types';
import classnames from 'classnames';
import scrollTo from '../lib/scroll';
import throttle from 'lodash.throttle';

class PageNav extends Component {
	static propTypes = {
		reduceOnMobile : PropTypes.bool,
		name : PropTypes.string.isRequired,
		isActive: PropTypes.bool.isRequired,
		isScrollTriggered: PropTypes.bool.isRequired,
		backgroundColor: PropTypes.string
	};

	shouldComponentUpdate(nextProps) {
		return this.props.isActive !== nextProps.isActive
			|| this.props.isScrollTriggered !== nextProps.isScrollTriggered;
	}

	componentDidMount(){
		global.addEventListener('scroll', throttle(()=> this.activateOnScroll(), 100))
	}

	activateOnScroll(){
		const {pageYOffset, innerHeight} = global;
		if(!this.props.isScrollTriggered
			&& pageYOffset > this.elem.offsetTop - innerHeight/3 && pageYOffset < this.elem.offsetTop + this.elem.offsetHeight - innerHeight/3) {
			this.props.setActiveSection(this.props.name);
		}
	}

	componentWillUpdate(newProps){
		if(newProps.isActive && newProps.isScrollTriggered)	{
			scrollTo(this.elem.offsetTop, 300, this.props.unsetScrollTriggered)
		}
	}

    render(){
    	const {children, reduceOnMobile, backgroundColor} = this.props;
    	const classNames = classnames({
			'c-homepage-section': true,
			'c-homepage-section--reduce-on-mobile' : reduceOnMobile,
			'c-homepage-section--pale-green': backgroundColor === 'pale-green'
		});

        return (

 this.elem = elem}
					 className={classNames}
					 data-js-animate-on-view>
				{children}

		)
    }
}

export default PageNav<|endoftext|>