'use strict';

var fs = require('fs-extra');
var path = require('path');
var webpack = require('webpack');
require('eslint-webpack-plugin');
require('fork-ts-checker-webpack-plugin');
require('html-webpack-plugin');
require('@backstage/cli-common');
require('react-dev-utils/ModuleScopePlugin');
require('run-script-webpack-plugin');
require('./index-CCLafGQH.cjs.js');
require('@manypkg/get-packages');
require('webpack-node-externals');
var packageDetection = require('./packageDetection-C__AGK-g.cjs.js');
require('lodash/pickBy');
require('./run-BcxUFacd.cjs.js');
require('mini-css-extract-plugin');
require('@pmmmwh/react-refresh-webpack-plugin');
var yn = require('yn');
var FileSizeReporter = require('react-dev-utils/FileSizeReporter');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var chalk = require('chalk');
require('@backstage/cli-node');
require('lodash/uniq');
require('react-dev-utils/openBrowser');
require('webpack-dev-server');
require('semver');
require('@yarnpkg/parsers');
require('@yarnpkg/lockfile');
require('minimatch');
require('./yarn-BDZCENk5.cjs.js');
require('lodash/partition');
var config = require('./config-OeQcmdz6.cjs.js');
var parallel = require('./parallel-BszNaKyc.cjs.js');
var os = require('os');
var tar = require('tar');
var createDistWorkspace = require('./createDistWorkspace-CLrZPAfL.cjs.js');

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

var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
var webpack__default = /*#__PURE__*/_interopDefaultCompat(webpack);
var yn__default = /*#__PURE__*/_interopDefaultCompat(yn);
var formatWebpackMessages__default = /*#__PURE__*/_interopDefaultCompat(formatWebpackMessages);
var chalk__default = /*#__PURE__*/_interopDefaultCompat(chalk);
var os__default = /*#__PURE__*/_interopDefaultCompat(os);
var tar__default = /*#__PURE__*/_interopDefaultCompat(tar);

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 = packageDetection.resolveBundlingPaths(options);
  const publicPaths = await packageDetection.resolveOptionalBundlingPaths({
    entry: "src/index-public-experimental",
    dist: "dist/public"
  });
  const detectedModulesEntryPoint = await packageDetection.createDetectedModulesEntryPoint({
    config: options.fullConfig,
    targetPath: paths.targetPath
  });
  const commonConfigOptions = {
    ...options,
    checksEnabled: false,
    isDev: false,
    getFrontendAppConfigs: () => options.frontendAppConfigs
  };
  const configs = [
    await packageDetection.createConfig(paths, {
      ...commonConfigOptions,
      additionalEntryPoints: detectedModulesEntryPoint,
      appMode: publicPaths ? "protected" : "public"
    })
  ];
  if (publicPaths) {
    console.log(
      chalk__default.default.yellow(
        `\u26A0\uFE0F  WARNING: The app /public entry point is an experimental feature that may receive immediate breaking changes.`
      )
    );
    configs.push(
      await packageDetection.createConfig(publicPaths, {
        ...commonConfigOptions,
        appMode: "public"
      })
    );
  }
  const isCi = yn__default.default(process.env.CI, { default: false });
  const previousFileSizes = await FileSizeReporter.measureFileSizesBeforeBuild(paths.targetDist);
  const previousAuthSizes = publicPaths ? await FileSizeReporter.measureFileSizesBeforeBuild(publicPaths.targetDist) : void 0;
  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 (publicPaths) {
      await fs__default.default.copy(paths.targetPublic, publicPaths.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(configs, isCi);
  if (!stats) {
    throw new Error("No stats returned");
  }
  const [mainStats, authStats] = stats.stats;
  if (statsJsonEnabled) {
    await require("bfj").write(
      path.resolve(paths.targetDist, "bundle-stats.json"),
      mainStats.toJson()
    );
  }
  FileSizeReporter.printFileSizesAfterBuild(
    mainStats,
    previousFileSizes,
    paths.targetDist,
    WARN_AFTER_BUNDLE_GZIP_SIZE,
    WARN_AFTER_CHUNK_GZIP_SIZE
  );
  if (publicPaths && previousAuthSizes) {
    FileSizeReporter.printFileSizesAfterBuild(
      authStats,
      previousAuthSizes,
      publicPaths.targetDist,
      WARN_AFTER_BUNDLE_GZIP_SIZE,
      WARN_AFTER_CHUNK_GZIP_SIZE
    );
  }
}
async function build(configs, isCi) {
  var _a, _b, _c;
  const stats = await new Promise(
    (resolve, reject) => {
      webpack__default.default(configs, (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 } = options;
  const { name } = await fs__default.default.readJson(path.resolve(targetDir, "package.json"));
  await buildBundle({
    targetDir,
    entry: "src/index",
    parallelism: parallel.getEnvironmentParallelism(),
    statsJsonEnabled: writeStats,
    ...await config.loadCliConfig({
      args: configPaths,
      fromPackage: name
    })
  });
}

const BUNDLE_FILE = "bundle.tar.gz";
const SKELETON_FILE = "skeleton.tar.gz";
async function buildBackend(options) {
  const { targetDir, skipBuildDependencies, configPaths, minify } = options;
  const pkg = await fs__default.default.readJson(path.resolve(targetDir, "package.json"));
  await createDistWorkspace.buildPackage({
    targetDir,
    packageJson: pkg,
    outputs: /* @__PURE__ */ new Set([createDistWorkspace.Output.cjs]),
    minify
  });
  const tmpDir = await fs__default.default.mkdtemp(path.resolve(os__default.default.tmpdir(), "backstage-bundle"));
  try {
    await createDistWorkspace.createDistWorkspace([pkg.name], {
      targetDir: tmpDir,
      configPaths,
      buildDependencies: !skipBuildDependencies,
      buildExcludes: [pkg.name],
      parallelism: parallel.getEnvironmentParallelism(),
      skeleton: SKELETON_FILE,
      minify
    });
    const distDir = path.resolve(targetDir, "dist");
    await fs__default.default.remove(distDir);
    await fs__default.default.mkdir(distDir);
    await fs__default.default.move(
      path.resolve(tmpDir, SKELETON_FILE),
      path.resolve(distDir, SKELETON_FILE)
    );
    await tar__default.default.create(
      {
        file: path.resolve(distDir, BUNDLE_FILE),
        cwd: tmpDir,
        portable: true,
        noMtime: true,
        gzip: true
      },
      [""]
    );
  } finally {
    await fs__default.default.remove(tmpDir);
  }
}

exports.buildBackend = buildBackend;
exports.buildFrontend = buildFrontend;
//# sourceMappingURL=buildBackend-Cv6N14cB.cjs.js.map
