// src/actions/package/clean-outputs.ts
import path2 from "path";
import chalk2 from "chalk";

// src/lib/deleteGlob.ts
import fs from "fs";
import { glob } from "glob";
var deleteGlob = (globPath) => {
  const files = glob.sync(globPath);
  for (const file of files) {
    fs.rmSync(file, { recursive: true, force: true });
  }
};

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

// src/lib/loadConfig.ts
import chalk from "chalk";
import { cosmiconfig } from "cosmiconfig";
import { TypeScriptLoader } from "cosmiconfig-typescript-loader";
import deepmerge from "deepmerge";
var config;
var rootConfigPath;
function createExplorer() {
  return cosmiconfig("xy", { cache: true, loaders: { ".ts": TypeScriptLoader() } });
}
var loadConfig = async (params) => {
  if (config === void 0) {
    const cosmicConfigResult = await createExplorer().search();
    config = cosmicConfigResult?.config ?? {};
    rootConfigPath = cosmicConfigResult?.filepath;
    const configFilePath = cosmicConfigResult?.filepath;
    if (configFilePath !== void 0) {
      console.log(chalk.green(`Loaded config from ${configFilePath}`));
      if (config.verbose) {
        console.log(chalk.gray(`${JSON.stringify(config, null, 2)}`));
      }
    }
  }
  return deepmerge(config, params ?? {});
};

// src/lib/packageName.ts
import { readFileSync } from "fs";
import path from "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(readFileSync(pkgPath, "utf8"));
    return pkg.name;
  } catch {
    return void 0;
  }
}

// src/actions/package/clean-outputs.ts
var packageCleanOutputs = () => {
  const pkg = INIT_CWD();
  const pkgName = packageName();
  const folders = [path2.join(pkg, "dist"), path2.join(pkg, "build"), path2.join(pkg, "docs")];
  console.log(chalk2.green(`Cleaning Outputs [${pkgName}]`));
  for (const folder of folders) {
    deleteGlob(folder);
  }
  return 0;
};

// src/actions/package/clean-typescript.ts
import path3 from "path";
import chalk3 from "chalk";
var packageCleanTypescript = () => {
  const pkg = INIT_CWD();
  const pkgName = packageName();
  console.log(chalk3.green(`Cleaning Typescript [${pkgName}]`));
  const files = [path3.join(pkg, "*.tsbuildinfo"), path3.join(pkg, ".tsconfig.*"), path3.join(pkg, ".eslintcache")];
  for (const file of files) {
    deleteGlob(file);
  }
  return 0;
};

// src/actions/package/clean.ts
var packageClean = () => {
  return [packageCleanOutputs(), packageCleanTypescript()].reduce((prev, value) => prev + value, 0);
};

// src/actions/package/compile/compile.ts
import { cwd as cwd4 } from "process";
import chalk8 from "chalk";

// src/actions/package/compile/packageCompileTsup.ts
import chalk7 from "chalk";
import { build, defineConfig } from "tsup";

// src/actions/package/compile/inputs.ts
import chalk4 from "chalk";
import { glob as glob2 } from "glob";
var getAllInputs = (srcDir, verbose = false) => {
  return [...glob2.sync(`${srcDir}/**/*.ts`, { posix: true }).map((file) => {
    const result = file.slice(Math.max(0, srcDir.length + 1));
    if (verbose) {
      console.log(chalk4.gray(`getAllInputs: ${JSON.stringify(result, null, 2)}`));
    }
    return result;
  }), ...glob2.sync(`${srcDir}/**/*.tsx`, { posix: true }).map((file) => {
    const result = file.slice(Math.max(0, srcDir.length + 1));
    if (verbose) {
      console.log(chalk4.gray(`getAllInputs: ${JSON.stringify(result, null, 2)}`));
    }
    return result;
  })];
};

// src/actions/package/compile/buildEntries.ts
var isSpecOrStory = (entry) => {
  return entry.includes(".spec.") || entry.includes(".stories.") || entry.startsWith("spec/") || entry.includes("/spec/") || entry.startsWith("stories/") || entry.includes("/stories/") || entry === "spec.ts" || entry.endsWith("/spec.ts") || entry === "stories.ts" || entry.endsWith("/stories.ts");
};
var buildEntries = (srcDir, entryMode = "single", options, excludeSpecAndStories = true, verbose = false) => {
  let entries;
  switch (entryMode) {
    case "platform": {
      entries = ["index-node.ts", "index-browser.ts"];
      break;
    }
    case "all": {
      entries = (excludeSpecAndStories ? getAllInputs(srcDir).filter((entry) => !isSpecOrStory(entry)) : getAllInputs(srcDir)).filter((entry) => !entry.endsWith(".d.ts"));
      break;
    }
    case "custom": {
      entries = [];
      break;
    }
    default: {
      entries = ["index.ts"];
      break;
    }
  }
  if (typeof options !== "boolean" && Array.isArray(options?.entry)) {
    entries.push(...options.entry);
  }
  if (verbose) console.log(`buildEntries [${entryMode}] ${entries.length}`);
  return entries;
};

// src/actions/package/compile/deepMerge.ts
function deepMerge(target, source) {
  if (!source || typeof source !== "object") return target;
  for (const key of Object.keys(source)) {
    const sourceVal = source[key];
    if (typeof sourceVal === "object" && sourceVal !== null && !Array.isArray(sourceVal)) {
      if (!target[key] || typeof target[key] !== "object") {
        target[key] = {};
      }
      deepMerge(target[key], sourceVal);
    } else {
      target[key] = sourceVal;
    }
  }
  return target;
}
function deepMergeObjects(objects) {
  const result = {};
  for (const obj of objects) {
    deepMerge(result, obj);
  }
  return result;
}

// src/actions/package/compile/packageCompileTsc.ts
import { cwd as cwd2 } from "process";
import chalk5 from "chalk";
import { createProgramFromConfig } from "tsc-prog";
import ts, {
  DiagnosticCategory,
  formatDiagnosticsWithColorAndContext,
  getPreEmitDiagnostics,
  sys
} from "typescript";

// src/actions/package/compile/getCompilerOptions.ts
import { cwd } from "process";
import deepmerge2 from "deepmerge";
import { getTsconfig } from "get-tsconfig";
var getCompilerOptions = (options = {}, fileName = "tsconfig.json") => {
  const resolvedTsConfigCompilerOptions = getTsconfig(cwd(), fileName)?.config?.compilerOptions ?? {};
  return deepmerge2(resolvedTsConfigCompilerOptions, options);
};

// src/actions/package/compile/packageCompileTsc.ts
var packageCompileTsc = (platform, entries, srcDir = "src", outDir = "dist", compilerOptionsParam, verbose = false) => {
  const pkg = cwd2();
  if (verbose) {
    console.log(chalk5.cyan(`Validating code START: ${entries.length} files to ${outDir} from ${srcDir}`));
  }
  const configFilePath = ts.findConfigFile(
    pkg,
    (fileName) => ts.sys.fileExists(fileName),
    "tsconfig.json"
  );
  if (configFilePath === void 0) {
    throw new Error("Could not find tsconfig.json");
  }
  const compilerOptions = {
    ...getCompilerOptions({
      removeComments: false,
      skipDefaultLibCheck: true,
      skipLibCheck: true,
      sourceMap: false
    }),
    ...compilerOptionsParam,
    outDir: `${outDir}/${platform}`,
    emitDeclarationOnly: true,
    noEmit: false
  };
  console.log(chalk5.cyan(`Validating Files: ${entries.length}`));
  if (verbose) {
    for (const entry of entries) {
      console.log(chalk5.grey(`Validating: ${entry}`));
    }
  }
  try {
    if (entries.length > 0) {
      const program = createProgramFromConfig({
        configFilePath,
        basePath: pkg,
        compilerOptions,
        files: entries.map((entry) => `${srcDir}/${entry}`),
        include: [`${srcDir}/**/*.*`]
      });
      const diagnostics = getPreEmitDiagnostics(program);
      if (diagnostics.length > 0) {
        const formattedDiagnostics = formatDiagnosticsWithColorAndContext(
          diagnostics,
          {
            getCanonicalFileName: (fileName) => fileName,
            getCurrentDirectory: () => srcDir,
            getNewLine: () => sys.newLine
          }
        );
        console.error(formattedDiagnostics);
      }
      const nonEmitPatterns = [".stories.", "/stories/", "/stories.", ".spec.", "/spec/", "/spec.", ".example."];
      program.emit(void 0, (fileName, text, writeByteOrderMark) => {
        if (nonEmitPatterns.some((pattern) => fileName.includes(pattern))) {
          return;
        }
        ts.sys.writeFile(fileName, text, writeByteOrderMark);
      });
      return diagnostics.reduce((acc, diag) => acc + (diag.category === DiagnosticCategory.Error ? 1 : 0), 0);
    }
    return 0;
  } finally {
    if (verbose) {
      console.log(chalk5.cyan(`Validating code FINISH: ${entries.length} files to ${outDir} from ${srcDir}`));
    }
  }
};

// src/actions/package/compile/packageCompileTscTypes.ts
import path4 from "path";
import { cwd as cwd3 } from "process";
import chalk6 from "chalk";
import { rollup } from "rollup";
import dts from "rollup-plugin-dts";
import nodeExternals from "rollup-plugin-node-externals";
var ignoredWarningCodes = /* @__PURE__ */ new Set(["EMPTY_BUNDLE", "UNRESOLVED_IMPORT"]);
async function bundleDts(inputPath, outputPath, platform, options, verbose = false) {
  const pkg = cwd3();
  const tsconfigPath = path4.resolve(pkg, "tsconfig.json");
  const nodePlugIns = platform === "node" ? [nodeExternals()] : [];
  try {
    const bundle = await rollup({
      input: inputPath,
      plugins: [dts({
        ...options,
        tsconfig: tsconfigPath,
        compilerOptions: {
          emitDeclarationOnly: true,
          noEmit: false,
          declarationMap: true
        }
      }), ...nodePlugIns],
      onwarn(warning, warn) {
        if (ignoredWarningCodes.has(warning.code ?? "")) {
          return;
        }
        console.warn(chalk6.yellow(`[${warning.code}] ${warning.message}`));
        console.warn(chalk6.gray(inputPath));
        warn(warning);
      }
    });
    await bundle.write({
      file: outputPath,
      format: "es"
    });
  } catch (ex) {
    const error = ex;
    console.warn(chalk6.red(error));
    console.warn(chalk6.gray(inputPath));
  }
  if (verbose) {
    console.log(`Bundled declarations written to ${outputPath}`);
  }
}
var packageCompileTscTypes = async (entries, outDir, platform, srcDir = "build", verbose = false) => {
  if (verbose) {
    console.log(chalk6.cyan(`Compiling Types START [${platform}]: ${entries.length} files to ${outDir} from ${srcDir}`));
    console.log(`Entries: ${entries.join(", ")}`);
  }
  const pkg = cwd3();
  const srcRoot = `${pkg}/${srcDir}/${platform}`;
  const entryNameToTypeName = (entry) => {
    const splitEntryName = entry.split(".");
    const newEntryExtension = "d." + splitEntryName.at(-1);
    return [...splitEntryName.slice(0, -1), newEntryExtension].join(".");
  };
  const compilerOptions = getCompilerOptions({
    removeComments: false,
    skipDefaultLibCheck: true,
    skipLibCheck: true,
    declarationMap: true,
    emitDeclarationOnly: true,
    noEmit: true
  });
  const entryNames = entries.map((entry) => entry.split(`${srcDir}/`).at(-1) ?? entry);
  await Promise.all(entryNames.map(async (entryName) => {
    const entryTypeName = entryNameToTypeName(entryName);
    await bundleDts(`${srcRoot}/${entryTypeName}`, `${outDir}/${entryTypeName}`, platform, { compilerOptions }, verbose);
  }));
  if (verbose) {
    console.log(chalk6.cyan(`Compiling Types FINISH: ${entries.length} files to ${outDir} from ${srcDir}`));
  }
  return 0;
};

// src/actions/package/compile/packageCompileTsup.ts
var compileFolder = async (srcDir, entries, buildDir, options, bundleTypes = false, verbose) => {
  const outDir = options?.outDir ?? "dist";
  if (verbose) {
    console.log(`compileFolder [${srcDir}, ${options?.outDir}]`);
  }
  if (entries.length === 0) {
    console.warn(chalk7.yellow(`No entries found in ${srcDir} to compile`));
    return 0;
  }
  if (verbose) {
    console.log(chalk7.gray(`buildDir [${buildDir}]`));
  }
  const validationResult = packageCompileTsc(options?.platform ?? "neutral", entries, srcDir, buildDir, void 0, verbose);
  if (validationResult !== 0) {
    console.error(chalk7.red(`Compile:Validation had ${validationResult} errors`));
    return validationResult;
  }
  const optionsParams = tsupOptions([{
    bundle: true,
    cjsInterop: true,
    clean: false,
    dts: false,
    format: ["esm"],
    outDir,
    silent: true,
    sourcemap: true,
    splitting: false,
    tsconfig: "tsconfig.json",
    ...options,
    entry: entries.map((entry) => `${srcDir}/${entry}`)
  }]);
  const optionsResult = defineConfig(optionsParams);
  const optionsList = (await Promise.all(
    (Array.isArray(optionsResult) ? optionsResult : [optionsResult]).flatMap(async (options2) => {
      const result = typeof options2 === "function" ? await options2({}) : [options2];
      return Array.isArray(result) ? result : [result];
    })
  )).flat();
  if (verbose) {
    console.log(chalk7.cyan(`TSUP:build:start [${srcDir}]`));
    console.log(chalk7.gray(`TSUP:build:options [${JSON.stringify(optionsList, null, 2)}]`));
  }
  await Promise.all(optionsList.map((options2) => build(options2)));
  if (verbose) {
    console.log(chalk7.cyan(`TSUP:build:stop [${srcDir}]`));
  }
  if (bundleTypes) {
    await packageCompileTscTypes(entries, outDir, options?.platform ?? "neutral", buildDir, verbose);
  }
  return 0;
};
var resolvePlatformRecord = (value) => {
  if (value === void 0 || value === true) return { src: {} };
  if (value === false) return {};
  return value;
};
var resolvePlatformEsbuildOptions = (value) => {
  if (typeof value !== "object" || value === null) return {};
  const entry = value.esbuildOptions;
  return entry ?? {};
};
var tsupOptions = (options = []) => {
  const standardLoaders = {
    ".gif": "copy",
    ".html": "copy",
    ".jpg": "copy",
    ".json": "json",
    ".png": "copy",
    ".svg": "text",
    ".webp": "copy"
  };
  const standardOptions = {
    bundle: true,
    format: ["esm"],
    loader: standardLoaders,
    outExtension: ({ format }) => format === "esm" ? { js: ".mjs" } : { js: ".cjs" },
    skipNodeModulesBundle: true,
    sourcemap: true,
    target: "esnext"
  };
  return deepMergeObjects([standardOptions, ...options]);
};
var packageCompileTsup = async (config2) => {
  const compile = config2?.compile;
  const verbose = config2?.verbose ?? false;
  const outDirAsBuildDir = compile?.outDirAsBuildDir ?? true;
  const bundleTypes = compile?.bundleTypes ?? false;
  if (verbose) {
    console.log("Compiling with TSUP");
  }
  const compileForNode = resolvePlatformRecord(compile?.node);
  const compileForBrowser = resolvePlatformRecord(compile?.browser);
  const compileForNeutral = resolvePlatformRecord(compile?.neutral);
  const nodeEsbuild = resolvePlatformEsbuildOptions(compile?.node);
  const browserEsbuild = resolvePlatformEsbuildOptions(compile?.browser);
  const neutralEsbuild = resolvePlatformEsbuildOptions(compile?.neutral);
  const compilePlatform = async (platform, entries, platformEsbuild) => {
    const results = await Promise.all(
      Object.entries(entries).map(async ([srcDir, options]) => {
        const rootOutDir = options.outDir ?? "dist";
        const outDir = `${rootOutDir}/${platform}`;
        const entry = buildEntries(srcDir, compile?.entryMode, options, true, verbose);
        return compileFolder(
          srcDir,
          entry,
          outDirAsBuildDir ? rootOutDir : "build",
          tsupOptions([
            platformEsbuild,
            compile?.tsup?.options ?? {},
            options,
            { platform, outDir }
          ]),
          bundleTypes,
          verbose
        );
      })
    );
    return results.reduce((prev, value) => prev + value, 0);
  };
  const [nodeErrors, browserErrors, neutralErrors] = await Promise.all([
    compilePlatform("node", compileForNode, nodeEsbuild),
    compilePlatform("browser", compileForBrowser, browserEsbuild),
    compilePlatform("neutral", compileForNeutral, neutralEsbuild)
  ]);
  return nodeErrors + browserErrors + neutralErrors;
};

// src/actions/package/compile/compile.ts
var packageCompile = async (inConfig = {}) => {
  const pkg = cwd4();
  console.log(chalk8.green(`Compiling ${pkg}`));
  const config2 = await loadConfig(inConfig);
  return await packageCompileTsup(config2);
};

// src/actions/package/compile/XyConfig.ts
var ALL_PUBLINT_CHECKS = [
  "files",
  "importToDefault",
  "main",
  "module",
  "peerDeps",
  "publint",
  "resolutions",
  "rootSource",
  "rootTypes",
  "sideEffects",
  "source",
  "types"
];
var PUBLISH_ONLY_CHECKS = [
  "files",
  "importToDefault",
  "main",
  "module",
  "publint",
  "rootSource",
  "rootTypes",
  "sideEffects",
  "source",
  "types"
];

// src/actions/package/copy-assets.ts
import path5 from "path/posix";
import chalk9 from "chalk";
import cpy from "cpy";
var copyTargetAssets = async (target, name, location) => {
  try {
    const values = await cpy(
      ["**/*.jpg", "**/*.png", "**/*.gif", "**/*.svg", "**/*.webp", "**/*.sass", "**/*.scss", "**/*.gif", "**/*.css"],
      `../dist/${target}`,
      {
        cwd: path5.join(location, "src"),
        flat: false
      }
    );
    if (values.length > 0) {
      console.log(chalk9.green(`Copying Assets [${target.toUpperCase()}] - ${name} - ${location}`));
    }
    for (const value of values) {
      console.log(`${value.split("/").pop()} => ./dist/${target}`);
    }
    return 0;
  } catch (ex) {
    const error = ex;
    console.log(`Copy Assets Failed: ${name}: ${error.message}`);
    return 1;
  }
};
var packageCopyAssets = async ({ target }) => {
  const pkg = INIT_CWD();
  const pkgName = packageName() ?? "Unknown";
  switch (target) {
    case "esm": {
      return await copyTargetAssets("esm", pkgName, pkg);
    }
    case "cjs": {
      return await copyTargetAssets("cjs", pkgName, pkg);
    }
    default: {
      return await copyTargetAssets("esm", pkgName, pkg) || await copyTargetAssets("cjs", pkgName, pkg);
    }
  }
};

// src/actions/package/gen-docs.ts
import { existsSync } from "fs";
import path6 from "path";
import chalk10 from "chalk";
import {
  Application,
  ArgumentsReader,
  TSConfigReader,
  TypeDocReader
} from "typedoc";
var ExitCodes = {
  CompileError: 3,
  ExceptionThrown: 6,
  NoEntryPoints: 2,
  Ok: 0,
  OptionError: 1,
  OutputError: 5,
  ValidationError: 4
};
var packageGenDocs = async () => {
  const pkg = INIT_CWD();
  if (pkg !== void 0 && !existsSync(path6.join(pkg, "typedoc.json"))) {
    return;
  }
  const app = await Application.bootstrap({
    entryPointStrategy: "merge",
    entryPoints: [`${pkg}/src/**/*.ts`, `${pkg}/packages/*/dist/docs.json`],
    excludeExternals: true,
    json: `${pkg}/dist/docs.json`,
    logLevel: "Error",
    tsconfig: `${pkg}/tsconfig.json`
  });
  app.options.addReader(new ArgumentsReader(0));
  app.options.addReader(new TypeDocReader());
  app.options.addReader(new TSConfigReader());
  app.options.addReader(new ArgumentsReader(300));
  return await runTypeDoc(app);
};
var runTypeDoc = async (app) => {
  const pkgName = packageName();
  if (app.options.getValue("version")) {
    console.log(app.toString());
    return ExitCodes.Ok;
  }
  if (app.options.getValue("showConfig")) {
    console.log(app.options.getRawValues());
    return ExitCodes.Ok;
  }
  if (app.logger.hasErrors()) {
    return ExitCodes.OptionError;
  }
  if (app.options.getValue("treatWarningsAsErrors") && app.logger.hasWarnings()) {
    return ExitCodes.OptionError;
  }
  if (app.options.getValue("entryPoints").length === 0) {
    app.logger.error("No entry points provided");
    return ExitCodes.NoEntryPoints;
  }
  if (app.options.getValue("watch")) {
    await app.convertAndWatch(async (project2) => {
      const out = app.options.getValue("out");
      if (out) {
        await app.generateDocs(project2, out);
      }
      const json = app.options.getValue("json");
      if (json) {
        await app.generateJson(project2, json);
      }
      if (!out && !json) {
        await app.generateDocs(project2, "./docs");
      }
    });
    return ExitCodes.Ok;
  }
  const project = await app.convert();
  if (!project) {
    return ExitCodes.CompileError;
  }
  if (app.options.getValue("treatWarningsAsErrors") && app.logger.hasWarnings()) {
    return ExitCodes.CompileError;
  }
  app.validate(project);
  if (app.logger.hasErrors()) {
    return ExitCodes.ValidationError;
  }
  if (app.options.getValue("treatWarningsAsErrors") && app.logger.hasWarnings()) {
    return ExitCodes.ValidationError;
  }
  if (app.options.getValue("emit") !== "none") {
    const out = app.options.getValue("out");
    if (out) {
      await app.generateDocs(project, out);
    }
    const json = app.options.getValue("json");
    if (json) {
      await app.generateJson(project, json);
    }
    if (!out && !json) {
      await app.generateDocs(project, "./docs");
    }
    if (app.logger.hasErrors()) {
      return ExitCodes.OutputError;
    }
    if (app.options.getValue("treatWarningsAsErrors") && app.logger.hasWarnings()) {
      return ExitCodes.OutputError;
    }
  }
  console.log(chalk10.green(`${pkgName} - Ok`));
  return ExitCodes.Ok;
};

// src/actions/package/lint.ts
import { readdirSync } from "fs";
import path7 from "path";
import { cwd as cwd5 } from "process";
import { pathToFileURL } from "url";
import chalk11 from "chalk";
import { ESLint } from "eslint";
import { findUp } from "find-up";
import picomatch from "picomatch";
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(chalk11.gray(`
${lintResult.filePath}`));
      for (const message of lintResult.messages) {
        console.log(
          chalk11.gray(`	${message.line}:${message.column}`),
          chalk11[colors[message.severity]](`	${severity[message.severity]}`),
          chalk11.white(`	${message.message}`),
          chalk11.gray(`	${message.ruleId}`)
        );
      }
    }
  }
};
async function getRootESLintConfig() {
  const configPath = await findUp(["eslint.config.ts", "eslint.config.mjs"]);
  if (configPath === void 0) {
    throw new Error("eslint.config.ts not found in the monorepo");
  }
  return pathToFileURL(configPath);
}
function getFiles(dir, ignoreFolders) {
  const currentDirectory = cwd5();
  const subDirectory = dir.split(currentDirectory)[1]?.split("/")[1];
  if (ignoreFolders.includes(subDirectory)) return [];
  return readdirSync(dir, { withFileTypes: true }).flatMap((dirent) => {
    const res = path7.resolve(dir, dirent.name);
    const relativePath = subDirectory === void 0 ? dirent.name : `${subDirectory}/${dirent.name}`;
    const ignoreMatchers = ignoreFolders.map((pattern) => picomatch(pattern));
    if (ignoreMatchers.some((isMatch) => isMatch(relativePath))) return [];
    return dirent.isDirectory() ? getFiles(res, ignoreFolders) : [res];
  });
}
var packageLint = async (fix = false, verbose = false, cache = true) => {
  const pkg = INIT_CWD();
  const configPath = await getRootESLintConfig();
  const { default: eslintConfig } = await import(configPath.href);
  const start = Date.now();
  const ignoreFolders = ["node_modules", "dist", "packages", ".git", "build", ".yarn", ".vscode", ".github"];
  const engine = new ESLint({
    baseConfig: [...eslintConfig],
    fix,
    warnIgnored: false,
    cache
  });
  const files = getFiles(cwd5(), ignoreFolders);
  console.log(chalk11.green(`Linting ${pkg} [files = ${files.length}]`));
  if (verbose) {
    for (const file of files) {
      console.log(chalk11.gray(`	${file}`));
    }
  }
  const lintResults = await engine.lintFiles(files);
  dumpMessages(lintResults);
  if (fix) {
    await ESLint.outputFixes(lintResults);
  }
  const filesCountColor = files.length < 100 ? "green" : files.length < 1e3 ? "yellow" : "red";
  const lintTime = Date.now() - start;
  const lintTimeColor = lintTime < 1e3 ? "green" : lintTime < 3e3 ? "yellow" : "red";
  console.log(chalk11.white(`Linted ${chalk11[filesCountColor](files.length)} files in ${chalk11[lintTimeColor](lintTime)}ms`));
  return lintResults.reduce((prev, lintResult) => prev + lintResult.errorCount, 0);
};

// src/actions/package/publint.ts
import { promises as fs2 } from "fs";
import path8 from "path";
import chalk12 from "chalk";
import { glob as glob3 } from "glob";
import sortPackageJson from "sort-package-json";
var removeSourceFromExports = (exports) => {
  let removed = false;
  for (const [key, value] of Object.entries(exports)) {
    if (key === "source") {
      delete exports[key];
      removed = true;
    } else if (typeof value === "object" && value !== null && removeSourceFromExports(value)) removed = true;
  }
  return removed;
};
var hasSourceInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "source") return true;
    if (typeof value === "object" && value !== null && hasSourceInExports(value)) return true;
  }
  return false;
};
var hasImportKeyInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "import" && typeof value === "string" && value.endsWith(".mjs")) return true;
    if (typeof value === "object" && value !== null && hasImportKeyInExports(value)) return true;
  }
  return false;
};
var replaceImportWithDefault = (exports) => {
  let modified = false;
  for (const [key, value] of Object.entries(exports)) {
    if (key === "import" && typeof value === "string" && value.endsWith(".mjs")) {
      if (exports.default === void 0) {
        exports.default = value;
      }
      delete exports.import;
      if (exports.types === void 0) {
        exports.types = value.replace(/\.mjs$/, ".d.ts");
      }
      modified = true;
    } else if (typeof value === "object" && value !== null && replaceImportWithDefault(value)) modified = true;
  }
  return modified;
};
var hasTypesInExports = (exports) => {
  for (const [key, value] of Object.entries(exports)) {
    if (key === "types") return true;
    if (typeof value === "object" && value !== null && hasTypesInExports(value)) return true;
  }
  return false;
};
function ensureExportsPath(value) {
  if (value.startsWith("./") || value.startsWith("../")) return value;
  return `./${value}`;
}
function emptyCustomResult() {
  return {
    errors: 0,
    modified: false,
    warnings: 0
  };
}
function mergeResults(target, source) {
  target.errors += source.errors;
  target.warnings += source.warnings;
  target.modified = target.modified || source.modified;
}
function checkFiles(pkg, fix) {
  const result = emptyCustomResult();
  const files = pkg.files;
  if (files === void 0) {
    console.warn(chalk12.yellow('Publint [custom]: "files" field is missing'));
    result.warnings++;
  }
  if (Array.isArray(files) && !files.includes("README.md")) {
    files.push("README.md");
    console.warn(chalk12.yellow('Publint [custom]: added "README.md" to "files"'));
    result.modified = true;
    result.warnings++;
  }
  if (Array.isArray(files) && files.includes("src")) {
    if (fix) {
      pkg.files = files.filter((f) => f !== "src");
      console.warn(chalk12.yellow('Publint [custom]: removed "src" from "files"'));
      result.modified = true;
    } else {
      console.warn(chalk12.yellow('Publint [custom]: "src" should not be in "files" (use --fix to remove)'));
    }
    result.warnings++;
  }
  return result;
}
function checkExportsSource(pkg, fix) {
  const result = emptyCustomResult();
  const exports = pkg.exports;
  if (exports && typeof exports === "object" && hasSourceInExports(exports)) {
    if (fix) {
      removeSourceFromExports(exports);
      console.warn(chalk12.yellow('Publint [custom]: removed "source" entries from "exports"'));
      result.modified = true;
    } else {
      console.warn(chalk12.yellow('Publint [custom]: "source" entries should not be in "exports" (use --fix to remove)'));
    }
    result.warnings++;
  }
  return result;
}
function migrateFieldToExports(pkg, field, exportKey, fix) {
  const result = emptyCustomResult();
  if (pkg[field] === void 0) return result;
  const fieldValue = pkg[field];
  if (!fieldValue.endsWith(".js") && !fieldValue.endsWith(".mjs") && !fieldValue.endsWith(".cjs")) return result;
  if (fix) {
    const exportValue = ensureExportsPath(fieldValue);
    const exports = pkg.exports;
    if (exports && typeof exports === "object") {
      const dot = exports["."];
      if (dot && typeof dot === "object" && !dot[exportKey]) {
        dot[exportKey] = exportValue;
        console.warn(chalk12.yellow(`Publint [custom]: migrated "${field}" to "exports['.'].${exportKey}" (${fieldValue})`));
      }
    } else if (!pkg.exports) {
      pkg.exports = { ".": { [exportKey]: exportValue } };
      console.warn(chalk12.yellow(`Publint [custom]: migrated "${field}" to "exports" (.\u2192${fieldValue})`));
    }
    delete pkg[field];
    console.warn(chalk12.yellow(`Publint [custom]: removed deprecated "${field}" field`));
    result.modified = true;
  } else {
    console.warn(chalk12.yellow(`Publint [custom]: "${field}" field is deprecated, use "exports" instead (use --fix to remove)`));
  }
  result.warnings++;
  return result;
}
function checkSideEffects(pkg) {
  const result = emptyCustomResult();
  if (pkg.sideEffects !== false) {
    console.warn(chalk12.yellow('Publint [custom]: "sideEffects" field should be set to false'));
    result.warnings++;
  }
  return result;
}
function checkRootSource(pkg, fix) {
  const result = emptyCustomResult();
  for (const field of ["source", "src"]) {
    if (pkg[field] !== void 0) {
      if (fix) {
        delete pkg[field];
        console.warn(chalk12.yellow(`Publint [custom]: removed root-level "${field}" field`));
        result.modified = true;
      } else {
        console.warn(chalk12.yellow(`Publint [custom]: root-level "${field}" field should not be in package.json (use --fix to remove)`));
      }
      result.warnings++;
    }
  }
  return result;
}
function checkResolutions(pkg) {
  const result = emptyCustomResult();
  if (pkg.resolutions !== void 0) {
    console.warn(chalk12.yellow('Publint [custom]: "resolutions" in use'));
    console.warn(chalk12.gray(JSON.stringify(pkg.resolutions, null, 2)));
    result.warnings++;
  }
  return result;
}
function checkImportToDefault(pkg, fix) {
  const result = emptyCustomResult();
  const exports = pkg.exports;
  if (!exports || typeof exports !== "object") return result;
  if (!hasImportKeyInExports(exports)) return result;
  if (fix) {
    replaceImportWithDefault(exports);
    console.warn(chalk12.yellow('Publint [custom]: renamed "import" to "default" in "exports" and ensured "types" siblings'));
    result.modified = true;
  } else {
    console.warn(chalk12.yellow('Publint [custom]: "import" entries in "exports" should use "default" instead (use --fix to rename)'));
  }
  result.warnings++;
  return result;
}
function checkRootTypes(pkg, fix) {
  const result = emptyCustomResult();
  if (pkg.types === void 0) return result;
  const exports = pkg.exports;
  if (!exports || typeof exports !== "object" || !hasTypesInExports(exports)) return result;
  if (fix) {
    delete pkg.types;
    console.warn(chalk12.yellow('Publint [custom]: removed redundant root "types" field (already defined in "exports")'));
    result.modified = true;
  } else {
    console.warn(chalk12.yellow('Publint [custom]: root "types" field is redundant when "exports" defines types (use --fix to remove)'));
  }
  result.warnings++;
  return result;
}
function customPubLint(pkg, fix = false, exclude = /* @__PURE__ */ new Set()) {
  const result = emptyCustomResult();
  if (!exclude.has("files")) mergeResults(result, checkFiles(pkg, fix));
  if (!exclude.has("source")) mergeResults(result, checkExportsSource(pkg, fix));
  if (!exclude.has("rootSource")) mergeResults(result, checkRootSource(pkg, fix));
  if (!exclude.has("main")) mergeResults(result, migrateFieldToExports(pkg, "main", "default", fix));
  if (!exclude.has("types")) mergeResults(result, migrateFieldToExports(pkg, "types", "types", fix));
  if (!exclude.has("module")) mergeResults(result, migrateFieldToExports(pkg, "module", "default", fix));
  if (!exclude.has("importToDefault")) mergeResults(result, checkImportToDefault(pkg, fix));
  if (!exclude.has("rootTypes")) mergeResults(result, checkRootTypes(pkg, fix));
  if (!exclude.has("sideEffects")) mergeResults(result, checkSideEffects(pkg));
  if (!exclude.has("resolutions")) mergeResults(result, checkResolutions(pkg));
  return [result.errors, result.warnings, result.modified];
}
var ALWAYS_INCLUDED_PATTERNS = [
  "package.json",
  "README",
  "README.*",
  "LICENCE",
  "LICENCE.*",
  "LICENSE",
  "LICENSE.*",
  "CHANGELOG",
  "CHANGELOG.*"
];
async function resolvePackFiles(pkgDir, filesField) {
  const patterns = [...ALWAYS_INCLUDED_PATTERNS];
  if (filesField) {
    for (const pattern of filesField) {
      if (pattern.startsWith("!")) {
        patterns.push(pattern);
      } else {
        patterns.push(pattern, `${pattern}/**`);
      }
    }
  }
  const matched = await glob3(patterns, {
    cwd: pkgDir,
    nodir: true,
    dot: false
  });
  const files = await Promise.all(
    matched.map(async (rel) => {
      const abs = path8.join(pkgDir, rel);
      const data = await fs2.readFile(abs, "utf8").catch(() => "");
      return { name: path8.join(pkgDir, rel), data };
    })
  );
  return files;
}
async function runPublintLibrary(pkgDir, pkg, strict, pack) {
  const { publint } = await import("publint");
  let packOption = false;
  if (pack) {
    const files = await resolvePackFiles(pkgDir, pkg.files);
    packOption = { files };
  }
  const { messages } = await publint({
    level: "suggestion",
    pack: packOption,
    pkgDir,
    strict
  });
  const { formatMessage } = await import("publint/utils");
  for (const message of messages) {
    switch (message.type) {
      case "error": {
        console.error(chalk12.red(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
      case "warning": {
        console.warn(chalk12.yellow(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
      default: {
        console.log(chalk12.white(`[${message.code}] ${formatMessage(message, pkg)}`));
        break;
      }
    }
  }
  return {
    errors: messages.filter((message) => message.type === "error").length,
    total: messages.length
  };
}
var packagePublint = async ({
  exclude = /* @__PURE__ */ new Set(),
  fix = false,
  pack = true,
  pkgDir: pkgDirParam,
  strict = true,
  verbose: _verbose = false
} = {}) => {
  const pkgDir = pkgDirParam ?? INIT_CWD();
  const sortedPkg = sortPackageJson(await fs2.readFile(`${pkgDir}/package.json`, "utf8"));
  await fs2.writeFile(`${pkgDir}/package.json`, sortedPkg);
  const pkg = JSON.parse(await fs2.readFile(`${pkgDir}/package.json`, "utf8"));
  const effectiveExclude = pkg.private ? /* @__PURE__ */ new Set([...exclude, ...PUBLISH_ONLY_CHECKS]) : exclude;
  console.log(chalk12.green(`Publint: ${String(pkg.name)}${pkg.private ? chalk12.gray(" (private)") : ""}`));
  console.log(chalk12.gray(pkgDir));
  let libraryErrors = 0;
  if (!effectiveExclude.has("publint")) {
    const library = await runPublintLibrary(pkgDir, pkg, strict, pack);
    libraryErrors = library.errors;
  }
  const [errorCount, _warningCount, modified] = customPubLint(pkg, fix, effectiveExclude);
  if (modified) {
    const sorted = sortPackageJson(JSON.stringify(pkg, null, 2));
    await fs2.writeFile(`${pkgDir}/package.json`, sorted);
  }
  return libraryErrors + errorCount;
};

// src/actions/package/recompile.ts
var packageRecompile = async () => {
  return packageClean() || await packageCompile();
};
export {
  ALL_PUBLINT_CHECKS,
  PUBLISH_ONLY_CHECKS,
  packageClean,
  packageCleanOutputs,
  packageCleanTypescript,
  packageCompile,
  packageCompileTsc,
  packageCompileTsup,
  packageCopyAssets,
  packageGenDocs,
  packageLint,
  packagePublint,
  packageRecompile,
  tsupOptions
};
//# sourceMappingURL=index.mjs.map