// src/lib/copyAssetFiles.ts
import { copyFileSync, mkdirSync } from "node:fs";
import path from "node:path/posix";
import { globSync } from "glob";
var ASSET_PATTERNS = [
  "**/*.jpg",
  "**/*.png",
  "**/*.gif",
  "**/*.svg",
  "**/*.webp",
  "**/*.sass",
  "**/*.scss",
  "**/*.css"
];
function copyAssetFiles(srcDir, destDir) {
  const matches = globSync(ASSET_PATTERNS, { cwd: srcDir, nodir: true });
  const copied = [];
  for (const relativePath of matches) {
    const from = path.join(srcDir, relativePath);
    const to = path.join(destDir, relativePath);
    mkdirSync(path.dirname(to), { recursive: true });
    copyFileSync(from, to);
    copied.push(to);
  }
  return copied;
}

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync as globSync2 } from "glob";
function readJsonFile(path3) {
  if (!existsSync(path3)) return void 0;
  try {
    return JSON.parse(readFileSync(path3, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH.resolve(cwd, "package.json"));
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!(packageManager != null && packageManager.length > 0)) return void 0;
  return packageManager.split("@", 1)[0];
}

// src/pm/detectPackageManager.ts
import { existsSync as existsSync2 } from "node:fs";
var knownPackageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
function detectPackageManager() {
  const packageManager = detectPackageManagerFromPackageJson();
  if (packageManager != null && packageManager.length > 0 && knownPackageManagers.has(packageManager)) {
    return packageManager;
  }
  if (existsSync2("pnpm-lock.yaml") || existsSync2("pnpm-workspace.yaml")) return "pnpm";
  if (existsSync2("bun.lock") || existsSync2("bun.lockb")) return "bun";
  if (existsSync2("yarn.lock") || existsSync2(".yarnrc.yml")) return "yarn";
  if (existsSync2("package-lock.json") || existsSync2("npm-shrinkwrap.json")) return "npm";
  return "yarn";
}

// src/pm/registry.ts
var implementations = /* @__PURE__ */ new Map();
function getPackageManager(name) {
  const pmName = name ?? detectPackageManager();
  const pm = implementations.get(pmName);
  if (!pm) {
    throw new Error(
      `No package manager implementation registered for "${pmName}". Ensure registerPackageManager() has been called before getPackageManager().`
    );
  }
  return pm;
}

// src/lib/reporting/runWithEnvelope.ts
import { performance as performance2 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var reporterState = {
  currentCommand: "unknown",
  isEnvelopeEmitted: false,
  isJsonModeEnabled: false,
  isStrictModeEnabled: false,
  originalStdoutWrite: void 0,
  startTime: 0
};
function isJsonMode() {
  return reporterState.isJsonModeEnabled;
}
function setCurrentCommand(name) {
  reporterState.currentCommand = name;
  reporterState.startTime = performance.now();
  reporterState.isEnvelopeEmitted = false;
}
function emitJson(envelope) {
  if (reporterState.isEnvelopeEmitted) return;
  reporterState.isEnvelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (reporterState.originalStdoutWrite) {
    reporterState.originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

// src/lib/reporting/runWithEnvelope.ts
async function runWithEnvelope(command, action) {
  setCurrentCommand(command);
  const start = performance2.now();
  let exitCode;
  let envelope;
  try {
    const ret = await action();
    if (typeof ret === "number") {
      exitCode = ret;
    } else {
      exitCode = ret.exitCode;
      envelope = ret.envelope;
    }
  } catch (ex) {
    exitCode = 1;
    const message = ex instanceof Error ? ex.message : String(ex);
    envelope = {
      errorCount: 1,
      errors: [{ message }]
    };
    if (!isJsonMode()) {
      console.error(message);
    }
  }
  if (isJsonMode()) {
    emitJson({
      command,
      data: envelope?.data,
      durationMs: Math.round(performance2.now() - start),
      errorCount: envelope?.errorCount ?? (exitCode === 0 ? 0 : 1),
      errors: envelope?.errors,
      exitCode,
      schemaVersion: 1,
      success: exitCode === 0,
      warningCount: envelope?.warningCount ?? 0,
      warnings: envelope?.warnings
    });
  }
  return exitCode;
}
async function withEnvelope(command, action) {
  process.exitCode = await runWithEnvelope(command, action);
}

// src/actions/copy-assets.ts
import path2 from "node:path/posix";
import chalk from "chalk";
var copyPackageTargetAssets = async (target, name, location) => {
  try {
    const srcDir = path2.join(process.cwd(), location, "src");
    const destDir = path2.join(srcDir, "..", "dist", target);
    const values = copyAssetFiles(srcDir, destDir);
    for (const value of values) {
      console.log(`${value.split("/").pop()} => ./dist/${target}`);
    }
    return 0;
  } catch (reason) {
    console.log(`Copy Failed: ${name}: ${String(reason)}`);
    return 1;
  }
};
var copyTargetAssets = async (target, pkg) => {
  const workspaces = getPackageManager().listWorkspaces();
  console.log(chalk.green(`Copying Assets [${target.toUpperCase()}]`));
  const workspaceList = workspaces.filter(({ name }) => {
    return pkg === void 0 || name === pkg;
  });
  if (workspaceList.length === 0) {
    console.error(`Package not found [${pkg}]`);
  } else {
    const results = await Promise.all(
      workspaceList.map(async (workspace) => {
        const { location, name } = workspace;
        return await copyPackageTargetAssets(target, name, location);
      })
    );
    return results.reduce((prev, result) => prev || result, 0);
  }
  return 0;
};
var copyAssets = async ({ target, pkg }) => {
  switch (target) {
    case "esm": {
      return await copyTargetAssets("esm", pkg);
    }
    case "cjs": {
      return await copyTargetAssets("cjs", pkg);
    }
    default: {
      return await copyTargetAssets("esm", pkg) || await copyTargetAssets("cjs", pkg);
    }
  }
};

// src/xy/build/copyAssetsCommand.ts
var copyAssetsCommand = {
  command: "copy-assets [package]",
  describe: "Copy Assets - Copy the assets from src to dist",
  builder: (yargs) => {
    return yargs.positional("package", { describe: "Specific package to copy assets" });
  },
  handler: async (argv) => {
    if (argv.verbose) console.log(`Copying Assets: ${argv.package ?? "all"}`);
    await withEnvelope("copy-assets", () => copyAssets({ pkg: argv.package }));
  }
};
export {
  copyAssetsCommand
};
//# sourceMappingURL=copyAssetsCommand.mjs.map
