@mostfeatured/dbi 0.2.14 → 0.2.16
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/src/types/Components/HTMLComponentsV2/index.d.ts +35 -1
- package/dist/src/types/Components/HTMLComponentsV2/index.d.ts.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/index.js +416 -83
- package/dist/src/types/Components/HTMLComponentsV2/index.js.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/parser.d.ts +52 -0
- package/dist/src/types/Components/HTMLComponentsV2/parser.d.ts.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/parser.js +275 -0
- package/dist/src/types/Components/HTMLComponentsV2/parser.js.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteParser.d.ts +28 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteParser.d.ts.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteParser.js +478 -34
- package/dist/src/types/Components/HTMLComponentsV2/svelteParser.js.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteRenderer.d.ts +12 -0
- package/dist/src/types/Components/HTMLComponentsV2/svelteRenderer.d.ts.map +1 -1
- package/dist/src/types/Components/HTMLComponentsV2/svelteRenderer.js +102 -18
- package/dist/src/types/Components/HTMLComponentsV2/svelteRenderer.js.map +1 -1
- package/dist/test/index.js +76 -3
- package/dist/test/index.js.map +1 -1
- package/dist/test/test.d.ts +2 -0
- package/dist/test/test.d.ts.map +1 -0
- package/dist/test/test.js +7 -0
- package/dist/test/test.js.map +1 -0
- package/docs/ADVANCED_FEATURES.md +4 -0
- package/docs/API_REFERENCE.md +4 -0
- package/docs/CHAT_INPUT.md +4 -0
- package/docs/COMPONENTS.md +4 -0
- package/docs/EVENTS.md +4 -0
- package/docs/GETTING_STARTED.md +4 -0
- package/docs/LOCALIZATION.md +4 -0
- package/docs/README.md +4 -0
- package/docs/SVELTE_COMPONENTS.md +162 -6
- package/docs/llm/ADVANCED_FEATURES.txt +521 -0
- package/docs/llm/API_REFERENCE.txt +659 -0
- package/docs/llm/CHAT_INPUT.txt +514 -0
- package/docs/llm/COMPONENTS.txt +595 -0
- package/docs/llm/EVENTS.txt +449 -0
- package/docs/llm/GETTING_STARTED.txt +296 -0
- package/docs/llm/LOCALIZATION.txt +501 -0
- package/docs/llm/README.txt +193 -0
- package/docs/llm/SVELTE_COMPONENTS.txt +566 -0
- package/generated/svelte-dbi.d.ts +122 -0
- package/package.json +1 -1
- package/src/types/Components/HTMLComponentsV2/index.ts +478 -95
- package/src/types/Components/HTMLComponentsV2/parser.ts +317 -0
- package/src/types/Components/HTMLComponentsV2/svelteParser.ts +536 -35
- package/src/types/Components/HTMLComponentsV2/svelteRenderer.ts +121 -20
- package/test/index.ts +76 -3
- package/test/product-showcase.svelte +383 -24
- package/test/test.ts +3 -0
- package/llm.txt +0 -1088
|
@@ -7,15 +7,167 @@ const parser_1 = require("./parser");
|
|
|
7
7
|
const svelteRenderer_1 = require("./svelteRenderer");
|
|
8
8
|
const svelteParser_1 = require("./svelteParser");
|
|
9
9
|
const fs_1 = tslib_1.__importDefault(require("fs"));
|
|
10
|
+
/**
|
|
11
|
+
* Parse Discord API error and provide helpful context about which HTML element caused the error
|
|
12
|
+
*/
|
|
13
|
+
function parseDiscordAPIError(error, source, componentName) {
|
|
14
|
+
// Check if it's a Discord API error with form body issues
|
|
15
|
+
const message = error.message || '';
|
|
16
|
+
const rawError = error.rawError || error;
|
|
17
|
+
// Extract the path from error message like "data.components[0].components[0].accessory.media.url"
|
|
18
|
+
const pathMatch = message.match(/data\.components(\[[^\]]+\](?:\.[^\[\s\[]+|\[[^\]]+\])*)/);
|
|
19
|
+
if (!pathMatch) {
|
|
20
|
+
return error; // Not a parseable Discord API error
|
|
21
|
+
}
|
|
22
|
+
const errorPath = pathMatch[1];
|
|
23
|
+
const errorCode = message.match(/\[([A-Z_]+)\]/)?.[1] || 'UNKNOWN';
|
|
24
|
+
// Parse the path to understand the component structure
|
|
25
|
+
// e.g., "[0].components[0].accessory.media.url" -> component index 0, child 0, accessory.media.url
|
|
26
|
+
const parts = errorPath.split(/\.|\[|\]/).filter(Boolean);
|
|
27
|
+
// Build a human-readable path description
|
|
28
|
+
let description = '';
|
|
29
|
+
let elementHint = '';
|
|
30
|
+
let currentPath = [];
|
|
31
|
+
for (let i = 0; i < parts.length; i++) {
|
|
32
|
+
const part = parts[i];
|
|
33
|
+
if (!isNaN(Number(part))) {
|
|
34
|
+
currentPath.push(`[${part}]`);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
currentPath.push(part);
|
|
38
|
+
// Provide hints based on known Discord component structure
|
|
39
|
+
if (part === 'accessory') {
|
|
40
|
+
elementHint = '<section> element\'s accessory (thumbnail/button)';
|
|
41
|
+
}
|
|
42
|
+
else if (part === 'media') {
|
|
43
|
+
elementHint = '<thumbnail> or <media-gallery> element';
|
|
44
|
+
}
|
|
45
|
+
else if (part === 'url') {
|
|
46
|
+
elementHint = 'media URL attribute';
|
|
47
|
+
}
|
|
48
|
+
else if (part === 'components') {
|
|
49
|
+
// Skip, it's container
|
|
50
|
+
}
|
|
51
|
+
else if (part === 'content') {
|
|
52
|
+
elementHint = 'text content of a <text-display> element';
|
|
53
|
+
}
|
|
54
|
+
else if (part === 'label') {
|
|
55
|
+
elementHint = 'label attribute of a <button> or <option>';
|
|
56
|
+
}
|
|
57
|
+
else if (part === 'custom_id') {
|
|
58
|
+
elementHint = 'name attribute of an interactive element';
|
|
59
|
+
}
|
|
60
|
+
else if (part === 'placeholder') {
|
|
61
|
+
elementHint = 'placeholder attribute of a select menu';
|
|
62
|
+
}
|
|
63
|
+
else if (part === 'title') {
|
|
64
|
+
elementHint = 'title attribute of a <modal> or <section>';
|
|
65
|
+
}
|
|
66
|
+
else if (part === 'options') {
|
|
67
|
+
elementHint = '<option> elements inside a <string-select>';
|
|
68
|
+
}
|
|
69
|
+
else if (part === 'value') {
|
|
70
|
+
elementHint = 'value attribute of an <option> or <text-input>';
|
|
71
|
+
}
|
|
72
|
+
else if (part === 'description') {
|
|
73
|
+
elementHint = 'description attribute of an <option>';
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Map error codes to helpful messages
|
|
78
|
+
const errorMessages = {
|
|
79
|
+
'BASE_TYPE_REQUIRED': 'This field is required but was empty or undefined',
|
|
80
|
+
'STRING_TYPE_REQUIRED': 'This field must be a string',
|
|
81
|
+
'NUMBER_TYPE_REQUIRED': 'This field must be a number',
|
|
82
|
+
'BOOLEAN_TYPE_REQUIRED': 'This field must be a boolean',
|
|
83
|
+
'INVALID_URL': 'The URL provided is not valid',
|
|
84
|
+
'MAX_LENGTH': 'The value exceeds the maximum allowed length',
|
|
85
|
+
'MIN_LENGTH': 'The value is shorter than the minimum required length',
|
|
86
|
+
'CHOICE_NOT_FOUND': 'The selected value is not in the list of options',
|
|
87
|
+
};
|
|
88
|
+
const errorExplanation = errorMessages[errorCode] || `Error code: ${errorCode}`;
|
|
89
|
+
// Build the enhanced error message
|
|
90
|
+
let enhancedMessage = `
|
|
91
|
+
╔══════════════════════════════════════════════════════════════╗
|
|
92
|
+
║ Discord API Error - Invalid Component Data ║
|
|
93
|
+
╚══════════════════════════════════════════════════════════════╝
|
|
94
|
+
|
|
95
|
+
📍 Component: ${componentName || 'unknown'}
|
|
96
|
+
📍 Error Path: data.components${errorPath}
|
|
97
|
+
📍 Error Code: ${errorCode}
|
|
98
|
+
|
|
99
|
+
❌ ${errorExplanation}
|
|
100
|
+
${elementHint ? `\n💡 This error is likely in: ${elementHint}` : ''}
|
|
101
|
+
|
|
102
|
+
🔍 What to check:
|
|
103
|
+
`;
|
|
104
|
+
// Add specific suggestions based on error type
|
|
105
|
+
if (errorPath.includes('media.url')) {
|
|
106
|
+
enhancedMessage += ` • Make sure the image/media URL is provided and valid
|
|
107
|
+
• Check that the data property used for the image exists
|
|
108
|
+
• Example: <thumbnail media={product?.image}> - is product.image defined?
|
|
109
|
+
`;
|
|
110
|
+
}
|
|
111
|
+
else if (errorPath.includes('accessory')) {
|
|
112
|
+
enhancedMessage += ` • The <section> element requires valid content in its accessory
|
|
113
|
+
• If using <thumbnail>, ensure the media URL is valid
|
|
114
|
+
`;
|
|
115
|
+
}
|
|
116
|
+
else if (errorPath.includes('content')) {
|
|
117
|
+
enhancedMessage += ` • Text content cannot be empty or undefined
|
|
118
|
+
• Check your template expressions like {variable?.property}
|
|
119
|
+
`;
|
|
120
|
+
}
|
|
121
|
+
else if (errorPath.includes('options')) {
|
|
122
|
+
enhancedMessage += ` • Select menu options must have valid value and label
|
|
123
|
+
• Each <option> needs: value="..." and text content
|
|
124
|
+
`;
|
|
125
|
+
}
|
|
126
|
+
else if (errorPath.includes('label') || errorPath.includes('custom_id')) {
|
|
127
|
+
enhancedMessage += ` • Interactive elements (buttons, selects) need valid labels/names
|
|
128
|
+
• Check that text content and name attributes are not empty
|
|
129
|
+
`;
|
|
130
|
+
}
|
|
131
|
+
// If we have source, try to highlight relevant section
|
|
132
|
+
if (source && elementHint) {
|
|
133
|
+
const elementType = elementHint.match(/<(\w+-?\w*)>/)?.[1];
|
|
134
|
+
if (elementType) {
|
|
135
|
+
const elementRegex = new RegExp(`<${elementType}[^>]*>`, 'g');
|
|
136
|
+
const matches = source.match(elementRegex);
|
|
137
|
+
if (matches && matches.length > 0) {
|
|
138
|
+
enhancedMessage += `\n📝 Found ${matches.length} <${elementType}> element(s) in template:`;
|
|
139
|
+
matches.slice(0, 3).forEach((m, i) => {
|
|
140
|
+
enhancedMessage += `\n ${i + 1}. ${m.substring(0, 80)}${m.length > 80 ? '...' : ''}`;
|
|
141
|
+
});
|
|
142
|
+
if (matches.length > 3) {
|
|
143
|
+
enhancedMessage += `\n ... and ${matches.length - 3} more`;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const enhancedError = new Error(enhancedMessage);
|
|
149
|
+
enhancedError.originalError = error;
|
|
150
|
+
enhancedError.type = 'discord-api-error';
|
|
151
|
+
enhancedError.path = errorPath;
|
|
152
|
+
enhancedError.code = errorCode;
|
|
153
|
+
return enhancedError;
|
|
154
|
+
}
|
|
10
155
|
class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
11
156
|
template;
|
|
12
157
|
file;
|
|
13
158
|
mode = 'eta';
|
|
14
159
|
svelteComponentInfo = null;
|
|
15
160
|
_userOnExecute;
|
|
161
|
+
/** The directory of the source file (used for resolving relative imports) */
|
|
162
|
+
_sourceDir;
|
|
16
163
|
// Store handler contexts per ref for lifecycle management
|
|
17
164
|
// Key: ref id, Value: handlerContext with lifecycle hooks
|
|
18
165
|
_activeContexts = new Map();
|
|
166
|
+
// Store pending modal promises for await showModal() support
|
|
167
|
+
// Key: modal customId, Value: { resolve, reject } functions
|
|
168
|
+
_pendingModals = new Map();
|
|
169
|
+
// Track initialization promise
|
|
170
|
+
_initPromise = null;
|
|
19
171
|
constructor(dbi, args) {
|
|
20
172
|
// Store user's onExecute callback before passing to super
|
|
21
173
|
const userOnExecute = args.onExecute;
|
|
@@ -31,14 +183,19 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
31
183
|
this.name = args.name;
|
|
32
184
|
this.handlers = args.handlers || [];
|
|
33
185
|
this.mode = args.mode || 'eta';
|
|
186
|
+
// Store source directory for resolving relative imports in Svelte components
|
|
187
|
+
if (this.file) {
|
|
188
|
+
const path = require("path");
|
|
189
|
+
this._sourceDir = path.dirname(path.resolve(this.file));
|
|
190
|
+
}
|
|
34
191
|
// Store user's onExecute callback if provided
|
|
35
192
|
if (userOnExecute) {
|
|
36
193
|
this._userOnExecute = userOnExecute;
|
|
37
194
|
}
|
|
38
195
|
// Pre-extract Svelte handlers at registration time (lazy loaded)
|
|
39
196
|
if (this.mode === 'svelte' && this.template) {
|
|
40
|
-
//
|
|
41
|
-
this._initSvelteComponent();
|
|
197
|
+
// Store the promise so we can await it in _handleExecute
|
|
198
|
+
this._initPromise = this._initSvelteComponent();
|
|
42
199
|
}
|
|
43
200
|
// Re-assign onExecute method after super() call because parent class sets it to undefined
|
|
44
201
|
this.onExecute = this._handleExecute.bind(this);
|
|
@@ -48,7 +205,11 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
48
205
|
this.svelteComponentInfo = await (0, svelteParser_1.parseSvelteComponent)(this.template);
|
|
49
206
|
}
|
|
50
207
|
}
|
|
51
|
-
_handleExecute(ctx) {
|
|
208
|
+
async _handleExecute(ctx) {
|
|
209
|
+
// Wait for Svelte component initialization if not yet completed
|
|
210
|
+
if (this._initPromise) {
|
|
211
|
+
await this._initPromise;
|
|
212
|
+
}
|
|
52
213
|
// Call user's onExecute callback first if provided
|
|
53
214
|
if (this._userOnExecute) {
|
|
54
215
|
this._userOnExecute(ctx);
|
|
@@ -57,83 +218,158 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
57
218
|
if (this.mode === 'svelte' && this.svelteComponentInfo) {
|
|
58
219
|
const [elementName, ...handlerData] = ctx.data;
|
|
59
220
|
if (typeof elementName === 'string') {
|
|
60
|
-
//
|
|
221
|
+
// Check if this is a modal submit (elementName is the modal id)
|
|
222
|
+
const modalHandlerInfo = this.svelteComponentInfo.modalHandlers.get(elementName);
|
|
223
|
+
if (modalHandlerInfo) {
|
|
224
|
+
// This is a modal submit - execute the onsubmit handler (or just resolve promise if no handler)
|
|
225
|
+
this._executeModalSubmit(ctx, elementName, modalHandlerInfo.onsubmitHandler, handlerData);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
// Find the handler info for this element (button, select, etc.)
|
|
61
229
|
const handlerInfo = this.svelteComponentInfo.handlers.get(elementName);
|
|
62
230
|
if (handlerInfo) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
231
|
+
this._executeElementHandler(ctx, handlerInfo, handlerData);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Execute a modal submit handler
|
|
238
|
+
*/
|
|
239
|
+
_executeModalSubmit(ctx, modalId, handlerName, handlerData) {
|
|
240
|
+
// Extract current state from handlerData (refs that were passed)
|
|
241
|
+
const currentState = handlerData[0] || {};
|
|
242
|
+
// Get ref id for lifecycle tracking (if available)
|
|
243
|
+
const refId = currentState?.$ref || null;
|
|
244
|
+
// Extract all field values from modal interaction (text inputs, selects, file uploads, etc.)
|
|
245
|
+
const modalInteraction = ctx.interaction;
|
|
246
|
+
const fields = this._extractModalFields(modalInteraction);
|
|
247
|
+
// Check if there's a pending promise for this modal (from await showModal())
|
|
248
|
+
// Use the modal's customId to find the pending promise
|
|
249
|
+
const pendingKey = modalInteraction.customId;
|
|
250
|
+
const pendingModal = this._pendingModals.get(pendingKey);
|
|
251
|
+
if (pendingModal) {
|
|
252
|
+
// Resolve the promise with fields and interaction
|
|
253
|
+
pendingModal.resolve({
|
|
254
|
+
fields,
|
|
255
|
+
interaction: modalInteraction,
|
|
256
|
+
ctx: ctx
|
|
257
|
+
});
|
|
258
|
+
this._pendingModals.delete(pendingKey);
|
|
259
|
+
}
|
|
260
|
+
// If no onsubmit handler defined, just return (promise-based usage)
|
|
261
|
+
if (!handlerName) {
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
// Create handler context for modal submit
|
|
265
|
+
const handlerContext = (0, svelteParser_1.createHandlerContext)(this.svelteComponentInfo.scriptContent, typeof currentState === 'object' ? currentState : {}, this, ctx, this._sourceDir);
|
|
266
|
+
const handlerFn = handlerContext.handlers[handlerName];
|
|
267
|
+
if (handlerFn && typeof handlerFn === 'function') {
|
|
268
|
+
try {
|
|
269
|
+
// Store context for lifecycle management
|
|
270
|
+
if (refId) {
|
|
271
|
+
const existingContext = this._activeContexts.get(refId);
|
|
272
|
+
if (existingContext && existingContext.destroyCallbacks) {
|
|
273
|
+
handlerContext.destroyCallbacks.push(...existingContext.destroyCallbacks);
|
|
274
|
+
}
|
|
275
|
+
this._activeContexts.set(refId, handlerContext);
|
|
276
|
+
}
|
|
277
|
+
handlerContext.setInHandler(true);
|
|
278
|
+
try {
|
|
279
|
+
// Call handler with ctx and fields object
|
|
280
|
+
handlerFn.call(this, handlerContext.wrappedCtx, fields, ...handlerData.slice(1));
|
|
281
|
+
}
|
|
282
|
+
finally {
|
|
283
|
+
handlerContext.setInHandler(false);
|
|
284
|
+
}
|
|
285
|
+
handlerContext.runEffects();
|
|
286
|
+
if (handlerContext.hasPendingRender()) {
|
|
287
|
+
handlerContext.flushRender();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
// Modal handler execution failed
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Execute an element handler (button, select, etc.)
|
|
297
|
+
*/
|
|
298
|
+
_executeElementHandler(ctx, handlerInfo, handlerData) {
|
|
299
|
+
// Extract current state from handlerData (refs that were passed)
|
|
300
|
+
// The second element in data array contains the current state
|
|
301
|
+
const currentState = handlerData[0] || {};
|
|
302
|
+
// Get ref id for lifecycle tracking (if available)
|
|
303
|
+
const refId = currentState?.$ref || null;
|
|
304
|
+
// Check if this is first execution for this ref
|
|
305
|
+
const isFirstExecution = refId && !this._activeContexts.has(refId);
|
|
306
|
+
// Get existing context if any (to preserve lifecycle callbacks like intervals)
|
|
307
|
+
const existingContext = refId ? this._activeContexts.get(refId) : null;
|
|
308
|
+
// Create a NEW handler context for each execution with the current state
|
|
309
|
+
// This ensures each interaction has its own isolated state
|
|
310
|
+
// Pass 'this' so handlers can access component methods like toJSON()
|
|
311
|
+
// Pass ctx so handlers can access ctx.interaction, ctx.data, ctx.locale, etc.
|
|
312
|
+
const handlerContext = (0, svelteParser_1.createHandlerContext)(this.svelteComponentInfo.scriptContent, typeof currentState === 'object' ? currentState : {}, this, ctx, this._sourceDir);
|
|
313
|
+
const handlerFn = handlerContext.handlers[handlerInfo.handlerName];
|
|
314
|
+
if (handlerFn && typeof handlerFn === 'function') {
|
|
315
|
+
try {
|
|
316
|
+
// Store context for lifecycle management
|
|
317
|
+
if (refId) {
|
|
318
|
+
// If there's an existing context, transfer its destroy callbacks to the new context
|
|
319
|
+
// This preserves intervals/timers created in onMount
|
|
320
|
+
if (existingContext && existingContext.destroyCallbacks) {
|
|
321
|
+
// Merge existing destroy callbacks (don't run them!)
|
|
322
|
+
handlerContext.destroyCallbacks.push(...existingContext.destroyCallbacks);
|
|
323
|
+
}
|
|
324
|
+
this._activeContexts.set(refId, handlerContext);
|
|
325
|
+
// Wrap $unRef to call onDestroy when ref is deleted (only wrap once)
|
|
326
|
+
const stateObj = currentState;
|
|
327
|
+
if (stateObj.$unRef && !stateObj.__unRefWrapped__) {
|
|
328
|
+
const originalUnRef = stateObj.$unRef.bind(stateObj);
|
|
329
|
+
stateObj.$unRef = () => {
|
|
330
|
+
// Run destroy callbacks before unref
|
|
331
|
+
const ctx = this._activeContexts.get(refId);
|
|
332
|
+
if (ctx && ctx.runDestroy) {
|
|
333
|
+
ctx.runDestroy();
|
|
127
334
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
335
|
+
this._activeContexts.delete(refId);
|
|
336
|
+
return originalUnRef();
|
|
337
|
+
};
|
|
338
|
+
stateObj.__unRefWrapped__ = true;
|
|
132
339
|
}
|
|
133
340
|
}
|
|
341
|
+
// Run onMount callbacks only on first execution
|
|
342
|
+
if (isFirstExecution && handlerContext.runMount) {
|
|
343
|
+
handlerContext.runMount();
|
|
344
|
+
}
|
|
345
|
+
// Mark that we're inside handler execution (prevents auto-render during handler)
|
|
346
|
+
handlerContext.setInHandler(true);
|
|
347
|
+
try {
|
|
348
|
+
// Bind 'this' to the DBIHTMLComponentsV2 instance so handlers can use this.toJSON()
|
|
349
|
+
// Pass wrappedCtx so handlers use the proxy-wrapped ctx that tracks interaction calls
|
|
350
|
+
// This ensures __asyncInteractionCalled__ flag is set when handler calls ctx.interaction.reply() etc.
|
|
351
|
+
handlerFn.call(this, handlerContext.wrappedCtx, ...handlerData.slice(1));
|
|
352
|
+
}
|
|
353
|
+
finally {
|
|
354
|
+
// Always reset handler execution flag
|
|
355
|
+
handlerContext.setInHandler(false);
|
|
356
|
+
}
|
|
357
|
+
// Run effects after handler execution (state may have changed)
|
|
358
|
+
handlerContext.runEffects();
|
|
359
|
+
// If there are pending data changes and no interaction method was called,
|
|
360
|
+
// flush the render now (synchronously uses interaction.update)
|
|
361
|
+
if (handlerContext.hasPendingRender()) {
|
|
362
|
+
handlerContext.flushRender();
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
// Handler execution failed
|
|
134
367
|
}
|
|
135
368
|
}
|
|
136
369
|
}
|
|
370
|
+
// Store last render's modals for showModal() to access
|
|
371
|
+
// Note: Used internally by handler context, not truly private
|
|
372
|
+
__lastRenderModals__ = null;
|
|
137
373
|
async toJSON(arg = {}) {
|
|
138
374
|
if (this.mode === 'svelte' && this.template) {
|
|
139
375
|
// Render Svelte component
|
|
@@ -141,6 +377,8 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
141
377
|
data: arg.data,
|
|
142
378
|
ttl: this.ttl
|
|
143
379
|
});
|
|
380
|
+
// Store modals for showModal() to access
|
|
381
|
+
this.__lastRenderModals__ = result.modals;
|
|
144
382
|
return result.components;
|
|
145
383
|
}
|
|
146
384
|
else {
|
|
@@ -173,8 +411,12 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
173
411
|
* ```
|
|
174
412
|
*/
|
|
175
413
|
async send(target, options = {}) {
|
|
414
|
+
// Wait for Svelte component initialization if not yet completed
|
|
415
|
+
if (this._initPromise) {
|
|
416
|
+
await this._initPromise;
|
|
417
|
+
}
|
|
176
418
|
const { data = {}, flags = ["IsComponentsV2"], content, ephemeral, reply, followUp } = options;
|
|
177
|
-
// Render components (toJSON is async)
|
|
419
|
+
// Render components (toJSON is async) - this also creates $ref in data if not present
|
|
178
420
|
const components = await this.toJSON({ data });
|
|
179
421
|
// Build message options
|
|
180
422
|
const messageOptions = { components, flags };
|
|
@@ -186,21 +428,32 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
186
428
|
let message;
|
|
187
429
|
const isInteraction = target.reply && target.user; // Interactions have both reply method and user property
|
|
188
430
|
const isChannel = target.send && !target.user; // Channels have send but no user
|
|
189
|
-
|
|
190
|
-
if (
|
|
191
|
-
|
|
431
|
+
try {
|
|
432
|
+
if (isInteraction) {
|
|
433
|
+
if (followUp) {
|
|
434
|
+
message = await target.followUp(messageOptions);
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
message = await target.reply(messageOptions);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
else if (isChannel) {
|
|
441
|
+
message = await target.send(messageOptions);
|
|
192
442
|
}
|
|
193
443
|
else {
|
|
194
|
-
|
|
444
|
+
throw new Error("Invalid target: must be an interaction or channel");
|
|
195
445
|
}
|
|
196
446
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
447
|
+
catch (error) {
|
|
448
|
+
// Check if it's a Discord API error and enhance it with helpful context
|
|
449
|
+
if (error.code || error.rawError || (error.message && error.message.includes('Invalid Form Body'))) {
|
|
450
|
+
const source = this.file ? fs_1.default.readFileSync(this.file, 'utf-8') : this.template;
|
|
451
|
+
throw parseDiscordAPIError(error, source, this.name);
|
|
452
|
+
}
|
|
453
|
+
throw error;
|
|
202
454
|
}
|
|
203
455
|
// If Svelte mode, create initial handler context and run onMount
|
|
456
|
+
// After toJSON, data.$ref is guaranteed to exist (created in renderSvelteComponent)
|
|
204
457
|
if (this.mode === 'svelte' && this.svelteComponentInfo && data.$ref) {
|
|
205
458
|
const refId = data.$ref;
|
|
206
459
|
// Create handler context with a fake ctx that has the message
|
|
@@ -211,7 +464,7 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
211
464
|
message: message,
|
|
212
465
|
}
|
|
213
466
|
};
|
|
214
|
-
const handlerContext = (0, svelteParser_1.createHandlerContext)(this.svelteComponentInfo.scriptContent, data, this, fakeCtx);
|
|
467
|
+
const handlerContext = (0, svelteParser_1.createHandlerContext)(this.svelteComponentInfo.scriptContent, data, this, fakeCtx, this._sourceDir);
|
|
215
468
|
// Store the context for lifecycle management
|
|
216
469
|
this._activeContexts.set(refId, handlerContext);
|
|
217
470
|
// Wrap $unRef to call onDestroy when ref is deleted
|
|
@@ -268,6 +521,86 @@ class DBIHTMLComponentsV2 extends Interaction_1.DBIBaseInteraction {
|
|
|
268
521
|
this.dbi.data.refs.delete(refId);
|
|
269
522
|
return true;
|
|
270
523
|
}
|
|
524
|
+
/**
|
|
525
|
+
* Extract all field values from a modal interaction
|
|
526
|
+
* Supports text inputs, select menus (string, user, role, mentionable, channel), and file uploads
|
|
527
|
+
*
|
|
528
|
+
* Returns an object where keys are the custom_id of each component and values are:
|
|
529
|
+
* - For text inputs: string value
|
|
530
|
+
* - For string selects: string[] of selected values
|
|
531
|
+
* - For user selects: string[] of user IDs
|
|
532
|
+
* - For role selects: string[] of role IDs
|
|
533
|
+
* - For mentionable selects: { users: string[], roles: string[] }
|
|
534
|
+
* - For channel selects: string[] of channel IDs
|
|
535
|
+
* - For file uploads: attachment objects array
|
|
536
|
+
*/
|
|
537
|
+
_extractModalFields(modalInteraction) {
|
|
538
|
+
const fields = {};
|
|
539
|
+
// Handle classic text input fields via ModalSubmitFields
|
|
540
|
+
if (modalInteraction.fields && modalInteraction.fields.fields) {
|
|
541
|
+
for (const [customId, field] of modalInteraction.fields.fields) {
|
|
542
|
+
// Text input - field.value is the string
|
|
543
|
+
fields[customId] = field.value;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
// Handle new modal components from interaction.data.components
|
|
547
|
+
// The new modal structure uses Label wrappers with nested components
|
|
548
|
+
const data = modalInteraction.data || modalInteraction.data;
|
|
549
|
+
if (data && data.components) {
|
|
550
|
+
this._extractFieldsFromComponents(data.components, fields);
|
|
551
|
+
}
|
|
552
|
+
return fields;
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Recursively extract field values from component structure
|
|
556
|
+
*/
|
|
557
|
+
_extractFieldsFromComponents(components, fields) {
|
|
558
|
+
for (const component of components) {
|
|
559
|
+
const type = component.type;
|
|
560
|
+
const customId = component.custom_id;
|
|
561
|
+
// Type 18 = Label - has nested component
|
|
562
|
+
if (type === 18 && component.component) {
|
|
563
|
+
this._extractFieldsFromComponents([component.component], fields);
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
// Type 1 = Action Row - has nested components array
|
|
567
|
+
if (type === 1 && component.components) {
|
|
568
|
+
this._extractFieldsFromComponents(component.components, fields);
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
if (!customId)
|
|
572
|
+
continue;
|
|
573
|
+
switch (type) {
|
|
574
|
+
case 4: // Text Input
|
|
575
|
+
fields[customId] = component.value || '';
|
|
576
|
+
break;
|
|
577
|
+
case 3: // String Select
|
|
578
|
+
fields[customId] = component.values || [];
|
|
579
|
+
break;
|
|
580
|
+
case 5: // User Select
|
|
581
|
+
fields[customId] = component.values || [];
|
|
582
|
+
break;
|
|
583
|
+
case 6: // Role Select
|
|
584
|
+
fields[customId] = component.values || [];
|
|
585
|
+
break;
|
|
586
|
+
case 7: // Mentionable Select - can have both users and roles
|
|
587
|
+
// Discord returns resolved data for mentionables
|
|
588
|
+
fields[customId] = {
|
|
589
|
+
values: component.values || [],
|
|
590
|
+
users: component.resolved?.users ? Object.keys(component.resolved.users) : [],
|
|
591
|
+
roles: component.resolved?.roles ? Object.keys(component.resolved.roles) : []
|
|
592
|
+
};
|
|
593
|
+
break;
|
|
594
|
+
case 8: // Channel Select
|
|
595
|
+
fields[customId] = component.values || [];
|
|
596
|
+
break;
|
|
597
|
+
case 19: // File Upload
|
|
598
|
+
// File uploads come through as attachments
|
|
599
|
+
fields[customId] = component.attachments || [];
|
|
600
|
+
break;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
271
604
|
/**
|
|
272
605
|
* Destroy all active instances of this component
|
|
273
606
|
* Useful for cleanup when the bot shuts down or component is unloaded
|