'use strict';

var cliNode = require('@backstage/cli-node');
var fs = require('fs-extra');
var index = require('./index-79e50cf7.cjs.js');
var chokidar = require('chokidar');
var path = require('path');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
var chokidar__default = /*#__PURE__*/_interopDefaultLegacy(chokidar);

async function findRoleFromCommand(opts) {
  var _a;
  if (opts.role) {
    return (_a = cliNode.PackageRoles.getRoleInfo(opts.role)) == null ? void 0 : _a.role;
  }
  const pkg = await fs__default["default"].readJson(index.paths.resolveTarget("package.json"));
  const info = cliNode.PackageRoles.getRoleFromPackage(pkg);
  if (!info) {
    throw new Error(`Target package must have 'backstage.role' set`);
  }
  return info;
}

const DETECTED_MODULES_MODULE_NAME = "__backstage-autodetected-plugins__";
function readPackageDetectionConfig(config) {
  const packages = config.getOptional("app.experimental.packages");
  if (packages === void 0 || packages === null) {
    return void 0;
  }
  if (typeof packages === "string") {
    if (packages !== "all") {
      throw new Error(
        `Invalid app.experimental.packages mode, got '${packages}', expected 'all'`
      );
    }
    return {};
  }
  return {
    include: config.getOptionalStringArray("app.experimental.packages.include"),
    exclude: config.getOptionalStringArray("app.experimental.packages.exclude")
  };
}
async function detectPackages(targetPath, { include, exclude }) {
  var _a;
  const pkg = await fs__default["default"].readJson(
    path.resolve(targetPath, "package.json")
  );
  return Object.keys((_a = pkg.dependencies) != null ? _a : {}).flatMap((depName) => {
    var _a2, _b;
    const depPackageJson = require(
      require.resolve(`${depName}/package.json`, { paths: [targetPath] })
    );
    if (["frontend-plugin", "frontend-plugin-module"].includes(
      (_b = (_a2 = depPackageJson.backstage) == null ? void 0 : _a2.role) != null ? _b : ""
    )) {
      return [depName];
    }
    return [];
  }).filter((name) => {
    if (exclude == null ? void 0 : exclude.includes(name)) {
      return false;
    }
    if (include && !include.includes(name)) {
      return false;
    }
    return true;
  });
}
async function writeDetectedPackagesModule(packageNames) {
  const requirePackageScript = packageNames == null ? void 0 : packageNames.map((pkg) => `{ name: '${pkg}', default: require('${pkg}').default }`).join(",");
  await fs__default["default"].writeFile(
    path.join(
      index.paths.targetRoot,
      "node_modules",
      `${DETECTED_MODULES_MODULE_NAME}.js`
    ),
    `window['__@backstage/discovered__'] = { modules: [${requirePackageScript}] };`
  );
}
async function createDetectedModulesEntryPoint(options) {
  const { config, watch, targetPath } = options;
  const detectionConfig = readPackageDetectionConfig(config);
  if (!detectionConfig) {
    return [];
  }
  if (watch) {
    const watcher = chokidar__default["default"].watch(path.resolve(targetPath, "package.json"));
    watcher.on("change", async () => {
      await writeDetectedPackagesModule(
        await detectPackages(targetPath, detectionConfig)
      );
      watch();
    });
  }
  await writeDetectedPackagesModule(
    await detectPackages(targetPath, detectionConfig)
  );
  return [DETECTED_MODULES_MODULE_NAME];
}

exports.createDetectedModulesEntryPoint = createDetectedModulesEntryPoint;
exports.findRoleFromCommand = findRoleFromCommand;
//# sourceMappingURL=packageDetection-2556dd6d.cjs.js.map
