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 { output, promptableOption, REASONABLE_NAME_SCHEMA, requireSession, safelyPromptTextWithValidation, sessionIntro, } from "../utils" import { accent, dimmed } from "../lib/io" import { clearSpinner, startSpinner } from "../lib/spinner" /** Arguments accepted by the organization creation command. */ const createOrgOptsSchema = globalOptionsSchema.extend({ name: promptableOption(REASONABLE_NAME_SCHEMA, "--name"), }) export const orgCreateCommand = defineCommand({ name: "create", description: "Create a new organization", options: { ...globalOptions, name: { type: "string", short: "n", }, }, optionDescriptions: { name: "The name of the organization", }, schema: globalOptionsSchema.extend(createOrgOptsSchema.shape), run: createOrganization, }) /** * Creates an organization for the authenticated user. * * @param opts - Validated options containing an optional organization name. */ export async function createOrganization( opts: z.infer, ) { const session = await requireSession("create an organization") output.normal(() => sessionIntro(session)) let name = opts.name if (name == null) { name = await promptName( session.user.name && !z.email().safeParse(session.user.name).success ? session.user.name : null, ) } startSpinner("Creating organization") const org = await apiClient.org.create({ name }) clearSpinner() output .normal(() => log.success(`Created ${accent(org.name)} ${dimmed(org.id)}`)) .json(org) } /** * Prompts for an organization name and validates the response. * * @param userName - User name used to derive the suggested organization name. */ async function promptName(userName?: string | null) { const defaultName = userName ? `${userName}'s Organization` : "My Organization" return await safelyPromptTextWithValidation( { message: "What should we name the organization?", placeholder: defaultName, defaultValue: defaultName, }, REASONABLE_NAME_SCHEMA, "--name", ) }