commandkit 1.0.0-dev.20250601132421 → 1.0.0-dev.20250601135251

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/{CommandKit-Dbkak3_n.d.ts → CommandKit-LJlFFidn.d.ts} +2 -2
  2. package/dist/{CommandKit-BhdXwM9b.js → CommandKit-pZKcOltw.js} +12 -6
  3. package/dist/CommandKit-pZKcOltw.js.map +1 -0
  4. package/dist/CommandKit.d.ts +2 -2
  5. package/dist/CommandKit.js +4 -4
  6. package/dist/{EventWorkerContext-6BHysn1E.d.ts → EventWorkerContext-sHV9x0eB.d.ts} +2 -2
  7. package/dist/app/commands/AppCommandRunner.d.ts +2 -2
  8. package/dist/app/commands/AppCommandRunner.js +4 -4
  9. package/dist/app/commands/Context.d.ts +2 -2
  10. package/dist/app/commands/Context.js +4 -4
  11. package/dist/app/events/EventWorkerContext.d.ts +3 -3
  12. package/dist/app/handlers/AppCommandHandler.d.ts +2 -2
  13. package/dist/app/handlers/AppCommandHandler.js +4 -4
  14. package/dist/app/handlers/AppEventsHandler.d.ts +2 -2
  15. package/dist/app/handlers/AppEventsHandler.js +4 -4
  16. package/dist/app/index.d.ts +2 -2
  17. package/dist/app/index.js +4 -4
  18. package/dist/app/register/CommandRegistrar.d.ts +2 -2
  19. package/dist/app/register/CommandRegistrar.js +4 -4
  20. package/dist/{app-process-juzsCZp9.js → app-process-DGKqfi5y.js} +3 -3
  21. package/dist/{app-process-juzsCZp9.js.map → app-process-DGKqfi5y.js.map} +1 -1
  22. package/dist/{build-D45Rr7KV.js → build-CXO5bwcP.js} +5 -5
  23. package/dist/{build-D45Rr7KV.js.map → build-CXO5bwcP.js.map} +1 -1
  24. package/dist/cli/app-process.js +5 -5
  25. package/dist/cli/build.d.ts +2 -2
  26. package/dist/cli/build.js +7 -7
  27. package/dist/cli/common.d.ts +6 -6
  28. package/dist/cli/common.js +3 -3
  29. package/dist/cli/development.js +8 -8
  30. package/dist/cli/env.d.ts +2 -1
  31. package/dist/cli/env.js +3 -2
  32. package/dist/cli/generators.js +3 -3
  33. package/dist/cli/information.js +1 -1
  34. package/dist/cli/init.d.ts +1 -1
  35. package/dist/cli/init.js +5 -5
  36. package/dist/cli/production.d.ts +2 -2
  37. package/dist/cli/production.js +8 -8
  38. package/dist/cli/type-checker.js +4 -4
  39. package/dist/{common-CtMBxAf-.js → common-CoUM9Czx.js} +2 -2
  40. package/dist/{common-CtMBxAf-.js.map → common-CoUM9Czx.js.map} +1 -1
  41. package/dist/components/index.js +4 -4
  42. package/dist/components/v1/button/Button.js +4 -4
  43. package/dist/components/v1/button/ButtonKit.js +4 -4
  44. package/dist/components/v1/modal/Modal.js +4 -4
  45. package/dist/components/v1/modal/ModalKit.js +4 -4
  46. package/dist/components/v1/select-menu/ChannelSelectMenuKit.js +4 -4
  47. package/dist/components/v1/select-menu/MentionableSelectMenuKit.js +4 -4
  48. package/dist/components/v1/select-menu/RoleSelectMenuKit.js +4 -4
  49. package/dist/components/v1/select-menu/SelectMenu.js +4 -4
  50. package/dist/components/v1/select-menu/StringSelectMenuKit.js +4 -4
  51. package/dist/components/v1/select-menu/UserSelectMenuKit.js +4 -4
  52. package/dist/config/config.d.ts +5 -5
  53. package/dist/config/config.js +4 -4
  54. package/dist/config/default.d.ts +4 -4
  55. package/dist/config/default.js +4 -4
  56. package/dist/config/loader.d.ts +4 -4
  57. package/dist/config/loader.js +4 -4
  58. package/dist/config/types.d.ts +3 -3
  59. package/dist/config/utils.d.ts +4 -4
  60. package/dist/{config-1zOALegW.d.ts → config-bs6v9gyT.d.ts} +3 -3
  61. package/dist/{constants-Ce6w4OFe.d.ts → constants-BPWSrMkn.d.ts} +3 -2
  62. package/dist/{constants-DOPSzXI0.js → constants-CCqS_v55.js} +8 -1
  63. package/dist/constants-CCqS_v55.js.map +1 -0
  64. package/dist/context/async-context.d.ts +2 -2
  65. package/dist/context/async-context.js +4 -4
  66. package/dist/context/environment.d.ts +2 -2
  67. package/dist/context/environment.js +4 -4
  68. package/dist/{env-DXL8PZiG.js → env-D3rn_eei.js} +10 -1
  69. package/dist/{env-DXL8PZiG.js.map → env-D3rn_eei.js.map} +1 -1
  70. package/dist/events/CommandKitEventsChannel.d.ts +2 -2
  71. package/dist/{feature-flags-xogLBr7K.js → feature-flags-DhHcB5h5.js} +2 -2
  72. package/dist/{feature-flags-xogLBr7K.js.map → feature-flags-DhHcB5h5.js.map} +1 -1
  73. package/dist/flags/feature-flags.d.ts +2 -2
  74. package/dist/flags/feature-flags.js +5 -5
  75. package/dist/flags/store.d.ts +2 -2
  76. package/dist/index.d.ts +8 -8
  77. package/dist/index.js +8 -7
  78. package/dist/{init-B6_jkuag.js → init-B_2lOZKJ.js} +9 -4
  79. package/dist/init-B_2lOZKJ.js.map +1 -0
  80. package/dist/{init-CT348Okf.d.ts → init-CEa28dgv.d.ts} +3 -3
  81. package/dist/logger/DefaultLogger.js +4 -4
  82. package/dist/logger/Logger.js +4 -4
  83. package/dist/plugins/CompilerPlugin.d.ts +2 -2
  84. package/dist/plugins/PluginCommon.d.ts +2 -2
  85. package/dist/plugins/RuntimePlugin.d.ts +2 -2
  86. package/dist/plugins/index.d.ts +2 -2
  87. package/dist/plugins/index.js +4 -4
  88. package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.d.ts +2 -2
  89. package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.js +4 -4
  90. package/dist/plugins/plugin-runtime/CompilerPluginRuntime.d.ts +2 -2
  91. package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.d.ts +2 -2
  92. package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.js +4 -4
  93. package/dist/plugins/plugin-runtime/builtin/MacroPlugin.d.ts +2 -2
  94. package/dist/plugins/plugin-runtime/builtin/MacroPlugin.js +4 -4
  95. package/dist/plugins/plugin-runtime/runtime.d.ts +2 -2
  96. package/dist/plugins/types.d.ts +2 -2
  97. package/dist/{type-checker-BILXtCjQ.js → type-checker-FHABnKlq.js} +2 -2
  98. package/dist/{type-checker-BILXtCjQ.js.map → type-checker-FHABnKlq.js.map} +1 -1
  99. package/dist/{types-BiXh_it_.d.ts → types--Jq7UV8B.d.ts} +2 -2
  100. package/dist/{types-package-BrES1tNq.js → types-package-B0Z-xrbB.js} +2 -2
  101. package/dist/{types-package-BrES1tNq.js.map → types-package-B0Z-xrbB.js.map} +1 -1
  102. package/dist/types.d.ts +2 -2
  103. package/dist/utils/constants.d.ts +2 -2
  104. package/dist/utils/constants.js +2 -1
  105. package/dist/utils/dev-hooks.d.ts +2 -2
  106. package/dist/utils/dev-hooks.js +4 -4
  107. package/dist/utils/types-package.js +2 -2
  108. package/dist/utils/utilities.js +4 -4
  109. package/dist/{utils-IW7KDBhF.d.ts → utils-BJAW-jcv.d.ts} +2 -2
  110. package/dist/{version-B_LxfzVV.js → version-wRFKSz6q.js} +2 -2
  111. package/dist/{version-B_LxfzVV.js.map → version-wRFKSz6q.js.map} +1 -1
  112. package/dist/version.js +1 -1
  113. package/package.json +2 -2
  114. package/dist/CommandKit-BhdXwM9b.js.map +0 -1
  115. package/dist/constants-DOPSzXI0.js.map +0 -1
  116. package/dist/init-B6_jkuag.js.map +0 -1
@@ -3,7 +3,7 @@ import { Fragment, createElement } from "./element-D_nyVwgB.js";
3
3
  import { MessageCommandOptions, MessageCommandParser } from "./MessageCommandParser-tzroBwij.js";
4
4
  import { Command, CommandsRouter, Middleware } from "./CommandsRouter-C7X-eXE2.js";
5
5
  import { EventsRouter, ParsedEvent } from "./EventsRouter-BacqK6z3.js";
6
- import { HMREventType } from "./constants-Ce6w4OFe.js";
6
+ import { HMREventType } from "./constants-BPWSrMkn.js";
7
7
  import EventEmitter from "node:events";
8
8
  import { AutocompleteInteraction, Awaitable, CacheType, ChatInputCommandInteraction, Client, ClientEvents, Collection, ContextMenuCommandBuilder, ContextMenuCommandInteraction, Guild, Interaction, Locale, Message, MessageContextMenuCommandInteraction, RESTPostAPIApplicationCommandsJSONBody, SlashCommandBuilder, TextBasedChannel, UserContextMenuCommandInteraction } from "discord.js";
9
9
  import { DirectiveTransformerOptions } from "directive-to-hof";
@@ -933,4 +933,4 @@ declare class CommandKit extends EventEmitter {
933
933
  declare const commandkit: CommandKit;
934
934
  //#endregion
935
935
  export { AnyCommandExecute, AppCommandHandler, AppCommandRunner, AppEventsHandler, AppEventsHandlerLoadedData, AsyncFunction, AutocompleteCommand, AutocompleteCommandContext, AutocompleteCommandMiddlewareContext, BootstrapFunction, ChatInputCommand, ChatInputCommandContext, CommandBuilderLike, CommandContext, CommandContextOptions, CommandData, CommandExecutionMode, CommandFlagContext, CommandKit, CommandKitConfiguration, CommandKitEnvironment, CommandKitEnvironmentInternalData, CommandKitEnvironmentType, CommandKitEventDispatch, CommandKitEventsChannel, CommandKitHMREvent, CommandKitOptions, CommandKitPlugin, CommandKitPluginRuntime, CommandRegistrar, CommandTypeData, CommonDirectiveTransformer, CommonDirectiveTransformerOptions, CommonPluginRuntime, CompilerPlugin, CompilerPluginRuntime, Context, ContextParameters, CustomEvaluationContext, CustomEvaluationFunction, DecideFunction, EvaluationContext, EventFlagContext, EventListener, FeatureFlag, FeatureFlagDefinition, FlagRunner, FlagStore, GenericFunction, IdentifyFunction, InteractionCommandContext, InteractionCommandMiddlewareContext, ListenerFunction, LoadedCommand, LoadedEvent, MaybeFalsey, MaybePromise, MessageCommand, MessageCommandContext, MessageCommandMiddlewareContext, MessageContextMenuCommand, MessageContextMenuCommandContext, MessageContextMenuCommandMiddlewareContext, MiddlewareContext, MiddlewareContextArgs, PluginCommon, PluginOptions, PluginTransformParameters, PluginType, PreRegisterCommandsEvent, PreparedAppCommandExecution, ResolvableCommand, RunCommand, RuntimePlugin, SlashCommandMiddlewareContext, TemplateHandler, TransformedResult, UserContextMenuCommand, UserContextMenuCommandContext, UserContextMenuCommandMiddlewareContext, after, cancelAfter, commandkit, exitContext, flag, getCommandKit, getContext, isCommandWorkerContext, isCompilerPlugin, isPlugin, isRuntimePlugin, makeContextAwareFunction, onApplicationBootstrap, onBootstrap, provideContext, registerDevHooks, useEnvironment };
936
- //# sourceMappingURL=CommandKit-Dbkak3_n.d.ts.map
936
+ //# sourceMappingURL=CommandKit-LJlFFidn.d.ts.map
@@ -3,17 +3,17 @@ const require_colors = require('./colors-Cd4Oz-r-.js');
3
3
  const require_error_codes = require('./error-codes-C_UO39jz.js');
4
4
  const require_element = require('./element-DcqNz1dV.js');
5
5
  const require_EventInterceptor = require('./EventInterceptor-Bvh05z7n.js');
6
- const require_constants = require('./constants-DOPSzXI0.js');
6
+ const require_constants = require('./constants-CCqS_v55.js');
7
7
  const require_CompilerPlugin = require('./CompilerPlugin-XzuGixkC.js');
8
8
  const require_RuntimePlugin = require('./RuntimePlugin-CKsd83M3.js');
9
9
  const require_EventWorkerContext = require('./EventWorkerContext-BAKiTqJz.js');
10
10
  const require_resolve_file_url = require('./resolve-file-url-ifwdwqmq.js');
11
11
  const require_MessageCommandParser = require('./MessageCommandParser-D02-wpZN.js');
12
12
  const require_signals = require('./signals-scJdEbly.js');
13
- const require_types_package = require('./types-package-BrES1tNq.js');
13
+ const require_types_package = require('./types-package-B0Z-xrbB.js');
14
14
  const require_CommandsRouter = require('./CommandsRouter-B91EHi6O.js');
15
15
  const require_EventsRouter = require('./EventsRouter-C_J0M3uO.js');
16
- const require_common = require('./common-CtMBxAf-.js');
16
+ const require_common = require('./common-CoUM9Czx.js');
17
17
  const require_CommandKitEventsChannel = require('./CommandKitEventsChannel-BnSPcFdq.js');
18
18
  const require_store = require('./store-B9bo6On8.js');
19
19
  const node_events = require_chunk.__toESM(require("node:events"));
@@ -1357,9 +1357,15 @@ function defineConfig(config = {}) {
1357
1357
  //#region src/utils/utilities.ts
1358
1358
  let appDir = null;
1359
1359
  let currentDir = null;
1360
+ function getSrcDir() {
1361
+ if (require_constants.COMMANDKIT_IS_CLI) return "src";
1362
+ if (require_constants.COMMANDKIT_IS_DEV) return ".commandkit";
1363
+ return getConfig().distDir;
1364
+ }
1360
1365
  function getCurrentDirectory() {
1361
1366
  if (currentDir) return currentDir;
1362
- let root = (0, node_path.join)(process.cwd(), require_constants.COMMANDKIT_IS_DEV ? ".commandkit" : getConfig().distDir);
1367
+ const src = getSrcDir();
1368
+ let root = (0, node_path.join)(process.cwd(), src);
1363
1369
  if (!(0, node_fs.existsSync)(root)) root = process.cwd();
1364
1370
  currentDir = root;
1365
1371
  return root;
@@ -1379,7 +1385,7 @@ function getSourceDirectories() {
1379
1385
  */
1380
1386
  function findAppDirectory() {
1381
1387
  if (appDir) return appDir;
1382
- let root = (0, node_path.join)(process.cwd(), require_constants.COMMANDKIT_IS_DEV ? ".commandkit" : getConfig().distDir);
1388
+ let root = (0, node_path.join)(process.cwd(), getSrcDir());
1383
1389
  if (!(0, node_fs.existsSync)(root)) root = process.cwd();
1384
1390
  const dirs = ["app"].map((dir) => (0, node_path.join)(root, dir));
1385
1391
  for (const dir of dirs) if ((0, node_fs.existsSync)(dir)) {
@@ -3353,4 +3359,4 @@ Object.defineProperty(exports, 'useEnvironment', {
3353
3359
  return useEnvironment;
3354
3360
  }
3355
3361
  });
3356
- //# sourceMappingURL=CommandKit-BhdXwM9b.js.map
3362
+ //# sourceMappingURL=CommandKit-pZKcOltw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CommandKit-pZKcOltw.js","names":[],"sources":["../src/context/async-context.ts","../src/components/v1/button/ButtonKit.ts","../src/components/v1/button/Button.ts","../src/components/v1/modal/ModalKit.ts","../src/components/v1/modal/Modal.ts","../src/components/v1/select-menu/StringSelectMenuKit.ts","../src/components/v1/select-menu/ChannelSelectMenuKit.ts","../src/components/v1/select-menu/MentionableSelectMenuKit.ts","../src/components/v1/select-menu/UserSelectMenuKit.ts","../src/components/v1/select-menu/RoleSelectMenuKit.ts","../src/components/v1/select-menu/SelectMenu.ts","../src/logger/DefaultLogger.ts","../src/logger/Logger.ts","../src/plugins/plugin-runtime/CommandKitPluginRuntime.ts","../src/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.ts","../src/plugins/plugin-runtime/builtin/MacroPlugin.ts","../src/config/default.ts","../src/config/config.ts","../src/utils/utilities.ts","../src/app/register/CommandRegistrar.ts","../src/context/environment.ts","../src/app/commands/Context.ts","../src/app/commands/AppCommandRunner.ts","../src/app/handlers/AppCommandHandler.ts","../src/app/handlers/AppEventsHandler.ts","../src/config/loader.ts","../src/utils/dev-hooks.ts","../src/CommandKit.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { CommandKitEnvironment } from './environment';\nimport { CommandKit } from '../CommandKit';\nimport { isCommandKitError } from '../utils/error-codes';\n\nconst kCommandWorker = Symbol('commandkitCommandWorker');\nconst context = new AsyncLocalStorage<CommandKitEnvironment>();\n\nexport type GenericFunction<A extends any[] = any[]> = (...args: A) => any;\n\nexport function isCommandWorkerContext(\n worker: any,\n): worker is CommandKitEnvironment {\n return worker && Reflect.get(worker, kCommandWorker) === true;\n}\n\n/**\n * Represents an async function that can be cached\n * @template R - Array of argument types\n * @template T - Return type\n */\nexport type AsyncFunction<R extends any[] = any[], T = any> = (\n ...args: R\n) => Promise<T>;\n\nexport function exitContext<T>(fn: () => T): T {\n return context.exit(fn);\n}\n\nexport function provideContext<R>(\n value: CommandKitEnvironment,\n receiver: () => R,\n): R {\n Reflect.set(value, kCommandWorker, true);\n return context.run(value, receiver);\n}\n\n/**\n * Returns a context-aware version of the given function.\n * @param env - The commandkit environment data.\n * @param fn - The target function.\n * @param finalizer - An optional finalizer function to run after the target function. This function will be context-aware.\n * @internal\n */\nexport function makeContextAwareFunction<\n R extends GenericFunction,\n F extends GenericFunction,\n>(env: CommandKitEnvironment, fn: R, finalizer?: F): R {\n const _fn = (...args: any[]) => {\n return provideContext(env, async () => {\n try {\n // execute the target function\n const result = await fn(...args);\n\n return result;\n } catch (e) {\n if (!isCommandKitError(e)) {\n env.setExecutionError(e as Error);\n }\n } finally {\n if (typeof finalizer === 'function') {\n // execute the finalizer function\n setImmediate(async () => {\n try {\n await finalizer(...args);\n } catch {\n // no-op\n }\n });\n }\n }\n });\n };\n\n return _fn as R;\n}\n\n/**\n * Retrieves commandkit\n * @private\n * @internal\n */\nexport function getCommandKit(): CommandKit | undefined;\nexport function getCommandKit(strict: true): CommandKit;\nexport function getCommandKit(strict: false): CommandKit | undefined;\nexport function getCommandKit(strict = false): CommandKit | undefined {\n const kit = context.getStore()?.commandkit ?? CommandKit.instance;\n\n if (!kit && strict) {\n throw new Error('CommandKit instance not found.');\n }\n\n return kit;\n}\n\n/**\n * Get the current commandkit context.\n * @internal\n */\nexport function getContext(): CommandKitEnvironment | undefined {\n const ctx = context.getStore();\n return ctx;\n}\n\n/**\n * Use current commandkit context. Throws an error if no context is found.\n */\nexport function useEnvironment(): CommandKitEnvironment {\n const ctx = context.getStore();\n if (!ctx) {\n throw new Error(\n 'No commandkit environment found. Please make sure you are inside commandkit handler.',\n );\n }\n\n return ctx;\n}\n","import {\n type Awaitable,\n type ButtonInteraction,\n ButtonStyle,\n ButtonBuilder,\n Events,\n} from 'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext,\n} from '../../../context/async-context';\nimport {\n EventInterceptorContextData,\n EventInterceptorErrorHandler,\n} from '../../common/EventInterceptor';\n\nexport type ButtonKitPredicate = (\n interaction: ButtonInteraction,\n) => Awaitable<boolean>;\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnButtonKitClick =\n CommandKitButtonBuilderInteractionCollectorDispatch;\n\n/**\n * The handler to run when the interaction collector ends. This handler is called with the reason as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnButtonKitEnd = CommandKitButtonBuilderOnEnd;\n\n/**\n * The handler to run when a button is clicked. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitButtonBuilderInteractionCollectorDispatch = (\n interaction: ButtonInteraction,\n context: ButtonKit,\n) => Awaitable<void>;\n\nexport type CommandKitButtonBuilderOnEnd = (reason: string) => Awaitable<void>;\n\nexport type CommandKitButtonBuilderInteractionCollectorDispatchContextData =\n EventInterceptorContextData<Events.InteractionCreate>;\n\nexport class ButtonKit extends ButtonBuilder {\n #onClickHandler: CommandKitButtonBuilderInteractionCollectorDispatch | null =\n null;\n #contextData: CommandKitButtonBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: true,\n time: 5 * 60 * 1000,\n once: false,\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets up an inline interaction collector for this button. This collector by default allows as many interactions as possible if it is actively used.\n * If unused, this expires after 24 hours or custom time if specified.\n * @param handler The handler to run when the button is clicked\n * @param data The context data to use for the interaction collector\n * @returns This button\n * @example\n * ```ts\n * const button = new ButtonKit()\n * .setLabel('Click me')\n * .setStyle(ButtonStyle.Primary)\n * .setCustomId('click_me')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onClick(async (interaction) => {\n * await interaction.reply('You clicked me!');\n * });\n *\n * const row = new ActionRowBuilder().addComponents(button);\n *\n * const message = await channel.send({ content: 'Click the button', components: [row] });\n *\n * // Remove onClick handler and destroy the interaction collector\n * button.onClick(null);\n * ```\n */\n public onClick(\n handler: CommandKitButtonBuilderInteractionCollectorDispatch,\n data?: CommandKitButtonBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onClick\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n if (this.#onClickHandler) {\n this.#destroyCollector();\n }\n\n this.#onClickHandler = handler;\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd,\n };\n }\n\n this.#setupInteractionCollector();\n\n return this;\n }\n\n public onEnd(handler: CommandKitButtonBuilderOnEnd): this {\n if (this.data.style === ButtonStyle.Link) {\n throw new TypeError('Cannot setup \"onEnd\" handler on link buttons.');\n }\n\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate The filter to use for the interaction collector\n */\n public filter(predicate: ButtonKitPredicate): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000,\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupInteractionCollector() {\n if (\n this.data.style === ButtonStyle.Link ||\n !this.#contextData ||\n !this.#onClickHandler\n )\n return;\n\n const myCustomId = this.customId ?? null;\n\n if (myCustomId === null) {\n throw new TypeError(\n 'Cannot setup \"onClick\" handler on a button without a custom id.',\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isButton()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onClickHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData,\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#contextData = null;\n this.#onClickHandler = null;\n }\n}\n","import { ButtonStyle, ComponentEmojiResolvable } from 'discord.js';\nimport {\n ButtonKit,\n CommandKitButtonBuilderOnEnd,\n type CommandKitButtonBuilderInteractionCollectorDispatch,\n type CommandKitButtonBuilderInteractionCollectorDispatchContextData,\n} from './ButtonKit';\nimport { CommandKitElement } from '../../common/element';\nimport { MaybeArray } from '../../common/types';\nimport { EventInterceptorErrorHandler } from '../../common/EventInterceptor';\n\nexport type ButtonChildrenLike = string | number | boolean;\n\nexport interface ButtonProps {\n label?: string;\n style?: ButtonStyle;\n emoji?: ComponentEmojiResolvable;\n disabled?: boolean;\n customId?: string;\n url?: string;\n skuId?: string;\n onClick?: CommandKitButtonBuilderInteractionCollectorDispatch;\n onError?: EventInterceptorErrorHandler;\n options?: CommandKitButtonBuilderInteractionCollectorDispatchContextData;\n onEnd?: CommandKitButtonBuilderOnEnd;\n children?: MaybeArray<ButtonChildrenLike>;\n}\n\n/**\n * The button component.\n * @param props The button properties.\n * @returns The commandkit element.\n * @example <Button style={ButtonStyle.Primary} customId=\"click_me\">Click Me</Button>\n */\nexport function Button(props: ButtonProps): CommandKitElement<'button-kit'> {\n const button = new ButtonKit();\n\n props.style ??= ButtonStyle.Primary;\n\n // auto-generate customId if not provided (only if onClick is set)\n if (props.onClick) {\n props.customId ??= `buttonkit::${crypto.randomUUID()}`;\n }\n\n if (props.customId) {\n button.setCustomId(props.customId);\n }\n\n if (props.onClick) {\n button.onClick(props.onClick, props.options);\n }\n\n if (props.disabled) {\n button.setDisabled(props.disabled);\n }\n\n if (props.emoji) {\n button.setEmoji(props.emoji);\n }\n\n if (props.skuId) {\n button.setSKUId(props.skuId);\n }\n\n if (props.url) {\n button.setURL(props.url);\n }\n\n if (props.style) {\n button.setStyle(props.style);\n }\n\n const label = props.label || props.children;\n\n if (label) {\n button.setLabel(\n Array.isArray(label)\n ? label.join(' ')\n : typeof label === 'string'\n ? label\n : String(label),\n );\n }\n\n if (props.onEnd) {\n button.onEnd(props.onEnd);\n }\n\n if (props.onError) {\n button.onError(props.onError);\n }\n\n return button;\n}\n","import {\n Awaitable,\n Events,\n ModalBuilder,\n ModalSubmitInteraction,\n} from 'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext,\n} from '../../../context/async-context';\nimport {\n EventInterceptorContextData,\n EventInterceptorErrorHandler,\n} from '../../common/EventInterceptor';\n\nexport type ModalKitPredicate = (\n interaction: ModalSubmitInteraction,\n) => Awaitable<boolean>;\n\n/**\n * The handler to run when a modal is submitted. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnModalKitSubmit =\n CommandKitModalBuilderInteractionCollectorDispatch;\n\n/**\n * The handler to run when the interaction collector ends. This handler is called with the reason as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type OnModalKitEnd = CommandKitModalBuilderOnEnd;\n\n/**\n * The handler to run when a modal is submitted. This handler is called with the interaction as the first argument.\n * If the first argument is null, it means that the interaction collector has been destroyed.\n */\nexport type CommandKitModalBuilderInteractionCollectorDispatch = (\n interaction: ModalSubmitInteraction,\n context: ModalKit,\n) => Awaitable<void>;\n\nexport type CommandKitModalBuilderOnEnd = (reason: string) => Awaitable<void>;\n\nexport type CommandKitModalBuilderInteractionCollectorDispatchContextData =\n EventInterceptorContextData<Events.InteractionCreate>;\n\nexport class ModalKit extends ModalBuilder {\n #onSubmitHandler: CommandKitModalBuilderInteractionCollectorDispatch | null =\n null;\n #contextData: CommandKitModalBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true,\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new ModalKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onSubmit(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSubmit(\n handler: CommandKitModalBuilderInteractionCollectorDispatch,\n data?: CommandKitModalBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n if (this.#onSubmitHandler) {\n this.#destroyCollector();\n }\n\n this.#onSubmitHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd,\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitModalBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(predicate: ModalKitPredicate): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000,\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.',\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isModalSubmit()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSubmitHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData,\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSubmitHandler = null;\n this.#contextData = null;\n }\n}\n","import { ActionRowBuilder, TextInputBuilder, TextInputStyle } from 'discord.js';\nimport { MaybeArray } from '../../common/types';\nimport { CommandKitElement } from '../../common/element';\nimport {\n CommandKitModalBuilderInteractionCollectorDispatchContextData,\n ModalKit,\n OnModalKitEnd,\n OnModalKitSubmit,\n} from './ModalKit';\nimport { EventInterceptorErrorHandler } from '../../common/EventInterceptor';\n\nexport interface ModalProps {\n customId?: string;\n title: string;\n children?: MaybeArray<TextInputBuilder | ActionRowBuilder>;\n onSubmit?: OnModalKitSubmit;\n onEnd?: OnModalKitEnd;\n onError?: EventInterceptorErrorHandler;\n options?: CommandKitModalBuilderInteractionCollectorDispatchContextData;\n}\n\n/**\n * The modal component.\n * @param props The modal properties.\n * @returns The commandkit element.\n * @example <Modal title=\"My Modal\" onSubmit={onSubmit}>...</Modal>\n */\nexport function Modal(props: ModalProps): CommandKitElement<'modal'> {\n const modal = new ModalKit();\n\n if (props.title) {\n modal.setTitle(props.title);\n }\n\n if (props.onSubmit) {\n props.customId ??= `modalkit::${crypto.randomUUID()}`;\n }\n\n if (props.customId) {\n modal.setCustomId(props.customId);\n }\n\n if (props.onSubmit) {\n modal.onSubmit(props.onSubmit, props.options);\n }\n\n if (props.children) {\n const childs = (\n Array.isArray(props.children) ? props.children : [props.children]\n )\n .map((c) => {\n if (c instanceof ActionRowBuilder) return c;\n if (c instanceof TextInputBuilder)\n return new ActionRowBuilder().addComponents(c);\n })\n .filter((c): c is ActionRowBuilder<TextInputBuilder> => c != null);\n\n modal.addComponents(childs);\n }\n\n if (props.onEnd) {\n modal.onEnd(props.onEnd);\n }\n\n if (props.onError) {\n modal.onError(props.onError);\n }\n\n return modal;\n}\n\nexport interface TextInputProps {\n customId: string;\n label: string;\n placeholder?: string;\n maxLength?: number;\n minLength?: number;\n value?: string;\n required?: boolean;\n}\n\n/**\n * The text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <TextInput customId=\"input\" label=\"Input\" style={TextInputStyle.Short} />\n */\nexport function TextInput(\n props: TextInputProps & { style: TextInputStyle },\n): CommandKitElement<'text-input'> {\n const input = new TextInputBuilder().setStyle(props.style);\n\n if (props.customId) {\n input.setCustomId(props.customId);\n }\n\n if (props.label) {\n input.setLabel(props.label);\n }\n\n if (props.placeholder) {\n input.setPlaceholder(props.placeholder);\n }\n\n if (props.maxLength) {\n input.setMaxLength(props.maxLength);\n }\n\n if (props.minLength) {\n input.setMinLength(props.minLength);\n }\n\n if (props.value) {\n input.setValue(props.value);\n }\n\n if (props.required) {\n input.setRequired(props.required);\n }\n\n return input;\n}\n\n/**\n * The short text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <ShortInput customId=\"input\" label=\"Input\" />\n */\nexport function ShortInput(\n props: TextInputProps,\n): CommandKitElement<'text-input'> {\n return TextInput({ ...props, style: TextInputStyle.Short });\n}\n\n/**\n * The paragraph text input component.\n * @param props The text input properties.\n * @returns The commandkit element.\n * @example <ParagraphInput customId=\"input\" label=\"Input\" />\n */\nexport function ParagraphInput(\n props: TextInputProps,\n): CommandKitElement<'text-input'> {\n return TextInput({ ...props, style: TextInputStyle.Paragraph });\n}\n","import {\n Events,\n StringSelectMenuBuilder,\n StringSelectMenuInteraction,\n} from 'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext,\n} from '../../../context/async-context';\nimport { EventInterceptorErrorHandler } from '../../common/EventInterceptor';\nimport {\n CommandKitSelectMenuBuilderInteractionCollectorDispatch,\n CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n CommandKitSelectMenuBuilderOnEnd,\n OnSelectMenuKitSubmit,\n SelectMenuKitPredicate,\n} from './common';\n\nexport type OnStringSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n StringSelectMenuInteraction,\n StringSelectMenuKit\n>;\n\nexport type StringSelectMenuKitPredicate =\n SelectMenuKitPredicate<StringSelectMenuInteraction>;\n\nexport class StringSelectMenuKit extends StringSelectMenuBuilder {\n #onSelectHandler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n StringSelectMenuInteraction,\n StringSelectMenuKit\n > | null = null;\n #contextData: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true,\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new StringSelectMenuKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onSelect(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSelect(\n handler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n StringSelectMenuInteraction,\n StringSelectMenuKit\n >,\n data?: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n if (this.#onSelectHandler) {\n this.#destroyCollector();\n }\n\n this.#onSelectHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd,\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitSelectMenuBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(\n predicate: SelectMenuKitPredicate<StringSelectMenuInteraction>,\n ): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000,\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.',\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isStringSelectMenu()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSelectHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData,\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSelectHandler = null;\n this.#contextData = null;\n }\n}\n","import {\n Events,\n ChannelSelectMenuBuilder,\n ChannelSelectMenuInteraction,\n} from 'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext,\n} from '../../../context/async-context';\nimport { EventInterceptorErrorHandler } from '../../common/EventInterceptor';\nimport {\n CommandKitSelectMenuBuilderInteractionCollectorDispatch,\n CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n CommandKitSelectMenuBuilderOnEnd,\n OnSelectMenuKitSubmit,\n SelectMenuKitPredicate,\n} from './common';\n\nexport type OnChannelSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n ChannelSelectMenuInteraction,\n ChannelSelectMenuKit\n>;\n\nexport type ChannelSelectMenuKitPredicate =\n SelectMenuKitPredicate<ChannelSelectMenuInteraction>;\n\nexport class ChannelSelectMenuKit extends ChannelSelectMenuBuilder {\n #onSelectHandler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n ChannelSelectMenuInteraction,\n ChannelSelectMenuKit\n > | null = null;\n #contextData: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true,\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new ChannelSelectMenuKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.Channel.id === '1234567890')\n * .onSelect(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSelect(\n handler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n ChannelSelectMenuInteraction,\n ChannelSelectMenuKit\n >,\n data?: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n if (this.#onSelectHandler) {\n this.#destroyCollector();\n }\n\n this.#onSelectHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd,\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitSelectMenuBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(\n predicate: SelectMenuKitPredicate<ChannelSelectMenuInteraction>,\n ): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000,\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.',\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isChannelSelectMenu()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSelectHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData,\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSelectHandler = null;\n this.#contextData = null;\n }\n}\n","import {\n Events,\n MentionableSelectMenuBuilder,\n MentionableSelectMenuInteraction,\n} from 'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext,\n} from '../../../context/async-context';\nimport { EventInterceptorErrorHandler } from '../../common/EventInterceptor';\nimport {\n CommandKitSelectMenuBuilderInteractionCollectorDispatch,\n CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n CommandKitSelectMenuBuilderOnEnd,\n OnSelectMenuKitSubmit,\n SelectMenuKitPredicate,\n} from './common';\n\nexport type OnMentionableSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n MentionableSelectMenuInteraction,\n MentionableSelectMenuKit\n>;\n\nexport type MentionableSelectMenuKitPredicate =\n SelectMenuKitPredicate<MentionableSelectMenuInteraction>;\n\nexport class MentionableSelectMenuKit extends MentionableSelectMenuBuilder {\n #onSelectHandler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n MentionableSelectMenuInteraction,\n MentionableSelectMenuKit\n > | null = null;\n #contextData: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true,\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new MentionableSelectMenuKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.Mentionable.id === '1234567890')\n * .onSelect(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSelect(\n handler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n MentionableSelectMenuInteraction,\n MentionableSelectMenuKit\n >,\n data?: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n if (this.#onSelectHandler) {\n this.#destroyCollector();\n }\n\n this.#onSelectHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd,\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitSelectMenuBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(\n predicate: SelectMenuKitPredicate<MentionableSelectMenuInteraction>,\n ): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000,\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.',\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isMentionableSelectMenu()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSelectHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData,\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSelectHandler = null;\n this.#contextData = null;\n }\n}\n","import {\n Events,\n UserSelectMenuBuilder,\n UserSelectMenuInteraction,\n} from 'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext,\n} from '../../../context/async-context';\nimport { EventInterceptorErrorHandler } from '../../common/EventInterceptor';\nimport {\n CommandKitSelectMenuBuilderInteractionCollectorDispatch,\n CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n CommandKitSelectMenuBuilderOnEnd,\n OnSelectMenuKitSubmit,\n SelectMenuKitPredicate,\n} from './common';\n\nexport type OnUserSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n UserSelectMenuInteraction,\n UserSelectMenuKit\n>;\n\nexport type UserSelectMenuKitPredicate =\n SelectMenuKitPredicate<UserSelectMenuInteraction>;\n\nexport class UserSelectMenuKit extends UserSelectMenuBuilder {\n #onSelectHandler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n UserSelectMenuInteraction,\n UserSelectMenuKit\n > | null = null;\n #contextData: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true,\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new UserSelectMenuKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.user.id === '1234567890')\n * .onSelect(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSelect(\n handler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n UserSelectMenuInteraction,\n UserSelectMenuKit\n >,\n data?: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n if (this.#onSelectHandler) {\n this.#destroyCollector();\n }\n\n this.#onSelectHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd,\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitSelectMenuBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(\n predicate: SelectMenuKitPredicate<UserSelectMenuInteraction>,\n ): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000,\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.',\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isUserSelectMenu()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSelectHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData,\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSelectHandler = null;\n this.#contextData = null;\n }\n}\n","import {\n Events,\n RoleSelectMenuBuilder,\n RoleSelectMenuInteraction,\n} from 'discord.js';\nimport {\n exitContext,\n getCommandKit,\n getContext,\n} from '../../../context/async-context';\nimport { EventInterceptorErrorHandler } from '../../common/EventInterceptor';\nimport {\n CommandKitSelectMenuBuilderInteractionCollectorDispatch,\n CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n CommandKitSelectMenuBuilderOnEnd,\n OnSelectMenuKitSubmit,\n SelectMenuKitPredicate,\n} from './common';\n\nexport type OnRoleSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n RoleSelectMenuInteraction,\n RoleSelectMenuKit\n>;\n\nexport type RoleSelectMenuKitPredicate =\n SelectMenuKitPredicate<RoleSelectMenuInteraction>;\n\nexport class RoleSelectMenuKit extends RoleSelectMenuBuilder {\n #onSelectHandler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n RoleSelectMenuInteraction,\n RoleSelectMenuKit\n > | null = null;\n #contextData: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData | null =\n {\n autoReset: false,\n time: 5 * 60 * 1000,\n once: true,\n };\n #unsub: (() => void) | null = null;\n\n #getEventInterceptor() {\n const ctx = getContext();\n if (!ctx) return getCommandKit(true).eventInterceptor;\n\n return exitContext(() => ctx.commandkit.eventInterceptor);\n }\n\n /**\n * Sets the handler to run when the modal is submitted.\n * @param handler - The handler to run when the modal is submitted.\n * @param data - The context data for the interaction collector.\n * @returns This instance of the modal builder.\n * @example\n * ```ts\n * const modal = new RoleSelectMenuKit()\n * .setTitle('My Modal')\n * .setCustomId('my-modal')\n * .filter((interaction) => interaction.Role.id === '1234567890')\n * .onSelect(async (interaction) => {\n * await interaction.reply('You submitted the modal!');\n * })\n * .addComponents(actionRow1, actionRow2);\n * ```\n */\n public onSelect(\n handler: CommandKitSelectMenuBuilderInteractionCollectorDispatch<\n RoleSelectMenuInteraction,\n RoleSelectMenuKit\n >,\n data?: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n ): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onClick\" without a handler function parameter.',\n );\n }\n\n if (this.#onSelectHandler) {\n this.#destroyCollector();\n }\n\n this.#onSelectHandler = handler;\n\n if (data) {\n this.#contextData = {\n autoReset: data.autoReset ?? this.#contextData?.autoReset ?? true,\n time: data.time ?? this.#contextData?.time ?? 5 * 60 * 1000,\n filter: data.filter ?? this.#contextData?.filter,\n onEnd: data.onEnd ?? this.#contextData?.onEnd,\n };\n }\n\n this.#setupCollector();\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onEnd(handler: CommandKitSelectMenuBuilderOnEnd): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onEnd\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onEnd = handler;\n\n return this;\n }\n\n /**\n * Sets the handler to run when the interaction collector ends.\n * @param handler - The handler to run when the interaction collector ends.\n * @returns This instance of the modal builder.\n */\n public onError(handler: EventInterceptorErrorHandler): this {\n if (!handler) {\n throw new TypeError(\n 'Cannot setup \"onError\" without a handler function parameter.',\n );\n }\n\n this.#contextData ??= {};\n this.#contextData.onError = handler;\n\n return this;\n }\n\n /**\n * Sets a filter for the interaction collector.\n * @param predicate - The filter to use for the interaction collector.\n * @returns This instance of the modal builder.\n */\n public filter(\n predicate: SelectMenuKitPredicate<RoleSelectMenuInteraction>,\n ): this {\n this.#contextData ??= {\n autoReset: true,\n time: 5 * 60 * 1000,\n };\n // @ts-ignore\n this.#contextData.filter = predicate;\n\n return this;\n }\n\n private get customId() {\n // @ts-ignore\n return this.data.custom_id ?? this.data.customId;\n }\n\n #setupCollector() {\n if (!this.#contextData) return;\n\n if (!this.customId) {\n throw new TypeError(\n 'Cannot setup an modal collector without a custom ID.',\n );\n }\n\n const interceptor = this.#getEventInterceptor();\n if (!interceptor) return;\n\n this.#unsub = interceptor.subscribe(\n Events.InteractionCreate,\n async (interaction) => {\n if (!interaction.isRoleSelectMenu()) return;\n\n const myCustomId = this.customId ?? null;\n const interactionCustomId = interaction.customId;\n\n if (myCustomId && interactionCustomId !== myCustomId) return;\n\n const filter = this.#contextData?.filter;\n\n if (filter && !(await filter(interaction))) return;\n\n const handler = this.#onSelectHandler;\n\n if (!handler) return this.#unsub?.();\n\n return handler(interaction, this);\n },\n this.#contextData,\n );\n }\n\n public dispose() {\n this.#destroyCollector();\n return this;\n }\n\n #destroyCollector() {\n this.#unsub?.();\n this.#unsub = null;\n this.#onSelectHandler = null;\n this.#contextData = null;\n }\n}\n","import {\n APISelectMenuOption,\n BaseSelectMenuComponentData,\n ChannelSelectMenuComponentData,\n ChannelSelectMenuInteraction,\n MentionableSelectMenuComponentData,\n MentionableSelectMenuInteraction,\n RoleSelectMenuComponentData,\n RoleSelectMenuInteraction,\n SelectMenuComponentOptionData,\n StringSelectMenuInteraction,\n StringSelectMenuOptionBuilder,\n UserSelectMenuComponentData,\n UserSelectMenuInteraction,\n} from 'discord.js';\nimport { ChannelSelectMenuKit } from './ChannelSelectMenuKit';\nimport { MentionableSelectMenuKit } from './MentionableSelectMenuKit';\nimport { RoleSelectMenuKit } from './RoleSelectMenuKit';\nimport { StringSelectMenuKit } from './StringSelectMenuKit';\nimport { UserSelectMenuKit } from './UserSelectMenuKit';\nimport { MaybeArray } from '../../common/types';\nimport {\n CommandKitSelectMenuBuilderInteractionCollectorDispatch,\n CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData,\n CommandKitSelectMenuBuilderOnEnd,\n} from './common';\n\nexport interface CommonSelectMenuProps<T, C> {\n onSelect?: CommandKitSelectMenuBuilderInteractionCollectorDispatch<T, C>;\n onEnd?: CommandKitSelectMenuBuilderOnEnd;\n onError?: (error: Error) => any;\n options?: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData;\n}\n\nexport interface SelectMenuProps<T, C>\n extends Partial<Omit<BaseSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<T, C> {}\n\nexport interface StringSelectMenuProps\n extends SelectMenuProps<StringSelectMenuInteraction, StringSelectMenuKit> {\n children?: MaybeArray<StringSelectMenuOptionBuilder>;\n}\n\nexport type CommonBuilderKit =\n | StringSelectMenuKit\n | UserSelectMenuKit\n | RoleSelectMenuKit\n | ChannelSelectMenuKit\n | MentionableSelectMenuKit;\n\nexport type ResolveBuilderInteraction<T> = T extends StringSelectMenuKit\n ? StringSelectMenuInteraction\n : T extends UserSelectMenuKit\n ? UserSelectMenuInteraction\n : T extends RoleSelectMenuKit\n ? RoleSelectMenuInteraction\n : T extends ChannelSelectMenuKit\n ? ChannelSelectMenuInteraction\n : T extends MentionableSelectMenuKit\n ? MentionableSelectMenuInteraction\n : never;\n\nfunction applyPropsToBuilder<B extends CommonBuilderKit>(\n builder: B,\n props: Partial<Omit<BaseSelectMenuComponentData, 'type'>> &\n CommonSelectMenuProps<ResolveBuilderInteraction<B>, B>,\n) {\n builder.setCustomId(props.customId ?? `select-menu::${crypto.randomUUID()}`);\n\n if (props.maxValues != null) {\n builder.setMaxValues(props.maxValues);\n }\n\n if (props.minValues != null) {\n builder.setMinValues(props.minValues);\n }\n\n if (props.placeholder) {\n builder.setPlaceholder(props.placeholder);\n }\n\n if (props.disabled) {\n builder.setDisabled(props.disabled);\n }\n\n if (props.onEnd) {\n builder.onEnd(props.onEnd);\n }\n\n if (props.onError) {\n builder.onError(props.onError);\n }\n\n if (props.onSelect) {\n // @ts-ignore\n builder.onSelect(props.onSelect, props.options);\n }\n}\n\nexport function StringSelectMenu(props: StringSelectMenuProps) {\n const builder = new StringSelectMenuKit();\n\n applyPropsToBuilder(builder, props);\n\n if (props.children) {\n builder.setOptions(\n Array.isArray(props.children) ? props.children : [props.children],\n );\n }\n\n if (props.children) {\n builder.setOptions(\n Array.isArray(props.children) ? props.children : [props.children],\n );\n }\n\n return builder;\n}\n\nexport type StringSelectMenuOptionProps =\n | SelectMenuComponentOptionData\n | APISelectMenuOption;\n\nexport function StringSelectMenuOption(props: StringSelectMenuOptionProps) {\n return new StringSelectMenuOptionBuilder(props);\n}\n\nexport interface UserSelectMenuProps\n extends Partial<Omit<UserSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<UserSelectMenuInteraction, UserSelectMenuKit> {}\n\nexport function UserSelectMenu(props: UserSelectMenuProps) {\n const builder = new UserSelectMenuKit();\n\n applyPropsToBuilder(builder, props);\n\n if (props.defaultValues) {\n builder.setDefaultUsers(\n Array.isArray(props.defaultValues)\n ? props.defaultValues\n : [props.defaultValues],\n );\n }\n\n return builder;\n}\n\nexport interface RoleSelectMenuProps\n extends Partial<Omit<RoleSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<RoleSelectMenuInteraction, RoleSelectMenuKit> {}\n\nexport function RoleSelectMenu(props: RoleSelectMenuProps) {\n const builder = new RoleSelectMenuKit();\n\n applyPropsToBuilder(builder, props);\n\n if (props.defaultValues) {\n builder.setDefaultRoles(\n Array.isArray(props.defaultValues)\n ? props.defaultValues\n : [props.defaultValues],\n );\n }\n\n return builder;\n}\n\nexport interface MentionableSelectMenuProps\n extends Partial<Omit<MentionableSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<\n MentionableSelectMenuInteraction,\n MentionableSelectMenuKit\n > {}\n\nexport function MentionableSelectMenu(props: MentionableSelectMenuProps) {\n const builder = new MentionableSelectMenuKit();\n\n applyPropsToBuilder(builder, props);\n\n if (props.defaultValues) {\n builder.setDefaultValues(\n Array.isArray(props.defaultValues)\n ? props.defaultValues\n : [props.defaultValues],\n );\n }\n\n return builder;\n}\n\nexport interface ChannelSelectMenuProps\n extends Partial<Omit<ChannelSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<ChannelSelectMenuInteraction, ChannelSelectMenuKit> {}\n\nexport function ChannelSelectMenu(props: ChannelSelectMenuProps) {\n const builder = new ChannelSelectMenuKit();\n\n applyPropsToBuilder(builder, props);\n\n if (props.defaultValues) {\n builder.setDefaultChannels(\n Array.isArray(props.defaultValues)\n ? props.defaultValues\n : [props.defaultValues],\n );\n }\n\n if (props.channelTypes) {\n builder.setChannelTypes(\n Array.isArray(props.channelTypes)\n ? props.channelTypes\n : [props.channelTypes],\n );\n }\n\n return builder;\n}\n","import { getContext } from '../context/async-context';\nimport colors from '../utils/colors';\nimport { ILogger } from './ILogger';\n\nenum LogLevel {\n DEBUG,\n INFO,\n WARN,\n ERROR,\n DEFAULT,\n}\n\nconst execHandlerKind = {\n autocomplete: 'Autocomplete',\n messageContextMenu: 'MessageContextMenu',\n userContextMenu: 'UserContextMenu',\n chatInput: 'ChatInputCommand',\n message: 'Message',\n};\n\nconst TextColorMap = {\n [LogLevel.DEBUG]: colors.blue,\n [LogLevel.INFO]: colors.green,\n [LogLevel.WARN]: colors.yellow,\n [LogLevel.ERROR]: colors.red,\n [LogLevel.DEFAULT]: colors.white,\n};\n\nconst TextBgColorMap = {\n [LogLevel.DEBUG]: colors.bgBlue,\n [LogLevel.INFO]: colors.bgGreen,\n [LogLevel.WARN]: colors.bgYellow,\n [LogLevel.ERROR]: colors.bgRed,\n [LogLevel.DEFAULT]: colors.bgWhite,\n};\n\nconst BoxChars = {\n vertical: '│',\n horizontalDown: '┬',\n horizontalUp: '┴',\n verticalRight: '├',\n corner: '└',\n};\n\nexport class DefaultLogger implements ILogger {\n private logger: Console;\n\n public constructor(\n public stdout = process.stdout,\n public stderr = process.stderr,\n ) {\n this.logger = new console.Console(this.stdout, this.stderr);\n }\n\n private _formatTime(date: Date): string {\n const hours = date.getHours().toString().padStart(2, '0');\n const minutes = date.getMinutes().toString().padStart(2, '0');\n const seconds = date.getSeconds().toString().padStart(2, '0');\n const millis = date.getMilliseconds().toString().padStart(3, '0');\n return `${hours}:${minutes}:${seconds}.${millis}`;\n }\n\n private _getContext(): string {\n const ctx = getContext();\n if (!ctx) return '';\n\n const kind = ctx.variables.get('execHandlerKind');\n const commandHandler = ctx.variables.get('commandHandlerType');\n const command = ctx.variables.get('currentCommandName');\n if (!kind && !commandHandler) return '';\n\n const h = execHandlerKind[kind as keyof typeof execHandlerKind];\n\n if (!h && !commandHandler) return '';\n\n const forwardedBy = ctx.variables.get('forwardedBy');\n const forwardedTo = ctx.variables.get('forwardedTo');\n\n const cmdText = command ? colors.magenta(`/${command}`) + ' ' : '';\n const forward = forwardedTo\n ? `${colors.yellowBright(`(${forwardedBy || command} → ${forwardedTo})`)} `\n : '';\n\n return (\n colors.dim(`${BoxChars.vertical} `) +\n colors.cyanBright(\n `${cmdText}${forward}${h ? colors.gray(`[${h}]`) : ''}`.trim(),\n )\n );\n }\n\n private _getLevelLabel(level: LogLevel): string {\n let label: string;\n switch (level) {\n case LogLevel.DEBUG:\n label = '[DEBUG]';\n break;\n case LogLevel.INFO:\n label = '[INFO]';\n break;\n case LogLevel.WARN:\n label = '[WARN]';\n break;\n case LogLevel.ERROR:\n label = '[ERROR]';\n break;\n default:\n label = '[LOG]';\n }\n\n const coloredLabel = TextBgColorMap[level](\n colors.whiteBright(` ${label} `),\n );\n return `${coloredLabel} `;\n }\n\n private _getPrefix(level: LogLevel): string {\n const timestamp = this._formatTime(new Date());\n const label = this._getLevelLabel(level);\n return `${label}${colors.dim(BoxChars.vertical)} ${colors.dim(timestamp)}`;\n }\n\n private _log(level: LogLevel, ...args: any[]): void {\n const prefix = this._getPrefix(level);\n const context = this._getContext();\n const colorFn = TextColorMap[level];\n\n if (context) {\n this.logger.log(\n `${prefix}\\n${context} ${colors.dim(BoxChars.corner)}`,\n ...args.map((arg) => colorFn(arg)),\n );\n } else {\n this.logger.log(\n `${prefix} ${colors.dim(BoxChars.corner)}`,\n ...args.map((arg) => colorFn(arg)),\n );\n }\n }\n\n public debug(...args: any[]): void {\n this._log(LogLevel.DEBUG, ...args);\n }\n\n public error(...args: any[]): void {\n this._log(LogLevel.ERROR, ...args);\n }\n\n public log(...args: any[]): void {\n this._log(LogLevel.DEFAULT, ...args);\n }\n\n public info(...args: any[]): void {\n this._log(LogLevel.INFO, ...args);\n }\n\n public warn(...args: any[]): void {\n this._log(LogLevel.WARN, ...args);\n }\n}\n","import { DefaultLogger } from './DefaultLogger';\nimport type { ILogger } from './ILogger';\n\nexport interface CommandKitLoggerOptions {\n /**\n * The logger provider to use.\n */\n provider: ILogger;\n}\n\nexport interface LoggerImpl extends ILogger {\n configure(options: CommandKitLoggerOptions): void;\n}\n\nexport function createLogger(options: CommandKitLoggerOptions): LoggerImpl {\n let opt = options;\n\n if (!opt?.provider) {\n throw new Error('A logger provider must be provided.');\n }\n\n const methods = ['log', 'error', 'warn', 'info', 'debug'] as const;\n\n const impl = {\n configure(options) {\n opt = options;\n },\n } as LoggerImpl;\n\n for (const method of methods) {\n impl[method] = (...args: any[]) => {\n opt.provider[method](...args);\n };\n }\n\n return impl;\n}\n\nexport const Logger = createLogger({\n provider: new DefaultLogger(),\n});\n","import { Collection } from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport { RuntimePlugin } from '../RuntimePlugin';\nimport {\n CommandKitErrorCodes,\n createCommandKitError,\n isErrorType,\n} from '../../utils/error-codes';\nimport { Logger } from '../../logger/Logger';\nimport { AsyncFunction } from '../../context/async-context';\n\nexport class CommandKitPluginRuntime {\n private plugins = new Collection<string, RuntimePlugin>();\n\n public constructor(public readonly commandkit: CommandKit) {}\n\n public getPlugins() {\n return this.plugins;\n }\n\n public getPlugin(pluginName: string): RuntimePlugin | null {\n return this.plugins.get(pluginName) ?? null;\n }\n\n public async softRegisterPlugin(plugin: RuntimePlugin) {\n const pluginName = plugin.name;\n\n if (this.plugins.has(pluginName)) return;\n\n try {\n await plugin.activate(this);\n this.plugins.set(pluginName, plugin);\n } catch (e: any) {\n throw new Error(\n `Failed to activate plugin \"${pluginName}\": ${e?.stack || e}`,\n );\n }\n }\n\n public async registerPlugin(plugin: RuntimePlugin) {\n const pluginName = plugin.name;\n\n if (this.plugins.has(pluginName)) {\n throw new Error(`Plugin with name \"${pluginName}\" already exists.`);\n }\n\n try {\n await plugin.activate(this);\n this.plugins.set(pluginName, plugin);\n } catch (e: any) {\n throw new Error(\n `Failed to activate plugin \"${pluginName}\": ${e?.stack || e}`,\n );\n }\n }\n\n public async unregisterPlugin(plugin: RuntimePlugin) {\n const pluginName = plugin.name;\n\n if (!this.plugins.has(pluginName)) {\n throw new Error(`Plugin with name \"${pluginName}\" does not exist.`);\n }\n\n this.plugins.delete(pluginName);\n\n try {\n await plugin.deactivate(this);\n } catch (e: any) {\n throw new Error(\n `Failed to deactivate plugin \"${pluginName}\": ${e?.stack || e}`,\n );\n }\n }\n\n public async unregisterAllPlugins() {\n for (const plugin of this.plugins.values()) {\n await this.unregisterPlugin(plugin);\n }\n }\n\n public capture() {\n throw createCommandKitError(CommandKitErrorCodes.PluginCaptureHandle);\n }\n\n public async execute<R = any>(\n f: AsyncFunction<[CommandKitPluginRuntime, RuntimePlugin], R | undefined>,\n ) {\n let result: R | undefined;\n for (const plugin of this.plugins.values()) {\n try {\n result = await f(this, plugin);\n } catch (e: any) {\n if (isErrorType(e, CommandKitErrorCodes.PluginCaptureHandle)) {\n return true;\n }\n\n Logger.error(`Plugin \"${plugin.name}\" failed`, e?.stack || e);\n }\n }\n\n return result;\n }\n}\n","import { DirectiveTransformerOptions } from 'directive-to-hof';\nimport {\n CompilerPlugin,\n CompilerPluginRuntime,\n MaybeFalsey,\n PluginTransformParameters,\n TransformedResult,\n} from '../..';\n\nexport type CommonDirectiveTransformerOptions = DirectiveTransformerOptions & {\n enabled?: boolean;\n};\n\nexport abstract class CommonDirectiveTransformer extends CompilerPlugin<CommonDirectiveTransformerOptions> {\n private transformer: ReturnType<\n typeof import('directive-to-hof').createDirectiveTransformer\n > | null = null;\n\n public async activate(ctx: CompilerPluginRuntime): Promise<void> {\n const { createDirectiveTransformer } = await import('directive-to-hof');\n this.transformer = createDirectiveTransformer(this.options);\n }\n\n public async deactivate(ctx: CompilerPluginRuntime): Promise<void> {\n this.transformer = null;\n }\n\n public async transform(\n params: PluginTransformParameters,\n ): Promise<MaybeFalsey<TransformedResult>> {\n if (!this.options.enabled) return null;\n if (!this.transformer) return null;\n if (/\\.json$/.test(params.id)) return null;\n\n const result = await this.transformer(params.code.toString(), params.id);\n\n return {\n code: result.contents,\n map: null,\n };\n }\n}\n","import {\n CompilerPlugin,\n MaybeFalsey,\n PluginTransformParameters,\n TransformedResult,\n} from '../..';\n\nexport class MacroPlugin extends CompilerPlugin {\n public readonly name = 'MacroPlugin';\n\n private macroTransformer!: import('use-macro').MacroTransformer;\n\n public async activate(): Promise<void> {\n const transform = await import('use-macro');\n this.macroTransformer = new transform.MacroTransformer();\n }\n\n public async deactivate(): Promise<void> {\n this.macroTransformer = null!;\n }\n\n public async transform(\n params: PluginTransformParameters,\n ): Promise<MaybeFalsey<TransformedResult>> {\n if (!this.options.enabled) return null;\n if (/\\.json$/.test(params.id)) return null;\n\n const { contents } = await this.macroTransformer.transform(\n params.code,\n params.id,\n );\n\n return {\n code:\n typeof contents === 'string'\n ? contents\n : new TextDecoder().decode(contents),\n map: null,\n };\n }\n}\n","import { MacroPlugin } from '../plugins/plugin-runtime/builtin/MacroPlugin';\nimport { ResolvedCommandKitConfig } from './utils';\nimport json from '@rollup/plugin-json';\n\nexport const defaultConfig: ResolvedCommandKitConfig = {\n plugins: [new MacroPlugin({ enabled: true })],\n rolldownPlugins: [json() as any],\n compilerOptions: {\n macro: {\n development: false,\n },\n },\n static: true,\n typescript: {\n ignoreBuildErrors: false,\n },\n distDir: 'dist',\n env: {},\n sourceMap: {\n development: true,\n production: true,\n },\n typedCommands: true,\n};\n","import { MaybeArray } from '../components';\nimport { CommandKitPlugin } from '../plugins';\nimport { defaultConfig } from './default';\nimport { CommandKitConfig } from './types';\nimport { ResolvedCommandKitConfig } from './utils';\n\nlet defined: ResolvedCommandKitConfig = defaultConfig;\n\n/**\n * Get the defined configuration for CommandKit.\n */\nexport function getConfig(): ResolvedCommandKitConfig {\n return defined;\n}\n\n/**\n * Define the configuration for CommandKit.\n * @param config The configuration to use.\n */\nexport function defineConfig(\n config: Partial<CommandKitConfig> = {},\n): ResolvedCommandKitConfig {\n // defined = mergeDeep(\n // config as ResolvedCommandKitConfig,\n // mergeDeep({} as ResolvedCommandKitConfig, defaultConfig),\n // );\n\n defined = {\n compilerOptions: {\n macro: {\n ...defaultConfig.compilerOptions.macro,\n ...config.compilerOptions?.macro,\n },\n },\n distDir: config.distDir ?? defaultConfig.distDir,\n env: {\n ...defaultConfig.env,\n ...config.env,\n },\n rolldownPlugins: [\n ...(config.rolldownPlugins ?? []),\n ...(defaultConfig.rolldownPlugins ?? []),\n ],\n plugins: [...(config.plugins ?? []), ...(defaultConfig.plugins ?? [])].flat(\n Infinity,\n ) as MaybeArray<CommandKitPlugin[]>,\n sourceMap: {\n ...defaultConfig.sourceMap,\n ...config.sourceMap,\n },\n static: config.static ?? defaultConfig.static,\n typedCommands: config.typedCommands ?? defaultConfig.typedCommands,\n typescript: {\n ...defaultConfig.typescript,\n ...config.typescript,\n },\n };\n\n return defined;\n}\n","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { COMMANDKIT_IS_CLI, COMMANDKIT_IS_DEV } from './constants';\nimport { getConfig } from '../config/config';\nimport { eventWorkerContext } from '../app/events/EventWorkerContext';\n\nlet appDir: string | null = null;\nlet currentDir: string | null = null;\n\nfunction getSrcDir() {\n if (COMMANDKIT_IS_CLI) {\n return 'src';\n }\n\n if (COMMANDKIT_IS_DEV) {\n return '.commandkit';\n }\n\n return getConfig().distDir;\n}\n\nexport function getCurrentDirectory(): string {\n if (currentDir) return currentDir;\n const src = getSrcDir();\n let root = join(process.cwd(), src);\n\n if (!existsSync(root)) root = process.cwd();\n\n currentDir = root;\n\n return root;\n}\n\nexport function getSourceDirectories(): string[] {\n const dist = getConfig().distDir;\n const locations = ['src', '.commandkit', dist].map((dir) =>\n join(process.cwd(), dir),\n );\n\n return locations;\n}\n\n/**\n * Returns the path to the app directory.\n * @returns The path to the app directory or `null` if not found.\n */\nexport function findAppDirectory(): string | null {\n if (appDir) return appDir;\n\n let root = join(process.cwd(), getSrcDir());\n\n if (!existsSync(root)) root = process.cwd();\n\n const dirs = ['app'].map((dir) => join(root, dir));\n\n for (const dir of dirs) {\n if (existsSync(dir)) {\n appDir = dir;\n return dir;\n }\n }\n\n return null;\n}\n\n/**\n * Debounces a function.\n * @param fn The function to debounce.\n * @param ms The debounce time in milliseconds.\n * @returns The debounced function.\n */\nexport function debounce<R, F extends (...args: any[]) => R>(\n fn: F,\n ms: number,\n): F {\n let timer: NodeJS.Timeout | null = null;\n let resolve: ((value: R | PromiseLike<R>) => void) | null = null;\n\n return ((...args: any[]) => {\n if (timer) {\n clearTimeout(timer);\n if (resolve) {\n resolve(null as unknown as R); // Resolve with null if debounced\n }\n }\n\n return new Promise<R>((res) => {\n resolve = res;\n timer = setTimeout(() => {\n const result = fn(...args);\n res(result);\n timer = null;\n resolve = null;\n }, ms);\n });\n }) as F;\n}\n\n/**\n * Creates a function from the given function that runs only in development mode.\n * @param fn The function to run in development mode.\n * @returns The function that runs only in development mode.\n * @example\n * ```ts\n * const devOnlyFn = devOnly(() => {\n * console.log('This function runs only in development mode');\n * });\n * devOnlyFn(); // This will log the message only in development mode\n * ```\n */\nexport function devOnly<T extends (...args: any[]) => any>(fn: T): T {\n const f = (...args: Parameters<T>) => {\n if (COMMANDKIT_IS_DEV) {\n return fn(...args);\n }\n };\n\n return f as T;\n}\n\n/**\n * Custom error for stopping event propagation.\n */\nexport class StopEventPropagationError extends Error {\n constructor() {\n super('Event propagation stopped');\n this.name = 'StopEventPropagationError';\n }\n}\n\n/**\n * Stops event propagation.\n * @throws {StopEventPropagationError}\n */\nexport function stopEvents(): never {\n if (!eventWorkerContext.getStore()) {\n throw new Error('stopEvents() may only be called inside an event handler');\n }\n\n throw new StopEventPropagationError();\n}\n\nexport interface SimpleProxy<T extends object> {\n proxy: T;\n setTarget(newTarget: T): void;\n}\n\n/**\n * Creates a simple proxy object that mirrors the target object.\n * @param target The target object to proxy.\n * @returns The proxied object.\n */\nexport function createProxy<T extends object>(target: T): SimpleProxy<T> {\n let _target = target;\n\n const proxy = new Proxy(_target, {\n get(target, prop, receiver) {\n return Reflect.get(_target, prop, receiver);\n },\n set(target, prop, value, receiver) {\n return Reflect.set(_target, prop, value, receiver);\n },\n deleteProperty(target, prop) {\n return Reflect.deleteProperty(_target, prop);\n },\n has(target, prop) {\n return Reflect.has(_target, prop);\n },\n ownKeys(target) {\n return Reflect.ownKeys(_target);\n },\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(_target, prop);\n },\n defineProperty(target, prop, attributes) {\n return Reflect.defineProperty(_target, prop, attributes);\n },\n getPrototypeOf(target) {\n return Reflect.getPrototypeOf(_target);\n },\n setPrototypeOf(target, proto) {\n return Reflect.setPrototypeOf(_target, proto);\n },\n isExtensible(target) {\n return Reflect.isExtensible(_target);\n },\n preventExtensions(target) {\n return Reflect.preventExtensions(_target);\n },\n apply(target, thisArg, args) {\n // @ts-ignore\n return Reflect.apply(_target, thisArg, args);\n },\n construct(target, args, newTarget) {\n // @ts-ignore\n return Reflect.construct(_target, args, newTarget);\n },\n });\n\n return {\n proxy,\n setTarget(newTarget: T) {\n _target = newTarget;\n },\n };\n}\n","import { ApplicationCommandType, REST, Routes } from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport { CommandData } from '../../types';\nimport { Logger } from '../../logger/Logger';\n\nexport interface PreRegisterCommandsEvent {\n preventDefault(): void;\n commands: CommandData[];\n}\n\nexport class CommandRegistrar {\n private api = new REST();\n\n /**\n * Creates an instance of CommandRegistrar.\n * @param commandkit The commandkit instance.\n */\n public constructor(public readonly commandkit: CommandKit) {\n this.api.setToken(\n this.commandkit.client.token ??\n process.env.DISCORD_TOKEN ??\n process.env.TOKEN ??\n '',\n );\n }\n\n /**\n * Gets the commands data.\n */\n public getCommandsData(): CommandData[] {\n const handler = this.commandkit.commandHandler;\n // Use the public method instead of accessing private property\n const commands = handler.getCommandsArray();\n\n return commands.flatMap((cmd) => {\n const json: CommandData =\n 'toJSON' in cmd.data.command\n ? cmd.data.command.toJSON()\n : cmd.data.command;\n\n const collections: CommandData[] = [json];\n\n // Handle context menu commands\n if (\n cmd.data.userContextMenu &&\n json.type !== ApplicationCommandType.User\n ) {\n collections.push({\n ...json,\n type: ApplicationCommandType.User,\n options: undefined,\n description_localizations: undefined,\n // @ts-ignore\n description: undefined,\n });\n }\n\n if (\n cmd.data.messageContextMenu &&\n json.type !== ApplicationCommandType.Message\n ) {\n collections.push({\n ...json,\n type: ApplicationCommandType.Message,\n description_localizations: undefined,\n // @ts-ignore\n description: undefined,\n options: undefined,\n });\n }\n\n return collections;\n });\n }\n\n /**\n * Registers loaded commands.\n */\n public async register() {\n const commands = this.getCommandsData();\n\n let preRegistrationPrevented = false;\n const preRegisterEvent: PreRegisterCommandsEvent = {\n preventDefault() {\n preRegistrationPrevented = true;\n },\n commands,\n };\n\n await this.commandkit.plugins.execute(async (ctx, plugin) => {\n if (preRegistrationPrevented) return;\n return plugin.onBeforeRegisterCommands(ctx, preRegisterEvent);\n });\n\n if (preRegistrationPrevented) return;\n\n // we check this after the plugin event\n // because plugins may be able to register commands\n // before the client is ready\n if (!this.commandkit.client.isReady()) {\n throw new Error('Cannot register commands before the client is ready');\n }\n\n const guildCommands = commands\n .filter((command) => command.guilds?.filter(Boolean).length)\n .map((c) => ({\n ...c,\n guilds: Array.from(new Set(c.guilds?.filter(Boolean))),\n }));\n\n const globalCommands = commands.filter(\n (command) => !command.guilds?.filter(Boolean).length,\n );\n\n await this.updateGlobalCommands(globalCommands);\n await this.updateGuildCommands(guildCommands);\n }\n\n /**\n * Updates the global commands.\n */\n public async updateGlobalCommands(commands: CommandData[]) {\n if (!commands.length) return;\n\n let prevented = false;\n const preRegisterEvent: PreRegisterCommandsEvent = {\n preventDefault() {\n prevented = true;\n },\n commands,\n };\n\n await this.commandkit.plugins.execute(async (ctx, plugin) => {\n if (prevented) return;\n return plugin.onBeforeRegisterGlobalCommands(ctx, preRegisterEvent);\n });\n\n try {\n const data = (await this.api.put(\n Routes.applicationCommands(this.commandkit.client.user!.id),\n {\n body: commands.map((c) => ({\n ...c,\n guilds: undefined,\n })),\n },\n )) as CommandData[];\n\n Logger.info(\n `✨ Refreshed ${data.length} global application (/) commands`,\n );\n } catch (e) {\n Logger.error('Failed to update global application (/) commands', e);\n }\n }\n\n /**\n * Updates the guild commands.\n */\n public async updateGuildCommands(commands: CommandData[]) {\n if (!commands.length) return;\n\n let prevented = false;\n const preRegisterEvent: PreRegisterCommandsEvent = {\n preventDefault() {\n prevented = true;\n },\n commands,\n };\n await this.commandkit.plugins.execute(async (ctx, plugin) => {\n if (prevented) return;\n return plugin.onBeforePrepareGuildCommandsRegistration(\n ctx,\n preRegisterEvent,\n );\n });\n if (prevented) return;\n\n try {\n const guildCommandsMap = new Map<string, CommandData[]>();\n\n commands.forEach((command) => {\n if (!command.guilds?.length) return;\n\n command.guilds.forEach((guild) => {\n if (!guildCommandsMap.has(guild)) {\n guildCommandsMap.set(guild, []);\n }\n\n guildCommandsMap.get(guild)!.push(command);\n });\n });\n\n if (!guildCommandsMap.size) return;\n\n let count = 0;\n\n for (const [guild, guildCommands] of guildCommandsMap) {\n let prevented = false;\n const preRegisterEvent: PreRegisterCommandsEvent = {\n preventDefault() {\n prevented = true;\n },\n commands: guildCommands,\n };\n\n await this.commandkit.plugins.execute(async (ctx, plugin) => {\n if (prevented) return;\n return plugin.onBeforeRegisterGuildCommands(ctx, preRegisterEvent);\n });\n\n if (prevented) continue;\n\n const data = (await this.api.put(\n Routes.applicationGuildCommands(\n this.commandkit.client.user!.id,\n guild,\n ),\n {\n body: guildCommands.map((b) => ({\n ...b,\n guilds: undefined,\n })),\n },\n )) as CommandData[];\n\n count += data.length;\n }\n\n Logger.info(`✨ Refreshed ${count} guild application (/) commands`);\n } catch (e) {\n Logger.error('Failed to update guild application (/) commands', e);\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport { CommandKit } from '../CommandKit';\nimport { GenericFunction, getContext } from './async-context';\nimport type { Context } from '../app';\n\nexport interface CommandKitEnvironmentInternalData {\n executionError: Error | null;\n type: CommandKitEnvironmentType | null;\n variables: Map<string, any>;\n deferredFunctions: Map<string, GenericFunction<[CommandKitEnvironment]>>;\n marker: string;\n markStart: number;\n markEnd: number;\n context: Context | null;\n}\n\nexport class CommandKitEnvironment {\n #data: CommandKitEnvironmentInternalData = {\n executionError: null,\n type: null,\n variables: new Map(),\n deferredFunctions: new Map(),\n marker: '',\n markStart: 0,\n markEnd: 0,\n context: null,\n };\n\n /**\n * Creates the commandkit execution environment.\n * @param commandkit - The commandkit instance.\n */\n public constructor(public readonly commandkit: CommandKit) {}\n\n /**\n * Set the context.\n * @param context - The context to set.\n */\n public setContext(context: Context): void {\n this.#data.context = context;\n }\n\n /**\n * Get the context. `null` if not set.\n * @internal\n */\n public get context(): Context | null {\n return this.#data.context;\n }\n\n /**\n * Get the execution error.\n * @internal\n */\n public getExecutionError(): Error | null {\n return this.#data.executionError;\n }\n\n /**\n * Set the execution error.\n * @param error - The error to set.\n * @internal\n */\n public setExecutionError(error: Error): void {\n if (this.#data.executionError) {\n throw new Error('Execution error already set.');\n }\n\n this.#data.executionError = error;\n }\n\n /**\n * Get the environment type.\n */\n public getType(): CommandKitEnvironmentType {\n const type = this.#data.type;\n\n if (!type) {\n throw new Error('Environment type not set.');\n }\n\n return type;\n }\n\n /**\n * Set the environment type.\n * @param type - The environment type to set.\n * @internal\n */\n public setType(type: CommandKitEnvironmentType): void {\n this.#data.type = type;\n }\n\n /**\n * The variables store for this environment.\n */\n public get variables(): Map<string, any> {\n return this.#data.variables;\n }\n\n /**\n * Register a deferred function.\n * @param fn - The deferred function to register.\n * @returns The deferred function id.\n * @internal\n */\n public registerDeferredFunction(\n fn: GenericFunction<[CommandKitEnvironment]>,\n ): string {\n const id = randomUUID();\n this.#data.deferredFunctions.set(id, fn);\n return id;\n }\n\n /**\n * Clear a deferred function by id.\n * @param id - The deferred function id to clear.\n * @internal\n */\n public clearDeferredFunction(id: string): void {\n this.#data.deferredFunctions.delete(id);\n }\n\n /**\n * Run all deferred functions sequentially.\n * @internal\n */\n public async runDeferredFunctions(): Promise<void> {\n for (const [id, fn] of this.#data.deferredFunctions) {\n try {\n await fn(this);\n } catch (e) {\n this.commandkit.emit('unhandledDeferredFunctionRejection', e);\n } finally {\n this.clearDeferredFunction(id);\n }\n }\n }\n\n /**\n * Clear all deferred functions.\n * @internal\n */\n public clearAllDeferredFunctions(): void {\n this.#data.deferredFunctions.clear();\n }\n\n /**\n * Mark the start of a command execution.\n * @param marker - The marker to set.\n * @internal\n */\n public markStart(marker: string): void {\n this.#data.marker = marker;\n this.#data.markStart = performance.now();\n }\n\n /**\n * Mark the end of a command execution.\n * @internal\n */\n public markEnd(): void {\n if (!this.#data.markEnd) {\n this.#data.markEnd = performance.now();\n }\n }\n\n /**\n * Get the marker.\n * @internal\n */\n public getMarker(): string {\n return this.#data.marker;\n }\n\n /**\n * Get the execution time in milliseconds.\n * @internal\n */\n public getExecutionTime(): number {\n return Math.abs(this.#data.markEnd - this.#data.markStart);\n }\n}\n\nexport enum CommandKitEnvironmentType {\n CommandHandler = 'COMMAND_HANDLER',\n}\n\n/**\n * Runs the given function after the current command has finished executing.\n * @param fn The function to run after the current command.\n * @returns The deferred function id. This can be used to cancel the deferred function.\n */\nexport function after(fn: GenericFunction<[CommandKitEnvironment]>): string {\n const env = getContext();\n\n if (!env) {\n throw new Error('after must be called inside commandkit handler.');\n }\n\n return env.registerDeferredFunction(fn);\n}\n\n/**\n * Cancels a deferred function registered with `after`.\n * @param id The deferred function id to cancel.\n */\nexport function cancelAfter(id: string): void {\n const env = getContext();\n\n if (!env) {\n throw new Error('cancelAfter must be called inside commandkit handler.');\n }\n\n env.clearDeferredFunction(id);\n}\n","import {\n AutocompleteInteraction,\n ChatInputCommandInteraction,\n MessageContextMenuCommandInteraction,\n Message,\n Locale,\n Interaction,\n UserContextMenuCommandInteraction,\n Client,\n Awaitable,\n Guild,\n TextBasedChannel,\n} from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport {\n MessageCommandOptions,\n MessageCommandParser,\n} from './MessageCommandParser';\nimport { CommandKitEnvironment } from '../../context/environment';\nimport { GenericFunction, getContext } from '../../context/async-context';\nimport { exitMiddleware, redirect } from '../middleware/signals';\nimport {\n LoadedCommand,\n ResolvableCommand,\n RunCommand,\n} from '../handlers/AppCommandHandler';\n\nexport const CommandExecutionMode = {\n ChatInputCommand: 'chatInput',\n MessageContextMenu: 'messageContextMenu',\n UserContextMenu: 'userContextMenu',\n Autocomplete: 'autocomplete',\n Message: 'message',\n} as const;\n\nexport type CommandExecutionMode =\n (typeof CommandExecutionMode)[keyof typeof CommandExecutionMode];\n\nexport interface ContextParameters<\n T extends CommandExecutionMode,\n Args = Record<string, any>,\n> {\n command: LoadedCommand;\n environment?: CommandKitEnvironment;\n executionMode: T;\n interaction: T extends 'chatInput'\n ? ChatInputCommandInteraction\n : T extends 'messageContextMenu'\n ? MessageContextMenuCommandInteraction\n : T extends 'userContextMenu'\n ? UserContextMenuCommandInteraction\n : T extends 'autocomplete'\n ? AutocompleteInteraction\n : never;\n message: T extends 'message' ? Message : never;\n forwarded?: boolean;\n messageCommandParser?: T extends 'message' ? MessageCommandParser : never;\n store?: Map<string, any>;\n customArgs?: Args;\n}\n\nexport type MessageCommandContext = Context<'message'>;\nexport type InteractionCommandContext = Context<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'\n>;\nexport type MessageCommandMiddlewareContext = MiddlewareContext<'message'>;\nexport type InteractionCommandMiddlewareContext = MiddlewareContext<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'\n>;\nexport type ChatInputCommandContext = Context<'chatInput'>;\nexport type SlashCommandMiddlewareContext = MiddlewareContext<'chatInput'>;\nexport type AutocompleteCommandContext = Context<'autocomplete'>;\nexport type AutocompleteCommandMiddlewareContext =\n MiddlewareContext<'autocomplete'>;\nexport type MessageContextMenuCommandContext = Context<'messageContextMenu'>;\nexport type MessageContextMenuCommandMiddlewareContext =\n MiddlewareContext<'messageContextMenu'>;\nexport type UserContextMenuCommandContext = Context<'userContextMenu'>;\nexport type UserContextMenuCommandMiddlewareContext =\n MiddlewareContext<'userContextMenu'>;\n\nexport type CommandContextOptions<T extends CommandExecutionMode> =\n T extends 'message'\n ? MessageCommandOptions\n : T extends 'chatInput'\n ? ChatInputCommandInteraction['options']\n : T extends 'autocomplete'\n ? AutocompleteInteraction['options']\n : T extends 'messageContextMenu'\n ? MessageContextMenuCommandInteraction['options']\n : T extends 'userContextMenu'\n ? UserContextMenuCommandInteraction['options']\n : never;\n\nexport type AnyCommandExecute<ContextType extends Context = Context> = (\n ctx: ContextType,\n) => Awaitable<unknown>;\n\nexport type ChatInputCommand = AnyCommandExecute<ChatInputCommandContext>;\nexport type AutocompleteCommand = AnyCommandExecute<AutocompleteCommandContext>;\nexport type MessageContextMenuCommand =\n AnyCommandExecute<MessageContextMenuCommandContext>;\nexport type UserContextMenuCommand =\n AnyCommandExecute<UserContextMenuCommandContext>;\nexport type MessageCommand = AnyCommandExecute<MessageCommandContext>;\n\nexport interface MiddlewareContextArgs {\n setCommandRunner?: GenericFunction<[RunCommand]>;\n}\n\nexport class Context<\n ExecutionMode extends CommandExecutionMode = CommandExecutionMode,\n Args extends Record<string, any> = Record<string, any>,\n> {\n /**\n * The interaction that triggered the command.\n */\n public readonly interaction: ContextParameters<ExecutionMode>['interaction'];\n\n /**\n * The message that triggered the command.\n */\n public readonly message: ContextParameters<ExecutionMode>['message'];\n\n /**\n * The guild where the command was triggered.\n */\n public readonly guild!: Guild | null;\n\n /**\n * The guild ID where the command was triggered.\n */\n public readonly guildId!: string | null;\n\n /**\n * The channel where the command was triggered.\n */\n public readonly channel!: TextBasedChannel | null;\n\n /**\n * The channel id where the command was triggered.\n */\n public readonly channelId!: string | null;\n\n /**\n * The client instance.\n */\n public readonly client: Client;\n\n /**\n * The command that this context belongs to.\n */\n public readonly command: LoadedCommand;\n\n #store: Map<string, any>;\n\n private _locale: Locale | null = null;\n\n /**\n * Creates a new command context.\n * @param commandkit The command kit instance.\n * @param config The context parameters.\n */\n public constructor(\n public readonly commandkit: CommandKit,\n protected readonly config: ContextParameters<ExecutionMode, Args>,\n ) {\n // these are assigned to readonly properties to make them accessible via object destructuring\n this.interaction = config.interaction;\n this.message = config.message;\n this.client = commandkit.client;\n this.#store = config.store ?? new Map();\n this.command = config.command;\n\n if (config.interaction) {\n this.guild = config.interaction.guild;\n this.guildId = config.interaction.guildId;\n this.channel = config.interaction.channel;\n this.channelId = config.interaction.channelId;\n }\n\n if (config.message) {\n this.guild = config.message.guild;\n this.guildId = config.message.guildId;\n this.channel = config.message.channel;\n this.channelId = config.message.channelId;\n }\n\n if (this.config.environment) {\n this.config.environment.setContext(this);\n }\n }\n\n /**\n * The shared key-value store for this context. This can be used to store data that needs to be shared between middlewares or commands.\n * This store is shared across all contexts in the same command execution, including the cloned contexts and middleware contexts.\n */\n public get store() {\n return this.#store;\n }\n\n public get commandName(): string {\n if (this.isInteraction()) {\n return this.interaction.commandName;\n } else {\n return this.config.messageCommandParser!.getCommand();\n }\n }\n\n public get options(): CommandContextOptions<ExecutionMode> {\n if (this.isMessage()) {\n const parser = this.config.messageCommandParser!;\n // @ts-expect-error\n return parser.options;\n } else {\n const interaction = (<InteractionCommandContext>this).interaction;\n // @ts-expect-error\n return interaction.options;\n }\n }\n\n /**\n * Whether this context was forwarded from another context. This happens when a command forwards its context to another command.\n */\n public get forwarded(): boolean {\n return this.config.forwarded ?? false;\n }\n\n /**\n * Forwards the context to another command. The target handler will be the same as current handler.\n * @param command The command to forward to.\n */\n public async forwardCommand<C extends ResolvableCommand>(\n command: C,\n ): Promise<never> {\n const target = await this.commandkit.commandHandler.prepareCommandRun(\n (this.isInteraction() ? this.interaction : this.message) as Interaction,\n command,\n );\n\n if (!target) {\n throw new Error(`Command ${command} not found`);\n }\n\n const env = this.config.environment ?? getContext();\n\n if (!env) {\n throw new Error('No commandkit environment found.');\n }\n\n const handlers = {\n chatInput: target.command.data.chatInput,\n autocomplete: target.command.data.autocomplete,\n message: target.command.data.message,\n messageContextMenu: target.command.data.messageContextMenu,\n userContextMenu: target.command.data.userContextMenu,\n };\n\n const handlerKind = env.variables.get(\n 'execHandlerKind',\n ) as keyof typeof handlers;\n\n if (!handlerKind) {\n throw new Error('No execution handler kind found.');\n }\n\n const handler = handlers[handlerKind];\n\n if (!handler) {\n throw new Error(`No handler found for ${handlerKind}`);\n }\n\n env.variables.set('forwardedBy', this.commandName);\n env.variables.set('forwardedTo', command);\n\n await handler(this.clone({ forwarded: true }));\n\n redirect();\n }\n\n /**\n * The execution mode of the command.\n */\n public get executionMode(): ExecutionMode {\n return this.config.executionMode;\n }\n\n // /**\n // * The guild where this command was triggered.\n // */\n // public get guild() {\n // if (this.isInteraction()) {\n // return this.interaction.guild;\n // } else {\n // return (<MessageCommandContext>this).message.guild;\n // }\n // }\n\n // /**\n // * The guild ID where this command was triggered.\n // */\n // public get guildId() {\n // if (this.isInteraction()) {\n // return this.interaction.guildId;\n // } else {\n // return (<MessageCommandContext>this).message.guildId;\n // }\n // }\n\n /**\n * Whether the command was triggered by an interaction.\n */\n public isInteraction(): this is InteractionCommandContext {\n return (\n this.executionMode === CommandExecutionMode.ChatInputCommand ||\n this.executionMode === CommandExecutionMode.Autocomplete ||\n this.executionMode === CommandExecutionMode.MessageContextMenu ||\n this.executionMode === CommandExecutionMode.UserContextMenu\n );\n }\n\n /**\n * Whether the command was triggered by a slash command interaction.\n */\n public isChatInputCommand(): this is ChatInputCommandContext {\n return this.executionMode === CommandExecutionMode.ChatInputCommand;\n }\n\n /**\n * Whether the command was triggered by an autocomplete interaction.\n */\n public isAutocomplete(): this is AutocompleteCommandContext {\n return this.executionMode === CommandExecutionMode.Autocomplete;\n }\n\n /**\n * Whether the command was triggered by a message context menu interaction.\n */\n public isMessageContextMenu(): this is MessageContextMenuCommandContext {\n return this.executionMode === CommandExecutionMode.MessageContextMenu;\n }\n\n /**\n * Whether the command was triggered by a user context menu interaction.\n */\n public isUserContextMenu(): this is UserContextMenuCommandContext {\n return this.executionMode === CommandExecutionMode.UserContextMenu;\n }\n\n /**\n * Whether the command was triggered by a message.\n */\n public isMessage(): this is Context<'message'> {\n return this.executionMode === CommandExecutionMode.Message;\n }\n\n /**\n * Returns the command identifier.\n */\n public getCommandIdentifier(): string {\n if (this.isInteraction()) {\n return this.interaction.commandName;\n } else {\n return this.message.content.split(' ')[0].slice(1);\n }\n }\n\n /**\n * Returns the locale of the guild where this command was triggered.\n */\n public getGuildLocale(): Locale | null {\n if (this.isInteraction()) {\n return this.interaction.guildLocale;\n } else {\n return this.message.guild?.preferredLocale ?? null;\n }\n }\n\n /**\n * Returns the locale of the user who triggered this command.\n */\n public getUserLocale(): Locale | null {\n if (this.isInteraction()) {\n return this.interaction.locale;\n } else {\n return null;\n }\n }\n\n /**\n * Returns the locale for this command.\n * @param preferUser Whether to prefer the user's locale over the guild's locale.\n * @returns The locale for this command. If no locale is found, the default locale is returned.\n */\n public getLocale(preferUser = false): Locale {\n if (this._locale) return this._locale;\n\n const locale = preferUser ? this.getUserLocale() : this.getGuildLocale();\n\n if (!locale) {\n return this.commandkit.config.defaultLocale;\n }\n\n return locale;\n }\n\n /**\n * Sets the locale for this command.\n * @param locale The locale to set.\n */\n public setLocale(locale: Locale | null): void {\n this._locale = locale;\n }\n\n /**\n * Creates a clone of this context\n */\n public clone(\n config?: Partial<ContextParameters<ExecutionMode>>,\n ): Context<ExecutionMode> {\n if (!config) return new Context(this.commandkit, this.config);\n\n const ctx = new Context(this.commandkit, {\n ...this.config,\n ...config,\n store: this.#store,\n });\n\n return ctx;\n }\n\n public isMiddleware(): this is MiddlewareContext<ExecutionMode> {\n return this instanceof MiddlewareContext;\n }\n\n public args(): string[] {\n if (this.isMessage()) {\n return this.config.messageCommandParser!.getArgs();\n }\n\n return [];\n }\n\n /**\n * Stops upcoming middleware or current command execution.\n * If this is called inside pre-stage middleware, the next run will be the actual command, skipping all other pre-stage middlewares.\n * If this is called inside a command itself, it will skip all post-stage middlewares.\n * If this is called inside post-stage middleware, it will skip all other post-stage middlewares.\n */\n public exit(): never {\n exitMiddleware();\n }\n}\n\nexport class MiddlewareContext<\n T extends CommandExecutionMode = CommandExecutionMode,\n> extends Context<T, MiddlewareContextArgs> {\n #cancel = false;\n\n /**\n * Whether the command execution was cancelled.\n */\n public get cancelled(): boolean {\n return this.#cancel;\n }\n\n /**\n * Cancels the command execution.\n */\n public cancel(): void {\n this.#cancel = true;\n }\n\n /**\n * Sets command runner function to wrap the command execution.\n * @param fn The function to set.\n * @example ctx.setCommandRunner(async (execute) => {\n * // do something before command execution\n * await execute();\n * // do something after command execution\n * })\n */\n public setCommandRunner(fn: RunCommand): void {\n this.config.customArgs?.setCommandRunner?.(fn);\n }\n}\n","import { ChatInputCommandInteraction, Interaction, Message } from 'discord.js';\nimport {\n CommandKitEnvironment,\n CommandKitEnvironmentType,\n} from '../../context/environment';\nimport { Logger } from '../../logger/Logger';\nimport {\n AppCommandHandler,\n PreparedAppCommandExecution,\n RunCommand,\n} from '../handlers/AppCommandHandler';\nimport { CommandExecutionMode, MiddlewareContext } from './Context';\nimport {\n makeContextAwareFunction,\n provideContext,\n useEnvironment,\n} from '../../context/async-context';\nimport { CommandKitErrorCodes, isErrorType } from '../../utils/error-codes';\n\nexport class AppCommandRunner {\n public constructor(private handler: AppCommandHandler) {}\n\n public async runCommand(\n prepared: PreparedAppCommandExecution,\n source: Interaction | Message,\n ) {\n const { commandkit } = this.handler;\n\n const executionMode = this.getExecutionMode(source);\n\n let runCommand: RunCommand | null = null;\n\n const env = new CommandKitEnvironment(commandkit);\n env.setType(CommandKitEnvironmentType.CommandHandler);\n env.variables.set('commandHandlerType', 'app');\n env.variables.set('currentCommandName', prepared.command.command.name);\n env.variables.set('execHandlerKind', executionMode);\n\n const ctx = new MiddlewareContext(commandkit, {\n command: prepared.command,\n environment: env,\n executionMode,\n interaction: !(source instanceof Message)\n ? (source as ChatInputCommandInteraction)\n : (null as never),\n message: source instanceof Message ? source : (null as never),\n forwarded: false,\n customArgs: {\n setCommandRunner: (fn: RunCommand) => {\n runCommand = fn;\n },\n },\n messageCommandParser: prepared.messageCommandParser,\n });\n\n let middlewaresCanceled = false;\n\n // Run middleware before command execution\n if (prepared.middlewares.length) {\n await provideContext(env, async () => {\n for (const middleware of prepared.middlewares) {\n if (!middleware.data.beforeExecute) continue;\n try {\n await middleware.data.beforeExecute(ctx);\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n middlewaresCanceled = true;\n return;\n }\n\n if (\n isErrorType(e, [\n CommandKitErrorCodes.ForwardedCommand,\n CommandKitErrorCodes.InvalidCommandPrefix,\n ])\n ) {\n continue;\n }\n\n throw e;\n }\n }\n });\n }\n\n if (!ctx.cancelled) {\n // Determine which function to run based on whether we're executing a command or subcommand\n const targetData = prepared.command.data;\n const fn = targetData[executionMode];\n\n if (!fn) {\n Logger.warn(\n `Command ${prepared.command.command.name} has no handler for ${executionMode}`,\n );\n }\n\n if (fn) {\n try {\n const _executeCommand = makeContextAwareFunction(\n env,\n async () => {\n env.registerDeferredFunction((env) => {\n env.markEnd();\n const error = env.getExecutionError();\n const marker = env.getMarker();\n const time = `${env.getExecutionTime().toFixed(2)}ms`;\n\n if (error) {\n Logger.error(\n `[${marker} - ${time}] Error executing command: ${error.stack || error}`,\n );\n\n return;\n }\n\n Logger.info(\n `[${marker} - ${time}] Command executed successfully`,\n );\n });\n\n return fn(ctx.clone());\n },\n this.#finalizer.bind(this),\n );\n\n const executeCommand =\n runCommand != null\n ? (runCommand as RunCommand)(_executeCommand)\n : _executeCommand;\n\n env.markStart(prepared.command.data.command.name);\n\n const res = await commandkit.plugins.execute(async (ctx, plugin) => {\n return plugin.executeCommand(\n ctx,\n env,\n source,\n prepared,\n executeCommand,\n );\n });\n\n if (!res) {\n await executeCommand();\n }\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n middlewaresCanceled = true;\n }\n\n if (\n !isErrorType(e, [\n CommandKitErrorCodes.ForwardedCommand,\n CommandKitErrorCodes.ExitMiddleware,\n ])\n ) {\n Logger.error(e);\n }\n }\n }\n }\n\n // Run middleware after command execution\n if (!middlewaresCanceled && prepared.middlewares.length) {\n await provideContext(env, async () => {\n for (const middleware of prepared.middlewares) {\n if (!middleware.data.afterExecute) continue;\n try {\n await middleware.data.afterExecute(ctx);\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.ExitMiddleware)) {\n return;\n }\n\n throw e;\n }\n }\n });\n }\n }\n\n async #finalizer() {\n const env = useEnvironment();\n\n await env.runDeferredFunctions();\n\n env.clearAllDeferredFunctions();\n\n // plugins may have their own deferred function, useful for cleanup or post-command analytics\n await this.handler.commandkit.plugins.execute(async (ctx, plugin) => {\n await plugin.onAfterCommand(ctx, env);\n });\n }\n\n public getExecutionMode(source: Interaction | Message): CommandExecutionMode {\n if (source instanceof Message) return CommandExecutionMode.Message;\n if (source.isChatInputCommand())\n return CommandExecutionMode.ChatInputCommand;\n if (source.isAutocomplete()) {\n return CommandExecutionMode.Autocomplete;\n }\n if (source.isMessageContextMenuCommand()) {\n return CommandExecutionMode.MessageContextMenu;\n }\n if (source.isUserContextMenuCommand()) {\n return CommandExecutionMode.UserContextMenu;\n }\n\n return null as never;\n }\n}\n","import type { CommandKit } from '../../CommandKit';\nimport {\n AutocompleteInteraction,\n Awaitable,\n Collection,\n CommandInteraction,\n ContextMenuCommandBuilder,\n Events,\n Interaction,\n Message,\n SlashCommandBuilder,\n} from 'discord.js';\nimport { Context } from '../commands/Context';\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { MessageCommandParser } from '../commands/MessageCommandParser';\nimport { CommandKitErrorCodes, isErrorType } from '../../utils/error-codes';\nimport { CommandRegistrar } from '../register/CommandRegistrar';\nimport { AsyncFunction, GenericFunction } from '../../context/async-context';\nimport { Logger } from '../../logger/Logger';\nimport { Command, Middleware } from '../router';\nimport { AppCommandRunner } from '../commands/AppCommandRunner';\nimport { COMMANDKIT_IS_DEV } from '../../utils/constants';\nimport { rewriteCommandDeclaration } from '../../utils/types-package';\nimport colors from '../../utils/colors';\n\nexport type RunCommand = <T extends AsyncFunction>(fn: T) => T;\n\ninterface AppCommand {\n command: SlashCommandBuilder | Record<string, any>;\n chatInput?: (ctx: Context) => Awaitable<unknown>;\n autocomplete?: (ctx: Context) => Awaitable<unknown>;\n message?: (ctx: Context) => Awaitable<unknown>;\n messageContextMenu?: (ctx: Context) => Awaitable<unknown>;\n userContextMenu?: (ctx: Context) => Awaitable<unknown>;\n}\n\ninterface AppCommandMiddleware {\n beforeExecute: (ctx: Context) => Awaitable<unknown>;\n afterExecute: (ctx: Context) => Awaitable<unknown>;\n}\n\nexport interface LoadedCommand {\n command: Command;\n data: AppCommand;\n guilds?: string[];\n}\n\nexport type CommandTypeData = string;\n\nexport type ResolvableCommand = CommandTypeData | (string & {});\n\ninterface LoadedMiddleware {\n middleware: Middleware;\n data: AppCommandMiddleware;\n}\n\nexport interface PreparedAppCommandExecution {\n command: LoadedCommand;\n middlewares: LoadedMiddleware[];\n messageCommandParser?: MessageCommandParser;\n}\n\nexport type CommandBuilderLike =\n | SlashCommandBuilder\n | ContextMenuCommandBuilder\n | Record<string, any>;\n\nconst commandDataSchema = {\n command: (c: unknown) =>\n c instanceof SlashCommandBuilder ||\n c instanceof ContextMenuCommandBuilder ||\n (c && typeof c === 'object'),\n chatInput: (c: unknown) => typeof c === 'function',\n autocomplete: (c: unknown) => typeof c === 'function',\n message: (c: unknown) => typeof c === 'function',\n messageContextMenu: (c: unknown) => typeof c === 'function',\n userContextMenu: (c: unknown) => typeof c === 'function',\n};\n\nconst middlewareDataSchema = {\n beforeExecute: (c: unknown) => typeof c === 'function',\n afterExecute: (c: unknown) => typeof c === 'function',\n};\n\nexport class AppCommandHandler {\n private loadedCommands = new Collection<string, LoadedCommand>();\n private loadedMiddlewares = new Collection<string, LoadedMiddleware>();\n\n // Name-to-ID mapping for easier lookup\n private commandNameToId = new Map<string, string>();\n private subcommandPathToId = new Map<string, string>();\n\n public readonly registrar: CommandRegistrar;\n private onInteraction: GenericFunction<[Interaction]> | null = null;\n private onMessageCreate: GenericFunction<[Message]> | null = null;\n public readonly commandRunner = new AppCommandRunner(this);\n\n public readonly externalCommandData = new Collection<string, Command>();\n public readonly externalMiddlewareData = new Collection<string, Middleware>();\n\n public constructor(public readonly commandkit: CommandKit) {\n this.registrar = new CommandRegistrar(this.commandkit);\n }\n\n public printBanner() {\n const uncategorized = crypto.randomUUID();\n\n // Group commands by category\n const categorizedCommands = this.getCommandsArray().reduce(\n (acc, cmd) => {\n const category = cmd.command.category || uncategorized;\n acc[category] = acc[category] || [];\n acc[category].push(cmd);\n return acc;\n },\n {} as Record<string, LoadedCommand[]>,\n );\n\n console.log(\n colors.green(\n `Loaded ${colors.magenta(this.loadedCommands.size.toString())} commands:`,\n ),\n );\n\n const categories = Object.keys(categorizedCommands).sort();\n\n // Build category tree for all nesting depths\n const categoryTree: Record<string, string[]> = {};\n\n // Find the best parent for nested categories\n categories.forEach((category) => {\n if (category === uncategorized) return;\n\n if (category.includes(':')) {\n const parts = category.split(':');\n let bestParent = null;\n\n // Try to find the deepest existing parent\n for (let i = parts.length - 1; i > 0; i--) {\n const potentialParent = parts.slice(0, i).join(':');\n if (categories.includes(potentialParent)) {\n bestParent = potentialParent;\n break;\n }\n }\n\n // If we found a parent, add this category as its child\n if (bestParent) {\n categoryTree[bestParent] = categoryTree[bestParent] || [];\n categoryTree[bestParent].push(category);\n }\n }\n });\n\n // Track categories we've processed to avoid duplicates\n const processedCategories = new Set<string>();\n\n // Recursive function to print a category and its children\n const printCategory = (\n category: string,\n indent: string = '',\n isLast: boolean = false,\n parentPrefix: string = '',\n ) => {\n // Skip if already processed\n if (processedCategories.has(category)) return;\n processedCategories.add(category);\n\n const commands = categorizedCommands[category];\n const hasChildren =\n categoryTree[category] && categoryTree[category].length > 0;\n const thisPrefix = isLast ? '└─' : '├─';\n const childIndent = parentPrefix + (isLast ? ' ' : '│ ');\n\n // Print category name if not uncategorized\n if (category !== uncategorized) {\n // For nested categories, only print the last part after the colon\n const displayName = category.includes(':')\n ? category.split(':').pop()\n : category;\n\n console.log(\n colors.cyan(`${indent}${thisPrefix} ${colors.bold(displayName!)}`),\n );\n }\n\n // Print commands in this category\n commands.forEach((cmd, cmdIndex) => {\n const cmdIsLast = cmdIndex === commands.length - 1 && !hasChildren;\n const cmdPrefix = cmdIsLast ? '└─' : '├─';\n const cmdIndent = category !== uncategorized ? childIndent : indent;\n\n const name = cmd.data.command.name;\n const hasMw = cmd.command.middlewares.length > 0;\n const middlewareIcon = hasMw ? colors.magenta(' (λ)') : '';\n\n console.log(\n `${colors.green(`${cmdIndent}${cmdPrefix}`)} ${colors.yellow(name)}${middlewareIcon}`,\n );\n });\n\n // Process nested categories\n if (hasChildren) {\n const children = categoryTree[category].sort();\n children.forEach((childCategory, idx) => {\n const childIsLast = idx === children.length - 1;\n printCategory(childCategory, childIndent, childIsLast, childIndent);\n });\n }\n };\n\n // Find and print top-level categories\n const topLevelCategories = categories\n .filter((category) => {\n if (category === uncategorized) return true;\n\n if (category.includes(':')) {\n const parts = category.split(':');\n // Check if any parent path exists as a category\n for (let i = 1; i < parts.length; i++) {\n const parentPath = parts.slice(0, i).join(':');\n if (categories.includes(parentPath)) {\n return false; // Not top-level, it has a parent\n }\n }\n return true; // No parent found, so it's top-level\n }\n\n return true; // Not nested, so it's top-level\n })\n .sort();\n\n // Print each top-level category\n topLevelCategories.forEach((category, index) => {\n const isLast = index === topLevelCategories.length - 1;\n printCategory(category, '', isLast);\n });\n }\n\n public getCommandsArray() {\n return Array.from(this.loadedCommands.values());\n }\n\n public registerCommandHandler() {\n this.onInteraction ??= async (interaction: Interaction) => {\n const success = await this.commandkit.plugins.execute(\n async (ctx, plugin) => {\n return plugin.onBeforeInteraction(ctx, interaction);\n },\n );\n\n // plugin will handle the interaction\n if (success) return;\n\n const isCommandLike =\n interaction.isCommand() ||\n interaction.isAutocomplete() ||\n interaction.isUserContextMenuCommand() ||\n interaction.isMessageContextMenuCommand();\n\n if (!isCommandLike) return;\n\n const prepared = await this.prepareCommandRun(interaction);\n\n if (!prepared) return;\n\n return this.commandRunner.runCommand(prepared, interaction);\n };\n\n this.onMessageCreate ??= async (message: Message) => {\n const success = await this.commandkit.plugins.execute(\n async (ctx, plugin) => {\n return plugin.onBeforeMessageCommand(ctx, message);\n },\n );\n\n // plugin will handle the message\n if (success) return;\n if (message.author.bot) return;\n\n const prepared = await this.prepareCommandRun(message);\n\n if (!prepared) return;\n\n return this.commandRunner.runCommand(prepared, message);\n };\n\n this.commandkit.client.on(Events.InteractionCreate, this.onInteraction);\n this.commandkit.client.on(Events.MessageCreate, this.onMessageCreate);\n }\n\n public async prepareCommandRun(\n source: Interaction | Message,\n cmdName?: string,\n ): Promise<PreparedAppCommandExecution | null> {\n let parser: MessageCommandParser | undefined;\n\n // Extract command name (and possibly subcommand) from the source\n if (!cmdName) {\n if (source instanceof Message) {\n if (source.author.bot) return null;\n\n const prefix =\n await this.commandkit.config.getMessageCommandPrefix(source);\n\n parser = new MessageCommandParser(\n source,\n Array.isArray(prefix) ? prefix : [prefix],\n (command: string) => {\n // Find the command by name\n const commandId = this.commandNameToId.get(command);\n if (!commandId) return null;\n\n const loadedCommand = this.loadedCommands.get(commandId);\n if (!loadedCommand) return null;\n\n if (\n source.guildId &&\n loadedCommand.guilds?.length &&\n !loadedCommand.guilds.includes(source.guildId!)\n ) {\n return null;\n }\n\n const json =\n 'toJSON' in loadedCommand.data.command\n ? loadedCommand.data.command.toJSON()\n : loadedCommand.data.command;\n\n return (\n json.options?.reduce(\n (acc: Record<string, unknown>, opt: Record<string, any>) => {\n acc[opt.name] = opt.type;\n return acc;\n },\n {} as Record<string, unknown>,\n ) ?? {}\n );\n },\n );\n\n try {\n const fullCommand = parser.getFullCommand();\n const parts = fullCommand.split(' ');\n cmdName = parts[0];\n } catch (e) {\n if (isErrorType(e, CommandKitErrorCodes.InvalidCommandPrefix)) {\n return null;\n }\n Logger.error(e);\n return null;\n }\n } else {\n const isAnyCommand =\n source.isChatInputCommand() ||\n source.isAutocomplete() ||\n source.isContextMenuCommand();\n\n if (!isAnyCommand) return null;\n\n cmdName = source.commandName;\n }\n }\n\n // Find the command by name\n const commandId = this.commandNameToId.get(cmdName);\n if (!commandId) return null;\n\n const loadedCommand = this.loadedCommands.get(commandId);\n if (!loadedCommand) return null;\n\n // If this is a guild specific command, check if we're in the right guild\n if (\n (source instanceof CommandInteraction ||\n source instanceof AutocompleteInteraction) &&\n source.guildId &&\n loadedCommand.guilds?.length &&\n !loadedCommand.guilds.includes(source.guildId)\n ) {\n return null;\n }\n\n // Collect all applicable middleware\n const middlewares: LoadedMiddleware[] = [];\n\n // Add command-level middleware\n for (const middlewareId of loadedCommand.command.middlewares) {\n const middleware = this.loadedMiddlewares.get(middlewareId);\n if (middleware) {\n middlewares.push(middleware);\n }\n }\n\n // No middleware for subcommands since they inherit from parent command\n return {\n command: loadedCommand,\n middlewares,\n messageCommandParser: parser,\n };\n }\n\n public async reloadCommands() {\n this.loadedCommands.clear();\n this.loadedMiddlewares.clear();\n this.commandNameToId.clear();\n this.subcommandPathToId.clear();\n this.externalCommandData.clear();\n this.externalMiddlewareData.clear();\n\n await this.loadCommands();\n }\n\n public async addExternalMiddleware(data: Middleware[]) {\n for (const middleware of data) {\n if (!middleware.id) continue;\n\n this.externalMiddlewareData.set(middleware.id, middleware);\n }\n }\n\n public async addExternalCommands(data: Command[]) {\n for (const command of data) {\n if (!command.id) continue;\n\n this.externalCommandData.set(command.id, command);\n }\n }\n\n public async registerExternalLoadedMiddleware(data: LoadedMiddleware[]) {\n for (const middleware of data) {\n this.loadedMiddlewares.set(middleware.middleware.id, middleware);\n }\n }\n\n public async registerExternalLoadedCommands(data: LoadedCommand[]) {\n for (const command of data) {\n this.loadedCommands.set(command.command.id, command);\n this.commandNameToId.set(command.command.name, command.command.id);\n }\n }\n\n public async loadCommands() {\n await this.commandkit.plugins.execute((ctx, plugin) => {\n return plugin.onBeforeCommandsLoad(ctx);\n });\n\n const commandsRouter = this.commandkit.commandsRouter;\n\n if (!commandsRouter) {\n throw new Error('Commands router has not yet initialized');\n }\n\n const { commands, middlewares } = commandsRouter.getData();\n\n const combinedCommands = this.externalCommandData.size\n ? commands.concat(this.externalCommandData)\n : commands;\n\n const combinedMiddlewares = this.externalMiddlewareData.size\n ? middlewares.concat(this.externalMiddlewareData)\n : middlewares;\n\n // Load middlewares first\n for (const [id, middleware] of combinedMiddlewares) {\n await this.loadMiddleware(id, middleware);\n }\n\n // Load commands\n for (const [id, command] of combinedCommands) {\n await this.loadCommand(id, command);\n }\n\n // generate types\n if (COMMANDKIT_IS_DEV) {\n await rewriteCommandDeclaration(\n `type CommandTypeData = ${Array.from(\n this.loadedCommands\n .mapValues((v) => JSON.stringify(v.command.name))\n .values(),\n ).join(' | ')}`,\n );\n }\n\n await this.commandkit.plugins.execute((ctx, plugin) => {\n return plugin.onAfterCommandsLoad(ctx);\n });\n }\n\n private async loadMiddleware(id: string, middleware: Middleware) {\n try {\n const data = await import(\n `${toFileURL(middleware.path)}?t=${Date.now()}`\n );\n\n let handlerCount = 0;\n for (const [key, validator] of Object.entries(middlewareDataSchema)) {\n if (data[key] && !(await validator(data[key]))) {\n throw new Error(\n `Invalid export for middleware ${id}: ${key} does not match expected value`,\n );\n }\n\n if (data[key]) handlerCount++;\n }\n\n if (handlerCount === 0) {\n throw new Error(\n `Invalid export for middleware ${id}: at least one handler function must be provided`,\n );\n }\n\n this.loadedMiddlewares.set(id, { middleware, data });\n } catch (error) {\n Logger.error(`Failed to load middleware ${id}`, error);\n }\n }\n\n private async loadCommand(id: string, command: Command) {\n try {\n // Skip if path is null (directory-only command group)\n if (command.path === null) {\n this.loadedCommands.set(id, {\n command,\n data: {\n command: {\n name: command.name,\n description: `${command.name} commands`,\n type: 1,\n },\n },\n });\n return;\n }\n\n const data = await import(`${toFileURL(command.path)}?t=${Date.now()}`);\n\n if (!data.command) {\n throw new Error(\n `Invalid export for command ${command.name}: no command definition found`,\n );\n }\n\n let handlerCount = 0;\n for (const [key, validator] of Object.entries(commandDataSchema)) {\n if (key !== 'command' && data[key]) handlerCount++;\n if (data[key] && !(await validator(data[key]))) {\n throw new Error(\n `Invalid export for command ${command.name}: ${key} does not match expected value`,\n );\n }\n }\n\n if (handlerCount === 0) {\n throw new Error(\n `Invalid export for command ${command.name}: at least one handler function must be provided`,\n );\n }\n\n let lastUpdated = data.command;\n\n await this.commandkit.plugins.execute(async (ctx, plugin) => {\n const res = await plugin.prepareCommand(ctx, lastUpdated);\n\n if (res) {\n lastUpdated = res;\n }\n });\n\n this.loadedCommands.set(id, {\n command,\n guilds: data.guilds,\n data: {\n ...data,\n command: 'toJSON' in lastUpdated ? lastUpdated.toJSON() : lastUpdated,\n },\n });\n\n // Map command name to ID for easier lookup\n this.commandNameToId.set(command.name, id);\n } catch (error) {\n Logger.error(`Failed to load command ${command.name} (${id})`, error);\n }\n }\n}\n","import { Collection } from 'discord.js';\nimport { CommandKit } from '../../CommandKit';\nimport { ListenerFunction } from '../../events/CommandKitEventsChannel';\nimport { Logger } from '../../logger/Logger';\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { StopEventPropagationError } from '../../utils/utilities';\nimport { runInEventWorkerContext } from '../events/EventWorkerContext';\nimport { ParsedEvent } from '../router';\nimport { CommandKitEventDispatch } from '../../plugins';\n\nexport type EventListener = {\n handler: ListenerFunction;\n once: boolean;\n};\n\nexport interface LoadedEvent {\n name: string;\n namespace: string | null;\n event: ParsedEvent;\n listeners: EventListener[];\n mainListener?: EventListener;\n executedOnceListeners?: Set<ListenerFunction>; // Track executed once listeners\n}\n\nexport interface AppEventsHandlerLoadedData {\n name: string;\n namespace: string | null;\n onceListeners: number;\n regularListeners: number;\n metadata: ParsedEvent;\n}\n\nexport class AppEventsHandler {\n private loadedEvents = new Collection<string, LoadedEvent>();\n public constructor(public readonly commandkit: CommandKit) {}\n\n public getEvents(): AppEventsHandlerLoadedData[] {\n if (this.loadedEvents.size === 0) return [];\n\n const events = this.loadedEvents.toJSON();\n\n return events.map(\n (event) =>\n ({\n name: event.name,\n namespace: event.namespace,\n onceListeners: event.listeners.filter((listener) => listener.once)\n .length,\n regularListeners: event.listeners.filter((listener) => !listener.once)\n .length,\n metadata: event.event,\n }) satisfies AppEventsHandlerLoadedData,\n );\n }\n\n public async reloadEvents() {\n this.unregisterAll();\n await this.loadEvents();\n }\n\n public async loadEvents() {\n await this.commandkit.plugins.execute((ctx, plugin) => {\n return plugin.onBeforeEventsLoad(ctx);\n });\n\n const router = this.commandkit.eventsRouter;\n\n const events = await router.scan();\n\n for (const event of Object.values(events)) {\n const listeners: EventListener[] = [];\n\n for (const listener of event.listeners) {\n const handler = await import(toFileURL(listener, true));\n\n if (!handler.default || typeof handler.default !== 'function') {\n Logger.error(\n `Event handler for ${event.event}${event.namespace ? ` of namespace ${event.namespace}` : ''} does not have a default export or is not a function`,\n );\n }\n\n listeners.push({\n handler: handler.default,\n once: !!handler.once,\n });\n }\n\n const len = listeners.length;\n\n if (!len) {\n Logger.warn(\n `Event ${event.event}${event.namespace ? ` of namespace ${event.namespace}` : ''} does not have any listeners`,\n );\n }\n\n const key = `${event.namespace ? `${event.namespace}:` : ''}${event.event}`;\n\n this.loadedEvents.set(key, {\n name: event.event,\n namespace: event.namespace,\n event,\n listeners,\n });\n\n Logger.info(\n `✨ Loaded event ${event.event}${event.namespace ? ` of namespace ${event.namespace}` : ''} with ${len} listener${len === 1 ? '' : 's'}`,\n );\n }\n\n this.registerAllClientEvents();\n\n await this.commandkit.plugins.execute((ctx, plugin) => {\n return plugin.onAfterEventsLoad(ctx);\n });\n }\n\n public unregisterAll() {\n this.unregisterAllClientListeners();\n this.loadedEvents.clear();\n }\n\n public registerAllClientEvents() {\n const client = this.commandkit.client;\n\n for (const [key, data] of this.loadedEvents.entries()) {\n const { name, listeners, namespace } = data;\n\n // Separate listeners into \"once\" and \"on\" groups\n const onceListeners = listeners.filter((listener) => listener.once);\n const onListeners = listeners.filter((listener) => !listener.once);\n\n // Initialize set to track executed once listeners\n const executedOnceListeners = new Set<ListenerFunction>();\n\n // Create main handler for regular \"on\" listeners\n const mainHandler: ListenerFunction = async (...args) => {\n let accepted = false;\n\n const event: CommandKitEventDispatch = {\n name,\n args,\n namespace: namespace ?? null,\n once: false,\n metadata: data.event,\n accept() {\n if (accepted) return;\n accepted = true;\n },\n };\n\n await this.commandkit.plugins\n .execute(async (ctx, plugin) => {\n if (accepted) return;\n return plugin.willEmitEvent?.(ctx, event);\n })\n .catch(Object);\n\n await runInEventWorkerContext(\n {\n event: name,\n namespace: namespace ?? null,\n data: data.event,\n commandkit: this.commandkit,\n arguments: args,\n },\n async () => {\n for (const listener of onListeners) {\n try {\n await listener.handler(...args);\n } catch (e) {\n // Check if this is a stop propagation signal\n if (e instanceof StopEventPropagationError) {\n Logger.debug(\n `Event propagation stopped for ${name}${\n namespace ? ` of namespace ${namespace}` : ''\n }`,\n );\n break; // Stop executing remaining listeners\n }\n\n // Otherwise log the error as usual\n Logger.error(\n `Error handling event ${name}${\n namespace ? ` of namespace ${namespace}` : ''\n }`,\n e,\n );\n }\n }\n },\n );\n };\n\n // Create handler for \"once\" listeners with cleanup logic\n const onceHandler: ListenerFunction = async (...args) => {\n let broken = false;\n let accepted = false;\n\n const event: CommandKitEventDispatch = {\n name,\n args,\n namespace: namespace ?? null,\n once: true,\n metadata: data.event,\n accept() {\n if (accepted) return;\n accepted = true;\n },\n };\n\n await this.commandkit.plugins\n .execute(async (ctx, plugin) => {\n if (accepted) return;\n return plugin.willEmitEvent?.(ctx, event);\n })\n .catch(Object);\n\n for (const listener of onceListeners) {\n if (broken) break; // Stop executing remaining listeners if propagation was stopped\n\n await runInEventWorkerContext(\n {\n event: name,\n namespace: namespace ?? null,\n data: data.event,\n commandkit: this.commandkit,\n arguments: args,\n },\n async () => {\n try {\n // Skip if already executed (shouldn't happen with proper .once registration, but just in case)\n if (executedOnceListeners.has(listener.handler)) return;\n\n await listener.handler(...args);\n executedOnceListeners.add(listener.handler);\n } catch (e) {\n // Check if this is a stop propagation signal\n if (e instanceof StopEventPropagationError) {\n Logger.debug(\n `Event propagation stopped for ${name}${\n namespace ? ` of namespace ${namespace}` : ''\n }`,\n );\n broken = true; // Stop executing remaining listeners\n }\n\n // Otherwise log the error as usual\n Logger.error(\n `Error handling event ${name}${\n namespace ? ` of namespace ${namespace}` : ''\n }`,\n e,\n );\n }\n },\n );\n }\n\n // Cleanup: Remove once listeners that have been executed\n if (\n executedOnceListeners.size === onceListeners.length &&\n onListeners.length === 0\n ) {\n // If all once listeners executed and no regular listeners, remove event entirely\n this.loadedEvents.delete(key);\n Logger.info(\n `🧹 Cleaned up completed once-only event ${name}${\n namespace ? ` of namespace ${namespace}` : ''\n }`,\n );\n }\n };\n\n // Store main handlers in loadedEvents for later unregistration\n this.loadedEvents.set(key, {\n ...data,\n mainListener:\n onListeners.length > 0\n ? { handler: mainHandler, once: false }\n : undefined,\n executedOnceListeners,\n });\n\n // Register handlers with appropriate methods\n if (namespace) {\n if (onListeners.length > 0) {\n this.commandkit.events.on(namespace, name, mainHandler);\n }\n if (onceListeners.length > 0) {\n this.commandkit.events.once(namespace, name, onceHandler);\n }\n } else {\n if (onListeners.length > 0) {\n client.on(name, mainHandler);\n }\n if (onceListeners.length > 0) {\n client.once(name, onceHandler);\n }\n }\n\n Logger.info(\n `🔌 Registered event ${name}${\n namespace ? ` of namespace ${namespace}` : ''\n } (${onListeners.length} regular, ${onceListeners.length} once-only)`,\n );\n }\n }\n\n public unregisterAllClientListeners() {\n const client = this.commandkit.client;\n\n for (const [\n key,\n { name, mainListener, namespace },\n ] of this.loadedEvents.entries()) {\n if (mainListener) {\n if (namespace) {\n this.commandkit.events.off(namespace, name, mainListener.handler);\n } else {\n client.off(name, mainListener.handler);\n }\n } else {\n if (namespace) {\n this.commandkit.events.removeAllListeners(namespace, name);\n } else {\n client.removeAllListeners(name);\n }\n }\n\n this.loadedEvents.delete(key);\n\n Logger.info(\n `🗑️ Unregistered event ${name}${\n namespace ? ` of namespace ${namespace}` : ''\n }`,\n );\n }\n }\n}\n","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { loadConfigFileFromPath } from '../cli/common';\nimport { getConfig } from './config';\n\nconst CONFIG_FILE_NAMES = [\n 'commandkit.config.js',\n 'commandkit.config.mjs',\n 'commandkit.config.cjs',\n 'commandkit.config.ts',\n];\n\nexport function getPossibleConfigPaths(root: string) {\n return CONFIG_FILE_NAMES.map((name) => join(root, name));\n}\n\nfunction findConfigFile(cwd: string) {\n const locations = getPossibleConfigPaths(cwd);\n\n for (const location of locations) {\n if (existsSync(location)) {\n return {\n path: location,\n isTypeScript: /\\.ts$/.test(location),\n };\n }\n }\n\n return null;\n}\n\nlet loadedConfig: ReturnType<typeof getConfig> | null = null;\n\n/**\n * Load the configuration file from the given entrypoint.\n * @param entrypoint The entrypoint to load the configuration file from. Defaults to the current working directory.\n */\nexport async function loadConfigFile(entrypoint = process.cwd()) {\n if (loadedConfig) return loadedConfig;\n const filePath = findConfigFile(entrypoint);\n if (!filePath) return getConfig();\n\n const config = await loadConfigFileFromPath(filePath.path);\n\n loadedConfig = config;\n\n return config;\n}\n","import type { CommandKit } from '../CommandKit';\nimport { Logger } from '../logger/Logger';\nimport { COMMANDKIT_IS_DEV, HMREventType } from './constants';\n\ninterface IpcMessageCommand {\n event: HMREventType;\n path: string;\n id?: string;\n}\n\nexport interface CommandKitHMREvent {\n event: HMREventType;\n path: string;\n accept: () => void;\n preventDefault: () => void;\n}\n\nexport function registerDevHooks(commandkit: CommandKit) {\n if (!COMMANDKIT_IS_DEV) return;\n\n process.on('message', async (message) => {\n if (typeof message !== 'object' || message === null) return;\n\n const { event, path, id } = message as IpcMessageCommand;\n if (!event) return;\n\n if (process.env.COMMANDKIT_DEBUG_HMR === 'true') {\n Logger.info(`Received HMR event: ${event}${path ? ` for ${path}` : ''}`);\n }\n\n let accepted = false,\n prevented = false,\n handled = false;\n\n const hmrEvent: CommandKitHMREvent = {\n accept() {\n accepted = true;\n },\n preventDefault() {\n prevented = true;\n },\n path,\n event,\n };\n\n try {\n await commandkit.plugins.execute(async (ctx, plugin) => {\n // some plugin accepted the event\n if (accepted) return;\n await plugin.performHMR?.(ctx, hmrEvent);\n });\n\n // plugin took care of it\n if (prevented) return;\n\n switch (event) {\n case HMREventType.ReloadCommands:\n commandkit.commandHandler.reloadCommands();\n handled = true;\n break;\n case HMREventType.ReloadEvents:\n commandkit.eventHandler.reloadEvents();\n handled = true;\n break;\n case HMREventType.Unknown:\n // Handle unknown events if needed\n handled = false;\n break;\n default:\n // invalid hmr event\n break;\n }\n } finally {\n // Send acknowledgment back to dev server if an id was provided\n if (id && process.send) {\n process.send({\n type: 'commandkit-hmr-ack',\n id,\n handled: handled || accepted,\n });\n }\n }\n });\n}\n","import EventEmitter from 'node:events';\nimport type { CommandKitOptions } from './types';\nimport colors from './utils/colors';\nimport { createElement, Fragment } from './components';\nimport { EventInterceptor } from './components/common/EventInterceptor';\nimport { Awaitable, Client, Events, Locale, Message } from 'discord.js';\nimport { createProxy, findAppDirectory, SimpleProxy } from './utils/utilities';\nimport { join } from 'node:path';\nimport { AppCommandHandler } from './app/handlers/AppCommandHandler';\nimport { CommandsRouter, EventsRouter } from './app/router';\nimport { AppEventsHandler } from './app/handlers/AppEventsHandler';\nimport { CommandKitPluginRuntime } from './plugins/plugin-runtime/CommandKitPluginRuntime';\nimport { loadConfigFile } from './config/loader';\nimport { COMMANDKIT_IS_DEV } from './utils/constants';\nimport { registerDevHooks } from './utils/dev-hooks';\nimport { writeFileSync } from 'node:fs';\nimport { CommandKitEventsChannel } from './events/CommandKitEventsChannel';\nimport { isRuntimePlugin } from './plugins';\nimport { generateTypesPackage } from './utils/types-package';\nimport { Logger } from './logger/Logger';\nimport { AsyncFunction, GenericFunction } from './context/async-context';\nimport { FlagStore } from './flags/store';\n\nexport interface CommandKitConfiguration {\n defaultLocale: Locale;\n getMessageCommandPrefix: (message: Message) => Awaitable<string | string[]>;\n}\n\nexport type BootstrapFunction =\n | GenericFunction<[CommandKit]>\n | AsyncFunction<[CommandKit]>;\n\nconst bootstrapHooks = new Set<BootstrapFunction>();\nconst onApplicationBootstrapHooks = new Set<BootstrapFunction>();\n\n/**\n * Registers a bootstrap hook that will be called when the CommandKit instance is created.\n * This is useful for plugins that need to run some code after the CommandKit instance is fully initialized.\n * Note that not all commandkit dependiencs are available at this point. It is recommended to use the `onApplicationBootstrap` hook instead,\n * if you need access to the commandkit dependencies.\n * @param fn The bootstrap function to register.\n * @example ```ts\n * import { onBootstrap } from 'commandkit';\n *\n * onBootstrap(async (commandkit) => {\n * // Do something with the commandkit instance\n * })\n * ```\n */\nexport function onBootstrap<F extends BootstrapFunction>(fn: F): void {\n bootstrapHooks.add(fn);\n}\n\n/**\n * Registers a bootstrap hook that will be called when the CommandKit instance is created.\n * This is useful for plugins that need to run some code after the CommandKit instance is fully initialized.\n * @param fn The bootstrap function to register.\n * @example ```ts\n * import { onApplicationBootstrap } from 'commandkit';\n *\n * onApplicationBootstrap(async (commandkit) => {\n * // Do something with the commandkit instance\n * })\n * ```\n */\nexport function onApplicationBootstrap<F extends BootstrapFunction>(\n fn: F,\n): void {\n onApplicationBootstrapHooks.add(fn);\n}\n\nexport class CommandKit extends EventEmitter {\n #started = false;\n #clientProxy: SimpleProxy<Client> | null = createProxy({} as Client);\n #client!: Client;\n public eventInterceptor!: EventInterceptor;\n\n public static readonly createElement = createElement;\n public static readonly Fragment = Fragment;\n\n public readonly config: CommandKitConfiguration = {\n defaultLocale: Locale.EnglishUS,\n getMessageCommandPrefix: () => '!',\n };\n\n public readonly store = new Map<string, any>();\n public readonly flags = new FlagStore();\n\n public commandsRouter!: CommandsRouter;\n public eventsRouter!: EventsRouter;\n public commandHandler!: AppCommandHandler;\n public eventHandler!: AppEventsHandler;\n public plugins!: CommandKitPluginRuntime;\n public events!: CommandKitEventsChannel;\n\n static instance: CommandKit | undefined = undefined;\n\n /**\n * Create a new command and event handler with CommandKit.\n *\n * @param options - The default CommandKit configuration.\n * @see {@link https://commandkit.js.org/docs/guide/commandkit-setup}\n */\n constructor(options: CommandKitOptions = {}) {\n if (CommandKit.instance) {\n process.emitWarning(\n 'CommandKit instance already exists. Having multiple instance in same project is discouraged and it may lead to unexpected behavior.',\n {\n code: 'MultiInstanceWarning',\n },\n );\n }\n\n super();\n\n if (!CommandKit.instance) {\n CommandKit.instance = this;\n }\n\n if (options?.client) {\n this.setClient(options.client);\n }\n\n this.plugins = new CommandKitPluginRuntime(this);\n\n this.#bootstrapHooks();\n }\n\n async #bootstrapHooks() {\n for (const hook of bootstrapHooks) {\n try {\n await hook(this);\n } catch (e) {\n Logger.error('Error while executing bootstrap hook: ', e);\n } finally {\n bootstrapHooks.delete(hook);\n }\n }\n\n // force clear just in case we missed something\n bootstrapHooks.clear();\n }\n\n async #applicationBootstrapHooks() {\n for (const hook of onApplicationBootstrapHooks) {\n try {\n await hook(this);\n } catch (e) {\n Logger.error('Error while executing application bootstrap hook: ', e);\n } finally {\n onApplicationBootstrapHooks.delete(hook);\n }\n }\n // force clear just in case we missed something\n onApplicationBootstrapHooks.clear();\n }\n\n /**\n * Starts the commandkit application.\n * @param token The application token to connect to the discord gateway. If not provided, it will use the `TOKEN` or `DISCORD_TOKEN` environment variable. If set to `false`, it will not login.\n */\n async start(token?: string | false) {\n if (this.#started) return;\n\n if (!this.#client) {\n throw new Error(\n colors.red('\"client\" is required when starting CommandKit.'),\n );\n }\n\n this.eventInterceptor = new EventInterceptor(this.client);\n\n if (COMMANDKIT_IS_DEV) {\n try {\n registerDevHooks(this);\n\n await generateTypesPackage();\n } catch (e) {\n // ignore\n if (process.env.COMMANDKIT_DEBUG_TYPEGEN) {\n Logger.error(e);\n }\n }\n }\n\n await this.loadPlugins();\n\n await this.#init();\n\n this.commandHandler.registerCommandHandler();\n this.incrementClientListenersCount();\n\n if (token !== false && !this.client.isReady()) {\n this.client.once(Events.ClientReady, async () => {\n await this.commandHandler.registrar.register();\n });\n\n await this.plugins.execute((ctx, plugin) => {\n return plugin.onBeforeClientLogin?.(ctx);\n });\n\n const botToken =\n token ??\n this.client.token ??\n process.env.TOKEN ??\n process.env.DISCORD_TOKEN;\n\n await this.client.login(botToken);\n\n await this.plugins.execute((ctx, plugin) => {\n return plugin.onAfterClientLogin?.(ctx);\n });\n } else if (this.client.isReady()) {\n await this.commandHandler.registrar.register();\n }\n\n this.#started = true;\n\n await this.#applicationBootstrapHooks();\n }\n\n /**\n * Loads all the plugins.\n */\n async loadPlugins() {\n const config = await loadConfigFile();\n const plugins = config.plugins.flat(2).filter((p) => isRuntimePlugin(p));\n\n if (!plugins.length) return;\n\n for (const plugin of plugins) {\n await this.plugins.softRegisterPlugin(plugin);\n }\n }\n\n /**\n * Whether or not the commandkit application has started.\n */\n get started() {\n return this.#started;\n }\n\n /**\n * Sets the prefix resolver for the command handler.\n * @param resolver The resolver function.\n */\n setPrefixResolver(\n resolver: (message: Message) => Awaitable<string | string[]>,\n ) {\n this.config.getMessageCommandPrefix = resolver;\n return this;\n }\n\n /**\n * Sets the default locale for the command handler.\n * @param locale The default locale.\n */\n setDefaultLocale(locale: Locale) {\n this.config.defaultLocale = locale;\n return this;\n }\n\n /**\n * Get the client attached to this CommandKit instance.\n */\n get client(): Client {\n const client = this.#client || this.#clientProxy?.proxy;\n\n if (!client) {\n throw new Error('Client instance is not set');\n }\n\n return client;\n }\n\n /**\n * Sets the client attached to this CommandKit instance.\n * @param client The client to set.\n */\n setClient(client: Client) {\n this.#client = client;\n\n // update the proxy target if it exists\n if (this.#clientProxy) {\n // this is a hack to update the proxy target\n // because some of the dependencies of commandkit may\n // depend on the client instance\n this.#clientProxy.setTarget(client);\n this.#clientProxy = null;\n }\n\n return this;\n }\n\n async #init() {\n const appDir = this.getAppDirectory();\n if (!appDir) return;\n\n const commandsPath = this.getPath('commands')!;\n const events = this.getPath('events')!;\n\n this.commandHandler = new AppCommandHandler(this);\n this.eventHandler = new AppEventsHandler(this);\n this.events = new CommandKitEventsChannel(this);\n\n this.commandsRouter = new CommandsRouter({\n entrypoint: commandsPath,\n });\n\n await this.plugins.execute((ctx, plugin) => {\n return plugin.onCommandsRouterInit(ctx);\n });\n\n this.eventsRouter = new EventsRouter({\n entrypoints: [events],\n });\n\n await this.plugins.execute((ctx, plugin) => {\n return plugin.onEventsRouterInit(ctx);\n });\n\n await this.#initEvents();\n await this.#initCommands();\n }\n\n async #initCommands() {\n if (this.commandsRouter.isValidPath()) {\n const result = await this.commandsRouter.scan();\n\n if (COMMANDKIT_IS_DEV) {\n writeFileSync(\n './.commandkit/commands.json',\n JSON.stringify(result, null, 2),\n );\n }\n }\n\n await this.commandHandler.loadCommands();\n\n this.commandHandler.printBanner();\n }\n\n async #initEvents() {\n if (this.eventsRouter.isValidPath()) {\n await this.eventsRouter.scan();\n }\n\n await this.eventHandler.loadEvents();\n }\n\n /**\n * Updates application commands with the latest from \"commandsPath\".\n */\n async reloadCommands() {\n await this.commandHandler.reloadCommands();\n }\n\n /**\n * Updates application events with the latest from \"eventsPath\".\n */\n async reloadEvents() {\n await this.eventHandler.reloadEvents();\n }\n\n /**\n * Increment the client listeners count.\n */\n incrementClientListenersCount() {\n this.client.setMaxListeners(this.client.getMaxListeners() + 1);\n }\n\n /**\n * Decrement the client listeners count.\n */\n decrementClientListenersCount() {\n this.client.setMaxListeners(this.client.getMaxListeners() - 1);\n }\n\n /**\n * Path to the app directory. Returns `null` if not found.\n * The lookup order is:\n * - `./app`\n * - `./src/app`\n */\n getAppDirectory() {\n return findAppDirectory();\n }\n\n getPath(to: 'commands' | 'events') {\n const appDir = this.getAppDirectory();\n if (!appDir) return null;\n\n switch (to) {\n case 'commands':\n return join(appDir, 'commands');\n case 'events':\n return join(appDir, 'events');\n default:\n return to satisfies never;\n }\n }\n}\n\nexport const commandkit = CommandKit.instance || new CommandKit();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,iBAAiB,OAAO,0BAA0B;AACxD,MAAM,UAAU,IAAI;AAIpB,SAAgB,uBAChB,QACkC;AAChC,QAAO,UAAU,QAAQ,IAAI,QAAQ,eAAe,KAAK;AAC3D;AAWA,SAAgB,YAAe,IAAgB;AAC7C,QAAO,QAAQ,KAAK,GAAG;AACzB;AAEA,SAAgB,eAChB,OACA,UACI;AACF,SAAQ,IAAI,OAAO,gBAAgB,KAAK;AACxC,QAAO,QAAQ,IAAI,OAAO,SAAS;AACrC;;;;;;;;AASA,SAAgB,yBAGhB,KAA4B,IAAO,WAAkB;CACnD,MAAM,MAAM,CAAC,GAAG,SAAgB;AAC9B,SAAO,eAAe,KAAK,YAAY;AACrC,OAAI;IAEF,MAAM,SAAS,MAAM,GAAG,GAAG,KAAK;AAEhC,WAAO;GACR,SAAQ,GAAG;AACV,SAAK,sCAAkB,EAAE,CACvB,KAAI,kBAAkB,EAAW;GAEpC,UAAS;AACR,eAAW,cAAc,WAEvB,cAAa,YAAY;AACvB,SAAI;AACF,YAAM,UAAU,GAAG,KAAK;KACzB,QAAO,CAGR;IAAA,EAAA;GAEN;EACD,EAAC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;CACxC;;;;CAKA,gCAAgC;AAC9B,OAAK,OAAO,gBAAgB,KAAK,OAAO,iBAAiB,GAAG,EAAE;CAChE;;;;CAKA,gCAAgC;AAC9B,OAAK,OAAO,gBAAgB,KAAK,OAAO,iBAAiB,GAAG,EAAE;CAChE;;;;;;;CAQA,kBAAkB;AAChB,SAAO,kBAAkB;CAC3B;CAEA,QAAQ,IAA2B;EACjC,MAAM,WAAS,KAAK,iBAAiB;AACrC,OAAK,SAAQ,QAAO;AAEpB,UAAQ,IAAR;GACE,KAAK,WACH,QAAO,oBAAK,UAAQ,WAAW;GACjC,KAAK,SACH,QAAO,oBAAK,UAAQ,SAAS;GAC/B,QACE,QAAO;EACX;CACF;AACF;AAEA,MAAa,aAAa,WAAW,YAAY,IAAI"}
@@ -1,4 +1,4 @@
1
- import { BootstrapFunction, CommandKit, CommandKitConfiguration, commandkit, onApplicationBootstrap, onBootstrap } from "./CommandKit-Dbkak3_n.js";
1
+ import { BootstrapFunction, CommandKit, CommandKitConfiguration, commandkit, onApplicationBootstrap, onBootstrap } from "./CommandKit-LJlFFidn.js";
2
2
  import "./EventInterceptor-D_oEWSnF.js";
3
3
  import "./ButtonKit-BSI7lCI0.js";
4
4
  import "./ModalKit-CKtQ8eXW.js";
@@ -28,5 +28,5 @@ import "./helpers-DAmE106r.js";
28
28
  import "./CommandsRouter-C7X-eXE2.js";
29
29
  import "./EventsRouter-BacqK6z3.js";
30
30
  import "./index-CUPkUUOR.js";
31
- import "./constants-Ce6w4OFe.js";
31
+ import "./constants-BPWSrMkn.js";
32
32
  export { BootstrapFunction, CommandKit, CommandKitConfiguration, commandkit, onApplicationBootstrap, onBootstrap };