nuxt-discord 0.0.13 → 0.0.14

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/README.md CHANGED
@@ -253,7 +253,7 @@ Here's what's planned for future releases:
253
253
  - [ ] Better JSDocs support JSDoc comments
254
254
  - [ ] Localization support
255
255
  - [ ] File-based subcommands
256
- - [ ] Auto-complete API
256
+ - [x] Auto-complete API
257
257
  - [ ] Guild-specific commands
258
258
  - [ ] Nuxt-devtools integration
259
259
  - [ ] Unit tests
package/dist/module.d.mts CHANGED
@@ -3,7 +3,7 @@ import * as __runtime_logger from '../dist/runtime/logger.js';
3
3
  import * as _nuxt_kit from '@nuxt/kit';
4
4
  import * as nuxt_schema from 'nuxt/schema';
5
5
  import { DiscordClient } from '/Users/jeffz/Dev/nuxt-discord/dist/runtime/server/utils/client.js';
6
- import { IntegerOption, NumberOption, StringOption } from '../dist/runtime/server/utils/describeOption.js';
6
+ import { IntegerOption, NumberOption, StringOption, DescribeOptionOptions } from '../dist/runtime/server/utils/describeOption.js';
7
7
  import { ClientOptions, ApplicationCommandOptionType, ChatInputCommandInteraction } from 'discord.js';
8
8
  import { ListenOptions } from 'listhen';
9
9
  import { MaybeRef } from 'vue';
@@ -93,6 +93,7 @@ interface SlashCommandOptionBase {
93
93
  description: string;
94
94
  type: ApplicationCommandOptionType;
95
95
  required: boolean;
96
+ hasAutocomplete: boolean;
96
97
  }
97
98
  interface SlashCommandIntegerOption extends SlashCommandOptionBase, Omit<IntegerOption, 'name' | 'description'> {
98
99
  type: ApplicationCommandOptionType.Integer;
@@ -113,13 +114,16 @@ interface SlashCommand {
113
114
  name: string;
114
115
  description: string;
115
116
  path: string;
116
- options: SlashCommandOption[];
117
+ options: (SlashCommandOption & {
118
+ varname: string;
119
+ })[];
117
120
  }
118
121
  interface SlashCommandRuntime extends SlashCommand {
119
122
  /** if execute is not defined load must be defined */
120
- load?: () => Promise<SlashCommandRuntime['execute']>;
123
+ load?: () => Promise<Pick<SlashCommandRuntime, 'execute' | 'optionMacros'>>;
121
124
  execute?: (...args: (SlashCommandOptionType | undefined)[]) => SlashCommandReturnType;
122
125
  id?: string;
126
+ optionMacros?: Record<string, DescribeOptionOptions>;
123
127
  }
124
128
  interface NuxtDiscordContext {
125
129
  nuxt: nuxt_schema.Nuxt;
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "configKey": "discord",
4
- "version": "0.0.13",
4
+ "version": "0.0.14",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.1",
7
7
  "unbuild": "3.5.0"
package/dist/module.mjs CHANGED
@@ -3,7 +3,7 @@ import { ApplicationCommandOptionType, GatewayIntentBits } from 'discord.js';
3
3
  import { logger } from '../dist/runtime/logger.js';
4
4
  import fs, { globSync, readFileSync } from 'node:fs';
5
5
  import path from 'node:path';
6
- import ts from 'typescript';
6
+ import ts, { isFunctionExpression, isArrowFunction } from 'typescript';
7
7
  import chokidar from 'chokidar';
8
8
  import { listen } from 'listhen';
9
9
  import { rollup } from 'rollup';
@@ -94,6 +94,8 @@ const macros = {
94
94
  const macroOptions = parseLiteral(node.arguments[1]);
95
95
  const validOptionKeys = ["name", "description", "min", "max", "minLength", "maxLength", "choices"];
96
96
  const isValidOptionKey = (key) => validOptionKeys.includes(key);
97
+ Reflect.deleteProperty(macroOptions, "autocomplete");
98
+ option.hasAutocomplete = node.arguments[1].properties.find((prop) => ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.escapedText === "autocomplete" || ts.isMethodDeclaration(prop) && ts.isIdentifier(prop.name) && prop.name.escapedText === "autocomplete") != null;
97
99
  for (const key in macroOptions) {
98
100
  if (!isValidOptionKey(key)) {
99
101
  ctx.logger.warn(`describeOption: unknown option key "${key}" for option "${name}" in command "${command.name}"`);
@@ -147,30 +149,25 @@ function parseLiteral(node) {
147
149
  return void 0;
148
150
  }
149
151
 
150
- function collectSlashCommands(ctx, out) {
152
+ function collectSlashCommands(ctx) {
151
153
  const commandFiles = globSync(`${ctx.resolve.root(ctx.options.dir, "commands")}/**/*.ts`);
152
- out ??= ctx.slashCommands;
154
+ ctx.slashCommands = [];
153
155
  for (const file of commandFiles) {
154
156
  const command = processCommandFile(ctx, file);
155
157
  if (command) {
156
- out.push(command);
158
+ ctx.slashCommands.push(command);
157
159
  }
158
160
  }
159
161
  }
160
162
  function processCommandFile(ctx, file) {
161
- const sourceFile = ts.createSourceFile(file, readFileSync(file).toString(), ts.ScriptTarget.Latest, true);
162
- let commandDefinition;
163
- ts.forEachChild(sourceFile, (node) => {
164
- if (ts.isExportAssignment(node)) {
165
- if (ts.isArrowFunction(node.expression)) {
166
- commandDefinition = node.expression;
167
- } else if (ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText === "defineSlashCommand" && (ts.isArrowFunction(node.expression.arguments[0]) || ts.isFunctionExpression(node.expression.arguments[0]))) {
168
- commandDefinition = node.expression.arguments[0];
169
- }
170
- } else if (ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
171
- commandDefinition = node;
172
- }
173
- });
163
+ const sourceFile = ts.createSourceFile(
164
+ file,
165
+ readFileSync(file).toString(),
166
+ ts.ScriptTarget.Latest,
167
+ /* setParentNodes */
168
+ true
169
+ );
170
+ const commandDefinition = extractCommandDefinition(sourceFile);
174
171
  if (!commandDefinition) {
175
172
  ctx.logger.warn(`No command definition found for ${file}`);
176
173
  return;
@@ -279,6 +276,8 @@ function processCommandFile(ctx, file) {
279
276
  type: typeIdentifierToEnum[type],
280
277
  description: jsdocDescription,
281
278
  required: !param.questionToken,
279
+ varname: name2,
280
+ hasAutocomplete: false,
282
281
  ...modifiers,
283
282
  ...choices ? {
284
283
  choices: choices.map((choice) => {
@@ -291,23 +290,53 @@ function processCommandFile(ctx, file) {
291
290
  } : {}
292
291
  });
293
292
  }
293
+ const [macroCalls, outOfRangMacroCalls] = extractMacroCalls(commandDefinition.body);
294
+ for (const macroCall of macroCalls) {
295
+ const macroName = macroCall.expression.escapedText;
296
+ macros[macroName](ctx, macroCall, command);
297
+ }
298
+ if (outOfRangMacroCalls.length > 0) {
299
+ ctx.logger.warn(`Macros in file ${file} must be called at the top of the file`);
300
+ }
301
+ return command;
302
+ }
303
+ function extractCommandDefinition(sourceFile) {
304
+ let commandDefinition;
305
+ ts.forEachChild(sourceFile, (node) => {
306
+ if (ts.isExportAssignment(node)) {
307
+ if (ts.isArrowFunction(node.expression)) {
308
+ commandDefinition = node.expression;
309
+ } else if (ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText === "defineSlashCommand" && (ts.isArrowFunction(node.expression.arguments[0]) || ts.isFunctionExpression(node.expression.arguments[0]))) {
310
+ commandDefinition = node.expression.arguments[0];
311
+ }
312
+ } else if (ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
313
+ commandDefinition = node;
314
+ }
315
+ });
316
+ return commandDefinition;
317
+ }
318
+ function extractMacroCalls(definitionBody) {
294
319
  let macrosEnd = false;
295
- let warned = false;
296
- ts.forEachChild(commandDefinition.body, (node) => {
297
- if (ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText in macros) {
320
+ const macroCalls = [];
321
+ const outOfRangMacroCalls = [];
322
+ ts.forEachChild(definitionBody, (node) => {
323
+ if (isMacroCallExpression(node)) {
298
324
  if (macrosEnd) {
299
- if (!warned) {
300
- ctx.logger.warn(`${node.expression.expression.escapedText} macro must be called at the top in file ${file}`);
301
- warned = true;
302
- }
325
+ outOfRangMacroCalls.push(node.expression);
303
326
  return;
304
327
  }
305
- macros[node.expression.expression.escapedText](ctx, node.expression, command);
328
+ macroCalls.push(node.expression);
306
329
  } else {
307
330
  macrosEnd = true;
308
331
  }
309
332
  });
310
- return command;
333
+ return [
334
+ macroCalls,
335
+ outOfRangMacroCalls
336
+ ];
337
+ }
338
+ function isMacroCallExpression(node) {
339
+ return ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText in macros;
311
340
  }
312
341
  function getJSDocTags(node) {
313
342
  const tags = ts.getJSDocTags(node);
@@ -326,6 +355,104 @@ function getJSDocTags(node) {
326
355
  return [];
327
356
  }
328
357
 
358
+ const TransformPlugin = (ctx) => {
359
+ const commandsDir = ctx.resolve.root(ctx.options.dir, "commands");
360
+ return {
361
+ name: "transform-slash-commands",
362
+ async load(id) {
363
+ if (!id.startsWith(commandsDir)) {
364
+ return;
365
+ }
366
+ try {
367
+ const sourceFile = ts.createSourceFile(
368
+ id,
369
+ fs.readFileSync(id, "utf-8"),
370
+ ts.ScriptTarget.Latest,
371
+ /* setParentNodes */
372
+ true
373
+ );
374
+ let commandDefinition = extractCommandDefinition(sourceFile);
375
+ if (!commandDefinition || !commandDefinition.body) {
376
+ return;
377
+ }
378
+ const transformer = (context) => {
379
+ return (sourceFile2) => {
380
+ const visitor = (node) => {
381
+ if (ts.isExportAssignment(node) || ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
382
+ if (ts.isFunctionDeclaration(commandDefinition)) {
383
+ commandDefinition = ts.factory.createFunctionExpression(
384
+ ts.getModifiers(commandDefinition)?.filter((m) => m.kind !== ts.SyntaxKind.ExportKeyword && m.kind !== ts.SyntaxKind.DefaultKeyword),
385
+ commandDefinition.asteriskToken,
386
+ commandDefinition.name,
387
+ commandDefinition.typeParameters,
388
+ commandDefinition.parameters,
389
+ commandDefinition.type,
390
+ commandDefinition.body
391
+ );
392
+ }
393
+ commandDefinition = commandDefinition;
394
+ const [macroCalls] = extractMacroCalls(commandDefinition.body);
395
+ if (ts.isBlock(commandDefinition.body)) {
396
+ if (isFunctionExpression(commandDefinition)) {
397
+ commandDefinition = ts.factory.createFunctionExpression(
398
+ commandDefinition.modifiers,
399
+ commandDefinition.asteriskToken,
400
+ commandDefinition.name,
401
+ commandDefinition.typeParameters,
402
+ commandDefinition.parameters,
403
+ commandDefinition.type,
404
+ ts.factory.createBlock(
405
+ commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
406
+ true
407
+ )
408
+ );
409
+ } else if (isArrowFunction(commandDefinition)) {
410
+ commandDefinition = ts.factory.createArrowFunction(
411
+ commandDefinition.modifiers,
412
+ commandDefinition.typeParameters,
413
+ commandDefinition.parameters,
414
+ commandDefinition.type,
415
+ commandDefinition.equalsGreaterThanToken,
416
+ ts.factory.createBlock(
417
+ commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
418
+ true
419
+ )
420
+ );
421
+ }
422
+ }
423
+ return ts.factory.createExportAssignment(
424
+ [],
425
+ false,
426
+ ts.factory.createObjectLiteralExpression([
427
+ ts.factory.createPropertyAssignment("execute", commandDefinition),
428
+ ts.factory.createPropertyAssignment(
429
+ "optionMacros",
430
+ ts.factory.createObjectLiteralExpression(
431
+ macroCalls.filter((m) => m.expression.escapedText === "describeOption" && ts.isIdentifier(m.arguments[0]) && m.arguments.length > 1).map((m) => ts.factory.createPropertyAssignment(m.arguments[0].escapedText, m.arguments[1]))
432
+ )
433
+ )
434
+ ])
435
+ );
436
+ }
437
+ return ts.visitEachChild(node, visitor, context);
438
+ };
439
+ return ts.visitNode(sourceFile2, visitor);
440
+ };
441
+ };
442
+ const res = ts.transform(sourceFile, [transformer]);
443
+ const printer = ts.createPrinter({
444
+ newLine: ts.NewLineKind.LineFeed,
445
+ removeComments: false
446
+ });
447
+ const transformed = printer.printFile(res.transformed[0]);
448
+ return transformed;
449
+ } catch {
450
+ return null;
451
+ }
452
+ }
453
+ };
454
+ };
455
+
329
456
  function prepareHMR(ctx) {
330
457
  const { nuxt, options } = ctx;
331
458
  if (nuxt.options.dev) {
@@ -348,8 +475,15 @@ function prepareHMR(ctx) {
348
475
  nitroIgnored.push(existingNitroIgnored);
349
476
  }
350
477
  nitroConfig.watchOptions.ignored = nitroIgnored;
351
- nitroConfig.hooks ??= {
352
- "rollup:before": (_, config) => {
478
+ const originalBeforeHook = nitroConfig.hooks?.["rollup:before"];
479
+ nitroConfig.hooks = {
480
+ ...nitroConfig.hooks,
481
+ "rollup:before": (nitroCtx, config) => {
482
+ originalBeforeHook?.(nitroCtx, config);
483
+ config.plugins = [
484
+ config.plugins,
485
+ TransformPlugin(ctx)
486
+ ];
353
487
  rollupConfig = config;
354
488
  }
355
489
  };
@@ -378,12 +512,11 @@ function prepareHMR(ctx) {
378
512
  };
379
513
  listener.server.on("upgrade", websocket.serve);
380
514
  websocket.on("full-update", (client) => {
381
- const commands = [];
382
- collectSlashCommands(ctx, commands);
515
+ collectSlashCommands(ctx);
383
516
  try {
384
517
  client.send(JSON.stringify({
385
518
  event: "full-update",
386
- commands
519
+ commands: ctx.slashCommands
387
520
  }));
388
521
  } catch {
389
522
  }
@@ -527,17 +660,17 @@ function prepareTemplates(ctx) {
527
660
  filename: "discord/slashCommands",
528
661
  getContents: () => getSlashCommandTemplateContent(
529
662
  ctx,
530
- /* importExecute */
663
+ /* commandRuntime */
531
664
  true
532
665
  )
533
666
  });
534
667
  addTemplate({
535
668
  filename: "discord/slashCommands",
536
- getContents: () => `${getSlashCommandTemplateContent(
669
+ getContents: () => getSlashCommandTemplateContent(
537
670
  ctx,
538
- /* importExecute */
671
+ /* commandRuntime */
539
672
  false
540
- )}`
673
+ )
541
674
  });
542
675
  const typesTemplateDst = addTypeTemplate({
543
676
  filename: "discord/types.d.ts",
@@ -577,20 +710,23 @@ declare global {
577
710
  include: [typesTemplateDst]
578
711
  });
579
712
  }
580
- function getSlashCommandTemplateContent(ctx, importExecute) {
581
- const imports = importExecute ? ctx.slashCommands.map(({ path }) => {
713
+ function getSlashCommandTemplateContent(ctx, commandRuntime) {
714
+ const imports = commandRuntime ? ctx.slashCommands.map(({ path }) => {
582
715
  const name = genSafeVariableName(path);
583
716
  return { name, code: genImport(path, [{ name: "default", as: name }]) };
584
717
  }) : [];
585
718
  return [
586
719
  ...imports.map(({ code }) => code),
587
- `export default ${genArrayFromRaw(
588
- ctx.slashCommands.map(({ options, ...rest }, i) => ({
589
- ...Object.fromEntries(Object.entries(rest).map(([key, value]) => [key, genString(value)])),
590
- options: genArrayFromRaw(options, void 0, { preserveTypes: true }),
591
- ...importExecute ? { execute: imports[i].name } : {}
592
- }))
593
- )}`
720
+ `export default [
721
+ ${ctx.slashCommands.map(({ options, ...rest }, i) => ` {
722
+ ${Object.entries(rest).map(([key, value]) => `${key}: ${genString(value)}`).join(",\n ")},
723
+
724
+ options: ${genArrayFromRaw(options, void 0, { preserveTypes: true })},
725
+ ${commandRuntime ? `
726
+ ...${imports[i].name},
727
+ ` : ""}
728
+ },
729
+ `).join("")}]`
594
730
  ].join("\n");
595
731
  }
596
732
 
@@ -330,6 +330,13 @@ const statusClasses = {
330
330
  color="error"
331
331
  size="sm"
332
332
  />
333
+ <UBadge
334
+ v-if="option.hasAutocomplete"
335
+ label="autocomplete"
336
+ variant="soft"
337
+ color="info"
338
+ size="sm"
339
+ />
333
340
  <!-- Restriction badges -->
334
341
  <UBadge
335
342
  v-if="'min' in option && option.min !== void 0"
@@ -1,4 +1,4 @@
1
- import type { APIApplicationCommand, ChatInputCommandInteraction, RESTGetAPIApplicationCommandsResult, RESTPutAPIApplicationCommandsResult } from 'discord.js';
1
+ import type { APIApplicationCommand, ChatInputCommandInteraction, CommandInteraction, RESTGetAPIApplicationCommandsResult, RESTPutAPIApplicationCommandsResult } from 'discord.js';
2
2
  import type { NuxtDiscordOptions, SlashCommandRuntime } from '../../../types.js';
3
3
  import { Client as InternalClient } from 'discord.js';
4
4
  export interface DiscordClientErrorBase {
@@ -7,17 +7,17 @@ export interface DiscordClientErrorBase {
7
7
  }
8
8
  export interface UnknownSlashCommandError extends DiscordClientErrorBase {
9
9
  type: 'UnknownSlashCommandError';
10
- interaction: ChatInputCommandInteraction;
10
+ interaction: CommandInteraction;
11
11
  }
12
12
  export interface MissingRequiredOptionError extends DiscordClientErrorBase {
13
13
  type: 'MissingRequiredOptionError';
14
- interaction: ChatInputCommandInteraction;
14
+ interaction: CommandInteraction;
15
15
  command: SlashCommandRuntime;
16
16
  option: string;
17
17
  }
18
18
  export interface SlashCommandExecutionError extends DiscordClientErrorBase {
19
19
  type: 'SlashCommandExecutionError';
20
- interaction: ChatInputCommandInteraction;
20
+ interaction: CommandInteraction;
21
21
  command: SlashCommandRuntime;
22
22
  error: unknown;
23
23
  }
@@ -37,11 +37,7 @@ export class DiscordClient {
37
37
  this.#clientOptions = { ...options };
38
38
  await this.#nitro.hooks.callHook("discord:client:config", this.#clientOptions);
39
39
  this.#client = new InternalClient(this.#clientOptions);
40
- this.#client.on(Events.InteractionCreate, (interaction) => {
41
- if (!interaction.isChatInputCommand())
42
- return;
43
- this.#handleSlashCommand(interaction);
44
- });
40
+ this.#client.on(Events.InteractionCreate, (interaction) => this.#handleInteraction(interaction));
45
41
  this.startScope();
46
42
  const { resolve, promise } = Promise.withResolvers();
47
43
  this.#client.once(Events.ClientReady, (readyClient) => {
@@ -52,6 +48,52 @@ export class DiscordClient {
52
48
  await this.#client.login(this.#token);
53
49
  return promise;
54
50
  }
51
+ async #handleInteraction(interaction) {
52
+ if (!interaction.isAutocomplete() && !interaction.isChatInputCommand()) {
53
+ return;
54
+ }
55
+ const commandName = interaction.commandName;
56
+ const command = this.#slashCommands.find((cmd) => cmd.name === commandName);
57
+ if (!command) {
58
+ logger.warn(`Unknown slash command: ${commandName}`);
59
+ this.#nitro.hooks.callHook("discord:client:error", {
60
+ type: "UnknownSlashCommandError",
61
+ client: this,
62
+ interaction
63
+ });
64
+ return;
65
+ }
66
+ if (!command.execute && command.load) {
67
+ try {
68
+ const dynamicCommand = await command.load();
69
+ Object.assign(command, dynamicCommand);
70
+ } catch (error) {
71
+ this.#nitro.hooks.callHook("discord:client:error", {
72
+ type: "SlashCommandExecutionError",
73
+ client: this,
74
+ interaction,
75
+ command,
76
+ error
77
+ });
78
+ return;
79
+ }
80
+ }
81
+ if (!command.execute && !command.load) {
82
+ this.#nitro.hooks.callHook("discord:client:error", {
83
+ type: "SlashCommandExecutionError",
84
+ client: this,
85
+ interaction,
86
+ command,
87
+ error: new Error(`Slash command "${commandName}" cannot be executed or loaded`)
88
+ });
89
+ return;
90
+ }
91
+ if (interaction.isAutocomplete()) {
92
+ await this.#handleAutocomplete(interaction, command);
93
+ } else if (interaction.isChatInputCommand()) {
94
+ await this.#handleSlashCommand(interaction, command);
95
+ }
96
+ }
55
97
  async stop() {
56
98
  if (this.#client) {
57
99
  await this.#client.destroy();
@@ -107,18 +149,7 @@ export class DiscordClient {
107
149
  }
108
150
  #interactionScopes = /* @__PURE__ */ new WeakMap();
109
151
  #commandFinalizationRegistry = new FinalizationRegistry((scope) => scope.stop());
110
- async #handleSlashCommand(interaction) {
111
- const name = interaction.commandName;
112
- const command = this.#slashCommands.find((cmd) => cmd.name === name);
113
- if (!command) {
114
- logger.warn(`Unknown slash command: ${name}`);
115
- this.#nitro.hooks.callHook("discord:client:error", {
116
- type: "UnknownSlashCommandError",
117
- client: this,
118
- interaction
119
- });
120
- return;
121
- }
152
+ async #handleSlashCommand(interaction, command) {
122
153
  const args = [];
123
154
  for (const option of command.options) {
124
155
  const opt = interaction.options.get(option.name, option.required);
@@ -134,29 +165,6 @@ export class DiscordClient {
134
165
  }
135
166
  args.push(opt?.value);
136
167
  }
137
- if (!command.execute && !command.load) {
138
- this.#nitro.hooks.callHook("discord:client:error", {
139
- type: "SlashCommandExecutionError",
140
- client: this,
141
- interaction,
142
- command,
143
- error: new Error(`Slash command "${name}" cannot be executed or loaded`)
144
- });
145
- return;
146
- } else if (!command.execute && command.load) {
147
- try {
148
- command.execute = await command.load();
149
- } catch (error) {
150
- this.#nitro.hooks.callHook("discord:client:error", {
151
- type: "SlashCommandExecutionError",
152
- client: this,
153
- interaction,
154
- command,
155
- error
156
- });
157
- return;
158
- }
159
- }
160
168
  let scope;
161
169
  if (this.#scope) {
162
170
  this.#scope.run(() => scope = effectScope());
@@ -235,6 +243,29 @@ export class DiscordClient {
235
243
  });
236
244
  }
237
245
  }
246
+ async #handleAutocomplete(interaction, command) {
247
+ const commandName = interaction.commandName;
248
+ if (!command) {
249
+ logger.warn(`Unknown slash command: ${commandName}`);
250
+ this.#nitro.hooks.callHook("discord:client:error", {
251
+ type: "UnknownSlashCommandError",
252
+ client: this,
253
+ interaction
254
+ });
255
+ return;
256
+ }
257
+ const focusedOption = interaction.options.getFocused(true);
258
+ const varname = command.options.find((opt) => opt.name === focusedOption.name)?.varname;
259
+ if (!varname) {
260
+ return;
261
+ }
262
+ const autocompleteFunction = command.optionMacros?.[varname]?.autocomplete;
263
+ if (!autocompleteFunction) {
264
+ return;
265
+ }
266
+ const choices = await autocompleteFunction(focusedOption.value, interaction);
267
+ await interaction.respond(choices);
268
+ }
238
269
  #getSlashCommandBuilder(command) {
239
270
  const builder = new SlashCommandBuilder().setName(command.name).setDescription(command.description);
240
271
  for (const option of command.options) {
@@ -250,6 +281,9 @@ export class DiscordClient {
250
281
  opt = opt.setMaxLength(option.maxLength);
251
282
  if (option.choices)
252
283
  opt = opt.addChoices(...option.choices);
284
+ if (option.hasAutocomplete) {
285
+ opt = opt.setAutocomplete(true);
286
+ }
253
287
  return opt;
254
288
  });
255
289
  break;
@@ -264,6 +298,8 @@ export class DiscordClient {
264
298
  opt = opt.setMaxValue(option.max);
265
299
  if (option.choices)
266
300
  opt = opt.addChoices(...option.choices);
301
+ if (option.hasAutocomplete)
302
+ opt = opt.setAutocomplete(true);
267
303
  return opt;
268
304
  });
269
305
  break;
@@ -278,6 +314,8 @@ export class DiscordClient {
278
314
  opt = opt.setMaxValue(option.max);
279
315
  if (option.choices)
280
316
  opt = opt.addChoices(...option.choices);
317
+ if (option.hasAutocomplete)
318
+ opt = opt.setAutocomplete(true);
281
319
  return opt;
282
320
  });
283
321
  break;
@@ -427,6 +465,9 @@ function optionEqual(a, b) {
427
465
  return false;
428
466
  }
429
467
  }
468
+ if (a.hasAutocomplete !== !!("autocomplete" in b && b.autocomplete)) {
469
+ return false;
470
+ }
430
471
  return true;
431
472
  }
432
473
  export function isPromise(value) {
@@ -1,4 +1,4 @@
1
- import type { APIApplicationCommandOptionChoice } from 'discord.js';
1
+ import type { APIApplicationCommandOptionChoice, ApplicationCommandOptionChoiceData, AutocompleteInteraction } from 'discord.js';
2
2
  import type { SlashCommandOptionType } from '../../../types.js';
3
3
  export interface DescribeOptionOptionsBase {
4
4
  /** The name of the command. */
@@ -6,6 +6,10 @@ export interface DescribeOptionOptionsBase {
6
6
  /** A brief description of the command. */
7
7
  description?: string;
8
8
  }
9
+ type MaybePromise<T> = T | Promise<T>;
10
+ interface AutocompleteFunction {
11
+ (value: string, interaction: AutocompleteInteraction): MaybePromise<ApplicationCommandOptionChoiceData[]>;
12
+ }
9
13
  export interface IntegerOption<T extends number = number> extends DescribeOptionOptionsBase {
10
14
  /** The minimum value for the integer option. */
11
15
  min?: number;
@@ -13,6 +17,8 @@ export interface IntegerOption<T extends number = number> extends DescribeOption
13
17
  max?: number;
14
18
  /** An array of choices for the integer option. */
15
19
  choices?: APIApplicationCommandOptionChoice<T>[];
20
+ /** A function to handle autocomplete for the integer option. */
21
+ autocomplete?: AutocompleteFunction;
16
22
  }
17
23
  export interface NumberOption<T extends number = number> extends DescribeOptionOptionsBase {
18
24
  /** The minimum value for the number option. */
@@ -21,6 +27,8 @@ export interface NumberOption<T extends number = number> extends DescribeOptionO
21
27
  max?: number;
22
28
  /** An array of choices for the number option. */
23
29
  choices?: APIApplicationCommandOptionChoice<T>[];
30
+ /** A function to handle autocomplete for the number option. */
31
+ autocomplete?: AutocompleteFunction;
24
32
  }
25
33
  export interface StringOption<T extends string = string> extends DescribeOptionOptionsBase {
26
34
  /** The minimum length of the string option. */
@@ -29,8 +37,11 @@ export interface StringOption<T extends string = string> extends DescribeOptionO
29
37
  maxLength?: number;
30
38
  /** An array of choices for the string option. */
31
39
  choices?: APIApplicationCommandOptionChoice<T>[];
40
+ /** A function to handle autocomplete for the string option. */
41
+ autocomplete?: AutocompleteFunction;
32
42
  }
33
43
  export type DescribeOptionOptions = IntegerOption | NumberOption | StringOption;
44
+ export type NarrowedDescribeOptionOptions<T extends SlashCommandOptionType> = T extends integer ? IntegerOption<T> : T extends number ? NumberOption<T> : T extends string ? StringOption<T> : never;
34
45
  /**
35
46
  * A compiler macro that describes a slash command option. Used for defining
36
47
  * metadata for registering slash command options. Options defined here will
@@ -54,4 +65,5 @@ export type DescribeOptionOptions = IntegerOption | NumberOption | StringOption;
54
65
  * ],
55
66
  * })
56
67
  */
57
- export declare function describeOption<const T extends SlashCommandOptionType>(_option: T | undefined, _options: T extends integer ? IntegerOption<T> : T extends number ? NumberOption<T> : T extends string ? StringOption<T> : never): void;
68
+ export declare function describeOption<const T extends SlashCommandOptionType>(_option: T | undefined, _options: NarrowedDescribeOptionOptions<T>): void;
69
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "type": "module",
4
- "version": "0.0.13",
4
+ "version": "0.0.14",
5
5
  "description": "A Nuxt module for building Discord bots",
6
6
  "author": "Jize Zou <jeffzou2001@gmail.com> (https://github.com/zojize)",
7
7
  "license": "MIT",