// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync(path, "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/file/constants.ts
var WINDOWS_NEWLINE_REGEX = /\r\n/g;
var CROSS_PLATFORM_NEWLINE = "\n";

// src/lib/file/fileLines.ts
import {
  existsSync as existsSync3,
  readFileSync as readFileSync2,
  writeFileSync
} from "node:fs";

// src/lib/string/empty.ts
var isEmpty = (value) => value?.trim().length === 0;
var isNotEmpty = (value) => !isEmpty(value);

// src/lib/string/union.ts
var union = (a, b) => /* @__PURE__ */ new Set([...new Set(a), ...new Set(b)]);

// src/lib/file/ReadFileSyncOptions.ts
var defaultReadFileSyncOptions = { encoding: "utf8" };

// src/lib/file/fileLines.ts
var readLines = (uri, options = defaultReadFileSyncOptions) => existsSync3(uri) ? readFileSync2(uri, options).replace(WINDOWS_NEWLINE_REGEX, () => CROSS_PLATFORM_NEWLINE).split(CROSS_PLATFORM_NEWLINE) : [];
var readNonEmptyLines = (uri, options = defaultReadFileSyncOptions) => readLines(uri, options).filter(isNotEmpty);
var writeLines = (uri, lines, options = defaultReadFileSyncOptions) => {
  const existing = existsSync3(uri) ? readFileSync2(uri, options) : void 0;
  const desired = lines.join(CROSS_PLATFORM_NEWLINE);
  if (existing !== desired) writeFileSync(uri, desired, options);
};

// src/lib/generateIgnoreFiles.ts
import chalk from "chalk";

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/generateIgnoreFiles.ts
var localeCompare = (a, b) => a.localeCompare(b);
var mergeEntries = (a, b) => [...union(a, b)].toSorted(localeCompare);
var generateIgnoreFiles = (filename2, pkg) => {
  console.log(chalk.green(`Generate ${filename2} Files`));
  const cwd = INIT_CWD();
  const pm = getPackageManager();
  const singleWorkspace = pkg != null && pkg.length > 0 ? pm.findWorkspace(pkg) : void 0;
  const workspaces = singleWorkspace ? [singleWorkspace] : pm.listWorkspaces();
  const readEntries = (location) => readNonEmptyLines(`${location}/${filename2}`);
  const writeEntries = (location, entries) => writeLines(`${location}/${filename2}`, entries);
  const results = workspaces.map(({ location, name }) => {
    try {
      writeEntries(location, mergeEntries(readEntries(cwd), readEntries(location)));
      return 0;
    } catch (ex) {
      const error = ex;
      console.error(`Generate ${filename2} Files [${name}] [${error.message}]`);
      return 1;
    }
  });
  const isSucceeded = results.every((result) => result === 0);
  return isSucceeded ? 0 : 1;
};

// 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/npmignore-gen.ts
var filename = ".npmignore";
var npmignoreGen = (pkg) => generateIgnoreFiles(filename, pkg);

// src/xy/common/npmignoreGenCommand.ts
var npmignoreGenCommand = {
  command: "npmignore-gen",
  describe: "NpmIgnore Gen - Generate .npmignore files",
  handler: async (argv) => {
    if (Boolean(argv.verbose)) console.log("NpmIgnore Gen");
    await withEnvelope("npmignore-gen", () => npmignoreGen());
  }
};
export {
  npmignoreGenCommand
};
//# sourceMappingURL=npmignoreGenCommand.mjs.map
