@seedcord/gateway 0.0.1 → 0.1.0-next.1

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.cjs CHANGED
@@ -1,9 +1,4041 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) {
14
+ __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ }
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
2
27
 
3
- //#region src/index.ts
28
+ //#endregion
29
+ require("reflect-metadata");
30
+ let _seedcord_core = require("@seedcord/core");
31
+ let _seedcord_core_internal = require("@seedcord/core/internal");
32
+ let discord_js = require("discord.js");
33
+ let _seedcord_errors = require("@seedcord/errors");
34
+ let _seedcord_errors_internal = require("@seedcord/errors/internal");
35
+ let _seedcord_utils = require("@seedcord/utils");
36
+ let _seedcord_services = require("@seedcord/services");
37
+ let chalk = require("chalk");
38
+ chalk = __toESM(chalk, 1);
39
+ let _discordjs_builders = require("@discordjs/builders");
40
+ let _seedcord_utils_internal = require("@seedcord/utils/internal");
41
+ let _seedcord_event_emitter = require("@seedcord/event-emitter");
42
+ let node_fs = require("node:fs");
43
+ let node_path = require("node:path");
44
+ let node_url = require("node:url");
45
+ let _seedcord_rate_limiter = require("@seedcord/rate-limiter");
46
+ let _seedcord_types_internal = require("@seedcord/types/internal");
47
+ let envapt = require("envapt");
48
+ let node_crypto = require("node:crypto");
49
+ node_crypto = __toESM(node_crypto, 1);
50
+
51
+ //#region src/bot/decorators/Events.ts
52
+ /**
53
+ * Registers an event handler class with one or more Discord.js events.
54
+ *
55
+ * Associates the decorated class with the provided Discord client events for automatic registration and execution when those events are emitted.
56
+ *
57
+ * Supply any number of event tuples. Each tuple can include per event options.
58
+ *
59
+ * @typeParam EventKey - Union of Discord.js ClientEvents keys to register for
60
+ * @param defs - One or more tuples of [event, options]
61
+ * @decorator
62
+ * @example
63
+ * ```ts
64
+ * \@RegisterEvent([Events.MessageCreate])
65
+ * class MessageHandler extends EventHandler<Events.MessageCreate> {
66
+ * async execute() {
67
+ * // Handle message creation
68
+ * }
69
+ * }
70
+ * ```
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
75
+ * class MessageHandler extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
76
+ * async execute() {
77
+ * // Handle message creation or update
78
+ * }
79
+ * }
80
+ * ```
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * \@RegisterEvent([Events.MessageCreate, { frequency: 'once' }], [Events.MessageUpdate])
85
+ * class OneTimeMessageHandler extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
86
+ * async execute() {
87
+ * // Handle only the first message creation, and message update normally
88
+ * }
89
+ * }
90
+ * ```
91
+ */
92
+ function RegisterEvent(...defs) {
93
+ return function(constructor) {
94
+ const existing = Reflect.getMetadata(_seedcord_core_internal.EventMetadataKey, constructor) ?? [];
95
+ const entries = defs.map(([event, options]) => ({
96
+ event,
97
+ frequency: options?.frequency ?? "on"
98
+ }));
99
+ Reflect.defineMetadata(_seedcord_core_internal.EventMetadataKey, [...existing, ...entries], constructor);
100
+ };
101
+ }
102
+
103
+ //#endregion
104
+ //#region src/bot/decorators/Gated.ts
105
+ /**
106
+ * Attaches gates to a handler. The gates run before `execute`, and a gate refusing stops the handler with
107
+ * the reply or drop the gate threw. Multiple gates are ANDed, so each must pass. A gate that requires a
108
+ * context the handler does not provide (a button gate on a slash handler, an interaction gate on an event
109
+ * handler) is a compile error at this line, and the error names the gate and the handler kind. Place it
110
+ * above the route decorator.
111
+ *
112
+ * Combine gates with {@link and} or {@link or} to build a single gate from multiple arms.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * import { PermissionFlagsBits } from 'discord.js';
117
+ *
118
+ * \@Gated(GuildOnly(), RequirePermissions([PermissionFlagsBits.Administrator]))
119
+ * \@SlashRoute('maintenance')
120
+ * class Maintenance extends SlashHandler<'maintenance'> {
121
+ * async execute() {
122
+ * // both gates passed, so this runs in a guild with an admin caller
123
+ * }
124
+ * }
125
+ * ```
126
+ *
127
+ * @typeParam Gates - The non-empty tuple of gates to run, in order, against the handler's context.
128
+ * @typeParam TCtor - The decorated handler's constructor, checked against every gate's required context.
129
+ * @param gates - One or more gates to attach, each ANDed so the handler runs only when all pass.
130
+ * @param ctor - The handler class being decorated, rejected at compile time when a gate needs a context it lacks.
131
+ *
132
+ * @see {@link defineGate}
133
+ * @see {@link defineEffectGate}
134
+ * @decorator
135
+ */
136
+ function Gated(...gates) {
137
+ return function(ctor) {
138
+ const existing = Reflect.getMetadata(_seedcord_core_internal.GatedMetadataKey, ctor) ?? [];
139
+ Reflect.defineMetadata(_seedcord_core_internal.GatedMetadataKey, [...existing, ...gates], ctor);
140
+ };
141
+ }
142
+
143
+ //#endregion
144
+ //#region src/miscellaneous/areRoutes.ts
145
+ /**
146
+ * Checks if the provided value is an array of strings.
147
+ *
148
+ * @internal
149
+ */
150
+ function areRoutes(routes) {
151
+ return Array.isArray(routes) && routes.every((r) => typeof r === "string");
152
+ }
153
+
154
+ //#endregion
155
+ //#region src/bot/decorators/Interactions.ts
156
+ /**
157
+ * Types of select menus supported for routing
158
+ */
159
+ let SelectMenuKind = /* @__PURE__ */ function(SelectMenuKind) {
160
+ SelectMenuKind["String"] = "string";
161
+ SelectMenuKind["User"] = "user";
162
+ SelectMenuKind["Role"] = "role";
163
+ SelectMenuKind["Channel"] = "channel";
164
+ SelectMenuKind["Mentionable"] = "mentionable";
165
+ return SelectMenuKind;
166
+ }({});
167
+ /**
168
+ * Routes one or more slash commands to a {@link SlashHandler}.
169
+ *
170
+ * Pass the same route string(s) as the handler's generic. A single command reads `this.options`, several
171
+ * commands branch with `this.match`. The decorator routes and the generic must match exactly, so listing
172
+ * fewer or more than the handler declares is a compile error. Subcommands use a slash path.
173
+ *
174
+ * @param routes - The route string(s) this handler serves, e.g. `'ban'`, `'ban', 'kick'`, or `'demo/setup'`.
175
+ * @decorator
176
+ * @example
177
+ * ```ts
178
+ * \@SlashRoute('ban')
179
+ * class BanHandler extends SlashHandler<'ban'> {
180
+ * async execute() {
181
+ * const target = this.options.getUser('target');
182
+ * }
183
+ * }
184
+ * ```
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * \@SlashRoute('ban', 'kick')
189
+ * class ModerationHandler extends SlashHandler<'ban' | 'kick'> {
190
+ * async execute() {
191
+ * await this.match({ ban: (o) => o.getUser('target'), kick: (o) => o.getUser('member') });
192
+ * }
193
+ * }
194
+ * ```
195
+ */
196
+ function SlashRoute(...routes) {
197
+ return function(constructor) {
198
+ storeMetadata(_seedcord_core_internal.InteractionRoutes.Slash, routes, constructor);
199
+ };
200
+ }
201
+ /**
202
+ * Routes button interactions to handler classes.
203
+ *
204
+ * Pass the {@link CustomId} definition(s) this handler decodes and list the same ones in the handler's
205
+ * generic. Passing different definitions to the decorator and the generic is a compile error. Routing
206
+ * matches the stable prefix, so a wire minted from an older shape still reaches the handler, where
207
+ * reading this.params throws StaleCustomId and the controller boundary turns it into a reply.
208
+ *
209
+ * @param defs - The customId definition(s) this handler decodes, one per route.
210
+ * @decorator
211
+ */
212
+ function ButtonRoute(...defs) {
213
+ return function(constructor) {
214
+ storeComponentRoute(_seedcord_core_internal.InteractionRoutes.Button, defs, constructor);
215
+ };
216
+ }
217
+ /**
218
+ * Routes modal submissions to handler classes.
219
+ *
220
+ * Pass the {@link CustomId} definition(s) this handler decodes and list the same ones in the handler's
221
+ * generic. Passing different definitions to the decorator and the generic is a compile error. Routing
222
+ * matches the stable prefix, so an older-shape wire still reaches the handler and throws StaleCustomId
223
+ * on read, the same as a button route.
224
+ *
225
+ * @param defs - The customId definition(s) this handler decodes, one per route.
226
+ * @decorator
227
+ */
228
+ function ModalRoute(...defs) {
229
+ return function(constructor) {
230
+ storeComponentRoute(_seedcord_core_internal.InteractionRoutes.Modal, defs, constructor);
231
+ };
232
+ }
233
+ /**
234
+ * Routes one or more context-menu commands to a {@link ContextMenuHandler}.
235
+ *
236
+ * Pass the kind (`ApplicationCommandType.User` or `ApplicationCommandType.Message`) and the command name(s),
237
+ * each checked against that kind's registry, so a typo is a compile error. The same kind must sit on the
238
+ * handler's generic, cross-checked both directions. Context menus carry no options, so a multi-name handler
239
+ * reads `this.target` uniformly with no branch.
240
+ *
241
+ * @param kind - The context-menu kind, `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
242
+ * @param names - The command name(s) this handler serves, keyed off the matching registry.
243
+ * @decorator
244
+ * @example
245
+ * ```ts
246
+ * \@ContextMenuRoute(ApplicationCommandType.User, 'View Profile')
247
+ * class ViewProfile extends ContextMenuHandler<ApplicationCommandType.User> {
248
+ * async execute() {
249
+ * const user = this.target;
250
+ * }
251
+ * }
252
+ * ```
253
+ */
254
+ function ContextMenuRoute(kind, ...names) {
255
+ return function(constructor) {
256
+ storeMetadata(kind === discord_js.ApplicationCommandType.User ? _seedcord_core_internal.InteractionRoutes.UserContextMenu : _seedcord_core_internal.InteractionRoutes.MessageContextMenu, names, constructor);
257
+ };
258
+ }
259
+ /**
260
+ * Routes one or more commands' autocomplete to an {@link AutocompleteHandler}.
261
+ *
262
+ * Pass the same command route string(s) as the handler's generic. One command branches with `this.match`
263
+ * over its autocompletable fields, several commands share one handler whose arms span every command's
264
+ * fields. The decorator routes and the generic must match exactly, so listing fewer or more than the
265
+ * handler declares is a compile error.
266
+ *
267
+ * @param routes - The command route string(s) this handler serves, e.g. `'search'` or `'search', 'find'`.
268
+ * @decorator
269
+ * @example
270
+ * ```ts
271
+ * \@AutocompleteRoute('search')
272
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
273
+ * async execute() {
274
+ * await this.match({ query: (value, respond) => respond([{ name: value, value }]) });
275
+ * }
276
+ * }
277
+ * ```
278
+ */
279
+ function AutocompleteRoute(...routes) {
280
+ return function(constructor) {
281
+ storeMetadata(_seedcord_core_internal.InteractionRoutes.Autocomplete, routes, constructor);
282
+ };
283
+ }
284
+ /**
285
+ * Routes select menu interactions to handler classes.
286
+ *
287
+ * Pass the select kind and the {@link CustomId} definition(s) this handler decodes. The handler's
288
+ * generic must list the same definitions, and its second generic argument must be the matching select
289
+ * interaction type, or it is a compile error.
290
+ *
291
+ * @param type - Select menu kind from {@link SelectMenuKind}.
292
+ * @param defs - The customId definition(s) this handler decodes, one per route.
293
+ * @decorator
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * \@SelectMenuRoute(SelectMenuKind.User, AssignId)
298
+ * class AssignSelect extends SelectMenuHandler<SelectMenuKind.User, [typeof AssignId]> {
299
+ * // handles user select menus minted from AssignId
300
+ * }
301
+ * ```
302
+ */
303
+ function SelectMenuRoute(type, ...defs) {
304
+ return function(constructor) {
305
+ storeComponentRoute({
306
+ ["string"]: _seedcord_core_internal.InteractionRoutes.StringMenu,
307
+ ["user"]: _seedcord_core_internal.InteractionRoutes.UserMenu,
308
+ ["role"]: _seedcord_core_internal.InteractionRoutes.RoleMenu,
309
+ ["channel"]: _seedcord_core_internal.InteractionRoutes.ChannelMenu,
310
+ ["mentionable"]: _seedcord_core_internal.InteractionRoutes.MentionableMenu
311
+ }[type], defs, constructor);
312
+ };
313
+ }
314
+ function storeComponentRoute(route, defs, constructor) {
315
+ storeMetadata(route, defs.map((def) => def.prefix), constructor);
316
+ Reflect.defineMetadata(_seedcord_core_internal.ComponentDefsKey, defs, constructor);
317
+ }
318
+ function storeMetadata(route, routes, constructor) {
319
+ const key = _seedcord_core_internal.InteractionRouteKeys[route];
320
+ const savedRoutes = Reflect.getMetadata(key, constructor);
321
+ const existing = areRoutes(savedRoutes) ? savedRoutes : [];
322
+ const toStore = Array.isArray(routes) ? routes : [routes];
323
+ Reflect.defineMetadata(key, [...existing, ...toStore], constructor);
324
+ Reflect.defineMetadata(_seedcord_core_internal.InteractionMetadataKey, true, constructor);
325
+ }
326
+
327
+ //#endregion
328
+ //#region src/bot/decorators/Middlewares.ts
329
+ /**
330
+ * Middleware types supported by Seedcord
331
+ */
332
+ let MiddlewareType = /* @__PURE__ */ function(MiddlewareType) {
333
+ MiddlewareType["Interaction"] = "interaction";
334
+ MiddlewareType["Event"] = "event";
335
+ return MiddlewareType;
336
+ }({});
337
+ /**
338
+ * Decorator used to register middleware with priority ordering. The lower the priority number, the earlier it runs.
339
+ *
340
+ * Interaction middleware cannot specify event filters.
341
+ *
342
+ * @param type - Middleware kind from {@link MiddlewareType}
343
+ * @param priority - Ordering value where lower runs earlier. {@default `0`}
344
+ * @param options - Additional registration options
345
+ *
346
+ * @decorator
347
+ *
348
+ * @example
349
+ * ```ts
350
+ * \@Middleware(MiddlewareType.Event, 10, { events: [Events.MessageCreate, Events.MessageUpdate] })
351
+ * class MyEventMiddleware extends EventMiddleware {}
352
+ * ```
353
+ * @throws A **SeedcordTypeError** If priority is not a finite number
354
+ * @throws A **SeedcordError** If interaction middleware specifies event filters
355
+ */
356
+ function Middleware(type, priority = 0, options = {}) {
357
+ return (ctor) => {
358
+ const normalizedPriority = Number(priority);
359
+ if (!Number.isFinite(normalizedPriority)) throw new _seedcord_errors_internal.SeedcordTypeError(_seedcord_errors.SeedcordErrorCode.DecoratorInvalidMiddlewarePriority);
360
+ if (type === "interaction" && Array.isArray(options.events) && options.events.length > 0) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.DecoratorInteractionEventFilter);
361
+ const metadata = {
362
+ priority: normalizedPriority,
363
+ type,
364
+ ...options.events && options.events.length > 0 && { events: options.events }
365
+ };
366
+ Reflect.defineMetadata(_seedcord_core_internal.MiddlewareMetadataKey, metadata, ctor);
367
+ };
368
+ }
369
+
370
+ //#endregion
371
+ //#region src/bot/gates/catalog/IgnoreBots.ts
372
+ /**
373
+ * Drops a client event whose actor is a bot, with a {@link Silence} so nothing is replied. Event-only, because a
374
+ * Silence on an interaction would leave Discord's failed-interaction state. It rejects an interaction handler at
375
+ * the decorator line. Takes no options, so attach it directly without calling it.
376
+ *
377
+ * @see {@link Gated}
378
+ *
379
+ * @example
380
+ * ```ts
381
+ * import { Events } from 'discord.js';
382
+ *
383
+ * \@Gated(IgnoreBots)
384
+ * class OnMessage extends EventHandler<Events.MessageCreate> {
385
+ * async execute() {
386
+ * // ...
387
+ * }
388
+ * }
389
+ * ```
390
+ */
391
+ const IgnoreBots = (0, _seedcord_core.defineGate)("IgnoreBots", (ctx) => {
392
+ if (ctx.user?.bot) throw new _seedcord_core.Silence("actor is a bot");
393
+ });
394
+
395
+ //#endregion
396
+ //#region src/bot/notices/utils.ts
397
+ function mentionFor(subject) {
398
+ if (subject instanceof discord_js.Role) return `<@&${subject.id}>`;
399
+ if (subject instanceof discord_js.TextChannel) return `<#${subject.id}>`;
400
+ if (subject instanceof discord_js.GuildMember) return `<@${subject.id}>`;
401
+ return `\`${subject.name}\``;
402
+ }
403
+ function labelFor(subject) {
404
+ if (subject instanceof discord_js.Role) return "role";
405
+ if (subject instanceof discord_js.TextChannel) return "channel";
406
+ if (subject instanceof discord_js.GuildMember) return "member";
407
+ return "guild";
408
+ }
409
+
410
+ //#endregion
411
+ //#region src/bot/notices/index.ts
412
+ var NotNsfw = class extends _seedcord_core_internal.GateNotice {
413
+ constructor(message = "This can only be used in an age-restricted channel.") {
414
+ super(message);
415
+ }
416
+ };
417
+ var MissingRole = class extends _seedcord_core_internal.GateNotice {
418
+ role;
419
+ constructor(message, role) {
420
+ super(message ?? (role ? `You need the ${role.name} role to use this.` : "You do not have the required role."));
421
+ this.role = role;
422
+ }
423
+ };
424
+ var RoleHigherThanMe = class extends _seedcord_core.Notice {
425
+ role;
426
+ botRole;
427
+ constructor(message, role, botRole) {
428
+ super(message);
429
+ this.role = role;
430
+ this.botRole = botRole;
431
+ }
432
+ render() {
433
+ return { components: [new _seedcord_core_internal.NoticeCard(`I cannot assign a role that is higher than me.\n\nThe role <@&${this.role.id}> is higher than my role <@&${this.botRole.id}> in the hierarchy.`).component] };
434
+ }
435
+ };
436
+ var CannotAssignBotRole = class extends _seedcord_core.Notice {
437
+ constructor(message = "I cannot assign a managed role.") {
438
+ super(message);
439
+ }
440
+ render() {
441
+ return { components: [new _seedcord_core_internal.NoticeCard("I cannot assign a managed role.").component] };
442
+ }
443
+ };
444
+ var MissingPermissions = class extends _seedcord_core.Notice {
445
+ where;
446
+ missingPerms;
447
+ constructor(message, where, missingPerms) {
448
+ super(message);
449
+ this.where = where;
450
+ this.missingPerms = missingPerms;
451
+ }
452
+ render() {
453
+ const bullets = this.missingPerms.map((perm) => `• ${perm}`).join("\n");
454
+ return { components: [new _seedcord_core_internal.NoticeCard(`The ${labelFor(this.where)} ${mentionFor(this.where)} is missing the following permission entries:\n\n${bullets}`).component] };
455
+ }
456
+ };
457
+ var HasDangerousPermissions = class extends _seedcord_core.Notice {
458
+ target;
459
+ dangerousPerms;
460
+ constructor(message, target, dangerousPerms) {
461
+ super(message);
462
+ this.target = target;
463
+ this.dangerousPerms = dangerousPerms;
464
+ }
465
+ render() {
466
+ const bullets = this.dangerousPerms.map((perm) => `• ${perm}`).join("\n");
467
+ return { components: [new _seedcord_core_internal.NoticeCard(`The ${labelFor(this.target)} ${mentionFor(this.target)} has the following permission entries that must not be enabled:\n\n${bullets}`).component] };
468
+ }
469
+ };
470
+ var UserNotFound = class extends _seedcord_core.Notice {
471
+ userArg;
472
+ constructor(userArg) {
473
+ super(`User not found: ${userArg}`);
474
+ this.userArg = userArg;
475
+ }
476
+ render() {
477
+ return { components: [new _seedcord_core_internal.NoticeCard(`User probably doesn't exist or was deleted.\n**User Argument:** \`${this.userArg}\`\nPlease check the user ID and try again. Only pass valid user IDs as the argument.`, "User Not Found").component] };
478
+ }
479
+ };
480
+ var UserNotInGuild = class extends _seedcord_core.Notice {
481
+ constructor(message = "User is not in the guild.") {
482
+ super(message);
483
+ }
484
+ render() {
485
+ return { components: [new _seedcord_core_internal.NoticeCard(this.message).component] };
486
+ }
487
+ };
488
+ var RoleDoesNotExist = class extends _seedcord_core.Notice {
489
+ roleId;
490
+ constructor(message, roleId) {
491
+ super(message);
492
+ this.roleId = roleId;
493
+ }
494
+ render() {
495
+ return { components: [new _seedcord_core_internal.NoticeCard(`The role with ID \`${this.roleId}\` does not exist.`).component] };
496
+ }
497
+ };
498
+ var CouldNotFindChannel = class extends _seedcord_core.Notice {
499
+ channelId;
500
+ constructor(message, channelId) {
501
+ super(message);
502
+ this.channelId = channelId;
503
+ }
504
+ render() {
505
+ return { components: [new _seedcord_core_internal.NoticeCard(`Could not find channel with ID \`${this.channelId}\`. It could also be that the channel is not a text channel.`).component] };
506
+ }
507
+ };
508
+
509
+ //#endregion
510
+ //#region src/bot/gates/catalog/Nsfw.ts
511
+ function channelIsNsfw(channel) {
512
+ if (!channel) return false;
513
+ if (channel.isThread()) return channel.parent?.nsfw ?? false;
514
+ return "nsfw" in channel ? channel.nsfw : false;
515
+ }
516
+ /**
517
+ * Requires an age-restricted channel, else refuses. Pass {@link GateNoticeOptions} to reword or replace the refusal.
518
+ *
519
+ * A thread inherits its parent channel's nsfw flag. ModalSubmit has no reliable channel, so it is excluded.
520
+ *
521
+ * @param options - Reword the default refusal with `message`, or replace it with `notice`.
522
+ *
523
+ * @see {@link Gated}
524
+ *
525
+ * @example
526
+ * ```ts
527
+ * \@Gated(Nsfw())
528
+ * \@SlashRoute('nsfwcmd')
529
+ * class NsfwHandler extends SlashHandler<'nsfwcmd'> {
530
+ * async execute() {
531
+ * // ...
532
+ * }
533
+ * }
534
+ * ```
535
+ */
536
+ function Nsfw(options) {
537
+ return (0, _seedcord_core.defineGate)("Nsfw", (ctx) => {
538
+ if (channelIsNsfw(ctx.interaction.channel)) return;
539
+ throw (0, _seedcord_core_internal.pickNotice)(options, (message) => new NotNsfw(message));
540
+ });
541
+ }
542
+
543
+ //#endregion
544
+ //#region src/bot/utilities/permissions/checkPermissions.ts
545
+ /**
546
+ * Map of permission bits to their prettified human readable names.
547
+ */
548
+ const PermissionNames = new Map(Object.entries(discord_js.PermissionFlagsBits).map(([key, bit]) => [bit, (0, _seedcord_utils.prettify)(key)]));
549
+ function checkPermissions(a, b, c, d, e) {
550
+ const { for: pFor, in: pIn, scope, inverse = false, missing: missingCtor, dangerous: dangerousCtor } = a instanceof discord_js.Role || a instanceof discord_js.GuildMember ? {
551
+ for: a,
552
+ in: b,
553
+ scope: c,
554
+ inverse: d ?? false,
555
+ ...e
556
+ } : a;
557
+ const Missing = missingCtor ?? MissingPermissions;
558
+ const Dangerous = dangerousCtor ?? HasDangerousPermissions;
559
+ const perms = pIn instanceof discord_js.Guild ? pFor.permissions : pIn.permissionsFor(pFor, true);
560
+ const names = (bits) => bits.map((bit) => PermissionNames.get(bit) ?? String(bit));
561
+ const present = scope.filter((bit) => perms.has(bit, true));
562
+ const presentNames = names(present);
563
+ if (inverse) {
564
+ if (present.length > 0) throw new Dangerous(`${pFor instanceof discord_js.Role ? "Role" : "Member"} has dangerous permissions in this ${pIn instanceof discord_js.Guild ? "guild" : "channel"}`, pFor, presentNames);
565
+ return;
566
+ }
567
+ const missingBits = scope.filter((bit) => !perms.has(bit, true));
568
+ if (missingBits.length > 0) throw new Missing("Missing Any/All/No Permissions", pFor, names(missingBits));
569
+ }
570
+
571
+ //#endregion
572
+ //#region src/bot/gates/catalog/permissions.ts
573
+ const UNCACHED_MEMBER = "Your server member data could not be resolved. Try again.";
574
+ /**
575
+ * Requires the caller to hold every permission in `scope`, via `checkPermissions`. Refuses outside a guild.
576
+ *
577
+ * Interaction-only and excludes ModalSubmit, since a modal lacks a reliable cached caller member.
578
+ *
579
+ * @param scope - The permission flag bits the caller must all hold.
580
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-permissions one with `missing`.
581
+ *
582
+ * @see {@link Gated}
583
+ *
584
+ * @example
585
+ * ```ts
586
+ * import { PermissionFlagsBits } from 'discord.js';
587
+ *
588
+ * \@Gated(RequirePermissions([PermissionFlagsBits.BanMembers]))
589
+ * \@SlashRoute('ban')
590
+ * class BanHandler extends SlashHandler<'ban'> {
591
+ * async execute() {
592
+ * const target = this.options.getUser('target');
593
+ * }
594
+ * }
595
+ * ```
596
+ */
597
+ function RequirePermissions(scope, options) {
598
+ return (0, _seedcord_core.defineGate)("RequirePermissions", (ctx) => {
599
+ if (!ctx.guild) throw (0, _seedcord_core_internal.pickNotice)(options?.notInGuild, (message) => new _seedcord_core_internal.NotInGuild(message));
600
+ if (!ctx.member) throw (0, _seedcord_core_internal.pickNotice)(options?.notInGuild, (message) => new _seedcord_core_internal.NotInGuild(message ?? UNCACHED_MEMBER));
601
+ checkPermissions(ctx.member, ctx.guild, scope, false, options?.missing ? { missing: options.missing } : void 0);
602
+ });
603
+ }
604
+ /**
605
+ * Requires the bot to hold every permission in `scope`, via `checkPermissions`. Refuses outside a guild.
606
+ *
607
+ * It reads the bot's own member, so it attaches to modal handlers as well.
608
+ *
609
+ * @param scope - The permission flag bits the bot must all hold.
610
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-permissions one with `missing`.
611
+ *
612
+ * @see {@link Gated}
613
+ *
614
+ * @example
615
+ * ```ts
616
+ * import { PermissionFlagsBits } from 'discord.js';
617
+ *
618
+ * \@Gated(RequireBotPermissions([PermissionFlagsBits.BanMembers]))
619
+ * \@ModalRoute(MyModalId)
620
+ * class MyModalHandler extends ModalHandler<[typeof MyModalId]> {
621
+ * async execute() {
622
+ * // ...
623
+ * }
624
+ * }
625
+ * ```
626
+ */
627
+ function RequireBotPermissions(scope, options) {
628
+ return (0, _seedcord_core.defineGate)("RequireBotPermissions", (ctx) => {
629
+ const botMember = ctx.guild?.members.me;
630
+ if (!ctx.guild || !botMember) throw (0, _seedcord_core_internal.pickNotice)(options?.notInGuild, (message) => new _seedcord_core_internal.NotInGuild(message));
631
+ checkPermissions(botMember, ctx.guild, scope, false, options?.missing ? { missing: options.missing } : void 0);
632
+ });
633
+ }
634
+ /**
635
+ * Requires the caller to have `roleId`, read from the member's role cache. Refuses outside a guild first, then
636
+ * when the role is missing.
637
+ *
638
+ * Interaction-only and excludes ModalSubmit.
639
+ *
640
+ * @param roleId - The role snowflake the caller must hold, read from the member's role cache.
641
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-role one with `missingRole`.
642
+ *
643
+ * @see {@link Gated}
644
+ *
645
+ * @example
646
+ * ```ts
647
+ * \@Gated(RequireRole('123456789012345678'))
648
+ * \@SlashRoute('vip')
649
+ * class VipHandler extends SlashHandler<'vip'> {
650
+ * async execute() {
651
+ * // ...
652
+ * }
653
+ * }
654
+ * ```
655
+ */
656
+ function RequireRole(roleId, options) {
657
+ return (0, _seedcord_core.defineGate)("RequireRole", (ctx) => {
658
+ if (!ctx.guild) throw (0, _seedcord_core_internal.pickNotice)(options?.notInGuild, (message) => new _seedcord_core_internal.NotInGuild(message));
659
+ if (!ctx.member) throw (0, _seedcord_core_internal.pickNotice)(options?.notInGuild, (message) => new _seedcord_core_internal.NotInGuild(message ?? UNCACHED_MEMBER));
660
+ if (ctx.member.roles.cache.has(roleId)) return;
661
+ const role = ctx.guild.roles.cache.get(roleId) ?? null;
662
+ throw (0, _seedcord_core_internal.pickNotice)(options?.missingRole, (message) => new MissingRole(message, role));
663
+ });
664
+ }
665
+
666
+ //#endregion
667
+ //#region src/bot/injectors/EmojiInjector.ts
668
+ const emojiStorage = {};
669
+ function isEmojiTuple(v) {
670
+ return Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "string";
671
+ }
672
+ /**
673
+ * Global emoji mappings object
674
+ *
675
+ * @see {@link EmojiMap}
676
+ */
677
+ const Emojis = emojiStorage;
678
+ /**
679
+ * Loads and injects emojis based on bot configuration.
680
+ *
681
+ * For emojis injected from specific guilds, ensure that the Guilds intent is provided in client options.
682
+ *
683
+ * @internal
684
+ */
685
+ var EmojiInjector = class {
686
+ core;
687
+ logger = new _seedcord_services.Logger("Emojis");
688
+ constructor(core) {
689
+ this.core = core;
690
+ }
691
+ async init() {
692
+ this.clearEmojis();
693
+ if (!this.core.config.bot.emojis || Object.keys(this.core.config.bot.emojis).length === 0) {
694
+ this.logger.debug(chalk.default.bold.yellow("No emojis configured, skipping emoji injection."));
695
+ return;
696
+ }
697
+ const configEmojis = this.core.config.bot.emojis;
698
+ await this.core.bot.client.application?.emojis.fetch();
699
+ const failures = [];
700
+ const fetchedGuilds = /* @__PURE__ */ new Set();
701
+ for (const [key, value] of Object.entries(configEmojis)) if (isEmojiTuple(value)) await this.resolveTuple(key, value, failures, fetchedGuilds);
702
+ else if (typeof value === "string") this.resolveString(key, value, failures);
703
+ else failures.push(` - "${key}" has an invalid value (expected a name or [name, guildId])`);
704
+ if (failures.length > 0) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigEmojiUnresolved, [failures.length, failures.join("\n")]);
705
+ this.logger.utils.summary("Loaded emojis", { emojis: Object.keys(emojiStorage).length });
706
+ }
707
+ async resolveTuple(key, value, failures, fetchedGuilds) {
708
+ const [emojiName, guildId] = value;
709
+ const guild = this.core.bot.client.guilds.cache.get(guildId);
710
+ if (!guild) {
711
+ failures.push(` - "${emojiName}" for "${key}" targets guild ${guildId}, which is not available (check the Guilds intent)`);
712
+ return;
713
+ }
714
+ if (!fetchedGuilds.has(guildId)) {
715
+ await guild.emojis.fetch();
716
+ fetchedGuilds.add(guildId);
717
+ }
718
+ const guildEmoji = guild.emojis.cache.find((e) => e.name === emojiName);
719
+ if (!guildEmoji) {
720
+ failures.push(` - "${emojiName}" for "${key}" was not found in guild ${guildId}`);
721
+ return;
722
+ }
723
+ emojiStorage[key] = guildEmoji;
724
+ }
725
+ resolveString(key, emojiName, failures) {
726
+ const appEmoji = this.core.bot.client.application?.emojis.cache.find((e) => e.name === emojiName);
727
+ if (!appEmoji) {
728
+ failures.push(` - "${emojiName}" for "${key}" was not found among the application emojis`);
729
+ return;
730
+ }
731
+ emojiStorage[key] = appEmoji;
732
+ }
733
+ clearEmojis() {
734
+ for (const key of Object.keys(emojiStorage)) Reflect.deleteProperty(emojiStorage, key);
735
+ }
736
+ };
737
+
738
+ //#endregion
739
+ //#region src/bot/injectors/CommandMentionInjector.ts
740
+ const mentionStorage = {};
741
+ /**
742
+ * Ready-to-send command mention strings, keyed by {@link SlashOptionRegistry}.
743
+ *
744
+ * A value is a clickable `</name:id>` when the command's id resolved from the deploy, otherwise the plain
745
+ * `/name` text. Populated by {@link CommandMentionInjector} after each deploy.
746
+ */
747
+ const CommandMentions = mentionStorage;
748
+ const MULTI_GUILD = Symbol("seedcord:commandmentions:multi-guild");
749
+ /**
750
+ * Turns each deployed slash route into a clickable command mention exposed through {@link CommandMentions}.
751
+ *
752
+ * Consumes the ids {@link DeployResult} carries, so it runs after a deploy rather than resolving from a name
753
+ * cache (discord.js offers none for command ids). A global command is clickable everywhere by its app-wide id.
754
+ * A guild command deployed to one guild is clickable by that guild's id. A command deployed to two or more
755
+ * guilds mints a different id per guild, so one accessor key cannot resolve it, and it falls back to plain
756
+ * `/name` text with one warn. On a non-owning shard a guild command also falls back to plain text.
757
+ *
758
+ * @internal
759
+ */
760
+ var CommandMentionInjector = class {
761
+ core;
762
+ logger = new _seedcord_services.Logger("CommandMentions");
763
+ constructor(core) {
764
+ this.core = core;
765
+ }
766
+ inject(deploy) {
767
+ this.clear();
768
+ const globalIds = this.indexByName(deploy.global);
769
+ const guildIds = this.indexGuilds(deploy.guilds);
770
+ const warned = /* @__PURE__ */ new Set();
771
+ let clickable = 0;
772
+ for (const command of this.allSlashBuilders()) {
773
+ const id = this.resolveId(command.name, globalIds, guildIds, warned);
774
+ for (const leaf of (0, _seedcord_utils_internal.routeLeavesOf)(command.toJSON())) {
775
+ mentionStorage[leaf.route] = id ? this.toMention(leaf.route, id) : this.toPlain(leaf.route);
776
+ if (id) clickable++;
777
+ }
778
+ }
779
+ this.logger.utils.summary("Linked mentions", {
780
+ clickable,
781
+ plain: Object.keys(mentionStorage).length - clickable
782
+ });
783
+ }
784
+ allSlashBuilders() {
785
+ const registry = this.core.bot.commands;
786
+ if (!registry) return [];
787
+ const slash = [...registry.globalCommands, ...registry.guildCommands.values()].flat().filter((command) => command instanceof _discordjs_builders.SlashCommandBuilder);
788
+ return [...new Set(slash)];
789
+ }
790
+ indexByName(collection) {
791
+ const map = /* @__PURE__ */ new Map();
792
+ for (const command of collection.values()) map.set(command.name, command.id);
793
+ return map;
794
+ }
795
+ indexGuilds(guilds) {
796
+ const map = /* @__PURE__ */ new Map();
797
+ for (const collection of guilds.values()) for (const command of collection.values()) {
798
+ const existing = map.get(command.name);
799
+ if (existing === void 0) map.set(command.name, command.id);
800
+ else if (existing !== command.id) map.set(command.name, MULTI_GUILD);
801
+ }
802
+ return map;
803
+ }
804
+ resolveId(name, globalIds, guildIds, warned) {
805
+ const global = globalIds.get(name);
806
+ if (global) return global;
807
+ const guild = guildIds.get(name);
808
+ if (guild === void 0) return void 0;
809
+ if (guild === MULTI_GUILD) {
810
+ if (!warned.has(name)) {
811
+ this.logger.warn(`${name} is deployed to multiple guilds, falling back to plain text (not clickable).`);
812
+ warned.add(name);
813
+ }
814
+ return;
815
+ }
816
+ return guild;
817
+ }
818
+ toMention(route, id) {
819
+ const [name, middle, sub] = route.split("/");
820
+ if (name && middle && sub) return (0, discord_js.chatInputApplicationCommandMention)(name, middle, sub, id);
821
+ if (name && middle) return (0, discord_js.chatInputApplicationCommandMention)(name, middle, id);
822
+ return (0, discord_js.chatInputApplicationCommandMention)(name ?? route, id);
823
+ }
824
+ toPlain(route) {
825
+ return `/${route.replaceAll("/", " ")}`;
826
+ }
827
+ clear() {
828
+ for (const key of Object.keys(mentionStorage)) Reflect.deleteProperty(mentionStorage, key);
829
+ }
830
+ };
831
+
832
+ //#endregion
833
+ //#region src/bot/utilities/channels/fetchText.ts
834
+ /**
835
+ * Fetches and validates a text channel. Refuses when the channel doesn't exist or isn't a text channel.
836
+ *
837
+ * @param client - The Discord client instance
838
+ * @param channelId - Channel ID or TextChannel instance
839
+ * @returns Promise resolving to the text channel
840
+ */
841
+ async function fetchText(client, channelId) {
842
+ if (channelId instanceof discord_js.TextChannel) return channelId;
843
+ let channel = client.channels.cache.get(channelId);
844
+ if (!channel) try {
845
+ channel = await client.channels.fetch(channelId);
846
+ } catch (err) {
847
+ if (err instanceof discord_js.DiscordAPIError && err.code === discord_js.RESTJSONErrorCodes.UnknownChannel) throw new CouldNotFindChannel("Channel not found or not a text channel", channelId);
848
+ throw err;
849
+ }
850
+ if (channel?.isTextBased()) return channel;
851
+ throw new CouldNotFindChannel("Channel not found or not a text channel", channelId);
852
+ }
853
+
854
+ //#endregion
855
+ //#region src/bot/utilities/permissions/checkBotPermissions.ts
856
+ /**
857
+ * Checks if the bot has required permissions in a {@link Guild} or {@link TextChannel}. Refuses when a
858
+ * required permission is missing.
859
+ *
860
+ * @param target - Guild or text channel to check in
861
+ * @param scope - Permission bits to validate
862
+ * @param inverse - Whether to check for absence of the given permissions
863
+ * @param errors - Optional custom error constructors
864
+ *
865
+ * @example
866
+ * ```ts
867
+ * import { PermissionFlagsBits } from 'discord.js';
868
+ * import { checkBotPermissions } from '@seedcord/gateway';
869
+ *
870
+ * // Check if the bot has SendMessages and ViewChannel permissions in a text channel
871
+ * checkBotPermissions(textChannel, [
872
+ * PermissionFlagsBits.SendMessages,
873
+ * PermissionFlagsBits.ViewChannel
874
+ * ]);
875
+ * ```
876
+ */
877
+ function checkBotPermissions(target, scope, inverse = false, errors) {
878
+ if (target instanceof discord_js.Guild) {
879
+ const me = target.members.me;
880
+ if (!me) {
881
+ const names = scope.map((bit) => PermissionNames.get(bit) ?? String(bit));
882
+ throw new ((errors?.missing) ?? MissingPermissions)("Missing Permissions", target, names);
883
+ }
884
+ checkPermissions(me, target, scope, inverse, errors);
885
+ return;
886
+ }
887
+ const me = target.guild.members.me;
888
+ if (!me) {
889
+ new _seedcord_services.Logger("checkBotPermissions").warn(`Bot member is unavailable in guild ${target.guild.id} while checking permissions in channel ${target.id}`);
890
+ const names = scope.map((bit) => PermissionNames.get(bit) ?? String(bit));
891
+ throw new ((errors?.missing) ?? MissingPermissions)("Missing Permissions", target, names);
892
+ }
893
+ checkPermissions(me, target, scope, inverse, errors);
894
+ }
895
+
896
+ //#endregion
897
+ //#region src/bot/utilities/roles/getBotRole.ts
898
+ /**
899
+ * Gets the bot's managed role in a guild.
900
+ *
901
+ * @param guild - The guild to get the bot role from
902
+ * @returns The bot's managed role in the guild
903
+ * @throws A **SeedcordError** if the client user is unavailable or if the bot role is missing
904
+ */
905
+ function getBotRole(guild) {
906
+ const botRole = guild.roles.botRoleFor(guild.client.user);
907
+ if (!botRole) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CoreBotRoleMissing, [guild.id]);
908
+ return botRole;
909
+ }
910
+
911
+ //#endregion
912
+ //#region src/bot/utilities/permissions/hasPermsToAssign.ts
913
+ /**
914
+ * Validates if the bot can assign a target role. Refuses when the target role is above the bot's, is managed, or the bot lacks Manage Roles.
915
+ *
916
+ * @param roleOrOptions - Target role or complete options for the check
917
+ *
918
+ * @example
919
+ * ```ts
920
+ * import { hasPermsToAssign } from '@seedcord/gateway';
921
+ *
922
+ * // Check if the bot can assign a specific role
923
+ * hasPermsToAssign(role);
924
+ *
925
+ * // Check with custom error handling
926
+ * hasPermsToAssign({
927
+ * targetRole: role,
928
+ * errors: {
929
+ * higher: CustomHigherError,
930
+ * managed: CustomManagedError,
931
+ * missing: CustomMissingPermissionsError
932
+ * }
933
+ * });
934
+ * ```
935
+ */
936
+ function hasPermsToAssign(roleOrOptions) {
937
+ const { targetRole, errors } = roleOrOptions instanceof discord_js.Role ? {
938
+ targetRole: roleOrOptions,
939
+ errors: void 0
940
+ } : roleOrOptions;
941
+ const HigherErr = errors?.higher ?? RoleHigherThanMe;
942
+ const ManagedErr = errors?.managed ?? CannotAssignBotRole;
943
+ const Missing = errors?.missing ?? MissingPermissions;
944
+ const botRole = getBotRole(targetRole.guild);
945
+ if (targetRole.comparePositionTo(botRole) >= 0) throw new HigherErr("Role is higher than me", targetRole, botRole);
946
+ if (targetRole.managed) throw new ManagedErr(`Cannot assign managed role ${targetRole.name}`);
947
+ checkBotPermissions(targetRole.guild, [discord_js.PermissionFlagsBits.ManageRoles], false, { missing: Missing });
948
+ }
949
+
950
+ //#endregion
951
+ //#region src/bot/utilities/roles/fetchRole.ts
952
+ function isUnknownRole(err) {
953
+ return err instanceof discord_js.DiscordAPIError && err.code === discord_js.RESTJSONErrorCodes.UnknownRole;
954
+ }
955
+ async function fetchRoleInGuild(guild, roleId) {
956
+ const cached = guild.roles.cache.get(roleId);
957
+ if (cached) return cached;
958
+ try {
959
+ return await guild.roles.fetch(roleId);
960
+ } catch (err) {
961
+ if (isUnknownRole(err)) throw new RoleDoesNotExist("Role not found in specified guild", roleId);
962
+ throw err;
963
+ }
964
+ }
965
+ async function scanGuildsForRole(client, roleId) {
966
+ const cached = client.guilds.cache.map((guild) => guild.roles.cache.get(roleId)).find(Boolean);
967
+ if (cached) return cached;
968
+ for (const guild of client.guilds.cache.values()) try {
969
+ const role = await guild.roles.fetch(roleId);
970
+ if (role) return role;
971
+ } catch (err) {
972
+ if (isUnknownRole(err)) continue;
973
+ throw err;
974
+ }
975
+ return null;
976
+ }
977
+ /**
978
+ * Fetches a role by ID from a client or guild. Refuses when the role doesn't exist.
979
+ *
980
+ * @param clientOrGuild - Discord client or guild instance
981
+ * @param roleId - The role ID to fetch
982
+ * @returns Promise resolving to the role
983
+ */
984
+ async function fetchRole(clientOrGuild, roleId) {
985
+ if (!roleId) throw new RoleDoesNotExist("Role ID is null or undefined", roleId);
986
+ const role = clientOrGuild instanceof discord_js.Guild ? await fetchRoleInGuild(clientOrGuild, roleId) : await scanGuildsForRole(clientOrGuild, roleId);
987
+ if (!role) throw new RoleDoesNotExist("Role not found", roleId);
988
+ return role;
989
+ }
990
+
991
+ //#endregion
992
+ //#region src/bot/utilities/users/fetchGuildMember.ts
993
+ /**
994
+ * Fetches a guild member by user ID. Refuses when the user is not in the guild.
995
+ *
996
+ * @param guild - The guild to fetch the member from
997
+ * @param userId - The Discord user ID
998
+ * @returns Promise resolving to the guild member
999
+ */
1000
+ async function fetchGuildMember(guild, userId) {
1001
+ let user = guild.members.cache.get(userId);
1002
+ user ??= await guild.members.fetch(userId).catch((err) => {
1003
+ if (err instanceof discord_js.DiscordAPIError && err.code === discord_js.RESTJSONErrorCodes.UnknownMember) throw new UserNotInGuild(`User with ID ${userId} not found in guild`);
1004
+ throw err;
1005
+ });
1006
+ return user;
1007
+ }
1008
+
1009
+ //#endregion
1010
+ //#region src/bot/utilities/users/fetchManyGuildMembers.ts
1011
+ /**
1012
+ * Fetches multiple guild members by user IDs.
1013
+ *
1014
+ * @param guild - The guild to fetch members from
1015
+ * @param userIds - Array of Discord user IDs
1016
+ * @returns Promise resolving to array of successfully fetched members
1017
+ */
1018
+ async function fetchManyGuildMembers(guild, userIds) {
1019
+ return (await Promise.allSettled(userIds.map((userId) => fetchGuildMember(guild, userId)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
1020
+ }
1021
+
1022
+ //#endregion
1023
+ //#region src/bot/utilities/users/fetchUser.ts
1024
+ /**
1025
+ * Fetches a Discord user by ID. Refuses when the user doesn't exist, with `options.throwAs` or the default.
1026
+ *
1027
+ * @param client - The Discord client instance
1028
+ * @param userId - The Discord user ID
1029
+ * @param options - Optional overrides, including the {@link FetchUserOptions.throwAs} notice
1030
+ * @returns Promise resolving to the user
1031
+ */
1032
+ async function fetchUser(client, userId, options) {
1033
+ const Throw = options?.throwAs ?? UserNotFound;
1034
+ let user = client.users.cache.get(userId);
1035
+ user ??= await client.users.fetch(userId).catch((err) => {
1036
+ if (err instanceof discord_js.DiscordAPIError && err.code === discord_js.RESTJSONErrorCodes.UnknownUser) throw new Throw(userId);
1037
+ throw err;
1038
+ });
1039
+ return user;
1040
+ }
1041
+
1042
+ //#endregion
1043
+ //#region src/bot/utilities/users/fetchManyUsers.ts
1044
+ /**
1045
+ * Fetches multiple Discord users by IDs.
1046
+ *
1047
+ * @param client - The Discord client instance
1048
+ * @param userIds - Array of Discord user IDs
1049
+ * @param options - Optional overrides threaded to each {@link fetchUser} call
1050
+ * @returns Promise resolving to array of successfully fetched users
1051
+ */
1052
+ async function fetchManyUsers(client, userIds, options) {
1053
+ return (await Promise.allSettled(userIds.map((userId) => fetchUser(client, userId, options)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
1054
+ }
1055
+
1056
+ //#endregion
1057
+ //#region src/bot/utilities/users/updateMemberRoles.ts
1058
+ /**
1059
+ * Updates a guild member's roles by adding and removing specified roles.
1060
+ *
1061
+ * @param rolesToAdd - Array of role IDs to add to the member
1062
+ * @param rolesToRemove - Array of role IDs to remove from the member
1063
+ * @param member - The guild member to update
1064
+ * @returns Promise that resolves when roles are updated
1065
+ */
1066
+ async function updateMemberRoles(rolesToAdd, rolesToRemove, member) {
1067
+ const current = new Set(member.roles.cache.map((r) => r.id));
1068
+ const toAdd = new Set(rolesToAdd);
1069
+ const toRemove = new Set(rolesToRemove);
1070
+ const updated = current.union(toAdd).difference(toRemove);
1071
+ await member.roles.set([...updated]);
1072
+ }
1073
+
1074
+ //#endregion
1075
+ //#region src/bot/harmlessApiCodes.ts
1076
+ /**
1077
+ * Discord API error codes that mean a dead end on an interaction, a dead token, a double ack, or a gone
1078
+ * message. There is nothing to show the user and no bug to report. The controller boundary drops them on
1079
+ * the original throw, and {@link ReplySender} drops them on its own send.
1080
+ *
1081
+ * @internal
1082
+ */
1083
+ const HARMLESS_API_CODES = new Set([
1084
+ discord_js.RESTJSONErrorCodes.UnknownInteraction,
1085
+ discord_js.RESTJSONErrorCodes.InteractionHasAlreadyBeenAcknowledged,
1086
+ discord_js.RESTJSONErrorCodes.UnknownMessage
1087
+ ]);
1088
+
1089
+ //#endregion
1090
+ //#region src/miscellaneous/flagsFor.ts
1091
+ /**
1092
+ * Builds the `flags` bitfield for a framework reply. Every framework reply is ComponentsV2, so the
1093
+ * IsComponentsV2 flag is always set.
1094
+ *
1095
+ * @param ephemeral - Whether the reply is ephemeral.
1096
+ * @returns The OR'd `MessageFlags` value as a plain number.
1097
+ *
1098
+ * @internal
1099
+ */
1100
+ function flagsFor(ephemeral) {
1101
+ let flags = discord_js.MessageFlags.IsComponentsV2;
1102
+ if (ephemeral) flags |= discord_js.MessageFlags.Ephemeral;
1103
+ return flags;
1104
+ }
1105
+
1106
+ //#endregion
1107
+ //#region src/bot/ReplySender.ts
1108
+ /**
1109
+ * Sends a {@link ReplyResponse} to an interaction, picking reply, editReply, or followUp from the live
1110
+ * acknowledgement state. Logs and drops its own send failures so a dead token never escapes into the
1111
+ * controller.
1112
+ */
1113
+ var ReplySender = class {
1114
+ interaction;
1115
+ logger = new _seedcord_services.Logger("ReplySender");
1116
+ constructor(interaction) {
1117
+ this.interaction = interaction;
1118
+ }
1119
+ /**
1120
+ * Sends the reply and returns the sent message so a caller can attach a collector to it. Never throws,
1121
+ * a failed send is logged and dropped and resolves to `undefined`.
1122
+ *
1123
+ * @param response - The ComponentsV2 reply to show.
1124
+ * @param ephemeral - Whether the reply is ephemeral. {@default `true`}
1125
+ * @returns The sent {@link Message}, or `undefined` when the send was swallowed.
1126
+ */
1127
+ async send(response, ephemeral = true) {
1128
+ try {
1129
+ return await this.dispatch(response, ephemeral);
1130
+ } catch (error) {
1131
+ this.logSwallowed("send", error);
1132
+ return;
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Edits an already-sent message to a new {@link ReplyResponse}. Used to swap a confirmation prompt for
1137
+ * its outcome. Never throws, a failed edit is logged and dropped.
1138
+ *
1139
+ * @param message - The message to edit (the handle a prior {@link send} returned).
1140
+ * @param response - The reply to replace it with.
1141
+ */
1142
+ async edit(message, response) {
1143
+ try {
1144
+ await this.interaction.webhook.editMessage(message, this.editBody(response));
1145
+ } catch (error) {
1146
+ this.logSwallowed("edit", error);
1147
+ }
1148
+ }
1149
+ async dispatch(response, ephemeral) {
1150
+ if (this.interaction.replied) return await this.interaction.followUp(this.replyOptions(response, ephemeral));
1151
+ if (this.interaction.deferred) {
1152
+ if (this.interaction.ephemeral === null) return await this.interaction.followUp(this.replyOptions(response, ephemeral));
1153
+ return await this.interaction.editReply(this.editBody(response));
1154
+ }
1155
+ await this.interaction.reply(this.replyOptions(response, ephemeral));
1156
+ return await this.interaction.fetchReply();
1157
+ }
1158
+ replyOptions(response, ephemeral) {
1159
+ return {
1160
+ components: response.components,
1161
+ flags: flagsFor(ephemeral),
1162
+ ...response.allowedMentions && { allowedMentions: response.allowedMentions },
1163
+ ...response.files && { files: response.files }
1164
+ };
1165
+ }
1166
+ editBody(response) {
1167
+ return {
1168
+ components: response.components,
1169
+ flags: discord_js.MessageFlags.IsComponentsV2,
1170
+ ...response.allowedMentions && { allowedMentions: response.allowedMentions },
1171
+ ...response.files && { files: response.files }
1172
+ };
1173
+ }
1174
+ logSwallowed(action, error) {
1175
+ if (error instanceof discord_js.DiscordAPIError && HARMLESS_API_CODES.has(error.code)) {
1176
+ this.logger.debug(`reply ${action} hit harmless code ${error.code}`);
1177
+ return;
1178
+ }
1179
+ this.logger.error(`reply ${action} failed`, error);
1180
+ }
1181
+ };
1182
+
1183
+ //#endregion
1184
+ //#region src/bot/confirm/reserved.ts
1185
+ const RESERVED_CONFIRM_PREFIX = "__seedcord_confirm";
1186
+ /**
1187
+ * The reserved confirm/cancel codec. It has no route, so the dispatcher ignores its clicks and only the
1188
+ * in-process collector reads them. Do not mint a real component from it.
1189
+ *
1190
+ * @internal
1191
+ */
1192
+ const CONFIRM_DEF = new _seedcord_core.CustomId(RESERVED_CONFIRM_PREFIX).oneOf("choice", ["confirm", "cancel"]);
1193
+
1194
+ //#endregion
1195
+ //#region src/bot/confirm/getConfirmation.ts
1196
+ const DEFAULT_TIMEOUT_MS = 3e4;
1197
+ const CONFIRM_IDS = {
1198
+ confirm: CONFIRM_DEF.encode({ choice: "confirm" }),
1199
+ cancel: CONFIRM_DEF.encode({ choice: "cancel" })
1200
+ };
1201
+ var ConfirmButtons = class extends _seedcord_core.RowComponent {
1202
+ constructor(options) {
1203
+ super("button");
1204
+ this.instance.addComponents(new _discordjs_builders.ButtonBuilder().setCustomId(CONFIRM_IDS.confirm).setLabel(options?.confirmLabel ?? "Confirm").setStyle(options?.confirmStyle ?? discord_js.ButtonStyle.Danger), new _discordjs_builders.ButtonBuilder().setCustomId(CONFIRM_IDS.cancel).setLabel(options?.cancelLabel ?? "Cancel").setStyle(discord_js.ButtonStyle.Secondary));
1205
+ }
1206
+ };
1207
+ var ConfirmPromptCard = class extends _seedcord_core.BuilderComponent {
1208
+ constructor(text, options) {
1209
+ super("container");
1210
+ this.instance.addTextDisplayComponents(new _discordjs_builders.TextDisplayBuilder().setContent(text)).addActionRowComponents(new ConfirmButtons(options).component);
1211
+ }
1212
+ };
1213
+ function defaultPrompt(text, options) {
1214
+ return { components: [new ConfirmPromptCard(text, options).component] };
1215
+ }
1216
+ async function collectChoice(message, userId, timeoutMs) {
1217
+ try {
1218
+ return await message.awaitMessageComponent({
1219
+ componentType: discord_js.ComponentType.Button,
1220
+ time: timeoutMs,
1221
+ filter: (click) => click.user.id === userId && CONFIRM_DEF.owns(click.customId)
1222
+ });
1223
+ } catch {
1224
+ return null;
1225
+ }
1226
+ }
1227
+ async function settle(sender, interaction, message, outcome) {
1228
+ if (outcome === void 0) {
1229
+ await interaction.deleteReply(message).catch(() => void 0);
1230
+ return;
1231
+ }
1232
+ await sender.edit(message, typeof outcome === "function" ? await outcome() : outcome);
1233
+ }
1234
+ async function getConfirmation(interaction, prompt, options) {
1235
+ const { ephemeral = true, timeoutMs = DEFAULT_TIMEOUT_MS } = options ?? {};
1236
+ const response = typeof prompt === "string" ? defaultPrompt(prompt, options) : await prompt(CONFIRM_IDS);
1237
+ const sender = new ReplySender(interaction);
1238
+ const message = await sender.send(response, ephemeral);
1239
+ if (!message) return false;
1240
+ const winner = await collectChoice(message, interaction.user.id, timeoutMs);
1241
+ if (!winner) {
1242
+ await settle(sender, interaction, message, options?.onTimeout);
1243
+ return false;
1244
+ }
1245
+ await winner.deferUpdate().catch(() => void 0);
1246
+ const confirmed = winner.customId === CONFIRM_IDS.confirm;
1247
+ await settle(sender, interaction, message, confirmed ? options?.onConfirm : options?.onCancel);
1248
+ return confirmed;
1249
+ }
1250
+
1251
+ //#endregion
1252
+ //#region src/hmr/devChannel.ts
1253
+ let channel;
1254
+ function setDevChannel(next) {
1255
+ channel = next;
1256
+ }
1257
+ function getDevChannel() {
1258
+ return channel;
1259
+ }
1260
+
1261
+ //#endregion
1262
+ //#region src/interfaces/Plugin.ts
1263
+ /**
1264
+ * Base class for Seedcord plugins
1265
+ *
1266
+ * Extend this class to create plugins that integrate with the Seedcord lifecycle.
1267
+ * Plugins have access to the core instance and must implement initialization logic.
1268
+ */
1269
+ var Plugin = class extends _seedcord_event_emitter.TypedEventEmitter {
1270
+ pluggable;
1271
+ name = this.constructor.name;
1272
+ constructor(pluggable) {
1273
+ super();
1274
+ this.pluggable = pluggable;
1275
+ }
1276
+ /**
1277
+ * Reloads plugin state on an HMR update. The base implementation is a no-op, override it in your plugin.
1278
+ * @virtual
1279
+ */
1280
+ onHmr(_event) {
1281
+ return Promise.resolve();
1282
+ }
1283
+ /**
1284
+ * Registers critical file patterns that should trigger a full restart when changed in Dev HMR.
1285
+ * @param patterns - Glob patterns relative to the project root
1286
+ */
1287
+ registerCriticalFiles(patterns) {
1288
+ getDevChannel()?.send("seedcord:register-critical-files", { patterns });
1289
+ }
1290
+ /** @internal */
1291
+ removeListener(event, listener) {
1292
+ return super.removeListener(event, listener);
1293
+ }
1294
+ /** @internal */
1295
+ removeAllListeners(event) {
1296
+ return super.removeAllListeners(event);
1297
+ }
1298
+ };
1299
+ /**
1300
+ * Base class for objects that can have plugins attached.
1301
+ *
1302
+ * Provides plugin attachment capabilities and lifecycle management. Plugins are attached during
1303
+ * configuration and initialized during startup. Not constructed directly, the host is a {@link Seedcord}.
1304
+ */
1305
+ var Pluggable = class Pluggable extends _seedcord_event_emitter.TypedEventEmitter {
1306
+ isInitialized = false;
1307
+ shutdown;
1308
+ startup;
1309
+ plugins = [];
1310
+ static PLUGIN_INIT_TIMEOUT_MS = 15e3;
1311
+ constructor(shutdown, startup) {
1312
+ super();
1313
+ this.shutdown = shutdown;
1314
+ this.startup = startup;
1315
+ }
1316
+ /** @internal */
1317
+ async init() {
1318
+ if (this.isInitialized) return this;
1319
+ await this.startup.run();
1320
+ this.isInitialized = true;
1321
+ return this;
1322
+ }
1323
+ /**
1324
+ * Attaches a plugin to this instance
1325
+ *
1326
+ * Plugins provide external functionality and are initialized during the specified startup phase.
1327
+ * The plugin instance becomes available as a property in `core` wherever it's available.
1328
+ *
1329
+ * Make sure to augment the {@link Core} interface with the plugin type to ensure TypeScript recognizes it and provides intellisense.
1330
+ *
1331
+ * @typeParam Key - The property name for accessing the plugin
1332
+ * @typeParam Ctor - The plugin constructor type
1333
+ * @param key - Property name to access the plugin instance
1334
+ * @param Plugin - Plugin constructor class
1335
+ * @param startupPhase - When during startup to initialize this plugin ({@link StartupPhase})
1336
+ * @param args - Additional arguments to pass to the plugin constructor
1337
+ * @returns This instance with the plugin attached as a typed property
1338
+ * @throws A **SeedcordError** When called after initialization or if key already exists
1339
+ * @example
1340
+ * ```typescript
1341
+ * seedcord.attach('db', Mongo, StartupPhase.Configuration, { uri: 'mongodb://...', name: 'seedcord', dir: ... })
1342
+ * ```
1343
+ */
1344
+ attach(key, Plugin, startupPhase, ...args) {
1345
+ if (this.isInitialized) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CorePluginAfterInit);
1346
+ if (key in this) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CorePluginKeyExists, [key]);
1347
+ const instance = new Plugin(this, ...args);
1348
+ this.plugins.push(instance);
1349
+ const entry = { [key]: instance };
1350
+ this.startup.addTask(startupPhase, `Plugin:${key}`, async () => {
1351
+ instance.logger.utils.initialization(key, "start");
1352
+ await instance.init();
1353
+ instance.logger.utils.initialization(key, "end");
1354
+ }, Pluggable.PLUGIN_INIT_TIMEOUT_MS);
1355
+ return Object.assign(this, entry);
1356
+ }
1357
+ /** @internal */
1358
+ removeListener(event, listener) {
1359
+ return super.removeListener(event, listener);
1360
+ }
1361
+ /** @internal */
1362
+ removeAllListeners(event) {
1363
+ return super.removeAllListeners(event);
1364
+ }
1365
+ };
1366
+
1367
+ //#endregion
1368
+ //#region src/handlers/BaseHandler.ts
1369
+ /**
1370
+ * Base class for a Discord event or interaction handler. Don't register handlers directly, use the more specific handler subclasses.
1371
+ */
1372
+ var BaseHandler = class {
1373
+ core;
1374
+ event;
1375
+ logger;
1376
+ dispatch;
1377
+ constructor(event, core, dispatch) {
1378
+ this.core = core;
1379
+ this.event = event;
1380
+ this.logger = new _seedcord_services.Logger(this.constructor.name);
1381
+ this.dispatch = dispatch;
1382
+ }
1383
+ /** @internal */
1384
+ getEvent() {
1385
+ return this.event;
1386
+ }
1387
+ };
1388
+
1389
+ //#endregion
1390
+ //#region src/handlers/interaction/InteractionMiddleware.ts
1391
+ /**
1392
+ * Base class for interaction middleware
1393
+ *
1394
+ * Middleware runs before interaction handlers and can modify behavior or block execution.
1395
+ * Unlike handlers, middleware should not send responses directly.
1396
+ *
1397
+ * @typeParam Repliable - The interaction type this middleware processes
1398
+ */
1399
+ var InteractionMiddleware = class extends BaseHandler {
1400
+ constructor(event, core) {
1401
+ super(event, core);
1402
+ }
1403
+ };
1404
+
1405
+ //#endregion
1406
+ //#region src/handlers/interaction/InteractionHandler.ts
1407
+ /**
1408
+ * Shared base the typed interaction handlers extend.
1409
+ *
1410
+ * Not a public entry point. You should be using {@link SlashHandler}, {@link ButtonHandler}, {@link ModalHandler},
1411
+ * or {@link SelectMenuHandler} instead. This class only carries the repliable-event plumbing those bases share,
1412
+ * so DO NOT use it directly.
1413
+ *
1414
+ * @typeParam Repliable - The interaction type this handler processes
1415
+ */
1416
+ var InteractionHandler = class extends BaseHandler {
1417
+ constructor(event, core, dispatch) {
1418
+ super(event, core, dispatch);
1419
+ }
1420
+ };
1421
+
1422
+ //#endregion
1423
+ //#region src/bot/utilities/miscellaneous/slashRouteOf.ts
1424
+ /**
1425
+ * Computes the dispatch route for a chat-input or autocomplete interaction. The controller and
1426
+ * `seedcord codegen` both assemble route keys through the same {@link buildSlashRoute}, so a dispatched
1427
+ * interaction and a generated registry key always match.
1428
+ *
1429
+ * @internal
1430
+ */
1431
+ function slashRouteOf(interaction) {
1432
+ const group = interaction.options.getSubcommandGroup(false) ?? void 0;
1433
+ const subcommand = interaction.options.getSubcommand(false) ?? void 0;
1434
+ return (0, _seedcord_utils_internal.buildSlashRoute)(interaction.commandName, subcommand, group);
1435
+ }
1436
+
1437
+ //#endregion
1438
+ //#region src/handlers/interaction/SlashHandler.ts
1439
+ /**
1440
+ * Base class for a chat-input (slash) command handler.
1441
+ *
1442
+ * Pass the route from the generated registry as the generic, the same string as `@SlashRoute`, then read
1443
+ * `this.options` for a single command or `this.match` for several. Command authoring stays plain
1444
+ * discord.js, `seedcord codegen` reads its `toJSON()` to type these options.
1445
+ *
1446
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'ban'` or `'ban' | 'kick'`.
1447
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1448
+ *
1449
+ * @example
1450
+ * ```ts
1451
+ * \@SlashRoute('ban')
1452
+ * class BanHandler extends SlashHandler<'ban'> {
1453
+ * async execute() {
1454
+ * const target = this.options.getUser('target'); // User
1455
+ * const reason = this.options.getString('reason'); // string | null
1456
+ * }
1457
+ * }
1458
+ * ```
1459
+ */
1460
+ var SlashHandler = class extends InteractionHandler {
1461
+ /**
1462
+ * The typed options for this command's route. Required options drop the null, choices narrow to their
1463
+ * literal union, and only the getters for kinds this command actually uses appear. Use `this.event.options`
1464
+ * directly for anything outside this view, such as narrowing a channel option by type.
1465
+ */
1466
+ get options() {
1467
+ return this.event.options;
1468
+ }
1469
+ /**
1470
+ * Run the arm for whichever command fired. Use this only when the handler is registered for several
1471
+ * routes. A single-route handler reads `this.options` directly instead, match buys nothing there.
1472
+ *
1473
+ * Provide one arm per registered route, keyed by its route string, and each arm receives that route's
1474
+ * own narrowed options. The arms must cover every route in the generic, a missing route or an unknown
1475
+ * key is a compile error.
1476
+ *
1477
+ * @param arms - One handler per registered route, keyed by route string.
1478
+ * @returns The result of the arm that ran.
1479
+ *
1480
+ * @example
1481
+ * ```ts
1482
+ * \@SlashRoute('ban', 'kick')
1483
+ * class ModHandler extends SlashHandler<'ban' | 'kick'> {
1484
+ * async execute() {
1485
+ * await this.match({
1486
+ * ban: (options) => this.event.guild?.members.ban(options.getUser('target', true).id),
1487
+ * kick: (options) => this.event.guild?.members.kick(options.getUser('member', true).id)
1488
+ * });
1489
+ * }
1490
+ * }
1491
+ * ```
1492
+ */
1493
+ async match(arms) {
1494
+ const route = slashRouteOf(this.event);
1495
+ const arm = arms[route];
1496
+ if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.SlashMatchArmMissing, [route]);
1497
+ return await arm(this.options);
1498
+ }
1499
+ };
1500
+
1501
+ //#endregion
1502
+ //#region src/handlers/interaction/ContextMenuHandler.ts
1503
+ /**
1504
+ * Base class for a context-menu command handler (right-click a user or a message).
1505
+ *
1506
+ * Pass the kind from `discord.js`'s {@link ApplicationCommandType} as the generic, the same value as
1507
+ * `@ContextMenuRoute`. Read the right-clicked entity from `this.target`, a `User` for a user menu and a
1508
+ * `Message` for a message menu. Context menus carry no options, so a handler registered for several names
1509
+ * reads `this.target` uniformly with no per-name branch.
1510
+ *
1511
+ * @typeParam Kind - `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
1512
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1513
+ *
1514
+ * @example
1515
+ * ```ts
1516
+ * \@ContextMenuRoute(ApplicationCommandType.Message, 'Report Message')
1517
+ * class ReportMessage extends ContextMenuHandler<ApplicationCommandType.Message> {
1518
+ * async execute() {
1519
+ * const message = this.target;
1520
+ * }
1521
+ * }
1522
+ * ```
1523
+ */
1524
+ var ContextMenuHandler = class extends InteractionHandler {
1525
+ get target() {
1526
+ const event = this.event;
1527
+ return "targetUser" in event ? event.targetUser : event.targetMessage;
1528
+ }
1529
+ /**
1530
+ * The invoking guild member, resolved only on user menus. Reading it on a message menu is a compile
1531
+ * error since the type is `never` there.
1532
+ */
1533
+ get targetMember() {
1534
+ return this.event.targetMember;
1535
+ }
1536
+ };
1537
+
1538
+ //#endregion
1539
+ //#region src/handlers/interaction/AutocompleteHandler.ts
1540
+ /**
1541
+ * Base class for a Discord autocomplete handler.
1542
+ *
1543
+ * Pass the command route(s) from the generated registry as the generic, the same string(s) as
1544
+ * `@AutocompleteRoute`. Branch on the focused field with `this.match`, read already-entered sibling options
1545
+ * with `this.options`, and find which command fired with `this.route`.
1546
+ *
1547
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'search'` or `'search' | 'find'`.
1548
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1549
+ *
1550
+ * @example
1551
+ * ```ts
1552
+ * \@AutocompleteRoute('search')
1553
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
1554
+ * async execute() {
1555
+ * await this.match({
1556
+ * query: (value, respond) => respond([{ name: value, value }])
1557
+ * });
1558
+ * }
1559
+ * }
1560
+ * ```
1561
+ */
1562
+ var AutocompleteHandler = class extends BaseHandler {
1563
+ constructor(event, core, dispatch) {
1564
+ super(event, core, dispatch);
1565
+ }
1566
+ /**
1567
+ * The focused option for this interaction. `value` is always the raw partial string the user is typing,
1568
+ * even for an integer or number option, so coerce it yourself when you need a number.
1569
+ */
1570
+ decodedFocused;
1571
+ get focused() {
1572
+ if (this.decodedFocused) return this.decodedFocused;
1573
+ const raw = this.event.options.getFocused(true);
1574
+ const focused = {
1575
+ name: raw.name,
1576
+ value: raw.value
1577
+ };
1578
+ this.decodedFocused = focused;
1579
+ return focused;
1580
+ }
1581
+ /**
1582
+ * Run the arm for the focused field. An autocomplete always dispatches by which field is focused, so
1583
+ * match is how you read it. There is no single-field shortcut the way slash/component handlers have one.
1584
+ *
1585
+ * Provide one arm per autocompletable field across the registered commands, keyed by field name. Each
1586
+ * arm receives the focused partial value and a `respond` pinned to that field's choice value type. The
1587
+ * arms must cover every autocompletable field, a missing field or an unknown key is a compile error. A
1588
+ * focused field with no arm, only reachable from a stale-deployed command, throws at runtime.
1589
+ *
1590
+ * @param arms - One handler per autocompletable field, keyed by field name.
1591
+ * @returns The result of the arm that ran.
1592
+ *
1593
+ * @example
1594
+ * ```ts
1595
+ * \@AutocompleteRoute('search')
1596
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
1597
+ * async execute() {
1598
+ * await this.match({
1599
+ * query: (value, respond) => respond(titles(value).map((s) => ({ name: s, value: s }))),
1600
+ * tag: (value, respond) => respond(tags(value).map((s) => ({ name: s, value: s })))
1601
+ * });
1602
+ * }
1603
+ * }
1604
+ * ```
1605
+ */
1606
+ async match(arms) {
1607
+ const { name, value } = this.focused;
1608
+ const respond = (choices) => this.event.respond(choices);
1609
+ const arm = arms[name];
1610
+ if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.AutocompleteMatchArmMissing, [name]);
1611
+ return await arm(value, respond);
1612
+ }
1613
+ /** The firing command route, for a field whose completion differs per registered command. */
1614
+ get route() {
1615
+ return slashRouteOf(this.event);
1616
+ }
1617
+ /**
1618
+ * The already-entered options on this command, restricted to the kinds Discord resolves during autocomplete
1619
+ * (string, integer, number, boolean) with every read nullable, since a sibling is partial while the user
1620
+ * types the focused field. Read the focused field from `this.focused`, not here.
1621
+ */
1622
+ get options() {
1623
+ return this.event.options;
1624
+ }
1625
+ };
1626
+
1627
+ //#endregion
1628
+ //#region src/handlers/interaction/components/ComponentHandler.ts
1629
+ /**
1630
+ * Shared base the customId-routed component handlers extend.
1631
+ *
1632
+ * Not a public entry point. You should be using {@link ButtonHandler}, {@link SelectMenuHandler}, or
1633
+ * {@link ModalHandler} instead. This class only carries the customId decode and route-matching plumbing
1634
+ * those bases share, so DO NOT use it directly.
1635
+ *
1636
+ * @typeParam Event - The component interaction type this handler processes
1637
+ * @typeParam Defs - The customId route definitions registered on the concrete handler
1638
+ */
1639
+ var ComponentHandler = class extends InteractionHandler {
1640
+ get registeredDefs() {
1641
+ const defs = Reflect.getMetadata(_seedcord_core_internal.ComponentDefsKey, this.constructor);
1642
+ if (!defs) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CustomIdHandlerRouteMissing, [this.constructor.name]);
1643
+ return defs;
1644
+ }
1645
+ decoded;
1646
+ get route() {
1647
+ if (this.decoded) return this.decoded;
1648
+ const decoded = (0, _seedcord_core_internal.decodeFor)(this.registeredDefs, this.event.customId);
1649
+ this.decoded = decoded;
1650
+ return decoded;
1651
+ }
1652
+ /**
1653
+ * The decoded params of the single route this handler is registered for.
1654
+ *
1655
+ * Reading this decodes `this.event.customId` once (cached after the first read) and throws
1656
+ * `StaleCustomId` or `InvalidCustomId` when the wire no longer matches the current shape, which the
1657
+ * controller boundary turns into a reply. On a handler registered for several routes this is
1658
+ * `never`, so use {@link match} instead.
1659
+ */
1660
+ get params() {
1661
+ return this.route.params;
1662
+ }
1663
+ /**
1664
+ * Run the arm for whichever route the component was minted from. Use this only when the handler is
1665
+ * registered for several routes. A single-route handler reads `this.params` directly. On a multi-route
1666
+ * handler `this.params` is `never`, so match is the only way to read the decoded params.
1667
+ *
1668
+ * Provide one arm per registered route, keyed by its prefix, and each arm receives that route's own
1669
+ * decoded params. The arms must cover every registered def, a missing prefix or an unknown key is a
1670
+ * compile error. Decoding runs before any arm, so a stale or corrupt wire throws before an arm body executes.
1671
+ *
1672
+ * @param arms - One handler per registered route, keyed by prefix.
1673
+ * @returns The result of the arm that ran.
1674
+ *
1675
+ * @example
1676
+ * ```ts
1677
+ * \@ButtonRoute(Approve, Reject)
1678
+ * class ReviewButtons extends ButtonHandler<[typeof Approve, typeof Reject]> {
1679
+ * async execute() {
1680
+ * await this.match({
1681
+ * approve: ({ userId }) => this.event.reply(`approved <@${userId}>`),
1682
+ * reject: ({ userId }) => this.event.reply(`rejected <@${userId}>`)
1683
+ * });
1684
+ * }
1685
+ * }
1686
+ * ```
1687
+ */
1688
+ async match(arms) {
1689
+ const { prefix, params } = this.route;
1690
+ const arm = arms[prefix];
1691
+ if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CustomIdMatchArmMissing, [prefix]);
1692
+ return await arm(params);
1693
+ }
1694
+ };
1695
+
1696
+ //#endregion
1697
+ //#region src/handlers/interaction/components/ButtonHandler.ts
1698
+ /**
1699
+ * Base class for a button interaction handler.
1700
+ *
1701
+ * Register the customId definitions this handler decodes with `@ButtonRoute`, list the same ones in the
1702
+ * generic, then read `this.params` for a single route or `this.match` for several. Passing different
1703
+ * definitions to the decorator and the generic is a compile error.
1704
+ *
1705
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ApproveId]`.
1706
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1707
+ *
1708
+ * @example
1709
+ * ```ts
1710
+ * \@ButtonRoute(ApproveId)
1711
+ * class ApproveButton extends ButtonHandler<[typeof ApproveId]> {
1712
+ * async execute() {
1713
+ * const { userId } = this.params;
1714
+ * await this.event.reply(`approved <@${userId}>`);
1715
+ * }
1716
+ * }
1717
+ * ```
1718
+ */
1719
+ var ButtonHandler = class extends ComponentHandler {};
1720
+
1721
+ //#endregion
1722
+ //#region src/handlers/interaction/components/ModalHandler.ts
1723
+ /**
1724
+ * Base class for a modal submit handler.
1725
+ *
1726
+ * Register the customId definitions this handler decodes with `@ModalRoute`, list the same ones in the
1727
+ * generic, then read `this.params` for a single route or `this.match` for several. Read the submitted
1728
+ * inputs from `this.event.fields`.
1729
+ *
1730
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ConfigId]`.
1731
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1732
+ *
1733
+ * @example
1734
+ * ```ts
1735
+ * \@ModalRoute(ConfigId)
1736
+ * class ConfigModal extends ModalHandler<[typeof ConfigId]> {
1737
+ * async execute() {
1738
+ * const { guildId } = this.params;
1739
+ * const name = this.event.fields.getTextInputValue('name');
1740
+ * await this.event.reply(`saved ${name} for ${guildId}`);
1741
+ * }
1742
+ * }
1743
+ * ```
1744
+ */
1745
+ var ModalHandler = class extends ComponentHandler {};
1746
+
1747
+ //#endregion
1748
+ //#region src/handlers/interaction/components/SelectMenuHandler.ts
1749
+ /**
1750
+ * Base class for a select menu handler.
1751
+ *
1752
+ * Pass the select kind first and the customId definitions second, the same order as `@SelectMenuRoute`,
1753
+ * so `this.event` and `this.event.values` are narrowed to that kind. Read `this.params` for a single
1754
+ * route or `this.match` for several.
1755
+ *
1756
+ * @typeParam Kind - The select kind from {@link SelectMenuKind}, e.g. `SelectMenuKind.User`.
1757
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof AssignId]`.
1758
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1759
+ *
1760
+ * @example
1761
+ * ```ts
1762
+ * \@SelectMenuRoute(SelectMenuKind.User, AssignId)
1763
+ * class AssignSelect extends SelectMenuHandler<SelectMenuKind.User, [typeof AssignId]> {
1764
+ * async execute() {
1765
+ * const { roleId } = this.params;
1766
+ * await this.event.reply(`assigning ${this.event.values.length} member(s) to <@&${roleId}>`);
1767
+ * }
1768
+ * }
1769
+ * ```
1770
+ */
1771
+ var SelectMenuHandler = class extends ComponentHandler {};
1772
+
1773
+ //#endregion
1774
+ //#region src/handlers/event/EventHandler.ts
1775
+ /**
1776
+ * Base class for a Discord client event handler.
1777
+ *
1778
+ * Pass the event name(s) as the generic, the same one(s) as `@RegisterEvent`. A single-event handler reads
1779
+ * `this.event` (the payload tuple) directly. A handler registered for several events branches with `this.match`,
1780
+ * keyed by event name, since the union of payload tuples is not directly readable.
1781
+ *
1782
+ * @typeParam Names - One or more `ClientEvents` keys, e.g. `Events.MessageCreate` or `Events.MessageCreate | Events.MessageUpdate`.
1783
+ *
1784
+ * @example
1785
+ * ```ts
1786
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
1787
+ * class PingPong extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
1788
+ * async execute() {
1789
+ * await this.match({
1790
+ * [Events.MessageCreate]: (message) => message.reply('pong'),
1791
+ * [Events.MessageUpdate]: (_oldMessage, edited) => edited.reply('pong')
1792
+ * });
1793
+ * }
1794
+ * }
1795
+ * ```
1796
+ */
1797
+ var EventHandler = class extends BaseHandler {
1798
+ firedEvent;
1799
+ constructor(event, core, eventName) {
1800
+ super(event, core);
1801
+ this.firedEvent = eventName;
1802
+ }
1803
+ /**
1804
+ * Run the arm for whichever event fired. Use this only when the handler is registered for several
1805
+ * events. A single-event handler reads `this.event` directly. On a multi-event handler `this.event` is
1806
+ * `never`, so match is the only way to read the payload.
1807
+ *
1808
+ * Provide one arm per registered event, keyed by its name, and each arm receives that event's own
1809
+ * payload tuple. The arms must cover every event in the generic, a missing event or an unknown key is a
1810
+ * compile error.
1811
+ *
1812
+ * @param arms - One handler per registered event, keyed by event name.
1813
+ * @returns The result of the arm that ran.
1814
+ *
1815
+ * @example
1816
+ * ```ts
1817
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
1818
+ * class MessageWatcher extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
1819
+ * async execute() {
1820
+ * await this.match({
1821
+ * [Events.MessageCreate]: (message) => this.scan(message),
1822
+ * [Events.MessageUpdate]: (_old, updated) => this.scan(updated)
1823
+ * });
1824
+ * }
1825
+ * }
1826
+ * ```
1827
+ */
1828
+ async match(arms) {
1829
+ const name = this.firedEvent;
1830
+ if (name === void 0) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.EventMatchArmMissing, ["<no event>"]);
1831
+ const arm = arms[name];
1832
+ if (typeof arm !== "function") throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.EventMatchArmMissing, [name]);
1833
+ return await arm(...this.getEvent());
1834
+ }
1835
+ };
1836
+
1837
+ //#endregion
1838
+ //#region src/handlers/event/EventMiddleware.ts
1839
+ /**
1840
+ * Base class for Discord event middleware.
1841
+ *
1842
+ * Middleware runs before event handlers and can stop the event by throwing a `Silence`. Unlike `EventHandler`, it
1843
+ * runs the SAME for every event it is registered for, so it has no `match`. Specify a single event in the
1844
+ * generic and `{ events }` to read `this.event` fully typed. Span several events (or omit `{ events }` for a
1845
+ * catchall) and `this.event` narrows to `never`, read `this.eventName` and do work that does not depend on the
1846
+ * payload shape. A middleware that needs each event's payload is written one event per class.
1847
+ *
1848
+ * @typeParam EventName - One or more `ClientEvents` keys. Defaults to every event (catchall).
1849
+ */
1850
+ var EventMiddleware = class extends BaseHandler {
1851
+ firedEvent;
1852
+ constructor(event, core, eventName) {
1853
+ super(event, core);
1854
+ this.firedEvent = eventName;
1855
+ }
1856
+ /**
1857
+ * The event that fired this middleware. Read it on a catchall or multi-event middleware, where `this.event`
1858
+ * is `never`, to do work that does not depend on the payload shape. A single-event middleware reads
1859
+ * `this.event` directly and does not need this.
1860
+ */
1861
+ get eventName() {
1862
+ if (this.firedEvent === void 0) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.EventMiddlewareNameUnavailable);
1863
+ return this.firedEvent;
1864
+ }
1865
+ };
1866
+
1867
+ //#endregion
1868
+ //#region src/pagination/controls.ts
1869
+ const DEFAULT_LABEL = {
1870
+ first: "First",
1871
+ prev: "Prev",
1872
+ indicator: "",
1873
+ next: "Next",
1874
+ last: "Last"
1875
+ };
1876
+ const CONTROL_SLOT = {
1877
+ first: 0,
1878
+ prev: 1,
1879
+ indicator: 2,
1880
+ next: 3,
1881
+ last: 4
1882
+ };
1883
+ const MAX_BUTTONS_PER_ROW = 5;
1884
+ var Controls = class {
1885
+ cursor;
1886
+ view;
1887
+ constructor(cursor, view) {
1888
+ this.cursor = cursor;
1889
+ this.view = view;
1890
+ }
1891
+ button(key, cosmetics) {
1892
+ const { target, disabled } = this.navState(key);
1893
+ const defaultLabel = key === "indicator" ? this.indicatorText() : DEFAULT_LABEL[key];
1894
+ const label = cosmetics?.label ?? (key === "indicator" || !cosmetics?.emoji ? defaultLabel : void 0);
1895
+ const button = new _discordjs_builders.ButtonBuilder().setCustomId(this.cursor.encode({
1896
+ page: Math.min(Math.max(0, target), _seedcord_core_internal.PAGE_MAX),
1897
+ slot: CONTROL_SLOT[key]
1898
+ })).setStyle(cosmetics?.style ?? discord_js.ButtonStyle.Secondary).setDisabled(disabled);
1899
+ if (label !== void 0) button.setLabel(label);
1900
+ if (cosmetics?.emoji) button.setEmoji(cosmetics.emoji);
1901
+ return button;
1902
+ }
1903
+ navState(key) {
1904
+ const { page, totalPages, hasPrev, hasNext } = this.view;
1905
+ const knownTotal = totalPages !== void 0;
1906
+ return {
1907
+ target: {
1908
+ first: 0,
1909
+ prev: page - 1,
1910
+ indicator: page,
1911
+ next: page + 1,
1912
+ last: knownTotal ? totalPages - 1 : page
1913
+ }[key],
1914
+ disabled: {
1915
+ first: !hasPrev,
1916
+ prev: !hasPrev,
1917
+ indicator: true,
1918
+ next: !hasNext || page + 1 > _seedcord_core_internal.PAGE_MAX,
1919
+ last: !hasNext || !knownTotal || totalPages - 1 > _seedcord_core_internal.PAGE_MAX
1920
+ }[key]
1921
+ };
1922
+ }
1923
+ row(...keys) {
1924
+ if (keys.length === 0) throw new _seedcord_errors_internal.SeedcordRangeError(_seedcord_errors.SeedcordErrorCode.PaginationEmptyControls);
1925
+ if (keys.length > MAX_BUTTONS_PER_ROW) throw new _seedcord_errors_internal.SeedcordRangeError(_seedcord_errors.SeedcordErrorCode.PaginationTooManyControls, [keys.length]);
1926
+ const seen = /* @__PURE__ */ new Set();
1927
+ for (const key of keys) {
1928
+ if (seen.has(key)) throw new _seedcord_errors_internal.SeedcordTypeError(_seedcord_errors.SeedcordErrorCode.PaginationDuplicateControls, [key]);
1929
+ seen.add(key);
1930
+ }
1931
+ return new _discordjs_builders.ActionRowBuilder().addComponents(keys.map((key) => this.button(key)));
1932
+ }
1933
+ indicatorText() {
1934
+ const { page, totalPages } = this.view;
1935
+ return totalPages === void 0 ? `Page ${page + 1}` : `Page ${page + 1} of ${totalPages}`;
1936
+ }
1937
+ };
1938
+
1939
+ //#endregion
1940
+ //#region src/pagination/render.ts
1941
+ var PageContainer = class extends _seedcord_core.BuilderComponent {
1942
+ constructor(view, renderItem, controlRow) {
1943
+ super("container");
1944
+ const base = view.page * view.perPage;
1945
+ let lines = [];
1946
+ const flush = () => {
1947
+ if (lines.length === 0) return;
1948
+ this.instance.addTextDisplayComponents(new _discordjs_builders.TextDisplayBuilder().setContent(lines.join("\n")));
1949
+ lines = [];
1950
+ };
1951
+ view.items.forEach((item, offset) => {
1952
+ const rendered = renderItem(item, base + offset);
1953
+ if (typeof rendered === "string") {
1954
+ lines.push(rendered);
1955
+ return;
1956
+ }
1957
+ flush();
1958
+ this.instance.addSectionComponents(rendered.component);
1959
+ });
1960
+ flush();
1961
+ this.instance.addActionRowComponents(controlRow);
1962
+ }
1963
+ };
1964
+ function toReplyResponse(renderable) {
1965
+ if (typeof renderable === "string") return { components: [new _discordjs_builders.TextDisplayBuilder().setContent(renderable)] };
1966
+ if (Array.isArray(renderable)) return { components: renderable };
1967
+ return renderable;
1968
+ }
1969
+ const ARRAY_KEYS = [
1970
+ "first",
1971
+ "prev",
1972
+ "indicator",
1973
+ "next",
1974
+ "last"
1975
+ ];
1976
+ const CURSOR_KEYS = [
1977
+ "prev",
1978
+ "indicator",
1979
+ "next"
1980
+ ];
1981
+ /**
1982
+ * Build a page's V2 reply. A `render` override builds the whole tree, otherwise the default container lists
1983
+ * the items and appends the controls (all five for a known total, prev/indicator/next for a cursor source).
1984
+ */
1985
+ function renderPage(view, cursor, config) {
1986
+ const controls = new Controls(cursor, view);
1987
+ if (config.render) return toReplyResponse(config.render(view, controls));
1988
+ return { components: [new PageContainer(view, config.renderItem ?? String, controls.row(...view.totalPages === void 0 ? CURSOR_KEYS : ARRAY_KEYS)).component] };
1989
+ }
1990
+
1991
+ //#endregion
1992
+ //#region src/pagination/Paginator.ts
1993
+ function contextOf(interaction, core) {
1994
+ return {
1995
+ interaction,
1996
+ user: interaction.user,
1997
+ guild: interaction.guild,
1998
+ ...core && { core }
1999
+ };
2000
+ }
2001
+ /**
2002
+ * A restart-proof paginator. Each nav button's customId encodes its full target page, so clicks are
2003
+ * idempotent and survive a restart. A persistent `@ButtonRoute` on `Handler` dispatches the clicks.
2004
+ *
2005
+ * @typeParam Item - The item type, inferred from the source.
2006
+ * @typeParam Prefix - The route prefix, inferred from `config.prefix`.
2007
+ *
2008
+ * @example
2009
+ * ```ts
2010
+ * export const Bans = new Paginator({
2011
+ * prefix: 'bans',
2012
+ * source: new ArraySource((ctx) => ctx.guild.bans.fetch().then((b) => [...b.values()]), { perPage: 10 }),
2013
+ * renderItem: (ban) => ban.user.tag
2014
+ * });
2015
+ *
2016
+ * \@ButtonRoute(Bans.cursor)
2017
+ * export class BansNav extends Bans.Handler {}
2018
+ * ```
2019
+ */
2020
+ var Paginator = class {
2021
+ /** The page cursor, pass it to your `@ButtonRoute`. */
2022
+ cursor;
2023
+ /** The nav handler base. Extend it with an empty body and decorate it, `@ButtonRoute(p.cursor)`. */
2024
+ Handler;
2025
+ config;
2026
+ constructor(config) {
2027
+ this.cursor = (0, _seedcord_core_internal.pageCursor)(config.prefix);
2028
+ this.config = config;
2029
+ const loadPage = (ctx, n) => this.page(ctx, n);
2030
+ this.Handler = class Nav extends ButtonHandler {
2031
+ async execute() {
2032
+ await this.event.deferUpdate();
2033
+ const response = await loadPage(contextOf(this.event, this.core), this.params.page);
2034
+ await new ReplySender(this.event).edit(this.event.message, response);
2035
+ }
2036
+ };
2037
+ }
2038
+ /** Render page 0 and send it, picking reply or followUp from the interaction's state. */
2039
+ async start(interaction, core) {
2040
+ const response = await this.page(contextOf(interaction, core), 0);
2041
+ return new ReplySender(interaction).send(response, this.config.ephemeral ?? false);
2042
+ }
2043
+ /** Render a page as a {@link ReplyResponse}. To post it elsewhere, add `flags: MessageFlags.IsComponentsV2`. */
2044
+ async page(ctx, n) {
2045
+ return renderPage(await this.config.source.page(ctx, n), this.cursor, this.config);
2046
+ }
2047
+ };
2048
+
2049
+ //#endregion
2050
+ //#region src/pagination/sources.ts
2051
+ const DEFAULT_PER_PAGE = 10;
2052
+ /**
2053
+ * A source for a bounded list you can load whole. It loads the full list on every click, then slices the
2054
+ * page via {@link paginate}, so the real total is known (a real last button, "Page X of Y"). Cache inside
2055
+ * your loader if the load is expensive.
2056
+ *
2057
+ * @typeParam Item - The item type, inferred from the loader's return.
2058
+ */
2059
+ var ArraySource = class {
2060
+ load;
2061
+ perPage;
2062
+ constructor(load, opts) {
2063
+ this.load = load;
2064
+ this.perPage = opts?.perPage ?? DEFAULT_PER_PAGE;
2065
+ if (!Number.isSafeInteger(this.perPage) || this.perPage <= 0) throw new _seedcord_errors_internal.SeedcordRangeError(_seedcord_errors.SeedcordErrorCode.PaginationInvalidPerPage, [this.perPage]);
2066
+ }
2067
+ async page(ctx, n) {
2068
+ return (0, _seedcord_core.paginate)(await this.load(ctx), n, this.perPage);
2069
+ }
2070
+ };
2071
+ /**
2072
+ * A source for a large or unknown-length set you fetch one page at a time (SQL LIMIT/OFFSET, a paged API).
2073
+ * The fetcher receives the page index and the page size and reports whether a next page exists. A cursor
2074
+ * source has no cheap total, so `totalPages` is undefined, the last button is omitted, and the indicator
2075
+ * reads "Page X".
2076
+ *
2077
+ * @typeParam Item - The item type, inferred from the fetcher's slice.
2078
+ */
2079
+ var CursorSource = class {
2080
+ fetch;
2081
+ perPage;
2082
+ constructor(fetch, opts) {
2083
+ this.fetch = fetch;
2084
+ this.perPage = opts?.perPage ?? DEFAULT_PER_PAGE;
2085
+ if (!Number.isSafeInteger(this.perPage) || this.perPage <= 0) throw new _seedcord_errors_internal.SeedcordRangeError(_seedcord_errors.SeedcordErrorCode.PaginationInvalidPerPage, [this.perPage]);
2086
+ }
2087
+ async page(ctx, n) {
2088
+ const page = Math.max(0, Math.trunc(n));
2089
+ const { items, hasNext } = await this.fetch(ctx, page, this.perPage);
2090
+ return {
2091
+ items: [...items],
2092
+ page,
2093
+ perPage: this.perPage,
2094
+ hasPrev: page > 0,
2095
+ hasNext
2096
+ };
2097
+ }
2098
+ };
2099
+
2100
+ //#endregion
2101
+ //#region src/subscribers/Subscriber.ts
2102
+ /**
2103
+ * Abstract base class for handling application subscribers.
2104
+ *
2105
+ * Provides type-safe access to subscribers data and the core framework instance.
2106
+ * Extend this class to create custom subscriber handlers.
2107
+ *
2108
+ * @typeParam KeyOfSubscribers - The specific subscriber type this handler processes
2109
+ */
2110
+ var Subscriber = class {
2111
+ data;
2112
+ core;
2113
+ logger;
2114
+ /**
2115
+ * Instantiates the subscriber with event data and core.
2116
+ *
2117
+ * @param data - The subscriber event data
2118
+ * @param core - The core framework instance
2119
+ */
2120
+ constructor(data, core) {
2121
+ this.data = data;
2122
+ this.core = core;
2123
+ this.logger = new _seedcord_services.Logger(this.constructor.name);
2124
+ }
2125
+ };
2126
+
2127
+ //#endregion
2128
+ //#region src/subscribers/decorators/Subscribe.ts
2129
+ /**
2130
+ * Registers a subscriber handler class with a specific subscriber event.
2131
+ *
2132
+ * Associates the decorated class with a subscriber event type for automatic
2133
+ * registration and execution when the subscriber is emitted.
2134
+ *
2135
+ * @typeParam TSubscriber - The subscriber event name to register for
2136
+ * @param subscriber - The subscriber event name to register for
2137
+ * @param options - Options to configure the subscriber handler registration.
2138
+ * @decorator
2139
+ * @example
2140
+ * ```typescript
2141
+ * \@Subscribe('userJoin')
2142
+ * class WelcomeHandler extends Subscriber<'userJoin'> {
2143
+ * async execute() {
2144
+ * // Handle user join event
2145
+ * }
2146
+ * }
2147
+ * ```
2148
+ * @example
2149
+ * ```ts
2150
+ * \@Subscribe('userJoin', { frequency: 'once' })
2151
+ * // or
2152
+ * \@Subscribe('userJoin')
2153
+ * ```
2154
+ */
2155
+ function Subscribe(subscriber, options) {
2156
+ return function(constructor) {
2157
+ const meta = {
2158
+ subscriber,
2159
+ frequency: options?.frequency
2160
+ };
2161
+ Reflect.defineMetadata(_seedcord_core_internal.SubscribeMetadataKey, meta, constructor);
2162
+ };
2163
+ }
2164
+
2165
+ //#endregion
2166
+ //#region src/subscribers/bases/WebhookLog.ts
2167
+ /**
2168
+ * Abstract webhook logging handler for subscriber events.
2169
+ *
2170
+ * Extends Subscriber to provide webhook-based logging capabilities.
2171
+ * Implementations must define the webhook client to send messages to by implementing the webhook property.
2172
+ *
2173
+ * @typeParam KeyOfSubscribers - The specific subscriber type this handler processes
2174
+ */
2175
+ var WebhookLog = class extends Subscriber {
2176
+ constructor(data, core) {
2177
+ super(data, core);
2178
+ }
2179
+ };
2180
+
2181
+ //#endregion
2182
+ //#region src/hmr/HmrModuleHandler.ts
2183
+ /**
2184
+ * Reloads THandler and optional TMiddleware modules on HMR updates.
2185
+ *
2186
+ * You can either implement a custom `onHmr()` method in your class by extending `HmrAware`, or if it's a plugin, override the existing `onHmr()` with fully custom logic. Or, use this class's `handle()` method inside your `onHmr()` to get standard HMR handling for your modules based on the provided options you give to the constructor.
2187
+ *
2188
+ * This is only useful during development.
2189
+ */
2190
+ var HmrModuleHandler = class {
2191
+ store;
2192
+ options;
2193
+ constructor(options) {
2194
+ this.options = {
2195
+ ...options,
2196
+ logger: options.logger.inChannel("hmr")
2197
+ };
2198
+ this.store = {
2199
+ fileToHandlers: /* @__PURE__ */ new Map(),
2200
+ fileToMiddlewares: /* @__PURE__ */ new Map(),
2201
+ handlerArtifacts: /* @__PURE__ */ new Map()
2202
+ };
2203
+ }
2204
+ /**
2205
+ * Handles an HMR update event by reloading affected modules based on the event details and config. It receives an {@link HmrUpdateEvent}, then checks the type of update.
2206
+ *
2207
+ * - If it's a deletion, it unloads the module.
2208
+ * - If it's an update/creation, it checks if the file is tracked, unloads it if so, then reloads the file if it is in the handlers or middlewares directory and is a valid handler/middleware.
2209
+ */
2210
+ async handle(event) {
2211
+ const { file, affectedModules, type } = event;
2212
+ const { logger, handlersDir, middlewaresDir } = this.options;
2213
+ if (type === "delete" || type === "deleteDir") {
2214
+ this.unload(file);
2215
+ return;
2216
+ }
2217
+ if (type === "update" && !(0, node_fs.existsSync)(file)) {
2218
+ if (this.isTracked(file)) {
2219
+ logger.info(`Received update for non-existent file: ${(0, _seedcord_utils.formatFilePath)(file)}, treating as delete`);
2220
+ this.unload(file);
2221
+ }
2222
+ return;
2223
+ }
2224
+ const rollbackEnabled = event.rollback ?? true;
2225
+ const filesToReload = affectedModules && affectedModules.length > 0 ? affectedModules : [file];
2226
+ const absHandlersDir = (0, node_path.resolve)(process.cwd(), handlersDir);
2227
+ const absMiddlewaresDir = middlewaresDir ? (0, node_path.resolve)(process.cwd(), middlewaresDir) : null;
2228
+ for (const fileToReload of filesToReload) {
2229
+ const isHandler = fileToReload.startsWith(absHandlersDir);
2230
+ const isMiddleware = absMiddlewaresDir ? fileToReload.startsWith(absMiddlewaresDir) : false;
2231
+ if (!isHandler && !isMiddleware) continue;
2232
+ await this.reloadWithRollback(fileToReload, rollbackEnabled);
2233
+ }
2234
+ }
2235
+ async reloadWithRollback(file, rollbackEnabled) {
2236
+ const { logger } = this.options;
2237
+ const snapshot = this.snapshotUnits(file);
2238
+ this.unload(file);
2239
+ if (await this.reloadFile(file)) return;
2240
+ this.unload(file);
2241
+ if (!rollbackEnabled) return;
2242
+ this.restoreUnits(file, snapshot);
2243
+ logger.warn(`${chalk.default.yellow.bold("Rolled back")} ${chalk.default.gray((0, _seedcord_utils.formatFilePath)(file))} to the last-good version`);
2244
+ }
2245
+ /**
2246
+ * Tracks a handler module as being loaded from a specific file.
2247
+ * @param file - The file path the handler was loaded from.
2248
+ * @param handler - The handler module instance.
2249
+ */
2250
+ trackHandler(file, handler) {
2251
+ let set = this.store.fileToHandlers.get(file);
2252
+ if (!set) {
2253
+ set = /* @__PURE__ */ new Set();
2254
+ this.store.fileToHandlers.set(file, set);
2255
+ }
2256
+ set.add(handler);
2257
+ if (this.options.getArtifacts) {
2258
+ const artifacts = this.options.getArtifacts(handler);
2259
+ this.store.handlerArtifacts.set(handler, artifacts);
2260
+ }
2261
+ }
2262
+ /**
2263
+ * Tracks a middleware module as being loaded from a specific file.
2264
+ * @param file - The file path the middleware was loaded from.
2265
+ * @param middleware - The middleware module instance.
2266
+ */
2267
+ trackMiddleware(file, middleware) {
2268
+ let set = this.store.fileToMiddlewares.get(file);
2269
+ if (!set) {
2270
+ set = /* @__PURE__ */ new Set();
2271
+ this.store.fileToMiddlewares.set(file, set);
2272
+ }
2273
+ set.add(middleware);
2274
+ }
2275
+ isTracked(file) {
2276
+ return this.store.fileToHandlers.has(file) || this.store.fileToMiddlewares.has(file);
2277
+ }
2278
+ unload(file) {
2279
+ const { logger } = this.options;
2280
+ const handlers = this.store.fileToHandlers.get(file);
2281
+ if (handlers) {
2282
+ for (const handler of handlers) {
2283
+ const artifacts = this.store.handlerArtifacts.get(handler);
2284
+ this.options.unregisterHandler(handler, artifacts);
2285
+ this.store.handlerArtifacts.delete(handler);
2286
+ const name = handler.name ?? "Handler";
2287
+ logger.info(`${chalk.default.red.bold("Unloaded")} ${chalk.default.cyan.bold(name)} from ${chalk.default.gray((0, _seedcord_utils.formatFilePath)(file))}`);
2288
+ }
2289
+ this.store.fileToHandlers.delete(file);
2290
+ }
2291
+ const middlewares = this.store.fileToMiddlewares.get(file);
2292
+ if (middlewares) {
2293
+ for (const middleware of middlewares) {
2294
+ this.options.unregisterMiddleware?.(middleware);
2295
+ const name = middleware.name ?? "Middleware";
2296
+ logger.info(`${chalk.default.red.bold("Unloaded")} ${chalk.default.cyan.bold(name)} from ${chalk.default.gray((0, _seedcord_utils.formatFilePath)(file))}`);
2297
+ }
2298
+ this.store.fileToMiddlewares.delete(file);
2299
+ }
2300
+ }
2301
+ async reloadFile(file) {
2302
+ const { logger, isHandler, isMiddleware, registerHandler, registerMiddleware } = this.options;
2303
+ if (!(0, node_fs.existsSync)(file)) {
2304
+ logger.info(`File does not exist, skipping reload: ${(0, _seedcord_utils.formatFilePath)(file)}`);
2305
+ return false;
2306
+ }
2307
+ try {
2308
+ let fileUrl = (0, node_url.pathToFileURL)(file).href;
2309
+ if (process.env.VITEST === "true") fileUrl += `?update=${Date.now()}`;
2310
+ const imported = await import(fileUrl);
2311
+ for (const val of Object.values(imported)) if (isHandler(val)) {
2312
+ registerHandler(val, file);
2313
+ this.trackHandler(file, val);
2314
+ const name = val.name ?? "Handler";
2315
+ logger.info(`${chalk.default.blue.bold("Reloaded")} ${chalk.default.cyan.bold(name)} from ${chalk.default.gray((0, _seedcord_utils.formatFilePath)(file))}`);
2316
+ } else if (isMiddleware && registerMiddleware && isMiddleware(val)) {
2317
+ registerMiddleware(val, file);
2318
+ this.trackMiddleware(file, val);
2319
+ const name = val.name ?? "Middleware";
2320
+ logger.info(`${chalk.default.blue.bold("Reloaded")} ${chalk.default.cyan.bold(name)} from ${chalk.default.gray((0, _seedcord_utils.formatFilePath)(file))}`);
2321
+ }
2322
+ return true;
2323
+ } catch (error) {
2324
+ logger.error(`Failed to reload file: ${file}`, error);
2325
+ return false;
2326
+ }
2327
+ }
2328
+ snapshotUnits(file) {
2329
+ return {
2330
+ handlers: [...this.store.fileToHandlers.get(file) ?? []],
2331
+ middlewares: [...this.store.fileToMiddlewares.get(file) ?? []]
2332
+ };
2333
+ }
2334
+ restoreUnits(file, snapshot) {
2335
+ for (const handler of snapshot.handlers) {
2336
+ this.options.registerHandler(handler, file);
2337
+ this.trackHandler(file, handler);
2338
+ }
2339
+ if (this.options.registerMiddleware) for (const middleware of snapshot.middlewares) {
2340
+ this.options.registerMiddleware(middleware, file);
2341
+ this.trackMiddleware(file, middleware);
2342
+ }
2343
+ }
2344
+ };
2345
+
2346
+ //#endregion
2347
+ //#region src/bot/utilities/miscellaneous/contextMenuLeaves.ts
2348
+ /**
2349
+ * Collects the names of every registered context-menu command across a set of command builders, split into a
2350
+ * user set and a message set. The same builder may appear more than once (a guild command is pushed once per
2351
+ * guild), and slash commands carry no context-menu name, so both collapse here. The split mirrors the
2352
+ * controller's two name-keyed maps, so the boot guard checks each name against its own kind.
2353
+ *
2354
+ * @internal
2355
+ */
2356
+ function contextMenuLeaves(commands) {
2357
+ const user = /* @__PURE__ */ new Set();
2358
+ const message = /* @__PURE__ */ new Set();
2359
+ for (const command of commands) {
2360
+ if (!(command instanceof _discordjs_builders.ContextMenuCommandBuilder)) continue;
2361
+ if (command.type === discord_js.ApplicationCommandType.User) user.add(command.name);
2362
+ else message.add(command.name);
2363
+ }
2364
+ return {
2365
+ user,
2366
+ message
2367
+ };
2368
+ }
2369
+
2370
+ //#endregion
2371
+ //#region src/bot/utilities/miscellaneous/slashRouteLeaves.ts
2372
+ /**
2373
+ * Collects the route keys of every executable slash leaf across a set of command builders, deduplicated. The
2374
+ * same builder may appear more than once (a guild command is pushed once per guild), and context-menu
2375
+ * commands carry no slash route, so both collapse here. Route keys come from the same {@link routeLeavesOf}
2376
+ * that `seedcord codegen` reads, so the boot-time check compares against the generated registry's keys.
2377
+ *
2378
+ * @internal
2379
+ */
2380
+ function slashRouteLeaves(commands) {
2381
+ const leaves = /* @__PURE__ */ new Set();
2382
+ for (const command of commands) {
2383
+ if (!(command instanceof _discordjs_builders.SlashCommandBuilder)) continue;
2384
+ for (const leaf of (0, _seedcord_utils_internal.routeLeavesOf)(command.toJSON())) leaves.add(leaf.route);
2385
+ }
2386
+ return leaves;
2387
+ }
2388
+
2389
+ //#endregion
2390
+ //#region src/bot/controllers/CommandRegistry.ts
2391
+ /**
2392
+ * Manages Discord application command registration and deployment.
2393
+ *
2394
+ * Scans command directories, builds command structures, and registers both global and guild-scoped commands
2395
+ * to Discord's API. Accessed via `core.bot.commands`. Do not construct it directly.
2396
+ */
2397
+ var CommandRegistry = class {
2398
+ core;
2399
+ onDeployed;
2400
+ name = "Commands";
2401
+ logger = new _seedcord_services.Logger("Commands");
2402
+ isInitialised = false;
2403
+ globalCommands = [];
2404
+ guildCommands = new discord_js.Collection();
2405
+ ctorToCommand = /* @__PURE__ */ new Map();
2406
+ hmrHandler;
2407
+ pendingEvents = /* @__PURE__ */ new Map();
2408
+ constructor(core, onDeployed) {
2409
+ this.core = core;
2410
+ this.onDeployed = onDeployed;
2411
+ const commandsDir = this.core.config.bot.commands.path;
2412
+ if (!commandsDir) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CoreControllerPathMissing, ["CommandRegistry", "commands"]);
2413
+ if (!envapt.Envapter.isDevelopment && !envapt.Envapter.isTest) return;
2414
+ this.hmrHandler = new HmrModuleHandler({
2415
+ handlersDir: commandsDir,
2416
+ isHandler: this.isCommandClass.bind(this),
2417
+ registerHandler: this.registerCommand.bind(this),
2418
+ unregisterHandler: this.unregisterCommand.bind(this),
2419
+ getArtifacts: this.getArtifacts.bind(this),
2420
+ logger: this.logger
2421
+ });
2422
+ }
2423
+ getArtifacts(ctor) {
2424
+ return this.ctorToCommand.get(ctor);
2425
+ }
2426
+ /** @internal */
2427
+ async init() {
2428
+ if (this.isInitialised) return;
2429
+ this.isInitialised = true;
2430
+ const commandsDir = this.core.config.bot.commands.path;
2431
+ if (!commandsDir) return;
2432
+ this.logger.info(chalk.default.bold(commandsDir));
2433
+ await this.loadCommands(commandsDir);
2434
+ this.logger.utils.summary("Loaded commands", {
2435
+ global: this.globalCommands.length,
2436
+ "guild groups": this.guildCommands.size
2437
+ });
2438
+ getDevChannel()?.on("seedcord:refresh-commands", (data) => {
2439
+ this.refresh(data.shouldRefresh);
2440
+ });
2441
+ }
2442
+ /** @internal */
2443
+ async refresh(shouldRefresh = true) {
2444
+ if (!shouldRefresh) {
2445
+ this.logger.info(chalk.default.italic("Command refresh cancelled."));
2446
+ this.pendingEvents.clear();
2447
+ return;
2448
+ }
2449
+ this.logger.info(chalk.default.italic("Refreshing commands..."));
2450
+ for (const event of this.pendingEvents.values()) await this.hmrHandler?.handle(event);
2451
+ this.pendingEvents.clear();
2452
+ await this.setCommands();
2453
+ }
2454
+ /** @internal */
2455
+ async onHmr(event) {
2456
+ const commandsDir = this.core.config.bot.commands.path;
2457
+ if (commandsDir && event.file.startsWith((0, node_path.resolve)(process.cwd(), commandsDir))) {
2458
+ this.pendingEvents.delete(event.file);
2459
+ this.pendingEvents.set(event.file, event);
2460
+ getDevChannel()?.send("seedcord:commands-update-prompt", { files: [...this.pendingEvents.keys()].map((f) => (0, _seedcord_utils.formatFilePath)(f)) });
2461
+ } else await this.hmrHandler?.handle(event);
2462
+ }
2463
+ async loadCommands(dir) {
2464
+ await (0, _seedcord_utils.traverseDirectory)(dir, (fullPath, rel, mod) => {
2465
+ for (const exported of Object.values(mod)) if (this.isCommandClass(exported)) {
2466
+ this.registerCommand(exported, rel);
2467
+ this.hmrHandler?.trackHandler(fullPath, exported);
2468
+ }
2469
+ }, this.logger);
2470
+ }
2471
+ isCommandClass(obj) {
2472
+ if (typeof obj !== "function") return false;
2473
+ return obj.prototype instanceof _seedcord_core.BuilderComponent && Reflect.hasMetadata(_seedcord_core_internal.CommandMetadataKey, obj);
2474
+ }
2475
+ registerCommand(ctor, rel) {
2476
+ const meta = Reflect.getMetadata(_seedcord_core_internal.CommandMetadataKey, ctor);
2477
+ if (!meta) return;
2478
+ const comp = new ctor().component;
2479
+ const commandType = comp instanceof _discordjs_builders.SlashCommandBuilder ? "slash command" : "context menu command";
2480
+ if (meta.scope === "global") {
2481
+ this.globalCommands.push(comp);
2482
+ this.logger.utils.registration(ctor.name, rel);
2483
+ this.logger.utils.item(`Global ${commandType}: ${chalk.default.bold.cyan(comp.name)}`);
2484
+ } else {
2485
+ for (const g of meta.guilds) {
2486
+ const arr = this.guildCommands.get(g) ?? [];
2487
+ arr.push(comp);
2488
+ this.guildCommands.set(g, arr);
2489
+ }
2490
+ this.logger.utils.registration(ctor.name, rel);
2491
+ this.logger.utils.item(`Guild ${commandType}: ${chalk.default.bold.cyan(comp.name)} for ${chalk.default.magenta.bold(meta.guilds.length)} guild(s)`);
2492
+ }
2493
+ this.ctorToCommand.set(ctor, {
2494
+ name: comp.name,
2495
+ scope: meta.scope,
2496
+ ...meta.scope === "guild" && { guilds: meta.guilds }
2497
+ });
2498
+ }
2499
+ unregisterCommand(ctor, artifacts) {
2500
+ const info = artifacts ?? this.ctorToCommand.get(ctor);
2501
+ if (!info) return;
2502
+ if (info.scope === "global") {
2503
+ const idx = this.globalCommands.findIndex((c) => c.name === info.name);
2504
+ if (idx !== -1) this.globalCommands.splice(idx, 1);
2505
+ } else for (const g of info.guilds ?? []) {
2506
+ const arr = this.guildCommands.get(g);
2507
+ if (arr) {
2508
+ const idx = arr.findIndex((c) => c.name === info.name);
2509
+ if (idx !== -1) arr.splice(idx, 1);
2510
+ }
2511
+ }
2512
+ this.ctorToCommand.delete(ctor);
2513
+ }
2514
+ /** @internal */
2515
+ async setCommands() {
2516
+ const result = {
2517
+ global: new discord_js.Collection(),
2518
+ guilds: new discord_js.Collection()
2519
+ };
2520
+ if (this.globalCommands.length > 0) {
2521
+ const deployed = await this.core.bot.client.application?.commands.set(this.globalCommands);
2522
+ if (deployed) result.global = deployed;
2523
+ const tag = this.globalCommands.length === 1 ? "command" : "commands";
2524
+ this.logger.utils.summary("Configured global", { [tag]: this.globalCommands.length });
2525
+ this.logger.utils.item(`${this.globalCommands.map((command) => chalk.default.bold.cyan(command.name)).join(", ")}`);
2526
+ }
2527
+ for (const [guildId, commands] of this.guildCommands.entries()) {
2528
+ const guild = this.core.bot.client.guilds.cache.get(guildId);
2529
+ if (!guild) {
2530
+ this.logger.warn(`Guild with ID ${guildId} not found, skipping command registration.`);
2531
+ continue;
2532
+ }
2533
+ const deployed = await guild.commands.set(commands);
2534
+ result.guilds.set(guildId, deployed);
2535
+ const tag = commands.length === 1 ? "command" : "commands";
2536
+ this.logger.utils.summary(`Configured commands for ${chalk.default.bold.yellow(guild.name)}`, { [tag]: commands.length });
2537
+ this.logger.utils.item(`${commands.map((command) => chalk.default.bold.cyan(command.name)).join(", ")}`);
2538
+ }
2539
+ this.onDeployed?.(result);
2540
+ return result;
2541
+ }
2542
+ /** The deduplicated slash route keys across every global and guild command. @internal */
2543
+ routeLeaves() {
2544
+ return slashRouteLeaves([...this.globalCommands, ...this.guildCommands.values()].flat());
2545
+ }
2546
+ /** The registered context-menu command names, split by kind, across every global and guild command. @internal */
2547
+ contextMenuLeaves() {
2548
+ return contextMenuLeaves([...this.globalCommands, ...this.guildCommands.values()].flat());
2549
+ }
2550
+ };
2551
+
2552
+ //#endregion
2553
+ //#region src/miscellaneous/deriveEventActor.ts
2554
+ function deriveEventActor(args) {
2555
+ const tuple = Array.isArray(args) ? args : [args];
2556
+ for (const arg of tuple) {
2557
+ if (arg instanceof discord_js.Message) return {
2558
+ guild: arg.guild,
2559
+ member: arg.member,
2560
+ user: arg.author,
2561
+ channelId: arg.channelId
2562
+ };
2563
+ if (arg instanceof discord_js.GuildMember) return {
2564
+ guild: arg.guild,
2565
+ member: arg,
2566
+ user: arg.user,
2567
+ channelId: null
2568
+ };
2569
+ if (arg instanceof discord_js.User) return {
2570
+ guild: null,
2571
+ member: null,
2572
+ user: arg,
2573
+ channelId: null
2574
+ };
2575
+ }
2576
+ return {
2577
+ guild: null,
2578
+ member: null,
2579
+ user: null,
2580
+ channelId: null
2581
+ };
2582
+ }
2583
+
2584
+ //#endregion
2585
+ //#region src/bot/gates/runGates.ts
2586
+ function interactionGateContext(interaction, core) {
2587
+ const rawMember = interaction.member;
2588
+ const memberRoleIds = rawMember instanceof discord_js.GuildMember ? [...rawMember.roles.cache.keys()].filter((id) => id !== interaction.guildId) : rawMember?.roles ?? [];
2589
+ return {
2590
+ kind: "interaction",
2591
+ interaction,
2592
+ core,
2593
+ user: interaction.user,
2594
+ guild: interaction.guild,
2595
+ member: rawMember instanceof discord_js.GuildMember ? rawMember : null,
2596
+ userId: interaction.user.id,
2597
+ guildId: interaction.guildId,
2598
+ channelId: interaction.channelId,
2599
+ memberRoleIds,
2600
+ memberPermissions: interaction.memberPermissions?.bitfield ?? null,
2601
+ routeId: null
2602
+ };
2603
+ }
2604
+ function eventGateContext(eventName, args, core) {
2605
+ const actor = deriveEventActor(args);
2606
+ return {
2607
+ kind: "event",
2608
+ core,
2609
+ eventName,
2610
+ payload: args,
2611
+ user: actor.user,
2612
+ guild: actor.guild,
2613
+ member: actor.member,
2614
+ userId: actor.user?.id ?? null,
2615
+ guildId: actor.guild?.id ?? null,
2616
+ channelId: actor.channelId,
2617
+ memberRoleIds: actor.member ? [...actor.member.roles.cache.keys()].filter((id) => id !== actor.guild?.id) : [],
2618
+ memberPermissions: actor.member?.permissions.bitfield ?? null,
2619
+ routeId: null
2620
+ };
2621
+ }
2622
+
2623
+ //#endregion
2624
+ //#region src/miscellaneous/FaultThrottle.ts
2625
+ /**
2626
+ * Drops duplicate fault reports inside a fixed window so a recurring fault (a database outage on a
2627
+ * hot path) reports once per window instead of flooding the webhook. Keyed on a structural string, so
2628
+ * the map stays small, and a stale entry is evicted on the next read of its key.
2629
+ *
2630
+ * @internal
2631
+ */
2632
+ var FaultThrottle = class {
2633
+ windowMs;
2634
+ now;
2635
+ lastReportedAt = /* @__PURE__ */ new Map();
2636
+ constructor(windowMs = 6e4, now = () => Date.now()) {
2637
+ this.windowMs = windowMs;
2638
+ this.now = now;
2639
+ }
2640
+ /** Evicts the entry for this key if it has aged out, so the map never holds stale keys forever. */
2641
+ shouldReport(key) {
2642
+ const last = this.lastReportedAt.get(key);
2643
+ if (last === void 0) return true;
2644
+ if (this.now() - last < this.windowMs) return false;
2645
+ this.lastReportedAt.delete(key);
2646
+ return true;
2647
+ }
2648
+ markReported(key) {
2649
+ this.lastReportedAt.set(key, this.now());
2650
+ }
2651
+ clear() {
2652
+ this.lastReportedAt.clear();
2653
+ }
2654
+ };
2655
+
2656
+ //#endregion
2657
+ //#region src/miscellaneous/extractErrorResponse.ts
2658
+ const logger$2 = new _seedcord_services.Logger("ErrorsHandling");
2659
+ /**
2660
+ * The single throttle for every fault publish, so a recurring fault reports once per window across both
2661
+ * the interaction and event paths. Exported so tests reset it between cases.
2662
+ *
2663
+ * @internal
2664
+ */
2665
+ const faultThrottle = new FaultThrottle();
2666
+ /**
2667
+ * Processes an error into a user-facing reply and routes its report.
2668
+ *
2669
+ * A {@link Notice} always renders its own reply. A reporting denial (`report: true`) additionally
2670
+ * publishes `handledException` on the interaction path. A raw, non-denial throw publishes
2671
+ * `unknownException` and renders the configured `defaultError` (or a generic {@link Fault}). One uuid is
2672
+ * threaded into both the reply and the bus payload.
2673
+ *
2674
+ * @internal
2675
+ */
2676
+ function extractErrorResponse(error, core, origin) {
2677
+ const uuid = node_crypto.randomUUID();
2678
+ const developerUsername = core.config.notifications?.developerUsername;
2679
+ const ctx = developerUsername === void 0 ? { uuid } : {
2680
+ uuid,
2681
+ developerUsername
2682
+ };
2683
+ if (error instanceof _seedcord_core.Notice) {
2684
+ if (error.report) reportFault(error, core, origin, uuid);
2685
+ return {
2686
+ uuid,
2687
+ response: error.render(ctx)
2688
+ };
2689
+ }
2690
+ reportRawFault(error, core, origin, uuid);
2691
+ const override = core.config.errors?.defaultError;
2692
+ return {
2693
+ uuid,
2694
+ response: override ? new override(uuid).render(ctx) : new _seedcord_core.Fault().render(ctx)
2695
+ };
2696
+ }
2697
+ function withThrottle(origin, error, publish) {
2698
+ const key = faultKey(origin, error);
2699
+ if (!faultThrottle.shouldReport(key)) {
2700
+ logger$2.info(`throttled duplicate fault ${key}`);
2701
+ return;
2702
+ }
2703
+ publish();
2704
+ faultThrottle.markReported(key);
2705
+ }
2706
+ function reportFault(denial, core, origin, uuid) {
2707
+ withThrottle(origin, denial, () => {
2708
+ logger$2.error(`${denial.name}: ${uuid}`, denial);
2709
+ if (origin.interaction) core.bus.publish("handledException", {
2710
+ denial,
2711
+ uuid,
2712
+ source: buildInteractionSource(origin.interaction)
2713
+ });
2714
+ else if (origin.event) core.bus.publish("handledException", {
2715
+ denial,
2716
+ uuid,
2717
+ source: buildEventSource(origin.event, origin)
2718
+ });
2719
+ else core.bus.publish("unknownException", {
2720
+ uuid,
2721
+ error: denial,
2722
+ guild: origin.guild,
2723
+ user: origin.user,
2724
+ metadata: metadataFor(origin)
2725
+ });
2726
+ });
2727
+ }
2728
+ function reportRawFault(error, core, origin, uuid) {
2729
+ withThrottle(origin, error, () => {
2730
+ if (core.config.errors?.errorStack ?? false) logger$2.error(uuid, error);
2731
+ else logger$2.error(`${uuid} | ${error.message}`);
2732
+ core.bus.publish("unknownException", {
2733
+ uuid,
2734
+ error,
2735
+ guild: origin.guild,
2736
+ user: origin.user,
2737
+ metadata: metadataFor(origin)
2738
+ });
2739
+ });
2740
+ }
2741
+ function metadataFor(origin) {
2742
+ if (origin.event) return {
2743
+ eventName: origin.event.name,
2744
+ handler: origin.event.handler,
2745
+ args: origin.event.args
2746
+ };
2747
+ return origin.metadata;
2748
+ }
2749
+ function buildEventSource(event, origin) {
2750
+ return {
2751
+ kind: "event",
2752
+ eventName: event.name,
2753
+ handler: event.handler,
2754
+ userId: origin.user?.id ?? null,
2755
+ guildId: origin.guild?.id ?? null,
2756
+ channelId: event.channelId,
2757
+ raw: event.args
2758
+ };
2759
+ }
2760
+ function faultKey(origin, error) {
2761
+ const name = error instanceof _seedcord_core.Notice ? error.name : error instanceof discord_js.DiscordAPIError ? String(error.code) : error.constructor.name;
2762
+ if (origin.event) return `${origin.event.name}:${origin.event.handler}:${name}`;
2763
+ if (origin.interaction) return `${interactionRoute(origin.interaction)}:${name}`;
2764
+ if (origin.route) return `autocomplete:${origin.route}:${name}`;
2765
+ return `autocomplete:${name}`;
2766
+ }
2767
+ function interactionRoute(interaction) {
2768
+ if (interaction.isChatInputCommand()) return slashRouteOf(interaction);
2769
+ if (interaction.isContextMenuCommand()) return interaction.commandName;
2770
+ if (interaction.isButton() || interaction.isAnySelectMenu() || interaction.isModalSubmit()) return (0, _seedcord_core_internal.prefixOf)(interaction.customId) || interaction.customId;
2771
+ return "interaction";
2772
+ }
2773
+ function buildInteractionSource(interaction) {
2774
+ const command = interaction.isChatInputCommand() ? slashRouteOf(interaction) : interaction.isContextMenuCommand() ? interaction.commandName : null;
2775
+ const customId = interaction.isButton() || interaction.isAnySelectMenu() || interaction.isModalSubmit() ? interaction.customId : null;
2776
+ return {
2777
+ kind: "interaction",
2778
+ interactionKind: interactionKind(interaction),
2779
+ command,
2780
+ customId,
2781
+ userId: interaction.user.id,
2782
+ guildId: interaction.guildId,
2783
+ channelId: interaction.channelId,
2784
+ interactionId: interaction.id,
2785
+ raw: interaction
2786
+ };
2787
+ }
2788
+ function interactionKind(interaction) {
2789
+ if (interaction.isChatInputCommand()) return "slash";
2790
+ if (interaction.isContextMenuCommand()) return "context-menu";
2791
+ if (interaction.isButton()) return "button";
2792
+ if (interaction.isAnySelectMenu()) return "select";
2793
+ return "modal";
2794
+ }
2795
+
2796
+ //#endregion
2797
+ //#region src/bot/handleEventFault.ts
2798
+ const logger$1 = new _seedcord_services.Logger("EventBoundary");
2799
+ /**
2800
+ * The event controller boundary. Reports a throw from an event handler and never replies, since a
2801
+ * generic event has no reply target. A {@link Silence} or a non-reporting {@link Notice} stops quietly, a
2802
+ * reporting denial or a raw error publishes a fault with a best-effort actor derived from the args.
2803
+ *
2804
+ * @internal
2805
+ */
2806
+ function handleEventFault(caught, eventName, handlerName, args, core) {
2807
+ if (caught instanceof _seedcord_core.Silence) {
2808
+ if (caught.reason !== void 0) logger$1.debug(`Silence: ${caught.reason}`);
2809
+ return;
2810
+ }
2811
+ if (!Error.isError(caught)) throw caught;
2812
+ const ignore = new Set(core.config.errors?.ignoreEventApiCodes ?? []);
2813
+ if (caught instanceof discord_js.DiscordAPIError && ignore.has(caught.code)) {
2814
+ logger$1.debug(`swallowed api code ${caught.code}`);
2815
+ return;
2816
+ }
2817
+ if (caught instanceof _seedcord_core.Notice && !caught.report) return;
2818
+ const actor = deriveEventActor(args);
2819
+ extractErrorResponse(caught, core, {
2820
+ event: {
2821
+ name: eventName,
2822
+ handler: handlerName,
2823
+ args,
2824
+ channelId: actor.channelId
2825
+ },
2826
+ guild: actor.guild,
2827
+ user: actor.user
2828
+ });
2829
+ }
2830
+
2831
+ //#endregion
2832
+ //#region src/bot/controllers/EventDispatcher.ts
2833
+ /**
2834
+ * Scans event handler directories, registers handlers with Discord client events,
2835
+ * and coordinates event execution through the handler system. Does not handle interactions.
2836
+ * Multiple handlers can point to one event.
2837
+ *
2838
+ * @internal
2839
+ */
2840
+ var EventDispatcher = class {
2841
+ core;
2842
+ logger = new _seedcord_services.Logger("Events");
2843
+ isInitialized = false;
2844
+ name = "Events";
2845
+ eventMap = /* @__PURE__ */ new Map();
2846
+ middlewares = [];
2847
+ executedOnceHandlers = /* @__PURE__ */ new Set();
2848
+ attachedEvents = /* @__PURE__ */ new Set();
2849
+ hmrHandler;
2850
+ constructor(core) {
2851
+ this.core = core;
2852
+ const eventsDir = this.core.config.bot.events.path;
2853
+ if (!eventsDir) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CoreControllerPathMissing, ["EventDispatcher", "events"]);
2854
+ if (!envapt.Envapter.isDevelopment && !envapt.Envapter.isTest) return;
2855
+ this.hmrHandler = new HmrModuleHandler({
2856
+ handlersDir: eventsDir,
2857
+ ...(0, _seedcord_utils.hasKeys)(this.core.config.bot.events, ["middlewares"]) && { middlewaresDir: this.core.config.bot.events.middlewares },
2858
+ isHandler: this.isEventHandlerClass.bind(this),
2859
+ isMiddleware: this.isMiddlewareClass.bind(this),
2860
+ registerHandler: this.registerHandler.bind(this),
2861
+ registerMiddleware: this.registerMiddleware.bind(this),
2862
+ unregisterHandler: this.unregisterHandler.bind(this),
2863
+ unregisterMiddleware: this.unregisterMiddleware.bind(this),
2864
+ getArtifacts: this.getArtifacts.bind(this),
2865
+ logger: this.logger
2866
+ });
2867
+ }
2868
+ getArtifacts(ctor) {
2869
+ const events = [];
2870
+ for (const [event, handlers] of this.eventMap.entries()) if (handlers.some((h) => h.ctor === ctor)) events.push(event);
2871
+ return events;
2872
+ }
2873
+ async init() {
2874
+ if (this.isInitialized) return;
2875
+ this.isInitialized = true;
2876
+ const handlersDir = this.core.config.bot.events.path;
2877
+ if (!handlersDir) return;
2878
+ this.logger.info(chalk.default.bold(handlersDir));
2879
+ const middlewareDir = (0, _seedcord_utils.hasKeys)(this.core.config.bot.events, ["middlewares"]) ? this.core.config.bot.events.middlewares : void 0;
2880
+ if (middlewareDir) {
2881
+ this.logger.info(`${chalk.default.bold(middlewareDir)} ${chalk.default.gray("(middlewares)")}`);
2882
+ await this.loadMiddlewares(middlewareDir);
2883
+ }
2884
+ await this.loadHandlers(handlersDir);
2885
+ this.attachToClient();
2886
+ this.logger.info(`${chalk.default.bold.green("Loaded event handlers:")}`);
2887
+ const eventList = [`${chalk.default.magenta.bold(this.middlewares.length)} middlewares`];
2888
+ this.eventMap.forEach((handlers, eventName) => {
2889
+ eventList.push(`${chalk.default.magenta.bold(handlers.length)} ${eventName}`);
2890
+ });
2891
+ this.logger.utils.list(eventList);
2892
+ }
2893
+ async loadHandlers(dir) {
2894
+ await (0, _seedcord_utils.traverseDirectory)(dir, (fullPath, relativePath, imported) => {
2895
+ for (const val of Object.values(imported)) {
2896
+ if (!this.isEventHandlerClass(val)) continue;
2897
+ this.registerHandler(val, relativePath);
2898
+ this.hmrHandler?.trackHandler(fullPath, val);
2899
+ }
2900
+ }, this.logger);
2901
+ }
2902
+ async loadMiddlewares(dir) {
2903
+ await (0, _seedcord_utils.traverseDirectory)(dir, (fullPath, relativePath, imported) => {
2904
+ for (const val of Object.values(imported)) {
2905
+ if (!this.isMiddlewareClass(val)) continue;
2906
+ this.registerMiddleware(val, relativePath);
2907
+ this.hmrHandler?.trackMiddleware(fullPath, val);
2908
+ }
2909
+ }, this.logger);
2910
+ }
2911
+ /** @internal For use in dev mode */
2912
+ async onHmr(event) {
2913
+ await this.hmrHandler?.handle(event);
2914
+ }
2915
+ unregisterHandler(handlerClass, artifacts) {
2916
+ const events = artifacts ?? [...this.eventMap.keys()];
2917
+ for (const event of events) {
2918
+ const handlers = this.eventMap.get(event);
2919
+ if (!handlers) continue;
2920
+ const index = handlers.findIndex((h) => h.ctor === handlerClass);
2921
+ if (index !== -1) {
2922
+ handlers.splice(index, 1);
2923
+ if (handlers.length === 0) this.eventMap.delete(event);
2924
+ }
2925
+ }
2926
+ }
2927
+ unregisterMiddleware(middlewareCtor) {
2928
+ const index = this.middlewares.findIndex((entry) => entry.ctor === middlewareCtor);
2929
+ if (index !== -1) this.middlewares.splice(index, 1);
2930
+ }
2931
+ registerMiddleware(middlewareCtor, relativePath) {
2932
+ const metadata = Reflect.getMetadata(_seedcord_core_internal.MiddlewareMetadataKey, middlewareCtor);
2933
+ if (metadata?.type !== "event") return;
2934
+ if (this.middlewares.some((entry) => entry.ctor === middlewareCtor)) return;
2935
+ this.middlewares.push({
2936
+ ctor: middlewareCtor,
2937
+ priority: metadata.priority,
2938
+ ...metadata.events && { events: metadata.events }
2939
+ });
2940
+ this.middlewares.sort((a, b) => a.priority - b.priority);
2941
+ this.logger.utils.registration(`${middlewareCtor.name} ${chalk.default.gray(`(${metadata.priority})`)}`, relativePath, "event middleware");
2942
+ }
2943
+ async runMiddlewares(eventName, args) {
2944
+ for (const { ctor, events } of this.middlewares) {
2945
+ if (events && !events.includes(eventName)) continue;
2946
+ try {
2947
+ await new ctor(args, this.core, eventName).execute();
2948
+ } catch (caught) {
2949
+ handleEventFault(caught, String(eventName), ctor.name, args, this.core);
2950
+ return false;
2951
+ }
2952
+ }
2953
+ return true;
2954
+ }
2955
+ isEventHandlerClass(obj) {
2956
+ if (typeof obj !== "function") return false;
2957
+ return obj.prototype instanceof EventHandler && Reflect.hasMetadata(_seedcord_core_internal.EventMetadataKey, obj);
2958
+ }
2959
+ isMiddlewareClass(obj) {
2960
+ if (typeof obj !== "function") return false;
2961
+ return obj.prototype instanceof EventMiddleware && Reflect.hasMetadata(_seedcord_core_internal.MiddlewareMetadataKey, obj);
2962
+ }
2963
+ registerHandler(handlerClass, relativePath) {
2964
+ const raw = Reflect.getMetadata(_seedcord_core_internal.EventMetadataKey, handlerClass);
2965
+ const register = (key, frequency) => {
2966
+ let handlers = this.eventMap.get(key);
2967
+ if (!handlers) {
2968
+ handlers = [];
2969
+ this.eventMap.set(key, handlers);
2970
+ }
2971
+ handlers.push({
2972
+ ctor: handlerClass,
2973
+ frequency
2974
+ });
2975
+ if (this.isInitialized && !this.attachedEvents.has(key)) this.attachListener(key);
2976
+ };
2977
+ if (Array.isArray(raw)) for (const entry of raw) register(entry.event, entry.frequency);
2978
+ else {
2979
+ const names = areRoutes(raw) ? raw : typeof raw === "string" ? [raw] : [];
2980
+ for (const name of names) register(name, "on");
2981
+ }
2982
+ this.logger.utils.registration(handlerClass.name, relativePath);
2983
+ }
2984
+ attachToClient() {
2985
+ for (const [eventName] of this.eventMap) this.attachListener(eventName);
2986
+ }
2987
+ attachListener(eventName) {
2988
+ if (this.attachedEvents.has(eventName)) return;
2989
+ this.attachedEvents.add(eventName);
2990
+ const handlerEntries = this.eventMap.get(eventName);
2991
+ this.logger.debug(`Attaching ${chalk.default.bold.green(eventName)} to the client with ${chalk.default.gray(handlerEntries?.length ?? 0)} handler(s)`);
2992
+ this.core.bot.client.on(eventName, (...args) => {
2993
+ this.core.bot.emitSafe("any:event", eventName, ...args);
2994
+ (async () => {
2995
+ await this.processEvent(eventName, args).catch((err) => {
2996
+ this.logger.error(`[${chalk.default.bold.red("UNHANDLED ERROR AT ROOT")}] ${err.name}`, err.stack);
2997
+ this.core.bot.emit("error:unhandled:event", err);
2998
+ });
2999
+ })();
3000
+ });
3001
+ }
3002
+ async processEvent(eventName, args) {
3003
+ const handlerEntries = this.eventMap.get(eventName);
3004
+ if (!handlerEntries || handlerEntries.length === 0) return;
3005
+ const handlersToExecute = handlerEntries.filter((entry) => entry.frequency !== "once" || !this.executedOnceHandlers.has(entry.ctor));
3006
+ if (handlersToExecute.length === 0) return;
3007
+ if (!await this.runMiddlewares(eventName, args)) return;
3008
+ for (const entry of handlersToExecute) {
3009
+ if (entry.frequency === "once") {
3010
+ if (this.executedOnceHandlers.has(entry.ctor)) continue;
3011
+ this.executedOnceHandlers.add(entry.ctor);
3012
+ }
3013
+ await this.processHandler(eventName, entry.ctor, args);
3014
+ }
3015
+ }
3016
+ async processHandler(eventName, ctor, args) {
3017
+ try {
3018
+ this.logger.debug(`Processing ${chalk.default.bold.green(eventName)} with ${chalk.default.gray(ctor.name)}`);
3019
+ const handler = new ctor(args, this.core, eventName);
3020
+ await (0, _seedcord_core_internal.runHandlerGates)(ctor, eventGateContext(eventName, args, this.core));
3021
+ await handler.execute();
3022
+ } catch (caught) {
3023
+ handleEventFault(caught, String(eventName), ctor.name, args, this.core);
3024
+ }
3025
+ }
3026
+ };
3027
+
3028
+ //#endregion
3029
+ //#region src/bot/defaults/UnhandledEvent.ts
3030
+ /**
3031
+ * Default handler for unhandled interactions. A reply failure here rides the controller boundary as a
3032
+ * raw fault, so it needs no decorator of its own.
3033
+ *
3034
+ * @internal
3035
+ */
3036
+ var UnhandledEvent = class extends InteractionHandler {
3037
+ async execute() {
3038
+ await this.event.reply({
3039
+ content: `Feature not implemented yet.`,
3040
+ flags: discord_js.MessageFlags.Ephemeral
3041
+ });
3042
+ }
3043
+ };
3044
+
3045
+ //#endregion
3046
+ //#region src/bot/handleInteractionFault.ts
3047
+ const logger = new _seedcord_services.Logger("InteractionBoundary");
3048
+ /**
3049
+ * The interaction controller boundary. Sorts a throw from any handler-lifecycle phase into the right
3050
+ * user reply plus the right bus event, building a {@link ReplySender} lazily so it reads the live
3051
+ * acknowledgement state at catch time.
3052
+ *
3053
+ * @internal
3054
+ */
3055
+ async function handleInteractionFault(caught, interaction, core) {
3056
+ if (caught instanceof _seedcord_core.Silence) {
3057
+ if (caught.reason !== void 0) logger.debug(`Silence: ${caught.reason}`);
3058
+ return;
3059
+ }
3060
+ if (!Error.isError(caught)) throw caught;
3061
+ const ignore = new Set(core.config.errors?.ignoreApiCodes ?? []);
3062
+ if (caught instanceof discord_js.DiscordAPIError && ignore.has(caught.code)) {
3063
+ logger.debug(`swallowed api code ${caught.code}`);
3064
+ return;
3065
+ }
3066
+ if (interaction.isAutocomplete()) {
3067
+ extractErrorResponse(caught, core, {
3068
+ guild: interaction.guild,
3069
+ user: interaction.user,
3070
+ metadata: interaction,
3071
+ route: slashRouteOf(interaction)
3072
+ });
3073
+ return;
3074
+ }
3075
+ const { response } = extractErrorResponse(caught, core, {
3076
+ interaction,
3077
+ guild: interaction.guild,
3078
+ user: interaction.user,
3079
+ metadata: interaction
3080
+ });
3081
+ await new ReplySender(interaction).send(response, caught instanceof _seedcord_core.Notice ? caught.ephemeral : true);
3082
+ }
3083
+
3084
+ //#endregion
3085
+ //#region src/bot/controllers/InteractionDispatcher.ts
3086
+ /**
3087
+ * Scans handler directories, routes each interaction to its registered handler, and runs the handler.
3088
+ * One handler per interaction.
3089
+ *
3090
+ * @internal
3091
+ */
3092
+ var InteractionDispatcher = class {
3093
+ core;
3094
+ logger = new _seedcord_services.Logger("Interactions");
3095
+ isInitialized = false;
3096
+ name = "Interactions";
3097
+ slashMap = /* @__PURE__ */ new Map();
3098
+ buttonMap = /* @__PURE__ */ new Map();
3099
+ modalMap = /* @__PURE__ */ new Map();
3100
+ stringSelectMap = /* @__PURE__ */ new Map();
3101
+ userSelectMap = /* @__PURE__ */ new Map();
3102
+ roleSelectMap = /* @__PURE__ */ new Map();
3103
+ channelSelectMap = /* @__PURE__ */ new Map();
3104
+ mentionableSelectMap = /* @__PURE__ */ new Map();
3105
+ messageContextMenuMap = /* @__PURE__ */ new Map();
3106
+ userContextMenuMap = /* @__PURE__ */ new Map();
3107
+ autocompleteMap = /* @__PURE__ */ new Map();
3108
+ keysToIgnore = /* @__PURE__ */ new Set();
3109
+ middlewares = [];
3110
+ hmrHandler;
3111
+ routeTypes = [
3112
+ [_seedcord_core_internal.InteractionRoutes.Slash, this.slashMap],
3113
+ [_seedcord_core_internal.InteractionRoutes.Button, this.buttonMap],
3114
+ [_seedcord_core_internal.InteractionRoutes.Modal, this.modalMap],
3115
+ [_seedcord_core_internal.InteractionRoutes.StringMenu, this.stringSelectMap],
3116
+ [_seedcord_core_internal.InteractionRoutes.UserMenu, this.userSelectMap],
3117
+ [_seedcord_core_internal.InteractionRoutes.RoleMenu, this.roleSelectMap],
3118
+ [_seedcord_core_internal.InteractionRoutes.ChannelMenu, this.channelSelectMap],
3119
+ [_seedcord_core_internal.InteractionRoutes.MentionableMenu, this.mentionableSelectMap],
3120
+ [_seedcord_core_internal.InteractionRoutes.MessageContextMenu, this.messageContextMenuMap],
3121
+ [_seedcord_core_internal.InteractionRoutes.UserContextMenu, this.userContextMenuMap],
3122
+ [_seedcord_core_internal.InteractionRoutes.Autocomplete, this.autocompleteMap]
3123
+ ];
3124
+ constructor(core) {
3125
+ this.core = core;
3126
+ const ignoredKeysFromConfig = (0, _seedcord_utils.hasKeys)(this.core.config.bot.interactions, ["ignoreCustomIds"]) ? this.core.config.bot.interactions.ignoreCustomIds : void 0;
3127
+ if (ignoredKeysFromConfig) for (const ignoredKey of ignoredKeysFromConfig) this.keysToIgnore.add(ignoredKey);
3128
+ this.keysToIgnore.add(CONFIRM_DEF);
3129
+ const interactionsDir = this.core.config.bot.interactions.path;
3130
+ if (!interactionsDir) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CoreControllerPathMissing, ["InteractionDispatcher", "interactions"]);
3131
+ if (!envapt.Envapter.isDevelopment && !envapt.Envapter.isTest) return;
3132
+ this.hmrHandler = new HmrModuleHandler({
3133
+ handlersDir: interactionsDir,
3134
+ ...(0, _seedcord_utils.hasKeys)(this.core.config.bot.interactions, ["middlewares"]) && this.core.config.bot.interactions.middlewares && { middlewaresDir: this.core.config.bot.interactions.middlewares },
3135
+ isHandler: this.isHandlerClass.bind(this),
3136
+ isMiddleware: this.isMiddlewareClass.bind(this),
3137
+ registerHandler: this.registerHandler.bind(this),
3138
+ registerMiddleware: this.registerMiddleware.bind(this),
3139
+ unregisterHandler: this.unregisterHandler.bind(this),
3140
+ unregisterMiddleware: this.unregisterMiddleware.bind(this),
3141
+ getArtifacts: this.getArtifacts.bind(this),
3142
+ logger: this.logger
3143
+ });
3144
+ }
3145
+ /**
3146
+ * Warns for each command route with no registered `@SlashRoute` handler, which would fall through to
3147
+ * UnhandledEvent at runtime. A bot may route commands outside the registry, so this does not throw.
3148
+ *
3149
+ * @internal
3150
+ */
3151
+ warnUnhandledRoutes(commandLeaves) {
3152
+ for (const route of commandLeaves) if (!this.slashMap.has(route)) this.logger.warn(`Slash route ${chalk.default.bold.cyan(route)} has no registered ${chalk.default.bold("@SlashRoute")} handler.`);
3153
+ }
3154
+ /**
3155
+ * Warns for each context-menu command with no matching handler, which would fall through to UnhandledEvent
3156
+ * at runtime. Checked per kind since a user and a message command can share a name.
3157
+ *
3158
+ * @internal
3159
+ */
3160
+ warnUnhandledContextMenuRoutes(leaves) {
3161
+ for (const name of leaves.user) if (!this.userContextMenuMap.has(name)) this.logger.warn(`User context menu ${chalk.default.bold.cyan(name)} has no registered ${chalk.default.bold("@ContextMenuRoute")} handler.`);
3162
+ for (const name of leaves.message) if (!this.messageContextMenuMap.has(name)) this.logger.warn(`Message context menu ${chalk.default.bold.cyan(name)} has no registered ${chalk.default.bold("@ContextMenuRoute")} handler.`);
3163
+ }
3164
+ getArtifacts(handlerClass) {
3165
+ const artifacts = [];
3166
+ for (const [routeType] of this.routeTypes) {
3167
+ const meta = Reflect.getMetadata(_seedcord_core_internal.InteractionRouteKeys[routeType], handlerClass);
3168
+ if (areRoutes(meta)) artifacts.push({
3169
+ routeType,
3170
+ routes: meta
3171
+ });
3172
+ }
3173
+ return artifacts;
3174
+ }
3175
+ async init() {
3176
+ if (this.isInitialized) return;
3177
+ this.isInitialized = true;
3178
+ const handlersDir = this.core.config.bot.interactions.path;
3179
+ if (!handlersDir) return;
3180
+ this.logger.info(chalk.default.bold(handlersDir));
3181
+ const middlewareDir = (0, _seedcord_utils.hasKeys)(this.core.config.bot.interactions, ["middlewares"]) ? this.core.config.bot.interactions.middlewares : void 0;
3182
+ if (middlewareDir) {
3183
+ this.logger.info(`${chalk.default.bold(middlewareDir)} ${chalk.default.gray("(middlewares)")}`);
3184
+ await this.loadMiddlewares(middlewareDir);
3185
+ }
3186
+ await this.loadHandlers(handlersDir);
3187
+ this.attachToClient();
3188
+ this.logger.info(`${chalk.default.bold.green("Loaded interaction handlers:")}`);
3189
+ this.logger.utils.list([
3190
+ `${chalk.default.magenta.bold(this.middlewares.length)} middlewares`,
3191
+ `${chalk.default.magenta.bold(this.slashMap.size)} slash commands`,
3192
+ `${chalk.default.magenta.bold(this.buttonMap.size)} buttons`,
3193
+ `${chalk.default.magenta.bold(this.modalMap.size)} modals`,
3194
+ `${chalk.default.magenta.bold(this.stringSelectMap.size)} string selects`,
3195
+ `${chalk.default.magenta.bold(this.userSelectMap.size)} user selects`,
3196
+ `${chalk.default.magenta.bold(this.roleSelectMap.size)} role selects`,
3197
+ `${chalk.default.magenta.bold(this.channelSelectMap.size)} channel selects`,
3198
+ `${chalk.default.magenta.bold(this.mentionableSelectMap.size)} mentionable selects`,
3199
+ `${chalk.default.magenta.bold(this.messageContextMenuMap.size)} message context menus`,
3200
+ `${chalk.default.magenta.bold(this.userContextMenuMap.size)} user context menus`,
3201
+ `${chalk.default.magenta.bold(this.autocompleteMap.size)} autocomplete`
3202
+ ]);
3203
+ }
3204
+ async loadHandlers(dir) {
3205
+ await (0, _seedcord_utils.traverseDirectory)(dir, (fullPath, relativePath, imported) => {
3206
+ for (const val of Object.values(imported)) {
3207
+ if (!this.isHandlerClass(val)) continue;
3208
+ this.registerHandler(val, relativePath);
3209
+ this.hmrHandler?.trackHandler(fullPath, val);
3210
+ }
3211
+ }, this.logger);
3212
+ }
3213
+ async loadMiddlewares(dir) {
3214
+ await (0, _seedcord_utils.traverseDirectory)(dir, (fullPath, relativePath, imported) => {
3215
+ for (const val of Object.values(imported)) {
3216
+ if (!this.isMiddlewareClass(val)) continue;
3217
+ this.registerMiddleware(val, relativePath);
3218
+ this.hmrHandler?.trackMiddleware(fullPath, val);
3219
+ }
3220
+ }, this.logger);
3221
+ }
3222
+ registerMiddleware(middlewareCtor, relativePath) {
3223
+ const metadata = Reflect.getMetadata(_seedcord_core_internal.MiddlewareMetadataKey, middlewareCtor);
3224
+ if (metadata?.type !== "interaction") return;
3225
+ if (this.middlewares.some((entry) => entry.ctor === middlewareCtor)) return;
3226
+ if (this.middlewares.some((entry) => entry.ctor.name === middlewareCtor.name)) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.InteractionDuplicateMiddleware, [middlewareCtor.name]);
3227
+ this.middlewares.push({
3228
+ ctor: middlewareCtor,
3229
+ priority: metadata.priority
3230
+ });
3231
+ this.middlewares.sort((a, b) => a.priority - b.priority);
3232
+ this.logger.utils.registration(`${middlewareCtor.name} ${chalk.default.gray(`(${metadata.priority})`)}`, relativePath, "middleware");
3233
+ }
3234
+ isHandlerClass(obj) {
3235
+ if (typeof obj !== "function") return false;
3236
+ return obj.prototype instanceof InteractionHandler && Reflect.hasMetadata(_seedcord_core_internal.InteractionMetadataKey, obj) || obj.prototype instanceof AutocompleteHandler && Reflect.hasMetadata(_seedcord_core_internal.InteractionMetadataKey, obj);
3237
+ }
3238
+ isMiddlewareClass(obj) {
3239
+ if (typeof obj !== "function") return false;
3240
+ return obj.prototype instanceof InteractionMiddleware && Reflect.hasMetadata(_seedcord_core_internal.MiddlewareMetadataKey, obj);
3241
+ }
3242
+ registerHandler(handlerClass, relativePath) {
3243
+ const writes = [];
3244
+ for (const [routeType, map] of this.routeTypes) {
3245
+ const meta = Reflect.getMetadata(_seedcord_core_internal.InteractionRouteKeys[routeType], handlerClass);
3246
+ if (!areRoutes(meta)) continue;
3247
+ for (const route of meta) {
3248
+ const existing = map.get(route);
3249
+ if (existing && existing !== handlerClass) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.InteractionDuplicateRoute, [
3250
+ route,
3251
+ existing.name,
3252
+ handlerClass.name
3253
+ ]);
3254
+ writes.push([map, route]);
3255
+ }
3256
+ this.logger.utils.registration(handlerClass.name, (0, _seedcord_utils.formatFilePath)(relativePath));
3257
+ }
3258
+ for (const [map, route] of writes) map.set(route, handlerClass);
3259
+ }
3260
+ /** @internal For use in dev mode */
3261
+ async onHmr(event) {
3262
+ await this.hmrHandler?.handle(event);
3263
+ }
3264
+ unregisterHandler(handlerClass, artifacts) {
3265
+ if (artifacts) {
3266
+ for (const { routeType, routes } of artifacts) {
3267
+ const map = this.routeTypes.find(([type]) => type === routeType)?.[1];
3268
+ if (map) routes.forEach((route) => map.delete(route));
3269
+ }
3270
+ return;
3271
+ }
3272
+ for (const [routeType, map] of this.routeTypes) {
3273
+ const meta = Reflect.getMetadata(_seedcord_core_internal.InteractionRouteKeys[routeType], handlerClass);
3274
+ if (!areRoutes(meta)) continue;
3275
+ meta.forEach((route) => map.delete(route));
3276
+ }
3277
+ }
3278
+ unregisterMiddleware(middlewareCtor) {
3279
+ const index = this.middlewares.findIndex((entry) => entry.ctor === middlewareCtor);
3280
+ if (index !== -1) this.middlewares.splice(index, 1);
3281
+ }
3282
+ attachToClient() {
3283
+ this.core.bot.client.on(discord_js.Events.InteractionCreate, (interaction) => {
3284
+ this.core.bot.emitSafe("any:interaction", interaction);
3285
+ this.handleInteraction(interaction).catch((err) => {
3286
+ this.logger.error(`[${chalk.default.bold.red("UNHANDLED ERROR AT ROOT")}] ${err.name}`, err.stack);
3287
+ this.core.bot.emit("error:unhandled:interaction", err);
3288
+ });
3289
+ });
3290
+ }
3291
+ async handleCustomIdInteraction(interaction, getMap, interactionType) {
3292
+ if ([...this.keysToIgnore].some((matcher) => matcher.owns(interaction.customId))) return;
3293
+ const prefix = (0, _seedcord_core_internal.prefixOf)(interaction.customId);
3294
+ if (!prefix) return this.logger.warn(`${interactionType} has invalid customId: ${interaction.customId}`);
3295
+ await this.processInteraction(interaction, () => prefix, (key) => getMap().get(key));
3296
+ }
3297
+ async processInteraction(interaction, extractKey, getHandler) {
3298
+ const key = extractKey(interaction);
3299
+ try {
3300
+ if (!interaction.isAutocomplete()) for (const { ctor } of this.middlewares) await new ctor(interaction, this.core).execute();
3301
+ let HandlerCtor = getHandler(key);
3302
+ if (!HandlerCtor) {
3303
+ this.logger.warn(`No handler found for key ${chalk.default.bold.cyan(key)}. Falling back to UnhandledEvent.`);
3304
+ HandlerCtor = UnhandledEvent;
3305
+ }
3306
+ this.logger.debug(`Processing ${chalk.default.bold.green(key)} with ${chalk.default.gray(HandlerCtor.name)}`);
3307
+ const dispatch = new _seedcord_core.DispatchContext((0, _seedcord_core_internal.routeIdOf)(HandlerCtor));
3308
+ const handler = new HandlerCtor(interaction, this.core, dispatch);
3309
+ if (!interaction.isAutocomplete()) await (0, _seedcord_core_internal.runHandlerGates)(HandlerCtor, interactionGateContext(interaction, this.core));
3310
+ await handler.execute();
3311
+ } catch (caught) {
3312
+ await handleInteractionFault(caught, interaction, this.core);
3313
+ }
3314
+ }
3315
+ async handleInteraction(interaction) {
3316
+ switch (true) {
3317
+ case interaction.isChatInputCommand():
3318
+ await this.handleSlashCommand(interaction);
3319
+ break;
3320
+ case interaction.isButton():
3321
+ await this.handleButton(interaction);
3322
+ break;
3323
+ case interaction.isModalSubmit():
3324
+ await this.handleModal(interaction);
3325
+ break;
3326
+ case interaction.isStringSelectMenu():
3327
+ await this.handleStringSelectMenu(interaction);
3328
+ break;
3329
+ case interaction.isUserSelectMenu():
3330
+ await this.handleUserSelectMenu(interaction);
3331
+ break;
3332
+ case interaction.isRoleSelectMenu():
3333
+ await this.handleRoleSelectMenu(interaction);
3334
+ break;
3335
+ case interaction.isChannelSelectMenu():
3336
+ await this.handleChannelSelectMenu(interaction);
3337
+ break;
3338
+ case interaction.isMentionableSelectMenu():
3339
+ await this.handleMentionableSelectMenu(interaction);
3340
+ break;
3341
+ case interaction.isMessageContextMenuCommand():
3342
+ await this.handleMessageContextMenu(interaction);
3343
+ break;
3344
+ case interaction.isUserContextMenuCommand():
3345
+ await this.handleUserContextMenu(interaction);
3346
+ break;
3347
+ case interaction.isAutocomplete():
3348
+ await this.handleAutocomplete(interaction);
3349
+ break;
3350
+ default:
3351
+ this.logger.warn(`Unhandled interaction type: ${interaction.type}`);
3352
+ break;
3353
+ }
3354
+ }
3355
+ async handleSlashCommand(interaction) {
3356
+ const route = slashRouteOf(interaction);
3357
+ await this.processInteraction(interaction, () => route, (key) => this.slashMap.get(key));
3358
+ }
3359
+ async handleButton(interaction) {
3360
+ await this.handleCustomIdInteraction(interaction, () => this.buttonMap, "Button");
3361
+ }
3362
+ async handleModal(interaction) {
3363
+ await this.handleCustomIdInteraction(interaction, () => this.modalMap, "Modal");
3364
+ }
3365
+ async handleStringSelectMenu(interaction) {
3366
+ await this.handleCustomIdInteraction(interaction, () => this.stringSelectMap, "String select menu");
3367
+ }
3368
+ async handleUserSelectMenu(interaction) {
3369
+ await this.handleCustomIdInteraction(interaction, () => this.userSelectMap, "User select menu");
3370
+ }
3371
+ async handleRoleSelectMenu(interaction) {
3372
+ await this.handleCustomIdInteraction(interaction, () => this.roleSelectMap, "Role select menu");
3373
+ }
3374
+ async handleChannelSelectMenu(interaction) {
3375
+ await this.handleCustomIdInteraction(interaction, () => this.channelSelectMap, "Channel select menu");
3376
+ }
3377
+ async handleMentionableSelectMenu(interaction) {
3378
+ await this.handleCustomIdInteraction(interaction, () => this.mentionableSelectMap, "Mentionable select menu");
3379
+ }
3380
+ async handleMessageContextMenu(interaction) {
3381
+ await this.processInteraction(interaction, () => interaction.commandName, (key) => this.messageContextMenuMap.get(key));
3382
+ }
3383
+ async handleUserContextMenu(interaction) {
3384
+ await this.processInteraction(interaction, () => interaction.commandName, (key) => this.userContextMenuMap.get(key));
3385
+ }
3386
+ async handleAutocomplete(interaction) {
3387
+ const route = slashRouteOf(interaction);
3388
+ if (!this.autocompleteMap.has(route)) {
3389
+ this.logger.warn(`No autocomplete handler for ${chalk.default.bold.cyan(route)}.`);
3390
+ await interaction.respond([]);
3391
+ return;
3392
+ }
3393
+ await this.processInteraction(interaction, () => route, (key) => this.autocompleteMap.get(key));
3394
+ }
3395
+ };
3396
+
3397
+ //#endregion
3398
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorateMetadata.js
3399
+ function __decorateMetadata(k, v) {
3400
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
3401
+ }
3402
+
3403
+ //#endregion
3404
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorate.js
3405
+ function __decorate(decorators, target, key, desc) {
3406
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3407
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
3408
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3409
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3410
+ }
3411
+
3412
+ //#endregion
3413
+ //#region src/bot/Bot.ts
3414
+ /**
3415
+ * Discord bot implementation that manages client and controllers
3416
+ *
3417
+ * Don't instantiate this class directly. Use `core.bot` instead.
3418
+ */
3419
+ var Bot = class extends Plugin {
3420
+ /** @internal */
3421
+ logger = new _seedcord_services.Logger("Bot");
3422
+ isInitialized = false;
3423
+ _client;
3424
+ interactions;
3425
+ events;
3426
+ commands;
3427
+ emojiInjector;
3428
+ emojis = Emojis;
3429
+ mentions = CommandMentions;
3430
+ /** @internal For use in dev mode */
3431
+ async onHmr(event) {
3432
+ if (this.interactions) await this.interactions.onHmr(event);
3433
+ if (this.events) await this.events.onHmr(event);
3434
+ if (this.commands) await this.commands.onHmr(event);
3435
+ }
3436
+ /** @internal */
3437
+ constructor(core) {
3438
+ super(core);
3439
+ this._client = new discord_js.Client(core.config.bot.clientOptions);
3440
+ if (core.config.bot.interactions.path) this.interactions = new InteractionDispatcher(core);
3441
+ if (core.config.bot.events.path) this.events = new EventDispatcher(core);
3442
+ if (core.config.bot.commands.path) {
3443
+ const mentionInjector = new CommandMentionInjector(core);
3444
+ this.commands = new CommandRegistry(core, (result) => {
3445
+ mentionInjector.inject(result);
3446
+ });
3447
+ }
3448
+ this.emojiInjector = new EmojiInjector(core);
3449
+ core.shutdown.addTask(_seedcord_services.ShutdownPhase.DiscordCleanup, "stop-bot", async () => await this.stop(), 2e3);
3450
+ }
3451
+ /**
3452
+ * Initializes Discord client and all controllers
3453
+ * @internal
3454
+ */
3455
+ async init() {
3456
+ if (this.isInitialized) return;
3457
+ this.isInitialized = true;
3458
+ const token = this.botToken;
3459
+ if (this.interactions) await this.interactions.init();
3460
+ if (this.events) await this.events.init();
3461
+ await this.login(token);
3462
+ await this.emojiInjector.init();
3463
+ if (this.commands) {
3464
+ await this.commands.init();
3465
+ await this.commands.setCommands();
3466
+ this.interactions?.warnUnhandledRoutes(this.commands.routeLeaves());
3467
+ this.interactions?.warnUnhandledContextMenuRoutes(this.commands.contextMenuLeaves());
3468
+ }
3469
+ }
3470
+ /**
3471
+ * Stops the bot and cleans up connections
3472
+ * @internal
3473
+ */
3474
+ async stop() {
3475
+ this._client.removeAllListeners();
3476
+ await this.logout();
3477
+ }
3478
+ /**
3479
+ * Logs the bot into Discord using the configured token
3480
+ */
3481
+ async login(token) {
3482
+ await this._client.login(token);
3483
+ this.logger.info(`Logged in as ${chalk.default.bold.magenta(this._client.user?.username)}!`);
3484
+ return this;
3485
+ }
3486
+ /**
3487
+ * Logs out and destroys the Discord client connection
3488
+ */
3489
+ async logout() {
3490
+ await this._client.destroy();
3491
+ this.logger.info(chalk.default.bold.red("Logged out of Discord!"));
3492
+ }
3493
+ get client() {
3494
+ return this._client;
3495
+ }
3496
+ emit(event, ...args) {
3497
+ return super.emit(event, ...args);
3498
+ }
3499
+ emitSafe(event, ...args) {
3500
+ return super.emitSafe(event, ...args);
3501
+ }
3502
+ onListenerError(error, event) {
3503
+ this.logger.error(`listener for ${String(event)} threw`, error);
3504
+ }
3505
+ };
3506
+ __decorate([(0, envapt.Envapt)("DISCORD_BOT_TOKEN", { converter: (raw) => (0, _seedcord_errors_internal.validateDiscordToken)(raw) }), __decorateMetadata("design:type", String)], Bot.prototype, "botToken", void 0);
3507
+
3508
+ //#endregion
3509
+ //#region src/hmr/HmrManager.ts
3510
+ var HmrManager = class {
3511
+ logger = new _seedcord_services.Logger("HMR", { channel: "hmr" });
3512
+ listeners = /* @__PURE__ */ new Set();
3513
+ constructor() {}
3514
+ /** @internal */
3515
+ init() {
3516
+ if (!{}.hot) return;
3517
+ setDevChannel((0, _seedcord_types_internal.wrapHot)({}.hot));
3518
+ if (envapt.Envapter.isDevelopment || envapt.Envapter.isTest) {
3519
+ this.logger.info("Enabled");
3520
+ getDevChannel()?.on("seedcord:hmr", (payload) => {
3521
+ const affected = payload.affectedModules?.length ?? 0;
3522
+ this.logger.info(`${chalk.default.bold("1")} module changed, ${chalk.default.bold(affected)} affected modules`);
3523
+ if (payload.affectedModules) this.logger.utils.list(payload.affectedModules.map((mod) => (0, _seedcord_utils.formatFilePath)(mod)), "Affected modules: ");
3524
+ this.handleUpdate(payload);
3525
+ });
3526
+ }
3527
+ }
3528
+ /** @internal */
3529
+ register(listener) {
3530
+ this.listeners.add(listener);
3531
+ }
3532
+ /** @internal */
3533
+ unregister(listener) {
3534
+ this.listeners.delete(listener);
3535
+ }
3536
+ async handleUpdate(event) {
3537
+ const promises = [...this.listeners].map(async (listener) => {
3538
+ try {
3539
+ await listener.onHmr(event);
3540
+ } catch (error) {
3541
+ this.logger.error(`Error handling HMR update in ${chalk.default.bold(listener.name)}: `, error);
3542
+ }
3543
+ });
3544
+ await Promise.all(promises);
3545
+ }
3546
+ };
3547
+
3548
+ //#endregion
3549
+ //#region src/subscribers/bases/webhookHelpers.ts
3550
+ const DISCORD_WEBHOOK_REGEX = new RegExp(String.raw`^https?:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[\w$-]+$`);
3551
+ /**
3552
+ * Whether a string is a well-formed Discord webhook URL.
3553
+ *
3554
+ * @internal
3555
+ */
3556
+ function isDiscordWebhookUrl(value) {
3557
+ return URL.canParse(value) && DISCORD_WEBHOOK_REGEX.test(value);
3558
+ }
3559
+ /**
3560
+ * Serializes a value to a JSON attachment, made circular-safe first.
3561
+ *
3562
+ * @internal
3563
+ */
3564
+ function jsonAttachment(name, description, data) {
3565
+ const content = (0, _seedcord_utils.filterCirculars)(data);
3566
+ return new discord_js.AttachmentBuilder(Buffer.from(JSON.stringify(content, void 0, 2), "utf8"), {
3567
+ name,
3568
+ description
3569
+ });
3570
+ }
3571
+ /**
3572
+ * The small divider the default webhook reporters place between sections.
3573
+ *
3574
+ * @internal
3575
+ */
3576
+ var WebhookSeparator = class extends _seedcord_core.BuilderComponent {
3577
+ constructor() {
3578
+ super("separator");
3579
+ this.instance.setSpacing(discord_js.SeparatorSpacingSize.Small).setDivider(true);
3580
+ }
3581
+ };
3582
+
3583
+ //#endregion
3584
+ //#region src/subscribers/default/HandledException.ts
3585
+ var _HandledException;
3586
+ function webhookUrlValidator$1(raw) {
3587
+ if (raw !== null && typeof raw !== "string") throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigHandledExceptionWebhookInvalid);
3588
+ const value = raw?.trim() ?? "";
3589
+ if (value === "") throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigHandledExceptionWebhookMissing);
3590
+ if (!isDiscordWebhookUrl(value)) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigHandledExceptionWebhookInvalid);
3591
+ return value;
3592
+ }
3593
+ let HandledException = class HandledException extends WebhookLog {
3594
+ static {
3595
+ _HandledException = this;
3596
+ }
3597
+ webhook = new discord_js.WebhookClient({ url: _HandledException.handledExceptionWebhookUrl });
3598
+ async execute() {
3599
+ const { source } = this.data;
3600
+ try {
3601
+ await this.webhook.send({
3602
+ flags: flagsFor(false),
3603
+ withComponents: true,
3604
+ username: "Handled Exception",
3605
+ components: [new HandledExceptionContainer(this.data).component],
3606
+ files: [jsonAttachment("source.json", "The raw source the fault came from", source.raw)]
3607
+ });
3608
+ } catch (error) {
3609
+ this.logger.error("Failed to send handled exception webhook", error);
3610
+ }
3611
+ }
3612
+ };
3613
+ __decorate([(0, envapt.Envapt)("HANDLED_EXCEPTION_WEBHOOK_URL", { converter: (raw) => webhookUrlValidator$1(raw) }), __decorateMetadata("design:type", String)], HandledException, "handledExceptionWebhookUrl", void 0);
3614
+ HandledException = _HandledException = __decorate([Subscribe("handledException")], HandledException);
3615
+ var HandledExceptionContainer = class extends _seedcord_core.BuilderComponent {
3616
+ constructor(data) {
3617
+ super("container");
3618
+ const { denial, uuid, source } = data;
3619
+ this.instance.addTextDisplayComponents((text) => text.setContent(faultSummary(denial, source))).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### UUID \`${uuid}\`\n\`\`\`${causeStack(denial)}\`\`\``)).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Source")).addFileComponents((file) => file.setURL("attachment://source.json"));
3620
+ }
3621
+ };
3622
+ /**
3623
+ * The summary block of a fault report, narrowed per source kind so an interaction fault shows its
3624
+ * command and customId while an event fault shows its event name and handler.
3625
+ *
3626
+ * @internal
3627
+ */
3628
+ function faultSummary(denial, source) {
3629
+ const head = `### A handled fault was reported: \`${denial.name}\`\n**Message:** ${denial.message}\n`;
3630
+ if (source.kind === "event") return `${head}**Event:** ${source.eventName}\n**Handler:** ${source.handler}\n**User ID:** \`${source.userId ?? "n/a"}\`\n**Guild ID:** \`${source.guildId ?? "n/a"}\`\n**Channel ID:** \`${source.channelId ?? "n/a"}\``;
3631
+ return `${head}**Kind:** ${source.interactionKind}\n**Command:** ${source.command ?? "n/a"}\n**CustomId:** ${source.customId ?? "n/a"}\n**User ID:** \`${source.userId}\`\n**Guild ID:** \`${source.guildId ?? "n/a"}\`\n**Channel ID:** \`${source.channelId ?? "n/a"}\`\n**Interaction ID:** \`${source.interactionId}\``;
3632
+ }
3633
+ /**
3634
+ * The text shown for a denial's cause in the report. Tolerates a non-serializable cause (a bigint or a
3635
+ * circular object) so building the report never throws.
3636
+ *
3637
+ * @internal
3638
+ */
3639
+ function causeStack(denial) {
3640
+ const { cause } = denial;
3641
+ if (Error.isError(cause)) return cause.stack ?? cause.message;
3642
+ if (typeof cause === "string") return cause;
3643
+ if (typeof cause === "bigint" || typeof cause === "symbol" || typeof cause === "function") return cause.toString();
3644
+ if (cause !== void 0) try {
3645
+ return JSON.stringify(cause);
3646
+ } catch {
3647
+ return "[unserializable cause]";
3648
+ }
3649
+ return denial.stack ?? "No cause recorded.";
3650
+ }
3651
+
3652
+ //#endregion
3653
+ //#region src/subscribers/default/UnknownException.ts
3654
+ var _UnknownException;
3655
+ function webhookUrlValidator(raw) {
3656
+ if (raw !== null && typeof raw !== "string") throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigUnknownExceptionWebhookInvalid);
3657
+ const value = raw?.trim() ?? "";
3658
+ if (value === "") throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigUnknownExceptionWebhookMissing);
3659
+ if (!isDiscordWebhookUrl(value)) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigUnknownExceptionWebhookInvalid);
3660
+ return value;
3661
+ }
3662
+ let UnknownException = class UnknownException extends WebhookLog {
3663
+ static {
3664
+ _UnknownException = this;
3665
+ }
3666
+ webhook = new discord_js.WebhookClient({ url: _UnknownException.unknownExceptionWebhookUrl });
3667
+ async execute() {
3668
+ const { metadata } = this.data;
3669
+ const metadataFile = metadata ? jsonAttachment("metadata.json", "Metadata associated with the error", metadata) : null;
3670
+ try {
3671
+ await this.webhook.send({
3672
+ flags: flagsFor(false),
3673
+ withComponents: true,
3674
+ username: "Unknown Exception",
3675
+ components: [new UnhandledErrorContainer(this.data).component],
3676
+ files: metadataFile ? [metadataFile] : []
3677
+ });
3678
+ } catch (error) {
3679
+ this.logger.error("Failed to send unknown exception webhook", error);
3680
+ }
3681
+ }
3682
+ };
3683
+ __decorate([(0, envapt.Envapt)("UNKNOWN_EXCEPTION_WEBHOOK_URL", { converter: (raw) => webhookUrlValidator(raw) }), __decorateMetadata("design:type", String)], UnknownException, "unknownExceptionWebhookUrl", void 0);
3684
+ UnknownException = _UnknownException = __decorate([Subscribe("unknownException")], UnknownException);
3685
+ var UnhandledErrorContainer = class extends _seedcord_core.BuilderComponent {
3686
+ constructor(data) {
3687
+ super("container");
3688
+ const { uuid, error, guild, user, metadata } = data;
3689
+ this.instance.addTextDisplayComponents((text) => text.setContent(`### An unknown exception was thrown\n**Guild ID:** \`${guild?.id ?? "Not used in a guild"}\`\n**Guild Name:** ${guild?.name ?? "Not used in a guild"}\n**User ID:** \`${user?.id ?? "Missing user info"}\`\n**Username:** ${user?.username ?? "Missing user info"}\n`)).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### UUID \`${uuid}\`\n\`\`\`${error.stack}\`\`\``));
3690
+ this.addTimestampsIfAvailable(error);
3691
+ this.addMetadataIfAvailable(metadata);
3692
+ }
3693
+ addTimestampsIfAvailable(error) {
3694
+ if (!(error instanceof discord_js.DiscordAPIError)) return;
3695
+ const now = Date.now();
3696
+ const snowflake = error.url.match(/\/interactions\/(\d+)\//)?.[1];
3697
+ if (!snowflake) return void 0;
3698
+ const interactionTs = Number(discord_js.SnowflakeUtil.deconstruct(snowflake).timestamp);
3699
+ const diff = now - interactionTs;
3700
+ const seconds = Math.floor(diff / 1e3);
3701
+ const millis = diff % 1e3;
3702
+ this.instance.addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### Timestamps\n- **\`Interaction sent\` :** ${new Date(interactionTs).toISOString()} (${interactionTs})\n- **\`Error logged \` :** ${new Date(now).toISOString()} (${now})\n- **\`Offset \` :** ${seconds}s ${millis}ms`));
3703
+ }
3704
+ addMetadataIfAvailable(metadata) {
3705
+ if (!metadata) return;
3706
+ this.instance.addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Metadata")).addFileComponents((file) => file.setURL("attachment://metadata.json"));
3707
+ }
3708
+ };
3709
+
3710
+ //#endregion
3711
+ //#region src/subscribers/Bus.ts
3712
+ /**
3713
+ * Manages application subscribers and event handling
3714
+ *
3715
+ * Provides a centralized system for registering and executing custom subscribers
3716
+ * throughout the application lifecycle. Bus subscribers are loaded from configured directories
3717
+ * and can be triggered programmatically or by framework events. Accessed via `core.bus`. Do not
3718
+ * construct it directly.
3719
+ */
3720
+ var Bus = class extends Plugin {
3721
+ core;
3722
+ logger = new _seedcord_services.Logger("Subscribers");
3723
+ /** @internal */
3724
+ name = "Subscribers";
3725
+ isInitialized = false;
3726
+ subscribersMap = /* @__PURE__ */ new Map();
3727
+ executedOnceHandlers = /* @__PURE__ */ new Set();
3728
+ hmrHandler;
3729
+ constructor(core) {
3730
+ super(core);
3731
+ this.core = core;
3732
+ if (this.core.config.subscribers.path) {
3733
+ if (!envapt.Envapter.isDevelopment && !envapt.Envapter.isTest) return;
3734
+ this.hmrHandler = new HmrModuleHandler({
3735
+ handlersDir: this.core.config.subscribers.path,
3736
+ isHandler: this.isSubscriber.bind(this),
3737
+ registerHandler: this.registerSubscriber.bind(this),
3738
+ unregisterHandler: this.unregisterSubscriber.bind(this),
3739
+ getArtifacts: this.getArtifacts.bind(this),
3740
+ logger: this.logger
3741
+ });
3742
+ }
3743
+ }
3744
+ getArtifacts(ctor) {
3745
+ return [Reflect.getMetadata(_seedcord_core_internal.SubscribeMetadataKey, ctor).subscriber];
3746
+ }
3747
+ /** @internal */
3748
+ async init() {
3749
+ if (this.isInitialized) return;
3750
+ this.isInitialized = true;
3751
+ this.registerSubscriber(UnknownException);
3752
+ this.registerSubscriber(HandledException);
3753
+ envapt.Envapter.require("UNKNOWN_EXCEPTION_WEBHOOK_URL", "HANDLED_EXCEPTION_WEBHOOK_URL");
3754
+ const subscribersDir = this.core.config.subscribers.path;
3755
+ if (subscribersDir) {
3756
+ this.logger.info(chalk.default.bold(subscribersDir));
3757
+ await this.loadSubscribers(subscribersDir);
3758
+ const totalSubscribers = [...this.subscribersMap.values()].reduce((acc, handlers) => acc + handlers.length, 0);
3759
+ this.logger.utils.list([`${chalk.default.bold.magenta(totalSubscribers)} subscribers`], chalk.default.bold.green("Loaded"));
3760
+ }
3761
+ }
3762
+ /** @internal For use in dev mode */
3763
+ async onHmr(event) {
3764
+ if (this.hmrHandler) await this.hmrHandler.handle(event);
3765
+ }
3766
+ async loadSubscribers(dir) {
3767
+ await (0, _seedcord_utils.traverseDirectory)(dir, (fullPath, relativePath, imported) => {
3768
+ for (const exportName of Object.keys(imported)) {
3769
+ const val = imported[exportName];
3770
+ if (this.isSubscriber(val)) {
3771
+ this.registerSubscriber(val);
3772
+ this.hmrHandler?.trackHandler(fullPath, val);
3773
+ this.logger.utils.registration(val.name, relativePath);
3774
+ }
3775
+ }
3776
+ }, this.logger);
3777
+ }
3778
+ registerSubscriber(handler) {
3779
+ const options = Reflect.getMetadata(_seedcord_core_internal.SubscribeMetadataKey, handler);
3780
+ let handlers = this.subscribersMap.get(options.subscriber);
3781
+ if (!handlers) {
3782
+ handlers = [];
3783
+ this.subscribersMap.set(options.subscriber, handlers);
3784
+ }
3785
+ handlers.push({
3786
+ ctor: handler,
3787
+ frequency: options.frequency ?? "on"
3788
+ });
3789
+ }
3790
+ unregisterSubscriber(handler, artifacts) {
3791
+ const subscribers = artifacts ?? [...this.subscribersMap.keys()];
3792
+ for (const subscriber of subscribers) {
3793
+ const handlers = this.subscribersMap.get(subscriber);
3794
+ if (!handlers) continue;
3795
+ const index = handlers.findIndex((entry) => entry.ctor === handler);
3796
+ if (index !== -1) handlers.splice(index, 1);
3797
+ }
3798
+ }
3799
+ isSubscriber(obj) {
3800
+ if (typeof obj !== "function") return false;
3801
+ return obj.prototype instanceof Subscriber && Reflect.hasMetadata(_seedcord_core_internal.SubscribeMetadataKey, obj);
3802
+ }
3803
+ /**
3804
+ * Publishes an event to its subscribers and native listeners.
3805
+ *
3806
+ * Fire-and-forget, so subscriber handlers run asynchronously and this returns before they
3807
+ * complete, and callers must not assume side effects have landed. Errors thrown by a subscriber
3808
+ * are caught and logged, never surfaced here. A `'once'` subscriber is marked as executed when
3809
+ * it starts (even if it throws), so it never runs twice.
3810
+ *
3811
+ * @param event - The subscription key to publish
3812
+ * @param data - Payload passed to each subscriber
3813
+ * @returns Whether the underlying emitter had native listeners for the event
3814
+ */
3815
+ publish(event, data) {
3816
+ this.processSubscriber(event, data);
3817
+ return super.emit(event, ...[data]);
3818
+ }
3819
+ async processSubscriber(subscriberName, data) {
3820
+ const handlers = this.subscribersMap.get(subscriberName);
3821
+ if (!handlers) return;
3822
+ for (const entry of handlers) {
3823
+ if (entry.frequency === "once" && this.executedOnceHandlers.has(entry.ctor)) continue;
3824
+ try {
3825
+ if (entry.frequency === "once") this.executedOnceHandlers.add(entry.ctor);
3826
+ const Ctor = entry.ctor;
3827
+ await new Ctor(data, this.core).execute();
3828
+ } catch (err) {
3829
+ this.logger.error(`Error in subscriber ${String(subscriberName)} handler ${entry.ctor.name}:`, err);
3830
+ }
3831
+ }
3832
+ }
3833
+ };
3834
+
3835
+ //#endregion
3836
+ //#region src/version.ts
4
3837
  /** Package version */
5
- const version = "0.0.1";
3838
+ const version = "0.1.0-next.1";
3839
+
3840
+ //#endregion
3841
+ //#region src/Seedcord.ts
3842
+ /**
3843
+ * Main Seedcord bot framework class
3844
+ *
3845
+ * Primary entry point for creating Discord bots with Seedcord.
3846
+ * Manages component lifecycle and provides plugin support.
3847
+ */
3848
+ var Seedcord = class Seedcord extends Pluggable {
3849
+ config;
3850
+ /** @internal */
3851
+ [_seedcord_types_internal.SeedcordBrand] = true;
3852
+ /** @internal */
3853
+ augmentTarget = "@seedcord/gateway";
3854
+ /** @internal */
3855
+ version = version;
3856
+ static isInstantiated = false;
3857
+ /** @see {@link CoordinatedShutdown} */
3858
+ shutdown;
3859
+ /** @see {@link CoordinatedStartup} */
3860
+ startup;
3861
+ /** @see {@link Bus} */
3862
+ bus;
3863
+ /** @see {@link Bot} */
3864
+ bot;
3865
+ /** @see {@link IRateLimiter} */
3866
+ rateLimiter;
3867
+ /** @see {@link HealthCheck} */
3868
+ healthCheck;
3869
+ /** @see {@link HmrManager} */
3870
+ hmrManager;
3871
+ /**
3872
+ * Creates a new Seedcord instance
3873
+ *
3874
+ * @param config - Bot configuration including paths and Discord client options
3875
+ * @throws A **SeedcordError** When attempting to create multiple instances (singleton)
3876
+ */
3877
+ constructor(config) {
3878
+ if (Seedcord.isInstantiated) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CoreSingletonViolation);
3879
+ Seedcord.isInstantiated = true;
3880
+ const shutdown = new _seedcord_services.CoordinatedShutdown(config.shutdownEnabled);
3881
+ const startup = new _seedcord_services.CoordinatedStartup();
3882
+ super(shutdown, startup);
3883
+ this.config = config;
3884
+ (0, _seedcord_core_internal.setBotColor)(config.botColor);
3885
+ this.shutdown = shutdown;
3886
+ this.startup = startup;
3887
+ this.hmrManager = new HmrManager();
3888
+ this.hmrManager.init();
3889
+ this.bus = new Bus(this);
3890
+ this.bot = new Bot(this);
3891
+ this.rateLimiter = config.store ?? new _seedcord_rate_limiter.MemoryRateLimiter();
3892
+ this.healthCheck = new _seedcord_services.HealthCheck(this.shutdown, config.healthCheck);
3893
+ this.registerStartupTasks();
3894
+ }
3895
+ /** @internal */
3896
+ static reset() {
3897
+ Seedcord.isInstantiated = false;
3898
+ }
3899
+ /**
3900
+ * Registers default startup tasks
3901
+ * @internal
3902
+ */
3903
+ registerStartupTasks() {
3904
+ if (envapt.Envapter.isDevelopment || envapt.Envapter.isTest) this.registerHmrAwareModules();
3905
+ this.startup.addTask(_seedcord_services.StartupPhase.Configuration, "Bus Initialization", async () => {
3906
+ this.bus.logger.utils.initialization("Subscribers", "start");
3907
+ await this.bus.init();
3908
+ this.bus.logger.utils.initialization("Subscribers", "end");
3909
+ });
3910
+ this.startup.addTask(_seedcord_services.StartupPhase.Instantiation, "Bot Initialization", async () => {
3911
+ this.bot.logger.utils.initialization("Bot", "start");
3912
+ await this.bot.init();
3913
+ this.bot.logger.utils.initialization("Bot", "end");
3914
+ });
3915
+ this.startup.addTask(_seedcord_services.StartupPhase.Ready, "Health Check", async () => {
3916
+ this.healthCheck.logger.utils.initialization("HealthCheck", "start");
3917
+ await this.healthCheck.init();
3918
+ this.healthCheck.logger.utils.initialization("HealthCheck", "end");
3919
+ });
3920
+ }
3921
+ /**
3922
+ * Starts the bot and runs all initialization tasks
3923
+ *
3924
+ * @returns This Seedcord instance when fully initialized
3925
+ */
3926
+ async start() {
3927
+ await super.init();
3928
+ return this;
3929
+ }
3930
+ registerHmrAwareModules() {
3931
+ this.startup.addTask(_seedcord_services.StartupPhase.Configuration, "HMR Registration", async () => {
3932
+ this.hmrManager.register(this.bot);
3933
+ this.hmrManager.register(this.bus);
3934
+ for (const plugin of this.plugins) this.hmrManager.register(plugin);
3935
+ await Promise.resolve();
3936
+ });
3937
+ }
3938
+ };
6
3939
 
7
3940
  //#endregion
3941
+ exports.ArraySource = ArraySource;
3942
+ exports.AutocompleteHandler = AutocompleteHandler;
3943
+ exports.AutocompleteRoute = AutocompleteRoute;
3944
+ exports.ButtonHandler = ButtonHandler;
3945
+ exports.ButtonRoute = ButtonRoute;
3946
+ exports.CommandMentions = CommandMentions;
3947
+ exports.ContextMenuHandler = ContextMenuHandler;
3948
+ exports.ContextMenuRoute = ContextMenuRoute;
3949
+ exports.CursorSource = CursorSource;
3950
+ exports.Emojis = Emojis;
3951
+ exports.EventHandler = EventHandler;
3952
+ exports.EventMiddleware = EventMiddleware;
3953
+ exports.Gated = Gated;
3954
+ exports.HmrModuleHandler = HmrModuleHandler;
3955
+ exports.IgnoreBots = IgnoreBots;
3956
+ exports.InteractionHandler = InteractionHandler;
3957
+ exports.InteractionMiddleware = InteractionMiddleware;
3958
+ exports.Middleware = Middleware;
3959
+ exports.MiddlewareType = MiddlewareType;
3960
+ exports.ModalHandler = ModalHandler;
3961
+ exports.ModalRoute = ModalRoute;
3962
+ exports.Nsfw = Nsfw;
3963
+ exports.Paginator = Paginator;
3964
+ exports.Pluggable = Pluggable;
3965
+ exports.Plugin = Plugin;
3966
+ Object.defineProperty(exports, 'RegisterCommand', {
3967
+ enumerable: true,
3968
+ get: function () {
3969
+ return _seedcord_core.RegisterCommand;
3970
+ }
3971
+ });
3972
+ exports.RegisterEvent = RegisterEvent;
3973
+ exports.ReplySender = ReplySender;
3974
+ exports.RequireBotPermissions = RequireBotPermissions;
3975
+ exports.RequirePermissions = RequirePermissions;
3976
+ exports.RequireRole = RequireRole;
3977
+ exports.Seedcord = Seedcord;
3978
+ exports.SelectMenuHandler = SelectMenuHandler;
3979
+ exports.SelectMenuKind = SelectMenuKind;
3980
+ exports.SelectMenuRoute = SelectMenuRoute;
3981
+ exports.SlashHandler = SlashHandler;
3982
+ exports.SlashRoute = SlashRoute;
3983
+ exports.Subscribe = Subscribe;
3984
+ exports.Subscriber = Subscriber;
3985
+ exports.WebhookLog = WebhookLog;
3986
+ exports.checkBotPermissions = checkBotPermissions;
3987
+ exports.checkPermissions = checkPermissions;
3988
+ exports.fetchGuildMember = fetchGuildMember;
3989
+ exports.fetchManyGuildMembers = fetchManyGuildMembers;
3990
+ exports.fetchManyUsers = fetchManyUsers;
3991
+ exports.fetchRole = fetchRole;
3992
+ exports.fetchText = fetchText;
3993
+ exports.fetchUser = fetchUser;
3994
+ exports.getBotRole = getBotRole;
3995
+ exports.getConfirmation = getConfirmation;
3996
+ exports.hasPermsToAssign = hasPermsToAssign;
3997
+ exports.updateMemberRoles = updateMemberRoles;
8
3998
  exports.version = version;
3999
+ Object.keys(_seedcord_core).forEach(function (k) {
4000
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
4001
+ enumerable: true,
4002
+ get: function () { return _seedcord_core[k]; }
4003
+ });
4004
+ });
4005
+
4006
+ Object.keys(_seedcord_errors).forEach(function (k) {
4007
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
4008
+ enumerable: true,
4009
+ get: function () { return _seedcord_errors[k]; }
4010
+ });
4011
+ });
4012
+
4013
+ Object.keys(_seedcord_event_emitter).forEach(function (k) {
4014
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
4015
+ enumerable: true,
4016
+ get: function () { return _seedcord_event_emitter[k]; }
4017
+ });
4018
+ });
4019
+
4020
+ Object.keys(_seedcord_rate_limiter).forEach(function (k) {
4021
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
4022
+ enumerable: true,
4023
+ get: function () { return _seedcord_rate_limiter[k]; }
4024
+ });
4025
+ });
4026
+
4027
+ Object.keys(_seedcord_services).forEach(function (k) {
4028
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
4029
+ enumerable: true,
4030
+ get: function () { return _seedcord_services[k]; }
4031
+ });
4032
+ });
4033
+
4034
+ Object.keys(_seedcord_utils).forEach(function (k) {
4035
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
4036
+ enumerable: true,
4037
+ get: function () { return _seedcord_utils[k]; }
4038
+ });
4039
+ });
4040
+
9
4041
  //# sourceMappingURL=index.cjs.map