all repos — kitten @ 8a511d99dc35b383139b6948bc1f4c265aff202c

pkgs/router/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
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
import {
	type Client,
	type ChatInputCommandInteraction,
	type AutocompleteInteraction,
	type ButtonInteraction,
	type AnySelectMenuInteraction,
	type ModalSubmitInteraction,
	type APIApplicationCommandOption,
	type APIApplicationCommandBasicOption,
	type UserContextMenuCommandInteraction,
	type MessageContextMenuCommandInteraction,
	BaseInteraction,
	type RESTPostAPIApplicationCommandsJSONBody,
	ApplicationCommandType,
} from "discord.js";

import { HaltExecution } from "./errors";
import { type Option, type CommandOption, type InferOptions, OPTION_TYPES } from "./options";
import { KittenComponent, type KittenComponentInteraction } from "./components";
import {
	Command,
	CommandBuilder,
	SubcommandGroupBuilder,
	ContextMenuCommand,
	type IntegrationType,
	type InteractionContextType,
	type CommandResultType,
	type Middleware,
	type ErrorHandler,
} from "./commands";
import { baseLogger, type KittenLogger } from "./logger";

export interface KittenOptions {
	logger?: KittenLogger;
	onError?: ErrorHandler<BaseInteraction, any>;
}

export class Kitten {
	private commands = new Map<string, Command<any> | SubcommandGroupBuilder<any>>();
	private userContextMenus = new Map<string, ContextMenuCommand<any, any>>();
	private messageContextMenus = new Map<string, ContextMenuCommand<any, any>>();
	private components = new Map<string, KittenComponent<any, any, any>>();
	private logger: KittenLogger;
	private globalOnError?: ErrorHandler<BaseInteraction, any>;

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

	builder() {
		return new CommandBuilder();
	}

	onError(handler: ErrorHandler<BaseInteraction, any>) {
		this.globalOnError = handler;
		return this;
	}

	command<O extends Record<string, CommandOption<any, any>>>(
		name: string,
		config: {
			description: string;
			options?: O;
			integrationTypes?: IntegrationType[];
			contexts?: InteractionContextType[];
			onError?: ErrorHandler<ChatInputCommandInteraction, {}>;
			run: (interaction: ChatInputCommandInteraction, args: InferOptions<O>) => CommandResultType;
		},
	): Command<{}>;

	command(
		name: string,
		config: {
			description: string;
			integrationTypes?: IntegrationType[];
			contexts?: InteractionContextType[];
		},
	): SubcommandGroupBuilder<{}>;

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

	userContextMenu(
		name: string,
		runOrConfig:
			| ((interaction: UserContextMenuCommandInteraction) => CommandResultType)
			| {
					integrationTypes?: IntegrationType[];
					contexts?: InteractionContextType[];
					onError?: ErrorHandler<UserContextMenuCommandInteraction, {}>;
					run: (interaction: UserContextMenuCommandInteraction) => CommandResultType;
			  },
	): ContextMenuCommand<{}, UserContextMenuCommandInteraction> {
		return this.builder().userContextMenu(name, runOrConfig as any);
	}

	messageContextMenu(
		name: string,
		runOrConfig:
			| ((interaction: MessageContextMenuCommandInteraction) => CommandResultType)
			| {
					integrationTypes?: IntegrationType[];
					contexts?: InteractionContextType[];
					onError?: ErrorHandler<MessageContextMenuCommandInteraction, {}>;
					run: (interaction: MessageContextMenuCommandInteraction) => CommandResultType;
			  },
	): ContextMenuCommand<{}, MessageContextMenuCommandInteraction> {
		return this.builder().messageContextMenu(name, runOrConfig as any);
	}

	button<O extends Record<string, Option<any, any>>>(
		name: string,
		config: {
			options?: O;
			onError?: ErrorHandler<ButtonInteraction, {}>;
			run: (interaction: ButtonInteraction, args: InferOptions<O>) => CommandResultType;
		},
	): KittenComponent<ButtonInteraction, O, {}> {
		return this.builder().button(name, config);
	}

	selectMenu<O extends Record<string, Option<any, any>>>(
		name: string,
		config: {
			options?: O;
			onError?: ErrorHandler<AnySelectMenuInteraction, {}>;
			run: (interaction: AnySelectMenuInteraction, args: InferOptions<O>) => CommandResultType;
		},
	): KittenComponent<AnySelectMenuInteraction, O, {}> {
		return this.builder().selectMenu(name, config);
	}

	modal<O extends Record<string, Option<any, any>>>(
		name: string,
		config: {
			options?: O;
			onError?: ErrorHandler<ModalSubmitInteraction, {}>;
			run: (interaction: ModalSubmitInteraction, args: InferOptions<O>) => CommandResultType;
		},
	): KittenComponent<ModalSubmitInteraction, O, {}> {
		return this.builder().modal(name, config);
	}

	register(registry: {
		commands?: (Command<any> | SubcommandGroupBuilder<any> | ContextMenuCommand<any, any>)[];
		components?: KittenComponent<any, any, any>[];
	}) {
		registry.commands?.forEach((cmd) => {
			if (cmd instanceof ContextMenuCommand) {
				if (cmd.type === "user") {
					this.userContextMenus.set(cmd.name, cmd);
					this.logger.debug(`registered user context menu: "${cmd.name}"`);
				} else if (cmd.type === "message") {
					this.messageContextMenus.set(cmd.name, cmd);
					this.logger.debug(`registered message context menu: "${cmd.name}"`);
				}
			} else {
				this.commands.set(cmd.name, cmd);
				const subInfo = cmd instanceof SubcommandGroupBuilder ? " (subcommand group)" : "";
				this.logger.debug(`registered command: "${cmd.name}"${subInfo}`);
			}
		});
		registry.components?.forEach((comp) => {
			this.components.set(comp.name, comp);
			this.logger.debug(`registered component prefix: "${comp.name}"`);
		});
	}

	private async handleInteraction(interaction: BaseInteraction) {
		this.logger.debug(`received interaction ID: ${interaction.id}, Type: ${interaction.type}`);

		switch (true) {
			// commands
			case interaction.isChatInputCommand():
				return await this.routeCommand(interaction);
			case interaction.isAutocomplete():
				return await this.routeAutocomplete(interaction);
			case interaction.isUserContextMenuCommand():
				return await this.routeContextMenu(interaction, "user");
			case interaction.isMessageContextMenuCommand():
				return await this.routeContextMenu(interaction, "message");

			// components
			case interaction.isButton():
				return await this.routeComponent(interaction);
			case interaction.isAnySelectMenu():
				return await this.routeComponent(interaction);
			case interaction.isModalSubmit():
				return await this.routeComponent(interaction);
			default:
				this.logger.debug(`interaction ID: ${interaction.id} could not be classified or handled.`);
		}
	}

	private async routeCommand(interaction: ChatInputCommandInteraction) {
		const entry = this.commands.get(interaction.commandName);
		if (!entry) {
			this.logger.debug(`command routing aborted: "${interaction.commandName}" is not registered.`);
			return;
		}

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

			this.logger.debug(
				`routing group-based command: "${interaction.commandName}", group: ${groupName ?? "none"}, subcommand: ${subName ?? "none"}`,
			);

			if (groupName) {
				const group = entry.groups[groupName];
				if (!group) {
					this.logger.debug(
						`subcommand group "${groupName}" not found under "${interaction.commandName}".`,
					);
					return;
				}
				const subcommand = group.subcommands[subName ?? ""];
				if (!subcommand) {
					this.logger.debug(
						`subcommand "${subName}" not found in group "${groupName}" under "${interaction.commandName}".`,
					);
					return;
				}

				await this.executeWithMiddlewares(
					interaction,
					entry.middlewares,
					subcommand.config.run,
					subcommand.config.options,
					undefined,
					{
						localOnError: subcommand.config.onError,
						builderErrorHandlers: entry.errorHandlers,
					},
				);
			} else if (subName) {
				const subcommand = entry.subcommands[subName];
				if (!subcommand) {
					this.logger.debug(
						`subcommand "${subName}" not found under "${interaction.commandName}".`,
					);
					return;
				}

				await this.executeWithMiddlewares(
					interaction,
					entry.middlewares,
					subcommand.config.run,
					subcommand.config.options,
					undefined,
					{
						localOnError: subcommand.config.onError,
						builderErrorHandlers: entry.errorHandlers,
					},
				);
			}
		} else {
			this.logger.debug(`routing top-level chat command: "${interaction.commandName}"`);
			await this.executeWithMiddlewares(
				interaction,
				entry.middlewares,
				entry.config.run,
				entry.config.options,
				undefined,
				{
					localOnError: entry.config.onError,
					builderErrorHandlers: entry.errorHandlers,
				},
			);
		}
	}

	private async routeContextMenu(
		interaction: UserContextMenuCommandInteraction | MessageContextMenuCommandInteraction,
		type: "user" | "message",
	) {
		const entry =
			type === "user"
				? this.userContextMenus.get(interaction.commandName)
				: this.messageContextMenus.get(interaction.commandName);

		if (!entry) {
			this.logger.debug(
				`context menu routing aborted: "${interaction.commandName}" (${type}) is not registered.`,
			);
			return;
		}

		this.logger.debug(`routing context menu command: "${interaction.commandName}" (${type})`);
		await this.executeWithMiddlewares(
			interaction,
			entry.middlewares,
			entry.run,
			undefined,
			undefined,
			{
				localOnError: entry.config?.onError,
				builderErrorHandlers: entry.errorHandlers,
			},
		);
	}

	private async executeWithMiddlewares(
		interaction: BaseInteraction,
		middlewares: Middleware<any, any, any>[],
		run: Function,
		optionsSchema?: Record<string, Option<any, any>>,
		componentArgs?: Record<string, any>,
		extra?: {
			localOnError?: ErrorHandler<any, any>;
			builderErrorHandlers?: ErrorHandler<any, any>[];
		},
	) {
		let context: Record<string, any> = {};
		try {
			this.logger.debug(
				`Running ${middlewares.length} middleware(s) for interaction ${interaction.id}`,
			);

			for (let i = 0; i < middlewares.length; i++) {
				const mw = middlewares[i];
				if (!mw) continue;
				this.logger.debug(`executing middleware [${i + 1}/${middlewares.length}]`);
				const result = await mw(interaction, context);
				if (result) context = { ...context, ...result };
			}

			if (interaction.isChatInputCommand()) {
				const args = this.parseSlashOptions(interaction, optionsSchema);
				this.logger.debug(`executing command handler for "${interaction.commandName}"`, { args });
				await run(interaction, args, context);
			} else if (
				interaction.isButton() ||
				interaction.isAnySelectMenu() ||
				interaction.isModalSubmit()
			) {
				const customId = (interaction as any).customId;
				this.logger.debug(`executing component handler for custom ID: "${customId}"`, {
					componentArgs,
				});
				await run(interaction, componentArgs ?? {}, context);
			} else {
				this.logger.debug(`executing generic fallback handler for interaction ${interaction.id}`);
				await run(interaction, context);
			}
		} catch (err) {
			if (err instanceof HaltExecution) {
				this.logger.debug(`execution halted intentionally for interaction ${interaction.id}.`);
				if (
					err.replyPayload &&
					interaction.isRepliable() &&
					!interaction.replied &&
					!interaction.deferred
				) {
					const replyOptions =
						typeof err.replyPayload === "string"
							? { content: err.replyPayload, ephemeral: true }
							: err.replyPayload;
					await interaction.reply(replyOptions).catch(() => null);
				}
				return;
			}

			let activeError = err;
			let handled = false;

			// 1. Try local error handler first
			try {
				if (extra?.localOnError) {
					this.logger.debug(`executing local error handler for interaction ${interaction.id}`);
					await extra.localOnError(activeError, interaction, context);
					handled = true;
				}
			} catch (localErr) {
				this.logger.debug(`local error handler threw an error, propagating...`);
				activeError = localErr;
			}

			// 2. Fallback to builder-level error handlers
			if (!handled && extra?.builderErrorHandlers) {
				for (const handler of extra.builderErrorHandlers) {
					try {
						this.logger.debug(`executing builder error handler for interaction ${interaction.id}`);
						await handler(activeError, interaction, context);
						handled = true;
						break;
					} catch (builderErr) {
						this.logger.debug(
							`builder error handler threw an error, propagating to next handler...`,
						);
						activeError = builderErr;
					}
				}
			}

			if (!handled && this.globalOnError) {
				try {
					this.logger.debug(`executing global error handler for interaction ${interaction.id}`);
					await this.globalOnError(activeError, interaction, context);
					handled = true;
				} catch (globalErr) {
					this.logger.debug(
						`global error handler threw an error, falling back to default logging.`,
					);
					activeError = globalErr;
				}
			}

			if (!handled) {
				const isCommand = "commandName" in interaction;
				const identifier = isCommand
					? (interaction as any).commandName
					: "customId" in interaction
						? (interaction as any).customId
						: "unknown";
				const typeLabel = isCommand ? "command" : "component";

				this.logger.error(`unhandled error executing ${typeLabel} ${identifier}:`, {
					error: activeError instanceof Error ? activeError.stack : String(activeError),
					[typeLabel]: identifier,
					user: interaction.user.id,
				});

				if (interaction.isRepliable() && !interaction.replied && !interaction.deferred) {
					await interaction
						.reply({
							content: `An error occurred while executing this ${typeLabel}.`,
							flags: ["Ephemeral"],
						})
						.catch(() => null);
				}
			}
		}
	}

	private async routeAutocomplete(interaction: AutocompleteInteraction) {
		const entry = this.commands.get(interaction.commandName);
		if (!entry) {
			this.logger.debug(
				`autocomplete aborted: command "${interaction.commandName}" not registered.`,
			);
			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) {
			this.logger.debug(
				`handling autocomplete for command "${interaction.commandName}" option "${focused.name}" with value "${focused.value}"`,
			);
			const choices = await opt.autocomplete(interaction, focused.value);
			await interaction.respond(choices).catch(() => null);
		} else {
			this.logger.debug(
				`no autocomplete handler configured for option "${focused.name}" in command "${interaction.commandName}"`,
			);
		}
	}

	private async routeComponent(interaction: KittenComponentInteraction) {
		const [prefix] = interaction.customId.split(":");
		if (!prefix) {
			this.logger.debug(
				`component routing skipped: unable to extract prefix from customId "${interaction.customId}".`,
			);
			return;
		}

		const component = this.components.get(prefix);
		if (!component) {
			this.logger.debug(
				`component routing skipped: no component handler registered for prefix "${prefix}".`,
			);
			return;
		}

		this.logger.debug(
			`routing component for prefix "${prefix}" (customId:${interaction.customId})`,
		);
		const args = component.parseArgs(interaction.customId);
		await this.executeWithMiddlewares(
			interaction,
			component.middlewares,
			component.config.run,
			undefined,
			args,
			{
				localOnError: component.config.onError,
				builderErrorHandlers: component.errorHandlers,
			},
		);
	}

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

		this.logger.debug(`parsing options for command "${interaction.commandName}"`);

		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;
				default:
					this.logger.debug(`skipping option "${name}" due to unmapped option type: "${opt.type}"`);
			}
		}
		return parsed;
	}

	async sync({ guildId }: { guildId?: string } = {}) {
		const payloads: RESTPostAPIApplicationCommandsJSONBody[] = [];

		// chat input commands
		for (const cmd of this.commands.values()) {
			if (cmd instanceof SubcommandGroupBuilder) {
				const subcommandOptions: APIApplicationCommandOption[] = 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: APIApplicationCommandOption[] = 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),
						})),
					}),
				);

				const payload: RESTPostAPIApplicationCommandsJSONBody = {
					type: ApplicationCommandType.ChatInput,
					name: cmd.name,
					description: cmd.description,
					options: [...subcommandOptions, ...groupOptions],
				};

				if (cmd.config?.integrationTypes) payload.integration_types = cmd.config.integrationTypes;
				if (cmd.config?.contexts) payload.contexts = cmd.config.contexts;

				payloads.push(payload);
			} else {
				const payload: RESTPostAPIApplicationCommandsJSONBody = {
					type: ApplicationCommandType.ChatInput,
					name: cmd.name,
					description: cmd.config.description,
					options: this.transformOptionsForDiscord(cmd.config.options),
				};

				if (cmd.config.integrationTypes) payload.integration_types = cmd.config.integrationTypes;
				if (cmd.config.contexts) payload.contexts = cmd.config.contexts;

				payloads.push(payload);
			}
		}

		// context menus
		for (const cmd of this.userContextMenus.values()) {
			const payload: RESTPostAPIApplicationCommandsJSONBody = {
				type: ApplicationCommandType.User,
				name: cmd.name,
			};

			if (cmd.config?.integrationTypes) payload.integration_types = cmd.config.integrationTypes;
			if (cmd.config?.contexts) payload.contexts = cmd.config.contexts;

			payloads.push(payload);
		}

		for (const cmd of this.messageContextMenus.values()) {
			const payload: RESTPostAPIApplicationCommandsJSONBody = {
				type: ApplicationCommandType.Message,
				name: cmd.name,
			};

			if (cmd.config?.integrationTypes) payload.integration_types = cmd.config.integrationTypes;
			if (cmd.config?.contexts) payload.contexts = cmd.config.contexts;

			payloads.push(payload);
		}

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

		this.logger.debug(`preparing to sync ${payloads.length} command(s) to Discord API...`);

		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, CommandOption<any, any>>,
	): APIApplicationCommandBasicOption[] {
		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 APIApplicationCommandBasicOption;
		});
	}
}