all repos — kitten @ ec4ee6e742f7af41cc1d4ec1a7d2b057dcfbf1a0

pkgs/core/src/kitten.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
import {
  type Client,
  type ChatInputCommandInteraction,
  type AutocompleteInteraction,
  type ButtonInteraction,
  type AnySelectMenuInteraction,
  type ModalSubmitInteraction,
  type ApplicationCommandNonOptionsData,
  BaseInteraction,
} from "discord.js";

import { HaltExecution } from "./errors";
import { type Option, type InferOptions, OPTION_TYPES } from "./options";
import { KittenComponent, type KittenComponentInteraction } from "./components";
import { Command, CommandBuilder, SubcommandGroupBuilder } from "./commands";
import { baseLogger, type KittenLogger } from "./logger";

export interface KittenOptions {
  logger?: KittenLogger;
}

export class Kitten {
  private commands = new Map<string, Command | SubcommandGroupBuilder<any>>();
  private components = new Map<string, KittenComponent<any, any>>();
  private logger: KittenLogger;

  constructor(
    private client: Client,
    options: KittenOptions = {},
  ) {
    this.client.on("interactionCreate", this.handleInteraction.bind(this));
    this.logger = options.logger ?? baseLogger;
  }

  builder() {
    return new CommandBuilder();
  }

  command<O extends Record<string, Option<any, any>>>(
    name: string,
    config: {
      description: string;
      options?: O;
      run: (
        interaction: ChatInputCommandInteraction,
        args: InferOptions<O>,
      ) => Promise<void> | void;
    },
  ): Command;

  command(name: string, config: { description: string }): SubcommandGroupBuilder<{}>;

  command(name: string, config: any): any {
    return this.builder().command(name, config);
  }

  button<O extends Record<string, Option<any, any>>>(
    name: string,
    config: {
      options?: O;
      run: (interaction: ButtonInteraction, args: InferOptions<O>) => Promise<void> | void;
    },
  ): KittenComponent<ButtonInteraction, O> {
    return new KittenComponent<ButtonInteraction, O>(name, config);
  }

  selectMenu<O extends Record<string, Option<any, any>>>(
    name: string,
    config: {
      options?: O;
      run: (interaction: AnySelectMenuInteraction, args: InferOptions<O>) => Promise<void> | void;
    },
  ): KittenComponent<AnySelectMenuInteraction, O> {
    return new KittenComponent<AnySelectMenuInteraction, O>(name, config);
  }

  modal<O extends Record<string, Option<any, any>>>(
    name: string,
    config: {
      options?: O;
      run: (interaction: ModalSubmitInteraction, args: InferOptions<O>) => Promise<void> | void;
    },
  ): KittenComponent<ModalSubmitInteraction, O> {
    return new KittenComponent<ModalSubmitInteraction, O>(name, config);
  }

  register(registry: {
    commands?: (Command | SubcommandGroupBuilder<any>)[];
    components?: KittenComponent<any, any>[];
  }) {
    registry.commands?.forEach((cmd) => this.commands.set(cmd.name, cmd));
    registry.components?.forEach((comp) => this.components.set(comp.name, comp));
  }

  private async handleInteraction(interaction: BaseInteraction) {
    // commands
    if (interaction.isChatInputCommand()) await this.routeCommand(interaction);
    else if (interaction.isAutocomplete()) await this.routeAutocomplete(interaction);

    // components
    else if (interaction.isButton()) await this.routeComponent(interaction, "button");
    else if (interaction.isAnySelectMenu()) await this.routeComponent(interaction, "select menu");
    else if (interaction.isModalSubmit()) await this.routeComponent(interaction, "modal");
  }

  private async routeCommand(interaction: ChatInputCommandInteraction) {
    const entry = this.commands.get(interaction.commandName);
    if (!entry) return;

    if (entry instanceof SubcommandGroupBuilder) {
      const groupName = interaction.options.getSubcommandGroup(false);
      const subName = interaction.options.getSubcommand(false);

      if (groupName) {
        const group = entry.groups[groupName];
        if (!group) return;
        const subcommand = group.subcommands[subName ?? ""];
        if (!subcommand) return;

        await this.executeWithMiddlewares(
          interaction,
          entry.middlewares,
          subcommand.config.run,
          subcommand.config.options,
        );
      } else if (subName) {
        const subcommand = entry.subcommands[subName];
        if (!subcommand) return;

        await this.executeWithMiddlewares(
          interaction,
          entry.middlewares,
          subcommand.config.run,
          subcommand.config.options,
        );
      }
    } else {
      await this.executeWithMiddlewares(
        interaction,
        entry.middlewares,
        entry.config.run,
        entry.config.options,
      );
    }
  }

  private async executeWithMiddlewares(
    interaction: ChatInputCommandInteraction,
    middlewares: Function[],
    run: Function,
    optionsSchema?: Record<string, Option<any, any>>,
  ) {
    try {
      let context = {};
      for (const mw of middlewares) {
        const result = await mw(interaction, context);
        if (result) context = { ...context, ...result };
      }

      const args = this.parseSlashOptions(interaction, optionsSchema);
      await run(interaction, args, context);
    } catch (err) {
      // TODO)) custom error handlers
      if (err instanceof HaltExecution) return;

      this.logger.error(`unhandled error executing command ${interaction.commandName}:`, {
        error: err instanceof Error ? err.stack : String(err),
        command: interaction.commandName,
        user: interaction.user.id,
      });

      if (!interaction.replied && !interaction.deferred) {
        await interaction
          .reply({ content: "an error occurred while executing this command.", ephemeral: true })
          .catch(() => null);
      }
    }
  }

  private async routeAutocomplete(interaction: AutocompleteInteraction) {
    const entry = this.commands.get(interaction.commandName);
    if (!entry) return;

    const focused = interaction.options.getFocused(true);
    let optionsSchema: Record<string, Option<any, any>> | undefined;

    if (entry instanceof SubcommandGroupBuilder) {
      const groupName = interaction.options.getSubcommandGroup(false);
      const subName = interaction.options.getSubcommand(false);

      if (groupName && subName)
        optionsSchema = entry.groups[groupName]?.subcommands[subName]?.config.options;
      else if (subName) optionsSchema = entry.subcommands[subName]?.config.options;
    } else {
      optionsSchema = entry.config.options;
    }

    const opt = optionsSchema?.[focused.name];
    if (opt?.autocomplete) {
      const choices = await opt.autocomplete(interaction, focused.value);
      await interaction.respond(choices).catch(() => null);
    }
  }

  private async routeComponent(interaction: KittenComponentInteraction, typeName: string) {
    const [prefix] = interaction.customId.split(":");
    if (!prefix) return;

    const component = this.components.get(prefix);
    if (!component) return;

    try {
      const args = component.parseArgs(interaction.customId);
      await component.config.run(interaction, args);
    } catch (err) {
      this.logger.error(`error executing ${typeName} ${prefix}:`, {
        error: err instanceof Error ? err.stack : String(err),
        component: prefix,
        user: interaction.user.id,
      });
    }
  }

  private parseSlashOptions(
    interaction: ChatInputCommandInteraction,
    optionsSchema?: Record<string, Option<any, any>>,
  ): Record<string, any> {
    if (!optionsSchema) return {};
    const parsed: Record<string, any> = {};

    for (const [name, opt] of Object.entries(optionsSchema)) {
      switch (opt.type) {
        case "string":
          parsed[name] = interaction.options.getString(name);
          break;
        case "integer":
          parsed[name] = interaction.options.getInteger(name);
          break;
        case "number":
          parsed[name] = interaction.options.getNumber(name);
          break;
        case "boolean":
          parsed[name] = interaction.options.getBoolean(name);
          break;
        case "user":
          parsed[name] = interaction.options.getUser(name);
          break;
        case "channel":
          parsed[name] = interaction.options.getChannel(name);
          break;
        case "role":
          parsed[name] = interaction.options.getRole(name);
          break;
        case "mentionable":
          parsed[name] = interaction.options.getMentionable(name);
          break;
        case "attachment":
          parsed[name] = interaction.options.getAttachment(name);
          break;
      }
    }
    return parsed;
  }

  async sync({ guildId }: { guildId?: string } = {}) {
    const payloads = Array.from(this.commands.values()).map((cmd) => {
      if (cmd instanceof SubcommandGroupBuilder) {
        const subcommandOptions = Object.values(cmd.subcommands).map((sub) => ({
          type: OPTION_TYPES.subcommand,
          name: sub.name,
          description: sub.config.description,
          options: this.transformOptionsForDiscord(sub.config.options),
        }));

        const groupOptions = Object.values(cmd.groups).map((group) => ({
          type: OPTION_TYPES.subcommandGroup,
          name: group.name,
          description: group.description,
          options: Object.values(group.subcommands).map((sub) => ({
            type: OPTION_TYPES.subcommand,
            name: sub.name,
            description: sub.config.description,
            options: this.transformOptionsForDiscord(sub.config.options),
          })),
        }));

        return {
          name: cmd.name,
          description: cmd.description,
          options: [...subcommandOptions, ...groupOptions],
        };
      } else {
        return {
          name: cmd.name,
          description: cmd.config.description,
          options: this.transformOptionsForDiscord(cmd.config.options),
        };
      }
    });

    if (!this.client.application) {
      throw new Error("client application not ready to sync. ensure you await client.login()");
    }

    if (guildId) {
      await this.client.application.commands.set(payloads, guildId);
      this.logger.info(`synced ${payloads.length} commands to guild ${guildId}.`, {
        guildId,
        commandCount: payloads.length,
      });
    } else {
      await this.client.application.commands.set(payloads);
      this.logger.info(`synced ${payloads.length} global commands.`, {
        commandCount: payloads.length,
      });
    }
  }

  private transformOptionsForDiscord(
    options?: Record<string, Option<any, any>>,
  ): ApplicationCommandNonOptionsData[] {
    if (!options) return [];

    return Object.entries(options).map(([name, opt]) => {
      const payload: any = {
        name,
        description: opt.description,
        type: OPTION_TYPES[opt.type],
        required: opt.required,
      };

      if (opt.autocomplete) {
        payload.autocomplete = true;
      }

      return payload as ApplicationCommandNonOptionsData;
    });
  }
}