// karma-webpack doesn't exit on compile error.
// This plugin makes it exit on compile error.
class ExitOnErrorWebpackPlugin {
  apply(compiler) {
    compiler.hooks.done.tap('ExitOnErrorWebpackPlugin', (stats) => {
      if (stats && stats.hasErrors()) {
        stats.toJson().errors.forEach((error) => {
          console.error(error);
        });
        process.exit(1);
      }
    });
  }
}

/**
 * Blocks until the webpack config is read.
 */
function readWebpackConfig() {
  const argv = require('yargs').argv;
  const sleep = require('deasync').runLoopOnce;
  const maybeConfig = require('./webpack.config.js');
  const config = maybeConfig instanceof Function ? maybeConfig(null, argv) : maybeConfig;
  if (!(config instanceof Promise)) {
    return config;
  }

  let unwrappedConfig;
  config.then((result) => {
    unwrappedConfig = result;
  });

  while (!unwrappedConfig) {
    sleep();
  }

  return unwrappedConfig;
}

webpackConfig = readWebpackConfig();
webpackConfig['plugins'].push(new ExitOnErrorWebpackPlugin());
webpackConfig['mode'] = 'development';
webpackConfig['devtool'] = 'inline-source-map';
delete webpackConfig.optimization; // karma doesn't work with splitChunks...or runtimeChunk
delete webpackConfig.entry; // test runner doesn't use the entry points

const testIndex = './tests/karma/index.ts';

const files = [
  './public/js/vendor.js',
  './public/js/app-deps.js',
  './public/js/locales/en.js',
  './tests/karma/globals.js', // shims for tests
  testIndex,
];

const preprocessors = {};
preprocessors[testIndex] = ['webpack', 'sourcemap'];

module.exports = function (config) {
  config.set({
    autoWatch: true,
    basePath: '.',
    browsers: ['ChromeHeadless'],
    colors: true,
    concurrency: Infinity,
    exclude: [],
    frameworks: ['jasmine'],
    files: files,
    logLevel: config.LOG_INFO,
    mime: { 'text/x-typescript': ['ts', 'tsx'] },
    port: 9876,
    preprocessors: preprocessors,
    reporters: ['progress'],
    singleRun: false, // set to true for the process to exit after completing.
    webpack: webpackConfig,
    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only'
    },
  });
};

@@ -774,31 +774,21 @@
 %0A%0A  let 
-unwrappedConfig
+value
 ;%0A  conf
@@ -817,112 +817,179 @@
     
-unwrappedConfig = result;%0A  %7D);%0A%0A  while (!unwrappedConfig) %7B%0A    sleep();%0A  %7D%0A%0A  return unwrappedConfig
+value = result;%0A  %7D).catch((error) =%3E %7B%0A    value = error;%0A  %7D);%0A%0A  while (!value) %7B%0A    sleep();%0A  %7D%0A%0A  if (value instanceof Error) %7B%0A    throw value;%0A  %7D%0A%0A  return value
 ;%0A%7D%0A

throw if promise errored.