commandkit 1.2.0-rc.1 → 1.2.0-rc.10

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 (252) hide show
  1. package/README.md +4 -12
  2. package/dist/{ActionRow-CmTHbo2t.js → ActionRow-CbdGFWMT.js} +3 -2
  3. package/dist/{ActionRow-CmTHbo2t.js.map → ActionRow-CbdGFWMT.js.map} +1 -1
  4. package/dist/{CommandKitEventsChannel-Bgw0XCOl.js → CommandKitEventsChannel-BtRzr3Tz.js} +3 -2
  5. package/dist/{CommandKitEventsChannel-Bgw0XCOl.js.map → CommandKitEventsChannel-BtRzr3Tz.js.map} +1 -1
  6. package/dist/{CommandsRouter-Ci1Pe8Vd.js → CommandsRouter-Dmzw-ikm.js} +18 -13
  7. package/dist/{CommandsRouter-Ci1Pe8Vd.js.map → CommandsRouter-Dmzw-ikm.js.map} +1 -1
  8. package/dist/{CompilerPlugin-CjoZAAR8.js → CompilerPlugin-M8r3yNAl.js} +2 -2
  9. package/dist/{CompilerPlugin-CjoZAAR8.js.map → CompilerPlugin-M8r3yNAl.js.map} +1 -1
  10. package/dist/{DefaultLogger-Cy55-uPl.d.ts → DefaultLogger-XCOl5nLd.d.ts} +19 -12
  11. package/dist/{EventInterceptor-CQ4PBpBJ.js → EventInterceptor-CQEXyUTp.js} +3 -5
  12. package/dist/{EventInterceptor-CQ4PBpBJ.js.map → EventInterceptor-CQEXyUTp.js.map} +1 -1
  13. package/dist/{EventWorkerContext-DJUi1W3T.d.ts → EventWorkerContext-DNWfsE1t.d.ts} +2 -2
  14. package/dist/{EventWorkerContext-CSlD9rbx.js → EventWorkerContext-Dq29tieI.js} +3 -2
  15. package/dist/{EventWorkerContext-CSlD9rbx.js.map → EventWorkerContext-Dq29tieI.js.map} +1 -1
  16. package/dist/{EventsRouter-C_J0M3uO.js → EventsRouter-3Gygh-km.js} +9 -5
  17. package/dist/{EventsRouter-C_J0M3uO.js.map → EventsRouter-3Gygh-km.js.map} +1 -1
  18. package/dist/ILogger-BW8GM-YZ.d.ts +64 -0
  19. package/dist/{Logger-iSjA-DWN.d.ts → Logger-DyfkPk7u.d.ts} +2 -2
  20. package/dist/{MessageCommandParser-ROLibZPX.d.ts → MessageCommandParser-BsGMOTDo.d.ts} +3 -3
  21. package/dist/{MessageCommandParser-B_BEQ3p8.js → MessageCommandParser-Dl0xxtdr.js} +9 -4
  22. package/dist/MessageCommandParser-Dl0xxtdr.js.map +1 -0
  23. package/dist/{PluginCommon-Di1xIa8d.js → PluginCommon-Cvl5yYM_.js} +3 -2
  24. package/dist/{PluginCommon-Di1xIa8d.js.map → PluginCommon-Cvl5yYM_.js.map} +1 -1
  25. package/dist/{RuntimePlugin-CBgBLXTG.js → RuntimePlugin-BUecuBIU.js} +3 -2
  26. package/dist/RuntimePlugin-BUecuBIU.js.map +1 -0
  27. package/dist/analytics/analytics-engine.d.ts +6 -6
  28. package/dist/analytics/analytics-engine.js +29 -28
  29. package/dist/analytics/analytics-provider.d.ts +6 -6
  30. package/dist/analytics/constants.js +1 -1
  31. package/dist/analytics/utils.js +29 -28
  32. package/dist/{analytics-engine-vA4MaJYx.d.ts → analytics-engine-jVeSoxEk.d.ts} +113 -32
  33. package/dist/app/commands/AppCommandRunner.d.ts +6 -6
  34. package/dist/app/commands/AppCommandRunner.js +29 -28
  35. package/dist/app/commands/Context.d.ts +6 -6
  36. package/dist/app/commands/Context.js +29 -28
  37. package/dist/app/commands/MessageCommandParser.d.ts +1 -1
  38. package/dist/app/commands/MessageCommandParser.js +2 -2
  39. package/dist/app/commands/helpers.js +1 -1
  40. package/dist/app/events/EventWorkerContext.d.ts +7 -7
  41. package/dist/app/events/EventWorkerContext.js +1 -1
  42. package/dist/app/handlers/AppCommandHandler.d.ts +6 -6
  43. package/dist/app/handlers/AppCommandHandler.js +29 -28
  44. package/dist/app/handlers/AppEventsHandler.d.ts +6 -6
  45. package/dist/app/handlers/AppEventsHandler.js +29 -28
  46. package/dist/app/index.d.ts +7 -7
  47. package/dist/app/index.js +31 -31
  48. package/dist/app/interrupt/signals.d.ts +2 -2
  49. package/dist/app/interrupt/signals.js +5 -5
  50. package/dist/app/middlewares/permissions.d.ts +42 -0
  51. package/dist/app/middlewares/permissions.js +39 -0
  52. package/dist/app/register/CommandRegistrar.d.ts +6 -6
  53. package/dist/app/register/CommandRegistrar.js +29 -28
  54. package/dist/app/router/CommandsRouter.js +1 -1
  55. package/dist/app/router/EventsRouter.js +1 -1
  56. package/dist/app/router/index.d.ts +1 -1
  57. package/dist/app/router/index.js +3 -3
  58. package/dist/{app-process-CjMovpoZ.js → app-process-cj2vF12T.js} +8 -5
  59. package/dist/{app-process-CjMovpoZ.js.map → app-process-cj2vF12T.js.map} +1 -1
  60. package/dist/{build-DXl8uEv4.js → build-DB_aX5xt.js} +18 -14
  61. package/dist/build-DB_aX5xt.js.map +1 -0
  62. package/dist/cli/app-process.js +4 -4
  63. package/dist/cli/build.d.ts +6 -6
  64. package/dist/cli/build.js +31 -30
  65. package/dist/cli/common.d.ts +13 -7
  66. package/dist/cli/common.js +4 -3
  67. package/dist/cli/development.js +45 -44
  68. package/dist/cli/development.js.map +1 -1
  69. package/dist/cli/generators.js +42 -11
  70. package/dist/cli/generators.js.map +1 -1
  71. package/dist/cli/information.js +14 -19
  72. package/dist/cli/information.js.map +1 -1
  73. package/dist/cli/init.js +30 -29
  74. package/dist/cli/production.js +34 -32
  75. package/dist/cli/production.js.map +1 -1
  76. package/dist/cli/type-checker.js +4 -4
  77. package/dist/{colors-Cd4Oz-r-.js → colors-DL3ucTiT.js} +3 -2
  78. package/dist/{colors-Cd4Oz-r-.js.map → colors-DL3ucTiT.js.map} +1 -1
  79. package/dist/{commandkit-DMEW0kJg.js → commandkit-lhbfAyX9.js} +523 -353
  80. package/dist/commandkit-lhbfAyX9.js.map +1 -0
  81. package/dist/commandkit.d.ts +6 -6
  82. package/dist/commandkit.js +29 -28
  83. package/dist/{common-DNADUU3_.js → common-CrqwC-sx.js} +33 -18
  84. package/dist/common-CrqwC-sx.js.map +1 -0
  85. package/dist/common-vnMIelAE.js.map +1 -1
  86. package/dist/components/common/EventInterceptor.js +1 -1
  87. package/dist/components/index.d.ts +2 -2
  88. package/dist/components/index.js +29 -28
  89. package/dist/components/v1/action-row/ActionRow.js +1 -1
  90. package/dist/components/v1/button/Button.js +29 -28
  91. package/dist/components/v1/button/ButtonKit.js +29 -28
  92. package/dist/components/v1/modal/Modal.js +29 -28
  93. package/dist/components/v1/modal/ModalKit.js +29 -28
  94. package/dist/components/v1/select-menu/ChannelSelectMenuKit.js +29 -28
  95. package/dist/components/v1/select-menu/MentionableSelectMenuKit.js +29 -28
  96. package/dist/components/v1/select-menu/RoleSelectMenuKit.js +29 -28
  97. package/dist/components/v1/select-menu/SelectMenu.js +29 -28
  98. package/dist/components/v1/select-menu/StringSelectMenuKit.js +29 -28
  99. package/dist/components/v1/select-menu/UserSelectMenuKit.js +29 -28
  100. package/dist/components/v2/container.js +1 -1
  101. package/dist/components/v2/file.js +1 -1
  102. package/dist/components/v2/index.d.ts +1 -1
  103. package/dist/components/v2/index.js +6 -6
  104. package/dist/components/v2/media-gallery.js +1 -1
  105. package/dist/components/v2/section.js +1 -1
  106. package/dist/components/v2/separator.js +1 -1
  107. package/dist/components/v2/text-display.js +1 -1
  108. package/dist/config/config.d.ts +7 -7
  109. package/dist/config/config.js +29 -28
  110. package/dist/config/default.d.ts +6 -6
  111. package/dist/config/default.js +29 -28
  112. package/dist/config/loader.d.ts +6 -6
  113. package/dist/config/loader.js +29 -28
  114. package/dist/config/types.d.ts +6 -6
  115. package/dist/config/utils.d.ts +6 -6
  116. package/dist/config/utils.js +1 -1
  117. package/dist/{config-CcWJ-vz5.d.ts → config-YAQdMBqh.d.ts} +2 -2
  118. package/dist/constants-4oxxvaJA.js.map +1 -1
  119. package/dist/constants-B5_Ta7PR.js.map +1 -1
  120. package/dist/{constants-CUND8XkG.js → constants-BOOGN85p.js} +3 -2
  121. package/dist/{constants-CUND8XkG.js.map → constants-BOOGN85p.js.map} +1 -1
  122. package/dist/{constants-DrjIvQd6.d.ts → constants-D8PMA9on.d.ts} +1 -1
  123. package/dist/{container-z621KfH5.js → container-C6GtfAPW.js} +3 -2
  124. package/dist/{container-z621KfH5.js.map → container-C6GtfAPW.js.map} +1 -1
  125. package/dist/context/async-context.d.ts +7 -7
  126. package/dist/context/async-context.js +31 -29
  127. package/dist/context/environment.d.ts +6 -6
  128. package/dist/context/environment.js +29 -28
  129. package/dist/{dotprops-C_4L7RPD.js → dotprops-tnhpnszJ.js} +2 -2
  130. package/dist/{dotprops-C_4L7RPD.js.map → dotprops-tnhpnszJ.js.map} +1 -1
  131. package/dist/element-Bak9llw_.js.map +1 -1
  132. package/dist/env-_68PRRoA.js.map +1 -1
  133. package/dist/error-codes-B4TyW4Ct.d.ts +54 -0
  134. package/dist/{error-codes-C-ViHyu-.js → error-codes-Ds0bnPvT.js} +2 -2
  135. package/dist/error-codes-Ds0bnPvT.js.map +1 -0
  136. package/dist/events/CommandKitEventsChannel.d.ts +6 -6
  137. package/dist/events/CommandKitEventsChannel.js +1 -1
  138. package/dist/{feature-flags-Cxl9JtVG.js → feature-flags-DnnKABHf.js} +11 -16
  139. package/dist/{feature-flags-Cxl9JtVG.js.map → feature-flags-DnnKABHf.js.map} +1 -1
  140. package/dist/{file-DVZC0QXI.js → file-DVOELoNv.js} +3 -2
  141. package/dist/{file-DVZC0QXI.js.map → file-DVOELoNv.js.map} +1 -1
  142. package/dist/flags/FlagProvider.d.ts +6 -6
  143. package/dist/flags/FlagProvider.js.map +1 -1
  144. package/dist/flags/feature-flags.d.ts +6 -6
  145. package/dist/flags/feature-flags.js +30 -29
  146. package/dist/flags/store.d.ts +6 -6
  147. package/dist/flags/store.js +1 -1
  148. package/dist/{helpers-BUlN3lIz.js → helpers-Dl8wW6aO.js} +3 -2
  149. package/dist/{helpers-BUlN3lIz.js.map → helpers-Dl8wW6aO.js.map} +1 -1
  150. package/dist/index-CUPkUUOR.d.ts +1 -0
  151. package/dist/index-Dw5cCt-A.d.ts +1 -0
  152. package/dist/index-E7Wvm5uX.d.ts +1 -0
  153. package/dist/index.d.ts +13 -12
  154. package/dist/index.js +47 -38
  155. package/dist/index.js.map +1 -0
  156. package/dist/{init-DTBFphOg.js → init-CY7OJPF-.js} +11 -8
  157. package/dist/{init-DTBFphOg.js.map → init-CY7OJPF-.js.map} +1 -1
  158. package/dist/kv/constants.d.ts +1 -1
  159. package/dist/kv/dotprops.js +1 -1
  160. package/dist/kv/kv.d.ts +2 -2
  161. package/dist/kv/kv.js +8 -10
  162. package/dist/kv/kv.js.map +1 -1
  163. package/dist/kv/serde.d.ts +2 -2
  164. package/dist/kv/serde.js +1 -1
  165. package/dist/logger/DefaultLogger.d.ts +2 -2
  166. package/dist/logger/DefaultLogger.js +29 -28
  167. package/dist/logger/ILogger.d.ts +1 -1
  168. package/dist/logger/Logger.d.ts +2 -2
  169. package/dist/logger/Logger.js +29 -28
  170. package/dist/logger/NoopLogger.d.ts +41 -11
  171. package/dist/logger/NoopLogger.js +5 -25
  172. package/dist/logger/NoopLogger.js.map +1 -1
  173. package/dist/{media-gallery-CIKypjbJ.js → media-gallery-zDtJ3kxb.js} +3 -2
  174. package/dist/{media-gallery-CIKypjbJ.js.map → media-gallery-zDtJ3kxb.js.map} +1 -1
  175. package/dist/plugins/CompilerPlugin.d.ts +6 -6
  176. package/dist/plugins/CompilerPlugin.js +2 -2
  177. package/dist/plugins/PluginCommon.d.ts +6 -6
  178. package/dist/plugins/PluginCommon.js +1 -1
  179. package/dist/plugins/RuntimePlugin.d.ts +6 -6
  180. package/dist/plugins/RuntimePlugin.js +2 -2
  181. package/dist/plugins/index.d.ts +6 -6
  182. package/dist/plugins/index.js +29 -28
  183. package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.d.ts +6 -6
  184. package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.js +29 -28
  185. package/dist/plugins/plugin-runtime/CompilerPluginRuntime.d.ts +6 -6
  186. package/dist/plugins/plugin-runtime/CompilerPluginRuntime.js +29 -28
  187. package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.d.ts +6 -6
  188. package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.js +29 -28
  189. package/dist/plugins/plugin-runtime/builtin/MacroPlugin.d.ts +6 -6
  190. package/dist/plugins/plugin-runtime/builtin/MacroPlugin.js +29 -28
  191. package/dist/plugins/plugin-runtime/runtime.d.ts +6 -6
  192. package/dist/plugins/plugin-runtime/runtime.js +1 -1
  193. package/dist/plugins/types.d.ts +6 -6
  194. package/dist/{resolve-file-url-DHTQj2mU.js → resolve-file-url-ChIyw-Vf.js} +4 -4
  195. package/dist/{resolve-file-url-DHTQj2mU.js.map → resolve-file-url-ChIyw-Vf.js.map} +1 -1
  196. package/dist/{section-CuYr0Inu.js → section-DlvrDoJK.js} +4 -4
  197. package/dist/{section-CuYr0Inu.js.map → section-DlvrDoJK.js.map} +1 -1
  198. package/dist/{separator-DLdWBjSN.js → separator-DL6QH5H1.js} +4 -4
  199. package/dist/{separator-DLdWBjSN.js.map → separator-DL6QH5H1.js.map} +1 -1
  200. package/dist/{serde-BUDI03pX.d.ts → serde-BYaKrsOV.d.ts} +2 -2
  201. package/dist/{serde-CHySNpFr.js → serde-Cc8iUa9J.js} +2 -2
  202. package/dist/{serde-CHySNpFr.js.map → serde-Cc8iUa9J.js.map} +1 -1
  203. package/dist/{signals-DHdYrd-n.js → signals-ChFMD7mB.js} +12 -15
  204. package/dist/signals-ChFMD7mB.js.map +1 -0
  205. package/dist/{signals-BQbEfy3X.d.ts → signals-SHg7J1U_.d.ts} +4 -7
  206. package/dist/{store-CiqLHedg.js → store-CM6pWVZh.js} +3 -2
  207. package/dist/{store-CiqLHedg.js.map → store-CM6pWVZh.js.map} +1 -1
  208. package/dist/{text-display--p2-BoUa.js → text-display-DbMumig_.js} +3 -2
  209. package/dist/{text-display--p2-BoUa.js.map → text-display-DbMumig_.js.map} +1 -1
  210. package/dist/{type-checker-1Iu1jJcy.js → type-checker-ocNSZh0W.js} +7 -5
  211. package/dist/{type-checker-1Iu1jJcy.js.map → type-checker-ocNSZh0W.js.map} +1 -1
  212. package/dist/{types-package-DrnIdWLg.js → types-package-BWArjyBF.js} +7 -4
  213. package/dist/{types-package-DrnIdWLg.js.map → types-package-BWArjyBF.js.map} +1 -1
  214. package/dist/types.d.ts +7 -7
  215. package/dist/utils/colors.js +1 -1
  216. package/dist/utils/dev-hooks.d.ts +6 -6
  217. package/dist/utils/dev-hooks.js +29 -28
  218. package/dist/utils/error-codes.d.ts +2 -54
  219. package/dist/utils/error-codes.js +1 -1
  220. package/dist/utils/resolve-file-url.js +1 -1
  221. package/dist/utils/types-package.js +1 -1
  222. package/dist/utils/useful-stuff/async-queue.js.map +1 -1
  223. package/dist/utils/useful-stuff/mutex.js +1 -2
  224. package/dist/utils/useful-stuff/mutex.js.map +1 -1
  225. package/dist/utils/useful-stuff/ratelimiter.js +2 -4
  226. package/dist/utils/useful-stuff/ratelimiter.js.map +1 -1
  227. package/dist/utils/useful-stuff/semaphore.js +2 -4
  228. package/dist/utils/useful-stuff/semaphore.js.map +1 -1
  229. package/dist/utils/utilities.js +29 -28
  230. package/dist/utils/warn-unstable.js.map +1 -1
  231. package/dist/utils-DCSnVAZ6.js.map +1 -1
  232. package/dist/{utils-BnXM4eKk.js → utils-KsNof0Xz.js} +1 -1
  233. package/dist/{utils-BnXM4eKk.js.map → utils-KsNof0Xz.js.map} +1 -1
  234. package/dist/{version-rfStvlqX.js → version-BCILNeQb.js} +2 -2
  235. package/dist/{version-rfStvlqX.js.map → version-BCILNeQb.js.map} +1 -1
  236. package/dist/version.js +1 -1
  237. package/hooks.cjs +2 -0
  238. package/hooks.d.ts +3 -1
  239. package/package.json +60 -59
  240. package/dist/ILogger-DBGON5wx.d.ts +0 -34
  241. package/dist/MessageCommandParser-B_BEQ3p8.js.map +0 -1
  242. package/dist/RuntimePlugin-CBgBLXTG.js.map +0 -1
  243. package/dist/build-DXl8uEv4.js.map +0 -1
  244. package/dist/commandkit-DMEW0kJg.js.map +0 -1
  245. package/dist/common-DNADUU3_.js.map +0 -1
  246. package/dist/error-codes-C-ViHyu-.js.map +0 -1
  247. package/dist/index-DKcmsWXw.d.ts +0 -1
  248. package/dist/index-DSBMRX9A.d.ts +0 -1
  249. package/dist/index-DdqikUQD.d.ts +0 -1
  250. package/dist/signals-DHdYrd-n.js.map +0 -1
  251. /package/dist/{router-DHnFRADH.js → router-Dn35v30f.js} +0 -0
  252. /package/dist/{runtime-5fxB4uhe.js → runtime-DB9CiPfe.js} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"commandkit-DMEW0kJg.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/CompilerPluginRuntime.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/context/environment.ts","../src/app/commands/Context.ts","../src/app/commands/AppCommandRunner.ts","../src/app/register/CommandRegistrar.ts","../src/app/handlers/AppCommandHandler.ts","../src/app/handlers/AppEventsHandler.ts","../src/config/loader.ts","../src/utils/dev-hooks.ts","../src/analytics/utils.ts","../src/analytics/analytics-engine.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\n/**\n * Represents a generic function type that can accept any number of arguments.\n */\nexport type GenericFunction<A extends any[] = any[]> = (...args: A) => any;\n\n/**\n * Checks if the given worker is a CommandKit worker context.\n * @param worker The worker to check.\n * @returns True if the worker is a CommandKit worker context, false otherwise.\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\n/**\n * Executes the provided function within a CommandKit context.\n * @param value The CommandKit environment to use for the context.\n * @param receiver The function to execute within the context.\n * @returns The result of the receiver function.\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\n/**\n * The predicate function that filters button interactions.\n * It receives a ButtonInteraction and returns a boolean or a Promise that resolves to a boolean.\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\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 CommandKitButtonBuilderOnEnd = (reason: string) => Awaitable<void>;\n\n/**\n * The context data for the interaction collector.\n * This includes the autoReset, time, filter, onEnd, and onError properties.\n */\nexport type CommandKitButtonBuilderInteractionCollectorDispatchContextData =\n EventInterceptorContextData<Events.InteractionCreate>;\n\n/**\n * A builder for creating buttons with additional features like interaction collectors and event handling.\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 /**\n * Disposes of the button collector and cleans up resources.\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\n/**\n * The button children type.\n */\nexport type ButtonChildrenLike = string | number | boolean;\n\n/**\n * The button props\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\n/**\n * The predicate function that filters modal interactions.\n * It receives a ModalSubmitInteraction and returns a boolean or a Promise that resolves to a boolean.\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\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 CommandKitModalBuilderOnEnd = (reason: string) => Awaitable<void>;\n\n/**\n * The context data for the interaction collector.\n * This includes the autoReset, time, filter, onEnd, and onError properties.\n */\nexport type CommandKitModalBuilderInteractionCollectorDispatchContextData =\n EventInterceptorContextData<Events.InteractionCreate>;\n\n/**\n * A builder for creating modals with additional features like interaction collectors and event handling.\n * This class extends the ModalBuilder from discord.js and adds methods for handling interactions.\n * It allows you to set a handler for when the modal is submitted, filter interactions, and handle the end of the interaction collector.\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 /**\n * Disposes of the modal collector and cleans up resources.\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\n/**\n * The properties for the modal component.\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\n/**\n * Type for the handler function that is called when the string select menu is submitted.\n */\nexport type OnStringSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n StringSelectMenuInteraction,\n StringSelectMenuKit\n>;\n\n/**\n * Type for the predicate function that filters string select menu interactions.\n * It receives a StringSelectMenuInteraction and returns a boolean or a Promise that resolves to a boolean.\n */\nexport type StringSelectMenuKitPredicate =\n SelectMenuKitPredicate<StringSelectMenuInteraction>;\n\n/**\n * A builder for creating string select menus with additional features like interaction collectors and event handling.\n * This class extends the StringSelectMenuBuilder from discord.js and adds methods for handling interactions.\n * It allows you to set a handler for when the string select menu is submitted, filter interactions, and handle the end of the interaction collector.\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 /**\n * Disposes of the interaction collector and cleans up resources.\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\n/**\n * Type for the handler function that is called when the channel select menu is submitted.\n */\nexport type OnChannelSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n ChannelSelectMenuInteraction,\n ChannelSelectMenuKit\n>;\n\n/**\n * Type for the predicate function that filters channel select menu interactions.\n * It receives a ChannelSelectMenuInteraction and returns a boolean or a Promise that resolves to a boolean.\n */\nexport type ChannelSelectMenuKitPredicate =\n SelectMenuKitPredicate<ChannelSelectMenuInteraction>;\n\n/**\n * A builder for creating channel select menus with additional features like interaction collectors and event handling.\n * This class extends the ChannelSelectMenuBuilder from discord.js and adds methods for handling interactions.\n * It allows you to set a handler for when the channel select menu is submitted, filter interactions, and handle the end of the interaction collector.\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 /**\n * Cleans up the interaction collector and removes the handler.\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\n/**\n * Type for the handler function that is called when the mentionable select menu is submitted.\n */\nexport type OnMentionableSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n MentionableSelectMenuInteraction,\n MentionableSelectMenuKit\n>;\n\n/**\n * Type for the predicate function that filters mentionable select menu interactions.\n * It receives a MentionableSelectMenuInteraction and returns a boolean or a Promise that resolves to a boolean.\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 /**\n * Disposes of the mentionable select menu kit, cleaning up any resources used by the interaction collector.\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\n/**\n * Type for the handler function that is called when the user select menu is submitted.\n */\nexport type OnUserSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n UserSelectMenuInteraction,\n UserSelectMenuKit\n>;\n\n/**\n * Type for the predicate function that filters user select menu interactions.\n * It receives a UserSelectMenuInteraction and returns a boolean or a Promise that resolves to a boolean.\n */\nexport type UserSelectMenuKitPredicate =\n SelectMenuKitPredicate<UserSelectMenuInteraction>;\n\n/**\n * A builder for creating user select menus with additional features like interaction collectors and event handling.\n * This class extends the UserSelectMenuBuilder from discord.js and adds methods for handling interactions.\n * It allows you to set a handler for when the user select menu is submitted, filter interactions, and handle the end of the interaction collector.\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 /**\n * Disposes of the user select menu kit, cleaning up any collectors and handlers.\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\n/**\n * Type for the handler function that is called when the role select menu is submitted.\n */\nexport type OnRoleSelectMenuKitSubmit = OnSelectMenuKitSubmit<\n RoleSelectMenuInteraction,\n RoleSelectMenuKit\n>;\n\n/**\n * Type for the predicate function that filters role select menu interactions.\n * It receives a RoleSelectMenuInteraction and returns a boolean or a Promise that resolves to a boolean.\n */\nexport type RoleSelectMenuKitPredicate =\n SelectMenuKitPredicate<RoleSelectMenuInteraction>;\n\n/**\n * A builder for creating role select menus with additional features like interaction collectors and event handling.\n * This class extends the RoleSelectMenuBuilder from discord.js and adds methods for handling interactions.\n * It allows you to set a handler for when the role select menu is submitted, filter interactions, and handle the end of the interaction collector.\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 /**\n * Disposes of the role select menu kit, cleaning up any resources and event listeners.\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\n/**\n * Type for the common properties shared by all select menu builders.\n */\nexport interface CommonSelectMenuProps<T, C> {\n onSelect?: CommandKitSelectMenuBuilderInteractionCollectorDispatch<T, C>;\n onEnd?: CommandKitSelectMenuBuilderOnEnd;\n onError?: (error: Error) => any;\n options?: CommandKitSelectMenuBuilderInteractionCollectorDispatchContextData;\n}\n\n/**\n * Type for the base select menu component data.\n */\nexport interface SelectMenuProps<T, C>\n extends Partial<Omit<BaseSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<T, C> {}\n\n/**\n * The properties for a string select menu component.\n */\nexport interface StringSelectMenuProps\n extends SelectMenuProps<StringSelectMenuInteraction, StringSelectMenuKit> {\n children?: MaybeArray<StringSelectMenuOptionBuilder>;\n}\n\n/**\n * Type for the common builder kit that can be used with select menus.\n */\nexport type CommonBuilderKit =\n | StringSelectMenuKit\n | UserSelectMenuKit\n | RoleSelectMenuKit\n | ChannelSelectMenuKit\n | MentionableSelectMenuKit;\n\n/**\n * Type that resolves to the specific interaction type based on the builder type.\n * This is used to ensure that the interaction type matches the builder type.\n * For example, if the builder is a StringSelectMenuKit, the interaction type will be StringSelectMenuInteraction.\n * If the builder is a UserSelectMenuKit, the interaction type will be UserSelectMenuInteraction, and so on.\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\n/**\n * @private\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\n/**\n * The StringSelectMenu component.\n * @param props The properties for the string select menu component.\n * @returns The string select menu builder instance.\n * @example ```tsx\n * import { StringSelectMenu } from 'commandkit';\n *\n * const stringSelectMenu = <StringSelectMenu\n * customId=\"my-select-menu\"\n * placeholder=\"Select an option\"\n * maxValues={1}\n * minValues={1}\n * >\n * <StringSelectMenuOption label=\"Option 1\" value=\"option1\" />\n * <StringSelectMenuOption label=\"Option 2\" value=\"option2\" />\n * </StringSelectMenu>\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\n/**\n * Represents the properties for a string select menu option.\n * This can be either a SelectMenuComponentOptionData or an APISelectMenuOption.\n */\nexport type StringSelectMenuOptionProps =\n | SelectMenuComponentOptionData\n | APISelectMenuOption;\n\n/**\n * A select menu option for the string select menu.\n * @param props The properties for the string select menu option.\n * @returns The string select menu option builder instance.\n * @example ```tsx\n * import { StringSelectMenuOption } from 'commandkit';\n *\n * const option = <StringSelectMenuOption label=\"Option 1\" value=\"option1\" />;\n * ```\n */\nexport function StringSelectMenuOption(props: StringSelectMenuOptionProps) {\n return new StringSelectMenuOptionBuilder(props);\n}\n\n/**\n * The UserSelectMenu component.\n */\nexport interface UserSelectMenuProps\n extends Partial<Omit<UserSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<UserSelectMenuInteraction, UserSelectMenuKit> {}\n\n/**\n * The UserSelectMenu component.\n * @param props The properties for the user select menu component.\n * @returns The user select menu builder instance.\n * @example ```tsx\n * import { UserSelectMenu } from 'commandkit';\n *\n * const userSelectMenu = <UserSelectMenu />\n * ```\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\n/**\n * The RoleSelectMenu component props.\n */\nexport interface RoleSelectMenuProps\n extends Partial<Omit<RoleSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<RoleSelectMenuInteraction, RoleSelectMenuKit> {}\n\n/**\n * The RoleSelectMenu component.\n * @param props The properties for the role select menu component.\n * @returns The role select menu builder instance.\n * @example ```tsx\n * import { RoleSelectMenu } from 'commandkit';\n *\n * const roleSelectMenu = <RoleSelectMenu />\n * ```\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\n/**\n * The MentionableSelectMenu component props.\n */\nexport interface MentionableSelectMenuProps\n extends Partial<Omit<MentionableSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<\n MentionableSelectMenuInteraction,\n MentionableSelectMenuKit\n > {}\n\n/**\n * The MentionableSelectMenu component.\n * @param props The properties for the mentionable select menu component.\n * @returns The mentionable select menu builder instance.\n * @example ```tsx\n * import { MentionableSelectMenu } from 'commandkit';\n * const mentionableSelectMenu = <MentionableSelectMenu />\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\n/**\n * The ChannelSelectMenu component props.\n */\nexport interface ChannelSelectMenuProps\n extends Partial<Omit<ChannelSelectMenuComponentData, 'type'>>,\n CommonSelectMenuProps<ChannelSelectMenuInteraction, ChannelSelectMenuKit> {}\n\n/**\n * The ChannelSelectMenu component.\n * @param props The properties for the channel select menu component.\n * @returns The channel select menu builder instance.\n * @example ```tsx\n * import { ChannelSelectMenu } from 'commandkit';\n * const channelSelectMenu = <ChannelSelectMenu />\n * ```\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\n/**\n * Log levels for the logger.\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\n/**\n * Default logger implementation that logs messages to the console.\n * It formats the log messages with timestamps, log levels, and context information.\n */\nexport class DefaultLogger implements ILogger {\n private logger: Console;\n\n /**\n * Creates a new instance of DefaultLogger.\n * @param stdout The output stream for standard messages (default: process.stdout).\n * @param stderr The output stream for error messages (default: process.stderr).\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 /**\n * Logs a debug message.\n * @param args The message arguments to log.\n */\n public debug(...args: any[]): void {\n this._log(LogLevel.DEBUG, ...args);\n }\n\n /**\n * Logs an error message.\n * @param args The message arguments to log.\n */\n public error(...args: any[]): void {\n this._log(LogLevel.ERROR, ...args);\n }\n\n /**\n * Logs a default message.\n * @param args The message arguments to log.\n */\n public log(...args: any[]): void {\n this._log(LogLevel.DEFAULT, ...args);\n }\n\n /**\n * Logs an info message.\n * @param args The message arguments to log.\n */\n public info(...args: any[]): void {\n this._log(LogLevel.INFO, ...args);\n }\n\n /**\n * Logs a warning message.\n * @param args The message arguments to log.\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\n/**\n * Options for configuring the CommandKit logger.\n */\nexport interface CommandKitLoggerOptions {\n /**\n * The logger provider to use.\n */\n provider: ILogger;\n}\n\n/**\n * Logger implementation for CommandKit.\n */\nexport interface LoggerImpl extends ILogger {\n /**\n * Configures the logger with the specified options.\n * @param options The logger options to apply.\n */\n configure(options: CommandKitLoggerOptions): void;\n}\n\n/**\n * Creates a new logger instance with the specified options.\n * @param options The options for configuring the logger.\n * @returns A new logger instance.\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\n/**\n * Default logger instance for CommandKit. This logger uses the DefaultLogger as its provider.\n * The provider can be replaced with a custom logger implementation using the `configure` method.\n */\nexport const Logger = createLogger({\n provider: new DefaultLogger(),\n});\n","import { Collection, Constructable } 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\n/**\n * Represents the runtime environment for CommandKit plugins.\n */\nexport class CommandKitPluginRuntime {\n private plugins = new Collection<string, RuntimePlugin>();\n\n /**\n * Creates a new instance of CommandKitPluginRuntime.\n * @param commandkit The CommandKit instance associated with this runtime.\n */\n public constructor(public readonly commandkit: CommandKit) {}\n\n /**\n * Returns the plugins registered in this runtime.\n * @returns A collection of plugins.\n */\n public getPlugins() {\n return this.plugins;\n }\n\n /**\n * Checks if there are no plugins registered in this runtime.\n * @param pluginName The name of the plugin to check.\n * @returns Boolean indicating whether the runtime is empty.\n */\n public getPlugin(pluginName: string): RuntimePlugin | null {\n return this.plugins.get(pluginName) ?? null;\n }\n\n /**\n * Fetches the given plugin\n * @param plugin The plugin to be fetched.\n */\n public get<T extends Constructable<any>>(plugin: T): InstanceType<T> | null {\n const p = this.plugins.find((p) => p instanceof plugin) ?? null;\n return p as InstanceType<T> | null;\n }\n\n /**\n * Soft registers a plugin in the runtime.\n * @param plugin The plugin to be registered.\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 /**\n * Registers a plugin in the runtime.\n * @param plugin The plugin to be registered.\n * @throws If a plugin with the same name already exists.\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 /**\n * Unregisters a plugin from the runtime.\n * @param plugin The plugin to be unregistered.\n * @throws If the plugin does not exist.\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 /**\n * Unregisters all plugins from the runtime.\n */\n public async unregisterAllPlugins() {\n for (const plugin of this.plugins.values()) {\n await this.unregisterPlugin(plugin);\n }\n }\n\n /**\n * Signals the runtime to allow the current plugin take ownership of the execution context.\n */\n public capture() {\n throw createCommandKitError(CommandKitErrorCodes.PluginCaptureHandle);\n }\n\n /**\n * Executes a function for each plugin in the runtime.\n * @param f The function to execute for each plugin.\n * @returns The result of the last executed function, or undefined if no plugins were executed.\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 {\n CompilerPlugin,\n MaybeFalsey,\n TransformedResult,\n TemplateHandler,\n isCompilerPlugin,\n} from '..';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { Logger } from '../../logger/Logger';\n\n/**\n * Interface representing a template entry in the plugin runtime.\n * It contains a handler function for the template and the plugin that owns it.\n * @private\n */\ninterface TemplateEntry {\n handler: TemplateHandler;\n plugin: CompilerPlugin;\n}\n\n/**\n * Enum representing the execution mode of a plugin.\n * It can be either 'activate' or 'deactivate'.\n * @private\n */\nenum PluginExecutionMode {\n Activate = 'activate',\n Deactivate = 'deactivate',\n}\n\n/**\n * Context for the plugin execution, containing the plugin and its execution mode.\n * This is used to manage the state of the plugin during activation and deactivation.\n * @private\n */\ntype PluginContext = {\n plugin: CompilerPlugin;\n mode: PluginExecutionMode;\n};\n\n/**\n * CompilerPluginRuntime is a runtime for managing compiler plugins in CommandKit.\n */\nexport class CompilerPluginRuntime {\n public readonly name = 'CompilerPluginRuntime';\n private initialized = false;\n private templates = new Map<string, TemplateEntry>();\n #pluginContext = new AsyncLocalStorage<PluginContext>();\n\n /**\n * Creates a new instance of CompilerPluginRuntime.\n * @param plugins An array of compiler plugins to be managed by this runtime.\n */\n public constructor(private readonly plugins: CompilerPlugin[]) {\n this.plugins = this.plugins.filter((p) => !!p && isCompilerPlugin(p));\n }\n\n /**\n * Returns the plugins managed by this runtime.\n */\n public getPlugins() {\n return this.plugins;\n }\n\n /**\n * Checks if there are no plugins registered in this runtime.\n */\n public isEmpty() {\n return !this.plugins.length;\n }\n\n /**\n * Registers a template handler for a given name.\n * This method must be called inside the activate() method of a plugin.\n * @param name - The name of the template to register.\n * @param handler - The handler function for the template.\n */\n public registerTemplate(name: string, handler: TemplateHandler) {\n const ctx = this.#pluginContext.getStore();\n\n if (!ctx || ctx.mode !== PluginExecutionMode.Activate) {\n throw new Error(\n 'registerTemplate() must be called inside activate() method',\n );\n }\n\n if (this.templates.has(name)) {\n throw new Error(`Template \"${name}\" already exists`);\n }\n\n this.templates.set(name, { handler, plugin: ctx.plugin });\n }\n\n /**\n * Unregister a template handler for a given name.\n * This method must be called inside the deactivate() method of a plugin.\n * @param name - The name of the template to unregister.\n */\n public unregisterTemplate(name: string) {\n const ctx = this.#pluginContext.getStore();\n\n if (!ctx || ctx.mode !== PluginExecutionMode.Deactivate) {\n throw new Error(\n 'unregisterTemplate() must be called inside deactivate() method',\n );\n }\n\n const template = this.templates.get(name);\n if (!template) {\n throw new Error(`Template \"${name}\" does not exist`);\n }\n\n if (template.plugin !== ctx.plugin) {\n throw new Error(\n `Template \"${name}\" is owned by plugin \"${template.plugin.name}\" and cannot be unregistered by \"${ctx.plugin.name}\"`,\n );\n }\n\n this.templates.delete(name);\n }\n\n /**\n * Retrieves a template handler by its name.\n * @param name - The name of the template to retrieve.\n * @returns The template handler if found, otherwise undefined.\n */\n public getTemplate(name: string): TemplateHandler | undefined {\n return this.templates.get(name)?.handler;\n }\n\n /**\n * Returns a map of all registered templates with their handlers.\n * The keys are the template names and the values are the template handlers.\n */\n public getTemplates(): Map<string, TemplateHandler> {\n return new Map(\n Array.from(this.templates.entries()).map(([name, entry]) => [\n name,\n entry.handler,\n ]),\n );\n }\n\n /**\n * Transforms the given code using all registered plugins.\n * Each plugin's transform method is called in sequence, allowing them to modify the code.\n * @param code - The code to be transformed.\n * @param id - The identifier for the code being transformed (e.g., filename).\n * @returns An object containing the transformed code and an optional source map.\n */\n public async transform(\n code: string,\n id: string,\n ): Promise<{ code: string; map: string | null }> {\n let map: string | null = null;\n for (const plugin of this.plugins) {\n if (!plugin?.transform || typeof plugin?.transform !== 'function') {\n Logger.warn(\n `Plugin ${plugin?.name ?? '<unknown>'} is invalid or does not have a transform method or the method is not a function`,\n );\n continue;\n }\n\n try {\n const res: MaybeFalsey<TransformedResult> = await plugin.transform?.({\n code,\n id,\n });\n\n if (!res) continue;\n\n if (res.code) {\n code = res.code;\n }\n\n if (res.map) {\n map = res.map;\n }\n } catch (e: any) {\n const err = e instanceof Error ? e : new Error(e);\n throw new Error(\n `Plugin ${plugin.name} failed to transform: ${err.message}`,\n );\n }\n }\n\n return {\n code,\n map,\n };\n }\n\n /**\n * Initializes the plugin runtime by activating all registered plugins.\n * This method should be called once to set up the plugins.\n */\n public async init() {\n if (this.initialized) return;\n\n for (const plugin of this.plugins) {\n try {\n await this.#pluginContext.run(\n {\n plugin,\n mode: PluginExecutionMode.Activate,\n },\n async () => {\n await plugin.activate?.(this);\n },\n );\n } catch (e: any) {\n console.error(\n `Plugin ${plugin.name} failed to activate with ${e?.stack || e}`,\n );\n }\n }\n\n this.initialized = true;\n }\n\n /**\n * Destroys the plugin runtime by deactivating all registered plugins.\n * This method should be called when the runtime is no longer needed.\n */\n public async destroy() {\n if (!this.initialized) return;\n\n for (const plugin of this.plugins) {\n try {\n await this.#pluginContext.run(\n {\n plugin,\n mode: PluginExecutionMode.Deactivate,\n },\n async () => {\n await plugin.deactivate?.(this);\n },\n );\n } catch (e: any) {\n console.error(\n `Plugin ${plugin.name} failed to deactivate with ${e?.stack || e}`,\n );\n }\n }\n\n this.initialized = false;\n }\n\n /**\n * Converts the plugin runtime to a JSON representation.\n * This is useful for serialization or debugging purposes.\n * @returns An object containing the name of the runtime and the transform method.\n */\n public toJSON() {\n return {\n name: this.name,\n transform: this.transform.bind(this),\n };\n }\n}\n","import { DirectiveTransformerOptions } from 'directive-to-hof';\nimport {\n CompilerPlugin,\n CompilerPluginRuntime,\n MaybeFalsey,\n PluginTransformParameters,\n TransformedResult,\n} from '../..';\n\n/**\n * Directive transformer plugin options\n */\nexport type CommonDirectiveTransformerOptions = DirectiveTransformerOptions & {\n /**\n * Whether the directive transformer is enabled.\n * Defaults to true.\n */\n enabled?: boolean;\n};\n\n/**\n * Common directive transformer plugin is a compiler plugin that transforms directives to higher-order functions.\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\n/**\n * Macro plugin enables the use of `\"use macro\"` directive in the code.\n * Functions with this directive will be transformed at compile time\n * and only the result will be included in the final bundle.\n * @example function myMacro() {\n * \"use macro\";\n * return Math.random();\n * }\n *\n * // This will be transformed to a constant value at compile time.\n * const result = myMacro();\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\n/**\n * Default configuration for CommandKit.\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 tsdown: {},\n disableChunking: false,\n },\n entrypoints: [],\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 disablePrefixCommands: false,\n showUnknownPrefixCommandsWarning: true,\n antiCrashScript: {\n development: true,\n production: false,\n },\n};\n","import { MaybeArray } from '../components';\nimport { CommandKitPlugin } from '../plugins';\nimport { defaultConfig } from './default';\nimport { CommandKitConfig } from './types';\nimport { mergeDeep, 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 tsdown: {\n ...defaultConfig.compilerOptions.tsdown,\n ...config.compilerOptions?.tsdown,\n },\n disableChunking:\n config.compilerOptions?.disableChunking ??\n defaultConfig.compilerOptions.disableChunking,\n },\n entrypoints: [\n ...(config.entrypoints ?? []),\n ...(defaultConfig.entrypoints ?? []),\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 disablePrefixCommands:\n config.disablePrefixCommands ?? defaultConfig.disablePrefixCommands,\n showUnknownPrefixCommandsWarning:\n config.showUnknownPrefixCommandsWarning ??\n defaultConfig.showUnknownPrefixCommandsWarning,\n antiCrashScript: {\n ...defaultConfig.antiCrashScript,\n ...config.antiCrashScript,\n },\n };\n\n return defined;\n}\n","import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n COMMANDKIT_CWD,\n COMMANDKIT_IS_CLI,\n COMMANDKIT_IS_DEV,\n} from './constants';\nimport { getConfig } from '../config/config';\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\n/**\n * Returns the current working directory of the CommandKit application.\n * This is typically the directory where the source code is located.\n */\nexport function getCurrentDirectory(): string {\n if (currentDir) return currentDir;\n const src = getSrcDir();\n let root = join(COMMANDKIT_CWD, src);\n\n if (!existsSync(root)) root = COMMANDKIT_CWD;\n\n currentDir = root;\n\n return root;\n}\n\n/**\n * Returns the possible source directories for the CommandKit application.\n * This includes the `src`, `.commandkit`, and the distribution directory.\n * @returns An array of possible source directories.\n */\nexport function getSourceDirectories(): string[] {\n const dist = getConfig().distDir;\n const locations = ['src', '.commandkit', dist].map((dir) =>\n join(COMMANDKIT_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(COMMANDKIT_CWD, getSrcDir());\n\n if (!existsSync(root)) root = COMMANDKIT_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 * @example\n * const debouncedFn = debounce(() => {\n * console.log('Debounced function called');\n * }, 300);\n *\n * debouncedFn(); // Will only execute after 300ms of inactivity\n * debouncedFn(); // Will reset the timer\n * debouncedFn(); // Will reset the timer again\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 * Defers the execution of a function.\n * @param fn The function to defer.\n * @param timeout The time in milliseconds to wait before executing the function. Defaults to 0.\n * @example\n * defer(() => {\n * console.log('This will run after a delay');\n * });\n *\n * console.log('This will run immediately');\n */\nexport function defer<T>(fn: () => T, timeout = 0): void {\n setTimeout(() => {\n return fn();\n }, timeout).unref();\n}\n\n/**\n * Serializes a value to JSON.\n * @param value The value to serialize.\n * @param defaultValue The default value to return if the value is not serializable.\n * @returns The serialized value.\n */\nexport function JsonSerialize<R = any>(value: any, defaultValue = {} as R): R {\n try {\n return JSON.parse(JSON.stringify(value));\n } catch {\n return defaultValue;\n }\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 * Represents a simple proxy object that mirrors a target object.\n */\nexport interface SimpleProxy<T extends object> {\n /**\n * The proxied object that mirrors the target.\n */\n proxy: T;\n /**\n * Sets a new target object for the proxy.\n * @param newTarget The new target object to set.\n */\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 { randomUUID } from 'node:crypto';\nimport { CommandKit } from '../commandkit';\nimport { GenericFunction, getContext } from './async-context';\nimport type { Context } from '../app';\n\n/**\n * Represents the internal data structure for the CommandKit environment.\n */\nexport interface CommandKitEnvironmentInternalData {\n /**\n * The error that occurred during command execution, if any.\n * This is set when an error occurs during the execution of a command.\n */\n executionError: Error | null;\n /**\n * The type of the environment, which can be used to differentiate between\n * different execution contexts (e.g., command handler, event handler, etc.).\n */\n type: CommandKitEnvironmentType | null;\n /**\n * A map of variables that can be used to store and retrieve data during command execution.\n * This allows for sharing data between different parts of the command execution process.\n */\n variables: Map<string, any>;\n /**\n * A map of deferred functions that will be executed after the command has finished executing.\n * This is useful for running cleanup tasks or additional processing after the main command logic.\n */\n deferredFunctions: Map<string, GenericFunction<[CommandKitEnvironment]>>;\n /**\n * A marker string that can be used to identify the command execution.\n * This is useful for logging and debugging purposes.\n */\n marker: string;\n /**\n * The start time of the command execution.\n */\n markStart: number;\n /**\n * The end time of the command execution.\n */\n markEnd: number;\n /**\n * The context associated with the command execution.\n * This can be used to access request-specific data or application state.\n */\n context: Context | null;\n}\n\n/**\n * Represents the execution environment for CommandKit commands.\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 * Schedules the given function to run 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 * @example import { after } from 'commandkit';\n *\n * // inside a command\n * export const chatInput: ChatInputCommand = async (ctx) => {\n * after(() => {\n * console.log('This will run after the command has finished executing.');\n * });\n *\n * // ... command logic\n * }\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 * @example import { cancelAfter } from 'commandkit';\n * // inside a command\n * export const chatInput: ChatInputCommand = async (ctx) => {\n * const id = after(() => {\n * console.log('This will run after the command has finished executing.');\n * });\n *\n * // cancel the deferred function if needed\n * if (something) cancelAfter(id);\n * }\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 '../interrupt/signals';\nimport {\n LoadedCommand,\n ResolvableCommand,\n RunCommand,\n} from '../handlers/AppCommandHandler';\n\n/**\n * Enumeration of different command execution modes supported by CommandKit.\n */\nexport const CommandExecutionMode = {\n ChatInputCommand: 'chatInput',\n MessageContextMenu: 'messageContextMenu',\n UserContextMenu: 'userContextMenu',\n Autocomplete: 'autocomplete',\n Message: 'message',\n} as const;\n\n/**\n * Type representing the possible command execution modes.\n */\nexport type CommandExecutionMode =\n (typeof CommandExecutionMode)[keyof typeof CommandExecutionMode];\n\n/**\n * Parameters required to create a command context.\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\n/**\n * Context for message-based commands.\n */\nexport type MessageCommandContext = Context<'message'>;\n\n/**\n * Context for interaction-based commands.\n */\nexport type InteractionCommandContext = Context<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'\n>;\n\n/**\n * Middleware context for message-based commands.\n */\nexport type MessageCommandMiddlewareContext = MiddlewareContext<'message'>;\n\n/**\n * Middleware context for interaction-based commands.\n */\nexport type InteractionCommandMiddlewareContext = MiddlewareContext<\n 'autocomplete' | 'chatInput' | 'messageContextMenu' | 'userContextMenu'\n>;\n\n/**\n * Context for chat input (slash) commands.\n */\nexport type ChatInputCommandContext = Context<'chatInput'>;\n\n/**\n * Middleware context for slash commands.\n */\nexport type SlashCommandMiddlewareContext = MiddlewareContext<'chatInput'>;\n\n/**\n * Context for autocomplete interactions.\n */\nexport type AutocompleteCommandContext = Context<'autocomplete'>;\n\n/**\n * Middleware context for autocomplete interactions.\n */\nexport type AutocompleteCommandMiddlewareContext =\n MiddlewareContext<'autocomplete'>;\n\n/**\n * Context for message context menu commands.\n */\nexport type MessageContextMenuCommandContext = Context<'messageContextMenu'>;\n\n/**\n * Middleware context for message context menu commands.\n */\nexport type MessageContextMenuCommandMiddlewareContext =\n MiddlewareContext<'messageContextMenu'>;\n\n/**\n * Context for user context menu commands.\n */\nexport type UserContextMenuCommandContext = Context<'userContextMenu'>;\n\n/**\n * Middleware context for user context menu commands.\n */\nexport type UserContextMenuCommandMiddlewareContext =\n MiddlewareContext<'userContextMenu'>;\n\n/**\n * Type representing command context options based on execution mode.\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\n/**\n * Generic type for command execution functions.\n */\nexport type AnyCommandExecute<ContextType extends Context = Context> = (\n ctx: ContextType,\n) => Awaitable<unknown>;\n\n/**\n * Type for chat input command execution functions.\n */\nexport type ChatInputCommand = AnyCommandExecute<ChatInputCommandContext>;\n\n/**\n * Type for autocomplete command execution functions.\n */\nexport type AutocompleteCommand = AnyCommandExecute<AutocompleteCommandContext>;\n\n/**\n * Type for message context menu command execution functions.\n */\nexport type MessageContextMenuCommand =\n AnyCommandExecute<MessageContextMenuCommandContext>;\n\n/**\n * Type for user context menu command execution functions.\n */\nexport type UserContextMenuCommand =\n AnyCommandExecute<UserContextMenuCommandContext>;\n\n/**\n * Type for message command execution functions.\n */\nexport type MessageCommand = AnyCommandExecute<MessageCommandContext>;\n\n/**\n * Arguments for middleware context.\n */\nexport interface MiddlewareContextArgs {\n setCommandRunner?: GenericFunction<[RunCommand]>;\n}\n\n/**\n * Represents the execution context for a command, providing access to Discord.js objects,\n * command metadata, and various utility methods for command execution.\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 /**\n * @private\n * @internal\n */\n #store: Map<string, any>;\n\n /**\n * @private\n * @internal\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 /**\n * Gets the name of the current command.\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 /**\n * Gets the command options based on the execution mode.\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.appConfig.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 * @param config - Optional partial config to override in the clone\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 /**\n * Checks if this context is a middleware context.\n */\n public isMiddleware(): this is MiddlewareContext<ExecutionMode> {\n return this instanceof MiddlewareContext;\n }\n\n /**\n * Gets the command arguments (only available for message commands).\n * @returns Array of command arguments\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\n/**\n * Extended context class for middleware execution with additional control methods.\n */\nexport class MiddlewareContext<\n T extends CommandExecutionMode = CommandExecutionMode,\n> extends Context<T, MiddlewareContextArgs> {\n /**\n * @private\n * @internal\n */\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';\nimport { AnalyticsEvents } from '../../analytics/constants';\n\n/**\n * Options for running a command in CommandKit.\n */\nexport interface RunCommandOptions {\n /**\n * The handler to use for executing the command.\n * If not provided, the execution mode will determine the handler.\n * For example, 'chatInputCommand', 'message', etc.\n */\n handler?: string;\n /**\n * Whether to throw an error if the command execution fails.\n * If true, any error during execution will be thrown.\n * Default is false, which means errors will be logged but not thrown.\n * @default false\n */\n throwOnError?: boolean;\n}\n\n/**\n * Handles the execution of application commands for CommandKit.\n * Manages middleware execution, environment setup, and command invocation.\n */\nexport class AppCommandRunner {\n /**\n * Creates a new AppCommandRunner instance.\n * @param handler - The app command handler instance to use for command execution\n */\n public constructor(private handler: AppCommandHandler) {}\n\n /**\n * Executes a prepared command with middleware support and environment setup.\n * Handles the complete command lifecycle including before/after middleware execution.\n * @param prepared - The prepared command execution data\n * @param source - The source interaction or message that triggered the command\n */\n public async runCommand(\n prepared: PreparedAppCommandExecution,\n source: Interaction | Message,\n options?: RunCommandOptions,\n ) {\n const { commandkit } = this.handler;\n\n const shouldThrowOnError = !!options?.throwOnError;\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 env.variables.set('customHandler', options?.handler ?? null);\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 let result: any;\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[options?.handler || executionMode];\n\n if (!fn) {\n Logger.warn(\n `Command ${prepared.command.command.name} has no handler for ${executionMode}`,\n );\n }\n\n const analytics = commandkit.analytics;\n\n if (fn) {\n try {\n const _executeCommand = makeContextAwareFunction(\n env,\n async () => {\n env.registerDeferredFunction(async (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 const commandName =\n prepared.command?.data?.command?.name ??\n prepared.command.command.name;\n\n await analytics.track({\n name: AnalyticsEvents.COMMAND_EXECUTION,\n id: commandName,\n data: {\n error: true,\n executionTime: env.getExecutionTime().toFixed(2),\n type: executionMode,\n command: commandName,\n },\n });\n\n return;\n }\n\n Logger.info(\n `[${marker} - ${time}] Command executed successfully`,\n );\n\n const commandName =\n prepared.command?.data?.command?.name ??\n prepared.command.command.name;\n\n await analytics.track({\n name: AnalyticsEvents.COMMAND_EXECUTION,\n id: commandName,\n data: {\n error: false,\n executionTime: env.getExecutionTime().toFixed(2),\n type: executionMode,\n command: commandName,\n },\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 result = 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 if (shouldThrowOnError) {\n throw e;\n }\n\n Logger.error(e);\n }\n }\n }\n } else {\n result = {\n error: true,\n message: 'Command execution was cancelled by the middleware.',\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 return result;\n }\n\n /**\n * @private\n * @internal\n * Finalizes command execution by running deferred functions and plugin cleanup.\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 /**\n * Determines the execution mode based on the source of the command.\n * @param source - The interaction or message that triggered the command\n * @returns The appropriate command execution mode\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 { ApplicationCommandType, REST, Routes } from 'discord.js';\nimport { CommandKit } from '../../commandkit';\nimport { CommandData } from '../../types';\nimport { Logger } from '../../logger/Logger';\n\n/**\n * Event object passed to plugins before command registration.\n */\nexport interface PreRegisterCommandsEvent {\n preventDefault(): void;\n commands: CommandData[];\n}\n\n/**\n * Handles registration of Discord application commands (slash commands, context menus).\n */\nexport class CommandRegistrar {\n /**\n * @private\n * @internal\n */\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 {\n ApplicationCommandType,\n AutocompleteInteraction,\n Awaitable,\n Collection,\n CommandInteraction,\n ContextMenuCommandBuilder,\n Events,\n Interaction,\n Message,\n SlashCommandBuilder,\n} from 'discord.js';\nimport type { CommandKit } from '../../commandkit';\nimport { AsyncFunction, GenericFunction } from '../../context/async-context';\nimport { Logger } from '../../logger/Logger';\nimport type { CommandData } from '../../types';\nimport colors from '../../utils/colors';\nimport { COMMANDKIT_IS_DEV } from '../../utils/constants';\nimport { CommandKitErrorCodes, isErrorType } from '../../utils/error-codes';\nimport { toFileURL } from '../../utils/resolve-file-url';\nimport { rewriteCommandDeclaration } from '../../utils/types-package';\nimport { AppCommandRunner } from '../commands/AppCommandRunner';\nimport { Context } from '../commands/Context';\nimport { MessageCommandParser } from '../commands/MessageCommandParser';\nimport { CommandRegistrar } from '../register/CommandRegistrar';\nimport { Command, Middleware } from '../router';\nimport { getConfig } from '../../config/config';\n\n/**\n * Function type for wrapping command execution with custom logic.\n */\nexport type RunCommand = <T extends AsyncFunction>(fn: T) => T;\n\n/**\n * Represents a native command structure used in CommandKit.\n * This structure includes the command definition and various handlers for different interaction types.\n * It can be used to define slash commands, context menu commands, and message commands.\n */\nexport interface AppCommandNative {\n command: CommandData | 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\n/**\n * Custom properties that can be added to an AppCommand.\n * This allows for additional metadata or configuration to be associated with a command.\n */\nexport interface CustomAppCommandProps {\n [key: string]: any;\n}\n\n/**\n * Represents a command in the CommandKit application, including its metadata and handlers.\n * This type extends the native command structure with additional properties.\n */\nexport type AppCommand = AppCommandNative & CustomAppCommandProps;\n\n/**\n * @private\n * @internal\n */\ninterface AppCommandMiddleware {\n beforeExecute: (ctx: Context) => Awaitable<unknown>;\n afterExecute: (ctx: Context) => Awaitable<unknown>;\n}\n\n/**\n * Represents a loaded command with its metadata and configuration.\n */\nexport interface LoadedCommand {\n command: Command;\n data: AppCommand;\n guilds?: string[];\n}\n\n/**\n * Type representing command data identifier.\n */\nexport type CommandTypeData = string;\n\n/**\n * Type for commands that can be resolved by the handler.\n */\nexport type ResolvableCommand = CommandTypeData | (string & {});\n\n/**\n * @private\n * @internal\n */\ninterface LoadedMiddleware {\n middleware: Middleware;\n data: AppCommandMiddleware;\n}\n\n/**\n * Represents a prepared command execution with all necessary data and middleware.\n */\nexport interface PreparedAppCommandExecution {\n command: LoadedCommand;\n middlewares: LoadedMiddleware[];\n messageCommandParser?: MessageCommandParser;\n}\n\n/**\n * Type representing command builder objects supported by CommandKit.\n */\nexport type CommandBuilderLike =\n | SlashCommandBuilder\n | ContextMenuCommandBuilder\n | Record<string, any>;\n\n/**\n * @private\n * @internal\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\nexport type CommandDataSchema = typeof commandDataSchema;\nexport type CommandDataSchemaKey = keyof CommandDataSchema;\nexport type CommandDataSchemaValue = CommandDataSchema[CommandDataSchemaKey];\n\n/**\n * @private\n * @internal\n */\nconst middlewareDataSchema = {\n beforeExecute: (c: unknown) => typeof c === 'function',\n afterExecute: (c: unknown) => typeof c === 'function',\n};\n\n/**\n * Handles application commands for CommandKit, including loading, registration, and execution.\n * Manages both slash commands and message commands with middleware support.\n */\nexport class AppCommandHandler {\n /**\n * @private\n * @internal\n */\n private loadedCommands = new Collection<string, LoadedCommand>();\n\n /**\n * @private\n * @internal\n */\n private loadedMiddlewares = new Collection<string, LoadedMiddleware>();\n\n /**\n * Command registrar for handling Discord API registration.\n */\n public readonly registrar: CommandRegistrar;\n\n /**\n * @private\n * @internal\n */\n private onInteraction: GenericFunction<[Interaction]> | null = null;\n\n /**\n * @private\n * @internal\n */\n private onMessageCreate: GenericFunction<[Message]> | null = null;\n\n /**\n * Command runner instance for executing commands.\n */\n public readonly commandRunner = new AppCommandRunner(this);\n\n /**\n * External command data storage.\n */\n public readonly externalCommandData = new Collection<string, Command>();\n\n /**\n * External middleware data storage.\n */\n public readonly externalMiddlewareData = new Collection<string, Middleware>();\n\n /**\n * Creates a new AppCommandHandler instance.\n * @param commandkit - The CommandKit instance\n */\n public constructor(public readonly commandkit: CommandKit) {\n this.registrar = new CommandRegistrar(this.commandkit);\n }\n\n /**\n * Prints a formatted banner showing all loaded commands organized by category.\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 /**\n * Gets an array of all loaded commands.\n * @returns Array of loaded commands\n */\n public getCommandsArray() {\n return Array.from(this.loadedCommands.values());\n }\n\n /**\n * Registers event handlers for Discord interactions and messages.\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 /**\n * Prepares a command for execution by resolving the command and its middleware.\n * @param source - The interaction or message that triggered the command\n * @param cmdName - Optional command name override\n * @returns Prepared command execution data or null if command not found\n */\n public async prepareCommandRun(\n source: Interaction | Message,\n cmdName?: string,\n ): Promise<PreparedAppCommandExecution | null> {\n const config = getConfig();\n\n if (config.disablePrefixCommands && source instanceof Message) {\n return null;\n }\n\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.appConfig.getMessageCommandPrefix(source);\n\n if (!prefix || !prefix.length) return null;\n\n parser = new MessageCommandParser(\n source,\n Array.isArray(prefix) ? prefix : [prefix],\n (command: string) => {\n // Find the command by name\n const loadedCommand = this.findCommandByName(command);\n if (!loadedCommand) {\n if (\n COMMANDKIT_IS_DEV &&\n this.commandkit.config.showUnknownPrefixCommandsWarning\n ) {\n Logger.error(\n `Prefix command \"${command}\" was not found.\\nNote: This warning is only shown in development mode as an alert to help you find the command. If you wish to remove this warning, set \\`showUnknownPrefixCommandsWarning\\` to \\`false\\` in your commandkit config.`,\n );\n }\n return null;\n }\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 loadedCommand = this.findCommandByName(cmdName);\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 /**\n * Finds a command by name.\n * @param name - The command name to search for\n * @returns The loaded command or null if not found\n */\n private findCommandByName(name: string): LoadedCommand | null {\n for (const [, loadedCommand] of this.loadedCommands) {\n if (loadedCommand.data.command.name === name) {\n return loadedCommand;\n }\n\n // Check aliases for prefix commands\n const aliases = loadedCommand.data.command.aliases;\n if (aliases && Array.isArray(aliases) && aliases.includes(name)) {\n return loadedCommand;\n }\n }\n return null;\n }\n\n /**\n * Reloads all commands and middleware from scratch.\n */\n public async reloadCommands() {\n this.loadedCommands.clear();\n this.loadedMiddlewares.clear();\n this.externalCommandData.clear();\n this.externalMiddlewareData.clear();\n\n await this.loadCommands();\n }\n\n /**\n * Adds external middleware data to be loaded.\n * @param data - Array of middleware data to add\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 /**\n * Adds external command data to be loaded.\n * @param data - Array of command data to add\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 /**\n * Registers externally loaded middleware.\n * @param data - Array of loaded middleware to register\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 /**\n * Registers externally loaded commands.\n * @param data - Array of loaded commands to register\n */\n public async registerExternalLoadedCommands(data: LoadedCommand[]) {\n for (const command of data) {\n this.loadedCommands.set(command.command.id, command);\n }\n }\n\n /**\n * Loads all commands and middleware from the router.\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 const commandNames = Array.from(this.loadedCommands.values()).map(\n (v) => v.data.command.name,\n );\n const aliases = Array.from(this.loadedCommands.values()).flatMap(\n (v) => v.data.command.aliases || [],\n );\n\n const allNames = [...commandNames, ...aliases];\n\n await rewriteCommandDeclaration(\n `type CommandTypeData = ${allNames.map((name) => JSON.stringify(name)).join(' | ')}`,\n );\n }\n\n await this.commandkit.plugins.execute((ctx, plugin) => {\n return plugin.onAfterCommandsLoad(ctx);\n });\n }\n\n /**\n * @private\n * @internal\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 /**\n * @private\n * @internal\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} command`,\n type: 1,\n },\n },\n });\n return;\n }\n\n const commandFileData = (await import(\n `${toFileURL(command.path)}?t=${Date.now()}`\n )) as AppCommandNative;\n\n if (!commandFileData.command) {\n throw new Error(\n `Invalid export for command ${command.name}: no command definition found`,\n );\n }\n\n // Apply the specified logic for name and description\n const commandName = commandFileData.command.name || command.name;\n const commandDescription =\n commandFileData.command.description || `${commandName} command`;\n\n // Update the command data with resolved name and description\n const updatedCommandData = {\n ...commandFileData.command,\n name: commandName,\n description: commandDescription,\n aliases: commandFileData.command.aliases,\n } as CommandData;\n\n let handlerCount = 0;\n\n for (const [key, propValidator] of Object.entries(commandDataSchema) as [\n CommandDataSchemaKey,\n CommandDataSchemaValue,\n ][]) {\n const exportedProp = commandFileData[key];\n\n if (exportedProp) {\n if (!(await propValidator(exportedProp))) {\n throw new Error(\n `Invalid export for command ${command.name}: ${key} does not match expected value`,\n );\n }\n\n if (key !== 'command') {\n // command file includes a handler function (chatInput, message, etc)\n handlerCount++;\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 = updatedCommandData;\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 as CommandData;\n }\n });\n\n this.loadedCommands.set(id, {\n command,\n guilds: commandFileData.command.guilds,\n data: {\n ...commandFileData,\n command:\n 'toJSON' in lastUpdated && typeof lastUpdated.toJSON === 'function'\n ? lastUpdated.toJSON()\n : lastUpdated,\n },\n });\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 { runInEventWorkerContext } from '../events/EventWorkerContext';\nimport { ParsedEvent } from '../router';\nimport { CommandKitEventDispatch } from '../../plugins';\nimport { CommandKitErrorCodes, isErrorType } from '../../utils/error-codes';\n\n/**\n * Represents an event listener with its configuration.\n */\nexport type EventListener = {\n handler: ListenerFunction;\n once: boolean;\n};\n\n/**\n * Represents a loaded event with all its listeners.\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\n/**\n * Data structure representing loaded event information for external consumption.\n */\nexport interface AppEventsHandlerLoadedData {\n name: string;\n namespace: string | null;\n onceListeners: number;\n regularListeners: number;\n metadata: ParsedEvent;\n}\n\n/**\n * Handles Discord.js events and CommandKit custom events with support for namespacing and middleware.\n */\nexport class AppEventsHandler {\n /**\n * @private\n * @internal\n */\n private loadedEvents = new Collection<string, LoadedEvent>();\n\n /**\n * Creates a new AppEventsHandler instance.\n * @param commandkit - The CommandKit instance\n */\n public constructor(public readonly commandkit: CommandKit) {}\n\n /**\n * Gets information about all loaded events.\n * @returns Array of loaded event data\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 /**\n * Reloads all events by unregistering existing ones and loading them again.\n */\n public async reloadEvents() {\n this.unregisterAll();\n await this.loadEvents();\n }\n\n /**\n * Loads all events from the events router and registers them with Discord.js client.\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 /**\n * Unregisters all event listeners and clears loaded events.\n */\n public unregisterAll() {\n this.unregisterAllClientListeners();\n this.loadedEvents.clear();\n }\n\n /**\n * Registers all loaded events with the Discord.js client and CommandKit event system.\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 variables: new Map(),\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 (isErrorType(e, CommandKitErrorCodes.StopEvents)) {\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 variables: new Map(),\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 (isErrorType(e, CommandKitErrorCodes.StopEvents)) {\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 /**\n * Unregisters all client event listeners and cleans up loaded events.\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';\nimport { COMMANDKIT_CWD } from '../utils/constants';\n\nconst CONFIG_FILE_NAMES = [\n 'commandkit.config.js',\n 'commandkit.config.mjs',\n 'commandkit.config.cjs',\n 'commandkit.config.ts',\n];\n\n/**\n * Returns an array of possible configuration file paths based on the provided root directory.\n * @param root The root directory to search for configuration files.\n * @returns The array of possible configuration file paths.\n * @private\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 = COMMANDKIT_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\n/**\n * Represents HMR inter-process communication messages.\n */\nexport interface IpcMessageCommand {\n /**\n * The type of HMR event being communicated.\n */\n event: HMREventType;\n /**\n * The path associated with the HMR event.\n */\n path: string;\n /**\n * An optional identifier for the HMR event, used for acknowledgment.\n */\n id?: string;\n}\n\n/**\n * Represents an HMR event in CommandKit.\n */\nexport interface CommandKitHMREvent {\n /**\n * The type of HMR event.\n */\n event: HMREventType;\n /**\n * The path associated with the HMR event.\n */\n path: string;\n /**\n * Accepts the HMR event, indicating that it has been handled.\n * This prevents further processing of the event.\n */\n accept: () => void;\n /**\n * Prevents the default action for the HMR event.\n * This can be used to stop further processing of the event.\n */\n preventDefault: () => void;\n}\n\n/**\n * Registers development hooks for CommandKit to handle HMR (Hot Module Replacement) events.\n * @param commandkit - The CommandKit instance to register hooks for.\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 { getEventWorkerContext } from '../app/events/EventWorkerContext';\nimport { getContext } from '../context/async-context';\nimport { DO_NOT_TRACK_KEY } from './constants';\n\n/**\n * @private\n * @internal\n */\nfunction getVariableStore() {\n const ctx = getContext();\n\n if (!ctx) {\n try {\n const eventContext = getEventWorkerContext();\n return eventContext.variables;\n } catch {\n return null;\n }\n }\n\n return ctx.variables;\n}\n\n/**\n * @private\n * @internal\n */\nexport function getDoNotTrack() {\n const variables = getVariableStore();\n return variables?.get(DO_NOT_TRACK_KEY) === true;\n}\n\n/**\n * Signals commandkit to not track further analytics events within current context.\n * This is useful for scenarios where you want to disable analytics tracking\n * for a specific command or operation, such as during testing or when the user opts out.\n * @example import { noAnalytics } from 'commandkit/analytics';\n *\n * // inside commandkit context\n * noAnalytics();\n */\nexport function noAnalytics() {\n const variables = getVariableStore();\n\n if (!variables) {\n throw new Error('noAnalytics may only be used inside commandkit context');\n }\n\n variables.set(DO_NOT_TRACK_KEY, true);\n}\n","import { CommandKit } from '../commandkit';\nimport { Logger } from '../logger/Logger';\nimport { warnUnstable } from '../utils/warn-unstable';\nimport {\n AnalyticsEvent,\n AnalyticsProvider,\n IdentifyEvent,\n} from './analytics-provider';\nimport { getDoNotTrack } from './utils';\n\n/**\n * Filter function type for analytics events.\n * @param engine The analytics engine instance.\n * @param event The analytics event to filter.\n * @returns A boolean indicating whether the event should be tracked.\n */\nexport type FilterFunction = (\n engine: AnalyticsEngine,\n event: AnalyticsEvent,\n) => boolean;\n\n/**\n * AnalyticsEngine class for managing analytics providers and tracking events.\n * This class allows you to register a provider, set a filter for events, and track or identify events.\n */\nexport class AnalyticsEngine {\n #provider: AnalyticsProvider | null = null;\n #filter: FilterFunction | null = null;\n\n /**\n * Creates an instance of the AnalyticsEngine.\n * @param commandkit The CommandKit instance.\n */\n public constructor(public readonly commandkit: CommandKit) {}\n\n /**\n * Sets a filter function for analytics events.\n * This function will be called before tracking an event to determine if it should be tracked.\n * If the filter returns `false`, the event will not be tracked.\n * If the filter is set to `null`, all events will be tracked unless `doNotTrack` is enabled.\n * @param filter The filter function to set, or `null` to remove the filter.\n */\n public setFilter(filter: FilterFunction | null) {\n this.#filter = filter;\n }\n\n /**\n * Registers an analytics provider.\n * This provider will be used to track and identify events.\n * If a provider is already registered, it will be replaced with the new one.\n * @param provider The analytics provider to register.\n */\n public registerProvider(provider: AnalyticsProvider) {\n this.#provider = provider;\n }\n\n /**\n * Removes the currently registered analytics provider.\n * @param provider The analytics provider to remove.\n */\n public removeProvider(provider: AnalyticsProvider) {\n if (this.#provider === provider) {\n this.#provider = null;\n }\n }\n\n /**\n * Retrieves the currently registered analytics provider.\n * @returns The currently registered analytics provider, or `null` if no provider is registered.\n */\n public getProvider(): AnalyticsProvider | null {\n return this.#provider;\n }\n\n /**\n * Identifies a user with the analytics provider.\n * This method sends an identify event to the provider, which can be used to associate user data with events.\n * @param event The identify event containing user data to send to the provider.\n */\n public async identify(event: IdentifyEvent) {\n if (!this.#provider) return;\n\n try {\n await this.#provider!.identify?.(this, event);\n } catch (error) {\n Logger.error(\n `Error identifying with provider ${this.#provider!.name}`,\n error,\n );\n }\n }\n\n /**\n * Tracks an analytics event with the registered provider.\n * This method sends the event to the provider, which can then process it as needed.\n * If the `doNotTrack` setting is enabled or if the filter function returns `false`, the event will not be tracked.\n * @param event The analytics event to track.\n */\n public async track(event: AnalyticsEvent) {\n if (!this.#provider) return;\n try {\n if (await this.#doNotTrack(event)) return;\n await this.#provider!.track(this, event);\n } catch (error) {\n Logger.error(\n `Error tracking ${event.name} event with provider ${this.#provider!.name}`,\n error,\n );\n }\n }\n\n async #doNotTrack(event: AnalyticsEvent): Promise<boolean> {\n const dnt = getDoNotTrack();\n\n if (dnt) return true;\n\n if (this.#filter) {\n return !this.#filter(this, event);\n }\n\n return false;\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';\nimport { AnalyticsEngine } from './analytics/analytics-engine';\nimport { ResolvedCommandKitConfig } from './config/utils';\nimport { getConfig } from './config/config';\n\n/**\n * Configurations for the CommandKit instance.\n */\nexport interface CommandKitConfiguration {\n /**\n * The default locale for the CommandKit instance. This will be used to infer the locale of the guild or user if it has not been set explicitly.\n * @default Locale.EnglishUS\n */\n defaultLocale: Locale;\n /**\n * A function that returns the command prefix for a given message.\n * This is used to determine how to parse commands from messages.\n * @param message The message to get the command prefix for.\n * @returns The command prefix or an array of prefixes.\n */\n getMessageCommandPrefix: (message: Message) => Awaitable<string | string[]>;\n}\n\n/**\n * Represents the function executed during the bootstrap phase of CommandKit.\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 dependencies 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\n/**\n * The commandkit class that serves as the main entry point for the CommandKit framework.\n */\nexport class CommandKit extends EventEmitter {\n #started = false;\n #clientProxy: SimpleProxy<Client> | null = createProxy({} as Client);\n #client!: Client;\n /**\n * The event interceptor to quickly register temporary event listeners\n */\n public eventInterceptor!: EventInterceptor;\n\n /**\n * The static createElement function to create jsx elements\n */\n public static readonly createElement = createElement;\n /**\n * The static Fragment component to create jsx fragments\n */\n public static readonly Fragment = Fragment;\n\n /**\n * The configuration for the CommandKit instance.\n */\n public readonly appConfig: CommandKitConfiguration = {\n defaultLocale: Locale.EnglishUS,\n getMessageCommandPrefix: () => '!',\n };\n\n /**\n * The configuration for the CommandKit environment.\n */\n public config: ResolvedCommandKitConfig = getConfig();\n\n /**\n * A key-value store for storing arbitrary data.\n */\n public readonly store = new Map<string, any>();\n /**\n * A flag store for storing flags that can be used to enable or disable features.\n */\n public readonly flags = new FlagStore();\n\n /**\n * The command router for the CommandKit instance.\n */\n public commandsRouter!: CommandsRouter;\n /**\n * The events router for the CommandKit instance.\n */\n public eventsRouter!: EventsRouter;\n /**\n * The command handler for the CommandKit instance.\n * This is responsible for handling commands and their execution.\n */\n public commandHandler!: AppCommandHandler;\n /**\n * The event handler for the CommandKit instance.\n * This is responsible for handling events and their execution.\n */\n public eventHandler!: AppEventsHandler;\n /**\n * The plugins runtime for the CommandKit instance.\n */\n public plugins!: CommandKitPluginRuntime;\n /**\n * The events channel for the CommandKit instance. This can be used to emit custom events.\n */\n public events!: CommandKitEventsChannel;\n /**\n * The analytics engine for the CommandKit instance.\n * This is responsible for tracking events and user interactions.\n */\n public analytics!: AnalyticsEngine;\n\n /**\n * The static instance of CommandKit.\n */\n static instance: CommandKit | undefined = undefined;\n\n /**\n * Create a new command and event handler with CommandKit.\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 // lazily load the actual config file\n loadConfigFile().then((config) => (this.config = config));\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 this.analytics = new AnalyticsEngine(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.appConfig.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.appConfig.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 /**\n * Get the path to the commands or events directory.\n * @param to The type of path to get, either 'commands' or 'events'.\n * @returns The path to the commands or events directory\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\n/**\n * The singleton instance of CommandKit.\n */\nexport const commandkit = CommandKit.instance || new CommandKit();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,iBAAiB,OAAO;AAC9B,MAAM,UAAU,IAAI;;;;;;AAYpB,SAAgB,uBAChB,QACkC;AAChC,QAAO,UAAU,QAAQ,IAAI,QAAQ,oBAAoB;AAC3D;AAWA,SAAgB,YAAe,IAAgB;AAC7C,QAAO,QAAQ,KAAK;AACtB;;;;;;;AAQA,SAAgB,eAChB,OACA,UACI;AACF,SAAQ,IAAI,OAAO,gBAAgB;AACnC,QAAO,QAAQ,IAAI,OAAO;AAC5B;;;;;;;;AASA,SAAgB,yBAGhB,KAA4B,IAAO,WAAkB;CACnD,MAAM,OAAO,GAAG,SAAgB;AAC9B,SAAO,eAAe,KAAK,YAAY;AACrC,OAAI;IAEF,MAAM,SAAS,MAAM,GAAG,GAAG;AAE3B,WAAO;GACR,SAAQ,GAAG;AACV,QAAI,CAAC,sCAAkB,GACrB,KAAI,kBAAkB;GAEzB,UAAS;AACR,QAAI,OAAO,cAAc,WAEvB,cAAa,YAAY;AACvB,SAAI;AACF,YAAM,UAAU,GAAG;KACpB,QAAO,CAGR;IAAA;GAEN;EACD;CACF;AAED,QAAO;AACT;AAUA,SAAgB,cAAc,SAAS,OAA+B;;CACpE,MAAM,4BAAM,QAAQ,kFAAY,eAAc,WAAW;AAEzD,KAAI,CAAC,OAAO,OACV,OAAM,IAAI,MAAM;AAGlB,QAAO;AACT;;;;;AAMA,SAAgB,aAAgD;CAC9D,MAAM,MAAM,QAAQ;AACpB,QAAO;AACT;;;;AAKA,SAAgB,iBAAwC;CACtD,MAAM,MAAM,QAAQ;AACpB,KAAI,CAAC,IACH,OAAM,IAAI,MACR;AAIJ,QAAO;AACT;;;;;;;ACnEA,IAAa,YAAb,cAA+B,yBAAc;CAC3C,kBACA;CACA,eACA;EACE,WAAW;EACX,MAAM,M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