#!/usr/bin/env node
import {
  BaseCommand
} from "../../chunk-SRFNNOLC.js";
import {
  ensureDir,
  getErrorMessage,
  glob,
  pluginManifestSchema,
  readFileSafe,
  setVerbose,
  verbose,
  warn,
  writeFile
} from "../../chunk-473YHDYQ.js";
import {
  DEFAULT_BRANDING,
  DEFAULT_PLUGIN_NAME,
  DEFAULT_VERSION,
  MAX_PLUGIN_FILE_SIZE,
  PLUGIN_MANIFEST_DIR
} from "../../chunk-FVN5PFFY.js";
import {
  init_esm_shims
} from "../../chunk-DHET7RCE.js";

// src/cli/commands/build/marketplace.ts
init_esm_shims();
import { Flags } from "@oclif/core";
import path2 from "path";
import { sortBy as sortBy2 } from "remeda";

// src/cli/lib/marketplace-generator.ts
init_esm_shims();
import path from "path";
import { sortBy } from "remeda";
var PLUGIN_MANIFEST_PATH = ".claude-plugin/plugin.json";
var MARKETPLACE_SCHEMA_URL = "https://anthropic.com/claude-code/marketplace.schema.json";
var CATEGORY_PATTERNS = [
  { pattern: /^web-/, category: "web" },
  { pattern: /^api-/, category: "api" },
  { pattern: /^cli-/, category: "cli" },
  { pattern: /^meta-/, category: "methodology" },
  { pattern: /^infra-/, category: "infra" },
  { pattern: /^mobile-/, category: "mobile" },
  { pattern: /^security-/, category: "security" }
];
function inferCategoryFromPluginName(pluginName) {
  for (const { pattern, category } of CATEGORY_PATTERNS) {
    if (pattern.test(pluginName)) {
      return category;
    }
  }
  return void 0;
}
async function readPluginManifest(pluginDir) {
  const manifestPath = path.join(pluginDir, PLUGIN_MANIFEST_PATH);
  try {
    const content = await readFileSafe(manifestPath, MAX_PLUGIN_FILE_SIZE);
    return pluginManifestSchema.parse(JSON.parse(content));
  } catch (error) {
    verbose(`Failed to read plugin manifest at '${manifestPath}': ${getErrorMessage(error)}`);
    return null;
  }
}
function convertManifestToMarketplacePlugin(manifest, pluginRoot, pluginDirName) {
  const category = inferCategoryFromPluginName(manifest.name);
  const plugin = {
    name: manifest.name,
    source: `./${pluginRoot}/${pluginDirName}`,
    description: manifest.description,
    version: manifest.version,
    author: manifest.author,
    keywords: manifest.keywords
  };
  if (category) {
    plugin.category = category;
  }
  return plugin;
}
async function generateMarketplace(pluginsDir, options) {
  verbose(`Scanning plugins directory: ${pluginsDir}`);
  const manifestFiles = await glob(`**/${PLUGIN_MANIFEST_PATH}`, pluginsDir);
  verbose(`Found ${manifestFiles.length} plugin manifests`);
  const plugins = [];
  for (const manifestFile of manifestFiles) {
    const pluginDirName = manifestFile.split("/")[0];
    const pluginDir = path.join(pluginsDir, pluginDirName);
    const manifest = await readPluginManifest(pluginDir);
    if (!manifest) {
      warn(`Could not read plugin manifest: '${manifestFile}'`);
      continue;
    }
    const plugin = convertManifestToMarketplacePlugin(
      manifest,
      options.pluginRoot.replace(/^\.\//, ""),
      pluginDirName
    );
    plugins.push(plugin);
    verbose(`  [OK] ${plugin.name}`);
  }
  const sortedPlugins = sortBy(plugins, (p) => p.name);
  const marketplace = {
    $schema: MARKETPLACE_SCHEMA_URL,
    name: options.name,
    version: options.version ?? "1.0.0",
    owner: {
      name: options.ownerName
    },
    metadata: {
      pluginRoot: options.pluginRoot
    },
    plugins: sortedPlugins
  };
  if (options.description) {
    marketplace.description = options.description;
  }
  if (options.ownerEmail) {
    marketplace.owner.email = options.ownerEmail;
  }
  return marketplace;
}
async function writeMarketplace(outputPath, marketplace) {
  await ensureDir(path.dirname(outputPath));
  const content = `${JSON.stringify(marketplace, null, 2)}
`;
  await writeFile(outputPath, content);
}
function getMarketplaceStats(marketplace) {
  const byCategory = {};
  for (const plugin of marketplace.plugins) {
    const category = plugin.category ?? "uncategorized";
    byCategory[category] = (byCategory[category] ?? 0) + 1;
  }
  return {
    total: marketplace.plugins.length,
    byCategory
  };
}

// src/cli/commands/build/marketplace.ts
var DEFAULT_PLUGINS_DIR = "dist/plugins";
var DEFAULT_OUTPUT_FILE = `${PLUGIN_MANIFEST_DIR}/marketplace.json`;
var DEFAULT_DESCRIPTION = "Community skills and stacks for Claude Code";
var DEFAULT_OWNER_NAME = DEFAULT_BRANDING.NAME;
var DEFAULT_OWNER_EMAIL = `hello@${DEFAULT_PLUGIN_NAME}.com`;
var BuildMarketplace = class _BuildMarketplace extends BaseCommand {
  static summary = "Generate marketplace.json from built plugins (requires skills repo)";
  static description = "Generate marketplace.json from built plugins. This command scans the plugins directory and generates a marketplace manifest file.";
  static examples = [
    "<%= config.bin %> <%= command.id %>",
    "<%= config.bin %> <%= command.id %> --plugins-dir dist/stacks",
    "<%= config.bin %> <%= command.id %> --output .claude-plugin/market.json",
    "<%= config.bin %> <%= command.id %> --name my-marketplace --version 2.0.0"
  ];
  static flags = {
    ...BaseCommand.baseFlags,
    "plugins-dir": Flags.string({
      char: "p",
      description: "Plugins directory",
      default: DEFAULT_PLUGINS_DIR
    }),
    output: Flags.string({
      char: "o",
      description: "Output file",
      default: DEFAULT_OUTPUT_FILE
    }),
    name: Flags.string({
      description: "Marketplace name",
      default: DEFAULT_PLUGIN_NAME
    }),
    version: Flags.string({
      description: "Marketplace version",
      default: DEFAULT_VERSION
    }),
    description: Flags.string({
      description: "Marketplace description",
      default: DEFAULT_DESCRIPTION
    }),
    "owner-name": Flags.string({
      description: "Owner name",
      default: DEFAULT_OWNER_NAME
    }),
    "owner-email": Flags.string({
      description: "Owner email",
      default: DEFAULT_OWNER_EMAIL
    }),
    verbose: Flags.boolean({
      char: "v",
      description: "Enable verbose logging",
      default: false
    })
  };
  async run() {
    const { flags } = await this.parse(_BuildMarketplace);
    setVerbose(flags.verbose);
    const projectRoot = process.cwd();
    const pluginsDir = path2.resolve(projectRoot, flags["plugins-dir"]);
    const outputPath = path2.resolve(projectRoot, flags.output);
    this.log("");
    this.log("Generating marketplace.json");
    this.log(`  Plugins directory: ${pluginsDir}`);
    this.log(`  Output file: ${outputPath}`);
    this.log("");
    try {
      this.log("Scanning plugins...");
      const marketplace = await generateMarketplace(pluginsDir, {
        name: flags.name,
        version: flags.version,
        description: flags.description,
        ownerName: flags["owner-name"],
        ownerEmail: flags["owner-email"],
        pluginRoot: `./${flags["plugins-dir"]}`
      });
      const stats = getMarketplaceStats(marketplace);
      this.log(`Found ${stats.total} plugins`);
      this.log("");
      this.log("Category breakdown:");
      const sortedCategories = sortBy2(Object.entries(stats.byCategory), ([, count]) => -count);
      for (const [category, count] of sortedCategories) {
        this.log(`  ${category}: ${count}`);
      }
      this.log("Writing marketplace.json...");
      await writeMarketplace(outputPath, marketplace);
      this.log(`Wrote ${outputPath}`);
      this.log("");
      this.log("Sample plugins:");
      const sampleSize = 5;
      for (const plugin of marketplace.plugins.slice(0, sampleSize)) {
        const version = plugin.version ? `v${plugin.version}` : "";
        const category = plugin.category ? `[${plugin.category}]` : "";
        this.log(`  ${plugin.name} ${version} ${category}`);
        if (plugin.description) {
          this.log(`    ${plugin.description}`);
        }
      }
      if (marketplace.plugins.length > sampleSize) {
        this.log(`  ... and ${marketplace.plugins.length - sampleSize} more`);
      }
      this.log("");
      this.logSuccess(`Marketplace generated with ${stats.total} plugins!`);
      this.log("");
    } catch (error) {
      this.log("Generation failed");
      this.handleError(error);
    }
  }
};
export {
  BuildMarketplace as default
};
//# sourceMappingURL=marketplace.js.map