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