bakit 1.0.0-beta.13 → 1.0.0-beta.14

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 (2) hide show
  1. package/dist/index.js +247 -597
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,41 +1,25 @@
1
- // src/BakitClient.ts
2
- import {
3
- Client,
4
- codeBlock,
5
- Events
6
- } from "discord.js";
7
-
8
- // src/command/CommandRegistry.ts
9
- import {
10
- Collection as Collection2,
11
- SlashCommandBuilder,
12
- SlashCommandSubcommandBuilder,
13
- SlashCommandSubcommandGroupBuilder
14
- } from "discord.js";
15
- import glob from "tiny-glob";
16
- import { pathToFileURL } from "url";
1
+ import { Collection, SlashCommandBuilder, SlashCommandSubcommandGroupBuilder, SlashCommandSubcommandBuilder, ChatInputCommandInteraction, Message, Client, Events, codeBlock } from 'discord.js';
2
+ import glob from 'tiny-glob';
3
+ import { pathToFileURL } from 'url';
4
+ import { AsyncLocalStorage } from 'async_hooks';
17
5
 
18
- // src/command/CommandEntry.ts
19
- import { Collection } from "discord.js";
6
+ // src/BakitClient.ts
20
7
 
21
8
  // src/base/BaseEntry.ts
22
9
  var BaseEntry = class {
23
10
  target;
24
11
  hooks = {
25
- ["MAIN" /* Main */]: void 0,
26
- ["ERROR" /* Error */]: void 0,
27
- ["POST" /* Post */]: void 0,
28
- ["PRE" /* Pre */]: void 0
12
+ MAIN: void 0,
13
+ ERROR: void 0,
14
+ POST: void 0,
15
+ PRE: void 0
29
16
  };
30
17
  main;
31
18
  pre;
32
19
  post;
33
20
  error;
34
21
  constructor() {
35
- this.main = this.createMainHookDecorator("MAIN" /* Main */);
36
- this.pre = this.createMainHookDecorator("PRE" /* Pre */);
37
- this.post = this.createMainHookDecorator("POST" /* Post */);
38
- this.error = this.createMainHookDecorator("ERROR" /* Error */);
22
+ this.main = this.createMainHookDecorator("MAIN" /* Main */), this.pre = this.createMainHookDecorator("PRE" /* Pre */), this.post = this.createMainHookDecorator("POST" /* Post */), this.error = this.createMainHookDecorator("ERROR" /* Error */);
39
23
  }
40
24
  setTarget(target) {
41
25
  this.target = target;
@@ -51,14 +35,12 @@ var BaseEntry = class {
51
35
  };
52
36
  }
53
37
  addHook(state, target, descriptor) {
54
- if (this.target && this.target !== target.constructor) {
38
+ if (this.target && this.target !== target.constructor)
55
39
  throw new Error("Hook is used at wrong constructor.");
56
- }
57
- const { value: method } = descriptor;
58
- if (typeof method !== "function") {
40
+ let { value: method } = descriptor;
41
+ if (typeof method != "function")
59
42
  throw new Error("Invalid target method for hook.");
60
- }
61
- const hook = {
43
+ let hook = {
62
44
  state,
63
45
  method,
64
46
  entry: this
@@ -73,37 +55,29 @@ var BaseCommandEntry = class extends BaseEntry {
73
55
  super();
74
56
  this.options = options;
75
57
  }
76
- };
77
- var BaseCommandGroupEntry = class extends BaseCommandEntry {
58
+ }, BaseCommandGroupEntry = class extends BaseCommandEntry {
78
59
  children = new Collection();
79
60
  subcommand(options) {
80
- const fullOptions = typeof options === "string" ? { name: options, description: `${options} command` } : { description: `${options.name} command`, ...options };
81
- if (this.children.has(fullOptions.name)) {
61
+ let fullOptions = typeof options == "string" ? { name: options, description: `${options} command` } : { description: `${options.name} command`, ...options };
62
+ if (this.children.has(fullOptions.name))
82
63
  throw new Error(`Entry "${fullOptions.name}" is already existed.`);
83
- }
84
- const subcommand = new SubcommandEntry(fullOptions, this);
85
- this.children.set(fullOptions.name, subcommand);
86
- return subcommand;
64
+ let subcommand = new SubcommandEntry(fullOptions, this);
65
+ return this.children.set(fullOptions.name, subcommand), subcommand;
87
66
  }
88
- };
89
- var RootCommandEntry = class extends BaseCommandGroupEntry {
67
+ }, RootCommandEntry = class extends BaseCommandGroupEntry {
90
68
  group(options) {
91
- const fullOptions = typeof options === "string" ? { name: options, description: `${options} command` } : { description: `${options.name} command`, ...options };
92
- if (this.children.has(fullOptions.name)) {
69
+ let fullOptions = typeof options == "string" ? { name: options, description: `${options} command` } : { description: `${options.name} command`, ...options };
70
+ if (this.children.has(fullOptions.name))
93
71
  throw new Error(`Entry "${fullOptions.name}" is already existed.`);
94
- }
95
- const group = new CommandGroupEntry(fullOptions, this);
96
- this.children.set(fullOptions.name, group);
97
- return group;
72
+ let group = new CommandGroupEntry(fullOptions, this);
73
+ return this.children.set(fullOptions.name, group), group;
98
74
  }
99
- };
100
- var CommandGroupEntry = class extends BaseCommandGroupEntry {
75
+ }, CommandGroupEntry = class extends BaseCommandGroupEntry {
101
76
  constructor(options, parent) {
102
77
  super(options);
103
78
  this.parent = parent;
104
79
  }
105
- };
106
- var SubcommandEntry = class extends BaseCommandEntry {
80
+ }, SubcommandEntry = class extends BaseCommandEntry {
107
81
  constructor(options, parent) {
108
82
  super(options);
109
83
  this.parent = parent;
@@ -113,11 +87,10 @@ var SubcommandEntry = class extends BaseCommandEntry {
113
87
  // src/command/Command.ts
114
88
  var CommandAPI;
115
89
  ((CommandAPI2) => {
116
- const rootEntries = /* @__PURE__ */ new WeakMap();
90
+ let rootEntries = /* @__PURE__ */ new WeakMap();
117
91
  function use(root) {
118
92
  return (target) => {
119
- root.setTarget(target);
120
- rootEntries.set(target, root);
93
+ root.setTarget(target), rootEntries.set(target, root);
121
94
  };
122
95
  }
123
96
  CommandAPI2.use = use;
@@ -125,102 +98,51 @@ var CommandAPI;
125
98
  return rootEntries.get(constructor);
126
99
  }
127
100
  CommandAPI2.getRoot = getRoot;
128
- })(CommandAPI || (CommandAPI = {}));
101
+ })(CommandAPI ||= {});
129
102
  function CommandFactory(options) {
130
- if (typeof options === "string") {
131
- options = { name: options };
132
- }
133
- if (!options.description) {
134
- options.description = options.name;
135
- }
136
- return new RootCommandEntry(options);
103
+ return typeof options == "string" && (options = { name: options }), options.description || (options.description = options.name), new RootCommandEntry(options);
137
104
  }
138
105
  var Command = Object.assign(CommandFactory, CommandAPI);
139
106
 
140
107
  // src/command/argument/Argument.ts
141
- var ArgumentType = /* @__PURE__ */ ((ArgumentType2) => {
142
- ArgumentType2["String"] = "string";
143
- ArgumentType2["Integer"] = "integer";
144
- ArgumentType2["Number"] = "number";
145
- ArgumentType2["User"] = "user";
146
- ArgumentType2["Member"] = "member";
147
- return ArgumentType2;
148
- })(ArgumentType || {});
108
+ var ArgumentType = /* @__PURE__ */ ((ArgumentType2) => (ArgumentType2.String = "string", ArgumentType2.Integer = "integer", ArgumentType2.Number = "number", ArgumentType2.User = "user", ArgumentType2.Member = "member", ArgumentType2))(ArgumentType || {});
149
109
 
150
110
  // src/command/argument/Arg.ts
151
111
  var store = /* @__PURE__ */ new WeakMap();
152
112
  function getMethodArguments(method, init = false) {
153
113
  let args = store.get(method);
154
- if (!args) {
155
- args = [];
156
- if (init) {
157
- store.set(method, args);
158
- }
159
- }
160
- return init ? args : Object.freeze([...args]);
114
+ return args || (args = [], init && store.set(method, args)), init ? args : Object.freeze([...args]);
161
115
  }
162
116
  function createArgument(type) {
163
117
  return function(options) {
164
- const objOptions = typeof options === "string" ? { name: options } : options;
165
- const fullOptions = { ...objOptions, type };
166
- if (!fullOptions.description) {
167
- fullOptions.description = fullOptions.name;
168
- }
169
- if (!("required" in fullOptions)) {
170
- fullOptions.required = true;
171
- }
172
- return function(target, key, _index) {
173
- const method = Object.getOwnPropertyDescriptor(target, key)?.value;
174
- if (!method) {
118
+ let fullOptions = { ...typeof options == "string" ? { name: options } : options, type };
119
+ return fullOptions.description || (fullOptions.description = fullOptions.name), "required" in fullOptions || (fullOptions.required = true), function(target, key, _index) {
120
+ let method = Object.getOwnPropertyDescriptor(target, key)?.value;
121
+ if (!method)
175
122
  throw new Error("No method found");
176
- }
177
- const args = getMethodArguments(method, true);
178
- args.unshift(fullOptions);
123
+ getMethodArguments(method, true).unshift(fullOptions);
179
124
  };
180
125
  };
181
126
  }
182
- var string = createArgument("string" /* String */);
183
- var integer = createArgument("integer" /* Integer */);
184
- var number = createArgument("number" /* Number */);
185
- var user = createArgument("user" /* User */);
186
- var member = createArgument("member" /* Member */);
127
+ var string = createArgument("string" /* String */), integer = createArgument("integer" /* Integer */), number = createArgument("number" /* Number */), user = createArgument("user" /* User */), member = createArgument("member" /* Member */);
187
128
  function describeArgumentExpectation(arg) {
188
- const parts = [arg.type];
129
+ let parts = [arg.type];
189
130
  switch (arg.type) {
190
131
  case "string" /* String */: {
191
- if (arg.minLength && !arg.maxLength) {
192
- parts.push(`\u2265 ${String(arg.minLength)}`);
193
- }
194
- if (!arg.minLength && arg.maxLength) {
195
- parts.push(`\u2264 ${String(arg.maxLength)}`);
196
- }
197
- if (arg.minLength && arg.maxLength) {
198
- parts.push(`${String(arg.minLength)} - ${String(arg.maxLength)}`);
199
- }
132
+ arg.minLength && !arg.maxLength && parts.push(`\u2265 ${String(arg.minLength)}`), !arg.minLength && arg.maxLength && parts.push(`\u2264 ${String(arg.maxLength)}`), arg.minLength && arg.maxLength && parts.push(`${String(arg.minLength)} - ${String(arg.maxLength)}`);
200
133
  break;
201
134
  }
202
135
  case "number" /* Number */:
203
136
  case "integer" /* Integer */: {
204
- if (arg.minValue !== void 0 && arg.maxValue === void 0) {
205
- parts.push(`\u2265 ${String(arg.minValue)}`);
206
- }
207
- if (arg.minValue === void 0 && arg.maxValue !== void 0) {
208
- parts.push(`\u2264 ${String(arg.maxValue)}`);
209
- }
210
- if (arg.minValue !== void 0 && arg.maxValue !== void 0) {
211
- parts.push(`${String(arg.minValue)} - ${String(arg.maxValue)}`);
212
- }
137
+ arg.minValue !== void 0 && arg.maxValue === void 0 && parts.push(`\u2265 ${String(arg.minValue)}`), arg.minValue === void 0 && arg.maxValue !== void 0 && parts.push(`\u2264 ${String(arg.maxValue)}`), arg.minValue !== void 0 && arg.maxValue !== void 0 && parts.push(`${String(arg.minValue)} - ${String(arg.maxValue)}`);
213
138
  break;
214
139
  }
215
140
  }
216
141
  return parts.join(", ");
217
142
  }
218
143
  function format(arg) {
219
- const { name, required, tuple } = arg;
220
- const opening = required ? "<" : "[";
221
- const closing = required ? ">" : "]";
222
- const prefix = tuple ? "..." : "";
223
- return `${opening}${prefix}${name}: ${describeArgumentExpectation(arg)}${closing}`;
144
+ let { name, required, tuple } = arg, opening = required ? "<" : "[", closing = required ? ">" : "]";
145
+ return `${opening}${tuple ? "..." : ""}${name}: ${describeArgumentExpectation(arg)}${closing}`;
224
146
  }
225
147
  var Arg = {
226
148
  getMethodArguments,
@@ -236,20 +158,18 @@ var Arg = {
236
158
 
237
159
  // src/command/CommandRegistry.ts
238
160
  var CommandRegistry = class _CommandRegistry {
239
- static constructors = new Collection2();
240
- static instances = new Collection2();
161
+ static constructors = new Collection();
162
+ static instances = new Collection();
241
163
  /**
242
164
  * Add a command to the registry.
243
165
  * @param constructor The command class you want to add.
244
166
  */
245
167
  static add(constructor) {
246
- const root = Command.getRoot(constructor);
247
- if (!root) {
168
+ let root = Command.getRoot(constructor);
169
+ if (!root)
248
170
  throw new Error(`No root found for "${constructor.name}"`);
249
- }
250
- const { options } = root;
251
- this.constructors.set(options.name, constructor);
252
- this.instances.set(options.name, new constructor());
171
+ let { options } = root;
172
+ this.constructors.set(options.name, constructor), this.instances.set(options.name, new constructor());
253
173
  }
254
174
  /**
255
175
  * Load and add all commands which matched provided glob pattern to the registry.
@@ -258,20 +178,15 @@ var CommandRegistry = class _CommandRegistry {
258
178
  * @returns All loaded command constructors.
259
179
  */
260
180
  static async load(pattern, parallel = true) {
261
- const files = await glob(pattern);
262
- const loaders = files.map(async (file) => {
263
- const fileURL = pathToFileURL(file).toString();
264
- const { default: constructor } = await import(fileURL);
265
- _CommandRegistry.add(constructor);
266
- return constructor;
181
+ let loaders = (await glob(pattern)).map(async (file) => {
182
+ let fileURL = pathToFileURL(file).toString(), { default: constructor } = await import(fileURL);
183
+ return _CommandRegistry.add(constructor), constructor;
267
184
  });
268
- if (parallel) {
185
+ if (parallel)
269
186
  return await Promise.all(loaders);
270
- }
271
- const result = [];
272
- for (const loader of loaders) {
187
+ let result = [];
188
+ for (let loader of loaders)
273
189
  result.push(await loader);
274
- }
275
190
  return result;
276
191
  }
277
192
  /**
@@ -280,95 +195,59 @@ var CommandRegistry = class _CommandRegistry {
280
195
  * @returns a REST JSON version of the application command data.
281
196
  */
282
197
  static buildSlashCommand(constructor) {
283
- const root = Command.getRoot(constructor);
284
- if (!root) {
198
+ let root = Command.getRoot(constructor);
199
+ if (!root)
285
200
  throw new Error(`No root found for "${constructor.name}"`);
286
- }
287
- const { options } = root;
288
- const builder = new SlashCommandBuilder().setName(options.name).setDescription(options.description).setNSFW(Boolean(options.nsfw));
289
- const args = this.getMainHookArguments(root);
290
- if (root.children.size) {
291
- this.buildSlashCommandSubcommands(builder, root, args);
292
- } else {
293
- this.buildSlashCommandOptions(builder, args);
294
- }
295
- return builder.toJSON();
201
+ let { options } = root, builder = new SlashCommandBuilder().setName(options.name).setDescription(options.description).setNSFW(!!options.nsfw), args = this.getMainHookArguments(root);
202
+ return root.children.size ? this.buildSlashCommandSubcommands(builder, root, args) : this.buildSlashCommandOptions(builder, args), builder.toJSON();
296
203
  }
297
204
  static getMainHookArguments(entry) {
298
- const { hooks } = entry;
299
- const mainHook = hooks["MAIN" /* Main */];
205
+ let { hooks } = entry, mainHook = hooks.MAIN;
300
206
  return mainHook ? Arg.getMethodArguments(mainHook.method) : [];
301
207
  }
302
208
  static buildSlashCommandSubcommands(parent, entry, inheritedArgs) {
303
- const { children } = entry;
304
- for (const child of children.values()) {
209
+ let { children } = entry;
210
+ for (let child of children.values())
305
211
  if (child instanceof CommandGroupEntry && parent instanceof SlashCommandBuilder) {
306
- const { options } = child;
307
- const group = new SlashCommandSubcommandGroupBuilder().setName(options.name).setDescription(options.description);
212
+ let { options } = child, group = new SlashCommandSubcommandGroupBuilder().setName(options.name).setDescription(options.description);
308
213
  this.buildSlashCommandSubcommands(group, child, [
309
214
  ...inheritedArgs,
310
215
  ...this.getMainHookArguments(child)
311
- ]);
312
- parent.addSubcommandGroup(group);
216
+ ]), parent.addSubcommandGroup(group);
313
217
  } else if (child instanceof SubcommandEntry) {
314
- const { options } = child;
315
- const subcommand = new SlashCommandSubcommandBuilder().setName(options.name).setDescription(options.description);
218
+ let { options } = child, subcommand = new SlashCommandSubcommandBuilder().setName(options.name).setDescription(options.description);
316
219
  this.buildSlashCommandOptions(subcommand, [
317
220
  ...inheritedArgs,
318
221
  ...this.getMainHookArguments(child)
319
- ]);
320
- parent.addSubcommand(subcommand);
222
+ ]), parent.addSubcommand(subcommand);
321
223
  }
322
- }
323
224
  }
324
225
  static buildSlashCommandOptions(builder, args) {
325
- const argGroup = Object.groupBy(args, ({ required }) => required ? "required" : "optional");
326
- const orderedArgs = [...argGroup.required || [], ...argGroup.optional || []];
327
- for (const arg of orderedArgs) {
226
+ let argGroup = Object.groupBy(args, ({ required }) => required ? "required" : "optional"), orderedArgs = [...argGroup.required || [], ...argGroup.optional || []];
227
+ for (let arg of orderedArgs)
328
228
  this.attachSlashCommandOption(builder, arg);
329
- }
330
229
  }
331
230
  static attachSlashCommandOption(builder, arg) {
332
- const setupOption = (option) => {
333
- return option.setName(arg.name).setDescription(arg.description || arg.name).setRequired(Boolean(arg.required));
334
- };
231
+ let setupOption = (option) => option.setName(arg.name).setDescription(arg.description || arg.name).setRequired(!!arg.required);
335
232
  switch (arg.type) {
336
233
  case "string" /* String */: {
337
234
  builder.addStringOption((data) => {
338
- const option = setupOption(data);
339
- if (arg.maxLength) {
340
- option.setMaxLength(arg.maxLength);
341
- }
342
- if (arg.minLength) {
343
- option.setMinLength(arg.minLength);
344
- }
345
- return option;
235
+ let option = setupOption(data);
236
+ return arg.maxLength && option.setMaxLength(arg.maxLength), arg.minLength && option.setMinLength(arg.minLength), option;
346
237
  });
347
238
  break;
348
239
  }
349
240
  case "integer" /* Integer */: {
350
241
  builder.addIntegerOption((data) => {
351
- const option = setupOption(data);
352
- if (arg.maxValue) {
353
- option.setMaxValue(arg.maxValue);
354
- }
355
- if (arg.minValue) {
356
- option.setMinValue(arg.minValue);
357
- }
358
- return option;
242
+ let option = setupOption(data);
243
+ return arg.maxValue && option.setMaxValue(arg.maxValue), arg.minValue && option.setMinValue(arg.minValue), option;
359
244
  });
360
245
  break;
361
246
  }
362
247
  case "number" /* Number */: {
363
248
  builder.addNumberOption((data) => {
364
- const option = setupOption(data);
365
- if (arg.maxValue) {
366
- option.setMaxValue(arg.maxValue);
367
- }
368
- if (arg.minValue) {
369
- option.setMinValue(arg.minValue);
370
- }
371
- return option;
249
+ let option = setupOption(data);
250
+ return arg.maxValue && option.setMaxValue(arg.maxValue), arg.minValue && option.setMinValue(arg.minValue), option;
372
251
  });
373
252
  break;
374
253
  }
@@ -380,12 +259,6 @@ var CommandRegistry = class _CommandRegistry {
380
259
  }
381
260
  }
382
261
  };
383
-
384
- // src/command/Context.ts
385
- import {
386
- ChatInputCommandInteraction,
387
- Message
388
- } from "discord.js";
389
262
  var BaseContext = class {
390
263
  constructor(source) {
391
264
  this.source = source;
@@ -406,25 +279,21 @@ var BaseContext = class {
406
279
  return this.source.guildId;
407
280
  }
408
281
  inGuild() {
409
- return Boolean(this.guildId);
282
+ return !!this.guildId;
410
283
  }
411
284
  inCachedGuild() {
412
- if (this.isChatInput()) {
285
+ if (this.isChatInput())
413
286
  return this.source.inCachedGuild();
414
- } else if (this.isMessage()) {
287
+ if (this.isMessage())
415
288
  return this.source.inGuild();
416
- } else {
417
- throw new Error("Invalid source");
418
- }
289
+ throw new Error("Invalid source");
419
290
  }
420
291
  get author() {
421
- if (this.isChatInput()) {
292
+ if (this.isChatInput())
422
293
  return this.source.user;
423
- } else if (this.isMessage()) {
294
+ if (this.isMessage())
424
295
  return this.source.author;
425
- } else {
426
- throw new Error("Invalid source");
427
- }
296
+ throw new Error("Invalid source");
428
297
  }
429
298
  isChatInput() {
430
299
  return this.source instanceof ChatInputCommandInteraction;
@@ -432,65 +301,45 @@ var BaseContext = class {
432
301
  isMessage() {
433
302
  return this.source instanceof Message;
434
303
  }
435
- };
436
- var ChatInputContext = class extends BaseContext {
304
+ }, ChatInputContext = class extends BaseContext {
437
305
  async send(options) {
438
- if (typeof options === "string") {
439
- options = { content: options };
440
- }
441
- const sendOptions = {
306
+ typeof options == "string" && (options = { content: options });
307
+ let sendOptions = {
442
308
  ...options,
443
309
  withResponse: true
444
310
  };
445
- if (this.source.deferred || this.source.replied) {
446
- return await this.source.followUp(sendOptions);
447
- }
448
- const response = await this.source.reply(sendOptions);
449
- return response.resource?.message;
311
+ return this.source.deferred || this.source.replied ? await this.source.followUp(sendOptions) : (await this.source.reply(sendOptions)).resource?.message;
450
312
  }
451
- };
452
- var MessageContext = class extends BaseContext {
313
+ }, MessageContext = class extends BaseContext {
453
314
  async send(options) {
454
- const { channel } = this;
455
- if (!channel?.isSendable()) {
315
+ let { channel } = this;
316
+ if (!channel?.isSendable())
456
317
  throw new Error("Invalid channel or channel is not sendable");
457
- }
458
318
  return await channel.send(options);
459
319
  }
460
320
  };
461
321
 
462
322
  // src/utils/user.ts
463
323
  function extractId(value) {
464
- const idMatch = value.match(/^<@!?(\d+)>$/);
465
- if (idMatch) {
324
+ let idMatch = value.match(/^<@!?(\d+)>$/);
325
+ if (idMatch)
466
326
  return idMatch[1];
467
- }
468
- const numericMatch = value.match(/^(\d{17,19})$/);
469
- if (numericMatch) {
470
- return numericMatch[1];
471
- }
472
- return null;
327
+ let numericMatch = value.match(/^(\d{17,19})$/);
328
+ return numericMatch ? numericMatch[1] : null;
473
329
  }
474
330
 
475
331
  // src/errors/CommandSyntaxError.ts
476
- var CommandSyntaxErrorType = /* @__PURE__ */ ((CommandSyntaxErrorType2) => {
477
- CommandSyntaxErrorType2["MissingRequireArgument"] = "MISSING_REQUIRE_ARGUMENT";
478
- CommandSyntaxErrorType2["InvalidArgument"] = "INVALID_ARGUMENT";
479
- CommandSyntaxErrorType2["InvalidVariadicArgumentValue"] = "INVALID_VARIADIC_ARGUMENT_VALUE";
480
- return CommandSyntaxErrorType2;
481
- })(CommandSyntaxErrorType || {});
482
- var CommandSyntaxError = class extends Error {
332
+ var CommandSyntaxErrorType = /* @__PURE__ */ ((CommandSyntaxErrorType2) => (CommandSyntaxErrorType2.MissingRequireArgument = "MISSING_REQUIRE_ARGUMENT", CommandSyntaxErrorType2.InvalidArgument = "INVALID_ARGUMENT", CommandSyntaxErrorType2.InvalidVariadicArgumentValue = "INVALID_VARIADIC_ARGUMENT_VALUE", CommandSyntaxErrorType2))(CommandSyntaxErrorType || {}), CommandSyntaxError = class extends Error {
483
333
  arg;
484
334
  type;
485
335
  expected;
486
336
  received;
487
337
  constructor(options) {
488
- let message;
489
- const { arg, type, received } = options;
490
- const expected = Arg.describeArgumentExpectation(arg);
338
+ let message, { arg, type, received } = options, expected = Arg.describeArgumentExpectation(arg);
491
339
  switch (type) {
492
340
  case "MISSING_REQUIRE_ARGUMENT" /* MissingRequireArgument */: {
493
- message = [`Missing required argument "${arg.name}"`, `> Expected: ${expected}`].join("\n");
341
+ message = [`Missing required argument "${arg.name}"`, `> Expected: ${expected}`].join(`
342
+ `);
494
343
  break;
495
344
  }
496
345
  case "INVALID_ARGUMENT" /* InvalidArgument */: {
@@ -498,7 +347,8 @@ var CommandSyntaxError = class extends Error {
498
347
  `Invalid value received for argument "${arg.name}"`,
499
348
  `> Expected: ${expected}`,
500
349
  `> Received: ${String(received)}`
501
- ].join("\n");
350
+ ].join(`
351
+ `);
502
352
  break;
503
353
  }
504
354
  case "INVALID_VARIADIC_ARGUMENT_VALUE" /* InvalidVariadicArgumentValue */: {
@@ -506,7 +356,8 @@ var CommandSyntaxError = class extends Error {
506
356
  `Invalid value received for variadic argument "${arg.name}"`,
507
357
  `> Expected: ${expected}`,
508
358
  `> Received: ${String(received)}`
509
- ].join("\n");
359
+ ].join(`
360
+ `);
510
361
  break;
511
362
  }
512
363
  default: {
@@ -514,12 +365,7 @@ var CommandSyntaxError = class extends Error {
514
365
  break;
515
366
  }
516
367
  }
517
- super(message);
518
- this.arg = arg;
519
- this.type = type;
520
- this.expected = expected;
521
- this.received = received;
522
- Error.captureStackTrace(this, this.constructor);
368
+ super(message), this.arg = arg, this.type = type, this.expected = expected, this.received = received, Error.captureStackTrace(this, this.constructor);
523
369
  }
524
370
  get name() {
525
371
  return `CommandSyntaxError[${this.type}]`;
@@ -554,19 +400,15 @@ var ArgumentResolver = class _ArgumentResolver {
554
400
  return this.options.message.client;
555
401
  }
556
402
  static create(message) {
557
- const client = message.client;
558
- const { enableMentionPrefix } = client.options;
559
- const prefixes = [
403
+ let client = message.client, { enableMentionPrefix } = client.options, prefix = [
560
404
  // Custom prefixes specified in options
561
405
  ...client.options.prefixes ?? [],
562
406
  // Use bot mention as prefix if enabled
563
407
  ...enableMentionPrefix ? [client.user.toString()] : []
564
- ];
565
- const prefix = prefixes.find((p) => message.content.startsWith(p)) ?? null;
566
- if (!prefix) {
408
+ ].find((p) => message.content.startsWith(p)) ?? null;
409
+ if (!prefix)
567
410
  return;
568
- }
569
- const values = message.content.slice(prefix.length).trim().split(/\s+/);
411
+ let values = message.content.slice(prefix.length).trim().split(/\s+/);
570
412
  return new _ArgumentResolver({
571
413
  message,
572
414
  startAt: 1,
@@ -577,108 +419,84 @@ var ArgumentResolver = class _ArgumentResolver {
577
419
  });
578
420
  }
579
421
  async resolve(args) {
580
- const child = new _ArgumentResolver({
422
+ let child = new _ArgumentResolver({
581
423
  prefix: this.options.prefix,
582
424
  message: this.options.message,
583
425
  values: this.options.values,
584
426
  args,
585
427
  startAt: this.options.startAt
586
428
  });
587
- child.parsedValues = [...this.parsedValues];
588
- if (!child.options.args.length) {
589
- return child;
590
- }
591
- if (this.specifiedAmount >= child.options.args.length) {
592
- await child.absoluteParse();
593
- } else {
594
- await child.dynamicParse();
595
- }
596
- return child;
429
+ return child.parsedValues = [...this.parsedValues], child.options.args.length && (this.specifiedAmount >= child.options.args.length ? await child.absoluteParse() : await child.dynamicParse()), child;
597
430
  }
598
431
  async absoluteParse() {
599
- const { args, values, startAt } = this.options;
600
- let valueIndex = startAt;
601
- let argIndex = 0;
602
- while (valueIndex < values.length && argIndex < args.length) {
603
- const value = values[valueIndex];
604
- const arg = args[argIndex];
432
+ let { args, values, startAt } = this.options, valueIndex = startAt, argIndex = 0;
433
+ for (; valueIndex < values.length && argIndex < args.length; ) {
434
+ let value = values[valueIndex], arg = args[argIndex];
605
435
  if (arg.tuple) {
606
436
  this.parsedValues.push(...await this.resolveTuple(arg, valueIndex, argIndex));
607
437
  break;
608
438
  }
609
- const matchedValue = await this.matchValue(arg, value);
610
- if (matchedValue === null) {
439
+ let matchedValue = await this.matchValue(arg, value);
440
+ if (matchedValue === null)
611
441
  throw new CommandSyntaxError({
612
442
  arg,
613
443
  type: "INVALID_ARGUMENT" /* InvalidArgument */,
614
444
  received: value
615
445
  });
616
- }
617
- this.parsedValues.push(matchedValue);
618
- valueIndex++;
619
- argIndex++;
446
+ this.parsedValues.push(matchedValue), valueIndex++, argIndex++;
620
447
  }
621
448
  }
622
449
  async dynamicParse() {
623
- const { args, values } = this.options;
624
- let argIndex = 0;
625
- let valueIndex = this.options.startAt + 1;
626
- while (valueIndex < values.length && argIndex < args.length) {
627
- const value = values[valueIndex];
628
- const arg = args[argIndex];
450
+ let { args, values } = this.options, argIndex = 0, valueIndex = this.options.startAt + 1;
451
+ for (; valueIndex < values.length && argIndex < args.length; ) {
452
+ let value = values[valueIndex], arg = args[argIndex];
629
453
  if (arg.tuple) {
630
454
  this.parsedValues.push(...await this.resolveTuple(arg, valueIndex, argIndex));
631
455
  break;
632
456
  }
633
- const matchedValue = await this.matchValue(arg, value);
634
- if (matchedValue !== null) {
635
- this.parsedValues.push(matchedValue);
636
- valueIndex++;
637
- } else if (arg.required) {
457
+ let matchedValue = await this.matchValue(arg, value);
458
+ if (matchedValue !== null)
459
+ this.parsedValues.push(matchedValue), valueIndex++;
460
+ else if (arg.required)
638
461
  throw new CommandSyntaxError({
639
462
  arg,
640
463
  type: "MISSING_REQUIRE_ARGUMENT" /* MissingRequireArgument */,
641
464
  received: value
642
465
  });
643
- }
644
466
  argIndex++;
645
467
  }
646
- while (argIndex < args.length) {
647
- const arg = args[argIndex];
648
- if (arg.required) {
468
+ for (; argIndex < args.length; ) {
469
+ let arg = args[argIndex];
470
+ if (arg.required)
649
471
  throw new CommandSyntaxError({
650
472
  arg,
651
473
  type: "MISSING_REQUIRE_ARGUMENT" /* MissingRequireArgument */,
652
474
  received: "nothing"
653
475
  });
654
- }
655
476
  argIndex++;
656
477
  }
657
478
  }
658
479
  async resolveTuple(arg, startIndex, argIndex) {
659
- const { args } = this.options;
660
- if (argIndex !== args.length - 1) {
480
+ let { args } = this.options;
481
+ if (argIndex !== args.length - 1)
661
482
  throw new SyntaxError("Tuple argument must be the last argument");
662
- }
663
- const values = [];
664
- for (const rest of this.values.slice(startIndex)) {
665
- const matchedValue = await this.matchValue(arg, rest);
666
- if (matchedValue === null) {
483
+ let values = [];
484
+ for (let rest of this.values.slice(startIndex)) {
485
+ let matchedValue = await this.matchValue(arg, rest);
486
+ if (matchedValue === null)
667
487
  throw new CommandSyntaxError({
668
488
  arg,
669
489
  type: "INVALID_VARIADIC_ARGUMENT_VALUE" /* InvalidVariadicArgumentValue */,
670
490
  received: rest
671
491
  });
672
- }
673
492
  values.push(matchedValue);
674
493
  }
675
- if (values.length === 0 && arg.required) {
494
+ if (values.length === 0 && arg.required)
676
495
  throw new CommandSyntaxError({
677
496
  arg,
678
497
  type: "MISSING_REQUIRE_ARGUMENT" /* MissingRequireArgument */,
679
498
  received: "nothing"
680
499
  });
681
- }
682
500
  return values;
683
501
  }
684
502
  async matchValue(arg, value) {
@@ -696,50 +514,22 @@ var ArgumentResolver = class _ArgumentResolver {
696
514
  }
697
515
  }
698
516
  async matchUserValue(arg, value) {
699
- const userId = extractId(value);
700
- if (!userId) {
701
- return null;
702
- }
703
- const user2 = await this.client.users.fetch(userId).catch(() => null);
704
- if (!user2) {
517
+ let userId = extractId(value);
518
+ if (!userId)
705
519
  return null;
706
- }
707
- return user2;
520
+ let user2 = await this.client.users.fetch(userId).catch(() => null);
521
+ return user2 || null;
708
522
  }
709
523
  matchIntegerValue(arg, value) {
710
- const intVal = parseInt(value, 10);
711
- if (isNaN(intVal)) {
712
- return null;
713
- }
714
- if (arg.minValue !== void 0 && intVal < arg.minValue) {
715
- return null;
716
- }
717
- if (arg.maxValue !== void 0 && intVal > arg.maxValue) {
718
- return null;
719
- }
720
- return intVal;
524
+ let intVal = parseInt(value, 10);
525
+ return isNaN(intVal) || arg.minValue !== void 0 && intVal < arg.minValue || arg.maxValue !== void 0 && intVal > arg.maxValue ? null : intVal;
721
526
  }
722
527
  matchNumberValue(arg, value) {
723
- const numVal = parseFloat(value);
724
- if (isNaN(numVal)) {
725
- return null;
726
- }
727
- if (arg.minValue !== void 0 && numVal < arg.minValue) {
728
- return null;
729
- }
730
- if (arg.maxValue !== void 0 && numVal > arg.maxValue) {
731
- return null;
732
- }
733
- return numVal;
528
+ let numVal = parseFloat(value);
529
+ return isNaN(numVal) || arg.minValue !== void 0 && numVal < arg.minValue || arg.maxValue !== void 0 && numVal > arg.maxValue ? null : numVal;
734
530
  }
735
531
  matchStringValue(arg, value) {
736
- if (arg.minLength !== void 0 && value.length < arg.minLength) {
737
- return null;
738
- }
739
- if (arg.maxLength !== void 0 && value.length > arg.maxLength) {
740
- return null;
741
- }
742
- return value;
532
+ return arg.minLength !== void 0 && value.length < arg.minLength || arg.maxLength !== void 0 && value.length > arg.maxLength ? null : value;
743
533
  }
744
534
  static resolveChatInput(interaction, arg) {
745
535
  switch (arg.type) {
@@ -758,41 +548,33 @@ var ArgumentResolver = class _ArgumentResolver {
758
548
  }
759
549
  }
760
550
  };
761
-
762
- // src/libs/StateBox.ts
763
- import { AsyncLocalStorage } from "async_hooks";
764
551
  var StateBox = class _StateBox {
765
552
  static STATES_KEY = Symbol("states");
766
553
  static storage = new AsyncLocalStorage();
767
554
  static getState() {
768
- const state = this.storage.getStore();
769
- if (!state) {
555
+ let state = this.storage.getStore();
556
+ if (!state)
770
557
  throw new Error("No active context, did you forget to wrap it with StateBox.wrap()?");
771
- }
772
558
  return state;
773
559
  }
774
560
  static run(fn, store2 = {}) {
775
561
  return this.storage.run(store2, fn);
776
562
  }
777
563
  static wrap(fn) {
778
- const currentStore = this.storage.getStore();
779
- if (!currentStore) {
564
+ let currentStore = this.storage.getStore();
565
+ if (!currentStore)
780
566
  throw new Error("No active context, cannot wrap function outside a StateBox.run()");
781
- }
782
567
  return () => this.run(fn, currentStore);
783
568
  }
784
569
  static use(defaultValue) {
785
570
  return (target, key) => {
786
571
  Object.defineProperty(target, key, {
787
572
  get() {
788
- const states = _StateBox.getState();
789
- if (!(key in states)) {
790
- states[key] = defaultValue;
791
- }
792
- return states[key];
573
+ let states = _StateBox.getState();
574
+ return key in states || (states[key] = defaultValue), states[key];
793
575
  },
794
576
  set(value) {
795
- const states = _StateBox.getState();
577
+ let states = _StateBox.getState();
796
578
  states[key] = value;
797
579
  },
798
580
  enumerable: true,
@@ -813,7 +595,7 @@ var ListenerEntry = class extends BaseEntry {
813
595
  // src/listener/Listener.ts
814
596
  var ListenerAPI;
815
597
  ((ListenerAPI2) => {
816
- const entries = /* @__PURE__ */ new WeakMap();
598
+ let entries = /* @__PURE__ */ new WeakMap();
817
599
  function use(entry) {
818
600
  return (target) => {
819
601
  entries.set(target, entry);
@@ -824,16 +606,12 @@ var ListenerAPI;
824
606
  return entries.get(target);
825
607
  }
826
608
  ListenerAPI2.getEntry = getEntry;
827
- })(ListenerAPI || (ListenerAPI = {}));
609
+ })(ListenerAPI ||= {});
828
610
  function ListenerFactory(options) {
829
- const fullOptions = typeof options !== "object" ? { name: options, once: false } : { once: false, ...options };
611
+ let fullOptions = typeof options != "object" ? { name: options, once: false } : { once: false, ...options };
830
612
  return new ListenerEntry(fullOptions);
831
613
  }
832
614
  var Listener = Object.assign(ListenerFactory, ListenerAPI);
833
-
834
- // src/listener/ListenerRegistry.ts
835
- import glob2 from "tiny-glob";
836
- import { pathToFileURL as pathToFileURL2 } from "url";
837
615
  var ListenerRegistry = class {
838
616
  static client;
839
617
  static constructors = /* @__PURE__ */ new Set();
@@ -845,24 +623,18 @@ var ListenerRegistry = class {
845
623
  * @param constructor The listener class you want to add.
846
624
  */
847
625
  static add(constructor) {
848
- const entry = Listener.getEntry(constructor);
849
- if (!entry) {
626
+ let entry = Listener.getEntry(constructor);
627
+ if (!entry)
850
628
  throw new Error(`No entry found for "${constructor.name}"`);
851
- }
852
- const { options } = entry;
629
+ let { options } = entry;
853
630
  if (!options.emitter) {
854
- if (!this.client) {
631
+ if (!this.client)
855
632
  throw new Error("Client is not ready.");
856
- }
857
633
  options.emitter = this.client;
858
634
  }
859
- const instance = new constructor();
860
- const executor = this.createExecutor(constructor, instance);
861
- this.constructors.add(constructor);
862
- this.instances.set(constructor, instance);
863
- this.executors.set(instance, executor);
864
- options.emitter[options.once ? "once" : "on"](options.name, (...args) => {
865
- void executor(...args);
635
+ let instance = new constructor(), executor = this.createExecutor(constructor, instance);
636
+ this.constructors.add(constructor), this.instances.set(constructor, instance), this.executors.set(instance, executor), options.emitter[options.once ? "once" : "on"](options.name, (...args) => {
637
+ executor(...args);
866
638
  });
867
639
  }
868
640
  /**
@@ -871,24 +643,19 @@ var ListenerRegistry = class {
871
643
  * @returns `boolean`, returns `true` if the listener is removed successfully.
872
644
  */
873
645
  static remove(constructor) {
874
- const entry = Listener.getEntry(constructor);
875
- if (!entry) {
646
+ let entry = Listener.getEntry(constructor);
647
+ if (!entry)
876
648
  return false;
877
- }
878
649
  this.constructors.delete(constructor);
879
- const instance = this.instances.get(constructor);
880
- if (!instance) {
650
+ let instance = this.instances.get(constructor);
651
+ if (!instance)
881
652
  return false;
882
- }
883
653
  this.instances.delete(constructor);
884
- const executor = this.executors.get(instance);
885
- if (!executor) {
654
+ let executor = this.executors.get(instance);
655
+ if (!executor)
886
656
  return false;
887
- }
888
- const { name, emitter } = entry.options;
889
- emitter?.removeListener(name, executor);
890
- this.executors.delete(instance);
891
- return true;
657
+ let { name, emitter } = entry.options;
658
+ return emitter?.removeListener(name, executor), this.executors.delete(instance), true;
892
659
  }
893
660
  /**
894
661
  * Remove and unregister all listeners from the registry.
@@ -896,11 +663,8 @@ var ListenerRegistry = class {
896
663
  */
897
664
  static removeAll() {
898
665
  let removedAmount = 0;
899
- for (const constructor of this.constructors) {
900
- if (this.remove(constructor)) {
901
- removedAmount++;
902
- }
903
- }
666
+ for (let constructor of this.constructors)
667
+ this.remove(constructor) && removedAmount++;
904
668
  return removedAmount;
905
669
  }
906
670
  /**
@@ -911,38 +675,25 @@ var ListenerRegistry = class {
911
675
  this.client = newClient;
912
676
  }
913
677
  static createExecutor(constructor, instance) {
914
- const entry = Listener.getEntry(constructor);
915
- if (!entry) {
678
+ let entry = Listener.getEntry(constructor);
679
+ if (!entry)
916
680
  throw new Error("Missing listener entry");
917
- }
918
- const { hooks } = entry;
681
+ let { hooks } = entry;
919
682
  return async function(...args) {
920
- const mainHook = hooks["MAIN" /* Main */];
921
- const preHook = hooks["PRE" /* Pre */];
922
- const postHook = hooks["POST" /* Post */];
923
- const errorHook = hooks["ERROR" /* Error */];
924
- if (!mainHook) {
925
- return;
926
- }
927
- try {
928
- if (preHook) {
929
- await preHook.method.call(instance, ...args);
930
- }
931
- await mainHook.method.call(instance, ...args);
932
- if (postHook) {
933
- await postHook.method.call(instance, ...args);
934
- }
935
- } catch (error) {
936
- if (errorHook) {
937
- await errorHook.method.call(
938
- instance,
939
- error,
940
- ...args
941
- );
942
- } else {
943
- throw error;
683
+ let mainHook = hooks.MAIN, preHook = hooks.PRE, postHook = hooks.POST, errorHook = hooks.ERROR;
684
+ if (mainHook)
685
+ try {
686
+ preHook && await preHook.method.call(instance, ...args), await mainHook.method.call(instance, ...args), postHook && await postHook.method.call(instance, ...args);
687
+ } catch (error) {
688
+ if (errorHook)
689
+ await errorHook.method.call(
690
+ instance,
691
+ error,
692
+ ...args
693
+ );
694
+ else
695
+ throw error;
944
696
  }
945
- }
946
697
  };
947
698
  }
948
699
  /**
@@ -952,20 +703,15 @@ var ListenerRegistry = class {
952
703
  * @returns All loaded listener constructors.
953
704
  */
954
705
  static async load(pattern, parallel = true) {
955
- const files = await glob2(pattern);
956
- const loaders = files.map(async (file) => {
957
- const fileURL = pathToFileURL2(file).toString();
958
- const { default: constructor } = await import(fileURL);
959
- this.add(constructor);
960
- return constructor;
706
+ let loaders = (await glob(pattern)).map(async (file) => {
707
+ let fileURL = pathToFileURL(file).toString(), { default: constructor } = await import(fileURL);
708
+ return this.add(constructor), constructor;
961
709
  });
962
- if (parallel) {
710
+ if (parallel)
963
711
  return Promise.all(loaders);
964
- }
965
- const result = [];
966
- for (const loader of loaders) {
712
+ let result = [];
713
+ for (let loader of loaders)
967
714
  result.push(await loader);
968
- }
969
715
  return result;
970
716
  }
971
717
  };
@@ -973,197 +719,125 @@ var ListenerRegistry = class {
973
719
  // src/BakitClient.ts
974
720
  var BakitClient = class _BakitClient extends Client {
975
721
  constructor(options) {
976
- if (options.getSyntaxErrorMessage === void 0) {
977
- options.getSyntaxErrorMessage = _BakitClient.getSyntaxErrorMessage;
978
- }
979
- super(options);
980
- ListenerRegistry["setClient"](this);
981
- this.once(
722
+ options.getSyntaxErrorMessage === void 0 && (options.getSyntaxErrorMessage = _BakitClient.getSyntaxErrorMessage), super(options), ListenerRegistry.setClient(this), this.once(
982
723
  Events.ClientReady,
983
724
  (client) => void this.registerApplicationCommands(client)
984
- );
985
- this.on(Events.InteractionCreate, (interaction) => void this.handleInteraction(interaction));
986
- this.on(Events.MessageCreate, (message) => void this.handleMessage(message));
725
+ ), this.on(Events.InteractionCreate, (interaction) => void this.handleInteraction(interaction)), this.on(Events.MessageCreate, (message) => void this.handleMessage(message));
987
726
  }
988
727
  static getSyntaxErrorMessage = (command, error, context, args, prefix) => {
989
- const requiredSyntax = args.map((x) => Arg.format(x)).join(" ");
990
- const root = Command.getRoot(command.constructor);
991
- if (!root) {
992
- return;
993
- }
994
- const content = [
995
- codeBlock(error.message),
996
- "Required Syntax:",
997
- codeBlock(`${prefix}${root.options.name} ${requiredSyntax}`)
998
- ].join("\n");
999
- return {
1000
- content
1001
- };
728
+ let requiredSyntax = args.map((x) => Arg.format(x)).join(" "), root = Command.getRoot(command.constructor);
729
+ return root ? {
730
+ content: [
731
+ codeBlock(error.message),
732
+ "Required Syntax:",
733
+ codeBlock(`${prefix}${root.options.name} ${requiredSyntax}`)
734
+ ].join(`
735
+ `)
736
+ } : void 0;
1002
737
  };
1003
738
  async registerApplicationCommands(client) {
1004
- const commands = CommandRegistry.constructors.map((c) => CommandRegistry.buildSlashCommand(c));
739
+ let commands = CommandRegistry.constructors.map((c) => CommandRegistry.buildSlashCommand(c));
1005
740
  await client.application.commands.set(commands);
1006
741
  }
1007
742
  async handleMessage(message) {
1008
- if (message.author.bot) {
1009
- return;
1010
- }
1011
- const context = new MessageContext(message);
1012
- const resolver = ArgumentResolver.create(message);
1013
- if (!resolver) {
743
+ if (message.author.bot)
1014
744
  return;
1015
- }
1016
- const { trigger } = resolver;
1017
- const command = CommandRegistry.instances.get(trigger);
1018
- if (!command) {
745
+ let context = new MessageContext(message), resolver = ArgumentResolver.create(message);
746
+ if (!resolver)
1019
747
  return;
1020
- }
1021
- await StateBox.run(() => this.handleMessageHooks(context, command, resolver));
748
+ let { trigger } = resolver, command = CommandRegistry.instances.get(trigger);
749
+ command && await StateBox.run(() => this.handleMessageHooks(context, command, resolver));
1022
750
  }
1023
751
  async handleInteraction(interaction) {
1024
- if (!interaction.isChatInputCommand()) {
752
+ if (!interaction.isChatInputCommand())
1025
753
  return;
1026
- }
1027
- const { commandName } = interaction;
1028
- const command = CommandRegistry.instances.get(commandName);
1029
- if (!command) {
754
+ let { commandName } = interaction, command = CommandRegistry.instances.get(commandName);
755
+ if (!command)
1030
756
  return;
1031
- }
1032
- const context = new ChatInputContext(interaction);
757
+ let context = new ChatInputContext(interaction);
1033
758
  await StateBox.run(() => this.handleChatInputHooks(context, command));
1034
759
  }
1035
760
  async handleChatInputHooks(context, instance) {
1036
- const targetHooks = this.getChatInputTargetHooks(context.source, instance);
1037
- let inheritedArgs = [];
1038
- for (const hooks of [targetHooks.root, targetHooks.group, targetHooks.subcommand]) {
1039
- if (!hooks) {
761
+ let targetHooks = this.getChatInputTargetHooks(context.source, instance), inheritedArgs = [];
762
+ for (let hooks of [targetHooks.root, targetHooks.group, targetHooks.subcommand]) {
763
+ if (!hooks)
1040
764
  continue;
1041
- }
1042
- const newArgs = await this.runChatInputHooks(context, instance, hooks, inheritedArgs);
1043
- if (newArgs) {
1044
- inheritedArgs = newArgs;
1045
- }
765
+ let newArgs = await this.runChatInputHooks(context, instance, hooks, inheritedArgs);
766
+ newArgs && (inheritedArgs = newArgs);
1046
767
  }
1047
768
  }
1048
769
  async handleMessageHooks(context, instance, resolver) {
1049
- if (!resolver) {
1050
- return;
1051
- }
1052
- const root = Command.getRoot(instance.constructor);
1053
- if (!root) {
1054
- return;
1055
- }
1056
- resolver = await this.runMessageHooks(context, instance, root.hooks, resolver);
1057
- if (!resolver) {
770
+ if (!resolver)
1058
771
  return;
1059
- }
1060
- await this.handleChildMessageHooks(context, root, instance, resolver);
772
+ let root = Command.getRoot(instance.constructor);
773
+ root && (resolver = await this.runMessageHooks(context, instance, root.hooks, resolver), resolver && await this.handleChildMessageHooks(context, root, instance, resolver));
1061
774
  }
1062
775
  async handleChildMessageHooks(context, parent, instance, resolver, skip = 1) {
1063
- if (!resolver) {
1064
- return;
1065
- }
1066
- const usedValues = resolver.parsedValues.length;
1067
- const nextTrigger = resolver.values[usedValues + skip];
1068
- const child = parent.children.get(nextTrigger);
1069
- if (!child) {
776
+ if (!resolver)
1070
777
  return;
1071
- }
1072
- resolver = await this.runMessageHooks(context, instance, child.hooks, resolver);
1073
- if (child instanceof CommandGroupEntry) {
1074
- await this.handleChildMessageHooks(context, child, instance, resolver, skip + 1);
1075
- }
778
+ let usedValues = resolver.parsedValues.length, nextTrigger = resolver.values[usedValues + skip], child = parent.children.get(nextTrigger);
779
+ child && (resolver = await this.runMessageHooks(context, instance, child.hooks, resolver), child instanceof CommandGroupEntry && await this.handleChildMessageHooks(context, child, instance, resolver, skip + 1));
1076
780
  }
1077
781
  async runMessageHooks(context, instance, hooks, resolver) {
1078
- const mainHook = hooks["MAIN" /* Main */];
1079
- if (!mainHook) {
782
+ let mainHook = hooks.MAIN;
783
+ if (!mainHook)
1080
784
  return resolver;
1081
- }
1082
- const args = Arg.getMethodArguments(mainHook.method);
785
+ let args = Arg.getMethodArguments(mainHook.method);
1083
786
  try {
1084
787
  resolver = await resolver.resolve(args);
1085
788
  } catch (error) {
1086
789
  if (error instanceof CommandSyntaxError) {
1087
- const errorContent = await this.options.getSyntaxErrorMessage?.(
790
+ let errorContent = await this.options.getSyntaxErrorMessage?.(
1088
791
  instance,
1089
792
  error,
1090
793
  context,
1091
794
  args,
1092
795
  resolver.options.prefix
1093
796
  );
1094
- if (errorContent) {
1095
- await context.send(errorContent);
1096
- }
1097
- return null;
797
+ return errorContent && await context.send(errorContent), null;
1098
798
  }
1099
799
  throw error;
1100
800
  }
1101
- await this.runHooks(context, instance, hooks, resolver.parsedValues);
1102
- return resolver;
801
+ return await this.runHooks(context, instance, hooks, resolver.parsedValues), resolver;
1103
802
  }
1104
803
  async runChatInputHooks(context, instance, hooks, inheritedArgs) {
1105
- const mainHook = hooks["MAIN" /* Main */];
1106
- if (!mainHook) {
804
+ let mainHook = hooks.MAIN;
805
+ if (!mainHook)
1107
806
  return;
1108
- }
1109
- const newArgs = Arg.getMethodArguments(mainHook.method).map(
807
+ let newArgs = Arg.getMethodArguments(mainHook.method).map(
1110
808
  (arg) => ArgumentResolver.resolveChatInput(context.source, arg)
1111
- );
1112
- const argValues = [...inheritedArgs, ...newArgs];
1113
- await this.runHooks(context, instance, hooks, argValues);
1114
- return argValues;
809
+ ), argValues = [...inheritedArgs, ...newArgs];
810
+ return await this.runHooks(context, instance, hooks, argValues), argValues;
1115
811
  }
1116
812
  async runHooks(context, instance, hooks, args) {
1117
- const mainHook = hooks["MAIN" /* Main */];
1118
- const preHook = hooks["PRE" /* Pre */];
1119
- const postHook = hooks["POST" /* Post */];
1120
- const errorHook = hooks["ERROR" /* Error */];
1121
- if (!mainHook) {
813
+ let mainHook = hooks.MAIN, preHook = hooks.PRE, postHook = hooks.POST, errorHook = hooks.ERROR;
814
+ if (!mainHook)
1122
815
  return;
1123
- }
1124
- const execute = async (hook, error) => {
1125
- if (!hook) {
1126
- return;
1127
- }
1128
- if (hook.state === "ERROR" /* Error */) {
1129
- await hook.method.call(instance, error, context, ...args);
1130
- } else {
1131
- await hook.method.call(instance, context, ...args);
1132
- }
816
+ let execute = async (hook, error) => {
817
+ hook && (hook.state === "ERROR" /* Error */ ? await hook.method.call(instance, error, context, ...args) : await hook.method.call(instance, context, ...args));
1133
818
  };
1134
819
  try {
1135
- await execute(preHook);
1136
- await execute(mainHook);
1137
- await execute(postHook);
820
+ await execute(preHook), await execute(mainHook), await execute(postHook);
1138
821
  } catch (error) {
1139
- if (errorHook) {
822
+ if (errorHook)
1140
823
  await execute(errorHook, error);
1141
- } else {
824
+ else
1142
825
  throw error;
1143
- }
1144
826
  }
1145
827
  }
1146
828
  getChatInputTargetHooks(interaction, instance) {
1147
- const subcommandName = interaction.options.getSubcommand(false);
1148
- const groupName = interaction.options.getSubcommandGroup(false);
1149
- const root = Command.getRoot(instance.constructor);
1150
- if (!root) {
829
+ let subcommandName = interaction.options.getSubcommand(false), groupName = interaction.options.getSubcommandGroup(false), root = Command.getRoot(instance.constructor);
830
+ if (!root)
1151
831
  throw new Error("No root found.");
1152
- }
1153
832
  let group;
1154
833
  if (groupName) {
1155
- const child = root.children.get(groupName);
1156
- if (child instanceof CommandGroupEntry) {
1157
- group = child;
1158
- }
834
+ let child = root.children.get(groupName);
835
+ child instanceof CommandGroupEntry && (group = child);
1159
836
  }
1160
837
  let subcommand;
1161
838
  if (subcommandName) {
1162
- const parent = group || root;
1163
- const child = parent.children.get(subcommandName);
1164
- if (child instanceof SubcommandEntry) {
1165
- subcommand = child;
1166
- }
839
+ let child = (group || root).children.get(subcommandName);
840
+ child instanceof SubcommandEntry && (subcommand = child);
1167
841
  }
1168
842
  return {
1169
843
  root: root.hooks,
@@ -1172,29 +846,5 @@ var BakitClient = class _BakitClient extends Client {
1172
846
  };
1173
847
  }
1174
848
  };
1175
- export {
1176
- Arg,
1177
- ArgumentType,
1178
- BakitClient,
1179
- BaseCommandEntry,
1180
- BaseCommandGroupEntry,
1181
- BaseContext,
1182
- ChatInputContext,
1183
- Command,
1184
- CommandAPI,
1185
- CommandFactory,
1186
- CommandGroupEntry,
1187
- CommandRegistry,
1188
- CommandSyntaxError,
1189
- CommandSyntaxErrorType,
1190
- Listener,
1191
- ListenerAPI,
1192
- ListenerEntry,
1193
- ListenerFactory,
1194
- ListenerRegistry,
1195
- MessageContext,
1196
- RootCommandEntry,
1197
- StateBox,
1198
- SubcommandEntry,
1199
- extractId
1200
- };
849
+
850
+ export { Arg, ArgumentType, BakitClient, BaseCommandEntry, BaseCommandGroupEntry, BaseContext, ChatInputContext, Command, CommandAPI, CommandFactory, CommandGroupEntry, CommandRegistry, CommandSyntaxError, CommandSyntaxErrorType, Listener, ListenerAPI, ListenerEntry, ListenerFactory, ListenerRegistry, MessageContext, RootCommandEntry, StateBox, SubcommandEntry, extractId };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bakit",
3
- "version": "1.0.0-beta.13",
3
+ "version": "1.0.0-beta.14",
4
4
  "description": "A framework for discord.js",
5
5
  "type": "module",
6
6
  "exports": {