#!/usr/bin/env node
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// node_modules/.pnpm/tsup@8.5.0_jiti@2.5.1_postcss@8.5.6_tsx@4.19.2_typescript@5.9.2_yaml@2.4.5/node_modules/tsup/assets/cjs_shims.js
var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();

// src/bin.mts
var import_std_env8 = require("std-env");

// src/cli.mts
var import_citty4 = require("citty");

// src/commands/root.mts
var import_citty3 = require("citty");
var import_consola24 = require("consola");

// src/config/get-cwd.mts
var import_pathe = require("pathe");
var import_std_env = require("std-env");
var ACTUAL_CWD = (
  // biome-ignore lint/suspicious/noExplicitAny: it's fine
  import_std_env.process.cwd?.() || (import_std_env.isDeno ? globalThis.Deno.cwd() : "")
);
var cwd;
function getCWD(args12) {
  return cwd ||= args12?.cwd ? (0, import_pathe.resolve)(ACTUAL_CWD, args12.cwd) : ACTUAL_CWD;
}

// src/utils/define-args.mts
function defineArgs(args12, dontSort) {
  return dontSort ? args12 : sortArgs(args12);
}
function sortArgs(args12) {
  return Object.fromEntries(
    Object.entries(args12).sort(([nameA, argA], [nameB, argB]) => {
      const aliasA = getAlias(argA);
      const aliasB = getAlias(argB);
      if (aliasA) {
        nameA = aliasA;
      }
      if (aliasB) {
        nameB = aliasB;
      }
      return nameA.localeCompare(nameB);
    })
  );
}
function getAlias(arg) {
  const { alias } = arg;
  if (!alias) {
    return null;
  }
  if (Array.isArray(alias)) {
    return alias.at(0) || null;
  }
  return alias;
}

// src/utils/define-command.mts
function defineCommand(args12, command) {
  return {
    ...command,
    args: args12,
    subCommands: sortSubCommands(command.subCommands)
  };
}
function sortSubCommands(subCommands3) {
  if (!subCommands3) {
    return;
  }
  return Object.fromEntries(
    Object.entries(subCommands3).sort(
      ([nameA], [nameB]) => nameA.localeCompare(nameB)
    )
  );
}

// src/utils/is-in-subcommand.mts
function isInSubcommand(context) {
  const {
    cmd: { subCommands: subCommands3 },
    rawArgs
  } = context;
  if (!subCommands3) {
    return false;
  }
  const potentialSubCommand = rawArgs.find((arg) => !arg.startsWith("-"));
  return potentialSubCommand !== void 0 && potentialSubCommand in subCommands3;
}

// src/utils/version.mts
var import_promises = require("fs/promises");
var import_confbox = require("confbox");
var import_consola = require("consola");
var import_ofetch = require("ofetch");
var import_pathe2 = require("pathe");
var import_pkg_types2 = require("pkg-types");
var import_std_env3 = require("std-env");

// src/utils/is-object.mts
function isObject(thing) {
  return typeof thing === "object" && thing !== null && !Array.isArray(thing);
}

// src/utils/package-manager.mts
var import_nypm = require("nypm");
var import_std_env2 = require("std-env");
async function getPackageManager() {
  const packageManager = await (0, import_nypm.detectPackageManager)(getCWD(), {
    ignoreArgv: true,
    includeParentDirs: true
  });
  if (packageManager) {
    return { ...packageManager, inProject: true };
  }
  const name = import_std_env2.isDeno ? "deno" : import_std_env2.isBun ? "bun" : "npm";
  return { name, command: name, inProject: false };
}

// src/utils/pkg-json.mts
var import_pkg_types = require("pkg-types");
var PACKAGE_JSONS = {};
async function getConsumerPackageJSON() {
  return await getPackageJSON({ startingFrom: getCWD() });
}
async function getCTLPackageJSON() {
  return await getPackageJSON({ id: "kysely-ctl" });
}
async function getPackageJSON(options) {
  const { id, startingFrom = __dirname } = options;
  return PACKAGE_JSONS[`${String(id)}_${startingFrom}`] ||= await (0, import_pkg_types.readPackageJSON)(id, { from: startingFrom });
}

// src/utils/version.mts
async function getKyselyInstalledVersion() {
  try {
    const pkgJSON = await getConsumerPackageJSON();
    const version = getVersionFromPackageJSON("kysely", pkgJSON);
    if (!version) {
      return null;
    }
    if (version.startsWith("catalog:")) {
      return await getVersionFromCatalog("kysely", version);
    }
    return version;
  } catch {
    return null;
  }
}
async function getCTLInstalledVersion() {
  try {
    const pkgJSON = await getCTLPackageJSON();
    return getVersionFromPackageJSON("kysely-ctl", pkgJSON);
  } catch {
    return null;
  }
}
function getVersionFromPackageJSON(name, pkgJSON) {
  if (pkgJSON.name === name) {
    return pkgJSON.version || null;
  }
  return pkgJSON.dependencies?.[name] || pkgJSON.devDependencies?.[name] || null;
}
async function printInstalledVersions() {
  const [cliVersion, kyselyVersion] = await Promise.all([
    getCTLInstalledVersion(),
    getKyselyInstalledVersion()
  ]);
  import_consola.consola.log(
    `kysely ${kyselyVersion ? `v${kyselyVersion}` : "[not installed]"}`
  );
  import_consola.consola.log(`kysely-ctl v${cliVersion}`);
}
async function getKyselyLatestVersion() {
  return await getPackageLatestVersion("kysely");
}
async function getCTLLatestVersion() {
  return await getPackageLatestVersion("kysely-ctl");
}
async function getPackageLatestVersion(packageName) {
  const response = await (0, import_ofetch.ofetch)(
    `https://registry.npmjs.org/${packageName}`
  );
  return response["dist-tags"].latest;
}
async function printUpgradeNotice(args12) {
  if (args12["outdated-check"] === false || import_std_env3.isCI) {
    return;
  }
  const [
    kyselyInstalledVersion,
    kyselyLatestVersion,
    ctlInstalledVersion,
    ctlLatestVersion
  ] = await Promise.all([
    getKyselyInstalledVersion(),
    getKyselyLatestVersion(),
    getCTLInstalledVersion(),
    getCTLLatestVersion()
  ]);
  const notices = [];
  if (!kyselyInstalledVersion?.includes(kyselyLatestVersion)) {
    notices.push([
      "Kysely",
      "kysely",
      kyselyInstalledVersion,
      kyselyLatestVersion
    ]);
  }
  if (!ctlInstalledVersion?.includes(ctlLatestVersion)) {
    notices.push([
      "KyselyCTL",
      "kysely-ctl",
      ctlInstalledVersion,
      ctlLatestVersion
    ]);
  }
  if (!notices.length) {
    return;
  }
  const { command, name: packageManagerName } = await getPackageManager();
  const installGloballyCommand = {
    bun: (name) => `add -g ${name}@latest`,
    deno: (name) => `install -g -f npm:${name}@latest`,
    npm: (name) => `i -g ${name}@latest`,
    pnpm: (name) => `add -g ${name}@latest`,
    // doesn't support global installs in modern versions.
    yarn: (name) => `add -D ${name}@latest`
  }[packageManagerName];
  const installLocallyCommand = {
    bun: (name, dev) => `add ${dev ? "-D " : ""}${name}@latest`,
    deno: (name, dev) => `install ${dev ? "-D " : ""}npm:${name}@latest`,
    npm: (name, dev) => `i ${dev ? "-D " : ""}${name}@latest`,
    pnpm: (name, dev) => `add ${dev ? "-D " : ""}${name}@latest`,
    yarn: (name, dev) => `add ${dev ? "-D " : ""}${name}@latest`
  }[packageManagerName];
  import_consola.consola.box(
    notices.map(
      ([prettyName, name, installedVersion, latestVersion]) => `A new ${prettyName} version is available: ${installedVersion ? `v${installedVersion}` : "[not installed]"} -> v${latestVersion}
Run \`${command} ${name === "kysely-ctl" ? installGloballyCommand(name) : installLocallyCommand(name)}\` to upgrade.`
    ).join("\n\n")
  );
}
async function getVersionFromCatalog(packageName, catalogReference) {
  const workspaceDirPath = await (0, import_pkg_types2.findWorkspaceDir)(getCWD());
  import_consola.consola.debug("workspaceDirPath", workspaceDirPath);
  if (import_std_env3.runtime === "node") {
    const rawWorkspaceFile = await (0, import_promises.readFile)(
      (0, import_pathe2.join)(workspaceDirPath, "pnpm-workspace.yaml"),
      { encoding: "utf8" }
    );
    import_consola.consola.debug("rawWorkspaceFile", rawWorkspaceFile);
    const workspaceFile = (0, import_confbox.parseYAML)(rawWorkspaceFile);
    import_consola.consola.debug("workspaceFile", workspaceFile);
    return extractVersionFromCatalogContainer(
      workspaceFile,
      packageName,
      catalogReference
    );
  }
  if (import_std_env3.isBun) {
    const rootPkgJSON = await (0, import_pkg_types2.readPackageJSON)(workspaceDirPath);
    import_consola.consola.debug("rootPkgJSON", rootPkgJSON);
    const { workspaces } = rootPkgJSON;
    if (!isObject(workspaces)) {
      return null;
    }
    return extractVersionFromCatalogContainer(
      workspaces,
      packageName,
      catalogReference
    );
  }
  return null;
}
var CATALOG_REFERENCE_PREFIX_REGEX = /^catalog:/;
function extractVersionFromCatalogContainer(container, packageName, catalogReference) {
  if (catalogReference === "catalog:") {
    return container.catalog?.[packageName] || null;
  }
  const catalogName = catalogReference.replace(
    CATALOG_REFERENCE_PREFIX_REGEX,
    ""
  );
  return container.catalogs?.[catalogName]?.[packageName] || null;
}

// src/commands/init.mts
var import_promises2 = require("fs/promises");
var import_consola5 = require("consola");
var import_pathe6 = require("pathe");

// src/arguments/cwd.mts
var CWDArg = defineArgs(
  {
    cwd: {
      description: "The current working directory to use for relative paths.",
      type: "string"
    }
  },
  true
);

// src/arguments/debug.mts
var DebugArg = defineArgs(
  {
    debug: {
      default: false,
      description: "Show debug information.",
      type: "boolean"
    }
  },
  true
);

// src/arguments/extension.mts
var TS_EXTENSIONS = ["ts", "mts", "cts"];
var JS_EXTENSIONS = ["js", "mjs", "cjs"];
var ALL_EXTENSIONS = [...TS_EXTENSIONS, ...JS_EXTENSIONS];
var ExtensionArg = defineArgs(
  {
    extension: {
      alias: "x",
      default: "ts",
      description: "The file extension to use.",
      type: "string",
      valueHint: ALL_EXTENSIONS.map((extension) => `"${extension}"`).join(
        " | "
      )
    }
  },
  true
);
function assertExtension(thing, config, context) {
  const allowJS = config?.[context || "migrations"].allowJS ?? true;
  if (!allowJS && JS_EXTENSIONS.includes(thing)) {
    throw new Error(
      `Invalid file extension "${thing}"! Expected ${TS_EXTENSIONS.map(
        (extension) => `"${extension}"`
      ).join(" | ")}. To use JS extensions, set "${context}.allowJS" to true.`
    );
  }
  const extensions = allowJS ? ALL_EXTENSIONS : TS_EXTENSIONS;
  if (!extensions.includes(thing)) {
    throw new Error(
      `Invalid file extension "${thing}"! Expected ${ExtensionArg.extension.valueHint}`
    );
  }
}

// src/arguments/no-outdated-check.mts
var NoOutdatedCheckArg = defineArgs(
  {
    "no-outdated-check": {
      description: "Will not check for latest kysely/kysely-ctl versions and notice newer versions exist.",
      type: "boolean"
    }
  },
  true
);

// src/config/get-config.mts
var import_c12 = require("c12");
var import_consola4 = require("consola");
var import_pathe5 = require("pathe");
var import_pkg_types3 = require("pkg-types");

// src/utils/jiti.mts
var import_consola3 = require("consola");
var import_pathe4 = require("pathe");
var import_std_env4 = require("std-env");

// src/utils/tsconfig.mts
var import_consola2 = require("consola");
var import_pathe3 = require("pathe");
var import_tsconfck = require("tsconfck");
var cache = new import_tsconfck.TSConfckCache();
async function getTSConfigs() {
  const { extended, tsconfig, tsconfigFile } = await (0, import_tsconfck.parse)(
    (0, import_pathe3.join)(getCWD(), "index.ts"),
    { cache }
  );
  import_consola2.consola.debug("extended", JSON.stringify(extended, null, 2));
  import_consola2.consola.debug("tsconfig", JSON.stringify(tsconfig, null, 2));
  return {
    configs: extended?.map((result) => ({
      filepath: result.tsconfigFile,
      tsconfig: result.tsconfig
    })) || (tsconfig ? [{ filepath: tsconfigFile, tsconfig }] : []),
    merged: tsconfig
  };
}

// src/utils/jiti.mts
async function getJiti(args12) {
  const jitiOptions = await getJitiOptions(args12);
  import_consola3.consola.debug("jitiOptions", jitiOptions);
  const { createJiti } = await import("jiti");
  return createJiti(importMetaUrl, jitiOptions);
}
async function getJitiOptions(args12) {
  return {
    alias: args12.experimentalResolveTSConfigPaths ? await getJitiAliasFromTSConfig() : void 0,
    debug: Boolean(args12.debug),
    fsCache: Boolean(args12.filesystemCaching),
    jsx: true,
    tryNative: import_std_env4.runtime !== "node"
  };
}
async function getJitiAliasFromTSConfig() {
  try {
    const { configs, merged } = await getTSConfigs();
    if (!configs.length) {
      return {};
    }
    const { filepath, paths } = resolvePaths(configs) || {};
    import_consola3.consola.debug("filepath", filepath);
    import_consola3.consola.debug("paths", JSON.stringify(paths, null, 2));
    if (!paths) {
      return {};
    }
    const { baseUrl = "." } = merged?.compilerOptions || {};
    const dirpath = (0, import_pathe4.dirname)(filepath);
    const jitiAlias = {};
    for (const [alias, [path]] of Object.entries(paths)) {
      if (!path) {
        continue;
      }
      jitiAlias[removeWildcards(alias)] = removeWildcards(
        (0, import_pathe4.resolve)(dirpath, baseUrl, path)
      );
    }
    return jitiAlias;
  } catch {
    return {};
  }
}
function resolvePaths(results) {
  for (const result of results) {
    const { filepath, tsconfig } = result;
    const { paths } = tsconfig.compilerOptions || {};
    if (paths) {
      return {
        filepath,
        paths
      };
    }
  }
  return null;
}
var WILDCARDS_REGEX = /(\/\*{1,2}|\*)+$/;
function removeWildcards(path) {
  return path.replace(WILDCARDS_REGEX, "");
}

// src/config/get-file-prefix.mts
function getMillisPrefix() {
  return `${Date.now()}_`;
}

// src/config/get-config.mts
var CAPTURE_DOT_CONFIG_FOLDER = /\/\.config$/;
async function getConfig(args12) {
  const { config: configArg, environment } = args12;
  const configPath = configArg ? (0, import_pathe5.resolve)(getCWD(), (0, import_pathe5.dirname)(configArg)) : await findNearestKyselyConfigPath();
  if (!configPath) {
    return null;
  }
  const jiti = await getJiti({
    debug: args12.debug,
    filesystemCaching: args12["filesystem-caching"],
    experimentalResolveTSConfigPaths: args12["experimental-resolve-tsconfig-paths"]
  });
  import_consola4.consola.debug("configPath", configPath);
  const loadedConfig = await (0, import_c12.loadConfig)({
    configFile: configArg ? (0, import_pathe5.basename)(configArg) : void 0,
    cwd: configPath,
    dotenv: {
      cwd: configPath.replace(CAPTURE_DOT_CONFIG_FOLDER, ""),
      fileName: environment ? [".env", `.env.${environment}`] : ".env"
    },
    envName: environment,
    jiti,
    globalRc: false,
    name: configArg ? void 0 : "kysely",
    packageJson: false,
    rcFile: false
  });
  import_consola4.consola.debug("loadedConfig", loadedConfig);
  const { config, ...configMetadata } = loadedConfig;
  return {
    ...config,
    args: args12,
    configMetadata,
    cwd: configPath,
    migrations: {
      allowJS: false,
      getMigrationPrefix: getMillisPrefix,
      ...config.migrations,
      disableTransactions: args12.transaction === false || config.migrations?.disableTransactions,
      migrationFolder: resolveCollectionFolderPath(
        configPath,
        config.migrations?.migrationFolder,
        "migrations"
      )
    },
    seeds: {
      allowJS: false,
      getSeedPrefix: getMillisPrefix,
      ...config.seeds,
      seedFolder: resolveCollectionFolderPath(
        configPath,
        config.seeds?.seedFolder,
        "seeds"
      )
    }
  };
}
async function getConfigOrFail(args12) {
  const config = await getConfig(args12);
  if (!configFileExists(config)) {
    throw new Error(
      "No config file found. Try creating one by running `kysely init`."
    );
  }
  return config;
}
function configFileExists(config) {
  if (!config) {
    return false;
  }
  const { configFile } = config.configMetadata;
  return configFile !== void 0 && configFile !== "kysely.config";
}
var BASE_CONFIG_FILESNAMES = ALL_EXTENSIONS.flatMap((extension) => [
  `.config/kysely.config.${extension}`,
  `kysely.config.${extension}`
]);
async function findNearestKyselyConfigPath() {
  try {
    const kyselyConfigPath = await (0, import_pkg_types3.findNearestFile)(BASE_CONFIG_FILESNAMES, {
      startingFrom: getCWD()
    });
    import_consola4.consola.debug("found kysely config file at", kyselyConfigPath);
    return (0, import_pathe5.dirname)(kyselyConfigPath);
  } catch {
    return null;
  }
}
function resolveCollectionFolderPath(configPath, configuredFolderPath, defaultFolderName) {
  const defaultRelativeFolderPath = `${(0, import_pathe5.basename)(configPath) === ".config" ? "../" : "./"}${defaultFolderName}`;
  return (0, import_pathe5.resolve)(configPath, configuredFolderPath || defaultRelativeFolderPath);
}

// src/utils/create-subcommand.mts
function createSubcommand(name, def) {
  return {
    [name]: { ...def, meta: { ...def.meta, name } }
  };
}

// src/utils/get-template-extension.mts
async function getTemplateExtension(extension) {
  if (extension === "js") {
    const pkgJSON = await getConsumerPackageJSON();
    return pkgJSON.type === "module" ? "mjs" : "cjs";
  }
  return extension === "cjs" || extension === "mjs" ? extension : "ts";
}

// src/commands/init.mts
var args = defineArgs({
  ...CWDArg,
  ...DebugArg,
  ...ExtensionArg,
  ...NoOutdatedCheckArg
});
var Command = defineCommand(args, {
  meta: {
    description: "Create a sample `kysely.config` file"
  },
  async run(context) {
    const { args: args12 } = context;
    const { extension } = args12;
    import_consola5.consola.debug(context, []);
    const config = await getConfig(args12);
    if (configFileExists(config)) {
      return import_consola5.consola.warn(
        `Init skipped: config file already exists at ${config.configMetadata.configFile}`
      );
    }
    assertExtension(extension);
    const configFolderPath = (0, import_pathe6.join)(getCWD(), ".config");
    import_consola5.consola.debug("Config folder path:", configFolderPath);
    const wasConfigFolderCreated = Boolean(
      await (0, import_promises2.mkdir)(configFolderPath, { recursive: true })
    );
    if (wasConfigFolderCreated) {
      import_consola5.consola.debug("Config folder created");
    }
    const filePath = (0, import_pathe6.join)(configFolderPath, `kysely.config.${extension}`);
    import_consola5.consola.debug("File path:", filePath);
    const templateExtension = await getTemplateExtension(extension);
    const templatePath = (0, import_pathe6.join)(
      __dirname,
      `templates/config-template.${templateExtension}`
    );
    import_consola5.consola.debug("Template path:", templatePath);
    await (0, import_promises2.copyFile)(templatePath, filePath);
    import_consola5.consola.success(`Config file created at ${filePath}`);
  }
});
var InitCommand = createSubcommand("init", Command);

// src/commands/migrate/down.mts
var import_consola10 = require("consola");

// src/arguments/config.mts
var ConfigArg = defineArgs(
  {
    config: {
      alias: "c",
      description: "Path to the config file.",
      type: "string"
    }
  },
  true
);

// src/arguments/environment.mts
var EnvironmentArg = defineArgs(
  {
    environment: {
      alias: "e",
      description: "Apply environment-specific overrides to the configuration. See https://github.com/unjs/c12#environment-specific-configuration for more information.",
      type: "string",
      valueHint: "production | development | test | ..."
    }
  },
  true
);

// src/arguments/jiti.mts
var JitiArgs = defineArgs(
  {
    "experimental-resolve-tsconfig-paths": {
      default: false,
      description: "Attempts to resolve path aliases using your `tsconfig.json` file/s.",
      type: "boolean"
    },
    "no-filesystem-caching": {
      description: "Will not write cache files to disk. See https://github.com/unjs/jiti#fscache for more information.",
      type: "boolean"
    }
  },
  true
);

// src/arguments/common.mts
var CommonArgs = defineArgs({
  ...ConfigArg,
  ...CWDArg,
  ...DebugArg,
  ...EnvironmentArg,
  ...JitiArgs,
  ...NoOutdatedCheckArg
});

// src/arguments/migrate.mts
var MigrateArgs = defineArgs(
  {
    "no-transaction": {
      description: "Don't use a transaction when running the migrations. This will not work for now if you've provided your own Migrator factory.",
      type: "boolean"
    }
  },
  true
);

// src/arguments/migration-name.mts
var createMigrationNameArg = (required = false) => defineArgs(
  {
    migration_name: {
      description: "Migration name to run/undo.",
      required,
      type: "positional"
    }
  },
  true
);

// src/kysely/is-wrong-direction.mts
async function isWrongDirection(migrationName, expectedDirection, migrator) {
  if (!migrationName) {
    return false;
  }
  const migrations2 = await migrator.getMigrations();
  return migrations2.find(
    (migration) => migration.name === migrationName && (expectedDirection === "up" && migration.executedAt !== void 0 || expectedDirection === "down" && !migration.executedAt)
  ) !== void 0;
}

// src/kysely/process-migration-result-set.mts
var import_consola7 = require("consola");
var import_utils = require("consola/utils");

// src/utils/assert-defined.mts
function assertDefined(thing) {
  if (thing === void 0) {
    throw new Error("Expected value to be defined");
  }
}

// src/utils/error.mts
var import_consola6 = require("consola");
var import_std_env5 = require("std-env");
function exitWithError(error) {
  if (error instanceof AggregateError) {
    for (const subError of error.errors) {
      import_consola6.consola.error(subError);
    }
  } else {
    import_consola6.consola.error(error);
  }
  import_std_env5.process.exit?.(1);
  throw error;
}

// src/kysely/get-migrations.mts
var migrations;
async function getMigrations(migrator) {
  return migrations ||= await migrator.getMigrations();
}

// src/kysely/process-migration-result-set.mts
async function processMigrationResultSet(resultSet, direction, migrator) {
  import_consola7.consola.debug(resultSet);
  let { error, results } = resultSet;
  if (error) {
    const failedMigration = results?.find((result) => result.status === "Error");
    import_consola7.consola.fail(
      `Migration failed with \`${error}\`${failedMigration ? ` @ "${failedMigration.migrationName}"` : ""}`
    );
    exitWithError(error);
  }
  if (!results?.length) {
    return import_consola7.consola.info(
      `Migration skipped: no ${direction === "up" ? "new" : "completed"} migrations found`
    );
  }
  import_consola7.consola.success("Migration complete");
  import_consola7.consola.info(
    `${direction === "up" ? "Ran" : "Undone"} ${results.length} migration${results.length > 1 ? "s" : ""}:`
  );
  if (direction === "down") {
    results = [...results].reverse();
  }
  const migrations2 = await getMigrations(migrator);
  const firstResult = results[0];
  assertDefined(firstResult);
  const { migrationName: firstResultMigrationName } = firstResult;
  const untouchedMigrationsBefore = migrations2.slice(
    0,
    migrations2.findIndex(
      (migration) => migration.name === firstResultMigrationName
    )
  );
  const lastResult = results.at(-1);
  assertDefined(lastResult);
  const { migrationName: lastResultMigrationName } = lastResult;
  const untouchedMigrationsAfter = migrations2.slice(
    migrations2.findIndex(
      (migration) => migration.name === lastResultMigrationName
    ) + 1
  );
  for (const migration of untouchedMigrationsBefore) {
    import_consola7.consola.log(`[\u2713] ${migration.name}`);
  }
  for (const result of results) {
    import_consola7.consola.log(
      `[${(0, import_utils.colorize)("green", result.direction === "Up" ? "\u2713" : "\u237B")}] ${result.migrationName}`
    );
  }
  for (const migration of untouchedMigrationsAfter) {
    import_consola7.consola.log(`[ ] ${migration.name}`);
  }
}

// src/kysely/get-migrator.mts
var import_kysely = require("kysely");

// src/utils/hydrate.mts
async function hydrate(factory, parameters, defaultValue) {
  if (factory == null) {
    return defaultValue?.() ?? factory;
  }
  if (typeof factory !== "function") {
    return factory;
  }
  return await factory(...parameters);
}

// src/kysely/ts-file-migration-provider.mts
var import_consola8 = require("consola");
var import_pathe7 = require("pathe");
var import_utils2 = require("pathe/utils");

// src/utils/get-file-type.mts
function getFileType(path) {
  let extension = "";
  const lastIndex = path.length - 1;
  let i = 0;
  for (; i < 3; i++) {
    const char = path.charAt(lastIndex - i);
    if (char === ".") {
      break;
    }
    extension = `${char}${extension}`;
  }
  if (extension.length < 2 || path.charAt(lastIndex - i) !== "." || path.charAt(lastIndex - (i + 1)) === "d" && path.charAt(lastIndex - (i + 2)) === ".") {
    return "IRRELEVANT";
  }
  if (["ts", "mts", "cts"].includes(extension)) {
    return "TS";
  }
  if (["js", "mjs", "cjs"].includes(extension)) {
    return "JS";
  }
  return "IRRELEVANT";
}

// src/utils/import-ts-file.mts
var import_std_env6 = require("std-env");
async function importTSFile(path, args12) {
  if (import_std_env6.runtime !== "node") {
    return await import(path);
  }
  const jiti = await getJiti(args12);
  return await jiti.import(path);
}

// src/utils/safe-readdir.mts
var import_promises3 = require("fs/promises");
async function safeReaddir(path) {
  try {
    return await (0, import_promises3.readdir)(path);
  } catch {
    await (0, import_promises3.mkdir)(path);
    return await (0, import_promises3.readdir)(path);
  }
}

// src/kysely/ts-file-migration-provider.mts
var TSFileMigrationProvider = class {
  #props;
  constructor(props) {
    this.#props = props;
  }
  async getMigrations() {
    const files = await safeReaddir(this.#props.migrationFolder);
    const migrations2 = {};
    for (const fileName of files) {
      const fileType = getFileType(fileName);
      const isTS = fileType === "TS";
      if (!isTS) {
        if (!this.#props.allowJS) {
          import_consola8.consola.warn(`Ignoring \`${fileName}\` - not a TS file.`);
          continue;
        }
        if (fileType !== "JS") {
          import_consola8.consola.warn(`Ignoring \`${fileName}\` - not a TS/JS file.`);
          continue;
        }
      }
      const filePath = (0, import_pathe7.join)(this.#props.migrationFolder, fileName);
      const migrationModule = await (isTS ? importTSFile(filePath, this.#props) : import(filePath));
      const migrationKey = (0, import_utils2.filename)(fileName);
      if (!migrationKey) {
        continue;
      }
      const migration = isMigration(migrationModule?.default) ? migrationModule.default : isMigration(migrationModule) ? migrationModule : null;
      if (!migration) {
        import_consola8.consola.warn(`Ignoring \`${fileName}\` - not a migration.`);
        continue;
      }
      migrations2[migrationKey] = migration;
    }
    return migrations2;
  }
};
function isMigration(thing) {
  return isObject(thing) && typeof thing.up === "function";
}

// src/kysely/get-migrator.mts
async function getMigrator(config) {
  const { args: args12, kysely, migrations: migrations2 } = config;
  const { allowJS, migrationFolder, migrator, ...migratorOptions } = migrations2;
  if (migrator) {
    return await hydrate(migrator, [kysely]);
  }
  const provider = await hydrate(
    migrations2.provider,
    [],
    () => new TSFileMigrationProvider({
      allowJS,
      debug: args12.debug,
      experimentalResolveTSConfigPaths: args12["experimental-resolve-tsconfig-paths"],
      filesystemCaching: args12["filesystem-caching"],
      migrationFolder
    })
  );
  return new import_kysely.Migrator({ ...migratorOptions, db: kysely, provider });
}

// src/kysely/get-kysely.mts
var import_consola9 = require("consola");
var import_kysely3 = require("kysely");

// src/kysely/get-dialect.mts
var import_kysely2 = require("kysely");
async function getDialect(config) {
  const { dialect } = config;
  if (!dialect) {
    throw new Error("No dialect provided");
  }
  if (typeof dialect !== "string") {
    return await hydrate(dialect, []);
  }
  const dialectConfig = await hydrate(config.dialectConfig, []);
  if (dialect === "pg") {
    return new import_kysely2.PostgresDialect(dialectConfig);
  }
  if (dialect === "mysql2") {
    return new import_kysely2.MysqlDialect(dialectConfig);
  }
  if (dialect === "tedious") {
    return new (await import("kysely")).MssqlDialect(dialectConfig);
  }
  if (dialect === "better-sqlite3") {
    return new import_kysely2.SqliteDialect(dialectConfig);
  }
  if (dialect === "postgres" || dialect === "bun") {
    return new (await import("kysely-postgres-js")).PostgresJSDialect(
      dialectConfig
    );
  }
  if (dialect === "@neondatabase/serverless") {
    return new (await import("kysely-neon")).NeonDialect(dialectConfig);
  }
  dialect;
  throw new Error(`Unknown dialect: "${dialect}"`);
}

// src/kysely/get-kysely.mts
async function getKysely(config, debug = false) {
  const { kysely } = config;
  if (kysely) {
    return await hydrate(kysely, []);
  }
  const [dialect, plugins] = await Promise.all([
    getDialect(config),
    hydrate(config.plugins, [])
  ]);
  return new import_kysely3.Kysely({
    dialect,
    log: debug ? (event) => {
      if (event.level === "error") {
        return import_consola9.consola.error(event.error);
      }
      return import_consola9.consola.log(
        `executed \`${event.query.sql}\` in ${event.queryDurationMillis}ms`
      );
    } : [],
    plugins
  });
}

// src/kysely/using-kysely.mts
async function usingKysely(config, callback) {
  const kysely = await getKysely(config);
  try {
    return await callback(kysely);
  } finally {
    if (config.destroyOnExit !== false) {
      await kysely.destroy();
    }
  }
}

// src/kysely/using-migrator.mts
async function usingMigrator(args12, callback) {
  const config = await getConfigOrFail(args12);
  return await usingKysely(config, async (kysely) => {
    const migrator = await getMigrator({ ...config, kysely });
    return await callback(migrator);
  });
}

// src/commands/migrate/down.mts
var args2 = defineArgs({
  ...CommonArgs,
  ...MigrateArgs,
  ...createMigrationNameArg()
});
var Command2 = defineCommand(args2, {
  meta: {
    description: "Undo the last/specified migration that was run"
  },
  async run(context) {
    const { args: args12 } = context;
    const { migration_name } = context.args;
    import_consola10.consola.debug(context, []);
    await usingMigrator(args12, async (migrator) => {
      if (await isWrongDirection(migration_name, "down", migrator)) {
        return import_consola10.consola.info(
          `Migration skipped: "${migration_name}" has not been run yet`
        );
      }
      import_consola10.consola.start("Starting migration down");
      const resultSet = migration_name ? await migrator.migrateTo(migration_name) : await migrator.migrateDown();
      await processMigrationResultSet(resultSet, "down", migrator);
    });
  }
});
var DownCommand = createSubcommand("down", Command2);
var LegacyDownCommand = createSubcommand("migrate:down", Command2);

// src/commands/migrate/latest.mts
var import_consola11 = require("consola");
var args3 = defineArgs({ ...CommonArgs, ...MigrateArgs });
var Command3 = defineCommand(args3, {
  meta: {
    description: "Update the database schema to the latest version"
  },
  async run(context) {
    import_consola11.consola.debug(context, []);
    await usingMigrator(context.args, async (migrator) => {
      import_consola11.consola.start("Starting migration to latest");
      const resultSet = await migrator.migrateToLatest();
      await processMigrationResultSet(resultSet, "up", migrator);
    });
  }
});
var LatestCommand = createSubcommand("latest", Command3);
var LegacyLatestCommand = createSubcommand("migrate:latest", Command3);

// src/commands/migrate/list.mts
var import_consola12 = require("consola");
var args4 = defineArgs({
  ...CommonArgs,
  "fail-on-pending": {
    default: false,
    description: "Fail if there are pending migrations",
    type: "boolean"
  }
});
var Command4 = defineCommand(args4, {
  meta: {
    description: "List both completed and pending migrations"
  },
  async run(context) {
    import_consola12.consola.debug(context, []);
    const migrations2 = await usingMigrator(context.args, getMigrations);
    import_consola12.consola.debug(migrations2);
    if (!migrations2.length) {
      return import_consola12.consola.info("No migrations found.");
    }
    import_consola12.consola.info(
      `Found ${migrations2.length} migration${migrations2.length > 1 ? "s" : ""}:`
    );
    for (const migration of migrations2) {
      import_consola12.consola.log(`[${migration.executedAt ? "`\u2713`" : " "}] ${migration.name}`);
    }
    if (!context.args["fail-on-pending"]) {
      return;
    }
    const hasPending = migrations2.some(
      (migration) => migration.executedAt == null
    );
    if (hasPending) {
      exitWithError("Failed due to pending migrations.");
    }
  }
});
var ListCommand = createSubcommand("list", Command4);
var LegacyListCommand = createSubcommand("migrate:list", Command4);

// src/commands/migrate/make.mts
var import_promises4 = require("fs/promises");
var import_consola13 = require("consola");
var import_pathe8 = require("pathe");
var args5 = defineArgs({
  ...CommonArgs,
  ...createMigrationNameArg(true),
  ...ExtensionArg
});
var Command5 = defineCommand(args5, {
  meta: {
    description: "Create a new migration file"
  },
  async run(context) {
    const { args: args12 } = context;
    const { extension } = args12;
    import_consola13.consola.debug(context, []);
    const config = await getConfigOrFail(args12);
    assertExtension(extension, config, "migrations");
    const { getMigrationPrefix, migrationFolder } = config.migrations;
    const wasMigrationsFolderCreated = Boolean(
      await (0, import_promises4.mkdir)(migrationFolder, { recursive: true })
    );
    if (wasMigrationsFolderCreated) {
      import_consola13.consola.debug("Migrations folder created");
    }
    const filename3 = `${await getMigrationPrefix()}${args12.migration_name}.${extension}`;
    import_consola13.consola.debug("Filename:", filename3);
    const filePath = (0, import_pathe8.join)(migrationFolder, filename3);
    import_consola13.consola.debug("File path:", filePath);
    const templateExtension = await getTemplateExtension(extension);
    const templatePath = (0, import_pathe8.join)(
      __dirname,
      `templates/migration-template.${templateExtension}`
    );
    import_consola13.consola.debug("Template path:", templatePath);
    await (0, import_promises4.copyFile)(templatePath, filePath);
    import_consola13.consola.success(`Created migration file at ${filePath}`);
  }
});
var MakeCommand = createSubcommand("make", Command5);
var LegacyMakeCommand = createSubcommand("migrate:make", Command5);

// src/commands/migrate/rollback.mts
var import_consola14 = require("consola");
var import_kysely4 = require("kysely");
var args6 = defineArgs({
  ...CommonArgs,
  ...MigrateArgs,
  all: {
    description: "Rollback all completed migrations",
    required: true,
    // remove this if and when Migrator supports migration batches.
    type: "boolean"
  }
});
var Command6 = defineCommand(args6, {
  meta: {
    description: "Rollback all the completed migrations"
  },
  async run(context) {
    import_consola14.consola.debug(context, []);
    await usingMigrator(context.args, async (migrator) => {
      import_consola14.consola.start("Starting migration rollback");
      const resultSet = await migrator.migrateTo(import_kysely4.NO_MIGRATIONS);
      await processMigrationResultSet(resultSet, "down", migrator);
    });
  }
});
var RollbackCommand = createSubcommand("rollback", Command6);
var LegacyRollbackCommand = createSubcommand(
  "migrate:rollback",
  Command6
);

// src/commands/migrate/root.mts
var import_citty = require("citty");
var import_consola16 = require("consola");

// src/commands/migrate/up.mts
var import_consola15 = require("consola");
var args7 = defineArgs({
  ...CommonArgs,
  ...MigrateArgs,
  ...createMigrationNameArg()
});
var Command7 = defineCommand(args7, {
  meta: {
    description: "Run the next migration that has not yet been run"
  },
  async run(context) {
    const { args: args12 } = context;
    const { migration_name } = args12;
    import_consola15.consola.debug(context, []);
    await usingMigrator(args12, async (migrator) => {
      if (await isWrongDirection(migration_name, "up", migrator)) {
        return import_consola15.consola.info(
          `Migration skipped: migration "${migration_name}" has already been run`
        );
      }
      import_consola15.consola.start("Starting migration up");
      const resultSet = migration_name ? await migrator.migrateTo(migration_name) : await migrator.migrateUp();
      await processMigrationResultSet(resultSet, "up", migrator);
    });
  }
});
var UpCommand = createSubcommand("up", Command7);
var LegacyUpCommand = createSubcommand("migrate:up", Command7);

// src/commands/migrate/root.mts
var subCommands = {
  ...DownCommand,
  ...LatestCommand,
  ...ListCommand,
  ...MakeCommand,
  ...RollbackCommand,
  ...UpCommand
  // biome-ignore lint/suspicious/noExplicitAny: it's fine
};
var MigrateCommand = createSubcommand("migrate", {
  args: {},
  meta: {
    description: `\`${Object.keys(subCommands).sort().join("|")}\``
  },
  async run(context) {
    if (!isInSubcommand(context)) {
      import_consola16.consola.debug(context, []);
      await (0, import_citty.showUsage)(context.cmd, RootCommand);
    }
  },
  subCommands
});

// src/commands/seed/make.mts
var import_promises5 = require("fs/promises");
var import_consola17 = require("consola");
var import_pathe9 = require("pathe");
var args8 = defineArgs({
  ...CommonArgs,
  ...ExtensionArg,
  seed_name: {
    description: "Seed file name to create",
    required: true,
    type: "positional"
  }
});
var Command8 = defineCommand(args8, {
  meta: {
    description: "Create a new seed file"
  },
  async run(context) {
    const { args: args12 } = context;
    const { extension } = args12;
    import_consola17.consola.debug(context, []);
    const config = await getConfigOrFail(args12);
    assertExtension(extension, config, "seeds");
    const { getSeedPrefix, seedFolder } = config.seeds;
    const wasSeedsFolderCreated = Boolean(
      await (0, import_promises5.mkdir)(seedFolder, { recursive: true })
    );
    if (wasSeedsFolderCreated) {
      import_consola17.consola.debug("Seeds folder created");
    }
    const filename3 = `${await getSeedPrefix()}${args12.seed_name}.${extension}`;
    import_consola17.consola.debug("Filename:", filename3);
    const filePath = (0, import_pathe9.join)(seedFolder, filename3);
    import_consola17.consola.debug("File path:", filePath);
    const templateExtension = await getTemplateExtension(extension);
    const templatePath = (0, import_pathe9.join)(
      __dirname,
      `templates/seed-template.${templateExtension}`
    );
    import_consola17.consola.debug("Template path:", templatePath);
    await (0, import_promises5.copyFile)(templatePath, filePath);
    import_consola17.consola.success(`Created seed file at ${filePath}`);
  }
});
var MakeCommand2 = createSubcommand("make", Command8);
var LegacyMakeCommand2 = createSubcommand("seed:make", Command8);

// src/commands/seed/root.mts
var import_citty2 = require("citty");
var import_consola21 = require("consola");

// src/commands/seed/list.mts
var import_consola19 = require("consola");

// src/seeds/file-seed-provider.mts
var import_consola18 = require("consola");
var import_pathe10 = require("pathe");
var import_utils3 = require("pathe/utils");

// src/utils/as-array.mts
function asArray(thing) {
  return Array.isArray(thing) ? thing : [thing];
}

// src/seeds/file-seed-provider.mts
var FileSeedProvider = class {
  #props;
  constructor(props) {
    this.#props = props;
  }
  async getSeeds(seedNames) {
    const seedNamesMap = {};
    if (seedNames) {
      for (const seedName of asArray(seedNames)) {
        seedNamesMap[seedName] = true;
      }
    }
    const fileNames = await safeReaddir(this.#props.seedFolder);
    const seeds = {};
    for (const fileName of fileNames) {
      const fileType = getFileType(fileName);
      const isTS = fileType === "TS";
      if (!isTS) {
        if (!this.#props.allowJS) {
          import_consola18.consola.warn(`Ignoring \`${fileName}\` - not a TS file.`);
          continue;
        }
        if (fileType !== "JS") {
          import_consola18.consola.warn(`Ignoring \`${fileName}\` - not a TS/JS file.`);
          continue;
        }
      }
      const seedKey = (0, import_utils3.filename)(fileName);
      if (!seedKey || seedNames && !seedNamesMap[seedKey]) {
        continue;
      }
      const filePath = (0, import_pathe10.join)(this.#props.seedFolder, fileName);
      const seedModule = await (isTS ? importTSFile(filePath, this.#props) : import(filePath));
      const seed = isSeed(seedModule?.default) ? seedModule.default : isSeed(seedModule) ? seedModule : null;
      if (!seed) {
        import_consola18.consola.warn(`Ignoring \`${fileName}\` - not a seed.`);
        continue;
      }
      seeds[seedKey] = seed;
    }
    return seeds;
  }
};
function isSeed(thing) {
  return isObject(thing) && typeof thing.seed === "function";
}

// src/seeds/seeder.mts
var Seeder = class {
  #props;
  constructor(props) {
    this.#props = props;
  }
  async getSeeds(seedNames) {
    const seeds = await this.#props.provider.getSeeds(seedNames);
    return Object.entries(seeds).map(([name, seed]) => ({
      name,
      seed
    }));
  }
  async run(seedNames) {
    const seeds = await this.getSeeds(seedNames);
    const resultSet = {
      error: void 0,
      results: seeds.map(
        (seed) => ({
          seedName: seed.name,
          status: "NotExecuted"
        })
      )
    };
    for (let i = 0, len = seeds.length; i < len && !resultSet.error; ++i) {
      const result = resultSet.results[i];
      assertDefined(result);
      const seedInfo = seeds[i];
      assertDefined(seedInfo);
      try {
        await seedInfo.seed.seed(this.#props.db);
        result.status = "Success";
      } catch (err) {
        result.status = "Error";
        resultSet.error = err;
      }
    }
    return resultSet;
  }
};

// src/seeds/get-seeder.mts
async function getSeeder(config) {
  const { args: args12, kysely, seeds } = config;
  const { allowJS, seedFolder, seeder, ...seederOptions } = seeds;
  if (seeder) {
    return await hydrate(seeder, [kysely]);
  }
  const provider = await hydrate(
    seeds.provider,
    [],
    () => new FileSeedProvider({
      allowJS,
      debug: args12.debug,
      filesystemCaching: args12["filesystem-caching"],
      experimentalResolveTSConfigPaths: args12["experimental-resolve-tsconfig-paths"],
      seedFolder
    })
  );
  return new Seeder({ ...seederOptions, db: kysely, provider });
}

// src/seeds/using-seeder.mts
async function usingSeeder(args12, callback) {
  const config = await getConfigOrFail(args12);
  return await usingKysely(config, async (kysely) => {
    const seeder = await getSeeder({ ...config, kysely });
    return await callback(seeder);
  });
}

// src/commands/seed/list.mts
var Command9 = defineCommand(CommonArgs, {
  meta: {
    description: "List seeds"
  },
  async run(context) {
    import_consola19.consola.debug(context, []);
    const seeds = await usingSeeder(context.args, (seeder) => seeder.getSeeds());
    import_consola19.consola.debug(seeds);
    if (!seeds.length) {
      return import_consola19.consola.info("No seeds found.");
    }
    import_consola19.consola.info(`Found ${seeds.length} seed${seeds.length > 1 ? "s" : ""}:`);
    for (const seed of seeds) {
      import_consola19.consola.log(seed.name);
    }
  }
});
var ListCommand2 = createSubcommand("list", Command9);

// src/commands/seed/run.mts
var import_consola20 = require("consola");
var import_utils4 = require("consola/utils");
var args9 = defineArgs({
  ...CommonArgs,
  specific: {
    description: "Run seed file/s with given name/s",
    type: "string"
  }
});
var Command10 = defineCommand(args9, {
  meta: {
    description: "Run seed files"
  },
  async run(context) {
    const { args: args12 } = context;
    const { specific } = args12;
    import_consola20.consola.debug(context, []);
    import_consola20.consola.start("Starting seed run");
    const resultSet = await usingSeeder(args12, (seeder) => seeder.run(specific));
    import_consola20.consola.debug(resultSet);
    const { error, results } = resultSet;
    if (!results.length) {
      return import_consola20.consola.info("No seeds found.");
    }
    if (!error) {
      import_consola20.consola.success("Seed successful");
    }
    const actuallyRan = error ? results.filter((result) => result.status !== "NotExecuted") : results;
    import_consola20.consola.info(
      `Ran ${actuallyRan.length} seed${actuallyRan.length > 1 ? "s" : ""}:`
    );
    for (const result of results) {
      import_consola20.consola.log(
        `[${{
          Error: (0, import_utils4.colorize)("red", "\u2717"),
          NotExecuted: " ",
          Success: (0, import_utils4.colorize)("green", "\u2713")
        }[result.status]}] ${result.seedName}${error && result.status === "Error" ? ` - ${error}` : ""}`
      );
    }
    if (error) {
      exitWithError(error);
    }
  }
});
var RunCommand = createSubcommand("run", Command10);
var LegacyRunCommand = createSubcommand("seed:run", Command10);

// src/commands/seed/root.mts
var subCommands2 = {
  ...ListCommand2,
  ...MakeCommand2,
  ...RunCommand
  // biome-ignore lint/suspicious/noExplicitAny: it's fine
};
var SeedCommand = createSubcommand("seed", {
  args: {},
  meta: {
    description: `\`${Object.keys(subCommands2).sort().join("|")}\``
  },
  async run(context) {
    if (!isInSubcommand(context)) {
      import_consola21.consola.debug(context, []);
      await (0, import_citty2.showUsage)(context.cmd, RootCommand);
    }
  },
  subCommands: subCommands2
});

// src/commands/sql.mts
var import_promises6 = require("readline/promises");
var import_consola23 = require("consola");
var import_utils5 = require("consola/utils");
var import_std_env7 = require("std-env");

// src/kysely/execute-query.mts
var import_kysely5 = require("kysely");
async function executeQuery(query, config) {
  return await config.kysely.executeQuery(
    import_kysely5.CompiledQuery.raw(query.sql, query.parameters)
  );
}

// src/kysely/infer-dialect-name.mts
var CAPTURE_COMMON_CLASS_SUFFIXES = /adapter|dialect/gi;
function inferDialectName(kysely) {
  return kysely.getExecutor().adapter.constructor.name.replaceAll(CAPTURE_COMMON_CLASS_SUFFIXES, "").toLowerCase();
}

// src/utils/print-csv.mts
var import_consola22 = require("consola");
function printCSV(rows) {
  const [row0] = rows;
  if (!row0) {
    return;
  }
  import_consola22.consola.log(`"${Object.keys(row0).join('","')}"`);
  for (const row of rows) {
    const transformedValues = [];
    for (const value of Object.values(row)) {
      transformedValues.push(typeof value === "string" ? `"${value}"` : value);
    }
    import_consola22.consola.log(transformedValues.join(","));
  }
}

// src/commands/sql.mts
var args10 = defineArgs({
  ...CommonArgs,
  format: {
    alias: "f",
    default: "csv",
    description: "The format to output the result in.",
    required: false,
    type: "string",
    valueHint: "csv | json"
  },
  query: {
    description: "The SQL query to execute. When not provided, and not in CI, will open an interactive SQL shell.",
    required: import_std_env7.isCI,
    type: "positional"
  }
});
var Command11 = defineCommand(args10, {
  meta: {
    name: "sql",
    description: "Execute SQL queries"
  },
  subCommands: {},
  async run(context) {
    const { args: args12 } = context;
    const { format, query } = args12;
    import_consola23.consola.debug(context, []);
    assertQuery(query);
    assertFormat(format);
    const config = await getConfigOrFail(args12);
    await usingKysely(config, async (kysely) => {
      const hydratedConfig = { ...config, kysely };
      if (query) {
        return await executeQueryAndPrint(args12, hydratedConfig);
      }
      await startInteractiveExecution(args12, hydratedConfig);
    });
  }
});
var SqlCommand = createSubcommand("sql", Command11);
function assertQuery(thing) {
  if (!import_std_env7.isCI && typeof thing !== "string" || typeof thing === "string" && thing.length > 0) {
    return;
  }
  throw new Error("Query must be a non-empty string!");
}
var FORMATS = ["csv", "json"];
function assertFormat(thing) {
  if (thing == null || FORMATS.includes(thing)) {
    return;
  }
  throw new Error(
    `Invalid format "${thing}"! Expected ${FORMATS.map(
      (format) => `"${format}"`
    ).join(" | ")}`
  );
}
async function executeQueryAndPrint(argz, config) {
  const result = await executeQuery({ sql: argz.query }, config);
  if (argz.format === "json") {
    return import_consola23.consola.log(JSON.stringify(result, null, 2));
  }
  const { insertId, numAffectedRows, numChangedRows, rows } = result;
  const [row0] = rows;
  if (!row0 && (insertId != null || numAffectedRows != null || numChangedRows != null)) {
    const summary = {
      "Affected Rows": numAffectedRows,
      "Changed Rows": numChangedRows,
      "Insert ID": insertId,
      rowCount: rows.length
    };
    return printCSV([summary]);
  }
  return printCSV(rows);
}
async function startInteractiveExecution(argz, config) {
  while (true) {
    let query = await import_consola23.consola.prompt(getPrompt(argz, config), {
      cancel: "null",
      placeholder: "select 1;",
      required: true,
      type: "text"
    });
    if (query == null) {
      return;
    }
    query = query.trim();
    if (isSafeword(query)) {
      return;
    }
    if (!query.endsWith(";")) {
      const readline = (0, import_promises6.createInterface)({
        // biome-ignore lint/style/noNonNullAssertion: yolo
        input: import_std_env7.process.stdin,
        output: import_std_env7.process.stdout
      });
      do {
        const moreQuery = await readline.question("");
        query += ` ${moreQuery.trim()}`;
      } while (!query.endsWith(";"));
      readline.close();
    }
    try {
      await executeQueryAndPrint({ ...argz, query }, config);
    } catch (error) {
      import_consola23.consola.error(error instanceof Error ? error.message : error);
    }
  }
}
var SAFEWORDS = ["exit", "quit", "bye", ":q"];
function isSafeword(thing) {
  return SAFEWORDS.includes(thing);
}
function getPrompt(argz, config) {
  const { environment } = argz;
  const { dialect } = config;
  return [
    typeof dialect === "string" ? dialect : inferDialectName(config.kysely),
    environment ? (0, import_utils5.colorize)("gray", `(${environment})`) : null,
    (0, import_utils5.colorize)("cyan", "\u276F")
  ].filter(Boolean).join(" ");
}

// src/commands/root.mts
var args11 = defineArgs({
  help: {
    alias: "h",
    default: false,
    description: "Show help information",
    type: "boolean"
  },
  version: {
    alias: "v",
    default: false,
    description: "Show version number",
    type: "boolean"
  }
});
var RootCommand = defineCommand(args11, {
  meta: {
    name: "kysely",
    description: "A command-line tool for Kysely"
  },
  subCommands: {
    ...InitCommand,
    ...LegacyDownCommand,
    ...LegacyLatestCommand,
    ...LegacyListCommand,
    ...LegacyMakeCommand,
    ...LegacyRollbackCommand,
    ...LegacyRunCommand,
    ...LegacyMakeCommand2,
    ...LegacyUpCommand,
    ...MigrateCommand,
    ...SeedCommand,
    ...SqlCommand
  },
  setup(context) {
    const { args: args12 } = context;
    if (args12.debug) {
      import_consola24.consola.level = import_consola24.LogLevels.debug;
    }
    import_consola24.consola.options.formatOptions.date = false;
    import_consola24.consola.debug("cwd", getCWD(args12));
  },
  async run(context) {
    const { args: args12 } = context;
    if (!isInSubcommand(context)) {
      import_consola24.consola.debug(context, []);
      if (args12.version) {
        return await printInstalledVersions(args12);
      }
      await (0, import_citty3.showUsage)(context.cmd);
    }
    try {
      await printUpgradeNotice(args12);
    } catch (error) {
      import_consola24.consola.debug("Failed to print upgrade notice:", error);
    }
    import_consola24.consola.debug(`finished running from "${__filename}"`);
  }
});

// src/cli.mts
function buildCLI() {
  const runCLI = (0, import_citty4.createMain)(RootCommand);
  return {
    parse: async (argv) => {
      await runCLI({ rawArgs: argv });
    }
  };
}

// src/bin.mts
var cli = buildCLI();
cli.parse(import_std_env8.process.argv.slice(2));
