<commit_before>// @flow

import { dirname, relative as relativePath, resolve as resolvePath } from 'path';
import { stat, readFile } from 'mz/fs';
import dotenv from 'dotenv';
import chalk from 'chalk';
import nodeExternals from 'webpack-node-externals';
import webpack from 'webpack';

import { createWebpackLoaders, createWebpackPlugins, loadEnvVariables } from './helpers';
import type { ServerManagerInterface } from './types';

export type WebpackConfig = {
  devtool: string,
  entry:
    | string
    | Array<string>
    | {
        [key: string]: string | Array<string>,
      },
  output: {
    filename: string,
    libraryTarget: string,
    path: string,
    publicPath: string,
  },
  module: {
    strictExportPresence: boolean,
    rules: Array<{
      enforce?: string,
      test:
        | string
        | RegExp
        | ((path: string) => boolean | Array<string | RegExp | (() => boolean)>),
      use?: Array<
        | string
        | {
          loader: string,
          options?: { [key: string]: any },
        },
      >,
      include?: string | Array<string> | RegExp | ((path: string) => boolean),
    }>,
  },
  plugins: Array<any>,
  target: string,
};

export type Configuration = {
  client: WebpackConfig,
  server: WebpackConfig,
};

type Args = {
  env: 'development' | 'production',
  serverManager?: ?ServerManagerInterface,
  srcDir: string,
  useBabili: boolean,
  workDir: string,
};

async function configure({
  env,
  serverManager,
  srcDir,
  useBabili,
  workDir,
}: Args): Promise<Configuration> {
  const isDev = env === 'development';
  const appDir = resolvePath(workDir, srcDir);
  const clientBundlePath = resolvePath(workDir, './bundle/client');
  const serverBundlePath = resolvePath(workDir, './bundle/server');

  const variables = {
    // provide full path to webpack-assets.json so you can easily load it server side
    ASSETS_JSON_PATH: resolvePath(serverBundlePath, 'webpack-assets.json'),
    ASSETS_PATH: clientBundlePath,
    CLIENT_BUNDLE_PATH: clientBundlePath,
    SERVER_BUNDLE_PATH: serverBundlePath,
    NODE_ENV: env,
    // for build.js this is not specified because we want user to have option to change it
    // PORT: process.env.PORT,
    ...(await loadEnvVariables(workDir)),
    // force port from start.js during development
    // because of proxying requests
    ...(isDev ? { PORT: process.env.PORT } : {}),
  };

  const envVariables = Object.keys(variables).reduce(
    (res, key) => ({ ...res, [`process.env.${key}`]: JSON.stringify(variables[key]) }),
    {},
  );

  return {
    client: {
      bail: !isDev,
      devtool: isDev ? 'cheap-module-source-map' : 'source-map',
      entry: [
        isDev ? require.resolve('react-dev-utils/webpackHotDevClient') : null,
        require.resolve('./polyfills/client'),
        /* isDev ? require.resolve('react-error-overlay') : null, */
        resolvePath(appDir, './client/index.js'),
      ].filter(Boolean),
      output: {
        filename: isDev ? 'static/js/[name].js' : 'static/js/[name].[chunkhash:8].js',
        chunkFilename: 'static/js/[name].[chunkhash:8].js',
        libraryTarget: 'var',
        path: clientBundlePath,
        pathinfo: isDev,
        publicPath: '/',
        devtoolModuleFilenameTemplate: isDev
          ? info => resolvePath(info.absoluteResourcePath)
          : info => relativePath(appDir, info.absoluteResourcePath),
      },
      resolve: {
        extensions: ['.js', '.json', '.jsx'],
        alias: {
          'babel-runtime': dirname(require.resolve('babel-runtime/package.json')),
        },
      },
      module: {
        strictExportPresence: true,
        rules: createWebpackLoaders({ appDir, isDev, isServer: false, useBabili }, envVariables),
      },
      node: {
        fs: 'empty',
        net: 'empty',
        tls: 'empty',
      },
      performance: isDev
        ? false
        : {
            hints: 'warning',
          },
      plugins: createWebpackPlugins(
        { isDev, isServer: false, clientBundlePath, serverBundlePath, serverManager, useBabili },
        envVariables,
      ),
      target: 'web',
    },
    server: {
      bail: !isDev,
      devtool: isDev ? 'eval' : 'source-map',
      entry: [
        isDev ? require.resolve('source-map-support/register') : null,
        isDev ? require.resolve('./helpers/serverWrapper') : null,
        require.resolve('./polyfills/server'),
        require.resolve('./helpers/provideVariables'),
        resolvePath(appDir, './server/index.js'),
      ].filter(Boolean),
      externals: [
        nodeExternals({
          whitelist: [
            /\.(eot|woff|woff2|ttf|otf)$/,
            /\.(svg|png|jpg|jpeg|gif|ico)$/,
            /\.(mp4|mp3|ogg|swf|webp)$/,
            /\.(css|scss|sass|sss|less)$/,
          ],
        }),
      ],
      output: {
        filename: 'server.js',
        libraryTarget: 'commonjs2',
        path: serverBundlePath,
        publicPath: '/',
        devtoolModuleFilenameTemplate: info => relativePath(appDir, info.absoluteResourcePath),
      },
      resolve: {
        extensions: ['.js', '.json', '.jsx'],
      },
      module: {
        strictExportPresence: true,
        rules: createWebpackLoaders({ appDir, isDev, isServer: true, useBabili }, envVariables),
      },
      node: {
        __dirname: true,
        __filename: true,
      },
      plugins: createWebpackPlugins(
        { isDev, isServer: true, clientBundlePath, serverBundlePath, serverManager, useBabili },
        envVariables,
      ),
      performance: false,
      target: 'node',
    },
  };
}

export default configure;<commit_msg>🔧 add resolve.modules configuration option<commit_after>// @flow

import { dirname, relative as relativePath, resolve as resolvePath } from 'path';
import { stat, readFile } from 'mz/fs';
import dotenv from 'dotenv';
import chalk from 'chalk';
import nodeExternals from 'webpack-node-externals';
import webpack from 'webpack';

import { createWebpackLoaders, createWebpackPlugins, loadEnvVariables } from './helpers';
import type { ServerManagerInterface } from './types';

export type WebpackConfig = {
  devtool: string,
  entry:
    | string
    | Array<string>
    | {
        [key: string]: string | Array<string>,
      },
  output: {
    filename: string,
    libraryTarget: string,
    path: string,
    publicPath: string,
  },
  module: {
    strictExportPresence: boolean,
    rules: Array<{
      enforce?: string,
      test:
        | string
        | RegExp
        | ((path: string) => boolean | Array<string | RegExp | (() => boolean)>),
      use?: Array<
        | string
        | {
          loader: string,
          options?: { [key: string]: any },
        },
      >,
      include?: string | Array<string> | RegExp | ((path: string) => boolean),
    }>,
  },
  plugins: Array<any>,
  target: string,
};

export type Configuration = {
  client: WebpackConfig,
  server: WebpackConfig,
};

type Args = {
  env: 'development' | 'production',
  serverManager?: ?ServerManagerInterface,
  srcDir: string,
  useBabili: boolean,
  workDir: string,
};

async function configure({
  env,
  serverManager,
  srcDir,
  useBabili,
  workDir,
}: Args): Promise<Configuration> {
  const isDev = env === 'development';
  const appDir = resolvePath(workDir, srcDir);
  const clientBundlePath = resolvePath(workDir, './bundle/client');
  const serverBundlePath = resolvePath(workDir, './bundle/server');

  const variables = {
    // provide full path to webpack-assets.json so you can easily load it server side
    ASSETS_JSON_PATH: resolvePath(serverBundlePath, 'webpack-assets.json'),
    ASSETS_PATH: clientBundlePath,
    CLIENT_BUNDLE_PATH: clientBundlePath,
    SERVER_BUNDLE_PATH: serverBundlePath,
    NODE_ENV: env,
    // for build.js this is not specified because we want user to have option to change it
    // PORT: process.env.PORT,
    ...(await loadEnvVariables(workDir)),
    // force port from start.js during development
    // because of proxying requests
    ...(isDev ? { PORT: process.env.PORT } : {}),
  };

  const envVariables = Object.keys(variables).reduce(
    (res, key) => ({ ...res, [`process.env.${key}`]: JSON.stringify(variables[key]) }),
    {},
  );

  return {
    client: {
      bail: !isDev,
      devtool: isDev ? 'cheap-module-source-map' : 'source-map',
      entry: [
        isDev ? require.resolve('react-dev-utils/webpackHotDevClient') : null,
        require.resolve('./polyfills/client'),
        /* isDev ? require.resolve('react-error-overlay') : null, */
        resolvePath(appDir, './client/index.js'),
      ].filter(Boolean),
      output: {
        filename: isDev ? 'static/js/[name].js' : 'static/js/[name].[chunkhash:8].js',
        chunkFilename: 'static/js/[name].[chunkhash:8].js',
        libraryTarget: 'var',
        path: clientBundlePath,
        pathinfo: isDev,
        publicPath: '/',
        devtoolModuleFilenameTemplate: isDev
          ? info => resolvePath(info.absoluteResourcePath)
          : info => relativePath(appDir, info.absoluteResourcePath),
      },
      resolve: {
        extensions: ['.js', '.json', '.jsx'],
        modules: ['node_modules', resolvePath(workDir, './node_modules')],
        alias: {
          'babel-runtime': dirname(require.resolve('babel-runtime/package.json')),
        },
      },
      module: {
        strictExportPresence: true,
        rules: createWebpackLoaders({ appDir, isDev, isServer: false, useBabili }, envVariables),
      },
      node: {
        fs: 'empty',
        net: 'empty',
        tls: 'empty',
      },
      performance: isDev
        ? false
        : {
            hints: 'warning',
          },
      plugins: createWebpackPlugins(
        { isDev, isServer: false, clientBundlePath, serverBundlePath, serverManager, useBabili },
        envVariables,
      ),
      target: 'web',
    },
    server: {
      bail: !isDev,
      devtool: isDev ? 'eval' : 'source-map',
      entry: [
        isDev ? require.resolve('source-map-support/register') : null,
        isDev ? require.resolve('./helpers/serverWrapper') : null,
        require.resolve('./polyfills/server'),
        require.resolve('./helpers/provideVariables'),
        resolvePath(appDir, './server/index.js'),
      ].filter(Boolean),
      externals: [
        nodeExternals({
          whitelist: [
            /\.(eot|woff|woff2|ttf|otf)$/,
            /\.(svg|png|jpg|jpeg|gif|ico)$/,
            /\.(mp4|mp3|ogg|swf|webp)$/,
            /\.(css|scss|sass|sss|less)$/,
          ],
        }),
      ],
      output: {
        filename: 'server.js',
        libraryTarget: 'commonjs2',
        path: serverBundlePath,
        publicPath: '/',
        devtoolModuleFilenameTemplate: info => relativePath(appDir, info.absoluteResourcePath),
      },
      resolve: {
        extensions: ['.js', '.json', '.jsx'],
        modules: ['node_modules', resolvePath(workDir, './node_modules')],
      },
      module: {
        strictExportPresence: true,
        rules: createWebpackLoaders({ appDir, isDev, isServer: true, useBabili }, envVariables),
      },
      node: {
        __dirname: true,
        __filename: true,
      },
      plugins: createWebpackPlugins(
        { isDev, isServer: true, clientBundlePath, serverBundlePath, serverManager, useBabili },
        envVariables,
      ),
      performance: false,
      target: 'node',
    },
  };
}

export default configure;
{'fraction_non_alphanumeric': 0.1443443268305485, 'fraction_numerical': 0.0010497769224039892, 'mean_word_length': 2.524044389642417, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2436003', 'n_tokens_mistral': 3464, 'n_tokens_neox': 3415, 'n_words': 757}