<commit_before>// Helper: root() is defined at the bottom
var path = require('path');
var webpack = require('webpack');

// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
var isTest = ENV === 'test' || isTestWatch;
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isProd) {
    config.devtool = 'source-map';
  }
  else if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   */
  config.entry = isTest ? {} : {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts' // our angular app
  };

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   */
  config.output = isTest ? {} : {
    path: root('dist'),
    publicPath: isProd ? '/' : 'http://localhost:8080/',
    filename: isProd ? 'js/[name].[hash].js' : 'js/[name].js',
    chunkFilename: isProd ? '[id].[hash].chunk.js' : '[id].chunk.js'
  };

  /**
   * Resolve
   * Reference: http://webpack.github.io/docs/configuration.html#resolve
   */
  config.resolve = {
    // only discover files that have those extensions
    extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'],
  };

  var atlOptions = '';
  if (isTest && !isTestWatch) {
    // awesome-typescript-loader needs to output inlineSourceMap for code coverage to work with source maps.
    atlOptions = 'inlineSourceMap=true&sourceMap=false';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */
  config.module = {
    rules: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader?' + atlOptions, 'angular2-template-loader', '@angularclass/hmr-loader'],
        exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
      },

      // copy those assets to output
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader?name=fonts/[name].[hash].[ext]?'
      },

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

      // Support for CSS as raw text
      // use 'null' loader in test mode (https://github.com/webpack/null-loader)
      // all css in src/style will be bundled in an external css file
      {
        test: /\.css$/,
        exclude: root('src', 'app'),
        loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css-loader', 'postcss-loader']})
      },
      // all css required in src/app files will be merged in js files
      {test: /\.css$/, include: root('src', 'app'), loader: 'raw-loader!postcss-loader'},

      // support for .scss files
      // use 'null' loader in test mode (https://github.com/webpack/null-loader)
      // all css in src/style will be bundled in an external css file
      {
        test: /\.(scss|sass)$/,
        exclude: root('src', 'app'),
        loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css-loader', 'postcss-loader', 'sass-loader']})
      },
      // all css required in src/app files will be merged in js files
      {test: /\.(scss|sass)$/, exclude: root('src', 'style'), loader: 'raw-loader!postcss-loader!sass-loader'},

      // support for .html as raw text
      // todo: change the loader to something that adds a hash to images
      {test: /\.html$/, loader: 'raw-loader',  exclude: root('src', 'public')}
    ]
  };

  if (isTest && !isTestWatch) {
    // instrument only testing sources with Istanbul, covers ts files
    config.module.rules.push({
      test: /\.ts$/,
      enforce: 'post',
      include: path.resolve('src'),
      loader: 'istanbul-instrumenter-loader',
      exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
    });
  }

  if (!isTest || !isTestWatch) {
    // tslint support
    config.module.rules.push({
      test: /\.ts$/,
      enforce: 'pre',
      loader: 'tslint-loader'
    });
  }

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
    // Define env variables to help with builds
    // Reference: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      // Environment helpers
      'process.env': {
        ENV: JSON.stringify(ENV)
      }
    }),

    // Workaround needed for angular 2 angular/angular#11580
      new webpack.ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        root('./src') // location of your src
      ),

    // Tslint configuration for webpack 2
    new webpack.LoaderOptionsPlugin({
      options: {
        /**
         * Apply the tslint loader as pre/postLoader
         * Reference: https://github.com/wbuchwalter/tslint-loader
         */
        tslint: {
          emitErrors: false,
          failOnHint: false
        },
        /**
         * Sass
         * Reference: https://github.com/jtangelder/sass-loader
         * Transforms .scss files to .css
         */
        sassLoader: {
          //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
        },
        /**
         * PostCSS
         * Reference: https://github.com/postcss/autoprefixer-core
         * Add vendor prefixes to your css
         */
        postcss: [
          autoprefixer({
            browsers: ['last 2 version']
          })
        ]
      }
    })
  ];

  if (!isTest && !isTestWatch) {
    config.plugins.push(
      new ForkCheckerPlugin(),

      // Generate common chunks if necessary
      // Reference: https://webpack.github.io/docs/code-splitting.html
      // Reference: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
      new CommonsChunkPlugin({
        name: ['vendor', 'polyfills']
      }),

      // Inject script and link tags into html files
      // Reference: https://github.com/ampedandwired/html-webpack-plugin
      new HtmlWebpackPlugin({
        template: './src/public/index.html',
        chunksSortMode: 'dependency'
      }),

      // Extract css files
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin({filename: 'css/[name].[hash].css', disable: !isProd})
    );
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // // 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: root('src/public')
      }])
    );
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    historyApiFallback: true,
    quiet: true,
    stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
  };

  return config;
}();

// Helper functions
function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
<commit_msg>remove fork checker plugin, not needed anymore<commit_after>// Helper: root() is defined at the bottom
var path = require('path');
var webpack = require('webpack');

// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
var isTest = ENV === 'test' || isTestWatch;
var isProd = ENV === 'build';

module.exports = function makeWebpackConfig() {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isProd) {
    config.devtool = 'source-map';
  }
  else if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   */
  config.entry = isTest ? {} : {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts' // our angular app
  };

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   */
  config.output = isTest ? {} : {
    path: root('dist'),
    publicPath: isProd ? '/' : 'http://localhost:8080/',
    filename: isProd ? 'js/[name].[hash].js' : 'js/[name].js',
    chunkFilename: isProd ? '[id].[hash].chunk.js' : '[id].chunk.js'
  };

  /**
   * Resolve
   * Reference: http://webpack.github.io/docs/configuration.html#resolve
   */
  config.resolve = {
    // only discover files that have those extensions
    extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'],
  };

  var atlOptions = '';
  if (isTest && !isTestWatch) {
    // awesome-typescript-loader needs to output inlineSourceMap for code coverage to work with source maps.
    atlOptions = 'inlineSourceMap=true&sourceMap=false';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */
  config.module = {
    rules: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader?' + atlOptions, 'angular2-template-loader', '@angularclass/hmr-loader'],
        exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
      },

      // copy those assets to output
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader?name=fonts/[name].[hash].[ext]?'
      },

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

      // Support for CSS as raw text
      // use 'null' loader in test mode (https://github.com/webpack/null-loader)
      // all css in src/style will be bundled in an external css file
      {
        test: /\.css$/,
        exclude: root('src', 'app'),
        loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css-loader', 'postcss-loader']})
      },
      // all css required in src/app files will be merged in js files
      {test: /\.css$/, include: root('src', 'app'), loader: 'raw-loader!postcss-loader'},

      // support for .scss files
      // use 'null' loader in test mode (https://github.com/webpack/null-loader)
      // all css in src/style will be bundled in an external css file
      {
        test: /\.(scss|sass)$/,
        exclude: root('src', 'app'),
        loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: ['css-loader', 'postcss-loader', 'sass-loader']})
      },
      // all css required in src/app files will be merged in js files
      {test: /\.(scss|sass)$/, exclude: root('src', 'style'), loader: 'raw-loader!postcss-loader!sass-loader'},

      // support for .html as raw text
      // todo: change the loader to something that adds a hash to images
      {test: /\.html$/, loader: 'raw-loader',  exclude: root('src', 'public')}
    ]
  };

  if (isTest && !isTestWatch) {
    // instrument only testing sources with Istanbul, covers ts files
    config.module.rules.push({
      test: /\.ts$/,
      enforce: 'post',
      include: path.resolve('src'),
      loader: 'istanbul-instrumenter-loader',
      exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
    });
  }

  if (!isTest || !isTestWatch) {
    // tslint support
    config.module.rules.push({
      test: /\.ts$/,
      enforce: 'pre',
      loader: 'tslint-loader'
    });
  }

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
    // Define env variables to help with builds
    // Reference: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      // Environment helpers
      'process.env': {
        ENV: JSON.stringify(ENV)
      }
    }),

    // Workaround needed for angular 2 angular/angular#11580
      new webpack.ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        root('./src') // location of your src
      ),

    // Tslint configuration for webpack 2
    new webpack.LoaderOptionsPlugin({
      options: {
        /**
         * Apply the tslint loader as pre/postLoader
         * Reference: https://github.com/wbuchwalter/tslint-loader
         */
        tslint: {
          emitErrors: false,
          failOnHint: false
        },
        /**
         * Sass
         * Reference: https://github.com/jtangelder/sass-loader
         * Transforms .scss files to .css
         */
        sassLoader: {
          //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
        },
        /**
         * PostCSS
         * Reference: https://github.com/postcss/autoprefixer-core
         * Add vendor prefixes to your css
         */
        postcss: [
          autoprefixer({
            browsers: ['last 2 version']
          })
        ]
      }
    })
  ];

  if (!isTest && !isTestWatch) {
    config.plugins.push(
      // Generate common chunks if necessary
      // Reference: https://webpack.github.io/docs/code-splitting.html
      // Reference: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
      new CommonsChunkPlugin({
        name: ['vendor', 'polyfills']
      }),

      // Inject script and link tags into html files
      // Reference: https://github.com/ampedandwired/html-webpack-plugin
      new HtmlWebpackPlugin({
        template: './src/public/index.html',
        chunksSortMode: 'dependency'
      }),

      // Extract css files
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin({filename: 'css/[name].[hash].css', disable: !isProd})
    );
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // // 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: root('src/public')
      }])
    );
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    historyApiFallback: true,
    quiet: true,
    stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
  };

  return config;
}();

// Helper functions
function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}
<|endoftext|>


<commit_before>'use strict';

/*jslint latedef:false*/

(function() {
  angular.module('o19s.splainer-search')
    .factory('EsSearcherFactory', [
      '$http',
      '$q',
      '$log',
      'EsDocFactory',
      'activeQueries',
      'esSearcherPreprocessorSvc',
      'esUrlSvc',
      'SearcherFactory',
      'transportSvc',
      EsSearcherFactory
    ]);

  function EsSearcherFactory(
    $http, $q, $log,
    EsDocFactory,
    activeQueries,
    esSearcherPreprocessorSvc, esUrlSvc,
    SearcherFactory,
    transportSvc
  ) {

    var Searcher = function(options) {
      SearcherFactory.call(this, options, esSearcherPreprocessorSvc);
    };

    Searcher.prototype = Object.create(SearcherFactory.prototype);
    Searcher.prototype.constructor = Searcher; // Reset the constructor

    Searcher.prototype.addDocToGroup    = addDocToGroup;
    Searcher.prototype.pager            = pager;
    Searcher.prototype.search           = search;
    Searcher.prototype.explainOther     = explainOther;
    Searcher.prototype.explain          = explain;
    Searcher.prototype.majorVersion     = majorVersion;
    Searcher.prototype.isTemplateCall   = isTemplateCall;

    function addDocToGroup (groupedBy, group, solrDoc) {
      /*jslint validthis:true*/
      var self = this;

      if (!self.grouped.hasOwnProperty(groupedBy)) {
        self.grouped[groupedBy] = [];
      }

      var found = null;
      angular.forEach(self.grouped[groupedBy], function(groupedDocs) {
        if (groupedDocs.value === group && !found) {
          found = groupedDocs;
        }
      });

      if (!found) {
        found = {docs:[], value:group};
        self.grouped[groupedBy].push(found);
      }

      found.docs.push(solrDoc);
    }

    // return a new searcher that will give you
    // the next page upon search(). To get the subsequent
    // page, call pager on that searcher ad infinidum
    function pager () {
      /*jslint validthis:true*/
      var self      = this;
      var pagerArgs = { from: 0, size: self.config.numberOfRows };
      var nextArgs  = angular.copy(self.args);

      if (nextArgs.hasOwnProperty('pager') && nextArgs.pager !== undefined) {
        pagerArgs = nextArgs.pager;
      } else if (self.hasOwnProperty('pagerArgs') && self.pagerArgs !== undefined) {
        pagerArgs = self.pagerArgs;
      }

      if (pagerArgs.hasOwnProperty('from')) {
        pagerArgs.from = parseInt(pagerArgs.from) + pagerArgs.size;

        if (pagerArgs.from >= self.numFound) {
          return null; // no more results
        }
      } else {
        pagerArgs.from = pagerArgs.size;
      }

      nextArgs.pager      = pagerArgs;
      var options         = {
        args:       nextArgs,
        config:     self.config,
        fieldList:  self.fieldList,
        queryText:  self.queryText,
        type:       self.type,
        url:        self.url,
      };

      var nextSearcher = new Searcher(options);

      return nextSearcher;
    }

    // search (execute the query) and produce results
    // to the returned future
    function search () {
      /*jslint validthis:true*/
      var self      = this;
      var uri       = esUrlSvc.parseUrl(self.url);
      var apiMethod = self.config.apiMethod;

      if ( esUrlSvc.isBulkCall(uri) ) {
        apiMethod = 'BULK';
      }

      // Using templates assumes that the _source field is defined
      // in the template, not passed in
      if (apiMethod === 'GET' && !esUrlSvc.isTemplateCall(uri)) {
        var fieldList = (self.fieldList === '*') ? '*' : self.fieldList.join(',');

        if ( 5 <= self.majorVersion() ) {
          /*jshint camelcase: false */
          esUrlSvc.setParams(uri, {
            _source:       fieldList,
          });
        } else {
          esUrlSvc.setParams(uri, {
            _source: fieldList,
          });
        }
      }

      var url       = esUrlSvc.buildUrl(uri);
      var transport = transportSvc.getTransport({apiMethod: apiMethod});

      var queryDslWithPagerArgs = angular.copy(self.queryDsl);
      if (self.pagerArgs) {
        if (esUrlSvc.isTemplateCall(uri)) {
          queryDslWithPagerArgs.params.from = self.pagerArgs.from;
          queryDslWithPagerArgs.params.size = self.pagerArgs.size;
        }
        else {
          queryDslWithPagerArgs.from = self.pagerArgs.from;
          queryDslWithPagerArgs.size = self.pagerArgs.size;
        }
      }

      if (esUrlSvc.isTemplateCall(uri)) {
        delete queryDslWithPagerArgs._source;
        delete queryDslWithPagerArgs.highlight;
      } else if (self.config.highlight===false) {
        delete queryDslWithPagerArgs.highlight;
      }

      self.inError  = false;

      var getExplData = function(doc) {
        if (doc.hasOwnProperty('_explanation')) {
          return doc._explanation;
        }
        else {
          return null;
        }
      };

      var getHlData = function(doc) {
        if (doc.hasOwnProperty('highlight')) {
          return doc.highlight;
        } else {
          return null;
        }
      };

      var getQueryParsingData = function(data) {
        if (data.hasOwnProperty('profile')) {
          return data.profile;
        }
        else {
          return {};
        }
      };

      var formatError = function(msg) {
          var errorMsg = '';
          if (msg) {
            if (msg.status >= 400) {
              errorMsg = 'HTTP Error: ' + msg.status + ' ' + msg.statusText;
            }
            if (msg.status > 0) {
              if (msg.hasOwnProperty('data') && msg.data) {

                if (msg.data.hasOwnProperty('error')) {
                  errorMsg += '\n' + JSON.stringify(msg.data.error, null, 2);
                }
                if (msg.data.hasOwnProperty('_shards')) {
                  angular.forEach(msg.data._shards.failures, function(failure) {
                    errorMsg += '\n' + JSON.stringify(failure, null, 2);
                  });
                }

              }
            }
            else if (msg.status === -1 || msg.status === 0) {
              errorMsg +=  'Network Error! (host not found)\n';
              errorMsg += '\n';
              errorMsg +=  'or CORS needs to be configured for your Elasticsearch\n';
              errorMsg +=  '\n';
              errorMsg +=  'Enable CORS in elasticsearch.yml:\n';
              errorMsg += '\n';
              errorMsg += 'http.cors.allow-origin: "/https?:\\\\/\\\\/(.*?\\\\.)?(quepid\\\\.com|splainer\\\\.io)/"\n';
              errorMsg += 'http.cors.enabled: true\n';
            }
            msg.searchError = errorMsg;
          }
          return msg;
      };

      // Build URL with params if any
      // Eg. without params:  /_search
      // Eg. with params:     /_search?size=5&from=5
      //esUrlSvc.setParams(uri, self.pagerArgs);

      var headers = esUrlSvc.getHeaders(uri, self.config.customHeaders);

      activeQueries.count++;
      return transport.query(url, queryDslWithPagerArgs, headers)
        .then(function success(httpConfig) {
          var data = httpConfig.data;
          activeQueries.count--;
          if (data.hits.hasOwnProperty('total') && data.hits.total.hasOwnProperty('value')) {
            self.numFound = data.hits.total.value;
          }
          else {
            self.numFound = data.hits.total;
          }
          self.parsedQueryDetails = getQueryParsingData(data);

          var parseDoc = function(doc, groupedBy, group) {
            var explDict  = getExplData(doc);
            var hlDict    = getHlData(doc);

            var options = {
              groupedBy:          groupedBy,
              group:              group,
              fieldList:          self.fieldList,
              url:                self.url,
              explDict:           explDict,
              hlDict:             hlDict,
              version:            self.majorVersion(),
            };

            return new EsDocFactory(doc, options);
          };

          angular.forEach(data.hits.hits, function(hit) {
            var doc = parseDoc(hit);
            self.docs.push(doc);
          });

          if ( angular.isDefined(data._shards) && data._shards.failed > 0 ) {
            return $q.reject(formatError(httpConfig));
          }
        }, function error(msg) {
          activeQueries.count--;
          self.inError = true;
          return $q.reject(formatError(msg));
        })
        .catch(function(response) {
          $log.debug('Failed to execute search');
          return $q.reject(response);
        });
    } // end of search()

    function explainOther (otherQuery) {
      /*jslint validthis:true*/
      var self = this;

      var otherSearcherOptions = {
        fieldList:  self.fieldList,
        url:        self.url,
        args:       self.args,
        queryText:  otherQuery,
        config:     {
          apiMethod:    'POST',
          numberOfRows: self.config.numberOfRows,
          version:      self.config.version,
        },
        type:       self.type,
      };

      if ( angular.isDefined(self.pagerArgs) && self.pagerArgs !== null ) {
        otherSearcherOptions.args.pager = self.pagerArgs;
      }

      var otherSearcher = new Searcher(otherSearcherOptions);

      return otherSearcher.search()
        .then(function() {
          self.numFound = otherSearcher.numFound;

          var defer     = $q.defer();
          var promises  = [];
          var docs      = [];

          angular.forEach(otherSearcher.docs, function(doc) {
            var promise = self.explain(doc)
              .then(function(parsedDoc) {
                docs.push(parsedDoc);
              });

            promises.push(promise);
          });

          $q.all(promises)
            .then(function () {
              self.docs = docs;
              defer.resolve();
            });

          return defer.promise;
        }).catch(function(response) {
          $log.debug('Failed to run explainOther');
          return response;
        });
    } // end of explainOther()

    function explain(doc) {
      /*jslint validthis:true*/
      var self    = this;
      var uri     = esUrlSvc.parseUrl(self.url);
      var url     = esUrlSvc.buildExplainUrl(uri, doc);
      var headers = esUrlSvc.getHeaders(uri, self.config.customHeaders);

      return $http.post(url, { query: self.queryDsl.query }, {headers: headers})
        .then(function(response) {
          var explDict  = response.data.explanation || null;

          var options = {
            fieldList: self.fieldList,
            url:       self.url,
            explDict:  explDict,
          };

          return new EsDocFactory(doc, options);
        }).catch(function(response) {
          $log.debug('Failed to run explain');
          return response;
        });
    } // end of explain()

    function majorVersion() {
      var self = this;

      if ( angular.isDefined(self.config) &&
        angular.isDefined(self.config.version) &&
        self.config.version !== null &&
        self.config.version !== ''
      ) {
        return parseInt(self.config.version.split('.')[0]);
      } else {
        return null;
      }
    }

    function isTemplateCall() {
      var self = this;

      return esUrlSvc.isTemplateCall(esUrlSvc.parseUrl(self.url));
    }

    // Return factory object
    return Searcher;
  }
})();
<commit_msg>Part 1 of fix for explain other<commit_after>'use strict';

/*jslint latedef:false*/

(function() {
  angular.module('o19s.splainer-search')
    .factory('EsSearcherFactory', [
      '$http',
      '$q',
      '$log',
      'EsDocFactory',
      'activeQueries',
      'esSearcherPreprocessorSvc',
      'esUrlSvc',
      'SearcherFactory',
      'transportSvc',
      EsSearcherFactory
    ]);

  function EsSearcherFactory(
    $http, $q, $log,
    EsDocFactory,
    activeQueries,
    esSearcherPreprocessorSvc, esUrlSvc,
    SearcherFactory,
    transportSvc
  ) {

    var Searcher = function(options) {
      SearcherFactory.call(this, options, esSearcherPreprocessorSvc);
    };

    Searcher.prototype = Object.create(SearcherFactory.prototype);
    Searcher.prototype.constructor = Searcher; // Reset the constructor

    Searcher.prototype.addDocToGroup    = addDocToGroup;
    Searcher.prototype.pager            = pager;
    Searcher.prototype.search           = search;
    Searcher.prototype.explainOther     = explainOther;
    Searcher.prototype.explain          = explain;
    Searcher.prototype.majorVersion     = majorVersion;
    Searcher.prototype.isTemplateCall   = isTemplateCall;

    function addDocToGroup (groupedBy, group, solrDoc) {
      /*jslint validthis:true*/
      var self = this;

      if (!self.grouped.hasOwnProperty(groupedBy)) {
        self.grouped[groupedBy] = [];
      }

      var found = null;
      angular.forEach(self.grouped[groupedBy], function(groupedDocs) {
        if (groupedDocs.value === group && !found) {
          found = groupedDocs;
        }
      });

      if (!found) {
        found = {docs:[], value:group};
        self.grouped[groupedBy].push(found);
      }

      found.docs.push(solrDoc);
    }

    // return a new searcher that will give you
    // the next page upon search(). To get the subsequent
    // page, call pager on that searcher ad infinidum
    function pager () {
      /*jslint validthis:true*/
      var self      = this;
      var pagerArgs = { from: 0, size: self.config.numberOfRows };
      var nextArgs  = angular.copy(self.args);

      if (nextArgs.hasOwnProperty('pager') && nextArgs.pager !== undefined) {
        pagerArgs = nextArgs.pager;
      } else if (self.hasOwnProperty('pagerArgs') && self.pagerArgs !== undefined) {
        pagerArgs = self.pagerArgs;
      }

      if (pagerArgs.hasOwnProperty('from')) {
        pagerArgs.from = parseInt(pagerArgs.from) + pagerArgs.size;

        if (pagerArgs.from >= self.numFound) {
          return null; // no more results
        }
      } else {
        pagerArgs.from = pagerArgs.size;
      }

      nextArgs.pager      = pagerArgs;
      var options         = {
        args:       nextArgs,
        config:     self.config,
        fieldList:  self.fieldList,
        queryText:  self.queryText,
        type:       self.type,
        url:        self.url,
      };

      var nextSearcher = new Searcher(options);

      return nextSearcher;
    }

    // search (execute the query) and produce results
    // to the returned future
    function search () {
      /*jslint validthis:true*/
      var self      = this;
      var uri       = esUrlSvc.parseUrl(self.url);
      var apiMethod = self.config.apiMethod;

      if ( esUrlSvc.isBulkCall(uri) ) {
        apiMethod = 'BULK';
      }

      // Using templates assumes that the _source field is defined
      // in the template, not passed in
      if (apiMethod === 'GET' && !esUrlSvc.isTemplateCall(uri)) {
        var fieldList = (self.fieldList === '*') ? '*' : self.fieldList.join(',');

        if ( 5 <= self.majorVersion() ) {
          /*jshint camelcase: false */
          esUrlSvc.setParams(uri, {
            _source:       fieldList,
          });
        } else {
          esUrlSvc.setParams(uri, {
            _source: fieldList,
          });
        }
      }

      var url       = esUrlSvc.buildUrl(uri);
      var transport = transportSvc.getTransport({apiMethod: apiMethod});

      var queryDslWithPagerArgs = angular.copy(self.queryDsl);
      if (self.pagerArgs) {
        if (esUrlSvc.isTemplateCall(uri)) {
          queryDslWithPagerArgs.params.from = self.pagerArgs.from;
          queryDslWithPagerArgs.params.size = self.pagerArgs.size;
        }
        else {
          queryDslWithPagerArgs.from = self.pagerArgs.from;
          queryDslWithPagerArgs.size = self.pagerArgs.size;
        }
      }

      if (esUrlSvc.isTemplateCall(uri)) {
        delete queryDslWithPagerArgs._source;
        delete queryDslWithPagerArgs.highlight;
      } else if (self.config.highlight===false) {
        delete queryDslWithPagerArgs.highlight;
      }

      self.inError  = false;

      var getExplData = function(doc) {
        if (doc.hasOwnProperty('_explanation')) {
          return doc._explanation;
        }
        else {
          return null;
        }
      };

      var getHlData = function(doc) {
        if (doc.hasOwnProperty('highlight')) {
          return doc.highlight;
        } else {
          return null;
        }
      };

      var getQueryParsingData = function(data) {
        if (data.hasOwnProperty('profile')) {
          return data.profile;
        }
        else {
          return {};
        }
      };

      var formatError = function(msg) {
          var errorMsg = '';
          if (msg) {
            if (msg.status >= 400) {
              errorMsg = 'HTTP Error: ' + msg.status + ' ' + msg.statusText;
            }
            if (msg.status > 0) {
              if (msg.hasOwnProperty('data') && msg.data) {

                if (msg.data.hasOwnProperty('error')) {
                  errorMsg += '\n' + JSON.stringify(msg.data.error, null, 2);
                }
                if (msg.data.hasOwnProperty('_shards')) {
                  angular.forEach(msg.data._shards.failures, function(failure) {
                    errorMsg += '\n' + JSON.stringify(failure, null, 2);
                  });
                }

              }
            }
            else if (msg.status === -1 || msg.status === 0) {
              errorMsg +=  'Network Error! (host not found)\n';
              errorMsg += '\n';
              errorMsg +=  'or CORS needs to be configured for your Elasticsearch\n';
              errorMsg +=  '\n';
              errorMsg +=  'Enable CORS in elasticsearch.yml:\n';
              errorMsg += '\n';
              errorMsg += 'http.cors.allow-origin: "/https?:\\\\/\\\\/(.*?\\\\.)?(quepid\\\\.com|splainer\\\\.io)/"\n';
              errorMsg += 'http.cors.enabled: true\n';
            }
            msg.searchError = errorMsg;
          }
          return msg;
      };

      // Build URL with params if any
      // Eg. without params:  /_search
      // Eg. with params:     /_search?size=5&from=5
      //esUrlSvc.setParams(uri, self.pagerArgs);

      var headers = esUrlSvc.getHeaders(uri, self.config.customHeaders);

      activeQueries.count++;
      return transport.query(url, queryDslWithPagerArgs, headers)
        .then(function success(httpConfig) {
          var data = httpConfig.data;
          activeQueries.count--;
          if (data.hits.hasOwnProperty('total') && data.hits.total.hasOwnProperty('value')) {
            self.numFound = data.hits.total.value;
          }
          else {
            self.numFound = data.hits.total;
          }
          self.parsedQueryDetails = getQueryParsingData(data);

          var parseDoc = function(doc, groupedBy, group) {
            var explDict  = getExplData(doc);
            var hlDict    = getHlData(doc);

            var options = {
              groupedBy:          groupedBy,
              group:              group,
              fieldList:          self.fieldList,
              url:                self.url,
              explDict:           explDict,
              hlDict:             hlDict,
              version:            self.majorVersion(),
            };

            return new EsDocFactory(doc, options);
          };

          angular.forEach(data.hits.hits, function(hit) {
            var doc = parseDoc(hit);
            self.docs.push(doc);
          });

          if ( angular.isDefined(data._shards) && data._shards.failed > 0 ) {
            return $q.reject(formatError(httpConfig));
          }
        }, function error(msg) {
          activeQueries.count--;
          self.inError = true;
          return $q.reject(formatError(msg));
        })
        .catch(function(response) {
          $log.debug('Failed to execute search');
          return $q.reject(response);
        });
    } // end of search()

    function explainOther (otherQuery) {
      /*jslint validthis:true*/
      var self = this;

      var otherSearcherOptions = {
        fieldList:  self.fieldList,
        url:        self.url,
        args:       self.args,
        queryText:  otherQuery,
        config:     {
          apiMethod:    'POST',
          customHeaders: self.config.customHeaders,
          numberOfRows: self.config.numberOfRows,
          version:      self.config.version,
        },
        type:       self.type,
      };

      if ( angular.isDefined(self.pagerArgs) && self.pagerArgs !== null ) {
        otherSearcherOptions.args.pager = self.pagerArgs;
      }

      var otherSearcher = new Searcher(otherSearcherOptions);

      return otherSearcher.search()
        .then(function() {
          self.numFound = otherSearcher.numFound;

          var defer     = $q.defer();
          var promises  = [];
          var docs      = [];

          angular.forEach(otherSearcher.docs, function(doc) {
            var promise = self.explain(doc)
              .then(function(parsedDoc) {
                docs.push(parsedDoc);
              });

            promises.push(promise);
          });

          $q.all(promises)
            .then(function () {
              self.docs = docs;
              defer.resolve();
            });

          return defer.promise;
        }).catch(function(response) {
          $log.debug('Failed to run explainOther');
          return response;
        });
    } // end of explainOther()

    function explain(doc) {
      /*jslint validthis:true*/
      var self    = this;
      var uri     = esUrlSvc.parseUrl(self.url);
      var url     = esUrlSvc.buildExplainUrl(uri, doc);
      var headers = esUrlSvc.getHeaders(uri, self.config.customHeaders);

      return $http.post(url, { query: self.queryDsl.query }, {headers: headers})
        .then(function(response) {
          var explDict  = response.data.explanation || null;

          var options = {
            fieldList: self.fieldList,
            url:       self.url,
            explDict:  explDict,
          };

          return new EsDocFactory(doc, options);
        }).catch(function(response) {
          $log.debug('Failed to run explain');
          return response;
        });
    } // end of explain()

    function majorVersion() {
      var self = this;

      if ( angular.isDefined(self.config) &&
        angular.isDefined(self.config.version) &&
        self.config.version !== null &&
        self.config.version !== ''
      ) {
        return parseInt(self.config.version.split('.')[0]);
      } else {
        return null;
      }
    }

    function isTemplateCall() {
      var self = this;

      return esUrlSvc.isTemplateCall(esUrlSvc.parseUrl(self.url));
    }

    // Return factory object
    return Searcher;
  }
})();
<|endoftext|>


<commit_before>/**
 * WEBPACK CONFIG
 *
 * Notes on Config hasProperties:
 *
 * 'webpack/hot/dev-server'
 * By adding a script to your index.html file and a special entry point in your configuration
 * you will be able to get live reloads when doing changes to your files.
 *
 * devtool: 'eval-source-map'
 * http://www.cnblogs.com/Answer1215/p/4312265.html
 * The source map file will only be downloaded if you have source maps enabled and your dev tools open.
 *
 * HotModuleReplacementPlugin()
 * Hot Module Replacement (HMR) exchanges, adds or removes modules while an application is running without page reload.
 *
 * NoErrorsPlugin()
 * Hot loader is better when used with NoErrorsPlugin and hot/only-dev-server since it eliminates page reloads
 * altogether and recovers after syntax errors.
 */

/* eslint-disable no-var */
var webpack = require('webpack');
var path = require('path');

module.exports = {
  entry: [
    'webpack-dev-server/client?http://localhost:5000',
    'webpack/hot/dev-server',
    './scripts/index'
  ],
  output: {
    path: __dirname,
    filename: 'bundle.js',
    publicPath: '/scripts/'
  },
  resolve: {
    extensions: ['', '.js']
  },
  devtool: 'eval-source-map',
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['react-hot', 'babel'],
        include: path.join(__dirname, 'scripts')
      }
    ]
  }
};
<commit_msg>Added config notes<commit_after>/**
 * WEBPACK CONFIG
 *
 * Notes on config properties:
 *
 * 'entry'
 * Entry point for the bundle.
 *
 * 'output'
 * If you pass an array - the modules are loaded on startup. The last one is exported.
 *
 * 'resolve'
 * Array of file extensions used to resolve modules.
 *
 * 'webpack-dev-server'
 * Is a little node.js Express server, which uses the webpack-dev-middleware to serve a webpack bundle.
 * It also has a little runtime which is connected to the server via Socket.IO.
 *
 * 'webpack/hot/dev-server'
 * By adding a script to your index.html file and a special entry point in your configuration
 * you will be able to get live reloads when doing changes to your files.
 *
 * devtool: 'eval-source-map'
 * http://www.cnblogs.com/Answer1215/p/4312265.html
 * The source map file will only be downloaded if you have source maps enabled and your dev tools open.
 *
 * HotModuleReplacementPlugin()
 * Hot Module Replacement (HMR) exchanges, adds or removes modules while an application is running without page reload.
 *
 * NoErrorsPlugin()
 * Hot loader is better when used with NoErrorsPlugin and hot/only-dev-server since it eliminates page reloads
 * altogether and recovers after syntax errors.
 *
 * 'react-hot'
 * React Hot Loader is a plugin for Webpack that allows instantaneous live refresh without losing state
 * while editing React components.
 *
 * 'babel'
 * Babel enables the use of ES6 today by transpiling your ES6 JavaScript into equivalent ES5 source
 * that is actually delivered to the end user browser.
 */

/* eslint-disable no-var */
var webpack = require('webpack');
var path = require('path');

module.exports = {
  entry: [
    'webpack-dev-server/client?http://localhost:5000',
    'webpack/hot/dev-server',
    './scripts/index'
  ],
  output: {
    path: __dirname,
    filename: 'bundle.js',
    publicPath: '/scripts/'
  },
  resolve: {
    extensions: ['', '.js']
  },
  devtool: 'eval-source-map',
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['react-hot', 'babel'],
        include: path.join(__dirname, 'scripts')
      }
    ]
  }
};
<|endoftext|>


<commit_before>var webpack = require('webpack');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var path = require('path');

module.exports = {
    entry: {
       client: "./src/index.ts",
       // server: "./src/server/index.ts",
       // test: "./test/index.ts",
       vendor: ["three", "react", "react-dom", "socket.io-client", "redux", "lodash"]
    },
    output: {
        path: path.join(__dirname, "dist", "www"),
        filename: "[name].bundle.js"
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    module: {
        loaders: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript",
                exclude: /node_modules/
            },
            {
                test: /\.scss$/,
                loader: "style!css!sass",
                exclude: /node_modules/
            },
            {
                test: /\.pug$/,
                loader: "pug",
                exclude: /node_modules/
            }
        ],

        preLoaders: [
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                test: /\.(js|ts)$/,
                loader: "source-map-loader"
            }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    /*externals: {
        "react": "React",
        "react-dom": "ReactDOM",
        "three": "THREE"
},*/
    plugins: [
        new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js"),
        new HtmlWebpackPlugin({
            template: 'src/server/index.pug'
        }),
        new BrowserSyncPlugin({
            // browse to http://localhost:3000/ during development,
            // ./public directory is being served
            host: 'localhost',
            port: 3000,
            server: { baseDir: ['dist/www'] }
        })
    ]
};
<commit_msg>fixed vendor/client code splitting<commit_after>var webpack = require('webpack');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var path = require('path');
var pkg = require('./package.json');

module.exports = {
    entry: {
        client: "./src/index.ts",
        // server: "./src/server/index.ts",
        // test: "./test/index.ts",
        vendor: ["three", "react", "react-dom", "socket.io-client", "redux", "lodash"]
    },
    output: {
        path: path.join(__dirname, "dist", "www"),
        filename: "[name].bundle.js"
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },

    module: {
        loaders: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript",
                exclude: /node_modules/
            },
            {
                test: /\.scss$/,
                loader: "style!css!sass",
                exclude: /node_modules/
            },
            {
                test: /\.pug$/,
                loader: "pug",
                exclude: /node_modules/
            }
        ],

        preLoaders: [
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                test: /\.(js|ts)$/,
                loader: "source-map-loader"
            }
        ]
    },

    // When importing a module whose path matches one of the following, just
    // assume a corresponding global variable exists and use that instead.
    // This is important because it allows us to avoid bundling all of our
    // dependencies, which allows browsers to cache those libraries between builds.
    /*externals: {
        "react": "React",
        "react-dom": "ReactDOM",
        "three": "THREE"
},*/
    plugins: [
        new webpack.ProvidePlugin({
            THREE: "three"
        }),
        new webpack.optimize.CommonsChunkPlugin({ name: 'vendor' }),
        new webpack.optimize.UglifyJsPlugin({
            compress: { unused: true, dead_code: true, warnings: false }
        }),
        new HtmlWebpackPlugin({
            template: 'src/server/index.pug'
        }),
        new BrowserSyncPlugin({
            // browse to http://localhost:3000/ during development,
            // ./public directory is being served
            host: 'localhost',
            port: 3000,
            server: { baseDir: ['dist/www'] }
        })
    ]
};
<|endoftext|>


<commit_before>require('jquery-stupid-table/stupidtable');
const Backbone = require('backbone');
const URI = require('urijs');

const charts = require('./charts');
const clipboard = require('./clipboard');
const editor = require('./editor');
const filters = require('./filters');
const keyboardShortcuts = require('./keyboard-shortcuts');
const journal = require('./journal');
const treeTable = require('./tree-table');
const documentsUpload = require('./documents-upload');

// These parts of the page should not change.
// So they only need to be initialized once.
function initPage() {
  filters.init();
  keyboardShortcuts.init();

  $('.overlay-wrapper').click((event) => {
    event.preventDefault();
    if ($(event.target).hasClass('overlay-wrapper') || $(event.target).hasClass('close-overlay')) {
      $('.overlay-wrapper').removeClass('shown');
    }
  });

  $('#aside-button').click((event) => {
    event.preventDefault();
    $('aside').toggleClass('active');
    $('#aside-button').toggleClass('active');
  });

  $('#notifications').on('click', 'li', (event) => {
    $(event.currentTarget).remove();
  });
}

function updatePage() {
  filters.update();
  $('table.sortable').stupidtable();
  keyboardShortcuts.update();

  treeTable.initTreeTable();

  if ($('#chart-container').length) {
    charts.initCharts();
  }

  editor.initEditor();

  if ($('#journal-table').length) {
    journal.initJournal();
  }

  if ($('.status-indicator').length) {
    clipboard.initClipboard();
  }

  if ($('.tree-table').length || $('h1.droptarget').length) {
    documentsUpload.initDocumentsUpload();
  }
}

// Notifications
Backbone.on('info', (msg) => {
  $('#notifications').append(`<li>${msg}</li>`);
});

Backbone.on('error', (msg) => {
  $('#notifications').append(`<li class="error">${msg}</li>`);
});

const Router = Backbone.Router.extend({
  initialize() {
    this.isFirstRoute = true;
    this.listenTo(Backbone, 'file-modified', () => {
      $('aside').load(`/${Backbone.history.fragment} aside`);
    });
  },
  routes: {
    '*path': 'replaceArticle',
  },
  replaceArticle() {
    if (this.isFirstRoute) {
      this.isFirstRoute = false;
      return;
    }

    $.get(`/${Backbone.history.fragment}`, { partial: true }, (data) => {
      $('article').html(data);
      updatePage();
      document.title = window.documentTitle;
      $('h1 strong').html(window.pageTitle);
      $('#reload-page').addClass('hidden');
    });
  },
});

const app = new Router();

function updateURL(url) {
  const newURL = new URI(url);
  $.each(['account', 'from', 'payee', 'tag', 'time'], (_, filter) => {
    newURL.removeSearch(filter);
    if ($(`#${filter}-filter`).val()) {
      newURL.setSearch(filter, $(`#${filter}-filter`).val());
    }
  });
  const $interval = $('#chart-interval');
  if ($interval.length) {
    newURL.setSearch('interval', $interval.val());
    if ($interval.val() === $interval.data('default')) {
      newURL.removeSearch('interval');
    }
  }
  return newURL.toString();
}

function initRouter() {
  Backbone.history.start({ pushState: true });

  $(document).on('click', 'a', (event) => {
    const $link = $(event.currentTarget);
    let href = $link.attr('href');

    const isHttp = $link.prop('protocol').indexOf('http') === 0;
    const format = (href.indexOf('.') > 0) ? href.slice(href.indexOf('.') + 1) : 'html';
    const isRemote = $link.data('remote');

    if (!event.isDefaultPrevented() && !isRemote && isHttp && format === 'html') {
      event.preventDefault();
      $('.selected').removeClass('selected');
      $link.addClass('selected');

      // update sidebar links
      if (!$link.data('no-update') && $link.parents()[2].tagName === 'ASIDE') {
        href = updateURL(href);
      }
      app.navigate(href, { trigger: true });
    }
  });

  $('#reload-page').click((event) => {
    event.preventDefault();
    app.replaceArticle();
  });

  $(document).on('submit', '#filter-form', (event) => {
    event.preventDefault();
    app.navigate(updateURL(Backbone.history.location.pathname), { trigger: true });
  });

  $(document).on('submit', '#query-form', (event) => {
    event.preventDefault();
    const url = new URI(`/${Backbone.history.fragment}`)
      .setSearch('query_string', $('#query-editor').val())
      .toString();
    $.get(url, { partial: true, result_only: true }, (data) => {
      $('#query-container').html(data);
    });
  });

  $(document).on('change', '#chart-interval', (event) => {
    event.preventDefault();
    app.navigate(updateURL(Backbone.history.location.pathname), { trigger: true });
  });
}

function doPoll() {
  $.get(window.changedUrl, (data) => {
    if (data.success && data.changed) {
      $('#reload-page').removeClass('hidden');
      Backbone.trigger('file-modified');
    }
  })
    .always(() => { setTimeout(doPoll, 5000); });
}

$(document).ready(() => {
  initPage();
  updatePage();
  initRouter();
  setTimeout(doPoll, 5000);
});
<commit_msg>js: don't intercept clicks on links when modifier keys are pressed<commit_after>require('jquery-stupid-table/stupidtable');
const Backbone = require('backbone');
const URI = require('urijs');

const charts = require('./charts');
const clipboard = require('./clipboard');
const editor = require('./editor');
const filters = require('./filters');
const keyboardShortcuts = require('./keyboard-shortcuts');
const journal = require('./journal');
const treeTable = require('./tree-table');
const documentsUpload = require('./documents-upload');

// These parts of the page should not change.
// So they only need to be initialized once.
function initPage() {
  filters.init();
  keyboardShortcuts.init();

  $('.overlay-wrapper').click((event) => {
    event.preventDefault();
    if ($(event.target).hasClass('overlay-wrapper') || $(event.target).hasClass('close-overlay')) {
      $('.overlay-wrapper').removeClass('shown');
    }
  });

  $('#aside-button').click((event) => {
    event.preventDefault();
    $('aside').toggleClass('active');
    $('#aside-button').toggleClass('active');
  });

  $('#notifications').on('click', 'li', (event) => {
    $(event.currentTarget).remove();
  });
}

function updatePage() {
  filters.update();
  $('table.sortable').stupidtable();
  keyboardShortcuts.update();

  treeTable.initTreeTable();

  if ($('#chart-container').length) {
    charts.initCharts();
  }

  editor.initEditor();

  if ($('#journal-table').length) {
    journal.initJournal();
  }

  if ($('.status-indicator').length) {
    clipboard.initClipboard();
  }

  if ($('.tree-table').length || $('h1.droptarget').length) {
    documentsUpload.initDocumentsUpload();
  }
}

// Notifications
Backbone.on('info', (msg) => {
  $('#notifications').append(`<li>${msg}</li>`);
});

Backbone.on('error', (msg) => {
  $('#notifications').append(`<li class="error">${msg}</li>`);
});

const Router = Backbone.Router.extend({
  initialize() {
    this.isFirstRoute = true;
    this.listenTo(Backbone, 'file-modified', () => {
      $('aside').load(`/${Backbone.history.fragment} aside`);
    });
  },
  routes: {
    '*path': 'replaceArticle',
  },
  replaceArticle() {
    if (this.isFirstRoute) {
      this.isFirstRoute = false;
      return;
    }

    $.get(`/${Backbone.history.fragment}`, { partial: true }, (data) => {
      $('article').html(data);
      updatePage();
      document.title = window.documentTitle;
      $('h1 strong').html(window.pageTitle);
      $('#reload-page').addClass('hidden');
    });
  },
});

const app = new Router();

function updateURL(url) {
  const newURL = new URI(url);
  $.each(['account', 'from', 'payee', 'tag', 'time'], (_, filter) => {
    newURL.removeSearch(filter);
    if ($(`#${filter}-filter`).val()) {
      newURL.setSearch(filter, $(`#${filter}-filter`).val());
    }
  });
  const $interval = $('#chart-interval');
  if ($interval.length) {
    newURL.setSearch('interval', $interval.val());
    if ($interval.val() === $interval.data('default')) {
      newURL.removeSearch('interval');
    }
  }
  return newURL.toString();
}

function initRouter() {
  Backbone.history.start({ pushState: true });

  $(document).on('click', 'a', (event) => {
    if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
      return;
    }
    const $link = $(event.currentTarget);
    let href = $link.attr('href');

    const isHttp = $link.prop('protocol').indexOf('http') === 0;
    const format = (href.indexOf('.') > 0) ? href.slice(href.indexOf('.') + 1) : 'html';
    const isRemote = $link.data('remote');

    if (!event.isDefaultPrevented() && !isRemote && isHttp && format === 'html') {
      event.preventDefault();
      $('.selected').removeClass('selected');
      $link.addClass('selected');

      // update sidebar links
      if (!$link.data('no-update') && $link.parents()[2].tagName === 'ASIDE') {
        href = updateURL(href);
      }
      app.navigate(href, { trigger: true });
    }
  });

  $('#reload-page').click((event) => {
    event.preventDefault();
    app.replaceArticle();
  });

  $(document).on('submit', '#filter-form', (event) => {
    event.preventDefault();
    app.navigate(updateURL(Backbone.history.location.pathname), { trigger: true });
  });

  $(document).on('submit', '#query-form', (event) => {
    event.preventDefault();
    const url = new URI(`/${Backbone.history.fragment}`)
      .setSearch('query_string', $('#query-editor').val())
      .toString();
    $.get(url, { partial: true, result_only: true }, (data) => {
      $('#query-container').html(data);
    });
  });

  $(document).on('change', '#chart-interval', (event) => {
    event.preventDefault();
    app.navigate(updateURL(Backbone.history.location.pathname), { trigger: true });
  });
}

function doPoll() {
  $.get(window.changedUrl, (data) => {
    if (data.success && data.changed) {
      $('#reload-page').removeClass('hidden');
      Backbone.trigger('file-modified');
    }
  })
    .always(() => { setTimeout(doPoll, 5000); });
}

$(document).ready(() => {
  initPage();
  updatePage();
  initRouter();
  setTimeout(doPoll, 5000);
});
<|endoftext|>


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

module.exports = {

    entry: {
        index: './src/index.ts'
    },

    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        library: 'InversifyReact',
        libraryTarget: 'umd'
    },

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

    devtool: 'source-map',

    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                use: 'ts-loader'
            }
        ]
    },

    externals: {
        "react": {
            commonjs: "react",
            commonjs2: "react",
            amd: "react",
            root: "React"
        },
        "inversify": {
            commonjs: "inversify",
            commonjs2: "inversify",
            amd: "inversify",
            root: "Inversify"
        },
        "prop-types": {
            commonjs: "prop-types",
            commonjs2: "prop-types",
            amd: "prop-types",
            root: "PropTypes"
        }
    }
};<commit_msg>allow usage in ssr (fixes #8)<commit_after>const path = require('path');
const webpack = require('webpack');

module.exports = {

    entry: {
        index: './src/index.ts'
    },

    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        library: 'InversifyReact',
        libraryTarget: 'umd',
        globalObject: `(typeof self !== 'undefined' ? self : this)`
    },

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

    devtool: 'source-map',

    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                use: 'ts-loader'
            }
        ]
    },

    externals: {
        "react": {
            commonjs: "react",
            commonjs2: "react",
            amd: "react",
            root: "React"
        },
        "inversify": {
            commonjs: "inversify",
            commonjs2: "inversify",
            amd: "inversify",
            root: "Inversify"
        },
        "prop-types": {
            commonjs: "prop-types",
            commonjs2: "prop-types",
            amd: "prop-types",
            root: "PropTypes"
        }
    }
};<|endoftext|>


<commit_before>const BASE_PATH = __dirname;

const path = require('path');

// Webpack Plugins
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
// PostCSS plugins
const PostcssNext = require('postcss-cssnext');
const PostcssMediaMinMax = require('postcss-media-minmax');
const PostcssImport = require('postcss-import');
const PostcssCssVariables = require('postcss-css-variables');
const WebpackPostcssTools = require('webpack-postcss-tools');

// Markdown
const marked = require('marked');

// Constants
const IS_DEV = process.env.NODE_ENV !== 'production';
const PUBLIC_PATH = '/minutes/';
const HTML_INDEX_FILENAME = 'index.html';
const colorsMap = WebpackPostcssTools.makeVarMap('./src/styles/vendor/colors.css');
const definitionMap = WebpackPostcssTools.makeVarMap('./src/styles/variables.css');

const renderer = new marked.Renderer();
renderer.blockquote = text => `<blockquote>${text.replace(/<\/?p>/, '')}</blockquote>`;

const postcssOptions = {
  plugins: () => [
    PostcssCssVariables({
      variables: Object.assign(colorsMap.vars, definitionMap.vars)
    }),
    PostcssImport(),
    PostcssMediaMinMax(),
    PostcssNext({
      browsers: ['last 2 versions', '> 5%'],
    }),
  ],
};

const htmlWebpackConfig = [HTML_INDEX_FILENAME, '404.html'].map(filename => (
  new HtmlWebpackPlugin({
    template: './src/public/template.html',
    filename,
    manifestFile: `${PUBLIC_PATH}manifest.json`,
    // minify: !IS_DEV,
    title: 'Remaining Minutes of the Day',
    hash: false,
    inject: 'body',
  })
));

const webpackConfig = {
  name: 'minutes',
  target: 'web',
  entry: {
    app: './src/index.js',
    markdown: [
      './src/markdown/about.en.md',
      './src/markdown/about.es.md',
      './src/markdown/what-is-this.en.md',
      './src/markdown/what-is-this.es.md',
    ],
    vendor: [
      'react',
      'react-intl',
      'react-router',
      'react-router-dom',
    ]
  },
  output: {
    path: path.join(BASE_PATH, 'docs'),
    publicPath: PUBLIC_PATH,
    filename: '[name].[hash].js',
    chunkFilename: 'minutes-[name]-[chunkhash].js',
    sourceMapFilename: '[name].map.js',
  },
  resolve: {
    modules: [
      'node_modules',
    ],
    extensions: ['.js', '.jsx', '.json', '.css', '.md'],
  },
  module: {
    rules: [
      {
        test: /\.jsx?/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  'es2015', {
                    loose: true,
                    modules: false,
                  },
                ],
              ],
              plugins: [
                [
                  'transform-react-jsx',
                  'transform-object-rest-spread',
                ],
              ],
            },
          },
        ],
        include: path.join(BASE_PATH, 'src'),
      },
      {
        test: /\.css/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[local]',
            },
          },
          {
            loader: 'postcss-loader',
            options: postcssOptions,
          },
        ],
      },
      {
        test: /\.md$/,
        use: [
          {
            loader: 'html-loader'
          },
          {
            loader: 'markdown-loader',
            options: {
              renderer,
            }
          }
        ]
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              mimetype: 'image/svg+xml'
            }
          }
        ]
      },
      {
        test: /\.json$/,
        use: 'json-loader'
      },
    ],
  },
  devtool: IS_DEV ? 'cheap-module-eval-source-map' : 'source-map',
  plugins: [
    new webpack.NamedModulesPlugin(),
    ...htmlWebpackConfig,
    new FaviconsWebpackPlugin({
      logo: './src/public/minutes-circle.png',
      emitStats: false,
      inject: true,
      prefix: 'icons/',
      title: 'Minutes',
      icons: {
        android: true,
        appleIcon: true,
        appleStartup: true,
        coast: false,
        favicons: true,
        firefox: true,
        opengraph: false,
        twitter: false,
        yandex: false,
        windows: false
      }
    }),
  ],
};

if (IS_DEV) {
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin() /* eslint comma-dangle: 0 */
  );
  webpackConfig.devServer = {
    contentBase: './src',
    historyApiFallback: {
      index: `${PUBLIC_PATH}${HTML_INDEX_FILENAME}`,
    },
    host: 'localhost',
    hot: true,
    inline: true,
    port: process.env.PORT || 8000,
    publicPath: PUBLIC_PATH,
    stats: {
      cached: true,
      cachedAssets: true,
      chunks: true,
      chunkModules: false,
      colors: true,
      hash: false,
      reasons: true,
      timings: true,
      version: false,
    },
  };
} else {
  webpackConfig.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({
      names: ['markdown', 'vendor'],
      minChunks(module) {
        // this assumes your vendor imports exist in the node_modules directory
        return module.context && module.context.indexOf('node_modules') !== -1/* || module.context.indexOf('src/markdown') !== -1)*/;
      },
    }),
    new CleanWebpackPlugin(path.join(BASE_PATH, 'docs')),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new CopyWebpackPlugin([
      { from: './src/public/manifest.json' },
    ]),
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.UglifyJsPlugin({
      beautify: false,
      compress: {
        screw_ie8: true,
        warnings: false,
      },
      output: {
        comments: false,
        screw_ie8: true,
      },
      mangle: {
        screw_ie8: true,
      },
      sourceMap: false,
    })
  );

  webpackConfig.module.rules.forEach((rule) => {
    if (rule.test.test('.css')) {
      rule.use = ExtractTextPlugin.extract({ /* eslint no-param-reassign: 0 */
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[hash:base64:8]',
            },
          },
          {
            loader: 'postcss-loader',
            options: postcssOptions,
          },
        ],
      });
    }
  });
}

module.exports = webpackConfig;
<commit_msg>Changed devtool to cheap-module-eval-source-map<commit_after>const BASE_PATH = __dirname;

const path = require('path');

// Webpack Plugins
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
// PostCSS plugins
const PostcssNext = require('postcss-cssnext');
const PostcssMediaMinMax = require('postcss-media-minmax');
const PostcssImport = require('postcss-import');
const PostcssCssVariables = require('postcss-css-variables');
const WebpackPostcssTools = require('webpack-postcss-tools');

// Markdown
const marked = require('marked');

// Constants
const IS_DEV = process.env.NODE_ENV !== 'production';
const PUBLIC_PATH = '/minutes/';
const HTML_INDEX_FILENAME = 'index.html';
const colorsMap = WebpackPostcssTools.makeVarMap('./src/styles/vendor/colors.css');
const definitionMap = WebpackPostcssTools.makeVarMap('./src/styles/variables.css');

const renderer = new marked.Renderer();
renderer.blockquote = text => `<blockquote>${text.replace(/<\/?p>/, '')}</blockquote>`;

const postcssOptions = {
  plugins: () => [
    PostcssCssVariables({
      variables: Object.assign(colorsMap.vars, definitionMap.vars)
    }),
    PostcssImport(),
    PostcssMediaMinMax(),
    PostcssNext({
      browsers: ['last 2 versions', '> 5%'],
    }),
  ],
};

const htmlWebpackConfig = [HTML_INDEX_FILENAME, '404.html'].map(filename => (
  new HtmlWebpackPlugin({
    template: './src/public/template.html',
    filename,
    manifestFile: `${PUBLIC_PATH}manifest.json`,
    // minify: !IS_DEV,
    title: 'Remaining Minutes of the Day',
    hash: false,
    inject: 'body',
  })
));

const webpackConfig = {
  name: 'minutes',
  target: 'web',
  entry: {
    app: './src/index.js',
    markdown: [
      './src/markdown/about.en.md',
      './src/markdown/about.es.md',
      './src/markdown/what-is-this.en.md',
      './src/markdown/what-is-this.es.md',
    ],
    vendor: [
      'react',
      'react-intl',
      'react-router',
      'react-router-dom',
    ]
  },
  output: {
    path: path.join(BASE_PATH, 'docs'),
    publicPath: PUBLIC_PATH,
    filename: '[name].[hash].js',
    chunkFilename: 'minutes-[name]-[chunkhash].js',
    sourceMapFilename: '[name].map.js',
  },
  resolve: {
    modules: [
      'node_modules',
    ],
    extensions: ['.js', '.jsx', '.json', '.css', '.md'],
  },
  module: {
    rules: [
      {
        test: /\.jsx?/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  'es2015', {
                    loose: true,
                    modules: false,
                  },
                ],
              ],
              plugins: [
                [
                  'transform-react-jsx',
                  'transform-object-rest-spread',
                ],
              ],
            },
          },
        ],
        include: path.join(BASE_PATH, 'src'),
      },
      {
        test: /\.css/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              localIdentName: '[local]',
            },
          },
          {
            loader: 'postcss-loader',
            options: postcssOptions,
          },
        ],
      },
      {
        test: /\.md$/,
        use: [
          {
            loader: 'html-loader'
          },
          {
            loader: 'markdown-loader',
            options: {
              renderer,
            }
          }
        ]
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              mimetype: 'image/svg+xml'
            }
          }
        ]
      },
      {
        test: /\.json$/,
        use: 'json-loader'
      },
    ],
  },
  devtool: IS_DEV ? 'cheap-module-inline-source-map' : 'source-map',
  plugins: [
    new webpack.NamedModulesPlugin(),
    ...htmlWebpackConfig,
    new FaviconsWebpackPlugin({
      logo: './src/public/minutes-circle.png',
      emitStats: false,
      inject: true,
      prefix: 'icons/',
      title: 'Minutes',
      icons: {
        android: true,
        appleIcon: true,
        appleStartup: true,
        coast: false,
        favicons: true,
        firefox: true,
        opengraph: false,
        twitter: false,
        yandex: false,
        windows: false
      }
    }),
  ],
};

if (IS_DEV) {
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin() /* eslint comma-dangle: 0 */
  );
  webpackConfig.devServer = {
    contentBase: './src',
    historyApiFallback: {
      index: `${PUBLIC_PATH}${HTML_INDEX_FILENAME}`,
    },
    host: 'localhost',
    hot: true,
    inline: true,
    port: process.env.PORT || 8000,
    publicPath: PUBLIC_PATH,
    stats: {
      cached: true,
      cachedAssets: true,
      chunks: true,
      chunkModules: false,
      colors: true,
      hash: false,
      reasons: true,
      timings: true,
      version: false,
    },
  };
} else {
  webpackConfig.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({
      names: ['markdown', 'vendor'],
      minChunks(module) {
        // this assumes your vendor imports exist in the node_modules directory
        return module.context && module.context.indexOf('node_modules') !== -1/* || module.context.indexOf('src/markdown') !== -1)*/;
      },
    }),
    new CleanWebpackPlugin(path.join(BASE_PATH, 'docs')),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false,
    }),
    new CopyWebpackPlugin([
      { from: './src/public/manifest.json' },
    ]),
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.UglifyJsPlugin({
      beautify: false,
      compress: {
        screw_ie8: true,
        warnings: false,
      },
      output: {
        comments: false,
        screw_ie8: true,
      },
      mangle: {
        screw_ie8: true,
      },
      sourceMap: false,
    })
  );

  webpackConfig.module.rules.forEach((rule) => {
    if (rule.test.test('.css')) {
      rule.use = ExtractTextPlugin.extract({ /* eslint no-param-reassign: 0 */
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[hash:base64:8]',
            },
          },
          {
            loader: 'postcss-loader',
            options: postcssOptions,
          },
        ],
      });
    }
  });
}

module.exports = webpackConfig;
<|endoftext|>


<commit_before>/**
 * Dependencies declared
 * @type {Object}
 */
const path = require('path'),
  ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: ['./server/Server.js', './client/src/assets/css/Index.scss'],
  output: { path: __dirname, filename: './client/public/build/Bundle.js' },
  watch: true,
  devServer: {
    contentBase: 'client/public/'
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        exclude: /node_modules/,
        use: [
          { loader: 'babel-loader' },
          { loader: 'eslint-loader' }
        ]
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: [
          { loader: 'style-loader!css-loader' }
        ]
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
          { loader: 'sass-loader' }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.css']
  }
};
<commit_msg>chore(webpack):redirect-webpack-to-entry-files<commit_after>/**
 * Dependencies declared
 * @type {Object}
 */
const path = require('path'),
  ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: ['./server/Server.js', './client/src/css/Index.scss'],
  output: { path: __dirname, filename: './client/public/build/Bundle.js' },
  watch: true,
  devServer: {
    contentBase: 'client/public/'
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        exclude: /node_modules/,
        use: [
          { loader: 'babel-loader' },
          { loader: 'eslint-loader' }
        ]
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: [
          { loader: 'style-loader!css-loader' }
        ]
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
          { loader: 'sass-loader' }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.css']
  }
};
<|endoftext|>


<commit_before>/*mish mash between different webpack examples
react hot boilerplate
https://github.com/shanewilson/react-webpack-example/blob/master/webpack.config.js
*/
var fs      = require('fs');
var path    = require('path');
var webpack = require('webpack');
var CompressionPlugin = require("compression-webpack-plugin");

var host    = "localhost";
var port    = 3000;
var srcPath = "src"
var xtraModulesWLoaders = ["js-csp/src","glView-helpers"]//add any module names that you want loaders to apply to

var production = process.env.NODE_ENV == 'production';
var dev        = process.env.NODE_ENV == 'dev';

var getSymlinkedModules = function(){

  var rootPath = path.join(__dirname, "node_modules");
  var contents = fs.readdirSync(rootPath);
  var results = contents
  .map(function(entry){
    var fPath  = path.join(rootPath,entry);
    return fPath;
  })
  .filter(function(fPath){
    function check( entry ){
      var stats=fs.lstatSync(fPath);
      return stats.isSymbolicLink();
    }
    return check(fPath);
  })
  .map(function(fPath){
      return fs.realpathSync( fPath );
  });
  return results;
}

//add any extra folders we want to apply loaders to
var extraModulePaths = xtraModulesWLoaders.map(function(entry){ return path.join(__dirname, "node_modules",entry); });
var pathsToInclude = getSymlinkedModules().concat( path.join(__dirname, srcPath) ).concat( extraModulePaths );

//FIXME !! temporary hack: add any paths where loaders should be apllied
pathsToInclude.push( path.join(__dirname, "node_modules", "glView-helpers") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-kernel2") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-asset-manager") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-xhr-store") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-desktop-store") )

//ugh, also needed because of workers (ie worker loader)
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-stl-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ctm-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ply-parser")   )

//console.log("will user loaders on",pathsToInclude)

var config= {
  host:host,
  port:port,
  devtool: 'eval',
  entry: [
    './'+srcPath+'/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/' //'/'+'dist'+'/'
  },
  plugins: [
    //new webpack.NoErrorsPlugin(),
    //new webpack.optimize.DedupePlugin()
  ],
  module: {
    loaders: [
      { test: /\.json$/,   loader: "json-loader" },
      { test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      { test: /\.js?$/, loaders: ['react-hot', 'babel?experimental&optional=runtime'],include : pathsToInclude},
      { test: /\.css$/, loader: "style-loader!css-loader" }
    ],
    noParse: /\.min\.js/
  },
  resolve: {
    extensions: ['', '.js', '.jsx','json'],
    root: [
      path.join(__dirname, "node_modules"),
    ],
    /*alias: {
        "q$":path.join(__dirname, "node_modules","usco-kernel2/src/kernel.js"),//needed only FOR DEV
    }*/
    alias: {
      "three$":path.join(__dirname, "node_modules","three/three.min.js")
    }
  },
  resolveLoader:{
    root : path.join(__dirname, "node_modules")
  }
};

//console.log("production",production,"dev",dev)

if (production) {
  config.bail = true
  config.debug = false
  config.profile = false
  config.output.pathInfo = false
  config.output.publicPath = './dist/'//withouth this, issues with webworker paths

  //config.devtool = "#source-map";
  //config.output.filename = "[name].min.js"//"[name].[hash].min.js"
  //config.output.chunkFilename = '[id].js'
  config.plugins = config.plugins.concat([
    new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production') } }),
    new webpack.optimize.DedupePlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({minimize: true})
    /*
    new webpack.optimize.UglifyJsPlugin({
      mangle: {
        except: ['require', 'export', '$super', 'import']
      },
      compress: {
        warnings: false,
        sequences: true,
        dead_code: true,
        conditionals: true,
        booleans: true,
        unused: true,
        if_return: true,
        join_vars: true,
        drop_console: true
      }
    })*/
    /*,
    new CompressionPlugin({
      asset: "{file}.gz",
      algorithm: "gzip",
      regExp: /\.js$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    })*/
  ]);
}
else{
  config.entry = config.entry.concat([
    'webpack-dev-server/client?',//http://'+host+":"+port,
    'webpack/hot/only-dev-server',
  ])
  config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
  ])
}

module.exports = config;
<commit_msg>- updated webpack config to match updated babeljs params<commit_after>/*mish mash between different webpack examples
react hot boilerplate
https://github.com/shanewilson/react-webpack-example/blob/master/webpack.config.js
*/
var fs      = require('fs');
var path    = require('path');
var webpack = require('webpack');
var CompressionPlugin = require("compression-webpack-plugin");

var host    = "localhost";
var port    = 3000;
var srcPath = "src"
var xtraModulesWLoaders = ["js-csp/src","glView-helpers"]//add any module names that you want loaders to apply to

var production = process.env.NODE_ENV == 'production';
var dev        = process.env.NODE_ENV == 'dev';

var getSymlinkedModules = function(){

  var rootPath = path.join(__dirname, "node_modules");
  var contents = fs.readdirSync(rootPath);
  var results = contents
  .map(function(entry){
    var fPath  = path.join(rootPath,entry);
    return fPath;
  })
  .filter(function(fPath){
    function check( entry ){
      var stats=fs.lstatSync(fPath);
      return stats.isSymbolicLink();
    }
    return check(fPath);
  })
  .map(function(fPath){
      return fs.realpathSync( fPath );
  });
  return results;
}

//add any extra folders we want to apply loaders to
var extraModulePaths = xtraModulesWLoaders.map(function(entry){ return path.join(__dirname, "node_modules",entry); });
var pathsToInclude = getSymlinkedModules().concat( path.join(__dirname, srcPath) ).concat( extraModulePaths );

//FIXME !! temporary hack: add any paths where loaders should be apllied
pathsToInclude.push( path.join(__dirname, "node_modules", "glView-helpers") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-kernel2") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-asset-manager") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-xhr-store") )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-desktop-store") )

//ugh, also needed because of workers (ie worker loader)
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-stl-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ctm-parser")   )
pathsToInclude.push( path.join(__dirname, "node_modules", "usco-ply-parser")   )

//console.log("will user loaders on",pathsToInclude)

var config= {
  host:host,
  port:port,
  devtool: 'eval',
  entry: [
    './'+srcPath+'/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/' //'/'+'dist'+'/'
  },
  plugins: [
    //new webpack.NoErrorsPlugin(),
    //new webpack.optimize.DedupePlugin()
  ],
  module: {
    loaders: [
      { test: /\.json$/,   loader: "json-loader" },
      { test: /-worker*\.js$/, loader: "worker-loader",include : pathsToInclude},//if any module does "require(XXX-worker)" it converts to a web worker
      { test: /\.js?$/, loaders: ['react-hot', 'babel?optional[]=runtime&optional=es6.blockScoping'],include : pathsToInclude},
      { test: /\.css$/, loader: "style-loader!css-loader" }
    ],
    noParse: /\.min\.js/
  },
  resolve: {
    extensions: ['', '.js', '.jsx','json'],
    root: [
      path.join(__dirname, "node_modules"),
    ],
    /*alias: {
        "q$":path.join(__dirname, "node_modules","usco-kernel2/src/kernel.js"),//needed only FOR DEV
    }*/
    alias: {
      "three$":path.join(__dirname, "node_modules","three/three.min.js")
    }
  },
  resolveLoader:{
    root : path.join(__dirname, "node_modules")
  }
};

//console.log("production",production,"dev",dev)

if (production) {
  config.bail = true
  config.debug = false
  config.profile = false
  config.output.pathInfo = false
  config.output.publicPath = './dist/'//withouth this, issues with webworker paths

  //config.devtool = "#source-map";
  //config.output.filename = "[name].min.js"//"[name].[hash].min.js"
  //config.output.chunkFilename = '[id].js'
  config.plugins = config.plugins.concat([
    new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production') } }),
    new webpack.optimize.DedupePlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.optimize.UglifyJsPlugin({minimize: true})
    /*
    new webpack.optimize.UglifyJsPlugin({
      mangle: {
        except: ['require', 'export', '$super', 'import']
      },
      compress: {
        warnings: false,
        sequences: true,
        dead_code: true,
        conditionals: true,
        booleans: true,
        unused: true,
        if_return: true,
        join_vars: true,
        drop_console: true
      }
    })*/
    /*,
    new CompressionPlugin({
      asset: "{file}.gz",
      algorithm: "gzip",
      regExp: /\.js$|\.html$/,
      threshold: 10240,
      minRatio: 0.8
    })*/
  ]);
}
else{
  config.entry = config.entry.concat([
    'webpack-dev-server/client?',//http://'+host+":"+port,
    'webpack/hot/only-dev-server',
  ])
  config.plugins = config.plugins.concat([
    new webpack.HotModuleReplacementPlugin(),
  ])
}

module.exports = config;
<|endoftext|>


<commit_before>var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')

const DEBUG = !(process.env.NODE_ENV === 'production')
const VERBOSE = process.argv.includes('--verbose')
const WATCH =  process.argv.includes('--watch')
const HOT_DEPLOY = !!process.env.HOT_DEPLOY
let CONTEXT_PATH = `${(process.env.CONTEXT_PATH || '')}`

module.exports = {
  context: __dirname + '/src/main/client',
  entry: {
    'js/bundle': [...(HOT_DEPLOY ? ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true'] : []), './index.js']
  },
  output: {
    path: __dirname + (WATCH ? '/build/resources/main' : '/src/main/resources') + '/static',
    filename: '[name].js',
    publicPath: `${CONTEXT_PATH}/`
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devtool: DEBUG ? 'cheap-module-eval-source-map' : false,
  plugins: [
    new webpack.DefinePlugin({
      'process.env.CONTEXT_PATH': `"${CONTEXT_PATH}"`,
      'process.env.NODE_ENV': `"${process.env.NODE_ENV || (DEBUG ? 'development' : 'production')}"`
    }),
    ...(HOT_DEPLOY ? [new webpack.HotModuleReplacementPlugin()] : []),
    ...(DEBUG ? [] : [new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.AggressiveMergingPlugin(),
      new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, warnings: VERBOSE } })
    ]),
    new HtmlWebpackPlugin({
      title: 'himawari',
      template: 'index.ejs'
    }),
    new CopyWebpackPlugin([
      { from: 'assets'}
    ])
  ],
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: ['babel']
      },
      {
        test: /\.css?$/,
        loaders: [ 'style', 'raw' ],
        include: __dirname
      },
      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]'
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.yaml$/,
        loader: 'yaml'
      }
    ]
  }
}
<commit_msg>'cheap-module-eval-source-map' とデバッグしづらかったので変更<commit_after>var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')

const DEBUG = !(process.env.NODE_ENV === 'production')
const VERBOSE = process.argv.includes('--verbose')
const WATCH =  process.argv.includes('--watch')
const HOT_DEPLOY = !!process.env.HOT_DEPLOY
let CONTEXT_PATH = `${(process.env.CONTEXT_PATH || '')}`

module.exports = {
  context: __dirname + '/src/main/client',
  entry: {
    'js/bundle': [...(HOT_DEPLOY ? ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true'] : []), './index.js']
  },
  output: {
    path: __dirname + (WATCH ? '/build/resources/main' : '/src/main/resources') + '/static',
    filename: '[name].js',
    publicPath: `${CONTEXT_PATH}/`
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devtool: DEBUG ? 'source-map' : false,
  plugins: [
    new webpack.DefinePlugin({
      'process.env.CONTEXT_PATH': `"${CONTEXT_PATH}"`,
      'process.env.NODE_ENV': `"${process.env.NODE_ENV || (DEBUG ? 'development' : 'production')}"`
    }),
    ...(HOT_DEPLOY ? [new webpack.HotModuleReplacementPlugin()] : []),
    ...(DEBUG ? [] : [new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.AggressiveMergingPlugin(),
      new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, warnings: VERBOSE } })
    ]),
    new HtmlWebpackPlugin({
      title: 'himawari',
      template: 'index.ejs'
    }),
    new CopyWebpackPlugin([
      { from: 'assets'}
    ])
  ],
  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: ['babel']
      },
      {
        test: /\.css?$/,
        loaders: [ 'style', 'raw' ],
        include: __dirname
      },
      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]'
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.yaml$/,
        loader: 'yaml'
      }
    ]
  }
}
<|endoftext|>