import { log } from "@clack/prompts" import { defineCommand } from "../lib/command" import { globalOptions, globalOptionsSchema } from "../lib/global-options" import z from "zod" import { apiClient } from "../lib/api-client" import { accent, dimmed } from "../lib/io" import { clearSpinner, startSpinner } from "../lib/spinner" import { API_KEY_OPT, apiKeyOptsSchema, ORG_OPT, output, promptableOption, REASONABLE_NAME_SCHEMA, requireSession, safelyPromptTextWithValidation, sessionIntro, useOrganization, useOrganizationApiKey, ORG_OPTION_DESCRIPTIONS, API_KEY_OPTION_DESCRIPTIONS, } from "../utils" /** Validates API key selection and replacement name options. */ const renameApiKeyOptsSchema = apiKeyOptsSchema.extend({ name: promptableOption(REASONABLE_NAME_SCHEMA, "--name"), }) export const orgApiKeyRenameCommand = defineCommand({ name: "rename", description: "Rename an organization API key", options: { ...globalOptions, ...API_KEY_OPT, ...ORG_OPT, name: { type: "string", short: "n", }, }, optionDescriptions: { ...API_KEY_OPTION_DESCRIPTIONS, ...ORG_OPTION_DESCRIPTIONS, name: "New name for the API key", }, schema: globalOptionsSchema.extend(renameApiKeyOptsSchema.shape), run: renameOrganizationApiKey, }) /** * Renames an organization API key. * * @param opts - Organization, API key, and replacement name options. */ export async function renameOrganizationApiKey( opts: z.infer, ) { const session = await requireSession("rename an organization API key") output.normal(() => sessionIntro(session)) const organization = await useOrganization(opts) const apiKey = await useOrganizationApiKey(organization.id, opts) const newName = opts.name ?? (await safelyPromptTextWithValidation( { message: "What should the new API key name be?", initialValue: apiKey.name ?? undefined, }, REASONABLE_NAME_SCHEMA, "--name", )) startSpinner("Renaming API key") // Retain the normalized API response until the spinner has cleared. const renamed = await apiClient.apiKey.update({ keyId: apiKey.id, name: newName, }) clearSpinner() output .normal(() => log.success(`Renamed to ${accent(newName)} ${dimmed(apiKey.id)}`), ) .json(renamed) }