nuxt-discord 0.0.17 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +249 -171
  2. package/dist/module.d.mts +146 -10
  3. package/dist/module.json +3 -3
  4. package/dist/module.mjs +1077 -348
  5. package/dist/runtime/acknowledgement.d.ts +11 -0
  6. package/dist/runtime/acknowledgement.js +156 -0
  7. package/dist/runtime/client/chat-theme.css +52 -0
  8. package/dist/runtime/client/components/ChatAvatar.d.vue.ts +6 -0
  9. package/dist/runtime/client/components/ChatAvatar.vue +11 -0
  10. package/dist/runtime/client/components/ChatAvatar.vue.d.ts +6 -0
  11. package/dist/runtime/client/components/CommandPicker.d.vue.ts +24 -0
  12. package/dist/runtime/client/components/CommandPicker.vue +67 -0
  13. package/dist/runtime/client/components/CommandPicker.vue.d.ts +24 -0
  14. package/dist/runtime/client/components/CommandReference.d.vue.ts +20 -0
  15. package/dist/runtime/client/components/CommandReference.vue +21 -0
  16. package/dist/runtime/client/components/CommandReference.vue.d.ts +20 -0
  17. package/dist/runtime/client/components/CommandTestBar.d.vue.ts +60 -0
  18. package/dist/runtime/client/components/CommandTestBar.vue +332 -0
  19. package/dist/runtime/client/components/CommandTestBar.vue.d.ts +60 -0
  20. package/dist/runtime/client/components/CommandTranscript.d.vue.ts +39 -0
  21. package/dist/runtime/client/components/CommandTranscript.vue +147 -0
  22. package/dist/runtime/client/components/CommandTranscript.vue.d.ts +39 -0
  23. package/dist/runtime/client/components/ProjectLogo.d.vue.ts +3 -0
  24. package/dist/runtime/client/components/ProjectLogo.vue +31 -0
  25. package/dist/runtime/client/components/ProjectLogo.vue.d.ts +3 -0
  26. package/dist/runtime/client/components/ReferenceContent.d.ts +26 -0
  27. package/dist/runtime/client/components/ReferenceContent.js +73 -0
  28. package/dist/runtime/client/components/TheHeader.d.vue.ts +3 -0
  29. package/dist/runtime/client/components/TheHeader.vue +53 -16
  30. package/dist/runtime/client/components/TheHeader.vue.d.ts +2 -2
  31. package/dist/runtime/client/components/appearance-select.d.ts +17 -0
  32. package/dist/runtime/client/components/appearance-select.js +15 -0
  33. package/dist/runtime/client/pages/activity.d.vue.ts +3 -0
  34. package/dist/runtime/client/pages/activity.vue +202 -0
  35. package/dist/runtime/client/pages/activity.vue.d.ts +3 -0
  36. package/dist/runtime/client/pages/context-menus.d.vue.ts +3 -0
  37. package/dist/runtime/client/pages/context-menus.vue +120 -0
  38. package/dist/runtime/client/pages/context-menus.vue.d.ts +3 -0
  39. package/dist/runtime/client/pages/listeners.d.vue.ts +3 -0
  40. package/dist/runtime/client/pages/listeners.vue +68 -0
  41. package/dist/runtime/client/pages/listeners.vue.d.ts +3 -0
  42. package/dist/runtime/client/pages/overview.d.vue.ts +3 -0
  43. package/dist/runtime/client/pages/overview.vue +280 -0
  44. package/dist/runtime/client/pages/overview.vue.d.ts +3 -0
  45. package/dist/runtime/client/pages/slash-commands.d.vue.ts +3 -0
  46. package/dist/runtime/client/pages/slash-commands.vue +185 -359
  47. package/dist/runtime/client/pages/slash-commands.vue.d.ts +2 -3
  48. package/dist/runtime/client/reference.css +46 -0
  49. package/dist/runtime/client/style.css +4 -1
  50. package/dist/runtime/client/useActivityLog.d.ts +7 -0
  51. package/dist/runtime/client/useActivityLog.js +76 -0
  52. package/dist/runtime/client/useCommandRegistry.d.ts +7 -0
  53. package/dist/runtime/client/useCommandRegistry.js +34 -0
  54. package/dist/runtime/client/useDashboardCatalog.d.ts +5 -0
  55. package/dist/runtime/client/useDashboardCatalog.js +9 -0
  56. package/dist/runtime/client/useDiscordCommandReference.d.ts +2 -0
  57. package/dist/runtime/client/useDiscordCommandReference.js +6 -0
  58. package/dist/runtime/dashboard/auth.d.ts +4 -0
  59. package/dist/runtime/dashboard/auth.js +55 -0
  60. package/dist/runtime/dashboard/oauth.d.ts +17 -0
  61. package/dist/runtime/dashboard/oauth.js +172 -0
  62. package/dist/runtime/dashboard/origin.d.ts +3 -0
  63. package/dist/runtime/dashboard/origin.js +15 -0
  64. package/dist/runtime/dashboard/permissions.d.ts +4 -0
  65. package/dist/runtime/dashboard/permissions.js +84 -0
  66. package/dist/runtime/dashboard/signin.d.ts +3 -0
  67. package/dist/runtime/dashboard/signin.js +42 -0
  68. package/dist/runtime/diagnostics.d.ts +4 -0
  69. package/dist/runtime/diagnostics.js +24 -0
  70. package/dist/runtime/discordInvocation.d.ts +14 -0
  71. package/dist/runtime/discordInvocation.js +28 -0
  72. package/dist/runtime/middleware.d.ts +1 -0
  73. package/dist/runtime/middleware.js +12 -0
  74. package/dist/runtime/reference/access.d.ts +6 -0
  75. package/dist/runtime/reference/access.js +143 -0
  76. package/dist/runtime/reference/catalog.d.ts +2 -0
  77. package/dist/runtime/reference/catalog.js +9 -0
  78. package/dist/runtime/reference/document.d.ts +2 -0
  79. package/dist/runtime/reference/document.js +22 -0
  80. package/dist/runtime/reference/hosted.d.ts +2 -0
  81. package/dist/runtime/reference/hosted.js +16 -0
  82. package/dist/runtime/reference/oauth.d.ts +2 -0
  83. package/dist/runtime/reference/oauth.js +4 -0
  84. package/dist/runtime/registration.d.ts +65 -0
  85. package/dist/runtime/registration.js +354 -0
  86. package/dist/runtime/server/api/discord/activity.get.d.ts +2 -0
  87. package/dist/runtime/server/api/discord/activity.get.js +6 -0
  88. package/dist/runtime/server/api/discord/catalog.get.d.ts +2 -0
  89. package/dist/runtime/server/api/discord/catalog.get.js +3 -0
  90. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.d.ts +2 -0
  91. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.js +14 -0
  92. package/dist/runtime/server/api/discord/slash-command/register.post.d.ts +1 -1
  93. package/dist/runtime/server/api/discord/slash-command/register.post.js +1 -1
  94. package/dist/runtime/server/api/discord/slash-command/remote-all.get.d.ts +1 -1
  95. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.d.ts +1 -238
  96. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.js +3 -1
  97. package/dist/runtime/server/api/discord/slash-command/test.post.d.ts +20 -0
  98. package/dist/runtime/server/api/discord/slash-command/test.post.js +19 -0
  99. package/dist/runtime/server/plugins/discord.js +95 -31
  100. package/dist/runtime/server/utils/client.d.ts +59 -246
  101. package/dist/runtime/server/utils/client.js +413 -451
  102. package/dist/runtime/server/utils/defineContextMenu.d.ts +49 -0
  103. package/dist/runtime/server/utils/defineContextMenu.js +12 -0
  104. package/dist/runtime/server/utils/defineListener.d.ts +24 -0
  105. package/dist/runtime/server/utils/defineListener.js +7 -0
  106. package/dist/runtime/server/utils/defineMiddleware.d.ts +29 -0
  107. package/dist/runtime/server/utils/defineMiddleware.js +24 -0
  108. package/dist/runtime/server/utils/describeCommand.d.ts +2 -0
  109. package/dist/runtime/server/utils/describeOption.d.ts +1 -1
  110. package/dist/runtime/server/utils/messageSender.d.ts +37 -0
  111. package/dist/runtime/server/utils/messageSender.js +149 -0
  112. package/dist/runtime/server/utils/middleware/cooldown.d.ts +1 -0
  113. package/dist/runtime/server/utils/middleware/cooldown.js +39 -0
  114. package/dist/runtime/server/utils/middleware/guildOnly.d.ts +1 -0
  115. package/dist/runtime/server/utils/middleware/guildOnly.js +6 -0
  116. package/dist/runtime/server/utils/middleware/ownerOnly.d.ts +1 -0
  117. package/dist/runtime/server/utils/middleware/ownerOnly.js +10 -0
  118. package/dist/runtime/server/utils/middleware/requireRole.d.ts +1 -0
  119. package/dist/runtime/server/utils/middleware/requireRole.js +15 -0
  120. package/dist/runtime/server/utils/reply.d.ts +13 -3
  121. package/dist/runtime/server/utils/reply.js +111 -162
  122. package/dist/runtime/server/utils/simulateInteraction.d.ts +20 -0
  123. package/dist/runtime/server/utils/simulateInteraction.js +127 -0
  124. package/dist/runtime/server/utils/useTextChannel.d.ts +56 -0
  125. package/dist/runtime/server/utils/useTextChannel.js +105 -0
  126. package/dist/types.d.mts +11 -1
  127. package/dist/types.d.ts +11 -1
  128. package/package.json +62 -44
  129. package/dist/runtime/client/components/TheHeader.css +0 -1
  130. package/dist/runtime/client/pages/slash-commands.css +0 -1
  131. package/dist/runtime/client/uno.config.d.ts +0 -2
  132. package/dist/runtime/client/uno.config.js +0 -10
package/dist/module.mjs CHANGED
@@ -1,21 +1,26 @@
1
- import { createResolver, installModule, extendPages, updateTemplates, addVitePlugin, isIgnored, resolveAlias, addServerTemplate, addTemplate, addTypeTemplate, defineNuxtModule, addServerScanDir, addImports } from '@nuxt/kit';
2
- import { ApplicationCommandOptionType, GatewayIntentBits } from 'discord.js';
1
+ import fs, { globSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
2
+ import path, { relative, sep, join } from 'node:path';
3
+ import { createResolver, extendPages, addServerTemplate, addTemplate, addTypeTemplate, updateTemplates, isIgnored, defineNuxtModule, addImports, addComponent, addServerHandler, extendRouteRules, addServerScanDir, addServerPlugin, addServerImportsDir, loadNuxtModuleInstance } from '@nuxt/kit';
4
+ import { ApplicationCommandOptionType, Locale, GatewayIntentBits } from 'discord.js';
3
5
  import { logger } from '../dist/runtime/logger.js';
4
- import fs, { globSync, readFileSync } from 'node:fs';
5
- import path from 'node:path';
6
- import ts, { isFunctionExpression, isArrowFunction } from 'typescript';
6
+ import ts from 'typescript';
7
+ import '../dist/runtime/server/utils/defineMiddleware.js';
8
+ import { resolveMiddlewareTags } from '../dist/runtime/middleware.js';
9
+ import { rm, mkdir } from 'node:fs/promises';
10
+ import { pathToFileURL } from 'node:url';
7
11
  import chokidar from 'chokidar';
8
12
  import { listen } from 'listhen';
9
13
  import { rollup } from 'rollup';
10
14
  import { WebSocketServer } from 'ws';
11
- import defu from 'defu';
12
- import { genSafeVariableName, genImport, genArrayFromRaw, genString } from 'knitwork';
15
+ import { genSafeVariableName, genImport, genString, genArrayFromRaw } from 'knitwork';
13
16
 
14
17
  function createContext(options, nuxt) {
15
18
  return {
16
19
  nuxt,
17
20
  options,
18
21
  slashCommands: [],
22
+ contextMenus: [],
23
+ listeners: [],
19
24
  resolve: {
20
25
  root: createResolver(nuxt.options.rootDir).resolve,
21
26
  module: createResolver(import.meta.url).resolve
@@ -24,16 +29,53 @@ function createContext(options, nuxt) {
24
29
  };
25
30
  }
26
31
 
27
- async function prepareClient(ctx) {
32
+ function prepareClient(ctx) {
33
+ ctx.nuxt.hook("icon:clientBundleIcons", (icons) => {
34
+ for (const name of [
35
+ "lucide:blocks",
36
+ "lucide:circle-x",
37
+ "lucide:eye",
38
+ "lucide:pin",
39
+ "lucide:plus",
40
+ "lucide:send-horizontal",
41
+ "lucide:shapes",
42
+ "lucide:smile",
43
+ "simple-icons:discord",
44
+ "simple-icons:github"
45
+ ]) icons.add(name);
46
+ });
28
47
  ctx.nuxt.options.css.push(ctx.resolve.module("runtime/client/style.css"));
29
- await installModule("@nuxt/ui");
30
48
  extendPages((pages) => {
31
49
  pages.unshift(
32
50
  {
33
- name: "slash-commands",
51
+ name: "discord-overview",
52
+ path: "/discord",
53
+ file: ctx.resolve.module("./runtime/client/pages/overview.vue"),
54
+ mode: "client"
55
+ },
56
+ {
57
+ name: "discord-slash-commands",
34
58
  path: "/discord/slash-commands",
35
59
  file: ctx.resolve.module("./runtime/client/pages/slash-commands.vue"),
36
60
  mode: "client"
61
+ },
62
+ {
63
+ name: "discord-context-menus",
64
+ path: "/discord/context-menus",
65
+ file: ctx.resolve.module("./runtime/client/pages/context-menus.vue"),
66
+ mode: "client"
67
+ },
68
+ {
69
+ name: "discord-listeners",
70
+ path: "/discord/listeners",
71
+ file: ctx.resolve.module("./runtime/client/pages/listeners.vue"),
72
+ mode: "client"
73
+ },
74
+ {
75
+ name: "discord-activity",
76
+ path: "/discord/activity",
77
+ file: ctx.resolve.module("./runtime/client/pages/activity.vue"),
78
+ mode: "client"
37
79
  }
38
80
  );
39
81
  });
@@ -43,7 +85,12 @@ const typeIdentifierToEnum = {
43
85
  number: ApplicationCommandOptionType.Number,
44
86
  integer: ApplicationCommandOptionType.Integer,
45
87
  string: ApplicationCommandOptionType.String,
46
- boolean: ApplicationCommandOptionType.Boolean
88
+ boolean: ApplicationCommandOptionType.Boolean,
89
+ User: ApplicationCommandOptionType.User,
90
+ Channel: ApplicationCommandOptionType.Channel,
91
+ Role: ApplicationCommandOptionType.Role,
92
+ Mentionable: ApplicationCommandOptionType.Mentionable,
93
+ Attachment: ApplicationCommandOptionType.Attachment
47
94
  };
48
95
 
49
96
  const macros = {
@@ -52,7 +99,7 @@ const macros = {
52
99
  ctx.logger.warn("describeCommand macro requires a object literal as the first argument");
53
100
  return;
54
101
  }
55
- const describeCommandOptions = ["name", "description"];
102
+ const describeCommandOptions = ["name", "description", "defer"];
56
103
  const isValidOption = (key) => describeCommandOptions.includes(key);
57
104
  const options = {};
58
105
  for (const prop of node.arguments[0].properties) {
@@ -71,6 +118,11 @@ const macros = {
71
118
  command.name = options.name ?? command.name;
72
119
  }
73
120
  command.description = options.description ?? command.description;
121
+ if (options.defer !== void 0) {
122
+ if (!["public", "private", "manual"].includes(options.defer))
123
+ throw new Error(`Invalid describeCommand defer policy in ${command.path}`);
124
+ command.defer = options.defer;
125
+ }
74
126
  },
75
127
  describeOption(ctx, node, command) {
76
128
  if (node.arguments.length !== 2) {
@@ -95,7 +147,9 @@ const macros = {
95
147
  const validOptionKeys = ["name", "description", "min", "max", "minLength", "maxLength", "choices"];
96
148
  const isValidOptionKey = (key) => validOptionKeys.includes(key);
97
149
  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;
150
+ option.hasAutocomplete = node.arguments[1].properties.some(
151
+ (prop) => (ts.isPropertyAssignment(prop) || ts.isShorthandPropertyAssignment(prop) || ts.isMethodDeclaration(prop)) && (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) && prop.name.text === "autocomplete"
152
+ );
99
153
  for (const key in macroOptions) {
100
154
  if (!isValidOptionKey(key)) {
101
155
  ctx.logger.warn(`describeOption: unknown option key "${key}" for option "${name}" in command "${command.name}"`);
@@ -108,6 +162,10 @@ const macros = {
108
162
  }
109
163
  option[key] = value;
110
164
  }
165
+ },
166
+ useMiddleware(_ctx, _node, command) {
167
+ command.hasRuntimeMiddleware = true;
168
+ command.middleware ??= [];
111
169
  }
112
170
  };
113
171
  function parseLiteral(node) {
@@ -149,26 +207,126 @@ function parseLiteral(node) {
149
207
  return void 0;
150
208
  }
151
209
 
152
- function collectSlashCommands(ctx) {
210
+ function readMiddlewareTags(file, definition) {
211
+ const statement = file.statements.find((node) => ts.isExportAssignment(node) || ts.isFunctionDeclaration(node) && node.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword));
212
+ const blocks = statement?.jsDoc ?? [];
213
+ const tags = /* @__PURE__ */ new Set([...blocks.flatMap((block) => [...block.tags ?? []]), ...definition ? ts.getJSDocTags(definition) : []]);
214
+ const names = [...tags].filter((tag) => tag.tagName.text === "middleware").map((tag) => tag.comment?.toString().trim() ?? "");
215
+ resolveMiddlewareTags(names, file.fileName);
216
+ return names;
217
+ }
218
+
219
+ function isOptionTypeIdentifier(s) {
220
+ return s in typeIdentifierToEnum;
221
+ }
222
+ const validLocales = new Set(Object.values(Locale));
223
+ const LOCALE_TAG_RE = /^\.([a-z]{2}(?:-[A-Z]{2})?)\s(.+)$/s;
224
+ const modifiersMap = {
225
+ string: ["minLength", "maxLength", "choices"],
226
+ number: ["min", "max", "choices"],
227
+ integer: ["min", "max", "choices"],
228
+ boolean: [],
229
+ User: [],
230
+ Channel: [],
231
+ Role: [],
232
+ Mentionable: [],
233
+ Attachment: []
234
+ };
235
+ function containsCommandFile(commands, file) {
236
+ return commands.some((command) => command.path === file || containsCommandFile(command.subcommands, file));
237
+ }
238
+ function collectSlashCommands(ctx, changed) {
153
239
  const commandFiles = globSync(`${ctx.resolve.root(ctx.options.dir, "commands")}/**/*.ts`);
240
+ const previous = ctx.slashCommands;
241
+ const options = { noLib: true, noResolve: true, types: [] };
242
+ const changes = changed && ts.createProgram(
243
+ commandFiles.filter((file) => changed.has(file.split(path.sep).join("/"))),
244
+ options,
245
+ ts.createCompilerHost(options, true)
246
+ );
247
+ const problem = changes?.getSyntacticDiagnostics()[0];
248
+ if (problem) {
249
+ throw new SyntaxError(ts.formatDiagnostic(problem, {
250
+ getCanonicalFileName: (file) => file,
251
+ getCurrentDirectory: ts.sys.getCurrentDirectory,
252
+ getNewLine: () => "\n"
253
+ }));
254
+ }
154
255
  ctx.slashCommands = [];
155
256
  for (const file of commandFiles) {
156
- const command = processCommandFile(ctx, file);
257
+ const checkedSource = changes?.getSourceFile(file);
258
+ const command = processCommandFile(ctx, file, checkedSource);
157
259
  if (command) {
158
260
  ctx.slashCommands.push(command);
261
+ } else if (checkedSource && containsCommandFile(previous, file)) {
262
+ throw new Error(`Edited command has no supported default handler in ${file}`);
159
263
  }
160
264
  }
161
265
  processSubcommands(ctx);
266
+ applyLocalizations(ctx);
162
267
  }
163
- function processCommandFile(ctx, file) {
164
- const sourceFile = ts.createSourceFile(
165
- file,
166
- readFileSync(file).toString(),
167
- ts.ScriptTarget.Latest,
168
- /* setParentNodes */
169
- true
170
- );
171
- const commandDefinition = extractCommandDefinition(sourceFile);
268
+ function applyLocalizations(ctx) {
269
+ const localesDir = ctx.resolve.root(ctx.options.dir, "locales");
270
+ const localeFiles = globSync(`${localesDir}/*.json`);
271
+ if (localeFiles.length === 0)
272
+ return;
273
+ for (const localeFile of localeFiles) {
274
+ const localeName = path.parse(localeFile).name;
275
+ if (!validLocales.has(localeName)) {
276
+ ctx.logger.warn(`Unknown locale "${localeName}" in ${localeFile}, skipping. Valid locales: ${[...validLocales].join(", ")}`);
277
+ continue;
278
+ }
279
+ const locale = localeName;
280
+ let entries;
281
+ try {
282
+ entries = JSON.parse(readFileSync(localeFile, "utf-8"));
283
+ } catch {
284
+ ctx.logger.warn(`Failed to parse locale file: ${localeFile}`);
285
+ continue;
286
+ }
287
+ for (const [commandName, entry] of Object.entries(entries)) {
288
+ const command = ctx.slashCommands.find((c) => c.name === commandName);
289
+ if (!command) {
290
+ ctx.logger.warn(`Locale "${locale}": command "${commandName}" not found`);
291
+ continue;
292
+ }
293
+ if (entry.name) {
294
+ command.nameLocalizations ??= {};
295
+ command.nameLocalizations[locale] = entry.name;
296
+ }
297
+ if (entry.description) {
298
+ command.descriptionLocalizations ??= {};
299
+ command.descriptionLocalizations[locale] = entry.description;
300
+ }
301
+ if (entry.options) {
302
+ for (const [optionName, optionEntry] of Object.entries(entry.options)) {
303
+ const option = command.options.find((o) => o.name === optionName);
304
+ if (!option) {
305
+ ctx.logger.warn(`Locale "${locale}": option "${optionName}" not found in command "${commandName}"`);
306
+ continue;
307
+ }
308
+ if (optionEntry.name) {
309
+ option.nameLocalizations ??= {};
310
+ option.nameLocalizations[locale] = optionEntry.name;
311
+ }
312
+ if (optionEntry.description) {
313
+ option.descriptionLocalizations ??= {};
314
+ option.descriptionLocalizations[locale] = optionEntry.description;
315
+ }
316
+ }
317
+ }
318
+ }
319
+ }
320
+ }
321
+ function readGuildTags(tags) {
322
+ const guildTags = tags.filter((tag) => tag.tagName.text === "guild");
323
+ if (!guildTags.length)
324
+ return void 0;
325
+ const ids = guildTags.flatMap((tag) => tag.comment?.toString().trim() || []);
326
+ return ids.length ? ids : true;
327
+ }
328
+ function processCommandFile(ctx, file, sourceFile = ts.createSourceFile(file, readFileSync(file).toString(), ts.ScriptTarget.Latest, true)) {
329
+ const commandDefinition = findCommandExport(sourceFile)?.handler;
172
330
  if (!commandDefinition) {
173
331
  ctx.logger.warn(`No command definition found for ${file}`);
174
332
  return;
@@ -183,11 +341,49 @@ function processCommandFile(ctx, file) {
183
341
  if ((ts.isFunctionDeclaration(commandDefinition) || ts.isFunctionExpression(commandDefinition)) && !!commandDefinition.name && ts.isIdentifier(commandDefinition.name) && commandDefinition.name.escapedText) {
184
342
  command.name = commandDefinition.name.escapedText;
185
343
  }
344
+ const jsDocComment = getJSDocComment(commandDefinition);
186
345
  const jsDocTags = getJSDocTags(commandDefinition);
187
- const nameTag = jsDocTags.find((tag) => tag.tagName.escapedText === "name");
188
- const descriptionTag = jsDocTags.find((tag) => tag.tagName.escapedText === "description");
346
+ const isBaseTag = (tag) => !tag.comment?.toString().startsWith(".");
347
+ const nameTag = jsDocTags.find((tag) => tag.tagName.escapedText === "name" && isBaseTag(tag));
348
+ const descriptionTag = jsDocTags.find((tag) => tag.tagName.escapedText === "description" && isBaseTag(tag));
189
349
  command.name = nameTag?.comment?.toString() ?? command.name;
190
- command.description = descriptionTag?.comment?.toString() ?? command.description;
350
+ command.description = descriptionTag?.comment?.toString() ?? jsDocComment;
351
+ const nsfwTag = jsDocTags.find((tag) => tag.tagName.escapedText === "nsfw");
352
+ if (nsfwTag) {
353
+ command.nsfw = nsfwTag.comment?.toString().trim() !== "false";
354
+ }
355
+ const dmTag = jsDocTags.find((tag) => tag.tagName.escapedText === "dm");
356
+ if (dmTag) {
357
+ const allowDm = dmTag.comment?.toString().trim() !== "false";
358
+ command.contexts = allowDm ? [0, 1, 2] : [0];
359
+ }
360
+ const permissionsTag = jsDocTags.find((tag) => tag.tagName.escapedText === "defaultMemberPermissions");
361
+ if (permissionsTag && permissionsTag.comment) {
362
+ command.defaultMemberPermissions = permissionsTag.comment.toString().trim();
363
+ }
364
+ command.guilds = readGuildTags(jsDocTags);
365
+ const middleware = readMiddlewareTags(sourceFile, commandDefinition);
366
+ if (middleware.length)
367
+ command.middleware = middleware;
368
+ for (const tag of jsDocTags) {
369
+ const tagName = tag.tagName.escapedText;
370
+ const comment = tag.comment?.toString();
371
+ if (!comment)
372
+ continue;
373
+ if (tagName === "name" || tagName === "description") {
374
+ const localeMatch = comment.match(LOCALE_TAG_RE);
375
+ if (localeMatch) {
376
+ const [, locale, value] = localeMatch;
377
+ if (!validLocales.has(locale)) {
378
+ ctx.logger.warn(`Unknown locale "${locale}" in @${tagName}.${locale} for ${file}`);
379
+ continue;
380
+ }
381
+ const key = tagName === "name" ? "nameLocalizations" : "descriptionLocalizations";
382
+ command[key] ??= {};
383
+ command[key][locale] = value.trim();
384
+ }
385
+ }
386
+ }
191
387
  if (!commandDefinition.body) {
192
388
  ctx.logger.warn(`No body found for command definition in ${file}`);
193
389
  return;
@@ -202,8 +398,16 @@ function processCommandFile(ctx, file) {
202
398
  }
203
399
  }
204
400
  };
205
- const getType = (type) => {
401
+ const getType = (type, initializer) => {
206
402
  if (!type) {
403
+ if (initializer) {
404
+ if (ts.isNumericLiteral(initializer) || ts.isPrefixUnaryExpression(initializer) && [ts.SyntaxKind.MinusToken, ts.SyntaxKind.PlusToken].includes(initializer.operator) && ts.isNumericLiteral(initializer.operand))
405
+ return { type: "number" };
406
+ if (initializer.kind === ts.SyntaxKind.TrueKeyword || initializer.kind === ts.SyntaxKind.FalseKeyword)
407
+ return { type: "boolean" };
408
+ if (ts.isStringLiteralLike(initializer))
409
+ return { type: "string" };
410
+ }
207
411
  ctx.logger.warn(`No type found for slash command option in ${file}, defaulting to string`);
208
412
  return { type: "string" };
209
413
  }
@@ -214,7 +418,7 @@ function processCommandFile(ctx, file) {
214
418
  return { type: "string" };
215
419
  }
216
420
  const typeName2 = types.values().next().value;
217
- if (!(typeName2 in typeIdentifierToEnum)) {
421
+ if (!typeName2 || !isOptionTypeIdentifier(typeName2)) {
218
422
  ctx.logger.warn(`Unrecognizable type ${type.getText(sourceFile)}, defaulting to string`);
219
423
  return { type: "string" };
220
424
  }
@@ -239,7 +443,7 @@ function processCommandFile(ctx, file) {
239
443
  };
240
444
  }
241
445
  const typeName = type.getText(sourceFile);
242
- if (typeName && typeName in typeIdentifierToEnum) {
446
+ if (typeName && isOptionTypeIdentifier(typeName)) {
243
447
  return { type: typeName };
244
448
  }
245
449
  ctx.logger.warn(`Unknown slash command option type: ${type.getText(sourceFile)} in ${file}, defaulting to string`);
@@ -247,7 +451,7 @@ function processCommandFile(ctx, file) {
247
451
  };
248
452
  for (const param of commandDefinition.parameters) {
249
453
  const name2 = param.name.getText(sourceFile);
250
- let { type, choices } = getType(param.type);
454
+ let { type, choices } = getType(param.type, param.initializer);
251
455
  const jsDocTagIdx = jsDocTags.findIndex((tag) => ts.isJSDocParameterTag(tag) && tag.name.getText() === name2);
252
456
  const findModifiers = (modifiers2) => {
253
457
  let idx = jsDocTagIdx;
@@ -264,20 +468,13 @@ function processCommandFile(ctx, file) {
264
468
  return ret;
265
469
  };
266
470
  const jsdocDescription = jsDocTagIdx !== -1 ? jsDocTags[jsDocTagIdx].comment?.toString() ?? "" : "";
267
- const modifiersMap = {
268
- string: ["minLength", "maxLength", "choices"],
269
- number: ["min", "max", "choices"],
270
- integer: ["min", "max", "choices"],
271
- boolean: []
272
- };
273
471
  const modifiers = findModifiers(modifiersMap[type]);
274
472
  choices = choices ?? modifiers.choices;
275
473
  command.options.push({
276
474
  name: name2,
277
- // TODO: remove this type assertion
278
475
  type: typeIdentifierToEnum[type],
279
476
  description: jsdocDescription,
280
- required: !param.questionToken,
477
+ required: !param.questionToken && !param.initializer,
281
478
  varname: name2,
282
479
  hasAutocomplete: false,
283
480
  ...modifiers,
@@ -297,6 +494,7 @@ function processCommandFile(ctx, file) {
297
494
  const macroName = macroCall.expression.escapedText;
298
495
  macros[macroName](ctx, macroCall, command);
299
496
  }
497
+ command.description ||= command.name;
300
498
  if (outOfRangMacroCalls.length > 0) {
301
499
  ctx.logger.warn(`Macros in file ${file} must be called at the top of the file`);
302
500
  }
@@ -350,20 +548,21 @@ ${command.parents.map((p) => ` - ${p}`).join("\n")}`);
350
548
  }
351
549
  ctx.slashCommands = ctx.slashCommands.filter((c) => c.parents.length === 0);
352
550
  }
353
- function extractCommandDefinition(sourceFile) {
354
- let commandDefinition;
355
- ts.forEachChild(sourceFile, (node) => {
356
- if (ts.isExportAssignment(node)) {
357
- if (ts.isArrowFunction(node.expression)) {
358
- commandDefinition = node.expression;
359
- } 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]))) {
360
- commandDefinition = node.expression.arguments[0];
361
- }
362
- } else if (ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
363
- commandDefinition = node;
551
+ function findCommandExport(sourceFile) {
552
+ for (const statement of sourceFile.statements) {
553
+ if (ts.isFunctionDeclaration(statement) && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword))
554
+ return { statement, handler: statement };
555
+ if (!ts.isExportAssignment(statement) || statement.isExportEquals)
556
+ continue;
557
+ const expression = statement.expression;
558
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression))
559
+ return { statement, handler: expression };
560
+ if (ts.isCallExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === "defineSlashCommand") {
561
+ const handler = expression.arguments[0];
562
+ if (handler && (ts.isArrowFunction(handler) || ts.isFunctionExpression(handler)))
563
+ return { statement, handler };
364
564
  }
365
- });
366
- return commandDefinition;
565
+ }
367
566
  }
368
567
  function extractMacroCalls(definitionBody) {
369
568
  let macrosEnd = false;
@@ -388,6 +587,17 @@ function extractMacroCalls(definitionBody) {
388
587
  function isMacroCallExpression(node) {
389
588
  return ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.escapedText in macros;
390
589
  }
590
+ function getJSDocComment(node) {
591
+ const jsDocs = ts.getJSDocCommentsAndTags(node);
592
+ for (const doc of jsDocs) {
593
+ if (ts.isJSDoc(doc) && doc.comment) {
594
+ return typeof doc.comment === "string" ? doc.comment : doc.comment.map((c) => c.text).join("");
595
+ }
596
+ }
597
+ if (node.parent) {
598
+ return getJSDocComment(node.parent);
599
+ }
600
+ }
391
601
  function getJSDocTags(node) {
392
602
  const tags = ts.getJSDocTags(node);
393
603
  if (tags.length > 0) {
@@ -405,115 +615,548 @@ function getJSDocTags(node) {
405
615
  return [];
406
616
  }
407
617
 
408
- const TransformPlugin = (ctx) => {
409
- const commandsDir = ctx.resolve.root(ctx.options.dir, "commands");
410
- return {
411
- name: "transform-slash-commands",
412
- async load(id) {
413
- if (!id.startsWith(commandsDir)) {
414
- return;
618
+ function collectContextMenus(ctx) {
619
+ const contextMenuDir = ctx.resolve.root(ctx.options.dir, "context-menus");
620
+ const allFiles = globSync(`${contextMenuDir}/**/*.ts`);
621
+ ctx.contextMenus = [];
622
+ for (const file of allFiles) {
623
+ const menu = processContextMenuFile(ctx, file);
624
+ if (menu) {
625
+ ctx.contextMenus.push(menu);
626
+ }
627
+ }
628
+ }
629
+ function processContextMenuFile(ctx, file) {
630
+ const source = readFileSync(file, "utf-8");
631
+ const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
632
+ let type;
633
+ let nameFromDefine;
634
+ let hasRuntimeMiddleware = false;
635
+ ts.forEachChild(sourceFile, (node) => {
636
+ if (ts.isExportAssignment(node) && ts.isCallExpression(node.expression)) {
637
+ const call = node.expression;
638
+ if (ts.isIdentifier(call.expression)) {
639
+ const fnName = call.expression.escapedText;
640
+ if (fnName === "defineUserContextMenu") {
641
+ type = "user";
642
+ } else if (fnName === "defineMessageContextMenu") {
643
+ type = "message";
644
+ }
645
+ if (type && call.arguments.length > 0) {
646
+ hasRuntimeMiddleware = call.arguments.length >= 3;
647
+ const firstArg = call.arguments[0];
648
+ if (ts.isStringLiteral(firstArg)) {
649
+ nameFromDefine = firstArg.text;
650
+ }
651
+ }
415
652
  }
416
- try {
417
- const sourceFile = ts.createSourceFile(
418
- id,
419
- fs.readFileSync(id, "utf-8"),
420
- ts.ScriptTarget.Latest,
421
- /* setParentNodes */
422
- true
423
- );
424
- let commandDefinition = extractCommandDefinition(sourceFile);
425
- if (!commandDefinition || !commandDefinition.body) {
426
- return;
653
+ }
654
+ });
655
+ if (!type) {
656
+ ctx.logger.warn(`No defineUserContextMenu or defineMessageContextMenu call found in ${file}`);
657
+ return;
658
+ }
659
+ let name = nameFromDefine;
660
+ if (!name) {
661
+ const jsDocName = getJSDocTag(sourceFile, "name");
662
+ if (jsDocName) {
663
+ name = jsDocName;
664
+ }
665
+ }
666
+ if (!name) {
667
+ name = path.basename(file, ".ts");
668
+ }
669
+ const middleware = readMiddlewareTags(sourceFile);
670
+ const definition = sourceFile.statements.find(ts.isExportAssignment);
671
+ const guilds = readGuildTags(ts.getJSDocTags(definition));
672
+ return { name, type, path: file, ...hasRuntimeMiddleware ? { hasRuntimeMiddleware: true } : {}, ...guilds && { guilds }, ...middleware.length > 0 ? { middleware } : {} };
673
+ }
674
+ function getJSDocTag(sourceFile, tagName) {
675
+ let result;
676
+ ts.forEachChild(sourceFile, (node) => {
677
+ if (ts.isExportAssignment(node)) {
678
+ const tags = ts.getJSDocTags(node);
679
+ for (const tag of tags) {
680
+ if (tag.tagName.escapedText === tagName && tag.comment) {
681
+ result = tag.comment.toString().trim();
427
682
  }
428
- const transformer = (context) => {
429
- return (sourceFile2) => {
430
- const visitor = (node) => {
431
- if (ts.isExportAssignment(node) || ts.isFunctionDeclaration(node) && !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.ExportDefault)) {
432
- if (ts.isFunctionDeclaration(commandDefinition)) {
433
- commandDefinition = ts.factory.createFunctionExpression(
434
- ts.getModifiers(commandDefinition)?.filter((m) => m.kind !== ts.SyntaxKind.ExportKeyword && m.kind !== ts.SyntaxKind.DefaultKeyword),
435
- commandDefinition.asteriskToken,
436
- commandDefinition.name,
437
- commandDefinition.typeParameters,
438
- commandDefinition.parameters,
439
- commandDefinition.type,
440
- commandDefinition.body
441
- );
442
- }
443
- commandDefinition = commandDefinition;
444
- const [macroCalls] = extractMacroCalls(commandDefinition.body);
445
- if (ts.isBlock(commandDefinition.body)) {
446
- if (isFunctionExpression(commandDefinition)) {
447
- commandDefinition = ts.factory.createFunctionExpression(
448
- commandDefinition.modifiers,
449
- commandDefinition.asteriskToken,
450
- commandDefinition.name,
451
- commandDefinition.typeParameters,
452
- commandDefinition.parameters,
453
- commandDefinition.type,
454
- ts.factory.createBlock(
455
- commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
456
- true
457
- )
458
- );
459
- } else if (isArrowFunction(commandDefinition)) {
460
- commandDefinition = ts.factory.createArrowFunction(
461
- commandDefinition.modifiers,
462
- commandDefinition.typeParameters,
463
- commandDefinition.parameters,
464
- commandDefinition.type,
465
- commandDefinition.equalsGreaterThanToken,
466
- ts.factory.createBlock(
467
- commandDefinition.body.statements.filter((s) => !isMacroCallExpression(s)),
468
- true
469
- )
470
- );
471
- }
472
- }
473
- return ts.factory.createExportAssignment(
474
- [],
475
- false,
476
- ts.factory.createObjectLiteralExpression([
477
- ts.factory.createPropertyAssignment("execute", commandDefinition),
478
- ts.factory.createPropertyAssignment(
479
- "optionMacros",
480
- ts.factory.createObjectLiteralExpression(
481
- 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]))
482
- )
483
- )
484
- ])
485
- );
683
+ }
684
+ if (!result) {
685
+ const comments = ts.getJSDocCommentsAndTags(node);
686
+ for (const doc of comments) {
687
+ if (ts.isJSDoc(doc) && doc.tags) {
688
+ for (const tag of doc.tags) {
689
+ if (tag.tagName.escapedText === tagName && tag.comment) {
690
+ result = tag.comment.toString().trim();
486
691
  }
487
- return ts.visitEachChild(node, visitor, context);
488
- };
489
- return ts.visitNode(sourceFile2, visitor);
490
- };
692
+ }
693
+ }
694
+ }
695
+ }
696
+ }
697
+ });
698
+ return result;
699
+ }
700
+
701
+ function collectListeners(ctx) {
702
+ const listenersDir = ctx.resolve.root(ctx.options.dir, "listeners");
703
+ const listenerFiles = globSync(`${listenersDir}/**/*.ts`);
704
+ ctx.listeners = [];
705
+ for (const file of listenerFiles) {
706
+ const listener = processListenerFile(ctx, file);
707
+ if (listener) {
708
+ ctx.listeners.push(listener);
709
+ }
710
+ }
711
+ }
712
+ function processListenerFile(ctx, file) {
713
+ const source = readFileSync(file, "utf-8");
714
+ const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
715
+ let event;
716
+ let once = false;
717
+ ts.forEachChild(sourceFile, (node) => {
718
+ if (ts.isExportAssignment(node) && ts.isCallExpression(node.expression)) {
719
+ const call = node.expression;
720
+ if (ts.isIdentifier(call.expression) && call.expression.escapedText === "defineListener") {
721
+ const firstArg = call.arguments[0];
722
+ if (firstArg && ts.isStringLiteral(firstArg)) {
723
+ event = firstArg.text;
724
+ }
725
+ const thirdArg = call.arguments[2];
726
+ if (thirdArg && ts.isObjectLiteralExpression(thirdArg)) {
727
+ for (const prop of thirdArg.properties) {
728
+ if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.escapedText === "once" && prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
729
+ once = true;
730
+ }
731
+ }
732
+ }
733
+ }
734
+ }
735
+ });
736
+ if (!event) {
737
+ ctx.logger.warn(`No defineListener call found in ${file}`);
738
+ return;
739
+ }
740
+ return { path: file, event, once };
741
+ }
742
+
743
+ const registry = '(globalThis[Symbol.for("nuxt-discord.hmr.modules")] ??= new Map())';
744
+ const livePrefix = "\0discord:live:";
745
+ const registryEntry = "\0discord:hot-registry";
746
+ function captureCommandImports(rootDir, buildDir, runtimeDir, publish) {
747
+ const importsByModule = /* @__PURE__ */ new Map();
748
+ return {
749
+ name: "discord:capture-command-imports",
750
+ transform: {
751
+ order: "post",
752
+ async handler(code, id) {
753
+ const projectFile = id.startsWith(rootDir + path.sep) && !id.startsWith(buildDir + path.sep) && !id.includes("/node_modules/");
754
+ if (!projectFile && !id.startsWith(runtimeDir + path.sep) && !id.endsWith("discord/slashCommands"))
755
+ return;
756
+ const sources = new Set(ts.preProcessFile(code, true).importedFiles.map((file) => file.fileName));
757
+ const lines = [];
758
+ const ids = [];
759
+ for (const source of sources) {
760
+ const resolved = await this.resolve(source, id);
761
+ if (!resolved || resolved.external)
762
+ continue;
763
+ ids.push(resolved.id);
764
+ lines.push(`;${registry}.set(${JSON.stringify(resolved.id)}, () => import(${JSON.stringify(source)}))`);
765
+ }
766
+ importsByModule.set(id, ids);
767
+ if (lines.length)
768
+ return { code: `${code}
769
+ ${lines.join("\n")}`, map: null };
770
+ }
771
+ },
772
+ writeBundle() {
773
+ const ids = /* @__PURE__ */ new Set();
774
+ const visited = /* @__PURE__ */ new Set();
775
+ const visit = (id) => {
776
+ const info = this.getModuleInfo(id);
777
+ if (visited.has(id) || !info?.isIncluded)
778
+ return;
779
+ visited.add(id);
780
+ importsByModule.get(id)?.forEach((dep) => ids.add(dep));
781
+ info.importedIds.forEach(visit);
782
+ };
783
+ for (const id of this.getModuleIds()) {
784
+ if (id.endsWith("discord/slashCommands") || this.getModuleInfo(id)?.isEntry)
785
+ visit(id);
786
+ }
787
+ publish(ids);
788
+ }
789
+ };
790
+ }
791
+ function reuseCommandDependencies(entries, updated, changed) {
792
+ return {
793
+ name: "discord:reuse-command-imports",
794
+ resolveId: {
795
+ order: "pre",
796
+ async handler(source, importer, options) {
797
+ if (!importer || source.startsWith(livePrefix))
798
+ return;
799
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
800
+ if (!resolved || resolved.id.startsWith(livePrefix) || changed.has(resolved.id))
801
+ return resolved;
802
+ const url = updated.get(resolved.id);
803
+ if (url)
804
+ return { id: url, external: true };
805
+ return entries.has(resolved.id) ? livePrefix + resolved.id : resolved;
806
+ }
807
+ },
808
+ load(id) {
809
+ if (id.startsWith(livePrefix)) {
810
+ return {
811
+ code: `export const __discordNamespace = await ${registry}.get(${JSON.stringify(id.slice(livePrefix.length))})(); export default __discordNamespace.default`,
812
+ syntheticNamedExports: "__discordNamespace"
491
813
  };
492
- const res = ts.transform(sourceFile, [transformer]);
493
- const printer = ts.createPrinter({
494
- newLine: ts.NewLineKind.LineFeed,
495
- removeComments: false
496
- });
497
- const transformed = printer.printFile(res.transformed[0]);
498
- return transformed;
499
- } catch {
500
- return null;
501
814
  }
502
815
  }
503
816
  };
817
+ }
818
+
819
+ function resolveReference(options) {
820
+ if (options === void 0 || options === false)
821
+ return;
822
+ if (!options || !["public", "private", "authenticated", "members"].includes(options.access) || options.page !== void 0 && typeof options.page !== "boolean") {
823
+ throw new Error("discord.reference requires a valid access mode and an optional boolean page setting.");
824
+ }
825
+ if (Object.keys(options).some((key) => !["access", "page", "guilds"].includes(key)))
826
+ throw new Error("discord.reference accepts access, page and guilds.");
827
+ if (options.access === "members") {
828
+ if (options.guilds === void 0)
829
+ return { access: options.access, page: options.page ?? true };
830
+ if (!Array.isArray(options.guilds) || !options.guilds.length || options.guilds.some((id) => typeof id !== "string" || !/^[1-9]\d{0,19}$/.test(id)))
831
+ throw new Error("discord.reference.guilds requires Discord server IDs for members access.");
832
+ return { access: options.access, page: options.page ?? true, guilds: [...new Set(options.guilds)] };
833
+ }
834
+ if ("guilds" in options)
835
+ throw new Error("discord.reference.guilds is used only with members access.");
836
+ return { access: options.access, page: options.page ?? true };
837
+ }
838
+ function restricted(item) {
839
+ return Boolean(item.guilds || item.hasRuntimeMiddleware || item.middleware?.some((name) => name !== "cooldown" && name !== "guildOnly") || "nsfw" in item && item.nsfw || "defaultMemberPermissions" in item && item.defaultMemberPermissions != null);
840
+ }
841
+ function projectOption(option) {
842
+ const type = ApplicationCommandOptionType[option.type].toLowerCase();
843
+ return {
844
+ name: option.name,
845
+ description: option.description,
846
+ type,
847
+ required: option.required,
848
+ hasAutocomplete: option.hasAutocomplete,
849
+ ..."min" in option && { min: option.min },
850
+ ..."max" in option && { max: option.max },
851
+ ..."minLength" in option && { minLength: option.minLength },
852
+ ..."maxLength" in option && { maxLength: option.maxLength },
853
+ ..."choices" in option && { choices: option.choices?.map(({ name, value }) => ({ name, value })) }
854
+ };
855
+ }
856
+ function projectReference(commands, menus, access) {
857
+ function leaves(tree, prefix = "") {
858
+ return tree.flatMap((command) => {
859
+ if (access !== "private" && restricted(command))
860
+ return [];
861
+ const name = prefix + command.name;
862
+ return command.subcommands.length ? leaves(command.subcommands, `${name} `) : [{ name, description: command.description, options: command.options.map(projectOption) }];
863
+ });
864
+ }
865
+ return {
866
+ commands: leaves(commands).sort((a, b) => a.name.localeCompare(b.name)),
867
+ menus: menus.filter((menu) => access === "private" || !restricted(menu)).map(({ name, type }) => ({ name, type })).sort((a, b) => a.name.localeCompare(b.name))
868
+ };
869
+ }
870
+
871
+ function prepareTemplates(ctx) {
872
+ addServerTemplate({
873
+ filename: "discord/catalog",
874
+ getContents: () => {
875
+ const catalog = { commands: ctx.slashCommands, menus: ctx.contextMenus, listeners: ctx.listeners };
876
+ return `export default ${JSON.stringify(catalog, (key, value) => key === "path" && !ctx.nuxt.options.dev ? relative(ctx.nuxt.options.rootDir, value).split(sep).join("/") : value)}`;
877
+ }
878
+ });
879
+ addServerTemplate({
880
+ filename: "discord/slashCommands",
881
+ getContents: () => getSlashCommandTemplateContent(
882
+ ctx,
883
+ /* commandRuntime */
884
+ true
885
+ )
886
+ });
887
+ addTemplate({
888
+ filename: "discord/slashCommands",
889
+ getContents: () => getSlashCommandTemplateContent(
890
+ ctx,
891
+ /* commandRuntime */
892
+ false
893
+ )
894
+ });
895
+ addServerTemplate({
896
+ filename: "discord/contextMenus",
897
+ getContents: () => {
898
+ if (ctx.contextMenus.length === 0) {
899
+ return "export default []";
900
+ }
901
+ const entries = ctx.contextMenus.map((cm, i) => {
902
+ const varName = `cm_${i}`;
903
+ return {
904
+ importLine: `import ${varName} from '${cm.path}'`,
905
+ entry: `{ ...${varName}, name: ${JSON.stringify(cm.name)}, middleware: ${JSON.stringify(cm.middleware ?? [])}, guilds: ${JSON.stringify(cm.guilds)}, path: ${JSON.stringify(cm.path)} }`
906
+ };
907
+ });
908
+ return [
909
+ ...entries.map((e) => e.importLine),
910
+ `export default [${entries.map((e) => e.entry).join(", ")}]`
911
+ ].join("\n");
912
+ }
913
+ });
914
+ addTemplate({
915
+ filename: "discord/contextMenus",
916
+ getContents: () => {
917
+ return `export default ${JSON.stringify(ctx.contextMenus.map((cm) => ({
918
+ name: cm.name,
919
+ type: cm.type,
920
+ guilds: cm.guilds,
921
+ path: cm.path
922
+ })))}`;
923
+ }
924
+ });
925
+ addServerTemplate({
926
+ filename: "discord/listeners",
927
+ getContents: () => {
928
+ if (ctx.listeners.length === 0) {
929
+ return "export default []";
930
+ }
931
+ const imports = ctx.listeners.map((l, i) => {
932
+ const name = `listener_${i}`;
933
+ return { name, code: `import ${name} from '${l.path}'` };
934
+ });
935
+ return [
936
+ ...imports.map((i) => i.code),
937
+ `export default [${imports.map((i) => i.name).join(", ")}]`
938
+ ].join("\n");
939
+ }
940
+ });
941
+ addTemplate({
942
+ filename: "discord/listeners",
943
+ getContents: () => {
944
+ return `export default ${JSON.stringify(ctx.listeners.map((l) => ({
945
+ event: l.event,
946
+ once: l.once ?? false,
947
+ path: l.path
948
+ })))}`;
949
+ }
950
+ });
951
+ addTypeTemplate({
952
+ filename: "discord/types.d.ts",
953
+ getContents: () => `
954
+ declare module 'discord/reference' {
955
+ export function getCatalog(): import('nuxt-discord').DiscordCommandReference | Promise<import('nuxt-discord').DiscordCommandReference>
956
+ export const policy: import('nuxt-discord').DiscordReferenceOptions
957
+ export const styles: string
958
+ }
959
+ declare module 'discord/catalog' {
960
+ const catalog: import('nuxt-discord').DashboardCatalog
961
+ export default catalog
962
+ }
963
+
964
+ declare module 'discord/slashCommands' {
965
+ const slashCommands: import('nuxt-discord').SlashCommandRuntime[]
966
+ export default slashCommands
967
+ }
968
+
969
+ declare module '#build/discord/slashCommands' {
970
+ const slashCommands: import('nuxt-discord').SlashCommand[]
971
+ export default slashCommands
972
+ }
973
+
974
+ declare module '#build/discord/contextMenus' {
975
+ const contextMenus: import('nuxt-discord').ContextMenu[]
976
+ export default contextMenus
977
+ }
978
+
979
+ declare module '#build/discord/listeners' {
980
+ const listeners: import('nuxt-discord').Listener[]
981
+ export default listeners
982
+ }
983
+
984
+ declare module 'discord/contextMenus' {
985
+ const contextMenus: (import('nuxt-discord/types').ContextMenuDefinition & { name: string, path: string })[]
986
+ export default contextMenus
987
+ }
988
+
989
+ declare module 'discord/listeners' {
990
+ const listeners: import('nuxt-discord/types').ListenerDefinition[]
991
+ export default listeners
992
+ }
993
+
994
+ type integer = import('nuxt-discord').integer
995
+ `
996
+ }, { nuxt: true, nitro: true });
997
+ addTypeTemplate({
998
+ filename: "discord/augmentations.d.ts",
999
+ getContents: () => `
1000
+ import type { DiscordClient, DiscordClientError, DiscordRuntimeConfig, NuxtDiscordOptions } from 'nuxt-discord/types'
1001
+ import type { Interaction } from 'discord.js'
1002
+
1003
+ declare module 'nitropack/types' {
1004
+ interface NitroRuntimeHooks {
1005
+ 'discord:client:config': (options: NuxtDiscordOptions['client']) => void
1006
+ 'discord:client:ready': (client: DiscordClient) => void
1007
+ 'discord:client:error': (error: DiscordClientError) => void
1008
+ 'discord:interaction:before': (ctx: { interaction: Interaction, type: 'command' | 'context-menu' }) => void
1009
+ 'discord:interaction:after': (ctx: { interaction: Interaction, type: 'command' | 'context-menu', status: 'ok' | 'denied' | 'error', detail?: string }) => void
1010
+ 'discord:interaction:denied': (ctx: { interaction: Interaction, type: 'command' | 'context-menu', reason: string, middleware: string }) => void
1011
+ }
1012
+ }
1013
+
1014
+ declare module '@nuxt/schema' {
1015
+ interface RuntimeConfig {
1016
+ discord: DiscordRuntimeConfig
1017
+ }
1018
+ interface PublicRuntimeConfig {
1019
+ discord: { wsUrl?: string }
1020
+ }
1021
+ }
1022
+ `
1023
+ }, { nuxt: true, nitro: true });
1024
+ }
1025
+ function getSlashCommandTemplateContent(ctx, commandRuntime) {
1026
+ const imports = commandRuntime ? Object.fromEntries(ctx.slashCommands.flatMap(
1027
+ function getImports(cmd) {
1028
+ const name = genSafeVariableName(cmd.path);
1029
+ return [
1030
+ [cmd.path, { name, code: genImport(cmd.path, [{ name: "default", as: name }]) }],
1031
+ ..."subcommands" in cmd ? cmd.subcommands.flatMap(getImports) : []
1032
+ ];
1033
+ }
1034
+ )) : {};
1035
+ return [
1036
+ ...Object.values(imports).map(({ code }) => code),
1037
+ `export default [
1038
+ ${ctx.slashCommands.map((cmd) => genCommandObject(cmd)).join(",\n")}]`
1039
+ ].join("\n");
1040
+ function genCommandObject({
1041
+ options,
1042
+ parents,
1043
+ subcommands,
1044
+ ...rest
1045
+ }) {
1046
+ return ` {
1047
+ ${Object.entries(rest).filter(([, v]) => v !== void 0).map(([key, value]) => `${key}: ${typeof value === "string" ? genString(value) : JSON.stringify(value)}`).join(",\n ")},
1048
+ options: ${genArrayFromRaw(options, void 0, { preserveTypes: true })},
1049
+ ${subcommands.length > 0 ? `subcommands: [${subcommands.map(genCommandObject).join(",")}],` : ""}
1050
+ ${commandRuntime ? `...${imports[rest.path].name},` : ""}
1051
+ }`;
1052
+ }
1053
+ }
1054
+
1055
+ const TransformPlugin = (ctx) => {
1056
+ const commandsDir = `${ctx.resolve.root(ctx.options.dir, "commands").split(path.sep).join("/")}/`;
1057
+ const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
1058
+ return {
1059
+ name: "transform-slash-commands",
1060
+ load(id) {
1061
+ if (!id.split(path.sep).join("/").startsWith(commandsDir) || !id.endsWith(".ts"))
1062
+ return;
1063
+ const source = ts.createSourceFile(id, fs.readFileSync(id, "utf-8"), ts.ScriptTarget.Latest, true);
1064
+ const command = findCommandExport(source);
1065
+ if (!command || !command.handler.body)
1066
+ return;
1067
+ const runtime = createRuntimeExport(command.handler, command.handler.body);
1068
+ const statements = source.statements.map((statement) => statement === command.statement ? runtime : statement);
1069
+ return printer.printFile(ts.factory.updateSourceFile(source, statements));
1070
+ }
1071
+ };
504
1072
  };
1073
+ function createRuntimeExport(handler, originalBody) {
1074
+ const [macroCalls] = extractMacroCalls(originalBody);
1075
+ const body = ts.isBlock(originalBody) ? ts.factory.updateBlock(originalBody, originalBody.statements.filter((statement) => !isMacroCallExpression(statement))) : originalBody;
1076
+ let execute;
1077
+ if (ts.isArrowFunction(handler)) {
1078
+ execute = ts.factory.updateArrowFunction(handler, handler.modifiers, handler.typeParameters, handler.parameters, handler.type, handler.equalsGreaterThanToken, body);
1079
+ } else {
1080
+ execute = ts.factory.createFunctionExpression(
1081
+ ts.getModifiers(handler)?.filter((modifier) => modifier.kind !== ts.SyntaxKind.ExportKeyword && modifier.kind !== ts.SyntaxKind.DefaultKeyword),
1082
+ handler.asteriskToken,
1083
+ handler.name,
1084
+ handler.typeParameters,
1085
+ handler.parameters,
1086
+ handler.type,
1087
+ body
1088
+ // Function declarations and function expressions always have a block body.
1089
+ );
1090
+ }
1091
+ const middlewareCalls = macroCalls.filter((m) => m.expression.escapedText === "useMiddleware" && m.arguments.length >= 1);
1092
+ const middlewareEntries = middlewareCalls.map((m) => {
1093
+ const ref = m.arguments[0];
1094
+ const props = [
1095
+ ts.factory.createPropertyAssignment("name", ts.factory.createPropertyAccessExpression(ref, "name")),
1096
+ ts.factory.createPropertyAssignment("fn", ts.factory.createPropertyAccessExpression(ref, "fn"))
1097
+ ];
1098
+ if (m.arguments.length > 1) {
1099
+ props.push(ts.factory.createPropertyAssignment("options", m.arguments[1]));
1100
+ }
1101
+ return ts.factory.createObjectLiteralExpression(props);
1102
+ });
1103
+ return ts.factory.createExportAssignment(
1104
+ [],
1105
+ false,
1106
+ ts.factory.createObjectLiteralExpression([
1107
+ ts.factory.createPropertyAssignment("execute", execute),
1108
+ ts.factory.createPropertyAssignment(
1109
+ "optionMacros",
1110
+ ts.factory.createObjectLiteralExpression(
1111
+ macroCalls.filter((m) => m.expression.escapedText === "describeOption" && m.arguments.length > 1 && ts.isIdentifier(m.arguments[0])).map((m) => ts.factory.createPropertyAssignment(m.arguments[0].escapedText, m.arguments[1]))
1112
+ )
1113
+ ),
1114
+ ...middlewareEntries.length > 0 ? [ts.factory.createPropertyAssignment(
1115
+ "middlewareEntries",
1116
+ ts.factory.createArrayLiteralExpression(middlewareEntries)
1117
+ )] : []
1118
+ ])
1119
+ );
1120
+ }
505
1121
 
506
- function prepareHMR(ctx) {
1122
+ function prepareHMR(ctx, liveReferenceFile) {
507
1123
  const { nuxt, options } = ctx;
508
- if (nuxt.options.dev) {
509
- const commandsDir = ctx.resolve.root(options.dir, "commands");
1124
+ const watching = nuxt.options.dev && options.watch.enabled;
1125
+ const commandsDir = ctx.resolve.root(options.dir, "commands") + path.sep;
1126
+ const commandIdPrefix = commandsDir.split(path.sep).join("/");
1127
+ const hotDir = path.join(nuxt.options.buildDir, "discord", "hmr");
1128
+ let dependencies = /* @__PURE__ */ new Set();
1129
+ const updated = /* @__PURE__ */ new Map();
1130
+ let revision = 0;
1131
+ let nextRevision = 0;
1132
+ let rollupConfig;
1133
+ nuxt.hook("nitro:init", (nitro) => {
1134
+ nitro.hooks.hook("rollup:before", (_nitro, config) => {
1135
+ config.plugins = [config.plugins, TransformPlugin(ctx)];
1136
+ if (watching) {
1137
+ rollupConfig = { ...config, plugins: config.plugins };
1138
+ config.plugins = [config.plugins, captureCommandImports(nuxt.options.rootDir, nuxt.options.buildDir, ctx.resolve.module("runtime/server"), (ids) => {
1139
+ dependencies = ids;
1140
+ updated.clear();
1141
+ revision = 0;
1142
+ })];
1143
+ }
1144
+ });
1145
+ });
1146
+ if (watching) {
1147
+ let publishReference = function(snapshot) {
1148
+ if (liveReferenceFile && options.reference) {
1149
+ const catalog = projectReference(snapshot.slashCommands, snapshot.contextMenus, options.reference.access);
1150
+ writeFileSync(`${liveReferenceFile}.tmp`, JSON.stringify(catalog));
1151
+ renameSync(`${liveReferenceFile}.tmp`, liveReferenceFile);
1152
+ }
1153
+ };
510
1154
  const ignoreCommandsDir = (file) => {
511
- if (file.startsWith(commandsDir)) {
1155
+ if (file === commandsDir.slice(0, -1) || file.startsWith(commandsDir)) {
512
1156
  return true;
513
1157
  }
514
1158
  return isIgnored(file);
515
1159
  };
516
- let rollupConfig;
517
1160
  nuxt.hook("nitro:config", (nitroConfig) => {
518
1161
  nitroConfig.watchOptions ??= {};
519
1162
  const existingNitroIgnored = nitroConfig.watchOptions.ignored;
@@ -525,18 +1168,6 @@ function prepareHMR(ctx) {
525
1168
  nitroIgnored.push(existingNitroIgnored);
526
1169
  }
527
1170
  nitroConfig.watchOptions.ignored = nitroIgnored;
528
- const originalBeforeHook = nitroConfig.hooks?.["rollup:before"];
529
- nitroConfig.hooks = {
530
- ...nitroConfig.hooks,
531
- "rollup:before": (nitroCtx, config) => {
532
- originalBeforeHook?.(nitroCtx, config);
533
- config.plugins = [
534
- config.plugins,
535
- TransformPlugin(ctx)
536
- ];
537
- rollupConfig = config;
538
- }
539
- };
540
1171
  });
541
1172
  nuxt.options.vite.server ??= {};
542
1173
  nuxt.options.vite.server.watch ??= {};
@@ -553,78 +1184,149 @@ function prepareHMR(ctx) {
553
1184
  let websocket;
554
1185
  let listener;
555
1186
  const websocketOptions = options.watch || {};
556
- if (websocketOptions.enabled) {
557
- nuxt.hook("nitro:init", async (nitro) => {
558
- websocket = createWebSocket();
559
- listener = await listen(() => "Nuxt Discord", websocketOptions);
560
- nitro.options.runtimeConfig.public.discord = {
561
- wsUrl: listener.url.replace("http", "ws")
562
- };
563
- listener.server.on("upgrade", websocket.serve);
564
- websocket.on("full-update", (client) => {
565
- collectSlashCommands(ctx);
566
- try {
567
- client.send(JSON.stringify({
568
- event: "full-update",
569
- commands: ctx.slashCommands
570
- }));
571
- } catch {
572
- }
573
- });
1187
+ nuxt.hook("nitro:init", async (nitro) => {
1188
+ websocket = createWebSocket();
1189
+ await rm(hotDir, { recursive: true, force: true });
1190
+ if (liveReferenceFile) {
1191
+ await mkdir(hotDir, { recursive: true });
1192
+ publishReference(ctx);
1193
+ }
1194
+ listener = await listen(() => "Nuxt Discord", websocketOptions);
1195
+ nitro.options.runtimeConfig.public.discord = {
1196
+ wsUrl: listener.url.replace("http", "ws")
1197
+ };
1198
+ listener.server.on("upgrade", websocket.serve);
1199
+ websocket.on("full-update", (client) => {
1200
+ try {
1201
+ client.send(JSON.stringify({
1202
+ event: "full-update",
1203
+ commands: ctx.slashCommands
1204
+ }));
1205
+ } catch {
1206
+ }
574
1207
  });
575
- }
576
- const commandsBuildDir = path.join(ctx.nuxt.options.buildDir, "discord", "commands");
577
- fs.rmSync(commandsBuildDir, { recursive: true, force: true });
578
- fs.mkdirSync(commandsBuildDir, { recursive: true });
579
- chokidar.watch(ctx.resolve.root(ctx.options.dir, "commands"), { ignoreInitial: true }).on("all", async (event, path2) => {
580
- if (event === "all" || event === "error" || event === "raw") {
1208
+ websocket.on("command-revision", (client) => {
1209
+ if (revision)
1210
+ client.send(JSON.stringify({ event: "command-revision", revision }));
1211
+ });
1212
+ websocket.on("registration-updated", () => websocket.broadcast({ event: "registration-updated" }));
1213
+ websocket.on("activity", (_client, message) => {
1214
+ websocket.broadcast(message);
1215
+ });
1216
+ });
1217
+ const dirty = /* @__PURE__ */ new Set();
1218
+ const modified = /* @__PURE__ */ new Set();
1219
+ nuxt.hook("nitro:init", (nitro) => {
1220
+ nitro.hooks.hook("compiled", () => {
1221
+ modified.forEach((file) => dirty.add(file));
1222
+ void rebuild();
1223
+ });
1224
+ });
1225
+ let building = false;
1226
+ let closed = false;
1227
+ async function rebuild() {
1228
+ if (building || !rollupConfig || closed)
581
1229
  return;
582
- }
583
- const fullPath = ctx.resolve.root(path2);
584
- if (fullPath.startsWith(commandsDir)) {
585
- path2 = ctx.resolve.root(path2);
586
- const command = processCommandFile(ctx, path2) ?? null;
587
- if (event === "add" || event === "change") {
588
- ctx.logger.log(`Dynamically loading slash command at ${path2}`);
589
- await generateDynamicCommandBuild(path2, rollupConfig, ctx);
1230
+ building = true;
1231
+ try {
1232
+ while (dirty.size) {
1233
+ if (closed)
1234
+ return;
1235
+ const changed = new Set(dirty);
1236
+ dirty.clear();
1237
+ const version = ++nextRevision;
1238
+ const initial = dependencies;
1239
+ const outputDir = path.join(hotDir, String(version));
1240
+ try {
1241
+ const snapshot = { ...ctx };
1242
+ if (liveReferenceFile) {
1243
+ collectContextMenus(snapshot);
1244
+ if (![...changed].some((file) => file.startsWith(commandIdPrefix))) {
1245
+ publishReference(snapshot);
1246
+ ctx.contextMenus = snapshot.contextMenus;
1247
+ continue;
1248
+ }
1249
+ }
1250
+ collectSlashCommands(snapshot, changed);
1251
+ const source = getSlashCommandTemplateContent(snapshot, true);
1252
+ const additions = await buildCommandUpdate(rollupConfig, source, outputDir, initial, updated, changed);
1253
+ if (initial !== dependencies || closed) {
1254
+ changed.forEach((file) => dirty.add(file));
1255
+ continue;
1256
+ }
1257
+ if (liveReferenceFile) {
1258
+ publishReference(snapshot);
1259
+ ctx.contextMenus = snapshot.contextMenus;
1260
+ }
1261
+ ctx.slashCommands = snapshot.slashCommands;
1262
+ for (const id of changed)
1263
+ updated.delete(id);
1264
+ additions.forEach((url, id) => updated.set(id, url));
1265
+ revision = version;
1266
+ websocket?.broadcast({ event: "command-revision", revision });
1267
+ websocket?.broadcast({ event: "full-update", commands: ctx.slashCommands });
1268
+ await updateTemplates({ filter: (template) => template.filename === "discord/slashCommands" });
1269
+ } catch (error) {
1270
+ ctx.logger.error("Could not reload slash commands:", error);
1271
+ const retry = dirty.size > 0;
1272
+ changed.forEach((file) => dirty.add(file));
1273
+ if (!retry)
1274
+ break;
1275
+ }
590
1276
  }
591
- websocket?.broadcast({ event, path: path2, command });
592
- await updateTemplates({
593
- filter: (template) => template.filename === "discord/slashCommands"
594
- });
1277
+ } finally {
1278
+ building = false;
1279
+ }
1280
+ }
1281
+ const watched = liveReferenceFile ? [commandsDir, ctx.resolve.root(options.dir, "context-menus")] : [commandsDir];
1282
+ const watcher = chokidar.watch(watched, { ignoreInitial: true }).on("all", (event, file) => {
1283
+ if (["add", "change", "unlink"].includes(event) && file.endsWith(".ts")) {
1284
+ const id = path.resolve(file).split(path.sep).join("/");
1285
+ dirty.add(id);
1286
+ modified.add(id);
1287
+ void rebuild();
595
1288
  }
596
1289
  });
597
- nuxt.hook("close", () => {
1290
+ nuxt.hook("close", async () => {
1291
+ closed = true;
1292
+ await watcher.close();
598
1293
  listener?.server.close();
599
1294
  websocket?.close();
600
1295
  });
601
- const packageJson = ctx.resolve.module("../package.json");
602
- if (fs.existsSync(packageJson) && JSON.parse(fs.readFileSync(packageJson, "utf-8")).name === "nuxt-discord") {
603
- (async () => {
604
- const { createGenerator } = await import('unocss');
605
- const config = (await import('../dist/runtime/client/uno.config.js')).default;
606
- const generator = await createGenerator(config);
607
- const clientDir = ctx.resolve.module("runtime/client");
608
- const generateCSS = async (path2) => {
609
- if (path2.startsWith(clientDir) && path2.endsWith(".vue")) {
610
- const content = fs.readFileSync(path2, "utf-8");
611
- const tokens = await generator.applyExtractors(content, path2);
612
- const { css } = await generator.generate(tokens);
613
- fs.writeFileSync(path2.replace(".vue", ".css"), css, "utf-8");
614
- }
615
- };
616
- const globPattern = `${clientDir}/**/*.vue`;
617
- fs.globSync(globPattern).forEach(generateCSS);
618
- addVitePlugin({
619
- name: "dev-nuxt-discord-generate-css",
620
- configureServer(server) {
621
- server.watcher.add(globPattern);
622
- server.watcher.on("change", generateCSS);
623
- }
624
- });
625
- })();
1296
+ }
1297
+ }
1298
+ async function buildCommandUpdate(config, source, outputDir, dependencies, updated, changed) {
1299
+ const additions = /* @__PURE__ */ new Map();
1300
+ const bundle = await rollup({
1301
+ ...config,
1302
+ input: registryEntry,
1303
+ treeshake: false,
1304
+ preserveEntrySignatures: "strict",
1305
+ plugins: [
1306
+ { name: "discord:hot-registry", resolveId: (id) => id === registryEntry ? id : null, load: (id) => id === registryEntry ? source : null },
1307
+ reuseCommandDependencies(dependencies, updated, changed),
1308
+ config.plugins
1309
+ ]
1310
+ });
1311
+ try {
1312
+ const { output } = await bundle.write({
1313
+ ...config.output,
1314
+ dir: outputDir,
1315
+ entryFileNames: (chunk) => chunk.facadeModuleId === registryEntry ? "commands.mjs" : "[name]-[hash].mjs",
1316
+ inlineDynamicImports: false,
1317
+ preserveModules: true,
1318
+ minifyInternalExports: false,
1319
+ manualChunks: void 0,
1320
+ sourcemap: false
1321
+ });
1322
+ for (const chunk of output) {
1323
+ if (chunk.type === "chunk" && chunk.facadeModuleId)
1324
+ additions.set(chunk.facadeModuleId, pathToFileURL(path.join(outputDir, chunk.fileName)).href);
626
1325
  }
1326
+ } finally {
1327
+ await bundle.close();
627
1328
  }
1329
+ return additions;
628
1330
  }
629
1331
  function createWebSocket() {
630
1332
  const wss = new WebSocketServer({ noServer: true });
@@ -673,34 +1375,6 @@ function createWebSocket() {
673
1375
  }
674
1376
  };
675
1377
  }
676
- async function generateDynamicCommandBuild(file, config, ctx) {
677
- let bundle;
678
- try {
679
- bundle = await rollup({
680
- ...config,
681
- input: file,
682
- plugins: [
683
- config.plugins,
684
- {
685
- name: "discord:resolve-alias-and-externalize",
686
- resolveId: (id) => {
687
- if (!id.includes(file) && !id.endsWith(".ts")) {
688
- return { id: resolveAlias(id), external: true };
689
- }
690
- }
691
- }
692
- ]
693
- });
694
- const { output } = await bundle.generate({ ...config.output, sourcemap: false });
695
- const outputFilePath = file.replace(ctx.resolve.root(ctx.nuxt.options.rootDir), ctx.nuxt.options.buildDir).replace(".ts", ".mjs");
696
- fs.mkdirSync(path.dirname(outputFilePath), { recursive: true });
697
- fs.writeFileSync(outputFilePath, output[0].code, { encoding: "utf-8", flush: true });
698
- } catch (error) {
699
- ctx.logger.error(`Error processing command file ${file}:`, error);
700
- return;
701
- }
702
- await bundle.close();
703
- }
704
1378
 
705
1379
  function prepareRuntimeConfig(ctx) {
706
1380
  ctx.nuxt.hook("nitro:config", (config) => {
@@ -709,107 +1383,34 @@ function prepareRuntimeConfig(ctx) {
709
1383
  config.runtimeConfig.discord.client = ctx.options.client;
710
1384
  config.runtimeConfig.discord.autoStart = ctx.options.autoStart;
711
1385
  config.runtimeConfig.discord.sync = ctx.options.watch.sync ?? false;
1386
+ config.runtimeConfig.discord.guilds = ctx.options.guilds ?? [];
712
1387
  config.runtimeConfig.discord.dir = ctx.resolve.root(ctx.options.dir);
713
1388
  config.runtimeConfig.discord.buildDir = ctx.nuxt.options.buildDir;
714
1389
  config.runtimeConfig.discord.rootDir = ctx.nuxt.options.rootDir;
1390
+ config.runtimeConfig.discord.interactionTimeout = ctx.options.interactionTimeout;
715
1391
  });
716
1392
  }
717
1393
 
718
- function prepareTemplates(ctx) {
719
- addServerTemplate({
720
- filename: "discord/slashCommands",
721
- getContents: () => getSlashCommandTemplateContent(
722
- ctx,
723
- /* commandRuntime */
724
- true
725
- )
726
- });
727
- addTemplate({
728
- filename: "discord/slashCommands",
729
- getContents: () => getSlashCommandTemplateContent(
730
- ctx,
731
- /* commandRuntime */
732
- false
733
- )
734
- });
735
- const typesTemplateDst = addTypeTemplate({
736
- filename: "discord/types.d.ts",
737
- // proposal-string-dedent when?
738
- getContents: () => `
739
- declare module 'discord/slashCommands' {
740
- declare const slashCommands: import('nuxt-discord').SlashCommandRuntime[]
741
- export default slashCommands
742
- }
743
-
744
- declare module '#build/discord/slashCommands' {
745
- declare const slashCommands: import('nuxt-discord').SlashCommand[]
746
- export default slashCommands
747
- }
748
-
749
- type integer = import('nuxt-discord').integer
750
-
751
- declare global {
752
- declare module 'nitropack/types' {
753
- interface NitroRuntimeHooks {
754
- 'discord:client:config': (options: import('nuxt-discord').NuxtDiscordOptions['client']) => void
755
- 'discord:client:ready': (client: DiscordClient) => void
756
- 'discord:client:error': (error: DiscordClientError) => void
757
- }
758
- }
759
-
760
- declare module '@nuxt/schema' {
761
- interface RuntimeConfig {
762
- discord: import('nuxt-discord').DiscordRuntimeConfig
763
- }
764
- interface PublicRuntimeConfig {
765
- discord: {
766
- wsUrl?: string
767
- }
768
- }
769
- }
770
- }
771
- `
772
- }).dst;
773
- ctx.nuxt.options.nitro.typescript ||= {};
774
- ctx.nuxt.options.nitro.typescript.tsConfig = defu(ctx.nuxt.options.nitro.typescript.tsConfig, {
775
- include: [typesTemplateDst]
776
- });
777
- }
778
- function getSlashCommandTemplateContent(ctx, commandRuntime) {
779
- const imports = commandRuntime ? Object.fromEntries(ctx.slashCommands.flatMap(
780
- function getImports(cmd) {
781
- const name = genSafeVariableName(cmd.path);
782
- return [
783
- [cmd.path, { name, code: genImport(cmd.path, [{ name: "default", as: name }]) }],
784
- ..."subcommands" in cmd ? cmd.subcommands.flatMap(getImports) : []
785
- ];
786
- }
787
- )) : {};
788
- return [
789
- ...Object.values(imports).map(({ code }) => code),
790
- `export default [
791
- ${ctx.slashCommands.map((cmd) => genCommandObject(cmd)).join(",\n")}]`
792
- ].join("\n");
793
- function genCommandObject({
794
- options,
795
- parents,
796
- subcommands,
797
- ...rest
798
- }) {
799
- return ` {
800
- ${Object.entries(rest).map(([key, value]) => `${key}: ${genString(value)}`).join(",\n ")},
801
- options: ${genArrayFromRaw(options, void 0, { preserveTypes: true })},
802
- ${subcommands.length > 0 ? `subcommands: [${subcommands.map(genCommandObject).join(",")}],` : ""}
803
- ${commandRuntime ? `...${imports[rest.path].name},` : ""}
804
- }`;
805
- }
806
- }
807
-
808
- const module = defineNuxtModule({
1394
+ const module$1 = defineNuxtModule({
809
1395
  meta: {
810
1396
  name: "nuxt-discord",
811
1397
  configKey: "discord"
812
1398
  },
1399
+ async moduleDependencies(nuxt) {
1400
+ if (nuxt.options.dev || nuxt.options._prepare)
1401
+ return { "@nuxt/ui": {} };
1402
+ let hosted = nuxt.options.discord && nuxt.options.discord.dashboard;
1403
+ for (const entry of nuxt.options.modules) {
1404
+ if (!Array.isArray(entry) || typeof entry[1]?.dashboard !== "boolean")
1405
+ continue;
1406
+ const { nuxtModule } = await loadNuxtModuleInstance(entry[0], nuxt);
1407
+ if ((await nuxtModule.getMeta?.())?.name === "nuxt-discord") {
1408
+ hosted = entry[1].dashboard;
1409
+ break;
1410
+ }
1411
+ }
1412
+ return hosted ? { "@nuxt/ui": {} } : {};
1413
+ },
813
1414
  defaults: {
814
1415
  client: {
815
1416
  intents: [GatewayIntentBits.Guilds],
@@ -829,18 +1430,146 @@ const module = defineNuxtModule({
829
1430
  },
830
1431
  setup(discordOptions, nuxt) {
831
1432
  const ctx = createContext(discordOptions, nuxt);
832
- addServerScanDir(ctx.resolve.module("runtime/server"));
833
- addImports([{
834
- name: "defineSlashCommand",
835
- as: "defineSlashCommand",
836
- from: ctx.resolve.module("runtime/server/utils/defineSlashCommand")
837
- }]);
1433
+ const development = nuxt.options.dev || nuxt.options._prepare;
1434
+ const hostedDashboard = !development && discordOptions.dashboard === true;
1435
+ const reference = resolveReference(discordOptions.reference);
1436
+ const liveReferenceFile = reference && nuxt.options.dev && discordOptions.watch.enabled ? join(nuxt.options.buildDir, "discord", "hmr", "reference.json") : void 0;
1437
+ if (reference) {
1438
+ addImports({ name: "useDiscordCommandReference", from: ctx.resolve.module("runtime/client/useDiscordCommandReference") });
1439
+ addComponent({ name: "DiscordCommandReference", filePath: ctx.resolve.module("runtime/client/components/CommandReference.vue") });
1440
+ addServerTemplate({
1441
+ filename: "discord/reference",
1442
+ getContents: () => [
1443
+ liveReferenceFile ? `import { readFile } from 'node:fs/promises'; export async function getCatalog() { return JSON.parse(await readFile(${JSON.stringify(liveReferenceFile)}, 'utf8')) }` : `const catalog = ${JSON.stringify(projectReference(ctx.slashCommands, ctx.contextMenus, reference.access))}; export const getCatalog = () => catalog`,
1444
+ `export const policy = ${JSON.stringify(reference)}`,
1445
+ `export const styles = ${JSON.stringify(readFileSync(ctx.resolve.module("runtime/client/reference.css"), "utf8"))}`
1446
+ ].join("\n")
1447
+ });
1448
+ const routes = [{ route: "/api/discord/reference", handler: "catalog" }];
1449
+ if (reference.page)
1450
+ routes.push({ route: "/commands", handler: "document" });
1451
+ if (reference.access !== "public") {
1452
+ for (const action of ["login", "callback", "logout"])
1453
+ routes.push({ route: `/__discord-reference/${action}`, handler: "oauth" });
1454
+ }
1455
+ for (const { route, handler } of routes) {
1456
+ addServerHandler({ route, method: route.endsWith("/logout") ? "post" : "get", handler: ctx.resolve.module(`runtime/reference/${handler}`) });
1457
+ extendRouteRules(route, { prerender: false, cache: false, isr: false, swr: false }, { override: true });
1458
+ }
1459
+ }
1460
+ if (hostedDashboard) {
1461
+ addServerHandler({ middleware: true, handler: ctx.resolve.module(reference ? "runtime/reference/hosted" : "runtime/dashboard/auth") });
1462
+ for (const route of ["/discord", "/discord/**", "/api/discord", "/api/discord/**"])
1463
+ extendRouteRules(route, { prerender: false, cache: false }, { override: true });
1464
+ for (const [path, method] of [
1465
+ ["catalog", "get"],
1466
+ ["activity", "get"],
1467
+ ["slash-command/all", "get"],
1468
+ ["slash-command/remote-all", "get"],
1469
+ ["slash-command/remote-diff", "post"],
1470
+ ["slash-command/register", "post"],
1471
+ ["slash-command/test", "post"],
1472
+ ["slash-command/autocomplete", "post"]
1473
+ ]) {
1474
+ addServerHandler({
1475
+ route: `/api/discord/${path}`,
1476
+ method,
1477
+ handler: ctx.resolve.module(`runtime/server/api/discord/${path}.${method}`)
1478
+ });
1479
+ }
1480
+ }
1481
+ if (development || hostedDashboard) {
1482
+ extendRouteRules("/discord", { ssr: false });
1483
+ extendRouteRules("/discord/**", { ssr: false });
1484
+ prepareClient(ctx);
1485
+ }
1486
+ if (development) {
1487
+ addServerScanDir(ctx.resolve.module("runtime/server"));
1488
+ } else {
1489
+ const plugin = ctx.resolve.module("runtime/server/plugins/discord");
1490
+ addServerPlugin(plugin);
1491
+ nuxt.hook("nitro:init", (nitro) => {
1492
+ nitro.hooks.hook("prerender:config", (config) => {
1493
+ config.plugins = config.plugins?.filter((entry) => entry !== plugin);
1494
+ });
1495
+ });
1496
+ addServerImportsDir(ctx.resolve.module("runtime/server/utils"));
1497
+ addServerImportsDir(ctx.resolve.module("runtime/server/utils/middleware"));
1498
+ }
1499
+ addImports([
1500
+ {
1501
+ name: "defineSlashCommand",
1502
+ as: "defineSlashCommand",
1503
+ from: ctx.resolve.module("runtime/server/utils/defineSlashCommand")
1504
+ },
1505
+ {
1506
+ name: "defineListener",
1507
+ as: "defineListener",
1508
+ from: ctx.resolve.module("runtime/server/utils/defineListener")
1509
+ },
1510
+ {
1511
+ name: "defineUserContextMenu",
1512
+ as: "defineUserContextMenu",
1513
+ from: ctx.resolve.module("runtime/server/utils/defineContextMenu")
1514
+ },
1515
+ {
1516
+ name: "defineMessageContextMenu",
1517
+ as: "defineMessageContextMenu",
1518
+ from: ctx.resolve.module("runtime/server/utils/defineContextMenu")
1519
+ },
1520
+ {
1521
+ name: "defineMiddleware",
1522
+ as: "defineMiddleware",
1523
+ from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
1524
+ },
1525
+ {
1526
+ name: "MiddlewareError",
1527
+ as: "MiddlewareError",
1528
+ from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
1529
+ },
1530
+ {
1531
+ name: "useMiddleware",
1532
+ as: "useMiddleware",
1533
+ from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
1534
+ },
1535
+ {
1536
+ name: "useMiddlewareContext",
1537
+ as: "useMiddlewareContext",
1538
+ from: ctx.resolve.module("runtime/server/utils/defineMiddleware")
1539
+ },
1540
+ {
1541
+ name: "guildOnly",
1542
+ as: "guildOnly",
1543
+ from: ctx.resolve.module("runtime/server/utils/middleware/guildOnly")
1544
+ },
1545
+ {
1546
+ name: "ownerOnly",
1547
+ as: "ownerOnly",
1548
+ from: ctx.resolve.module("runtime/server/utils/middleware/ownerOnly")
1549
+ },
1550
+ {
1551
+ name: "cooldown",
1552
+ as: "cooldown",
1553
+ from: ctx.resolve.module("runtime/server/utils/middleware/cooldown")
1554
+ },
1555
+ {
1556
+ name: "requireRole",
1557
+ as: "requireRole",
1558
+ from: ctx.resolve.module("runtime/server/utils/middleware/requireRole")
1559
+ },
1560
+ {
1561
+ name: "useTextChannel",
1562
+ as: "useTextChannel",
1563
+ from: ctx.resolve.module("runtime/server/utils/useTextChannel")
1564
+ }
1565
+ ]);
838
1566
  prepareRuntimeConfig(ctx);
839
1567
  collectSlashCommands(ctx);
1568
+ collectContextMenus(ctx);
1569
+ collectListeners(ctx);
840
1570
  prepareTemplates(ctx);
841
- prepareHMR(ctx);
842
- prepareClient(ctx);
1571
+ prepareHMR(ctx, liveReferenceFile);
843
1572
  }
844
1573
  });
845
1574
 
846
- export { module as default };
1575
+ export { module$1 as default };