import {
  LogLevel,
  brandIcon,
  cleanDirectories,
  formatLogMessage,
  getLogLevel,
  getLogLevelLabel,
  getStopwatch,
  writeDebug,
  writeFatal,
  writeSuccess,
  writeTrace,
  writeWarning
} from "./chunk-VUHSDRKE.js";
import {
  getDefaultOptions,
  toTSDownFormat
} from "./chunk-BMIIFT6J.js";

// src/build.ts
import {
  createProjectGraphAsync as createProjectGraphAsync2,
  readProjectsConfigurationFromProjectGraph as readProjectsConfigurationFromProjectGraph2,
  writeJsonFile
} from "@nx/devkit";

// ../build-tools/src/config.ts
var DEFAULT_ENVIRONMENT = "production";
var DEFAULT_TARGET = "esnext";
var DEFAULT_ORGANIZATION = "storm-software";

// ../build-tools/src/plugins/swc.ts
import { transform } from "@swc/core";

// ../build-tools/src/plugins/ts-resolve.ts
import fs from "node:fs";
import { builtinModules } from "node:module";
import path from "node:path";
import _resolve from "resolve";

// ../build-tools/src/plugins/type-definitions.ts
import { stripIndents } from "@nx/devkit";
import { relative } from "path";

// ../build-tools/src/utilities/copy-assets.ts
import { CopyAssetsHandler } from "@nx/js/src/utils/assets/copy-assets-handler";

// ../config-tools/src/utilities/correct-paths.ts
var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
  if (!input) {
    return input;
  }
  return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
var _UNC_REGEX = /^[/\\]{2}/;
var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
var _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
var correctPaths = function(path2) {
  if (!path2 || path2.length === 0) {
    return ".";
  }
  path2 = normalizeWindowsPath(path2);
  const isUNCPath = path2?.match(_UNC_REGEX);
  const isPathAbsolute = isAbsolute(path2);
  const trailingSeparator = path2[path2.length - 1] === "/";
  path2 = normalizeString(path2, !isPathAbsolute);
  if (path2.length === 0) {
    if (isPathAbsolute) {
      return "/";
    }
    return trailingSeparator ? "./" : ".";
  }
  if (trailingSeparator) {
    path2 += "/";
  }
  if (_DRIVE_LETTER_RE.test(path2)) {
    path2 += "/";
  }
  if (isUNCPath) {
    if (!isPathAbsolute) {
      return `//./${path2}`;
    }
    return `//${path2}`;
  }
  return isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2;
};
var joinPaths = function(...segments) {
  let path2 = "";
  for (const seg of segments) {
    if (!seg) {
      continue;
    }
    if (path2.length > 0) {
      const pathTrailing = path2[path2.length - 1] === "/";
      const segLeading = seg[0] === "/";
      const both = pathTrailing && segLeading;
      if (both) {
        path2 += seg.slice(1);
      } else {
        path2 += pathTrailing || segLeading ? seg : `/${seg}`;
      }
    } else {
      path2 += seg;
    }
  }
  return correctPaths(path2);
};
function normalizeString(path2, allowAboveRoot) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let char = null;
  for (let index = 0; index <= path2.length; ++index) {
    if (index < path2.length) {
      char = path2[index];
    } else if (char === "/") {
      break;
    } else {
      char = "/";
    }
    if (char === "/") {
      if (lastSlash === index - 1 || dots === 1) {
      } else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf("/");
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
            }
            lastSlash = index;
            dots = 0;
            continue;
          } else if (res.length > 0) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = index;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? "/.." : "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) {
          res += `/${path2.slice(lastSlash + 1, index)}`;
        } else {
          res = path2.slice(lastSlash + 1, index);
        }
        lastSegmentLength = index - lastSlash - 1;
      }
      lastSlash = index;
      dots = 0;
    } else if (char === "." && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
var isAbsolute = function(p) {
  return _IS_ABSOLUTE_RE.test(p);
};

// ../build-tools/src/utilities/copy-assets.ts
import { glob } from "glob";
import { readFile, writeFile } from "node:fs/promises";
var copyAssets = async (config, assets, outputPath, projectRoot, sourceRoot, generatePackageJson2 = true, includeSrc = false, banner, footer) => {
  const pendingAssets = Array.from(assets ?? []);
  pendingAssets.push({
    input: projectRoot,
    glob: "*.md",
    output: "."
  });
  pendingAssets.push({
    input: ".",
    glob: "LICENSE",
    output: "."
  });
  if (generatePackageJson2 === false) {
    pendingAssets.push({
      input: projectRoot,
      glob: "package.json",
      output: "."
    });
  }
  if (includeSrc === true) {
    pendingAssets.push({
      input: sourceRoot,
      glob: "**/{*.ts,*.tsx,*.js,*.jsx}",
      output: "src/"
    });
  }
  writeTrace(
    `\u{1F4DD}  Copying the following assets to the output directory:
${pendingAssets.map((pendingAsset) => typeof pendingAsset === "string" ? ` - ${pendingAsset} -> ${outputPath}` : `  - ${pendingAsset.input}/${pendingAsset.glob} -> ${joinPaths(outputPath, pendingAsset.output)}`).join("\n")}`,
    config
  );
  const assetHandler = new CopyAssetsHandler({
    projectDir: projectRoot,
    rootDir: config.workspaceRoot,
    outputDir: outputPath,
    assets: pendingAssets
  });
  await assetHandler.processAllAssetsOnce();
  writeTrace("Completed copying assets to the output directory", config);
  if (includeSrc === true) {
    writeDebug(
      `\u{1F4DD}  Adding banner and writing source files: ${joinPaths(
        outputPath,
        "src"
      )}`,
      config
    );
    const files = await glob([
      joinPaths(config.workspaceRoot, outputPath, "src/**/*.ts"),
      joinPaths(config.workspaceRoot, outputPath, "src/**/*.tsx"),
      joinPaths(config.workspaceRoot, outputPath, "src/**/*.js"),
      joinPaths(config.workspaceRoot, outputPath, "src/**/*.jsx")
    ]);
    await Promise.allSettled(
      files.map(
        async (file) => writeFile(
          file,
          `${banner && typeof banner === "string" ? banner.startsWith("//") ? banner : `// ${banner}` : ""}

${await readFile(file, "utf8")}

${footer && typeof footer === "string" ? footer.startsWith("//") ? footer : `// ${footer}` : ""}`
        )
      )
    );
  }
};

// ../build-tools/src/utilities/generate-package-json.ts
import { calculateProjectBuildableDependencies } from "@nx/js/src/utils/buildable-libs-utils";

// ../config-tools/src/utilities/find-up.ts
import { existsSync } from "node:fs";
import { join } from "node:path";
var MAX_PATH_SEARCH_DEPTH = 30;
var depth = 0;
function findFolderUp(startPath, endFileNames = [], endDirectoryNames = []) {
  const _startPath = startPath ?? process.cwd();
  if (endDirectoryNames.some(
    (endDirName) => existsSync(join(_startPath, endDirName))
  )) {
    return _startPath;
  }
  if (endFileNames.some((endFileName) => existsSync(join(_startPath, endFileName)))) {
    return _startPath;
  }
  if (_startPath !== "/" && depth++ < MAX_PATH_SEARCH_DEPTH) {
    const parent = join(_startPath, "..");
    return findFolderUp(parent, endFileNames, endDirectoryNames);
  }
  return void 0;
}

// ../config-tools/src/utilities/find-workspace-root.ts
var rootFiles = [
  "storm-workspace.json",
  "storm-workspace.yaml",
  "storm-workspace.yml",
  "storm-workspace.js",
  "storm-workspace.ts",
  ".storm-workspace.json",
  ".storm-workspace.yaml",
  ".storm-workspace.yml",
  ".storm-workspace.js",
  ".storm-workspace.ts",
  "lerna.json",
  "nx.json",
  "turbo.json",
  "npm-workspace.json",
  "yarn-workspace.json",
  "pnpm-workspace.json",
  "npm-workspace.yaml",
  "yarn-workspace.yaml",
  "pnpm-workspace.yaml",
  "npm-workspace.yml",
  "yarn-workspace.yml",
  "pnpm-workspace.yml",
  "npm-lock.json",
  "yarn-lock.json",
  "pnpm-lock.json",
  "npm-lock.yaml",
  "yarn-lock.yaml",
  "pnpm-lock.yaml",
  "npm-lock.yml",
  "yarn-lock.yml",
  "pnpm-lock.yml",
  "bun.lockb"
];
var rootDirectories = [
  ".storm-workspace",
  ".nx",
  ".git",
  ".github",
  ".vscode",
  ".verdaccio"
];
function findWorkspaceRootSafe(pathInsideMonorepo) {
  if (process.env.STORM_WORKSPACE_ROOT || process.env.NX_WORKSPACE_ROOT_PATH) {
    return correctPaths(
      process.env.STORM_WORKSPACE_ROOT ?? process.env.NX_WORKSPACE_ROOT_PATH
    );
  }
  return correctPaths(
    findFolderUp(
      pathInsideMonorepo ?? process.cwd(),
      rootFiles,
      rootDirectories
    )
  );
}
function findWorkspaceRoot(pathInsideMonorepo) {
  const result = findWorkspaceRootSafe(pathInsideMonorepo);
  if (!result) {
    throw new Error(
      `Cannot find workspace root upwards from known path. Files search list includes: 
${rootFiles.join(
        "\n"
      )}
Path: ${pathInsideMonorepo ? pathInsideMonorepo : process.cwd()}`
    );
  }
  return result;
}

// ../build-tools/src/utilities/generate-package-json.ts
import { Glob } from "glob";
import { existsSync as existsSync2, readFileSync } from "node:fs";
import { readFile as readFile2 } from "node:fs/promises";
import {
  createProjectGraphAsync,
  readCachedProjectGraph,
  readProjectsConfigurationFromProjectGraph
} from "nx/src/project-graph/project-graph";
var addPackageDependencies = async (workspaceRoot, projectRoot, projectName, packageJson) => {
  let projectGraph;
  try {
    projectGraph = readCachedProjectGraph();
  } catch {
    await createProjectGraphAsync();
    projectGraph = readCachedProjectGraph();
  }
  if (!projectGraph) {
    throw new Error(
      "The Build process failed because the project graph is not available. Please run the build command again."
    );
  }
  const projectDependencies = calculateProjectBuildableDependencies(
    void 0,
    projectGraph,
    workspaceRoot,
    projectName,
    process.env.NX_TASK_TARGET_TARGET || "build",
    process.env.NX_TASK_TARGET_CONFIGURATION || "production",
    true
  );
  const localPackages = [];
  for (const project of projectDependencies.dependencies.filter(
    (dep) => dep.node.type === "lib" && dep.node.data?.root !== projectRoot && dep.node.data?.root !== workspaceRoot
  )) {
    const projectNode = project.node;
    if (projectNode.data.root) {
      const projectPackageJsonPath = joinPaths(
        workspaceRoot,
        projectNode.data.root,
        "package.json"
      );
      if (existsSync2(projectPackageJsonPath)) {
        const projectPackageJsonContent = await readFile2(
          projectPackageJsonPath,
          "utf8"
        );
        const projectPackageJson = JSON.parse(projectPackageJsonContent);
        if (projectPackageJson.private !== true) {
          localPackages.push(projectPackageJson);
        }
      }
    }
  }
  if (localPackages.length > 0) {
    writeTrace(
      `\u{1F4E6}  Adding local packages to package.json: ${localPackages.map((p) => p.name).join(", ")}`
    );
    const projectJsonFile = await readFile2(
      joinPaths(projectRoot, "project.json"),
      "utf8"
    );
    const projectJson = JSON.parse(projectJsonFile);
    const projectName2 = projectJson.name;
    const projectConfigurations = readProjectsConfigurationFromProjectGraph(projectGraph);
    if (!projectConfigurations?.projects?.[projectName2]) {
      throw new Error(
        "The Build process failed because the project does not have a valid configuration in the project.json file. Check if the file exists in the root of the project."
      );
    }
    const implicitDependencies = projectConfigurations.projects?.[projectName2].implicitDependencies?.reduce((ret, dep) => {
      if (projectConfigurations.projects?.[dep]) {
        const depPackageJsonPath = joinPaths(
          workspaceRoot,
          projectConfigurations.projects[dep].root,
          "package.json"
        );
        if (existsSync2(depPackageJsonPath)) {
          const depPackageJsonContent = readFileSync(
            depPackageJsonPath,
            "utf8"
          );
          const depPackageJson = JSON.parse(depPackageJsonContent);
          if (depPackageJson.private !== true && !ret.includes(depPackageJson.name)) {
            ret.push(depPackageJson.name);
          }
        }
      }
      return ret;
    }, []);
    packageJson.dependencies = localPackages.reduce((ret, localPackage) => {
      if (!ret[localPackage.name] && !implicitDependencies?.includes(localPackage.name) && packageJson.devDependencies?.[localPackage.name] === void 0) {
        ret[localPackage.name] = `^${localPackage.version || "0.0.1"}`;
      }
      return ret;
    }, packageJson.dependencies ?? {});
    packageJson.devDependencies = localPackages.reduce((ret, localPackage) => {
      if (!ret[localPackage.name] && implicitDependencies?.includes(localPackage.name) && packageJson.dependencies?.[localPackage.name] === void 0) {
        ret[localPackage.name] = `^${localPackage.version || "0.0.1"}`;
      }
      return ret;
    }, packageJson.devDependencies ?? {});
  } else {
    writeTrace("\u{1F4E6}  No local packages dependencies to add to package.json");
  }
  return packageJson;
};
var addWorkspacePackageJsonFields = async (workspaceConfig, projectRoot, sourceRoot, projectName, includeSrc = false, packageJson) => {
  const workspaceRoot = workspaceConfig.workspaceRoot ? workspaceConfig.workspaceRoot : findWorkspaceRoot();
  const workspacePackageJsonContent = await readFile2(
    joinPaths(workspaceRoot, "package.json"),
    "utf8"
  );
  const workspacePackageJson = JSON.parse(workspacePackageJsonContent);
  packageJson.type ??= "module";
  packageJson.sideEffects ??= false;
  if (includeSrc === true) {
    let distSrc = sourceRoot.replace(projectRoot, "");
    if (distSrc.startsWith("/")) {
      distSrc = distSrc.substring(1);
    }
    packageJson.source ??= `${joinPaths(distSrc, "index.ts").replaceAll("\\", "/")}`;
  }
  packageJson.files ??= ["dist/**/*"];
  if (includeSrc === true && !packageJson.files.includes("src")) {
    packageJson.files.push("src/**/*");
  }
  packageJson.publishConfig ??= {
    access: "public"
  };
  packageJson.description ??= workspacePackageJson.description;
  packageJson.homepage ??= workspacePackageJson.homepage;
  packageJson.bugs ??= workspacePackageJson.bugs;
  packageJson.license ??= workspacePackageJson.license;
  packageJson.keywords ??= workspacePackageJson.keywords;
  packageJson.funding ??= workspacePackageJson.funding;
  packageJson.author ??= workspacePackageJson.author;
  packageJson.maintainers ??= workspacePackageJson.maintainers;
  if (!packageJson.maintainers && packageJson.author) {
    packageJson.maintainers = [packageJson.author];
  }
  packageJson.contributors ??= workspacePackageJson.contributors;
  if (!packageJson.contributors && packageJson.author) {
    packageJson.contributors = [packageJson.author];
  }
  packageJson.repository ??= workspacePackageJson.repository;
  packageJson.repository.directory ??= projectRoot ? projectRoot : joinPaths("packages", projectName);
  return packageJson;
};
var addPackageJsonExport = (file, type = "module", sourceRoot) => {
  let entry = file.replaceAll("\\", "/");
  if (sourceRoot) {
    entry = entry.replace(sourceRoot, "");
  }
  return {
    import: {
      types: `./dist/${entry}.d.${type === "module" ? "ts" : "mts"}`,
      default: `./dist/${entry}.${type === "module" ? "js" : "mjs"}`
    },
    require: {
      types: `./dist/${entry}.d.${type === "commonjs" ? "ts" : "cts"}`,
      default: `./dist/${entry}.${type === "commonjs" ? "js" : "cjs"}`
    },
    default: {
      types: `./dist/${entry}.d.${type !== "fixed" ? "ts" : "mts"}`,
      default: `./dist/${entry}.${type !== "fixed" ? "js" : "mjs"}`
    }
  };
};

// ../config-tools/src/config-file/get-config-file.ts
import { loadConfig } from "c12";
import defu from "defu";

// ../config/src/constants.ts
var STORM_DEFAULT_DOCS = "https://docs.stormsoftware.com";
var STORM_DEFAULT_HOMEPAGE = "https://stormsoftware.com";
var STORM_DEFAULT_CONTACT = "https://stormsoftware.com/contact";
var STORM_DEFAULT_LICENSING = "https://stormsoftware.com/license";
var STORM_DEFAULT_LICENSE = "Apache-2.0";
var STORM_DEFAULT_SOCIAL_DISCORD = "https://discord.gg/MQ6YVzakM5";
var STORM_DEFAULT_SOCIAL_SLACK = "https://join.slack.com/t/storm-software/shared_invite/zt-2gsmk04hs-i6yhK_r6urq0dkZYAwq2pA";
var STORM_DEFAULT_RELEASE_FOOTER = `
Storm Software is an open source software development organization with the mission is to make software development more accessible. Our ideal future is one where anyone can create software without years of prior development experience serving as a barrier to entry. We hope to achieve this via LLMs, Generative AI, and intuitive, high-level data modeling/programming languages.

Join us on [Discord](${STORM_DEFAULT_SOCIAL_DISCORD}) to chat with the team, receive release notifications, ask questions, and get involved.

If this sounds interesting, and you would like to help us in creating the next generation of development tools, please reach out on our [website](${STORM_DEFAULT_CONTACT}) or join our [Slack](${STORM_DEFAULT_SOCIAL_SLACK}) channel!
`;
var STORM_DEFAULT_ERROR_CODES_FILE = "tools/errors/codes.json";
var STORM_DEFAULT_BANNER_ALT = "The workspace's banner image";

// ../config/src/schema.ts
import * as z from "zod/v4/mini";
var schemaRegistry = z.registry();
var colorSchema = z.string().check(
  z.length(7),
  z.toLowerCase(),
  z.regex(/^#([0-9a-f]{3}){1,2}$/i),
  z.trim()
);
schemaRegistry.add(colorSchema, {
  description: "A base schema for describing the format of colors"
});
var darkColorSchema = z._default(colorSchema, "#151718");
schemaRegistry.add(darkColorSchema, {
  description: "The dark background color of the workspace"
});
var lightColorSchema = z._default(colorSchema, "#cbd5e1");
schemaRegistry.add(lightColorSchema, {
  description: "The light background color of the workspace"
});
var brandColorSchema = z._default(colorSchema, "#1fb2a6");
schemaRegistry.add(brandColorSchema, {
  description: "The primary brand specific color of the workspace"
});
var alternateColorSchema = z.optional(colorSchema);
schemaRegistry.add(alternateColorSchema, {
  description: "The alternate brand specific color of the workspace"
});
var accentColorSchema = z.optional(colorSchema);
schemaRegistry.add(accentColorSchema, {
  description: "The secondary brand specific color of the workspace"
});
var linkColorSchema = z._default(colorSchema, "#3fa6ff");
schemaRegistry.add(linkColorSchema, {
  description: "The color used to display hyperlink text"
});
var helpColorSchema = z._default(colorSchema, "#818cf8");
schemaRegistry.add(helpColorSchema, {
  description: "The second brand specific color of the workspace"
});
var successColorSchema = z._default(colorSchema, "#45b27e");
schemaRegistry.add(successColorSchema, {
  description: "The success color of the workspace"
});
var infoColorSchema = z._default(colorSchema, "#38bdf8");
schemaRegistry.add(infoColorSchema, {
  description: "The informational color of the workspace"
});
var debugColorSchema = z._default(colorSchema, "#8afafc");
schemaRegistry.add(debugColorSchema, {
  description: "The debug color of the workspace"
});
var warningColorSchema = z._default(colorSchema, "#f3d371");
schemaRegistry.add(warningColorSchema, {
  description: "The warning color of the workspace"
});
var dangerColorSchema = z._default(colorSchema, "#d8314a");
schemaRegistry.add(dangerColorSchema, {
  description: "The danger color of the workspace"
});
var fatalColorSchema = z.optional(colorSchema);
schemaRegistry.add(fatalColorSchema, {
  description: "The fatal color of the workspace"
});
var performanceColorSchema = z._default(colorSchema, "#80fd74");
schemaRegistry.add(performanceColorSchema, {
  description: "The performance color of the workspace"
});
var positiveColorSchema = z._default(colorSchema, "#4ade80");
schemaRegistry.add(positiveColorSchema, {
  description: "The positive number color of the workspace"
});
var negativeColorSchema = z._default(colorSchema, "#ef4444");
schemaRegistry.add(negativeColorSchema, {
  description: "The negative number color of the workspace"
});
var gradientStopsSchema = z.optional(z.array(colorSchema));
schemaRegistry.add(gradientStopsSchema, {
  description: "The color stops for the base gradient color pattern used in the workspace"
});
var darkColorsSchema = z.object({
  foreground: lightColorSchema,
  background: darkColorSchema,
  brand: brandColorSchema,
  alternate: alternateColorSchema,
  accent: accentColorSchema,
  link: linkColorSchema,
  help: helpColorSchema,
  success: successColorSchema,
  info: infoColorSchema,
  debug: debugColorSchema,
  warning: warningColorSchema,
  danger: dangerColorSchema,
  fatal: fatalColorSchema,
  performance: performanceColorSchema,
  positive: positiveColorSchema,
  negative: negativeColorSchema,
  gradient: gradientStopsSchema
});
var lightColorsSchema = z.object({
  foreground: darkColorSchema,
  background: lightColorSchema,
  brand: brandColorSchema,
  alternate: alternateColorSchema,
  accent: accentColorSchema,
  link: linkColorSchema,
  help: helpColorSchema,
  success: successColorSchema,
  info: infoColorSchema,
  debug: debugColorSchema,
  warning: warningColorSchema,
  danger: dangerColorSchema,
  fatal: fatalColorSchema,
  performance: performanceColorSchema,
  positive: positiveColorSchema,
  negative: negativeColorSchema,
  gradient: gradientStopsSchema
});
var multiColorsSchema = z.object({
  dark: darkColorsSchema,
  light: lightColorsSchema
});
var singleColorsSchema = z.object({
  dark: darkColorSchema,
  light: lightColorSchema,
  brand: brandColorSchema,
  alternate: alternateColorSchema,
  accent: accentColorSchema,
  link: linkColorSchema,
  help: helpColorSchema,
  success: successColorSchema,
  info: infoColorSchema,
  debug: debugColorSchema,
  warning: warningColorSchema,
  danger: dangerColorSchema,
  fatal: fatalColorSchema,
  performance: performanceColorSchema,
  positive: positiveColorSchema,
  negative: negativeColorSchema,
  gradient: gradientStopsSchema
});
var registryUrlConfigSchema = z.optional(z.url());
schemaRegistry.add(registryUrlConfigSchema, {
  description: "A remote registry URL used to publish distributable packages"
});
var registrySchema = z._default(
  z.object({
    github: registryUrlConfigSchema,
    npm: registryUrlConfigSchema,
    cargo: registryUrlConfigSchema,
    cyclone: registryUrlConfigSchema,
    container: registryUrlConfigSchema
  }),
  {}
);
schemaRegistry.add(registrySchema, {
  description: "A list of remote registry URLs used by Storm Software"
});
var colorsSchema = z.union([singleColorsSchema, multiColorsSchema]);
schemaRegistry.add(colorsSchema, {
  description: "Colors used for various workspace elements"
});
var themeColorsSchema = z.record(
  z.union([z.union([z.literal("base"), z.string()]), z.string()]),
  colorsSchema
);
schemaRegistry.add(themeColorsSchema, {
  description: "Storm theme config values used for styling various package elements"
});
var extendsSchema = z.optional(
  z.union([z.string().check(z.trim()), z.array(z.string().check(z.trim()))])
);
schemaRegistry.add(extendsSchema, {
  description: "The path to a base config file to use as a configuration preset file. Documentation can be found at https://github.com/unjs/c12#extending-configuration."
});
var workspaceBotNameSchema = z.string().check(z.trim());
schemaRegistry.add(workspaceBotNameSchema, {
  description: "The workspace bot user's name (this is the bot that will be used to perform various tasks)"
});
var workspaceBotEmailSchema = z.string().check(z.trim());
schemaRegistry.add(workspaceBotEmailSchema, {
  description: "The email of the workspace bot"
});
var workspaceBotSchema = z.object({
  name: workspaceBotNameSchema,
  email: workspaceBotEmailSchema
});
schemaRegistry.add(workspaceBotSchema, {
  description: "The workspace's bot user's config used to automated various operations tasks"
});
var workspaceReleaseBannerUrlSchema = z.optional(
  z.string().check(z.trim(), z.url())
);
schemaRegistry.add(workspaceReleaseBannerUrlSchema, {
  description: "A URL to a banner image used to display the workspace's release"
});
var workspaceReleaseBannerAltSchema = z._default(
  z.string().check(z.trim()),
  STORM_DEFAULT_BANNER_ALT
);
schemaRegistry.add(workspaceReleaseBannerAltSchema, {
  description: "The alt text for the workspace's release banner image"
});
var workspaceReleaseBannerSchema = z.object({
  url: workspaceReleaseBannerUrlSchema,
  alt: workspaceReleaseBannerAltSchema
});
schemaRegistry.add(workspaceReleaseBannerSchema, {
  description: "The workspace's banner image used during the release process"
});
var workspaceReleaseHeaderSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceReleaseHeaderSchema, {
  description: "A header message appended to the start of the workspace's release notes"
});
var workspaceReleaseFooterSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceReleaseFooterSchema, {
  description: "A footer message appended to the end of the workspace's release notes"
});
var workspaceReleaseSchema = z.object({
  banner: z.union([
    workspaceReleaseBannerSchema,
    z.string().check(z.trim(), z.url())
  ]),
  header: workspaceReleaseHeaderSchema,
  footer: workspaceReleaseFooterSchema
});
schemaRegistry.add(workspaceReleaseSchema, {
  description: "The workspace's release config used during the release process"
});
var workspaceSocialsTwitterSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceSocialsTwitterSchema, {
  description: "A Twitter/X account associated with the organization/project"
});
var workspaceSocialsDiscordSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceSocialsDiscordSchema, {
  description: "A Discord account associated with the organization/project"
});
var workspaceSocialsTelegramSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceSocialsTelegramSchema, {
  description: "A Telegram account associated with the organization/project"
});
var workspaceSocialsSlackSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceSocialsSlackSchema, {
  description: "A Slack account associated with the organization/project"
});
var workspaceSocialsMediumSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceSocialsMediumSchema, {
  description: "A Medium account associated with the organization/project"
});
var workspaceSocialsGithubSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceSocialsGithubSchema, {
  description: "A GitHub account associated with the organization/project"
});
var workspaceSocialsSchema = z.object({
  twitter: workspaceSocialsTwitterSchema,
  discord: workspaceSocialsDiscordSchema,
  telegram: workspaceSocialsTelegramSchema,
  slack: workspaceSocialsSlackSchema,
  medium: workspaceSocialsMediumSchema,
  github: workspaceSocialsGithubSchema
});
schemaRegistry.add(workspaceSocialsSchema, {
  description: "The workspace's account config used to store various social media links"
});
var workspaceDirectoryCacheSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceDirectoryCacheSchema, {
  description: "The directory used to store the environment's cached file data"
});
var workspaceDirectoryDataSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceDirectoryDataSchema, {
  description: "The directory used to store the environment's data files"
});
var workspaceDirectoryConfigSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceDirectoryConfigSchema, {
  description: "The directory used to store the environment's configuration files"
});
var workspaceDirectoryTempSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceDirectoryTempSchema, {
  description: "The directory used to store the environment's temp files"
});
var workspaceDirectoryLogSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(workspaceDirectoryLogSchema, {
  description: "The directory used to store the environment's log files"
});
var workspaceDirectoryBuildSchema = z._default(
  z.string().check(z.trim()),
  "dist"
);
schemaRegistry.add(workspaceDirectoryBuildSchema, {
  description: "The directory used to store the workspace's distributable files after a build (relative to the workspace root)"
});
var workspaceDirectorySchema = z.object({
  cache: workspaceDirectoryCacheSchema,
  data: workspaceDirectoryDataSchema,
  config: workspaceDirectoryConfigSchema,
  temp: workspaceDirectoryTempSchema,
  log: workspaceDirectoryLogSchema,
  build: workspaceDirectoryBuildSchema
});
schemaRegistry.add(workspaceDirectorySchema, {
  description: "Various directories used by the workspace to store data, cache, and configuration files"
});
var variantSchema = z._default(
  z.enum(["minimal", "monorepo"]),
  "monorepo"
);
schemaRegistry.add(variantSchema, {
  description: "The variant of the workspace. This can be used to enable or disable certain features or configurations."
});
var errorCodesFileSchema = z._default(
  z.string().check(z.trim()),
  STORM_DEFAULT_ERROR_CODES_FILE
);
schemaRegistry.add(errorCodesFileSchema, {
  description: "The path to the workspace's error codes JSON file"
});
var errorUrlSchema = z.optional(z.url());
schemaRegistry.add(errorUrlSchema, {
  description: "A URL to a page that looks up the workspace's error messages given a specific error code"
});
var errorSchema = z.object({
  codesFile: errorCodesFileSchema,
  url: errorUrlSchema
});
schemaRegistry.add(errorSchema, {
  description: "The workspace's error config used when creating error details during a system error"
});
var organizationNameSchema = z.optional(
  z.string().check(z.trim(), z.toLowerCase())
);
schemaRegistry.add(organizationNameSchema, {
  description: "The name of the organization"
});
var organizationDescriptionSchema = z.optional(
  z.string().check(z.trim())
);
schemaRegistry.add(organizationDescriptionSchema, {
  description: "A description of the organization"
});
var organizationLogoSchema = z.optional(z.url());
schemaRegistry.add(organizationLogoSchema, {
  description: "A URL to the organization's logo image"
});
var organizationIconSchema = z.optional(z.url());
schemaRegistry.add(organizationIconSchema, {
  description: "A URL to the organization's icon image"
});
var organizationUrlSchema = z.optional(z.url());
schemaRegistry.add(organizationUrlSchema, {
  description: "A URL to a page that provides more information about the organization"
});
var organizationSchema = z.object({
  name: organizationNameSchema,
  description: organizationDescriptionSchema,
  logo: organizationLogoSchema,
  icon: organizationIconSchema,
  url: organizationUrlSchema
});
schemaRegistry.add(organizationSchema, {
  description: "The workspace's organization details"
});
var schemaNameSchema = z._default(
  z.string().check(z.trim(), z.toLowerCase()),
  "https://public.storm-cdn.com/schemas/storm-workspace.schema.json"
);
schemaRegistry.add(schemaNameSchema, {
  description: "The URL or file path to the JSON schema file that describes the Storm configuration file"
});
var nameSchema = z.string().check(z.trim(), z.toLowerCase());
schemaRegistry.add(nameSchema, {
  description: "The name of the workspace/project/service/package/scope using this configuration"
});
var namespaceSchema = z.string().check(z.trim(), z.toLowerCase());
schemaRegistry.add(namespaceSchema, {
  description: "The namespace of the workspace/project/service/package/scope using this configuration"
});
var orgSchema = z.union([
  organizationSchema,
  z.string().check(z.trim(), z.toLowerCase())
]);
schemaRegistry.add(orgSchema, {
  description: "The organization of the workspace. This can be a string or an object containing the organization's details"
});
var repositorySchema = z.string().check(z.trim(), z.toLowerCase());
schemaRegistry.add(repositorySchema, {
  description: "The repo URL of the workspace (i.e. the GitHub repository URL)"
});
var licenseSchema = z._default(
  z.string().check(z.trim()),
  "Apache-2.0"
);
schemaRegistry.add(licenseSchema, {
  description: "The license type of the package"
});
var homepageSchema = z.optional(z.url());
schemaRegistry.add(homepageSchema, {
  description: "The homepage of the workspace"
});
var docsSchema = z.optional(z.url());
schemaRegistry.add(docsSchema, {
  description: "The documentation site for the workspace"
});
var portalSchema = z.optional(z.url());
schemaRegistry.add(portalSchema, {
  description: "The development portal site for the workspace"
});
var licensingSchema = z.optional(z.url());
schemaRegistry.add(licensingSchema, {
  description: "The licensing site for the workspace"
});
var contactSchema = z.optional(z.url());
schemaRegistry.add(contactSchema, {
  description: "The contact site for the workspace"
});
var supportSchema = z.optional(z.url());
schemaRegistry.add(supportSchema, {
  description: "The support site for the workspace. If not provided, this is defaulted to the `contact` config value"
});
var branchSchema = z._default(
  z.string().check(z.trim(), z.toLowerCase()),
  "main"
);
schemaRegistry.add(branchSchema, {
  description: "The branch of the workspace"
});
var preidSchema = z.optional(
  z.string().check(z.trim(), z.toLowerCase())
);
schemaRegistry.add(preidSchema, {
  description: "A tag specifying the version pre-release identifier"
});
var ownerSchema = z.optional(
  z.string().check(z.trim(), z.toLowerCase())
);
schemaRegistry.add(ownerSchema, {
  description: "The owner of the package"
});
var modeSchema = z._default(
  z.enum(["development", "test", "production"]).check(z.trim(), z.toLowerCase()),
  "production"
);
schemaRegistry.add(modeSchema, {
  description: "The current runtime environment mode for the package"
});
var workspaceRootSchema = z.string().check(z.trim(), z.toLowerCase());
schemaRegistry.add(workspaceRootSchema, {
  description: "The root directory of the workspace"
});
var skipCacheSchema = z._default(z.boolean(), false);
schemaRegistry.add(skipCacheSchema, {
  description: "Should all known types of workspace caching be skipped?"
});
var packageManagerSchema = z._default(
  z.enum(["npm", "yarn", "pnpm", "bun"]),
  "npm"
);
schemaRegistry.add(packageManagerSchema, {
  description: "The JavaScript/TypeScript package manager used by the repository"
});
var timezoneSchema = z._default(
  z.string().check(z.trim()),
  "America/New_York"
);
schemaRegistry.add(timezoneSchema, {
  description: "The default timezone of the workspace"
});
var localeSchema = z._default(z.string().check(z.trim()), "en-US");
schemaRegistry.add(localeSchema, {
  description: "The default locale of the workspace"
});
var logLevelSchema = z._default(
  z.enum([
    "silent",
    "fatal",
    "error",
    "warn",
    "success",
    "info",
    "performance",
    "debug",
    "trace",
    "all"
  ]),
  "info"
);
schemaRegistry.add(logLevelSchema, {
  description: "The log level used to filter out lower priority log messages. If not provided, this is defaulted using the `environment` config value (if `environment` is set to `production` then `level` is `error`, else `level` is `debug`)."
});
var skipConfigLoggingSchema = z._default(z.boolean(), true);
schemaRegistry.add(skipConfigLoggingSchema, {
  description: "Should the logging of the current Storm Workspace configuration be skipped?"
});
var configFileSchema = z._default(
  z.nullable(z.string().check(z.trim())),
  null
);
schemaRegistry.add(configFileSchema, {
  description: "The filepath of the Storm config. When this field is null, no config file was found in the current workspace."
});
var extensionsSchema = z._default(z.record(z.string(), z.any()), {});
schemaRegistry.add(extensionsSchema, {
  description: "Configuration of each used extension"
});
var workspaceConfigSchema = z.object({
  $schema: schemaNameSchema,
  extends: extendsSchema,
  name: nameSchema,
  variant: variantSchema,
  namespace: namespaceSchema,
  organization: orgSchema,
  repository: repositorySchema,
  license: licenseSchema,
  homepage: homepageSchema,
  docs: docsSchema,
  portal: portalSchema,
  licensing: licensingSchema,
  contact: contactSchema,
  support: supportSchema,
  branch: branchSchema,
  preid: preidSchema,
  owner: ownerSchema,
  bot: workspaceBotSchema,
  release: workspaceReleaseSchema,
  socials: workspaceSocialsSchema,
  error: errorSchema,
  mode: modeSchema,
  workspaceRoot: workspaceRootSchema,
  skipCache: skipCacheSchema,
  directories: workspaceDirectorySchema,
  packageManager: packageManagerSchema,
  timezone: timezoneSchema,
  locale: localeSchema,
  logLevel: logLevelSchema,
  skipConfigLogging: skipConfigLoggingSchema,
  registry: registrySchema,
  configFile: configFileSchema,
  colors: z.union([colorsSchema, themeColorsSchema]),
  extensions: extensionsSchema
});
schemaRegistry.add(extensionsSchema, {
  description: "Storm Workspace config values used during various dev-ops processes. This type is a combination of the StormPackageConfig and StormProject types. It represents the config of the entire monorepo."
});

// ../config/src/types.ts
var COLOR_KEYS = [
  "dark",
  "light",
  "base",
  "brand",
  "alternate",
  "accent",
  "link",
  "success",
  "help",
  "info",
  "warning",
  "danger",
  "fatal",
  "performance",
  "positive",
  "negative"
];

// ../config-tools/src/utilities/get-default-config.ts
import { existsSync as existsSync3 } from "node:fs";
import { readFile as readFile3 } from "node:fs/promises";
import { join as join2 } from "node:path";
async function getPackageJsonConfig(root) {
  let license = STORM_DEFAULT_LICENSE;
  let homepage = void 0;
  let support = void 0;
  let name = void 0;
  let namespace = void 0;
  let repository = void 0;
  const workspaceRoot = findWorkspaceRoot(root);
  if (existsSync3(join2(workspaceRoot, "package.json"))) {
    const file = await readFile3(
      joinPaths(workspaceRoot, "package.json"),
      "utf8"
    );
    if (file) {
      const packageJson = JSON.parse(file);
      if (packageJson.name) {
        name = packageJson.name;
      }
      if (packageJson.namespace) {
        namespace = packageJson.namespace;
      }
      if (packageJson.repository) {
        if (typeof packageJson.repository === "string") {
          repository = packageJson.repository;
        } else if (packageJson.repository.url) {
          repository = packageJson.repository.url;
        }
      }
      if (packageJson.license) {
        license = packageJson.license;
      }
      if (packageJson.homepage) {
        homepage = packageJson.homepage;
      }
      if (packageJson.bugs) {
        if (typeof packageJson.bugs === "string") {
          support = packageJson.bugs;
        } else if (packageJson.bugs.url) {
          support = packageJson.bugs.url;
        }
      }
    }
  }
  return {
    workspaceRoot,
    name,
    namespace,
    repository,
    license,
    homepage,
    support
  };
}
function applyDefaultConfig(config) {
  if (!config.support && config.contact) {
    config.support = config.contact;
  }
  if (!config.contact && config.support) {
    config.contact = config.support;
  }
  if (config.homepage) {
    if (!config.docs) {
      config.docs = `${config.homepage}/docs`;
    }
    if (!config.license) {
      config.license = `${config.homepage}/license`;
    }
    if (!config.support) {
      config.support = `${config.homepage}/support`;
    }
    if (!config.contact) {
      config.contact = `${config.homepage}/contact`;
    }
    if (!config.error?.codesFile || !config?.error?.url) {
      config.error ??= { codesFile: STORM_DEFAULT_ERROR_CODES_FILE };
      if (config.homepage) {
        config.error.url ??= `${config.homepage}/errors`;
      }
    }
  }
  return config;
}

// ../config-tools/src/config-file/get-config-file.ts
var getConfigFileByName = async (fileName, filePath, options = {}) => {
  const workspacePath = filePath || findWorkspaceRoot(filePath);
  const configs = await Promise.all([
    loadConfig({
      cwd: workspacePath,
      packageJson: true,
      name: fileName,
      envName: fileName?.toUpperCase(),
      jitiOptions: {
        debug: false,
        fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(
          process.env.STORM_CACHE_DIR || "node_modules/.cache/storm",
          "jiti"
        )
      },
      ...options
    }),
    loadConfig({
      cwd: workspacePath,
      packageJson: true,
      name: fileName,
      envName: fileName?.toUpperCase(),
      jitiOptions: {
        debug: false,
        fsCache: process.env.STORM_SKIP_CACHE === "true" ? false : joinPaths(
          process.env.STORM_CACHE_DIR || "node_modules/.cache/storm",
          "jiti"
        )
      },
      configFile: fileName,
      ...options
    })
  ]);
  return defu(configs[0] ?? {}, configs[1] ?? {});
};
var getConfigFile = async (filePath, additionalFileNames = []) => {
  const workspacePath = filePath ? filePath : findWorkspaceRoot(filePath);
  const result = await getConfigFileByName("storm-workspace", workspacePath);
  let config = result.config;
  const configFile = result.configFile;
  if (config && configFile && Object.keys(config).length > 0 && !config.skipConfigLogging) {
    writeTrace(
      `Found Storm configuration file "${configFile.includes(`${workspacePath}/`) ? configFile.replace(`${workspacePath}/`, "") : configFile}" at "${workspacePath}"`,
      {
        logLevel: "all"
      }
    );
  }
  if (additionalFileNames && additionalFileNames.length > 0) {
    const results = await Promise.all(
      additionalFileNames.map(
        (fileName) => getConfigFileByName(fileName, workspacePath)
      )
    );
    for (const result2 of results) {
      if (result2?.config && result2?.configFile && Object.keys(result2.config).length > 0) {
        if (!config.skipConfigLogging && !result2.config.skipConfigLogging) {
          writeTrace(
            `Found alternative configuration file "${result2.configFile.includes(`${workspacePath}/`) ? result2.configFile.replace(`${workspacePath}/`, "") : result2.configFile}" at "${workspacePath}"`,
            {
              logLevel: "all"
            }
          );
        }
        config = defu(result2.config ?? {}, config ?? {});
      }
    }
  }
  if (!config || Object.keys(config).length === 0) {
    return void 0;
  }
  config.configFile = configFile;
  return config;
};

// ../config-tools/src/create-storm-config.ts
import defu2 from "defu";
import { existsSync as existsSync4 } from "node:fs";

// ../config-tools/src/env/get-env.ts
var getExtensionEnv = (extensionName) => {
  const prefix = `STORM_EXTENSION_${extensionName.toUpperCase()}_`;
  return Object.keys(process.env).filter((key) => key.startsWith(prefix)).reduce((ret, key) => {
    const name = key.replace(prefix, "").split("_").map(
      (i) => i.length > 0 ? i.trim().charAt(0).toUpperCase() + i.trim().slice(1) : ""
    ).join("");
    if (name) {
      ret[name] = process.env[key];
    }
    return ret;
  }, {});
};
var getConfigEnv = () => {
  const prefix = "STORM_";
  let config = {
    extends: process.env[`${prefix}EXTENDS`] || void 0,
    name: process.env[`${prefix}NAME`] || void 0,
    variant: process.env[`${prefix}VARIANT`] || void 0,
    namespace: process.env[`${prefix}NAMESPACE`] || void 0,
    owner: process.env[`${prefix}OWNER`] || void 0,
    bot: {
      name: process.env[`${prefix}BOT_NAME`] || void 0,
      email: process.env[`${prefix}BOT_EMAIL`] || void 0
    },
    release: {
      banner: {
        url: process.env[`${prefix}RELEASE_BANNER_URL`] || void 0,
        alt: process.env[`${prefix}RELEASE_BANNER_ALT`] || void 0
      },
      header: process.env[`${prefix}RELEASE_HEADER`] || void 0,
      footer: process.env[`${prefix}RELEASE_FOOTER`] || void 0
    },
    error: {
      codesFile: process.env[`${prefix}ERROR_CODES_FILE`] || void 0,
      url: process.env[`${prefix}ERROR_URL`] || void 0
    },
    socials: {
      twitter: process.env[`${prefix}SOCIAL_TWITTER`] || void 0,
      discord: process.env[`${prefix}SOCIAL_DISCORD`] || void 0,
      telegram: process.env[`${prefix}SOCIAL_TELEGRAM`] || void 0,
      slack: process.env[`${prefix}SOCIAL_SLACK`] || void 0,
      medium: process.env[`${prefix}SOCIAL_MEDIUM`] || void 0,
      github: process.env[`${prefix}SOCIAL_GITHUB`] || void 0
    },
    organization: process.env[`${prefix}ORG`] || process.env[`${prefix}ORGANIZATION`] || process.env[`${prefix}ORG_NAME`] || process.env[`${prefix}ORGANIZATION_NAME`] ? process.env[`${prefix}ORG_DESCRIPTION`] || process.env[`${prefix}ORGANIZATION_DESCRIPTION`] || process.env[`${prefix}ORG_URL`] || process.env[`${prefix}ORGANIZATION_URL`] || process.env[`${prefix}ORG_LOGO`] || process.env[`${prefix}ORGANIZATION_LOGO`] ? {
      name: process.env[`${prefix}ORG`] || process.env[`${prefix}ORGANIZATION`] || process.env[`${prefix}ORG_NAME`] || process.env[`${prefix}ORGANIZATION_NAME`],
      description: process.env[`${prefix}ORG_DESCRIPTION`] || process.env[`${prefix}ORGANIZATION_DESCRIPTION`] || void 0,
      url: process.env[`${prefix}ORG_URL`] || process.env[`${prefix}ORGANIZATION_URL`] || void 0,
      logo: process.env[`${prefix}ORG_LOGO`] || process.env[`${prefix}ORGANIZATION_LOGO`] || void 0,
      icon: process.env[`${prefix}ORG_ICON`] || process.env[`${prefix}ORGANIZATION_ICON`] || void 0
    } : process.env[`${prefix}ORG`] || process.env[`${prefix}ORGANIZATION`] || process.env[`${prefix}ORG_NAME`] || process.env[`${prefix}ORGANIZATION_NAME`] : void 0,
    packageManager: process.env[`${prefix}PACKAGE_MANAGER`] || void 0,
    license: process.env[`${prefix}LICENSE`] || void 0,
    homepage: process.env[`${prefix}HOMEPAGE`] || void 0,
    docs: process.env[`${prefix}DOCS`] || void 0,
    portal: process.env[`${prefix}PORTAL`] || void 0,
    licensing: process.env[`${prefix}LICENSING`] || void 0,
    contact: process.env[`${prefix}CONTACT`] || void 0,
    support: process.env[`${prefix}SUPPORT`] || void 0,
    timezone: process.env[`${prefix}TIMEZONE`] || process.env.TZ || void 0,
    locale: process.env[`${prefix}LOCALE`] || process.env.LOCALE || void 0,
    configFile: process.env[`${prefix}WORKSPACE_CONFIG_FILE`] ? correctPaths(process.env[`${prefix}WORKSPACE_CONFIG_FILE`]) : void 0,
    workspaceRoot: process.env[`${prefix}WORKSPACE_ROOT`] ? correctPaths(process.env[`${prefix}WORKSPACE_ROOT`]) : void 0,
    directories: {
      cache: process.env[`${prefix}CACHE_DIR`] ? correctPaths(process.env[`${prefix}CACHE_DIR`]) : process.env[`${prefix}CACHE_DIRECTORY`] ? correctPaths(process.env[`${prefix}CACHE_DIRECTORY`]) : void 0,
      data: process.env[`${prefix}DATA_DIR`] ? correctPaths(process.env[`${prefix}DATA_DIR`]) : process.env[`${prefix}DATA_DIRECTORY`] ? correctPaths(process.env[`${prefix}DATA_DIRECTORY`]) : void 0,
      config: process.env[`${prefix}CONFIG_DIR`] ? correctPaths(process.env[`${prefix}CONFIG_DIR`]) : process.env[`${prefix}CONFIG_DIRECTORY`] ? correctPaths(process.env[`${prefix}CONFIG_DIRECTORY`]) : void 0,
      temp: process.env[`${prefix}TEMP_DIR`] ? correctPaths(process.env[`${prefix}TEMP_DIR`]) : process.env[`${prefix}TEMP_DIRECTORY`] ? correctPaths(process.env[`${prefix}TEMP_DIRECTORY`]) : void 0,
      log: process.env[`${prefix}LOG_DIR`] ? correctPaths(process.env[`${prefix}LOG_DIR`]) : process.env[`${prefix}LOG_DIRECTORY`] ? correctPaths(process.env[`${prefix}LOG_DIRECTORY`]) : void 0,
      build: process.env[`${prefix}BUILD_DIR`] ? correctPaths(process.env[`${prefix}BUILD_DIR`]) : process.env[`${prefix}BUILD_DIRECTORY`] ? correctPaths(process.env[`${prefix}BUILD_DIRECTORY`]) : void 0
    },
    skipCache: process.env[`${prefix}SKIP_CACHE`] !== void 0 ? Boolean(process.env[`${prefix}SKIP_CACHE`]) : void 0,
    mode: (process.env[`${prefix}MODE`] ?? process.env.NODE_ENV ?? process.env.ENVIRONMENT) || void 0,
    // ci:
    //   process.env[`${prefix}CI`] !== undefined
    //     ? Boolean(
    //         process.env[`${prefix}CI`] ??
    //           process.env.CI ??
    //           process.env.CONTINUOUS_INTEGRATION
    //       )
    //     : undefined,
    repository: process.env[`${prefix}REPOSITORY`] || void 0,
    branch: process.env[`${prefix}BRANCH`] || void 0,
    preid: process.env[`${prefix}PRE_ID`] || void 0,
    registry: {
      github: process.env[`${prefix}REGISTRY_GITHUB`] || void 0,
      npm: process.env[`${prefix}REGISTRY_NPM`] || void 0,
      cargo: process.env[`${prefix}REGISTRY_CARGO`] || void 0,
      cyclone: process.env[`${prefix}REGISTRY_CYCLONE`] || void 0,
      container: process.env[`${prefix}REGISTRY_CONTAINER`] || void 0
    },
    logLevel: process.env[`${prefix}LOG_LEVEL`] !== null && process.env[`${prefix}LOG_LEVEL`] !== void 0 ? process.env[`${prefix}LOG_LEVEL`] && Number.isSafeInteger(
      Number.parseInt(process.env[`${prefix}LOG_LEVEL`])
    ) ? getLogLevelLabel(
      Number.parseInt(process.env[`${prefix}LOG_LEVEL`])
    ) : process.env[`${prefix}LOG_LEVEL`] : void 0,
    skipConfigLogging: process.env[`${prefix}SKIP_CONFIG_LOGGING`] !== void 0 ? Boolean(process.env[`${prefix}SKIP_CONFIG_LOGGING`]) : void 0
  };
  const themeNames = Object.keys(process.env).filter(
    (envKey) => envKey.startsWith(`${prefix}COLOR_`) && COLOR_KEYS.every(
      (colorKey) => !envKey.startsWith(`${prefix}COLOR_LIGHT_${colorKey}`) && !envKey.startsWith(`${prefix}COLOR_DARK_${colorKey}`)
    )
  );
  config.colors = themeNames.length > 0 ? themeNames.reduce(
    (ret, themeName) => {
      ret[themeName] = getThemeColorsEnv(prefix, themeName);
      return ret;
    },
    {}
  ) : getThemeColorsEnv(prefix);
  if (config.docs === STORM_DEFAULT_DOCS) {
    if (config.homepage === STORM_DEFAULT_HOMEPAGE) {
      config.docs = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/docs`;
    } else {
      config.docs = `${config.homepage}/docs`;
    }
  }
  if (config.licensing === STORM_DEFAULT_LICENSING) {
    if (config.homepage === STORM_DEFAULT_HOMEPAGE) {
      config.licensing = `${STORM_DEFAULT_HOMEPAGE}/projects/${config.name}/licensing`;
    } else {
      config.licensing = `${config.homepage}/docs`;
    }
  }
  const serializedConfig = process.env[`${prefix}WORKSPACE_CONFIG`];
  if (serializedConfig) {
    const parsed = JSON.parse(serializedConfig);
    config = {
      ...config,
      ...parsed,
      colors: { ...config.colors, ...parsed.colors },
      extensions: { ...config.extensions, ...parsed.extensions }
    };
  }
  return config;
};
var getThemeColorsEnv = (prefix, theme) => {
  const themeName = `COLOR_${theme && theme !== "base" ? `${theme}_` : ""}`.toUpperCase();
  return process.env[`${prefix}${themeName}LIGHT_BRAND`] || process.env[`${prefix}${themeName}DARK_BRAND`] ? getMultiThemeColorsEnv(prefix + themeName) : getSingleThemeColorsEnv(prefix + themeName);
};
var getSingleThemeColorsEnv = (prefix) => {
  const gradient = [];
  if (process.env[`${prefix}GRADIENT_START`] && process.env[`${prefix}GRADIENT_END`]) {
    gradient.push(
      process.env[`${prefix}GRADIENT_START`],
      process.env[`${prefix}GRADIENT_END`]
    );
  } else if (process.env[`${prefix}GRADIENT_0`] || process.env[`${prefix}GRADIENT_1`]) {
    let index = process.env[`${prefix}GRADIENT_0`] ? 0 : 1;
    while (process.env[`${prefix}GRADIENT_${index}`]) {
      gradient.push(process.env[`${prefix}GRADIENT_${index}`]);
      index++;
    }
  }
  return {
    dark: process.env[`${prefix}DARK`],
    light: process.env[`${prefix}LIGHT`],
    brand: process.env[`${prefix}BRAND`],
    alternate: process.env[`${prefix}ALTERNATE`],
    accent: process.env[`${prefix}ACCENT`],
    link: process.env[`${prefix}LINK`],
    help: process.env[`${prefix}HELP`],
    success: process.env[`${prefix}SUCCESS`],
    info: process.env[`${prefix}INFO`],
    debug: process.env[`${prefix}DEBUG`],
    warning: process.env[`${prefix}WARNING`],
    danger: process.env[`${prefix}DANGER`],
    fatal: process.env[`${prefix}FATAL`],
    performance: process.env[`${prefix}PERFORMANCE`],
    positive: process.env[`${prefix}POSITIVE`],
    negative: process.env[`${prefix}NEGATIVE`],
    gradient
  };
};
var getMultiThemeColorsEnv = (prefix) => {
  return {
    light: getBaseThemeColorsEnv(`${prefix}_LIGHT_`),
    dark: getBaseThemeColorsEnv(`${prefix}_DARK_`)
  };
};
var getBaseThemeColorsEnv = (prefix) => {
  const gradient = [];
  if (process.env[`${prefix}GRADIENT_START`] && process.env[`${prefix}GRADIENT_END`]) {
    gradient.push(
      process.env[`${prefix}GRADIENT_START`],
      process.env[`${prefix}GRADIENT_END`]
    );
  } else if (process.env[`${prefix}GRADIENT_0`] || process.env[`${prefix}GRADIENT_1`]) {
    let index = process.env[`${prefix}GRADIENT_0`] ? 0 : 1;
    while (process.env[`${prefix}GRADIENT_${index}`]) {
      gradient.push(process.env[`${prefix}GRADIENT_${index}`]);
      index++;
    }
  }
  return {
    foreground: process.env[`${prefix}FOREGROUND`],
    background: process.env[`${prefix}BACKGROUND`],
    brand: process.env[`${prefix}BRAND`],
    alternate: process.env[`${prefix}ALTERNATE`],
    accent: process.env[`${prefix}ACCENT`],
    link: process.env[`${prefix}LINK`],
    help: process.env[`${prefix}HELP`],
    success: process.env[`${prefix}SUCCESS`],
    info: process.env[`${prefix}INFO`],
    debug: process.env[`${prefix}DEBUG`],
    warning: process.env[`${prefix}WARNING`],
    danger: process.env[`${prefix}DANGER`],
    fatal: process.env[`${prefix}FATAL`],
    performance: process.env[`${prefix}PERFORMANCE`],
    positive: process.env[`${prefix}POSITIVE`],
    negative: process.env[`${prefix}NEGATIVE`],
    gradient
  };
};

// ../config-tools/src/env/set-env.ts
var setExtensionEnv = (extensionName, extension) => {
  for (const key of Object.keys(extension ?? {})) {
    if (extension[key]) {
      const result = key?.replace(
        /([A-Z])+/g,
        (input) => input ? input[0]?.toUpperCase() + input.slice(1) : ""
      ).split(/(?=[A-Z])|[.\-\s_]/).map((x) => x.toLowerCase()) ?? [];
      let extensionKey;
      if (result.length === 0) {
        return;
      }
      if (result.length === 1) {
        extensionKey = result[0]?.toUpperCase() ?? "";
      } else {
        extensionKey = result.reduce((ret, part) => {
          return `${ret}_${part.toLowerCase()}`;
        });
      }
      process.env[`STORM_EXTENSION_${extensionName.toUpperCase()}_${extensionKey.toUpperCase()}`] = extension[key];
    }
  }
};
var setConfigEnv = (config) => {
  const prefix = "STORM_";
  if (config.extends) {
    process.env[`${prefix}EXTENDS`] = Array.isArray(config.extends) ? JSON.stringify(config.extends) : config.extends;
  }
  if (config.name) {
    process.env[`${prefix}NAME`] = config.name;
  }
  if (config.variant) {
    process.env[`${prefix}VARIANT`] = config.variant;
  }
  if (config.namespace) {
    process.env[`${prefix}NAMESPACE`] = config.namespace;
  }
  if (config.owner) {
    process.env[`${prefix}OWNER`] = config.owner;
  }
  if (config.bot) {
    process.env[`${prefix}BOT_NAME`] = config.bot.name;
    process.env[`${prefix}BOT_EMAIL`] = config.bot.email;
  }
  if (config.error) {
    process.env[`${prefix}ERROR_CODES_FILE`] = config.error.codesFile;
    process.env[`${prefix}ERROR_URL`] = config.error.url;
  }
  if (config.release) {
    if (config.release.banner) {
      if (typeof config.release.banner === "string") {
        process.env[`${prefix}RELEASE_BANNER`] = config.release.banner;
        process.env[`${prefix}RELEASE_BANNER_URL`] = config.release.banner;
      } else {
        process.env[`${prefix}RELEASE_BANNER`] = config.release.banner.url;
        process.env[`${prefix}RELEASE_BANNER_URL`] = config.release.banner.url;
        process.env[`${prefix}RELEASE_BANNER_ALT`] = config.release.banner.alt;
      }
    }
    process.env[`${prefix}RELEASE_HEADER`] = config.release.header;
    process.env[`${prefix}RELEASE_FOOTER`] = config.release.footer;
  }
  if (config.socials) {
    if (config.socials.twitter) {
      process.env[`${prefix}SOCIAL_TWITTER`] = config.socials.twitter;
    }
    if (config.socials.discord) {
      process.env[`${prefix}SOCIAL_DISCORD`] = config.socials.discord;
    }
    if (config.socials.telegram) {
      process.env[`${prefix}SOCIAL_TELEGRAM`] = config.socials.telegram;
    }
    if (config.socials.slack) {
      process.env[`${prefix}SOCIAL_SLACK`] = config.socials.slack;
    }
    if (config.socials.medium) {
      process.env[`${prefix}SOCIAL_MEDIUM`] = config.socials.medium;
    }
    if (config.socials.github) {
      process.env[`${prefix}SOCIAL_GITHUB`] = config.socials.github;
    }
  }
  if (config.organization) {
    if (typeof config.organization === "string") {
      process.env[`${prefix}ORG`] = config.organization;
      process.env[`${prefix}ORG_NAME`] = config.organization;
      process.env[`${prefix}ORGANIZATION`] = config.organization;
      process.env[`${prefix}ORGANIZATION_NAME`] = config.organization;
    } else {
      process.env[`${prefix}ORG`] = config.organization.name;
      process.env[`${prefix}ORG_NAME`] = config.organization.name;
      process.env[`${prefix}ORGANIZATION`] = config.organization.name;
      process.env[`${prefix}ORGANIZATION_NAME`] = config.organization.name;
      if (config.organization.url) {
        process.env[`${prefix}ORG_URL`] = config.organization.url;
        process.env[`${prefix}ORGANIZATION_URL`] = config.organization.url;
      }
      if (config.organization.description) {
        process.env[`${prefix}ORG_DESCRIPTION`] = config.organization.description;
        process.env[`${prefix}ORGANIZATION_DESCRIPTION`] = config.organization.description;
      }
      if (config.organization.logo) {
        process.env[`${prefix}ORG_LOGO`] = config.organization.logo;
        process.env[`${prefix}ORGANIZATION_LOGO`] = config.organization.logo;
      }
      if (config.organization.icon) {
        process.env[`${prefix}ORG_ICON`] = config.organization.icon;
        process.env[`${prefix}ORGANIZATION_ICON`] = config.organization.icon;
      }
    }
  }
  if (config.packageManager) {
    process.env[`${prefix}PACKAGE_MANAGER`] = config.packageManager;
  }
  if (config.license) {
    process.env[`${prefix}LICENSE`] = config.license;
  }
  if (config.homepage) {
    process.env[`${prefix}HOMEPAGE`] = config.homepage;
  }
  if (config.docs) {
    process.env[`${prefix}DOCS`] = config.docs;
  }
  if (config.portal) {
    process.env[`${prefix}PORTAL`] = config.portal;
  }
  if (config.licensing) {
    process.env[`${prefix}LICENSING`] = config.licensing;
  }
  if (config.contact) {
    process.env[`${prefix}CONTACT`] = config.contact;
  }
  if (config.support) {
    process.env[`${prefix}SUPPORT`] = config.support;
  }
  if (config.timezone) {
    process.env[`${prefix}TIMEZONE`] = config.timezone;
    process.env.TZ = config.timezone;
    process.env.DEFAULT_TIMEZONE = config.timezone;
    process.env.TIMEZONE = config.timezone;
  }
  if (config.locale) {
    process.env[`${prefix}LOCALE`] = config.locale;
    process.env.DEFAULT_LOCALE = config.locale;
    process.env.LOCALE = config.locale;
    process.env.LANG = config.locale ? `${config.locale.replaceAll("-", "_")}.UTF-8` : "en_US.UTF-8";
  }
  if (config.configFile) {
    process.env[`${prefix}WORKSPACE_CONFIG_FILE`] = correctPaths(
      config.configFile
    );
  }
  if (config.workspaceRoot) {
    process.env[`${prefix}WORKSPACE_ROOT`] = correctPaths(config.workspaceRoot);
    process.env.NX_WORKSPACE_ROOT = correctPaths(config.workspaceRoot);
    process.env.NX_WORKSPACE_ROOT_PATH = correctPaths(config.workspaceRoot);
  }
  if (config.directories) {
    if (!config.skipCache && config.directories.cache) {
      process.env[`${prefix}CACHE_DIR`] = correctPaths(
        config.directories.cache
      );
      process.env[`${prefix}CACHE_DIRECTORY`] = process.env[`${prefix}CACHE_DIR`];
    }
    if (config.directories.data) {
      process.env[`${prefix}DATA_DIR`] = correctPaths(config.directories.data);
      process.env[`${prefix}DATA_DIRECTORY`] = process.env[`${prefix}DATA_DIR`];
    }
    if (config.directories.config) {
      process.env[`${prefix}CONFIG_DIR`] = correctPaths(
        config.directories.config
      );
      process.env[`${prefix}CONFIG_DIRECTORY`] = process.env[`${prefix}CONFIG_DIR`];
    }
    if (config.directories.temp) {
      process.env[`${prefix}TEMP_DIR`] = correctPaths(config.directories.temp);
      process.env[`${prefix}TEMP_DIRECTORY`] = process.env[`${prefix}TEMP_DIR`];
    }
    if (config.directories.log) {
      process.env[`${prefix}LOG_DIR`] = correctPaths(config.directories.log);
      process.env[`${prefix}LOG_DIRECTORY`] = process.env[`${prefix}LOG_DIR`];
    }
    if (config.directories.build) {
      process.env[`${prefix}BUILD_DIR`] = correctPaths(
        config.directories.build
      );
      process.env[`${prefix}BUILD_DIRECTORY`] = process.env[`${prefix}BUILD_DIR`];
    }
  }
  if (config.skipCache !== void 0) {
    process.env[`${prefix}SKIP_CACHE`] = String(config.skipCache);
    if (config.skipCache) {
      process.env.NX_SKIP_NX_CACHE ??= String(config.skipCache);
      process.env.NX_CACHE_PROJECT_GRAPH ??= String(config.skipCache);
    }
  }
  if (config.mode) {
    process.env[`${prefix}MODE`] = config.mode;
    process.env.NODE_ENV = config.mode;
    process.env.ENVIRONMENT = config.mode;
  }
  if (config.colors?.base?.light || config.colors?.base?.dark) {
    for (const key of Object.keys(config.colors)) {
      setThemeColorsEnv(`${prefix}COLOR_${key}_`, config.colors[key]);
    }
  } else {
    setThemeColorsEnv(
      `${prefix}COLOR_`,
      config.colors
    );
  }
  if (config.repository) {
    process.env[`${prefix}REPOSITORY`] = config.repository;
  }
  if (config.branch) {
    process.env[`${prefix}BRANCH`] = config.branch;
  }
  if (config.preid) {
    process.env[`${prefix}PRE_ID`] = String(config.preid);
  }
  if (config.registry) {
    if (config.registry.github) {
      process.env[`${prefix}REGISTRY_GITHUB`] = String(config.registry.github);
    }
    if (config.registry.npm) {
      process.env[`${prefix}REGISTRY_NPM`] = String(config.registry.npm);
    }
    if (config.registry.cargo) {
      process.env[`${prefix}REGISTRY_CARGO`] = String(config.registry.cargo);
    }
    if (config.registry.cyclone) {
      process.env[`${prefix}REGISTRY_CYCLONE`] = String(
        config.registry.cyclone
      );
    }
    if (config.registry.container) {
      process.env[`${prefix}REGISTRY_CONTAINER`] = String(
        config.registry.container
      );
    }
  }
  if (config.logLevel) {
    process.env[`${prefix}LOG_LEVEL`] = String(config.logLevel);
    process.env.LOG_LEVEL = String(config.logLevel);
    process.env.NX_VERBOSE_LOGGING = String(
      getLogLevel(config.logLevel) >= LogLevel.DEBUG ? true : false
    );
    process.env.RUST_BACKTRACE = getLogLevel(config.logLevel) >= LogLevel.DEBUG ? "full" : "none";
  }
  if (config.skipConfigLogging !== void 0) {
    process.env[`${prefix}SKIP_CONFIG_LOGGING`] = String(
      config.skipConfigLogging
    );
  }
  process.env[`${prefix}WORKSPACE_CONFIG`] = JSON.stringify(config);
  for (const key of Object.keys(config.extensions ?? {})) {
    if (config.extensions[key] && Object.keys(config.extensions[key])) {
      setExtensionEnv(key, config.extensions[key]);
    }
  }
};
var setThemeColorsEnv = (prefix, config) => {
  return config?.light?.brand || config?.dark?.brand ? setMultiThemeColorsEnv(prefix, config) : setSingleThemeColorsEnv(prefix, config);
};
var setSingleThemeColorsEnv = (prefix, config) => {
  if (config.dark) {
    process.env[`${prefix}DARK`] = config.dark;
  }
  if (config.light) {
    process.env[`${prefix}LIGHT`] = config.light;
  }
  if (config.brand) {
    process.env[`${prefix}BRAND`] = config.brand;
  }
  if (config.alternate) {
    process.env[`${prefix}ALTERNATE`] = config.alternate;
  }
  if (config.accent) {
    process.env[`${prefix}ACCENT`] = config.accent;
  }
  if (config.link) {
    process.env[`${prefix}LINK`] = config.link;
  }
  if (config.help) {
    process.env[`${prefix}HELP`] = config.help;
  }
  if (config.success) {
    process.env[`${prefix}SUCCESS`] = config.success;
  }
  if (config.info) {
    process.env[`${prefix}INFO`] = config.info;
  }
  if (config.debug) {
    process.env[`${prefix}DEBUG`] = config.debug;
  }
  if (config.warning) {
    process.env[`${prefix}WARNING`] = config.warning;
  }
  if (config.danger) {
    process.env[`${prefix}DANGER`] = config.danger;
  }
  if (config.fatal) {
    process.env[`${prefix}FATAL`] = config.fatal;
  }
  if (config.performance) {
    process.env[`${prefix}PERFORMANCE`] = config.performance;
  }
  if (config.positive) {
    process.env[`${prefix}POSITIVE`] = config.positive;
  }
  if (config.negative) {
    process.env[`${prefix}NEGATIVE`] = config.negative;
  }
  if (config.gradient) {
    for (let i = 0; i < config.gradient.length; i++) {
      process.env[`${prefix}GRADIENT_${i}`] = config.gradient[i];
    }
  }
};
var setMultiThemeColorsEnv = (prefix, config) => {
  return {
    light: setBaseThemeColorsEnv(`${prefix}LIGHT_`, config.light),
    dark: setBaseThemeColorsEnv(`${prefix}DARK_`, config.dark)
  };
};
var setBaseThemeColorsEnv = (prefix, config) => {
  if (config.foreground) {
    process.env[`${prefix}FOREGROUND`] = config.foreground;
  }
  if (config.background) {
    process.env[`${prefix}BACKGROUND`] = config.background;
  }
  if (config.brand) {
    process.env[`${prefix}BRAND`] = config.brand;
  }
  if (config.alternate) {
    process.env[`${prefix}ALTERNATE`] = config.alternate;
  }
  if (config.accent) {
    process.env[`${prefix}ACCENT`] = config.accent;
  }
  if (config.link) {
    process.env[`${prefix}LINK`] = config.link;
  }
  if (config.help) {
    process.env[`${prefix}HELP`] = config.help;
  }
  if (config.success) {
    process.env[`${prefix}SUCCESS`] = config.success;
  }
  if (config.info) {
    process.env[`${prefix}INFO`] = config.info;
  }
  if (config.debug) {
    process.env[`${prefix}DEBUG`] = config.debug;
  }
  if (config.warning) {
    process.env[`${prefix}WARNING`] = config.warning;
  }
  if (config.danger) {
    process.env[`${prefix}DANGER`] = config.danger;
  }
  if (config.fatal) {
    process.env[`${prefix}FATAL`] = config.fatal;
  }
  if (config.performance) {
    process.env[`${prefix}PERFORMANCE`] = config.performance;
  }
  if (config.positive) {
    process.env[`${prefix}POSITIVE`] = config.positive;
  }
  if (config.negative) {
    process.env[`${prefix}NEGATIVE`] = config.negative;
  }
  if (config.gradient) {
    for (let i = 0; i < config.gradient.length; i++) {
      process.env[`${prefix}GRADIENT_${i}`] = config.gradient[i];
    }
  }
};

// ../config-tools/src/create-storm-config.ts
var _extension_cache = /* @__PURE__ */ new WeakMap();
var _static_cache = void 0;
var createStormWorkspaceConfig = async (extensionName, schema, workspaceRoot, skipLogs = false, useDefault = true) => {
  let result;
  if (!_static_cache?.data || !_static_cache?.timestamp || _static_cache.timestamp < Date.now() - 8e3) {
    let _workspaceRoot = workspaceRoot;
    if (!_workspaceRoot) {
      _workspaceRoot = findWorkspaceRoot();
    }
    const configEnv = getConfigEnv();
    const configFile = await getConfigFile(_workspaceRoot);
    if (!configFile) {
      if (!skipLogs) {
        writeWarning(
          "No Storm Workspace configuration file found in the current repository. Please ensure this is the expected behavior - you can add a `storm-workspace.json` file to the root of your workspace if it is not.\n",
          { logLevel: "all" }
        );
      }
      if (useDefault === false) {
        return void 0;
      }
    }
    const defaultConfig = await getPackageJsonConfig(_workspaceRoot);
    const configInput = defu2(
      configEnv,
      configFile,
      defaultConfig
    );
    if (!configInput.variant) {
      configInput.variant = existsSync4(joinPaths(_workspaceRoot, "nx.json")) || existsSync4(joinPaths(_workspaceRoot, ".nx")) || existsSync4(joinPaths(_workspaceRoot, "lerna.json")) || existsSync4(joinPaths(_workspaceRoot, "turbo.json")) ? "monorepo" : "minimal";
    }
    try {
      const parseResult = await Promise.resolve(
        workspaceConfigSchema._zod.parse(
          { value: configInput, issues: [] },
          { async: true }
        )
      );
      result = applyDefaultConfig(parseResult.value);
      result.workspaceRoot ??= _workspaceRoot;
    } catch (error) {
      throw new Error(
        `Failed to parse Storm Workspace configuration${error?.message ? `: ${error.message}` : ""}

Please ensure your configuration file is valid JSON and matches the expected schema. The current workspace configuration input is: ${formatLogMessage(
          configInput
        )}`,
        {
          cause: error
        }
      );
    }
  } else {
    result = _static_cache.data;
  }
  if (schema && extensionName) {
    result.extensions = {
      ...result.extensions,
      [extensionName]: createConfigExtension(extensionName, schema)
    };
  }
  _static_cache = {
    timestamp: Date.now(),
    data: result
  };
  return result;
};
var createConfigExtension = (extensionName, schema) => {
  const extension_cache_key = { extensionName };
  if (_extension_cache.has(extension_cache_key)) {
    return _extension_cache.get(extension_cache_key);
  }
  let extension = getExtensionEnv(extensionName);
  if (schema) {
    extension = schema.parse(extension);
  }
  _extension_cache.set(extension_cache_key, extension);
  return extension;
};
var loadStormWorkspaceConfig = async (workspaceRoot, skipLogs = false) => {
  const config = await createStormWorkspaceConfig(
    void 0,
    void 0,
    workspaceRoot,
    skipLogs,
    true
  );
  setConfigEnv(config);
  if (!skipLogs && !config.skipConfigLogging) {
    writeTrace(
      `\u2699\uFE0F  Using Storm Workspace configuration: 
${formatLogMessage(config)}`,
      config
    );
  }
  return config;
};

// ../config-tools/src/get-config.ts
function getConfig(workspaceRoot, skipLogs = false) {
  return loadStormWorkspaceConfig(workspaceRoot, skipLogs);
}
function getWorkspaceConfig(skipLogs = true, options = {}) {
  let workspaceRoot = options.workspaceRoot;
  if (!workspaceRoot) {
    workspaceRoot = findWorkspaceRoot(options.cwd);
  }
  return getConfig(workspaceRoot, skipLogs);
}

// ../build-tools/src/utilities/get-entry-points.ts
import { glob as glob2 } from "glob";

// ../build-tools/src/utilities/get-env.ts
var getEnv = (builder, options) => {
  return {
    STORM_BUILD: builder,
    STORM_ORG: options.orgName || DEFAULT_ORGANIZATION,
    STORM_NAME: options.name,
    STORM_MODE: options.mode || DEFAULT_ENVIRONMENT,
    STORM_PLATFORM: options.platform,
    STORM_FORMAT: JSON.stringify(options.format),
    STORM_TARGET: JSON.stringify(options.target),
    ...options.env
  };
};

// ../build-tools/src/utilities/read-nx-config.ts
import { existsSync as existsSync5 } from "node:fs";
import { readFile as readFile4 } from "node:fs/promises";

// ../build-tools/src/utilities/task-graph.ts
import {
  createTaskGraph,
  mapTargetDefaultsToDependencies
} from "nx/src/tasks-runner/create-task-graph";

// src/build.ts
import defu3 from "defu";
import { existsSync as existsSync6 } from "node:fs";
import hf from "node:fs/promises";
import { build as tsdown } from "tsdown";
var resolveOptions = async (userOptions) => {
  const options = getDefaultOptions(userOptions);
  const workspaceRoot = findWorkspaceRoot(options.projectRoot);
  if (!workspaceRoot) {
    throw new Error("Cannot find Nx workspace root");
  }
  const workspaceConfig = await getWorkspaceConfig(options.debug === true, {
    workspaceRoot
  });
  writeDebug("  \u2699\uFE0F   Resolving build options", workspaceConfig);
  const stopwatch = getStopwatch("Build options resolution");
  const projectGraph = await createProjectGraphAsync2({
    exitOnError: true
  });
  const projectJsonPath = joinPaths(
    workspaceRoot,
    options.projectRoot,
    "project.json"
  );
  if (!existsSync6(projectJsonPath)) {
    throw new Error("Cannot find project.json configuration");
  }
  const projectJsonFile = await hf.readFile(projectJsonPath, "utf8");
  const projectJson = JSON.parse(projectJsonFile);
  const projectName = projectJson.name;
  const projectConfigurations = readProjectsConfigurationFromProjectGraph2(projectGraph);
  if (!projectConfigurations?.projects?.[projectName]) {
    throw new Error(
      "The Build process failed because the project does not have a valid configuration in the project.json file. Check if the file exists in the root of the project."
    );
  }
  const packageJsonPath = joinPaths(
    workspaceRoot,
    options.projectRoot,
    "package.json"
  );
  if (!existsSync6(packageJsonPath)) {
    throw new Error("Cannot find package.json configuration");
  }
  const debug = options.debug ?? (options.mode || workspaceConfig.mode) === "development";
  const sourceRoot = projectJson.sourceRoot || joinPaths(options.projectRoot, "src");
  const result = {
    name: projectName,
    mode: "production",
    target: DEFAULT_TARGET,
    generatePackageJson: true,
    outDir: joinPaths("dist", options.projectRoot),
    minify: !debug,
    plugins: [],
    assets: [],
    dts: true,
    shims: true,
    silent: !debug,
    logLevel: workspaceConfig.logLevel === "success" || workspaceConfig.logLevel === "performance" || workspaceConfig.logLevel === "debug" || workspaceConfig.logLevel === "trace" || workspaceConfig.logLevel === "all" ? "info" : workspaceConfig.logLevel === "fatal" ? "error" : workspaceConfig.logLevel,
    sourcemap: debug ? "inline" : false,
    clean: false,
    fixedExtension: true,
    nodeProtocol: true,
    tsconfig: joinPaths(options.projectRoot, "tsconfig.json"),
    debug,
    sourceRoot,
    cwd: workspaceConfig.workspaceRoot,
    entry: {
      ["index"]: joinPaths(sourceRoot, "index.ts")
    },
    workspace: true,
    ...options,
    treeshake: options.treeShaking !== false,
    format: toTSDownFormat(options.format),
    workspaceConfig,
    projectName,
    projectGraph,
    projectConfigurations
  };
  result.env = defu3(
    options.env,
    getEnv("tsdown", result)
  );
  stopwatch();
  return result;
};
async function generatePackageJson(options) {
  if (options.generatePackageJson !== false && existsSync6(joinPaths(options.projectRoot, "package.json"))) {
    writeDebug("  \u270D\uFE0F   Writing package.json file", options.workspaceConfig);
    const stopwatch = getStopwatch("Write package.json file");
    const packageJsonPath = joinPaths(options.projectRoot, "project.json");
    if (!existsSync6(packageJsonPath)) {
      throw new Error("Cannot find package.json configuration");
    }
    const packageJsonFile = await hf.readFile(
      joinPaths(
        options.workspaceConfig.workspaceRoot,
        options.projectRoot,
        "package.json"
      ),
      "utf8"
    );
    if (!packageJsonFile) {
      throw new Error("Cannot find package.json configuration file");
    }
    let packageJson = JSON.parse(packageJsonFile);
    packageJson = await addPackageDependencies(
      options.workspaceConfig.workspaceRoot,
      options.projectRoot,
      options.projectName,
      packageJson
    );
    packageJson = await addWorkspacePackageJsonFields(
      options.workspaceConfig,
      options.projectRoot,
      options.sourceRoot,
      options.projectName,
      false,
      packageJson
    );
    packageJson.exports ??= {};
    packageJson.exports["./package.json"] ??= "./package.json";
    packageJson.exports["."] ??= addPackageJsonExport(
      "index",
      packageJson.type,
      options.sourceRoot
    );
    let entry = [{ in: "./src/index.ts", out: "./src/index.ts" }];
    if (options.entry) {
      if (Array.isArray(options.entry)) {
        entry = options.entry.map(
          (entryPoint) => typeof entryPoint === "string" ? { in: entryPoint, out: entryPoint } : entryPoint
        );
      }
      for (const entryPoint of entry) {
        const split = entryPoint.out.split(".");
        split.pop();
        const entry2 = split.join(".").replaceAll("\\", "/");
        packageJson.exports[`./${entry2}`] ??= addPackageJsonExport(
          entry2,
          options.fixedExtension ? "fixed" : packageJson.type,
          options.sourceRoot
        );
      }
    }
    packageJson.main = !options.fixedExtension && packageJson.type === "commonjs" ? "./dist/index.js" : "./dist/index.cjs";
    packageJson.module = !options.fixedExtension && packageJson.type === "module" ? "./dist/index.js" : "./dist/index.mjs";
    packageJson.types = `./dist/index.d.${!options.fixedExtension ? "ts" : "mts"}`;
    packageJson.exports = Object.keys(packageJson.exports).reduce(
      (ret, key) => {
        if (key.endsWith("/index") && !ret[key.replace("/index", "")]) {
          ret[key.replace("/index", "")] = packageJson.exports[key];
        }
        return ret;
      },
      packageJson.exports
    );
    await writeJsonFile(joinPaths(options.outDir, "package.json"), packageJson);
    stopwatch();
  }
  return options;
}
async function executeTSDown(options) {
  writeDebug(`  \u{1F680}  Running ${options.name} build`, options.workspaceConfig);
  const stopwatch = getStopwatch(`${options.name} build`);
  await tsdown({
    ...options,
    entry: options.entry,
    config: false
  });
  stopwatch();
  return options;
}
async function copyBuildAssets(options) {
  writeDebug(
    `  \u{1F4CB}  Copying asset files to output directory: ${options.outDir}`,
    options.workspaceConfig
  );
  const stopwatch = getStopwatch(`${options.name} asset copy`);
  await copyAssets(
    options.workspaceConfig,
    options.assets ?? [],
    options.outDir,
    options.projectRoot,
    options.sourceRoot,
    true,
    false
  );
  stopwatch();
  return options;
}
async function reportResults(options) {
  writeSuccess(
    `  \u{1F4E6}  The ${options.name} build completed successfully`,
    options.workspaceConfig
  );
}
async function cleanOutputPath(options) {
  if (options.clean !== false && options.workspaceConfig) {
    writeDebug(
      ` \u{1F9F9}  Cleaning ${options.name} output path: ${options.workspaceConfig}`,
      options.workspaceConfig
    );
    const stopwatch = getStopwatch(`${options.name} output clean`);
    await cleanDirectories(
      options.name,
      options.outDir,
      options.workspaceConfig
    );
    stopwatch();
  }
  return options;
}
async function build(options) {
  writeDebug(`  ${brandIcon()}   Executing Storm TSDown pipeline`);
  const stopwatch = getStopwatch("TSDown pipeline");
  try {
    const opts = Array.isArray(options) ? options : [options];
    if (opts.length === 0) {
      throw new Error("No build options were provided");
    }
    const resolved = await Promise.all(
      opts.map(async (opt) => await resolveOptions(opt))
    );
    if (resolved.length > 0) {
      await cleanOutputPath(resolved[0]);
      await generatePackageJson(resolved[0]);
      await Promise.all(
        resolved.map(async (opt) => {
          await executeTSDown(opt);
          await copyBuildAssets(opt);
          await reportResults(opt);
        })
      );
    } else {
      writeWarning(
        "  \u{1F6A7}   No options were passed to TSBuild. Please check the parameters passed to the `build` function."
      );
    }
    writeSuccess("  \u{1F3C1}  TSDown pipeline build completed successfully");
  } catch (error) {
    writeFatal(
      "Fatal errors that the build process could not recover from have occured. The build process has been terminated."
    );
    throw error;
  } finally {
    stopwatch();
  }
}

export {
  cleanOutputPath,
  build
};
