all repos — kitten @ 6742b6ccdb8cfbedfbee82d9baa7c6da27190208

pkgs/router/src/commands.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
import type {
	ChatInputCommandInteraction,
	UserContextMenuCommandInteraction,
	MessageContextMenuCommandInteraction,
	BaseInteraction,
	ButtonInteraction,
	AnySelectMenuInteraction,
	ModalSubmitInteraction,
	LocalizationMap,
} from "discord.js";
import type { CommandOption, Option, InferOptions } from "./options";
import {
	KittenComponent,
	KittenComponentInteraction,
	type KittenComponentConfig,
} from "./components";

export const INTEGRATION_TYPES = {
	GUILD_INSTALL: 0,
	USER_INSTALL: 1,
} as const;
export const INTERACTION_CONTEXTS = {
	GUILD: 0,
	BOT_DM: 1,
	PRIVATE_CHANNEL: 2,
} as const;

export const INTEGRATION_TYPE_PRESETS = {
	ALL: Object.values(INTEGRATION_TYPES),
	GUILD_ONLY: [INTEGRATION_TYPES.GUILD_INSTALL],
	USER_ONLY: [INTEGRATION_TYPES.USER_INSTALL],
};
export const INTEGRATION_CONTEXT_PRESETS = {
	EVERYWHERE: Object.values(INTERACTION_CONTEXTS),
	GUILDS_ONLY: [INTERACTION_CONTEXTS.GUILD],
	DMS_ONLY: [INTERACTION_CONTEXTS.BOT_DM, INTERACTION_CONTEXTS.PRIVATE_CHANNEL],
};

export type CommandResultType<Res = unknown> = Promise<Res> | Res;
export type IntegrationType = (typeof INTEGRATION_TYPES)[keyof typeof INTEGRATION_TYPES];
export type InteractionContextType =
	(typeof INTERACTION_CONTEXTS)[keyof typeof INTERACTION_CONTEXTS];

/**
 * pre-execution interceptors that let you chain execution checks and pass their
 * results down as strongly-typed context.
 *
 * @throws {HaltExecution} if you wish to intentionally stop propagation.
 */
export type Middleware<I extends BaseInteraction = BaseInteraction, InCtx = any, OutCtx = any> = (
	interaction: I,
	ctx: InCtx,
) => Promise<OutCtx | void> | OutCtx | void;

/**
 * an exception handler that can catch, handle, or rethrow errors.
 * these are context-aware and will receive whatever context was successfully accumulated
 * before the exception occurred.
 */
export type ErrorHandler<I extends BaseInteraction = BaseInteraction, Ctx = any> = (
	err: unknown,
	interaction: I,
	ctx: Ctx,
) => Promise<unknown> | unknown;

/**
 * strictly-typed post-execution flow handlers.
 *
 * afterwares run sequentially inside a safe `finally` block and execute regardless
 * of whether the interaction completed cleanly, threw an exception, or was halted.
 */
export type Afterware<I extends BaseInteraction = BaseInteraction, Ctx = any, Res = unknown> = (
	interaction: I,
	ctx: Ctx,
	error: unknown | null,
	result: Res | undefined,
) => Promise<void> | void;

export interface BaseCommandConfig<I extends BaseInteraction = BaseInteraction, Ctx = any> {
	integrationTypes?: IntegrationType[];
	contexts?: InteractionContextType[];
	nameLocalizations?: LocalizationMap;
	defaultMemberPermissions?: string | number | bigint | any;
	nsfw?: boolean;
	onError?: ErrorHandler<I, Ctx>;
}

export interface LocalizedDescription {
	description: string;
	descriptionLocalizations?: LocalizationMap;
}

export interface ChatCommandConfig<
	O extends Record<string, CommandOption<any, any>>,
	Ctx = any,
	Res = unknown,
>
	extends BaseCommandConfig<ChatInputCommandInteraction, Ctx>, LocalizedDescription {
	options?: O;
	run: (
		interaction: ChatInputCommandInteraction,
		args: InferOptions<O>,
		ctx: Ctx,
	) => CommandResultType<Res>;
}

export interface ContextMenuConfig<
	I extends BaseInteraction,
	Ctx = any,
	Res = unknown,
> extends BaseCommandConfig<I, Ctx> {
	run: (interaction: I, ctx: Ctx) => CommandResultType<Res>;
}

export class Subcommand {
	constructor(
		public name: string,
		public config: ChatCommandConfig<any, any, any>,
	) {}
}

export class SubcommandGroup<Ctx = {}, Res = unknown> {
	public subcommands: Record<string, Subcommand> = {};

	constructor(
		public name: string,
		public description: string,
		public config?: {
			nameLocalizations?: LocalizationMap;
			descriptionLocalizations?: LocalizationMap;
		},
	) {}

	/**
	 * append a subcommand to this specific group.
	 */
	subcommand<O extends Record<string, CommandOption<any, any>>, R extends Res>(
		name: string,
		config: ChatCommandConfig<O, Ctx, R>,
	): this {
		this.subcommands[name] = new Subcommand(name, config);
		return this;
	}
}

export class SubcommandGroupBuilder<Ctx = {}, Res = unknown> {
	public subcommands: Record<string, Subcommand> = {};
	public groups: Record<string, SubcommandGroup<Ctx, Res>> = {};

	constructor(
		public name: string,
		public description: string,
		public middlewares: Middleware<any, any, any>[] = [],
		public errorHandlers: ErrorHandler<any, any>[] = [],
		public afterwares: Afterware<any, any, any>[] = [],
		public config?: BaseCommandConfig<ChatInputCommandInteraction, Ctx> & LocalizedDescription,
	) {}

	/**
	 * chain a loose subcommand onto this builder.
	 */
	subcommand<O extends Record<string, CommandOption<any, any>>, R extends Res>(
		name: string,
		config: ChatCommandConfig<O, Ctx, R>,
	): this {
		this.subcommands[name] = new Subcommand(name, config);
		return this;
	}

	/**
	 * define a sub-group to isolate subcommands further.
	 */
	group(
		name: string,
		config: LocalizedDescription & { nameLocalizations?: LocalizationMap },
		setup: (group: SubcommandGroup<Ctx, Res>) => void,
	): this {
		const group = new SubcommandGroup<Ctx, Res>(name, config.description, config);
		setup(group);
		this.groups[name] = group;
		return this;
	}
}

export class Command<Ctx = any, Res = unknown> {
	constructor(
		public name: string,
		public config: ChatCommandConfig<any, Ctx, Res>,
		public middlewares: Middleware<any, any, any>[] = [],
		public errorHandlers: ErrorHandler<any, any>[] = [],
		public afterwares: Afterware<any, any, any>[] = [],
	) {}
}

export class ContextMenuCommand<
	Ctx = any,
	I extends UserContextMenuCommandInteraction | MessageContextMenuCommandInteraction = any,
	Res = unknown,
> {
	constructor(
		public name: string,
		public type: "user" | "message",
		public run: (interaction: I, ctx: Ctx) => CommandResultType<Res>,
		public middlewares: Middleware<any, any, any>[] = [],
		public errorHandlers: ErrorHandler<any, any>[] = [],
		public afterwares: Afterware<any, any, any>[] = [],
		public config?: BaseCommandConfig<I, Ctx>,
	) {}
}

/**
 * a chainable builder for creating commands, context menus, and components with shared
 * context, middleware, error handlers, and afterwares.
 */
export class CommandBuilder<Ctx = {}, Res = unknown> {
	constructor(
		private middlewares: Middleware<any, any, any>[] = [],
		private errorHandlers: ErrorHandler<any, any>[] = [],
		private afterwares: Afterware<any, any, Res>[] = [],
	) {}

	/**
	 * attach a middleware to this builder. any context returned will be merged and
	 * strictly typed for all subsequent middlewares and handlers.
	 */
	use<NewCtx extends Record<string, any>>(
		mw: (interaction: BaseInteraction, ctx: Ctx) => Promise<NewCtx | void> | NewCtx | void,
	): CommandBuilder<Ctx & NewCtx, Res> {
		return new CommandBuilder<Ctx & NewCtx, Res>(
			[...this.middlewares, mw],
			this.errorHandlers,
			this.afterwares,
		);
	}

	/**
	 * attach a builder-level error handler. if an exception is thrown inside a command
	 * or component produced by this builder, this handler will catch it.
	 */
	onError(handler: ErrorHandler<BaseInteraction, Ctx>): CommandBuilder<Ctx, Res> {
		return new CommandBuilder<Ctx, Res>(
			this.middlewares,
			[...this.errorHandlers, handler],
			this.afterwares,
		);
	}

	/**
	 * attach an afterware to this builder. these strictly enforce the return type of your commands
	 * to prevent type safety degradation.
	 *
	 * @example
	 * ```ts
	 * .after<MyResult>(async (interaction, ctx, err, result) => {
	 * 	// result is strictly typed as: MyResult | undefined
	 * })
	 * ```
	 */
	after<NewRes>(handler: Afterware<BaseInteraction, Ctx, NewRes>): CommandBuilder<Ctx, NewRes> {
		return new CommandBuilder<Ctx, NewRes>(this.middlewares, this.errorHandlers, [
			...this.afterwares,
			handler as any,
		]);
	}

	/**
	 * construct a top-level chat input command.
	 */
	command<O extends Record<string, CommandOption<any, any>>, R extends Res>(
		name: string,
		config: ChatCommandConfig<O, Ctx, R>,
	): Command<Ctx, R>;

	/**
	 * construct a subcommand group base.
	 */
	command(
		name: string,
		config: BaseCommandConfig<ChatInputCommandInteraction, Ctx> & LocalizedDescription,
	): SubcommandGroupBuilder<Ctx, Res>;

	command(name: string, config: any): any {
		if (config.run) {
			return new Command<Ctx, Res>(
				name,
				config,
				this.middlewares,
				this.errorHandlers,
				this.afterwares,
			);
		}
		return new SubcommandGroupBuilder<Ctx, Res>(
			name,
			config.description,
			this.middlewares,
			this.errorHandlers,
			this.afterwares,
			config,
		);
	}

	private createContextMenu<
		I extends UserContextMenuCommandInteraction | MessageContextMenuCommandInteraction,
		R extends Res,
	>(name: string, type: "user" | "message", runOrConfig: any) {
		const isFn = typeof runOrConfig === "function";
		return new ContextMenuCommand<Ctx, I, R>(
			name,
			type,
			isFn ? runOrConfig : runOrConfig.run,
			this.middlewares,
			this.errorHandlers,
			this.afterwares,
			isFn ? undefined : runOrConfig,
		);
	}

	/**
	 * construct a user context menu command.
	 */
	userContextMenu<R extends Res>(
		name: string,
		runOrConfig:
			| ((interaction: UserContextMenuCommandInteraction, ctx: Ctx) => CommandResultType<R>)
			| ContextMenuConfig<UserContextMenuCommandInteraction, Ctx, R>,
	): ContextMenuCommand<Ctx, UserContextMenuCommandInteraction, R> {
		return this.createContextMenu(name, "user", runOrConfig);
	}

	/**
	 * construct a message context menu command.
	 */
	messageContextMenu<R extends Res>(
		name: string,
		runOrConfig:
			| ((interaction: MessageContextMenuCommandInteraction, ctx: Ctx) => CommandResultType<R>)
			| ContextMenuConfig<MessageContextMenuCommandInteraction, Ctx, R>,
	): ContextMenuCommand<Ctx, MessageContextMenuCommandInteraction, R> {
		return this.createContextMenu(name, "message", runOrConfig);
	}

	private createComponent<
		I extends KittenComponentInteraction,
		O extends Record<string, Option<any, any>>,
		R extends Res,
	>(name: string, config: any): KittenComponent<I, O, Ctx, R> {
		return new KittenComponent<I, O, Ctx, R>(
			name,
			config,
			this.middlewares,
			this.errorHandlers,
			this.afterwares,
		);
	}

	/**
	 * construct a reusable button component handler.
	 */
	button<O extends Record<string, Option<any, any>>, R extends Res>(
		name: string,
		config: KittenComponentConfig<ButtonInteraction, O, Ctx, R>,
	): KittenComponent<ButtonInteraction, O, Ctx, R> {
		return this.createComponent(name, config);
	}

	/**
	 * construct a reusable select menu component handler.
	 */
	selectMenu<O extends Record<string, Option<any, any>>, R extends Res>(
		name: string,
		config: KittenComponentConfig<AnySelectMenuInteraction, O, Ctx, R>,
	): KittenComponent<AnySelectMenuInteraction, O, Ctx, R> {
		return this.createComponent(name, config);
	}

	/**
	 * construct a reusable modal component handler.
	 */
	modal<O extends Record<string, Option<any, any>>, R extends Res>(
		name: string,
		config: KittenComponentConfig<ModalSubmitInteraction, O, Ctx, R>,
	): KittenComponent<ModalSubmitInteraction, O, Ctx, R> {
		return this.createComponent(name, config);
	}
}