"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.bundle = bundle;
var _webpack = _interopRequireDefault(require("webpack"));
var _makeCompilerConfig = require("../common/config/makeCompilerConfig.js");
var _error = require("../common/error.js");
var _index = require("../common/index.js");
var _setupEnvironment = require("../common/setupEnvironment.js");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
 * Bundle command for React Native Community CLI.
 * It runs Webpack, builds bundle and saves it alongside any other assets and Source Map
 * to filesystem.
 *
 * @param _ Original, non-parsed arguments that were provided when running this command.
 * @param config React Native Community CLI configuration object.
 * @param args Parsed command line arguments.
 *
 * @internal
 * @category CLI command
 */
async function bundle(_, cliConfig, args) {
  const [config] = await (0, _makeCompilerConfig.makeCompilerConfig)({
    args: args,
    bundler: 'webpack',
    command: 'bundle',
    rootDir: cliConfig.root,
    platforms: [args.platform],
    reactNativePath: cliConfig.reactNativePath
  });

  // expose selected args as environment variables
  (0, _setupEnvironment.setupEnvironment)(args);
  if (!args.entryFile && !config.entry) {
    throw new _error.CLIError("Option '--entry-file <path>' argument is missing");
  }
  const errorHandler = async (error, stats) => {
    if (error) {
      throw new _error.CLIError(error.message);
    }
    if (stats?.hasErrors()) {
      stats.compilation?.errors?.forEach(e => {
        console.error(e);
      });
      process.exit(2);
    }
    if (args.json && stats !== undefined) {
      const statsOptions = (0, _index.normalizeStatsOptions)(compiler.options.stats, args.stats);
      const statsJson = stats.toJson(statsOptions);
      try {
        await (0, _index.writeStats)(statsJson, {
          filepath: args.json,
          rootDir: compiler.context
        });
      } catch (e) {
        throw new _error.CLIError(String(e));
      }
    }
  };
  const compiler = (0, _webpack.default)(config);
  return new Promise(resolve => {
    if (args.watch) {
      compiler.hooks.watchClose.tap('bundle', resolve);
      compiler.watch(config.watchOptions ?? {}, errorHandler);
    } else {
      compiler.run((error, stats) => {
        // make cache work: https://webpack.js.org/api/node/#run
        compiler.close(async closeErr => {
          if (closeErr) console.error(closeErr);
          await errorHandler(error, stats);
          resolve();
        });
      });
    }
  });
}
//# sourceMappingURL=bundle.js.map