'use strict';

var index = require('./index-79e50cf7.cjs.js');
var packageDetection = require('./packageDetection-2556dd6d.cjs.js');
var config = require('./config-fab10260.cjs.js');
var fs = require('fs-extra');
var path = require('path');
var FileSizeReporter = require('react-dev-utils/FileSizeReporter');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var chalk = require('chalk');
var webpack = require('webpack');
var yn = require('yn');
require('react-dev-utils/openBrowser');
require('@backstage/cli-node');
require('lodash/uniq');
require('webpack-dev-server');
require('@yarnpkg/lockfile');
require('@yarnpkg/parsers');
require('semver');
require('chokidar');
var parallel = require('./parallel-0df0ea12.cjs.js');
require('commander');
require('@backstage/errors');
require('@backstage/cli-common');
require('react-dev-utils/ModuleScopePlugin');
require('@manypkg/get-packages');
require('eslint-webpack-plugin');
require('fork-ts-checker-webpack-plugin');
require('html-webpack-plugin');
require('lodash/pickBy');
require('child_process');
require('util');
require('@openshift/dynamic-plugin-sdk-webpack');
require('@pmmmwh/react-refresh-webpack-plugin');
require('mini-css-extract-plugin');
require('@backstage/config');
require('@backstage/config-loader');
require('os');
require('worker_threads');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
var formatWebpackMessages__default = /*#__PURE__*/_interopDefaultLegacy(formatWebpackMessages);
var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
var webpack__default = /*#__PURE__*/_interopDefaultLegacy(webpack);
var yn__default = /*#__PURE__*/_interopDefaultLegacy(yn);

const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
function applyContextToError(error, moduleName) {
  return `Failed to compile '${moduleName}':
  ${error}`;
}
async function buildBundle(options) {
  const { statsJsonEnabled, schema: configSchema } = options;
  const paths = config.resolveBundlingPaths(options);
  const detectedModulesEntryPoint = await packageDetection.createDetectedModulesEntryPoint({
    config: options.fullConfig,
    targetPath: paths.targetPath
  });
  const config$1 = await config.createConfig(paths, {
    ...options,
    checksEnabled: false,
    isDev: false,
    baseUrl: config.resolveBaseUrl(options.frontendConfig),
    getFrontendAppConfigs: () => options.frontendAppConfigs,
    additionalEntryPoints: detectedModulesEntryPoint
  });
  const isCi = yn__default["default"](process.env.CI, { default: false });
  const previousFileSizes = await FileSizeReporter.measureFileSizesBeforeBuild(paths.targetDist);
  await fs__default["default"].emptyDir(paths.targetDist);
  if (paths.targetPublic) {
    await fs__default["default"].copy(paths.targetPublic, paths.targetDist, {
      dereference: true,
      filter: (file) => file !== paths.targetHtml
    });
  }
  if (configSchema) {
    await fs__default["default"].writeJson(
      path.resolve(paths.targetDist, ".config-schema.json"),
      configSchema.serialize(),
      { spaces: 2 }
    );
  }
  const { stats } = await build(config$1, isCi);
  if (!stats) {
    throw new Error("No stats returned");
  }
  if (statsJsonEnabled) {
    await require("bfj").write(
      path.resolve(paths.targetDist, "bundle-stats.json"),
      stats.toJson()
    );
  }
  FileSizeReporter.printFileSizesAfterBuild(
    stats,
    previousFileSizes,
    paths.targetDist,
    WARN_AFTER_BUNDLE_GZIP_SIZE,
    WARN_AFTER_CHUNK_GZIP_SIZE
  );
}
async function build(config, isCi) {
  var _a, _b, _c;
  const stats = await new Promise(
    (resolve, reject) => {
      webpack__default["default"](config, (err, buildStats) => {
        if (err) {
          if (err.message) {
            const { errors: errors2 } = formatWebpackMessages__default["default"]({
              errors: [err.message],
              warnings: new Array(),
              _showErrors: true,
              _showWarnings: true
            });
            throw new Error(errors2[0]);
          } else {
            reject(err);
          }
        } else {
          resolve(buildStats);
        }
      });
    }
  );
  if (!stats) {
    throw new Error("Failed to compile: No stats provided");
  }
  const serializedStats = stats.toJson({
    all: false,
    warnings: true,
    errors: true
  });
  const { errors, warnings } = formatWebpackMessages__default["default"]({
    errors: serializedStats.errors,
    warnings: serializedStats.warnings
  });
  if (errors.length) {
    const errorWithContext = applyContextToError(
      errors[0],
      (_c = (_b = (_a = serializedStats.errors) == null ? void 0 : _a[0]) == null ? void 0 : _b.moduleName) != null ? _c : ""
    );
    throw new Error(errorWithContext);
  }
  if (isCi && warnings.length) {
    const warningsWithContext = warnings.map((warning, i) => {
      var _a2, _b2, _c2;
      return applyContextToError(
        warning,
        (_c2 = (_b2 = (_a2 = serializedStats.warnings) == null ? void 0 : _a2[i]) == null ? void 0 : _b2.moduleName) != null ? _c2 : ""
      );
    });
    console.log(
      chalk__default["default"].yellow(
        "\nTreating warnings as errors because process.env.CI = true.\n"
      )
    );
    throw new Error(warningsWithContext.join("\n\n"));
  }
  return { stats };
}

async function buildFrontend(options) {
  const { targetDir, writeStats, configPaths, pluginMetadata } = options;
  const { name } = await fs__default["default"].readJson(path.resolve(targetDir, "package.json"));
  await buildBundle({
    targetDir,
    entry: "src/index",
    parallelism: parallel.getEnvironmentParallelism(),
    statsJsonEnabled: writeStats,
    pluginMetadata,
    ...await config.loadCliConfig({
      args: configPaths,
      fromPackage: name
    })
  });
}

async function command(opts) {
  const role = await packageDetection.findRoleFromCommand(opts);
  const configPaths = opts.config.map((arg) => {
    if (config.isValidUrl(arg)) {
      return arg;
    }
    return index.paths.resolveTarget(arg);
  });
  if (role === "frontend") {
    return buildFrontend({
      targetDir: index.paths.targetDir,
      configPaths,
      writeStats: Boolean(opts.stats)
    });
  }
  throw new Error(
    "Package role not supported, please use 'backstage-cli' instead"
  );
}

exports.command = command;
//# sourceMappingURL=index-94733ad0.cjs.js.map
