"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 __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(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/catalog-to-astro-content-directory.js
var catalog_to_astro_content_directory_exports = {};
__export(catalog_to_astro_content_directory_exports, {
  catalogToAstro: () => catalogToAstro
});
module.exports = __toCommonJS(catalog_to_astro_content_directory_exports);

// ../../node_modules/.pnpm/tsup@8.5.0_jiti@2.7.0_postcss@8.5.15_tsx@4.21.0_typescript@5.9.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js
var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();

// src/catalog-to-astro-content-directory.js
var import_glob = require("glob");
var path3 = __toESM(require("path"), 1);
var import_fs = __toESM(require("fs"), 1);
var import_url2 = require("url");
var import_node_os2 = __toESM(require("os"), 1);

// src/eventcatalog-config-file-utils.js
var import_promises = require("fs/promises");
var import_node_fs = require("fs");
var import_node_path = __toESM(require("path"), 1);
var import_uuid = require("uuid");
var import_url = require("url");
var import_node_os = require("os");
var import_gray_matter = __toESM(require("gray-matter"), 1);
async function cleanup(projectDirectory) {
  const filePath = import_node_path.default.join(projectDirectory, "eventcatalog.config.mjs");
  if ((0, import_node_fs.existsSync)(filePath)) {
    await (0, import_promises.rm)(filePath);
  }
}
var findNodeModulesDirectory = (directory) => {
  let currentDirectory = directory;
  while (true) {
    const nodeModulesDirectory = import_node_path.default.join(currentDirectory, "node_modules");
    if ((0, import_node_fs.existsSync)(nodeModulesDirectory)) {
      return nodeModulesDirectory;
    }
    const parentDirectory = import_node_path.default.dirname(currentDirectory);
    if (parentDirectory === currentDirectory) {
      return void 0;
    }
    currentDirectory = parentDirectory;
  }
};
var linkNodeModulesIntoTempDirectory = async ({ projectDirectory, tempDir }) => {
  const nodeModulesDirectory = findNodeModulesDirectory(projectDirectory);
  if (!nodeModulesDirectory) {
    return;
  }
  await (0, import_promises.symlink)(nodeModulesDirectory, import_node_path.default.join(tempDir, "node_modules"), "dir");
};
var createTemporaryConfigDirectory = async (projectDirectory) => {
  const nodeModulesDirectory = findNodeModulesDirectory(projectDirectory);
  if (nodeModulesDirectory) {
    return (0, import_promises.mkdtemp)(import_node_path.default.join(nodeModulesDirectory, ".eventcatalog-config-"));
  }
  const tempDir = await (0, import_promises.mkdtemp)(import_node_path.default.join((0, import_node_os.tmpdir)(), "eventcatalog-config-"));
  await linkNodeModulesIntoTempDirectory({ projectDirectory, tempDir });
  return tempDir;
};
var getEventCatalogConfigFile = async (projectDirectory) => {
  let tempDir;
  try {
    let configFilePath = import_node_path.default.join(projectDirectory, "eventcatalog.config.js");
    const filePath = import_node_path.default.join(projectDirectory, "package.json");
    const packageJson = JSON.parse(await (0, import_promises.readFile)(filePath, "utf-8"));
    if (packageJson?.type !== "module") {
      tempDir = await createTemporaryConfigDirectory(projectDirectory);
      configFilePath = import_node_path.default.join(tempDir, "eventcatalog.config.mjs");
      await (0, import_promises.copyFile)(import_node_path.default.join(projectDirectory, "eventcatalog.config.js"), configFilePath);
    }
    const configFileURL = `${(0, import_url.pathToFileURL)(configFilePath).href}?t=${Date.now()}`;
    const config = await import(
      /* @vite-ignore */
      configFileURL
    );
    return config.default;
  } finally {
    await cleanup(projectDirectory);
    if (tempDir) {
      await (0, import_promises.rm)(tempDir, { recursive: true, force: true });
    }
  }
};
var writeEventCatalogConfigFile = async (projectDirectory, newConfig) => {
  try {
    const configFilePath = import_node_path.default.join(projectDirectory, "eventcatalog.config.js");
    let content = await (0, import_promises.readFile)(configFilePath, "utf8");
    const startIndex = content.indexOf("export default {");
    if (startIndex === -1) {
      return;
    }
    Object.entries(newConfig).forEach(([key, value]) => {
      const valueString = JSON.stringify(value, null, 2).replace(/"/g, "'").replace(/\n/g, "\n  ");
      const keyRegex = new RegExp(`(${key}\\s*:)([^,}]+)`, "g");
      if (content.match(keyRegex)) {
        content = content.replace(keyRegex, `$1 ${valueString}`);
      } else {
        const insertPosition = content.indexOf("{", startIndex) + 1;
        content = content.slice(0, insertPosition) + `
  ${key}: ${valueString},` + content.slice(insertPosition);
      }
    });
    await (0, import_promises.writeFile)(configFilePath, content);
  } finally {
    await cleanup(projectDirectory);
  }
};
var verifyRequiredFieldsAreInCatalogConfigFile = async (projectDirectory) => {
  try {
    const config = await getEventCatalogConfigFile(projectDirectory);
    if (!config.cId) {
      await writeEventCatalogConfigFile(projectDirectory, { cId: (0, import_uuid.v4)() });
    }
  } catch (error) {
  }
};

// src/map-catalog-to-astro.js
var import_node_path2 = __toESM(require("path"), 1);
var COLLECTION_KEYS = [
  "agents",
  "events",
  "commands",
  "services",
  "domains",
  "flows",
  "pages",
  "changelogs",
  "queries",
  "channels",
  "ubiquitousLanguages",
  "dependencies"
];
function mapCatalogToAstro({ filePath, astroDir, projectDir }) {
  const relativeFilePath = removeBasePath(filePath, projectDir);
  if (isLikeC4Source(relativeFilePath)) {
    return [];
  }
  if (!isCatalogRelated(relativeFilePath)) {
    return [];
  }
  const baseTargetPaths = getBaseTargetPaths(relativeFilePath);
  const relativeTargetPath = getRelativeTargetPath(relativeFilePath);
  return baseTargetPaths.map((base) => import_node_path2.default.join(astroDir, base, relativeTargetPath));
}
function removeBasePath(fullPath, basePath) {
  const relativePath = import_node_path2.default.relative(basePath, fullPath);
  return relativePath.startsWith("..") ? fullPath : relativePath;
}
function isCollectionKey(key) {
  return COLLECTION_KEYS.includes(key);
}
function isLikeC4Source(filePath) {
  return filePath.endsWith(".c4") || filePath.endsWith(".likec4");
}
function isCatalogRelated(filePath) {
  const filePathArr = filePath.split(import_node_path2.default.sep).filter(Boolean);
  if ([
    "eventcatalog.config.js",
    // config file at root
    "eventcatalog.styles.css",
    // custom styles file at root
    "components",
    // custom components
    "snippets",
    // custom snippets
    "public",
    // public assets
    ".env",
    // env file
    ...COLLECTION_KEYS
  ].includes(filePathArr[0])) {
    return true;
  }
  return false;
}
function getBaseTargetPaths(filePath) {
  const filePathArr = filePath.split(import_node_path2.default.sep).filter(Boolean);
  if (isCollectionKey(filePathArr[0])) {
    const hasExtension = (str) => /\.[a-zA-Z0-9]{2,}$/.test(str);
    if (hasExtension(filePath)) {
      return [import_node_path2.default.join("public", "generated")];
    }
    return [import_node_path2.default.join("public", "generated")];
  }
  if (filePathArr[0] == "components") {
    return [import_node_path2.default.join("src", "custom-defined-components")];
  }
  if (filePathArr[0] == "snippets") {
    return [import_node_path2.default.join("src")];
  }
  if (filePathArr[0] == "public") {
    return [import_node_path2.default.join("public")];
  }
  return [import_node_path2.default.join("/")];
}
function getRelativeTargetPath(filePath) {
  const filePathArr = filePath.split(import_node_path2.default.sep).filter(Boolean);
  if (filePathArr[0] == "public" || filePathArr[0] == "components") {
    filePathArr.shift();
  }
  if (filePathArr[0] == "snippets") {
    return import_node_path2.default.join("snippets", ...filePathArr.slice(1));
  }
  const relativePath = [];
  for (let i = filePathArr.length - 1; i >= 0; i--) {
    relativePath.unshift(filePathArr[i]);
    if (isCollectionKey(filePathArr[i]) && filePathArr[i] != "snippets") break;
  }
  return import_node_path2.default.join(...relativePath);
}

// src/catalog-to-astro-content-directory.js
var __filename2 = (0, import_url2.fileURLToPath)(importMetaUrl);
var rootPkg = path3.resolve(path3.dirname(__filename2), "../");
var copyFiles = async (source, target) => {
  const files = await (0, import_glob.glob)(path3.join(source, "**"), {
    nodir: true,
    windowsPathsNoEscape: import_node_os2.default.platform() == "win32",
    ignore: ["node_modules/**", "**/dist/**", "**/teams", "**/users", "**/*.mdx", "**/*.md", "**/package.json", "**/Dockerfile"]
  });
  const snippets = await (0, import_glob.glob)(path3.join(source, "snippets/**/*.mdx"), {
    nodir: true,
    windowsPathsNoEscape: import_node_os2.default.platform() == "win32"
  });
  if (snippets.length > 0) {
    files.push(...snippets);
  }
  if (import_fs.default.existsSync(path3.join(source, ".env"))) {
    files.push(path3.join(source, ".env"));
  }
  for (const file of files) {
    mapCatalogToAstro({
      filePath: file,
      astroDir: target,
      projectDir: source
    }).map((astroPath) => {
      import_fs.default.cpSync(file, astroPath);
      return { oldPath: file, newPath: astroPath };
    });
  }
};
var removeGeneratedLikeC4Sources = async (target) => {
  const generatedDir = path3.join(target, "public", "generated");
  const files = await (0, import_glob.glob)(path3.join(generatedDir, "**/*.{c4,likec4}"), {
    nodir: true,
    windowsPathsNoEscape: import_node_os2.default.platform() == "win32"
  });
  for (const file of files) {
    import_fs.default.rmSync(file);
  }
};
var catalogToAstro = async (source, astroDir) => {
  const astroContentDir = path3.join(astroDir, "src/content/");
  if (import_fs.default.existsSync(astroContentDir)) import_fs.default.rmSync(astroContentDir, { recursive: true });
  import_fs.default.mkdirSync(astroContentDir);
  await verifyRequiredFieldsAreInCatalogConfigFile(source);
  if (!import_fs.default.existsSync(path3.join(source, "eventcatalog.styles.css"))) {
    import_fs.default.writeFileSync(path3.join(source, "eventcatalog.styles.css"), "");
  }
  await removeGeneratedLikeC4Sources(astroDir);
  await copyFiles(source, astroDir);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  catalogToAstro
});
