bakit 2.0.0-alpha.1 → 2.0.0-alpha.3

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.d.ts CHANGED
@@ -1,9 +1,14 @@
1
- import { GatewayIntentBits, ClientOptions, Message, Awaitable, ClientEvents, Client } from 'discord.js';
2
- import { z } from 'zod';
1
+ import * as discord_js from 'discord.js';
2
+ import { GatewayIntentBits, ClientOptions, ChatInputCommandInteraction, CacheType, Message, User, MessageCreateOptions, InteractionReplyOptions, Awaitable, Collection, ClientEvents, Events, IntentsBitField, Client } from 'discord.js';
3
+ import z$1, { z } from 'zod';
4
+ import { inspect } from 'node:util';
3
5
 
4
6
  declare const ProjectConfigSchema: z.ZodObject<{
5
7
  intents: z.ZodDefault<z.ZodUnion<readonly [z.ZodLiteral<"auto">, z.ZodBigInt, z.ZodArray<z.ZodEnum<typeof GatewayIntentBits>>]>>;
6
8
  clientOptions: z.ZodOptional<z.ZodCustom<Omit<ClientOptions, "intents">, Omit<ClientOptions, "intents">>>;
9
+ entryDir: z.ZodDefault<z.ZodString>;
10
+ prefixes: z.ZodDefault<z.ZodArray<z.ZodString>>;
11
+ token: z.ZodString;
7
12
  }, z.core.$strip>;
8
13
  type ProjectConfigInput = z.input<typeof ProjectConfigSchema>;
9
14
  type ProjectConfig = z.output<typeof ProjectConfigSchema>;
@@ -25,13 +30,289 @@ declare function loadConfig(cwd?: string): Promise<ProjectConfig>;
25
30
  */
26
31
  declare function getConfig(): ProjectConfig;
27
32
 
33
+ declare class Context {
34
+ canceled: boolean;
35
+ cancel(): void;
36
+ }
37
+
38
+ type ChatInputContextSendOptions = string | InteractionReplyOptions;
39
+ type MessageContextSendOptions = string | MessageCreateOptions;
40
+ type ContextSendOptions = ChatInputContextSendOptions | MessageContextSendOptions;
41
+ declare abstract class BaseCommandContext<Cached extends boolean, InGuild extends boolean> extends Context {
42
+ source: ChatInputCommandInteraction<Cached extends true ? "cached" : CacheType> | Message<InGuild>;
43
+ constructor(source: ChatInputCommandInteraction<Cached extends true ? "cached" : CacheType> | Message<InGuild>);
44
+ get client(): BakitClient<true>;
45
+ get channel(): discord_js.CacheTypeReducer<Cached extends true ? "cached" : CacheType, discord_js.GuildTextBasedChannel | null, discord_js.GuildTextBasedChannel | null, discord_js.GuildTextBasedChannel | null, discord_js.TextBasedChannel | null> | discord_js.If<InGuild, discord_js.GuildTextBasedChannel, discord_js.TextBasedChannel>;
46
+ get channelId(): string;
47
+ get guild(): discord_js.CacheTypeReducer<Cached extends true ? "cached" : CacheType, discord_js.Guild, null, discord_js.Guild | null, discord_js.Guild | null> | discord_js.If<InGuild, discord_js.Guild, null>;
48
+ get guildId(): discord_js.CacheTypeReducer<Cached extends true ? "cached" : CacheType, string, string, string, string | null> | discord_js.If<InGuild, string, null>;
49
+ get member(): discord_js.GuildMember | discord_js.CacheTypeReducer<Cached extends true ? "cached" : CacheType, discord_js.GuildMember, discord_js.APIInteractionGuildMember, discord_js.GuildMember | discord_js.APIInteractionGuildMember, discord_js.GuildMember | discord_js.APIInteractionGuildMember | null> | null;
50
+ inGuild(): this is CommandContext<Cached, true>;
51
+ inCachedGuild(): this is CommandContext<true, true>;
52
+ get user(): User;
53
+ isChatInput(): this is ChatInputContext;
54
+ isMessage(): this is MessageContext;
55
+ abstract send(options: ContextSendOptions): Promise<Message<InGuild>>;
56
+ }
57
+ declare class ChatInputContext<Cached extends boolean = boolean, InGuild extends boolean = boolean> extends BaseCommandContext<Cached, InGuild> {
58
+ source: ChatInputCommandInteraction<Cached extends true ? "cached" : CacheType>;
59
+ send(options: ContextSendOptions): Promise<Message<InGuild>>;
60
+ }
61
+ declare class MessageContext<Cached extends boolean = boolean, InGuild extends boolean = boolean> extends BaseCommandContext<Cached, InGuild> {
62
+ source: Message<InGuild>;
63
+ send(options: string | MessageCreateOptions): Promise<Message<InGuild>>;
64
+ }
65
+ type CommandContext<Cached extends boolean = boolean, InGuild extends boolean = boolean> = ChatInputContext<Cached, InGuild> | MessageContext<Cached, InGuild>;
66
+
67
+ declare enum HookState {
68
+ Pre = "PRE",
69
+ Main = "MAIN",
70
+ Post = "POST",
71
+ Error = "ERROR"
72
+ }
73
+ declare enum HookOrder {
74
+ First = 0,
75
+ Last = 1
76
+ }
77
+ type MainHookCallback<C extends Context, Args extends unknown[]> = (context: C, ...args: Args) => Awaitable<void>;
78
+ type ErrorHookCallback<C extends Context, Args extends unknown[]> = (context: C, error: unknown, ...args: Args) => Awaitable<void>;
79
+ declare class LifecycleManager<C extends Context, Args extends unknown[]> {
80
+ id: string;
81
+ private readonly hooks;
82
+ constructor(id: string);
83
+ getName(name: string): string;
84
+ setHook(name: string, state: HookState.Post, callback: MainHookCallback<C, Args>, order?: HookOrder): this;
85
+ setHook(name: string, state: HookState.Main, callback: MainHookCallback<C, Args>, order?: HookOrder): this;
86
+ setHook(name: string, state: HookState.Pre, callback: MainHookCallback<C, Args>, order?: HookOrder): this;
87
+ setHook(name: string, state: HookState.Error, callback: ErrorHookCallback<C, Args>, order?: HookOrder): this;
88
+ main(callback: MainHookCallback<C, Args>): this;
89
+ pre(callback: MainHookCallback<C, Args>): this;
90
+ post(callback: MainHookCallback<C, Args>): this;
91
+ error(callback: ErrorHookCallback<C, Args>): this;
92
+ execute(context: C, ...args: Args): Promise<void>;
93
+ }
94
+
95
+ declare enum ParamUserType {
96
+ Bot = "bot",
97
+ Normal = "normal",
98
+ Any = "any"
99
+ }
100
+ declare const BaseParamSchema: z.ZodObject<{
101
+ name: z.ZodString;
102
+ description: z.ZodOptional<z.ZodString>;
103
+ required: z.ZodDefault<z.ZodBoolean>;
104
+ }, z.core.$strip>;
105
+ declare const StringParamSchema: z.ZodObject<{
106
+ name: z.ZodString;
107
+ description: z.ZodOptional<z.ZodString>;
108
+ required: z.ZodDefault<z.ZodBoolean>;
109
+ maxLength: z.ZodOptional<z.ZodNumber>;
110
+ minLength: z.ZodOptional<z.ZodNumber>;
111
+ }, z.core.$strip>;
112
+ declare const NumberParamSchema: z.ZodObject<{
113
+ name: z.ZodString;
114
+ description: z.ZodOptional<z.ZodString>;
115
+ required: z.ZodDefault<z.ZodBoolean>;
116
+ maxValue: z.ZodOptional<z.ZodNumber>;
117
+ minValue: z.ZodOptional<z.ZodNumber>;
118
+ }, z.core.$strip>;
119
+ type BaseParamOptions = z.input<typeof BaseParamSchema>;
120
+ type StringOptions = z.input<typeof StringParamSchema>;
121
+ type NumberOptions = z.input<typeof NumberParamSchema>;
122
+
123
+ type ParamResolvedOutputType<OutputType, Required extends boolean = true> = Required extends true ? OutputType : OutputType | null;
124
+ declare abstract class BaseParam<Options extends BaseParamOptions, OutputType, Required extends boolean = true> {
125
+ options: Options & {
126
+ required: Required;
127
+ };
128
+ /**
129
+ * **Internal Phantom Type**
130
+ *
131
+ * Used strictly for TypeScript type inference to determine the runtime value
132
+ * of this parameter. This property does not exist at runtime.
133
+ *
134
+ * @internal
135
+ */
136
+ readonly _type: Required extends true ? OutputType : OutputType | null;
137
+ constructor(options: Options);
138
+ protected setOption(key: keyof Options, value: any): this;
139
+ name(value: string): this;
140
+ description(value: string): this;
141
+ required<V extends boolean>(value: V): BaseParam<Options, OutputType, V>;
142
+ resolve(context: CommandContext, value?: string): Promise<ParamResolvedOutputType<OutputType, Required>>;
143
+ abstract resolveMessage(context: MessageContext, value: string | undefined): Awaitable<ParamResolvedOutputType<OutputType, Required>>;
144
+ abstract resolveChatInput(context: ChatInputContext): Awaitable<ParamResolvedOutputType<OutputType, Required>>;
145
+ /**
146
+ * Helper to normalize string inputs into an options object.
147
+ */
148
+ protected static getOptions<Options>(options: Options | string): Options;
149
+ }
150
+ declare class StringParam<Required extends boolean = true> extends BaseParam<StringOptions, string, Required> {
151
+ constructor(options: string | StringOptions);
152
+ required<V extends boolean>(value: V): StringParam<V>;
153
+ resolveMessage(_context: CommandContext, value: string | undefined): ParamResolvedOutputType<string, Required>;
154
+ resolveChatInput(context: ChatInputContext): ParamResolvedOutputType<string, Required>;
155
+ /**
156
+ * Sets the minimum allowed length for this string.
157
+ * Pass `null` to remove this constraint.
158
+ */
159
+ min(length: number | null): this;
160
+ /**
161
+ * Sets the maximum allowed length for this string.
162
+ * Pass `null` to remove this constraint.
163
+ */
164
+ max(length: number | null): this;
165
+ }
166
+ declare class NumberParam<Required extends boolean = true> extends BaseParam<NumberOptions, number, Required> {
167
+ constructor(options: string | NumberOptions);
168
+ required<V extends boolean>(value: V): NumberParam<V>;
169
+ resolveMessage(ctx: CommandContext, value: string | undefined): ParamResolvedOutputType<number, Required>;
170
+ resolveChatInput(context: ChatInputContext): ParamResolvedOutputType<number, Required>;
171
+ /**
172
+ * Sets the minimum allowed value for this number.
173
+ * Pass `null` to remove this constraint.
174
+ */
175
+ min(value: number | null): this;
176
+ /**
177
+ * Sets the maximum allowed value for this number.
178
+ * Pass `null` to remove this constraint.
179
+ */
180
+ max(value: number | null): this;
181
+ }
182
+ type AnyParam<Required extends boolean = true> = BaseParam<any, any, Required>;
183
+ /**
184
+ * Helper type to extract the runtime value of a Param instance.
185
+ *
186
+ * @example
187
+ * const p = new StringParam("name").required(false);
188
+ * type T = InferParamValue<typeof p>; // string | null
189
+ */
190
+ type InferParamValue<P extends AnyParam<any>> = P["_type"];
191
+ type InferParamTuple<T extends readonly BaseParam<any, any, any>[]> = {
192
+ [K in keyof T]: T[K] extends AnyParam<any> ? InferParamValue<T[K]> : never;
193
+ };
194
+
195
+ declare const CommandOptionsSchema: z.ZodPipe<z.ZodObject<{
196
+ name: z.ZodString;
197
+ description: z.ZodOptional<z.ZodString>;
198
+ params: z.ZodDefault<z.ZodArray<z.ZodCustom<BaseParam<{
199
+ name: string;
200
+ description?: string | undefined;
201
+ required?: boolean | undefined;
202
+ }, unknown, boolean>, BaseParam<{
203
+ name: string;
204
+ description?: string | undefined;
205
+ required?: boolean | undefined;
206
+ }, unknown, boolean>>>>;
207
+ quotes: z.ZodDefault<z.ZodBoolean>;
208
+ }, z.core.$strip>, z.ZodTransform<{
209
+ description: string;
210
+ name: string;
211
+ params: BaseParam<{
212
+ name: string;
213
+ description?: string | undefined;
214
+ required?: boolean | undefined;
215
+ }, unknown, boolean>[];
216
+ quotes: boolean;
217
+ }, {
218
+ name: string;
219
+ params: BaseParam<{
220
+ name: string;
221
+ description?: string | undefined;
222
+ required?: boolean | undefined;
223
+ }, unknown, boolean>[];
224
+ quotes: boolean;
225
+ description?: string | undefined;
226
+ }>>;
227
+ type CommandOptionsInput = z.input<typeof CommandOptionsSchema>;
228
+ type CommandOptions = z.output<typeof CommandOptionsSchema>;
229
+ /**
230
+ * The command entry, used for registering command.
231
+ */
232
+ declare class Command<ParamsList extends readonly AnyParam<any>[] = any[]> extends LifecycleManager<CommandContext, [
233
+ ...args: InferParamTuple<ParamsList>
234
+ ]> {
235
+ options: CommandOptions;
236
+ constructor(options: (Omit<CommandOptionsInput, "params"> & {
237
+ params?: ParamsList;
238
+ }) | string);
239
+ private handleSyntaxError;
240
+ }
241
+ /**
242
+ * Define command entry, usually for modules.
243
+ * @param options The command options.
244
+ * @returns The entry of the command to deploy or register hooks.
245
+ * @example
246
+ * ```ts
247
+ * import { defineCommand } from "bakit";
248
+ *
249
+ * const command = defineCommand({
250
+ * name: "ping",
251
+ * description: "Displays bot's latency.",
252
+ * });
253
+ *
254
+ * command.main(async (context) => {
255
+ * await context.send(`Pong! ${context.client.ws.ping}ms!`);
256
+ * });
257
+ *
258
+ * export default command;
259
+ * ```
260
+ */
261
+ declare function defineCommand<const ParamsList extends readonly AnyParam<any>[] = any[]>(options: (Omit<CommandOptionsInput, "params"> & {
262
+ params?: ParamsList;
263
+ }) | string): Command<ParamsList>;
264
+
265
+ declare class BaseClientManager {
266
+ client: BakitClient;
267
+ constructor(client: BakitClient);
268
+ }
269
+
270
+ declare class CommandManager extends BaseClientManager {
271
+ commands: Collection<string, Command<any[]>>;
272
+ loadModules(): Promise<Command[]>;
273
+ add(command: Command): void;
274
+ remove(target: string | Command): Command | undefined;
275
+ get(name: string): Command<any[]> | undefined;
276
+ }
277
+
278
+ declare const ListenerOptionsSchema: z$1.ZodObject<{
279
+ name: z$1.ZodEnum<typeof Events>;
280
+ once: z$1.ZodDefault<z$1.ZodBoolean>;
281
+ }, z$1.z.core.$strip>;
282
+ type ListenerOptions<K extends EventKey = EventKey> = Omit<z$1.input<typeof ListenerOptionsSchema>, "name"> & {
283
+ name: K;
284
+ };
285
+ type EventKey = keyof ClientEvents;
286
+ declare class Listener<K extends EventKey = EventKey> extends LifecycleManager<Context, [...args: ClientEvents[K]]> {
287
+ options: ListenerOptions<K>;
288
+ constructor(options: K | ListenerOptions<K>);
289
+ }
290
+ declare function defineListener<const K extends EventKey = EventKey>(options: K | ListenerOptions<K>): Listener<K>;
291
+
292
+ declare class ListenerManager extends BaseClientManager {
293
+ listeners: Listener[];
294
+ private executors;
295
+ loadModules(): Promise<Listener[]>;
296
+ add(listener: Listener): void;
297
+ remove(target: string | Listener): Listener[];
298
+ getBaseIntents(): IntentsBitField;
299
+ getNeededIntents(): IntentsBitField;
300
+ }
301
+
28
302
  type GetPrefixFunction = (message: Message) => Awaitable<string[] | string>;
29
303
  interface BakitClientEvents extends ClientEvents {
30
304
  ready: [BakitClient<true>];
31
305
  clientReady: [BakitClient<true>];
32
306
  }
33
307
  declare class BakitClient<Ready extends boolean = boolean> extends Client<Ready> {
308
+ managers: {
309
+ commands: CommandManager;
310
+ listeners: ListenerManager;
311
+ };
34
312
  constructor(options: ClientOptions);
313
+ /**
314
+ * Check if the client is connected to gateway successfully and finished initialization.
315
+ */
35
316
  isReady(): this is BakitClient<true>;
36
317
  on<K extends keyof BakitClientEvents>(event: K, listener: (...args: BakitClientEvents[K]) => void): this;
37
318
  once<K extends keyof BakitClientEvents>(event: K, listener: (...args: BakitClientEvents[K]) => void): this;
@@ -39,6 +320,28 @@ declare class BakitClient<Ready extends boolean = boolean> extends Client<Ready>
39
320
  removeAllListeners(event?: keyof BakitClientEvents): this;
40
321
  removeListener<K extends keyof BakitClientEvents>(event: K, listener: (...args: BakitClientEvents[K]) => void): this;
41
322
  emit<K extends keyof BakitClientEvents>(event: K, ...args: BakitClientEvents[K]): boolean;
323
+ /**
324
+ * Override BakitClient output when using logger for security concern.
325
+ * @returns `BakitClient {}`
326
+ */
327
+ [inspect.custom](): string;
42
328
  }
43
329
 
44
- export { BakitClient, type BakitClientEvents, type GetPrefixFunction, type ProjectConfig, type ProjectConfigInput, defineConfig, getConfig, loadConfig };
330
+ declare const Params: {
331
+ readonly string: <Required extends boolean = true>(options: string | {
332
+ name: string;
333
+ description?: string | undefined;
334
+ required?: boolean | undefined;
335
+ maxLength?: number | undefined;
336
+ minLength?: number | undefined;
337
+ }) => StringParam<Required>;
338
+ readonly number: <Required extends boolean = true>(options: string | {
339
+ name: string;
340
+ description?: string | undefined;
341
+ required?: boolean | undefined;
342
+ maxValue?: number | undefined;
343
+ minValue?: number | undefined;
344
+ }) => NumberParam<Required>;
345
+ };
346
+
347
+ export { type AnyParam, BakitClient, type BakitClientEvents, BaseCommandContext, BaseParam, type BaseParamOptions, BaseParamSchema, ChatInputContext, type ChatInputContextSendOptions, Command, type CommandContext, CommandManager, type CommandOptions, type CommandOptionsInput, CommandOptionsSchema, type ContextSendOptions, type GetPrefixFunction, type InferParamTuple, type InferParamValue, Listener, ListenerManager, type ListenerOptions, ListenerOptionsSchema, MessageContext, type MessageContextSendOptions, type NumberOptions, NumberParam, NumberParamSchema, type ParamResolvedOutputType, ParamUserType, Params, type ProjectConfig, type ProjectConfigInput, ProjectConfigSchema, type StringOptions, StringParam, StringParamSchema, defineCommand, defineConfig, defineListener, getConfig, loadConfig };
package/dist/index.js CHANGED
@@ -1,12 +1,38 @@
1
- import { GatewayIntentBits, Client } from 'discord.js';
2
- import { z } from 'zod';
1
+ import { GatewayIntentBits, Events, Client, IntentsBitField, Collection, ChatInputCommandInteraction, Message } from 'discord.js';
2
+ import z3, { z } from 'zod';
3
3
  import { pathToFileURL } from 'url';
4
4
  import glob from 'tiny-glob';
5
+ import { inspect } from 'util';
6
+ import { posix } from 'path';
5
7
 
6
8
  // src/config.ts
7
9
  var ProjectConfigSchema = z.object({
10
+ /**
11
+ * The gateway intents to use for the Discord client.
12
+ *
13
+ * - `auto` — automatically determine the required intents.
14
+ * - bigint — a raw bitfield value representing the combined intents.
15
+ * - array — a list of individual intent flags from `GatewayIntentBits`.
16
+ *
17
+ * @defaultvalue `auto`
18
+ */
8
19
  intents: z.union([z.literal("auto"), z.bigint(), z.array(z.enum(GatewayIntentBits))]).default("auto"),
9
- clientOptions: z.custom().optional()
20
+ /**
21
+ * Optional custom client options for Discord.js (excluding `intents`).
22
+ *
23
+ * These are passed directly to the `Client` constructor when initializing the bot.
24
+ *
25
+ * @see {@link https://discord.js.org/docs/packages/discord.js/main/ClientOptions:Interface}
26
+ */
27
+ clientOptions: z.custom().optional(),
28
+ /**
29
+ * The path to the main project source directory.
30
+ *
31
+ * @defaultvalue `src`
32
+ */
33
+ entryDir: z.string().default("src"),
34
+ prefixes: z.array(z.string()).default([]),
35
+ token: z.string()
10
36
  });
11
37
  function defineConfig(config) {
12
38
  return config;
@@ -31,10 +57,533 @@ function getConfig() {
31
57
  throw new Error("Project config is not loaded.");
32
58
  return _config;
33
59
  }
34
- var BakitClient = class extends Client {
60
+
61
+ // src/base/lifecycle/Context.ts
62
+ var Context = class {
63
+ canceled = false;
64
+ cancel() {
65
+ this.canceled = true;
66
+ }
67
+ };
68
+
69
+ // src/command/CommandContext.ts
70
+ var BaseCommandContext = class extends Context {
71
+ constructor(source) {
72
+ super();
73
+ this.source = source;
74
+ }
75
+ get client() {
76
+ return this.source.client;
77
+ }
78
+ get channel() {
79
+ return this.source.channel;
80
+ }
81
+ get channelId() {
82
+ return this.source.channelId;
83
+ }
84
+ get guild() {
85
+ return this.source.guild;
86
+ }
87
+ get guildId() {
88
+ return this.source.guildId;
89
+ }
90
+ get member() {
91
+ return this.source.member;
92
+ }
93
+ inGuild() {
94
+ return !!this.guildId;
95
+ }
96
+ inCachedGuild() {
97
+ if (this.isChatInput())
98
+ return this.source.inCachedGuild();
99
+ if (this.isMessage())
100
+ return this.source.inGuild();
101
+ throw new Error("Invalid source");
102
+ }
103
+ get user() {
104
+ if (this.isChatInput())
105
+ return this.source.user;
106
+ if (this.isMessage())
107
+ return this.source.author;
108
+ throw new Error("Invalid source");
109
+ }
110
+ isChatInput() {
111
+ return this.source instanceof ChatInputCommandInteraction;
112
+ }
113
+ isMessage() {
114
+ return this.source instanceof Message;
115
+ }
116
+ }, ChatInputContext = class extends BaseCommandContext {
117
+ async send(options) {
118
+ typeof options == "string" && (options = { content: options });
119
+ let sendOptions = {
120
+ ...options,
121
+ withResponse: true
122
+ };
123
+ return this.source.deferred || this.source.replied ? await this.source.followUp(sendOptions) : (await this.source.reply(sendOptions)).resource?.message;
124
+ }
125
+ }, MessageContext = class extends BaseCommandContext {
126
+ async send(options) {
127
+ let { channel } = this;
128
+ if (!channel?.isSendable())
129
+ throw new Error("Invalid channel or channel is not sendable");
130
+ return await channel.send(options);
131
+ }
132
+ };
133
+ var LifecycleManager = class {
134
+ constructor(id) {
135
+ this.id = id;
136
+ }
137
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
138
+ hooks = {
139
+ MAIN: new Collection(),
140
+ PRE: new Collection(),
141
+ POST: new Collection(),
142
+ ERROR: new Collection()
143
+ };
144
+ getName(name) {
145
+ return `${this.id}:${name}`;
146
+ }
147
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
148
+ setHook(name, state, callback, order = 1 /* Last */) {
149
+ let currentHooks = this.hooks[state], key = this.getName(name);
150
+ if (currentHooks.has(key) && console.warn(`Overriding duplicate hook '${key}' for state '${state}'`), order === 1 /* Last */)
151
+ currentHooks.set(key, callback);
152
+ else {
153
+ let existingEntries = [...currentHooks.entries()].filter(([k]) => k !== key);
154
+ currentHooks.clear(), currentHooks.set(key, callback);
155
+ for (let [k, v] of existingEntries)
156
+ currentHooks.set(k, v);
157
+ }
158
+ return this;
159
+ }
160
+ main(callback) {
161
+ return this.setHook("main", "MAIN" /* Main */, callback);
162
+ }
163
+ pre(callback) {
164
+ return this.setHook("pre", "PRE" /* Pre */, callback);
165
+ }
166
+ post(callback) {
167
+ return this.setHook("post", "POST" /* Post */, callback);
168
+ }
169
+ error(callback) {
170
+ return this.setHook("error", "ERROR" /* Error */, callback);
171
+ }
172
+ async execute(context, ...args) {
173
+ let pipeline = [
174
+ ...this.hooks.PRE.values(),
175
+ ...this.hooks.MAIN.values(),
176
+ ...this.hooks.POST.values()
177
+ ], error;
178
+ for (let hook of pipeline) {
179
+ if (context.canceled)
180
+ break;
181
+ try {
182
+ await hook(context, ...args);
183
+ } catch (e) {
184
+ error = e;
185
+ break;
186
+ }
187
+ }
188
+ if (!error)
189
+ return;
190
+ if (!this.hooks.ERROR.size)
191
+ throw error;
192
+ for (let [key, callback] of this.hooks.ERROR.entries()) {
193
+ if (context.canceled)
194
+ break;
195
+ try {
196
+ await callback(context, error, ...args);
197
+ } catch (innerError) {
198
+ console.error(`[Lifecycle] Error handler for '${key}' failed:`, innerError);
199
+ }
200
+ }
201
+ }
202
+ };
203
+
204
+ // src/errors/BakitError.ts
205
+ var BakitError = class extends Error {
206
+ constructor(message) {
207
+ super(message), this.name = this.constructor.name, Object.setPrototypeOf(this, new.target.prototype);
208
+ }
209
+ };
210
+
211
+ // src/errors/ArgumentError.ts
212
+ var ArgumentError = class extends BakitError {
213
+ constructor(target, reason) {
214
+ super(`Invalid argument for '${target}': ${reason}`);
215
+ this.target = target;
216
+ this.reason = reason;
217
+ }
218
+ };
219
+
220
+ // src/command/param/Param.ts
221
+ var BaseParam = class {
222
+ options;
35
223
  constructor(options) {
36
- super(options);
224
+ this.options = { ...options, required: options.required ?? true };
225
+ }
226
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
227
+ setOption(key, value) {
228
+ return value === null ? delete this.options[key] : this.options[key] = value, this;
229
+ }
230
+ name(value) {
231
+ return this.setOption("name", value);
232
+ }
233
+ description(value) {
234
+ return this.setOption("description", value);
235
+ }
236
+ required(value) {
237
+ return this.setOption("required", value);
238
+ }
239
+ async resolve(context, value) {
240
+ if (context.isChatInput())
241
+ return await this.resolveChatInput(context);
242
+ if (context.isMessage())
243
+ return await this.resolveMessage(context, value);
244
+ throw new Error("Invalid context type provided");
245
+ }
246
+ /**
247
+ * Helper to normalize string inputs into an options object.
248
+ */
249
+ static getOptions(options) {
250
+ return typeof options == "string" ? { name: options } : options;
251
+ }
252
+ }, StringParam = class extends BaseParam {
253
+ constructor(options) {
254
+ super(BaseParam.getOptions(options));
255
+ }
256
+ required(value) {
257
+ return super.required(value);
258
+ }
259
+ resolveMessage(_context, value) {
260
+ let { required, minLength, maxLength, name } = this.options;
261
+ if (value === void 0) {
262
+ if (required)
263
+ throw new ArgumentError(name, "is required");
264
+ return null;
265
+ }
266
+ if (minLength && value.length < minLength)
267
+ throw new ArgumentError(name, `must be at least ${minLength} chars long`);
268
+ if (maxLength && value.length > maxLength)
269
+ throw new ArgumentError(name, `must be at most ${maxLength} chars long`);
270
+ return value;
271
+ }
272
+ resolveChatInput(context) {
273
+ let { name, required } = this.options;
274
+ return context.source.options.getString(name, required);
37
275
  }
276
+ /**
277
+ * Sets the minimum allowed length for this string.
278
+ * Pass `null` to remove this constraint.
279
+ */
280
+ min(length) {
281
+ return this.setOption("minLength", length);
282
+ }
283
+ /**
284
+ * Sets the maximum allowed length for this string.
285
+ * Pass `null` to remove this constraint.
286
+ */
287
+ max(length) {
288
+ return this.setOption("maxLength", length);
289
+ }
290
+ }, NumberParam = class extends BaseParam {
291
+ constructor(options) {
292
+ super(BaseParam.getOptions(options));
293
+ }
294
+ required(value) {
295
+ return super.required(value);
296
+ }
297
+ resolveMessage(ctx, value) {
298
+ let { required, minValue, maxValue, name } = this.options;
299
+ if (value === void 0) {
300
+ if (required)
301
+ throw new ArgumentError(name, "is required");
302
+ return null;
303
+ }
304
+ let num = Number(value);
305
+ if (isNaN(num))
306
+ throw new ArgumentError(name, "must be a number");
307
+ if (minValue !== void 0 && num < minValue)
308
+ throw new ArgumentError(name, `must be greater than ${minValue}`);
309
+ if (maxValue !== void 0 && num > maxValue)
310
+ throw new ArgumentError(name, `must be less than ${minValue}`);
311
+ return num;
312
+ }
313
+ resolveChatInput(context) {
314
+ let { name, required } = this.options;
315
+ return context.source.options.getString(name, required);
316
+ }
317
+ /**
318
+ * Sets the minimum allowed value for this number.
319
+ * Pass `null` to remove this constraint.
320
+ */
321
+ min(value) {
322
+ return this.setOption("minValue", value);
323
+ }
324
+ /**
325
+ * Sets the maximum allowed value for this number.
326
+ * Pass `null` to remove this constraint.
327
+ */
328
+ max(value) {
329
+ return this.setOption("maxValue", value);
330
+ }
331
+ };
332
+
333
+ // src/command/Command.ts
334
+ var CommandOptionsSchema = z.object({
335
+ name: z.string(),
336
+ description: z.string().min(1).max(100).optional(),
337
+ params: z.array(z.instanceof(BaseParam)).default([]),
338
+ quotes: z.boolean().default(true)
339
+ }).transform((data) => ({
340
+ ...data,
341
+ description: data.description ?? `Command ${data.name}`
342
+ })), Command = class extends LifecycleManager {
343
+ constructor(options) {
344
+ let _options = CommandOptionsSchema.parse(typeof options == "string" ? { name: options } : options);
345
+ super(`command:${_options.name}`), this.options = _options, this.setHook("syntaxError", "ERROR" /* Error */, async (ctx, error, ...args) => {
346
+ await this.handleSyntaxError(ctx, error, args);
347
+ });
348
+ }
349
+ async handleSyntaxError(context, error, _args) {
350
+ error instanceof BakitError && await context.send(error.message);
351
+ }
352
+ };
353
+ function defineCommand(options) {
354
+ return new Command(options);
355
+ }
356
+
357
+ // src/base/BaseClientManager.ts
358
+ var BaseClientManager = class {
359
+ constructor(client) {
360
+ this.client = client;
361
+ }
362
+ };
363
+
364
+ // src/command/CommandManager.ts
365
+ var CommandManager = class extends BaseClientManager {
366
+ commands = new Collection();
367
+ async loadModules() {
368
+ let entryDir = posix.resolve(getConfig().entryDir), pattern = posix.join(entryDir, "commands", "**/*.{ts,js}"), loads = (await glob(pattern, {
369
+ cwd: process.cwd()
370
+ })).map(async (file) => {
371
+ try {
372
+ let { default: command } = await import(pathToFileURL(file).toString());
373
+ if (!command) {
374
+ console.warn(`[Loader] File has no default export: ${file}`);
375
+ return;
376
+ }
377
+ if (!(command instanceof Command)) {
378
+ console.warn(`[Loader] Default export is not a Command: ${file}`);
379
+ return;
380
+ }
381
+ return this.add(command), command;
382
+ } catch (error) {
383
+ console.error(`An error occurred while trying to add command for '${file}':`, error);
384
+ }
385
+ }), loaded = (await Promise.all(loads)).filter((x) => x !== void 0);
386
+ return console.log(`Loaded ${loaded.length} command(s).`), loaded;
387
+ }
388
+ add(command) {
389
+ if (!(command instanceof Command))
390
+ throw new Error("Invalid command provided");
391
+ let { name } = command.options;
392
+ if (this.commands.has(name)) {
393
+ console.warn(`[Loader] Duplicate command registered: '${name}'`);
394
+ return;
395
+ }
396
+ this.commands.set(name, command);
397
+ }
398
+ remove(target) {
399
+ let name = typeof target == "string" ? target : target.options.name, existing = this.commands.get(name);
400
+ if (existing)
401
+ return this.commands.delete(name), existing;
402
+ }
403
+ get(name) {
404
+ return this.commands.get(name);
405
+ }
406
+ };
407
+ var ListenerOptionsSchema = z3.object({
408
+ name: z3.enum(Events),
409
+ once: z3.boolean().default(false)
410
+ }), Listener = class extends LifecycleManager {
411
+ options;
412
+ constructor(options) {
413
+ let _options = ListenerOptionsSchema.parse(typeof options == "string" ? { name: options } : options);
414
+ super(`listener:${_options.name}`), this.options = _options;
415
+ }
416
+ };
417
+ function defineListener(options) {
418
+ return new Listener(options);
419
+ }
420
+ var INTENT_GROUPS = {
421
+ [GatewayIntentBits.Guilds]: [
422
+ Events.GuildCreate,
423
+ Events.GuildDelete,
424
+ Events.GuildUpdate,
425
+ Events.GuildUnavailable,
426
+ Events.GuildRoleCreate,
427
+ Events.GuildRoleDelete,
428
+ Events.GuildRoleUpdate,
429
+ Events.ChannelCreate,
430
+ Events.ChannelDelete,
431
+ Events.ChannelUpdate,
432
+ Events.ChannelPinsUpdate,
433
+ Events.ThreadCreate,
434
+ Events.ThreadDelete,
435
+ Events.ThreadUpdate,
436
+ Events.ThreadListSync,
437
+ Events.ThreadMemberUpdate,
438
+ Events.ThreadMembersUpdate,
439
+ Events.StageInstanceCreate,
440
+ Events.StageInstanceUpdate,
441
+ Events.StageInstanceDelete
442
+ ],
443
+ [GatewayIntentBits.GuildMembers]: [
444
+ Events.GuildMemberAdd,
445
+ Events.GuildMemberUpdate,
446
+ Events.GuildMemberRemove,
447
+ Events.ThreadMembersUpdate
448
+ ],
449
+ [GatewayIntentBits.GuildModeration]: [Events.GuildAuditLogEntryCreate, Events.GuildBanAdd, Events.GuildBanRemove],
450
+ [GatewayIntentBits.GuildExpressions]: [
451
+ Events.GuildEmojiCreate,
452
+ Events.GuildEmojiDelete,
453
+ Events.GuildEmojiUpdate,
454
+ Events.GuildStickerCreate,
455
+ Events.GuildStickerDelete,
456
+ Events.GuildStickerUpdate,
457
+ Events.GuildSoundboardSoundCreate,
458
+ Events.GuildSoundboardSoundUpdate,
459
+ Events.GuildSoundboardSoundDelete,
460
+ Events.GuildSoundboardSoundsUpdate
461
+ ],
462
+ [GatewayIntentBits.GuildIntegrations]: [Events.GuildIntegrationsUpdate],
463
+ [GatewayIntentBits.GuildWebhooks]: [Events.WebhooksUpdate],
464
+ [GatewayIntentBits.GuildInvites]: [Events.InviteCreate, Events.InviteDelete],
465
+ [GatewayIntentBits.GuildVoiceStates]: [Events.VoiceStateUpdate],
466
+ [GatewayIntentBits.GuildPresences]: [Events.PresenceUpdate],
467
+ [GatewayIntentBits.GuildMessages]: [
468
+ Events.MessageCreate,
469
+ Events.MessageUpdate,
470
+ Events.MessageDelete,
471
+ Events.MessageBulkDelete
472
+ ],
473
+ [GatewayIntentBits.GuildMessageReactions]: [
474
+ Events.MessageReactionAdd,
475
+ Events.MessageReactionRemove,
476
+ Events.MessageReactionRemoveAll,
477
+ Events.MessageReactionRemoveEmoji
478
+ ],
479
+ [GatewayIntentBits.GuildMessageTyping]: [Events.TypingStart],
480
+ [GatewayIntentBits.DirectMessages]: [
481
+ Events.MessageCreate,
482
+ Events.MessageUpdate,
483
+ Events.MessageDelete,
484
+ Events.ChannelPinsUpdate
485
+ ],
486
+ [GatewayIntentBits.DirectMessageReactions]: [
487
+ Events.MessageReactionAdd,
488
+ Events.MessageReactionRemove,
489
+ Events.MessageReactionRemoveAll,
490
+ Events.MessageReactionRemoveEmoji
491
+ ],
492
+ [GatewayIntentBits.DirectMessageTyping]: [Events.TypingStart],
493
+ [GatewayIntentBits.MessageContent]: [Events.MessageCreate, Events.MessageUpdate],
494
+ [GatewayIntentBits.GuildScheduledEvents]: [
495
+ Events.GuildScheduledEventCreate,
496
+ Events.GuildScheduledEventDelete,
497
+ Events.GuildScheduledEventUpdate,
498
+ Events.GuildScheduledEventUserAdd,
499
+ Events.GuildScheduledEventUserRemove
500
+ ],
501
+ [GatewayIntentBits.AutoModerationConfiguration]: [
502
+ Events.AutoModerationRuleCreate,
503
+ Events.AutoModerationRuleDelete,
504
+ Events.AutoModerationRuleUpdate
505
+ ],
506
+ [GatewayIntentBits.AutoModerationExecution]: [Events.AutoModerationActionExecution],
507
+ [GatewayIntentBits.GuildMessagePolls]: [Events.MessagePollVoteAdd, Events.MessagePollVoteRemove],
508
+ [GatewayIntentBits.DirectMessagePolls]: [Events.MessagePollVoteAdd, Events.MessagePollVoteRemove]
509
+ }, EVENT_INTENT_MAPPING = {};
510
+ for (let [intentStr, events] of Object.entries(INTENT_GROUPS)) {
511
+ let intent = Number(intentStr);
512
+ for (let event of events)
513
+ EVENT_INTENT_MAPPING[event] ??= [], EVENT_INTENT_MAPPING[event].includes(intent) || EVENT_INTENT_MAPPING[event].push(intent);
514
+ }
515
+
516
+ // src/listener/ListenerManager.ts
517
+ var ListenerManager = class extends BaseClientManager {
518
+ listeners = [];
519
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
520
+ executors = /* @__PURE__ */ new WeakMap();
521
+ async loadModules() {
522
+ let entryDir = posix.resolve(getConfig().entryDir), pattern = posix.join(entryDir, "listeners", "**/*.{ts,js}"), loads = (await glob(pattern, {
523
+ cwd: process.cwd()
524
+ })).map(async (file) => {
525
+ try {
526
+ let { default: listener } = await import(pathToFileURL(file).toString());
527
+ if (!listener) {
528
+ console.warn(`[Loader] File has no default export: ${file}`);
529
+ return;
530
+ }
531
+ if (!(listener instanceof Listener)) {
532
+ console.warn(`[Loader] Default export is not a Listener: ${file}`);
533
+ return;
534
+ }
535
+ return this.add(listener), listener;
536
+ } catch (error) {
537
+ console.error(`An error occurred while trying to add listener for '${file}':`, error);
538
+ }
539
+ }), loaded = (await Promise.all(loads)).filter((x) => x !== void 0);
540
+ return console.log(`Loaded ${loaded.length} listener(s).`), loaded;
541
+ }
542
+ add(listener) {
543
+ if (!(listener instanceof Listener))
544
+ throw new Error("Invalid listener provided");
545
+ let execute = (...args) => {
546
+ listener.execute(new Context(), ...args);
547
+ };
548
+ this.listeners.push(listener), this.executors.set(listener, execute);
549
+ let { once, name } = listener.options;
550
+ this.client[once ? "once" : "on"](name, execute);
551
+ }
552
+ remove(target) {
553
+ let isMatched = (listener) => typeof target == "string" ? listener.options.name === target : listener === target, removed = [];
554
+ return this.listeners = this.listeners.filter((listener) => {
555
+ if (!isMatched(listener))
556
+ return true;
557
+ removed.push(listener);
558
+ let execute = this.executors.get(listener);
559
+ return execute && (this.client.removeListener(listener.options.name, execute), this.executors.delete(listener)), false;
560
+ }), removed;
561
+ }
562
+ getBaseIntents() {
563
+ return new IntentsBitField([GatewayIntentBits.Guilds]);
564
+ }
565
+ getNeededIntents() {
566
+ let result = this.getBaseIntents();
567
+ for (let listener of this.listeners) {
568
+ let eventName = listener.options.name, requiredIntents = EVENT_INTENT_MAPPING[eventName];
569
+ requiredIntents && result.add(requiredIntents);
570
+ }
571
+ return result;
572
+ }
573
+ };
574
+
575
+ // src/BakitClient.ts
576
+ var BakitClient3 = class extends Client {
577
+ managers;
578
+ constructor(options) {
579
+ super(options), this.managers = {
580
+ commands: new CommandManager(this),
581
+ listeners: new ListenerManager(this)
582
+ };
583
+ }
584
+ /**
585
+ * Check if the client is connected to gateway successfully and finished initialization.
586
+ */
38
587
  isReady() {
39
588
  return super.isReady();
40
589
  }
@@ -56,6 +605,33 @@ var BakitClient = class extends Client {
56
605
  emit(event, ...args) {
57
606
  return super.emit(event, ...args);
58
607
  }
608
+ /**
609
+ * Override BakitClient output when using logger for security concern.
610
+ * @returns `BakitClient {}`
611
+ */
612
+ [inspect.custom]() {
613
+ return `${this.constructor.name} {}`;
614
+ }
615
+ };
616
+ var ParamUserType = /* @__PURE__ */ ((ParamUserType2) => (ParamUserType2.Bot = "bot", ParamUserType2.Normal = "normal", ParamUserType2.Any = "any", ParamUserType2))(ParamUserType || {}), BaseParamSchema = z.object({
617
+ name: z.string(),
618
+ description: z.string().optional(),
619
+ required: z.boolean().default(true)
620
+ }), StringParamSchema = BaseParamSchema.extend({
621
+ maxLength: z.number().min(1).optional(),
622
+ minLength: z.number().min(1).optional()
623
+ }), NumberParamSchema = BaseParamSchema.extend({
624
+ maxValue: z.number().optional(),
625
+ minValue: z.number().optional()
626
+ });
627
+
628
+ // src/command/param/Params.ts
629
+ function createFactory(ctor) {
630
+ return (...args) => new ctor(...args);
631
+ }
632
+ var Params = {
633
+ string: createFactory(StringParam),
634
+ number: createFactory(NumberParam)
59
635
  };
60
636
 
61
- export { BakitClient, defineConfig, getConfig, loadConfig };
637
+ export { BakitClient3 as BakitClient, BaseCommandContext, BaseParam, BaseParamSchema, ChatInputContext, Command, CommandManager, CommandOptionsSchema, Listener, ListenerManager, ListenerOptionsSchema, MessageContext, NumberParam, NumberParamSchema, ParamUserType, Params, ProjectConfigSchema, StringParam, StringParamSchema, defineCommand, defineConfig, defineListener, getConfig, loadConfig };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bakit",
3
- "version": "2.0.0-alpha.1",
3
+ "version": "2.0.0-alpha.3",
4
4
  "description": "A framework for discord.js",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",