File "cli.js"

Full Path: /home/u165092617/domains/tadzz.com/public_html/admin/cli.js
File size: 348.58 KB
MIME-type: application/javascript
Charset: utf-8

#!/usr/bin/env node
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};

// libs/core/src/lib/collect-uncommitted.ts
function collectUncommitted({ cwd, log: log36 = import_npmlog.default }) {
  log36.silly("collect-uncommitted", "git status --porcelain (async)");
  return childProcess.exec("git", ["status", "--porcelain"], { cwd }).then(({ stdout }) => transformOutput(stdout));
}
var import_chalk, import_npmlog, childProcess, maybeColorize, cRed, cGreen, replaceStatus, colorizeStats, splitOnNewLine, filterEmpty, o, transformOutput;
var init_collect_uncommitted = __esm({
  "libs/core/src/lib/collect-uncommitted.ts"() {
    "use strict";
    import_chalk = __toESM(require("chalk"));
    import_npmlog = __toESM(require("npmlog"));
    childProcess = require("@lerna/child-process");
    maybeColorize = (colorize) => (s) => s !== " " ? colorize(s) : s;
    cRed = maybeColorize(import_chalk.default.red);
    cGreen = maybeColorize(import_chalk.default.green);
    replaceStatus = (_, maybeGreen, maybeRed) => `${cGreen(maybeGreen)}${cRed(maybeRed)}`;
    colorizeStats = (stats) => stats.replace(/^([^U]| )([A-Z]| )/gm, replaceStatus).replace(/^\?{2}|U{2}/gm, cRed("$&"));
    splitOnNewLine = (str) => str.split("\n");
    filterEmpty = (lines) => lines.filter((line) => line.length);
    o = (l, r) => (x) => l(r(x));
    transformOutput = o(filterEmpty, o(splitOnNewLine, colorizeStats));
  }
});

// libs/core/src/lib/describe-ref.ts
function getArgs(options, includeMergedTags = false) {
  let args = [
    "describe",
    "--always",
    "--long",
    "--dirty",
    "--first-parent"
  ];
  if (options.match) {
    args.push("--match", options.match);
  }
  if (includeMergedTags) {
    args = args.filter((arg) => arg !== "--first-parent");
  }
  return args;
}
function describeRef(options = {}, includeMergedTags) {
  const promise = childProcess2.exec("git", getArgs(options, includeMergedTags), options);
  return promise.then(({ stdout }) => {
    const result = parse(stdout, options.cwd);
    import_npmlog2.default.verbose("git-describe", "%j => %j", options && options.match, stdout);
    import_npmlog2.default.silly("git-describe", "parsed => %j", result);
    return result;
  });
}
function describeRefSync(options = {}, includeMergedTags) {
  const stdout = childProcess2.execSync("git", getArgs(options, includeMergedTags), options);
  const result = parse(stdout, options.cwd);
  import_npmlog2.default.silly("git-describe.sync", "%j => %j", stdout, result);
  return result;
}
function parse(stdout, cwd) {
  const minimalShaRegex = /^([0-9a-f]{7,40})(-dirty)?$/;
  if (minimalShaRegex.test(stdout)) {
    const [, sha2, isDirty2] = minimalShaRegex.exec(stdout);
    const refCount2 = childProcess2.execSync("git", ["rev-list", "--count", sha2], { cwd });
    return { refCount: refCount2, sha: sha2, isDirty: Boolean(isDirty2) };
  }
  const [, lastTagName, lastVersion, refCount, sha, isDirty] = /^((?:.*@)?(.*))-(\d+)-g([0-9a-f]+)(-dirty)?$/.exec(stdout) || [];
  return { lastTagName, lastVersion, refCount, sha, isDirty: Boolean(isDirty) };
}
var import_npmlog2, childProcess2;
var init_describe_ref = __esm({
  "libs/core/src/lib/describe-ref.ts"() {
    "use strict";
    import_npmlog2 = __toESM(require("npmlog"));
    childProcess2 = require("@lerna/child-process");
  }
});

// libs/core/src/lib/validation-error.ts
var import_npmlog3, ValidationError;
var init_validation_error = __esm({
  "libs/core/src/lib/validation-error.ts"() {
    "use strict";
    import_npmlog3 = __toESM(require("npmlog"));
    ValidationError = class extends Error {
      prefix;
      constructor(prefix, message, ...rest) {
        super(message);
        this.name = "ValidationError";
        this.prefix = prefix;
        import_npmlog3.default.resume();
        import_npmlog3.default.error(prefix, message, ...rest);
      }
    };
  }
});

// libs/core/src/lib/check-working-tree.ts
function checkWorkingTree({ cwd } = {}) {
  let chain = Promise.resolve();
  chain = chain.then(() => describeRef({ cwd }));
  const tests = [
    chain.then(throwIfReleased),
    chain.then(mkThrowIfUncommitted({ cwd }))
  ];
  return chain.then((result) => Promise.all(tests).then(() => result));
}
function throwIfReleased({ refCount }) {
  if (refCount === "0") {
    throw new ValidationError(
      "ERELEASED",
      "The current commit has already been released. Please make new commits before continuing."
    );
  }
}
function mkThrowIfUncommitted(options = {}) {
  return function throwIfUncommitted2({ isDirty }) {
    if (isDirty) {
      return collectUncommitted(options).then((uncommitted) => {
        throw new ValidationError("EUNCOMMIT", `${EUNCOMMIT_MSG}${uncommitted.join("\n")}`);
      });
    }
  };
}
var EUNCOMMIT_MSG, throwIfUncommitted;
var init_check_working_tree = __esm({
  "libs/core/src/lib/check-working-tree.ts"() {
    "use strict";
    init_collect_uncommitted();
    init_describe_ref();
    init_validation_error();
    EUNCOMMIT_MSG = "Working tree has uncommitted changes, please commit or remove the following changes before continuing:\n";
    throwIfUncommitted = mkThrowIfUncommitted();
  }
});

// libs/core/src/lib/cli.ts
function lernaCLI(argv, cwd) {
  const cli = (0, import_yargs.default)(argv, cwd);
  return globalOptions(cli).usage("Usage: $0 <command> [options]").demandCommand(1, "A command is required. Pass --help to see all available commands and options.").recommendCommands().strict().fail((msg, err) => {
    const actual = err || new Error(msg);
    if (actual.name !== "ValidationError" && !actual.pkg) {
      if (/Did you mean/.test(actual.message)) {
        import_npmlog4.default.error("lerna", `Unknown command "${cli.parsed.argv._[0]}"`);
      }
      import_npmlog4.default.error("lerna", actual.message);
    }
    cli.exit(actual.exitCode > 0 ? actual.exitCode : 1, actual);
  }).alias("h", "help").alias("v", "version").wrap(cli.terminalWidth()).epilogue(import_dedent.default`
      When a command fails, all logs are written to lerna-debug.log in the current working directory.

      For more information, check out the docs at https://lerna.js.org/docs/introduction
    `);
}
function globalOptions(argv) {
  const opts = {
    loglevel: {
      defaultDescription: "info",
      describe: "What level of logs to report.",
      type: "string"
    },
    concurrency: {
      defaultDescription: import_os.default.cpus().length,
      describe: "How many processes to use when lerna parallelizes tasks.",
      type: "number",
      requiresArg: true
    },
    "reject-cycles": {
      describe: "Fail if a cycle is detected among dependencies.",
      type: "boolean"
    },
    "no-progress": {
      describe: "Disable progress bars. (Always off in CI)",
      type: "boolean"
    },
    progress: {
      hidden: true,
      type: "boolean"
    },
    "no-sort": {
      describe: "Do not sort packages topologically (dependencies before dependents).",
      type: "boolean"
    },
    sort: {
      hidden: true,
      type: "boolean"
    },
    "max-buffer": {
      describe: "Set max-buffer (in bytes) for subcommand execution",
      type: "number",
      requiresArg: true
    }
  };
  const globalKeys = Object.keys(opts).concat(["help", "version"]);
  return argv.options(opts).group(globalKeys, "Global Options:").option("ci", {
    hidden: true,
    type: "boolean"
  });
}
var import_dedent, import_npmlog4, import_os, import_yargs;
var init_cli = __esm({
  "libs/core/src/lib/cli.ts"() {
    "use strict";
    import_dedent = __toESM(require("dedent"));
    import_npmlog4 = __toESM(require("npmlog"));
    import_os = __toESM(require("os"));
    import_yargs = __toESM(require("yargs/yargs"));
  }
});

// libs/core/src/lib/collect-updates/collect-dependents.ts
function collectDependents(nodes) {
  const collected = /* @__PURE__ */ new Set();
  nodes.forEach((currentNode) => {
    if (currentNode.localDependents.size === 0) {
      return;
    }
    const queue2 = [currentNode];
    const seen = /* @__PURE__ */ new Set();
    const visit = (dependentNode, dependentName, siblingDependents) => {
      if (seen.has(dependentNode)) {
        return;
      }
      seen.add(dependentNode);
      if (dependentNode === currentNode || siblingDependents.has(currentNode.name)) {
        return;
      }
      collected.add(dependentNode);
      queue2.push(dependentNode);
    };
    while (queue2.length) {
      const node = queue2.shift();
      node.localDependents.forEach(visit);
    }
  });
  return collected;
}
var init_collect_dependents = __esm({
  "libs/core/src/lib/collect-updates/collect-dependents.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/collect-updates/collect-packages.ts
function collectPackages(packages, { isCandidate = () => true, onInclude, excludeDependents } = {}) {
  const candidates = /* @__PURE__ */ new Set();
  packages.forEach((node, name) => {
    if (isCandidate(node, name)) {
      candidates.add(node);
    }
  });
  if (!excludeDependents) {
    collectDependents(candidates).forEach((node) => candidates.add(node));
  }
  const updates = [];
  packages.forEach((node, name) => {
    if (candidates.has(node)) {
      if (onInclude) {
        onInclude(name);
      }
      updates.push(node);
    }
  });
  return updates;
}
var init_collect_packages = __esm({
  "libs/core/src/lib/collect-updates/collect-packages.ts"() {
    "use strict";
    init_collect_dependents();
  }
});

// libs/core/src/lib/collect-updates/get-packages-for-option.ts
function getPackagesForOption(option) {
  let inputs = null;
  if (option === true) {
    inputs = ["*"];
  } else if (typeof option === "string") {
    inputs = option.split(",");
  } else if (Array.isArray(option)) {
    inputs = [...option];
  }
  return new Set(inputs);
}
var init_get_packages_for_option = __esm({
  "libs/core/src/lib/collect-updates/get-packages-for-option.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/collect-updates/has-tags.ts
function hasTags(opts) {
  import_npmlog5.default.silly("hasTags");
  let result = false;
  try {
    result = !!childProcess3.execSync("git", ["tag"], opts);
  } catch (err) {
    import_npmlog5.default.warn("ENOTAGS", "No git tags were reachable from this branch!");
    import_npmlog5.default.verbose("hasTags error", err);
  }
  import_npmlog5.default.verbose("hasTags", result);
  return result;
}
var import_npmlog5, childProcess3;
var init_has_tags = __esm({
  "libs/core/src/lib/collect-updates/has-tags.ts"() {
    "use strict";
    import_npmlog5 = __toESM(require("npmlog"));
    childProcess3 = require("@lerna/child-process");
  }
});

// libs/core/src/lib/collect-updates/make-diff-predicate.ts
function makeDiffPredicate(committish, execOpts, ignorePatterns = []) {
  const ignoreFilters = new Set(
    ignorePatterns.map(
      (p) => import_minimatch.default.filter(`!${p}`, {
        matchBase: true,
        dot: true
      })
    )
  );
  if (ignoreFilters.size) {
    import_npmlog6.default.info("ignoring diff in paths matching", ignorePatterns);
  }
  return function hasDiffSinceThatIsntIgnored(node) {
    const diff = diffSinceIn(committish, node.location, execOpts);
    if (diff === "") {
      import_npmlog6.default.silly("", "no diff found in %s", node.name);
      return false;
    }
    import_npmlog6.default.silly("found diff in", diff);
    let changedFiles = diff.split("\n");
    if (ignoreFilters.size) {
      for (const ignored of ignoreFilters) {
        changedFiles = changedFiles.filter(ignored);
      }
    }
    if (changedFiles.length) {
      import_npmlog6.default.verbose("filtered diff", changedFiles);
    } else {
      import_npmlog6.default.verbose("", "no diff found in %s (after filtering)", node.name);
    }
    return changedFiles.length > 0;
  };
}
function diffSinceIn(committish, location, opts) {
  const args = ["diff", "--name-only", committish];
  const formattedLocation = (0, import_slash.default)(import_path.default.relative(opts.cwd, location));
  if (formattedLocation) {
    args.push("--", formattedLocation);
  }
  import_npmlog6.default.silly("checking diff", formattedLocation);
  return childProcess4.execSync("git", args, opts);
}
var import_npmlog6, import_minimatch, import_path, import_slash, childProcess4;
var init_make_diff_predicate = __esm({
  "libs/core/src/lib/collect-updates/make-diff-predicate.ts"() {
    "use strict";
    import_npmlog6 = __toESM(require("npmlog"));
    import_minimatch = __toESM(require("minimatch"));
    import_path = __toESM(require("path"));
    import_slash = __toESM(require("slash"));
    childProcess4 = require("@lerna/child-process");
  }
});

// libs/core/src/lib/collect-updates/index.ts
function collectUpdates(filteredPackages, packageGraph, execOpts, commandOptions) {
  const { forcePublish, conventionalCommits, conventionalGraduate, excludeDependents } = commandOptions;
  const useConventionalGraduate = conventionalCommits && conventionalGraduate;
  const forced = getPackagesForOption(useConventionalGraduate ? conventionalGraduate : forcePublish);
  const packages = filteredPackages.length === packageGraph.size ? packageGraph : new Map(filteredPackages.map(({ name }) => [name, packageGraph.get(name)]));
  let committish = commandOptions.since;
  if (hasTags(execOpts)) {
    const { sha, refCount, lastTagName } = describeRefSync(execOpts, commandOptions.includeMergedTags);
    if (refCount === "0" && forced.size === 0 && !committish) {
      import_npmlog7.default.notice("", "Current HEAD is already released, skipping change detection.");
      return [];
    }
    if (commandOptions.canary) {
      committish = `${sha}^..${sha}`;
    } else if (!committish) {
      committish = lastTagName;
    }
  }
  if (forced.size) {
    import_npmlog7.default.warn(
      useConventionalGraduate ? "conventional-graduate" : "force-publish",
      forced.has("*") ? "all packages" : Array.from(forced.values()).join("\n")
    );
  }
  if (useConventionalGraduate) {
    if (forced.has("*")) {
      import_npmlog7.default.info("", "Graduating all prereleased packages");
    } else {
      import_npmlog7.default.info("", "Graduating prereleased packages");
    }
  } else if (!committish || forced.has("*")) {
    import_npmlog7.default.info("", "Assuming all packages changed");
    return collectPackages(packages, {
      onInclude: (name) => import_npmlog7.default.verbose("updated", name),
      excludeDependents
    });
  }
  import_npmlog7.default.info("", `Looking for changed packages since ${committish}`);
  const hasDiff = makeDiffPredicate(committish, execOpts, commandOptions.ignoreChanges);
  const needsBump = !commandOptions.bump || commandOptions.bump.startsWith("pre") ? () => false : (node) => node.prereleaseId;
  const isForced = (node, name) => (forced.has("*") || forced.has(name)) && (useConventionalGraduate ? node.prereleaseId : true);
  return collectPackages(packages, {
    isCandidate: (node, name) => isForced(node, name) || needsBump(node) || hasDiff(node),
    onInclude: (name) => import_npmlog7.default.verbose("updated", name),
    excludeDependents
  });
}
var import_npmlog7;
var init_collect_updates = __esm({
  "libs/core/src/lib/collect-updates/index.ts"() {
    "use strict";
    import_npmlog7 = __toESM(require("npmlog"));
    init_describe_ref();
    init_collect_packages();
    init_get_packages_for_option();
    init_has_tags();
    init_make_diff_predicate();
  }
});

// libs/core/src/lib/package-graph/cyclic-package-graph-node.ts
var lastCollapsedNodeId, CyclicPackageGraphNode;
var init_cyclic_package_graph_node = __esm({
  "libs/core/src/lib/package-graph/cyclic-package-graph-node.ts"() {
    "use strict";
    lastCollapsedNodeId = 0;
    CyclicPackageGraphNode = class extends Map {
      name;
      localDependencies;
      localDependents;
      constructor() {
        super();
        this.name = `(cycle) ${lastCollapsedNodeId += 1}`;
        this.localDependencies = /* @__PURE__ */ new Map();
        this.localDependents = /* @__PURE__ */ new Map();
      }
      get isCycle() {
        return true;
      }
      toString() {
        const parts = Array.from(
          this,
          ([key, node]) => node.isCycle ? `(nested cycle: ${node.toString()})` : key
        );
        parts.push(parts[0]);
        return parts.reverse().join(" -> ");
      }
      flatten() {
        const result = [];
        for (const node of this.values()) {
          if (node.isCycle) {
            result.push(...node.flatten());
          } else {
            result.push(node);
          }
        }
        return result;
      }
      contains(name) {
        for (const [currentName, currentNode] of this) {
          if (currentNode.isCycle) {
            if (currentNode.contains(name)) {
              return true;
            }
          } else if (currentName === name) {
            return true;
          }
        }
        return false;
      }
      insert(node) {
        this.set(node.name, node);
        this.unlink(node);
        for (const [dependencyName, dependencyNode] of node.localDependencies) {
          if (!this.contains(dependencyName)) {
            this.localDependencies.set(dependencyName, dependencyNode);
          }
        }
        for (const [dependentName, dependentNode] of node.localDependents) {
          if (!this.contains(dependentName)) {
            this.localDependents.set(dependentName, dependentNode);
          }
        }
      }
      unlink(candidateNode) {
        this.localDependencies.delete(candidateNode.name);
        this.localDependents.delete(candidateNode.name);
      }
    };
  }
});

// libs/core/src/lib/prerelease-id-from-version.ts
function prereleaseIdFromVersion(version) {
  return (import_semver.default.prerelease(version) || []).shift();
}
var import_semver;
var init_prerelease_id_from_version = __esm({
  "libs/core/src/lib/prerelease-id-from-version.ts"() {
    "use strict";
    import_semver = __toESM(require("semver"));
  }
});

// libs/core/src/lib/package-graph/package-graph-node.ts
var import_semver2, PKG, PackageGraphNode;
var init_package_graph_node = __esm({
  "libs/core/src/lib/package-graph/package-graph-node.ts"() {
    "use strict";
    import_semver2 = __toESM(require("semver"));
    init_prerelease_id_from_version();
    PKG = Symbol("pkg");
    PackageGraphNode = class {
      name;
      externalDependencies;
      localDependencies;
      localDependents;
      [PKG];
      constructor(pkg) {
        this.name = pkg.name;
        this[PKG] = pkg;
        Object.defineProperty(this, PKG, { enumerable: false });
        this.externalDependencies = /* @__PURE__ */ new Map();
        this.localDependencies = /* @__PURE__ */ new Map();
        this.localDependents = /* @__PURE__ */ new Map();
      }
      get location() {
        return this[PKG].location;
      }
      get pkg() {
        return this[PKG];
      }
      get prereleaseId() {
        return prereleaseIdFromVersion(this.version);
      }
      get version() {
        return this[PKG].version;
      }
      satisfies({ gitCommittish, gitRange, fetchSpec }) {
        return import_semver2.default.satisfies(this.version, gitCommittish || gitRange || fetchSpec);
      }
      toString() {
        return this.name;
      }
    };
  }
});

// libs/core/src/lib/package-graph/report-cycles.ts
function reportCycles(paths, rejectCycles) {
  if (!paths.length) {
    return;
  }
  const cycleMessage = ["Dependency cycles detected, you should fix these!"].concat(paths).join("\n");
  if (rejectCycles) {
    throw new ValidationError("ECYCLE", cycleMessage);
  }
  import_npmlog8.default.warn("ECYCLE", cycleMessage);
}
var import_npmlog8;
var init_report_cycles = __esm({
  "libs/core/src/lib/package-graph/report-cycles.ts"() {
    "use strict";
    import_npmlog8 = __toESM(require("npmlog"));
    init_validation_error();
  }
});

// libs/core/src/lib/package-graph/index.ts
var import_npm_package_arg, PackageGraph;
var init_package_graph = __esm({
  "libs/core/src/lib/package-graph/index.ts"() {
    "use strict";
    import_npm_package_arg = __toESM(require("npm-package-arg"));
    init_validation_error();
    init_cyclic_package_graph_node();
    init_package_graph_node();
    init_report_cycles();
    PackageGraph = class extends Map {
      constructor(packages, graphType = "allDependencies", forceLocal) {
        super(packages.map((pkg) => [pkg.name, new PackageGraphNode(pkg)]));
        if (packages.length !== this.size) {
          const seen = /* @__PURE__ */ new Map();
          for (const { name, location } of packages) {
            if (seen.has(name)) {
              seen.get(name).push(location);
            } else {
              seen.set(name, [location]);
            }
          }
          for (const [name, locations] of seen) {
            if (locations.length > 1) {
              throw new ValidationError(
                "ENAME",
                [`Package name "${name}" used in multiple packages:`, ...locations].join("\n	")
              );
            }
          }
        }
        this.forEach((currentNode, currentName) => {
          const graphDependencies = graphType === "dependencies" ? Object.assign({}, currentNode.pkg.optionalDependencies, currentNode.pkg.dependencies) : Object.assign(
            {},
            currentNode.pkg.devDependencies,
            currentNode.pkg.optionalDependencies,
            currentNode.pkg.dependencies
          );
          Object.keys(graphDependencies).forEach((depName) => {
            const depNode = this.get(depName);
            let spec = graphDependencies[depName].replace(/^link:/, "file:");
            const isWorkspaceSpec = /^workspace:/.test(spec);
            let fullWorkspaceSpec;
            let workspaceAlias;
            if (isWorkspaceSpec) {
              fullWorkspaceSpec = spec;
              spec = spec.replace(/^workspace:/, "");
              if (spec === "*" || spec === "^" || spec === "~") {
                workspaceAlias = spec;
                if (depNode?.version) {
                  const prefix = spec === "*" ? "" : spec;
                  const version = depNode.version;
                  spec = `${prefix}${version}`;
                } else {
                  spec = "*";
                }
              }
            }
            const resolved = import_npm_package_arg.default.resolve(depName, spec, currentNode.location);
            resolved.workspaceSpec = fullWorkspaceSpec;
            resolved.workspaceAlias = workspaceAlias;
            if (!depNode) {
              return currentNode.externalDependencies.set(depName, resolved);
            }
            if (forceLocal || resolved.fetchSpec === depNode.location || depNode.satisfies(resolved)) {
              currentNode.localDependencies.set(depName, resolved);
              depNode.localDependents.set(currentName, currentNode);
            } else {
              if (isWorkspaceSpec) {
                throw new ValidationError(
                  "EWORKSPACE",
                  `Package specification "${depName}@${spec}" could not be resolved within the workspace. To reference a non-matching, remote version of a local dependency, remove the 'workspace:' prefix.`
                );
              }
              currentNode.externalDependencies.set(depName, resolved);
            }
          });
        });
      }
      get rawPackageList() {
        return Array.from(this.values()).map((node) => node.pkg);
      }
      addDependencies(filteredPackages) {
        return this.extendList(filteredPackages, "localDependencies");
      }
      addDependents(filteredPackages) {
        return this.extendList(filteredPackages, "localDependents");
      }
      extendList(packageList, nodeProp) {
        const search = new Set(packageList.map(({ name }) => this.get(name)));
        const result = [];
        search.forEach((currentNode) => {
          result.push(currentNode);
          currentNode[nodeProp].forEach((meta, depName) => {
            const depNode = this.get(depName);
            if (depNode !== currentNode && !search.has(depNode)) {
              search.add(depNode);
            }
          });
        });
        return result.map((node) => node.pkg);
      }
      partitionCycles(rejectCycles) {
        const cyclePaths = /* @__PURE__ */ new Set();
        const cycleNodes = /* @__PURE__ */ new Set();
        this.forEach((currentNode, currentName) => {
          const seen = /* @__PURE__ */ new Set();
          const visits = (walk) => (dependentNode, dependentName, siblingDependents) => {
            const step = walk.concat(dependentName);
            if (seen.has(dependentNode)) {
              return;
            }
            seen.add(dependentNode);
            if (dependentNode === currentNode) {
              cycleNodes.add(currentNode);
              cyclePaths.add(step);
              return;
            }
            if (siblingDependents.has(currentName)) {
              const cycleDependentName = Array.from(dependentNode.localDependencies.keys()).find(
                (key) => currentNode.localDependents.has(key)
              );
              const pathToCycle = step.slice().reverse().concat(cycleDependentName);
              cycleNodes.add(dependentNode);
              cyclePaths.add(pathToCycle);
            }
            dependentNode.localDependents.forEach(visits(step));
          };
          currentNode.localDependents.forEach(visits([currentName]));
        });
        reportCycles(
          Array.from(cyclePaths, (cycle) => cycle.join(" -> ")),
          rejectCycles
        );
        return [cyclePaths, cycleNodes];
      }
      collapseCycles(rejectCycles) {
        const cyclePaths = [];
        const nodeToCycle = /* @__PURE__ */ new Map();
        const cycles = /* @__PURE__ */ new Set();
        const walkStack = [];
        const alreadyVisited = /* @__PURE__ */ new Set();
        function visits(baseNode, dependentNode) {
          if (nodeToCycle.has(baseNode)) {
            return;
          }
          let topLevelDependent = dependentNode;
          while (nodeToCycle.has(topLevelDependent)) {
            topLevelDependent = nodeToCycle.get(topLevelDependent);
          }
          const identifier = `${baseNode.name}:${topLevelDependent.name}`;
          if (alreadyVisited.has(identifier)) {
            return;
          }
          alreadyVisited.add(identifier);
          if (topLevelDependent === baseNode || topLevelDependent.isCycle && topLevelDependent.has(baseNode.name)) {
            const cycle = new CyclicPackageGraphNode();
            walkStack.forEach((nodeInCycle) => {
              nodeToCycle.set(nodeInCycle, cycle);
              cycle.insert(nodeInCycle);
              cycles.delete(nodeInCycle);
            });
            cycles.add(cycle);
            cyclePaths.push(cycle.toString());
            return;
          }
          if (walkStack.indexOf(topLevelDependent) === -1) {
            visitWithStack(baseNode, topLevelDependent);
          }
        }
        function visitWithStack(baseNode, currentNode = baseNode) {
          walkStack.push(currentNode);
          currentNode.localDependents.forEach(visits.bind(null, baseNode));
          walkStack.pop();
        }
        this.forEach((currentNode) => visitWithStack(currentNode));
        cycles.forEach((collapsedNode) => visitWithStack(collapsedNode));
        reportCycles(cyclePaths, rejectCycles);
        return cycles;
      }
      pruneCycleNodes(cycleNodes) {
        return this.prune(...cycleNodes);
      }
      prune(...candidates) {
        if (candidates.length === this.size) {
          return this.clear();
        }
        candidates.forEach((node) => this.remove(node));
      }
      remove(candidateNode) {
        this.delete(candidateNode.name);
        this.forEach((node) => {
          node.localDependencies.delete(candidateNode.name);
          node.localDependents.delete(candidateNode.name);
        });
      }
    };
  }
});

// libs/core/src/lib/package.ts
function binSafeName({ name, scope }) {
  return scope ? name.substring(scope.length + 1) : name;
}
function shallowCopy(json) {
  return Object.keys(json).reduce((obj, key) => {
    const val = json[key];
    if (Array.isArray(val)) {
      obj[key] = val.slice();
    } else if (val && typeof val === "object") {
      obj[key] = Object.assign({}, val);
    } else {
      obj[key] = val;
    }
    return obj;
  }, {});
}
var import_load_json_file, import_npm_package_arg2, import_path2, import_write_pkg, PKG2, _location, _resolved, _rootPath, _scripts, _contents, Package;
var init_package = __esm({
  "libs/core/src/lib/package.ts"() {
    "use strict";
    import_load_json_file = __toESM(require("load-json-file"));
    import_npm_package_arg2 = __toESM(require("npm-package-arg"));
    import_path2 = __toESM(require("path"));
    import_write_pkg = __toESM(require("write-pkg"));
    PKG2 = Symbol("pkg");
    _location = Symbol("location");
    _resolved = Symbol("resolved");
    _rootPath = Symbol("rootPath");
    _scripts = Symbol("scripts");
    _contents = Symbol("contents");
    Package = class {
      name;
      [PKG2];
      [_location];
      [_resolved];
      [_rootPath];
      [_scripts];
      [_contents];
      static lazy(ref, dir = ".") {
        if (typeof ref === "string") {
          const location = import_path2.default.resolve(import_path2.default.basename(ref) === "package.json" ? import_path2.default.dirname(ref) : ref);
          const manifest = import_load_json_file.default.sync(import_path2.default.join(location, "package.json"));
          return new Package(manifest, location);
        }
        if ("__isLernaPackage" in ref) {
          return ref;
        }
        return new Package(ref, dir);
      }
      constructor(pkg, location, rootPath = location) {
        const resolved = import_npm_package_arg2.default.resolve(pkg.name, `file:${import_path2.default.relative(rootPath, location)}`, rootPath);
        this.name = pkg.name;
        this[PKG2] = pkg;
        Object.defineProperty(this, PKG2, { enumerable: false, writable: true });
        this[_location] = location;
        this[_resolved] = resolved;
        this[_rootPath] = rootPath;
        this[_scripts] = { ...pkg.scripts };
      }
      get location() {
        return this[_location];
      }
      get private() {
        return Boolean(this[PKG2].private);
      }
      set private(isPrivate) {
        this[PKG2].private = isPrivate;
      }
      get resolved() {
        return this[_resolved];
      }
      get rootPath() {
        return this[_rootPath];
      }
      get scripts() {
        return this[_scripts];
      }
      get bin() {
        const pkg = this[PKG2];
        return typeof pkg.bin === "string" ? {
          [binSafeName(this.resolved)]: pkg.bin
        } : Object.assign({}, pkg.bin);
      }
      get binLocation() {
        return import_path2.default.join(this.location, "node_modules", ".bin");
      }
      get manifestLocation() {
        return import_path2.default.join(this.location, "package.json");
      }
      get nodeModulesLocation() {
        return import_path2.default.join(this.location, "node_modules");
      }
      get __isLernaPackage() {
        return true;
      }
      get version() {
        return this[PKG2].version;
      }
      set version(version) {
        this[PKG2].version = version;
      }
      get contents() {
        if (this[_contents]) {
          return this[_contents];
        }
        if (this[PKG2].publishConfig && this[PKG2].publishConfig.directory) {
          return import_path2.default.join(this.location, this[PKG2].publishConfig.directory);
        }
        return this.location;
      }
      set contents(subDirectory) {
        this[_contents] = import_path2.default.join(this.location, subDirectory);
      }
      get dependencies() {
        return this[PKG2].dependencies;
      }
      get devDependencies() {
        return this[PKG2].devDependencies;
      }
      get optionalDependencies() {
        return this[PKG2].optionalDependencies;
      }
      get peerDependencies() {
        return this[PKG2].peerDependencies;
      }
      get(key) {
        return this[PKG2][key];
      }
      set(key, val) {
        this[PKG2][key] = val;
        return this;
      }
      toJSON() {
        return shallowCopy(this[PKG2]);
      }
      refresh() {
        return (0, import_load_json_file.default)(this.manifestLocation).then((pkg) => {
          this[PKG2] = pkg;
          return this;
        });
      }
      serialize() {
        return (0, import_write_pkg.default)(this.manifestLocation, this[PKG2]).then(() => this);
      }
      updateLocalDependency(resolved, depVersion, savePrefix, options = { retainWorkspacePrefix: true }) {
        const depName = resolved.name;
        let depCollection = this.dependencies;
        if (!depCollection || !depCollection[depName]) {
          depCollection = this.optionalDependencies;
        }
        if (!depCollection || !depCollection[depName]) {
          depCollection = this.devDependencies;
        }
        if (resolved.workspaceSpec && options.retainWorkspacePrefix) {
          if (!resolved.workspaceAlias) {
            const workspacePrefix = resolved.workspaceSpec.match(/^(workspace:[*~^]?)/)[0];
            depCollection[depName] = `${workspacePrefix}${depVersion}`;
          }
        } else if (resolved.registry || resolved.type === "directory") {
          depCollection[depName] = `${savePrefix}${depVersion}`;
        } else if (resolved.gitCommittish) {
          const [tagPrefix] = /^\D*/.exec(resolved.gitCommittish);
          const { hosted } = resolved;
          hosted.committish = `${tagPrefix}${depVersion}`;
          depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
        } else if (resolved.gitRange) {
          const { hosted } = resolved;
          hosted.committish = `semver:${savePrefix}${depVersion}`;
          depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
        }
      }
      removePrivate() {
        delete this[PKG2].private;
      }
    };
  }
});

// libs/core/src/lib/project/deprecate-config.ts
function remap(search, target, { alsoRoot, toValue } = {}) {
  const pathsToSearch = [search];
  if (alsoRoot) {
    pathsToSearch.unshift(search.split(".").pop());
  }
  return (obj) => {
    for (const searchPath of pathsToSearch) {
      if (import_dot_prop.default.has(obj.config, searchPath)) {
        const fromVal = import_dot_prop.default.get(obj.config, searchPath);
        const toVal = toValue ? toValue(fromVal) : fromVal;
        import_npmlog9.default.warn("project", deprecationMessage(obj, target, searchPath, fromVal, toVal));
        import_dot_prop.default.set(obj.config, target, toVal);
        import_dot_prop.default.delete(obj.config, searchPath);
      }
    }
    return obj;
  };
}
function deprecationMessage(obj, target, searchPath, fromVal, toVal) {
  const localPath = import_path3.default.relative(".", obj.filepath);
  let from;
  let to;
  if (toVal === fromVal) {
    from = `"${searchPath}"`;
    to = `"${target}"`;
  } else {
    from = stringify({ [searchPath]: fromVal });
    to = stringify({ [target]: toVal });
  }
  return `Deprecated key "${searchPath}" found in ${localPath}
Please update ${from} => ${to}`;
}
function stringify(obj) {
  return JSON.stringify(obj).slice(1, -1);
}
function compose(...funcs) {
  return funcs.reduce(
    (a, b) => (...args) => a(b(...args))
  );
}
var import_dot_prop, import_npmlog9, import_path3, deprecateConfig;
var init_deprecate_config = __esm({
  "libs/core/src/lib/project/deprecate-config.ts"() {
    "use strict";
    import_dot_prop = __toESM(require("dot-prop"));
    import_npmlog9 = __toESM(require("npmlog"));
    import_path3 = __toESM(require("path"));
    deprecateConfig = compose(
      remap("command.add.includeFilteredDependencies", "command.add.includeDependencies", { alsoRoot: true }),
      remap("command.add.includeFilteredDependents", "command.add.includeDependents", { alsoRoot: true }),
      remap("command.bootstrap.includeFilteredDependencies", "command.bootstrap.includeDependencies"),
      remap("command.bootstrap.includeFilteredDependents", "command.bootstrap.includeDependents"),
      remap("command.clean.includeFilteredDependencies", "command.clean.includeDependencies"),
      remap("command.clean.includeFilteredDependents", "command.clean.includeDependents"),
      remap("command.exec.includeFilteredDependencies", "command.exec.includeDependencies"),
      remap("command.exec.includeFilteredDependents", "command.exec.includeDependents"),
      remap("command.list.includeFilteredDependencies", "command.list.includeDependencies"),
      remap("command.list.includeFilteredDependents", "command.list.includeDependents"),
      remap("command.run.includeFilteredDependencies", "command.run.includeDependencies"),
      remap("command.run.includeFilteredDependents", "command.run.includeDependents"),
      remap("command.version.githubRelease", "command.version.createRelease", {
        toValue: (value) => value && "github"
      }),
      remap("command.publish.githubRelease", "command.version.createRelease", {
        alsoRoot: true,
        toValue: (value) => value && "github"
      }),
      remap("command.publish.npmTag", "command.publish.distTag", { alsoRoot: true }),
      remap("command.publish.cdVersion", "command.publish.bump", { alsoRoot: true }),
      remap("command.publish.ignore", "command.publish.ignoreChanges"),
      remap("commands", "command"),
      (config, filepath) => ({ config, filepath })
    );
  }
});

// libs/core/src/lib/project/shallow-extend.ts
function shallowExtend(json, defaults = {}) {
  return Object.keys(json).reduce((obj, key) => {
    const val = json[key];
    if (Array.isArray(val)) {
      obj[key] = val.slice();
    } else if (val && typeof val === "object") {
      obj[key] = shallowExtend(val, obj[key]);
    } else {
      obj[key] = val;
    }
    return obj;
  }, defaults);
}
var init_shallow_extend = __esm({
  "libs/core/src/lib/project/shallow-extend.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/project/apply-extends.ts
function applyExtends(config, cwd, seen = /* @__PURE__ */ new Set()) {
  let defaultConfig = {};
  if ("extends" in config) {
    let pathToDefault;
    try {
      pathToDefault = (0, import_resolve_from.default)(cwd, config.extends);
    } catch (err) {
      throw new ValidationError("ERESOLVED", "Config .extends must be locally-resolvable", err);
    }
    if (seen.has(pathToDefault)) {
      throw new ValidationError("ECIRCULAR", "Config .extends cannot be circular", seen);
    }
    seen.add(pathToDefault);
    defaultConfig = require(pathToDefault);
    delete config.extends;
    deprecateConfig(defaultConfig, pathToDefault);
    defaultConfig = applyExtends(defaultConfig, import_path4.default.dirname(pathToDefault), seen);
  }
  return shallowExtend(config, defaultConfig);
}
var import_path4, import_resolve_from;
var init_apply_extends = __esm({
  "libs/core/src/lib/project/apply-extends.ts"() {
    "use strict";
    import_path4 = __toESM(require("path"));
    import_resolve_from = __toESM(require("resolve-from"));
    init_validation_error();
    init_deprecate_config();
    init_shallow_extend();
  }
});

// libs/core/src/lib/project/make-file-finder.ts
function normalize(results) {
  return results.map((fp) => import_path5.default.normalize(fp));
}
function getGlobOpts(rootPath, packageConfigs) {
  const globOpts = {
    cwd: rootPath,
    absolute: true,
    expandDirectories: false,
    followSymbolicLinks: false
  };
  if (packageConfigs.some((cfg) => cfg.indexOf("**") > -1)) {
    if (packageConfigs.some((cfg) => cfg.indexOf("node_modules") > -1)) {
      throw new ValidationError(
        "EPKGCONFIG",
        "An explicit node_modules package path does not allow globstars (**)"
      );
    }
    globOpts.ignore = [
      "**/node_modules/**"
    ];
  }
  return globOpts;
}
function makeFileFinder(rootPath, packageConfigs) {
  const globOpts = getGlobOpts(rootPath, packageConfigs);
  return (fileName, fileMapper, customGlobOpts) => {
    const options = Object.assign({}, customGlobOpts, globOpts);
    const promise = (0, import_p_map.default)(
      Array.from(packageConfigs).sort(),
      (globPath) => {
        let chain = (0, import_globby.default)(import_path5.default.posix.join(globPath, fileName), options);
        chain = chain.then((results) => results.sort());
        chain = chain.then(normalize);
        if (fileMapper) {
          chain = chain.then(fileMapper);
        }
        return chain;
      },
      { concurrency: 4 }
    );
    return promise.then((results) => results.reduce((acc, result) => acc.concat(result), []));
  };
}
function makeSyncFileFinder(rootPath, packageConfigs) {
  const globOpts = getGlobOpts(rootPath, packageConfigs);
  return (fileName, fileMapper, customGlobOpts) => {
    const options = Object.assign({}, customGlobOpts, globOpts);
    const patterns = packageConfigs.map((globPath) => import_path5.default.posix.join(globPath, fileName)).sort();
    let results = import_globby.default.sync(patterns, options);
    results = normalize(results);
    if (fileMapper) {
      results = results.map(fileMapper);
    }
    return results;
  };
}
var import_globby, import_p_map, import_path5;
var init_make_file_finder = __esm({
  "libs/core/src/lib/project/make-file-finder.ts"() {
    "use strict";
    import_globby = __toESM(require("globby"));
    import_p_map = __toESM(require("p-map"));
    import_path5 = __toESM(require("path"));
    init_validation_error();
  }
});

// libs/core/src/lib/project/index.ts
var import_devkit, import_cosmiconfig, import_dedent2, import_fs, import_glob_parent, import_globby2, import_js_yaml, import_load_json_file2, import_npmlog10, import_p_map2, import_path6, _Project, Project, getPackages, getPackagesSync;
var init_project = __esm({
  "libs/core/src/lib/project/index.ts"() {
    "use strict";
    import_devkit = require("@nrwl/devkit");
    import_cosmiconfig = require("cosmiconfig");
    import_dedent2 = __toESM(require("dedent"));
    import_fs = __toESM(require("fs"));
    import_glob_parent = __toESM(require("glob-parent"));
    import_globby2 = __toESM(require("globby"));
    import_js_yaml = require("js-yaml");
    import_load_json_file2 = __toESM(require("load-json-file"));
    import_npmlog10 = __toESM(require("npmlog"));
    import_p_map2 = __toESM(require("p-map"));
    import_path6 = __toESM(require("path"));
    init_package();
    init_validation_error();
    init_apply_extends();
    init_deprecate_config();
    init_make_file_finder();
    _Project = class {
      static getPackages(cwd) {
        return new _Project(cwd).getPackages();
      }
      static getPackagesSync(cwd) {
        return new _Project(cwd).getPackagesSync();
      }
      config;
      configNotFound;
      rootConfigLocation;
      rootPath;
      constructor(cwd) {
        const explorer = (0, import_cosmiconfig.cosmiconfigSync)("lerna", {
          searchPlaces: ["lerna.json", "package.json"],
          transform(obj) {
            if (!obj) {
              return {
                config: {},
                configNotFound: true,
                filepath: import_path6.default.resolve(cwd || ".", "lerna.json")
              };
            }
            deprecateConfig(obj.config, obj.filepath);
            obj.config = applyExtends(obj.config, import_path6.default.dirname(obj.filepath));
            return obj;
          }
        });
        let loaded;
        try {
          loaded = explorer.search(cwd);
        } catch (err) {
          if (err.name === "JSONError") {
            throw new ValidationError(err.name, err.message);
          }
          throw err;
        }
        this.config = loaded.config;
        this.configNotFound = loaded.configNotFound;
        this.rootConfigLocation = loaded.filepath;
        this.rootPath = import_path6.default.dirname(loaded.filepath);
        import_npmlog10.default.verbose("rootPath", this.rootPath);
      }
      get version() {
        return this.config.version;
      }
      set version(val) {
        this.config.version = val;
      }
      get packageConfigs() {
        if (this.config.npmClient === "pnpm") {
          import_npmlog10.default.verbose(
            "packageConfigs",
            "Package manager 'pnpm' detected. Resolving packages using 'pnpm-workspace.yaml'."
          );
          const workspaces = this.pnpmWorkspaceConfig.packages;
          if (!workspaces) {
            throw new ValidationError(
              "EWORKSPACES",
              "No 'packages' property found in pnpm-workspace.yaml. See https://pnpm.io/workspaces for help configuring workspaces in pnpm."
            );
          }
          return workspaces;
        }
        if (this.config.useWorkspaces) {
          const workspaces = this.manifest.get("workspaces");
          if (!workspaces) {
            throw new ValidationError(
              "EWORKSPACES",
              import_dedent2.default`
            Workspaces need to be defined in the root package.json.
            See: https://github.com/lerna/lerna/blob/master/commands/bootstrap/README.md#--use-workspaces
          `
            );
          }
          return workspaces.packages || workspaces;
        }
        if (this.manifest.get("workspaces")) {
          import_npmlog10.default.warn(
            "EWORKSPACES",
            import_dedent2.default`
          Workspaces exist in the root package.json, but Lerna is not configured to use them.
          To fix this and have Lerna use workspaces to resolve packages, set \`useWorkspaces: true\` in lerna.json.
        `
          );
        }
        if (this.config.packages) {
          return this.config.packages;
        }
        import_npmlog10.default.warn(
          "EPACKAGES",
          `No packages defined in lerna.json. Defaulting to packages in ${_Project.PACKAGE_GLOB}`
        );
        return [_Project.PACKAGE_GLOB];
      }
      get packageParentDirs() {
        return this.packageConfigs.map(import_glob_parent.default).map((parentDir) => import_path6.default.resolve(this.rootPath, parentDir));
      }
      get manifest() {
        let manifest;
        try {
          const manifestLocation = import_path6.default.join(this.rootPath, "package.json");
          const packageJson = import_load_json_file2.default.sync(manifestLocation);
          if (!packageJson.name) {
            packageJson.name = import_path6.default.basename(import_path6.default.dirname(manifestLocation));
          }
          manifest = new Package(packageJson, this.rootPath);
          Object.defineProperty(this, "manifest", {
            value: manifest
          });
        } catch (err) {
          if (err.name === "JSONError") {
            throw new ValidationError(err.name, err.message);
          }
        }
        return manifest;
      }
      get pnpmWorkspaceConfig() {
        let config;
        try {
          const configLocation = import_path6.default.join(this.rootPath, "pnpm-workspace.yaml");
          const configContent = import_fs.default.readFileSync(configLocation);
          config = (0, import_js_yaml.load)(configContent);
          Object.defineProperty(this, "pnpmWorkspaceConfig", {
            value: config
          });
        } catch (err) {
          if (err.message.includes("ENOENT: no such file or directory")) {
            throw new ValidationError(
              "ENOENT",
              "No pnpm-workspace.yaml found. See https://pnpm.io/workspaces for help configuring workspaces in pnpm."
            );
          }
          throw new ValidationError(err.name, err.message);
        }
        return config;
      }
      get licensePath() {
        let licensePath;
        try {
          const search = import_globby2.default.sync(_Project.LICENSE_GLOB, {
            cwd: this.rootPath,
            absolute: true,
            caseSensitiveMatch: false,
            deep: 0
          });
          licensePath = search.shift();
          if (licensePath) {
            licensePath = import_path6.default.normalize(licensePath);
            Object.defineProperty(this, "licensePath", {
              value: licensePath
            });
          }
        } catch (err) {
          throw new ValidationError(err.name, err.message);
        }
        return licensePath;
      }
      get fileFinder() {
        const finder = makeFileFinder(this.rootPath, this.packageConfigs);
        Object.defineProperty(this, "fileFinder", {
          value: finder
        });
        return finder;
      }
      getPackages() {
        const mapper = (packageConfigPath) => (0, import_load_json_file2.default)(packageConfigPath).then(
          (packageJson) => new Package(packageJson, import_path6.default.dirname(packageConfigPath), this.rootPath)
        );
        return this.fileFinder("package.json", (filePaths) => (0, import_p_map2.default)(filePaths, mapper, { concurrency: 50 }));
      }
      getPackagesSync() {
        return makeSyncFileFinder(this.rootPath, this.packageConfigs)("package.json", (packageConfigPath) => {
          return new Package(
            import_load_json_file2.default.sync(packageConfigPath),
            import_path6.default.dirname(packageConfigPath),
            this.rootPath
          );
        });
      }
      getPackageLicensePaths() {
        return this.fileFinder(_Project.LICENSE_GLOB, null, { caseSensitiveMatch: false });
      }
      isIndependent() {
        return this.version === "independent";
      }
      serializeConfig() {
        (0, import_devkit.writeJsonFile)(this.rootConfigLocation, this.config, { spaces: 2 });
        return this.rootConfigLocation;
      }
    };
    Project = _Project;
    __publicField(Project, "PACKAGE_GLOB", "packages/*");
    __publicField(Project, "LICENSE_GLOB", "LICEN{S,C}E{,.*}");
    getPackages = Project.getPackages;
    getPackagesSync = Project.getPackagesSync;
  }
});

// libs/core/src/lib/write-log-file.ts
function writeLogFile(cwd) {
  let logOutput = "";
  import_npmlog11.default.record.forEach((m) => {
    let pref = [m.id, m.level];
    if (m.prefix) {
      pref.push(m.prefix);
    }
    pref = pref.join(" ");
    m.message.trim().split(/\r?\n/).map((line) => `${pref} ${line}`.trim()).forEach((line) => {
      logOutput += line + import_os2.default.EOL;
    });
  });
  import_write_file_atomic.default.sync(import_path7.default.join(cwd, "lerna-debug.log"), logOutput);
  import_npmlog11.default.record.length = 0;
}
var import_npmlog11, import_os2, import_path7, import_write_file_atomic;
var init_write_log_file = __esm({
  "libs/core/src/lib/write-log-file.ts"() {
    "use strict";
    import_npmlog11 = __toESM(require("npmlog"));
    import_os2 = __toESM(require("os"));
    import_path7 = __toESM(require("path"));
    import_write_file_atomic = __toESM(require("write-file-atomic"));
  }
});

// libs/core/src/lib/command/clean-stack.ts
function cleanStack(err, className) {
  const lines = err.stack ? err.stack.split("\n") : String(err).split("\n");
  const cutoff = new RegExp(`^    at ${className}.runCommand .*$`);
  const relevantIndex = lines.findIndex((line) => cutoff.test(line));
  if (relevantIndex) {
    return lines.slice(0, relevantIndex).join("\n");
  }
  return err;
}
var init_clean_stack = __esm({
  "libs/core/src/lib/command/clean-stack.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/command/default-options.ts
function defaultOptions(...sources) {
  const options = {};
  for (const source of sources) {
    if (source != null) {
      for (const key of Object.keys(source)) {
        if (options[key] === void 0) {
          options[key] = source[key];
        }
      }
    }
  }
  return options;
}
var init_default_options = __esm({
  "libs/core/src/lib/command/default-options.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/command/log-package-error.ts
function logPackageError(err, stream = false) {
  import_npmlog12.default.error(err.command, `exited ${err.exitCode} in '${err.pkg.name}'`);
  if (stream) {
    return;
  }
  if (err.stdout) {
    import_npmlog12.default.error(err.command, "stdout:");
    directLog(err.stdout);
  }
  if (err.stderr) {
    import_npmlog12.default.error(err.command, "stderr:");
    directLog(err.stderr);
  }
  import_npmlog12.default.error(err.command, `exited ${err.exitCode} in '${err.pkg.name}'`);
}
function directLog(message) {
  import_npmlog12.default.pause();
  console.error(message);
  import_npmlog12.default.resume();
}
var import_npmlog12;
var init_log_package_error = __esm({
  "libs/core/src/lib/command/log-package-error.ts"() {
    "use strict";
    import_npmlog12 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/command/warn-if-hanging.ts
function warnIfHanging() {
  const childProcessCount = childProcess5.getChildProcessCount();
  if (childProcessCount > 0) {
    import_npmlog13.default.warn(
      "complete",
      `Waiting for ${childProcessCount} child process${childProcessCount === 1 ? "" : "es"} to exit. CTRL-C to exit immediately.`
    );
  }
}
var import_npmlog13, childProcess5;
var init_warn_if_hanging = __esm({
  "libs/core/src/lib/command/warn-if-hanging.ts"() {
    "use strict";
    import_npmlog13 = __toESM(require("npmlog"));
    childProcess5 = require("@lerna/child-process");
  }
});

// libs/core/src/lib/command/index.ts
var import_clone_deep, import_dedent3, import_execa, import_npmlog14, import_os3, DEFAULT_CONCURRENCY, Command;
var init_command = __esm({
  "libs/core/src/lib/command/index.ts"() {
    "use strict";
    import_clone_deep = __toESM(require("clone-deep"));
    import_dedent3 = __toESM(require("dedent"));
    import_execa = __toESM(require("execa"));
    import_npmlog14 = __toESM(require("npmlog"));
    import_os3 = __toESM(require("os"));
    init_package_graph();
    init_project();
    init_validation_error();
    init_write_log_file();
    init_clean_stack();
    init_default_options();
    init_log_package_error();
    init_warn_if_hanging();
    DEFAULT_CONCURRENCY = import_os3.default.cpus().length;
    Command = class {
      name;
      composed;
      project;
      options;
      runner;
      concurrency;
      toposort;
      execOpts;
      packageGraph;
      logger;
      constructor(_argv, { skipValidations } = { skipValidations: false }) {
        import_npmlog14.default.pause();
        import_npmlog14.default.heading = "lerna";
        const argv = (0, import_clone_deep.default)(_argv);
        import_npmlog14.default.silly("argv", argv);
        this.name = this.constructor.name.replace(/Command$/, "").toLowerCase();
        this.composed = typeof argv.composed === "string" && argv.composed !== this.name;
        if (!this.composed) {
          import_npmlog14.default.notice("cli", `v${argv.lernaVersion}`);
        }
        let runner = new Promise((resolve, reject) => {
          let chain = Promise.resolve();
          chain = chain.then(() => {
            this.project = new Project(argv.cwd);
          });
          chain = chain.then(() => this.configureEnvironment());
          chain = chain.then(() => this.configureOptions());
          chain = chain.then(() => this.configureProperties());
          chain = chain.then(() => this.configureLogging());
          if (!skipValidations) {
            chain = chain.then(() => this.runValidations());
          }
          chain = chain.then(() => this.runPreparations());
          chain = chain.then(() => this.runCommand());
          chain.then(
            (result) => {
              warnIfHanging();
              resolve(result);
            },
            (err) => {
              if (err.pkg) {
                logPackageError(err, this.options.stream);
              } else if (err.name !== "ValidationError") {
                import_npmlog14.default.error("", cleanStack(err, this.constructor.name));
              }
              if (err.name !== "ValidationError" && !err.pkg) {
                writeLogFile(this.project.rootPath);
              }
              warnIfHanging();
              reject(err);
            }
          );
        });
        if (argv.onResolved || argv.onRejected) {
          runner = runner.then(argv.onResolved, argv.onRejected);
          delete argv.onResolved;
          delete argv.onRejected;
        }
        for (const key of ["cwd", "$0"]) {
          Object.defineProperty(argv, key, { enumerable: false });
        }
        Object.defineProperty(this, "argv", {
          value: Object.freeze(argv)
        });
        Object.defineProperty(this, "runner", {
          value: runner
        });
      }
      then(onResolved, onRejected) {
        return this.runner.then(onResolved, onRejected);
      }
      catch(onRejected) {
        return this.runner.catch(onRejected);
      }
      get requiresGit() {
        return true;
      }
      get otherCommandConfigs() {
        return [];
      }
      configureEnvironment() {
        const ci = require("is-ci");
        let loglevel;
        let progress;
        if (ci || !process.stderr.isTTY) {
          import_npmlog14.default.disableColor();
          progress = false;
        } else if (!process.stdout.isTTY) {
          progress = false;
          loglevel = "error";
        } else if (process.stderr.isTTY) {
          import_npmlog14.default.enableColor();
          import_npmlog14.default.enableUnicode();
        }
        Object.defineProperty(this, "envDefaults", {
          value: {
            ci,
            progress,
            loglevel
          }
        });
      }
      configureOptions() {
        const commandConfig = this.project.config.command || {};
        const overrides = [this.name, ...this.otherCommandConfigs].map((key) => commandConfig[key]);
        this.options = defaultOptions(
          this.argv,
          ...overrides,
          this.project.config,
          this.envDefaults
        );
        if (this.options.verbose && this.options.loglevel !== "silly") {
          this.options.loglevel = "verbose";
        }
      }
      argv(argv, arg1, config, envDefaults) {
        throw new Error("Method not implemented.");
      }
      envDefaults(argv, arg1, config, envDefaults) {
        throw new Error("Method not implemented.");
      }
      configureProperties() {
        const { concurrency, sort, maxBuffer } = this.options;
        this.concurrency = Math.max(1, +concurrency || DEFAULT_CONCURRENCY);
        this.toposort = sort === void 0 || sort;
        this.execOpts = {
          cwd: this.project.rootPath,
          maxBuffer
        };
      }
      configureLogging() {
        const { loglevel } = this.options;
        if (loglevel) {
          import_npmlog14.default.level = loglevel;
        }
        import_npmlog14.default.addLevel("success", 3001, { fg: "green", bold: true });
        Object.defineProperty(this, "logger", {
          value: import_npmlog14.default["newGroup"](this.name)
        });
        import_npmlog14.default.resume();
      }
      enableProgressBar() {
        if (this.options.progress !== false) {
          import_npmlog14.default.enableProgress();
        }
      }
      gitInitialized() {
        const opts = {
          cwd: this.project.rootPath,
          reject: false,
          stdio: "ignore"
        };
        return import_execa.default.sync("git", ["rev-parse"], opts).exitCode === 0;
      }
      runValidations() {
        if ((this.options.since !== void 0 || this.requiresGit) && !this.gitInitialized()) {
          throw new ValidationError("ENOGIT", "The git binary was not found, or this is not a git repository.");
        }
        if (!this.project.manifest) {
          throw new ValidationError("ENOPKG", "`package.json` does not exist, have you run `lerna init`?");
        }
        if (this.project.configNotFound) {
          throw new ValidationError("ENOLERNA", "`lerna.json` does not exist, have you run `lerna init`?");
        }
        if (!this.project.version) {
          throw new ValidationError("ENOVERSION", "Required property version does not exist in `lerna.json`");
        }
        if (this.options.independent && !this.project.isIndependent()) {
          throw new ValidationError(
            "EVERSIONMODE",
            import_dedent3.default`
          You ran lerna with --independent or -i, but the repository is not set to independent mode.
          To use independent mode you need to set lerna.json's "version" property to "independent".
          Then you won't need to pass the --independent or -i flags.
        `
          );
        }
        if (this.options.npmClient === "pnpm" && !this.options.useWorkspaces) {
          throw new ValidationError(
            "ENOWORKSPACES",
            "Usage of pnpm without workspaces is not supported. To use pnpm with lerna, set useWorkspaces to true in lerna.json and configure pnpm to use workspaces: https://pnpm.io/workspaces."
          );
        }
      }
      runPreparations() {
        if (!this.composed && this.project.isIndependent()) {
          import_npmlog14.default.info("versioning", "independent");
        }
        if (!this.composed && this.options.ci) {
          import_npmlog14.default.info("ci", "enabled");
        }
        let chain = Promise.resolve();
        chain = chain.then(() => this.project.getPackages());
        chain = chain.then((packages) => {
          this.packageGraph = new PackageGraph(packages);
        });
        return chain;
      }
      runCommand() {
        return Promise.resolve().then(() => this.initialize()).then((proceed) => {
          if (proceed !== false) {
            return this.execute();
          }
        });
      }
      initialize() {
        throw new ValidationError(this.name, "initialize() needs to be implemented.");
      }
      execute() {
        throw new ValidationError(this.name, "execute() needs to be implemented.");
      }
    };
  }
});

// libs/core/src/lib/conventional-commits/get-changelog-config.ts
function isFunction(config) {
  return Object.prototype.toString.call(config) === "[object Function]";
}
function resolveConfigPromise(presetPackageName, presetConfig) {
  import_npmlog15.default.verbose("getChangelogConfig", "Attempting to resolve preset %j", presetPackageName);
  let config = require(presetPackageName);
  import_npmlog15.default.info("getChangelogConfig", "Successfully resolved preset %j", presetPackageName);
  if (isFunction(config)) {
    try {
      config = config(presetConfig);
    } catch (_) {
      config = (0, import_pify.default)(config)();
    }
  }
  return config;
}
function getChangelogConfig(changelogPreset = "conventional-changelog-angular", rootPath) {
  const presetName = typeof changelogPreset === "string" ? changelogPreset : changelogPreset.name;
  const presetConfig = typeof changelogPreset === "object" ? changelogPreset : {};
  const cacheKey = `${presetName}${presetConfig ? JSON.stringify(presetConfig) : ""}`;
  let config = cfgCache.get(cacheKey);
  if (!config) {
    let presetPackageName = presetName;
    const parsed = (0, import_npm_package_arg3.default)(presetPackageName, rootPath);
    import_npmlog15.default.verbose("getChangelogConfig", "using preset %j", presetPackageName);
    import_npmlog15.default.silly("npa", parsed);
    if (parsed.type === "directory") {
      if (parsed.raw[0] === "@") {
        parsed.name = parsed.raw;
        parsed.scope = parsed.raw.substring(0, parsed.raw.indexOf("/"));
      } else {
        presetPackageName = parsed.fetchSpec;
      }
    } else if (parsed.type === "git" && parsed.hosted && parsed.hosted.default === "shortcut") {
      parsed.name = parsed.raw;
    }
    try {
      config = resolveConfigPromise(presetPackageName, presetConfig);
      cfgCache.set(cacheKey, config);
      return Promise.resolve(config);
    } catch (err) {
      import_npmlog15.default.verbose("getChangelogConfig", err.message);
      import_npmlog15.default.info("getChangelogConfig", "Auto-prefixing conventional-changelog preset %j", presetName);
      parsed.name = parsed.raw;
    }
    if (parsed.name.indexOf("conventional-changelog-") < 0) {
      const parts = parsed.name.split("/");
      const start = parsed.scope ? 1 : 0;
      parts.splice(start, 1, `conventional-changelog-${parts[start]}`);
      presetPackageName = parts.join("/");
    }
    try {
      config = resolveConfigPromise(presetPackageName, presetConfig);
      cfgCache.set(cacheKey, config);
    } catch (err) {
      import_npmlog15.default.warn("getChangelogConfig", err.message);
      throw new ValidationError(
        "EPRESET",
        `Unable to load conventional-changelog preset '${presetName}'${presetName !== presetPackageName ? ` (${presetPackageName})` : ""}`
      );
    }
  }
  return Promise.resolve(config);
}
var import_npm_package_arg3, import_npmlog15, import_pify, cfgCache;
var init_get_changelog_config = __esm({
  "libs/core/src/lib/conventional-commits/get-changelog-config.ts"() {
    "use strict";
    import_npm_package_arg3 = __toESM(require("npm-package-arg"));
    import_npmlog15 = __toESM(require("npmlog"));
    import_pify = __toESM(require("pify"));
    init_validation_error();
    cfgCache = /* @__PURE__ */ new Map();
  }
});

// libs/core/src/lib/conventional-commits/recommend-version.ts
function recommendVersion(pkg, type, {
  changelogPreset,
  rootPath,
  tagPrefix,
  prereleaseId,
  conventionalBumpPrerelease
}) {
  import_npmlog16.default.silly(type, "for %s at %s", pkg.name, pkg.location);
  const options = {
    path: pkg.location
  };
  if (type === "independent") {
    options.lernaPackage = pkg.name;
  } else {
    options.tagPrefix = tagPrefix;
  }
  const shouldBumpPrerelease = (releaseType, version) => {
    if (!import_semver3.default.prerelease(version)) {
      return true;
    }
    switch (releaseType) {
      case "major":
        return import_semver3.default.minor(version) !== 0 || import_semver3.default.patch(version) !== 0;
      case "minor":
        return import_semver3.default.patch(version) !== 0;
      default:
        return false;
    }
  };
  let chain = Promise.resolve();
  chain = chain.then(() => getChangelogConfig(changelogPreset, rootPath));
  chain = chain.then((config) => {
    options.config = config;
    return new Promise((resolve, reject) => {
      (0, import_conventional_recommended_bump.default)(options, (err, data) => {
        if (err) {
          return reject(err);
        }
        let releaseType = data.releaseType || "patch";
        if (prereleaseId) {
          const shouldBump = conventionalBumpPrerelease || shouldBumpPrerelease(releaseType, pkg.version);
          const prereleaseType = shouldBump ? `pre${releaseType}` : "prerelease";
          import_npmlog16.default.verbose(type, "increment %s by %s", pkg.version, prereleaseType);
          resolve(import_semver3.default.inc(pkg.version, prereleaseType, prereleaseId));
        } else {
          if (import_semver3.default.major(pkg.version) === 0) {
            if (releaseType === "major") {
              releaseType = "minor";
            }
          }
          import_npmlog16.default.verbose(type, "increment %s by %s", pkg.version, releaseType);
          resolve(import_semver3.default.inc(pkg.version, releaseType));
        }
      });
    });
  });
  return chain;
}
var import_conventional_recommended_bump, import_npmlog16, import_semver3;
var init_recommend_version = __esm({
  "libs/core/src/lib/conventional-commits/recommend-version.ts"() {
    "use strict";
    import_conventional_recommended_bump = __toESM(require("conventional-recommended-bump"));
    import_npmlog16 = __toESM(require("npmlog"));
    import_semver3 = __toESM(require("semver"));
    init_get_changelog_config();
  }
});

// libs/core/src/lib/conventional-commits/constants.ts
var EOL, BLANK_LINE, COMMIT_GUIDELINE, CHANGELOG_HEADER;
var init_constants = __esm({
  "libs/core/src/lib/conventional-commits/constants.ts"() {
    "use strict";
    EOL = "\n";
    BLANK_LINE = EOL + EOL;
    COMMIT_GUIDELINE = "See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.";
    CHANGELOG_HEADER = [
      "# Change Log",
      "",
      "All notable changes to this project will be documented in this file.",
      COMMIT_GUIDELINE
    ].join(EOL);
  }
});

// libs/core/src/lib/conventional-commits/make-bump-only-filter.ts
function makeBumpOnlyFilter(pkg) {
  return (newEntry) => {
    if (!newEntry.split("\n").some((line) => line.startsWith("*"))) {
      const message = `**Note:** Version bump only for package ${pkg.name}`;
      return [newEntry.trim(), message, BLANK_LINE].join(BLANK_LINE);
    }
    return newEntry;
  };
}
var init_make_bump_only_filter = __esm({
  "libs/core/src/lib/conventional-commits/make-bump-only-filter.ts"() {
    "use strict";
    init_constants();
  }
});

// libs/core/src/lib/conventional-commits/read-existing-changelog.ts
function readExistingChangelog(pkg) {
  const changelogFileLoc = import_path8.default.join(pkg.location, "CHANGELOG.md");
  let chain = Promise.resolve();
  chain = chain.then(() => import_fs_extra.default.readFile(changelogFileLoc, "utf8").catch(() => ""));
  chain = chain.then((changelogContents) => {
    const headerIndex = changelogContents.indexOf(COMMIT_GUIDELINE);
    if (headerIndex !== -1) {
      return changelogContents.substring(headerIndex + COMMIT_GUIDELINE.length + BLANK_LINE.length);
    }
    return changelogContents;
  });
  chain = chain.then((changelogContents) => [changelogFileLoc, changelogContents]);
  return chain;
}
var import_fs_extra, import_path8;
var init_read_existing_changelog = __esm({
  "libs/core/src/lib/conventional-commits/read-existing-changelog.ts"() {
    "use strict";
    import_fs_extra = __toESM(require("fs-extra"));
    import_path8 = __toESM(require("path"));
    init_constants();
  }
});

// libs/core/src/lib/conventional-commits/update-changelog.ts
function updateChangelog(pkg, type, { changelogPreset, rootPath, tagPrefix = "v", version }) {
  import_npmlog17.default.silly(type, "for %s at %s", pkg.name, pkg.location);
  return getChangelogConfig(changelogPreset, rootPath).then((config) => {
    const options = {};
    const context = {};
    if (config.conventionalChangelog) {
      options.config = Object.assign({}, config.conventionalChangelog);
    } else {
      options.config = Object.assign({}, config);
    }
    const gitRawCommitsOpts = Object.assign({}, options.config.gitRawCommitsOpts);
    if (type === "root") {
      context.version = version;
      context.currentTag = `${tagPrefix}${version}`;
      options.tagPrefix = tagPrefix;
    } else {
      gitRawCommitsOpts.path = pkg.location;
      options.pkg = { path: pkg.manifestLocation };
      if (type === "independent") {
        options.lernaPackage = pkg.name;
      } else {
        options.tagPrefix = tagPrefix;
        context.currentTag = `${tagPrefix}${pkg.version}`;
      }
    }
    const changelogStream = (0, import_conventional_changelog_core.default)(options, context, gitRawCommitsOpts);
    return Promise.all([
      (0, import_get_stream.default)(changelogStream).then(makeBumpOnlyFilter(pkg)),
      readExistingChangelog(pkg)
    ]).then(([newEntry, [changelogFileLoc, changelogContents]]) => {
      import_npmlog17.default.silly(type, "writing new entry: %j", newEntry);
      const content = [CHANGELOG_HEADER, newEntry, changelogContents].join(BLANK_LINE);
      return import_fs_extra2.default.writeFile(changelogFileLoc, content.trim() + EOL).then(() => {
        import_npmlog17.default.verbose(type, "wrote", changelogFileLoc);
        return {
          logPath: changelogFileLoc,
          newEntry
        };
      });
    });
  });
}
var import_conventional_changelog_core, import_fs_extra2, import_get_stream, import_npmlog17;
var init_update_changelog = __esm({
  "libs/core/src/lib/conventional-commits/update-changelog.ts"() {
    "use strict";
    import_conventional_changelog_core = __toESM(require("conventional-changelog-core"));
    import_fs_extra2 = __toESM(require("fs-extra"));
    import_get_stream = __toESM(require("get-stream"));
    import_npmlog17 = __toESM(require("npmlog"));
    init_constants();
    init_get_changelog_config();
    init_make_bump_only_filter();
    init_read_existing_changelog();
  }
});

// libs/core/src/lib/conventional-commits/index.ts
var init_conventional_commits = __esm({
  "libs/core/src/lib/conventional-commits/index.ts"() {
    "use strict";
    init_recommend_version();
    init_update_changelog();
  }
});

// libs/core/src/lib/create-symlink.ts
function createSymlink(src, dest, type) {
  import_npmlog18.default.silly("createSymlink", [src, dest, type]);
  if (process.platform === "win32") {
    return createWindowsSymlink(src, dest, type);
  }
  return createPosixSymlink(src, dest, type);
}
function createSymbolicLink(src, dest, type) {
  import_npmlog18.default.silly("createSymbolicLink", [src, dest, type]);
  return import_fs_extra3.default.lstat(dest).then(() => import_fs_extra3.default.unlink(dest)).catch(() => {
  }).then(() => import_fs_extra3.default.symlink(src, dest, type));
}
function createPosixSymlink(src, dest, _type) {
  const type = _type === "exec" ? "file" : _type;
  const relativeSymlink = import_path9.default.relative(import_path9.default.dirname(dest), src);
  if (_type === "exec") {
    return import_fs_extra3.default.pathExists(src).then((exists) => {
      if (exists) {
        return createSymbolicLink(relativeSymlink, dest, type).then(() => import_fs_extra3.default.chmod(src, 493));
      }
      return shShim(src, dest, type).then(() => import_fs_extra3.default.chmod(dest, 493));
    });
  }
  return createSymbolicLink(relativeSymlink, dest, type);
}
function createWindowsSymlink(src, dest, type) {
  if (type === "exec") {
    return import_fs_extra3.default.pathExists(src).then((exists) => {
      if (exists) {
        return (0, import_cmd_shim.default)(src, dest);
      }
      return import_fs_extra3.default.outputFile(src, "").then(() => (0, import_cmd_shim.default)(src, dest)).then(
        () => import_fs_extra3.default.remove(src),
        (err) => import_fs_extra3.default.remove(src).then(() => {
          throw err;
        })
      );
    });
  }
  return createSymbolicLink(src, dest, type);
}
function shShim(src, dest, type) {
  import_npmlog18.default.silly("shShim", [src, dest, type]);
  const absTarget = import_path9.default.resolve(import_path9.default.dirname(dest), src);
  const scriptLines = ["#!/bin/sh", `chmod +x ${absTarget} && exec ${absTarget} "$@"`];
  return import_fs_extra3.default.writeFile(dest, scriptLines.join("\n"));
}
var import_cmd_shim, import_fs_extra3, import_npmlog18, import_path9;
var init_create_symlink = __esm({
  "libs/core/src/lib/create-symlink.ts"() {
    "use strict";
    import_cmd_shim = __toESM(require("cmd-shim"));
    import_fs_extra3 = __toESM(require("fs-extra"));
    import_npmlog18 = __toESM(require("npmlog"));
    import_path9 = __toESM(require("path"));
  }
});

// libs/core/src/lib/filter-packages.ts
function filterPackages(packagesToFilter, include = [], exclude = [], showPrivate, continueIfNoMatch) {
  const filtered = new Set(packagesToFilter);
  const patterns = [].concat(arrify(include), negate(exclude));
  if (showPrivate === false) {
    for (const pkg of filtered) {
      if (pkg.private) {
        filtered.delete(pkg);
      }
    }
  }
  if (patterns.length) {
    import_npmlog19.default.info("filter", patterns);
    if (!include.length) {
      patterns.unshift("**");
    }
    const pnames = Array.from(filtered).map((pkg) => pkg.name);
    const chosen = new Set((0, import_multimatch.default)(pnames, patterns));
    for (const pkg of filtered) {
      if (!chosen.has(pkg.name)) {
        filtered.delete(pkg);
      }
    }
    if (!filtered.size && !continueIfNoMatch) {
      throw new ValidationError("EFILTER", import_util.default.format("No packages remain after filtering", patterns));
    }
  }
  return Array.from(filtered);
}
function arrify(thing) {
  if (!thing) {
    return [];
  }
  if (!Array.isArray(thing)) {
    return [thing];
  }
  return thing;
}
function negate(patterns) {
  return arrify(patterns).map((pattern) => `!${pattern}`);
}
var import_multimatch, import_npmlog19, import_util;
var init_filter_packages = __esm({
  "libs/core/src/lib/filter-packages.ts"() {
    "use strict";
    import_multimatch = __toESM(require("multimatch"));
    import_npmlog19 = __toESM(require("npmlog"));
    import_util = __toESM(require("util"));
    init_validation_error();
  }
});

// libs/core/src/lib/filter-options.ts
function filterOptions(yargs2) {
  const opts = {
    scope: {
      describe: "Include only packages with names matching the given glob.",
      type: "string",
      requiresArg: true
    },
    ignore: {
      describe: "Exclude packages with names matching the given glob.",
      type: "string",
      requiresArg: true
    },
    "no-private": {
      describe: 'Exclude packages with { "private": true } in their package.json.',
      type: "boolean"
    },
    private: {
      hidden: true,
      type: "boolean"
    },
    since: {
      describe: import_dedent4.default`
        Only include packages that have been changed since the specified [ref].
        If no ref is passed, it defaults to the most-recent tag.
      `,
      type: "string"
    },
    "exclude-dependents": {
      describe: import_dedent4.default`
        Exclude all transitive dependents when running a command
        with --since, overriding the default "changed" algorithm.
      `,
      conflicts: "include-dependents",
      type: "boolean"
    },
    "include-dependents": {
      describe: import_dedent4.default`
        Include all transitive dependents when running a command
        regardless of --scope, --ignore, or --since.
      `,
      conflicts: "exclude-dependents",
      type: "boolean"
    },
    "include-dependencies": {
      describe: import_dedent4.default`
        Include all transitive dependencies when running a command
        regardless of --scope, --ignore, or --since.
      `,
      type: "boolean"
    },
    "include-merged-tags": {
      describe: "Include tags from merged branches when running a command with --since.",
      type: "boolean"
    },
    "continue-if-no-match": {
      describe: "Don't fail if no package is matched",
      hidden: true,
      type: "boolean"
    }
  };
  return yargs2.options(opts).group(Object.keys(opts), "Filter Options:").option("include-filtered-dependents", {
    hidden: true,
    conflicts: ["exclude-dependents", "include-dependents"],
    type: "boolean"
  }).option("include-filtered-dependencies", {
    hidden: true,
    conflicts: "include-dependencies",
    type: "boolean"
  }).check((argv) => {
    if (argv["includeFilteredDependents"]) {
      argv["includeDependents"] = true;
      argv["include-dependents"] = true;
      delete argv["includeFilteredDependents"];
      delete argv["include-filtered-dependents"];
      import_npmlog20.default.warn("deprecated", "--include-filtered-dependents has been renamed --include-dependents");
    }
    if (argv["includeFilteredDependencies"]) {
      argv["includeDependencies"] = true;
      argv["include-dependencies"] = true;
      delete argv["includeFilteredDependencies"];
      delete argv["include-filtered-dependencies"];
      import_npmlog20.default.warn("deprecated", "--include-filtered-dependencies has been renamed --include-dependencies");
    }
    return argv;
  });
}
function getFilteredPackages(packageGraph, execOpts, opts) {
  const options = { log: import_npmlog20.default, ...opts };
  if (options.scope) {
    options.log.notice("filter", "including %j", options.scope);
  }
  if (options.ignore) {
    options.log.notice("filter", "excluding %j", options.ignore);
  }
  let chain = Promise.resolve();
  chain = chain.then(
    () => filterPackages(
      packageGraph.rawPackageList,
      options.scope,
      options.ignore,
      options.private,
      options.continueIfNoMatch
    )
  );
  if (options.since !== void 0) {
    options.log.notice("filter", "changed since %j", options.since);
    if (options.excludeDependents) {
      options.log.notice("filter", "excluding dependents");
    }
    if (options.includeMergedTags) {
      options.log.notice("filter", "including merged tags");
    }
    chain = chain.then(
      (filteredPackages) => Promise.resolve(collectUpdates(filteredPackages, packageGraph, execOpts, opts)).then((updates) => {
        const updated = new Set(updates.map(({ pkg }) => pkg.name));
        return filteredPackages.filter((pkg) => updated.has(pkg.name));
      })
    );
  }
  if (options.includeDependents) {
    options.log.notice("filter", "including dependents");
    chain = chain.then((filteredPackages) => packageGraph.addDependents(filteredPackages));
  }
  if (options.includeDependencies) {
    options.log.notice("filter", "including dependencies");
    chain = chain.then((filteredPackages) => packageGraph.addDependencies(filteredPackages));
  }
  return chain;
}
var import_dedent4, import_npmlog20;
var init_filter_options = __esm({
  "libs/core/src/lib/filter-options.ts"() {
    "use strict";
    import_dedent4 = __toESM(require("dedent"));
    import_npmlog20 = __toESM(require("npmlog"));
    init_collect_updates();
    init_filter_packages();
  }
});

// libs/core/src/lib/has-npm-version.ts
function hasNpmVersion(range2) {
  return rangeSatisfies(getNpmVersion(), range2);
}
function rangeSatisfies(npmVersion, range2) {
  return Boolean(import_semver4.default.satisfies(npmVersion, range2));
}
function getNpmVersion() {
  return childProcess6.execSync("npm", ["--version"]);
}
var import_semver4, childProcess6;
var init_has_npm_version = __esm({
  "libs/core/src/lib/has-npm-version.ts"() {
    "use strict";
    import_semver4 = __toESM(require("semver"));
    childProcess6 = require("@lerna/child-process");
  }
});

// libs/core/src/lib/query-graph.ts
var QueryGraph, toposort;
var init_query_graph = __esm({
  "libs/core/src/lib/query-graph.ts"() {
    "use strict";
    init_package_graph();
    QueryGraph = class {
      graph;
      cycles;
      static toposort(packages, options) {
        const graph = new QueryGraph(packages, options);
        const result = [];
        let batch = graph.getAvailablePackages();
        while (batch.length) {
          for (const node of batch) {
            result.push(node.pkg);
            graph.markAsDone(node);
          }
          batch = graph.getAvailablePackages();
        }
        return result;
      }
      constructor(packages, { graphType = "allDependencies", rejectCycles } = {}) {
        this.graph = new PackageGraph(packages, graphType);
        this.cycles = this.graph.collapseCycles(rejectCycles);
      }
      _getNextLeaf() {
        return Array.from(this.graph.values()).filter((node) => node.localDependencies.size === 0);
      }
      _getNextCycle() {
        const cycle = Array.from(this.cycles).find((cycleNode) => cycleNode.localDependencies.size === 0);
        if (!cycle) {
          return [];
        }
        this.cycles.delete(cycle);
        return cycle.flatten();
      }
      getAvailablePackages() {
        const availablePackages = this._getNextLeaf();
        if (availablePackages.length > 0) {
          return availablePackages;
        }
        return this._getNextCycle();
      }
      markAsTaken(name) {
        this.graph.delete(name);
      }
      markAsDone(candidateNode) {
        this.graph.remove(candidateNode);
        for (const cycle of this.cycles) {
          cycle.unlink(candidateNode);
        }
      }
    };
    toposort = QueryGraph.toposort;
  }
});

// libs/core/src/lib/listable/listable-format.ts
function listableFormat(pkgList, options) {
  const viewOptions = parseViewOptions(options);
  const resultList = filterResultList(pkgList, viewOptions);
  const count = resultList.length;
  let text;
  if (viewOptions.showJSON) {
    text = formatJSON(resultList);
  } else if (viewOptions.showNDJSON) {
    text = formatNDJSON(resultList);
  } else if (viewOptions.showParseable) {
    text = formatParseable(resultList, viewOptions);
  } else if (viewOptions.showGraph) {
    text = formatJSONGraph(resultList, viewOptions);
  } else {
    text = formatColumns(resultList, viewOptions);
  }
  return { text, count };
}
function parseViewOptions(options) {
  const alias = options._[0];
  return {
    showAll: alias === "la" || options.all,
    showLong: alias === "la" || alias === "ll" || options.long,
    showJSON: options.json,
    showNDJSON: options.ndjson,
    showParseable: options.parseable,
    isTopological: options.toposort,
    showGraph: options.graph
  };
}
function filterResultList(pkgList, viewOptions) {
  let result = viewOptions.showAll ? pkgList.slice() : pkgList.filter((pkg) => !pkg.private);
  if (viewOptions.isTopological) {
    result = QueryGraph.toposort(result);
  }
  return result;
}
function toJSONList(resultList) {
  return resultList.map((pkg) => ({
    name: pkg.name,
    version: pkg.version,
    private: pkg.private,
    location: pkg.location
  }));
}
function formatJSON(resultList) {
  return JSON.stringify(toJSONList(resultList), null, 2);
}
function formatNDJSON(resultList) {
  return toJSONList(resultList).map((data) => JSON.stringify(data)).join("\n");
}
function formatJSONGraph(resultList, viewOptions) {
  const graph = {};
  const getNeighbors = viewOptions.showAll ? (pkg) => Object.keys(
    Object.assign(
      {},
      pkg.devDependencies,
      pkg.peerDependencies,
      pkg.optionalDependencies,
      pkg.dependencies
    )
  ).sort() : (pkg) => Object.keys(
    Object.assign(
      {},
      pkg.optionalDependencies,
      pkg.dependencies
    )
  ).sort();
  for (const pkg of resultList) {
    graph[pkg.name] = getNeighbors(pkg);
  }
  return JSON.stringify(graph, null, 2);
}
function makeParseable(pkg) {
  const result = [pkg.location, pkg.name];
  if (pkg.version) {
    result.push(pkg.version);
  } else {
    result.push("MISSING");
  }
  if (pkg.private) {
    result.push("PRIVATE");
  }
  return result.join(":");
}
function formatParseable(resultList, viewOptions) {
  return resultList.map(viewOptions.showLong ? makeParseable : (pkg) => pkg.location).join("\n");
}
function getColumnOrder(viewOptions) {
  const columns = ["name"];
  if (viewOptions.showLong) {
    columns.push("version", "location");
  }
  if (viewOptions.showAll) {
    columns.push("private");
  }
  return columns;
}
function trimmedColumns(formattedResults, viewOptions) {
  const str = (0, import_columnify.default)(formattedResults, {
    showHeaders: false,
    columns: getColumnOrder(viewOptions),
    config: {
      version: {
        align: "right"
      }
    }
  });
  return str.split("\n").map((line) => line.trimRight()).join("\n");
}
function formatColumns(resultList, viewOptions) {
  const formattedResults = resultList.map((result) => {
    const formatted = {
      name: result.name
    };
    if (result.version) {
      formatted.version = import_chalk2.default.green(`v${result.version}`);
    } else {
      formatted.version = import_chalk2.default.yellow("MISSING");
    }
    if (result.private) {
      formatted.private = `(${import_chalk2.default.red("PRIVATE")})`;
    }
    formatted.location = import_chalk2.default.grey(import_path10.default.relative(".", result.location));
    return formatted;
  });
  return trimmedColumns(formattedResults, viewOptions);
}
var import_chalk2, import_columnify, import_path10;
var init_listable_format = __esm({
  "libs/core/src/lib/listable/listable-format.ts"() {
    "use strict";
    import_chalk2 = __toESM(require("chalk"));
    import_columnify = __toESM(require("columnify"));
    import_path10 = __toESM(require("path"));
    init_query_graph();
  }
});

// libs/core/src/lib/listable/listable-options.ts
function listableOptions(yargs2, group = "Command Options:") {
  return yargs2.options({
    json: {
      group,
      describe: "Show information as a JSON array",
      type: "boolean"
    },
    ndjson: {
      group,
      describe: "Show information as newline-delimited JSON",
      type: "boolean"
    },
    a: {
      group,
      describe: "Show private packages that are normally hidden",
      type: "boolean",
      alias: "all"
    },
    l: {
      group,
      describe: "Show extended information",
      type: "boolean",
      alias: "long"
    },
    p: {
      group,
      describe: "Show parseable output instead of columnified view",
      type: "boolean",
      alias: "parseable"
    },
    toposort: {
      group,
      describe: "Sort packages in topological order instead of lexical by directory",
      type: "boolean"
    },
    graph: {
      group,
      describe: "Show dependency graph as a JSON-formatted adjacency list",
      type: "boolean"
    }
  });
}
var init_listable_options = __esm({
  "libs/core/src/lib/listable/listable-options.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/log-packed.ts
function logPacked(tarball) {
  import_npmlog21.default.notice("");
  import_npmlog21.default.notice("", `${hasUnicode ? "\u{1F4E6} " : "package:"} ${tarball.name}@${tarball.version}`);
  if (tarball.files && tarball.files.length) {
    import_npmlog21.default.notice("=== Tarball Contents ===");
    import_npmlog21.default.notice(
      "",
      (0, import_columnify2.default)(
        tarball.files.map((f) => {
          const bytes = (0, import_byte_size.default)(f.size);
          return {
            path: f.path,
            size: `${bytes.value}${bytes.unit}`
          };
        }),
        {
          include: ["size", "path"],
          showHeaders: false
        }
      )
    );
  }
  if (tarball.bundled && tarball.bundled.length) {
    import_npmlog21.default.notice("=== Bundled Dependencies ===");
    tarball.bundled.forEach((name) => import_npmlog21.default.notice("", name));
  }
  import_npmlog21.default.notice("=== Tarball Details ===");
  import_npmlog21.default.notice(
    "",
    (0, import_columnify2.default)(
      [
        { name: "name:", value: tarball.name },
        { name: "version:", value: tarball.version },
        tarball.filename && { name: "filename:", value: tarball.filename },
        tarball.size && { name: "package size:", value: (0, import_byte_size.default)(tarball.size) },
        tarball.unpackedSize && { name: "unpacked size:", value: (0, import_byte_size.default)(tarball.unpackedSize) },
        tarball.shasum && { name: "shasum:", value: tarball.shasum },
        tarball.integrity && { name: "integrity:", value: elideIntegrity(tarball.integrity) },
        tarball.bundled && tarball.bundled.length && {
          name: "bundled deps:",
          value: tarball.bundled.length
        },
        tarball.bundled && tarball.bundled.length && {
          name: "bundled files:",
          value: tarball.entryCount - tarball.files.length
        },
        tarball.bundled && tarball.bundled.length && {
          name: "own files:",
          value: tarball.files.length
        },
        tarball.entryCount && { name: "total files:", value: tarball.entryCount }
      ].filter((x) => x),
      {
        include: ["name", "value"],
        showHeaders: false
      }
    )
  );
  import_npmlog21.default.notice("", "");
}
function elideIntegrity(integrity) {
  const str = integrity.toString();
  return `${str.substr(0, 20)}[...]${str.substr(80)}`;
}
var import_byte_size, import_columnify2, import_npmlog21, import_has_unicode, hasUnicode;
var init_log_packed = __esm({
  "libs/core/src/lib/log-packed.ts"() {
    "use strict";
    import_byte_size = __toESM(require("byte-size"));
    import_columnify2 = __toESM(require("columnify"));
    import_npmlog21 = __toESM(require("npmlog"));
    import_has_unicode = __toESM(require("has-unicode"));
    hasUnicode = (0, import_has_unicode.default)();
  }
});

// libs/core/src/lib/get-npm-exec-opts.ts
function getNpmExecOpts(pkg, registry) {
  const env = {
    LERNA_PACKAGE_NAME: pkg.name
  };
  if (registry) {
    env.npm_config_registry = registry;
  }
  import_npmlog22.default.silly("getNpmExecOpts", pkg.location, registry);
  return {
    cwd: pkg.location,
    env,
    pkg
  };
}
var import_npmlog22;
var init_get_npm_exec_opts = __esm({
  "libs/core/src/lib/get-npm-exec-opts.ts"() {
    "use strict";
    import_npmlog22 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/npm-install.ts
function npmInstall(pkg, { registry, npmClient, npmClientArgs, npmGlobalStyle, mutex, stdio = "pipe", subCommand = "install" }) {
  const opts = getNpmExecOpts(pkg, registry);
  const args = [subCommand];
  let cmd = npmClient || "npm";
  if (npmGlobalStyle) {
    cmd = "npm";
    args.push("--global-style");
  }
  if (cmd === "yarn" && mutex) {
    args.push("--mutex", mutex);
  }
  if (cmd === "yarn") {
    args.push("--non-interactive");
  }
  if (npmClientArgs && npmClientArgs.length) {
    args.push(...npmClientArgs);
  }
  opts.stdio = stdio;
  opts.env.LERNA_EXEC_PATH = pkg.location;
  opts.env.LERNA_ROOT_PATH = pkg.rootPath;
  import_npmlog23.default.silly("npmInstall", [cmd, args]);
  return childProcess7.exec(cmd, args, opts);
}
function npmInstallDependencies(pkg, dependencies, config) {
  import_npmlog23.default.silly("npmInstallDependencies", pkg.name, dependencies);
  if (!(dependencies && dependencies.length)) {
    import_npmlog23.default.verbose("npmInstallDependencies", "no dependencies to install");
    return Promise.resolve();
  }
  const packageJsonBkp = `${pkg.manifestLocation}.lerna_backup`;
  import_npmlog23.default.silly("npmInstallDependencies", "backup", pkg.manifestLocation);
  return import_fs_extra4.default.copy(pkg.manifestLocation, packageJsonBkp).then(() => {
    const cleanup = () => {
      import_npmlog23.default.silly("npmInstallDependencies", "cleanup", pkg.manifestLocation);
      import_fs_extra4.default.renameSync(packageJsonBkp, pkg.manifestLocation);
    };
    const unregister = (0, import_signal_exit.default)(cleanup);
    const done = (finalError) => {
      cleanup();
      unregister();
      if (finalError) {
        throw finalError;
      }
    };
    const tempJson = transformManifest(pkg, dependencies);
    import_npmlog23.default.silly("npmInstallDependencies", "writing tempJson", tempJson);
    return (0, import_write_pkg2.default)(pkg.manifestLocation, tempJson).then(() => npmInstall(pkg, config)).then(() => done(), done);
  });
}
function transformManifest(pkg, dependencies) {
  const json = pkg.toJSON();
  const depMap = new Map(
    dependencies.map((dep) => {
      const { name, rawSpec } = (0, import_npm_package_arg4.default)(dep, pkg.location);
      return [name, rawSpec || "*"];
    })
  );
  delete json.scripts;
  ["dependencies", "devDependencies", "optionalDependencies"].forEach((depType) => {
    const collection = json[depType];
    if (collection) {
      Object.keys(collection).forEach((depName) => {
        if (depMap.has(depName)) {
          collection[depName] = depMap.get(depName);
          depMap.delete(depName);
        } else {
          delete collection[depName];
        }
      });
    }
  });
  ["bundledDependencies", "bundleDependencies"].forEach((depType) => {
    const collection = json[depType];
    if (Array.isArray(collection)) {
      const newCollection = [];
      for (const depName of collection) {
        if (depMap.has(depName)) {
          newCollection.push(depName);
          depMap.delete(depName);
        }
      }
      json[depType] = newCollection;
    }
  });
  if (depMap.size) {
    if (!json.dependencies) {
      json.dependencies = {};
    }
    depMap.forEach((depVersion, depName) => {
      json.dependencies[depName] = depVersion;
    });
  }
  return json;
}
var import_fs_extra4, import_npm_package_arg4, import_npmlog23, import_signal_exit, import_write_pkg2, childProcess7;
var init_npm_install = __esm({
  "libs/core/src/lib/npm-install.ts"() {
    "use strict";
    import_fs_extra4 = __toESM(require("fs-extra"));
    import_npm_package_arg4 = __toESM(require("npm-package-arg"));
    import_npmlog23 = __toESM(require("npmlog"));
    import_signal_exit = __toESM(require("signal-exit"));
    import_write_pkg2 = __toESM(require("write-pkg"));
    init_get_npm_exec_opts();
    childProcess7 = require("@lerna/child-process");
    module.exports.npmInstallDependencies = npmInstallDependencies;
  }
});

// libs/core/src/lib/prompt.ts
function promptConfirmation(message) {
  import_npmlog24.default.pause();
  return import_inquirer.default.prompt([
    {
      type: "expand",
      name: "confirm",
      message,
      default: 2,
      choices: [
        { key: "y", name: "Yes", value: true },
        { key: "n", name: "No", value: false }
      ]
    }
  ]).then((answers) => {
    import_npmlog24.default.resume();
    return answers.confirm;
  });
}
function promptSelectOne(message, { choices, filter, validate } = {}) {
  import_npmlog24.default.pause();
  return import_inquirer.default.prompt([
    {
      type: "list",
      name: "prompt",
      message,
      choices,
      pageSize: choices?.length,
      filter,
      validate
    }
  ]).then((answers) => {
    import_npmlog24.default.resume();
    return answers["prompt"];
  });
}
function promptTextInput(message, { filter, validate } = {}) {
  import_npmlog24.default.pause();
  return import_inquirer.default.prompt([
    {
      type: "input",
      name: "input",
      message,
      filter,
      validate
    }
  ]).then((answers) => {
    import_npmlog24.default.resume();
    return answers.input;
  });
}
var import_inquirer, import_npmlog24;
var init_prompt = __esm({
  "libs/core/src/lib/prompt.ts"() {
    "use strict";
    import_inquirer = __toESM(require("inquirer"));
    import_npmlog24 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/otplease.ts
function otplease(fn, _opts, otpCache) {
  const opts = { ...otpCache, ..._opts };
  return attempt(fn, opts, otpCache);
}
function attempt(fn, opts, otpCache) {
  return new Promise((resolve) => {
    resolve(fn(opts));
  }).catch((err) => {
    if (err.code !== "EOTP" && !(err.code === "E401" && /one-time pass/.test(err.body))) {
      throw err;
    } else if (!process.stdin.isTTY || !process.stdout.isTTY) {
      throw err;
    } else {
      if (otpCache != null && otpCache.otp != null && otpCache.otp !== opts["otp"]) {
        return attempt(fn, { ...opts, ...otpCache }, otpCache);
      }
      return semaphore.wait().then(() => {
        if (otpCache != null && otpCache.otp != null && otpCache.otp !== opts["otp"]) {
          semaphore.release();
          return attempt(fn, { ...opts, ...otpCache }, otpCache);
        }
        return getOneTimePassword().then(
          (otp) => {
            if (otpCache != null) {
              otpCache.otp = otp;
            }
            semaphore.release();
            return otp;
          },
          (promptError) => {
            semaphore.release();
            return Promise.reject(promptError);
          }
        ).then((otp) => {
          return fn({ ...opts, otp });
        });
      });
    }
  });
}
function getOneTimePassword(message = "This operation requires a one-time password:") {
  return promptTextInput(message, {
    filter: (otp) => otp.replace(/\s+/g, ""),
    validate: (otp) => otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp) || "Must be a valid one-time-password. See https://docs.npmjs.com/getting-started/using-two-factor-authentication"
  });
}
var semaphore;
var init_otplease = __esm({
  "libs/core/src/lib/otplease.ts"() {
    "use strict";
    init_prompt();
    semaphore = {
      _promise: void 0,
      _resolve: void 0,
      wait() {
        return new Promise((resolve) => {
          if (!this._promise) {
            this._promise = new Promise((release) => {
              this._resolve = release;
            });
            resolve(void 0);
          } else {
            resolve(this._promise.then(() => this.wait()));
          }
        });
      },
      release() {
        const resolve = this._resolve;
        if (resolve) {
          this._resolve = void 0;
          this._promise = void 0;
          resolve();
        }
      }
    };
  }
});

// libs/core/src/lib/npm-conf/env-replace.ts
function envReplace(str) {
  if (typeof str !== "string" || !str) {
    return str;
  }
  const regex = /(\\*)\$\{([^}]+)\}/g;
  return str.replace(regex, (orig, esc, name) => {
    esc = esc.length > 0 && esc.length % 2;
    if (esc) {
      return orig;
    }
    if (process.env[name] === void 0) {
      throw new Error(`Failed to replace env in config: ${orig}`);
    }
    return process.env[name];
  });
}
var init_env_replace = __esm({
  "libs/core/src/lib/npm-conf/env-replace.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/npm-conf/find-prefix.ts
function findPrefix(start) {
  let dir = import_path11.default.resolve(start);
  let walkedUp = false;
  while (import_path11.default.basename(dir) === "node_modules") {
    dir = import_path11.default.dirname(dir);
    walkedUp = true;
  }
  if (walkedUp) {
    return dir;
  }
  return find(dir, dir);
}
function find(name, original) {
  if (name === "/" || process.platform === "win32" && /^[a-zA-Z]:(\\|\/)?$/.test(name)) {
    return original;
  }
  try {
    const files = import_fs2.default.readdirSync(name);
    if (files.indexOf("node_modules") !== -1 || files.indexOf("package.json") !== -1) {
      return name;
    }
    const dirname = import_path11.default.dirname(name);
    if (dirname === name) {
      return original;
    }
    return find(dirname, original);
  } catch (err) {
    if (name === original) {
      if (err.code === "ENOENT") {
        return original;
      }
      throw err;
    }
    return original;
  }
}
var import_fs2, import_path11;
var init_find_prefix = __esm({
  "libs/core/src/lib/npm-conf/find-prefix.ts"() {
    "use strict";
    import_fs2 = __toESM(require("fs"));
    import_path11 = __toESM(require("path"));
  }
});

// libs/core/src/lib/npm-conf/types.ts
var require_types = __commonJS({
  "libs/core/src/lib/npm-conf/types.ts"(exports) {
    "use strict";
    var import_path23 = __toESM(require("path"));
    var import_stream = require("stream");
    var import_url2 = __toESM(require("url"));
    var Umask = () => {
    };
    var getLocalAddresses = () => [];
    var semver5 = () => {
    };
    exports.types = {
      access: [null, "restricted", "public"],
      "allow-same-version": Boolean,
      "always-auth": Boolean,
      also: [null, "dev", "development"],
      audit: Boolean,
      "audit-level": ["low", "moderate", "high", "critical"],
      "auth-type": ["legacy", "sso", "saml", "oauth"],
      "bin-links": Boolean,
      browser: [null, String],
      ca: [null, String, Array],
      cafile: import_path23.default,
      cache: import_path23.default,
      "cache-lock-stale": Number,
      "cache-lock-retries": Number,
      "cache-lock-wait": Number,
      "cache-max": Number,
      "cache-min": Number,
      cert: [null, String],
      cidr: [null, String, Array],
      color: ["always", Boolean],
      depth: Number,
      description: Boolean,
      dev: Boolean,
      "dry-run": Boolean,
      editor: String,
      "engine-strict": Boolean,
      force: Boolean,
      "fetch-retries": Number,
      "fetch-retry-factor": Number,
      "fetch-retry-mintimeout": Number,
      "fetch-retry-maxtimeout": Number,
      git: String,
      "git-tag-version": Boolean,
      "commit-hooks": Boolean,
      global: Boolean,
      globalconfig: import_path23.default,
      "global-style": Boolean,
      group: [Number, String],
      "https-proxy": [null, import_url2.default],
      "user-agent": String,
      "ham-it-up": Boolean,
      heading: String,
      "if-present": Boolean,
      "ignore-prepublish": Boolean,
      "ignore-scripts": Boolean,
      "init-module": import_path23.default,
      "init-author-name": String,
      "init-author-email": String,
      "init-author-url": ["", import_url2.default],
      "init-license": String,
      "init-version": semver5,
      json: Boolean,
      key: [null, String],
      "legacy-bundling": Boolean,
      link: Boolean,
      "local-address": getLocalAddresses(),
      loglevel: ["silent", "error", "warn", "notice", "http", "timing", "info", "verbose", "silly"],
      logstream: import_stream.Stream,
      "logs-max": Number,
      long: Boolean,
      maxsockets: Number,
      message: String,
      "metrics-registry": [null, String],
      "node-options": [null, String],
      "node-version": [null, semver5],
      noproxy: [null, String, Array],
      offline: Boolean,
      "onload-script": [null, String],
      only: [null, "dev", "development", "prod", "production"],
      optional: Boolean,
      "package-lock": Boolean,
      otp: [null, String],
      "package-lock-only": Boolean,
      parseable: Boolean,
      "prefer-offline": Boolean,
      "prefer-online": Boolean,
      prefix: import_path23.default,
      preid: String,
      production: Boolean,
      progress: Boolean,
      proxy: [null, false, import_url2.default],
      "read-only": Boolean,
      "rebuild-bundle": Boolean,
      registry: [null, import_url2.default],
      rollback: Boolean,
      save: Boolean,
      "save-bundle": Boolean,
      "save-dev": Boolean,
      "save-exact": Boolean,
      "save-optional": Boolean,
      "save-prefix": String,
      "save-prod": Boolean,
      scope: String,
      "script-shell": [null, String],
      "scripts-prepend-node-path": [false, true, "auto", "warn-only"],
      searchopts: String,
      searchexclude: [null, String],
      searchlimit: Number,
      searchstaleness: Number,
      "send-metrics": Boolean,
      shell: String,
      shrinkwrap: Boolean,
      "sign-git-commit": Boolean,
      "sign-git-tag": Boolean,
      "sso-poll-frequency": Number,
      "sso-type": [null, "oauth", "saml"],
      "strict-ssl": Boolean,
      tag: String,
      timing: Boolean,
      tmp: import_path23.default,
      unicode: Boolean,
      "unsafe-perm": Boolean,
      "update-notifier": Boolean,
      usage: Boolean,
      user: [Number, String],
      userconfig: import_path23.default,
      umask: Umask,
      version: Boolean,
      "tag-version-prefix": String,
      versions: Boolean,
      viewer: String,
      _exit: Boolean
    };
  }
});

// libs/core/src/lib/npm-conf/parse-field.ts
function parseField(input, key) {
  if (typeof input !== "string") {
    return input;
  }
  const typeList = [].concat(types[key]);
  const isPath = typeList.indexOf(import_path12.default) !== -1;
  const isBool = typeList.indexOf(Boolean) !== -1;
  const isString = typeList.indexOf(String) !== -1;
  const isNumber = typeList.indexOf(Number) !== -1;
  let field = `${input}`.trim();
  if (/^".*"$/.test(field)) {
    try {
      field = JSON.parse(field);
    } catch (err) {
      throw new Error(`Failed parsing JSON config key ${key}: ${field}`);
    }
  }
  if (isBool && !isString && field === "") {
    return true;
  }
  switch (field) {
    case "true": {
      return true;
    }
    case "false": {
      return false;
    }
    case "null": {
      return null;
    }
    case "undefined": {
      return void 0;
    }
  }
  field = envReplace(field);
  if (isPath) {
    const regex = process.platform === "win32" ? /^~(\/|\\)/ : /^~\//;
    if (regex.test(field) && process.env["HOME"]) {
      field = import_path12.default.resolve(process.env["HOME"], field.substr(2));
    }
    field = import_path12.default.resolve(field);
  }
  if (isNumber && !Number.isNaN(field)) {
    field = Number(field);
  }
  return field;
}
var import_path12, types;
var init_parse_field = __esm({
  "libs/core/src/lib/npm-conf/parse-field.ts"() {
    "use strict";
    import_path12 = __toESM(require("path"));
    init_env_replace();
    ({ types } = require_types());
  }
});

// libs/core/src/lib/npm-conf/nerf-dart.ts
function toNerfDart(uri) {
  const parsed = import_url.default.parse(uri);
  delete parsed.protocol;
  delete parsed.auth;
  delete parsed.query;
  delete parsed.search;
  delete parsed.hash;
  return import_url.default.resolve(import_url.default.format(parsed), ".");
}
var import_url;
var init_nerf_dart = __esm({
  "libs/core/src/lib/npm-conf/nerf-dart.ts"() {
    "use strict";
    import_url = __toESM(require("url"));
  }
});

// libs/core/src/lib/npm-conf/conf.ts
var import_assert, import_fs3, import_path13, ConfigChain, Conf;
var init_conf = __esm({
  "libs/core/src/lib/npm-conf/conf.ts"() {
    "use strict";
    import_assert = __toESM(require("assert"));
    import_fs3 = __toESM(require("fs"));
    import_path13 = __toESM(require("path"));
    init_env_replace();
    init_find_prefix();
    init_parse_field();
    init_nerf_dart();
    ({ ConfigChain } = require("config-chain"));
    Conf = class extends ConfigChain {
      root;
      constructor(base) {
        super(base);
        this.root = base;
      }
      add(data, marker) {
        try {
          for (const x of Object.keys(data)) {
            const newKey = envReplace(x);
            const newField = parseField(data[x], newKey);
            delete data[x];
            data[newKey] = newField;
          }
        } catch (err) {
          throw err;
        }
        return super.add(data, marker);
      }
      addFile(file, name = file) {
        const marker = { __source__: name };
        this["sources"][name] = { path: file, type: "ini" };
        this["push"](marker);
        this["_await"]();
        try {
          const contents = import_fs3.default.readFileSync(file, "utf8");
          this["addString"](contents, file, "ini", marker);
        } catch (err) {
          this["add"]({}, marker);
        }
        return this;
      }
      addEnv(env = process.env) {
        const conf = {};
        Object.keys(env).filter((x) => /^npm_config_/i.test(x)).forEach((x) => {
          if (!env[x]) {
            return;
          }
          const p = x.toLowerCase().replace(/^npm_config_/, "").replace(/(?!^)_/g, "-");
          conf[p] = env[x];
        });
        return super.addEnv("", conf, "env");
      }
      loadPrefix() {
        const cli = this["list"][0];
        Object.defineProperty(this, "prefix", {
          enumerable: true,
          set: (prefix) => {
            const g = this["get"]("global");
            this[g ? "globalPrefix" : "localPrefix"] = prefix;
          },
          get: () => {
            const g = this["get"]("global");
            return g ? this["globalPrefix"] : this["localPrefix"];
          }
        });
        Object.defineProperty(this, "globalPrefix", {
          enumerable: true,
          set: (prefix) => {
            this["set"]("prefix", prefix);
          },
          get: () => import_path13.default.resolve(this["get"]("prefix"))
        });
        let p;
        Object.defineProperty(this, "localPrefix", {
          enumerable: true,
          set: (prefix) => {
            p = prefix;
          },
          get: () => p
        });
        if (Object.prototype.hasOwnProperty.call(cli, "prefix")) {
          p = import_path13.default.resolve(cli.prefix);
        } else {
          try {
            p = findPrefix(process.cwd());
          } catch (err) {
            throw err;
          }
        }
        return p;
      }
      loadCAFile(file) {
        if (!file) {
          return;
        }
        try {
          const contents = import_fs3.default.readFileSync(file, "utf8");
          const delim = "-----END CERTIFICATE-----";
          const output2 = contents.split(delim).filter((x) => Boolean(x.trim())).map((x) => x.trimLeft() + delim);
          this["set"]("ca", output2);
        } catch (err) {
          if (err.code === "ENOENT") {
            return;
          }
          throw err;
        }
      }
      loadUser() {
        const defConf = this.root;
        if (this["get"]("global")) {
          return;
        }
        if (process.env["SUDO_UID"]) {
          defConf.user = Number(process.env["SUDO_UID"]);
          return;
        }
        const prefix = import_path13.default.resolve(this["get"]("prefix"));
        try {
          const stats = import_fs3.default.statSync(prefix);
          defConf.user = stats.uid;
        } catch (err) {
          if (err.code === "ENOENT") {
            return;
          }
          throw err;
        }
      }
      getCredentialsByURI(uri) {
        (0, import_assert.default)(uri && typeof uri === "string", "registry URL is required");
        const nerfed = toNerfDart(uri);
        const defnerf = toNerfDart(this["get"]("registry"));
        const c = {
          scope: nerfed,
          token: void 0,
          password: void 0,
          username: void 0,
          email: void 0,
          auth: void 0,
          alwaysAuth: void 0
        };
        if (this["get"](`${nerfed}:always-auth`) !== void 0) {
          const val = this["get"](`${nerfed}:always-auth`);
          c.alwaysAuth = val === "false" ? false : !!val;
        } else if (this["get"]("always-auth") !== void 0) {
          c.alwaysAuth = this["get"]("always-auth");
        }
        if (this["get"](`${nerfed}:_authToken`)) {
          c.token = this["get"](`${nerfed}:_authToken`);
          return c;
        }
        let authDef = this["get"]("_auth");
        let userDef = this["get"]("username");
        let passDef = this["get"]("_password");
        if (authDef && !(userDef && passDef)) {
          authDef = Buffer.from(authDef, "base64").toString();
          authDef = authDef.split(":");
          userDef = authDef.shift();
          passDef = authDef.join(":");
        }
        if (this["get"](`${nerfed}:_password`)) {
          c.password = Buffer.from(this["get"](`${nerfed}:_password`), "base64").toString("utf8");
        } else if (nerfed === defnerf && passDef) {
          c.password = passDef;
        }
        if (this["get"](`${nerfed}:username`)) {
          c.username = this["get"](`${nerfed}:username`);
        } else if (nerfed === defnerf && userDef) {
          c.username = userDef;
        }
        if (this["get"](`${nerfed}:email`)) {
          c.email = this["get"](`${nerfed}:email`);
        } else if (this["get"]("email")) {
          c.email = this["get"]("email");
        }
        if (c.username && c.password) {
          c.auth = Buffer.from(`${c.username}:${c.password}`).toString("base64");
        }
        return c;
      }
      setCredentialsByURI(uri, c) {
        (0, import_assert.default)(uri && typeof uri === "string", "registry URL is required");
        (0, import_assert.default)(c && typeof c === "object", "credentials are required");
        const nerfed = toNerfDart(uri);
        if (c.token) {
          this["set"](`${nerfed}:_authToken`, c.token, "user");
          this["del"](`${nerfed}:_password`, "user");
          this["del"](`${nerfed}:username`, "user");
          this["del"](`${nerfed}:email`, "user");
          this["del"](`${nerfed}:always-auth`, "user");
        } else if (c.username || c.password || c.email) {
          (0, import_assert.default)(c.username, "must include username");
          (0, import_assert.default)(c.password, "must include password");
          (0, import_assert.default)(c.email, "must include email address");
          this["del"](`${nerfed}:_authToken`, "user");
          const encoded = Buffer.from(c.password, "utf8").toString("base64");
          this["set"](`${nerfed}:_password`, encoded, "user");
          this["set"](`${nerfed}:username`, c.username, "user");
          this["set"](`${nerfed}:email`, c.email, "user");
          if (c.alwaysAuth !== void 0) {
            this["set"](`${nerfed}:always-auth`, c.alwaysAuth, "user");
          } else {
            this["del"](`${nerfed}:always-auth`, "user");
          }
        } else {
          throw new Error("No credentials to set.");
        }
      }
    };
  }
});

// libs/core/src/lib/npm-conf/defaults.ts
var require_defaults = __commonJS({
  "libs/core/src/lib/npm-conf/defaults.ts"(exports) {
    "use strict";
    var import_os4 = __toESM(require("os"));
    var import_path23 = __toESM(require("path"));
    var temp = import_os4.default.tmpdir();
    var uidOrPid = process.getuid ? process.getuid() : process.pid;
    var hasUnicode2 = () => true;
    var isWindows = process.platform === "win32";
    var osenv = {
      editor: () => process.env["EDITOR"] || process.env["VISUAL"] || (isWindows ? "notepad.exe" : "vi"),
      shell: () => isWindows ? process.env["COMSPEC"] || "cmd.exe" : process.env["SHELL"] || "/bin/bash"
    };
    var umask = {
      fromString: () => process.umask()
    };
    var home = import_os4.default.homedir();
    if (home) {
      process.env["HOME"] = home;
    } else {
      home = import_path23.default.resolve(temp, `npm-${uidOrPid}`);
    }
    var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm";
    var cacheRoot = process.platform === "win32" && process.env["APPDATA"] || home;
    var cache = import_path23.default.resolve(cacheRoot, cacheExtra);
    var defaults;
    var globalPrefix;
    Object.defineProperty(exports, "defaults", {
      get() {
        if (defaults) {
          return defaults;
        }
        if (process.env["PREFIX"]) {
          globalPrefix = process.env["PREFIX"];
        } else if (process.platform === "win32") {
          globalPrefix = import_path23.default.dirname(process.execPath);
        } else {
          globalPrefix = import_path23.default.dirname(import_path23.default.dirname(process.execPath));
          if (process.env["DESTDIR"]) {
            globalPrefix = import_path23.default.join(process.env["DESTDIR"], globalPrefix);
          }
        }
        defaults = {
          access: null,
          "allow-same-version": false,
          "always-auth": false,
          also: null,
          audit: true,
          "audit-level": "low",
          "auth-type": "legacy",
          "bin-links": true,
          browser: null,
          ca: null,
          cafile: null,
          cache,
          "cache-lock-stale": 6e4,
          "cache-lock-retries": 10,
          "cache-lock-wait": 1e4,
          "cache-max": Infinity,
          "cache-min": 10,
          cert: null,
          cidr: null,
          color: process.env["NO_COLOR"] == null,
          depth: Infinity,
          description: true,
          dev: false,
          "dry-run": false,
          editor: osenv.editor(),
          "engine-strict": false,
          force: false,
          "fetch-retries": 2,
          "fetch-retry-factor": 10,
          "fetch-retry-mintimeout": 1e4,
          "fetch-retry-maxtimeout": 6e4,
          git: "git",
          "git-tag-version": true,
          "commit-hooks": true,
          global: false,
          globalconfig: import_path23.default.resolve(globalPrefix, "etc", "npmrc"),
          "global-style": false,
          group: process.platform === "win32" ? 0 : process.env["SUDO_GID"] || process.getgid && process.getgid(),
          "ham-it-up": false,
          heading: "npm",
          "if-present": false,
          "ignore-prepublish": false,
          "ignore-scripts": false,
          "init-module": import_path23.default.resolve(home, ".npm-init.js"),
          "init-author-name": "",
          "init-author-email": "",
          "init-author-url": "",
          "init-version": "1.0.0",
          "init-license": "ISC",
          json: false,
          key: null,
          "legacy-bundling": false,
          link: false,
          "local-address": void 0,
          loglevel: "notice",
          logstream: process.stderr,
          "logs-max": 10,
          long: false,
          maxsockets: 50,
          message: "%s",
          "metrics-registry": null,
          "node-options": null,
          "node-version": process.version,
          offline: false,
          "onload-script": false,
          only: null,
          optional: true,
          otp: void 0,
          "package-lock": true,
          "package-lock-only": false,
          parseable: false,
          "prefer-offline": false,
          "prefer-online": false,
          prefix: globalPrefix,
          preid: "",
          production: process.env["NODE_ENV"] === "production",
          progress: !process.env["TRAVIS"] && !process.env["CI"],
          proxy: null,
          "https-proxy": null,
          noproxy: null,
          "user-agent": "npm/{npm-version} node/{node-version} {platform} {arch}",
          "read-only": false,
          "rebuild-bundle": true,
          registry: "https://registry.npmjs.org/",
          rollback: true,
          save: true,
          "save-bundle": false,
          "save-dev": false,
          "save-exact": false,
          "save-optional": false,
          "save-prefix": "^",
          "save-prod": false,
          scope: "",
          "script-shell": void 0,
          "scripts-prepend-node-path": "warn-only",
          searchopts: "",
          searchexclude: null,
          searchlimit: 20,
          searchstaleness: 15 * 60,
          "send-metrics": false,
          shell: osenv.shell(),
          shrinkwrap: true,
          "sign-git-commit": false,
          "sign-git-tag": false,
          "sso-poll-frequency": 500,
          "sso-type": "oauth",
          "strict-ssl": true,
          tag: "latest",
          "tag-version-prefix": "v",
          timing: false,
          tmp: temp,
          unicode: hasUnicode2(),
          "unsafe-perm": process.platform === "win32" || process.platform === "cygwin" || !(process.getuid && process.setuid && process.getgid && process.setgid) || process.getuid() !== 0,
          "update-notifier": true,
          usage: false,
          user: process.platform === "win32" || import_os4.default.type() === "OS400" ? 0 : "nobody",
          userconfig: import_path23.default.resolve(home, ".npmrc"),
          umask: process.umask ? process.umask() : umask.fromString("022"),
          version: false,
          versions: false,
          viewer: process.platform === "win32" ? "browser" : "man",
          _exit: true
        };
        return defaults;
      }
    });
  }
});

// libs/core/src/lib/npm-conf/index.ts
var require_npm_conf = __commonJS({
  "libs/core/src/lib/npm-conf/index.ts"(exports, module2) {
    "use strict";
    var import_path23 = __toESM(require("path"));
    init_conf();
    init_nerf_dart();
    var { defaults } = require_defaults();
    module2.exports = npmConf3;
    module2.exports.Conf = Conf;
    module2.exports.defaults = Object.assign({}, defaults);
    module2.exports.toNerfDart = toNerfDart;
    function npmConf3(opts) {
      const conf = new Conf(Object.assign({}, defaults));
      const cleanOpts = opts ? Object.keys(opts).reduce((acc, key) => {
        if (opts[key] !== void 0) {
          acc[key] = opts[key];
        }
        return acc;
      }, {}) : {};
      conf.add(cleanOpts, "cli");
      conf.addEnv();
      conf.loadPrefix();
      const projectConf = import_path23.default.resolve(conf["localPrefix"], ".npmrc");
      const userConf = conf["get"]("userconfig");
      if (!conf["get"]("global") && projectConf !== userConf) {
        conf.addFile(projectConf, "project");
      } else {
        conf.add({}, "project");
      }
      conf.addFile(conf["get"]("userconfig"), "user");
      if (conf["get"]("prefix")) {
        const etc = import_path23.default.resolve(conf["get"]("prefix"), "etc");
        conf.root.globalconfig = import_path23.default.resolve(etc, "npmrc");
        conf.root.globalignorefile = import_path23.default.resolve(etc, "npmignore");
      }
      conf.addFile(conf["get"]("globalconfig"), "global");
      conf.loadUser();
      const caFile = conf["get"]("cafile");
      if (caFile) {
        conf.loadCAFile(caFile);
      }
      return conf;
    }
  }
});

// libs/core/src/lib/run-lifecycle.ts
function flattenOptions(obj) {
  return {
    ignorePrepublish: obj["ignore-prepublish"],
    ignoreScripts: obj["ignore-scripts"],
    nodeOptions: obj["node-options"],
    scriptShell: obj["script-shell"],
    scriptsPrependNodePath: obj["scripts-prepend-node-path"],
    unsafePerm: obj["unsafe-perm"],
    ...obj
  };
}
function printCommandBanner(id, event, cmd, path23) {
  return console.log(`
> ${id ? `${id} ` : ""}${event} ${path23}
> ${cmd.trim().replace(/\n/g, "\n> ")}
`);
}
function runLifecycle(pkg, stage, options) {
  if ("root" in options) {
    options = options.snapshot;
  }
  const opts = {
    log: import_npmlog25.default,
    unsafePerm: true,
    ...flattenOptions(options)
  };
  const dir = pkg.location;
  const id = `${pkg.name}@${pkg.version}`;
  const config = {};
  if (opts.ignoreScripts) {
    opts.log.verbose("lifecycle", "%j ignored in %j", stage, pkg.name);
    return Promise.resolve();
  }
  if (!pkg.scripts || !pkg.scripts[stage]) {
    opts.log.silly("lifecycle", "No script for %j in %j, continuing", stage, pkg.name);
    return Promise.resolve();
  }
  if (stage === "prepublish" && opts.ignorePrepublish) {
    opts.log.verbose("lifecycle", "%j ignored in %j", stage, pkg.name);
    return Promise.resolve();
  }
  for (const [key, val] of Object.entries(opts)) {
    if (val != null && key !== "log" && key !== "logstream") {
      config[key] = val;
    }
  }
  if (pkg.__isLernaPackage) {
    pkg = pkg.toJSON();
  }
  pkg._id = id;
  opts.log.silly("lifecycle", "%j starting in %j", stage, pkg.name);
  opts.log.info("lifecycle", `${id}~${stage}: ${id}`);
  const stdio = opts.stdio || "pipe";
  if (import_npmlog25.default.level !== "silent") {
    printCommandBanner(id, stage, pkg.scripts[stage], dir);
  }
  return queue.add(
    async () => runScript({
      event: stage,
      path: dir,
      pkg,
      args: [],
      stdio,
      banner: false,
      scriptShell: config.scriptShell
    }).then(
      ({ stdout }) => {
        if (stdout) {
          console.log(stdout.toString().trimEnd());
        }
        opts.log.silly("lifecycle", "%j finished in %j", stage, pkg.name);
      },
      (err) => {
        const exitCode = err.code || 1;
        import_npmlog25.default.error("lifecycle", "%j errored in %j, exiting %d", stage, pkg.name, exitCode);
        err.name = "ValidationError";
        err.exitCode = exitCode;
        process.exitCode = exitCode;
        throw err;
      }
    )
  );
}
function createRunner(commandOptions) {
  const cfg = npmConf(commandOptions).snapshot;
  return (pkg, stage) => runLifecycle(pkg, stage, cfg);
}
var import_npmlog25, import_p_queue, runScript, npmConf, queue;
var init_run_lifecycle = __esm({
  "libs/core/src/lib/run-lifecycle.ts"() {
    "use strict";
    import_npmlog25 = __toESM(require("npmlog"));
    import_p_queue = __toESM(require("p-queue"));
    runScript = require("@npmcli/run-script");
    npmConf = require_npm_conf();
    queue = new import_p_queue.default({ concurrency: 1 });
  }
});

// libs/core/src/lib/npm-publish.ts
function flattenOptions2(obj) {
  return {
    defaultTag: obj["tag"] || "latest",
    dryRun: obj["dry-run"],
    strictSSL: obj["strict-ssl"],
    ...obj
  };
}
function npmPublish(pkg, tarFilePath, options = {}, otpCache) {
  const { dryRun, ...remainingOptions } = flattenOptions2(options);
  const { scope } = (0, import_npm_package_arg5.default)(pkg.name);
  const opts = {
    log: import_npmlog26.default,
    ...remainingOptions,
    projectScope: scope
  };
  opts.log.verbose("publish", pkg.name);
  let chain = Promise.resolve();
  if (!dryRun) {
    chain = chain.then(() => {
      let { manifestLocation } = pkg;
      if (pkg.contents !== pkg.location) {
        manifestLocation = import_path14.default.join(pkg.contents, "package.json");
      }
      return Promise.all([import_fs_extra5.default.readFile(tarFilePath), readJSONAsync(manifestLocation)]);
    });
    chain = chain.then(([tarData, manifest]) => {
      if (opts.defaultTag !== "latest" && manifest.publishConfig && manifest.publishConfig.tag && manifest.publishConfig.tag !== opts.defaultTag) {
        manifest.publishConfig.tag = opts.defaultTag;
      }
      if (manifest.publishConfig) {
        Object.assign(opts, publishConfigToOpts(manifest.publishConfig));
      }
      return otplease((innerOpts) => (0, import_libnpmpublish.publish)(manifest, tarData, innerOpts), opts, otpCache);
    });
  }
  chain = chain.then(() => runLifecycle(pkg, "publish", opts));
  chain = chain.then(() => runLifecycle(pkg, "postpublish", opts));
  return chain;
}
function publishConfigToOpts(publishConfig) {
  const opts = { ...publishConfig };
  if (publishConfig.tag) {
    opts.defaultTag = publishConfig.tag;
    delete opts.tag;
  }
  return opts;
}
var import_fs_extra5, import_libnpmpublish, import_npm_package_arg5, import_npmlog26, import_path14, import_pify2, readJSON, readJSONAsync;
var init_npm_publish = __esm({
  "libs/core/src/lib/npm-publish.ts"() {
    "use strict";
    import_fs_extra5 = __toESM(require("fs-extra"));
    import_libnpmpublish = require("libnpmpublish");
    import_npm_package_arg5 = __toESM(require("npm-package-arg"));
    import_npmlog26 = __toESM(require("npmlog"));
    import_path14 = __toESM(require("path"));
    import_pify2 = __toESM(require("pify"));
    init_otplease();
    init_run_lifecycle();
    readJSON = require("read-package-json");
    readJSONAsync = (0, import_pify2.default)(readJSON);
  }
});

// libs/core/src/lib/npm-run-script.ts
function npmRunScript(script, { args, npmClient, pkg, reject = true }) {
  import_npmlog27.default.silly("npmRunScript", script, args, pkg.name);
  const argv = ["run", script, ...args];
  const opts = makeOpts(pkg, reject);
  return childProcess8.exec(npmClient, argv, opts);
}
function npmRunScriptStreaming(script, { args, npmClient, pkg, prefix, reject = true }) {
  import_npmlog27.default.silly("npmRunScriptStreaming", [script, args, pkg.name]);
  const argv = ["run", script, ...args];
  const opts = makeOpts(pkg, reject);
  return childProcess8.spawnStreaming(npmClient, argv, opts, prefix && pkg.name);
}
function makeOpts(pkg, reject) {
  return Object.assign(getNpmExecOpts(pkg), {
    windowsHide: false,
    reject
  });
}
var import_npmlog27, childProcess8;
var init_npm_run_script = __esm({
  "libs/core/src/lib/npm-run-script.ts"() {
    "use strict";
    import_npmlog27 = __toESM(require("npmlog"));
    init_get_npm_exec_opts();
    childProcess8 = require("@lerna/child-process");
  }
});

// libs/core/src/lib/output.ts
function output(...args) {
  import_npmlog28.default["clearProgress"]();
  console.log(...args);
  import_npmlog28.default["showProgress"]();
}
var import_npmlog28;
var init_output = __esm({
  "libs/core/src/lib/output.ts"() {
    "use strict";
    import_npmlog28 = __toESM(require("npmlog"));
  }
});

// libs/core/src/lib/temp-write.ts
async function tempWrite(fileContent, filePath) {
  const tempPath = tempfile(filePath);
  const write = (0, import_is_stream.default)(fileContent) ? writeStream : writeFileP;
  await (0, import_make_dir.default)(import_path15.default.dirname(tempPath));
  await write(tempPath, fileContent);
  return tempPath;
}
var import_graceful_fs, import_is_stream, import_make_dir, import_path15, import_temp_dir, import_util2, uuid, writeFileP, tempfile, writeStream, temp_write_default;
var init_temp_write = __esm({
  "libs/core/src/lib/temp-write.ts"() {
    "use strict";
    import_graceful_fs = __toESM(require("graceful-fs"));
    import_is_stream = __toESM(require("is-stream"));
    import_make_dir = __toESM(require("make-dir"));
    import_path15 = __toESM(require("path"));
    import_temp_dir = __toESM(require("temp-dir"));
    import_util2 = require("util");
    uuid = __toESM(require("uuid"));
    writeFileP = (0, import_util2.promisify)(import_graceful_fs.default.writeFile);
    tempfile = (filePath) => import_path15.default.join(import_temp_dir.default, uuid.v4(), filePath || "");
    writeStream = async (filePath, fileContent) => new Promise((resolve, reject) => {
      const writable = import_graceful_fs.default.createWriteStream(filePath);
      fileContent.on("error", (error) => {
        reject(error);
        fileContent.unpipe(writable);
        writable.end();
      }).pipe(writable).on("error", reject).on("finish", resolve);
    });
    tempWrite.sync = (fileContent, filePath) => {
      const tempPath = tempfile(filePath);
      import_make_dir.default.sync(import_path15.default.dirname(tempPath));
      import_graceful_fs.default.writeFileSync(tempPath, fileContent);
      return tempPath;
    };
    temp_write_default = tempWrite;
  }
});

// libs/core/src/lib/get-packed.ts
function getPacked(pkg, tarFilePath) {
  const bundledWanted = new Set(pkg.bundleDependencies || pkg.bundledDependencies || []);
  const bundled = /* @__PURE__ */ new Set();
  const files = [];
  let totalEntries = 0;
  let totalEntrySize = 0;
  return import_tar.default.list({
    file: tarFilePath,
    onentry(entry) {
      totalEntries += 1;
      totalEntrySize += entry.size;
      const p = entry.path;
      if (p.startsWith("package/node_modules/")) {
        const name = p.match(/^package\/node_modules\/((?:@[^/]+\/)?[^/]+)/)[1];
        if (bundledWanted.has(name)) {
          bundled.add(name);
        }
      } else {
        files.push({
          path: entry.path.replace(/^package\//, ""),
          size: entry.size,
          mode: entry.mode
        });
      }
    },
    strip: 1
  }).then(
    () => Promise.all([
      import_fs_extra6.default.stat(tarFilePath),
      import_ssri.default.fromStream(import_fs_extra6.default.createReadStream(tarFilePath), {
        algorithms: ["sha1", "sha512"]
      })
    ])
  ).then(([{ size }, { sha1, sha512 }]) => {
    const shasum = sha1[0].hexDigest();
    return {
      id: `${pkg.name}@${pkg.version}`,
      name: pkg.name,
      version: pkg.version,
      size,
      unpackedSize: totalEntrySize,
      shasum,
      integrity: import_ssri.default.parse(sha512[0]),
      filename: import_path16.default.basename(tarFilePath),
      files,
      entryCount: totalEntries,
      bundled: Array.from(bundled),
      tarFilePath
    };
  });
}
var import_fs_extra6, import_path16, import_ssri, import_tar;
var init_get_packed = __esm({
  "libs/core/src/lib/get-packed.ts"() {
    "use strict";
    import_fs_extra6 = __toESM(require("fs-extra"));
    import_path16 = __toESM(require("path"));
    import_ssri = __toESM(require("ssri"));
    import_tar = __toESM(require("tar"));
  }
});

// libs/core/src/lib/pack-directory.ts
function packDirectory(_pkg, dir, options) {
  const pkg = Package.lazy(_pkg, dir);
  const opts = {
    log: import_npmlog29.default,
    ...options
  };
  opts.log.verbose("pack-directory", import_path17.default.relative(".", pkg.contents));
  let chain = Promise.resolve();
  if (opts.ignorePrepublish !== true) {
    chain = chain.then(() => runLifecycle(pkg, "prepublish", opts));
  }
  chain = chain.then(() => runLifecycle(pkg, "prepare", opts));
  if (opts.lernaCommand === "publish") {
    opts.stdio = "inherit";
    chain = chain.then(() => pkg.refresh());
    chain = chain.then(() => runLifecycle(pkg, "prepublishOnly", opts));
    chain = chain.then(() => pkg.refresh());
  }
  chain = chain.then(() => runLifecycle(pkg, "prepack", opts));
  chain = chain.then(() => pkg.refresh());
  chain = chain.then(() => (0, import_npm_packlist.default)({ path: pkg.contents }));
  chain = chain.then(
    (files) => import_tar2.default.create(
      {
        cwd: pkg.contents,
        prefix: "package/",
        portable: true,
        mtime: new Date("1985-10-26T08:15:00.000Z"),
        gzip: true
      },
      files.map((f) => `./${f}`)
    )
  );
  chain = chain.then((stream) => temp_write_default(stream, getTarballName(pkg)));
  chain = chain.then(
    (tarFilePath) => getPacked(pkg, tarFilePath).then(
      (packed) => Promise.resolve().then(() => runLifecycle(pkg, "postpack", opts)).then(() => packed)
    )
  );
  return chain;
}
function getTarballName(pkg) {
  const name = pkg.name[0] === "@" ? pkg.name.substr(1).replace(/\//g, "-") : pkg.name;
  return `${name}-${pkg.version}.tgz`;
}
var import_path17, import_npm_packlist, import_npmlog29, import_tar2;
var init_pack_directory = __esm({
  "libs/core/src/lib/pack-directory.ts"() {
    "use strict";
    import_path17 = __toESM(require("path"));
    import_npm_packlist = __toESM(require("npm-packlist"));
    import_npmlog29 = __toESM(require("npmlog"));
    import_tar2 = __toESM(require("tar"));
    init_temp_write();
    init_get_packed();
    init_package();
    init_run_lifecycle();
  }
});

// libs/core/src/lib/profiler.ts
function generateProfileOutputPath(outputDirectory) {
  return import_upath.default.join(import_upath.default.resolve(outputDirectory || "."), getTimeBasedFilename());
}
var import_fs_extra7, import_npmlog30, import_upath, hrtimeToMicroseconds, range, getTimeBasedFilename, Profiler;
var init_profiler = __esm({
  "libs/core/src/lib/profiler.ts"() {
    "use strict";
    import_fs_extra7 = __toESM(require("fs-extra"));
    import_npmlog30 = __toESM(require("npmlog"));
    import_upath = __toESM(require("upath"));
    hrtimeToMicroseconds = (hrtime) => {
      return (hrtime[0] * 1e9 + hrtime[1]) / 1e3;
    };
    range = (len) => {
      return Array(len).fill().map((_, idx) => idx);
    };
    getTimeBasedFilename = () => {
      const now = new Date();
      const datetime = now.toISOString().split(".")[0];
      const datetimeNormalized = datetime.replace(/-|:/g, "");
      return `Lerna-Profile-${datetimeNormalized}.json`;
    };
    Profiler = class {
      events;
      logger;
      outputPath;
      threads;
      constructor({ concurrency, log: log36 = import_npmlog30.default, outputDirectory }) {
        this.events = [];
        this.logger = log36;
        this.outputPath = generateProfileOutputPath(outputDirectory);
        this.threads = range(concurrency);
      }
      run(fn, name) {
        let startTime;
        let threadId;
        return Promise.resolve().then(() => {
          startTime = process.hrtime();
          threadId = this.threads.shift();
        }).then(() => fn()).then((value) => {
          const duration = process.hrtime(startTime);
          const event = {
            name,
            ph: "X",
            ts: hrtimeToMicroseconds(startTime),
            pid: 1,
            tid: threadId,
            dur: hrtimeToMicroseconds(duration)
          };
          this.events.push(event);
          this.threads.unshift(threadId);
          this.threads.sort();
          return value;
        });
      }
      output() {
        return import_fs_extra7.default.outputJson(this.outputPath, this.events).then(() => this.logger.info("profiler", `Performance profile saved to ${this.outputPath}`));
      }
    };
  }
});

// libs/core/src/lib/pulse-till-done.ts
function pulseStart(prefix) {
  pulsers += 1;
  if (pulsers > 1) {
    return;
  }
  pulse = setInterval(() => import_npmlog31.default["gauge"].pulse(prefix), 150);
}
function pulseStop() {
  pulsers -= 1;
  if (pulsers > 0) {
    return;
  }
  clearInterval(pulse);
}
function pulseTillDone(prefix, promise) {
  if (!promise) {
    promise = prefix;
    prefix = "";
  }
  pulseStart(prefix);
  return Promise.resolve(promise).then(
    (val) => {
      pulseStop();
      return val;
    },
    (err) => {
      pulseStop();
      throw err;
    }
  );
}
var import_npmlog31, pulsers, pulse;
var init_pulse_till_done = __esm({
  "libs/core/src/lib/pulse-till-done.ts"() {
    "use strict";
    import_npmlog31 = __toESM(require("npmlog"));
    pulsers = 0;
  }
});

// libs/core/src/lib/rimraf-dir.ts
function rimrafDir(dirPath) {
  import_npmlog32.default.silly("rimrafDir", dirPath);
  return (0, import_path_exists.default)(dirPath).then((exists) => {
    if (!exists) {
      return;
    }
    const slashed = import_path18.default.normalize(`${dirPath}/`);
    const args = [RIMRAF_CLI, "--no-glob", slashed];
    return childProcess9.spawn(process.execPath, args).then(() => {
      import_npmlog32.default.verbose("rimrafDir", "removed", dirPath);
      return dirPath;
    });
  });
}
var import_npmlog32, import_path18, import_path_exists, childProcess9, RIMRAF_CLI;
var init_rimraf_dir = __esm({
  "libs/core/src/lib/rimraf-dir.ts"() {
    "use strict";
    import_npmlog32 = __toESM(require("npmlog"));
    import_path18 = __toESM(require("path"));
    import_path_exists = __toESM(require("path-exists"));
    childProcess9 = require("@lerna/child-process");
    RIMRAF_CLI = require.resolve("rimraf/bin");
  }
});

// libs/core/src/lib/run-topologically.ts
function runTopologically(packages, runner, { concurrency, graphType, rejectCycles } = {}) {
  const queue2 = new import_p_queue2.default({ concurrency });
  const graph = new QueryGraph(packages, { graphType, rejectCycles });
  return new Promise((resolve, reject) => {
    const returnValues = [];
    const queueNextAvailablePackages = () => graph.getAvailablePackages().forEach(({ pkg, name }) => {
      graph.markAsTaken(name);
      queue2.add(
        () => runner(pkg).then((value) => returnValues.push(value)).then(() => graph.markAsDone(pkg)).then(() => queueNextAvailablePackages())
      ).catch(reject);
    });
    queueNextAvailablePackages();
    queue2.onIdle().then(() => resolve(returnValues));
  });
}
var import_p_queue2;
var init_run_topologically = __esm({
  "libs/core/src/lib/run-topologically.ts"() {
    "use strict";
    import_p_queue2 = __toESM(require("p-queue"));
    init_query_graph();
  }
});

// libs/core/src/lib/scm-clients/github/create-github-client.ts
function createGitHubClient() {
  import_npmlog33.default.silly("createGitHubClient");
  const { GH_TOKEN, GHE_API_URL, GHE_VERSION } = process.env;
  if (!GH_TOKEN) {
    throw new Error("A GH_TOKEN environment variable is required.");
  }
  if (GHE_VERSION) {
    import_rest.Octokit.plugin(require(`@octokit/plugin-enterprise-rest/ghe-${GHE_VERSION}`));
  }
  const options = {
    auth: `token ${GH_TOKEN}`
  };
  if (GHE_API_URL) {
    options.baseUrl = GHE_API_URL;
  }
  return new import_rest.Octokit(options);
}
function parseGitRepo(remote = "origin", opts) {
  import_npmlog33.default.silly("parseGitRepo");
  const args = ["config", "--get", `remote.${remote}.url`];
  import_npmlog33.default.verbose("git", args);
  const url2 = childProcess10.execSync("git", args, opts);
  if (!url2) {
    throw new Error(`Git remote URL could not be found using "${remote}".`);
  }
  return (0, import_git_url_parse.default)(url2);
}
var import_npmlog33, import_rest, import_git_url_parse, childProcess10;
var init_create_github_client = __esm({
  "libs/core/src/lib/scm-clients/github/create-github-client.ts"() {
    "use strict";
    import_npmlog33 = __toESM(require("npmlog"));
    import_rest = require("@octokit/rest");
    import_git_url_parse = __toESM(require("git-url-parse"));
    childProcess10 = require("@lerna/child-process");
  }
});

// libs/core/src/lib/scm-clients/gitlab/gitlab-client.ts
var import_node_fetch, import_npmlog34, import_path19, GitLabClient;
var init_gitlab_client = __esm({
  "libs/core/src/lib/scm-clients/gitlab/gitlab-client.ts"() {
    "use strict";
    import_node_fetch = __toESM(require("node-fetch"));
    import_npmlog34 = __toESM(require("npmlog"));
    import_path19 = __toESM(require("path"));
    GitLabClient = class {
      constructor(token, baseUrl = "https://gitlab.com/api/v4") {
        this.token = token;
        this.baseUrl = baseUrl;
      }
      createRelease({ owner, repo, name, tag_name: tagName, body }) {
        const releasesUrl = this.releasesUrl(owner, repo, "releases");
        import_npmlog34.default.silly("Requesting GitLab releases", releasesUrl);
        return (0, import_node_fetch.default)(releasesUrl, {
          method: "post",
          body: JSON.stringify({ name, tag_name: tagName, description: body }),
          headers: {
            "PRIVATE-TOKEN": this.token,
            "Content-Type": "application/json"
          }
        }).then(({ ok, status, statusText }) => {
          if (!ok) {
            import_npmlog34.default.error("gitlab", `Failed to create release
Request returned ${status} ${statusText}`);
          } else {
            import_npmlog34.default.silly("gitlab", "Created release successfully.");
          }
        });
      }
      releasesUrl(namespace, project) {
        return new URL(
          `${this.baseUrl}/${import_path19.default.join("projects", encodeURIComponent(`${namespace}/${project}`), "releases")}`
        ).toString();
      }
    };
  }
});

// libs/core/src/lib/scm-clients/gitlab/create-gitlab-client.ts
function OcktokitAdapter(client) {
  return { repos: { createRelease: client.createRelease.bind(client) } };
}
function createGitLabClient() {
  const { GL_API_URL, GL_TOKEN } = process.env;
  import_npmlog35.default.silly("Creating a GitLab client...");
  if (!GL_TOKEN) {
    throw new Error("A GL_TOKEN environment variable is required.");
  }
  const client = new GitLabClient(GL_TOKEN, GL_API_URL);
  return OcktokitAdapter(client);
}
var import_npmlog35;
var init_create_gitlab_client = __esm({
  "libs/core/src/lib/scm-clients/gitlab/create-gitlab-client.ts"() {
    "use strict";
    import_npmlog35 = __toESM(require("npmlog"));
    init_gitlab_client();
  }
});

// libs/core/src/lib/scm-clients/index.ts
var init_scm_clients = __esm({
  "libs/core/src/lib/scm-clients/index.ts"() {
    "use strict";
    init_create_github_client();
    init_create_gitlab_client();
  }
});

// libs/core/src/lib/symlink-binary/index.ts
function symlinkBinary(srcPackageRef, destPackageRef) {
  return Promise.all([Package.lazy(srcPackageRef), Package.lazy(destPackageRef)]).then(
    ([srcPackage, destPackage]) => {
      const actions = Object.keys(srcPackage.bin).map((name) => {
        const srcLocation = srcPackage.contents ? import_path20.default.resolve(srcPackage.location, srcPackage.contents) : srcPackage.location;
        const src = import_path20.default.join(srcLocation, srcPackage.bin[name]);
        const dst = import_path20.default.join(destPackage.binLocation, name);
        return { src, dst };
      });
      if (actions.length === 0) {
        return Promise.resolve();
      }
      return import_fs_extra8.default.mkdirp(destPackage.binLocation).then(
        () => (0, import_p_map3.default)(actions, (meta) => {
          if (meta) {
            return createSymlink(meta.src, meta.dst, "exec");
          }
        })
      );
    }
  );
}
var import_fs_extra8, import_p_map3, import_path20;
var init_symlink_binary = __esm({
  "libs/core/src/lib/symlink-binary/index.ts"() {
    "use strict";
    import_fs_extra8 = __toESM(require("fs-extra"));
    import_p_map3 = __toESM(require("p-map"));
    import_path20 = __toESM(require("path"));
    init_create_symlink();
    init_package();
  }
});

// libs/core/src/lib/resolve-symlink.ts
function resolveSymlink(filePath) {
  import_npmlog36.default.silly("resolveSymlink", filePath);
  let result;
  if (process.platform === "win32") {
    result = resolveWindowsSymlink(filePath);
  } else {
    result = resolvePosixSymlink(filePath);
  }
  import_npmlog36.default.verbose("resolveSymlink", [filePath, result]);
  return result;
}
function resolveSymbolicLink(filePath) {
  const lstat = import_fs_extra9.default.lstatSync(filePath);
  const resolvedPath = lstat.isSymbolicLink() ? import_path21.default.resolve(import_path21.default.dirname(filePath), import_fs_extra9.default.readlinkSync(filePath)) : false;
  return {
    resolvedPath,
    lstat
  };
}
function resolvePosixSymlink(filePath) {
  return resolveSymbolicLink(filePath).resolvedPath;
}
function resolveWindowsSymlink(filePath) {
  const { resolvedPath, lstat } = resolveSymbolicLink(filePath);
  if (lstat.isFile() && !resolvedPath) {
    try {
      return import_path21.default.resolve(import_path21.default.dirname(filePath), readCmdShim.sync(filePath));
    } catch (e) {
      return false;
    }
  }
  return resolvedPath && import_path21.default.resolve(resolvedPath);
}
var import_fs_extra9, import_npmlog36, import_path21, readCmdShim;
var init_resolve_symlink = __esm({
  "libs/core/src/lib/resolve-symlink.ts"() {
    "use strict";
    import_fs_extra9 = __toESM(require("fs-extra"));
    import_npmlog36 = __toESM(require("npmlog"));
    import_path21 = __toESM(require("path"));
    readCmdShim = require("read-cmd-shim");
  }
});

// libs/core/src/lib/symlink-dependencies.ts
function symlinkDependencies(packages, packageGraph, tracker) {
  tracker.info("", "Symlinking packages and binaries");
  tracker.addWork(packages.length);
  const nodes = packageGraph.size === packages.length ? packageGraph.values() : new Set(packages.map(({ name }) => packageGraph.get(name)));
  return (0, import_p_map_series.default)(nodes, (currentNode) => {
    const currentName = currentNode.name;
    const currentNodeModules = currentNode.pkg.nodeModulesLocation;
    return (0, import_p_map4.default)(currentNode.localDependencies, ([dependencyName, resolved]) => {
      if (resolved.type === "directory") {
        return;
      }
      const dependencyNode = packageGraph.get(dependencyName);
      const targetDirectory = import_path22.default.join(currentNodeModules, dependencyName);
      let chain = Promise.resolve();
      chain = chain.then(() => import_fs_extra10.default.pathExists(targetDirectory));
      chain = chain.then((dirExists) => {
        if (dirExists) {
          const isDepSymlink = resolveSymlink(targetDirectory);
          if (isDepSymlink !== false && isDepSymlink !== dependencyNode.location) {
            tracker.warn(
              "EREPLACE_OTHER",
              `Symlink already exists for ${dependencyName} dependency of ${currentName}, but links to different location. Replacing with updated symlink...`
            );
          } else if (isDepSymlink === false) {
            tracker.warn(
              "EREPLACE_EXIST",
              `${dependencyName} is already installed for ${currentName}. Replacing with symlink...`
            );
            return import_fs_extra10.default.remove(targetDirectory);
          }
        } else {
          return import_fs_extra10.default.ensureDir(import_path22.default.dirname(targetDirectory));
        }
      });
      const dependencyLocation = dependencyNode.pkg.contents ? import_path22.default.resolve(dependencyNode.location, dependencyNode.pkg.contents) : dependencyNode.location;
      chain = chain.then(() => createSymlink(dependencyLocation, targetDirectory, "junction"));
      chain = chain.then(() => symlinkBinary(dependencyNode.pkg, currentNode.pkg));
      return chain;
    }).then(() => {
      tracker.silly("actions", "finished", currentName);
      tracker.completeWork(1);
    });
  }).finally(() => tracker.finish());
}
var import_fs_extra10, import_p_map4, import_p_map_series, import_path22;
var init_symlink_dependencies = __esm({
  "libs/core/src/lib/symlink-dependencies.ts"() {
    "use strict";
    import_fs_extra10 = __toESM(require("fs-extra"));
    import_p_map4 = __toESM(require("p-map"));
    import_p_map_series = __toESM(require("p-map-series"));
    import_path22 = __toESM(require("path"));
    init_create_symlink();
    init_resolve_symlink();
    init_symlink_binary();
  }
});

// libs/core/src/lib/timer.ts
function timer() {
  if (process.env["LERNA_INTEGRATION"]) {
    return () => 0;
  }
  const startMillis = Date.now();
  return () => Date.now() - startMillis;
}
var init_timer = __esm({
  "libs/core/src/lib/timer.ts"() {
    "use strict";
  }
});

// libs/core/src/lib/npm-dist-tag.ts
var npm_dist_tag_exports = {};
__export(npm_dist_tag_exports, {
  add: () => add,
  list: () => list,
  remove: () => remove
});
function add(spec, tag, options, otpCache) {
  const opts = {
    log: import_npmlog37.default,
    ...options,
    spec: (0, import_npm_package_arg6.default)(spec)
  };
  const cleanTag = (tag || opts.defaultTag || opts.tag).trim();
  const { name, rawSpec: version } = opts.spec;
  opts.log.verbose("dist-tag", `adding "${cleanTag}" to ${name}@${version}`);
  if (opts.dryRun) {
    opts.log.silly("dist-tag", "dry-run configured, bailing now");
    return Promise.resolve();
  }
  return fetchTags(opts).then((tags) => {
    if (tags[cleanTag] === version) {
      opts.log.warn("dist-tag", `${name}@${cleanTag} already set to ${version}`);
      return tags;
    }
    const uri = `/-/package/${opts.spec.escapedName}/dist-tags/${encodeURIComponent(cleanTag)}`;
    const payload = {
      ...opts,
      method: "PUT",
      body: JSON.stringify(version),
      headers: {
        "content-type": "application/json"
      },
      spec: opts.spec
    };
    return otplease((wrappedPayload) => (0, import_npm_registry_fetch.default)(uri, wrappedPayload), payload, otpCache).then(() => {
      opts.log.verbose("dist-tag", `added "${cleanTag}" to ${name}@${version}`);
      tags[cleanTag] = version;
      return tags;
    });
  });
}
function remove(spec, tag, options, otpCache) {
  const opts = {
    log: import_npmlog37.default,
    ...options,
    spec: (0, import_npm_package_arg6.default)(spec)
  };
  opts.log.verbose("dist-tag", `removing "${tag}" from ${opts.spec.name}`);
  if (opts.dryRun) {
    opts.log.silly("dist-tag", "dry-run configured, bailing now");
    return Promise.resolve();
  }
  return fetchTags(opts).then((tags) => {
    const version = tags[tag];
    if (!version) {
      opts.log.info("dist-tag", `"${tag}" is not a dist-tag on ${opts.spec.name}`);
      return tags;
    }
    const uri = `/-/package/${opts.spec.escapedName}/dist-tags/${encodeURIComponent(tag)}`;
    const payload = {
      ...opts,
      method: "DELETE",
      spec: opts.spec
    };
    return otplease((wrappedPayload) => (0, import_npm_registry_fetch.default)(uri, wrappedPayload), payload, otpCache).then(() => {
      opts.log.verbose("dist-tag", `removed "${tag}" from ${opts.spec.name}@${version}`);
      delete tags[tag];
      return tags;
    });
  });
}
function list(spec, options) {
  const opts = {
    log: import_npmlog37.default,
    ...options,
    spec: (0, import_npm_package_arg6.default)(spec)
  };
  if (opts.dryRun) {
    opts.log.silly("dist-tag", "dry-run configured, bailing now");
    return Promise.resolve();
  }
  return fetchTags(opts);
}
function fetchTags(opts) {
  return import_npm_registry_fetch.default.json(`/-/package/${opts.spec.escapedName}/dist-tags`, {
    ...opts,
    preferOnline: true,
    spec: opts.spec
  }).then((data) => {
    if (data && typeof data === "object") {
      delete data["_etag"];
    }
    return data || {};
  });
}
var import_npm_package_arg6, import_npm_registry_fetch, import_npmlog37;
var init_npm_dist_tag = __esm({
  "libs/core/src/lib/npm-dist-tag.ts"() {
    "use strict";
    import_npm_package_arg6 = __toESM(require("npm-package-arg"));
    import_npm_registry_fetch = __toESM(require("npm-registry-fetch"));
    import_npmlog37 = __toESM(require("npmlog"));
    init_otplease();
  }
});

// libs/core/src/index.ts
var npmConf2, npmDistTag;
var init_src = __esm({
  "libs/core/src/index.ts"() {
    "use strict";
    init_check_working_tree();
    init_cli();
    init_collect_updates();
    init_command();
    init_conventional_commits();
    init_create_symlink();
    init_describe_ref();
    init_filter_options();
    init_has_npm_version();
    init_listable_format();
    init_listable_options();
    init_log_packed();
    init_npm_install();
    init_npm_publish();
    init_npm_run_script();
    init_otplease();
    init_output();
    init_pack_directory();
    init_package();
    init_package_graph();
    init_prerelease_id_from_version();
    init_profiler();
    init_project();
    init_prompt();
    init_pulse_till_done();
    init_rimraf_dir();
    init_run_lifecycle();
    init_run_topologically();
    init_scm_clients();
    init_symlink_binary();
    init_symlink_dependencies();
    init_temp_write();
    init_timer();
    init_validation_error();
    npmConf2 = require_npm_conf();
    npmDistTag = (init_npm_dist_tag(), __toCommonJS(npm_dist_tag_exports));
  }
});

// libs/commands/bootstrap/src/lib/has-dependency-installed.ts
var require_has_dependency_installed = __commonJS({
  "libs/commands/bootstrap/src/lib/has-dependency-installed.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_arborist = __toESM(require("@npmcli/arborist"));
    var import_semver5 = __toESM(require("semver"));
    var cache = /* @__PURE__ */ new Map();
    module2.exports.hasDependencyInstalled = hasDependencyInstalled;
    function hasDependencyInstalled(pkg, depName, needVersion) {
      import_npmlog38.default.silly("hasDependencyInstalled", pkg.name, depName);
      return getInstalled(pkg).then(
        (versions) => versions.has(depName) && import_semver5.default.satisfies(versions.get(depName), needVersion)
      );
    }
    function getInstalled(pkg) {
      if (cache.has(pkg)) {
        return Promise.resolve(cache.get(pkg));
      }
      const arb = new import_arborist.default({
        path: pkg.location
      });
      return arb.loadActual().then((tree) => {
        const deps = /* @__PURE__ */ new Map();
        for (const [dependencyName, node] of tree.children.entries()) {
          deps.set(dependencyName, node.version);
        }
        cache.set(pkg, deps);
        return deps;
      });
    }
  }
});

// libs/commands/bootstrap/src/lib/is-hoisted-package.ts
var require_is_hoisted_package = __commonJS({
  "libs/commands/bootstrap/src/lib/is-hoisted-package.ts"(exports, module2) {
    "use strict";
    var import_multimatch2 = __toESM(require("multimatch"));
    module2.exports.isHoistedPackage = isHoistedPackage;
    function isHoistedPackage(name, hoisting) {
      return (0, import_multimatch2.default)([name], hoisting).length > 0;
    }
  }
});

// libs/commands/bootstrap/src/index.ts
var require_src = __commonJS({
  "libs/commands/bootstrap/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_dedent5 = __toESM(require("dedent"));
    var import_get_port = __toESM(require("get-port"));
    var import_npm_package_arg7 = __toESM(require("npm-package-arg"));
    var import_p_map5 = __toESM(require("p-map"));
    var import_p_map_series2 = __toESM(require("p-map-series"));
    var import_p_waterfall = __toESM(require("p-waterfall"));
    var import_path23 = __toESM(require("path"));
    var { hasDependencyInstalled } = require_has_dependency_installed();
    var { isHoistedPackage } = require_is_hoisted_package();
    module2.exports = function factory(argv) {
      return new BootstrapCommand(argv);
    };
    var BootstrapCommand = class extends Command {
      get requiresGit() {
        return false;
      }
      initialize() {
        const { registry, npmClient = "npm", npmClientArgs = [], mutex, hoist, nohoist } = this.options;
        if (npmClient === "pnpm") {
          throw new ValidationError(
            "EWORKSPACES",
            "Bootstrapping with pnpm is not supported. Use pnpm directly to manage dependencies: https://pnpm.io/cli/install"
          );
        }
        if (npmClient === "yarn" && hoist) {
          throw new ValidationError(
            "EWORKSPACES",
            import_dedent5.default`
            --hoist is not supported with --npm-client=yarn, use yarn workspaces instead
            A guide is available at https://yarnpkg.com/blog/2017/08/02/introducing-workspaces/
          `
          );
        }
        if (npmClient === "yarn" && this.project.manifest.get("workspaces") && this.options.useWorkspaces !== true) {
          throw new ValidationError(
            "EWORKSPACES",
            import_dedent5.default`
            Yarn workspaces are configured in package.json, but not enabled in lerna.json!
            Please choose one: useWorkspaces = true in lerna.json, or remove package.json workspaces config
          `
          );
        }
        const { LERNA_EXEC_PATH = "leaf", LERNA_ROOT_PATH = "root" } = process.env;
        if (LERNA_EXEC_PATH === LERNA_ROOT_PATH) {
          this.logger.warn("bootstrap", "Skipping recursive execution");
          return false;
        }
        if (hoist) {
          let hoisting;
          if (hoist === true) {
            hoisting = ["**"];
          } else {
            hoisting = [].concat(hoist);
          }
          if (nohoist) {
            if (!Array.isArray(nohoist)) {
              hoisting = hoisting.concat(`!${nohoist}`);
            } else {
              hoisting = hoisting.concat(nohoist.map((str) => `!${str}`));
            }
          }
          this.logger.verbose("hoist", "using globs %j", hoisting);
          this.hoisting = hoisting;
        }
        this.runPackageLifecycle = createRunner({ registry });
        this.npmConfig = {
          registry,
          npmClient,
          npmClientArgs,
          mutex
        };
        if (npmClient === "npm" && this.options.ci && hasNpmVersion(">=5.7.0")) {
          this.npmConfig.subCommand = this.hoisting ? "install" : "ci";
          if (this.hoisting) {
            this.npmConfig.npmClientArgs.unshift("--no-save");
          }
        }
        const doubleDashArgs = this.options["--"] || [];
        if (doubleDashArgs.length) {
          this.npmConfig.npmClientArgs = [...npmClientArgs, ...doubleDashArgs];
        }
        if (this.options.ignoreScripts) {
          this.npmConfig.npmClientArgs.unshift("--ignore-scripts");
        }
        this.targetGraph = this.options.forceLocal ? new PackageGraph(this.packageGraph.rawPackageList, "allDependencies", "forceLocal") : this.packageGraph;
        let chain = Promise.resolve();
        chain = chain.then(() => {
          return getFilteredPackages(this.targetGraph, this.execOpts, this.options);
        });
        chain = chain.then((filteredPackages) => {
          this.filteredPackages = filteredPackages;
          if (this.options.contents) {
            for (const pkg of filteredPackages) {
              pkg.contents = this.options.contents;
            }
          }
          if (filteredPackages.length !== this.targetGraph.size && !this.options.forceLocal) {
            this.logger.warn("bootstrap", "Installing local packages that do not match filters from registry");
            this.targetGraph = new PackageGraph(filteredPackages, "allDependencies", this.options.forceLocal);
            this.npmConfig.npmClientArgs.unshift(npmClient === "yarn" ? "--pure-lockfile" : "--no-save");
            if (this.npmConfig.subCommand === "ci") {
              this.npmConfig.subCommand = "install";
            }
          }
        });
        chain = chain.then(() => {
          if (npmClient === "yarn" && !mutex) {
            return (0, import_get_port.default)({ port: 42424, host: "0.0.0.0" }).then((port) => {
              this.npmConfig.mutex = `network:${port}`;
              this.logger.silly("npmConfig", this.npmConfig);
            });
          }
          this.logger.silly("npmConfig", this.npmConfig);
        });
        return chain;
      }
      execute() {
        if (this.options.useWorkspaces || this.rootHasLocalFileDependencies()) {
          if (this.options.rejectCycles) {
            this.packageGraph.collapseCycles({ rejectCycles: this.options.rejectCycles });
          }
          return this.installRootPackageOnly();
        }
        const filteredLength = this.filteredPackages.length;
        const packageCountLabel = `${filteredLength} package${filteredLength > 1 ? "s" : ""}`;
        const scriptsEnabled = this.options.ignoreScripts !== true;
        this.enableProgressBar();
        this.logger.info("", `Bootstrapping ${packageCountLabel}`);
        const tasks = [];
        if (scriptsEnabled) {
          tasks.push(() => this.runLifecycleInPackages("preinstall"));
        }
        tasks.push(
          () => this.getDependenciesToInstall(),
          (result) => this.installExternalDependencies(result),
          () => this.symlinkPackages()
        );
        if (scriptsEnabled) {
          tasks.push(
            () => this.runLifecycleInPackages("install"),
            () => this.runLifecycleInPackages("postinstall")
          );
          if (!this.options.ignorePrepublish) {
            tasks.push(() => this.runLifecycleInPackages("prepublish"));
          }
          tasks.push(() => this.runLifecycleInPackages("prepare"));
        }
        return (0, import_p_waterfall.default)(tasks).then(() => {
          this.logger.success("", `Bootstrapped ${packageCountLabel}`);
        });
      }
      installRootPackageOnly() {
        this.logger.info("bootstrap", "root only");
        this.npmConfig.stdio = "inherit";
        return npmInstall(this.project.manifest, this.npmConfig);
      }
      rootHasLocalFileDependencies() {
        const rootDependencies = Object.assign({}, this.project.manifest.dependencies);
        return Object.keys(rootDependencies).some(
          (name) => this.targetGraph.has(name) && import_npm_package_arg7.default.resolve(name, rootDependencies[name], this.project.rootPath).type === "directory"
        );
      }
      runLifecycleInPackages(stage) {
        this.logger.verbose("lifecycle", stage);
        if (!this.filteredPackages.length) {
          return;
        }
        const tracker = this.logger.newItem(stage);
        const mapPackageWithScript = (pkg) => this.runPackageLifecycle(pkg, stage).then(() => {
          tracker.completeWork(1);
        });
        tracker.addWork(this.filteredPackages.length);
        const runner = this.toposort ? runTopologically(this.filteredPackages, mapPackageWithScript, {
          concurrency: this.concurrency,
          rejectCycles: this.options.rejectCycles
        }) : (0, import_p_map5.default)(this.filteredPackages, mapPackageWithScript, { concurrency: this.concurrency });
        return runner.finally(() => tracker.finish());
      }
      hoistedDirectory(dependency) {
        return import_path23.default.join(this.project.rootPath, "node_modules", dependency);
      }
      hoistedPackageJson(dependency) {
        try {
          return require(import_path23.default.join(this.hoistedDirectory(dependency), "package.json"));
        } catch (e) {
          return {};
        }
      }
      getDependenciesToInstall() {
        const rootPkg = this.project.manifest;
        const rootSet = /* @__PURE__ */ new Set();
        const leaves = /* @__PURE__ */ new Map();
        const depsToInstall = /* @__PURE__ */ new Map();
        const filteredNodes = new Map(
          this.filteredPackages.map((pkg) => [pkg.name, this.targetGraph.get(pkg.name)])
        );
        const mergedRootDeps = Object.assign(
          {},
          rootPkg.devDependencies,
          rootPkg.optionalDependencies,
          rootPkg.dependencies
        );
        const rootExternalVersions = new Map(
          Object.keys(mergedRootDeps).map((externalName) => [externalName, mergedRootDeps[externalName]])
        );
        rootExternalVersions.forEach((version, externalName) => {
          const externalDependents = /* @__PURE__ */ new Set();
          const record = /* @__PURE__ */ new Map();
          record.set(version, externalDependents);
          depsToInstall.set(externalName, record);
        });
        for (const [leafName, leafNode] of filteredNodes) {
          for (const [externalName, resolved] of leafNode.externalDependencies) {
            const version = resolved.rawSpec;
            const record = depsToInstall.get(externalName) || depsToInstall.set(externalName, /* @__PURE__ */ new Map()).get(externalName);
            const externalDependents = record.get(version) || record.set(version, /* @__PURE__ */ new Set()).get(version);
            externalDependents.add(leafName);
          }
        }
        const rootActions = [];
        const leafActions = [];
        let strictExitOnWarning = false;
        for (const [externalName, externalDependents] of depsToInstall) {
          let rootVersion;
          if (this.hoisting && isHoistedPackage(externalName, this.hoisting)) {
            const commonVersion = Array.from(externalDependents.keys()).reduce(
              (a, b) => externalDependents.get(a).size > externalDependents.get(b).size ? a : b
            );
            rootVersion = rootExternalVersions.get(externalName) || commonVersion;
            if (rootVersion !== commonVersion) {
              this.logger.warn(
                "EHOIST_ROOT_VERSION",
                `The repository root depends on ${externalName}@${rootVersion}, which differs from the more common ${externalName}@${commonVersion}.`
              );
              if (this.options.strict) {
                strictExitOnWarning = true;
              }
            }
            const dependents = Array.from(externalDependents.get(rootVersion)).map(
              (leafName) => this.targetGraph.get(leafName).pkg
            );
            externalDependents.delete(rootVersion);
            rootActions.push(
              () => hasDependencyInstalled(rootPkg, externalName, rootVersion).then((isSatisfied) => {
                rootSet.add({
                  name: externalName,
                  dependents,
                  dependency: `${externalName}@${rootVersion}`,
                  isSatisfied
                });
              })
            );
          }
          for (const [leafVersion, leafDependents] of externalDependents) {
            for (const leafName of leafDependents) {
              if (rootVersion) {
                this.logger.warn(
                  "EHOIST_PKG_VERSION",
                  `"${leafName}" package depends on ${externalName}@${leafVersion}, which differs from the hoisted ${externalName}@${rootVersion}.`
                );
                if (this.options.strict) {
                  strictExitOnWarning = true;
                }
              }
              const leafNode = this.targetGraph.get(leafName);
              const leafRecord = leaves.get(leafNode) || leaves.set(leafNode, /* @__PURE__ */ new Set()).get(leafNode);
              leafActions.push(
                () => hasDependencyInstalled(leafNode.pkg, externalName, leafVersion).then((isSatisfied) => {
                  leafRecord.add({
                    dependency: `${externalName}@${leafVersion}`,
                    isSatisfied
                  });
                })
              );
            }
          }
        }
        if (this.options.strict && strictExitOnWarning) {
          throw new ValidationError(
            "EHOISTSTRICT",
            "Package version inconsistencies found while hoisting. Fix the above warnings and retry."
          );
        }
        return (0, import_p_map_series2.default)([...rootActions, ...leafActions], (el) => el()).then(() => {
          this.logger.silly("root dependencies", JSON.stringify(rootSet, null, 2));
          this.logger.silly("leaf dependencies", JSON.stringify(leaves, null, 2));
          return { rootSet, leaves };
        });
      }
      installExternalDependencies({ leaves, rootSet }) {
        const tracker = this.logger.newItem("install dependencies");
        const rootPkg = this.project.manifest;
        const actions = [];
        if (rootSet.size) {
          const root = Array.from(rootSet);
          actions.push(() => {
            const depsToInstallInRoot = root.some(({ isSatisfied }) => !isSatisfied) ? root.map(({ dependency }) => dependency) : [];
            if (depsToInstallInRoot.length) {
              tracker.info("hoist", "Installing hoisted dependencies into root");
            }
            const promise = npmInstallDependencies(rootPkg, depsToInstallInRoot, this.npmConfig);
            return pulseTillDone(promise).then(
              () => (0, import_p_map_series2.default)(root, ({ name, dependents }) => {
                const { bin } = this.hoistedPackageJson(name);
                if (bin) {
                  return (0, import_p_map5.default)(dependents, (pkg) => {
                    const src = this.hoistedDirectory(name);
                    return symlinkBinary(src, pkg);
                  });
                }
              })
            ).then(() => {
              tracker.info("hoist", "Finished bootstrapping root");
              tracker.completeWork(1);
            });
          });
          actions.push(() => {
            const candidates = root.filter((dep) => dep.dependents.length).reduce((list2, { name, dependents }) => {
              const dirs = dependents.filter((pkg) => pkg.nodeModulesLocation !== rootPkg.nodeModulesLocation).map((pkg) => import_path23.default.join(pkg.nodeModulesLocation, name));
              return list2.concat(dirs);
            }, []);
            if (!candidates.length) {
              tracker.verbose("hoist", "nothing to prune");
              tracker.completeWork(1);
              return;
            }
            tracker.info("hoist", "Pruning hoisted dependencies");
            tracker.silly("prune", candidates);
            tracker.addWork(candidates.length);
            return (0, import_p_map5.default)(
              candidates,
              (dirPath) => pulseTillDone(rimrafDir(dirPath)).then(() => {
                tracker.verbose("prune", dirPath);
                tracker.completeWork(1);
              }),
              { concurrency: this.concurrency }
            ).then(() => {
              tracker.info("hoist", "Finished pruning hoisted dependencies");
              tracker.completeWork(1);
            });
          });
        }
        const leafNpmConfig = Object.assign({}, this.npmConfig, {
          npmGlobalStyle: !!this.options.hoist
        });
        leaves.forEach((leafRecord, leafNode) => {
          const deps = Array.from(leafRecord);
          if (deps.some(({ isSatisfied }) => !isSatisfied)) {
            actions.push(() => {
              const dependencies = deps.map(({ dependency }) => dependency);
              const promise = npmInstallDependencies(leafNode.pkg, dependencies, leafNpmConfig);
              return pulseTillDone(promise).then(() => {
                tracker.verbose("installed leaf", leafNode.name);
                tracker.completeWork(1);
              });
            });
          }
        });
        if (actions.length) {
          tracker.info("", "Installing external dependencies");
          tracker.verbose("actions", "%d actions, concurrency %d", actions.length, this.concurrency);
          tracker.addWork(actions.length);
        }
        return (0, import_p_map5.default)(actions, (act) => act(), { concurrency: this.concurrency }).finally(() => tracker.finish());
      }
      symlinkPackages() {
        return symlinkDependencies(
          this.filteredPackages,
          this.targetGraph,
          this.logger.newItem("bootstrap dependencies")
        );
      }
    };
    module2.exports.BootstrapCommand = BootstrapCommand;
  }
});

// libs/commands/add/src/lib/get-range-to-reference.ts
var require_get_range_to_reference = __commonJS({
  "libs/commands/add/src/lib/get-range-to-reference.ts"(exports, module2) {
    "use strict";
    var import_npm_package_arg7 = __toESM(require("npm-package-arg"));
    var import_path23 = __toESM(require("path"));
    var import_semver5 = __toESM(require("semver"));
    module2.exports.getRangeToReference = getRangeToReference;
    function getRangeToReference(spec, deps, loc, prefix) {
      const current = deps[spec.name];
      const resolved = spec.type === "tag" ? `${prefix}${spec.version}` : spec.fetchSpec;
      if (spec.saveRelativeFileSpec) {
        return import_npm_package_arg7.default.resolve(spec.name, import_path23.default.relative(loc, spec.version), loc).saveSpec;
      }
      if (prefix && current && import_semver5.default.intersects(current, resolved)) {
        return current;
      }
      return resolved;
    }
  }
});

// libs/commands/add/src/index.ts
var require_src2 = __commonJS({
  "libs/commands/add/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_dedent5 = __toESM(require("dedent"));
    var import_npm_package_arg7 = __toESM(require("npm-package-arg"));
    var import_p_map5 = __toESM(require("p-map"));
    var import_pacote = __toESM(require("pacote"));
    var import_path23 = __toESM(require("path"));
    var import_semver5 = __toESM(require("semver"));
    var bootstrap = require_src();
    var { getRangeToReference } = require_get_range_to_reference();
    module2.exports = function factory(argv) {
      return new AddCommand(argv);
    };
    var AddCommand = class extends Command {
      get requiresGit() {
        return false;
      }
      get dependencyType() {
        if (this.options.dev) {
          return "devDependencies";
        }
        if (this.options.peer) {
          return "peerDependencies";
        }
        return "dependencies";
      }
      initialize() {
        if (this.options.npmClient === "pnpm") {
          throw new ValidationError(
            "EPNPMNOTSUPPORTED",
            "Add is not supported when using `pnpm` workspaces. Use `pnpm` directly to add dependencies to packages: https://pnpm.io/cli/add"
          );
        }
        this.spec = (0, import_npm_package_arg7.default)(this.options.pkg);
        this.dirs = new Set(this.options.globs.map((fp) => import_path23.default.resolve(this.project.rootPath, fp)));
        this.selfSatisfied = this.packageSatisfied();
        this.savePrefix = this.options.exact ? "" : "^";
        if (this.packageGraph.has(this.spec.name) && !this.selfSatisfied) {
          const available = this.packageGraph.get(this.spec.name).version;
          throw new ValidationError(
            "ENOTSATISFIED",
            import_dedent5.default`
          Requested range not satisfiable:
          ${this.spec.name}@${this.spec.fetchSpec} (available: ${available})
        `
          );
        }
        let chain = Promise.resolve();
        chain = chain.then(() => this.getPackageVersion());
        chain = chain.then((version) => {
          if (version == null) {
            throw new ValidationError(
              "ENOTSATISFIED",
              import_dedent5.default`
            Requested package has no version: ${this.spec.name}
          `
            );
          }
          this.spec.version = version;
        });
        chain = chain.then(() => getFilteredPackages(this.packageGraph, this.execOpts, this.options));
        chain = chain.then((filteredPackages) => {
          this.filteredPackages = filteredPackages;
        });
        chain = chain.then(() => this.collectPackagesToChange());
        chain = chain.then((packagesToChange) => {
          this.packagesToChange = packagesToChange;
        });
        return chain.then(() => {
          const proceed = this.packagesToChange.length > 0;
          if (!proceed) {
            this.logger.warn(`No packages found where ${this.spec.name} can be added.`);
          }
          return proceed;
        });
      }
      execute() {
        const numberOfPackages = `${this.packagesToChange.length} package${this.packagesToChange.length > 1 ? "s" : ""}`;
        this.logger.info("", `Adding ${this.spec.name} in ${numberOfPackages}`);
        let chain = Promise.resolve();
        chain = chain.then(() => this.makeChanges());
        if (this.options.bootstrap !== false) {
          chain = chain.then(() => {
            const argv = Object.assign({}, this.options, {
              args: [],
              cwd: this.project.rootPath,
              composed: "add",
              scope: void 0,
              ignore: void 0,
              private: void 0,
              since: void 0,
              excludeDependents: void 0,
              includeDependents: void 0,
              includeDependencies: void 0
            });
            return bootstrap(argv);
          });
        }
        return chain;
      }
      collectPackagesToChange() {
        const { name: targetName } = this.spec;
        let result = this.filteredPackages;
        if (this.packageGraph.has(targetName)) {
          result = result.filter((pkg) => pkg.name !== targetName);
        }
        if (this.dirs.size) {
          result = result.filter((pkg) => this.dirs.has(pkg.location));
        }
        result = result.filter((pkg) => {
          const deps = this.getPackageDeps(pkg);
          if (!(targetName in deps)) {
            return true;
          }
          return getRangeToReference(this.spec, deps, pkg.location, this.savePrefix) !== deps[targetName];
        });
        return result;
      }
      makeChanges() {
        const { name: targetName } = this.spec;
        return (0, import_p_map5.default)(this.packagesToChange, (pkg) => {
          const deps = this.getPackageDeps(pkg);
          const range2 = getRangeToReference(this.spec, deps, pkg.location, this.savePrefix);
          this.logger.verbose("add", `${targetName}@${range2} to ${this.dependencyType} in ${pkg.name}`);
          deps[targetName] = range2;
          return pkg.serialize();
        });
      }
      getPackageDeps(pkg) {
        let deps = pkg.get(this.dependencyType);
        if (!deps) {
          deps = {};
          pkg.set(this.dependencyType, deps);
        }
        return deps;
      }
      getPackageVersion() {
        if (this.selfSatisfied) {
          const node = this.packageGraph.get(this.spec.name);
          return Promise.resolve(this.spec.saveRelativeFileSpec ? node.location : node.version);
        }
        const opts = npmConf2({
          includeDeprecated: false,
          registry: this.options.registry
        });
        return import_pacote.default.manifest(this.spec, opts.snapshot).then((pkg) => pkg.version);
      }
      packageSatisfied() {
        const { name, fetchSpec } = this.spec;
        const pkg = this.packageGraph.get(name);
        if (!pkg) {
          return false;
        }
        if (this.spec.type === "directory" && fetchSpec === pkg.location) {
          this.spec.saveRelativeFileSpec = true;
          return true;
        }
        this.spec.saveRelativeFileSpec = Array.from(this.packageGraph.values()).some(
          (node) => node.localDependencies.size && Array.from(node.localDependencies.values()).some((resolved) => resolved.type === "directory")
        );
        if (fetchSpec === "latest") {
          return true;
        }
        return import_semver5.default.intersects(pkg.version, fetchSpec);
      }
    };
    module2.exports.AddCommand = AddCommand;
  }
});

// libs/commands/add/src/command.ts
var require_command = __commonJS({
  "libs/commands/add/src/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "add <pkg> [globs..]",
      describe: "Add a single dependency to matched packages",
      builder(yargs2) {
        yargs2.positional("pkg", {
          describe: "Package name to add as a dependency",
          type: "string"
        }).positional("globs", {
          describe: "Optional package directory globs to match",
          type: "array"
        }).options({
          D: {
            group: "Command Options:",
            type: "boolean",
            alias: "dev",
            describe: "Save to devDependencies"
          },
          E: {
            group: "Command Options:",
            type: "boolean",
            alias: "exact",
            describe: "Save version exactly"
          },
          P: {
            group: "Command Options:",
            type: "boolean",
            alias: "peer",
            describe: "Save to peerDependencies"
          },
          registry: {
            group: "Command Options:",
            describe: "Use the specified registry for all npm client operations.",
            type: "string",
            requiresArg: true
          },
          "no-bootstrap": {
            group: "Command Options:",
            describe: "Do not automatically chain `lerna bootstrap` after changes are made.",
            type: "boolean"
          },
          bootstrap: {
            hidden: true,
            type: "boolean"
          }
        }).example(
          "$0 add module-1 packages/prefix-*",
          "Adds the module-1 package to the packages in the 'prefix-' prefixed folders"
        ).example("$0 add module-1 --scope=module-2", "Install module-1 to module-2").example("$0 add module-1 --scope=module-2 --dev", "Install module-1 to module-2 in devDependencies").example("$0 add module-1 --scope=module-2 --peer", "Install module-1 to module-2 in peerDependencies").example("$0 add module-1", "Install module-1 in all modules except module-1").example("$0 add module-1 --no-bootstrap", "Skip automatic `lerna bootstrap`").example("$0 add babel-core", "Install babel-core in all modules");
        return filterOptions(yargs2);
      },
      handler(argv) {
        return require_src2()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/bootstrap/src/command.ts
var require_command2 = __commonJS({
  "libs/commands/bootstrap/src/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "bootstrap",
      describe: "Link local packages together and install remaining package dependencies",
      builder(yargs2) {
        yargs2.example(
          "$0 bootstrap -- --no-optional",
          "# execute `npm install --no-optional` in bootstrapped packages"
        ).parserConfiguration({
          "populate--": true
        }).options({
          hoist: {
            group: "Command Options:",
            describe: "Install external dependencies matching [glob] to the repo root",
            defaultDescription: "'**'"
          },
          nohoist: {
            group: "Command Options:",
            describe: "Don't hoist external dependencies matching [glob] to the repo root",
            type: "string",
            requiresArg: true
          },
          mutex: {
            hidden: true
          },
          "ignore-prepublish": {
            group: "Command Options:",
            describe: "Don't run prepublish lifecycle scripts in bootstrapped packages.",
            type: "boolean"
          },
          "ignore-scripts": {
            group: "Command Options:",
            describe: "Don't run _any_ lifecycle scripts in bootstrapped packages",
            type: "boolean"
          },
          "npm-client": {
            group: "Command Options:",
            describe: "Executable used to install dependencies (npm, yarn, pnpm, ...)",
            type: "string",
            requiresArg: true
          },
          registry: {
            group: "Command Options:",
            describe: "Use the specified registry for all npm client operations.",
            type: "string",
            requiresArg: true
          },
          strict: {
            group: "Command Options:",
            describe: "Don't allow warnings when hoisting as it causes longer bootstrap times and other issues.",
            type: "boolean"
          },
          "use-workspaces": {
            group: "Command Options:",
            describe: "Enable integration with Yarn workspaces.",
            type: "boolean"
          },
          "force-local": {
            group: "Command Options:",
            describe: "Force local sibling links regardless of version range match",
            type: "boolean"
          },
          contents: {
            group: "Command Options:",
            describe: "Subdirectory to use as the source of any links. Must apply to ALL packages.",
            type: "string",
            defaultDescription: "."
          }
        });
        return filterOptions(yargs2);
      },
      handler(argv) {
        return require_src()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/changed/src/index.ts
var require_src3 = __commonJS({
  "libs/commands/changed/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    module2.exports = function factory(argv) {
      return new ChangedCommand(argv);
    };
    var ChangedCommand = class extends Command {
      result;
      get otherCommandConfigs() {
        return ["version", "publish"];
      }
      initialize() {
        if (this.options.conventionalGraduate) {
          this.options.conventionalCommits = true;
          if (this.options.forcePublish) {
            this.logger.warn("option", "--force-publish superseded by --conventional-graduate");
          }
        }
        const updates = collectUpdates(
          this.packageGraph.rawPackageList,
          this.packageGraph,
          this.execOpts,
          this.options
        );
        this.result = listableFormat(
          updates.map((node) => node.pkg),
          this.options
        );
        if (this.result.count === 0) {
          this.logger.info("", "No changed packages found");
          process.exitCode = 1;
          return false;
        }
      }
      execute() {
        output(this.result.text);
        this.logger.success(
          "found",
          "%d %s ready to publish",
          this.result.count,
          this.result.count === 1 ? "package" : "packages"
        );
      }
    };
    module2.exports.ChangedCommand = ChangedCommand;
  }
});

// libs/commands/changed/src/command.ts
var require_command3 = __commonJS({
  "libs/commands/changed/src/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "changed",
      aliases: ["updated"],
      describe: "List local packages that have changed since the last tagged release",
      builder(yargs2) {
        const opts = {
          "conventional-commits": {
            hidden: true,
            type: "boolean"
          },
          "conventional-graduate": {
            describe: "Detect currently prereleased packages that would change to a non-prerelease version."
          },
          "force-publish": {
            describe: "Always include targeted packages when detecting changed packages, skipping default logic."
          },
          "ignore-changes": {
            describe: [
              "Ignore changes in files matched by glob(s) when detecting changed packages.",
              "Pass --no-ignore-changes to completely disable."
            ].join("\n"),
            type: "array"
          },
          "include-merged-tags": {
            describe: "Include tags from merged branches when detecting changed packages.",
            type: "boolean"
          }
        };
        yargs2.options(opts).group(Object.keys(opts), "Command Options:");
        return listableOptions(yargs2, "Output Options:");
      },
      handler(argv) {
        return require_src3()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/clean/src/index.ts
var require_src4 = __commonJS({
  "libs/commands/clean/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_p_map5 = __toESM(require("p-map"));
    var import_path23 = __toESM(require("path"));
    module2.exports = function factory(argv) {
      return new CleanCommand(argv);
    };
    var CleanCommand = class extends Command {
      get requiresGit() {
        return false;
      }
      initialize() {
        let chain = Promise.resolve();
        chain = chain.then(() => getFilteredPackages(this.packageGraph, this.execOpts, this.options));
        chain = chain.then((filteredPackages) => {
          this.directoriesToDelete = filteredPackages.map((pkg) => pkg.nodeModulesLocation);
        });
        return chain.then(() => {
          if (this.options.yes) {
            return true;
          }
          this.logger.info("", "Removing the following directories:");
          this.logger.info(
            "clean",
            this.directoriesToDelete.map((dir) => import_path23.default.relative(this.project.rootPath, dir)).join("\n")
          );
          return promptConfirmation("Proceed?");
        });
      }
      execute() {
        this.enableProgressBar();
        const tracker = this.logger.newItem("clean");
        const mapper = (dirPath) => {
          tracker.info("clean", "removing", dirPath);
          return pulseTillDone(rimrafDir(dirPath)).then(() => {
            tracker.completeWork(1);
          });
        };
        tracker.addWork(this.directoriesToDelete.length);
        return (0, import_p_map5.default)(this.directoriesToDelete, mapper, { concurrency: this.concurrency }).then(() => {
          tracker.finish();
          this.logger.success("clean", "finished");
        });
      }
    };
    module2.exports.CleanCommand = CleanCommand;
  }
});

// libs/commands/clean/src/command.ts
var require_command4 = __commonJS({
  "libs/commands/clean/src/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "clean",
      describe: "Remove the node_modules directory from all packages",
      builder(yargs2) {
        yargs2.options({
          y: {
            group: "Command Options:",
            describe: "Skip all confirmation prompts",
            alias: "yes",
            type: "boolean"
          }
        });
        return filterOptions(yargs2);
      },
      handler(argv) {
        return require_src4()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/diff/src/lib/get-last-commit.ts
var require_get_last_commit = __commonJS({
  "libs/commands/diff/src/lib/get-last-commit.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.getLastCommit = getLastCommit;
    function getLastCommit(execOpts) {
      if (hasTags2(execOpts)) {
        import_npmlog38.default.silly("getLastTagInBranch");
        return childProcess11.execSync("git", ["describe", "--tags", "--abbrev=0"], execOpts);
      }
      import_npmlog38.default.silly("getFirstCommit");
      return childProcess11.execSync("git", ["rev-list", "--max-parents=0", "HEAD"], execOpts);
    }
    function hasTags2(opts) {
      let result = false;
      try {
        result = !!childProcess11.execSync("git", ["tag"], opts);
      } catch (err) {
        import_npmlog38.default.warn("ENOTAGS", "No git tags were reachable from this branch!");
        import_npmlog38.default.verbose("hasTags error", err);
      }
      import_npmlog38.default.verbose("hasTags", result);
      return result;
    }
  }
});

// libs/commands/diff/src/lib/has-commit.ts
var require_has_commit = __commonJS({
  "libs/commands/diff/src/lib/has-commit.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.hasCommit = hasCommit;
    function hasCommit(opts) {
      import_npmlog38.default.silly("hasCommit");
      let retVal;
      try {
        childProcess11.execSync("git", ["log"], opts);
        retVal = true;
      } catch (e) {
        retVal = false;
      }
      import_npmlog38.default.verbose("hasCommit", retVal);
      return retVal;
    }
  }
});

// libs/commands/diff/src/index.ts
var require_src5 = __commonJS({
  "libs/commands/diff/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var { getLastCommit } = require_get_last_commit();
    var { hasCommit } = require_has_commit();
    var childProcess11 = require("@lerna/child-process");
    module2.exports = function factory(argv) {
      return new DiffCommand(argv);
    };
    var DiffCommand = class extends Command {
      args;
      initialize() {
        const packageName = this.options.pkgName;
        let targetPackage;
        if (packageName) {
          targetPackage = this.packageGraph.get(packageName);
          if (!targetPackage) {
            throw new ValidationError("ENOPKG", `Cannot diff, the package '${packageName}' does not exist.`);
          }
        }
        if (!hasCommit(this.execOpts)) {
          throw new ValidationError("ENOCOMMITS", "Cannot diff, there are no commits in this repository yet.");
        }
        const args = ["diff", getLastCommit(this.execOpts), "--color=auto"];
        if (targetPackage) {
          args.push("--", targetPackage.location);
        } else {
          args.push("--", ...this.project.packageParentDirs);
        }
        if (this.options.ignoreChanges) {
          this.options.ignoreChanges.forEach((ignorePattern) => {
            args.push(`:(exclude,glob)${ignorePattern}`);
          });
        }
        this.args = args;
      }
      execute() {
        return childProcess11.spawn("git", this.args, this.execOpts).catch((err) => {
          if (err.exitCode) {
            throw err;
          }
        });
      }
    };
    module2.exports.DiffCommand = DiffCommand;
  }
});

// libs/commands/diff/src/command.ts
var require_command5 = __commonJS({
  "libs/commands/diff/src/command.ts"(exports, module2) {
    "use strict";
    var command = {
      command: "diff [pkgName]",
      describe: "Diff all packages or a single package since the last release",
      builder(yargs2) {
        return yargs2.positional("pkgName", {
          describe: "An optional package name to filter the diff output"
        }).options({
          "ignore-changes": {
            group: "Command Options:",
            describe: "Ignore changes in files matched by glob(s).",
            type: "array"
          }
        }).epilogue(
          "When ignoreChanges is configured in lerna.json, pass --no-ignore-changes to include ignored files."
        );
      },
      handler(argv) {
        return require_src5()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/exec/src/index.ts
var require_src6 = __commonJS({
  "libs/commands/exec/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_p_map5 = __toESM(require("p-map"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports = function factory(argv) {
      return new ExecCommand(argv);
    };
    var ExecCommand = class extends Command {
      get requiresGit() {
        return false;
      }
      initialize() {
        const dashedArgs = this.options["--"] || [];
        this.command = this.options.cmd || dashedArgs.shift();
        this.args = (this.options.args || []).concat(dashedArgs);
        if (!this.command) {
          throw new ValidationError("ENOCOMMAND", "A command to execute is required");
        }
        this.bail = this.options.bail !== false;
        this.prefix = this.options.prefix !== false;
        this.env = Object.assign({}, process.env);
        let chain = Promise.resolve();
        chain = chain.then(() => getFilteredPackages(this.packageGraph, this.execOpts, this.options));
        chain = chain.then((filteredPackages) => {
          this.filteredPackages = filteredPackages;
        });
        return chain.then(() => {
          this.count = this.filteredPackages.length;
          this.packagePlural = this.count === 1 ? "package" : "packages";
          this.joinedCommand = [this.command].concat(this.args).join(" ");
        });
      }
      execute() {
        this.logger.info(
          "",
          "Executing command in %d %s: %j",
          this.count,
          this.packagePlural,
          this.joinedCommand
        );
        let chain = Promise.resolve();
        if (this.options.parallel) {
          chain = chain.then(() => this.runCommandInPackagesParallel());
        } else if (this.toposort) {
          chain = chain.then(() => this.runCommandInPackagesTopological());
        } else {
          chain = chain.then(() => this.runCommandInPackagesLexical());
        }
        if (this.bail) {
          chain = chain.catch((err) => {
            process.exitCode = err.exitCode;
            throw err;
          });
        } else {
          chain = chain.then((results) => {
            if (results.some((result) => result.failed)) {
              const codes = results.filter((result) => result.failed).map((result) => result.exitCode);
              const exitCode = Math.max(...codes, 1);
              this.logger.error("", "Received non-zero exit code %d during execution", exitCode);
              process.exitCode = exitCode;
            }
          });
        }
        return chain.then(() => {
          this.logger.success(
            "exec",
            "Executed command in %d %s: %j",
            this.count,
            this.packagePlural,
            this.joinedCommand
          );
        });
      }
      getOpts(pkg) {
        return {
          cwd: pkg.location,
          shell: true,
          extendEnv: false,
          env: Object.assign({}, this.env, {
            LERNA_PACKAGE_NAME: pkg.name,
            LERNA_ROOT_PATH: this.project.rootPath
          }),
          reject: this.bail,
          pkg
        };
      }
      getRunner() {
        return this.options.stream ? (pkg) => this.runCommandInPackageStreaming(pkg) : (pkg) => this.runCommandInPackageCapturing(pkg);
      }
      runCommandInPackagesTopological() {
        let profiler;
        let runner;
        if (this.options.profile) {
          profiler = new Profiler({
            concurrency: this.concurrency,
            log: this.logger,
            outputDirectory: this.options.profileLocation || this.project.rootPath
          });
          const callback = this.getRunner();
          runner = (pkg) => profiler.run(() => callback(pkg), pkg.name);
        } else {
          runner = this.getRunner();
        }
        let chain = runTopologically(this.filteredPackages, runner, {
          concurrency: this.concurrency,
          rejectCycles: this.options.rejectCycles
        });
        if (profiler) {
          chain = chain.then((results) => profiler.output().then(() => results));
        }
        return chain;
      }
      runCommandInPackagesParallel() {
        return (0, import_p_map5.default)(this.filteredPackages, (pkg) => this.runCommandInPackageStreaming(pkg));
      }
      runCommandInPackagesLexical() {
        return (0, import_p_map5.default)(this.filteredPackages, this.getRunner(), { concurrency: this.concurrency });
      }
      runCommandInPackageStreaming(pkg) {
        return childProcess11.spawnStreaming(this.command, this.args, this.getOpts(pkg), this.prefix && pkg.name);
      }
      runCommandInPackageCapturing(pkg) {
        return childProcess11.spawn(this.command, this.args, this.getOpts(pkg));
      }
    };
    module2.exports.ExecCommand = ExecCommand;
  }
});

// libs/commands/exec/src/command.ts
var require_command6 = __commonJS({
  "libs/commands/exec/src/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "exec [cmd] [args..]",
      describe: "Execute an arbitrary command in each package",
      builder(yargs2) {
        yargs2.example("$0 exec ls -- --la", "# execute `ls -la` in all packages").example("$0 exec -- ls --la", "# execute `ls -la` in all packages, keeping cmd outside").parserConfiguration({
          "populate--": true
        }).positional("cmd", {
          describe: "The command to execute. Any command flags must be passed after --",
          type: "string"
        }).positional("args", {
          describe: "Positional arguments (not recognized by lerna) to send to command",
          type: "string"
        }).options({
          stream: {
            group: "Command Options:",
            describe: "Stream output with lines prefixed by originating package name.",
            type: "boolean"
          },
          parallel: {
            group: "Command Options:",
            describe: "Execute command with unlimited concurrency, streaming prefixed output.",
            type: "boolean"
          },
          "no-bail": {
            group: "Command Options:",
            describe: "Continue executing command despite non-zero exit in a given package.",
            type: "boolean"
          },
          bail: {
            hidden: true,
            type: "boolean"
          },
          "no-prefix": {
            group: "Command Options:",
            describe: "Do not prefix streaming output.",
            type: "boolean"
          },
          prefix: {
            hidden: true,
            type: "boolean"
          },
          profile: {
            group: "Command Options:",
            describe: "Profile command executions and output performance profile to default location.",
            type: "boolean"
          },
          "profile-location": {
            group: "Command Options:",
            describe: "Output performance profile to custom location instead of default project root.",
            type: "string"
          }
        });
        return filterOptions(yargs2);
      },
      handler(argv) {
        return require_src6()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/import/src/index.ts
var require_src7 = __commonJS({
  "libs/commands/import/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_dedent5 = __toESM(require("dedent"));
    var import_fs_extra11 = __toESM(require("fs-extra"));
    var import_p_map_series2 = __toESM(require("p-map-series"));
    var import_path23 = __toESM(require("path"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports = function factory(argv) {
      return new ImportCommand(argv);
    };
    var ImportCommand = class extends Command {
      gitParamsForTargetCommits() {
        const params = ["log", "--format=%h"];
        if (this.options.flatten) {
          params.push("--first-parent");
        }
        return params;
      }
      initialize() {
        const inputPath = this.options.dir;
        const externalRepoPath = import_path23.default.resolve(inputPath);
        const externalRepoBase = import_path23.default.basename(externalRepoPath);
        this.externalExecOpts = Object.assign({}, this.execOpts, {
          cwd: externalRepoPath
        });
        let stats;
        try {
          stats = import_fs_extra11.default.statSync(externalRepoPath);
        } catch (e) {
          if (e.code === "ENOENT") {
            throw new ValidationError("ENOENT", `No repository found at "${inputPath}"`);
          }
          throw e;
        }
        if (!stats.isDirectory()) {
          throw new ValidationError("ENODIR", `Input path "${inputPath}" is not a directory`);
        }
        const packageJson = import_path23.default.join(externalRepoPath, "package.json");
        const packageName = require(packageJson).name;
        if (!packageName) {
          throw new ValidationError("ENOPKG", `No package name specified in "${packageJson}"`);
        }
        const targetBase = this.getTargetBase();
        if (this.getPackageDirectories().indexOf(targetBase) === -1) {
          throw new ValidationError(
            "EDESTDIR",
            `--dest does not match with the package directories: ${this.getPackageDirectories()}`
          );
        }
        const targetDir = import_path23.default.join(targetBase, externalRepoBase);
        const gitRepoRoot = this.getWorkspaceRoot();
        const lernaRootRelativeToGitRoot = import_path23.default.relative(gitRepoRoot, this.project.rootPath);
        this.targetDirRelativeToGitRoot = import_path23.default.join(lernaRootRelativeToGitRoot, targetDir);
        if (import_fs_extra11.default.existsSync(import_path23.default.resolve(this.project.rootPath, targetDir))) {
          throw new ValidationError("EEXISTS", `Target directory already exists "${targetDir}"`);
        }
        this.commits = this.externalExecSync("git", this.gitParamsForTargetCommits()).split("\n").reverse();
        if (!this.commits.length) {
          throw new ValidationError("NOCOMMITS", `No git commits to import at "${inputPath}"`);
        }
        if (this.options.preserveCommit) {
          this.origGitEmail = this.execSync("git", ["config", "user.email"]);
          this.origGitName = this.execSync("git", ["config", "user.name"]);
        }
        this.preImportHead = this.getCurrentSHA();
        if (this.execSync("git", ["diff-index", "HEAD"])) {
          throw new ValidationError("ECHANGES", "Local repository has un-committed changes");
        }
        this.logger.info(
          "",
          `About to import ${this.commits.length} commits from ${inputPath} into ${targetDir}`
        );
        if (this.options.yes) {
          return true;
        }
        return promptConfirmation("Are you sure you want to import these commits onto the current branch?");
      }
      getPackageDirectories() {
        return this.project.packageConfigs.filter((p) => p.endsWith("*")).map((p) => import_path23.default.dirname(p));
      }
      getTargetBase() {
        if (this.options.dest) {
          return this.options.dest;
        }
        return this.getPackageDirectories().shift() || "packages";
      }
      getCurrentSHA() {
        return this.execSync("git", ["rev-parse", "HEAD"]);
      }
      getWorkspaceRoot() {
        return this.execSync("git", ["rev-parse", "--show-toplevel"]);
      }
      execSync(cmd, args) {
        return childProcess11.execSync(cmd, args, this.execOpts);
      }
      externalExecSync(cmd, args) {
        return childProcess11.execSync(cmd, args, this.externalExecOpts);
      }
      createPatchForCommit(sha) {
        let patch = null;
        if (this.options.flatten) {
          const diff = this.externalExecSync("git", [
            "log",
            "--reverse",
            "--first-parent",
            "-p",
            "-m",
            "--pretty=email",
            "--stat",
            "--binary",
            "-1",
            "--color=never",
            sha,
            `--src-prefix=COMPARE_A/`,
            `--dst-prefix=COMPARE_B/`
          ]);
          const version = this.externalExecSync("git", ["--version"]).replace(/git version /g, "");
          patch = `${diff}
--
${version}`;
        } else {
          patch = this.externalExecSync("git", [
            "format-patch",
            "-1",
            sha,
            "--stdout",
            `--src-prefix=COMPARE_A/`,
            `--dst-prefix=COMPARE_B/`
          ]);
        }
        const formattedTarget = this.targetDirRelativeToGitRoot.replace(/\\/g, "/");
        const replacement = `$1/${formattedTarget}`;
        return patch.replace(/^([-+]{3} "?COMPARE_[AB])/gm, replacement).replace(/^(diff --git "?COMPARE_A)/gm, replacement).replace(/^(diff --git (?! "?COMPARE_B\/).+ "?COMPARE_B)/gm, replacement).replace(/^(copy (from|to)) ("?)/gm, `$1 $3${formattedTarget}/`).replace(/^(rename (from|to)) ("?)/gm, `$1 $3${formattedTarget}/`);
      }
      getGitUserFromSha(sha) {
        return {
          email: this.externalExecSync("git", ["show", "-s", "--format='%ae'", sha]),
          name: this.externalExecSync("git", ["show", "-s", "--format='%an'", sha])
        };
      }
      configureGitUser({ email, name }) {
        this.execSync("git", ["config", "user.email", `"${email}"`]);
        this.execSync("git", ["config", "user.name", `"${name}"`]);
      }
      execute() {
        this.enableProgressBar();
        const tracker = this.logger.newItem("execute");
        const mapper = (sha) => {
          tracker.info(sha);
          const patch = this.createPatchForCommit(sha);
          const procArgs = ["am", "-3", "--keep-non-patch"];
          if (this.options.preserveCommit) {
            this.configureGitUser(this.getGitUserFromSha(sha));
            procArgs.push("--committer-date-is-author-date");
          }
          const proc = childProcess11.exec("git", procArgs, this.execOpts);
          proc.stdin.end(patch);
          return pulseTillDone(proc).then(() => {
            tracker.completeWork(1);
          }).catch((err) => {
            const diff = this.externalExecSync("git", ["diff", "-s", `${sha}^!`]).trim();
            if (diff === "") {
              tracker.completeWork(1);
              return childProcess11.exec("git", ["am", "--skip"], this.execOpts);
            }
            err.sha = sha;
            throw err;
          });
        };
        tracker.addWork(this.commits.length);
        return (0, import_p_map_series2.default)(this.commits, mapper).then(() => {
          tracker.finish();
          if (this.options.preserveCommit) {
            this.configureGitUser({
              email: this.origGitEmail,
              name: this.origGitName
            });
          }
          this.logger.success("import", "finished");
        }).catch((err) => {
          tracker.finish();
          if (this.options.preserveCommit) {
            this.configureGitUser({
              email: this.origGitEmail,
              name: this.origGitName
            });
          }
          this.logger.error("import", `Rolling back to previous HEAD (commit ${this.preImportHead})`);
          this.execSync("git", ["am", "--abort"]);
          this.execSync("git", ["reset", "--hard", this.preImportHead]);
          throw new ValidationError(
            "EIMPORT",
            import_dedent5.default`
            Failed to apply commit ${err.sha}.
            ${err.message}

            You may try again with --flatten to import flat history.
          `
          );
        });
      }
    };
    module2.exports.ImportCommand = ImportCommand;
  }
});

// libs/commands/import/src/command.ts
var require_command7 = __commonJS({
  "libs/commands/import/src/command.ts"(exports, module2) {
    "use strict";
    var command = {
      command: "import <dir>",
      describe: "Import a package into the monorepo with commit history",
      builder(yargs2) {
        return yargs2.positional("dir", { describe: "The path to an external git repository that contains an npm package" }).options({
          flatten: {
            group: "Command Options:",
            describe: "Import each merge commit as a single change the merge introduced",
            type: "boolean"
          },
          dest: {
            group: "Command Options:",
            describe: "Import destination directory for the external git repository",
            type: "string"
          },
          "preserve-commit": {
            group: "Command Options:",
            describe: "Preserve original committer in addition to original author",
            type: "boolean"
          },
          y: {
            group: "Command Options:",
            describe: "Skip all confirmation prompts",
            alias: "yes",
            type: "boolean"
          }
        });
      },
      handler(argv) {
        return require_src7()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/info/src/index.ts
var require_src8 = __commonJS({
  "libs/commands/info/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_envinfo = __toESM(require("envinfo"));
    module2.exports = function factory(argv) {
      return new InfoCommand(argv);
    };
    var InfoCommand = class extends Command {
      initialize() {
      }
      execute() {
        output("\n Environment info:");
        import_envinfo.default.run({
          System: ["OS", "CPU"],
          Binaries: ["Node", "Yarn", "npm"],
          Utilities: ["Git"],
          npmPackages: ["lerna"]
        }).then(output);
      }
    };
    module2.exports.InfoCommand = InfoCommand;
  }
});

// libs/commands/info/src/command.ts
var require_command8 = __commonJS({
  "libs/commands/info/src/command.ts"(exports, module2) {
    "use strict";
    var command = {
      command: "info",
      describe: "Prints debugging information about the local environment",
      handler(argv) {
        return require_src8()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/init/src/index.ts
var require_src9 = __commonJS({
  "libs/commands/init/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_devkit2 = require("@nrwl/devkit");
    var import_fs_extra11 = __toESM(require("fs-extra"));
    var import_p_map5 = __toESM(require("p-map"));
    var import_path23 = __toESM(require("path"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports = function factory(argv) {
      return new InitCommand(argv);
    };
    var InitCommand = class extends Command {
      exact;
      lernaVersion;
      get requiresGit() {
        return false;
      }
      runValidations() {
        this.logger.verbose(this.name, "skipping validations");
      }
      runPreparations() {
        this.logger.verbose(this.name, "skipping preparations");
      }
      initialize() {
        this.exact = this.options.exact;
        this.lernaVersion = this.options.lernaVersion;
        if (!this.gitInitialized()) {
          this.logger.info("", "Initializing Git repository");
          return childProcess11.exec("git", ["init"], this.execOpts);
        }
      }
      execute() {
        let chain = Promise.resolve();
        chain = chain.then(() => this.ensureGitIgnore());
        chain = chain.then(() => this.ensureConfig());
        chain = chain.then(() => this.ensurePackagesDir());
        return chain.then(() => {
          this.logger.success("", "Initialized Lerna files");
          this.logger.info("", "New to Lerna? Check out the docs: https://lerna.js.org/docs/getting-started");
        });
      }
      ensureGitIgnore() {
        const gitIgnorePath = import_path23.default.join(this.project.rootPath, ".gitignore");
        let chain = Promise.resolve();
        if (!import_fs_extra11.default.existsSync(gitIgnorePath)) {
          this.logger.info("", "Creating .gitignore");
          chain = chain.then(() => import_fs_extra11.default.writeFile(gitIgnorePath, "node_modules/"));
        }
        return chain;
      }
      ensureConfig() {
        const hasExistingLernaConfig = !!this.project.version;
        const hasExistingPackageJson = !!this.project.manifest;
        const useNx = !hasExistingLernaConfig || this.project.config.useNx !== false;
        const useWorkspaces = !hasExistingLernaConfig || this.project.config.useWorkspaces === true;
        let chain = Promise.resolve();
        if (!hasExistingPackageJson) {
          this.logger.info("", "Creating package.json");
          chain = chain.then(() => {
            const pkg = {
              name: "root",
              private: true
            };
            if (useWorkspaces) {
              pkg.workspaces = [Project.PACKAGE_GLOB];
            }
            return (0, import_devkit2.writeJsonFile)(import_path23.default.join(this.project.rootPath, "package.json"), pkg, {
              spaces: 2
            });
          });
        } else {
          this.logger.info("", "Updating package.json");
          chain = chain.then(() => {
            if (useWorkspaces && !this.project.manifest.get("workspaces")) {
              this.project.manifest.set("workspaces", [Project.PACKAGE_GLOB]);
              return this.project.manifest.serialize();
            }
          });
        }
        chain = chain.then(() => {
          const rootPkg = this.project.manifest;
          const setDependency = ({ name, version }) => {
            let targetDependencies;
            if (rootPkg.dependencies && rootPkg.dependencies[name]) {
              targetDependencies = rootPkg.dependencies;
            } else {
              if (!rootPkg.devDependencies) {
                rootPkg.set("devDependencies", {});
              }
              targetDependencies = rootPkg.devDependencies;
            }
            targetDependencies[name] = this.exact ? version : `^${version}`;
          };
          setDependency({ name: "lerna", version: this.lernaVersion });
          return rootPkg.serialize();
        });
        chain = chain.then(() => {
          let version;
          if (this.options.independent) {
            version = "independent";
          } else if (this.project.version) {
            version = this.project.version;
          } else {
            version = "0.0.0";
          }
          if (!hasExistingLernaConfig) {
            this.logger.info("", "Creating lerna.json");
          } else {
            this.logger.info("", "Updating lerna.json");
            if (!useWorkspaces && !this.project.config.packages) {
              Object.assign(this.project.config, {
                packages: [Project.PACKAGE_GLOB]
              });
            }
          }
          delete this.project.config.lerna;
          if (this.exact) {
            const commandConfig = this.project.config.command || (this.project.config.command = {});
            const initConfig = commandConfig.init || (commandConfig.init = {});
            initConfig.exact = true;
          }
          Object.assign(this.project.config, {
            $schema: "node_modules/lerna/schemas/lerna-schema.json",
            useWorkspaces,
            version,
            useNx: useNx === false ? false : void 0
          });
          return Promise.resolve(this.project.serializeConfig());
        });
        return chain;
      }
      ensurePackagesDir() {
        this.logger.info("", "Creating packages directory");
        return (0, import_p_map5.default)(this.project.packageParentDirs, (dir) => import_fs_extra11.default.mkdirp(dir));
      }
    };
    module2.exports.InitCommand = InitCommand;
  }
});

// libs/commands/init/src/command.ts
var require_command9 = __commonJS({
  "libs/commands/init/src/command.ts"(exports, module2) {
    "use strict";
    var command = {
      command: "init",
      describe: "Create a new Lerna repo or upgrade an existing repo to the current version of Lerna",
      builder: {
        exact: {
          describe: "Specify lerna dependency version in package.json without a caret (^)",
          type: "boolean"
        },
        independent: {
          describe: "Version packages independently",
          alias: "i",
          type: "boolean"
        }
      },
      handler(argv) {
        return require_src9()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/link/src/index.ts
var require_src10 = __commonJS({
  "libs/commands/link/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_p_map5 = __toESM(require("p-map"));
    var import_path23 = __toESM(require("path"));
    var import_slash2 = __toESM(require("slash"));
    module2.exports = function factory(argv) {
      return new LinkCommand(argv);
    };
    var LinkCommand = class extends Command {
      allPackages;
      targetGraph;
      get requiresGit() {
        return false;
      }
      initialize() {
        if (this.options.npmClient === "pnpm") {
          throw new ValidationError(
            "EWORKSPACES",
            "Link is not supported with pnpm workspaces, since pnpm will automatically link dependencies during `pnpm install`. See the pnpm docs for details: https://pnpm.io/workspaces"
          );
        }
        this.allPackages = this.packageGraph.rawPackageList;
        if (this.options.contents) {
          for (const pkg of this.allPackages) {
            pkg.contents = this.options.contents;
          }
        }
        this.targetGraph = this.options.forceLocal ? new PackageGraph(this.allPackages, "allDependencies", "forceLocal") : this.packageGraph;
      }
      execute() {
        if (this.options._.pop() === "convert") {
          return this.convertLinksToFileSpecs();
        }
        return symlinkDependencies(this.allPackages, this.targetGraph, this.logger.newItem("link dependencies"));
      }
      convertLinksToFileSpecs() {
        const rootPkg = this.project.manifest;
        const rootDependencies = {};
        const hoisted = {};
        const changed = /* @__PURE__ */ new Set();
        const savePrefix = "file:";
        for (const targetNode of this.targetGraph.values()) {
          const resolved = { name: targetNode.name, type: "directory" };
          rootDependencies[targetNode.name] = targetNode.pkg.resolved.saveSpec;
          for (const depNode of targetNode.localDependents.values()) {
            const depVersion = (0, import_slash2.default)(import_path23.default.relative(depNode.pkg.location, targetNode.pkg.location));
            depNode.pkg.updateLocalDependency(resolved, depVersion, savePrefix);
            changed.add(depNode);
          }
          if (targetNode.pkg.devDependencies) {
            Object.assign(hoisted, targetNode.pkg.devDependencies);
            targetNode.pkg.set("devDependencies", {});
            changed.add(targetNode);
          }
        }
        rootPkg.set("dependencies", rootDependencies);
        rootPkg.set("devDependencies", Object.assign(rootPkg.get("devDependencies") || {}, hoisted));
        return (0, import_p_map5.default)(changed, (node) => node.pkg.serialize()).then(() => rootPkg.serialize());
      }
    };
    module2.exports.LinkCommand = LinkCommand;
  }
});

// libs/commands/link/src/command.ts
var require_command10 = __commonJS({
  "libs/commands/link/src/command.ts"(exports, module2) {
    "use strict";
    function handler(argv) {
      return require_src10()(argv);
    }
    var command = {
      command: "link",
      describe: "Symlink together all packages that are dependencies of each other",
      builder(yargs2) {
        yargs2.options({
          "force-local": {
            group: "Command Options:",
            describe: "Force local sibling links regardless of version range match",
            type: "boolean"
          },
          contents: {
            group: "Command Options:",
            describe: "Subdirectory to use as the source of the symlink. Must apply to ALL packages.",
            type: "string",
            defaultDescription: "."
          }
        });
        return yargs2.command(
          "convert",
          "Replace local sibling version ranges with relative file: specifiers",
          () => {
          },
          handler
        );
      },
      handler
    };
    module2.exports = command;
  }
});

// libs/commands/list/src/index.ts
var require_src11 = __commonJS({
  "libs/commands/list/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    module2.exports = function factory(argv) {
      return new ListCommand(argv);
    };
    var ListCommand = class extends Command {
      result;
      get requiresGit() {
        return false;
      }
      initialize() {
        let chain = Promise.resolve();
        chain = chain.then(() => getFilteredPackages(this.packageGraph, this.execOpts, this.options));
        chain = chain.then((filteredPackages) => {
          this.result = listableFormat(filteredPackages, this.options);
        });
        return chain;
      }
      execute() {
        if (this.result.text.length) {
          output(this.result.text);
        }
        this.logger.success(
          "found",
          "%d %s",
          this.result.count,
          this.result.count === 1 ? "package" : "packages"
        );
      }
    };
    module2.exports.ListCommand = ListCommand;
  }
});

// libs/commands/list/src/command.ts
var require_command11 = __commonJS({
  "libs/commands/list/src/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "list",
      aliases: ["ls", "la", "ll"],
      describe: "List local packages",
      builder(yargs2) {
        listableOptions(yargs2);
        return filterOptions(yargs2);
      },
      handler(argv) {
        return require_src11()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/version/src/lib/get-current-branch.ts
var require_get_current_branch = __commonJS({
  "libs/commands/version/src/lib/get-current-branch.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.getCurrentBranch = getCurrentBranch;
    function getCurrentBranch(opts) {
      import_npmlog38.default.silly("getCurrentBranch");
      const branch = childProcess11.execSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], opts);
      import_npmlog38.default.verbose("currentBranch", branch);
      return branch;
    }
  }
});

// libs/commands/version/src/lib/git-add.ts
var require_git_add = __commonJS({
  "libs/commands/version/src/lib/git-add.ts"(exports, module2) {
    "use strict";
    var import_devkit2 = require("@nrwl/devkit");
    var import_fs4 = __toESM(require("fs"));
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_path23 = __toESM(require("path"));
    var import_slash2 = __toESM(require("slash"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.gitAdd = gitAdd;
    var resolvedPrettier;
    function resolvePrettier() {
      if (!resolvedPrettier) {
        try {
          const packageJson = (0, import_devkit2.readJsonFile)(import_path23.default.join(import_devkit2.workspaceRoot, "package.json"));
          const hasPrettier = packageJson.devDependencies?.prettier || packageJson.dependencies?.prettier;
          if (!hasPrettier) {
            return;
          }
          const prettierPath = import_path23.default.join(import_devkit2.workspaceRoot, "node_modules", "prettier");
          resolvedPrettier = require(prettierPath);
        } catch {
          return;
        }
      }
      return resolvedPrettier;
    }
    function maybeFormatFile(filePath) {
      const prettier = resolvePrettier();
      if (!prettier) {
        return;
      }
      const config = resolvedPrettier.resolveConfig.sync(filePath);
      const ignorePath = import_path23.default.join(import_devkit2.workspaceRoot, ".prettierignore");
      const fullFilePath = import_path23.default.join(import_devkit2.workspaceRoot, filePath);
      if (resolvedPrettier.getFileInfo.sync(fullFilePath, { ignorePath }).ignored) {
        import_npmlog38.default.silly("version", `Skipped applying prettier to ignored file: ${filePath}`);
        return;
      }
      try {
        const input = import_fs4.default.readFileSync(fullFilePath, "utf8");
        import_fs4.default.writeFileSync(
          fullFilePath,
          resolvedPrettier.format(input, { ...config, filepath: fullFilePath }),
          "utf8"
        );
        import_npmlog38.default.silly("version", `Successfully applied prettier to updated file: ${filePath}`);
      } catch {
        import_npmlog38.default.silly("version", `Failed to apply prettier to updated file: ${filePath}`);
      }
    }
    function gitAdd(changedFiles, gitOpts, execOpts) {
      let files = [];
      for (const file of changedFiles) {
        const filePath = (0, import_slash2.default)(import_path23.default.relative(execOpts.cwd, import_path23.default.resolve(execOpts.cwd, file)));
        maybeFormatFile(filePath);
        if (gitOpts.granularPathspec) {
          files.push(filePath);
        }
      }
      if (!gitOpts.granularPathspec) {
        files = ".";
      }
      import_npmlog38.default.silly("gitAdd", files);
      return childProcess11.exec("git", ["add", "--", ...files], execOpts);
    }
  }
});

// libs/commands/version/src/lib/git-commit.ts
var require_git_commit = __commonJS({
  "libs/commands/version/src/lib/git-commit.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_os4 = require("os");
    var childProcess11 = require("@lerna/child-process");
    module2.exports.gitCommit = gitCommit;
    function gitCommit(message, { amend, commitHooks, signGitCommit, signoffGitCommit }, opts) {
      import_npmlog38.default.silly("gitCommit", message);
      const args = ["commit"];
      if (commitHooks === false) {
        args.push("--no-verify");
      }
      if (signGitCommit) {
        args.push("--gpg-sign");
      }
      if (signoffGitCommit) {
        args.push("--signoff");
      }
      if (amend) {
        args.push("--amend", "--no-edit");
      } else if (message.indexOf(import_os4.EOL) > -1) {
        args.push("-F", temp_write_default.sync(message, "lerna-commit.txt"));
      } else {
        args.push("-m", message);
      }
      import_npmlog38.default.verbose("git", args);
      return childProcess11.exec("git", args, opts);
    }
  }
});

// libs/commands/version/src/lib/git-push.ts
var require_git_push = __commonJS({
  "libs/commands/version/src/lib/git-push.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.gitPush = gitPush;
    function gitPush(remote, branch, opts) {
      import_npmlog38.default.silly("gitPush", remote, branch);
      return childProcess11.exec("git", ["push", "--follow-tags", "--no-verify", "--atomic", remote, branch], opts).catch((error) => {
        if (/atomic/.test(error.stderr) || process.env.GIT_REDIRECT_STDERR === "2>&1" && /atomic/.test(error.stdout)) {
          import_npmlog38.default.warn("gitPush", error.stderr);
          import_npmlog38.default.info("gitPush", "--atomic failed, attempting non-atomic push");
          return childProcess11.exec("git", ["push", "--follow-tags", "--no-verify", remote, branch], opts);
        }
        throw error;
      });
    }
  }
});

// libs/commands/version/src/lib/git-tag.ts
var require_git_tag = __commonJS({
  "libs/commands/version/src/lib/git-tag.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.gitTag = gitTag;
    function gitTag(tag, { forceGitTag, signGitTag }, opts, command = "git tag %s -m %s") {
      import_npmlog38.default.silly("gitTag", tag, command);
      const [cmd, ...args] = command.split(" ");
      const interpolatedArgs = args.map((arg) => arg.replace(/%s/, tag));
      if (forceGitTag) {
        interpolatedArgs.push("--force");
      }
      if (signGitTag) {
        interpolatedArgs.push("--sign");
      }
      import_npmlog38.default.verbose(cmd, interpolatedArgs);
      return childProcess11.exec(cmd, interpolatedArgs, opts);
    }
  }
});

// libs/commands/version/src/lib/is-behind-upstream.ts
var require_is_behind_upstream = __commonJS({
  "libs/commands/version/src/lib/is-behind-upstream.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.isBehindUpstream = isBehindUpstream;
    function isBehindUpstream(gitRemote, branch, opts) {
      import_npmlog38.default.silly("isBehindUpstream");
      updateRemote(opts);
      const remoteBranch = `${gitRemote}/${branch}`;
      const [behind, ahead] = countLeftRight(`${remoteBranch}...${branch}`, opts);
      import_npmlog38.default.silly(
        "isBehindUpstream",
        `${branch} is behind ${remoteBranch} by ${behind} commit(s) and ahead by ${ahead}`
      );
      return Boolean(behind);
    }
    function updateRemote(opts) {
      childProcess11.execSync("git", ["remote", "update"], opts);
    }
    function countLeftRight(symmetricDifference, opts) {
      const stdout = childProcess11.execSync(
        "git",
        ["rev-list", "--left-right", "--count", symmetricDifference],
        opts
      );
      return stdout.split("	").map((val) => parseInt(val, 10));
    }
  }
});

// libs/commands/version/src/lib/remote-branch-exists.ts
var require_remote_branch_exists = __commonJS({
  "libs/commands/version/src/lib/remote-branch-exists.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.remoteBranchExists = remoteBranchExists;
    function remoteBranchExists(gitRemote, branch, opts) {
      import_npmlog38.default.silly("remoteBranchExists");
      const remoteBranch = `${gitRemote}/${branch}`;
      try {
        childProcess11.execSync("git", ["show-ref", "--verify", `refs/remotes/${remoteBranch}`], opts);
        return true;
      } catch (e) {
        return false;
      }
    }
  }
});

// libs/commands/version/src/lib/is-breaking-change.ts
var require_is_breaking_change = __commonJS({
  "libs/commands/version/src/lib/is-breaking-change.ts"(exports, module2) {
    "use strict";
    var import_semver5 = __toESM(require("semver"));
    module2.exports.isBreakingChange = isBreakingChange;
    function isBreakingChange(currentVersion, nextVersion) {
      const releaseType = import_semver5.default.diff(currentVersion, nextVersion);
      let breaking;
      if (releaseType === "major") {
        breaking = true;
      } else if (releaseType === "minor") {
        breaking = import_semver5.default.lt(currentVersion, "1.0.0");
      } else if (releaseType === "patch") {
        breaking = import_semver5.default.lt(currentVersion, "0.1.0");
      } else {
        breaking = false;
      }
      return breaking;
    }
  }
});

// libs/commands/version/src/lib/is-anything-committed.ts
var require_is_anything_committed = __commonJS({
  "libs/commands/version/src/lib/is-anything-committed.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.isAnythingCommitted = isAnythingCommitted;
    function isAnythingCommitted(opts) {
      import_npmlog38.default.silly("isAnythingCommitted");
      const anyCommits = childProcess11.execSync("git", ["rev-list", "--count", "--all", "--max-count=1"], opts);
      import_npmlog38.default.verbose("isAnythingCommitted", anyCommits);
      return Boolean(parseInt(anyCommits, 10));
    }
  }
});

// libs/commands/version/src/lib/prompt-version.ts
var require_prompt_version = __commonJS({
  "libs/commands/version/src/lib/prompt-version.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_semver5 = __toESM(require("semver"));
    module2.exports.makePromptVersion = makePromptVersion;
    function makePromptVersion(resolvePrereleaseId) {
      return (node) => promptVersion(node.version, node.name, resolvePrereleaseId(node.prereleaseId));
    }
    function promptVersion(currentVersion, name, prereleaseId) {
      const patch = import_semver5.default.inc(currentVersion, "patch");
      const minor = import_semver5.default.inc(currentVersion, "minor");
      const major = import_semver5.default.inc(currentVersion, "major");
      const prepatch = import_semver5.default.inc(currentVersion, "prepatch", prereleaseId);
      const preminor = import_semver5.default.inc(currentVersion, "preminor", prereleaseId);
      const premajor = import_semver5.default.inc(currentVersion, "premajor", prereleaseId);
      const message = `Select a new version ${name ? `for ${name} ` : ""}(currently ${currentVersion})`;
      return promptSelectOne(message, {
        choices: [
          { value: patch, name: `Patch (${patch})` },
          { value: minor, name: `Minor (${minor})` },
          { value: major, name: `Major (${major})` },
          { value: prepatch, name: `Prepatch (${prepatch})` },
          { value: preminor, name: `Preminor (${preminor})` },
          { value: premajor, name: `Premajor (${premajor})` },
          { value: "PRERELEASE", name: "Custom Prerelease" },
          { value: "CUSTOM", name: "Custom Version" }
        ]
      }).then((choice) => {
        if (choice === "CUSTOM") {
          return promptTextInput("Enter a custom version", {
            filter: import_semver5.default.valid,
            validate: (v) => v !== null || "Must be a valid semver version"
          });
        }
        if (choice === "PRERELEASE") {
          const defaultVersion = import_semver5.default.inc(currentVersion, "prerelease", prereleaseId);
          const prompt = `(default: "${prereleaseId}", yielding ${defaultVersion})`;
          return promptTextInput(`Enter a prerelease identifier ${prompt}`, {
            filter: (v) => import_semver5.default.inc(currentVersion, "prerelease", v || prereleaseId)
          });
        }
        return choice;
      });
    }
  }
});

// libs/commands/version/src/lib/create-release.ts
var require_create_release = __commonJS({
  "libs/commands/version/src/lib/create-release.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_semver5 = __toESM(require("semver"));
    module2.exports.createRelease = createRelease;
    module2.exports.createReleaseClient = createReleaseClient;
    function createReleaseClient(type) {
      switch (type) {
        case "gitlab":
          return createGitLabClient();
        case "github":
          return createGitHubClient();
        default:
          throw new ValidationError("ERELEASE", "Invalid release client type");
      }
    }
    function createRelease(client, { tags, releaseNotes }, { gitRemote, execOpts }) {
      const repo = parseGitRepo(gitRemote, execOpts);
      return Promise.all(
        releaseNotes.map(({ notes, name }) => {
          const tag = name === "fixed" ? tags[0] : tags.find((t) => t.startsWith(`${name}@`));
          if (!tag) {
            return Promise.resolve();
          }
          const prereleaseParts = import_semver5.default.prerelease(tag.replace(`${name}@`, "")) || [];
          return client.repos.createRelease({
            owner: repo.owner,
            repo: repo.name,
            tag_name: tag,
            name: tag,
            body: notes,
            draft: false,
            prerelease: prereleaseParts.length > 0
          });
        })
      );
    }
  }
});

// libs/commands/version/src/lib/update-lockfile-version.ts
var require_update_lockfile_version = __commonJS({
  "libs/commands/version/src/lib/update-lockfile-version.ts"(exports, module2) {
    "use strict";
    var import_devkit2 = require("@nrwl/devkit");
    var import_load_json_file3 = __toESM(require("load-json-file"));
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_path23 = __toESM(require("path"));
    module2.exports.updateLockfileVersion = updateLockfileVersion;
    function updateLockfileVersion(pkg) {
      const lockfilePath = import_path23.default.join(pkg.location, "package-lock.json");
      let chain = Promise.resolve();
      chain = chain.then(
        () => (0, import_load_json_file3.default)(lockfilePath).catch(() => {
          import_npmlog38.default.verbose("version", `${pkg.name} has no lockfile. Skipping lockfile update.`);
        })
      );
      chain = chain.then((obj) => {
        if (obj) {
          obj.version = pkg.version;
          if (obj.packages && obj.packages[""]) {
            obj.packages[""].version = pkg.version;
            if (obj.packages[""].dependencies) {
              const updatedPkgDependencies = Object.keys(obj.packages[""].dependencies).reduce(
                (prev, next) => ({ ...prev, [next]: pkg.dependencies[next] }),
                {}
              );
              obj.packages[""].dependencies = updatedPkgDependencies;
            }
            if (obj.packages[""].devDependencies) {
              const updatedPkgDevDependencies = Object.keys(obj.packages[""].devDependencies).reduce(
                (prev, next) => ({ ...prev, [next]: pkg.devDependencies[next] }),
                {}
              );
              obj.packages[""].devDependencies = updatedPkgDevDependencies;
            }
          }
          (0, import_devkit2.writeJsonFile)(lockfilePath, obj, {
            spaces: 2
          });
          return lockfilePath;
        }
      });
      return chain;
    }
  }
});

// libs/commands/version/src/index.ts
var require_src12 = __commonJS({
  "libs/commands/version/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_chalk3 = __toESM(require("chalk"));
    var import_dedent5 = __toESM(require("dedent"));
    var import_fs4 = __toESM(require("fs"));
    var import_minimatch2 = __toESM(require("minimatch"));
    var import_os4 = __toESM(require("os"));
    var import_p_map5 = __toESM(require("p-map"));
    var import_p_pipe = __toESM(require("p-pipe"));
    var import_p_reduce = __toESM(require("p-reduce"));
    var import_p_waterfall = __toESM(require("p-waterfall"));
    var import_path23 = __toESM(require("path"));
    var import_semver5 = __toESM(require("semver"));
    var childProcess11 = require("@lerna/child-process");
    var { getCurrentBranch } = require_get_current_branch();
    var { gitAdd } = require_git_add();
    var { gitCommit } = require_git_commit();
    var { gitPush } = require_git_push();
    var { gitTag } = require_git_tag();
    var { isBehindUpstream } = require_is_behind_upstream();
    var { remoteBranchExists } = require_remote_branch_exists();
    var { isBreakingChange } = require_is_breaking_change();
    var { isAnythingCommitted } = require_is_anything_committed();
    var { makePromptVersion } = require_prompt_version();
    var { createRelease, createReleaseClient } = require_create_release();
    var { updateLockfileVersion } = require_update_lockfile_version();
    module2.exports = function factory(argv) {
      return new VersionCommand(argv);
    };
    var VersionCommand = class extends Command {
      get otherCommandConfigs() {
        return ["publish"];
      }
      get requiresGit() {
        return this.commitAndTag || this.pushToRemote || this.options.allowBranch || this.options.conventionalCommits;
      }
      configureProperties() {
        super.configureProperties();
        const {
          amend,
          commitHooks = true,
          gitRemote = "origin",
          gitTagVersion = true,
          granularPathspec = true,
          push = true,
          signGitCommit,
          signoffGitCommit,
          signGitTag,
          forceGitTag,
          tagVersionPrefix = "v"
        } = this.options;
        this.gitRemote = gitRemote;
        this.tagPrefix = tagVersionPrefix;
        this.commitAndTag = gitTagVersion;
        this.pushToRemote = gitTagVersion && amend !== true && push;
        this.releaseClient = this.pushToRemote && this.options.createRelease && createReleaseClient(this.options.createRelease);
        this.releaseNotes = [];
        if (this.releaseClient && this.options.conventionalCommits !== true) {
          throw new ValidationError("ERELEASE", "To create a release, you must enable --conventional-commits");
        }
        if (this.releaseClient && this.options.changelog === false) {
          throw new ValidationError("ERELEASE", "To create a release, you cannot pass --no-changelog");
        }
        this.gitOpts = {
          amend,
          commitHooks,
          granularPathspec,
          signGitCommit,
          signoffGitCommit,
          signGitTag,
          forceGitTag
        };
        this.savePrefix = this.options.exact ? "" : "^";
      }
      initialize() {
        if (!this.project.isIndependent()) {
          this.logger.info("current version", this.project.version);
        }
        if (this.requiresGit) {
          if (!isAnythingCommitted(this.execOpts)) {
            throw new ValidationError(
              "ENOCOMMIT",
              "No commits in this repository. Please commit something before using version."
            );
          }
          this.currentBranch = getCurrentBranch(this.execOpts);
          if (this.currentBranch === "HEAD") {
            throw new ValidationError(
              "ENOGIT",
              "Detached git HEAD, please checkout a branch to choose versions."
            );
          }
          if (this.pushToRemote && !remoteBranchExists(this.gitRemote, this.currentBranch, this.execOpts)) {
            throw new ValidationError(
              "ENOREMOTEBRANCH",
              import_dedent5.default`
            Branch '${this.currentBranch}' doesn't exist in remote '${this.gitRemote}'.
            If this is a new branch, please make sure you push it to the remote first.
          `
            );
          }
          if (this.options.allowBranch && ![].concat(this.options.allowBranch).some((x) => (0, import_minimatch2.default)(this.currentBranch, x))) {
            throw new ValidationError(
              "ENOTALLOWED",
              import_dedent5.default`
            Branch '${this.currentBranch}' is restricted from versioning due to allowBranch config.
            Please consider the reasons for this restriction before overriding the option.
          `
            );
          }
          if (this.commitAndTag && this.pushToRemote && isBehindUpstream(this.gitRemote, this.currentBranch, this.execOpts)) {
            const message = `Local branch '${this.currentBranch}' is behind remote upstream ${this.gitRemote}/${this.currentBranch}`;
            if (!this.options.ci) {
              throw new ValidationError(
                "EBEHIND",
                import_dedent5.default`
              ${message}
              Please merge remote changes into '${this.currentBranch}' with 'git pull'
            `
              );
            }
            this.logger.warn("EBEHIND", `${message}, exiting`);
            return false;
          }
        } else {
          this.logger.notice(
            "FYI",
            "git repository validation has been skipped, please ensure your version bumps are correct"
          );
        }
        if (this.options.conventionalPrerelease && this.options.conventionalGraduate) {
          throw new ValidationError(
            "ENOTALLOWED",
            import_dedent5.default`
          --conventional-prerelease cannot be combined with --conventional-graduate.
        `
          );
        }
        this.updates = collectUpdates(
          this.packageGraph.rawPackageList,
          this.packageGraph,
          this.execOpts,
          this.options
        ).filter((node) => {
          if (node.pkg.private && this.options.private === false) {
            return false;
          }
          if (!node.version) {
            if (node.pkg.private) {
              this.logger.info("version", "Skipping unversioned private package %j", node.name);
            } else {
              throw new ValidationError(
                "ENOVERSION",
                import_dedent5.default`
              A version field is required in ${node.name}'s package.json file.
              If you wish to keep the package unversioned, it must be made private.
            `
              );
            }
          }
          return !!node.version;
        });
        if (!this.updates.length) {
          this.logger.success(`No changed packages to ${this.composed ? "publish" : "version"}`);
          return false;
        }
        this.hasRootedLeaf = this.packageGraph.has(this.project.manifest.name);
        if (this.hasRootedLeaf && !this.composed) {
          this.logger.info("version", "rooted leaf detected, skipping synthetic root lifecycles");
        }
        this.runPackageLifecycle = createRunner({ ...this.options, stdio: "inherit" });
        this.runRootLifecycle = /^(pre|post)?version$/.test(process.env.npm_lifecycle_event) ? (stage) => {
          this.logger.warn("lifecycle", "Skipping root %j because it has already been called", stage);
        } : (stage) => this.runPackageLifecycle(this.project.manifest, stage);
        const tasks = [
          () => this.getVersionsForUpdates(),
          (versions) => this.setUpdatesForVersions(versions),
          () => this.confirmVersions()
        ];
        if (this.commitAndTag && this.gitOpts.amend !== true) {
          const { forcePublish, conventionalCommits, conventionalGraduate } = this.options;
          const checkUncommittedOnly = forcePublish || conventionalCommits && conventionalGraduate;
          const check = checkUncommittedOnly ? throwIfUncommitted : checkWorkingTree;
          tasks.unshift(() => check(this.execOpts));
        } else {
          this.logger.warn("version", "Skipping working tree validation, proceed at your own risk");
        }
        return (0, import_p_waterfall.default)(tasks);
      }
      execute() {
        const tasks = [() => this.updatePackageVersions()];
        if (this.commitAndTag) {
          tasks.push(() => this.commitAndTagUpdates());
        } else {
          this.logger.info("execute", "Skipping git tag/commit");
        }
        if (this.pushToRemote) {
          tasks.push(() => this.gitPushToRemote());
        } else {
          this.logger.info("execute", "Skipping git push");
        }
        if (this.releaseClient) {
          this.logger.info("execute", "Creating releases...");
          tasks.push(
            () => createRelease(
              this.releaseClient,
              { tags: this.tags, releaseNotes: this.releaseNotes },
              { gitRemote: this.options.gitRemote, execOpts: this.execOpts }
            )
          );
        } else {
          this.logger.info("execute", "Skipping releases");
        }
        return (0, import_p_waterfall.default)(tasks).then(() => {
          if (!this.composed) {
            this.logger.success("version", "finished");
          }
          return {
            updates: this.updates,
            updatesVersions: this.updatesVersions
          };
        });
      }
      getVersionsForUpdates() {
        const independentVersions = this.project.isIndependent();
        const { bump, conventionalCommits, preid } = this.options;
        const repoVersion = bump ? import_semver5.default.clean(bump) : "";
        const increment = bump && !import_semver5.default.valid(bump) ? bump : "";
        const resolvePrereleaseId = (existingPreid) => preid || existingPreid || "alpha";
        const makeGlobalVersionPredicate = (nextVersion) => {
          this.globalVersion = nextVersion;
          return () => nextVersion;
        };
        let predicate;
        if (repoVersion) {
          predicate = makeGlobalVersionPredicate(repoVersion);
        } else if (increment && independentVersions) {
          predicate = (node) => import_semver5.default.inc(node.version, increment, resolvePrereleaseId(node.prereleaseId));
        } else if (increment) {
          const prereleaseId = prereleaseIdFromVersion(this.project.version);
          const nextVersion = import_semver5.default.inc(this.project.version, increment, resolvePrereleaseId(prereleaseId));
          predicate = makeGlobalVersionPredicate(nextVersion);
        } else if (conventionalCommits) {
          return this.recommendVersions(resolvePrereleaseId);
        } else if (independentVersions) {
          predicate = makePromptVersion(resolvePrereleaseId);
        } else {
          const prereleaseId = prereleaseIdFromVersion(this.project.version);
          const node = { version: this.project.version, prereleaseId };
          predicate = makePromptVersion(resolvePrereleaseId);
          predicate = predicate(node).then(makeGlobalVersionPredicate);
        }
        return Promise.resolve(predicate).then((getVersion) => this.reduceVersions(getVersion));
      }
      reduceVersions(getVersion) {
        const iterator = (versionMap, node) => Promise.resolve(getVersion(node)).then((version) => versionMap.set(node.name, version));
        return (0, import_p_reduce.default)(this.updates, iterator, /* @__PURE__ */ new Map());
      }
      getPrereleasePackageNames() {
        const prereleasePackageNames = getPackagesForOption(this.options.conventionalPrerelease);
        const isCandidate = prereleasePackageNames.has("*") ? () => true : (node, name) => prereleasePackageNames.has(name);
        return collectPackages(this.packageGraph, { isCandidate }).map((pkg) => pkg.name);
      }
      recommendVersions(resolvePrereleaseId) {
        const independentVersions = this.project.isIndependent();
        const { changelogPreset, conventionalGraduate, conventionalBumpPrerelease } = this.options;
        const rootPath = this.project.manifest.location;
        const type = independentVersions ? "independent" : "fixed";
        const prereleasePackageNames = this.getPrereleasePackageNames();
        const graduatePackageNames = Array.from(getPackagesForOption(conventionalGraduate));
        const shouldPrerelease = (name) => prereleasePackageNames && prereleasePackageNames.includes(name);
        const shouldGraduate = (name) => graduatePackageNames.includes("*") || graduatePackageNames.includes(name);
        const getPrereleaseId = (node) => {
          if (!shouldGraduate(node.name) && (shouldPrerelease(node.name) || node.prereleaseId)) {
            return resolvePrereleaseId(node.prereleaseId);
          }
        };
        let chain = Promise.resolve();
        if (type === "fixed") {
          chain = chain.then(() => this.setGlobalVersionFloor());
        }
        chain = chain.then(
          () => this.reduceVersions(
            (node) => recommendVersion(node, type, {
              changelogPreset,
              rootPath,
              tagPrefix: this.tagPrefix,
              prereleaseId: getPrereleaseId(node),
              conventionalBumpPrerelease
            })
          )
        );
        if (type === "fixed") {
          chain = chain.then((versions) => {
            this.globalVersion = this.setGlobalVersionCeiling(versions);
            return versions;
          });
        }
        return chain;
      }
      setGlobalVersionFloor() {
        const globalVersion = this.project.version;
        for (const node of this.updates) {
          if (import_semver5.default.lt(node.version, globalVersion)) {
            this.logger.verbose(
              "version",
              `Overriding version of ${node.name} from ${node.version} to ${globalVersion}`
            );
            node.pkg.set("version", globalVersion);
          }
        }
      }
      setGlobalVersionCeiling(versions) {
        let highestVersion = this.project.version;
        versions.forEach((bump) => {
          if (bump && import_semver5.default.gt(bump, highestVersion)) {
            highestVersion = bump;
          }
        });
        versions.forEach((_, name) => versions.set(name, highestVersion));
        return highestVersion;
      }
      setUpdatesForVersions(versions) {
        if (this.project.isIndependent() || versions.size === this.packageGraph.size) {
          this.updatesVersions = versions;
        } else {
          let hasBreakingChange;
          for (const [name, bump] of versions) {
            hasBreakingChange = hasBreakingChange || isBreakingChange(this.packageGraph.get(name).version, bump);
          }
          if (hasBreakingChange) {
            this.updates = Array.from(this.packageGraph.values());
            if (this.options.private === false) {
              this.updates = this.updates.filter((node) => !node.pkg.private);
            }
            this.updatesVersions = new Map(this.updates.map((node) => [node.name, this.globalVersion]));
          } else {
            this.updatesVersions = versions;
          }
        }
        this.packagesToVersion = this.updates.map((node) => node.pkg);
      }
      confirmVersions() {
        const changes = this.packagesToVersion.map((pkg) => {
          let line = ` - ${pkg.name}: ${pkg.version} => ${this.updatesVersions.get(pkg.name)}`;
          if (pkg.private) {
            line += ` (${import_chalk3.default.red("private")})`;
          }
          return line;
        });
        output("");
        output("Changes:");
        output(changes.join(import_os4.default.EOL));
        output("");
        if (this.options.yes) {
          this.logger.info("auto-confirmed");
          return true;
        }
        const message = this.composed ? "Are you sure you want to publish these packages?" : "Are you sure you want to create these versions?";
        return promptConfirmation(message);
      }
      updatePackageVersions() {
        const { conventionalCommits, changelogPreset, changelog = true } = this.options;
        const independentVersions = this.project.isIndependent();
        const rootPath = this.project.manifest.location;
        const changedFiles = /* @__PURE__ */ new Set();
        let chain = Promise.resolve();
        if (!this.hasRootedLeaf) {
          chain = chain.then(() => this.runRootLifecycle("preversion"));
        }
        const actions = [
          (pkg) => this.runPackageLifecycle(pkg, "preversion").then(() => pkg),
          (pkg) => pkg.refresh(),
          (pkg) => {
            pkg.set("version", this.updatesVersions.get(pkg.name));
            for (const [depName, resolved] of this.packageGraph.get(pkg.name).localDependencies) {
              const depVersion = this.updatesVersions.get(depName);
              if (depVersion && resolved.type !== "directory") {
                pkg.updateLocalDependency(resolved, depVersion, this.savePrefix);
              }
            }
            return Promise.all([updateLockfileVersion(pkg), pkg.serialize()]).then(([lockfilePath]) => {
              changedFiles.add(pkg.manifestLocation);
              if (lockfilePath) {
                changedFiles.add(lockfilePath);
              }
              return pkg;
            });
          },
          (pkg) => this.runPackageLifecycle(pkg, "version").then(() => pkg)
        ];
        if (conventionalCommits && changelog) {
          const type = independentVersions ? "independent" : "fixed";
          actions.push(
            (pkg) => updateChangelog(pkg, type, {
              changelogPreset,
              rootPath,
              tagPrefix: this.tagPrefix
            }).then(({ logPath, newEntry }) => {
              changedFiles.add(logPath);
              if (independentVersions) {
                this.releaseNotes.push({
                  name: pkg.name,
                  notes: newEntry
                });
              }
              return pkg;
            })
          );
        }
        const mapUpdate = (0, import_p_pipe.default)(...actions);
        chain = chain.then(
          () => runTopologically(this.packagesToVersion, mapUpdate, {
            concurrency: this.concurrency,
            rejectCycles: this.options.rejectCycles
          })
        );
        if (!independentVersions) {
          this.project.version = this.globalVersion;
          if (conventionalCommits && changelog) {
            chain = chain.then(
              () => updateChangelog(this.project.manifest, "root", {
                changelogPreset,
                rootPath,
                tagPrefix: this.tagPrefix,
                version: this.globalVersion
              }).then(({ logPath, newEntry }) => {
                changedFiles.add(logPath);
                this.releaseNotes.push({
                  name: "fixed",
                  notes: newEntry
                });
              })
            );
          }
          chain = chain.then(
            () => Promise.resolve(this.project.serializeConfig()).then((lernaConfigLocation) => {
              changedFiles.add(lernaConfigLocation);
            })
          );
        }
        const npmClientArgsRaw = this.options.npmClientArgs || [];
        const npmClientArgs = npmClientArgsRaw.reduce((args, arg) => args.concat(arg.split(/\s|,/)), []);
        if (this.options.npmClient === "pnpm") {
          chain = chain.then(() => {
            this.logger.verbose("version", "Updating root pnpm-lock.yaml");
            return childProcess11.exec("pnpm", ["install", "--lockfile-only", "--ignore-scripts", ...npmClientArgs], this.execOpts).then(() => {
              const lockfilePath = import_path23.default.join(this.project.rootPath, "pnpm-lock.yaml");
              changedFiles.add(lockfilePath);
            });
          });
        }
        if (this.options.npmClient === "npm" || !this.options.npmClient) {
          const lockfilePath = import_path23.default.join(this.project.rootPath, "package-lock.json");
          if (import_fs4.default.existsSync(lockfilePath)) {
            chain = chain.then(() => {
              this.logger.verbose("version", "Updating root package-lock.json");
              return childProcess11.exec(
                "npm",
                ["install", "--package-lock-only", "--ignore-scripts", ...npmClientArgs],
                this.execOpts
              ).then(() => {
                changedFiles.add(lockfilePath);
              });
            });
          }
        }
        if (!this.hasRootedLeaf) {
          chain = chain.then(() => this.runRootLifecycle("version"));
        }
        if (this.commitAndTag) {
          chain = chain.then(() => gitAdd(Array.from(changedFiles), this.gitOpts, this.execOpts));
        }
        return chain;
      }
      commitAndTagUpdates() {
        let chain = Promise.resolve();
        if (this.project.isIndependent()) {
          chain = chain.then(() => this.gitCommitAndTagVersionForUpdates());
        } else {
          chain = chain.then(() => this.gitCommitAndTagVersion());
        }
        chain = chain.then((tags) => {
          this.tags = tags;
        });
        chain = chain.then(
          () => (0, import_p_map5.default)(this.packagesToVersion, (pkg) => this.runPackageLifecycle(pkg, "postversion"))
        );
        if (!this.hasRootedLeaf) {
          chain = chain.then(() => this.runRootLifecycle("postversion"));
        }
        return chain;
      }
      gitCommitAndTagVersionForUpdates() {
        const tags = this.packagesToVersion.map((pkg) => `${pkg.name}@${this.updatesVersions.get(pkg.name)}`);
        const subject = this.options.message || "Publish";
        const message = tags.reduce((msg, tag) => `${msg}${import_os4.default.EOL} - ${tag}`, `${subject}${import_os4.default.EOL}`);
        return Promise.resolve().then(() => gitCommit(message, this.gitOpts, this.execOpts)).then(
          () => Promise.all(tags.map((tag) => gitTag(tag, this.gitOpts, this.execOpts, this.options.gitTagCommand)))
        ).then(() => tags);
      }
      gitCommitAndTagVersion() {
        const version = this.globalVersion;
        const tag = `${this.tagPrefix}${version}`;
        const message = this.options.message ? this.options.message.replace(/%s/g, tag).replace(/%v/g, version) : tag;
        return Promise.resolve().then(() => gitCommit(message, this.gitOpts, this.execOpts)).then(() => gitTag(tag, this.gitOpts, this.execOpts, this.options.gitTagCommand)).then(() => [tag]);
      }
      gitPushToRemote() {
        this.logger.info("git", "Pushing tags...");
        return gitPush(this.gitRemote, this.currentBranch, this.execOpts);
      }
    };
    module2.exports.VersionCommand = VersionCommand;
  }
});

// libs/commands/version/src/command.ts
var require_command12 = __commonJS({
  "libs/commands/version/src/command.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_semver5 = __toESM(require("semver"));
    function addBumpPositional(yargs2, additionalKeywords = []) {
      const semverKeywords = ["major", "minor", "patch", "premajor", "preminor", "prepatch", "prerelease"].concat(
        additionalKeywords
      );
      const bumpOptionList = `'${semverKeywords.slice(0, -1).join("', '")}', or '${semverKeywords[semverKeywords.length - 1]}'.`;
      yargs2.positional("bump", {
        describe: `Increment version(s) by explicit version _or_ semver keyword,
${bumpOptionList}`,
        type: "string",
        coerce: (choice) => {
          if (!import_semver5.default.valid(choice) && semverKeywords.indexOf(choice) === -1) {
            throw new Error(`bump must be an explicit version string _or_ one of: ${bumpOptionList}`);
          }
          return choice;
        }
      });
    }
    var command = {
      command: "version [bump]",
      describe: "Bump version of packages changed since the last release",
      builder(yargs2, composed) {
        const opts = {
          "allow-branch": {
            describe: "Specify which branches to allow versioning from.",
            type: "array"
          },
          amend: {
            describe: "Amend the existing commit, instead of generating a new one.",
            type: "boolean"
          },
          "conventional-commits": {
            describe: "Use conventional-changelog to determine version bump and generate CHANGELOG.",
            type: "boolean"
          },
          "conventional-graduate": {
            describe: "Version currently prereleased packages to a non-prerelease version."
          },
          "conventional-prerelease": {
            describe: "Version changed packages as prereleases when using --conventional-commits."
          },
          "conventional-bump-prerelease": {
            describe: "Bumps prerelease versions if conventional commits requires it.",
            type: "boolean"
          },
          "changelog-preset": {
            describe: "Custom conventional-changelog preset.",
            type: "string",
            requiresArg: true,
            defaultDescription: "angular"
          },
          exact: {
            describe: "Specify cross-dependency version numbers exactly rather than with a caret (^).",
            type: "boolean"
          },
          "force-publish": {
            describe: "Always include targeted packages in versioning operations, skipping default logic."
          },
          "git-remote": {
            describe: "Push git changes to the specified remote.",
            type: "string",
            requiresArg: true,
            defaultDescription: "origin"
          },
          "create-release": {
            describe: "Create an official GitHub or GitLab release for every version.",
            type: "string",
            choices: ["gitlab", "github"]
          },
          "ignore-changes": {
            describe: [
              "Ignore changes in files matched by glob(s) when detecting changed packages.",
              "Pass --no-ignore-changes to completely disable."
            ].join("\n"),
            type: "array"
          },
          "ignore-scripts": {
            describe: "Disable all lifecycle scripts",
            type: "boolean"
          },
          "include-merged-tags": {
            describe: "Include tags from merged branches when detecting changed packages.",
            type: "boolean"
          },
          m: {
            describe: "Use a custom commit message when creating the version commit.",
            alias: "message",
            type: "string",
            requiresArg: true
          },
          "no-changelog": {
            describe: "Do not generate CHANGELOG.md files when using --conventional-commits.",
            type: "boolean"
          },
          changelog: {
            hidden: true,
            type: "boolean"
          },
          "no-commit-hooks": {
            describe: "Do not run git commit hooks when committing version changes.",
            type: "boolean"
          },
          "commit-hooks": {
            hidden: true,
            type: "boolean"
          },
          "no-git-tag-version": {
            describe: "Do not commit or tag version changes.",
            type: "boolean"
          },
          "git-tag-version": {
            hidden: true,
            type: "boolean"
          },
          "no-granular-pathspec": {
            describe: "Do not stage changes file-by-file, but globally.",
            type: "boolean"
          },
          "granular-pathspec": {
            hidden: true,
            type: "boolean"
          },
          "no-private": {
            describe: "Do not version private packages.",
            type: "boolean"
          },
          private: {
            hidden: true,
            type: "boolean"
          },
          "no-push": {
            describe: "Do not push tagged commit to git remote.",
            type: "boolean"
          },
          push: {
            hidden: true,
            type: "boolean"
          },
          preid: {
            describe: "Specify the prerelease identifier when versioning a prerelease",
            type: "string",
            requiresArg: true,
            defaultDescription: "alpha"
          },
          "sign-git-commit": {
            describe: "Pass the `--gpg-sign` flag to `git commit`.",
            type: "boolean"
          },
          "signoff-git-commit": {
            describe: "Pass the `--signoff` flag to `git commit`.",
            type: "boolean"
          },
          "sign-git-tag": {
            describe: "Pass the `--sign` flag to `git tag`.",
            type: "boolean"
          },
          "force-git-tag": {
            describe: "Pass the `--force` flag to `git tag`.",
            type: "boolean"
          },
          "tag-version-prefix": {
            describe: "Customize the tag prefix. To remove entirely, pass an empty string.",
            type: "string",
            requiresArg: true,
            defaultDescription: "v"
          },
          "git-tag-command": {
            describe: "Allows users to specify a custom command to be used when applying git tags. For example, this may be useful for providing a wrapper command in CI/CD pipelines that have no direct write access.",
            type: "string"
          },
          "npm-client-args": {
            describe: "Additional arguments to pass to the npm client when performing 'npm install'.",
            type: "array"
          },
          y: {
            describe: "Skip all confirmation prompts.",
            alias: "yes",
            type: "boolean"
          }
        };
        if (composed) {
          Object.keys(opts).forEach((key) => {
            opts[key].hidden = true;
          });
          yargs2.default("composed", composed).hide("composed");
        } else {
          addBumpPositional(yargs2);
        }
        yargs2.options(opts);
        yargs2.parserConfiguration({
          "populate--": true
        });
        if (!composed) {
          yargs2.group(Object.keys(opts), "Command Options:");
        }
        return yargs2.option("ignore", {
          hidden: true,
          conflicts: "ignore-changes",
          type: "array"
        }).option("cd-version", {
          hidden: true,
          conflicts: "bump",
          type: "string",
          requiresArg: true
        }).option("repo-version", {
          hidden: true,
          conflicts: "bump",
          type: "string",
          requiresArg: true
        }).option("skip-git", {
          hidden: true,
          type: "boolean"
        }).option("github-release", {
          hidden: true,
          type: "boolean"
        }).check((argv) => {
          if (argv.ignore) {
            argv.ignoreChanges = argv.ignore;
            delete argv.ignore;
            import_npmlog38.default.warn("deprecated", "--ignore has been renamed --ignore-changes");
          }
          if (argv.cdVersion && !argv.bump) {
            argv.bump = argv.cdVersion;
            delete argv.cdVersion;
            delete argv["cd-version"];
            import_npmlog38.default.warn("deprecated", "--cd-version has been replaced by positional [bump]");
          }
          if (argv.repoVersion && !argv.bump) {
            argv.bump = argv.repoVersion;
            delete argv.repoVersion;
            delete argv["repo-version"];
            import_npmlog38.default.warn("deprecated", "--repo-version has been replaced by positional [bump]");
          }
          if (argv.skipGit) {
            argv.gitTagVersion = false;
            argv["git-tag-version"] = false;
            argv.push = false;
            delete argv.skipGit;
            delete argv["skip-git"];
            import_npmlog38.default.warn("deprecated", "--skip-git has been replaced by --no-git-tag-version --no-push");
          }
          if (argv.githubRelease) {
            argv.createRelease = "github";
            delete argv.githubRelease;
            import_npmlog38.default.warn("deprecated", "--github-release has been replaced by --create-release=github");
          }
          if (argv["--"]) {
            import_npmlog38.default.warn("EDOUBLEDASH", "Arguments after -- are no longer passed to subprocess executions.");
            import_npmlog38.default.warn("EDOUBLEDASH", "This will cause an error in a future major version.");
          }
          return argv;
        });
      },
      handler(argv) {
        return require_src12()(argv);
      },
      addBumpPositional
    };
    module2.exports = command;
  }
});

// libs/commands/publish/src/lib/create-temp-licenses.ts
var require_create_temp_licenses = __commonJS({
  "libs/commands/publish/src/lib/create-temp-licenses.ts"(exports, module2) {
    "use strict";
    var import_fs_extra11 = __toESM(require("fs-extra"));
    var import_p_map5 = __toESM(require("p-map"));
    var import_path23 = __toESM(require("path"));
    module2.exports.createTempLicenses = createTempLicenses;
    function createTempLicenses(srcLicensePath, packagesToBeLicensed) {
      if (!srcLicensePath || !packagesToBeLicensed.length) {
        return Promise.resolve();
      }
      const licenseFileName = import_path23.default.basename(srcLicensePath);
      const options = {
        preserveTimestamps: process.arch !== "ia32"
      };
      packagesToBeLicensed.forEach((pkg) => {
        pkg.licensePath = import_path23.default.join(pkg.contents, licenseFileName);
      });
      return (0, import_p_map5.default)(packagesToBeLicensed, (pkg) => import_fs_extra11.default.copy(srcLicensePath, pkg.licensePath, options));
    }
  }
});

// libs/commands/publish/src/lib/get-current-sha.ts
var require_get_current_sha = __commonJS({
  "libs/commands/publish/src/lib/get-current-sha.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.getCurrentSHA = getCurrentSHA;
    function getCurrentSHA(opts) {
      import_npmlog38.default.silly("getCurrentSHA");
      const sha = childProcess11.execSync("git", ["rev-parse", "HEAD"], opts);
      import_npmlog38.default.verbose("getCurrentSHA", sha);
      return sha;
    }
  }
});

// libs/commands/publish/src/lib/get-current-tags.ts
var require_get_current_tags = __commonJS({
  "libs/commands/publish/src/lib/get-current-tags.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_npm_package_arg7 = __toESM(require("npm-package-arg"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.getCurrentTags = getCurrentTags;
    function getCurrentTags(execOpts, matchingPattern) {
      import_npmlog38.default.silly("getCurrentTags", "matching %j", matchingPattern);
      const opts = Object.assign({}, execOpts, {
        reject: false
      });
      return childProcess11.exec("git", ["tag", "--sort", "version:refname", "--points-at", "HEAD", "--list", matchingPattern], opts).then((result) => {
        const lines = result.stdout.split("\n").filter(Boolean);
        if (matchingPattern === "*@*") {
          return lines.map((tag) => (0, import_npm_package_arg7.default)(tag).name);
        }
        return lines;
      });
    }
  }
});

// libs/commands/publish/src/lib/get-unpublished-packages.ts
var require_get_unpublished_packages = __commonJS({
  "libs/commands/publish/src/lib/get-unpublished-packages.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_p_map5 = __toESM(require("p-map"));
    var import_pacote = __toESM(require("pacote"));
    module2.exports.getUnpublishedPackages = getUnpublishedPackages;
    function getUnpublishedPackages(packageGraph, opts) {
      import_npmlog38.default.silly("getUnpublishedPackages");
      let chain = Promise.resolve();
      const graphNodesToCheck = Array.from(packageGraph.values());
      const mapper = (pkg) => import_pacote.default.packument(pkg.name, opts).then(
        (packument) => {
          if (packument.versions === void 0 || packument.versions[pkg.version] === void 0) {
            return pkg;
          }
        },
        () => {
          import_npmlog38.default.warn("", "Unable to determine published version, assuming %j unpublished.", pkg.name);
          return pkg;
        }
      );
      chain = chain.then(() => (0, import_p_map5.default)(graphNodesToCheck, mapper, { concurrency: 4 }));
      return chain.then((results) => results.filter(Boolean));
    }
  }
});

// libs/commands/publish/src/lib/fetch-config.ts
var require_fetch_config = __commonJS({
  "libs/commands/publish/src/lib/fetch-config.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    module2.exports.getFetchConfig = getFetchConfig;
    function getFetchConfig(options, extra) {
      return {
        log: import_npmlog38.default,
        ...options,
        ...extra
      };
    }
  }
});

// libs/commands/publish/src/lib/get-profile-data.ts
var require_get_profile_data = __commonJS({
  "libs/commands/publish/src/lib/get-profile-data.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_npm_registry_fetch2 = __toESM(require("npm-registry-fetch"));
    module2.exports.getProfileData = getProfileData;
    function getProfileData(opts) {
      opts.log.verbose("", "Retrieving npm user profile");
      return pulseTillDone(import_npm_registry_fetch2.default.json("/-/npm/v1/user", opts)).then((data) => {
        opts.log.silly("npm profile get", "received %j", data);
        return Object.assign(
          { username: data.name },
          data
        );
      });
    }
  }
});

// libs/commands/publish/src/lib/get-whoami.ts
var require_get_whoami = __commonJS({
  "libs/commands/publish/src/lib/get-whoami.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_npm_registry_fetch2 = __toESM(require("npm-registry-fetch"));
    module2.exports.getWhoAmI = getWhoAmI;
    function getWhoAmI(opts) {
      opts.log.verbose("", "Retrieving npm username");
      return pulseTillDone(import_npm_registry_fetch2.default.json("/-/whoami", opts)).then((data) => {
        opts.log.silly("npm whoami", "received %j", data);
        return data;
      });
    }
  }
});

// libs/commands/publish/src/lib/get-npm-username.ts
var require_get_npm_username = __commonJS({
  "libs/commands/publish/src/lib/get-npm-username.ts"(exports, module2) {
    "use strict";
    init_src();
    var { getFetchConfig } = require_fetch_config();
    var { getProfileData } = require_get_profile_data();
    var { getWhoAmI } = require_get_whoami();
    module2.exports.getNpmUsername = getNpmUsername;
    function getNpmUsername(options) {
      const opts = getFetchConfig(options, {
        fetchRetries: 0
      });
      opts.log.info("", "Verifying npm credentials");
      return getProfileData(opts).catch((err) => {
        if (err.code === "E500" || err.code === "E404") {
          return getWhoAmI(opts);
        }
        throw err;
      }).then(success, failure);
      function success(result) {
        opts.log.silly("get npm username", "received %j", result);
        if (!result.username) {
          throw new ValidationError(
            "ENEEDAUTH",
            "You must be logged in to publish packages. Use `npm login` and try again."
          );
        }
        return result.username;
      }
      function failure(err) {
        opts.log.pause();
        console.error(err.message);
        opts.log.resume();
        if (opts.registry === "https://registry.npmjs.org/") {
          if (err.code === "E403") {
            throw new ValidationError(
              "ENEEDAUTH",
              "Access verification failed. Ensure that your npm access token has both read and write access, or remove the verifyAccess option to skip this verification. Note that npm automation tokens do NOT have read access (https://docs.npmjs.com/creating-and-viewing-access-tokens)."
            );
          }
          throw new ValidationError("EWHOAMI", "Authentication error. Use `npm whoami` to troubleshoot.");
        }
        opts.log.warn(
          "EWHOAMI",
          "Unable to determine npm username from third-party registry, this command will likely fail soon!"
        );
      }
    }
  }
});

// libs/commands/publish/src/lib/get-tagged-packages.ts
var require_get_tagged_packages = __commonJS({
  "libs/commands/publish/src/lib/get-tagged-packages.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_path23 = __toESM(require("path"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.getTaggedPackages = getTaggedPackages;
    function getTaggedPackages(packageGraph, rootPath, execOpts) {
      import_npmlog38.default.silly("getTaggedPackages");
      return childProcess11.exec("git", ["diff-tree", "--name-only", "--no-commit-id", "--root", "-r", "-c", "HEAD"], execOpts).then(({ stdout }) => {
        const manifests = stdout.split("\n").filter((fp) => import_path23.default.basename(fp) === "package.json");
        const locations = new Set(manifests.map((fp) => import_path23.default.join(rootPath, import_path23.default.dirname(fp))));
        return Array.from(packageGraph.values()).filter((node) => locations.has(node.location));
      });
    }
  }
});

// libs/commands/publish/src/lib/get-packages-without-license.ts
var require_get_packages_without_license = __commonJS({
  "libs/commands/publish/src/lib/get-packages-without-license.ts"(exports, module2) {
    "use strict";
    var import_path23 = __toESM(require("path"));
    module2.exports.getPackagesWithoutLicense = getPackagesWithoutLicense;
    function getPackagesWithoutLicense(project, packagesToPublish) {
      return project.getPackageLicensePaths().then((licensePaths) => {
        const licensed = new Set(licensePaths.map((lp) => import_path23.default.dirname(lp)));
        return packagesToPublish.filter((pkg) => !licensed.has(pkg.location));
      });
    }
  }
});

// libs/commands/publish/src/lib/git-checkout.ts
var require_git_checkout = __commonJS({
  "libs/commands/publish/src/lib/git-checkout.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var childProcess11 = require("@lerna/child-process");
    module2.exports.gitCheckout = gitCheckout;
    function gitCheckout(stagedFiles, gitOpts, execOpts) {
      const files = gitOpts.granularPathspec ? stagedFiles : ".";
      import_npmlog38.default.silly("gitCheckout", files);
      return childProcess11.exec("git", ["checkout", "--"].concat(files), execOpts);
    }
  }
});

// libs/commands/publish/src/lib/remove-temp-licenses.ts
var require_remove_temp_licenses = __commonJS({
  "libs/commands/publish/src/lib/remove-temp-licenses.ts"(exports, module2) {
    "use strict";
    var import_fs_extra11 = __toESM(require("fs-extra"));
    var import_p_map5 = __toESM(require("p-map"));
    module2.exports.removeTempLicenses = removeTempLicenses;
    function removeTempLicenses(packagesToBeLicensed) {
      if (!packagesToBeLicensed.length) {
        return Promise.resolve();
      }
      return (0, import_p_map5.default)(packagesToBeLicensed, (pkg) => import_fs_extra11.default.remove(pkg.licensePath));
    }
  }
});

// libs/commands/publish/src/lib/verify-npm-package-access.ts
var require_verify_npm_package_access = __commonJS({
  "libs/commands/publish/src/lib/verify-npm-package-access.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_libnpmaccess = __toESM(require("libnpmaccess"));
    var { getFetchConfig } = require_fetch_config();
    module2.exports.verifyNpmPackageAccess = verifyNpmPackageAccess;
    function verifyNpmPackageAccess(packages, username, options) {
      const opts = getFetchConfig(options, {
        fetchRetries: 0
      });
      opts.log.silly("verifyNpmPackageAccess");
      return pulseTillDone(import_libnpmaccess.default.lsPackages(username, opts)).then(success, failure);
      function success(result) {
        if (result === null) {
          opts.log.warn(
            "",
            "The logged-in user does not have any previously-published packages, skipping permission checks..."
          );
        } else {
          for (const pkg of packages) {
            if (pkg.name in result && result[pkg.name] !== "read-write") {
              throw new ValidationError(
                "EACCESS",
                `You do not have write permission required to publish "${pkg.name}"`
              );
            }
          }
        }
      }
      function failure(err) {
        if (err.code === "E500" || err.code === "E404") {
          opts.log.warn(
            "EREGISTRY",
            "Registry %j does not support `npm access ls-packages`, skipping permission checks...",
            opts.registry
          );
          return;
        }
        opts.log.pause();
        console.error(err.message);
        opts.log.resume();
        throw new ValidationError("EWHOAMI", "Authentication error. Use `npm whoami` to troubleshoot.");
      }
    }
  }
});

// libs/commands/publish/src/lib/get-two-factor-auth-required.ts
var require_get_two_factor_auth_required = __commonJS({
  "libs/commands/publish/src/lib/get-two-factor-auth-required.ts"(exports, module2) {
    "use strict";
    init_src();
    var { getFetchConfig } = require_fetch_config();
    var { getProfileData } = require_get_profile_data();
    module2.exports.getTwoFactorAuthRequired = getTwoFactorAuthRequired;
    function getTwoFactorAuthRequired(options) {
      const opts = getFetchConfig(options, {
        fetchRetries: 0
      });
      opts.log.info("", "Checking two-factor auth mode");
      return getProfileData(opts).then(success, failure);
      function success(result) {
        opts.log.silly("2FA", result.tfa);
        if (result.tfa.pending) {
          return false;
        }
        return result.tfa.mode === "auth-and-writes";
      }
      function failure(err) {
        if (err.code === "E500" || err.code === "E404") {
          opts.log.warn(
            "EREGISTRY",
            `Registry "${opts.registry}" does not support 'npm profile get', skipping two-factor auth check...`
          );
          return false;
        }
        opts.log.pause();
        console.error(err.message);
        opts.log.resume();
        throw new ValidationError("ETWOFACTOR", "Unable to obtain two-factor auth mode");
      }
    }
  }
});

// libs/commands/publish/src/index.ts
var require_src13 = __commonJS({
  "libs/commands/publish/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_crypto = __toESM(require("crypto"));
    var import_fs4 = __toESM(require("fs"));
    var import_os4 = __toESM(require("os"));
    var import_p_map5 = __toESM(require("p-map"));
    var import_p_pipe = __toESM(require("p-pipe"));
    var import_path23 = __toESM(require("path"));
    var import_semver5 = __toESM(require("semver"));
    var versionCommand = require_src12();
    var { createTempLicenses } = require_create_temp_licenses();
    var { getCurrentSHA } = require_get_current_sha();
    var { getCurrentTags } = require_get_current_tags();
    var { getUnpublishedPackages } = require_get_unpublished_packages();
    var { getNpmUsername } = require_get_npm_username();
    var { getTaggedPackages } = require_get_tagged_packages();
    var { getPackagesWithoutLicense } = require_get_packages_without_license();
    var { gitCheckout } = require_git_checkout();
    var { removeTempLicenses } = require_remove_temp_licenses();
    var { verifyNpmPackageAccess } = require_verify_npm_package_access();
    var { getTwoFactorAuthRequired } = require_get_two_factor_auth_required();
    module2.exports = function factory(argv) {
      return new PublishCommand(argv);
    };
    var PublishCommand = class extends Command {
      get otherCommandConfigs() {
        return ["version"];
      }
      get requiresGit() {
        return this.options.bump !== "from-package";
      }
      configureProperties() {
        super.configureProperties();
        this.toposort = this.options.sort !== false;
        const {
          exact,
          gitHead,
          gitReset,
          tagVersionPrefix = "v",
          verifyAccess
        } = this.options;
        if (this.requiresGit && gitHead) {
          throw new ValidationError("EGITHEAD", "--git-head is only allowed with 'from-package' positional");
        }
        this.savePrefix = exact ? "" : "^";
        this.tagPrefix = tagVersionPrefix;
        this.gitReset = gitReset !== false;
        this.npmSession = import_crypto.default.randomBytes(8).toString("hex");
        this.verifyAccess = verifyAccess;
      }
      get userAgent() {
        return `lerna/${this.options.lernaVersion}/node@${process.version}+${process.arch} (${process.platform})`;
      }
      initialize() {
        if (this.options.verifyAccess === false) {
          this.logger.warn(
            "verify-access",
            "--verify-access=false and --no-verify-access are no longer needed, because the legacy preemptive access verification is now disabled by default. Requests will fail with appropriate errors when not authorized correctly."
          );
        }
        if (this.options.graphType === "dependencies") {
          this.logger.warn(
            "graph-type",
            "--graph-type=dependencies is deprecated and will be removed in lerna v6. If you have a use-case you feel requires it please open an issue to discuss: https://github.com/lerna/lerna/issues/new/choose"
          );
        }
        if (this.options.includePrivate) {
          if (this.options.includePrivate.length === 0) {
            throw new ValidationError(
              "EINCLPRIV",
              "Must specify at least one private package to include with --include-private."
            );
          }
          this.logger.info("publish", `Including private packages %j`, this.options.includePrivate);
        }
        if (this.options.skipNpm) {
          this.logger.warn("deprecated", "Instead of --skip-npm, call `lerna version` directly");
          return versionCommand(this.argv).then(() => false);
        }
        if (this.options.canary) {
          this.logger.info("canary", "enabled");
        }
        if (this.options.requireScripts) {
          this.logger.info("require-scripts", "enabled");
        }
        this.logger.verbose("session", this.npmSession);
        this.logger.verbose("user-agent", this.userAgent);
        this.conf = npmConf2({
          lernaCommand: "publish",
          _auth: this.options.legacyAuth,
          npmSession: this.npmSession,
          npmVersion: this.userAgent,
          otp: this.options.otp,
          registry: this.options.registry,
          "ignore-prepublish": this.options.ignorePrepublish,
          "ignore-scripts": this.options.ignoreScripts
        });
        this.otpCache = { otp: this.conf.get("otp") };
        this.conf.set("user-agent", this.userAgent, "cli");
        if (this.conf.get("registry") === "https://registry.yarnpkg.com") {
          this.logger.warn("", "Yarn's registry proxy is broken, replacing with public npm registry");
          this.logger.warn("", "If you don't have an npm token, you should exit and run `npm login`");
          this.conf.set("registry", "https://registry.npmjs.org/", "cli");
        }
        const distTag = this.getDistTag();
        if (distTag) {
          this.conf.set("tag", distTag.trim(), "cli");
        }
        this.hasRootedLeaf = this.packageGraph.has(this.project.manifest.name);
        if (this.hasRootedLeaf) {
          this.logger.info("publish", "rooted leaf detected, skipping synthetic root lifecycles");
        }
        this.runPackageLifecycle = createRunner(this.options);
        this.runRootLifecycle = /^(pre|post)?publish$/.test(process.env.npm_lifecycle_event) ? (stage) => {
          this.logger.warn("lifecycle", "Skipping root %j because it has already been called", stage);
        } : (stage) => this.runPackageLifecycle(this.project.manifest, stage);
        let chain = Promise.resolve();
        if (this.options.bump === "from-git") {
          chain = chain.then(() => this.detectFromGit());
        } else if (this.options.bump === "from-package") {
          chain = chain.then(() => this.detectFromPackage());
        } else if (this.options.canary) {
          chain = chain.then(() => this.detectCanaryVersions());
        } else {
          chain = chain.then(() => versionCommand(this.argv));
        }
        return chain.then((result) => {
          if (!result) {
            return false;
          }
          if (!result.updates.length) {
            this.logger.success("No changed packages to publish");
            return false;
          }
          this.updates = this.filterPrivatePkgUpdates(result.updates);
          this.updatesVersions = new Map(result.updatesVersions);
          this.packagesToPublish = this.updates.map((node) => node.pkg);
          if (this.options.contents) {
            for (const pkg of this.packagesToPublish) {
              pkg.contents = this.options.contents;
            }
          }
          if (result.needsConfirmation) {
            return this.confirmPublish();
          }
          return true;
        });
      }
      execute() {
        this.enableProgressBar();
        this.logger.info("publish", "Publishing packages to npm...");
        let chain = Promise.resolve();
        chain = chain.then(() => this.prepareRegistryActions());
        chain = chain.then(() => this.prepareLicenseActions());
        chain = chain.then(() => this.preparePrivatePackages());
        if (this.options.canary) {
          chain = chain.then(() => this.updateCanaryVersions());
        }
        chain = chain.then(() => this.resolveLocalDependencyLinks());
        chain = chain.then(() => this.resolveWorkspaceDependencyLinks());
        chain = chain.then(() => this.annotateGitHead());
        chain = chain.then(() => this.serializeChanges());
        chain = chain.then(() => this.packUpdated());
        chain = chain.then(() => this.publishPacked());
        chain = chain.then(() => this.restorePrivatePackages());
        chain = chain.then(() => this.serializeChanges());
        if (this.gitReset) {
          chain = chain.then(() => this.resetChanges());
        }
        if (this.options.tempTag) {
          chain = chain.then(() => this.npmUpdateAsLatest());
        }
        return chain.then(() => {
          const count = this.publishedPackages.length;
          const publishedPackagesSorted = this.publishedPackages.sort((a, b) => a.name.localeCompare(b.name));
          if (!count) {
            this.logger.success("All packages have already been published.");
            return;
          }
          output("Successfully published:");
          if (this.options.summaryFile !== void 0) {
            const filePath = this.options.summaryFile ? `${this.options.summaryFile}/lerna-publish-summary.json` : "./lerna-publish-summary.json";
            const jsonObject = publishedPackagesSorted.map((pkg) => {
              return {
                packageName: pkg.name,
                version: pkg.version
              };
            });
            output(jsonObject);
            try {
              import_fs4.default.writeFileSync(filePath, JSON.stringify(jsonObject));
              output("Publish summary created: ", filePath);
            } catch (error) {
              output("Failed to create the summary report", error);
            }
          } else {
            const message = publishedPackagesSorted.map((pkg) => ` - ${pkg.name}@${pkg.version}`);
            output(message.join(import_os4.default.EOL));
          }
          this.logger.success("published", "%d %s", count, count === 1 ? "package" : "packages");
        });
      }
      verifyWorkingTreeClean() {
        return describeRef(this.execOpts).then(throwIfUncommitted);
      }
      detectFromGit() {
        const matchingPattern = this.project.isIndependent() ? "*@*" : `${this.tagPrefix}*.*.*`;
        let chain = Promise.resolve();
        chain = chain.then(() => this.verifyWorkingTreeClean()).catch((err) => {
          if (err.failed && /git describe/.test(err.command)) {
            this.logger.silly("EWORKINGTREE", err.message);
            this.logger.notice("FYI", "Unable to verify working tree, proceed at your own risk");
          } else {
            throw err;
          }
        });
        chain = chain.then(() => getCurrentTags(this.execOpts, matchingPattern));
        chain = chain.then((taggedPackageNames) => {
          if (!taggedPackageNames.length) {
            this.logger.notice("from-git", "No tagged release found");
            return [];
          }
          if (this.project.isIndependent()) {
            return taggedPackageNames.map((name) => this.packageGraph.get(name));
          }
          return getTaggedPackages(this.packageGraph, this.project.rootPath, this.execOpts);
        });
        chain = chain.then((updates) => this.filterPrivatePkgUpdates(updates));
        return chain.then((updates) => {
          const updatesVersions = updates.map((node) => [node.name, node.version]);
          return {
            updates,
            updatesVersions,
            needsConfirmation: true
          };
        });
      }
      detectFromPackage() {
        let chain = Promise.resolve();
        chain = chain.then(() => this.verifyWorkingTreeClean()).catch((err) => {
          if (err.failed && /git describe/.test(err.command)) {
            this.logger.silly("EWORKINGTREE", err.message);
            this.logger.notice("FYI", "Unable to verify working tree, proceed at your own risk");
          } else {
            throw err;
          }
        });
        chain = chain.then(() => getUnpublishedPackages(this.packageGraph, this.conf.snapshot));
        chain = chain.then((updates) => this.filterPrivatePkgUpdates(updates));
        chain = chain.then((unpublished) => {
          if (!unpublished.length) {
            this.logger.notice("from-package", "No unpublished release found");
          }
          return unpublished;
        });
        return chain.then((updates) => {
          const updatesVersions = updates.map((node) => [node.name, node.version]);
          return {
            updates,
            updatesVersions,
            needsConfirmation: true
          };
        });
      }
      detectCanaryVersions() {
        const { cwd } = this.execOpts;
        const {
          bump = "prepatch",
          preid = "alpha",
          ignoreChanges,
          forcePublish,
          includeMergedTags
        } = this.options;
        const release = bump.startsWith("pre") ? bump.replace("release", "patch") : `pre${bump}`;
        let chain = Promise.resolve();
        chain = chain.then(() => this.verifyWorkingTreeClean()).catch((err) => {
          if (err.failed && /git describe/.test(err.command)) {
            this.logger.silly("EWORKINGTREE", err.message);
            this.logger.notice("FYI", "Unable to verify working tree, proceed at your own risk");
          } else {
            throw err;
          }
        });
        chain = chain.then(
          () => this.filterPrivatePkgUpdates(
            collectUpdates(this.packageGraph.rawPackageList, this.packageGraph, this.execOpts, {
              bump: "prerelease",
              canary: true,
              ignoreChanges,
              forcePublish,
              includeMergedTags
            })
          )
        );
        const makeVersion = (fallback) => ({ lastVersion = fallback, refCount, sha }) => {
          const nextVersion = import_semver5.default.inc(lastVersion.replace(this.tagPrefix, ""), release.replace("pre", ""));
          return `${nextVersion}-${preid}.${Math.max(0, refCount - 1)}+${sha}`;
        };
        if (this.project.isIndependent()) {
          chain = chain.then(
            (updates) => (0, import_p_map5.default)(
              updates,
              (node) => describeRef(
                {
                  match: `${node.name}@*`,
                  cwd
                },
                includeMergedTags
              ).then(makeVersion(node.version)).then((version) => [node.name, version])
            ).then((updatesVersions) => ({
              updates,
              updatesVersions
            }))
          );
        } else {
          chain = chain.then(
            (updates) => describeRef(
              {
                match: `${this.tagPrefix}*.*.*`,
                cwd
              },
              includeMergedTags
            ).then(makeVersion(this.project.version)).then((version) => updates.map((node) => [node.name, version])).then((updatesVersions) => ({
              updates,
              updatesVersions
            }))
          );
        }
        return chain.then(({ updates, updatesVersions }) => ({
          updates,
          updatesVersions,
          needsConfirmation: true
        }));
      }
      confirmPublish() {
        const count = this.packagesToPublish.length;
        const message = this.packagesToPublish.map(
          (pkg) => ` - ${pkg.name} => ${this.updatesVersions.get(pkg.name)}${pkg.private ? " (private!)" : ""}`
        );
        output("");
        output(`Found ${count} ${count === 1 ? "package" : "packages"} to publish:`);
        output(message.join(import_os4.default.EOL));
        output("");
        if (this.options.yes) {
          this.logger.info("auto-confirmed");
          return true;
        }
        return promptConfirmation("Are you sure you want to publish these packages?");
      }
      preparePrivatePackages() {
        return Promise.resolve().then(() => {
          this.privatePackagesToPublish = [];
          this.packagesToPublish.forEach((pkg) => {
            if (pkg.private) {
              pkg.removePrivate();
              this.privatePackagesToPublish.push(pkg);
            }
          });
        });
      }
      restorePrivatePackages() {
        return Promise.resolve().then(() => {
          this.privatePackagesToPublish.forEach((pkg) => {
            pkg.private = true;
          });
        });
      }
      prepareLicenseActions() {
        return Promise.resolve().then(() => getPackagesWithoutLicense(this.project, this.packagesToPublish)).then((packagesWithoutLicense) => {
          if (packagesWithoutLicense.length && !this.project.licensePath) {
            this.packagesToBeLicensed = [];
            const names = packagesWithoutLicense.map((pkg) => pkg.name);
            const noun = names.length > 1 ? "Packages" : "Package";
            const verb = names.length > 1 ? "are" : "is";
            const list2 = names.length > 1 ? `${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]}` : names[0];
            this.logger.warn(
              "ENOLICENSE",
              "%s %s %s missing a license.\n%s\n%s",
              noun,
              list2,
              verb,
              "One way to fix this is to add a LICENSE.md file to the root of this repository.",
              "See https://choosealicense.com for additional guidance."
            );
          } else {
            this.packagesToBeLicensed = packagesWithoutLicense;
          }
        });
      }
      prepareRegistryActions() {
        let chain = Promise.resolve();
        if (this.conf.get("registry") !== "https://registry.npmjs.org/") {
          this.logger.notice("", "Skipping all user and access validation due to third-party registry");
          this.logger.notice("", "Make sure you're authenticated properly \xAF\\_(\u30C4)_/\xAF");
          return chain;
        }
        if (process.env.LERNA_INTEGRATION) {
          return chain;
        }
        if (this.verifyAccess) {
          chain = chain.then(() => getNpmUsername(this.conf.snapshot));
          chain = chain.then((username) => {
            if (username) {
              return verifyNpmPackageAccess(this.packagesToPublish, username, this.conf.snapshot);
            }
          });
          chain = chain.then(() => getTwoFactorAuthRequired(this.conf.snapshot));
          chain = chain.then((isRequired) => {
            this.twoFactorAuthRequired = isRequired;
          });
        }
        return chain;
      }
      updateCanaryVersions() {
        return (0, import_p_map5.default)(this.updates, (node) => {
          node.pkg.set("version", this.updatesVersions.get(node.name));
          for (const [depName, resolved] of node.localDependencies) {
            const depVersion = this.updatesVersions.get(depName) || this.packageGraph.get(depName).pkg.version;
            node.pkg.updateLocalDependency(resolved, depVersion, this.savePrefix);
          }
        });
      }
      resolveLocalDependencyLinks() {
        const updatesWithLocalLinks = this.updates.filter(
          (node) => Array.from(node.localDependencies.values()).some((resolved) => resolved.type === "directory")
        );
        return (0, import_p_map5.default)(updatesWithLocalLinks, (node) => {
          for (const [depName, resolved] of node.localDependencies) {
            const depVersion = this.updatesVersions.get(depName) || this.packageGraph.get(depName).pkg.version;
            node.pkg.updateLocalDependency(resolved, depVersion, this.savePrefix);
          }
        });
      }
      resolveWorkspaceDependencyLinks() {
        const updatesWithWorkspaceLinks = this.updates.filter(
          (node) => Array.from(node.localDependencies.values()).some((resolved) => !!resolved.workspaceSpec)
        );
        return (0, import_p_map5.default)(updatesWithWorkspaceLinks, (node) => {
          for (const [depName, resolved] of node.localDependencies) {
            if (resolved.workspaceSpec) {
              let depVersion;
              let savePrefix;
              if (resolved.workspaceAlias) {
                depVersion = this.updatesVersions.get(depName) || this.packageGraph.get(depName).pkg.version;
                savePrefix = resolved.workspaceAlias === "*" ? "" : resolved.workspaceAlias;
              } else {
                const specMatch = resolved.workspaceSpec.match(/^workspace:([~^]?)(.*)/);
                savePrefix = specMatch[1];
                depVersion = specMatch[2];
              }
              node.pkg.updateLocalDependency(resolved, depVersion, savePrefix, { retainWorkspacePrefix: false });
            }
          }
        });
      }
      annotateGitHead() {
        try {
          const gitHead = this.options.gitHead || getCurrentSHA(this.execOpts);
          for (const pkg of this.packagesToPublish) {
            pkg.set("gitHead", gitHead);
          }
        } catch (err) {
          this.logger.silly("EGITHEAD", err.message);
          this.logger.notice(
            "FYI",
            "Unable to set temporary gitHead property, it will be missing from registry metadata"
          );
        }
      }
      serializeChanges() {
        return (0, import_p_map5.default)(this.packagesToPublish, (pkg) => pkg.serialize());
      }
      resetChanges() {
        const { cwd } = this.execOpts;
        const gitOpts = {
          granularPathspec: this.options.granularPathspec !== false
        };
        const dirtyManifests = [this.project.manifest].concat(this.packagesToPublish).map((pkg) => import_path23.default.relative(cwd, pkg.manifestLocation));
        return gitCheckout(dirtyManifests, gitOpts, this.execOpts).catch((err) => {
          this.logger.silly("EGITCHECKOUT", err.message);
          this.logger.notice("FYI", "Unable to reset working tree changes, this probably isn't a git repo.");
        });
      }
      execScript(pkg, script) {
        const scriptLocation = import_path23.default.join(pkg.location, "scripts", script);
        try {
          require(scriptLocation);
        } catch (ex) {
          this.logger.silly("execScript", `No ${script} script found at ${scriptLocation}`);
        }
        return pkg;
      }
      removeTempLicensesOnError(error) {
        return Promise.resolve().then(
          () => removeTempLicenses(this.packagesToBeLicensed).catch((removeError) => {
            this.logger.error(
              "licenses",
              "error removing temporary license files",
              removeError.stack || removeError
            );
          })
        ).then(() => {
          throw error;
        });
      }
      requestOneTimePassword() {
        if (this.otpCache.otp) {
          return;
        }
        return Promise.resolve().then(() => getOneTimePassword("Enter OTP:")).then((otp) => {
          this.otpCache.otp = otp;
        });
      }
      topoMapPackages(mapper) {
        return runTopologically(this.packagesToPublish, mapper, {
          concurrency: this.concurrency,
          rejectCycles: this.options.rejectCycles,
          graphType: this.options.graphType === "dependencies" ? "dependencies" : "allDependencies"
        });
      }
      packUpdated() {
        const tracker = this.logger.newItem("npm pack");
        tracker.addWork(this.packagesToPublish.length);
        let chain = Promise.resolve();
        chain = chain.then(() => createTempLicenses(this.project.licensePath, this.packagesToBeLicensed));
        if (!this.hasRootedLeaf) {
          chain = chain.then(() => this.runRootLifecycle("prepublish"));
          chain = chain.then(() => this.runPackageLifecycle(this.project.manifest, "prepare"));
          chain = chain.then(() => this.runPackageLifecycle(this.project.manifest, "prepublishOnly"));
          chain = chain.then(() => this.runPackageLifecycle(this.project.manifest, "prepack"));
        }
        const opts = this.conf.snapshot;
        const mapper = (0, import_p_pipe.default)(
          ...[
            this.options.requireScripts && ((pkg) => this.execScript(pkg, "prepublish")),
            (pkg) => pulseTillDone(packDirectory(pkg, pkg.location, opts)).then((packed) => {
              tracker.verbose("packed", import_path23.default.relative(this.project.rootPath, pkg.contents));
              tracker.completeWork(1);
              pkg.packed = packed;
              return pkg.refresh();
            })
          ].filter(Boolean)
        );
        chain = chain.then(() => {
          if (this.toposort) {
            return this.topoMapPackages(mapper);
          }
          return (0, import_p_map5.default)(this.packagesToPublish, mapper, { concurrency: this.concurrency });
        });
        chain = chain.then(() => removeTempLicenses(this.packagesToBeLicensed));
        chain = chain.catch((error) => this.removeTempLicensesOnError(error));
        if (!this.hasRootedLeaf) {
          chain = chain.then(() => this.runPackageLifecycle(this.project.manifest, "postpack"));
        }
        return chain.finally(() => tracker.finish());
      }
      publishPacked() {
        this.publishedPackages = [];
        const tracker = this.logger.newItem("publish");
        tracker.addWork(this.packagesToPublish.length);
        let chain = Promise.resolve();
        if (this.twoFactorAuthRequired) {
          chain = chain.then(() => this.requestOneTimePassword());
        }
        const opts = Object.assign(this.conf.snapshot, {
          tag: this.options.tempTag ? "lerna-temp" : this.conf.get("tag")
        });
        const mapper = (0, import_p_pipe.default)(
          ...[
            (pkg) => {
              const preDistTag = this.getPreDistTag(pkg);
              const tag = !this.options.tempTag && preDistTag ? preDistTag : opts.tag;
              const pkgOpts = Object.assign({}, opts, { tag });
              return pulseTillDone(npmPublish(pkg, pkg.packed.tarFilePath, pkgOpts, this.otpCache)).then(() => {
                this.publishedPackages.push(pkg);
                tracker.success("published", pkg.name, pkg.version);
                tracker.completeWork(1);
                logPacked(pkg.packed);
                return pkg;
              }).catch((err) => {
                if (err.code === "EPUBLISHCONFLICT") {
                  tracker.warn("publish", `Package is already published: ${pkg.name}@${pkg.version}`);
                  tracker.completeWork(1);
                  return pkg;
                }
                this.logger.silly("", err);
                this.logger.error(err.code, err.body && err.body.error || err.message);
                err.name = "ValidationError";
                process.exitCode = "errno" in err ? err.errno : 1;
                throw err;
              });
            },
            this.options.requireScripts && ((pkg) => this.execScript(pkg, "postpublish"))
          ].filter(Boolean)
        );
        chain = chain.then(() => {
          if (this.toposort) {
            return this.topoMapPackages(mapper);
          }
          return (0, import_p_map5.default)(this.packagesToPublish, mapper, { concurrency: this.concurrency });
        });
        if (!this.hasRootedLeaf) {
          chain = chain.then(() => this.runRootLifecycle("publish"));
          chain = chain.then(() => this.runRootLifecycle("postpublish"));
        }
        return chain.finally(() => tracker.finish());
      }
      npmUpdateAsLatest() {
        const tracker = this.logger.newItem("npmUpdateAsLatest");
        tracker.addWork(this.packagesToPublish.length);
        tracker.showProgress();
        let chain = Promise.resolve();
        const opts = this.conf.snapshot;
        const getDistTag = (publishConfig) => {
          if (opts.tag === "latest" && publishConfig && publishConfig.tag) {
            return publishConfig.tag;
          }
          return opts.tag;
        };
        const mapper = (pkg) => {
          const spec = `${pkg.name}@${pkg.version}`;
          const preDistTag = this.getPreDistTag(pkg);
          const distTag = preDistTag || getDistTag(pkg.get("publishConfig"));
          return Promise.resolve().then(() => pulseTillDone(npmDistTag.remove(spec, "lerna-temp", opts, this.otpCache))).then(() => pulseTillDone(npmDistTag.add(spec, distTag, opts, this.otpCache))).then(() => {
            tracker.success("dist-tag", "%s@%s => %j", pkg.name, pkg.version, distTag);
            tracker.completeWork(1);
            return pkg;
          });
        };
        chain = chain.then(() => {
          if (this.toposort) {
            return this.topoMapPackages(mapper);
          }
          return (0, import_p_map5.default)(this.packagesToPublish, mapper, { concurrency: this.concurrency });
        });
        return chain.finally(() => tracker.finish());
      }
      getDistTag() {
        if (this.options.distTag) {
          return this.options.distTag;
        }
        if (this.options.canary) {
          return "canary";
        }
      }
      getPreDistTag(pkg) {
        if (!this.options.preDistTag) {
          return;
        }
        const isPrerelease = prereleaseIdFromVersion(pkg.version);
        if (isPrerelease) {
          return this.options.preDistTag;
        }
      }
      filterPrivatePkgUpdates(updates) {
        const privatePackagesToInclude = new Set(this.options.includePrivate || []);
        return updates.filter(
          (node) => !node.pkg.private || privatePackagesToInclude.has("*") || privatePackagesToInclude.has(node.pkg.name)
        );
      }
    };
    module2.exports.PublishCommand = PublishCommand;
  }
});

// libs/commands/publish/src/command.ts
var require_command13 = __commonJS({
  "libs/commands/publish/src/command.ts"(exports, module2) {
    "use strict";
    var import_npmlog38 = __toESM(require("npmlog"));
    var versionCommand = require_command12();
    function composeVersionOptions(yargs2) {
      versionCommand.addBumpPositional(yargs2, ["from-git", "from-package"]);
      versionCommand.builder(yargs2, "publish");
      return yargs2;
    }
    var command = {
      command: "publish [bump]",
      describe: "Publish packages in the current project",
      builder(yargs2) {
        const opts = {
          c: {
            describe: "Publish packages after every successful merge using the sha as part of the tag.",
            alias: "canary",
            type: "boolean"
          },
          preid: {
            describe: "Specify the prerelease identifier when publishing a prerelease",
            type: "string",
            requiresArg: true,
            defaultDescription: "alpha"
          },
          contents: {
            describe: "Subdirectory to publish. Must apply to ALL packages.",
            type: "string",
            requiresArg: true,
            defaultDescription: "."
          },
          "dist-tag": {
            describe: "Publish packages with the specified npm dist-tag",
            type: "string",
            requiresArg: true
          },
          "legacy-auth": {
            describe: "Legacy Base64 Encoded username and password.",
            type: "string"
          },
          "pre-dist-tag": {
            describe: "Publish prerelease packages with the specified npm dist-tag",
            type: "string",
            requiresArg: true
          },
          "git-head": {
            describe: "Explicit SHA to set as gitHead when packing tarballs, only allowed with 'from-package' positional.",
            type: "string",
            requiresArg: true
          },
          "graph-type": {
            describe: "Type of dependency to use when determining package hierarchy.",
            choices: ["all", "dependencies"],
            defaultDescription: "dependencies"
          },
          "ignore-prepublish": {
            describe: "Disable deprecated 'prepublish' lifecycle script",
            type: "boolean"
          },
          "ignore-scripts": {
            describe: "Disable all lifecycle scripts",
            type: "boolean"
          },
          "no-granular-pathspec": {
            describe: "Do not reset changes file-by-file, but globally.",
            type: "boolean"
          },
          "granular-pathspec": {
            hidden: true,
            type: "boolean"
          },
          otp: {
            describe: "Supply a one-time password for publishing with two-factor authentication.",
            type: "string",
            requiresArg: true
          },
          registry: {
            describe: "Use the specified registry for all npm client operations.",
            type: "string",
            requiresArg: true
          },
          "require-scripts": {
            describe: "Execute ./scripts/prepublish.js and ./scripts/postpublish.js, relative to package root.",
            type: "boolean"
          },
          "no-git-reset": {
            describe: "Do not reset changes to working tree after publishing is complete.",
            type: "boolean"
          },
          "git-reset": {
            hidden: true,
            type: "boolean"
          },
          "temp-tag": {
            describe: "Create a temporary tag while publishing.",
            type: "boolean"
          },
          "no-verify-access": {
            describe: "Do not verify package read-write access for current npm user.",
            type: "boolean"
          },
          "verify-access": {
            describe: "Verify package read-write access for current npm user.",
            type: "boolean"
          },
          "summary-file": {
            describe: "Generate a json summary report after all packages have been successfully published, you can pass an optional path for where to save the file.",
            type: "string"
          },
          "include-private": {
            describe: "Include specified private packages when publishing by temporarily removing the private property from the package manifest. This should only be used for testing private packages that will become public. Private packages should not usually be published. See the npm docs for details (https://docs.npmjs.com/cli/v9/configuring-npm/package-json#private).",
            type: "array"
          }
        };
        composeVersionOptions(yargs2);
        yargs2.options(opts);
        const { hiddenOptions } = yargs2.getOptions();
        const sharedKeys = ["preid", "y", "ignore-scripts"];
        for (const sharedKey of sharedKeys) {
          hiddenOptions.splice(
            hiddenOptions.findIndex((k) => k === sharedKey),
            1
          );
        }
        yargs2.group(Object.keys(opts).concat(sharedKeys), "Command Options:");
        return yargs2.option("npm-tag", {
          hidden: true,
          conflicts: "dist-tag",
          type: "string",
          requiresArg: true
        }).option("verify-registry", {
          hidden: true,
          type: "boolean"
        }).option("skip-npm", {
          hidden: true,
          type: "boolean"
        }).check((argv) => {
          if (argv["npmTag"]) {
            argv["distTag"] = argv["npmTag"];
            argv["dist-tag"] = argv["npmTag"];
            delete argv["npmTag"];
            delete argv["npm-tag"];
            import_npmlog38.default.warn("deprecated", "--npm-tag has been renamed --dist-tag");
          }
          return argv;
        }).middleware((args) => {
          const { includePrivate } = args;
          if (includePrivate && Array.isArray(includePrivate)) {
            args["includePrivate"] = includePrivate.reduce((acc, pkg) => [...acc, ...pkg.split(/[\s,]/)], []);
          }
        }, true);
      },
      handler(argv) {
        return require_src13()(argv);
      }
    };
    module2.exports = command;
  }
});

// libs/commands/run/src/index.ts
var require_src14 = __commonJS({
  "libs/commands/run/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_fs_extra11 = require("fs-extra");
    var import_p_map5 = __toESM(require("p-map"));
    var import_path23 = __toESM(require("path"));
    var import_perf_hooks = require("perf_hooks");
    module2.exports = function factory(argv) {
      return new RunCommand(argv);
    };
    var RunCommand = class extends Command {
      script;
      args;
      npmClient;
      bail;
      prefix;
      get requiresGit() {
        return false;
      }
      initialize() {
        const { script, npmClient = "npm" } = this.options;
        this.script = script;
        this.args = this.options["--"] || [];
        this.npmClient = npmClient;
        if (!this.script) {
          throw new ValidationError("ENOSCRIPT", "You must specify a lifecycle script to run");
        }
        if (this.argv.npmClient && this.options.useNx !== false) {
          throw new ValidationError(
            "run",
            "The legacy task runner option `--npm-client` is not currently supported. Please open an issue on https://github.com/lerna/lerna if you require this feature."
          );
        }
        if (Array.isArray(this.script) && this.options.useNx === false) {
          throw new ValidationError(
            "run",
            "The legacy task runner does not support running multiple scripts concurrently. Please update to the latest version of lerna and ensure you do not have useNx set to false in your lerna.json."
          );
        }
        this.bail = this.options.bail !== false;
        this.prefix = this.options.prefix !== false;
        let chain = Promise.resolve();
        chain = chain.then(() => getFilteredPackages(this.packageGraph, this.execOpts, this.options));
        chain = chain.then((filteredPackages) => {
          this.packagesWithScript = script === "env" ? filteredPackages : filteredPackages.filter((pkg) => {
            if (Array.isArray(this.script)) {
              return this.script.some((scriptName) => pkg.scripts && pkg.scripts[scriptName]);
            }
            return pkg.scripts && pkg.scripts[script];
          });
        });
        return chain.then(() => {
          this.count = this.packagesWithScript.length;
          this.packagePlural = this.count === 1 ? "package" : "packages";
          this.joinedCommand = [this.npmClient, "run", this.script].concat(this.args).join(" ");
          if (!this.count) {
            this.logger.success("run", `No packages found with the lifecycle script '${script}'`);
            return false;
          }
        });
      }
      execute() {
        if (this.options.useNx === false) {
          this.logger.info(
            "",
            "Executing command in %d %s: %j",
            this.count,
            this.packagePlural,
            this.joinedCommand
          );
        }
        let chain = Promise.resolve();
        const getElapsed = timer();
        if (this.options.useNx !== false) {
          chain = chain.then(() => this.runScriptsUsingNx());
        } else if (this.options.parallel) {
          chain = chain.then(() => this.runScriptInPackagesParallel());
        } else if (this.toposort) {
          chain = chain.then(() => this.runScriptInPackagesTopological());
        } else {
          chain = chain.then(() => this.runScriptInPackagesLexical());
        }
        if (this.bail) {
          chain = chain.catch((err) => {
            process.exitCode = err.exitCode;
            throw err;
          });
        } else {
          chain = chain.then((results) => {
            if (results.some((result) => result.failed)) {
              const codes = results.filter((result) => result.failed).map((result) => result.exitCode);
              const exitCode = Math.max(...codes, 1);
              this.logger.error("", "Received non-zero exit code %d during execution", exitCode);
              process.exitCode = exitCode;
            }
          });
        }
        return chain.then(() => {
          this.logger.success(
            "run",
            "Ran npm script '%s' in %d %s in %ss:",
            this.script,
            this.count,
            this.packagePlural,
            (getElapsed() / 1e3).toFixed(1)
          );
          this.logger.success("", this.packagesWithScript.map((pkg) => `- ${pkg.name}`).join("\n"));
        });
      }
      getOpts(pkg) {
        return {
          args: this.args,
          npmClient: this.npmClient,
          prefix: this.prefix,
          reject: this.bail,
          pkg
        };
      }
      getRunner() {
        return this.options.stream ? (pkg) => this.runScriptInPackageStreaming(pkg) : (pkg) => this.runScriptInPackageCapturing(pkg);
      }
      runScriptInPackagesTopological() {
        let profiler;
        let runner;
        if (this.options.profile) {
          profiler = new Profiler({
            concurrency: this.concurrency,
            log: this.logger,
            outputDirectory: this.options.profileLocation
          });
          const callback = this.getRunner();
          runner = (pkg) => profiler.run(() => callback(pkg), pkg.name);
        } else {
          runner = this.getRunner();
        }
        let chain = runTopologically(this.packagesWithScript, runner, {
          concurrency: this.concurrency,
          rejectCycles: this.options.rejectCycles
        });
        if (profiler) {
          chain = chain.then((results) => profiler.output().then(() => results));
        }
        return chain;
      }
      addQuotesAroundScriptNameIfItHasAColon(scriptName) {
        if (scriptName.includes(":")) {
          return `"${scriptName}"`;
        } else {
          return scriptName;
        }
      }
      async runScriptsUsingNx() {
        if (this.options.ci) {
          process.env.CI = "true";
        }
        if (this.options.profile) {
          const absolutePath = generateProfileOutputPath(this.options.profileLocation);
          process.env.NX_PROFILE = import_path23.default.relative(this.project.rootPath, absolutePath);
        }
        import_perf_hooks.performance.mark("init-local");
        this.configureNxOutput();
        const { targetDependencies, options, extraOptions } = await this.prepNxOptions();
        if (this.packagesWithScript.length === 1) {
          const { runOne } = require("nx/src/command-line/run-one");
          const fullQualifiedTarget = this.packagesWithScript.map((p) => p.name)[0] + ":" + this.addQuotesAroundScriptNameIfItHasAColon(this.script);
          return runOne(
            process.cwd(),
            {
              "project:target:configuration": fullQualifiedTarget,
              ...options
            },
            targetDependencies,
            extraOptions
          );
        } else {
          const { runMany } = require("nx/src/command-line/run-many");
          const projects = this.packagesWithScript.map((p) => p.name).join(",");
          return runMany(
            {
              projects,
              targets: Array.isArray(this.script) ? this.script : [this.script],
              ...options
            },
            targetDependencies,
            extraOptions
          );
        }
      }
      async prepNxOptions() {
        const nxJsonExists = (0, import_fs_extra11.existsSync)(import_path23.default.join(this.project.rootPath, "nx.json"));
        const { readNxJson } = require("nx/src/config/configuration");
        const nxJson = readNxJson();
        const targetDependenciesAreDefined = Object.keys(nxJson.targetDependencies || nxJson.targetDefaults || {}).length > 0;
        const hasProjectSpecificNxConfiguration = this.packagesWithScript.some((p) => !!p.get("nx"));
        const hasCustomizedNxConfiguration = nxJsonExists && targetDependenciesAreDefined || hasProjectSpecificNxConfiguration;
        const mimicLernaDefaultBehavior = !hasCustomizedNxConfiguration;
        const targetDependencies = this.toposort && !this.options.parallel && mimicLernaDefaultBehavior ? {
          [this.script]: [
            {
              projects: "dependencies",
              target: this.script
            }
          ]
        } : {};
        if (this.options.prefix === false && !this.options.stream) {
          this.logger.warn(this.name, `"no-prefix" is ignored when not using streaming output.`);
        }
        const outputStyle = this.options.stream ? this.prefix ? "stream" : "stream-without-prefixes" : "dynamic";
        const options = {
          outputStyle,
          parallel: this.options.parallel && mimicLernaDefaultBehavior ? 999 : this.concurrency,
          nxBail: this.bail,
          nxIgnoreCycles: !this.options.rejectCycles,
          skipNxCache: this.options.skipNxCache,
          verbose: this.options.verbose,
          __overrides__: this.args.map((t) => t.toString())
        };
        if (hasCustomizedNxConfiguration) {
          this.logger.verbose(
            this.name,
            "Nx target configuration was found. Task dependencies will be automatically included."
          );
          if (this.options.parallel || this.options.sort !== void 0) {
            this.logger.warn(
              this.name,
              `"parallel", "sort", and "no-sort" are ignored when Nx targets are configured. See https://lerna.js.org/docs/lerna6-obsolete-options for details.`
            );
          }
          if (this.options.includeDependencies) {
            this.logger.info(
              this.name,
              `Using the "include-dependencies" option when Nx targets are configured will include both task dependencies detected by Nx and project dependencies detected by Lerna. See https://lerna.js.org/docs/lerna6-obsolete-options#--include-dependencies for details.`
            );
          }
          if (this.options.ignore) {
            this.logger.info(
              this.name,
              `Using the "ignore" option when Nx targets are configured will exclude only tasks that are not determined to be required by Nx. See https://lerna.js.org/docs/lerna6-obsolete-options#--ignore for details.`
            );
          }
        } else {
          this.logger.verbose(
            this.name,
            "Nx target configuration was not found. Task dependencies will not be automatically included."
          );
        }
        const extraOptions = {
          excludeTaskDependencies: mimicLernaDefaultBehavior,
          loadDotEnvFiles: this.options.loadEnvFiles ?? true
        };
        return { targetDependencies, options, extraOptions };
      }
      runScriptInPackagesParallel() {
        return (0, import_p_map5.default)(this.packagesWithScript, (pkg) => this.runScriptInPackageStreaming(pkg));
      }
      runScriptInPackagesLexical() {
        return (0, import_p_map5.default)(this.packagesWithScript, this.getRunner(), { concurrency: this.concurrency });
      }
      runScriptInPackageStreaming(pkg) {
        return npmRunScriptStreaming(this.script, this.getOpts(pkg));
      }
      runScriptInPackageCapturing(pkg) {
        const getElapsed = timer();
        return npmRunScript(this.script, this.getOpts(pkg)).then((result) => {
          this.logger.info(
            "run",
            "Ran npm script '%s' in '%s' in %ss:",
            this.script,
            pkg.name,
            (getElapsed() / 1e3).toFixed(1)
          );
          output(result.stdout);
          return result;
        });
      }
      configureNxOutput() {
        try {
          const nxOutput = require("nx/src/utils/output");
          nxOutput.output.cliName = "Lerna (powered by Nx)";
          nxOutput.output.formatCommand = (taskId) => taskId;
          return nxOutput;
        } catch (err) {
          this.logger.error(
            "\n",
            "There was a critical error when configuring the task runner, please report this on https://github.com/lerna/lerna"
          );
          throw err;
        }
      }
    };
    module2.exports.RunCommand = RunCommand;
  }
});

// libs/commands/run/src/command.ts
var require_command14 = __commonJS({
  "libs/commands/run/src/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "run <script>",
      describe: "Run an npm script in each package that contains that script",
      builder(yargs2) {
        yargs2.example("$0 run build -- --silent", "# `npm run build --silent` in all packages with a build script").parserConfiguration({
          "populate--": true
        }).positional("script", {
          describe: "The npm script to run. Pass flags to send to the npm client after --",
          type: "string",
          coerce: (script) => {
            if (script.includes(",")) {
              return script.split(",").filter(Boolean).map((s) => s.trim());
            }
            return script;
          }
        }).options({
          "npm-client": {
            group: "Command Options:",
            describe: "Executable used to run scripts (npm, yarn, pnpm, ...).",
            defaultDescription: "npm",
            type: "string",
            requiresArg: true
          },
          stream: {
            group: "Command Options:",
            describe: "Stream output with lines prefixed by package.",
            type: "boolean"
          },
          parallel: {
            group: "Command Options:",
            describe: "Run script with unlimited concurrency, streaming prefixed output.",
            type: "boolean"
          },
          "no-bail": {
            group: "Command Options:",
            describe: "Continue running script despite non-zero exit in a given package.",
            type: "boolean"
          },
          bail: {
            hidden: true,
            type: "boolean"
          },
          "no-prefix": {
            group: "Command Options:",
            describe: "Do not prefix streaming output.",
            type: "boolean"
          },
          prefix: {
            hidden: true,
            type: "boolean"
          },
          profile: {
            group: "Command Options:",
            describe: "Profile script executions and output performance profile to default location.",
            type: "boolean"
          },
          "profile-location": {
            group: "Command Options:",
            describe: "Output performance profile to custom location instead of default project root.",
            type: "string"
          },
          "skip-nx-cache": {
            hidden: true,
            type: "boolean"
          },
          verbose: {
            group: "Command Options:",
            describe: "When useNx is not false, show verbose output from dependent tasks.",
            type: "boolean"
          },
          "load-env-files": {
            group: "Command Options:",
            describe: "When useNx is not false, automatically load .env files",
            type: "boolean"
          }
        });
        return filterOptions(yargs2);
      },
      handler(argv) {
        return require_src14()(argv);
      }
    };
    module2.exports = command;
  }
});

// packages/lerna/src/commands/add-caching/index.ts
var require_add_caching = __commonJS({
  "packages/lerna/src/commands/add-caching/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_devkit2 = require("@nrwl/devkit");
    var import_inquirer2 = __toESM(require("inquirer"));
    var import_npmlog38 = __toESM(require("npmlog"));
    module2.exports = function factory(argv) {
      return new AddCachingCommand(argv);
    };
    var AddCachingCommand = class extends Command {
      uniqueScriptNames = [];
      constructor(argv) {
        super(argv, { skipValidations: true });
      }
      initialize() {
        if (this.options.useNx === false) {
          this.logger.error(
            "add-caching",
            "The `add-caching` command is only available when using the Nx task runner (do not set `useNx` to `false` in `lerna.json`)"
          );
          process.exit(1);
        }
        const packages = this.packageGraph?.rawPackageList || [];
        const uniqueScriptNames = /* @__PURE__ */ new Set();
        for (const pkg of packages) {
          for (const scriptName of Object.keys(pkg.scripts || {})) {
            uniqueScriptNames.add(scriptName);
          }
        }
        this.uniqueScriptNames = Array.from(uniqueScriptNames);
      }
      async execute() {
        this.logger.info(
          "add-caching",
          "Please answer the following questions about the scripts found in your workspace in order to generate task runner configuration"
        );
        process.stdout.write("\n");
        import_npmlog38.default.pause();
        const { targetDefaults } = await import_inquirer2.default.prompt([
          {
            type: "checkbox",
            name: "targetDefaults",
            message: "Which scripts need to be run in order? (e.g. before building a project, dependent projects must be built.)\n",
            choices: this.uniqueScriptNames
          }
        ]);
        const { cacheableOperations } = await import_inquirer2.default.prompt([
          {
            type: "checkbox",
            name: "cacheableOperations",
            message: "Which scripts are cacheable? (Produce the same output given the same input, e.g. build, test and lint usually are, serve and start are not.)\n",
            choices: this.uniqueScriptNames
          }
        ]);
        const scriptOutputs = {};
        for (const scriptName of cacheableOperations) {
          scriptOutputs[scriptName] = await import_inquirer2.default.prompt([
            {
              type: "input",
              name: scriptName,
              message: `Does the "${scriptName}" script create any outputs? If not, leave blank, otherwise provide a path relative to a project root (e.g. dist, lib, build, coverage)
`
            }
          ]);
        }
        import_npmlog38.default.resume();
        process.stdout.write("\n");
        this.convertAnswersToNxConfig({ cacheableOperations, targetDefaults, scriptOutputs });
        this.logger["success"]("add-caching", "Successfully updated task runner configuration in `nx.json`");
        this.logger.info(
          "add-caching",
          "Learn more about task runner configuration here: https://lerna.js.org/docs/concepts/task-pipeline-configuration"
        );
        this.logger.info(
          "add-caching",
          "Note that the legacy task runner options of --sort, --no-sort and --parallel no longer apply. Learn more here: https://lerna.js.org/docs/lerna6-obsolete-options"
        );
      }
      convertAnswersToNxConfig(answers) {
        const nxJsonPath = (0, import_devkit2.joinPathFragments)(import_devkit2.workspaceRoot, "nx.json");
        let nxJson = {};
        try {
          nxJson = (0, import_devkit2.readJsonFile)(nxJsonPath);
        } catch {
        }
        nxJson.tasksRunnerOptions = nxJson.tasksRunnerOptions || {};
        nxJson.tasksRunnerOptions["default"] = nxJson.tasksRunnerOptions["default"] || {};
        nxJson.tasksRunnerOptions["default"].runner = nxJson.tasksRunnerOptions["default"].runner || "nx/tasks-runners/default";
        nxJson.tasksRunnerOptions["default"].options = nxJson.tasksRunnerOptions["default"].options || {};
        if (nxJson.tasksRunnerOptions["default"].options.cacheableOperations) {
          this.logger.warn(
            "add-caching",
            "The `tasksRunnerOptions.default.cacheableOperations` property already exists in `nx.json` and will be overwritten by your answers"
          );
        }
        nxJson.tasksRunnerOptions["default"].options.cacheableOperations = answers.cacheableOperations;
        if (nxJson.targetDefaults) {
          this.logger.warn(
            "add-caching",
            "The `targetDefaults` property already exists in `nx.json` and will be overwritten by your answers"
          );
        }
        nxJson.targetDefaults = nxJson.targetDefaults || {};
        for (const scriptName of answers.targetDefaults) {
          nxJson.targetDefaults[scriptName] = nxJson.targetDefaults[scriptName] || {};
          nxJson.targetDefaults[scriptName] = { dependsOn: [`^${scriptName}`] };
        }
        for (const [scriptName, scriptAnswerData] of Object.entries(answers.scriptOutputs)) {
          if (!scriptAnswerData[scriptName]) {
            continue;
          }
          nxJson.targetDefaults[scriptName] = nxJson.targetDefaults[scriptName] || {};
          nxJson.targetDefaults[scriptName].outputs = [`{projectRoot}/${scriptAnswerData[scriptName]}`];
        }
        (0, import_devkit2.writeJsonFile)(nxJsonPath, nxJson);
      }
    };
    module2.exports.AddCachingCommand = AddCachingCommand;
  }
});

// packages/lerna/src/commands/add-caching/command.ts
var require_command15 = __commonJS({
  "packages/lerna/src/commands/add-caching/command.ts"(exports, module2) {
    "use strict";
    var command = {
      command: "add-caching",
      describe: "Interactive prompt to generate task runner configuration",
      builder(yargs2) {
        return yargs2;
      },
      handler(argv) {
        return require_add_caching()(argv);
      }
    };
    module2.exports = command;
  }
});

// packages/lerna/migrations.json
var require_migrations = __commonJS({
  "packages/lerna/migrations.json"(exports, module2) {
    module2.exports = {
      generators: {
        "remove-unnecessary-use-nx": {
          cli: "nx",
          version: "6.0.0-alpha.0",
          description: "Remove unnecessary `useNx: true` from lerna.json as it is the default",
          implementation: "./dist/migrations/remove-unnecessary-use-nx/remove-unnecessary-use-nx"
        }
      }
    };
  }
});

// packages/lerna/src/commands/repair/index.ts
var require_repair = __commonJS({
  "packages/lerna/src/commands/repair/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_npmlog38 = __toESM(require("npmlog"));
    var import_repair = require("nx/src/command-line/repair");
    var migrationsJson = require_migrations();
    module2.exports = function factory(argv) {
      return new RepairCommand(argv);
    };
    var RepairCommand = class extends Command {
      constructor(argv) {
        super(argv, { skipValidations: true });
      }
      initialize() {
      }
      async execute() {
        this.configureNxOutput();
        const verbose = this.options?.verbose ? true : import_npmlog38.default.level === "verbose";
        const lernaMigrations = Object.entries(migrationsJson.generators).map(
          ([name, migration]) => {
            return {
              package: "lerna",
              cli: "nx",
              name,
              description: migration.description,
              version: migration.version
            };
          }
        );
        await (0, import_repair.repair)({ verbose }, lernaMigrations);
      }
      configureNxOutput() {
        try {
          const nxOutput = require("nx/src/utils/output");
          nxOutput.output.cliName = "Lerna";
          nxOutput.output.formatCommand = (taskId) => taskId;
          return nxOutput;
        } catch (err) {
          this.logger.error("There was a critical issue when trying to execute the repair command.");
          throw err;
        }
      }
    };
    module2.exports.RepairCommand = RepairCommand;
  }
});

// packages/lerna/src/commands/repair/command.ts
var require_command16 = __commonJS({
  "packages/lerna/src/commands/repair/command.ts"(exports, module2) {
    "use strict";
    var command = {
      command: "repair",
      describe: "Runs automated migrations to repair the state of a lerna repo",
      builder(yargs2) {
        yargs2.options({
          verbose: {
            hidden: true,
            type: "boolean"
          }
        });
        return yargs2;
      },
      handler(argv) {
        return require_repair()(argv);
      }
    };
    module2.exports = command;
  }
});

// packages/lerna/src/commands/watch/index.ts
var require_watch = __commonJS({
  "packages/lerna/src/commands/watch/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var import_watch = require("nx/src/command-line/watch");
    var import_configuration = require("nx/src/config/configuration");
    module2.exports = function factory(argv) {
      return new WatchCommand(argv);
    };
    var WatchCommand = class extends Command {
      filteredPackages = [];
      count = 0;
      packagePlural = "packages";
      get requiresGit() {
        return false;
      }
      async initialize() {
        if (!this.options.command) {
          throw new ValidationError("ENOCOMMAND", "A command to execute is required");
        }
        this.filteredPackages = await getFilteredPackages(this.packageGraph, this.execOpts, this.options);
        this.count = this.filteredPackages.length;
        this.packagePlural = this.count === 1 ? "package" : "packages";
      }
      async execute() {
        this.logger.info(
          "watch",
          "Executing command %j on changes in %d %s.",
          this.options.command,
          this.count,
          this.packagePlural
        );
        const projectNames = getNxProjectNamesFromLernaPackageNames(this.filteredPackages.map((p) => p.name));
        await (0, import_watch.watch)({
          command: this.options.command,
          projectNameEnvName: "LERNA_PACKAGE_NAME",
          fileChangesEnvName: "LERNA_FILE_CHANGES",
          includeDependentProjects: false,
          projects: projectNames,
          verbose: this.options.verbose
        });
      }
    };
    var getNxProjectNamesFromLernaPackageNames = (packageNames) => {
      const nxJson = (0, import_configuration.readNxJson)();
      const nxConfiguredNpmScope = nxJson.npmScope;
      return nxConfiguredNpmScope ? packageNames.map((name) => name.replace(`@${nxConfiguredNpmScope}/`, "")) : packageNames;
    };
    module2.exports.WatchCommand = WatchCommand;
  }
});

// packages/lerna/src/commands/watch/command.ts
var require_command17 = __commonJS({
  "packages/lerna/src/commands/watch/command.ts"(exports, module2) {
    "use strict";
    init_src();
    var command = {
      command: "watch",
      describe: "Runs a command whenever packages or their dependents change.",
      builder(yargs2) {
        yargs2.parserConfiguration({
          "populate--": true,
          "strip-dashed": true
        }).option("command", { type: "string", hidden: true }).option("verbose", {
          type: "boolean",
          description: "Run watch mode in verbose mode, where commands are logged before execution."
        }).middleware((args) => {
          const { "--": doubleDash } = args;
          if (doubleDash && Array.isArray(doubleDash)) {
            args.command = doubleDash.join(" ");
          }
        }, true);
        return filterOptions(yargs2);
      },
      handler(argv) {
        return require_watch()(argv);
      }
    };
    module2.exports = command;
  }
});

// packages/lerna/src/index.ts
var require_src15 = __commonJS({
  "packages/lerna/src/index.ts"(exports, module2) {
    "use strict";
    init_src();
    var addCmd = __toESM(require_command());
    var bootstrapCmd = __toESM(require_command2());
    var changedCmd = __toESM(require_command3());
    var cleanCmd = __toESM(require_command4());
    var diffCmd = __toESM(require_command5());
    var execCmd = __toESM(require_command6());
    var importCmd = __toESM(require_command7());
    var infoCmd = __toESM(require_command8());
    var initCmd = __toESM(require_command9());
    var linkCmd = __toESM(require_command10());
    var listCmd = __toESM(require_command11());
    var publishCmd = __toESM(require_command13());
    var runCmd = __toESM(require_command14());
    var versionCmd = __toESM(require_command12());
    var addCachingCmd = __toESM(require_command15());
    var repairCmd = __toESM(require_command16());
    var watchCmd = __toESM(require_command17());
    var createCmd = require("@lerna/create/command");
    var pkg = require("../package.json");
    module2.exports = function main(argv) {
      const context = {
        lernaVersion: pkg.version
      };
      return lernaCLI().command(addCmd).command(addCachingCmd).command(bootstrapCmd).command(changedCmd).command(cleanCmd).command(createCmd).command(diffCmd).command(execCmd).command(importCmd).command(infoCmd).command(initCmd).command(linkCmd).command(listCmd).command(publishCmd).command(repairCmd).command(runCmd).command(watchCmd).command(versionCmd).parse(argv, context);
    };
  }
});

// packages/lerna/src/cli.ts
var importLocal = require("import-local");
if (importLocal(__filename)) {
  require("npmlog").info("cli", "using local version of lerna");
} else {
  require_src15()(process.argv.slice(2));
}