// src/xy/lint/lint/index.ts
import chalk8 from "chalk";

// src/lib/checkResult.ts
import chalk from "chalk";
var checkResult = (name, result, level = "error", exitOnFail = false) => {
  if (result) {
    const exiting = exitOnFail ? "[Exiting Process]" : "[Continuing]";
    const chalkFunc = level === "error" ? chalk.red : chalk.yellow;
    console[level](chalkFunc(`${name} had ${result} failures ${exiting}`));
    if (exitOnFail) {
      process.exit(result);
    }
  }
};

// src/lib/concurrency.ts
import { AsyncLocalStorage } from "node:async_hooks";
var outputStorage = new AsyncLocalStorage();
var captureInstalled = false;
function installOutputCapture() {
  if (captureInstalled) return;
  captureInstalled = true;
  const originalStdoutWrite2 = process.stdout.write.bind(process.stdout);
  const originalStderrWrite = process.stderr.write.bind(process.stderr);
  function intercept(original) {
    return function(chunk, ...args) {
      const buffer = outputStorage.getStore();
      if (buffer) {
        buffer.push(typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk));
        return true;
      }
      return original(chunk, ...args);
    };
  }
  process.stdout.write = intercept(originalStdoutWrite2);
  process.stderr.write = intercept(originalStderrWrite);
}
async function runWithConcurrency(items, concurrency, fn) {
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      await fn(items[i]);
    }
  }
  await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, () => worker()));
}

// src/lib/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// src/lib/packageManagerRuntime.ts
import fs from "node:fs";
import chalk2 from "chalk";
var DISPLAY_NAMES = {
  bun: "Bun",
  npm: "npm",
  pnpm: "pnpm",
  yarn: "Yarn"
};
var MAC_INSTALL_COMMANDS = {
  bun: "brew install oven-sh/bun/bun",
  npm: "brew install node",
  pnpm: "brew install pnpm",
  yarn: "brew install yarn"
};
function currentPlatform() {
  if (process.platform === "darwin" || process.platform === "linux" || process.platform === "win32") {
    return process.platform;
  }
  return "unknown";
}
function askYesNo(question) {
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
    return false;
  }
  process.stdout.write(question);
  const buffer = Buffer.alloc(1024);
  const bytesRead = fs.readSync(process.stdin.fd, buffer, 0, buffer.length, null);
  const answer = buffer.toString("utf8", 0, bytesRead).trim().toLowerCase();
  return answer === "y" || answer === "yes";
}
function isCommandInstalled(command) {
  const result = spawnSync(command, ["--version"], {
    encoding: "utf8",
    stdio: "ignore"
  });
  return !result.error && result.status === 0;
}
function isPackageManagerInstalled(pm) {
  return isCommandInstalled(pm);
}
function getPackageManagerInstallPlan(pm, platform = currentPlatform()) {
  const displayName = DISPLAY_NAMES[pm];
  if (platform === "darwin") {
    const command = MAC_INSTALL_COMMANDS[pm];
    return {
      command,
      manualInstructions: [
        `Install ${displayName} with: ${command}`
      ],
      packageManager: pm,
      platform,
      supported: true
    };
  }
  if (platform === "linux") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Linux yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  if (platform === "win32") {
    return {
      manualInstructions: [
        `Automatic installation for ${displayName} is not implemented on Windows yet.`,
        `Install ${displayName} manually and re-run the command.`
      ],
      packageManager: pm,
      platform,
      supported: false
    };
  }
  return {
    manualInstructions: [
      `Automatic installation for ${displayName} is not implemented on ${platform} yet.`,
      `Install ${displayName} manually and re-run the command.`
    ],
    packageManager: pm,
    platform,
    supported: false
  };
}
function printManualInstructions(plan, context) {
  console.error(chalk2.yellow(`${DISPLAY_NAMES[plan.packageManager]} is required for "${context.operation}".`));
  for (const line of plan.manualInstructions) {
    console.error(chalk2.gray(`  ${line}`));
  }
}
function installWithHomebrew(pm, cwd) {
  const command = MAC_INSTALL_COMMANDS[pm];
  const result = spawnSync("brew", command.replace("brew ", "").split(" "), {
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  return result.status === 0;
}
function ensurePackageManagerInstalled(pm, context) {
  if (isPackageManagerInstalled(pm)) return true;
  const plan = getPackageManagerInstallPlan(pm, context.platform ?? currentPlatform());
  const displayName = DISPLAY_NAMES[pm];
  console.error(chalk2.yellow(`${context.operation} requires ${displayName}, but it is not installed.`));
  if (!plan.supported) {
    printManualInstructions(plan, context);
    return false;
  }
  if (!isCommandInstalled("brew")) {
    console.error(chalk2.yellow("Homebrew is not installed, so automatic installation is unavailable."));
    console.error(chalk2.gray("  Install Homebrew from https://brew.sh and then run:"));
    console.error(chalk2.gray(`  ${plan.command}`));
    return false;
  }
  const confirmed = askYesNo(chalk2.cyan(`Install ${displayName} with Homebrew now? [y/N] `));
  if (!confirmed) {
    console.error(chalk2.gray(`Skipping install. Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk2.cyan(`Installing ${displayName} via Homebrew...
`));
  if (!installWithHomebrew(pm, context.cwd)) {
    console.error(chalk2.red(`Homebrew failed to install ${displayName}.`));
    console.error(chalk2.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  if (!isPackageManagerInstalled(pm)) {
    console.error(chalk2.red(`${displayName} still does not appear to be installed after Homebrew completed.`));
    console.error(chalk2.gray(`Run "${plan.command}" manually and then retry.`));
    return false;
  }
  console.error(chalk2.green(`${displayName} installed successfully.`));
  return true;
}
function failureResult() {
  return {
    output: ["", ""],
    pid: 0,
    signal: null,
    status: 1,
    stderr: "",
    stdout: ""
  };
}
function spawnPackageManagerSync(pm, args, options) {
  if (!ensurePackageManagerInstalled(pm, options.context)) {
    return failureResult();
  }
  return spawnSync(pm, args, { encoding: "utf8", ...options });
}

// src/pm/workspaces.ts
import { existsSync, readFileSync } from "node:fs";
import PATH from "node:path";
import { globSync } 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) return void 0;
  return packageManager.split("@")[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 && 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/processEx.ts
import chalk3 from "chalk";

// src/lib/withError.ts
var withError = (ex, closure, predicate = (ex2) => !!ex2.name && !!ex2.message) => {
  return predicate(ex) ? closure(ex) : void 0;
};

// src/lib/withErrnoException.ts
var withErrnoException = (ex, closure) => {
  return withError(ex, closure, (ex2) => ex2.errno !== void 0);
};

// src/lib/processEx.ts
var processEx = (ex) => {
  const error = typeof ex === "string" ? new Error(ex) : ex;
  const exitCode = withErrnoException(error, (error2) => {
    if (error2.code === "ENOENT") {
      console.error(chalk3.red(`'${error2.path}' not found.`));
    } else {
      console.error(chalk3.red(`Errno: ${error2.code}`));
    }
    return error2.errno ?? -1;
  }) ?? withError(error, (error2) => {
    console.error(chalk3.red(`${error2.name}: ${error2.message}`));
    return -1;
  }) ?? (() => {
    console.error(chalk3.red(`Unexpected Error: ${JSON.stringify(ex, null, 2)}`));
    return -1;
  })();
  process.exit(process.exitCode ?? exitCode);
};

// src/lib/safeExit.ts
var safeExit = (func, exitOnFail = true) => {
  try {
    const result = func();
    if (result && exitOnFail) {
      process.exit(result);
    }
    return result;
  } catch (ex) {
    return processEx(ex);
  }
};

// src/lib/toolchainVersion.ts
import { readFileSync as readFileSync2 } from "node:fs";
import { createRequire } from "node:module";
var require2 = createRequire(import.meta.url);
function bundledToolchainVersion() {
  const pkgPath = require2.resolve("@xylabs/toolchain/package.json");
  const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
  if (!pkg.version) throw new Error("Could not read @xylabs/toolchain version");
  return pkg.version;
}
function bundledToolchainRange() {
  return `^${bundledToolchainVersion()}`;
}

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

// src/lib/packageName.ts
import { readFileSync as readFileSync3 } from "node:fs";
import path from "node:path";
function packageName() {
  if (process.env.npm_package_name) {
    return process.env.npm_package_name;
  }
  try {
    const pkgPath = path.join(INIT_CWD(), "package.json");
    const pkg = JSON.parse(readFileSync3(pkgPath, "utf8"));
    return pkg.name;
  } catch {
    return void 0;
  }
}

// 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 jsonMode = false;
var strictMode = false;
var originalStdoutWrite;
var envelopeEmitted = false;
var currentCommand = "unknown";
var startTime = 0;
function isJsonMode() {
  return jsonMode;
}
function isStrictMode() {
  return strictMode || process.env.XY_STRICT === "1";
}
function setCurrentCommand(name) {
  currentCommand = name;
  startTime = performance.now();
  envelopeEmitted = false;
}
function emitJson(envelope) {
  if (envelopeEmitted) return;
  envelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (originalStdoutWrite) {
    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/lib/runInstall.ts
import chalk4 from "chalk";
function runInstall(cwd) {
  const pm = detectPackageManager();
  console.log(chalk4.gray(`Running ${pm} install...`));
  const result = spawnPackageManagerSync(pm, ["install"], {
    context: { cwd, operation: `Run ${pm} install` },
    cwd,
    encoding: "utf8",
    stdio: "inherit"
  });
  if (result.status !== 0) {
    console.warn(chalk4.yellow(`${pm} install failed`));
    return false;
  }
  console.log(chalk4.green("Dependencies installed"));
  return true;
}

// src/lib/runSteps.ts
import { existsSync as existsSync3 } from "node:fs";
import chalk5 from "chalk";
var packageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
var runSteps = (name, steps, exitOnFail = true, messages) => {
  return safeExit(() => {
    const pkgName = packageName();
    console.log(chalk5.green(`${name} [${pkgName}]`));
    let totalStatus = 0;
    for (const [i, [command, args, config]] of steps.entries()) {
      if (messages?.[i]) {
        console.log(chalk5.gray(messages?.[i]));
      }
      const argList = Array.isArray(args) ? args : args.split(" ");
      if (command === "node" && !existsSync3(argList[0])) {
        throw new Error(`File not found [${argList[0]}]`);
      }
      if (packageManagers.has(command) && !ensurePackageManagerInstalled(command, { operation: `${name}: ${command} ${Array.isArray(args) ? args.join(" ") : args}`.trim() })) {
        checkResult(name, 1, "error", exitOnFail);
        totalStatus += 1;
        continue;
      }
      const status = spawnSync(command, Array.isArray(args) ? args : args.split(" "), {
        ...config,
        encoding: "utf8",
        // Merge per-step env on top so callers can supply overrides
        // (e.g. NODE_OPTIONS=--max-old-space-size=...); process.env still
        // seeds the common case so FORCE_COLOR etc. survive.
        env: {
          FORCE_COLOR: "3",
          ...process.env,
          ...config?.env
        },
        stdio: isJsonMode() ? ["inherit", 2, 2] : "inherit"
      }).status ?? 0;
      checkResult(name, status, "error", exitOnFail);
      totalStatus += status ?? 0;
    }
    return totalStatus;
  }, !!exitOnFail);
};

// src/actions/lintNext.ts
import path2 from "node:path";
import chalk6 from "chalk";
import { ESLint } from "eslint";
var dumpMessages = (lintResults) => {
  const colors = ["white", "yellow", "red"];
  const severity = ["none", "warning", "error"];
  for (const lintResult of lintResults) {
    if (lintResult.messages.length > 0) {
      console.log(chalk6.gray(`
${lintResult.filePath}`));
      for (const message of lintResult.messages) {
        console.log(
          chalk6.gray(`	${message.line}:${message.column}`),
          chalk6[colors[message.severity]](`	${severity[message.severity]}`),
          chalk6.white(`	${message.message}`),
          chalk6.gray(`	${message.ruleId}`)
        );
      }
    }
  }
};
async function lintOnePackage({
  cache,
  cwd,
  fix,
  verbose
}) {
  const engine = new ESLint({
    cache,
    cacheLocation: path2.join(cwd, ".eslintcache"),
    cacheStrategy: "content",
    cwd,
    fix,
    warnIgnored: false
  });
  const lintResults = await engine.lintFiles(".");
  dumpMessages(lintResults);
  if (fix) {
    await ESLint.outputFixes(lintResults);
  }
  const errors = lintResults.reduce((sum, r) => sum + r.errorCount, 0);
  const warnings = lintResults.reduce((sum, r) => sum + r.warningCount, 0);
  const files = lintResults.length;
  if (verbose) {
    const filesColor = files < 100 ? "green" : files < 1e3 ? "yellow" : "red";
    console.log(chalk6.white(`  ${chalk6[filesColor](files)} files linted`));
  }
  return {
    errors,
    files,
    warnings
  };
}
async function lintNext({
  cache = false,
  fix = false,
  jobs,
  pkg,
  verbose = false
}) {
  const rootDir = INIT_CWD();
  const pm = getPackageManager();
  const allWorkspaces = pm.listWorkspaces();
  const workspaces = pkg ? allWorkspaces.filter((ws) => ws.name === pkg) : allWorkspaces;
  if (workspaces.length === 0) {
    console.log(chalk6.red(pkg ? `Package "${pkg}" not found` : "No workspaces found"));
    return 1;
  }
  const concurrency = jobs;
  const label = fix ? "Fix" : "Lint";
  installOutputCapture();
  const results = Array.from(
    { length: workspaces.length },
    () => ({
      errors: 0,
      files: 0,
      output: [],
      pkg: "",
      timeMs: 0,
      warnings: 0
    })
  );
  await runWithConcurrency(
    workspaces.map((ws, i) => ({ i, ws })),
    concurrency,
    async ({ i, ws }) => {
      const output = [];
      await outputStorage.run(output, async () => {
        const pkgStart = Date.now();
        const absCwd = path2.resolve(rootDir, ws.location);
        console.log(chalk6.green(`${label} [${ws.name}]`));
        try {
          const {
            errors,
            files,
            warnings
          } = await lintOnePackage({
            cache,
            cwd: absCwd,
            fix,
            verbose
          });
          const timeMs = Date.now() - pkgStart;
          results[i] = {
            errors,
            files,
            output,
            pkg: ws.name,
            timeMs,
            warnings
          };
        } catch (ex) {
          output.push(chalk6.red(`${label} failed for ${ws.name}: ${ex.message}
`));
          results[i] = {
            errors: 1,
            files: 0,
            output,
            pkg: ws.name,
            timeMs: Date.now() - pkgStart,
            warnings: 0
          };
        }
      });
    }
  );
  let totalErrors = 0;
  let totalWarnings = 0;
  let totalFiles = 0;
  for (const result of results) {
    for (const line of result.output) {
      process.stdout.write(line);
    }
    totalErrors += result.errors;
    totalWarnings += result.warnings;
    totalFiles += result.files;
  }
  const errColor = totalErrors > 0 ? "red" : "green";
  const warnColor = totalWarnings > 0 ? "yellow" : "green";
  console.log(
    chalk6[errColor](`${totalErrors} errors`) + chalk6.gray(", ") + chalk6[warnColor](`${totalWarnings} warnings`) + chalk6.gray(` across ${totalFiles} files in ${workspaces.length} packages`)
  );
  return totalErrors + (isStrictMode() ? totalWarnings : 0);
}

// src/actions/lint.ts
var lintPackage = ({
  pkg,
  fix,
  verbose
}) => {
  const pm = getPackageManager();
  return runSteps(`${fix ? "Fix" : "Lint"} [${pkg}]`, [
    pm.runInWorkspace(pkg, fix ? "package-fix" : verbose ? "package-lint-verbose" : "package-lint")
  ]);
};
var lint = ({
  cache,
  fix,
  jobs,
  next,
  pkg,
  verbose
}) => {
  if (next) {
    return lintNext({
      cache,
      fix,
      jobs,
      pkg,
      verbose
    });
  }
  return pkg === void 0 ? lintAllPackages({ fix }) : lintPackage({
    pkg,
    fix,
    verbose
  });
};
var lintAllPackages = ({ fix = false } = {}) => {
  const fixOptions = fix ? ["--fix"] : [];
  const strictOptions = isStrictMode() ? ["--max-warnings", "0"] : [];
  return runSteps(`${fix ? "Fix" : "Lint"} [All-Packages]`, [
    ["eslint", ["--cache", "--cache-location", ".eslintcache", "--cache-strategy", "content", ...fixOptions, ...strictOptions]]
  ]);
};

// src/actions/lint-init.ts
import {
  existsSync as existsSync4,
  readFileSync as readFileSync4,
  unlinkSync,
  writeFileSync
} from "node:fs";
import PATH2 from "node:path";
import { createInterface } from "node:readline";
import chalk7 from "chalk";
import { globSync as globSync2 } from "glob";
function askConfirmation(question) {
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
    });
  });
}
var DISALLOWED_IMPORTS_XYLABS = [
  "@xylabs/api",
  "@xylabs/array",
  "@xylabs/arraybuffer",
  "@xylabs/assert",
  "@xylabs/base",
  "@xylabs/bignumber",
  "@xylabs/buffer",
  "@xylabs/creatable",
  "@xylabs/decimal-precision",
  "@xylabs/delay",
  "@xylabs/enum",
  "@xylabs/error",
  "@xylabs/eth-address",
  "@xylabs/events",
  "@xylabs/exists",
  "@xylabs/fetch",
  "@xylabs/forget",
  "@xylabs/function-name",
  "@xylabs/hex",
  "@xylabs/logger",
  "@xylabs/object",
  "@xylabs/platform",
  "@xylabs/profile",
  "@xylabs/promise",
  "@xylabs/retry",
  "@xylabs/set",
  "@xylabs/static-implements",
  "@xylabs/storage",
  "@xylabs/telemetry",
  "@xylabs/telemetry-exporter",
  "@xylabs/timer",
  "@xylabs/typeof",
  "@xylabs/url",
  "@xylabs/zod"
];
var DISALLOWED_IMPORTS_XYO = [
  "@xyo-network/account",
  "@xyo-network/account-model",
  "@xyo-network/address-payload-plugin",
  "@xyo-network/api",
  "@xyo-network/api-location-diviner",
  "@xyo-network/api-models",
  "@xyo-network/archivist",
  "@xyo-network/archivist-abstract",
  "@xyo-network/archivist-memory",
  "@xyo-network/archivist-model",
  "@xyo-network/archivist-wrapper",
  "@xyo-network/boundwitness",
  "@xyo-network/boundwitness-builder",
  "@xyo-network/boundwitness-loader",
  "@xyo-network/boundwitness-model",
  "@xyo-network/boundwitness-validator",
  "@xyo-network/boundwitness-wrapper",
  "@xyo-network/bridge",
  "@xyo-network/bridge-abstract",
  "@xyo-network/bridge-model",
  "@xyo-network/bridge-wrapper",
  "@xyo-network/config-payload-plugin",
  "@xyo-network/core",
  "@xyo-network/core-payload-plugins",
  "@xyo-network/crypto",
  "@xyo-network/data",
  "@xyo-network/diviner",
  "@xyo-network/diviner-abstract",
  "@xyo-network/diviner-model",
  "@xyo-network/diviner-wrapper",
  "@xyo-network/dns",
  "@xyo-network/domain-payload-plugin",
  "@xyo-network/elliptic",
  "@xyo-network/hash",
  "@xyo-network/huri",
  "@xyo-network/id-payload-plugin",
  "@xyo-network/key-model",
  "@xyo-network/manifest",
  "@xyo-network/manifest-model",
  "@xyo-network/manifest-wrapper",
  "@xyo-network/metamask-connector",
  "@xyo-network/module",
  "@xyo-network/module-abstract",
  "@xyo-network/module-event-emitter",
  "@xyo-network/module-factory-locator",
  "@xyo-network/module-model",
  "@xyo-network/module-resolver",
  "@xyo-network/module-wrapper",
  "@xyo-network/modules",
  "@xyo-network/network",
  "@xyo-network/node",
  "@xyo-network/node-abstract",
  "@xyo-network/node-memory",
  "@xyo-network/node-model",
  "@xyo-network/node-wrapper",
  "@xyo-network/payload",
  "@xyo-network/payload-builder",
  "@xyo-network/payload-model",
  "@xyo-network/payload-plugin",
  "@xyo-network/payload-validator",
  "@xyo-network/payload-wrapper",
  "@xyo-network/payloadset-plugin",
  "@xyo-network/previous-hash-store",
  "@xyo-network/protocol",
  "@xyo-network/quadkey",
  "@xyo-network/query-payload-plugin",
  "@xyo-network/schema-cache",
  "@xyo-network/schema-name-validator",
  "@xyo-network/schema-payload-plugin",
  "@xyo-network/sdk-protocol-js",
  "@xyo-network/sdk-utils",
  "@xyo-network/sentinel",
  "@xyo-network/sentinel-abstract",
  "@xyo-network/sentinel-memory",
  "@xyo-network/sentinel-model",
  "@xyo-network/sentinel-wrapper",
  "@xyo-network/value-payload-plugin",
  "@xyo-network/wallet",
  "@xyo-network/wallet-model",
  "@xyo-network/wasm",
  "@xyo-network/witness",
  "@xyo-network/witness-abstract",
  "@xyo-network/witness-model",
  "@xyo-network/witness-wrapper"
];
var XYLABS_SDK_IMPORT_MESSAGE = "Use '@xylabs/sdk-js' instead.";
var XYO_SDK_IMPORT_MESSAGE = "Use '@xyo-network/sdk-js' instead.";
function getRequiredDevDependencies(react) {
  const configPkg = react ? "@xylabs/eslint-config-react-flat" : "@xylabs/eslint-config-flat";
  return {
    [configPkg]: bundledToolchainRange(),
    eslint: "^10.0.0"
  };
}
function formatDisallowedArray(name, imports, message) {
  const items = imports.map((i) => `  { name: '${i}', message: "${message}" },`).join("\n");
  return `const ${name} = [
${items}
]`;
}
function generateEslintConfig({
  react,
  useXyLabsBarrel,
  useXyoBarrel
}) {
  const configPkg = react ? "@xylabs/eslint-config-react-flat" : "@xylabs/eslint-config-flat";
  const lines = [
    "import type { Linter } from 'eslint'",
    "",
    `import { config as xylabsConfig } from '${configPkg}'`,
    ""
  ];
  if (useXyLabsBarrel) {
    lines.push(formatDisallowedArray("disallowedImportsXyLabs", DISALLOWED_IMPORTS_XYLABS, XYLABS_SDK_IMPORT_MESSAGE), "");
  }
  if (useXyoBarrel) {
    lines.push(formatDisallowedArray("disallowedImportsXyo", DISALLOWED_IMPORTS_XYO, XYO_SDK_IMPORT_MESSAGE), "");
  }
  lines.push("const config: Linter.Config[] = [", "  { ignores: ['.yarn/**', 'build', '**/build/**', '**/dist/**', 'dist', 'node_modules/**', '**/node_modules/**', '**/*.md/**', '.claude/worktrees/*'] },", "  ...xylabsConfig,");
  if (useXyLabsBarrel || useXyoBarrel) {
    lines.push("  {", "    rules:", "    {", "      'no-restricted-imports': [", "        'warn',", "        {");
    if (useXyLabsBarrel && useXyoBarrel) {
      lines.push("          paths: [", "            ...disallowedImportsXyLabs,", "            ...disallowedImportsXyo,", "          ],");
    } else if (useXyLabsBarrel) {
      lines.push("          paths: [", "            ...disallowedImportsXyLabs,", "          ],");
    } else {
      lines.push("          paths: [", "            ...disallowedImportsXyo,", "          ],");
    }
    lines.push("        },", "      ],", "    },", "  },");
  }
  lines.push("]", "", "export default config", "");
  return lines.join("\n");
}
function addDevDependencies(packageJsonPath, requiredDeps, verbose) {
  const content = readFileSync4(packageJsonPath, "utf8");
  const pkg = JSON.parse(content);
  const devDeps = pkg.devDependencies ?? {};
  let changed = false;
  for (const [name, version] of Object.entries(requiredDeps)) {
    if (!devDeps[name]) {
      devDeps[name] = version;
      changed = true;
      if (verbose) console.log(chalk7.gray(`  Added ${name}@${version} to devDependencies`));
    } else if (verbose) {
      console.log(chalk7.gray(`  ${name} already in devDependencies`));
    }
  }
  if (changed) {
    const sorted = Object.fromEntries(Object.entries(devDeps).toSorted(([a], [b]) => a.localeCompare(b)));
    pkg.devDependencies = sorted;
    writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 2)}
`, "utf8");
    console.log(chalk7.green("Updated package.json devDependencies"));
  } else {
    console.log(chalk7.gray("package.json devDependencies already up to date"));
  }
  return changed;
}
function hasReactDependency(packageJsonPath) {
  try {
    const content = readFileSync4(packageJsonPath, "utf8");
    const pkg = JSON.parse(content);
    const deps = pkg.dependencies;
    const devDeps = pkg.devDependencies;
    const peerDeps = pkg.peerDependencies;
    return deps?.react != null || devDeps?.react != null || peerDeps?.react != null;
  } catch {
    return false;
  }
}
function detectReactInMonorepo(cwd, verbose) {
  const rootPkgPath = PATH2.resolve(cwd, "package.json");
  if (hasReactDependency(rootPkgPath)) {
    if (verbose) console.log(chalk7.gray("  React detected in package.json"));
    return true;
  }
  const packageJsonPaths = globSync2("packages/**/package.json", {
    cwd,
    ignore: ["**/node_modules/**"]
  });
  for (const relPath of packageJsonPaths) {
    const fullPath = PATH2.resolve(cwd, relPath);
    if (hasReactDependency(fullPath)) {
      if (verbose) console.log(chalk7.gray(`  React detected in ${relPath}`));
      return true;
    }
  }
  return false;
}
function findExistingConfig(configPath, legacyConfigPath) {
  if (existsSync4(configPath)) return configPath;
  if (existsSync4(legacyConfigPath)) return legacyConfigPath;
  return void 0;
}
function removeLegacyConfig(legacyConfigPath) {
  if (existsSync4(legacyConfigPath)) {
    unlinkSync(legacyConfigPath);
    console.log(chalk7.gray("Removed legacy eslint.config.mjs"));
  }
}
function updateDependencies(packageJsonPath, react, cwd, verbose) {
  if (!existsSync4(packageJsonPath)) {
    console.log(chalk7.yellow("No package.json found \u2014 skipping dependency updates"));
    return;
  }
  const changed = addDevDependencies(packageJsonPath, getRequiredDevDependencies(react), verbose);
  if (changed) {
    runInstall(cwd);
  }
}
async function lintInit({ verbose } = {}) {
  const cwd = INIT_CWD();
  const configPath = PATH2.resolve(cwd, "eslint.config.ts");
  const legacyConfigPath = PATH2.resolve(cwd, "eslint.config.mjs");
  const existingPath = findExistingConfig(configPath, legacyConfigPath);
  if (existingPath) {
    const filename = PATH2.basename(existingPath);
    const confirmed = await askConfirmation(
      chalk7.yellow(`${filename} already exists. Replace it with eslint.config.ts? (y/N) `)
    );
    if (!confirmed) {
      console.log(chalk7.gray(`Skipped \u2014 existing ${filename} preserved`));
      return 0;
    }
  }
  const react = detectReactInMonorepo(cwd, verbose);
  if (react) {
    console.log(chalk7.cyan("Detected React packages \u2014 using @xylabs/eslint-config-react-flat"));
  } else if (verbose) {
    console.log(chalk7.gray("  No React packages detected \u2014 using @xylabs/eslint-config-flat"));
  }
  const useXyLabsBarrel = await askConfirmation(
    chalk7.cyan("Disallow @xylabs/sdk-js barrel imports? (y/N) ")
  );
  const useXyoBarrel = await askConfirmation(
    chalk7.cyan("Disallow @xyo-network/sdk-js barrel imports? (y/N) ")
  );
  const config = generateEslintConfig({
    react,
    useXyLabsBarrel,
    useXyoBarrel
  });
  writeFileSync(configPath, config, "utf8");
  console.log(chalk7.green("Generated eslint.config.ts"));
  removeLegacyConfig(legacyConfigPath);
  updateDependencies(PATH2.resolve(cwd, "package.json"), react, cwd, verbose);
  return 0;
}

// src/xy/lint/lint/initCommand.ts
var initCommand = {
  command: "init",
  describe: "Generate eslint.config.ts and add ESLint dependencies",
  handler: async (argv) => {
    if (argv.verbose) console.log("Lint Init");
    await withEnvelope("lint init", () => lintInit({ verbose: !!argv.verbose }));
  }
};

// src/xy/param.ts
var packagePositionalParam = (yargs) => {
  return yargs.positional("package", { describe: "Specific package to target", type: "string" });
};

// src/xy/lint/lint/runCommand.ts
var runCommand = {
  aliases: ["$0"],
  builder: (yargs) => {
    return packagePositionalParam(yargs).option("fix", {
      alias: "f",
      default: false,
      description: "Fix fixable issues",
      type: "boolean"
    }).option("cache", {
      alias: "c",
      default: false,
      description: "Use caching for performance",
      type: "boolean"
    }).option("next", {
      alias: "n",
      default: false,
      description: "Lint per-package (lower memory, parallel)",
      type: "boolean"
    });
  },
  command: "run [package]",
  describe: "Run ESLint",
  handler: async (argv) => {
    if (argv.verbose) console.log("Lint");
    await withEnvelope("lint", () => lint({
      cache: argv.cache,
      fix: argv.fix,
      jobs: argv.jobs,
      next: argv.next,
      pkg: argv.package,
      verbose: !!argv.verbose
    }));
  }
};

// src/xy/lint/lint/index.ts
var lintCommand = {
  builder: (yargs) => {
    return yargs.command(runCommand).command(initCommand).option("init", {
      default: false,
      description: "Generate eslint.config.ts and add ESLint dependencies",
      hidden: true,
      type: "boolean"
    });
  },
  command: "lint",
  describe: "Lint - Run ESLint",
  handler: async (argv) => {
    if (argv.init) {
      console.warn(chalk8.yellow('Deprecated: use "xy lint init" instead of "xy lint --init"'));
      await withEnvelope("lint init", () => lintInit({ verbose: !!argv.verbose }));
    }
  }
};
export {
  lintCommand
};
//# sourceMappingURL=index.mjs.map
