var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __using = (stack, value, async) => {
  if (value != null) {
    if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
    var dispose, inner;
    if (async) dispose = value[__knownSymbol("asyncDispose")];
    if (dispose === void 0) {
      dispose = value[__knownSymbol("dispose")];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") __typeError("Object not disposable");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    stack.push([async, dispose, value]);
  } else if (async) {
    stack.push([async]);
  }
  return value;
};
var __callDispose = (stack, error, hasError) => {
  var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
    return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
  };
  var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
  var next = (it) => {
    while (it = stack.pop()) {
      try {
        var result = it[1] && it[1].call(it[2]);
        if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
      } catch (e) {
        fail(e);
      }
    }
    if (hasError) throw error;
  };
  return next();
};
/**
 * @license
 * Copyright 2022-2026 Greg Lauckhart <greg@lauckhart.com>
 * SPDX-License-Identifier: Apache-2.0
 */
import { commander } from "../util/commander.js";
import { Package } from "../util/package.js";
import { reportCycles } from "./cycles.js";
import { buildDocs, mergeDocs } from "./docs.js";
import { Graph } from "./graph.js";
import { ProjectBuilder, Target } from "./project-builder.js";
import { Project } from "./project.js";
import { manageVersion } from "../versioning/cli.js";
import { relock } from "./relock.js";
import { ensureTsconfigTemplates, syncAllTsconfigs } from "./tsconfig.js";
var Mode = /* @__PURE__ */ ((Mode2) => {
  Mode2[Mode2["BuildProject"] = 0] = "BuildProject";
  Mode2[Mode2["BuildProjectWithDependencies"] = 1] = "BuildProjectWithDependencies";
  Mode2[Mode2["BuildWorkspace"] = 2] = "BuildWorkspace";
  Mode2[Mode2["DisplayGraph"] = 3] = "DisplayGraph";
  Mode2[Mode2["Configure"] = 4] = "Configure";
  Mode2[Mode2["BuildDocs"] = 5] = "BuildDocs";
  Mode2[Mode2["Relock"] = 6] = "Relock";
  Mode2[Mode2["SyncTsconfigs"] = 7] = "SyncTsconfigs";
  Mode2[Mode2["Circular"] = 8] = "Circular";
  Mode2[Mode2["Version"] = 9] = "Version";
  return Mode2;
})(Mode || {});
async function main(argv = process.argv) {
  const targets = Array();
  let mode = 0 /* BuildProject */;
  const program = commander("nacho-build", "Builds TypeScript packages and monorepos.").option("-p, --prefix <path>", "specify build directory", ".").option("-c, --clean", "clean before build", false).option("-d, --dependencies", "build dependencies", false).option("--tsc", "use tsc instead of tsgo for type checking");
  program.command("build").description("(default) build JS and type definitions").action(() => {
  });
  program.command("clean").description("remove build and dist directories").action(() => {
    targets.push(Target.clean);
  });
  program.command("types").description("build type definitions").action(() => {
    targets.push(Target.types);
  });
  program.command("esm").description("build JS (ES6 modules)").action(() => {
    targets.push(Target.esm);
  });
  program.command("cjs").description("build JS (CommonJS modules)").action(() => {
    targets.push(Target.cjs);
  });
  program.command("graph").description("display the workspace graph").action(() => {
    mode = 3 /* DisplayGraph */;
  });
  program.command("tsconfigs").description("sync all tsconfigs with package.json").action(() => {
    mode = 7 /* SyncTsconfigs */;
  });
  program.command("docs").description("build workspace documentation").action(() => {
    mode = 5 /* BuildDocs */;
  });
  program.command("configure").description("refresh tsconfig templates and sync all tsconfigs").action(() => {
    mode = 4 /* Configure */;
  });
  program.command("relock").description("remove package-lock.json and all node_modules directories so npm install regenerates them").action(() => {
    mode = 6 /* Relock */;
  });
  program.command("cycles").description("find circular dependencies").action(() => {
    mode = 8 /* Circular */;
  });
  let versionArgs;
  program.command("version").description("manage workspace package versions").argument("[version]").option("-s, --set", "set the release version").option("-a, --apply", "set package versions to the release version").option("-t, --tag", "add git tag for release version").action((version, opts) => {
    mode = 9 /* Version */;
    versionArgs = { ...opts, version };
  });
  program.action(() => {
  });
  const args = program.parse(argv).opts();
  const pkg = new Package({ path: args.prefix });
  if (mode === 0 /* BuildProject */) {
    mode = pkg.isWorkspace ? 2 /* BuildWorkspace */ : 1 /* BuildProjectWithDependencies */;
  }
  function builder(graph) {
    const { tsc, ...rest } = args;
    return new ProjectBuilder({ ...rest, tsgo: tsc ? false : void 0, targets: [...targets], graph });
  }
  switch (mode) {
    case 1 /* BuildProjectWithDependencies */:
      {
        const graph = await Graph.forProject(args.prefix);
        if (graph !== void 0) {
          await graph.build(builder(graph));
        } else {
          await builder().build(new Project(args.prefix));
        }
      }
      break;
    case 2 /* BuildWorkspace */:
      {
        const graph = await Graph.load();
        await ensureTsconfigTemplates(pkg);
        await syncAllTsconfigs(graph);
        await graph.build(builder(graph));
      }
      break;
    case 3 /* DisplayGraph */:
      (await Graph.load()).display();
      break;
    case 7 /* SyncTsconfigs */:
      {
        const graph = await Graph.load();
        await ensureTsconfigTemplates(pkg);
        await syncAllTsconfigs(graph);
      }
      break;
    case 4 /* Configure */:
      {
        await ensureTsconfigTemplates(pkg, true);
        if (pkg.isWorkspace) {
          const graph = await Graph.load();
          await syncAllTsconfigs(graph, true);
        }
      }
      break;
    case 6 /* Relock */:
      await relock();
      break;
    case 9 /* Version */:
      await manageVersion({
        ...versionArgs,
        prefix: versionArgs?.prefix ?? args.prefix
      });
      break;
    case 5 /* BuildDocs */: {
      var _stack = [];
      try {
        const progress = __using(_stack, pkg.start("Documenting"));
        if (pkg.isWorkspace) {
          const graph = await Graph.load();
          for (const node of graph.nodes) {
            if (node.pkg.isLibrary) {
              await progress.run(node.pkg.name, () => buildDocs(node.pkg, progress));
            }
          }
          await mergeDocs(Package.workspace);
        } else {
          await progress.run(pkg.name, () => buildDocs(pkg, progress));
        }
        break;
      } catch (_) {
        var _error = _, _hasError = true;
      } finally {
        __callDispose(_stack, _error, _hasError);
      }
    }
    case 8 /* Circular */: {
      var _stack2 = [];
      try {
        const progress = __using(_stack2, pkg.start("Analyzing dependencies"));
        if (pkg.isWorkspace) {
          const graph = await Graph.load();
          for (const node of graph.nodes) {
            if (node.pkg.isLibrary) {
              await reportCycles(node.pkg, progress);
            }
          }
        } else {
          await reportCycles(pkg, progress);
        }
        break;
      } catch (_2) {
        var _error2 = _2, _hasError2 = true;
      } finally {
        __callDispose(_stack2, _error2, _hasError2);
      }
    }
  }
}
export {
  main
};
//# sourceMappingURL=cli.js.map
