nuxt-discord 0.0.11 → 0.0.13

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
@@ -132,8 +132,6 @@ export default (name: string, style: string) => {
132
132
  }
133
133
  ```
134
134
 
135
- > **Coming Soon:** Support choices inferred from Typescript literal union types
136
-
137
135
  ## Web Interface
138
136
 
139
137
  Access the command management interface at `/discord/slash-commands` in your application. The interface provides:
@@ -272,12 +270,7 @@ Here's what's planned for future releases:
272
270
 
273
271
  ## Contribution
274
272
 
275
- <details>
276
- <summary>Local development</summary>
277
-
278
- Refer to the official [Module Author Guide](https://nuxt.com/docs/guide/going-further/modules)
279
-
280
- </details>
273
+ Refer to the official [Module Author Guide](https://nuxt.com/docs/guide/going-further/modules)
281
274
 
282
275
  ## Acknowledgement
283
276
 
package/dist/module.d.mts CHANGED
@@ -6,6 +6,7 @@ import { DiscordClient } from '/Users/jeffz/Dev/nuxt-discord/dist/runtime/server
6
6
  import { IntegerOption, NumberOption, StringOption } from '../dist/runtime/server/utils/describeOption.js';
7
7
  import { ClientOptions, ApplicationCommandOptionType, ChatInputCommandInteraction } from 'discord.js';
8
8
  import { ListenOptions } from 'listhen';
9
+ import { MaybeRef } from 'vue';
9
10
 
10
11
  interface NuxtDiscordOptions {
11
12
  /**
@@ -106,8 +107,8 @@ interface SlashCommandBooleanOption extends SlashCommandOptionBase {
106
107
  type: ApplicationCommandOptionType.Boolean;
107
108
  }
108
109
  type SlashCommandOption = SlashCommandIntegerOption | SlashCommandNumberOption | SlashCommandStringOption | SlashCommandBooleanOption;
109
- type SlashCommandCustomReturnHandler = (this: DiscordClient, interaction: ChatInputCommandInteraction, client: DiscordClient) => SlashCommandReturnType;
110
- type SlashCommandReturnType = void | string | SlashCommandCustomReturnHandler | Promise<SlashCommandReturnType> | Generator<SlashCommandReturnType> | AsyncGenerator<SlashCommandReturnType>;
110
+ type SlashCommandCustomReturnHandler = (this: DiscordClient, interaction: ChatInputCommandInteraction, client: DiscordClient) => unknown;
111
+ type SlashCommandReturnType = void | MaybeRef<string> | SlashCommandCustomReturnHandler | Promise<SlashCommandReturnType> | Generator<SlashCommandReturnType> | AsyncGenerator<SlashCommandReturnType>;
111
112
  interface SlashCommand {
112
113
  name: string;
113
114
  description: string;
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "configKey": "discord",
4
- "version": "0.0.11",
4
+ "version": "0.0.13",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.1",
7
7
  "unbuild": "3.5.0"
package/dist/module.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createResolver, installModule, extendPages, updateTemplates, addVitePlugin, isIgnored, addServerTemplate, addTemplate, addTypeTemplate, defineNuxtModule, addServerScanDir, addImports } from '@nuxt/kit';
2
2
  import { ApplicationCommandOptionType, GatewayIntentBits } from 'discord.js';
3
3
  import { logger } from '../dist/runtime/logger.js';
4
- import { globSync, readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
4
+ import fs, { globSync, readFileSync } from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import ts from 'typescript';
7
7
  import chokidar from 'chokidar';
@@ -193,20 +193,102 @@ function processCommandFile(ctx, file) {
193
193
  ctx.logger.warn(`No body found for command definition in ${file}`);
194
194
  return;
195
195
  }
196
+ const whichLiteral = (node) => {
197
+ if (ts.isLiteralTypeNode(node)) {
198
+ if (ts.isStringLiteral(node.literal)) {
199
+ return "string";
200
+ }
201
+ if (ts.isNumericLiteral(node.literal)) {
202
+ return "number";
203
+ }
204
+ }
205
+ };
206
+ const getType = (type) => {
207
+ if (!type) {
208
+ ctx.logger.warn(`No type found for slash command option in ${file}, defaulting to string`);
209
+ return { type: "string" };
210
+ }
211
+ if (ts.isUnionTypeNode(type)) {
212
+ const types = new Set(type.types.map((t) => whichLiteral(t)));
213
+ if (types.size !== 1) {
214
+ ctx.logger.warn(`Union type with multiple conflicting types found in ${file}, defaulting to string`);
215
+ return { type: "string" };
216
+ }
217
+ const typeName2 = types.values().next().value;
218
+ if (!(typeName2 in typeIdentifierToEnum)) {
219
+ ctx.logger.warn(`Unrecognizable type ${type.getText(sourceFile)}, defaulting to string`);
220
+ return { type: "string" };
221
+ }
222
+ return {
223
+ type: typeName2,
224
+ choices: typeName2 === "string" ? type.types.map((t) => t.getText(sourceFile).slice(1, -1)) : type.types.map((t) => Number(t.getText(sourceFile)))
225
+ };
226
+ }
227
+ if (ts.isLiteralTypeNode(type)) {
228
+ const typeName2 = whichLiteral(type);
229
+ if (!typeName2) {
230
+ ctx.logger.warn(`Unrecognizable literal type ${type.getText(sourceFile)}, defaulting to string`);
231
+ return { type: "string" };
232
+ }
233
+ if (!(typeName2 in typeIdentifierToEnum)) {
234
+ ctx.logger.warn(`Unrecognizable literal type ${type.getText(sourceFile)}, defaulting to string`);
235
+ return { type: "string" };
236
+ }
237
+ return {
238
+ type: typeName2,
239
+ choices: typeName2 === "string" ? [type.literal.getText(sourceFile).slice(1, -1)] : [Number(type.literal.getText(sourceFile))]
240
+ };
241
+ }
242
+ const typeName = type.getText(sourceFile);
243
+ if (typeName && typeName in typeIdentifierToEnum) {
244
+ return { type: typeName };
245
+ }
246
+ ctx.logger.warn(`Unknown slash command option type: ${type.getText(sourceFile)} in ${file}, defaulting to string`);
247
+ return { type: "string" };
248
+ };
196
249
  for (const param of commandDefinition.parameters) {
197
250
  const name2 = param.name.getText(sourceFile);
198
- let type = param.type?.getText(sourceFile);
199
- if (!type || !(type in typeIdentifierToEnum)) {
200
- ctx.logger.warn(`Unknown slash command option type: ${type} for parameter ${name2} in ${file}, defaulting to string`);
201
- type = "string";
202
- }
203
- const jsdocDescription = jsDocTags.find((tag) => ts.isJSDocParameterTag(tag) && tag.name.getText() === name2)?.comment?.toString() ?? "";
251
+ let { type, choices } = getType(param.type);
252
+ const jsDocTagIdx = jsDocTags.findIndex((tag) => ts.isJSDocParameterTag(tag) && tag.name.getText() === name2);
253
+ const findModifiers = (modifiers2) => {
254
+ let idx = jsDocTagIdx;
255
+ const ret = {};
256
+ while (idx >= 0) {
257
+ const tag = jsDocTags[idx];
258
+ if (modifiers2.includes(tag.tagName.escapedText) && tag.comment) {
259
+ ret[tag.tagName.escapedText] = JSON.parse(tag.comment.toString());
260
+ } else {
261
+ return ret;
262
+ }
263
+ idx -= 1;
264
+ }
265
+ return ret;
266
+ };
267
+ const jsdocDescription = jsDocTagIdx !== -1 ? jsDocTags[jsDocTagIdx].comment?.toString() ?? "" : "";
268
+ const modifiersMap = {
269
+ string: ["minLength", "maxLength", "choices"],
270
+ number: ["min", "max", "choices"],
271
+ integer: ["min", "max", "choices"],
272
+ boolean: []
273
+ };
274
+ const modifiers = findModifiers(modifiersMap[type]);
275
+ choices = choices ?? modifiers.choices;
204
276
  command.options.push({
205
277
  name: name2,
206
278
  // TODO: remove this type assertion
207
279
  type: typeIdentifierToEnum[type],
208
280
  description: jsdocDescription,
209
- required: !param.questionToken
281
+ required: !param.questionToken,
282
+ ...modifiers,
283
+ ...choices ? {
284
+ choices: choices.map((choice) => {
285
+ if (typeof choice === "string") {
286
+ return { name: choice, value: choice };
287
+ }
288
+ return { name: String(choice), value: choice };
289
+ })
290
+ // hmm... is it possible to not use `any` here?
291
+ } : {}
210
292
  });
211
293
  }
212
294
  let macrosEnd = false;
@@ -308,6 +390,9 @@ function prepareHMR(ctx) {
308
390
  });
309
391
  });
310
392
  }
393
+ const commandsBuildDir = path.join(ctx.nuxt.options.buildDir, "discord", "commands");
394
+ fs.rmSync(commandsBuildDir, { recursive: true, force: true });
395
+ fs.mkdirSync(commandsBuildDir, { recursive: true });
311
396
  chokidar.watch(ctx.resolve.root(ctx.options.dir, "commands"), { ignoreInitial: true }).on("all", async (event, path2) => {
312
397
  if (event === "all" || event === "error" || event === "raw") {
313
398
  return;
@@ -331,7 +416,7 @@ function prepareHMR(ctx) {
331
416
  websocket?.close();
332
417
  });
333
418
  const packageJson = ctx.resolve.module("../package.json");
334
- if (existsSync(packageJson) && JSON.parse(readFileSync(packageJson, "utf-8")).name === "nuxt-discord") {
419
+ if (fs.existsSync(packageJson) && JSON.parse(fs.readFileSync(packageJson, "utf-8")).name === "nuxt-discord") {
335
420
  (async () => {
336
421
  const { createGenerator } = await import('unocss');
337
422
  const config = (await import('../dist/runtime/client/uno.config.js')).default;
@@ -339,14 +424,14 @@ function prepareHMR(ctx) {
339
424
  const clientDir = ctx.resolve.module("runtime/client");
340
425
  const generateCSS = async (path2) => {
341
426
  if (path2.startsWith(clientDir) && path2.endsWith(".vue")) {
342
- const content = readFileSync(path2, "utf-8");
427
+ const content = fs.readFileSync(path2, "utf-8");
343
428
  const tokens = await generator.applyExtractors(content, path2);
344
429
  const { css } = await generator.generate(tokens);
345
- writeFileSync(path2.replace(".vue", ".css"), css, "utf-8");
430
+ fs.writeFileSync(path2.replace(".vue", ".css"), css, "utf-8");
346
431
  }
347
432
  };
348
433
  const globPattern = `${clientDir}/**/*.vue`;
349
- globSync(globPattern).forEach(generateCSS);
434
+ fs.globSync(globPattern).forEach(generateCSS);
350
435
  addVitePlugin({
351
436
  name: "dev-nuxt-discord-generate-css",
352
437
  configureServer(server) {
@@ -415,8 +500,8 @@ async function generateDynamicCommandBuild(file, config, ctx) {
415
500
  external: (id) => !id.includes(file) && !id.endsWith(".ts")
416
501
  });
417
502
  const { output } = await bundle.generate({ ...config.output, sourcemap: false });
418
- mkdirSync(path.join(ctx.nuxt.options.buildDir, "discord", "commands"), { recursive: true });
419
- writeFileSync(file.replace(ctx.resolve.root(ctx.nuxt.options.rootDir), ctx.nuxt.options.buildDir).replace(".ts", ".mjs"), output[0].code, { encoding: "utf-8", flush: true });
503
+ fs.mkdirSync(path.join(ctx.nuxt.options.buildDir, "discord", "commands"), { recursive: true });
504
+ fs.writeFileSync(file.replace(ctx.resolve.root(ctx.nuxt.options.rootDir), ctx.nuxt.options.buildDir).replace(".ts", ".mjs"), output[0].code, { encoding: "utf-8", flush: true });
420
505
  } catch (error) {
421
506
  ctx.logger.error(`Error processing command file ${file}:`, error);
422
507
  return;
@@ -104,7 +104,7 @@ const commandsWithStatus = computed(() => {
104
104
  name: cmd.name,
105
105
  description: cmd.description,
106
106
  path: "unknown",
107
- options: cmd.options,
107
+ options: cmd.options ?? [],
108
108
  status: "removed",
109
109
  remote: cmd
110
110
  })),
@@ -242,7 +242,6 @@ const statusClasses = {
242
242
  />
243
243
  </div>
244
244
 
245
- <!-- <UButton icon="i-lucide-circle" @click="test" /> -->
246
245
  <UButton
247
246
  v-if="!allSynced"
248
247
  :icon="pendingSync ? 'i-lucide-refresh-ccw' : 'i-lucide-cloud-upload'"
@@ -363,8 +362,12 @@ const statusClasses = {
363
362
  <!-- Choices dropdown -->
364
363
  <UDropdownMenu
365
364
  v-if="'choices' in option && option.choices && option.choices.length > 0"
366
- :items="option.choices.map((choice) => ({ label: choice.name }))"
365
+ :items="option.choices.map((choice) => ({
366
+ label: choice.name,
367
+ value: typeof choice.value === 'string' ? `\'${choice.value}\'` : choice.value
368
+ }))"
367
369
  :popper="{ placement: 'bottom-start' }"
370
+ :ui="{ itemTrailing: 'text-sm text-gray-500 dark:text-gray-400' }"
368
371
  >
369
372
  <UBadge
370
373
  v-if="'choices' in option && option.choices && option.choices.length > 0"
@@ -374,6 +377,9 @@ const statusClasses = {
374
377
  size="sm"
375
378
  class="hover:cursor-pointer"
376
379
  />
380
+ <template #item-trailing="{ item: { value } }">
381
+ {{ value }}
382
+ </template>
377
383
  </UDropdownMenu>
378
384
  </div>
379
385
 
@@ -1,2 +1,4 @@
1
- declare const _default: any;
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ commands: import("../../../../../types.js").SlashCommandRuntime[];
3
+ }>>;
2
4
  export default _default;
@@ -1,8 +1,9 @@
1
- import { defineEventHandler, useDiscordClient } from "#imports";
1
+ import { defineEventHandler } from "h3";
2
+ import { useDiscordClient } from "../../../utils/useDiscordClient.js";
2
3
  export default defineEventHandler(async () => {
3
4
  const client = useDiscordClient();
4
5
  const commands = client.getSlashCommands();
5
6
  return {
6
- commands: commands.map(({ execute, load, ...command }) => command)
7
+ commands
7
8
  };
8
9
  });
@@ -1,2 +1,2 @@
1
- declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<import("discord.js").RESTPutAPIApplicationCommandsResult | PromiseSettledResult<import("discord.js").APIApplicationCommand>[]>>;
2
2
  export default _default;
@@ -1,5 +1,5 @@
1
- import { useDiscordClient } from "#imports";
2
1
  import { defineEventHandler } from "h3";
2
+ import { useDiscordClient } from "../../../utils/useDiscordClient.js";
3
3
  export default defineEventHandler(async () => {
4
4
  const client = useDiscordClient();
5
5
  return client.registerSlashCommands();
@@ -1,2 +1,4 @@
1
- declare const _default: any;
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ commands: import("discord.js").RESTGetAPIApplicationCommandsResult;
3
+ }>>;
2
4
  export default _default;
@@ -1,4 +1,5 @@
1
- import { defineEventHandler, useDiscordClient } from "#imports";
1
+ import { defineEventHandler } from "h3";
2
+ import { useDiscordClient } from "../../../utils/useDiscordClient.js";
2
3
  export default defineEventHandler(async () => {
3
4
  const client = useDiscordClient();
4
5
  const commands = await client.getRemoteSlashCommands();
@@ -1,5 +1,5 @@
1
1
  import type { APIApplicationCommand } from 'discord.js';
2
- import type { SlashCommand, SlashCommandRuntime } from '~/src/types';
2
+ import type { SlashCommand, SlashCommandRuntime } from '../../../../../types.js';
3
3
  declare const _default: import("h3").EventHandler<{
4
4
  body?: {
5
5
  commands?: SlashCommand[];
@@ -1,5 +1,5 @@
1
- import { useDiscordClient } from "#imports";
2
1
  import { defineEventHandler, readBody } from "h3";
2
+ import { useDiscordClient } from "../../../utils/useDiscordClient.js";
3
3
  export default defineEventHandler(async (event) => {
4
4
  const client = useDiscordClient();
5
5
  const body = await readBody(event);
@@ -1,5 +1,5 @@
1
1
  import type { APIApplicationCommand, ChatInputCommandInteraction, RESTGetAPIApplicationCommandsResult, RESTPutAPIApplicationCommandsResult } from 'discord.js';
2
- import type { NuxtDiscordOptions, SlashCommandRuntime } from '~/src/types';
2
+ import type { NuxtDiscordOptions, SlashCommandRuntime } from '../../../types.js';
3
3
  import { Client as InternalClient } from 'discord.js';
4
4
  export interface DiscordClientErrorBase {
5
5
  type: string;
@@ -34,6 +34,8 @@ export declare class DiscordClient {
34
34
  constructor();
35
35
  start(options: NuxtDiscordOptions['client']): Promise<undefined>;
36
36
  stop(): Promise<void>;
37
+ startScope(): void;
38
+ stopScope(): void;
37
39
  isReady(): boolean;
38
40
  addSlashCommand(command: SlashCommandRuntime): void;
39
41
  addSlashCommands(commands: SlashCommandRuntime[]): void;
@@ -1,7 +1,9 @@
1
1
  import process from "node:process";
2
2
  import { ApplicationCommandOptionType, Events, Client as InternalClient, REST, Routes, SlashCommandBuilder } from "discord.js";
3
3
  import { useNitroApp } from "nitropack/runtime";
4
+ import { effectScope, isRef } from "vue";
4
5
  import { logger } from "../../logger.js";
6
+ import { reply } from "./reply.js";
5
7
  let currentInteraction = null;
6
8
  export function useInteraction() {
7
9
  return currentInteraction;
@@ -40,6 +42,7 @@ export class DiscordClient {
40
42
  return;
41
43
  this.#handleSlashCommand(interaction);
42
44
  });
45
+ this.startScope();
43
46
  const { resolve, promise } = Promise.withResolvers();
44
47
  this.#client.once(Events.ClientReady, (readyClient) => {
45
48
  logger.log(`Discord client is ready! Logged in as ${readyClient.user?.tag}`);
@@ -54,6 +57,22 @@ export class DiscordClient {
54
57
  await this.#client.destroy();
55
58
  this.#client = null;
56
59
  }
60
+ this.stopScope();
61
+ }
62
+ #scope;
63
+ startScope() {
64
+ if (this.#scope)
65
+ return;
66
+ this.#scope = effectScope(
67
+ /* detached */
68
+ true
69
+ );
70
+ }
71
+ stopScope() {
72
+ if (!this.#scope)
73
+ return;
74
+ this.#scope.stop();
75
+ this.#scope = void 0;
57
76
  }
58
77
  isReady() {
59
78
  return this.#client?.isReady() ?? false;
@@ -86,6 +105,8 @@ export class DiscordClient {
86
105
  getSlashCommand(name) {
87
106
  return this.#slashCommands.find((cmd) => cmd.name === name);
88
107
  }
108
+ #interactionScopes = /* @__PURE__ */ new WeakMap();
109
+ #commandFinalizationRegistry = new FinalizationRegistry((scope) => scope.stop());
89
110
  async #handleSlashCommand(interaction) {
90
111
  const name = interaction.commandName;
91
112
  const command = this.#slashCommands.find((cmd) => cmd.name === name);
@@ -136,10 +157,22 @@ export class DiscordClient {
136
157
  return;
137
158
  }
138
159
  }
160
+ let scope;
161
+ if (this.#scope) {
162
+ this.#scope.run(() => scope = effectScope());
163
+ } else {
164
+ scope = effectScope();
165
+ }
166
+ this.#interactionScopes.set(interaction, scope);
167
+ if (import.meta.dev)
168
+ this.#commandFinalizationRegistry.register(command, scope);
139
169
  try {
140
- currentInteraction = interaction;
141
- const result = command.execute(...args);
142
- currentInteraction = null;
170
+ let result;
171
+ scope.run(() => {
172
+ currentInteraction = interaction;
173
+ result = command.execute(...args);
174
+ currentInteraction = null;
175
+ });
143
176
  if (this.#clientOptions?.deferOnPromise && isPromise(result)) {
144
177
  await interaction.deferReply();
145
178
  }
@@ -160,15 +193,15 @@ export class DiscordClient {
160
193
  return;
161
194
  }
162
195
  try {
163
- if (typeof result === "string") {
164
- if (interaction.deferred) {
165
- return interaction.editReply({ content: result });
196
+ if (typeof result === "string" || isRef(result)) {
197
+ return this.#handleSlashCommandReturn(reply(result), interaction, command);
198
+ } else if (typeof result === "function") {
199
+ const scope = this.#interactionScopes.get(interaction);
200
+ if (!scope) {
201
+ return result.call(this, interaction, this);
166
202
  } else {
167
- return interaction.reply({ content: result });
203
+ return scope.run(() => result.call(this, interaction, this));
168
204
  }
169
- } else if (typeof result === "function") {
170
- const newResult = result.call(this, interaction, this);
171
- return this.#handleSlashCommandReturn(newResult, interaction, command);
172
205
  } else if (Symbol.iterator in result && typeof result[Symbol.iterator] === "function") {
173
206
  const gen = result[Symbol.iterator]();
174
207
  let next = gen.next();
@@ -344,7 +377,6 @@ export class DiscordClient {
344
377
  this.#nitro.hooks.callHook("discord:client:error", {
345
378
  type: "SlashCommandRegistrationError",
346
379
  client: this,
347
- interaction: currentInteraction,
348
380
  command: result.reason.command,
349
381
  error: result.reason.error
350
382
  });
@@ -1,10 +1,8 @@
1
- import type { SlashCommandOptionType, SlashCommandReturnType } from '~/src/types';
1
+ import type { SlashCommandOptionType, SlashCommandReturnType } from '../../../types.js';
2
2
  /**
3
3
  * Defines a slash command function that is automatically registered
4
4
  * by the Nuxt Discord module.
5
5
  *
6
6
  * @param command - The function that implements the slash command.
7
7
  */
8
- export declare function defineSlashCommand(command: {
9
- exec(...args: (SlashCommandOptionType | undefined)[]): SlashCommandReturnType;
10
- }['exec']): (...args: (SlashCommandOptionType | undefined)[]) => SlashCommandReturnType;
8
+ export declare function defineSlashCommand<Args extends (SlashCommandOptionType | undefined)[]>(command: (...args: Args) => SlashCommandReturnType): (...args: Args) => SlashCommandReturnType;
@@ -1,36 +1,57 @@
1
1
  import type { APIApplicationCommandOptionChoice } from 'discord.js';
2
- import type { SlashCommandOptionType } from '~/src/types';
2
+ import type { SlashCommandOptionType } from '../../../types.js';
3
3
  export interface DescribeOptionOptionsBase {
4
4
  /** The name of the command. */
5
5
  name?: string;
6
6
  /** A brief description of the command. */
7
7
  description?: string;
8
8
  }
9
- export interface IntegerOption extends DescribeOptionOptionsBase {
9
+ export interface IntegerOption<T extends number = number> extends DescribeOptionOptionsBase {
10
10
  /** The minimum value for the integer option. */
11
11
  min?: number;
12
12
  /** The maximum value for the integer option. */
13
13
  max?: number;
14
14
  /** An array of choices for the integer option. */
15
- choices?: APIApplicationCommandOptionChoice<number>[];
15
+ choices?: APIApplicationCommandOptionChoice<T>[];
16
16
  }
17
- export interface NumberOption extends DescribeOptionOptionsBase {
17
+ export interface NumberOption<T extends number = number> extends DescribeOptionOptionsBase {
18
18
  /** The minimum value for the number option. */
19
19
  min?: number;
20
20
  /** The maximum value for the number option. */
21
21
  max?: number;
22
22
  /** An array of choices for the number option. */
23
- choices?: APIApplicationCommandOptionChoice<number>[];
23
+ choices?: APIApplicationCommandOptionChoice<T>[];
24
24
  }
25
- export interface StringOption extends DescribeOptionOptionsBase {
25
+ export interface StringOption<T extends string = string> extends DescribeOptionOptionsBase {
26
26
  /** The minimum length of the string option. */
27
27
  minLength?: number;
28
28
  /** The maximum length of the string option. */
29
29
  maxLength?: number;
30
30
  /** An array of choices for the string option. */
31
- choices?: APIApplicationCommandOptionChoice<string>[];
31
+ choices?: APIApplicationCommandOptionChoice<T>[];
32
32
  }
33
33
  export type DescribeOptionOptions = IntegerOption | NumberOption | StringOption;
34
34
  /**
35
+ * A compiler macro that describes a slash command option. Used for defining
36
+ * metadata for registering slash command options. Options defined here will
37
+ * take higher precedence over the inferred ones from the function signature
38
+ * and JSDoc tags.
39
+ *
40
+ * @param _option - The type of the option, used for type inference.
41
+ * @param _options - The options for the command option.
42
+ * @example
43
+ * // this will describe the name option as a string with a minimum length of 1 and a maximum length of 32
44
+ * describeOption(name, {
45
+ * minLength: 1,
46
+ * maxLength: 32,
47
+ * })
48
+ * // this will describe the style option as a string with three choices
49
+ * describeOption(style, {
50
+ * choices: [
51
+ * { name: 'Formal', value: 'formal' },
52
+ * { name: 'Casual', value: 'casual' },
53
+ * { name: 'Enthusiastic', value: 'enthusiastic' },
54
+ * ],
55
+ * })
35
56
  */
36
- export declare function describeOption<const T extends SlashCommandOptionType>(_option: T | undefined, _options: T extends integer ? IntegerOption : T extends number ? NumberOption : T extends string ? StringOption : DescribeOptionOptionsBase): void;
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;
@@ -1,15 +1,22 @@
1
- import type { InteractionEditReplyOptions, InteractionReplyOptions } from 'discord.js';
2
- import type { SlashCommandCustomReturnHandler } from '~/src/types';
1
+ import type { BaseMessageOptions, InteractionCallbackResponse, InteractionReplyOptions, InteractionResponse, Message } from 'discord.js';
2
+ import type { MaybeRef } from 'vue';
3
+ import type { SlashCommandCustomReturnHandler } from '../../../types.js';
3
4
  type OmitPreservingCallSignature<T, K extends keyof T = keyof T> = Omit<T, K> & (T extends (...args: infer R) => infer S ? (...args: R) => S : unknown);
4
- interface ReplyFunction {
5
- (text: string, options?: InteractionReplyOptions): SlashCommandCustomReturnHandler;
6
- edit: EditReplyFunction;
7
- ephemeral: OmitPreservingCallSignature<ReplyFunction, 'edit' | 'ephemeral'>;
8
- flags: (flags: InteractionReplyOptions['flags']) => OmitPreservingCallSignature<ReplyFunction, 'edit'>;
9
- }
10
- interface EditReplyFunction {
11
- (text: string, options?: InteractionEditReplyOptions): SlashCommandCustomReturnHandler;
12
- flags: (flags: InteractionEditReplyOptions['flags']) => EditReplyFunction;
13
- }
5
+ type File = NonNullable<BaseMessageOptions['files']>[number];
6
+ type ReplyFunction = SlashCommandCustomReturnHandler & {
7
+ (text?: MaybeRef<string>, options?: InteractionReplyOptions): SlashCommandCustomReturnHandler & {
8
+ [Symbol.iterator]: () => {
9
+ next: (...args: ReadonlyArray<any>) => IteratorResult<ReplyFunction, Message | InteractionResponse | InteractionCallbackResponse>;
10
+ };
11
+ };
12
+ [Symbol.iterator]: () => {
13
+ next: (...args: ReadonlyArray<any>) => IteratorResult<never, Promise<Message | InteractionResponse | InteractionCallbackResponse>>;
14
+ };
15
+ ephemeral: OmitPreservingCallSignature<ReplyFunction, 'ephemeral'>;
16
+ flags: (flags: MaybeRef<InteractionReplyOptions['flags']>) => ReplyFunction;
17
+ file: (file: MaybeRef<File>) => ReplyFunction;
18
+ files: (files: MaybeRef<File[]>) => ReplyFunction;
19
+ send: ReplyFunction;
20
+ };
14
21
  export declare const reply: ReplyFunction;
15
22
  export {};
@@ -1,18 +1,63 @@
1
1
  import { MessageFlags } from "discord.js";
2
- function createReplyFunction({ editReply, ...defaultOptions } = {}) {
3
- const reply2 = (text, options) => async (interaction) => {
4
- if (editReply) {
5
- await interaction.editReply({
2
+ import { isRef, reactive, watch } from "vue";
3
+ function createReplyFunction({ ...defaultOptions } = {}) {
4
+ const reply2 = (...args) => {
5
+ if (typeof args[0] === "string" || typeof args[0] === "undefined" || isRef(args[0]) || typeof args[0] === "function") {
6
+ const [text, options] = args;
7
+ let message;
8
+ const replyOptions = reactive({
6
9
  content: text,
7
10
  ...defaultOptions,
8
11
  ...options
9
12
  });
10
- } else {
11
- await interaction.reply({
12
- content: text,
13
- ...defaultOptions,
14
- ...options
13
+ const handler = (interaction) => {
14
+ const method = interaction.replied ? "followUp" : interaction.deferred ? "editReply" : "reply";
15
+ message = interaction[method](
16
+ replyOptions
17
+ ).catch((err) => err);
18
+ return message;
19
+ };
20
+ Object.defineProperty(handler, Symbol.iterator, {
21
+ value: () => ({
22
+ next: () => message !== void 0 ? {
23
+ done: true,
24
+ value: message
25
+ } : {
26
+ done: false,
27
+ value: handler
28
+ }
29
+ })
15
30
  });
31
+ watch(replyOptions, async (options2) => {
32
+ const msg = await message;
33
+ if ("edit" in msg)
34
+ msg.edit(options2);
35
+ else
36
+ msg.resource?.message?.edit(options2);
37
+ }, { deep: true, flush: "sync" });
38
+ return handler;
39
+ } else {
40
+ const interaction = args[0];
41
+ const method = interaction.replied ? "followUp" : interaction.deferred ? "editReply" : "reply";
42
+ const options = reactive(defaultOptions);
43
+ const messagePromise = interaction[method](options).catch((err) => err);
44
+ watch(options, async (opts) => {
45
+ const message = await messagePromise;
46
+ if (!message)
47
+ return;
48
+ if ("edit" in message)
49
+ message.edit(opts);
50
+ else
51
+ message.resource?.message?.edit(opts);
52
+ }, { deep: true, flush: "sync" });
53
+ return {
54
+ [Symbol.iterator]: () => ({
55
+ next: () => ({
56
+ done: true,
57
+ value: messagePromise
58
+ })
59
+ })
60
+ };
16
61
  }
17
62
  };
18
63
  Object.defineProperties(reply2, {
@@ -32,13 +77,24 @@ function createReplyFunction({ editReply, ...defaultOptions } = {}) {
32
77
  });
33
78
  }
34
79
  },
35
- edit: {
80
+ file: {
36
81
  get() {
37
- return createReplyFunction({
82
+ return (file) => createReplyFunction({
38
83
  ...defaultOptions,
39
- editReply: true
84
+ files: defaultOptions.files != null ? [...defaultOptions.files, file] : [file]
40
85
  });
41
86
  }
87
+ },
88
+ files: {
89
+ get() {
90
+ return (files) => createReplyFunction({
91
+ ...defaultOptions,
92
+ files: defaultOptions.files != null ? [...defaultOptions.files, ...files] : files
93
+ });
94
+ }
95
+ },
96
+ send: {
97
+ value: reply2
42
98
  }
43
99
  });
44
100
  return reply2;
@@ -1,4 +1,4 @@
1
- import type { DiscordClient } from '#imports';
1
+ import type { DiscordClient } from './client.js';
2
2
  /**
3
3
  * Retrieves the Discord client from the event context.
4
4
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-discord",
3
3
  "type": "module",
4
- "version": "0.0.11",
4
+ "version": "0.0.13",
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",
@@ -83,6 +83,6 @@
83
83
  "lint": "eslint .",
84
84
  "test": "vitest run",
85
85
  "test:watch": "vitest watch",
86
- "test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit"
86
+ "test:types": "vue-tsc --noEmit"
87
87
  }
88
88
  }