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

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['', '.ts', '.js'],
    modulesDirectories: ['web_modules', 'node_modules'],
    alias: {
      AlloyImage: 'AlloyImage/combined/alloyimage.js'
    }
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        exclude: path.resolve('node_modules'),
        loaders: ['awesome-typescript-loader', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src'),
        loader: 'raw'
      },
      {
        test: /jquery\.js/,
        loader: 'null',
        exclude: path.resolve('node_modules')
      }
    ]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    }),
    new webpack.ProvidePlugin({
      '$': 'jquery',
      'jQuery': 'jquery',
      'window.jquery': 'jquery'
    })
  ]
};<commit_msg>编译bug<commit_after>const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const helpers = require('./helpers');

module.exports = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['', '.ts', '.js'],
    modulesDirectories: ['web_modules', 'node_modules'],
    alias: {
      AlloyImage: 'AlloyImage/combined/alloyimage.js'
    }
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=assets/[name].[hash].[ext]'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src'),
        loader: 'raw'
      },
      {
        test: /jquery\.js/,
        loader: 'null',
        exclude: path.resolve('node_modules')
      }
    ]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'src/index.html'
    }),
    new webpack.ProvidePlugin({
      '$': 'jquery',
      'jQuery': 'jquery',
      'window.jquery': 'jquery'
    })
  ]
};<|endoftext|>


<commit_before>require('@babel/polyfill');
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

const CopyPlugin = require('copy-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
  .BundleAnalyzerPlugin;
const ManifestPlugin = require('webpack-manifest-plugin');
const WebpackBar = require('webpackbar');

const headerFooterData = require('../src/platform/landing-pages/header-footer-data.json');
const BUCKETS = require('../src/site/constants/buckets');
const ENVIRONMENTS = require('../src/site/constants/environments');

const {
  getAppManifests,
  getWebpackEntryPoints,
} = require('./manifest-helpers');

// TODO: refactor the other approach for creating files without the hash so that we're only doing that in the webpack config: https://github.com/department-of-veterans-affairs/vets-website/blob/a012bad17e5bf024b0ea7326a72ae6a737e349ec/src/site/stages/build/plugins/process-entry-names.js#L35
const vaMedalliaStylesFilename = 'va-medallia-styles';

const generateWebpackDevConfig = require('./webpack.dev.config.js');

const timestamp = new Date().getTime();

const getAbsolutePath = relativePath =>
  path.join(__dirname, '../', relativePath);

const sharedModules = [
  getAbsolutePath('src/platform/polyfills'),
  'react',
  'react-dom',
  'react-redux',
  'redux',
  'redux-thunk',
  '@sentry/browser',
];

const globalEntryFiles = {
  polyfills: getAbsolutePath('src/platform/polyfills/preESModulesPolyfills.js'),
  style: getAbsolutePath('src/platform/site-wide/sass/style.scss'),
  [vaMedalliaStylesFilename]: getAbsolutePath(
    'src/platform/site-wide/sass/va-medallia-style.scss',
  ),
  styleConsolidated: getAbsolutePath(
    'src/applications/proxy-rewrite/sass/style-consolidated.scss',
  ),
  vendor: sharedModules,
  // This is to solve the issue of the vendor file being cached
  'shared-modules': sharedModules,
};

/**
 * Get a list of all the entry points.
 *
 * @param {String} entry - List of comma-delimited entries to build. Builds all
 *                         entries if no value is passed.
 * @return {Object} - The entry file paths mapped to the entry names
 */
function getEntryPoints(entry) {
  const manifests = getAppManifests();
  let manifestsToBuild = manifests;
  if (entry) {
    const entryNames = entry.split(',').map(name => name.trim());
    manifestsToBuild = manifests.filter(manifest =>
      entryNames.includes(manifest.entryName),
    );
  }

  return getWebpackEntryPoints(manifestsToBuild);
}

module.exports = env => {
  const buildOptions = {
    api: '',
    buildtype: 'localhost',
    host: 'localhost',
    port: 3001,
    scaffold: false,
    watch: false,
    ...env,
    // Using a getter so we can reference the buildtype
    get destination() {
      return path.resolve(__dirname, '../', 'build', this.buildtype);
    },
  };

  const apps = getEntryPoints(buildOptions.entry);
  const entryFiles = Object.assign({}, apps, globalEntryFiles);
  const isOptimizedBuild = [
    ENVIRONMENTS.VAGOVSTAGING,
    ENVIRONMENTS.VAGOVPROD,
  ].includes(buildOptions.buildtype);

  // enable css sourcemaps for all non-localhost builds
  // or if build options include local-css-sourcemaps or entry
  const enableCSSSourcemaps =
    buildOptions.buildtype !== ENVIRONMENTS.LOCALHOST ||
    buildOptions['local-css-sourcemaps'] ||
    !!buildOptions.entry;

  const outputPath = `${buildOptions.destination}/generated`;

  const baseConfig = {
    mode: 'development',
    entry: entryFiles,
    output: {
      path: outputPath,
      publicPath: '/generated/',
      filename: !isOptimizedBuild
        ? '[name].entry.js'
        : `[name].entry.[chunkhash]-${timestamp}.js`,
      chunkFilename: !isOptimizedBuild
        ? '[name].entry.js'
        : `[name].entry.[chunkhash]-${timestamp}.js`,
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              // Speed up compilation.
              cacheDirectory: '.babelcache',
              // Also see .babelrc
            },
          },
        },
        {
          test: /\.(sa|sc|c)ss$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
            },
            {
              loader: 'css-loader',
              options: {
                sourceMap: enableCSSSourcemaps,
              },
            },
            {
              loader: 'postcss-loader',
              options: {
                // use cssnano to minimize css only on optimized builds
                plugins: isOptimizedBuild
                  ? () => [require('autoprefixer'), require('cssnano')]
                  : () => [require('autoprefixer')],
              },
            },
            {
              loader: 'sass-loader',
              options: { sourceMap: true },
            },
          ],
        },
        {
          // if we want to minify these images, we could add img-loader
          // but it currently only would apply to three images from uswds
          test: /\.(jpe?g|png|gif)$/i,
          use: {
            loader: 'url-loader',
            options: {
              limit: 10000,
            },
          },
        },
        {
          test: /\.svg/,
          use: {
            loader: 'svg-url-loader?limit=1024',
          },
        },
        {
          test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: {
            loader: 'url-loader',
            options: {
              limit: 7000,
              mimetype: 'application/font-woff',
              name: '[name].[ext]',
            },
          },
        },
        {
          test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
            },
          },
        },
        {
          test: /react-jsonschema-form\/lib\/components\/(widgets|fields\/ObjectField|fields\/ArrayField)/,
          exclude: [/widgets\/index\.js/, /widgets\/TextareaWidget/],
          use: {
            loader: 'null-loader',
          },
        },
      ],
      noParse: [/mapbox\/vendor\/promise.js$/],
    },
    resolve: {
      extensions: ['.js', '.jsx'],
    },
    optimization: {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            output: {
              beautify: false,
              comments: false,
            },
            warnings: false,
          },
          // cache: true,
          parallel: 3,
          sourceMap: true,
        }),
      ],
      splitChunks: {
        cacheGroups: {
          // this needs to be "vendors" to overwrite a default group
          vendors: {
            chunks: 'all',
            test: 'vendor',
            name: 'vendor',
            enforce: true,
          },
        },
      },
    },
    plugins: [
      new webpack.DefinePlugin({
        __BUILDTYPE__: JSON.stringify(buildOptions.buildtype),
        __API__: JSON.stringify(buildOptions.api),
      }),

      new MiniCssExtractPlugin({
        moduleFilename: chunk => {
          const { name } = chunk;
          const isMedalliaStyleFile = name === vaMedalliaStylesFilename;

          const isStaging =
            buildOptions.buildtype === ENVIRONMENTS.VAGOVSTAGING;

          if (isMedalliaStyleFile && isStaging) return `[name].css`;

          return isOptimizedBuild
            ? `[name].[contenthash]-${timestamp}.css`
            : `[name].css`;
        },
      }),

      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),

      new WebpackBar(),
    ],
    devServer: generateWebpackDevConfig(buildOptions),
  };

  if (!buildOptions.watch) {
    baseConfig.plugins.push(
      new ManifestPlugin({
        fileName: 'file-manifest.json',
      }),
    );
  }

  // Optionally generate landing pages in the absence of a content build.
  if (buildOptions.scaffold) {
    const landingPagePath = rootUrl =>
      path.join(outputPath, '../', rootUrl, 'index.html');

    const inlineScripts = [
      'incompatible-browser.js',
      'record-event.js',
      'static-page-widgets.js',
    ].reduce(
      (scripts, filename) => ({
        ...scripts,
        [filename]: fs.readFileSync(path.join('src/site/assets/js', filename)),
      }),
      {},
    );

    // Modifies the style tags output from HTML Webpack Plugin
    // to match the order and attributes of style tags from real content.
    const modifyStyleTags = pluginStyleTags =>
      pluginStyleTags
        .reduce(
          (tags, tag) =>
            // Puts style.css before the app-specific stylesheet.
            tag.attributes.href.match(/style/)
              ? [tag, ...tags]
              : [...tags, tag],
          [],
        )
        .join('');

    // Modifies the script tags output from HTML Webpack Plugin
    // to match the order and attributes of script tags from real content.
    const modifyScriptTags = pluginScriptTags =>
      pluginScriptTags
        .reduce((tags, tag) => {
          // Exclude style.entry.js, which gets included with the style chunk.
          if (tag.attributes.src.match(/style/)) return tags;

          // Force polyfills.entry.js to be first (and set `nomodules`), since
          // vendor.entry.js gets put first even with chunksSortMode: 'manual'.
          return tag.attributes.src.match(/polyfills/)
            ? [
                { ...tag, attributes: { ...tag.attributes, nomodule: true } },
                ...tags,
              ]
            : [...tags, tag];
        }, [])
        .join('');

    const appRegistryPath = 'src/applications/registry.json';
    let appRegistry;

    if (fs.existsSync(appRegistryPath)) {
      appRegistry = JSON.parse(fs.readFileSync(appRegistryPath));
    }

    const generateLandingPage = ({
      appName,
      entryName = 'static-pages',
      rootUrl,
      template = {},
    }) =>
      new HtmlPlugin({
        chunks: ['polyfills', 'vendor', 'style', entryName],
        filename: landingPagePath(rootUrl),
        inject: false,
        scriptLoading: 'defer',
        template: 'src/platform/landing-pages/dev-template.ejs',
        templateParameters: {
          entryName,
          headerFooterData,
          inlineScripts,
          modifyScriptTags,
          modifyStyleTags,

          // Default template metadata.
          breadcrumbs_override: [], // eslint-disable-line camelcase
          includeBreadcrumbs: false,
          loadingMessage: 'Please wait while we load the application for you.',
          ...template, // Unpack any template metadata from the registry entry.
        },
        title: template.title || appName ? `${appName} | VA.gov` : 'VA.gov',
      });

    baseConfig.plugins = baseConfig.plugins.concat(
      // Fall back to using app manifests if app registry no longer exists.
      // The app registry is used primarily to get the template metadata
      // so the landing pages can resemble real content more closely.
      (appRegistry || getAppManifests())
        .filter(({ rootUrl }) => rootUrl)
        .map(generateLandingPage),
    );

    // Create a placeholder home page.
    baseConfig.plugins.push(
      new HtmlPlugin({
        filename: path.join(outputPath, '..', 'index.html'),
        inject: false,
        title: 'VA.gov',
      }),
    );

    // Copy over image assets to fill in the header and other content.
    baseConfig.plugins.push(
      new CopyPlugin({
        patterns: [
          {
            from: 'src/site/assets/img',
            to: path.join(outputPath, '..', 'img'),
          },
        ],
      }),
    );
  }

  if (isOptimizedBuild) {
    const bucket = BUCKETS[buildOptions.buildtype];

    baseConfig.plugins.push(
      new webpack.SourceMapDevToolPlugin({
        append: `\n//# sourceMappingURL=${bucket}/generated/[url]`,
        filename: '[file].map',
      }),
    );

    baseConfig.plugins.push(new webpack.HashedModuleIdsPlugin());
    baseConfig.mode = 'production';
  } else {
    baseConfig.devtool = '#eval-source-map';

    // The eval-source-map devtool doesn't seem to work for CSS, so we
    // add a separate plugin for CSS source maps.
    baseConfig.plugins.push(
      new webpack.SourceMapDevToolPlugin({
        test: /\.css$/,
      }),
    );
  }

  if (buildOptions.analyzer) {
    baseConfig.plugins.push(
      new BundleAnalyzerPlugin({
        analyzerMode: 'disabled',
        generateStatsFile: true,
      }),
    );
  }

  return baseConfig;
};
<commit_msg>Feature/turn off file hashes (#15154)<commit_after>require('@babel/polyfill');
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

const CopyPlugin = require('copy-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
  .BundleAnalyzerPlugin;
const ManifestPlugin = require('webpack-manifest-plugin');
const WebpackBar = require('webpackbar');

const headerFooterData = require('../src/platform/landing-pages/header-footer-data.json');
const BUCKETS = require('../src/site/constants/buckets');
const ENVIRONMENTS = require('../src/site/constants/environments');

const {
  getAppManifests,
  getWebpackEntryPoints,
} = require('./manifest-helpers');

// TODO: refactor the other approach for creating files without the hash so that we're only doing that in the webpack config: https://github.com/department-of-veterans-affairs/vets-website/blob/a012bad17e5bf024b0ea7326a72ae6a737e349ec/src/site/stages/build/plugins/process-entry-names.js#L35
const vaMedalliaStylesFilename = 'va-medallia-styles';

const generateWebpackDevConfig = require('./webpack.dev.config.js');

const timestamp = new Date().getTime();

const getAbsolutePath = relativePath =>
  path.join(__dirname, '../', relativePath);

const sharedModules = [
  getAbsolutePath('src/platform/polyfills'),
  'react',
  'react-dom',
  'react-redux',
  'redux',
  'redux-thunk',
  '@sentry/browser',
];

const globalEntryFiles = {
  polyfills: getAbsolutePath('src/platform/polyfills/preESModulesPolyfills.js'),
  style: getAbsolutePath('src/platform/site-wide/sass/style.scss'),
  [vaMedalliaStylesFilename]: getAbsolutePath(
    'src/platform/site-wide/sass/va-medallia-style.scss',
  ),
  styleConsolidated: getAbsolutePath(
    'src/applications/proxy-rewrite/sass/style-consolidated.scss',
  ),
  vendor: sharedModules,
  // This is to solve the issue of the vendor file being cached
  'shared-modules': sharedModules,
};

/**
 * Get a list of all the entry points.
 *
 * @param {String} entry - List of comma-delimited entries to build. Builds all
 *                         entries if no value is passed.
 * @return {Object} - The entry file paths mapped to the entry names
 */
function getEntryPoints(entry) {
  const manifests = getAppManifests();
  let manifestsToBuild = manifests;
  if (entry) {
    const entryNames = entry.split(',').map(name => name.trim());
    manifestsToBuild = manifests.filter(manifest =>
      entryNames.includes(manifest.entryName),
    );
  }

  return getWebpackEntryPoints(manifestsToBuild);
}

module.exports = env => {
  const buildOptions = {
    api: '',
    buildtype: 'localhost',
    host: 'localhost',
    port: 3001,
    scaffold: false,
    watch: false,
    ...env,
    // Using a getter so we can reference the buildtype
    get destination() {
      return path.resolve(__dirname, '../', 'build', this.buildtype);
    },
  };

  const apps = getEntryPoints(buildOptions.entry);
  const entryFiles = Object.assign({}, apps, globalEntryFiles);
  const isOptimizedBuild = [
    ENVIRONMENTS.VAGOVSTAGING,
    ENVIRONMENTS.VAGOVPROD,
  ].includes(buildOptions.buildtype);

  const useHashFilenames = [ENVIRONMENTS.VAGOVPROD].includes(
    buildOptions.buildtype,
  );

  // enable css sourcemaps for all non-localhost builds
  // or if build options include local-css-sourcemaps or entry
  const enableCSSSourcemaps =
    buildOptions.buildtype !== ENVIRONMENTS.LOCALHOST ||
    buildOptions['local-css-sourcemaps'] ||
    !!buildOptions.entry;

  const outputPath = `${buildOptions.destination}/generated`;

  const baseConfig = {
    mode: 'development',
    entry: entryFiles,
    output: {
      path: outputPath,
      publicPath: '/generated/',
      filename: !useHashFilenames
        ? '[name].entry.js'
        : `[name].entry.[chunkhash]-${timestamp}.js`,
      chunkFilename: !useHashFilenames
        ? '[name].entry.js'
        : `[name].entry.[chunkhash]-${timestamp}.js`,
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              // Speed up compilation.
              cacheDirectory: '.babelcache',
              // Also see .babelrc
            },
          },
        },
        {
          test: /\.(sa|sc|c)ss$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader,
            },
            {
              loader: 'css-loader',
              options: {
                sourceMap: enableCSSSourcemaps,
              },
            },
            {
              loader: 'postcss-loader',
              options: {
                // use cssnano to minimize css only on optimized builds
                plugins: isOptimizedBuild
                  ? () => [require('autoprefixer'), require('cssnano')]
                  : () => [require('autoprefixer')],
              },
            },
            {
              loader: 'sass-loader',
              options: { sourceMap: true },
            },
          ],
        },
        {
          // if we want to minify these images, we could add img-loader
          // but it currently only would apply to three images from uswds
          test: /\.(jpe?g|png|gif)$/i,
          use: {
            loader: 'url-loader',
            options: {
              limit: 10000,
            },
          },
        },
        {
          test: /\.svg/,
          use: {
            loader: 'svg-url-loader?limit=1024',
          },
        },
        {
          test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: {
            loader: 'url-loader',
            options: {
              limit: 7000,
              mimetype: 'application/font-woff',
              name: '[name].[ext]',
            },
          },
        },
        {
          test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
            },
          },
        },
        {
          test: /react-jsonschema-form\/lib\/components\/(widgets|fields\/ObjectField|fields\/ArrayField)/,
          exclude: [/widgets\/index\.js/, /widgets\/TextareaWidget/],
          use: {
            loader: 'null-loader',
          },
        },
      ],
      noParse: [/mapbox\/vendor\/promise.js$/],
    },
    resolve: {
      extensions: ['.js', '.jsx'],
    },
    optimization: {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            output: {
              beautify: false,
              comments: false,
            },
            warnings: false,
          },
          // cache: true,
          parallel: 3,
          sourceMap: true,
        }),
      ],
      splitChunks: {
        cacheGroups: {
          // this needs to be "vendors" to overwrite a default group
          vendors: {
            chunks: 'all',
            test: 'vendor',
            name: 'vendor',
            enforce: true,
          },
        },
      },
    },
    plugins: [
      new webpack.DefinePlugin({
        __BUILDTYPE__: JSON.stringify(buildOptions.buildtype),
        __API__: JSON.stringify(buildOptions.api),
      }),

      new MiniCssExtractPlugin({
        moduleFilename: chunk => {
          const { name } = chunk;
          const isMedalliaStyleFile = name === vaMedalliaStylesFilename;

          const isStaging =
            buildOptions.buildtype === ENVIRONMENTS.VAGOVSTAGING;

          if (isMedalliaStyleFile && isStaging) return `[name].css`;

          return useHashFilenames
            ? `[name].[contenthash]-${timestamp}.css`
            : `[name].css`;
        },
      }),

      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),

      new WebpackBar(),
    ],
    devServer: generateWebpackDevConfig(buildOptions),
  };

  if (!buildOptions.watch) {
    baseConfig.plugins.push(
      new ManifestPlugin({
        fileName: 'file-manifest.json',
      }),
    );
  }

  // Optionally generate landing pages in the absence of a content build.
  if (buildOptions.scaffold) {
    const landingPagePath = rootUrl =>
      path.join(outputPath, '../', rootUrl, 'index.html');

    const inlineScripts = [
      'incompatible-browser.js',
      'record-event.js',
      'static-page-widgets.js',
    ].reduce(
      (scripts, filename) => ({
        ...scripts,
        [filename]: fs.readFileSync(path.join('src/site/assets/js', filename)),
      }),
      {},
    );

    // Modifies the style tags output from HTML Webpack Plugin
    // to match the order and attributes of style tags from real content.
    const modifyStyleTags = pluginStyleTags =>
      pluginStyleTags
        .reduce(
          (tags, tag) =>
            // Puts style.css before the app-specific stylesheet.
            tag.attributes.href.match(/style/)
              ? [tag, ...tags]
              : [...tags, tag],
          [],
        )
        .join('');

    // Modifies the script tags output from HTML Webpack Plugin
    // to match the order and attributes of script tags from real content.
    const modifyScriptTags = pluginScriptTags =>
      pluginScriptTags
        .reduce((tags, tag) => {
          // Exclude style.entry.js, which gets included with the style chunk.
          if (tag.attributes.src.match(/style/)) return tags;

          // Force polyfills.entry.js to be first (and set `nomodules`), since
          // vendor.entry.js gets put first even with chunksSortMode: 'manual'.
          return tag.attributes.src.match(/polyfills/)
            ? [
                { ...tag, attributes: { ...tag.attributes, nomodule: true } },
                ...tags,
              ]
            : [...tags, tag];
        }, [])
        .join('');

    const appRegistryPath = 'src/applications/registry.json';
    let appRegistry;

    if (fs.existsSync(appRegistryPath)) {
      appRegistry = JSON.parse(fs.readFileSync(appRegistryPath));
    }

    const generateLandingPage = ({
      appName,
      entryName = 'static-pages',
      rootUrl,
      template = {},
    }) =>
      new HtmlPlugin({
        chunks: ['polyfills', 'vendor', 'style', entryName],
        filename: landingPagePath(rootUrl),
        inject: false,
        scriptLoading: 'defer',
        template: 'src/platform/landing-pages/dev-template.ejs',
        templateParameters: {
          entryName,
          headerFooterData,
          inlineScripts,
          modifyScriptTags,
          modifyStyleTags,

          // Default template metadata.
          breadcrumbs_override: [], // eslint-disable-line camelcase
          includeBreadcrumbs: false,
          loadingMessage: 'Please wait while we load the application for you.',
          ...template, // Unpack any template metadata from the registry entry.
        },
        title: template.title || appName ? `${appName} | VA.gov` : 'VA.gov',
      });

    baseConfig.plugins = baseConfig.plugins.concat(
      // Fall back to using app manifests if app registry no longer exists.
      // The app registry is used primarily to get the template metadata
      // so the landing pages can resemble real content more closely.
      (appRegistry || getAppManifests())
        .filter(({ rootUrl }) => rootUrl)
        .map(generateLandingPage),
    );

    // Create a placeholder home page.
    baseConfig.plugins.push(
      new HtmlPlugin({
        filename: path.join(outputPath, '..', 'index.html'),
        inject: false,
        title: 'VA.gov',
      }),
    );

    // Copy over image assets to fill in the header and other content.
    baseConfig.plugins.push(
      new CopyPlugin({
        patterns: [
          {
            from: 'src/site/assets/img',
            to: path.join(outputPath, '..', 'img'),
          },
        ],
      }),
    );
  }

  if (isOptimizedBuild) {
    const bucket = BUCKETS[buildOptions.buildtype];

    baseConfig.plugins.push(
      new webpack.SourceMapDevToolPlugin({
        append: `\n//# sourceMappingURL=${bucket}/generated/[url]`,
        filename: '[file].map',
      }),
    );

    baseConfig.plugins.push(new webpack.HashedModuleIdsPlugin());
    baseConfig.mode = 'production';
  } else {
    baseConfig.devtool = '#eval-source-map';

    // The eval-source-map devtool doesn't seem to work for CSS, so we
    // add a separate plugin for CSS source maps.
    baseConfig.plugins.push(
      new webpack.SourceMapDevToolPlugin({
        test: /\.css$/,
      }),
    );
  }

  if (buildOptions.analyzer) {
    baseConfig.plugins.push(
      new BundleAnalyzerPlugin({
        analyzerMode: 'disabled',
        generateStatsFile: true,
      }),
    );
  }

  return baseConfig;
};
<|endoftext|>


<commit_before>(function(){
  ko.components.register("ko-dropdown", {
    viewModel: function(params){
      var self = this;

      self.caption = params.caption;
      self.value = params.value;
      self.options = params.options;

      self.dropdownOpen = ko.observable();

      self.selectedOption = ko.observable();
      self.selectedText = ko.computed(function() {
        return ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).text : "";
      });

      self.dropdownOptions = ko.computed(function(){
        var retOptions = [];
        self.options().forEach(function(option){
          if (typeof option === 'object' || option instanceof Object){
            retOptions.push(option);
          } else {
            retOptions.push({
              value: option,
              text: option
            });
          }
        });

        if (retOptions.length > 0 && !ko.unwrap(self.caption)) {
          self.selectOption(retOptions[0]);
        }

        return retOptions;
      });

      if (ko.unwrap(self.value)){
        var e = self.dropdownOptions()
        self.selectedOption(findOptionByValue(ko.unwrap(self.value)));
      } else if (ko.unwrap(self.caption)){
        self.selectedOption({
          text: self.caption
        });
      }

      self.selectOption = function(option){
        self.value(option.value);
        self.selectedOption(option);
      }

      self.toggleOpen = function(data, event){
        event.stopPropagation();
        self.dropdownOpen(!self.dropdownOpen());
      }

      self.value.subscribe(function(newValue){
        var selectedValue = ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).value : null;

        if (newValue !== selectedValue){
          var option = findOptionByValue(newValue);
          if (option != null){
            self.selectOption(option);
          }
        }
      });

      window.addEventListener('click', function (e) {
          self.dropdownOpen(false);
      });

      function findOptionByValue(val){
        var foundOption = null;
        if (ko.unwrap(self.dropdownOptions)){
          self.dropdownOptions().forEach(function(option){
            if (option.value === val){
              foundOption = option;
            }
          });
        }
        return foundOption;
      }
    },
    template: "
\
        \

\

\

\

"
  });

}());
<commit_msg>Removed debugging code<commit_after>(function(){
  ko.components.register("ko-dropdown", {
    viewModel: function(params){
      var self = this;

      self.caption = params.caption;
      self.value = params.value;
      self.options = params.options;

      self.dropdownOpen = ko.observable();

      self.selectedOption = ko.observable();
      self.selectedText = ko.computed(function() {
        return ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).text : "";
      });

      self.dropdownOptions = ko.computed(function(){
        var retOptions = [];
        self.options().forEach(function(option){
          if (typeof option === 'object' || option instanceof Object){
            retOptions.push(option);
          } else {
            retOptions.push({
              value: option,
              text: option
            });
          }
        });

        if (retOptions.length > 0 && !ko.unwrap(self.caption)) {
          self.selectOption(retOptions[0]);
        }

        return retOptions;
      });

      if (ko.unwrap(self.value)){
        self.selectedOption(findOptionByValue(ko.unwrap(self.value)));
      } else if (ko.unwrap(self.caption)){
        self.selectedOption({
          text: self.caption
        });
      }

      self.selectOption = function(option){
        self.value(option.value);
        self.selectedOption(option);
      }

      self.toggleOpen = function(data, event){
        event.stopPropagation();
        self.dropdownOpen(!self.dropdownOpen());
      }

      self.value.subscribe(function(newValue){
        var selectedValue = ko.unwrap(self.selectedOption) ? ko.unwrap(self.selectedOption).value : null;

        if (newValue !== selectedValue){
          var option = findOptionByValue(newValue);
          if (option != null){
            self.selectOption(option);
          }
        }
      });

      window.addEventListener('click', function (e) {
          self.dropdownOpen(false);
      });

      function findOptionByValue(val){
        var foundOption = null;
        if (ko.unwrap(self.dropdownOptions)){
          self.dropdownOptions().forEach(function(option){
            if (option.value === val){
              foundOption = option;
            }
          });
        }
        return foundOption;
      }
    },
    template: "
\
        \

\

\

\

"
  });

}());
<|endoftext|>


<commit_before>/**
 * The Number class extentions
 *
 * Credits:
 *   Some methods inspired by
 *     - Ruby      (http://www.ruby-lang.org) Copyright (C) Yukihiro Matsumoto
 *
 * Copyright (C) 2008-2010 Nikolay V. Nemshilov
 */
Number.include({
  /**
   * executes the given callback the given number of times
   *
   * @param Function callback
   * @param Object optional callback execution scope
   * @return void
   */
  times: function(callback, scope) {
    for (var i=0; i < this; i++) {
      callback.call(scope, i);
    }
    return this;
  },

  upto: function(number, callback, scope) {
    for (var i=this+0; i <= number; i++) {
      callback.call(scope, i);
    }
    return this;
  },

  downto: function(number, callback, scope) {
    for (var i=this+0; i >= number; i--) {
      callback.call(scope, i);
    }
    return this;
  },

  abs: function() {
    return Math.abs(this);
  },

  round: function(size) {
    return size ? parseFloat(this.toFixed(size)) : Math.round(this);
  },

  ceil: function() {
    return Math.ceil(this);
  },

  floor: function() {
    return Math.floor(this);
  },

  min: function(value) {
    return this < value ? value : this + 0;
  },

  max: function(value) {
    return this > value ? value : this + 0;
  }
});
<commit_msg>New feature for Number#downto and #upto: if called without a callback argument, the methods now return an array of this kind: [instance, ... , number_argument].<commit_after>/**
 * The Number class extentions
 *
 * Credits:
 *   Some methods inspired by
 *     - Ruby      (http://www.ruby-lang.org) Copyright (C) Yukihiro Matsumoto
 *
 * Copyright (C) 2008-2010 Nikolay V. Nemshilov
 */
Number.include({
  /**
   * executes the given callback the given number of times
   *
   * @param Function callback
   * @param Object optional callback execution scope
   * @return void
   */
  times: function(callback, scope) {
    for (var i=0; i < this; i++) {
      callback.call(scope, i);
    }
    return this;
  },

  upto: function(number, callback, scope) {
    if (callback === undefined) {
      var numbers = [];
      for (var i=this+0; i <= number; i++) {
        numbers.push(i);
      }
      return numbers;
    } else {
      for (var i=this+0; i <= number; i++) {
        callback.call(scope, i);
      }
      return this;
    }
  },

  downto: function(number, callback, scope) {
    if (callback === undefined) {
      var numbers = [];
      for (var i=this+0; i >= number; i--) {
        numbers.push(i);
      }
      return numbers;
    } else {
      for (var i=this+0; i >= number; i--) {
        callback.call(scope, i);
      }
      return this;
    }
  },

  abs: function() {
    return Math.abs(this);
  },

  round: function(size) {
    return size ? parseFloat(this.toFixed(size)) : Math.round(this);
  },

  ceil: function() {
    return Math.ceil(this);
  },

  floor: function() {
    return Math.floor(this);
  },

  min: function(value) {
    return this < value ? value : this + 0;
  },

  max: function(value) {
    return this > value ? value : this + 0;
  }
});
<|endoftext|>


<commit_before>
L.Layer = L.Evented.extend({

	options: {
		pane: 'overlayPane',
		nonBubblingEvents: []  // Array of events that should not be bubbled to DOM parents (like the map)
	},

	addTo: function (map) {
		map.addLayer(this);
		return this;
	},

	remove: function () {
		return this.removeFrom(this._map || this._mapToAdd);
	},

	removeFrom: function (obj) {
		if (obj) {
			obj.removeLayer(this);
		}
		return this;
	},

	getPane: function (name) {
		return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
	},

	addInteractiveTarget: function (targetEl) {
		this._map._targets[L.stamp(targetEl)] = this;
		return this;
	},

	removeInteractiveTarget: function (targetEl) {
		delete this._map._targets[L.stamp(targetEl)];
		return this;
	},

	_layerAdd: function (e) {
		var map = e.target;

		// check in case layer gets added and then removed before the map is ready
		if (!map.hasLayer(this)) { return; }

		this._map = map;
		this._zoomAnimated = map._zoomAnimated;

		if (this.getEvents) {
			map.on(this.getEvents(), this);
		}

		this.onAdd(map);

		if (this.getAttribution && this._map.attributionControl) {
			this._map.attributionControl.addAttribution(this.getAttribution());
		}

		this.fire('add');
		map.fire('layeradd', {layer: this});
	}
});

L.Map.include({
	addLayer: function (layer) {
		var id = L.stamp(layer);
		if (this._layers[id]) { return layer; }
		this._layers[id] = layer;

		layer._mapToAdd = this;

		if (layer.beforeAdd) {
			layer.beforeAdd(this);
		}

		this.whenReady(layer._layerAdd, layer);

		return this;
	},

	removeLayer: function (layer) {
		var id = L.stamp(layer);

		if (!this._layers[id]) { return this; }

		if (this._loaded) {
			layer.onRemove(this);
		}

		if (layer.getAttribution && this.attributionControl) {
			this.attributionControl.removeAttribution(layer.getAttribution());
		}

		if (layer.getEvents) {
			this.off(layer.getEvents(), layer);
		}

		delete this._layers[id];

		if (this._loaded) {
			this.fire('layerremove', {layer: layer});
			layer.fire('remove');
		}

		layer._map = layer._mapToAdd = null;

		return this;
	},

	hasLayer: function (layer) {
		return !!layer && (L.stamp(layer) in this._layers);
	},

	eachLayer: function (method, context) {
		for (var i in this._layers) {
			method.call(context, this._layers[i]);
		}
		return this;
	},

	_addLayers: function (layers) {
		layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];

		for (var i = 0, len = layers.length; i < len; i++) {
			this.addLayer(layers[i]);
		}
	},

	_addZoomLimit: function (layer) {
		if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
			this._zoomBoundLayers[L.stamp(layer)] = layer;
			this._updateZoomLevels();
		}
	},

	_removeZoomLimit: function (layer) {
		var id = L.stamp(layer);

		if (this._zoomBoundLayers[id]) {
			delete this._zoomBoundLayers[id];
			this._updateZoomLevels();
		}
	},

	_updateZoomLevels: function () {
		var minZoom = Infinity,
			maxZoom = -Infinity,
			oldZoomSpan = this._getZoomSpan();

		for (var i in this._zoomBoundLayers) {
			var options = this._zoomBoundLayers[i].options;

			minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
			maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
		}

		this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
		this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;

		if (oldZoomSpan !== this._getZoomSpan()) {
			this.fire('zoomlevelschange');
		}
	}
});
<commit_msg>Scale tiles by maxNativeZoom<commit_after>
L.Layer = L.Evented.extend({

	options: {
		pane: 'overlayPane',
		nonBubblingEvents: []  // Array of events that should not be bubbled to DOM parents (like the map)
	},

	addTo: function (map) {
		map.addLayer(this);
		return this;
	},

	remove: function () {
		return this.removeFrom(this._map || this._mapToAdd);
	},

	removeFrom: function (obj) {
		if (obj) {
			obj.removeLayer(this);
		}
		return this;
	},

	getPane: function (name) {
		return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
	},

	addInteractiveTarget: function (targetEl) {
		this._map._targets[L.stamp(targetEl)] = this;
		return this;
	},

	removeInteractiveTarget: function (targetEl) {
		delete this._map._targets[L.stamp(targetEl)];
		return this;
	},

	isPopupOpen: function() {
		return this._popup.isOpen();
	},

	_layerAdd: function (e) {
		var map = e.target;

		// check in case layer gets added and then removed before the map is ready
		if (!map.hasLayer(this)) { return; }

		this._map = map;
		this._zoomAnimated = map._zoomAnimated;

		if (this.getEvents) {
			map.on(this.getEvents(), this);
		}

		this.onAdd(map);

		if (this.getAttribution && this._map.attributionControl) {
			this._map.attributionControl.addAttribution(this.getAttribution());
		}

		this.fire('add');
		map.fire('layeradd', {layer: this});
	}
});

L.Map.include({
	addLayer: function (layer) {
		var id = L.stamp(layer);
		if (this._layers[id]) { return layer; }
		this._layers[id] = layer;

		layer._mapToAdd = this;

		if (layer.beforeAdd) {
			layer.beforeAdd(this);
		}

		this.whenReady(layer._layerAdd, layer);

		return this;
	},

	removeLayer: function (layer) {
		var id = L.stamp(layer);

		if (!this._layers[id]) { return this; }

		if (this._loaded) {
			layer.onRemove(this);
		}

		if (layer.getAttribution && this.attributionControl) {
			this.attributionControl.removeAttribution(layer.getAttribution());
		}

		if (layer.getEvents) {
			this.off(layer.getEvents(), layer);
		}

		delete this._layers[id];

		if (this._loaded) {
			this.fire('layerremove', {layer: layer});
			layer.fire('remove');
		}

		layer._map = layer._mapToAdd = null;

		return this;
	},

	hasLayer: function (layer) {
		return !!layer && (L.stamp(layer) in this._layers);
	},

	eachLayer: function (method, context) {
		for (var i in this._layers) {
			method.call(context, this._layers[i]);
		}
		return this;
	},

	_addLayers: function (layers) {
		layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];

		for (var i = 0, len = layers.length; i < len; i++) {
			this.addLayer(layers[i]);
		}
	},

	_addZoomLimit: function (layer) {
		if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
			this._zoomBoundLayers[L.stamp(layer)] = layer;
			this._updateZoomLevels();
		}
	},

	_removeZoomLimit: function (layer) {
		var id = L.stamp(layer);

		if (this._zoomBoundLayers[id]) {
			delete this._zoomBoundLayers[id];
			this._updateZoomLevels();
		}
	},

	_updateZoomLevels: function () {
		var minZoom = Infinity,
			maxZoom = -Infinity,
			oldZoomSpan = this._getZoomSpan();

		for (var i in this._zoomBoundLayers) {
			var options = this._zoomBoundLayers[i].options;

			minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
			maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
		}

		this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
		this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;

		if (oldZoomSpan !== this._getZoomSpan()) {
			this.fire('zoomlevelschange');
		}
	}
});
<|endoftext|>


<commit_before>//
// Copyright (c) 2014 by Ark.com. All Rights Reserved.
// Created by Vitaly Aminev <v@aminev.me>
//

angular.module('ArkSDK')
    .factory('ArkQueryBuilder', [
        'ArkAvailableNetworks',
        function (ArkAvailableNetworks) {

            var _sexValues = ["male", "female", "other"];
            var _suggestAllowedFields = [
                'fullName',
                'header',
                'languages',
                'education.degree',
                'education.school',
                'experience.company',
                'experience.title'
            ];
            var _networks = _.values(ArkAvailableNetworks);

            var queryBuilder = {

                idQuery: function (id) {
                    return {
                        type: "id",
                        data: { id: id }
                    };
                },

                allQuery: function (text) {
                    return {
                        type: "_all",
                        data: { text: text }
                    };
                },

                emailQuery: function (email) {
                    return {
                        type: "email",
                        data: { email: email }
                    };
                },

                networkAndIdQuery: function (network, id) {
                    if (_.indexOf(_networks, network) === -1) {
                        throw new Error(network + " is not in the list of available networks");
                    }

                    var query = {
                        type: "network_id",
                        data: {
                            network: network,
                            network_id: id
                        }
                    };

                    return query;
                },

                placesQuery: function (place) {
                    return {
                        type: "places",
                        data: {
                            place: place
                        }
                    };
                },

                sexQuery: function (sex) {
                    if (_.indexOf(_sexValues, sex) === -1) {
                        throw new Error("Only " + _sexValues.join(",") + " are supported");
                    }

                    return {
                        type: "sex",
                        data: {
                            sex: sex
                        }
                    };
                },

                languageQuery: function (language) {
                    return {
                        type: "language",
                        data: {
                            language: language
                        }
                    };
                },

                fullNameQuery: function (name) {
                    return {
                        type: "full_name_exact",
                        data: {
                            fullName: name
                        }
                    };
                },

                fullNamePartialQuery: function (name) {
                    return {
                        type: "full_name_partial_translit",
                        data: {
                            fullName: name
                        }
                    };
                },

                educationQuery: function (school, degree, start, end) {
                    if (!school && !degree) {
                        throw new Error("At least school or degree should be specified");
                    }

                    var query = {
                        type: "education",
                        data: {}
                    };
                    var data = query.data;

                    ["school", "degree", "start", "end"].forEach(function(field, idx){
                        var val = arguments[idx];
                        if (val) {
                            data[field] = arguments[idx];
                        }
                    });

                    return query;
                },

                experienceQuery: function (company, title, start, end) {
                    if (!school && !degree) {
                        throw new Error("At least school or degree should be specified");
                    }

                    var query = {
                        type: "experience",
                        data: {}
                    };
                    var data = query.data;

                    ["company", "title", "start", "end"].forEach(function(field, idx){
                        var val = arguments[idx];
                        if (val) {
                            data[field] = arguments[idx];
                        }
                    });

                    return query;
                },

                suggestQuery: function (field, text) {
                    if (_.indexOf(_suggestAllowedFields, field) === -1 ) {
                        throw new Error("Suggest field must be one of the: " + _suggestAllowedFields.join(','));
                    }

                    var fieldName = field + ".completion";
                    return {
                        field: fieldName,
                        text: text
                    };
                }

            };

            return queryBuilder;
        }
    ]);
<commit_msg>Add place type<commit_after>//
// Copyright (c) 2014 by Ark.com. All Rights Reserved.
// Created by Vitaly Aminev <v@aminev.me>
//

angular.module('ArkSDK')
    .factory('ArkQueryBuilder', [
        'ArkAvailableNetworks',
        function (ArkAvailableNetworks) {

            var _sexValues = ["male", "female", "other"];
            var _suggestAllowedFields = [
                'fullName',
                'header',
                'languages',
                'education.degree',
                'education.school',
                'experience.company',
                'experience.title'
            ];
            var _networks = _.values(ArkAvailableNetworks);

            var queryBuilder = {

                idQuery: function (id) {
                    return {
                        type: "id",
                        data: { id: id }
                    };
                },

                allQuery: function (text) {
                    return {
                        type: "_all",
                        data: { text: text }
                    };
                },

                emailQuery: function (email) {
                    return {
                        type: "email",
                        data: { email: email }
                    };
                },

                networkAndIdQuery: function (network, id) {
                    if (_.indexOf(_networks, network) === -1) {
                        throw new Error(network + " is not in the list of available networks");
                    }

                    var query = {
                        type: "network_id",
                        data: {
                            network: network,
                            network_id: id
                        }
                    };

                    return query;
                },

                placesQuery: function (place, type) {
                    if (!place) {
                        throw new Error('At least place has to be specified');
                    }

                    var query = {
                        type: "places",
                        data: {
                            place: place
                        }
                    };

                    if (type) {
                        query.data.type = type;
                    }

                    return query;
                },

                sexQuery: function (sex) {
                    if (_.indexOf(_sexValues, sex) === -1) {
                        throw new Error("Only " + _sexValues.join(",") + " are supported");
                    }

                    return {
                        type: "sex",
                        data: {
                            sex: sex
                        }
                    };
                },

                languageQuery: function (language) {
                    return {
                        type: "language",
                        data: {
                            language: language
                        }
                    };
                },

                fullNameQuery: function (name) {
                    return {
                        type: "full_name_exact",
                        data: {
                            fullName: name
                        }
                    };
                },

                fullNamePartialQuery: function (name) {
                    return {
                        type: "full_name_partial_translit",
                        data: {
                            fullName: name
                        }
                    };
                },

                educationQuery: function (school, degree, start, end) {
                    if (!school && !degree) {
                        throw new Error("At least school or degree should be specified");
                    }

                    var query = {
                        type: "education",
                        data: {}
                    };
                    var data = query.data;

                    ["school", "degree", "start", "end"].forEach(function(field, idx){
                        var val = arguments[idx];
                        if (val) {
                            data[field] = arguments[idx];
                        }
                    });

                    return query;
                },

                experienceQuery: function (company, title, start, end) {
                    if (!school && !degree) {
                        throw new Error("At least school or degree should be specified");
                    }

                    var query = {
                        type: "experience",
                        data: {}
                    };
                    var data = query.data;

                    ["company", "title", "start", "end"].forEach(function(field, idx){
                        var val = arguments[idx];
                        if (val) {
                            data[field] = arguments[idx];
                        }
                    });

                    return query;
                },

                suggestQuery: function (field, text) {
                    if (_.indexOf(_suggestAllowedFields, field) === -1 ) {
                        throw new Error("Suggest field must be one of the: " + _suggestAllowedFields.join(','));
                    }

                    var fieldName = field + ".completion";
                    return {
                        field: fieldName,
                        text: text
                    };
                }

            };

            return queryBuilder;
        }
    ]);
<|endoftext|>


<commit_before>(function () {
    'use strict';
    /** @ngInject */
    function npMediaElementDirective($log) {
        $log.debug('\nnpReveal mediaelementDirective::Init\n');
        var Directive = function () {
            this.restrict = 'A';
            this.link = function (scope, element, attrs, controller) {
            };
        };
        return new Directive();
    }
    angular
            .module('newplayer.component')
            .controller('npRevealController',
                    function ($log, $scope, $sce, $element) {
                        var cmpData = $scope.component.data,
                                revealItems = $scope.component.revealItems,
                                revealItemsIndex = $scope.component.idx,
                                revealItemsButtonImage = $scope.component.revealItems.buttonImage;
                        var buttonData = $scope.feedback || {};
                        this.revealItems = $scope.component.revealItems;
                        this.revealItemComponent = $scope.component.revealItems[0];
                        this.revealItemComponents = $scope.component.revealItems;
                        this.revealItemVideoType = $scope.component.baseURL;
                        this.id = cmpData.id;
                        this.baseURL = cmpData.baseURL;
                        this.src = cmpData.image;
                        $scope.feedback = this.feedback = cmpData.feedback;
                        $scope.image = this.image = cmpData.image;
                        $log.debug('npReveal::data', cmpData, buttonData);
                        //////////////////////////////////////////////////////////////////////////////////////
                        //get ready
                        //////////////////////////////////////////////////////////////////////////////////////
                        setTimeout(function () {
                            $scope.$apply(function () {
                                //////////////////////////////////////////////////////////////////////////////////////
                                //on ready set states
                                //////////////////////////////////////////////////////////////////////////////////////
                                setTimeout(function () {
                                    var maxHeight = 0;
                                    $(".reveal-wrapper").each(function () {
//                                        console.log(
//                                                '\n::::::::::::::::::::::::::::::::::::::atTop::atTop:::::::::::::::::::::::::::::::::::::::::::::::::',
//                                                '\n::maxHeight::', maxHeight,
//                                                '\n::$(this).outerHeight()::', $(this).outerHeight(true),
//                                                '\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
//                                                );
                                        if ($(this).outerHeight() > maxHeight) {
                                            maxHeight = ($(this).outerHeight() + 100);
                                        }
                                    });
                                    $(".np-reveal").height(maxHeight);
                                }, 1);
                                TweenMax.to($(".reveal-object"), 0, {
                                    opacity: 0
                                });
                                TweenMax.set($(".reveal-button"), {
                                    opacity: 0,
                                    scale: .25,
                                    force3D: true
                                });
                                //////////////////////////////////////////////////////////////////////////////////////
                                //build init state
                                //////////////////////////////////////////////////////////////////////////////////////
                                TweenMax.to($(".button-screen"), 1.5, {
                                    autoAlpha: 0.75,
                                    ease: Power4.easeOut
                                });
                                TweenMax.staggerTo($(".reveal-button"), 2, {
                                    scale: 1,
                                    opacity: 1,
                                    delay: 0.25,
                                    ease: Power4.easeOut,
                                    force3D: true
                                }, 0.2);
                                TweenMax.to($(".button-screen"), 1.5, {
                                    autoAlpha: 0.75,
                                    ease: Power4.easeOut
                                });
                                TweenMax.to($(".button-screen")[0], 1.75, {
                                    autoAlpha: 0,
                                    delay: 1.75,
                                    ease: Power4.easeOut
                                });
                                TweenMax.to($(".reveal-object")[0], 1.75, {
                                    autoAlpha: 1,
                                    delay: 1.75,
                                    ease: Power4.easeOut
//                                    onComplete: function () {
//
//                                    }
                                });
                            });
                        });
                        this.update = function (button) {
                            var idx = this.revealItems.indexOf(button);
                            //////////////////////////////////////////////////////////////////////////////////////
                            //on navigation change stop and reset all video files
                            //////////////////////////////////////////////////////////////////////////////////////
                            $('video').each(function () {
                                this.pause();
                                this.currentTime = 0;
                                this.load();
                            });
                            //////////////////////////////////////////////////////////////////////////////////////
                            //on navigation change cross fade items
                            //////////////////////////////////////////////////////////////////////////////////////
                            TweenMax.to($(".button-screen"), 1.5, {
                                autoAlpha: 0.75,
                                ease: Power4.easeOut
                            });
                            TweenMax.to($(".button-screen")[idx], 1.75, {
                                autoAlpha: 0,
                                ease: Power4.easeOut
                            });
                            TweenMax.to($(".reveal-object"), 1.5, {
                                autoAlpha: 0,
                                ease: Power4.easeOut
                            });
                            TweenMax.to($(".reveal-object")[idx], 1.75, {
                                autoAlpha: 1,
                                ease: Power4.easeOut
                            });
                        };
                    }
            )
            .directive('mediaelement', npMediaElementDirective)
            /** @ngInject */
            .run(
                    function ($log, $rootScope) {
                        $log.debug('npReveal::component loaded!');
                    }
            );
})();<commit_msg>commit build test<commit_after>(function () {
    'use strict';
    /** @ngInject */
    function npMediaElementDirective($log) {
        $log.debug('\nnpReveal mediaelementDirective::Init\n');
        var Directive = function () {
            this.restrict = 'A';
            this.link = function (scope, element, attrs, controller) {
            };
        };
        return new Directive();
    }
    angular
            .module('newplayer.component')
            .controller('npRevealController',
                    function ($log, $scope, $sce, $element) {
                        var cmpData = $scope.component.data,
                                revealItems = $scope.component.revealItems,
                                revealItemsIndex = $scope.component.idx,
                                revealItemsButtonImage = $scope.component.revealItems.buttonImage;
                        var buttonData = $scope.feedback || {};
                        this.revealItems = $scope.component.revealItems;
                        this.revealItemComponent = $scope.component.revealItems[0];
                        this.revealItemComponents = $scope.component.revealItems;
                        this.revealItemVideoType = $scope.component.baseURL;
                        this.id = cmpData.id;
                        this.baseURL = cmpData.baseURL;
                        this.src = cmpData.image;
                        $scope.feedback = this.feedback = cmpData.feedback;
                        $scope.image = this.image = cmpData.image;
                        $log.debug('npReveal::data', cmpData, buttonData);
                        //////////////////////////////////////////////////////////////////////////////////////
                        //get ready
                        //////////////////////////////////////////////////////////////////////////////////////
                        setTimeout(function () {
                            $scope.$apply(function () {
                                //////////////////////////////////////////////////////////////////////////////////////
                                //on ready set states
                                //////////////////////////////////////////////////////////////////////////////////////
                                setTimeout(function () {
                                    var maxHeight = 0;
                                    $(".reveal-wrapper").each(function () {
//                                        console.log(
//                                                '\n::::::::::::::::::::::::::::::::::::::atTop::atTop:::::::::::::::::::::::::::::::::::::::::::::::::',
//                                                '\n::maxHeight::', maxHeight,
//                                                '\n::$(this).outerHeight()::', $(this).outerHeight(true),
//                                                '\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'
//                                                );
                                        if ($(this).outerHeight() > maxHeight) {
                                            maxHeight = ($(this).outerHeight() + 500);
                                        }
                                    });
                                    $(".np-reveal").height(maxHeight);
                                }, 1);
                                TweenMax.to($(".reveal-object"), 0, {
                                    opacity: 0
                                });
                                TweenMax.set($(".reveal-button"), {
                                    opacity: 0,
                                    scale: .25,
                                    force3D: true
                                });
                                //////////////////////////////////////////////////////////////////////////////////////
                                //build init state
                                //////////////////////////////////////////////////////////////////////////////////////
                                TweenMax.to($(".button-screen"), 1.5, {
                                    autoAlpha: 0.75,
                                    ease: Power4.easeOut
                                });
                                TweenMax.staggerTo($(".reveal-button"), 2, {
                                    scale: 1,
                                    opacity: 1,
                                    delay: 0.25,
                                    ease: Power4.easeOut,
                                    force3D: true
                                }, 0.2);
                                TweenMax.to($(".button-screen"), 1.5, {
                                    autoAlpha: 0.75,
                                    ease: Power4.easeOut
                                });
                                TweenMax.to($(".button-screen")[0], 1.75, {
                                    autoAlpha: 0,
                                    delay: 1.75,
                                    ease: Power4.easeOut
                                });
                                TweenMax.to($(".reveal-object")[0], 1.75, {
                                    autoAlpha: 1,
                                    delay: 1.75,
                                    ease: Power4.easeOut
//                                    onComplete: function () {
//
//                                    }
                                });
                            });
                        });
                        this.update = function (button) {
                            var idx = this.revealItems.indexOf(button);
                            //////////////////////////////////////////////////////////////////////////////////////
                            //on navigation change stop and reset all video files
                            //////////////////////////////////////////////////////////////////////////////////////
                            $('video').each(function () {
                                this.pause();
                                this.currentTime = 0;
                                this.load();
                            });
                            //////////////////////////////////////////////////////////////////////////////////////
                            //on navigation change cross fade items
                            //////////////////////////////////////////////////////////////////////////////////////
                            TweenMax.to($(".button-screen"), 1.5, {
                                autoAlpha: 0.75,
                                ease: Power4.easeOut
                            });
                            TweenMax.to($(".button-screen")[idx], 1.75, {
                                autoAlpha: 0,
                                ease: Power4.easeOut
                            });
                            TweenMax.to($(".reveal-object"), 1.5, {
                                autoAlpha: 0,
                                ease: Power4.easeOut
                            });
                            TweenMax.to($(".reveal-object")[idx], 1.75, {
                                autoAlpha: 1,
                                ease: Power4.easeOut
                            });
                        };
                    }
            )
            .directive('mediaelement', npMediaElementDirective)
            /** @ngInject */
            .run(
                    function ($log, $rootScope) {
                        $log.debug('npReveal::component loaded!');
                    }
            );
})();<|endoftext|>


<commit_before>(function () {

  'use strict';
  angular
    .module('newplayer.component')
  /** @ngInject */
    .controller('npTriviaController',
    function ($log, $scope, $rootScope, $timeout, ManifestService, $sce) {
      var vm = this;
      var cmpData = $scope.component.data;
      var pagesLen = $scope.components.length;
      $log.debug('npQuiz::data', cmpData);

      vm.id = cmpData.id;
      vm.content = $sce.trustAsHtml(cmpData.content);
      vm.type = cmpData.type;
      vm.currentPage = 0;
      vm.feedback = '';
      vm.assment = AssessmentService();
      vm.assment.setRequirements(pagesLen, pagesLen, null);
      vm.seenComponents = _.shuffle($scope.components);
      vm.pageId = vm.seenComponents[0].data.id;
      vm.difficulty = vm.seenComponents[0].components[0].data.difficulty || 0;

      // go to the first page, since pages were shuffled
      $timeout(function () {
    	  ManifestService.setPageId(vm.pageId)
      });

      $rootScope.$on('question.answered', function (evt, correct) {
      	if (correct) {
    			vm.assment.pageViewed();
      		vm.currentPage = vm.assment.getPageStats().viewed.total;
		      vm.pageId = vm.seenComponents[vm.currentPage] ?
		      	vm.seenComponents[vm.currentPage].data.id : '';
	    	  ManifestService.setPageId(vm.pageId);
					$rootScope.$emit('spin-to-win');

	    	  // end of the trivia questions
	    	  // TODO - add this message the template and set the two values
	    	  // here in the controller
	    	  if (!vm.pageId) {
	    	  	vm.feedback = 'Good job, you scored 5,000 points out of 7,500 possible.';
	    	  }
      	}
      });
    }
  )

  /** @ngInject */
    .run(
    function ($log, $rootScope) {
      $log.debug('npQuiz::component loaded!');
    }
  );

})();<commit_msg>docs(npTrivia): TODO language string from app<commit_after>(function () {

  'use strict';
  angular
    .module('newplayer.component')
  /** @ngInject */
    .controller('npTriviaController',
    function ($log, $scope, $rootScope, $timeout, ManifestService, $sce) {
      var vm = this;
      var cmpData = $scope.component.data;
      var pagesLen = $scope.components.length;
      $log.debug('npQuiz::data', cmpData);

      vm.id = cmpData.id;
      vm.content = $sce.trustAsHtml(cmpData.content);
      vm.type = cmpData.type;
      vm.currentPage = 0;
      vm.feedback = '';
      vm.assment = AssessmentService();
      vm.assment.setRequirements(pagesLen, pagesLen, null);
      vm.seenComponents = _.shuffle($scope.components);
      vm.pageId = vm.seenComponents[0].data.id;
      vm.difficulty = vm.seenComponents[0].components[0].data.difficulty || 0;

      // go to the first page, since pages were shuffled
      $timeout(function () {
        ManifestService.setPageId(vm.pageId);
      });

      $rootScope.$on('question.answered', function (evt, correct) {
      	if (correct) {
    			vm.assment.pageViewed();
      		vm.currentPage = vm.assment.getPageStats().viewed.total;
		      vm.pageId = vm.seenComponents[vm.currentPage] ?
		      	vm.seenComponents[vm.currentPage].data.id : '';
	    	  ManifestService.setPageId(vm.pageId);
					$rootScope.$emit('spin-to-win');

	    	  // end of the trivia questions
	    	  // TODO - add this message the template and set the two values
	    	  // here in the controller
          // NOTE: This text should come from the app
	    	  if (!vm.pageId) {
	    	  	vm.feedback = 'Good job, you scored 5,000 points out of 7,500 possible.';
	    	  }
      	}
      });
    }
  )

  /** @ngInject */
    .run(
    function ($log, $rootScope) {
      $log.debug('npQuiz::component loaded!');
    }
  );

})();
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name fec3App.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the fec3App
 */
angular.module('fec3App')
    .controller('productSelectorCtrl', function($scope, $localstorage, $routeParams, $location, $modal) {

        $scope.name = $routeParams.name;

        $scope.data = $modal.mathList();
        console.log($scope.data);
        //console.log($scope.ngDialogData);
        $scope.ngBootBoxClose = function() {

            bootbox.hideAll();
            // try {
            //     angular.element(document.getElementById('' + $('#divID').val())).scope().afterCloseWarning();
            // } catch (e) {}
        };

        $scope.proItem = {
            "pieceGold0": null
        };

        $scope.nextModal = function() {
            if ($scope.tabselected == "1") {
                //$location.path('/promotion?productCode=' + $scope.productCode + '&productType=' + $scope.productType)
                // if ($scope.productCode && $scope.productType) {
                //     $location.path('/promotion').search({
                //         id: $scope.id,
                //         name: $scope.name,
                //         productCode: $scope.productCode,
                //         productType: $scope.productType
                //     });
                // }

            } else {
                var customerProfile = $localstorage.getObject("customerProfile");
                var orderList = [];
                var order = {};
                var arr = $scope.data.childs;
                var sum = 0;
                for (var i = 0; i < arr.length; i++) {
                    var sum_i = 0;

                    if ($scope.proItem['piece' + arr[i].productInfo.color + i] && $scope.proItem['piece' + arr[i].productInfo.color + i] > 0) {
                        console.log("Tingtang:" + arr[i]);
                        //var order.PRODUCT_TYPE = arr[i].type;
                        var prod = arr[i];
                        order.PRODUCT_TYPE = prod.type;
                        order.PRODUCT_CODE = prod.code;
                        order.PRODUCT_NAME = prod.name;
                        order.PRICE = prod.price;
                        order.QTY = $scope.proItem['piece' + arr[i].productInfo.color + i];
                        order.TOTAL = order.QTY * order.PRICE;
                        order.IS_CAMPAIGN_PROMO_ITEM = 'N';
                        order.IS_PRODUCT_REQUESTFORM = 'N';
                        order.APPLECARE_CODE = null;

                        customerProfile.orderObj = {};
                        customerProfile.orderObj.order_product_item_list = [];

                        customerProfile.orderObj.order_product_item_list.push(order);

                    }

                }
                $localstorage.setObject("customerProfile", customerProfile);
                $localstorage.logObject("customerProfile");
                $location.path('/ordersummary');
            };
        };
    });
<commit_msg>product selector<commit_after>'use strict';

/**
 * @ngdoc function
 * @name fec3App.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the fec3App
 */
angular.module('fec3App')
    .controller('productSelectorCtrl', function($scope, $localstorage, $routeParams, $location, $modal) {

        $scope.id = $routeParams.id;
    $scope.name = $routeParams.name;
    $scope.productCode = null;
    $scope.productType = null;

        $scope.data = $modal.mathList();
        console.log($scope.data);
        //console.log($scope.ngDialogData);
        $scope.ngBootBoxClose = function() {

            bootbox.hideAll();
            // try {
            //     angular.element(document.getElementById('' + $('#divID').val())).scope().afterCloseWarning();
            // } catch (e) {}
        };

        $scope.proItem = {
            "pieceGold0": null
        };

        $scope.nextModal = function() {
            if ($scope.tabselected == "1") {
                $location.path('/promotion?productCode=' + $scope.productCode + '&productType=' + $scope.productType)
                if ($scope.productCode && $scope.productType) {
                    $location.path('/promotion').search({
                        id: $scope.id,
                        name: $scope.name,
                        productCode: $scope.productCode,
                        productType: $scope.productType
                    });
                }

            } else {
                var customerProfile = $localstorage.getObject("customerProfile");
                var orderList = [];
                var order = {};
                var arr = $scope.data.childs;
                var sum = 0;
                for (var i = 0; i < arr.length; i++) {
                    var sum_i = 0;

                    if ($scope.proItem['piece' + arr[i].productInfo.color + i] && $scope.proItem['piece' + arr[i].productInfo.color + i] > 0) {
                        console.log("Tingtang:" + arr[i]);
                        //var order.PRODUCT_TYPE = arr[i].type;
                        var prod = arr[i];
                        order.PRODUCT_TYPE = prod.type;
                        order.PRODUCT_CODE = prod.code;
                        order.PRODUCT_NAME = prod.name;
                        order.PRICE = prod.price;
                        order.QTY = $scope.proItem['piece' + arr[i].productInfo.color + i];
                        order.TOTAL = order.QTY * order.PRICE;
                        order.IS_CAMPAIGN_PROMO_ITEM = 'N';
                        order.IS_PRODUCT_REQUESTFORM = 'N';
                        order.APPLECARE_CODE = null;

                        customerProfile.orderObj = {};
                        customerProfile.orderObj.order_product_item_list = [];

                        customerProfile.orderObj.order_product_item_list.push(order);

                    }

                }
                $localstorage.setObject("customerProfile", customerProfile);
                $localstorage.logObject("customerProfile");
                $location.path('/ordersummary');
            };
        };
    });
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'

//路由
import index from '../components/index.vue'

//php
import php from '../components/php/index.vue'
import curl from '../components/php/curl.vue'

//zip
import zip from '../components/php/index.vue'
import json from '../components/zip/json'
import html from '../components/zip/html'
import javascript from '../components/zip/javascript'

//时间转换
import time from '../components/time/index.vue'

//qrcode
import qrcode from '../components/qrcode/index.vue'
//base64
import base64 from '../components/base64/index.vue'

//URI encode
import urlencode from '../components/url/encode.vue'

//翻译
import translation from '../components/translation.vue'

Vue.use(Router)

export default new Router({
  routes: [
  	{
	    path: '/',
	    name: 'index',
	    component: index
    },
    {
	    path: '/php',
	    // component: Foo,
	    component: php,
	    children: [
	      {path: 'curl', component: curl}
	    ]
  	},
  	{
	    path: '/zip',
	    // component: Foo,
	    component: zip,
	    children: [
	    	{path: 'html', component: html},
	    	{path: 'javascript', component: javascript},
	      	{path: 'json', component: json}
	    ]
  	},
  	{
	    path: '/time',
	    name: 'time',
	    component: time
  	},
  	{
	    path: '/qrcode',
	    name: 'qrcode',
	    component: qrcode
  	},
  	{
	    path: '/base64',
	    name: 'base64',
	    component: base64
  	},
  	{
	    path: '/encode',
	    name: 'encode',
	    component: urlencode
  	},
  	{
	    path: '/translation',
	    name: 'translation',
	    component: translation
  	}
  ]
})
<commit_msg>change router mode<commit_after>import Vue from 'vue'
import Router from 'vue-router'

//路由
import index from '../components/index.vue'

//php
import php from '../components/php/index.vue'
import curl from '../components/php/curl.vue'

//zip
import zip from '../components/php/index.vue'
import json from '../components/zip/json'
import html from '../components/zip/html'
import javascript from '../components/zip/javascript'

//时间转换
import time from '../components/time/index.vue'

//qrcode
import qrcode from '../components/qrcode/index.vue'
//base64
import base64 from '../components/base64/index.vue'

//URI encode
import urlencode from '../components/url/encode.vue'

//翻译
import translation from '../components/translation.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [
  	{
	    path: '/',
	    name: 'index',
	    component: index
    },
    {
	    path: '/php',
	    // component: Foo,
	    component: php,
	    children: [
	      {path: 'curl', component: curl}
	    ]
  	},
  	{
	    path: '/zip',
	    // component: Foo,
	    component: zip,
	    children: [
	    	{path: 'html', component: html},
	    	{path: 'javascript', component: javascript},
	      	{path: 'json', component: json}
	    ]
  	},
  	{
	    path: '/time',
	    name: 'time',
	    component: time
  	},
  	{
	    path: '/qrcode',
	    name: 'qrcode',
	    component: qrcode
  	},
  	{
	    path: '/base64',
	    name: 'base64',
	    component: base64
  	},
  	{
	    path: '/encode',
	    name: 'encode',
	    component: urlencode
  	},
  	{
	    path: '/translation',
	    name: 'translation',
	    component: translation
  	}
  ]
})
<|endoftext|>