All files wp.js

93.33% Statements 56/60
82.89% Branches 63/76
81.81% Functions 9/11
93.22% Lines 55/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 2142x 2x 2x 2x 2x 2x 2x 2x                       2x                                           2x                       7x         7x   7x 1x     1x 1x 1x   1x       1x       1x   1x   1x       1x         1x     1x 1x   1x   1x       7x                                   2x                     3x 1x 1x     2x 1x       1x     2x 1x   1x       1x     1x 1x     1x     1x           1x                               2x                   2x 1x 1x 1x 1x 1x     1x   1x         2x            
const path = require('path');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const { rimrafSync } = require('rimraf');
const { merge } = require('webpack-merge');
const { createFile, dynamicImport, errorMessageHandler, isPromise, OPTIONS } = require('./global');
const { color, consoleMessage } = require('./logger');
const { common, development, preprocessLoader, production } = require('./wpConfigs');
 
/**
 * @module webpack
 */
 
/**
 * Clean the "distribution" directory. Compensate for Webpack not cleaning output on development.
 *
 * @param {object} dotenv
 * @param {string} dotenv._BUILD_DIST_DIR
 */
const cleanDist = ({ _BUILD_DIST_DIR: DIST_DIR } = OPTIONS.dotenv || {}) => {
  rimrafSync(path.join(DIST_DIR, '*'), { glob: true });
};
 
// ToDo: review allowing mergeWithCustom
/**
 * Webpack merge base configuration files. If available merge extended configuration files.
 *
 * @param {object} options
 * @param {string} options.nodeEnv
 * @param {object} options.dotenv
 * @param {Array<string>} options.extendedConfigs
 * @param {object} settings
 * @param {Function} settings.consoleMessage
 * @param {Function} settings.dynamicImport
 * @param {Function} settings.isPromise
 * @param {Function} settings.webpackCommonConfig
 * @param {Function} settings.webpackDevelopmentConfig
 * @param {Function} settings.webpackPreprocessLoaderConfig
 * @param {Function} settings.webpackProductionConfig
 * @returns {Promise<object>}
 */
const createWpConfig = async (
  { nodeEnv, dotenv = {}, extendedConfigs } = OPTIONS,
  {
    consoleMessage: aliasConsoleMessage = consoleMessage,
    dynamicImport: aliasDynamicImport = dynamicImport,
    isPromise: aliasIsPromise = isPromise,
    webpackCommonConfig = common,
    webpackDevelopmentConfig = development,
    webpackPreprocessLoaderConfig = preprocessLoader,
    webpackProductionConfig = production
  } = {}
) => {
  const baseConfigs = [
    webpackCommonConfig(),
    webpackPreprocessLoaderConfig(),
    (nodeEnv === 'development' && webpackDevelopmentConfig()) || webpackProductionConfig()
  ];
  const extended = [];
 
  if (Array.isArray(extendedConfigs) && extendedConfigs?.length) {
    const result = await Promise.allSettled(extendedConfigs.map(arg => aliasDynamicImport(arg)));
 
    // Filter initial file results for fulfilled and actual values
    const filteredResults = result.filter(({ status, value }, index) => {
      const isFulfilled = status === 'fulfilled';
      const isValue = !!value;
 
      Iif (!isFulfilled || !isValue) {
        aliasConsoleMessage.warn(`Error loading, ${extendedConfigs[index]}`);
      }
 
      return isFulfilled && isValue;
    });
 
    // Run subsequent response promises, functions, or results again
    const parsedResults = await Promise.allSettled(
      filteredResults.map(({ value }) => {
        const defaultValue = value?.default || value;
 
        Iif (aliasIsPromise(defaultValue) || typeof defaultValue === 'function') {
          return defaultValue(dotenv);
        }
 
        return defaultValue;
      })
    );
 
    // Filter the subsequent promise, functions, or results again
    extended.push(
      ...parsedResults
        .filter(({ status, value }) => {
          const isFulfilled = status === 'fulfilled';
          const isValue = !!value;
 
          return isFulfilled && isValue;
        })
        .map(({ value }) => value)
    );
  }
 
  return merge(...baseConfigs, ...extended);
};
 
/**
 * webpack callback error and stats handler. Separated for testing.
 *
 * @param {*} err
 * @param {*} stats
 * @param {object} options
 * @param {undefined|string} options.stats
 * @param {undefined|string} options.statsFile
 * @param {undefined|string} options.statsPath
 * @param {object} settings
 * @param {object} settings.color
 * @param {Function} settings.consoleMessage
 * @param {Function} settings.createFile
 * @param {Function} settings.errorMessageHandler
 */
const startWpErrorStatsHandler = (
  err,
  stats,
  { stats: statsLevel, statsFile, statsPath } = OPTIONS,
  {
    color: aliasColor = color,
    consoleMessage: aliasConsoleMessage = consoleMessage,
    createFile: aliasCreateFile = createFile,
    errorMessageHandler: aliasErrorMessageHandler = errorMessageHandler
  } = {}
) => {
  if (err) {
    aliasConsoleMessage.error('Production build errors...', aliasErrorMessageHandler(err));
    return;
  }
 
  if (stats?.toJson && statsFile && statsPath) {
    aliasCreateFile(JSON.stringify(stats.toJson(statsLevel), null, 2), {
      dir: statsPath,
      filename: statsFile
    });
    aliasConsoleMessage.success('Stats file created');
  }
 
  if (stats?.hasErrors && stats.hasErrors()) {
    const compileErrors = aliasErrorMessageHandler(stats?.compilation?.errors);
 
    aliasConsoleMessage.error(
      'Production compile errors...',
      ...((Array.isArray(compileErrors) && compileErrors) || [compileErrors])
    );
    return;
  }
 
  Eif (stats?.toString) {
    const formattedStats = stats
      .toString(statsLevel)
      .split('\n')
      .map(v => (!/^\s*/.test(v) && ` * ${v}`) || `  ${v}`)
      .join('\n');
 
    aliasConsoleMessage.log(
      `Stats level ${aliasColor.YELLOW || ''}${statsLevel}${aliasColor.NOCOLOR || ''}...`,
      (formattedStats.trim() === '' && '  No stats output') || formattedStats
    );
  }
 
  aliasConsoleMessage.success('Build completed');
};
 
/**
 * Start webpack development or production.
 *
 * @param {object} webpackConfig
 * @param {object} options
 * @param {string} options.nodeEnv
 * @param {object} settings
 * @param {Function} settings.consoleMessage
 * @param {Function} settings.startWpErrorStatsHandler
 * @param {Function} settings.webpack
 * @param {Function} settings.WebpackDevServer
 * @returns {Promise<void>}
 */
const startWp = async (
  webpackConfig,
  { nodeEnv } = OPTIONS,
  {
    consoleMessage: aliasConsoleMessage = consoleMessage,
    startWpErrorStatsHandler: aliasStartWpErrorStatsHandler = startWpErrorStatsHandler,
    webpack: aliasWebpack = webpack,
    WebpackDevServer: AliasWebpackDevServer = WebpackDevServer
  } = {}
) => {
  if (webpackConfig?.devServer && nodeEnv === 'development') {
    aliasConsoleMessage.info('Development starting....');
    const compiler = aliasWebpack(webpackConfig);
    const server = new AliasWebpackDevServer(webpackConfig.devServer, compiler);
    await server.start();
    return;
  }
 
  aliasConsoleMessage.info('Production build starting....');
 
  aliasWebpack(webpackConfig, (err, stats) => {
    aliasStartWpErrorStatsHandler(err, stats);
  });
};
 
module.exports = {
  cleanDist,
  createWpConfig,
  startWp,
  startWpErrorStatsHandler
};