commandkit 0.1.11-dev.20250104132107 → 0.1.11-dev.20250112073408

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 (176) hide show
  1. package/bin/build.mjs +4 -0
  2. package/bin/development.mjs +3 -0
  3. package/bin/esbuild-plugins/use-cache.mjs +176 -0
  4. package/dist/{CommandKit-B6vQXLAL.d.mts → CommandKit-B3EDajLJ.d.mts} +29 -1
  5. package/dist/{CommandKit-BNAI1XIg.d.ts → CommandKit-BO77LFI2.d.ts} +29 -1
  6. package/dist/CommandKit.d.mts +3 -1
  7. package/dist/CommandKit.d.ts +3 -1
  8. package/dist/CommandKit.js +2 -2
  9. package/dist/CommandKit.js.map +1 -1
  10. package/dist/CommandKit.mjs +1 -1
  11. package/dist/async-context-C5FJOAIU.d.mts +142 -0
  12. package/dist/async-context-DnJSN785.d.ts +142 -0
  13. package/dist/cache/CacheProvider.d.mts +15 -0
  14. package/dist/cache/CacheProvider.d.ts +15 -0
  15. package/dist/cache/CacheProvider.js +2 -0
  16. package/dist/cache/CacheProvider.js.map +1 -0
  17. package/dist/cache/CacheProvider.mjs +2 -0
  18. package/dist/cache/MemoryCache.d.mts +13 -0
  19. package/dist/cache/MemoryCache.d.ts +13 -0
  20. package/dist/cache/MemoryCache.js +2 -0
  21. package/dist/cache/MemoryCache.js.map +1 -0
  22. package/dist/cache/MemoryCache.mjs +2 -0
  23. package/dist/cache/index.d.mts +49 -0
  24. package/dist/cache/index.d.ts +49 -0
  25. package/dist/cache/index.js +11 -0
  26. package/dist/cache/index.js.map +1 -0
  27. package/dist/cache/index.mjs +2 -0
  28. package/dist/cache/index.mjs.map +1 -0
  29. package/dist/chunk-47FOQCN7.mjs +2 -0
  30. package/dist/chunk-47FOQCN7.mjs.map +1 -0
  31. package/dist/{chunk-D7RDGUPK.mjs → chunk-4CG7S6RY.mjs} +2 -2
  32. package/dist/{chunk-J3ZMR7KK.mjs → chunk-4OV4GE7B.mjs} +2 -2
  33. package/dist/{chunk-UXQFRVAB.mjs → chunk-6AX5YJEO.mjs} +2 -2
  34. package/dist/{chunk-JFCJXIOI.mjs → chunk-6BSP7AD3.mjs} +2 -2
  35. package/dist/{chunk-7KD7ZCH6.mjs → chunk-6TIBWNPX.mjs} +1 -1
  36. package/dist/chunk-6TIBWNPX.mjs.map +1 -0
  37. package/dist/chunk-6TIGKCSX.mjs +2 -0
  38. package/dist/{chunk-GS3Q7VW7.mjs → chunk-6W2KY7FK.mjs} +2 -2
  39. package/dist/chunk-BKPSH6EL.mjs +2 -0
  40. package/dist/chunk-BKPSH6EL.mjs.map +1 -0
  41. package/dist/chunk-C6WU57FQ.mjs +2 -0
  42. package/dist/{chunk-ZE7AC2HG.mjs.map → chunk-C6WU57FQ.mjs.map} +1 -1
  43. package/dist/chunk-CKNUFVNV.mjs +2 -0
  44. package/dist/chunk-CKNUFVNV.mjs.map +1 -0
  45. package/dist/{chunk-YSVQ45EN.mjs → chunk-DW5KRS5H.mjs} +2 -2
  46. package/dist/chunk-GSYRGHXQ.mjs +2 -0
  47. package/dist/chunk-GSYRGHXQ.mjs.map +1 -0
  48. package/dist/{chunk-SFWUUQXC.mjs → chunk-K43A7OIY.mjs} +2 -2
  49. package/dist/chunk-MVPNDXHU.mjs +2 -0
  50. package/dist/chunk-MVPNDXHU.mjs.map +1 -0
  51. package/dist/chunk-Q7VUO3A3.mjs +2 -0
  52. package/dist/chunk-Q7VUO3A3.mjs.map +1 -0
  53. package/dist/{chunk-E2KEPOOS.mjs → chunk-RGQOLRR6.mjs} +2 -2
  54. package/dist/chunk-TZ77YGTD.mjs +2 -0
  55. package/dist/chunk-TZ77YGTD.mjs.map +1 -0
  56. package/dist/{chunk-4IWEG3WI.mjs → chunk-WNEBLBID.mjs} +2 -2
  57. package/dist/{chunk-4IWEG3WI.mjs.map → chunk-WNEBLBID.mjs.map} +1 -1
  58. package/dist/{chunk-I2MRY4KL.mjs → chunk-XJCWZEWC.mjs} +2 -2
  59. package/dist/{chunk-4U6VHAPY.mjs → chunk-Z4FBPRS6.mjs} +2 -2
  60. package/dist/components/ButtonKit.js +1 -1
  61. package/dist/components/ButtonKit.js.map +1 -1
  62. package/dist/components/ButtonKit.mjs +1 -1
  63. package/dist/components/index.js +1 -1
  64. package/dist/components/index.js.map +1 -1
  65. package/dist/components/index.mjs +1 -1
  66. package/dist/config.mjs +1 -1
  67. package/dist/context/async-context.d.mts +7 -0
  68. package/dist/context/async-context.d.ts +7 -0
  69. package/dist/context/async-context.js +11 -0
  70. package/dist/context/async-context.js.map +1 -0
  71. package/dist/context/async-context.mjs +2 -0
  72. package/dist/context/async-context.mjs.map +1 -0
  73. package/dist/context/environment.d.mts +7 -0
  74. package/dist/context/environment.d.ts +7 -0
  75. package/dist/context/environment.js +2 -0
  76. package/dist/context/environment.js.map +1 -0
  77. package/dist/context/environment.mjs +2 -0
  78. package/dist/context/environment.mjs.map +1 -0
  79. package/dist/handlers/command-handler/CommandHandler.d.mts +3 -1
  80. package/dist/handlers/command-handler/CommandHandler.d.ts +3 -1
  81. package/dist/handlers/command-handler/CommandHandler.js +2 -2
  82. package/dist/handlers/command-handler/CommandHandler.js.map +1 -1
  83. package/dist/handlers/command-handler/CommandHandler.mjs +1 -1
  84. package/dist/handlers/command-handler/functions/loadCommandsWithRest.d.mts +3 -1
  85. package/dist/handlers/command-handler/functions/loadCommandsWithRest.d.ts +3 -1
  86. package/dist/handlers/command-handler/functions/loadCommandsWithRest.js +1 -1
  87. package/dist/handlers/command-handler/functions/loadCommandsWithRest.js.map +1 -1
  88. package/dist/handlers/command-handler/functions/loadCommandsWithRest.mjs +1 -1
  89. package/dist/handlers/command-handler/functions/registerCommands.d.mts +3 -1
  90. package/dist/handlers/command-handler/functions/registerCommands.d.ts +3 -1
  91. package/dist/handlers/command-handler/functions/registerCommands.js +1 -1
  92. package/dist/handlers/command-handler/functions/registerCommands.js.map +1 -1
  93. package/dist/handlers/command-handler/functions/registerCommands.mjs +1 -1
  94. package/dist/handlers/command-handler/typings.d.mts +3 -1
  95. package/dist/handlers/command-handler/typings.d.ts +3 -1
  96. package/dist/handlers/command-handler/utils/areSlashCommandsDifferent.mjs +1 -1
  97. package/dist/handlers/command-handler/validations/devOnly.d.mts +3 -1
  98. package/dist/handlers/command-handler/validations/devOnly.d.ts +3 -1
  99. package/dist/handlers/command-handler/validations/devOnly.mjs +1 -1
  100. package/dist/handlers/command-handler/validations/index.d.mts +3 -1
  101. package/dist/handlers/command-handler/validations/index.d.ts +3 -1
  102. package/dist/handlers/command-handler/validations/index.mjs +1 -1
  103. package/dist/handlers/command-handler/validations/permissions.d.mts +3 -1
  104. package/dist/handlers/command-handler/validations/permissions.d.ts +3 -1
  105. package/dist/handlers/command-handler/validations/permissions.mjs +1 -1
  106. package/dist/handlers/event-handler/EventHandler.d.mts +3 -1
  107. package/dist/handlers/event-handler/EventHandler.d.ts +3 -1
  108. package/dist/handlers/event-handler/EventHandler.js +1 -1
  109. package/dist/handlers/event-handler/EventHandler.js.map +1 -1
  110. package/dist/handlers/event-handler/EventHandler.mjs +1 -1
  111. package/dist/handlers/event-handler/typings.d.mts +3 -1
  112. package/dist/handlers/event-handler/typings.d.ts +3 -1
  113. package/dist/handlers/index.d.mts +3 -1
  114. package/dist/handlers/index.d.ts +3 -1
  115. package/dist/handlers/index.js +2 -2
  116. package/dist/handlers/index.js.map +1 -1
  117. package/dist/handlers/index.mjs +1 -1
  118. package/dist/handlers/validation-handler/ValidationHandler.js +1 -1
  119. package/dist/handlers/validation-handler/ValidationHandler.js.map +1 -1
  120. package/dist/handlers/validation-handler/ValidationHandler.mjs +1 -1
  121. package/dist/index.d.mts +6 -1
  122. package/dist/index.d.ts +6 -1
  123. package/dist/index.js +2 -2
  124. package/dist/index.js.map +1 -1
  125. package/dist/index.mjs +1 -1
  126. package/dist/index.mjs.map +1 -1
  127. package/dist/types.d.mts +3 -1
  128. package/dist/types.d.ts +3 -1
  129. package/dist/types.js.map +1 -1
  130. package/dist/types.mjs +1 -1
  131. package/dist/types.mjs.map +1 -1
  132. package/dist/utils/clone.mjs +1 -1
  133. package/dist/utils/colors.js +1 -1
  134. package/dist/utils/colors.js.map +1 -1
  135. package/dist/utils/colors.mjs +1 -1
  136. package/dist/utils/constants.d.mts +3 -0
  137. package/dist/utils/constants.d.ts +3 -0
  138. package/dist/utils/constants.js +2 -0
  139. package/dist/utils/constants.js.map +1 -0
  140. package/dist/utils/constants.mjs +2 -0
  141. package/dist/utils/constants.mjs.map +1 -0
  142. package/dist/utils/error-codes.d.mts +9 -0
  143. package/dist/utils/error-codes.d.ts +9 -0
  144. package/dist/utils/error-codes.js +2 -0
  145. package/dist/utils/error-codes.js.map +1 -0
  146. package/dist/utils/error-codes.mjs +2 -0
  147. package/dist/utils/error-codes.mjs.map +1 -0
  148. package/dist/utils/get-paths.mjs +1 -1
  149. package/dist/utils/resolve-file-url.mjs +1 -1
  150. package/dist/utils/warn-unstable.d.mts +3 -0
  151. package/dist/utils/warn-unstable.d.ts +3 -0
  152. package/dist/utils/warn-unstable.js +2 -0
  153. package/dist/utils/warn-unstable.js.map +1 -0
  154. package/dist/utils/warn-unstable.mjs +2 -0
  155. package/dist/utils/warn-unstable.mjs.map +1 -0
  156. package/package.json +6 -2
  157. package/dist/chunk-FXJNQE5B.mjs +0 -2
  158. package/dist/chunk-FXJNQE5B.mjs.map +0 -1
  159. package/dist/chunk-IHC5YX2R.mjs +0 -2
  160. package/dist/chunk-IHC5YX2R.mjs.map +0 -1
  161. package/dist/chunk-PFU3PH6M.mjs +0 -1
  162. package/dist/chunk-YZT2CEWE.mjs +0 -2
  163. package/dist/chunk-ZE7AC2HG.mjs +0 -2
  164. /package/dist/{chunk-7KD7ZCH6.mjs.map → cache/CacheProvider.mjs.map} +0 -0
  165. /package/dist/{chunk-PFU3PH6M.mjs.map → cache/MemoryCache.mjs.map} +0 -0
  166. /package/dist/{chunk-D7RDGUPK.mjs.map → chunk-4CG7S6RY.mjs.map} +0 -0
  167. /package/dist/{chunk-J3ZMR7KK.mjs.map → chunk-4OV4GE7B.mjs.map} +0 -0
  168. /package/dist/{chunk-UXQFRVAB.mjs.map → chunk-6AX5YJEO.mjs.map} +0 -0
  169. /package/dist/{chunk-JFCJXIOI.mjs.map → chunk-6BSP7AD3.mjs.map} +0 -0
  170. /package/dist/{chunk-YZT2CEWE.mjs.map → chunk-6TIGKCSX.mjs.map} +0 -0
  171. /package/dist/{chunk-GS3Q7VW7.mjs.map → chunk-6W2KY7FK.mjs.map} +0 -0
  172. /package/dist/{chunk-YSVQ45EN.mjs.map → chunk-DW5KRS5H.mjs.map} +0 -0
  173. /package/dist/{chunk-SFWUUQXC.mjs.map → chunk-K43A7OIY.mjs.map} +0 -0
  174. /package/dist/{chunk-E2KEPOOS.mjs.map → chunk-RGQOLRR6.mjs.map} +0 -0
  175. /package/dist/{chunk-I2MRY4KL.mjs.map → chunk-XJCWZEWC.mjs.map} +0 -0
  176. /package/dist/{chunk-4U6VHAPY.mjs.map → chunk-Z4FBPRS6.mjs.map} +0 -0
package/bin/build.mjs CHANGED
@@ -11,6 +11,8 @@ import {
11
11
  write,
12
12
  } from './common.mjs';
13
13
  import ora from 'ora';
14
+ import { esbuildPluginUseMacro } from 'use-macro';
15
+ import { cacheDirectivePlugin } from './esbuild-plugins/use-cache.mjs';
14
16
 
15
17
  export async function bootstrapProductionBuild(config) {
16
18
  const {
@@ -44,7 +46,9 @@ export async function bootstrapProductionBuild(config) {
44
46
  outDir,
45
47
  silent: true,
46
48
  watch: false,
49
+ cjsInterop: true,
47
50
  entry: [src, '!dist', '!.commandkit', `!${outDir}`],
51
+ esbuildPlugins: [cacheDirectivePlugin()],
48
52
  });
49
53
 
50
54
  await injectShims(outDir, main, antiCrash, polyfillRequire);
@@ -13,6 +13,7 @@ import { parseEnv } from './parse-env.mjs';
13
13
  import child_process from 'node:child_process';
14
14
  import ora from 'ora';
15
15
  import { injectShims } from './build.mjs';
16
+ import { cacheDirectivePlugin } from './esbuild-plugins/use-cache.mjs';
16
17
 
17
18
  const RESTARTING_MSG_PATTERN = /^Restarting '|".+'|"\n?$/;
18
19
  const FAILED_RUNNING_PATTERN = /^Failed running '.+'|"\n?$/;
@@ -69,9 +70,11 @@ export async function bootstrapDevelopmentServer(opts) {
69
70
  silent: true,
70
71
  entry: [src, '!dist', '!.commandkit', `!${outDir}`].filter(Boolean),
71
72
  watch: watchMode,
73
+ cjsInterop: true,
72
74
  async onSuccess() {
73
75
  return await injectShims('.commandkit', main, false, requirePolyfill);
74
76
  },
77
+ esbuildPlugins: [cacheDirectivePlugin()],
75
78
  });
76
79
 
77
80
  status.succeed(
@@ -0,0 +1,176 @@
1
+ import * as parser from '@babel/parser';
2
+ import _traverse from '@babel/traverse';
3
+ import _generate from '@babel/generator';
4
+ import * as t from '@babel/types';
5
+
6
+ const traverse = _traverse.default || _traverse;
7
+ const generate = _generate.default || _generate;
8
+
9
+ const IMPORT_PATH = 'commandkit';
10
+ const DIRECTIVE = 'use cache';
11
+ const CACHE_IDENTIFIER = 'unstable_cache';
12
+
13
+ const generateRandomString = (length = 6) => {
14
+ const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
15
+ return Array.from(
16
+ { length },
17
+ () => chars[Math.floor(Math.random() * chars.length)],
18
+ ).join('');
19
+ };
20
+
21
+ export const cacheDirectivePlugin = () => {
22
+ return {
23
+ name: 'cache-directive',
24
+ setup(build) {
25
+ const fileFilter = /\.(c|m)?(t|j)sx?$/;
26
+
27
+ build.onLoad({ filter: fileFilter }, async (args) => {
28
+ const { readFile } = await import('fs/promises');
29
+ const source = await readFile(args.path, 'utf8');
30
+
31
+ const ast = parser.parse(source, {
32
+ sourceType: 'module',
33
+ plugins: ['typescript', 'jsx'],
34
+ });
35
+
36
+ let state = {
37
+ needsImport: false,
38
+ hasExistingImport: false,
39
+ cacheIdentifierName: CACHE_IDENTIFIER,
40
+ modifications: [],
41
+ };
42
+
43
+ // First pass: check for naming collisions and collect modifications
44
+ traverse(ast, {
45
+ Program: {
46
+ enter(path) {
47
+ const binding = path.scope.getBinding(CACHE_IDENTIFIER);
48
+ if (binding) {
49
+ state.cacheIdentifierName = `cache_${generateRandomString()}`;
50
+ }
51
+ },
52
+ },
53
+
54
+ ImportDeclaration(path) {
55
+ if (
56
+ path.node.source.value === IMPORT_PATH &&
57
+ path.node.specifiers.some(
58
+ (spec) =>
59
+ t.isImportSpecifier(spec) &&
60
+ spec.imported.name === CACHE_IDENTIFIER,
61
+ )
62
+ ) {
63
+ state.hasExistingImport = true;
64
+ if (state.cacheIdentifierName !== CACHE_IDENTIFIER) {
65
+ state.modifications.push(() => {
66
+ path.node.specifiers.forEach((spec) => {
67
+ if (
68
+ t.isImportSpecifier(spec) &&
69
+ spec.imported.name === CACHE_IDENTIFIER
70
+ ) {
71
+ spec.local.name = state.cacheIdentifierName;
72
+ }
73
+ });
74
+ });
75
+ }
76
+ }
77
+ },
78
+
79
+ 'FunctionDeclaration|FunctionExpression|ArrowFunctionExpression'(
80
+ path,
81
+ ) {
82
+ const body = t.isBlockStatement(path.node.body)
83
+ ? path.node.body
84
+ : null;
85
+ const hasUseCache = body?.directives?.some(
86
+ (d) => d.value.value === DIRECTIVE,
87
+ );
88
+
89
+ if (!hasUseCache && !t.isBlockStatement(path.node.body)) {
90
+ const parentFunction = path.findParent(
91
+ (p) =>
92
+ (p.isFunction() || p.isProgram()) && 'directives' in p.node,
93
+ );
94
+ if (
95
+ !parentFunction?.node.directives?.some(
96
+ (d) => d.value.value === DIRECTIVE,
97
+ )
98
+ ) {
99
+ return;
100
+ }
101
+ }
102
+
103
+ if (hasUseCache || !t.isBlockStatement(path.node.body)) {
104
+ // Check if the function is async
105
+ if (!path.node.async) {
106
+ throw new Error(
107
+ `"${DIRECTIVE}" directive may only be used in async functions at ${args.path}`,
108
+ );
109
+ }
110
+
111
+ state.needsImport = true;
112
+ const isDeclaration = t.isFunctionDeclaration(path.node);
113
+ const name = isDeclaration ? path.node.id?.name : undefined;
114
+
115
+ // Create a new body without the 'use cache' directive
116
+ const newBody = t.isBlockStatement(path.node.body)
117
+ ? t.blockStatement(
118
+ path.node.body.body,
119
+ path.node.body.directives.filter(
120
+ (d) => d.value.value !== DIRECTIVE,
121
+ ),
122
+ )
123
+ : path.node.body;
124
+
125
+ const wrapped = t.callExpression(
126
+ t.identifier(state.cacheIdentifierName),
127
+ [t.arrowFunctionExpression(path.node.params, newBody, true)],
128
+ );
129
+
130
+ state.modifications.push(() => {
131
+ if (name) {
132
+ path.replaceWith(
133
+ t.variableDeclaration('const', [
134
+ t.variableDeclarator(t.identifier(name), wrapped),
135
+ ]),
136
+ );
137
+ } else if (!t.isVariableDeclarator(path.parent)) {
138
+ path.replaceWith(wrapped);
139
+ } else {
140
+ path.parent.init = wrapped;
141
+ }
142
+ });
143
+ }
144
+ },
145
+ });
146
+
147
+ // Apply all collected modifications
148
+ if (state.modifications.length > 0) {
149
+ // Add import if needed
150
+ if (state.needsImport && !state.hasExistingImport) {
151
+ ast.program.body.unshift(
152
+ t.importDeclaration(
153
+ [
154
+ t.importSpecifier(
155
+ t.identifier(state.cacheIdentifierName),
156
+ t.identifier(CACHE_IDENTIFIER),
157
+ ),
158
+ ],
159
+ t.stringLiteral(IMPORT_PATH),
160
+ ),
161
+ );
162
+ }
163
+
164
+ // Apply collected modifications
165
+ state.modifications.forEach((modify) => modify());
166
+ }
167
+
168
+ const { code } = generate(ast);
169
+ return {
170
+ contents: code,
171
+ loader: args.path.split('.').pop(),
172
+ };
173
+ });
174
+ },
175
+ };
176
+ };
@@ -1,6 +1,8 @@
1
1
  import { ValidationHandler } from './handlers/validation-handler/ValidationHandler.mjs';
2
2
  import * as discord_js from 'discord.js';
3
3
  import { Client, Interaction, CacheType, ChatInputCommandInteraction, ContextMenuCommandInteraction, UserContextMenuCommandInteraction, MessageContextMenuCommandInteraction, AutocompleteInteraction, PermissionsString, RESTPostAPIApplicationCommandsJSONBody } from 'discord.js';
4
+ import EventEmitter from 'node:events';
5
+ import { CacheProvider } from './cache/CacheProvider.mjs';
4
6
 
5
7
  /**
6
8
  * Options for instantiating a CommandKit handler.
@@ -42,6 +44,15 @@ interface CommandKitOptions {
42
44
  * Bulk register application commands instead of one-by-one.
43
45
  */
44
46
  bulkRegister?: boolean;
47
+ /**
48
+ * Whether or not to debug the command handler.
49
+ */
50
+ debugCommands?: boolean;
51
+ /**
52
+ * The cache provider to use with CommandKit. Defaults to MemoryCache provider.
53
+ * Set this to `null` to not use any cache provider.
54
+ */
55
+ cacheProvider?: CacheProvider | null;
45
56
  }
46
57
  /**
47
58
  * Private data for the CommandKit class.
@@ -373,8 +384,9 @@ declare class EventHandler {
373
384
  reloadEvents(commandHandler?: CommandHandler): Promise<void>;
374
385
  }
375
386
 
376
- declare class CommandKit {
387
+ declare class CommandKit extends EventEmitter {
377
388
  #private;
389
+ static instance: CommandKit | undefined;
378
390
  /**
379
391
  * Create a new command and event handler with CommandKit.
380
392
  *
@@ -382,6 +394,14 @@ declare class CommandKit {
382
394
  * @see {@link https://commandkit.dev/guide/commandkit-setup}
383
395
  */
384
396
  constructor(options: CommandKitOptions);
397
+ /**
398
+ * Resolves the current cache provider.
399
+ */
400
+ getCacheProvider(): CacheProvider | null;
401
+ /**
402
+ * Whether or not to debug the command handler.
403
+ */
404
+ isDebuggingCommands(): boolean;
385
405
  /**
386
406
  * Get the client attached to this CommandKit instance.
387
407
  */
@@ -430,6 +450,14 @@ declare class CommandKit {
430
450
  * @returns An array of all the developer role IDs which was set when instantiating CommandKit.
431
451
  */
432
452
  get devRoleIds(): string[];
453
+ /**
454
+ * Increment the client listeners count.
455
+ */
456
+ incrementClientListenersCount(): void;
457
+ /**
458
+ * Decrement the client listeners count.
459
+ */
460
+ decrementClientListenersCount(): void;
433
461
  }
434
462
 
435
463
  export { type AutocompleteProps as A, type BuiltInValidationParams as B, CommandKit as C, type EventHandlerOptions as E, type MessageContextMenuCommandProps as M, type ReloadOptions as R, type SlashCommandProps as S, type UserContextMenuCommandProps as U, type ValidationProps as V, type CommandKitOptions as a, type CommandKitData as b, type CommandContext as c, type CommandFileObject as d, type CommandProps as e, type ContextMenuCommandProps as f, type CommandOptions as g, type CommandData as h, type CommandObject as i, ReloadType as j, type CommandHandlerOptions as k, type CommandHandlerData as l, type CommandKitInteraction as m, type BuiltInValidation as n, type hCommandContext as o, CommandHandler as p, type EventHandlerData as q, EventHandler as r };
@@ -1,6 +1,8 @@
1
1
  import { ValidationHandler } from './handlers/validation-handler/ValidationHandler.js';
2
2
  import * as discord_js from 'discord.js';
3
3
  import { Client, Interaction, CacheType, ChatInputCommandInteraction, ContextMenuCommandInteraction, UserContextMenuCommandInteraction, MessageContextMenuCommandInteraction, AutocompleteInteraction, PermissionsString, RESTPostAPIApplicationCommandsJSONBody } from 'discord.js';
4
+ import EventEmitter from 'node:events';
5
+ import { CacheProvider } from './cache/CacheProvider.js';
4
6
 
5
7
  /**
6
8
  * Options for instantiating a CommandKit handler.
@@ -42,6 +44,15 @@ interface CommandKitOptions {
42
44
  * Bulk register application commands instead of one-by-one.
43
45
  */
44
46
  bulkRegister?: boolean;
47
+ /**
48
+ * Whether or not to debug the command handler.
49
+ */
50
+ debugCommands?: boolean;
51
+ /**
52
+ * The cache provider to use with CommandKit. Defaults to MemoryCache provider.
53
+ * Set this to `null` to not use any cache provider.
54
+ */
55
+ cacheProvider?: CacheProvider | null;
45
56
  }
46
57
  /**
47
58
  * Private data for the CommandKit class.
@@ -373,8 +384,9 @@ declare class EventHandler {
373
384
  reloadEvents(commandHandler?: CommandHandler): Promise<void>;
374
385
  }
375
386
 
376
- declare class CommandKit {
387
+ declare class CommandKit extends EventEmitter {
377
388
  #private;
389
+ static instance: CommandKit | undefined;
378
390
  /**
379
391
  * Create a new command and event handler with CommandKit.
380
392
  *
@@ -382,6 +394,14 @@ declare class CommandKit {
382
394
  * @see {@link https://commandkit.dev/guide/commandkit-setup}
383
395
  */
384
396
  constructor(options: CommandKitOptions);
397
+ /**
398
+ * Resolves the current cache provider.
399
+ */
400
+ getCacheProvider(): CacheProvider | null;
401
+ /**
402
+ * Whether or not to debug the command handler.
403
+ */
404
+ isDebuggingCommands(): boolean;
385
405
  /**
386
406
  * Get the client attached to this CommandKit instance.
387
407
  */
@@ -430,6 +450,14 @@ declare class CommandKit {
430
450
  * @returns An array of all the developer role IDs which was set when instantiating CommandKit.
431
451
  */
432
452
  get devRoleIds(): string[];
453
+ /**
454
+ * Increment the client listeners count.
455
+ */
456
+ incrementClientListenersCount(): void;
457
+ /**
458
+ * Decrement the client listeners count.
459
+ */
460
+ decrementClientListenersCount(): void;
433
461
  }
434
462
 
435
463
  export { type AutocompleteProps as A, type BuiltInValidationParams as B, CommandKit as C, type EventHandlerOptions as E, type MessageContextMenuCommandProps as M, type ReloadOptions as R, type SlashCommandProps as S, type UserContextMenuCommandProps as U, type ValidationProps as V, type CommandKitOptions as a, type CommandKitData as b, type CommandContext as c, type CommandFileObject as d, type CommandProps as e, type ContextMenuCommandProps as f, type CommandOptions as g, type CommandData as h, type CommandObject as i, ReloadType as j, type CommandHandlerOptions as k, type CommandHandlerData as l, type CommandKitInteraction as m, type BuiltInValidation as n, type hCommandContext as o, CommandHandler as p, type EventHandlerData as q, EventHandler as r };
@@ -1,4 +1,6 @@
1
1
  import 'discord.js';
2
- export { C as CommandKit } from './CommandKit-B6vQXLAL.mjs';
2
+ import 'node:events';
3
+ export { C as CommandKit } from './CommandKit-B3EDajLJ.mjs';
4
+ import './cache/CacheProvider.mjs';
3
5
  import './handlers/validation-handler/ValidationHandler.mjs';
4
6
  import './handlers/validation-handler/typings.mjs';
@@ -1,4 +1,6 @@
1
1
  import 'discord.js';
2
- export { C as CommandKit } from './CommandKit-BNAI1XIg.js';
2
+ import 'node:events';
3
+ export { C as CommandKit } from './CommandKit-BO77LFI2.js';
4
+ import './cache/CacheProvider.js';
3
5
  import './handlers/validation-handler/ValidationHandler.js';
4
6
  import './handlers/validation-handler/typings.js';
@@ -1,4 +1,4 @@
1
- "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var CommandKit_exports={};__export(CommandKit_exports,{CommandKit:()=>CommandKit});module.exports=__toCommonJS(CommandKit_exports);var import_rfdc=__toESM(require("rfdc")),clone=(0,import_rfdc.default)();var resetColor="\x1B[0m",colors_default={reset:text=>`${text}${resetColor}`,bright:text=>`\x1B[1m${text}${resetColor}`,dim:text=>`\x1B[2m${text}${resetColor}`,underscore:text=>`\x1B[4m${text}${resetColor}`,blink:text=>`\x1B[5m${text}${resetColor}`,reverse:text=>`\x1B[7m${text}${resetColor}`,hidden:text=>`\x1B[8m${text}${resetColor}`,black:text=>`\x1B[30m${text}${resetColor}`,red:text=>`\x1B[31m${text}${resetColor}`,green:text=>`\x1B[32m${text}${resetColor}`,yellow:text=>`\x1B[33m${text}${resetColor}`,blue:text=>`\x1B[34m${text}${resetColor}`,magenta:text=>`\x1B[35m${text}${resetColor}`,cyan:text=>`\x1B[36m${text}${resetColor}`,white:text=>`\x1B[37m${text}${resetColor}`,bgBlack:text=>`\x1B[40m${text}${resetColor}`,bgRed:text=>`\x1B[41m${text}${resetColor}`,bgGreen:text=>`\x1B[42m${text}${resetColor}`,bgYellow:text=>`\x1B[43m${text}${resetColor}`,bgBlue:text=>`\x1B[44m${text}${resetColor}`,bgMagenta:text=>`\x1B[45m${text}${resetColor}`,bgCyan:text=>`\x1B[46m${text}${resetColor}`,bgWhite:text=>`\x1B[47m${text}${resetColor}`};var import_path=__toESM(require("path")),import_promises=__toESM(require("fs/promises"));async function getFilePaths(directory,nesting){let filePaths=[];if(!directory)return filePaths;let files=await import_promises.default.readdir(directory,{withFileTypes:!0});for(let file of files){let filePath=import_path.default.join(directory,file.name);file.isFile()&&filePaths.push(filePath),nesting&&file.isDirectory()&&(filePaths=[...filePaths,...await getFilePaths(filePath,!0)])}return filePaths}__name(getFilePaths,"getFilePaths");async function getFolderPaths(directory,nesting){let folderPaths=[];if(!directory)return folderPaths;let folders=await import_promises.default.readdir(directory,{withFileTypes:!0});for(let folder of folders){let folderPath=import_path.default.join(directory,folder.name);folder.isDirectory()&&(folderPaths.push(folderPath),nesting&&(folderPaths=[...folderPaths,...await getFolderPaths(folderPath,!0)]))}return folderPaths}__name(getFolderPaths,"getFolderPaths");var import_path2=__toESM(require("path"));function toFileURL(filePath){return"file://"+import_path2.default.resolve(filePath).replace(/\\\\|\\/g,"/")}__name(toFileURL,"toFileURL");async function loadCommandsWithRest(props){if(props.reloading)if(props.client.isReady())await handleLoading(props.client,props.commands,props.devGuildIds,props.reloading,props.type);else throw new Error(colors_default.red("Cannot reload commands when client is not ready."));else props.client.once("ready",async c=>{await handleLoading(c,props.commands,props.devGuildIds,props.reloading,props.type)})}__name(loadCommandsWithRest,"loadCommandsWithRest");async function handleLoading(client,commands,devGuildIds,reloading,type){commands=commands.filter(cmd=>!cmd.options?.deleted);let devOnlyCommands=commands.filter(cmd=>cmd.options?.devOnly),globalCommands=commands.filter(cmd=>!cmd.options?.devOnly);type==="dev"?await loadDevCommands(client,devOnlyCommands,devGuildIds,reloading):type==="global"?await loadGlobalCommands(client,globalCommands,reloading):(await loadDevCommands(client,devOnlyCommands,devGuildIds,reloading),await loadGlobalCommands(client,globalCommands,reloading))}__name(handleLoading,"handleLoading");async function loadGlobalCommands(client,commands,reloading){let requestBody=commands.map(cmd=>cmd.data);await client.application.commands.set(requestBody).catch(error=>{throw new Error(colors_default.red(`Error ${reloading?"reloading":"loading"} global application commands.
1
+ "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var CommandKit_exports={};__export(CommandKit_exports,{CommandKit:()=>CommandKit});module.exports=__toCommonJS(CommandKit_exports);var import_node_events=__toESM(require("events"));var import_rfdc=__toESM(require("rfdc")),clone=(0,import_rfdc.default)();var resetColor="\x1B[0m",colors_default={reset:__name(text=>`${text}${resetColor}`,"reset"),bright:__name(text=>`\x1B[1m${text}${resetColor}`,"bright"),dim:__name(text=>`\x1B[2m${text}${resetColor}`,"dim"),underscore:__name(text=>`\x1B[4m${text}${resetColor}`,"underscore"),blink:__name(text=>`\x1B[5m${text}${resetColor}`,"blink"),reverse:__name(text=>`\x1B[7m${text}${resetColor}`,"reverse"),hidden:__name(text=>`\x1B[8m${text}${resetColor}`,"hidden"),black:__name(text=>`\x1B[30m${text}${resetColor}`,"black"),red:__name(text=>`\x1B[31m${text}${resetColor}`,"red"),green:__name(text=>`\x1B[32m${text}${resetColor}`,"green"),yellow:__name(text=>`\x1B[33m${text}${resetColor}`,"yellow"),blue:__name(text=>`\x1B[34m${text}${resetColor}`,"blue"),magenta:__name(text=>`\x1B[35m${text}${resetColor}`,"magenta"),cyan:__name(text=>`\x1B[36m${text}${resetColor}`,"cyan"),white:__name(text=>`\x1B[37m${text}${resetColor}`,"white"),bgBlack:__name(text=>`\x1B[40m${text}${resetColor}`,"bgBlack"),bgRed:__name(text=>`\x1B[41m${text}${resetColor}`,"bgRed"),bgGreen:__name(text=>`\x1B[42m${text}${resetColor}`,"bgGreen"),bgYellow:__name(text=>`\x1B[43m${text}${resetColor}`,"bgYellow"),bgBlue:__name(text=>`\x1B[44m${text}${resetColor}`,"bgBlue"),bgMagenta:__name(text=>`\x1B[45m${text}${resetColor}`,"bgMagenta"),bgCyan:__name(text=>`\x1B[46m${text}${resetColor}`,"bgCyan"),bgWhite:__name(text=>`\x1B[47m${text}${resetColor}`,"bgWhite")};var import_path=__toESM(require("path")),import_promises=__toESM(require("fs/promises"));async function getFilePaths(directory,nesting){let filePaths=[];if(!directory)return filePaths;let files=await import_promises.default.readdir(directory,{withFileTypes:!0});for(let file of files){let filePath=import_path.default.join(directory,file.name);file.isFile()&&filePaths.push(filePath),nesting&&file.isDirectory()&&(filePaths=[...filePaths,...await getFilePaths(filePath,!0)])}return filePaths}__name(getFilePaths,"getFilePaths");async function getFolderPaths(directory,nesting){let folderPaths=[];if(!directory)return folderPaths;let folders=await import_promises.default.readdir(directory,{withFileTypes:!0});for(let folder of folders){let folderPath=import_path.default.join(directory,folder.name);folder.isDirectory()&&(folderPaths.push(folderPath),nesting&&(folderPaths=[...folderPaths,...await getFolderPaths(folderPath,!0)]))}return folderPaths}__name(getFolderPaths,"getFolderPaths");var import_path2=__toESM(require("path"));function toFileURL(filePath){return"file://"+import_path2.default.resolve(filePath).replace(/\\\\|\\/g,"/")}__name(toFileURL,"toFileURL");async function loadCommandsWithRest(props){if(props.reloading)if(props.client.isReady())await handleLoading(props.client,props.commands,props.devGuildIds,props.reloading,props.type);else throw new Error(colors_default.red("Cannot reload commands when client is not ready."));else props.client.once("ready",async c=>{await handleLoading(c,props.commands,props.devGuildIds,props.reloading,props.type)})}__name(loadCommandsWithRest,"loadCommandsWithRest");async function handleLoading(client,commands,devGuildIds,reloading,type){commands=commands.filter(cmd=>!cmd.options?.deleted);let devOnlyCommands=commands.filter(cmd=>cmd.options?.devOnly),globalCommands=commands.filter(cmd=>!cmd.options?.devOnly);type==="dev"?await loadDevCommands(client,devOnlyCommands,devGuildIds,reloading):type==="global"?await loadGlobalCommands(client,globalCommands,reloading):(await loadDevCommands(client,devOnlyCommands,devGuildIds,reloading),await loadGlobalCommands(client,globalCommands,reloading))}__name(handleLoading,"handleLoading");async function loadGlobalCommands(client,commands,reloading){let requestBody=commands.map(cmd=>cmd.data);await client.application.commands.set(requestBody).catch(error=>{throw new Error(colors_default.red(`Error ${reloading?"reloading":"loading"} global application commands.
2
2
  `),error)}),console.log(colors_default.green(`${reloading?"Reloaded":"Loaded"} ${requestBody.length} global commands.`))}__name(loadGlobalCommands,"loadGlobalCommands");async function loadDevCommands(client,commands,guildIds,reloading){let requestBody=commands.map(cmd=>cmd.data);for(let guildId of guildIds){let targetGuild=client.guilds.cache.get(guildId)||await client.guilds.fetch(guildId);if(!targetGuild){process.emitWarning(`Cannot ${reloading?"reload":"load"} commands in guild "${guildId}" - guild doesn't exist or client isn't part of the guild.`);continue}await targetGuild.commands.set(requestBody).catch(error=>{throw new Error(colors_default.red(`Error ${reloading?"reloading":"loading"} developer application commands in guild "${targetGuild?.name||guildId}".
3
3
  `),error)}),console.log(colors_default.green(`${reloading?"Reloaded":"Loaded"} ${requestBody.length} developer commands in guild "${targetGuild.name}".`))}}__name(loadDevCommands,"loadDevCommands");function areSlashCommandsDifferent(appCommand,localCommand){if(appCommand.options||(appCommand.options=[]),localCommand.options||(localCommand.options=[]),appCommand.description||(appCommand.description=""),localCommand.description||(localCommand.description=""),localCommand.description!==appCommand.description||localCommand.options.length!==appCommand.options.length)return!0}__name(areSlashCommandsDifferent,"areSlashCommandsDifferent");async function registerCommands(props){if(props.reloading)if(props.client.isReady())await handleRegistration(props.client,props.commands,props.devGuildIds,props.type);else throw new Error(colors_default.red("Cannot reload commands when client is not ready."));else props.client.once("ready",async c=>{await handleRegistration(c,props.commands,props.devGuildIds,props.type)})}__name(registerCommands,"registerCommands");async function handleRegistration(client,commands,devGuildIds,type){let devOnlyCommands=commands.filter(cmd=>cmd.options?.devOnly),globalCommands=commands.filter(cmd=>!cmd.options?.devOnly);type==="dev"?await registerDevCommands(client,devOnlyCommands,devGuildIds):type==="global"?await registerGlobalCommands(client,globalCommands):(await registerDevCommands(client,devOnlyCommands,devGuildIds),await registerGlobalCommands(client,globalCommands))}__name(handleRegistration,"handleRegistration");async function registerGlobalCommands(client,commands){let appCommandsManager=client.application.commands;await appCommandsManager.fetch();for(let command of commands){let targetCommand=appCommandsManager.cache.find(cmd=>cmd.name===command.data.name);if(command.options?.deleted){targetCommand?(await targetCommand.delete().catch(error=>{throw new Error(colors_default.red(`Failed to delete command "${command.data.name}" globally.
4
4
  `),error)}),console.log(colors_default.green(`Deleted command "${command.data.name}" globally.`))):process.emitWarning(colors_default.yellow(`Ignoring: Command "${command.data.name}" is globally marked as deleted.`));continue}if(targetCommand&&areSlashCommandsDifferent(targetCommand,command.data)){await targetCommand.edit(command.data).catch(error=>{throw new Error(colors_default.red(`Failed to edit command "${command.data.name}" globally.
@@ -7,5 +7,5 @@
7
7
  `),error)}),console.log(colors_default.green(`Edited command "${command.data.name}" in ${guildCommands.guild.name}.`));continue}targetCommand||(await guildCommands.create(command.data).catch(error=>{throw new Error(colors_default.red(`Failed to register command "${command.data.name}" in ${guildCommands.guild.name}.
8
8
  `),error)}),console.log(colors_default.green(`Registered command "${command.data.name}" in ${guildCommands.guild.name}.`)))}}__name(registerDevCommands,"registerDevCommands");function devOnly_default({interaction,targetCommand,handlerData}){if(!interaction.isAutocomplete()&&targetCommand.options?.devOnly){if(interaction.inGuild()&&!handlerData.devGuildIds.includes(interaction.guildId))return interaction.reply({content:"\u274C This command can only be used inside development servers.",ephemeral:!0}),!0;let memberRoles=interaction.guild?.members.cache.get(interaction.user.id)?.roles.cache,hasDevRole=!1;if(memberRoles?.forEach(role=>{handlerData.devRoleIds.includes(role.id)&&(hasDevRole=!0)}),!(handlerData.devUserIds.includes(interaction.user.id)||hasDevRole))return interaction.reply({content:"\u274C This command can only be used by developers.",ephemeral:!0}),!0}}__name(devOnly_default,"default");var import_discord=require("discord.js");function permissions_default({interaction,targetCommand}){if(interaction.isAutocomplete())return;let userPermissions=interaction.memberPermissions,userPermissionsRequired=targetCommand.options?.userPermissions,missingUserPermissions=[];typeof userPermissionsRequired=="string"&&(userPermissionsRequired=[userPermissionsRequired]);let botPermissions=interaction.guild?.members.me?.permissions,botPermissionsRequired=targetCommand.options?.botPermissions,missingBotPermissions=[];if(typeof botPermissionsRequired=="string"&&(botPermissionsRequired=[botPermissionsRequired]),!userPermissionsRequired?.length&&!botPermissionsRequired?.length)return;if(userPermissions&&userPermissionsRequired)for(let permission of userPermissionsRequired)userPermissions.has(permission)||missingUserPermissions.push(permission);if(botPermissions&&botPermissionsRequired)for(let permission of botPermissionsRequired)botPermissions.has(permission)||missingBotPermissions.push(permission);if(!missingUserPermissions.length&&!missingBotPermissions.length)return;let pattern=/([a-z])([A-Z])|([A-Z]+)([A-Z][a-z])/g;missingUserPermissions=missingUserPermissions.map(str=>str.replace(pattern,"$1$3 $2$4")),missingBotPermissions=missingBotPermissions.map(str=>str.replace(pattern,"$1$3 $2$4"));let embedDescription="",formatter=new Intl.ListFormat("en",{style:"long",type:"conjunction"}),getPermissionWord=__name(permissions=>permissions.length===1?"permission":"permissions","getPermissionWord");if(missingUserPermissions.length){let formattedPermissions=missingUserPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- You must have the ${permissionsString} ${getPermissionWord(missingUserPermissions)} to be able to run this command.
9
9
  `}if(missingBotPermissions.length){let formattedPermissions=missingBotPermissions.map(p=>`\`${p}\``),permissionsString=formatter.format(formattedPermissions);embedDescription+=`- I must have the ${permissionsString} ${getPermissionWord(missingBotPermissions)} to be able to execute this command.
10
- `}let embed=new import_discord.EmbedBuilder().setTitle(":x: Missing permissions!").setDescription(embedDescription).setColor("Red");return interaction.reply({embeds:[embed],ephemeral:!0}),!0}__name(permissions_default,"default");var validations_default=[devOnly_default,permissions_default];var CommandHandler=class{static{__name(this,"CommandHandler")}#data;constructor({...options}){this.#data={...options,builtInValidations:[],commands:[]}}async init(){await this.#buildCommands(),this.#buildBuiltInValidations();let devOnlyCommands=this.#data.commands.filter(cmd=>cmd.options?.devOnly);devOnlyCommands.length&&!this.#data.devGuildIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devGuildIds" have not been set.')),devOnlyCommands.length&&!this.#data.devUserIds.length&&!this.#data.devRoleIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devUserIds" or "devRoleIds" have not been set.')),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}),this.handleCommands()}async#buildCommands(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,commandFilePaths=(await getFilePaths(this.#data.commandsPath,!0)).filter(path3=>allowedExtensions.test(path3));for(let commandFilePath of commandFilePaths){let importedObj=await import(`${toFileURL(commandFilePath)}?t=${Date.now()}`),commandObj=clone(importedObj);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(commandFilePath)];let compactFilePath=commandFilePath.split(process.cwd())[1]||commandFilePath;if(commandObj.default&&(commandObj=commandObj.default),importedObj.default?commandObj.data=importedObj.default.data:commandObj.data=importedObj.data,!commandObj.data){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data".`));continue}if(!commandObj.data.name){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data.name".`));continue}if(!commandObj.run){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run".`));continue}if(typeof commandObj.run!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run" as a function.`));continue}commandObj.filePath=commandFilePath;let commandCategory=commandFilePath.split(this.#data.commandsPath)[1]?.replace(/\\\\|\\/g,"/").split("/")[1]||null;commandCategory&&allowedExtensions.test(commandCategory)?commandObj.category=null:commandObj.category=commandCategory,this.#data.commands.push(commandObj)}}#buildBuiltInValidations(){for(let builtInValidationFunction of validations_default)this.#data.builtInValidations.push(builtInValidationFunction)}handleCommands(){this.#data.client.on("interactionCreate",async interaction=>{if(!interaction.isChatInputCommand()&&!interaction.isContextMenuCommand()&&!interaction.isAutocomplete())return;let isAutocomplete=interaction.isAutocomplete(),targetCommand=this.#data.commands.find(cmd=>cmd.data.name===interaction.commandName);if(!targetCommand)return;let{data,options,run,autocomplete,...rest}=targetCommand;return isAutocomplete&&!autocomplete?void 0:__name(async()=>{let commandObj={data:targetCommand.data,options:targetCommand.options,...rest};if(this.#data.validationHandler){let canRun2=!0;for(let validationFunction of this.#data.validationHandler.validations)if(await validationFunction({interaction,commandObj,client:this.#data.client,handler:this.#data.commandkitInstance})){canRun2=!1;break}if(!canRun2)return}let canRun=!0;if(!this.#data.skipBuiltInValidations){for(let validation of this.#data.builtInValidations)if(validation({targetCommand,interaction,handlerData:this.#data})){canRun=!1;break}}if(!canRun)return;let command=targetCommand[isAutocomplete?"autocomplete":"run"],context={interaction,client:this.#data.client,handler:this.#data.commandkitInstance};return await command(context)},"executor")()})}get commands(){return this.#data.commands}async reloadCommands(type){if(!this.#data.commandsPath)throw new Error(colors_default.red('Cannot reload commands as "commandsPath" was not provided when instantiating CommandKit.'));this.#data.commands=[],await this.#buildCommands(),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type})}};var EventHandler=class{static{__name(this,"EventHandler")}#data;constructor({...options}){this.#data={...options,events:[]}}async init(){await this.#buildEvents(),this.#registerEvents()}async#buildEvents(){let eventFolderPaths=await getFolderPaths(this.#data.eventsPath);for(let eventFolderPath of eventFolderPaths){let eventName=eventFolderPath.replace(/\\\\|\\/g,"/").split("/").pop(),allowedExtensions=/\.(js|mjs|cjs|ts)$/i,eventFilePaths=(await getFilePaths(eventFolderPath,!0)).filter(path3=>allowedExtensions.test(path3)),eventObj={name:eventName,functions:[]};this.#data.events.push(eventObj);for(let eventFilePath of eventFilePaths){let importedFunction=(await import(`${toFileURL(eventFilePath)}?t=${Date.now()}`)).default,eventFunction=clone(importedFunction);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(eventFilePath)],eventFunction?.default&&(eventFunction=eventFunction.default);let compactFilePath=eventFilePath.split(process.cwd())[1]||eventFilePath;if(typeof eventFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Event file ${compactFilePath} does not export a function.`));continue}eventObj.functions.push(eventFunction)}}}#registerEvents(){let client=this.#data.client,handler=this.#data.commandKitInstance;for(let eventObj of this.#data.events)client.on(eventObj.name,async(...params)=>{for(let eventFunction of eventObj.functions)if(await eventFunction(...params,client,handler))break})}get events(){return this.#data.events}async reloadEvents(commandHandler){if(!this.#data.eventsPath)throw new Error(colors_default.red('Cannot reload events as "eventsPath" was not provided when instantiating CommandKit.'));this.#data.events=[],await this.#buildEvents(),this.#data.client.removeAllListeners(),this.#registerEvents(),commandHandler?.handleCommands()}};var ValidationHandler=class{static{__name(this,"ValidationHandler")}#data;constructor({...options}){this.#data={...options,validations:[]}}async init(){this.#data.validations=await this.#buildValidations()}async#buildValidations(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,validationFilePaths=(await getFilePaths(this.#data.validationsPath,!0)).filter(path3=>allowedExtensions.test(path3)),validationFunctions=[];for(let validationFilePath of validationFilePaths){let importedFunction=(await import(`${toFileURL(validationFilePath)}?t=${Date.now()}`)).default,validationFunction=clone(importedFunction);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(validationFilePath)],validationFunction?.default&&(validationFunction=validationFunction.default);let compactFilePath=validationFilePath.split(process.cwd())[1]||validationFilePath;if(typeof validationFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Validation file ${compactFilePath} does not export a function.`));continue}validationFunctions.push(validationFunction)}return validationFunctions}get validations(){return this.#data.validations}async reloadValidations(){if(!this.#data.validationsPath)throw new Error(colors_default.red('Cannot reload validations as "validationsPath" was not provided when instantiating CommandKit.'));let newValidations=await this.#buildValidations();this.#data.validations=newValidations}};var CommandKit=class{static{__name(this,"CommandKit")}#data;constructor(options){if(!options.client)throw new Error(colors_default.red('"client" is required when instantiating CommandKit.'));if(options.validationsPath&&!options.commandsPath)throw new Error(colors_default.red('"commandsPath" is required when "validationsPath" is set.'));this.#data=options,this.#init()}get client(){return this.#data.client}get commandHandler(){return this.#data.commandHandler}async#init(){if(this.#data.eventsPath){let eventHandler=new EventHandler({client:this.#data.client,eventsPath:this.#data.eventsPath,commandKitInstance:this});await eventHandler.init(),this.#data.eventHandler=eventHandler}if(this.#data.validationsPath){let validationHandler=new ValidationHandler({validationsPath:this.#data.validationsPath});await validationHandler.init(),this.#data.validationHandler=validationHandler}if(this.#data.commandsPath){let commandHandler=new CommandHandler({client:this.#data.client,commandsPath:this.#data.commandsPath,devGuildIds:this.#data.devGuildIds||[],devUserIds:this.#data.devUserIds||[],devRoleIds:this.#data.devRoleIds||[],validationHandler:this.#data.validationHandler,skipBuiltInValidations:this.#data.skipBuiltInValidations||!1,commandkitInstance:this,bulkRegister:this.#data.bulkRegister||!1});await commandHandler.init(),this.#data.commandHandler=commandHandler}}async reloadCommands(type){this.#data.commandHandler&&await this.#data.commandHandler.reloadCommands(type)}async reloadEvents(){this.#data.eventHandler&&await this.#data.eventHandler.reloadEvents(this.#data.commandHandler)}async reloadValidations(){this.#data.validationHandler&&await this.#data.validationHandler.reloadValidations()}get commands(){return this.#data.commandHandler?this.#data.commandHandler.commands.map(cmd=>{let{run,autocomplete,...command}=cmd;return command}):[]}get commandsPath(){return this.#data.commandsPath}get eventsPath(){return this.#data.eventsPath}get validationsPath(){return this.#data.validationsPath}get devUserIds(){return this.#data.devUserIds||[]}get devGuildIds(){return this.#data.devGuildIds||[]}get devRoleIds(){return this.#data.devRoleIds||[]}};0&&(module.exports={CommandKit});
10
+ `}let embed=new import_discord.EmbedBuilder().setTitle(":x: Missing permissions!").setDescription(embedDescription).setColor("Red");return interaction.reply({embeds:[embed],ephemeral:!0}),!0}__name(permissions_default,"default");var validations_default=[devOnly_default,permissions_default];var import_node_async_hooks=require("async_hooks");var CommandKitErrorCodes={GuildOnlyException:Symbol("kGuildOnlyException"),DMOnlyException:Symbol("kDMOnlyException")};function isCommandKitError(error){if(!(error instanceof Error))return!1;let code=Reflect.get(error,"code");for(let key in CommandKitErrorCodes)if(CommandKitErrorCodes[key]===code)return!0;return!1}__name(isCommandKitError,"isCommandKitError");var context=new import_node_async_hooks.AsyncLocalStorage;function makeContextAwareFunction(env,fn,finalizer){return __name((...args)=>context.run(env,async()=>{try{return await fn(...args)}catch(e){if(isCommandKitError(e)){let code=Reflect.get(e,"code"),interaction=env.variables.get("interaction");if(!interaction)return;switch(code){case CommandKitErrorCodes.GuildOnlyException:{interaction.isRepliable()&&await interaction.reply({content:"This command is only available in guilds.",ephemeral:!0});return}case CommandKitErrorCodes.DMOnlyException:{interaction.isRepliable()&&await interaction.reply({content:"This command is only available in DMs.",ephemeral:!0});return}}return}env.setExecutionError(e)}finally{if(typeof finalizer=="function")try{await finalizer(...args)}catch{}}}),"_fn")}__name(makeContextAwareFunction,"makeContextAwareFunction");function getContext(){return context.getStore()}__name(getContext,"getContext");function useEnvironment(){let ctx=context.getStore();if(!ctx)throw new Error("No commandkit environment found. Please make sure you are inside commandkit handler.");return ctx}__name(useEnvironment,"useEnvironment");var import_node_crypto=require("crypto");var CommandKitEnvironment=class{constructor(commandkit){this.commandkit=commandkit}static{__name(this,"CommandKitEnvironment")}#data={executionError:null,type:null,variables:new Map,deferredFunctions:new Map,marker:"",markStart:0,markEnd:0};getExecutionError(){return this.#data.executionError}setExecutionError(error){if(this.#data.executionError)throw new Error("Execution error already set.");this.#data.executionError=error}getType(){let type=this.#data.type;if(!type)throw new Error("Environment type not set.");return type}setType(type){this.#data.type=type}get variables(){return this.#data.variables}registerDeferredFunction(fn){let id=(0,import_node_crypto.randomUUID)();return this.#data.deferredFunctions.set(id,fn),id}clearDeferredFunction(id){this.#data.deferredFunctions.delete(id)}async runDeferredFunctions(){for(let[id,fn]of this.#data.deferredFunctions)try{await fn(this)}catch(e){this.commandkit.emit("unhandledDeferredFunctionRejection",e)}finally{this.clearDeferredFunction(id)}}clearAllDeferredFunctions(){this.#data.deferredFunctions.clear()}markStart(marker){this.#data.marker=marker,this.#data.markStart=performance.now()}markEnd(){this.#data.markEnd||(this.#data.markEnd=performance.now())}getMarker(){return this.#data.marker}getExecutionTime(){return Math.abs(this.#data.markEnd-this.#data.markStart)}};function after(fn){let env=getContext();if(!env)throw new Error("after must be called inside commandkit handler.");return env.registerDeferredFunction(fn)}__name(after,"after");var CommandHandler=class{static{__name(this,"CommandHandler")}#data;constructor({...options}){this.#data={...options,builtInValidations:[],commands:[]}}async init(){await this.#buildCommands(),this.#buildBuiltInValidations();let devOnlyCommands=this.#data.commands.filter(cmd=>cmd.options?.devOnly);devOnlyCommands.length&&!this.#data.devGuildIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devGuildIds" have not been set.')),devOnlyCommands.length&&!this.#data.devUserIds.length&&!this.#data.devRoleIds.length&&process.emitWarning(colors_default.yellow('You have commands marked as "devOnly", but "devUserIds" or "devRoleIds" have not been set.')),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands}),this.handleCommands()}async#buildCommands(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,commandFilePaths=(await getFilePaths(this.#data.commandsPath,!0)).filter(path3=>allowedExtensions.test(path3));for(let commandFilePath of commandFilePaths){let importedObj=await import(`${toFileURL(commandFilePath)}?t=${Date.now()}`),commandObj=clone(importedObj);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(commandFilePath)];let compactFilePath=commandFilePath.split(process.cwd())[1]||commandFilePath;if(commandObj.default&&(commandObj=commandObj.default),importedObj.default?commandObj.data=importedObj.default.data:commandObj.data=importedObj.data,!commandObj.data){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data".`));continue}if(!commandObj.data.name){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${compactFilePath} does not export "data.name".`));continue}if(!commandObj.run){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run".`));continue}if(typeof commandObj.run!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Command file ${commandObj.data.name} does not export "run" as a function.`));continue}commandObj.filePath=commandFilePath;let commandCategory=commandFilePath.split(this.#data.commandsPath)[1]?.replace(/\\\\|\\/g,"/").split("/")[1]||null;commandCategory&&allowedExtensions.test(commandCategory)?commandObj.category=null:commandObj.category=commandCategory,this.#data.commands.push(commandObj)}}#buildBuiltInValidations(){for(let builtInValidationFunction of validations_default)this.#data.builtInValidations.push(builtInValidationFunction)}async#commandFinalizer(){let env=useEnvironment();await env.runDeferredFunctions(),env.clearAllDeferredFunctions()}async#interactionHandler(interaction){if(!interaction.isChatInputCommand()&&!interaction.isContextMenuCommand()&&!interaction.isAutocomplete())return;let isAutocomplete=interaction.isAutocomplete(),targetCommand=this.#data.commands.find(cmd=>cmd.data.name===interaction.commandName);if(!targetCommand)return;let env=useEnvironment();env.variables.set("interaction",interaction);let{data,options,run,autocomplete,...rest}=targetCommand;return isAutocomplete&&!autocomplete?void 0:__name(async()=>{let commandObj={data:targetCommand.data,options:targetCommand.options,...rest};if(this.#data.validationHandler){let canRun2=!0;for(let validationFunction of this.#data.validationHandler.validations)if(await validationFunction({interaction,commandObj,client:this.#data.client,handler:this.#data.commandkitInstance})){canRun2=!1;break}if(!canRun2)return}let canRun=!0;if(!this.#data.skipBuiltInValidations){for(let validation of this.#data.builtInValidations)if(validation({targetCommand,interaction,handlerData:this.#data})){canRun=!1;break}}if(!canRun)return;let command=targetCommand[isAutocomplete?"autocomplete":"run"],context2={interaction,client:this.#data.client,handler:this.#data.commandkitInstance};if(!this.#data.commandkitInstance.isDebuggingCommands())return command(context2);after(env2=>{let error=env2.getExecutionError(),marker=env2.getMarker(),time=`${env2.getExecutionTime().toFixed(2)}ms`,cachedMarker=!!env2.variables.get("cacheHit")?" (cached)":"";if(error){console.error(colors_default.red(`[${marker} - ${time}]${cachedMarker} Error executing command: ${error}`));return}console.log(colors_default.green(`[${marker} - ${time}]${cachedMarker} Command executed successfully`))});try{return env.markStart(interaction.commandName),await command(context2)}finally{env.markEnd()}},"executor")()}handleCommands(){this.#data.client.on("interactionCreate",interaction=>{let env=new CommandKitEnvironment(this.#data.commandkitInstance);return env.setType("COMMAND_HANDLER"),makeContextAwareFunction(env,this.#interactionHandler.bind(this),this.#commandFinalizer.bind(this))(interaction)})}get commands(){return this.#data.commands}async reloadCommands(type){if(!this.#data.commandsPath)throw new Error(colors_default.red('Cannot reload commands as "commandsPath" was not provided when instantiating CommandKit.'));this.#data.commands=[],await this.#buildCommands(),this.#data.bulkRegister?await loadCommandsWithRest({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type}):await registerCommands({client:this.#data.client,devGuildIds:this.#data.devGuildIds,commands:this.#data.commands,reloading:!0,type})}};var EventHandler=class{static{__name(this,"EventHandler")}#data;constructor({...options}){this.#data={...options,events:[]}}async init(){await this.#buildEvents(),this.#registerEvents()}async#buildEvents(){let eventFolderPaths=await getFolderPaths(this.#data.eventsPath);for(let eventFolderPath of eventFolderPaths){let eventName=eventFolderPath.replace(/\\\\|\\/g,"/").split("/").pop(),allowedExtensions=/\.(js|mjs|cjs|ts)$/i,eventFilePaths=(await getFilePaths(eventFolderPath,!0)).filter(path3=>allowedExtensions.test(path3)),eventObj={name:eventName,functions:[]};this.#data.events.push(eventObj);for(let eventFilePath of eventFilePaths){let importedFunction=(await import(`${toFileURL(eventFilePath)}?t=${Date.now()}`)).default,eventFunction=clone(importedFunction);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(eventFilePath)],eventFunction?.default&&(eventFunction=eventFunction.default);let compactFilePath=eventFilePath.split(process.cwd())[1]||eventFilePath;if(typeof eventFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Event file ${compactFilePath} does not export a function.`));continue}eventObj.functions.push(eventFunction)}}}#registerEvents(){let client=this.#data.client,handler=this.#data.commandKitInstance;for(let eventObj of this.#data.events)client.on(eventObj.name,async(...params)=>{for(let eventFunction of eventObj.functions)if(await eventFunction(...params,client,handler))break})}get events(){return this.#data.events}async reloadEvents(commandHandler){if(!this.#data.eventsPath)throw new Error(colors_default.red('Cannot reload events as "eventsPath" was not provided when instantiating CommandKit.'));this.#data.events=[],await this.#buildEvents(),this.#data.client.removeAllListeners(),this.#registerEvents(),commandHandler?.handleCommands()}};var ValidationHandler=class{static{__name(this,"ValidationHandler")}#data;constructor({...options}){this.#data={...options,validations:[]}}async init(){this.#data.validations=await this.#buildValidations()}async#buildValidations(){let allowedExtensions=/\.(js|mjs|cjs|ts)$/i,validationFilePaths=(await getFilePaths(this.#data.validationsPath,!0)).filter(path3=>allowedExtensions.test(path3)),validationFunctions=[];for(let validationFilePath of validationFilePaths){let importedFunction=(await import(`${toFileURL(validationFilePath)}?t=${Date.now()}`)).default,validationFunction=clone(importedFunction);typeof module<"u"&&typeof require<"u"&&delete require.cache[require.resolve(validationFilePath)],validationFunction?.default&&(validationFunction=validationFunction.default);let compactFilePath=validationFilePath.split(process.cwd())[1]||validationFilePath;if(typeof validationFunction!="function"){process.emitWarning(colors_default.yellow(`Ignoring: Validation file ${compactFilePath} does not export a function.`));continue}validationFunctions.push(validationFunction)}return validationFunctions}get validations(){return this.#data.validations}async reloadValidations(){if(!this.#data.validationsPath)throw new Error(colors_default.red('Cannot reload validations as "validationsPath" was not provided when instantiating CommandKit.'));let newValidations=await this.#buildValidations();this.#data.validations=newValidations}};var CacheProvider=class{static{__name(this,"CacheProvider")}};var MemoryCache=class extends CacheProvider{static{__name(this,"MemoryCache")}#cache=new Map;async get(key){let entry=this.#cache.get(key);if(entry){if(entry.ttl&&Date.now()>entry.ttl){this.#cache.delete(key);return}return entry.value}}async set(key,value,ttl){this.#cache.set(key,{key,value,ttl:ttl!=null?Date.now()+ttl:void 0})}async exists(key){return this.#cache.has(key)}async delete(key){this.#cache.delete(key)}async clear(){this.#cache.clear()}async expire(key,ttl){let entry=this.#cache.get(key);if(!entry)return;let _ttl=Date.now()+ttl;if(_ttl<Date.now()){this.#cache.delete(key);return}entry.ttl=_ttl}};var CommandKit=class _CommandKit extends import_node_events.default{static{__name(this,"CommandKit")}#data;static instance=void 0;constructor(options){if(_CommandKit.instance&&process.emitWarning("CommandKit instance already exists. Having multiple instance in same project is discouraged and it may lead to unexpected behavior.",{code:"MultiInstanceWarning"}),!options.client)throw new Error(colors_default.red('"client" is required when instantiating CommandKit.'));if(options.validationsPath&&!options.commandsPath)throw new Error(colors_default.red('"commandsPath" is required when "validationsPath" is set.'));super(),options.debugCommands??=process.env.NODE_ENV!=="production",options.cacheProvider!==null&&(!options.cacheProvider||!(options.cacheProvider instanceof CacheProvider))&&(options.cacheProvider=new MemoryCache),this.#data=options,this.#init().then(()=>{this.incrementClientListenersCount()}),_CommandKit.instance||(_CommandKit.instance=this)}getCacheProvider(){return this.#data.cacheProvider??null}isDebuggingCommands(){return this.#data.debugCommands||!1}get client(){return this.#data.client}get commandHandler(){return this.#data.commandHandler}async#init(){if(this.#data.eventsPath){let eventHandler=new EventHandler({client:this.#data.client,eventsPath:this.#data.eventsPath,commandKitInstance:this});await eventHandler.init(),this.#data.eventHandler=eventHandler}if(this.#data.validationsPath){let validationHandler=new ValidationHandler({validationsPath:this.#data.validationsPath});await validationHandler.init(),this.#data.validationHandler=validationHandler}if(this.#data.commandsPath){let commandHandler=new CommandHandler({client:this.#data.client,commandsPath:this.#data.commandsPath,devGuildIds:this.#data.devGuildIds||[],devUserIds:this.#data.devUserIds||[],devRoleIds:this.#data.devRoleIds||[],validationHandler:this.#data.validationHandler,skipBuiltInValidations:this.#data.skipBuiltInValidations||!1,commandkitInstance:this,bulkRegister:this.#data.bulkRegister||!1});await commandHandler.init(),this.#data.commandHandler=commandHandler}}async reloadCommands(type){this.#data.commandHandler&&await this.#data.commandHandler.reloadCommands(type)}async reloadEvents(){this.#data.eventHandler&&await this.#data.eventHandler.reloadEvents(this.#data.commandHandler)}async reloadValidations(){this.#data.validationHandler&&await this.#data.validationHandler.reloadValidations()}get commands(){return this.#data.commandHandler?this.#data.commandHandler.commands.map(cmd=>{let{run,autocomplete,...command}=cmd;return command}):[]}get commandsPath(){return this.#data.commandsPath}get eventsPath(){return this.#data.eventsPath}get validationsPath(){return this.#data.validationsPath}get devUserIds(){return this.#data.devUserIds||[]}get devGuildIds(){return this.#data.devGuildIds||[]}get devRoleIds(){return this.#data.devRoleIds||[]}incrementClientListenersCount(){this.#data.client.setMaxListeners(this.#data.client.getMaxListeners()+1)}decrementClientListenersCount(){this.#data.client.setMaxListeners(this.#data.client.getMaxListeners()-1)}};0&&(module.exports={CommandKit});
11
11
  //# sourceMappingURL=CommandKit.js.map