'use strict';

var chalk = require('chalk');
var commander = require('commander');
var errors = require('@backstage/errors');
var fs = require('fs-extra');
var semver = require('semver');
var cliCommon = require('@backstage/cli-common');

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

var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
var semver__default = /*#__PURE__*/_interopDefaultLegacy(semver);

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
class CustomError extends Error {
  get name() {
    return this.constructor.name;
  }
}
class ExitCodeError extends CustomError {
  constructor(code, command) {
    super(
      command ? `Command '${command}' exited with code ${code}` : `Child exited with code ${code}`
    );
    __publicField(this, "code");
    this.code = code;
  }
}
function exitWithError(error) {
  if (error instanceof ExitCodeError) {
    process.stderr.write(`
${chalk__default["default"].red(error.message)}

`);
    process.exit(error.code);
  } else {
    process.stderr.write(`
${chalk__default["default"].red(`${error}`)}

`);
    process.exit(1);
  }
}

const configOption = [
  "--config <path>",
  "Config files to load instead of app-config.yaml",
  (opt, opts) => opts ? [...opts, opt] : [opt],
  Array()
];
function registerScriptCommand(program) {
  const command = program.command("package [command]").description("Lifecycle scripts for individual packages");
  command.command("start").description("Start a package for local development").option(...configOption).option("--role <name>", "Run the command with an explicit package role").option("--check", "Enable type checking and linting if available").option("--inspect", "Enable debugger in Node.js environments").option(
    "--inspect-brk",
    "Enable debugger in Node.js environments, breaking before code starts"
  ).action(lazy(() => Promise.resolve().then(function () { return require('./index-2135e357.cjs.js'); }).then((m) => m.command)));
  command.command("build").description("Build a package for production deployment or publishing").option("--role <name>", "Run the command with an explicit package role").option(
    "--minify",
    "Minify the generated code. Does not apply to app or backend packages."
  ).option(
    "--experimental-type-build",
    "Enable experimental type build. Does not apply to app or backend packages. [DEPRECATED]"
  ).option(
    "--skip-build-dependencies",
    "Skip the automatic building of local dependencies. Applies to backend packages only."
  ).option(
    "--stats",
    "If bundle stats are available, write them to the output directory. Applies to app packages only."
  ).option(
    "--config <path>",
    "Config files to load instead of app-config.yaml. Applies to app packages only.",
    (opt, opts) => opts ? [...opts, opt] : [opt],
    Array()
  ).action(lazy(() => Promise.resolve().then(function () { return require('./index-94733ad0.cjs.js'); }).then((m) => m.command)));
  command.command("export-dynamic-plugin").description(
    "Build and export a plugin package to be loaded as a dynamic plugin. The repackaged dynamic plugin is exported inside a ./dist-dynamic sub-folder."
  ).option("--minify", "Minify the generated code (backend plugin only).").option(
    "--embed-package [package-name...]",
    "Optional list of packages that should be embedded inside the generated code of a backend dynamic plugin, removed from the plugin dependencies, while their direct dependencies will be hoisted to the dynamic plugin dependencies (backend plugin only)."
  ).option(
    "--shared-package [package-name...]",
    "Optional list of packages that should be considered shared by all dynamic plugins, and will be moved to peer dependencies of the dynamic plugin. The `@backstage` packages are by default considered shared dependencies."
  ).option(
    "--override-interop <mode:package-name,package-name...>",
    "Optional list of packages for which the CommonJS Rollup output interop mode should be overridden to `mode` when building the dynamic plugin assets (backend plugin only).",
    (value, previous) => {
      const [key, val] = value.split(":");
      if (!["auto", "esModule", "default", "defaultOnly"].includes(key)) {
        throw new commander.InvalidArgumentError(
          `Invalid interop mode '${key}'. Possible values are: auto, esModule, default, defaultOnly (see https://rollupjs.org/configuration-options/#output-interop).`
        );
      }
      return { ...previous, [key]: (val == null ? void 0 : val.split(",")) || [] };
    },
    {}
  ).option(
    "--no-install",
    "Do not run `yarn install` to fill the dynamic plugin `node_modules` folder (backend plugin only)."
  ).option(
    "--clean",
    "Remove the dynamic plugin output before exporting again."
  ).option(
    "--dev",
    "Allow testing/debugging a backend plugin dynamic loading locally. This installs the dynamic plugin content (symlink) into the dynamic plugins root folder configured in the app config. This also creates a link from the dynamic plugin content to the plugin package `src` folder, to enable the use of source maps (backend plugin only)."
  ).action(lazy(() => Promise.resolve().then(function () { return require('./index-a465af1b.cjs.js'); }).then((m) => m.command)));
  command.command("schema").description("Print configuration schema for a package").action(lazy(() => Promise.resolve().then(function () { return require('./index-3f8700da.cjs.js'); }).then((m) => m.default)));
}
function registerCommands(program) {
  program.command("new").storeOptionsAsProperties(false).description(
    "Open up an interactive guide to creating new things in your app"
  ).option(
    "--select <name>",
    "Select the thing you want to be creating upfront"
  ).option(
    "--option <name>=<value>",
    "Pre-fill options for the creation process",
    (opt, arr) => [...arr, opt],
    []
  ).option(
    "--npm-registry <URL>",
    "The package registry to use for new packages"
  ).option(
    "--baseVersion <version>",
    "The version to use for any new packages (default: 0.1.0)"
  ).option("--no-private", "Do not mark new packages as private").option(
    "--do-not-edit-packages",
    "Do not edit packages/app and packages/backend"
  ).action(lazy(() => Promise.resolve().then(function () { return require('./new-a9a0e75f.cjs.js'); }).then((m) => m.default)));
  registerScriptCommand(program);
}
function lazy(getActionFunc) {
  return async (...args) => {
    try {
      const actionFunc = await getActionFunc();
      await actionFunc(...args);
      process.exit(0);
    } catch (error) {
      errors.assertError(error);
      exitWithError(error);
    }
  };
}

var name = "@janus-idp/cli";
var description = "CLI for developing Backstage plugins and apps";
var version$1 = "1.7.0";
var publishConfig = {
	access: "public"
};
var backstage = {
	role: "cli"
};
var homepage = "https://janus-idp.io";
var repository = {
	type: "git",
	url: "https://github.com/janus-idp/backstage-plugins",
	directory: "packages/cli"
};
var keywords = [
	"backstage"
];
var license = "Apache-2.0";
var main$1 = "dist/index.cjs.js";
var scripts = {
	build: "backstage-cli package build",
	lint: "backstage-cli package lint",
	tsc: "tsc",
	test: "backstage-cli package test --passWithNoTests --coverage",
	clean: "backstage-cli package clean",
	start: "nodemon --"
};
var bin = {
	"janus-cli": "bin/janus-cli"
};
var dependencies = {
	"@backstage/cli-common": "^0.1.13",
	"@backstage/cli-node": "^0.1.5",
	"@backstage/config": "^1.1.1",
	"@backstage/config-loader": "^1.5.1",
	"@backstage/errors": "^1.2.3",
	"@backstage/eslint-plugin": "^0.1.3",
	"@backstage/types": "^1.1.1",
	"@manypkg/get-packages": "^1.1.3",
	"@openshift/dynamic-plugin-sdk-webpack": "^3.0.0",
	"@pmmmwh/react-refresh-webpack-plugin": "^0.5.7",
	"@rollup/plugin-commonjs": "^25.0.4",
	"@rollup/plugin-json": "^6.0.0",
	"@rollup/plugin-node-resolve": "^15.2.1",
	"@rollup/plugin-yaml": "^4.0.0",
	"@svgr/rollup": "^8.1.0",
	"@svgr/webpack": "^6.5.1",
	"@yarnpkg/lockfile": "^1.1.0",
	"@yarnpkg/parsers": "^3.0.0-rc.4",
	bfj: "^7.0.2",
	chalk: "^4.0.0",
	chokidar: "^3.3.1",
	commander: "^9.1.0",
	"css-loader": "^6.5.1",
	esbuild: "^0.19.0",
	"esbuild-loader": "^2.18.0",
	eslint: "^8.49.0",
	"eslint-config-prettier": "^8.10.0",
	"eslint-webpack-plugin": "^3.2.0",
	express: "^4.18.2",
	"fork-ts-checker-webpack-plugin": "^7.0.0-alpha.8",
	"fs-extra": "^10.1.0",
	handlebars: "^4.7.7",
	"html-webpack-plugin": "^5.3.1",
	inquirer: "^8.2.0",
	lodash: "^4.17.21",
	"mini-css-extract-plugin": "^2.4.2",
	"node-libs-browser": "^2.2.1",
	"npm-packlist": "^5.0.0",
	ora: "^5.3.0",
	postcss: "^8.2.13",
	process: "^0.11.10",
	"react-dev-utils": "^12.0.0-next.60",
	"react-refresh": "^0.14.0",
	"recursive-readdir": "^2.2.2",
	rollup: "^2.78.0",
	"rollup-plugin-dts": "^4.0.1",
	"rollup-plugin-esbuild": "^4.7.2",
	"rollup-plugin-postcss": "^4.0.0",
	"rollup-pluginutils": "^2.8.2",
	semver: "^7.5.4",
	"style-loader": "^3.3.1",
	"swc-loader": "^0.2.3",
	"typescript-json-schema": "^0.62.0",
	webpack: "^5.89.0",
	"webpack-dev-server": "^4.15.1",
	"yml-loader": "^2.1.0",
	yn: "^4.0.0"
};
var devDependencies = {
	"@backstage/backend-common": "0.19.8",
	"@backstage/backend-plugin-api": "0.6.6",
	"@backstage/backend-test-utils": "0.2.7",
	"@backstage/cli": "0.23.0",
	"@backstage/core-app-api": "1.11.0",
	"@backstage/core-components": "0.13.6",
	"@backstage/core-plugin-api": "1.7.0",
	"@backstage/dev-utils": "1.0.22",
	"@backstage/plugin-scaffolder-backend": "1.18.0",
	"@backstage/plugin-scaffolder-node": "0.2.6",
	"@backstage/test-utils": "1.4.4",
	"@backstage/theme": "0.4.3",
	"@types/express": "4.17.20",
	"@types/fs-extra": "9.0.1",
	"@types/inquirer": "8.1.3",
	"@types/mock-fs": "4.13.4",
	"@types/node": "18.18.5",
	"@types/npm-packlist": "3.0.0",
	"@types/recursive-readdir": "2.2.0",
	"@types/rollup-plugin-postcss": "3.1.4",
	"@types/yarnpkg__lockfile": "1.1.4",
	"mock-fs": "5.2.0",
	msw: "1.3.2",
	nodemon: "3.0.1",
	"ts-node": "10.0.0",
	"type-fest": "4.3.1"
};
var peerDependencies = {
	"@microsoft/api-extractor": "^7.21.2"
};
var peerDependenciesMeta = {
	"@microsoft/api-extractor": {
		optional: true
	}
};
var files = [
	"asset-types",
	"templates",
	"config",
	"bin",
	"dist/**/*.js"
];
var nodemonConfig = {
	watch: "./src",
	exec: "bin/janus-cli",
	ext: "ts"
};
var configSchema = {
	$schema: "https://backstage.io/schema/config-v1",
	title: "@janus-idp/cli",
	type: "object",
	properties: {
		app: {
			type: "object",
			properties: {
				baseUrl: {
					type: "string",
					visibility: "frontend"
				},
				title: {
					type: "string",
					visibility: "frontend"
				},
				datadogRum: {
					type: "object",
					description: "Datadog RUM events configuration",
					properties: {
						env: {
							type: "string",
							visibility: "frontend",
							description: "Environment for Datadog RUM events"
						},
						clientToken: {
							type: "string",
							visibility: "frontend",
							description: "clientToken for Datadog RUM events"
						},
						applicationId: {
							type: "string",
							visibility: "frontend",
							description: "applicationId for Datadog RUM events"
						},
						site: {
							type: "string",
							visibility: "frontend",
							description: "site for Datadog RUM events"
						}
					},
					required: [
						"clientToken",
						"applicationId"
					]
				},
				listen: {
					type: "object",
					description: "Listening configuration for local development",
					properties: {
						host: {
							type: "string",
							visibility: "frontend",
							description: "The host that the frontend should be bound to. Only used for local development."
						},
						port: {
							type: "number",
							visibility: "frontend",
							description: "The port that the frontend should be bound to. Only used for local development."
						}
					}
				},
				https: {
					type: "object",
					description: "Only used for local development. The https object is passed to webpack in order to enable using https on localhost.",
					properties: {
						certificate: {
							type: "object",
							description: "Parent object containing certificate and the private key",
							required: [
								"key",
								"cert"
							],
							properties: {
								key: {
									type: "string",
									visibility: "secret",
									description: "Https Certificate private key. Use $file to load in a file"
								},
								cert: {
									type: "string",
									visibility: "secret",
									description: "Https Certificate. Use $file to load in a file"
								}
							}
						}
					}
				}
			}
		}
	}
};
var Manifest = {
	name: name,
	description: description,
	version: version$1,
	publishConfig: publishConfig,
	backstage: backstage,
	homepage: homepage,
	repository: repository,
	keywords: keywords,
	license: license,
	main: main$1,
	scripts: scripts,
	bin: bin,
	dependencies: dependencies,
	devDependencies: devDependencies,
	peerDependencies: peerDependencies,
	peerDependenciesMeta: peerDependenciesMeta,
	files: files,
	nodemonConfig: nodemonConfig,
	configSchema: configSchema
};

const paths = cliCommon.findPaths(__dirname);

function findVersion() {
  const pkgContent = fs__default["default"].readFileSync(paths.resolveOwn("package.json"), "utf8");
  return JSON.parse(pkgContent).version;
}
const version = findVersion();
const packageVersions = {
  ...Object.fromEntries(
    Object.entries(Manifest.devDependencies).filter(
      ([k, _v]) => k.startsWith("@backstage/")
    )
  ),
  ...Object.fromEntries(
    Object.entries(Manifest.dependencies).filter(
      ([k, _v]) => k.startsWith("@backstage/")
    )
  ),
  "@janus-idp/cli": version
};
function createPackageVersionProvider(lockfile) {
  return (name, versionHint) => {
    var _a;
    const packageVersion = packageVersions[name];
    const targetVersion = versionHint || packageVersion;
    if (!targetVersion) {
      throw new Error(`No version available for package ${name}`);
    }
    const lockfileEntries = lockfile == null ? void 0 : lockfile.get(name);
    if (name.startsWith("@types/") && (lockfileEntries == null ? void 0 : lockfileEntries.some((entry) => entry.range === "*"))) {
      return "*";
    }
    for (const specifier of ["^", "~", "*"]) {
      const range = `workspace:${specifier}`;
      if (lockfileEntries == null ? void 0 : lockfileEntries.some((entry) => entry.range === range)) {
        return range;
      }
    }
    const validRanges = lockfileEntries == null ? void 0 : lockfileEntries.filter(
      (entry) => semver__default["default"].satisfies(targetVersion, entry.range)
    );
    const highestRange = validRanges == null ? void 0 : validRanges.slice(-1)[0];
    if (highestRange == null ? void 0 : highestRange.range) {
      return highestRange == null ? void 0 : highestRange.range.replace(/^\^/, "");
    }
    if (packageVersion) {
      return packageVersion.replace(/^\^/, "");
    }
    if ((_a = semver__default["default"].parse(versionHint)) == null ? void 0 : _a.prerelease.length) {
      return versionHint;
    }
    return versionHint.replace(/^\^/, "");
  };
}

const main = (argv) => {
  commander.program.name("janus-cli").version(version);
  registerCommands(commander.program);
  commander.program.on("command:*", () => {
    console.log();
    console.log(chalk__default["default"].red(`Invalid command: ${commander.program.args.join(" ")}`));
    console.log();
    commander.program.outputHelp();
    process.exit(1);
  });
  commander.program.parse(argv);
};
process.on("unhandledRejection", (rejection) => {
  if (rejection instanceof Error) {
    exitWithError(rejection);
  } else {
    exitWithError(new Error(`Unknown rejection: '${rejection}'`));
  }
});
main(process.argv);

exports.ExitCodeError = ExitCodeError;
exports.createPackageVersionProvider = createPackageVersionProvider;
exports.paths = paths;
exports.version = version;
//# sourceMappingURL=index-79e50cf7.cjs.js.map