gralonium 0.3.0 → 0.4.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.
Files changed (44) hide show
  1. package/lib/classes/Client.d.ts +9 -3
  2. package/lib/classes/Client.js +2 -2
  3. package/lib/classes/Context.d.ts +42 -1
  4. package/lib/classes/Context.js +276 -13
  5. package/lib/classes/Cooldowns.d.ts +2 -0
  6. package/lib/classes/Cooldowns.js +28 -0
  7. package/lib/classes/HelpCommand.d.ts +55 -13
  8. package/lib/classes/HelpCommand.js +319 -1
  9. package/lib/classes/Loader.d.ts +10 -1
  10. package/lib/classes/Loader.js +143 -58
  11. package/lib/classes/Plugins.js +3 -2
  12. package/lib/classes/Utils.d.ts +1 -1
  13. package/lib/classes/Utils.js +103 -24
  14. package/lib/classes/builders/CommandBuilder.d.ts +24 -0
  15. package/lib/classes/builders/CommandBuilder.js +66 -2
  16. package/lib/classes/builders/ComponentsV2Builder.d.ts +288 -113
  17. package/lib/classes/builders/ComponentsV2Builder.js +1071 -180
  18. package/lib/classes/builders/GroupBuilder.d.ts +20 -0
  19. package/lib/classes/builders/GroupBuilder.js +37 -1
  20. package/lib/classes/builders/InteractionBuilder.d.ts +86 -25
  21. package/lib/classes/builders/InteractionBuilder.js +212 -1
  22. package/lib/classes/builders/ParamsBuilder.d.ts +118 -76
  23. package/lib/classes/builders/ParamsBuilder.js +167 -1
  24. package/lib/classes/builders/components/StyleMapper.d.ts +14 -2
  25. package/lib/classes/builders/components/StyleMapper.js +35 -9
  26. package/lib/classes/builders/components/helpers.d.ts +68 -4
  27. package/lib/classes/builders/components/helpers.js +366 -7
  28. package/lib/classes/builders/components/templates.d.ts +151 -9
  29. package/lib/classes/builders/components/templates.js +376 -17
  30. package/lib/classes/builders/components/text.d.ts +24 -0
  31. package/lib/classes/builders/components/text.js +91 -0
  32. package/lib/classes/experiments/Confirmator.d.ts +44 -26
  33. package/lib/classes/experiments/Confirmator.js +37 -21
  34. package/lib/classes/experiments/Paginator.d.ts +48 -29
  35. package/lib/classes/experiments/Paginator.js +48 -19
  36. package/lib/classes/views/V2Paginator.d.ts +91 -0
  37. package/lib/classes/views/V2Paginator.js +268 -0
  38. package/lib/classes/views/V2View.d.ts +113 -0
  39. package/lib/classes/views/V2View.js +438 -0
  40. package/lib/experiments.d.ts +2 -0
  41. package/lib/experiments.js +9 -1
  42. package/lib/main.d.ts +3 -0
  43. package/lib/main.js +3 -0
  44. package/package.json +3 -1
@@ -1,285 +1,1176 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ComponentsV2Builder = void 0;
3
+ exports.SelectMenuProxy = exports.ComponentsV2Builder = void 0;
4
4
 
5
+ const path_1 = require("path");
5
6
  const discord_js_1 = require("discord.js");
6
- const StyleMapper_js_1 = require("./components/StyleMapper.js");
7
7
  const helpers_js_1 = require("./components/helpers.js");
8
+ const StyleMapper_js_1 = require("./components/StyleMapper.js");
9
+ const text_js_1 = require("./components/text.js");
10
+ const templates = require("./components/templates.js");
11
+
12
+ const SELECT_TYPE_MAP = {
13
+ string: "string",
14
+ user: "user",
15
+ role: "role",
16
+ channel: "channel",
17
+ mentionable: "mentionable",
18
+ };
19
+
20
+ function sanitizeAttachmentName(name, fallback = "file.bin") {
21
+ const raw = String(name || "").trim();
22
+ if (!raw) return fallback;
23
+ const base = path_1.basename(raw).replace(/\s+/g, "_");
24
+ return base || fallback;
25
+ }
26
+
27
+ function splitTextIntoChunks(text, maxChunkSize) {
28
+ const limit = Math.max(10, Number(maxChunkSize) || 1900);
29
+ const chunks = [];
30
+ let remaining = String(text ?? "");
31
+
32
+ while (remaining.length > limit) {
33
+ let sliceAt = remaining.lastIndexOf("\n", limit);
34
+ if (sliceAt < Math.floor(limit * 0.4)) {
35
+ sliceAt = remaining.lastIndexOf(" ", limit);
36
+ }
37
+ if (sliceAt < Math.floor(limit * 0.4)) {
38
+ sliceAt = limit;
39
+ }
40
+ const piece = remaining.slice(0, sliceAt).trimEnd();
41
+ if (piece.length > 0) chunks.push(piece);
42
+ remaining = remaining.slice(sliceAt).replace(/^\n+/, "");
43
+ }
44
+
45
+ if (remaining.length > 0) {
46
+ chunks.push(remaining);
47
+ }
48
+ return chunks;
49
+ }
8
50
 
9
51
  /**
10
- * SelectMenuProxy gives a chainable API to add options to a StringSelectMenu
11
- * and then return to the parent ComponentsV2Builder via `.end()`.
52
+ * Proxy for configuring a StringSelectMenuBuilder using chained `.addOption(...)`
53
+ * and returning to the parent ComponentsV2Builder with `.end()`.
12
54
  */
13
55
  class SelectMenuProxy {
56
+ #parent;
57
+ #menu;
58
+
14
59
  constructor(parent, menu) {
15
- this._parent = parent;
16
- this._menu = menu;
17
- this._optionCount = 0;
60
+ this.#parent = parent;
61
+ this.#menu = menu;
18
62
  }
19
63
 
20
64
  /**
21
- * Add an option to the select menu.
65
+ * Adds an option to the select menu.
66
+ * Supports positional args `(label, value, description?, emoji?, isDefault?)`
67
+ * or an option object `{ label, value, description, emoji, default }`.
22
68
  */
23
- addOption(label, value, emoji, description) {
24
- this._optionCount += 1;
25
- helpers_js_1.validateSelectMenuOptions(this._optionCount);
69
+ addOption(labelOrOption, value, description, emoji, isDefault) {
70
+ const currentCount = this.#menu.options ? this.#menu.options.length : 0;
71
+ helpers_js_1.validateSelectMenuOptions(currentCount + 1);
72
+
73
+ let optionBuilder;
74
+ if (labelOrOption instanceof discord_js_1.StringSelectMenuOptionBuilder) {
75
+ optionBuilder = labelOrOption;
76
+ } else {
77
+ const cfg =
78
+ labelOrOption && typeof labelOrOption === "object"
79
+ ? labelOrOption
80
+ : { label: labelOrOption, value, description, emoji, default: isDefault };
26
81
 
27
- const option = new discord_js_1.StringSelectMenuOptionBuilder()
28
- .setLabel(label)
29
- .setValue(value ?? helpers_js_1.generateCustomId("opt"));
82
+ const optLabel = String(cfg.label ?? "").trim();
83
+ const optValue = String(cfg.value ?? optLabel);
84
+ if (!optLabel || !optValue) {
85
+ throw new Error("[ComponentsV2Builder] Select menu options require non-empty label and value.");
86
+ }
87
+
88
+ optionBuilder = new discord_js_1.StringSelectMenuOptionBuilder().setLabel(optLabel).setValue(optValue);
30
89
 
31
- if (emoji) option.setEmoji({ name: emoji });
32
- if (description) option.setDescription(description);
90
+ if (cfg.description) {
91
+ optionBuilder.setDescription(String(cfg.description));
92
+ }
93
+ if (cfg.emoji) {
94
+ const parsedEmoji = helpers_js_1.parseEmoji(cfg.emoji);
95
+ if (parsedEmoji) optionBuilder.setEmoji(parsedEmoji);
96
+ }
97
+ if (cfg.default !== undefined) {
98
+ optionBuilder.setDefault(Boolean(cfg.default));
99
+ }
100
+ }
101
+
102
+ this.#menu.addOptions(optionBuilder);
103
+ return this;
104
+ }
105
+
106
+ /**
107
+ * Adds multiple options at once (objects, tuples `[label, value, description?, emoji?, default?]`, or builders).
108
+ */
109
+ addOptions(options) {
110
+ if (!Array.isArray(options)) return this;
111
+ for (const item of options) {
112
+ if (!item) continue;
113
+ if (Array.isArray(item)) {
114
+ this.addOption(item[0], item[1], item[2], item[3], item[4]);
115
+ } else {
116
+ this.addOption(item);
117
+ }
118
+ }
119
+ return this;
120
+ }
121
+
122
+ setPlaceholder(placeholder) {
123
+ this.#menu.setPlaceholder(String(placeholder));
124
+ return this;
125
+ }
126
+
127
+ setMinValues(min) {
128
+ this.#menu.setMinValues(Number(min));
129
+ return this;
130
+ }
131
+
132
+ setMaxValues(max) {
133
+ this.#menu.setMaxValues(Number(max));
134
+ return this;
135
+ }
33
136
 
34
- this._menu.addOptions(option);
137
+ setDisabled(disabled = true) {
138
+ this.#menu.setDisabled(Boolean(disabled));
35
139
  return this;
36
140
  }
37
141
 
38
142
  /**
39
- * Return to the parent builder to continue chaining.
143
+ * Finishes configuring the select menu and returns to the parent ComponentsV2Builder.
40
144
  */
41
145
  end() {
42
- return this._parent;
146
+ return this.#parent;
43
147
  }
44
148
  }
149
+ exports.SelectMenuProxy = SelectMenuProxy;
45
150
 
46
151
  /**
47
- * ComponentsV2Builder — a fluent builder that abstracts the complexity of
48
- * Discord.js Components V2 (Containers, Separators, TextDisplays, Buttons,
49
- * and StringSelectMenus).
50
- *
51
- * @example
52
- * ```js
53
- * const { ComponentsV2Builder } = require("gralonium");
54
- *
55
- * const components = new ComponentsV2Builder()
56
- * .addText("## Welcome!")
57
- * .addSeparator("small")
58
- * .addButton("Click Me", "btn_1", "primary")
59
- * .addButton("Cancel", "btn_2", "secondary")
60
- * .build();
61
- *
62
- * interaction.reply({ components });
63
- * ```
152
+ * Fluent builder for Discord Components V2 messages with full support for
153
+ * Containers, Sections, MediaGalleries, Files/Attachments, typed SelectMenus,
154
+ * smart emojis, outside rows, limit guards, and ready-to-send payloads.
64
155
  */
65
156
  class ComponentsV2Builder {
66
- constructor() {
67
- this._container = new discord_js_1.ContainerBuilder();
68
- this._pendingButtons = [];
157
+ #topLevel = [];
158
+ #activeContainerEntry;
159
+ #placement = "inside";
160
+ #currentRow = null;
161
+ #currentRowPlacement = null;
162
+ #files = [];
163
+ #defaultSafeMentions = true;
164
+ #lastKindByTarget = { inside: null, outside: null };
165
+
166
+ static flags = discord_js_1.MessageFlags.IsComponentsV2;
167
+ static MAX_TEXT_LENGTH = helpers_js_1.MAX_V2_TEXT_LENGTH;
168
+ static SAFE_TEXT_LENGTH = helpers_js_1.SAFE_V2_TEXT_LENGTH;
169
+ static MAX_COMPONENTS = helpers_js_1.MAX_V2_COMPONENTS;
170
+ static MAX_TOP_LEVEL_COMPONENTS = helpers_js_1.MAX_V2_TOP_LEVEL_COMPONENTS;
171
+ static text = text_js_1.V2Text;
172
+ static clipText = helpers_js_1.clipText;
173
+ static resolveColor = helpers_js_1.resolveAccentColor;
174
+ static setDefaultButtonStyle = StyleMapper_js_1.setDefaultButtonStyle;
175
+ static getDefaultButtonStyle = StyleMapper_js_1.getDefaultButtonStyle;
176
+ static parseEmoji = helpers_js_1.parseEmoji;
177
+ static isValidMediaUrl = helpers_js_1.isValidMediaUrl;
178
+ static isValidLinkUrl = helpers_js_1.isValidLinkUrl;
179
+ static disableComponents = helpers_js_1.disableComponents;
180
+ static disableMessageComponents = helpers_js_1.disableMessageComponents;
181
+ static countTextLength = helpers_js_1.countTextLength;
182
+ static countComponents = helpers_js_1.countComponents;
183
+
184
+ static isBuilder(value) {
185
+ return Boolean(
186
+ value &&
187
+ (value instanceof ComponentsV2Builder ||
188
+ (typeof value === "object" && typeof value.toPayload === "function" && typeof value.build === "function"))
189
+ );
69
190
  }
70
191
 
71
- // ─── Internal helpers ────────────────────────────────────────────────────
192
+ constructor(options = {}) {
193
+ this.#defaultSafeMentions = options.safeMentions !== false;
194
+ this.#activeContainerEntry = this.#createContainerEntry(options);
195
+ }
196
+
197
+ #createContainerEntry(options = {}) {
198
+ const container = new discord_js_1.ContainerBuilder();
199
+ const colorInput = options.color !== undefined ? options.color : options.accentColor;
200
+ if (colorInput !== undefined && colorInput !== null) {
201
+ const resolved = helpers_js_1.resolveAccentColor(colorInput);
202
+ if (resolved !== null) container.setAccentColor(resolved);
203
+ }
204
+ if (options.spoiler) {
205
+ container.setSpoiler(true);
206
+ }
207
+ return {
208
+ kind: "container",
209
+ builder: container,
210
+ hasContent: false,
211
+ attached: false,
212
+ };
213
+ }
214
+
215
+ #ensureContainerAttached(entry) {
216
+ if (!entry.attached) {
217
+ this.#topLevel.push(entry);
218
+ entry.attached = true;
219
+ }
220
+ }
221
+
222
+ #flushPendingRow() {
223
+ if (!this.#currentRow || !this.#currentRow.components?.length) {
224
+ this.#currentRow = null;
225
+ this.#currentRowPlacement = null;
226
+ return;
227
+ }
228
+ const row = this.#currentRow;
229
+ const placement = this.#currentRowPlacement || "inside";
230
+ this.#currentRow = null;
231
+ this.#currentRowPlacement = null;
232
+ this.#appendDirect(row, "actionRow", placement);
233
+ }
234
+
235
+ #appendDirect(component, kind, placement = this.#placement) {
236
+ if (placement === "outside") {
237
+ this.#topLevel.push({ kind: "outside", component });
238
+ this.#lastKindByTarget.outside = kind;
239
+ return;
240
+ }
241
+
242
+ const entry = this.#activeContainerEntry;
243
+ this.#ensureContainerAttached(entry);
244
+ entry.hasContent = true;
245
+
246
+ const c = entry.builder;
247
+ switch (kind) {
248
+ case "text":
249
+ c.addTextDisplayComponents(component);
250
+ break;
251
+ case "separator":
252
+ c.addSeparatorComponents(component);
253
+ break;
254
+ case "section":
255
+ c.addSectionComponents(component);
256
+ break;
257
+ case "gallery":
258
+ c.addMediaGalleryComponents(component);
259
+ break;
260
+ case "file":
261
+ c.addFileComponents(component);
262
+ break;
263
+ case "actionRow":
264
+ c.addActionRowComponents(component);
265
+ break;
266
+ default:
267
+ throw new TypeError(`[ComponentsV2Builder] Unsupported component kind: ${String(kind)}`);
268
+ }
269
+ this.#lastKindByTarget.inside = kind;
270
+ }
271
+
272
+ #appendComponent(component, kind) {
273
+ this.#flushPendingRow();
274
+ this.#appendDirect(component, kind, this.#placement);
275
+ }
276
+
277
+ #ensureActionRow() {
278
+ if (this.#currentRow && this.#currentRowPlacement !== this.#placement) {
279
+ this.#flushPendingRow();
280
+ }
281
+ if (!this.#currentRow || this.#currentRow.components.length >= 5) {
282
+ this.#flushPendingRow();
283
+ this.#currentRow = new discord_js_1.ActionRowBuilder();
284
+ this.#currentRowPlacement = this.#placement;
285
+ }
286
+ return this.#currentRow;
287
+ }
288
+
289
+ #createButton(input, customIdArg, styleArg, urlArg, extraArg) {
290
+ if (input instanceof discord_js_1.ButtonBuilder) {
291
+ return input;
292
+ }
293
+
294
+ const cfg =
295
+ input && typeof input === "object"
296
+ ? input
297
+ : {
298
+ label: input,
299
+ customId: customIdArg,
300
+ style: styleArg,
301
+ url: urlArg,
302
+ ...(extraArg && typeof extraArg === "object" ? extraArg : {}),
303
+ };
304
+
305
+ const button = new discord_js_1.ButtonBuilder();
306
+ const resolvedStyle =
307
+ cfg.style !== undefined && cfg.style !== null
308
+ ? StyleMapper_js_1.mapButtonStyle(cfg.style)
309
+ : cfg.url
310
+ ? discord_js_1.ButtonStyle.Link
311
+ : StyleMapper_js_1.getDefaultButtonStyle();
312
+
313
+ button.setStyle(resolvedStyle);
314
+
315
+ const parsedEmoji = cfg.emoji ? helpers_js_1.parseEmoji(cfg.emoji) : null;
316
+ const hasLabel = cfg.label !== undefined && cfg.label !== null && String(cfg.label) !== "";
317
+
318
+ if (hasLabel) {
319
+ button.setLabel(String(cfg.label));
320
+ }
321
+ if (parsedEmoji) {
322
+ button.setEmoji(parsedEmoji);
323
+ }
324
+
325
+ const isLink = resolvedStyle === discord_js_1.ButtonStyle.Link;
326
+ const isPremium = discord_js_1.ButtonStyle.Premium !== undefined && resolvedStyle === discord_js_1.ButtonStyle.Premium;
327
+
328
+ if (!hasLabel && !parsedEmoji && !isPremium) {
329
+ throw new Error("[ComponentsV2Builder] A button requires a label, an emoji, or Premium skuId.");
330
+ }
331
+
332
+ if (isLink) {
333
+ if (!helpers_js_1.isValidLinkUrl(cfg.url)) {
334
+ throw new Error(`[ComponentsV2Builder] Link buttons require a valid http(s)/discord URL (received: ${String(cfg.url)}).`);
335
+ }
336
+ button.setURL(String(cfg.url).trim());
337
+ } else if (isPremium) {
338
+ if (!cfg.skuId) {
339
+ throw new Error("[ComponentsV2Builder] Premium buttons require a valid skuId.");
340
+ }
341
+ button.setSKUId(String(cfg.skuId));
342
+ } else {
343
+ const id = cfg.customId ?? cfg.id ?? helpers_js_1.generateCustomId("btn");
344
+ button.setCustomId(String(id));
345
+ }
346
+
347
+ if (cfg.disabled !== undefined) {
348
+ button.setDisabled(Boolean(cfg.disabled));
349
+ }
350
+
351
+ return button;
352
+ }
353
+
354
+ #normalizeTextInput(content, options = {}) {
355
+ if (content instanceof discord_js_1.TextDisplayBuilder) {
356
+ return content.data?.content ?? "";
357
+ }
358
+ if (Array.isArray(content)) {
359
+ const lines = content
360
+ .filter((line) => line !== false && line !== null && line !== undefined)
361
+ .map((line) => (line instanceof discord_js_1.TextDisplayBuilder ? line.data?.content ?? "" : String(line)))
362
+ .filter((line) => line.trim().length > 0);
363
+ return lines.join(options.joinWith ?? "\n");
364
+ }
365
+ return content;
366
+ }
72
367
 
73
368
  /**
74
- * Flush any pending buttons into an ActionRow inside the container.
369
+ * Sets or clears the accent color of the active container.
75
370
  */
76
- _flushButtons() {
77
- if (this._pendingButtons.length === 0) return;
78
- const row = new discord_js_1.ActionRowBuilder().addComponents(...this._pendingButtons);
79
- this._container.addActionRowComponents(row);
80
- this._pendingButtons = [];
371
+ setColor(color) {
372
+ if (color === null) {
373
+ this.#activeContainerEntry.builder.clearAccentColor();
374
+ return this;
375
+ }
376
+ const resolved = helpers_js_1.resolveAccentColor(color);
377
+ if (resolved !== null) {
378
+ this.#activeContainerEntry.builder.setAccentColor(resolved);
379
+ }
380
+ return this;
81
381
  }
82
382
 
83
- // ─── Public API ──────────────────────────────────────────────────────────
383
+ /**
384
+ * Alias of `setColor(color)`.
385
+ */
386
+ setAccentColor(color) {
387
+ return this.setColor(color);
388
+ }
84
389
 
85
390
  /**
86
- * Add a text display (markdown supported) to the container.
391
+ * Sets whether the active container is marked as a spoiler.
87
392
  */
88
- addText(content) {
89
- helpers_js_1.validateTextContent(content);
90
- this._flushButtons();
91
- this._container.addTextDisplayComponents(
92
- new discord_js_1.TextDisplayBuilder().setContent(content)
93
- );
393
+ setSpoiler(spoiler = true) {
394
+ this.#activeContainerEntry.builder.setSpoiler(Boolean(spoiler));
94
395
  return this;
95
396
  }
96
397
 
97
398
  /**
98
- * Add a separator to the container.
99
- *
100
- * @param spacing - "small" | "large" (defaults to "small")
101
- * @param divider - Whether to render a visual divider line (defaults to true)
399
+ * Starts a new ContainerBuilder (switching placement back to `"inside"`).
102
400
  */
103
- addSeparator(spacing, divider) {
104
- this._flushButtons();
105
- const spacingValue =
106
- spacing === "large"
107
- ? discord_js_1.SeparatorSpacingSize.Large
108
- : discord_js_1.SeparatorSpacingSize.Small;
109
- const sep = new discord_js_1.SeparatorBuilder()
110
- .setSpacing(spacingValue)
111
- .setDivider(divider !== false);
112
- this._container.addSeparatorComponents(sep);
401
+ addContainer(options = {}) {
402
+ this.#flushPendingRow();
403
+ const nextEntry = this.#createContainerEntry(options);
404
+ if (
405
+ !this.#activeContainerEntry.hasContent &&
406
+ !this.#activeContainerEntry.attached &&
407
+ this.#topLevel.length === 0
408
+ ) {
409
+ this.#activeContainerEntry = nextEntry;
410
+ } else {
411
+ this.#activeContainerEntry = nextEntry;
412
+ this.#ensureContainerAttached(nextEntry);
413
+ }
414
+ this.#placement = "inside";
415
+ this.#lastKindByTarget.inside = null;
113
416
  return this;
114
417
  }
115
418
 
116
419
  /**
117
- * Add a single button to the container.
118
- * Buttons are batched and placed into ActionRows automatically (max 5 per row).
119
- *
120
- * @param label - Button label text
121
- * @param customId - Custom ID (or URL for link buttons)
122
- * @param style - "primary" | "secondary" | "success" | "danger" | "link"
123
- * @param url - URL (only used when style is "link")
420
+ * Switches component placement outside the container (top-level message components).
124
421
  */
125
- addButton(label, customId, style, url) {
126
- const resolvedStyle = StyleMapper_js_1.mapButtonStyle(style);
422
+ outside() {
423
+ this.#flushPendingRow();
424
+ this.#placement = "outside";
425
+ return this;
426
+ }
427
+
428
+ /**
429
+ * Switches component placement back inside the active container (or creates one if `options.new` is true).
430
+ */
431
+ inside(options = {}) {
432
+ this.#flushPendingRow();
433
+ if (options?.new || options?.newContainer) {
434
+ return this.addContainer(options);
435
+ }
436
+ this.#placement = "inside";
437
+ if (options && (options.color !== undefined || options.accentColor !== undefined)) {
438
+ this.setColor(options.color !== undefined ? options.color : options.accentColor);
439
+ }
440
+ if (options?.spoiler !== undefined) {
441
+ this.setSpoiler(options.spoiler);
442
+ }
443
+ return this;
444
+ }
127
445
 
128
- // If we already have 5 buttons pending, flush them first
129
- if (this._pendingButtons.length >= 5) {
130
- this._flushButtons();
446
+ /**
447
+ * Adds a TextDisplay component. Pass `{ ignoreEmpty: true }` to skip empty/whitespace text safely.
448
+ */
449
+ addText(content, options = {}) {
450
+ if (content instanceof discord_js_1.TextDisplayBuilder) {
451
+ this.#appendComponent(content, "text");
452
+ return this;
453
+ }
454
+
455
+ const normalized = this.#normalizeTextInput(content, options);
456
+ if (!helpers_js_1.validateTextContent(normalized, options)) {
457
+ return this;
458
+ }
459
+
460
+ const finalText = options.maxLength ? helpers_js_1.clipText(normalized, options.maxLength) : String(normalized);
461
+ if (!helpers_js_1.validateTextContent(finalText, options)) {
462
+ return this;
131
463
  }
132
464
 
133
- const btn = new discord_js_1.ButtonBuilder()
134
- .setLabel(label)
135
- .setStyle(resolvedStyle);
465
+ const textComponent = new discord_js_1.TextDisplayBuilder().setContent(finalText);
466
+ this.#appendComponent(textComponent, "text");
467
+ return this;
468
+ }
136
469
 
137
- if (resolvedStyle === discord_js_1.ButtonStyle.Link) {
138
- if (!url) throw new Error("[ComponentsV2Builder] A link button requires a URL.");
139
- if (customId) {
140
- console.warn("[ComponentsV2Builder] customId is ignored for link buttons; use the 'url' parameter instead.");
470
+ /**
471
+ * Adds formatted key/value rows (`> **Label:** value`), filtering falsy/empty rows automatically.
472
+ */
473
+ addFields(rows, options = {}) {
474
+ const formatted = text_js_1.V2Text.fields(rows, options);
475
+ if (!formatted && options.omitIfEmpty !== false) {
476
+ return this;
477
+ }
478
+ if (!formatted) return this;
479
+ return this.addText(formatted, options);
480
+ }
481
+
482
+ /**
483
+ * Adds an independent section block (`**Heading**\n> **Label:** value`) with optional divider before it.
484
+ */
485
+ addSectionBlock(heading, rows, options = {}) {
486
+ const formatted = text_js_1.V2Text.sectionBlock(heading, rows, options);
487
+ if (!formatted) return this;
488
+
489
+ const targetHasContent =
490
+ this.#placement === "outside"
491
+ ? this.#topLevel.some((e) => e.kind === "outside")
492
+ : this.#activeContainerEntry.hasContent;
493
+
494
+ const wantsSeparator = options.separator !== false;
495
+ const lastKind = this.#lastKindByTarget[this.#placement];
496
+ if (targetHasContent && wantsSeparator && lastKind !== "separator") {
497
+ const spacing = typeof options.separator === "string" ? options.separator : "small";
498
+ this.addSeparator(spacing, true);
499
+ }
500
+
501
+ return this.addText(formatted, options);
502
+ }
503
+
504
+ /**
505
+ * Adds a blockquote TextDisplay block.
506
+ */
507
+ addQuote(text, options = {}) {
508
+ if (options.ignoreEmpty && (text === undefined || text === null || String(text).trim() === "")) {
509
+ return this;
510
+ }
511
+ const quoted = text_js_1.V2Text.quote(text, options.maxLength, options.fallback);
512
+ if (!quoted) return this;
513
+ return this.addText(quoted, options);
514
+ }
515
+
516
+ /**
517
+ * Adds text while protecting against Discord V2 text length limits (`overflow: "file" | "clip" | "split"`).
518
+ */
519
+ addSmartText(text, options = {}) {
520
+ const raw = String(text ?? "");
521
+ if (raw.trim().length === 0) {
522
+ if (options.ignoreEmpty) return this;
523
+ helpers_js_1.validateTextContent(raw, options);
524
+ }
525
+
526
+ const budgetLeft = this.remainingChars;
527
+ const hardLimit = options.maxLength ?? helpers_js_1.SAFE_V2_TEXT_LENGTH;
528
+ const effectiveLimit = Math.max(0, Math.min(hardLimit, budgetLeft));
529
+
530
+ if (raw.length <= effectiveLimit && effectiveLimit > 0) {
531
+ return this.addText(options.codeBlock ? `\`\`\`${options.codeBlock}\n${raw}\n\`\`\`` : raw);
532
+ }
533
+
534
+ const overflow = options.overflow || "file";
535
+
536
+ if (overflow === "clip") {
537
+ if (effectiveLimit <= 0) return this;
538
+ const clipped = helpers_js_1.clipText(raw, effectiveLimit);
539
+ return this.addText(clipped, { ignoreEmpty: true });
540
+ }
541
+
542
+ if (overflow === "split") {
543
+ const chunkSize = Math.min(options.chunkSize ?? 1900, helpers_js_1.SAFE_V2_TEXT_LENGTH);
544
+ const chunks = splitTextIntoChunks(raw, chunkSize);
545
+ const overflowChunks = [];
546
+
547
+ for (const chunk of chunks) {
548
+ const canFitChars = this.remainingChars;
549
+ const canFitComponents = this.remainingComponents;
550
+ if (chunk.length <= canFitChars && canFitComponents >= 2) {
551
+ this.addText(chunk);
552
+ } else {
553
+ overflowChunks.push(chunk);
554
+ }
555
+ }
556
+
557
+ if (overflowChunks.length > 0) {
558
+ const leftover = overflowChunks.join("\n\n");
559
+ if (options.fallbackToFile !== false) {
560
+ this.addFile(Buffer.from(raw, "utf8"), {
561
+ name: options.filename || "output.txt",
562
+ description: options.fileDescription,
563
+ spoiler: options.spoiler,
564
+ });
565
+ } else if (this.remainingChars > 10) {
566
+ this.addText(helpers_js_1.clipText(leftover, this.remainingChars), { ignoreEmpty: true });
567
+ }
568
+ }
569
+ return this;
570
+ }
571
+
572
+ // overflow === "file"
573
+ const filename = options.filename || "output.txt";
574
+ const notice = options.overflowNotice ?? `-# Contenido completo adjunto en \`${sanitizeAttachmentName(filename, "output.txt")}\`.`;
575
+
576
+ if (options.preview !== false) {
577
+ const codePrefix = options.codeBlock ? `\`\`\`${options.codeBlock}\n` : "";
578
+ const codeSuffix = options.codeBlock ? "\n```" : "";
579
+ const overhead = codePrefix.length + codeSuffix.length + (notice ? notice.length + 2 : 0);
580
+ const maxPreviewLen = Math.min(options.previewLimit ?? 600, Math.max(0, effectiveLimit - overhead));
581
+
582
+ if (maxPreviewLen >= 40) {
583
+ const clippedPreview = helpers_js_1.clipText(raw, maxPreviewLen);
584
+ const body = `${codePrefix}${clippedPreview}${codeSuffix}${notice ? `\n${notice}` : ""}`;
585
+ this.addText(body, { ignoreEmpty: true });
586
+ } else if (notice && notice.length <= effectiveLimit) {
587
+ this.addText(notice, { ignoreEmpty: true });
588
+ }
589
+ }
590
+
591
+ return this.addFile(Buffer.from(raw, "utf8"), {
592
+ name: filename,
593
+ description: options.fileDescription,
594
+ spoiler: options.spoiler,
595
+ });
596
+ }
597
+
598
+ /**
599
+ * Adds a Section (1-3 TextDisplay components paired with a Thumbnail or Button accessory).
600
+ * Falls back to `addText` automatically when no valid accessory is supplied (unless `fallbackToText: false`).
601
+ */
602
+ addSection(texts, accessoryOrOptions = {}) {
603
+ let options = {};
604
+ let thumbnailAccessory = null;
605
+ let buttonAccessory = null;
606
+
607
+ if (accessoryOrOptions instanceof discord_js_1.ThumbnailBuilder) {
608
+ thumbnailAccessory = accessoryOrOptions;
609
+ } else if (accessoryOrOptions instanceof discord_js_1.ButtonBuilder) {
610
+ buttonAccessory = accessoryOrOptions;
611
+ } else if (accessoryOrOptions && typeof accessoryOrOptions === "object") {
612
+ options = accessoryOrOptions;
613
+ if (options.thumbnail instanceof discord_js_1.ThumbnailBuilder) {
614
+ thumbnailAccessory = options.thumbnail;
615
+ } else if (options.thumbnail) {
616
+ const thumbCfg = typeof options.thumbnail === "string" ? { url: options.thumbnail } : options.thumbnail;
617
+ if (thumbCfg && helpers_js_1.isValidMediaUrl(thumbCfg.url)) {
618
+ thumbnailAccessory = new discord_js_1.ThumbnailBuilder().setURL(thumbCfg.url.trim());
619
+ const desc = thumbCfg.description ?? options.thumbnailDescription;
620
+ if (desc) thumbnailAccessory.setDescription(String(desc));
621
+ const spoiler = thumbCfg.spoiler ?? options.thumbnailSpoiler;
622
+ if (spoiler !== undefined) thumbnailAccessory.setSpoiler(Boolean(spoiler));
623
+ }
624
+ }
625
+
626
+ if (!thumbnailAccessory && options.button) {
627
+ buttonAccessory = this.#createButton(options.button);
628
+ }
629
+ }
630
+
631
+ const textBuilders = [];
632
+ if (Array.isArray(texts) && texts.some((item) => item instanceof discord_js_1.TextDisplayBuilder)) {
633
+ for (const item of texts) {
634
+ if (!item) continue;
635
+ if (item instanceof discord_js_1.TextDisplayBuilder) {
636
+ textBuilders.push(item);
637
+ } else {
638
+ const str = String(item).trim();
639
+ if (str) textBuilders.push(new discord_js_1.TextDisplayBuilder().setContent(str));
640
+ }
141
641
  }
142
- btn.setURL(url);
143
642
  } else {
144
- btn.setCustomId(customId ?? helpers_js_1.generateCustomId("btn"));
643
+ const normalized = this.#normalizeTextInput(texts, options);
644
+ if (!helpers_js_1.validateTextContent(normalized, options)) {
645
+ return this;
646
+ }
647
+ const finalText = options.maxLength ? helpers_js_1.clipText(normalized, options.maxLength) : String(normalized);
648
+ textBuilders.push(new discord_js_1.TextDisplayBuilder().setContent(finalText));
145
649
  }
146
650
 
147
- this._pendingButtons.push(btn);
651
+ if (textBuilders.length === 0) {
652
+ if (options.ignoreEmpty) return this;
653
+ throw new Error("[ComponentsV2Builder] Section requires at least one non-empty text display.");
654
+ }
655
+
656
+ if (!thumbnailAccessory && !buttonAccessory) {
657
+ if (options.fallbackToText !== false) {
658
+ for (const tb of textBuilders) {
659
+ this.#appendComponent(tb, "text");
660
+ }
661
+ return this;
662
+ }
663
+ throw new Error("[ComponentsV2Builder] Section requires a valid thumbnail URL or button accessory.");
664
+ }
665
+
666
+ if (textBuilders.length > 3) {
667
+ const merged = textBuilders.map((tb) => tb.data?.content || "").filter(Boolean).join("\n");
668
+ textBuilders.length = 0;
669
+ textBuilders.push(new discord_js_1.TextDisplayBuilder().setContent(merged));
670
+ }
671
+
672
+ const section = new discord_js_1.SectionBuilder().addTextDisplayComponents(...textBuilders);
673
+ if (thumbnailAccessory) {
674
+ section.setThumbnailAccessory(thumbnailAccessory);
675
+ } else if (buttonAccessory) {
676
+ section.setButtonAccessory(buttonAccessory);
677
+ }
678
+
679
+ this.#appendComponent(section, "section");
148
680
  return this;
149
681
  }
150
682
 
151
683
  /**
152
- * Add multiple pre-built ButtonBuilder instances at once.
153
- * They are batched into ActionRows automatically (max 5 per row).
684
+ * Adds a MediaGallery component (`http://`, `https://`, or `attachment://` URLs).
154
685
  */
155
- addButtons(...buttons) {
156
- for (const btn of buttons) {
157
- if (this._pendingButtons.length >= 5) {
158
- this._flushButtons();
686
+ addGallery(itemsOrUrl, options = {}) {
687
+ if (itemsOrUrl instanceof discord_js_1.MediaGalleryBuilder) {
688
+ this.#appendComponent(itemsOrUrl, "gallery");
689
+ return this;
690
+ }
691
+
692
+ const rawList = Array.isArray(itemsOrUrl) ? itemsOrUrl : [itemsOrUrl];
693
+ const validItems = [];
694
+
695
+ for (const entry of rawList) {
696
+ if (!entry) {
697
+ if (options.ignoreEmpty || options.ignoreInvalid) continue;
698
+ if (!Array.isArray(itemsOrUrl)) {
699
+ throw new Error("[ComponentsV2Builder] Invalid or empty media URL for MediaGallery.");
700
+ }
701
+ continue;
702
+ }
703
+
704
+ if (entry instanceof discord_js_1.MediaGalleryItemBuilder) {
705
+ validItems.push(entry);
706
+ continue;
707
+ }
708
+
709
+ const cfg = typeof entry === "string" ? { url: entry } : entry;
710
+ const url = cfg?.url;
711
+ if (!helpers_js_1.isValidMediaUrl(url)) {
712
+ if (options.ignoreInvalid) continue;
713
+ throw new Error(`[ComponentsV2Builder] Invalid media URL for MediaGallery: ${String(url)}`);
714
+ }
715
+
716
+ const item = new discord_js_1.MediaGalleryItemBuilder().setURL(url.trim());
717
+ const desc = cfg.description ?? options.description;
718
+ if (desc) item.setDescription(String(desc));
719
+ const spoiler = cfg.spoiler ?? options.spoiler;
720
+ if (spoiler !== undefined) item.setSpoiler(Boolean(spoiler));
721
+ validItems.push(item);
722
+ }
723
+
724
+ if (validItems.length === 0) {
725
+ if (options.ignoreEmpty || options.ignoreInvalid) return this;
726
+ throw new Error("[ComponentsV2Builder] MediaGallery requires at least one valid media item.");
727
+ }
728
+
729
+ if (validItems.length > 10 && !options.autoSplit) {
730
+ throw new Error("[ComponentsV2Builder] A MediaGallery cannot contain more than 10 items.");
731
+ }
732
+
733
+ for (let i = 0; i < validItems.length; i += 10) {
734
+ const slice = validItems.slice(i, i + 10);
735
+ const gallery = new discord_js_1.MediaGalleryBuilder().addItems(...slice);
736
+ this.#appendComponent(gallery, "gallery");
737
+ }
738
+ return this;
739
+ }
740
+
741
+ /**
742
+ * Attaches an AttachmentBuilder without emitting a File component (useful for `attachment://` galleries/thumbnails).
743
+ */
744
+ addAttachment(source, options = {}) {
745
+ if (source instanceof discord_js_1.AttachmentBuilder) {
746
+ if (options.name) source.setName(sanitizeAttachmentName(options.name));
747
+ if (options.description) source.setDescription(String(options.description));
748
+ this.#files.push(source);
749
+ return this;
750
+ }
751
+
752
+ const defaultName = typeof source === "string" ? path_1.basename(source) : "file.bin";
753
+ const filename = sanitizeAttachmentName(options.name || defaultName);
754
+ const attachmentOptions = { name: filename };
755
+ if (options.description) attachmentOptions.description = String(options.description);
756
+
757
+ const attachment = new discord_js_1.AttachmentBuilder(source, attachmentOptions);
758
+ this.#files.push(attachment);
759
+ return this;
760
+ }
761
+
762
+ /**
763
+ * Adds a File component and automatically registers its AttachmentBuilder in `files`.
764
+ * If `source` is already an `attachment://...` URL, adds only the File component.
765
+ */
766
+ addFile(source, options = {}) {
767
+ if (source instanceof discord_js_1.FileBuilder) {
768
+ this.#appendComponent(source, "file");
769
+ return this;
770
+ }
771
+
772
+ let attachmentUrl;
773
+ if (typeof source === "string" && /^attachment:\/\/[^\s/]+$/i.test(source.trim())) {
774
+ attachmentUrl = source.trim();
775
+ if (options.attachment) {
776
+ this.addAttachment(options.attachment, options);
777
+ }
778
+ } else if (source instanceof discord_js_1.AttachmentBuilder) {
779
+ const name = sanitizeAttachmentName(options.name || source.name || "file.bin");
780
+ if (!source.name) source.setName(name);
781
+ this.addAttachment(source, { ...options, name });
782
+ attachmentUrl = `attachment://${source.name}`;
783
+ } else {
784
+ const defaultName = typeof source === "string" ? path_1.basename(source) : "file.bin";
785
+ const name = sanitizeAttachmentName(options.name || defaultName);
786
+ this.addAttachment(source, { ...options, name });
787
+ attachmentUrl = `attachment://${name}`;
788
+ }
789
+
790
+ const fileBuilder = new discord_js_1.FileBuilder().setURL(attachmentUrl);
791
+ if (options.spoiler !== undefined) {
792
+ fileBuilder.setSpoiler(Boolean(options.spoiler));
793
+ }
794
+ this.#appendComponent(fileBuilder, "file");
795
+ return this;
796
+ }
797
+
798
+ /**
799
+ * Adds a visual separator or empty spacer (`divider: false`).
800
+ */
801
+ addSeparator(spacing = "small", divider = true) {
802
+ let spacingArg = spacing;
803
+ let dividerArg = divider;
804
+
805
+ if (spacing && typeof spacing === "object") {
806
+ spacingArg = spacing.spacing ?? "small";
807
+ dividerArg = spacing.divider !== undefined ? Boolean(spacing.divider) : true;
808
+ }
809
+
810
+ const size =
811
+ spacingArg === "large" || spacingArg === discord_js_1.SeparatorSpacingSize.Large
812
+ ? discord_js_1.SeparatorSpacingSize.Large
813
+ : discord_js_1.SeparatorSpacingSize.Small;
814
+
815
+ const separator = new discord_js_1.SeparatorBuilder().setSpacing(size).setDivider(Boolean(dividerArg));
816
+ this.#appendComponent(separator, "separator");
817
+ return this;
818
+ }
819
+
820
+ /**
821
+ * Shorthand for an invisible vertical spacer (`addSeparator(spacing, false)`).
822
+ */
823
+ addSpacer(spacing = "small") {
824
+ return this.addSeparator(spacing, false);
825
+ }
826
+
827
+ /**
828
+ * Adds a button to the current button ActionRow (creating a new row automatically at 5 buttons).
829
+ * Supports both an options object `{ label, customId, id, style, url, emoji, disabled }`
830
+ * and legacy positional args `(label, customId, style, url)`.
831
+ */
832
+ addButton(labelOrConfig, customId, style, url, extraOptions) {
833
+ const button = this.#createButton(labelOrConfig, customId, style, url, extraOptions);
834
+ this.#ensureActionRow().addComponents(button);
835
+ return this;
836
+ }
837
+
838
+ /**
839
+ * Adds a dedicated ActionRow containing up to 5 buttons (flushes any previous open button row).
840
+ */
841
+ addButtons(buttons, options = {}) {
842
+ this.#flushPendingRow();
843
+ const list = (Array.isArray(buttons) ? buttons : []).filter(Boolean);
844
+ if (list.length === 0) return this;
845
+
846
+ if (!options.autoWrap) {
847
+ helpers_js_1.validateButtonCount(list.length);
848
+ }
849
+
850
+ for (let i = 0; i < list.length; i += 5) {
851
+ const chunk = list.slice(i, i + 5);
852
+ const row = new discord_js_1.ActionRowBuilder();
853
+ for (const item of chunk) {
854
+ if (Array.isArray(item)) {
855
+ row.addComponents(this.#createButton(item[0], item[1], item[2], item[3], item[4]));
856
+ } else {
857
+ row.addComponents(this.#createButton(item));
858
+ }
159
859
  }
160
- this._pendingButtons.push(btn);
860
+ this.#appendDirect(row, "actionRow", this.#placement);
161
861
  }
862
+
162
863
  return this;
163
864
  }
164
865
 
165
866
  /**
166
- * Add a StringSelectMenu to the container and return a SelectMenuProxy
167
- * for adding options via a fluent sub-chain. Call `.end()` on the proxy
168
- * to return to this builder.
169
- *
170
- * @param customId - Custom ID for the select menu
171
- * @param placeholder - Placeholder text (optional)
867
+ * Alias of `addButtons(buttons, options)` for explicit ActionRow ergonomics.
868
+ */
869
+ addButtonsRow(buttons, options = {}) {
870
+ return this.addButtons(buttons, options);
871
+ }
872
+
873
+ /**
874
+ * Starts a legacy chained StringSelectMenu (`SelectMenuProxy`) OR adds a full select menu
875
+ * when passed an options object `{ customId, type, placeholder, options, ... }`.
172
876
  */
173
- addSelectMenu(customId, placeholder) {
174
- this._flushButtons();
175
- const menu = new discord_js_1.StringSelectMenuBuilder()
176
- .setCustomId(customId ?? helpers_js_1.generateCustomId("sel"))
177
- .setPlaceholder(placeholder ?? "Select an option...");
877
+ addSelectMenu(customIdOrConfig, placeholder = "Select an option") {
878
+ if (customIdOrConfig && typeof customIdOrConfig === "object") {
879
+ return this.addSelectRow(customIdOrConfig);
880
+ }
881
+
882
+ this.#flushPendingRow();
883
+ const select = new discord_js_1.StringSelectMenuBuilder()
884
+ .setCustomId(String(customIdOrConfig || helpers_js_1.generateCustomId("select")))
885
+ .setPlaceholder(String(placeholder));
886
+
887
+ const row = new discord_js_1.ActionRowBuilder().addComponents(select);
888
+ this.#appendDirect(row, "actionRow", this.#placement);
889
+ return new SelectMenuProxy(this, select);
890
+ }
891
+
892
+ /**
893
+ * Adds an ActionRow containing any Discord select menu (`string`, `user`, `role`, `channel`, `mentionable`).
894
+ */
895
+ addSelectRow(config = {}) {
896
+ this.#flushPendingRow();
897
+ const type = SELECT_TYPE_MAP[String(config.type || "string").toLowerCase()] || "string";
898
+ const customId = String(config.customId ?? config.id ?? helpers_js_1.generateCustomId("select"));
899
+
900
+ let menu;
901
+ switch (type) {
902
+ case "user":
903
+ menu = new discord_js_1.UserSelectMenuBuilder();
904
+ if (Array.isArray(config.defaultUsers) && config.defaultUsers.length > 0) {
905
+ menu.setDefaultUsers(config.defaultUsers);
906
+ } else if (Array.isArray(config.defaultValues) && config.defaultValues.length > 0) {
907
+ menu.setDefaultUsers(config.defaultValues);
908
+ }
909
+ break;
910
+
911
+ case "role":
912
+ menu = new discord_js_1.RoleSelectMenuBuilder();
913
+ if (Array.isArray(config.defaultRoles) && config.defaultRoles.length > 0) {
914
+ menu.setDefaultRoles(config.defaultRoles);
915
+ } else if (Array.isArray(config.defaultValues) && config.defaultValues.length > 0) {
916
+ menu.setDefaultRoles(config.defaultValues);
917
+ }
918
+ break;
919
+
920
+ case "channel":
921
+ menu = new discord_js_1.ChannelSelectMenuBuilder();
922
+ if (Array.isArray(config.channelTypes) && config.channelTypes.length > 0) {
923
+ menu.setChannelTypes(config.channelTypes);
924
+ }
925
+ if (Array.isArray(config.defaultChannels) && config.defaultChannels.length > 0) {
926
+ menu.setDefaultChannels(config.defaultChannels);
927
+ } else if (Array.isArray(config.defaultValues) && config.defaultValues.length > 0) {
928
+ menu.setDefaultChannels(config.defaultValues);
929
+ }
930
+ break;
931
+
932
+ case "mentionable":
933
+ menu = new discord_js_1.MentionableSelectMenuBuilder();
934
+ if (Array.isArray(config.defaultValues) && config.defaultValues.length > 0) {
935
+ menu.setDefaultValues(config.defaultValues);
936
+ } else {
937
+ if (Array.isArray(config.defaultUsers) && config.defaultUsers.length > 0) {
938
+ menu.addDefaultUsers(config.defaultUsers);
939
+ }
940
+ if (Array.isArray(config.defaultRoles) && config.defaultRoles.length > 0) {
941
+ menu.addDefaultRoles(config.defaultRoles);
942
+ }
943
+ }
944
+ break;
945
+
946
+ case "string":
947
+ default: {
948
+ menu = new discord_js_1.StringSelectMenuBuilder();
949
+ const proxy = new SelectMenuProxy(this, menu);
950
+ if (Array.isArray(config.options) && config.options.length > 0) {
951
+ proxy.addOptions(config.options);
952
+ }
953
+ break;
954
+ }
955
+ }
956
+
957
+ menu.setCustomId(customId);
958
+ if (config.placeholder) menu.setPlaceholder(String(config.placeholder));
959
+ if (config.minValues !== undefined) menu.setMinValues(Number(config.minValues));
960
+ if (config.maxValues !== undefined) menu.setMaxValues(Number(config.maxValues));
961
+ if (config.disabled !== undefined) menu.setDisabled(Boolean(config.disabled));
178
962
 
179
- // We need to add the row after options are configured; the proxy returns
180
- // to us via `.end()` which flushes remaining buttons and adds the row.
181
- // To support immediate chaining, we attach the row now — options get added
182
- // by the proxy in-place (discord.js builders are mutable).
183
963
  const row = new discord_js_1.ActionRowBuilder().addComponents(menu);
184
- this._container.addActionRowComponents(row);
185
- return new SelectMenuProxy(this, menu);
964
+ this.#appendDirect(row, "actionRow", this.#placement);
965
+ return this;
966
+ }
967
+
968
+ addUserSelectMenu(configOrCustomId, options = {}) {
969
+ const cfg = typeof configOrCustomId === "string" ? { ...options, customId: configOrCustomId } : { ...configOrCustomId };
970
+ return this.addSelectRow({ ...cfg, type: "user" });
971
+ }
972
+
973
+ addRoleSelectMenu(configOrCustomId, options = {}) {
974
+ const cfg = typeof configOrCustomId === "string" ? { ...options, customId: configOrCustomId } : { ...configOrCustomId };
975
+ return this.addSelectRow({ ...cfg, type: "role" });
976
+ }
977
+
978
+ addChannelSelectMenu(configOrCustomId, options = {}) {
979
+ const cfg = typeof configOrCustomId === "string" ? { ...options, customId: configOrCustomId } : { ...configOrCustomId };
980
+ return this.addSelectRow({ ...cfg, type: "channel" });
981
+ }
982
+
983
+ addMentionableSelectMenu(configOrCustomId, options = {}) {
984
+ const cfg = typeof configOrCustomId === "string" ? { ...options, customId: configOrCustomId } : { ...configOrCustomId };
985
+ return this.addSelectRow({ ...cfg, type: "mentionable" });
186
986
  }
187
987
 
188
988
  /**
189
- * Mark the container as a spoiler (blurred until clicked).
989
+ * Adds a raw discord.js component builder respecting the current container/outside placement.
190
990
  */
191
- setSpoiler(spoiler) {
192
- this._container.setSpoiler(spoiler);
991
+ addComponent(component) {
992
+ if (!component) return this;
993
+ this.#flushPendingRow();
994
+
995
+ if (component instanceof discord_js_1.ContainerBuilder) {
996
+ this.#topLevel.push({ kind: "container", builder: component, hasContent: true, attached: true });
997
+ return this;
998
+ }
999
+
1000
+ const type = component?.data?.type;
1001
+ if (component instanceof discord_js_1.TextDisplayBuilder || type === (discord_js_1.ComponentType?.TextDisplay ?? 10)) {
1002
+ this.#appendDirect(component, "text", this.#placement);
1003
+ } else if (component instanceof discord_js_1.SeparatorBuilder || type === (discord_js_1.ComponentType?.Separator ?? 14)) {
1004
+ this.#appendDirect(component, "separator", this.#placement);
1005
+ } else if (component instanceof discord_js_1.SectionBuilder || type === (discord_js_1.ComponentType?.Section ?? 9)) {
1006
+ this.#appendDirect(component, "section", this.#placement);
1007
+ } else if (component instanceof discord_js_1.MediaGalleryBuilder || type === (discord_js_1.ComponentType?.MediaGallery ?? 12)) {
1008
+ this.#appendDirect(component, "gallery", this.#placement);
1009
+ } else if (component instanceof discord_js_1.FileBuilder || type === (discord_js_1.ComponentType?.File ?? 13)) {
1010
+ this.#appendDirect(component, "file", this.#placement);
1011
+ } else if (component instanceof discord_js_1.ActionRowBuilder || type === (discord_js_1.ComponentType?.ActionRow ?? 1)) {
1012
+ this.#appendDirect(component, "actionRow", this.#placement);
1013
+ } else {
1014
+ this.#topLevel.push({ kind: "outside", component });
1015
+ }
193
1016
  return this;
194
1017
  }
195
1018
 
196
1019
  /**
197
- * Build and return the components array ready to pass to
198
- * `interaction.reply({ components })`.
199
- *
200
- * The `MessageFlags.IsComponentsV2` flag is **not** added here because it
201
- * must be set on the reply options object itself, not inside the components
202
- * array. Use the helper `ComponentsV2Builder.flags` constant when replying:
203
- *
204
- * ```js
205
- * interaction.reply({ components: builder.build(), flags: ComponentsV2Builder.flags });
206
- * ```
1020
+ * Total character count across all TextDisplay components added so far.
207
1021
  */
208
- build() {
209
- this._flushButtons();
210
- return [this._container];
1022
+ get textLength() {
1023
+ return helpers_js_1.countTextLength(this.#snapshotComponents());
211
1024
  }
212
1025
 
213
- // ─── Static helpers ──────────────────────────────────────────────────────
1026
+ /**
1027
+ * Remaining characters before reaching Discord's 4,000-char V2 text display limit.
1028
+ */
1029
+ get remainingChars() {
1030
+ return Math.max(0, helpers_js_1.MAX_V2_TEXT_LENGTH - this.textLength);
1031
+ }
214
1032
 
215
1033
  /**
216
- * The MessageFlags bitmask required for Components V2 messages.
217
- *
218
- * ```js
219
- * interaction.reply({ components: builder.build(), flags: ComponentsV2Builder.flags });
220
- * ```
1034
+ * Total component count (including nested Container, Section, ActionRow, and MediaGallery items).
221
1035
  */
222
- static get flags() {
223
- return discord_js_1.MessageFlags.IsComponentsV2;
1036
+ get componentCount() {
1037
+ return helpers_js_1.countComponents(this.#snapshotComponents());
224
1038
  }
225
1039
 
226
- // ─── Quick Templates ─────────────────────────────────────────────────────
1040
+ /**
1041
+ * Remaining component budget before reaching Discord's 40-component V2 limit.
1042
+ */
1043
+ get remainingComponents() {
1044
+ return Math.max(0, helpers_js_1.MAX_V2_COMPONENTS - this.componentCount);
1045
+ }
227
1046
 
228
1047
  /**
229
- * Create a Confirm / Cancel button container.
230
- *
231
- * @param confirmId - Custom ID for the confirm button (default: "cv2_confirm")
232
- * @param cancelId - Custom ID for the cancel button (default: "cv2_cancel")
1048
+ * Shallow copy of all AttachmentBuilders registered via `.addFile()` or `.addAttachment()`.
233
1049
  */
234
- static createConfirm(confirmId, cancelId) {
235
- return new ComponentsV2Builder()
236
- .addText("**Are you sure?**")
237
- .addSeparator("small")
238
- .addButton("Confirm", confirmId ?? "cv2_confirm", "success")
239
- .addButton("Cancel", cancelId ?? "cv2_cancel", "danger");
1050
+ get files() {
1051
+ return [...this.#files];
1052
+ }
1053
+
1054
+ #snapshotComponents() {
1055
+ const out = [];
1056
+ for (const entry of this.#topLevel) {
1057
+ if (entry.kind === "container") {
1058
+ if (entry.hasContent) out.push(entry.builder);
1059
+ } else {
1060
+ out.push(entry.component);
1061
+ }
1062
+ }
1063
+ if (this.#currentRow && this.#currentRow.components?.length) {
1064
+ out.push(this.#currentRow);
1065
+ }
1066
+ return out;
240
1067
  }
241
1068
 
242
1069
  /**
243
- * Create a ticket category select menu container.
244
- *
245
- * @param customId - Custom ID for the select menu (default: "cv2_ticket_menu")
1070
+ * Builds and returns the array of top-level discord.js V2 component builders.
246
1071
  */
247
- static createTicketMenu(customId) {
248
- return new ComponentsV2Builder()
249
- .addText("## 🎫 Open a Ticket")
250
- .addSeparator("small")
251
- .addSelectMenu(customId ?? "cv2_ticket_menu", "Select a category...")
252
- .addOption("General Support", "ticket_general", "❓")
253
- .addOption("Billing", "ticket_billing", "💳")
254
- .addOption("Technical Issue", "ticket_tech", "🔧")
255
- .end();
1072
+ build() {
1073
+ this.#flushPendingRow();
1074
+ const result = [];
1075
+ for (const entry of this.#topLevel) {
1076
+ if (entry.kind === "container") {
1077
+ if (entry.hasContent) {
1078
+ result.push(entry.builder);
1079
+ }
1080
+ } else {
1081
+ result.push(entry.component);
1082
+ }
1083
+ }
1084
+
1085
+ if (result.length === 0 && this.#topLevel.length === 0) {
1086
+ return [this.#activeContainerEntry.builder];
1087
+ }
1088
+
1089
+ return result;
256
1090
  }
257
1091
 
258
1092
  /**
259
- * Create a plan selector container (bot / game / web hosting example).
260
- *
261
- * @param customId - Custom ID for the select menu (default: "cv2_plan_menu")
1093
+ * Serializes the built top-level components into plain JSON objects.
262
1094
  */
263
- static createPlanSelector(customId) {
264
- return new ComponentsV2Builder()
265
- .addText("## Welcome!\nPlease select the plan you want to join!")
266
- .addSeparator("small")
267
- .addButton("Discord Bot Hosting", "plan_bot", "primary")
268
- .addButton("Game Hosting", "plan_game", "success")
269
- .addButton("Web Hosting", "plan_web", "danger");
1095
+ toJSON() {
1096
+ return this.build().map((comp) => (typeof comp?.toJSON === "function" ? comp.toJSON() : comp));
270
1097
  }
271
1098
 
272
1099
  /**
273
- * Create a role selector menu container.
274
- *
275
- * @param customId - Custom ID for the select menu (default: "cv2_role_menu")
1100
+ * Builds a ready-to-send Discord message/interaction payload with `IsComponentsV2` flag,
1101
+ * optional ephemeral/notification flags, attached files, and safe `allowedMentions`.
276
1102
  */
277
- static createRoleMenu(customId) {
278
- return new ComponentsV2Builder()
279
- .addText("## 🎭 Select a Role")
280
- .addSeparator("small")
281
- .addSelectMenu(customId ?? "cv2_role_menu", "Choose your role...")
282
- .end();
1103
+ toPayload(options = {}) {
1104
+ const components = this.build();
1105
+ let flags = discord_js_1.MessageFlags.IsComponentsV2;
1106
+
1107
+ if (options.ephemeral) {
1108
+ flags |= discord_js_1.MessageFlags.Ephemeral;
1109
+ }
1110
+ if (options.suppressNotifications && discord_js_1.MessageFlags.SuppressNotifications !== undefined) {
1111
+ flags |= discord_js_1.MessageFlags.SuppressNotifications;
1112
+ }
1113
+ if (typeof options.flags === "number" && Number.isFinite(options.flags)) {
1114
+ flags |= options.flags;
1115
+ }
1116
+
1117
+ const extraFiles = Array.isArray(options.files) ? options.files.filter(Boolean) : [];
1118
+ const mergedFiles = [...this.#files, ...extraFiles];
1119
+
1120
+ const payload = {
1121
+ components,
1122
+ flags,
1123
+ };
1124
+
1125
+ if (mergedFiles.length > 0) {
1126
+ payload.files = mergedFiles;
1127
+ }
1128
+
1129
+ const useSafeMentions = options.safeMentions !== undefined ? options.safeMentions : this.#defaultSafeMentions;
1130
+ if (options.allowedMentions !== undefined) {
1131
+ payload.allowedMentions = options.allowedMentions;
1132
+ } else if (useSafeMentions) {
1133
+ payload.allowedMentions = { parse: [], repliedUser: false };
1134
+ }
1135
+
1136
+ return payload;
1137
+ }
1138
+
1139
+ // =========================================================================
1140
+ // Agnostic & legacy static template factories
1141
+ // =========================================================================
1142
+
1143
+ static card(options) {
1144
+ return templates.createCard(options);
1145
+ }
1146
+
1147
+ static imageView(options) {
1148
+ return templates.createImageView(options);
1149
+ }
1150
+
1151
+ static list(options) {
1152
+ return templates.createList(options);
1153
+ }
1154
+
1155
+ static confirm(confirmIdOrOptions, cancelId, title, message) {
1156
+ return templates.createConfirm(confirmIdOrOptions, cancelId, title, message);
1157
+ }
1158
+
1159
+ static createConfirm(confirmIdOrOptions, cancelId, title, message) {
1160
+ return templates.createConfirm(confirmIdOrOptions, cancelId, title, message);
1161
+ }
1162
+
1163
+ static createTicketMenu(customId, title, description) {
1164
+ return templates.createTicketMenu(customId, title, description);
1165
+ }
1166
+
1167
+ static createPlanSelector(customId, title, description) {
1168
+ return templates.createPlanSelector(customId, title, description);
1169
+ }
1170
+
1171
+ static createRoleMenu(customId, title, description) {
1172
+ return templates.createRoleMenu(customId, title, description);
283
1173
  }
284
1174
  }
1175
+
285
1176
  exports.ComponentsV2Builder = ComponentsV2Builder;