gralonium 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/lib/classes/Client.d.ts +13 -3
  2. package/lib/classes/Client.js +23 -1
  3. package/lib/classes/Context.d.ts +2 -0
  4. package/lib/classes/Context.js +94 -21
  5. package/lib/classes/Cooldowns.d.ts +2 -0
  6. package/lib/classes/Cooldowns.js +28 -0
  7. package/lib/classes/Loader.d.ts +12 -3
  8. package/lib/classes/Loader.js +141 -19
  9. package/lib/classes/Plugins.js +3 -2
  10. package/lib/classes/Utils.d.ts +1 -1
  11. package/lib/classes/Utils.js +110 -20
  12. package/lib/classes/builders/CommandBuilder.d.ts +14 -0
  13. package/lib/classes/builders/CommandBuilder.js +50 -2
  14. package/lib/classes/builders/ComponentsV2Builder.d.ts +51 -3
  15. package/lib/classes/builders/ComponentsV2Builder.js +394 -72
  16. package/lib/classes/builders/GroupBuilder.d.ts +11 -0
  17. package/lib/classes/builders/GroupBuilder.js +21 -1
  18. package/lib/classes/builders/InteractionBuilder.d.ts +47 -0
  19. package/lib/classes/builders/InteractionBuilder.js +113 -2
  20. package/lib/classes/builders/ParamsBuilder.d.ts +118 -76
  21. package/lib/classes/builders/ParamsBuilder.js +167 -1
  22. package/lib/classes/builders/components/StyleMapper.d.ts +13 -1
  23. package/lib/classes/builders/components/StyleMapper.js +33 -8
  24. package/lib/classes/builders/components/helpers.d.ts +3 -0
  25. package/lib/classes/builders/components/helpers.js +56 -3
  26. package/lib/classes/builders/components/linter.d.ts +61 -0
  27. package/lib/classes/builders/components/linter.js +252 -0
  28. package/lib/classes/builders/components/overflow.d.ts +151 -0
  29. package/lib/classes/builders/components/overflow.js +534 -0
  30. package/lib/classes/views/V2Adaptive.d.ts +103 -0
  31. package/lib/classes/views/V2Adaptive.js +502 -0
  32. package/lib/classes/views/V2PersistentRouter.d.ts +124 -0
  33. package/lib/classes/views/V2PersistentRouter.js +511 -0
  34. package/lib/classes/views/V2View.d.ts +1 -0
  35. package/lib/classes/views/V2View.js +53 -15
  36. package/lib/experiments.d.ts +2 -0
  37. package/lib/experiments.js +2 -0
  38. package/lib/main.d.ts +4 -0
  39. package/lib/main.js +4 -0
  40. package/package.json +1 -1
@@ -1,8 +1,10 @@
1
1
  import { Client, ClientOptions, CommandInteraction, Message, Snowflake } from "discord.js";
2
2
  import { Context } from "./Context.js";
3
- import { Loader, Plugin } from "./Loader.js";
3
+ import { CommandLocalizer, Loader, Plugin } from "./Loader.js";
4
4
  import { HelpCommand, HelpCommandOptions } from "./HelpCommand.js";
5
5
  import { Cooldowns } from "./Cooldowns.js";
6
+ import type { V2AdaptiveConfigureOptions } from "./views/V2Adaptive.js";
7
+ import { V2PersistentRouter, V2PersistentRouterOptions } from "./views/V2PersistentRouter.js";
6
8
 
7
9
  export interface GraloniumRestrictions {
8
10
  userIDs: Set<Snowflake>;
@@ -25,17 +27,25 @@ export interface GraloniumOptions extends ClientOptions {
25
27
  debug?: boolean;
26
28
  bindProcessHandlers?: boolean;
27
29
  retryOnRateLimit?: boolean;
30
+ defaultLocale?: string;
31
+ localizeCommand?: CommandLocalizer;
32
+ beforeExecute?: (ctx: Context, command: any, options: any) => boolean | void | Promise<boolean | void>;
33
+ afterExecute?: (ctx: Context, command: any, options: any) => void | Promise<void>;
34
+ v2Adaptive?: V2AdaptiveConfigureOptions;
28
35
  }
29
36
 
30
37
  export declare class Gralonium extends Client {
31
38
  cooldowns: Cooldowns;
32
39
  loader: Loader;
40
+ persistentRouters: Map<string, V2PersistentRouter>;
33
41
  ops: GraloniumOptions;
34
42
  constructor(options: GraloniumOptions);
35
43
  addGlobalPlugins(plugins: Plugin[]): this;
44
+ createPersistentRouter(namespace: string, options?: V2PersistentRouterOptions): V2PersistentRouter;
45
+ registerPersistentRouter(router: V2PersistentRouter): V2PersistentRouter;
36
46
  getContext(data: CommandInteraction | Message): Context;
37
- load(dir: string, reload?: boolean): Promise<import("./Loader.js").ModuleData<import("./builders/InteractionBuilder.js").InteractionBuilder | import("./builders/CommandBuilder.js").CommandBuilder | import("./builders/EventBuilder.js").EventBuilder | import("./builders/GroupBuilder.js").GroupBuilder, any[]>[]>;
38
- sync(guildIDs?: string[]): Promise<void>;
47
+ load(dir: string, reload?: boolean): Promise<Array<import("./Loader.js").ModuleData<import("./builders/InteractionBuilder.js").InteractionBuilder | import("./builders/CommandBuilder.js").CommandBuilder | import("./builders/EventBuilder.js").EventBuilder | import("./builders/GroupBuilder.js").GroupBuilder | V2PersistentRouter, any[]> | V2PersistentRouter>>;
48
+ sync(guildIDs?: string[]): Promise<Record<string, any>[]>;
39
49
  handleFrameworkError(error: unknown, ctx?: Context | null): void;
40
50
  login(token: string): Promise<string>;
41
51
  destroy(): this;
@@ -7,6 +7,8 @@ const Context_js_1 = require("./Context.js");
7
7
  const Loader_js_1 = require("./Loader.js");
8
8
  const Cooldowns_js_1 = require("./Cooldowns.js");
9
9
  const Utils_js_1 = require("./Utils.js");
10
+ const V2Adaptive_js_1 = require("./views/V2Adaptive.js");
11
+ const V2PersistentRouter_js_1 = require("./views/V2PersistentRouter.js");
10
12
 
11
13
  class Gralonium extends discord_js_1.Client {
12
14
  static #processHandlersBound = false;
@@ -14,6 +16,7 @@ class Gralonium extends discord_js_1.Client {
14
16
 
15
17
  cooldowns = new Cooldowns_js_1.Cooldowns(this);
16
18
  loader = new Loader_js_1.Loader({ client: this });
19
+ persistentRouters = new Map();
17
20
  ops;
18
21
  #coreListenersBound = false;
19
22
 
@@ -35,6 +38,25 @@ class Gralonium extends discord_js_1.Client {
35
38
 
36
39
  if (this.ops.guildOnly === undefined) this.ops.guildOnly = true;
37
40
  if (typeof this.ops.debug !== "boolean") this.ops.debug = false;
41
+
42
+ V2Adaptive_js_1.ensureOverflowInteractionBridge(this);
43
+ if (this.ops.v2Adaptive && typeof this.ops.v2Adaptive === "object") {
44
+ V2Adaptive_js_1.V2Adaptive.configure(this.ops.v2Adaptive);
45
+ }
46
+ }
47
+
48
+ createPersistentRouter(namespace, routerOptions = {}) {
49
+ const router = V2PersistentRouter_js_1.createPersistentRouter(namespace, routerOptions);
50
+ this.persistentRouters.set(router.namespace, router);
51
+ return router;
52
+ }
53
+
54
+ registerPersistentRouter(router) {
55
+ if (!(router instanceof V2PersistentRouter_js_1.V2PersistentRouter)) {
56
+ throw new TypeError("[Gralonium] registerPersistentRouter() requires a V2PersistentRouter instance.");
57
+ }
58
+ this.persistentRouters.set(router.namespace, router);
59
+ return router;
38
60
  }
39
61
 
40
62
  addGlobalPlugins(plugins) {
@@ -52,7 +74,7 @@ class Gralonium extends discord_js_1.Client {
52
74
  }
53
75
 
54
76
  async sync(guildIDs) {
55
- await this.loader.sync(guildIDs);
77
+ return this.loader.sync(guildIDs);
56
78
  }
57
79
 
58
80
  #debug(message) {
@@ -55,6 +55,8 @@ export declare class Context {
55
55
  get channel(): DJS.TextBasedChannel | null;
56
56
  get member(): DJS.GuildMember | DJS.APIInteractionGuildMember | null;
57
57
  get guild(): DJS.Guild | null;
58
+ get locale(): DJS.Locale | string | null;
59
+ get guildLocale(): DJS.Locale | string | null;
58
60
  defer(options?: ContextDeferOptions): Promise<DJS.Message<boolean> | DJS.InteractionResponse<boolean> | null>;
59
61
  send(payload: ContextPayload, options?: ContextSendOptions): Promise<DJS.Message<boolean>>;
60
62
  reply(payload: ContextPayload, options?: ContextSendOptions): Promise<DJS.Message<boolean>>;
@@ -6,6 +6,7 @@ const tslib_1 = require("tslib");
6
6
  const DJS = tslib_1.__importStar(require("discord.js"));
7
7
  const ComponentsV2Builder_js_1 = require("./builders/ComponentsV2Builder.js");
8
8
  const helpers_js_1 = require("./builders/components/helpers.js");
9
+ const V2Adaptive_js_1 = require("./views/V2Adaptive.js");
9
10
 
10
11
  class Context {
11
12
  bot;
@@ -71,6 +72,14 @@ class Context {
71
72
  return this.data.guild || null;
72
73
  }
73
74
 
75
+ get locale() {
76
+ return this.data?.locale ?? null;
77
+ }
78
+
79
+ get guildLocale() {
80
+ return this.data?.guildLocale ?? this.guild?.preferredLocale ?? null;
81
+ }
82
+
74
83
  static #isRateLimitError(error) {
75
84
  if (!error) return false;
76
85
  if (error?.code === 429) return true;
@@ -261,6 +270,38 @@ class Context {
261
270
  return this.#sendWithOptionalRetry(() => this.data.deferReply(deferOptions));
262
271
  }
263
272
 
273
+ async #dispatchAdaptiveSend(payload, options, normalized, executorFn) {
274
+ try {
275
+ return await this.#sendWithOptionalRetry(() => executorFn(normalized));
276
+ } catch (error) {
277
+ const source =
278
+ V2Adaptive_js_1.V2Adaptive.extractOverflowSource(normalized) ||
279
+ V2Adaptive_js_1.V2Adaptive.extractOverflowSource(payload);
280
+
281
+ if (
282
+ !source ||
283
+ !source.usedNativeOverflow ||
284
+ !source.canFallback ||
285
+ !V2Adaptive_js_1.V2Adaptive.isOverflowRejectionError(error)
286
+ ) {
287
+ throw error;
288
+ }
289
+
290
+ V2Adaptive_js_1.V2Adaptive.markOverflowUnavailable();
291
+ const rebuilt = source.builder.toPayload({
292
+ ...(source.options || {}),
293
+ ...options,
294
+ forceOverflowFallback: true,
295
+ });
296
+
297
+ if (this.data instanceof DJS.Message) {
298
+ Context.#stripEphemeralForMessage(rebuilt);
299
+ }
300
+
301
+ return this.#sendWithOptionalRetry(() => executorFn(rebuilt));
302
+ }
303
+ }
304
+
264
305
  /**
265
306
  * Sends a reply in both prefix (`Message`) and slash/interaction modes.
266
307
  * Accepts strings, message option objects, or `ComponentsV2Builder` instances.
@@ -279,12 +320,17 @@ class Context {
279
320
 
280
321
  const hasPoll = Boolean(normalized && typeof normalized === "object" && normalized.poll !== undefined);
281
322
  if (thinkingWasV2 === isV2 && !hasPoll && typeof thinkingMsg.edit === "function") {
282
- const editData = normalized instanceof DJS.MessagePayload ? normalized : { ...normalized };
283
- if (editData && typeof editData === "object" && "reply" in editData) {
284
- delete editData.reply;
285
- }
323
+ const prepareEdit = (p) => {
324
+ const editData = p instanceof DJS.MessagePayload ? p : { ...p };
325
+ if (editData && typeof editData === "object" && "reply" in editData) {
326
+ delete editData.reply;
327
+ }
328
+ return editData;
329
+ };
286
330
  try {
287
- return await this.#sendWithOptionalRetry(() => thinkingMsg.edit(editData));
331
+ return await this.#dispatchAdaptiveSend(payload, options, normalized, (p) =>
332
+ thinkingMsg.edit(prepareEdit(p))
333
+ );
288
334
  } catch {
289
335
  // Fall through to sending a fresh message if placeholder can no longer be edited.
290
336
  }
@@ -295,20 +341,31 @@ class Context {
295
341
 
296
342
  const shouldReply = Boolean(options.reply ?? normalized?.reply ?? this.bot?.ops?.replyOnPrefix);
297
343
  if (shouldReply && !(normalized instanceof DJS.MessagePayload)) {
298
- if (!normalized.reply && this.data.id) {
299
- normalized.reply = { messageReference: this.data.id, failIfNotExists: false };
300
- }
301
- if (normalized.allowedMentions === undefined) {
302
- normalized.allowedMentions = { parse: [], repliedUser: false };
303
- }
344
+ const prepareReply = (p) => {
345
+ const out = { ...p };
346
+ if (!out.reply && this.data.id) {
347
+ out.reply = { messageReference: this.data.id, failIfNotExists: false };
348
+ }
349
+ if (out.allowedMentions === undefined) {
350
+ out.allowedMentions = { parse: [], repliedUser: false };
351
+ }
352
+ return out;
353
+ };
354
+
304
355
  if (typeof this.data.reply === "function" && !options.forceChannelSend) {
305
- const replyObj = { ...normalized };
306
- delete replyObj.reply;
307
- return this.#sendWithOptionalRetry(() => this.data.reply(replyObj));
356
+ return this.#dispatchAdaptiveSend(payload, options, normalized, (p) => {
357
+ const replyObj = prepareReply(p);
358
+ delete replyObj.reply;
359
+ return this.data.reply(replyObj);
360
+ });
308
361
  }
362
+
363
+ return this.#dispatchAdaptiveSend(payload, options, normalized, (p) =>
364
+ this.data.channel.send(prepareReply(p))
365
+ );
309
366
  }
310
367
 
311
- return this.#sendWithOptionalRetry(() => this.data.channel.send(normalized));
368
+ return this.#dispatchAdaptiveSend(payload, options, normalized, (p) => this.data.channel.send(p));
312
369
  }
313
370
 
314
371
  if (this.data.isAutocomplete?.()) {
@@ -321,17 +378,17 @@ class Context {
321
378
  if (this.data.deferred && !this.data.replied && typeof this.data.deleteReply === "function") {
322
379
  await this.data.deleteReply().catch(() => null);
323
380
  }
324
- return this.#sendWithOptionalRetry(() => this.data.followUp(normalized));
381
+ return this.#dispatchAdaptiveSend(payload, options, normalized, (p) => this.data.followUp(p));
325
382
  }
326
383
 
327
384
  if (options.followUp) {
328
- return this.#sendWithOptionalRetry(() => this.data.followUp(normalized));
385
+ return this.#dispatchAdaptiveSend(payload, options, normalized, (p) => this.data.followUp(p));
329
386
  }
330
387
 
331
- return this.#sendWithOptionalRetry(() => this.data.editReply(normalized));
388
+ return this.#dispatchAdaptiveSend(payload, options, normalized, (p) => this.data.editReply(p));
332
389
  }
333
390
 
334
- return this.#sendWithOptionalRetry(() => this.data.reply(normalized));
391
+ return this.#dispatchAdaptiveSend(payload, options, normalized, (p) => this.data.reply(p));
335
392
  }
336
393
 
337
394
  /**
@@ -364,12 +421,28 @@ class Context {
364
421
  const lowered = param.toLowerCase();
365
422
 
366
423
  if (this.params?.length) {
367
- return this.params.find((entry) => entry.name.toLowerCase() === lowered)?.value ?? null;
424
+ const match = this.params.find((entry) => entry?.name?.toLowerCase() === lowered);
425
+ if (match) return match.value ?? null;
368
426
  }
369
427
 
370
428
  if (this.data instanceof DJS.Message) return null;
371
429
 
372
- const option = this.data.options?.data?.find((entry) => entry.name.toLowerCase() === lowered);
430
+ const findOption = (entries) => {
431
+ if (!Array.isArray(entries)) return null;
432
+ for (const entry of entries) {
433
+ if ((entry?.type === 1 || entry?.type === 2) && Array.isArray(entry.options)) {
434
+ const nested = findOption(entry.options);
435
+ if (nested) return nested;
436
+ continue;
437
+ }
438
+ if (typeof entry?.name === "string" && entry.name.toLowerCase() === lowered) {
439
+ return entry;
440
+ }
441
+ }
442
+ return null;
443
+ };
444
+
445
+ const option = findOption(this.data.options?.data) ?? this.data.options?.get?.(param) ?? null;
373
446
  if (!option) return null;
374
447
 
375
448
  return option.attachment ?? option.member ?? option.channel ?? option.role ?? option.user ?? option.value ?? null;
@@ -13,6 +13,8 @@ export declare class Cooldowns {
13
13
  expiresAt: number;
14
14
  }>;
15
15
  constructor(bot: Gralonium);
16
+ static resolveKey(command: unknown, group?: unknown): string;
17
+ sweep(now?: number): number;
16
18
  getCooldownSource(command: string, id: string, bucket: Bucket): Promise<number | undefined>;
17
19
  setCooldownSource(command: string, id: string, bucket: Bucket, time: number): Promise<void>;
18
20
  check(command: string, id: string, cooldown: number, bucket: Bucket): Promise<{
@@ -23,6 +23,30 @@ class Cooldowns {
23
23
  return `${command}#${bucket}#${id}`;
24
24
  }
25
25
 
26
+ static resolveKey(command, group = null) {
27
+ const commandName =
28
+ typeof command === "string"
29
+ ? command
30
+ : command?.data?.name || command?.name || "unknown";
31
+ const groupName =
32
+ typeof group === "string"
33
+ ? group
34
+ : group?.data?.name || group?.name || "";
35
+
36
+ return groupName ? `${groupName}:${commandName}` : commandName;
37
+ }
38
+
39
+ sweep(now = Date.now()) {
40
+ let cleared = 0;
41
+ for (const [key, entry] of this.track.entries()) {
42
+ if (!entry || now >= entry.expiresAt) {
43
+ this.track.delete(key);
44
+ cleared += 1;
45
+ }
46
+ }
47
+ return cleared;
48
+ }
49
+
26
50
  async getCooldownSource(command, id, bucket) {
27
51
  const key = this.#key(command, id, bucket);
28
52
  const tracked = this.track.get(key);
@@ -38,6 +62,10 @@ class Cooldowns {
38
62
 
39
63
  async setCooldownSource(command, id, bucket, time) {
40
64
  const now = Date.now();
65
+ if (this.track.size >= 500) {
66
+ this.sweep(now);
67
+ }
68
+
41
69
  this.track.set(this.#key(command, id, bucket), {
42
70
  startedAt: now,
43
71
  expiresAt: now + time,
@@ -7,9 +7,10 @@ import { GroupBuilder } from "./builders/GroupBuilder.js";
7
7
  import { Plugins as GraloniumPlugins } from "../main.js";
8
8
  import { Context } from "./Context.js";
9
9
  import { Gralonium } from "./Client.js";
10
+ import { V2PersistentRouter } from "./views/V2PersistentRouter.js";
10
11
 
11
12
  export interface ModuleData<T extends unknown = unknown, K extends any[] = any[]> {
12
- data: CommandBuilder | GroupBuilder | InteractionBuilder | EventBuilder;
13
+ data: CommandBuilder | GroupBuilder | InteractionBuilder | EventBuilder | V2PersistentRouter;
13
14
  plugins?: T extends CommandBuilder ? (typeof GraloniumPlugins[] | Plugin[]) : never;
14
15
  params?: T extends CommandBuilder ? ParamsBuilder : never;
15
16
  code?: T extends CommandBuilder
@@ -68,6 +69,7 @@ type InteractionTypes =
68
69
  | "chatInput"
69
70
  | "messageContextMenu"
70
71
  | "modalSubmit"
72
+ | "overflowMenu"
71
73
  | "userContextMenu"
72
74
  | "channelSelectMenu"
73
75
  | "roleSelectMenu"
@@ -76,16 +78,23 @@ type InteractionTypes =
76
78
  | "mentionableSelectMenu"
77
79
  | "anyInteraction";
78
80
 
81
+ export type CommandLocalizer = (
82
+ commandJSON: Record<string, any>
83
+ ) => Record<string, any> | void | Promise<Record<string, any> | void>;
84
+
79
85
  export declare class Loader {
80
86
  client: Gralonium;
81
87
  commands: GraloniumCollected;
82
88
  interactions: Record<InteractionTypes, Collection<string, ModuleData<InteractionBuilder>>>;
83
89
  interactionMatchers: Map<InteractionTypes, ModuleData<InteractionBuilder>[]>;
90
+ localizer: CommandLocalizer | null;
84
91
  globalPlugins: Plugin[];
85
92
  rest: REST;
86
93
  constructor(options: LoaderOptions);
87
- load(dir: string, reload?: boolean): Promise<ModuleData<InteractionBuilder | CommandBuilder | EventBuilder | GroupBuilder, any[]>[]>;
94
+ setLocalizer(localizer: CommandLocalizer | null): this;
95
+ load(dir: string, reload?: boolean): Promise<Array<ModuleData<InteractionBuilder | CommandBuilder | EventBuilder | GroupBuilder | V2PersistentRouter, any[]> | V2PersistentRouter>>;
88
96
  resolvePatternInteraction(type: InteractionTypes, key: string, interaction?: any): ModuleData<InteractionBuilder> | null;
89
97
  walkCommands(callable?: (command: Command<Types>) => number): CommandHelpingObject[];
90
- sync(guildIDs?: string[]): Promise<void>;
98
+ buildApplicationCommands(): Promise<Record<string, any>[]>;
99
+ sync(guildIDs?: string[]): Promise<Record<string, any>[]>;
91
100
  }
@@ -12,6 +12,7 @@ const CommandBuilder_js_1 = require("./builders/CommandBuilder.js");
12
12
  const GroupBuilder_js_1 = require("./builders/GroupBuilder.js");
13
13
  const EventBuilder_js_1 = require("./builders/EventBuilder.js");
14
14
  const InteractionBuilder_js_1 = require("./builders/InteractionBuilder.js");
15
+ const V2PersistentRouter_js_1 = require("./views/V2PersistentRouter.js");
15
16
 
16
17
  const isValidFile = (file) => {
17
18
  if (file.endsWith(".d.ts")) return false;
@@ -32,6 +33,7 @@ class Loader {
32
33
  rest;
33
34
  #eventHandlers;
34
35
  #loadedSignature;
36
+ #loadedRouterNamespaces;
35
37
 
36
38
  constructor(options) {
37
39
  if (!(options?.client instanceof Client_js_1.Gralonium)) {
@@ -45,6 +47,7 @@ class Loader {
45
47
  button: new discord_js_1.Collection(),
46
48
  chatInput: new discord_js_1.Collection(),
47
49
  modalSubmit: new discord_js_1.Collection(),
50
+ overflowMenu: new discord_js_1.Collection(),
48
51
  userContextMenu: new discord_js_1.Collection(),
49
52
  messageContextMenu: new discord_js_1.Collection(),
50
53
  channelSelectMenu: new discord_js_1.Collection(),
@@ -57,8 +60,18 @@ class Loader {
57
60
  this.globalPlugins = [];
58
61
  this.rest = new discord_js_1.REST();
59
62
  this.interactionMatchers = new Map();
63
+ this.localizer = options.client?.ops?.localizeCommand ?? null;
60
64
  this.#eventHandlers = new Map();
61
65
  this.#loadedSignature = new Set();
66
+ this.#loadedRouterNamespaces = new Set();
67
+ }
68
+
69
+ /**
70
+ * Registers a global command localization transformer executed before syncing application commands.
71
+ */
72
+ setLocalizer(localizer) {
73
+ this.localizer = typeof localizer === "function" ? localizer : null;
74
+ return this;
62
75
  }
63
76
 
64
77
  #toAbsolutePath(inputPath) {
@@ -91,14 +104,48 @@ class Loader {
91
104
  const mod = require(absolute)?.data;
92
105
  if (!mod) continue;
93
106
 
94
- if (Array.isArray(mod)) output.push(...mod);
95
- else output.push(mod);
107
+ if (Array.isArray(mod)) {
108
+ for (const item of mod) {
109
+ const normalized = this.#normalizeLoadedModule(item);
110
+ if (normalized) output.push(normalized);
111
+ }
112
+ } else {
113
+ const normalized = this.#normalizeLoadedModule(mod);
114
+ if (normalized) output.push(normalized);
115
+ }
96
116
  }
97
117
  }
98
118
 
119
+ #normalizeLoadedModule(item) {
120
+ if (!item || typeof item !== "object") return null;
121
+ if (item instanceof V2PersistentRouter_js_1.V2PersistentRouter) {
122
+ return item;
123
+ }
124
+ if (!item.data && typeof item.name === "string" && typeof item.code === "function") {
125
+ return {
126
+ data: new EventBuilder_js_1.EventBuilder({
127
+ name: item.name,
128
+ once: Boolean(item.once),
129
+ description: item.description,
130
+ }),
131
+ code: item.code,
132
+ };
133
+ }
134
+ return item;
135
+ }
136
+
99
137
  #moduleSignature(moduleData) {
138
+ if (moduleData instanceof V2PersistentRouter_js_1.V2PersistentRouter) {
139
+ return `V2PersistentRouter:${moduleData.namespace}`;
140
+ }
100
141
  const data = moduleData?.data;
142
+ if (data instanceof V2PersistentRouter_js_1.V2PersistentRouter) {
143
+ return `V2PersistentRouter:${data.namespace}`;
144
+ }
101
145
  const type = data?.constructor?.name || "Unknown";
146
+ if (data instanceof EventBuilder_js_1.EventBuilder) {
147
+ return `${type}:${data.name}:${(0, crypto_1.randomUUID)()}`;
148
+ }
102
149
  if (data instanceof InteractionBuilder_js_1.InteractionBuilder) {
103
150
  const kind = data.type || "unknown";
104
151
  const patternTag =
@@ -122,6 +169,13 @@ class Loader {
122
169
  }
123
170
 
124
171
  #assertValidModule(moduleData) {
172
+ if (
173
+ moduleData instanceof V2PersistentRouter_js_1.V2PersistentRouter ||
174
+ moduleData?.data instanceof V2PersistentRouter_js_1.V2PersistentRouter
175
+ ) {
176
+ return;
177
+ }
178
+
125
179
  if (!moduleData?.data) {
126
180
  throw new Error("Invalid module: missing data builder.");
127
181
  }
@@ -171,6 +225,11 @@ class Loader {
171
225
  for (const key of Object.keys(this.interactions)) {
172
226
  this.interactions[key].clear();
173
227
  }
228
+
229
+ for (const ns of this.#loadedRouterNamespaces) {
230
+ this.client?.persistentRouters?.delete?.(ns);
231
+ }
232
+ this.#loadedRouterNamespaces.clear();
174
233
  }
175
234
 
176
235
  #storeInteraction(moduleData) {
@@ -231,6 +290,21 @@ class Loader {
231
290
  this.#assertValidModule(moduleData);
232
291
  this.#assertUnique(moduleData);
233
292
 
293
+ if (
294
+ moduleData instanceof V2PersistentRouter_js_1.V2PersistentRouter ||
295
+ moduleData.data instanceof V2PersistentRouter_js_1.V2PersistentRouter
296
+ ) {
297
+ const router =
298
+ moduleData instanceof V2PersistentRouter_js_1.V2PersistentRouter ? moduleData : moduleData.data;
299
+ if (typeof this.client.registerPersistentRouter === "function") {
300
+ this.client.registerPersistentRouter(router);
301
+ } else {
302
+ this.client.persistentRouters?.set?.(router.namespace, router);
303
+ }
304
+ this.#loadedRouterNamespaces.add(router.namespace);
305
+ continue;
306
+ }
307
+
234
308
  if (moduleData.data instanceof EventBuilder_js_1.EventBuilder) {
235
309
  this.#attachEvent(moduleData);
236
310
  continue;
@@ -274,9 +348,18 @@ class Loader {
274
348
  return output.sort(sorter);
275
349
  }
276
350
 
351
+ #serializeCommandParams(paramsBuilder) {
352
+ if (!paramsBuilder) return [];
353
+ if (typeof paramsBuilder.toJSON === "function") {
354
+ return paramsBuilder.toJSON();
355
+ }
356
+ return paramsBuilder.params || [];
357
+ }
358
+
277
359
  #buildTopLevelSlash(command) {
278
360
  const payload = { ...command.data.toJSON() };
279
- payload.options = command.params?.params || [];
361
+ payload.type = discord_js_1.ApplicationCommandType.ChatInput;
362
+ payload.options = this.#serializeCommandParams(command.params);
280
363
  return payload;
281
364
  }
282
365
 
@@ -285,7 +368,7 @@ class Loader {
285
368
  const subCommandJSON = { ...commandRef.data.toJSON() };
286
369
 
287
370
  subCommandJSON.type = 1;
288
- subCommandJSON.options = commandRef.params?.params || [];
371
+ subCommandJSON.options = this.#serializeCommandParams(commandRef.params);
289
372
 
290
373
  if (subCommandJSON.default_member_permissions === undefined && groupJSON.default_member_permissions !== undefined) {
291
374
  subCommandJSON.default_member_permissions = groupJSON.default_member_permissions;
@@ -315,46 +398,85 @@ class Loader {
315
398
  payloads.push(groupPayload);
316
399
  }
317
400
 
318
- async sync(guildIDs) {
319
- if (!this.client.token) {
320
- throw new Error("Cannot sync application commands before login token is set.");
321
- }
322
-
323
- if (!this.client.user?.id) {
324
- throw new Error("Cannot sync application commands before client is ready.");
325
- }
326
-
327
- this.rest.setToken(this.client.token);
328
-
401
+ /**
402
+ * Builds all application command payloads (ChatInput slash commands + User/Message Context Menus)
403
+ * and applies the configured localization hook if set.
404
+ */
405
+ async buildApplicationCommands() {
329
406
  const commands = this.walkCommands();
330
407
  const payload = [];
331
- const slashNames = new Set();
408
+ const registeredSignatures = new Set();
332
409
 
333
410
  for (const command of commands) {
334
411
  if (!command.data.as_slash) continue;
335
412
 
336
413
  if (!command.group) {
337
414
  const built = this.#buildTopLevelSlash(command);
338
- if (slashNames.has(built.name)) {
415
+ const sig = `${built.type}:${built.name}`;
416
+ if (registeredSignatures.has(sig)) {
339
417
  throw new Error(`Duplicate slash command name detected during sync: ${built.name}`);
340
418
  }
341
- slashNames.add(built.name);
419
+ registeredSignatures.add(sig);
342
420
  payload.push(built);
343
421
  continue;
344
422
  }
345
423
 
346
424
  if (!command.group.data.as_slash) continue;
347
425
  this.#mergeGroupSlashPayload(payload, command.group, command);
426
+ registeredSignatures.add(`${discord_js_1.ApplicationCommandType.ChatInput}:${command.group.data.name}`);
427
+ }
428
+
429
+ const contextMenuCollections = [this.interactions.userContextMenu, this.interactions.messageContextMenu];
430
+ for (const collection of contextMenuCollections) {
431
+ for (const entry of collection.values()) {
432
+ if (entry?.data?.as_command === false || !entry?.data?.name) continue;
433
+ const built = entry.data.toCommandJSON();
434
+ if (!built) continue;
435
+ const sig = `${built.type}:${built.name}`;
436
+ if (registeredSignatures.has(sig)) {
437
+ throw new Error(`Duplicate context menu command detected during sync: ${built.name}`);
438
+ }
439
+ registeredSignatures.add(sig);
440
+ payload.push(built);
441
+ }
442
+ }
443
+
444
+ const localizer = this.localizer ?? this.client?.ops?.localizeCommand;
445
+ if (typeof localizer === "function") {
446
+ for (let i = 0; i < payload.length; i += 1) {
447
+ const transformed = await localizer(payload[i]);
448
+ if (transformed && typeof transformed === "object") {
449
+ payload[i] = transformed;
450
+ }
451
+ }
452
+ }
453
+
454
+ return payload;
455
+ }
456
+
457
+ async sync(guildIDs) {
458
+ if (!this.client.token) {
459
+ throw new Error("Cannot sync application commands before login token is set.");
460
+ }
461
+
462
+ if (!this.client.user?.id) {
463
+ throw new Error("Cannot sync application commands before client is ready.");
348
464
  }
349
465
 
466
+ this.rest.setToken(this.client.token);
467
+
468
+ const payload = await this.buildApplicationCommands();
469
+
350
470
  if (!guildIDs?.length) {
351
471
  await this.rest.put(discord_js_1.Routes.applicationCommands(this.client.user.id), { body: payload });
352
- return;
472
+ return payload;
353
473
  }
354
474
 
355
475
  for (const guildID of guildIDs) {
356
476
  await this.rest.put(discord_js_1.Routes.applicationGuildCommands(this.client.user.id, guildID), { body: payload });
357
477
  }
478
+
479
+ return payload;
358
480
  }
359
481
  }
360
482
  exports.Loader = Loader;
@@ -91,11 +91,12 @@ function cooldown(seconds, bucket) {
91
91
  }
92
92
 
93
93
  const cooldownInMs = 1000 * seconds;
94
+ const commandKey = Cooldowns_js_1.Cooldowns.resolveKey(ctx.command, ctx.parent);
94
95
 
95
- const active = await ctx.bot.cooldowns.check(ctx.command.data.name, source, cooldownInMs, bucket);
96
+ const active = await ctx.bot.cooldowns.check(commandKey, source, cooldownInMs, bucket);
96
97
  if (active) throw new Errors.CommandInCooldown(ctx, active.left);
97
98
 
98
- await ctx.bot.cooldowns.setCooldownSource(ctx.command.data.name, source, bucket, cooldownInMs);
99
+ await ctx.bot.cooldowns.setCooldownSource(commandKey, source, bucket, cooldownInMs);
99
100
  return true;
100
101
  };
101
102
  }
@@ -10,7 +10,7 @@ export declare class Utils {
10
10
  static getChannel<T = DJS.Channel>(query: string, options: { guild: DJS.Guild; force?: boolean }): Promise<T | null>;
11
11
  static getRole(query: string, options: { guild: DJS.Guild; force?: boolean }): Promise<DJS.Role | null>;
12
12
  static getUser(query: string, bot: Gralonium): Promise<DJS.User | null>;
13
- static transform(input: string, param: P.BaseParam, ctx: Context, seeable?: boolean): Promise<{ break: boolean; value: any }>;
13
+ static transform(input: string, param: P.BaseParam, ctx: Context, seeable?: boolean, attachmentIndex?: number): Promise<{ break: boolean; value: any }>;
14
14
  static executeCommand(
15
15
  ctx: Context,
16
16
  command: Command<Types.Normal>,