seyfert 0.1.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +19 -30
  2. package/lib/api/CDN.d.ts +0 -8
  3. package/lib/api/CDN.js +7 -13
  4. package/lib/api/Router.d.ts +2 -2
  5. package/lib/api/Router.js +1 -1
  6. package/lib/api/Routes/applications.d.ts +1 -1
  7. package/lib/api/Routes/channels.d.ts +1 -1
  8. package/lib/api/Routes/gateway.d.ts +1 -1
  9. package/lib/api/Routes/guilds.d.ts +1 -1
  10. package/lib/api/Routes/interactions.d.ts +1 -1
  11. package/lib/api/Routes/invites.d.ts +1 -1
  12. package/lib/api/Routes/stage-instances.d.ts +1 -1
  13. package/lib/api/Routes/stickers.d.ts +1 -1
  14. package/lib/api/Routes/users.d.ts +1 -1
  15. package/lib/api/Routes/voice.d.ts +1 -1
  16. package/lib/api/Routes/webhooks.d.ts +1 -1
  17. package/lib/api/api.d.ts +44 -0
  18. package/lib/api/api.js +354 -0
  19. package/lib/api/bucket.d.ts +19 -0
  20. package/lib/api/bucket.js +71 -0
  21. package/lib/api/index.d.ts +1 -1
  22. package/lib/api/index.js +1 -1
  23. package/lib/api/shared.d.ts +33 -5
  24. package/lib/api/shared.js +2 -7
  25. package/lib/api/utils/constants.d.ts +1 -30
  26. package/lib/api/utils/constants.js +2 -41
  27. package/lib/api/utils/types.d.ts +1 -320
  28. package/lib/api/utils/utils.d.ts +0 -38
  29. package/lib/api/utils/utils.js +1 -139
  30. package/lib/builders/ActionRow.js +1 -1
  31. package/lib/builders/Attachment.d.ts +14 -6
  32. package/lib/builders/Attachment.js +30 -7
  33. package/lib/builders/Button.d.ts +5 -14
  34. package/lib/builders/Button.js +0 -11
  35. package/lib/builders/{MessageEmbed.d.ts → Embed.d.ts} +15 -15
  36. package/lib/builders/{MessageEmbed.js → Embed.js} +16 -16
  37. package/lib/builders/Modal.js +1 -1
  38. package/lib/builders/SelectMenu.d.ts +14 -15
  39. package/lib/builders/SelectMenu.js +19 -18
  40. package/lib/builders/index.d.ts +1 -1
  41. package/lib/builders/index.js +1 -1
  42. package/lib/builders/types.d.ts +2 -2
  43. package/lib/cache/adapters/default.d.ts +1 -0
  44. package/lib/cache/adapters/default.js +3 -2
  45. package/lib/cache/adapters/redis.d.ts +3 -3
  46. package/lib/cache/adapters/redis.js +14 -5
  47. package/lib/cache/adapters/types.d.ts +1 -0
  48. package/lib/cache/adapters/workeradapter.d.ts +10 -1
  49. package/lib/cache/adapters/workeradapter.js +8 -3
  50. package/lib/cache/index.d.ts +18 -5
  51. package/lib/cache/index.js +23 -9
  52. package/lib/cache/resources/channels.d.ts +6 -2
  53. package/lib/cache/resources/channels.js +12 -6
  54. package/lib/cache/resources/default/base.d.ts +17 -16
  55. package/lib/cache/resources/default/base.js +25 -24
  56. package/lib/cache/resources/default/guild-based.d.ts +22 -19
  57. package/lib/cache/resources/default/guild-based.js +32 -31
  58. package/lib/cache/resources/default/guild-related.d.ts +22 -19
  59. package/lib/cache/resources/default/guild-related.js +37 -43
  60. package/lib/cache/resources/emojis.d.ts +4 -2
  61. package/lib/cache/resources/emojis.js +8 -6
  62. package/lib/cache/resources/guilds.d.ts +4 -2
  63. package/lib/cache/resources/guilds.js +15 -8
  64. package/lib/cache/resources/members.d.ts +4 -2
  65. package/lib/cache/resources/members.js +16 -13
  66. package/lib/cache/resources/overwrites.d.ts +25 -0
  67. package/lib/cache/resources/overwrites.js +39 -0
  68. package/lib/cache/resources/presence.js +3 -4
  69. package/lib/cache/resources/roles.d.ts +4 -2
  70. package/lib/cache/resources/roles.js +8 -6
  71. package/lib/cache/resources/stickers.d.ts +4 -2
  72. package/lib/cache/resources/stickers.js +8 -6
  73. package/lib/cache/resources/threads.d.ts +4 -2
  74. package/lib/cache/resources/threads.js +8 -6
  75. package/lib/cache/resources/users.d.ts +4 -2
  76. package/lib/cache/resources/users.js +8 -6
  77. package/lib/cache/resources/voice-states.d.ts +3 -3
  78. package/lib/cache/resources/voice-states.js +6 -7
  79. package/lib/client/base.d.ts +48 -16
  80. package/lib/client/base.js +19 -15
  81. package/lib/client/client.d.ts +15 -4
  82. package/lib/client/client.js +26 -28
  83. package/lib/client/httpclient.d.ts +3 -5
  84. package/lib/client/httpclient.js +29 -16
  85. package/lib/client/{oninteraction.d.ts → oninteractioncreate.d.ts} +1 -1
  86. package/lib/client/{oninteraction.js → oninteractioncreate.js} +34 -23
  87. package/lib/client/onmessagecreate.d.ts +3 -0
  88. package/lib/client/onmessagecreate.js +337 -0
  89. package/lib/client/workerclient.d.ts +19 -2
  90. package/lib/client/workerclient.js +156 -46
  91. package/lib/collection.d.ts +1 -1
  92. package/lib/collection.js +9 -6
  93. package/lib/commands/applications/chat.d.ts +32 -25
  94. package/lib/commands/applications/chat.js +51 -34
  95. package/lib/commands/applications/chatcontext.d.ts +34 -16
  96. package/lib/commands/applications/chatcontext.js +99 -20
  97. package/lib/commands/applications/menu.d.ts +9 -8
  98. package/lib/commands/applications/menu.js +14 -5
  99. package/lib/commands/applications/menucontext.d.ts +27 -10
  100. package/lib/commands/applications/menucontext.js +51 -7
  101. package/lib/commands/applications/options.d.ts +13 -13
  102. package/lib/commands/applications/shared.d.ts +7 -2
  103. package/lib/commands/decorators.d.ts +14 -14
  104. package/lib/commands/decorators.js +9 -5
  105. package/lib/commands/handler.d.ts +2 -1
  106. package/lib/commands/handler.js +60 -14
  107. package/lib/commands/index.d.ts +1 -1
  108. package/lib/commands/index.js +2 -1
  109. package/lib/commands/optionresolver.d.ts +6 -5
  110. package/lib/commands/optionresolver.js +10 -6
  111. package/lib/common/bot/watcher.d.ts +3 -3
  112. package/lib/common/bot/watcher.js +3 -1
  113. package/lib/common/index.d.ts +1 -1
  114. package/lib/common/index.js +2 -1
  115. package/lib/common/it/logger.d.ts +11 -0
  116. package/lib/common/it/logger.js +51 -2
  117. package/lib/common/it/utils.d.ts +3 -13
  118. package/lib/common/it/utils.js +9 -30
  119. package/lib/common/shorters/channels.d.ts +55 -5
  120. package/lib/common/shorters/channels.js +59 -0
  121. package/lib/common/shorters/guilds.d.ts +5 -2
  122. package/lib/common/shorters/guilds.js +18 -0
  123. package/lib/common/shorters/messages.js +0 -2
  124. package/lib/common/shorters/overwrites.d.ts +29 -0
  125. package/lib/common/shorters/overwrites.js +63 -0
  126. package/lib/common/shorters/roles.js +3 -3
  127. package/lib/common/shorters/webhook.d.ts +2 -2
  128. package/lib/common/types/util.d.ts +3 -2
  129. package/lib/common/types/write.d.ts +3 -7
  130. package/lib/components/handler.d.ts +11 -17
  131. package/lib/components/handler.js +45 -93
  132. package/lib/components/index.d.ts +0 -1
  133. package/lib/components/index.js +0 -1
  134. package/lib/components/listener.d.ts +2 -2
  135. package/lib/components/listener.js +2 -3
  136. package/lib/events/event.d.ts +2 -2
  137. package/lib/events/handler.d.ts +3 -2
  138. package/lib/events/handler.js +14 -6
  139. package/lib/events/hooks/dispatch.d.ts +2 -1
  140. package/lib/events/hooks/dispatch.js +5 -1
  141. package/lib/events/hooks/thread.d.ts +63 -63
  142. package/lib/index.d.ts +8 -5
  143. package/lib/index.js +20 -10
  144. package/lib/langs/handler.d.ts +6 -4
  145. package/lib/langs/handler.js +10 -8
  146. package/lib/langs/router.d.ts +8 -9
  147. package/lib/langs/router.js +5 -5
  148. package/lib/structures/ClientUser.d.ts +1 -16
  149. package/lib/structures/ClientUser.js +0 -31
  150. package/lib/structures/Guild.d.ts +1 -1
  151. package/lib/structures/GuildMember.d.ts +12 -0
  152. package/lib/structures/GuildMember.js +14 -0
  153. package/lib/structures/GuildRole.d.ts +4 -2
  154. package/lib/structures/GuildRole.js +4 -1
  155. package/lib/structures/GuildTemplate.js +1 -1
  156. package/lib/structures/Interaction.d.ts +2 -0
  157. package/lib/structures/Interaction.js +12 -13
  158. package/lib/structures/Message.d.ts +7 -2
  159. package/lib/structures/Message.js +6 -3
  160. package/lib/structures/Sticker.d.ts +1 -1
  161. package/lib/structures/Sticker.js +1 -1
  162. package/lib/structures/User.d.ts +5 -0
  163. package/lib/structures/User.js +3 -0
  164. package/lib/structures/Webhook.d.ts +1 -1
  165. package/lib/structures/Webhook.js +1 -1
  166. package/lib/structures/channels.d.ts +45 -6
  167. package/lib/structures/channels.js +23 -7
  168. package/lib/structures/extra/BitField.d.ts +9 -6
  169. package/lib/structures/extra/BitField.js +27 -3
  170. package/lib/structures/extra/Permissions.d.ts +6 -1
  171. package/lib/structures/extra/Permissions.js +7 -0
  172. package/lib/websocket/constants/index.js +1 -3
  173. package/lib/websocket/discord/basesocket.js +0 -1
  174. package/lib/websocket/discord/shared.d.ts +2 -0
  175. package/lib/websocket/discord/worker.d.ts +23 -7
  176. package/lib/websocket/discord/workermanager.d.ts +32 -5
  177. package/lib/websocket/discord/workermanager.js +98 -29
  178. package/package.json +23 -21
  179. package/lib/api/REST.d.ts +0 -127
  180. package/lib/api/REST.js +0 -424
  181. package/lib/api/errors/DiscordAPIError.d.ts +0 -51
  182. package/lib/api/errors/DiscordAPIError.js +0 -81
  183. package/lib/api/errors/HTTPError.d.ts +0 -20
  184. package/lib/api/errors/HTTPError.js +0 -28
  185. package/lib/api/errors/RateLimitError.d.ts +0 -19
  186. package/lib/api/errors/RateLimitError.js +0 -37
  187. package/lib/api/handlers/BurstHandler.d.ts +0 -51
  188. package/lib/api/handlers/BurstHandler.js +0 -124
  189. package/lib/api/handlers/SequentialHandler.d.ts +0 -81
  190. package/lib/api/handlers/SequentialHandler.js +0 -365
  191. package/lib/api/handlers/Shared.d.ts +0 -14
  192. package/lib/api/handlers/Shared.js +0 -125
  193. package/lib/api/interfaces/Handler.d.ts +0 -21
  194. package/lib/api/interfaces/Handler.js +0 -2
  195. package/lib/websocket/discord/handlemessage.d.ts +0 -0
  196. package/lib/websocket/discord/handlemessage.js +0 -1
  197. package/lib/websocket/discord/memberUpdate.d.ts +0 -16
  198. package/lib/websocket/discord/memberUpdate.js +0 -47
@@ -0,0 +1,337 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.onMessageCreate = void 0;
4
+ const v10_1 = require("discord-api-types/v10");
5
+ const __1 = require("..");
6
+ const structures_1 = require("../structures");
7
+ function getCommandFromContent(commandRaw, self) {
8
+ const parentName = commandRaw[0];
9
+ const groupName = commandRaw.length === 3 ? commandRaw[1] : undefined;
10
+ const subcommandName = groupName ? commandRaw[2] : commandRaw[1];
11
+ const parent = self.commands.values.find(x => x.name === parentName);
12
+ const fullCommandName = `${parentName}${groupName ? ` ${groupName} ${subcommandName}` : ` ${subcommandName ?? ''}`}`;
13
+ if (!(parent instanceof __1.Command))
14
+ return { fullCommandName };
15
+ if (groupName && !parent.groups?.[groupName])
16
+ return getCommandFromContent([parentName, subcommandName], self);
17
+ if (subcommandName && !parent.options?.some(x => x instanceof __1.SubCommand && x.name === subcommandName))
18
+ return getCommandFromContent([parentName], self);
19
+ const command = groupName || subcommandName
20
+ ? parent.options?.find(opt => {
21
+ if (opt instanceof __1.SubCommand) {
22
+ if (groupName) {
23
+ if (opt.group !== groupName)
24
+ return false;
25
+ }
26
+ if (opt.group && !groupName)
27
+ return false;
28
+ return subcommandName === opt.name;
29
+ }
30
+ return false;
31
+ })
32
+ : parent;
33
+ return {
34
+ command,
35
+ fullCommandName,
36
+ parent,
37
+ };
38
+ }
39
+ async function onMessageCreate(self, rawMessage, shardId) {
40
+ if (!self.options?.commands)
41
+ return;
42
+ const message = new structures_1.Message(self, rawMessage);
43
+ const prefixes = ((await self.options.commands.prefix?.(message)) ?? []).sort((a, b) => b.length - a.length);
44
+ const prefix = prefixes.find(x => message.content.startsWith(x));
45
+ if (!prefix || !message.content.startsWith(prefix))
46
+ return;
47
+ const content = message.content.slice(prefix.length).trimStart();
48
+ const { fullCommandName, command, parent } = getCommandFromContent(content.split(' ').filter(x => x), self);
49
+ if (!command)
50
+ return;
51
+ if (!command.run)
52
+ return self.logger.warn(`${fullCommandName} command does not have 'run' callback`);
53
+ if (command.dm && !message.guildId)
54
+ return;
55
+ if (command.guild_id && !command.guild_id?.includes(message.guildId))
56
+ return;
57
+ const resolved = {
58
+ channels: {},
59
+ roles: {},
60
+ users: {},
61
+ members: {},
62
+ attachments: {},
63
+ };
64
+ const args = (self.options?.commands?.argsParser ?? defaultArgsParser)(content, command);
65
+ const { options, errors } = await parseOptions(self, command, rawMessage, args, resolved);
66
+ const optionsResolver = new __1.OptionResolver(self, options, parent, message.guildId, resolved);
67
+ const context = new __1.CommandContext(self, message, optionsResolver, shardId);
68
+ try {
69
+ if (command.botPermissions && message.guildId) {
70
+ const meMember = await self.cache.members?.get(self.botId, message.guildId);
71
+ if (!meMember)
72
+ return; //enable member cache and "Guilds" intent, lol
73
+ const appPermissions = await meMember.fetchPermissions();
74
+ const permissions = appPermissions.missings(...appPermissions.values(command.botPermissions));
75
+ if (permissions.length) {
76
+ return command.onPermissionsFail?.(context, appPermissions.keys(permissions));
77
+ }
78
+ }
79
+ if (errors.length) {
80
+ return command.onOptionsError?.(context, Object.fromEntries(errors.map(x => {
81
+ return [
82
+ x.name,
83
+ {
84
+ failed: true,
85
+ value: x.error,
86
+ },
87
+ ];
88
+ })));
89
+ }
90
+ const [erroredOptions, result] = await command.__runOptions(context, optionsResolver);
91
+ if (erroredOptions) {
92
+ return command.onOptionsError?.(context, result);
93
+ }
94
+ const resultRunGlobalMiddlewares = await command.__runGlobalMiddlewares(context);
95
+ if (resultRunGlobalMiddlewares.pass) {
96
+ return;
97
+ }
98
+ if ('error' in resultRunGlobalMiddlewares) {
99
+ return command.onMiddlewaresError?.(context, resultRunGlobalMiddlewares.error ?? 'Unknown error');
100
+ }
101
+ const resultRunMiddlewares = await command.__runMiddlewares(context);
102
+ if (resultRunMiddlewares.pass) {
103
+ return;
104
+ }
105
+ if ('error' in resultRunMiddlewares) {
106
+ return command.onMiddlewaresError?.(context, resultRunMiddlewares.error ?? 'Unknown error');
107
+ }
108
+ try {
109
+ await command.run?.(context);
110
+ await command.onAfterRun?.(context, undefined);
111
+ }
112
+ catch (error) {
113
+ await command.onRunError?.(context, error);
114
+ await command.onAfterRun?.(context, error);
115
+ }
116
+ }
117
+ catch (error) {
118
+ try {
119
+ await command.onInternalError?.(self, error);
120
+ }
121
+ catch {
122
+ // supress error
123
+ }
124
+ }
125
+ }
126
+ exports.onMessageCreate = onMessageCreate;
127
+ async function parseOptions(self, command, message, args, resolved) {
128
+ const options = [];
129
+ const errors = [];
130
+ for (const i of (command.options ?? [])) {
131
+ let value;
132
+ let indexAttachment = -1;
133
+ switch (i.type) {
134
+ case v10_1.ApplicationCommandOptionType.Attachment:
135
+ if (message.attachments[++indexAttachment]) {
136
+ value = message.attachments[indexAttachment].id;
137
+ resolved.attachments[value] = message.attachments[indexAttachment];
138
+ }
139
+ break;
140
+ case v10_1.ApplicationCommandOptionType.Boolean:
141
+ if (args[i.name]) {
142
+ value = ['yes', 'y', 'true', 'treu'].includes(args[i.name].toLowerCase());
143
+ }
144
+ break;
145
+ case v10_1.ApplicationCommandOptionType.Channel:
146
+ {
147
+ const rawId = message.content.match(/(?<=<#)[0-9]{17,19}(?=>)/g)?.find(x => args[i.name]?.includes(x));
148
+ if (rawId) {
149
+ const channel = i.required ? await self.channels.fetch(rawId) : await self.cache.channels?.get(rawId);
150
+ if (channel) {
151
+ if ('channel_types' in i) {
152
+ if (!i.channel_types.includes(channel.type)) {
153
+ errors.push({
154
+ name: i.name,
155
+ error: `The entered channel type is not one of ${i
156
+ .channel_types.map(t => v10_1.ChannelType[t])
157
+ .join(', ')}`,
158
+ });
159
+ break;
160
+ }
161
+ }
162
+ value = rawId;
163
+ //@ts-expect-error
164
+ resolved.channels[rawId] = channel;
165
+ }
166
+ }
167
+ }
168
+ break;
169
+ case v10_1.ApplicationCommandOptionType.Mentionable:
170
+ {
171
+ const matches = message.content.match(/<@[0-9]{17,19}(?=>)|<@&[0-9]{17,19}(?=>)/g) ?? [];
172
+ for (const match of matches) {
173
+ if (match.includes('&')) {
174
+ const rawId = match.slice(3);
175
+ if (rawId) {
176
+ const role = i.required
177
+ ? (await self.roles.list(message.guild_id)).find(x => x.id === rawId)
178
+ : await self.cache.roles?.get(rawId);
179
+ if (role) {
180
+ value = rawId;
181
+ //@ts-expect-error
182
+ resolved.roles[rawId] = role;
183
+ break;
184
+ }
185
+ }
186
+ }
187
+ else {
188
+ const rawId = match.slice(2);
189
+ const raw = message.mentions.find(x => rawId === x.id);
190
+ if (raw) {
191
+ value = raw.id;
192
+ resolved.users[raw.id] = raw;
193
+ break;
194
+ }
195
+ }
196
+ }
197
+ }
198
+ break;
199
+ case v10_1.ApplicationCommandOptionType.Role:
200
+ {
201
+ const rawId = message.mention_roles.find(x => args[i.name]?.includes(x));
202
+ if (rawId) {
203
+ const role = i.required
204
+ ? (await self.roles.list(message.guild_id)).find(x => x.id === rawId) //why, discord, why
205
+ : await self.cache.roles?.get(rawId);
206
+ if (role) {
207
+ value = rawId;
208
+ //@ts-expect-error
209
+ resolved.roles[rawId] = role;
210
+ }
211
+ }
212
+ }
213
+ break;
214
+ case v10_1.ApplicationCommandOptionType.User:
215
+ {
216
+ const raw = message.mentions.find(x => args[i.name]?.includes(x.id));
217
+ if (raw) {
218
+ value = raw.id;
219
+ resolved.users[raw.id] = raw;
220
+ }
221
+ }
222
+ break;
223
+ case v10_1.ApplicationCommandOptionType.String:
224
+ {
225
+ value = args[i.name];
226
+ const option = i;
227
+ if (value) {
228
+ if (option.min_length) {
229
+ if (value.length < option.min_length) {
230
+ value = undefined;
231
+ errors.push({
232
+ name: i.name,
233
+ error: `The entered string has less than ${option.min_length} characters. The minimum required is ${option.min_length} characters.`,
234
+ });
235
+ break;
236
+ }
237
+ }
238
+ if (option.max_length) {
239
+ if (value.length > option.max_length) {
240
+ value = undefined;
241
+ errors.push({
242
+ name: i.name,
243
+ error: `The entered string has more than ${option.max_length} characters. The maximum required is ${option.max_length} characters.`,
244
+ });
245
+ break;
246
+ }
247
+ }
248
+ if (option.choices?.length) {
249
+ if (!option.choices.some(x => x.name === value)) {
250
+ value = undefined;
251
+ errors.push({
252
+ name: i.name,
253
+ error: `The entered choice is invalid. Please choose one of the following options: ${option.choices
254
+ .map(x => x.name)
255
+ .join(', ')}.`,
256
+ });
257
+ break;
258
+ }
259
+ value = option.choices.find(x => x.name === value).value;
260
+ }
261
+ }
262
+ }
263
+ break;
264
+ case v10_1.ApplicationCommandOptionType.Number:
265
+ case v10_1.ApplicationCommandOptionType.Integer:
266
+ {
267
+ value = Number(args[i.name]);
268
+ if (args[i.name] === undefined) {
269
+ value = undefined;
270
+ break;
271
+ }
272
+ if (Number.isNaN(value)) {
273
+ value = undefined;
274
+ errors.push({
275
+ name: i.name,
276
+ error: 'The entered choice is an invalid number.',
277
+ });
278
+ break;
279
+ }
280
+ const option = i;
281
+ if (option.min_value) {
282
+ if (value < option.min_value) {
283
+ value = undefined;
284
+ errors.push({
285
+ name: i.name,
286
+ error: `The entered number is less than ${option.min_value}. The minimum allowed is ${option.min_value}`,
287
+ });
288
+ break;
289
+ }
290
+ }
291
+ if (option.max_value) {
292
+ if (value > option.max_value) {
293
+ value = undefined;
294
+ errors.push({
295
+ name: i.name,
296
+ error: `The entered number is greater than ${option.max_value}. The maximum allowed is ${option.max_value}`,
297
+ });
298
+ break;
299
+ }
300
+ }
301
+ if (option.choices?.length) {
302
+ if (!option.choices.some(x => x.name === value)) {
303
+ value = undefined;
304
+ errors.push({
305
+ name: i.name,
306
+ error: `The entered choice is invalid. Please choose one of the following options: ${option.choices
307
+ .map(x => x.name)
308
+ .join(', ')}.`,
309
+ });
310
+ break;
311
+ }
312
+ value = option.choices.find(x => x.name === value).value;
313
+ }
314
+ }
315
+ break;
316
+ default:
317
+ break;
318
+ }
319
+ if (value !== undefined) {
320
+ options.push({
321
+ name: i.name,
322
+ type: i.type,
323
+ value,
324
+ });
325
+ }
326
+ }
327
+ return { errors, options };
328
+ }
329
+ function defaultArgsParser(content) {
330
+ const args = {};
331
+ for (const i of content.match(/-(.*?)(?=\s-|$)/gs) ?? []) {
332
+ args[i.slice(1).split(' ')[0]] = i.split(' ').slice(1).join(' ');
333
+ }
334
+ return args;
335
+ }
336
+ //-(.*?)(?=\s-|$)/gs
337
+ //-(?<text>[^-]*)/gm
@@ -1,28 +1,45 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ /// <reference types="node" />
5
+ /// <reference types="node" />
1
6
  import type { Cache } from '../cache';
2
7
  import type { GatewayDispatchPayload, When } from '../common';
3
8
  import { Logger, type DeepPartial } from '../common';
4
9
  import { EventHandler } from '../events';
5
10
  import { ClientUser } from '../structures';
6
- import { Shard } from '../websocket';
11
+ import { Shard, type ShardManagerOptions } from '../websocket';
7
12
  import type { WorkerShardInfo } from '../websocket/discord/worker';
8
13
  import type { ManagerMessages } from '../websocket/discord/workermanager';
9
14
  import type { BaseClientOptions, StartOptions } from './base';
10
15
  import { BaseClient } from './base';
16
+ import type { Client } from './client';
11
17
  export declare class WorkerClient<Ready extends boolean = boolean> extends BaseClient {
18
+ private __handleGuilds?;
12
19
  logger: Logger;
13
20
  events: EventHandler;
14
21
  me: When<Ready, ClientUser>;
22
+ promises: Map<string, {
23
+ resolve: (value: any) => void;
24
+ timeout: NodeJS.Timeout;
25
+ }>;
15
26
  shards: Map<number, Shard>;
16
27
  options: WorkerClientOptions | undefined;
17
28
  constructor(options?: WorkerClientOptions);
18
29
  get workerId(): number;
30
+ get latency(): number;
19
31
  start(options?: Omit<DeepPartial<StartOptions>, 'httpConnection' | 'token' | 'connection'>): Promise<void>;
20
32
  loadEvents(dir?: string): Promise<void>;
21
- protected handleManagerMessages(data: ManagerMessages): Promise<void>;
33
+ protected handleManagerMessages(data: ManagerMessages): Promise<any>;
34
+ private generateNonce;
35
+ private generateSendPromise;
36
+ tellWorker(workerId: number, func: (_: this) => {}): Promise<unknown>;
22
37
  protected onPacket(packet: GatewayDispatchPayload, shardId: number): Promise<void>;
23
38
  }
24
39
  export declare function generateShardInfo(shard: Shard): WorkerShardInfo;
25
40
  interface WorkerClientOptions extends BaseClientOptions {
26
41
  disabledCache: Cache['disabledCache'];
42
+ commands?: NonNullable<Client['options']>['commands'];
43
+ handlePayload?: ShardManagerOptions['handlePayload'];
27
44
  }
28
45
  export {};
@@ -1,21 +1,26 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateShardInfo = exports.WorkerClient = void 0;
4
+ const node_crypto_1 = require("node:crypto");
4
5
  const node_worker_threads_1 = require("node:worker_threads");
6
+ const __1 = require("..");
5
7
  const cache_1 = require("../cache");
6
8
  const common_1 = require("../common");
7
9
  const events_1 = require("../events");
8
10
  const structures_1 = require("../structures");
9
11
  const websocket_1 = require("../websocket");
10
12
  const base_1 = require("./base");
11
- const oninteraction_1 = require("./oninteraction");
13
+ const oninteractioncreate_1 = require("./oninteractioncreate");
14
+ const onmessagecreate_1 = require("./onmessagecreate");
12
15
  const workerData = node_worker_threads_1.workerData;
13
16
  class WorkerClient extends base_1.BaseClient {
17
+ __handleGuilds = new Set();
14
18
  logger = new common_1.Logger({
15
19
  name: `[Worker #${workerData.workerId}]`,
16
20
  });
17
21
  events = new events_1.EventHandler(this.logger);
18
22
  me;
23
+ promises = new Map();
19
24
  shards = new Map();
20
25
  constructor(options) {
21
26
  super(options);
@@ -35,10 +40,24 @@ class WorkerClient extends base_1.BaseClient {
35
40
  logLevel: common_1.LogLevels.Debug,
36
41
  });
37
42
  }
43
+ if (workerData.workerProxy) {
44
+ this.setServices({
45
+ rest: new __1.ApiHandler({
46
+ token: workerData.token,
47
+ workerProxy: true,
48
+ debug: workerData.debug,
49
+ }),
50
+ });
51
+ }
38
52
  }
39
53
  get workerId() {
40
54
  return workerData.workerId;
41
55
  }
56
+ get latency() {
57
+ let acc = 0;
58
+ this.shards.forEach(s => (acc += s.latency));
59
+ return acc / this.shards.size;
60
+ }
42
61
  async start(options = {}) {
43
62
  await super.start(options);
44
63
  await this.loadEvents(options.eventsDir);
@@ -54,8 +73,10 @@ class WorkerClient extends base_1.BaseClient {
54
73
  async handleManagerMessages(data) {
55
74
  switch (data.type) {
56
75
  case 'CACHE_RESULT':
57
- if (this.cache.adapter.promises.has(data.nonce)) {
58
- this.cache.adapter.promises.get(data.nonce)?.(data.result);
76
+ if (this.cache.adapter instanceof cache_1.WorkerAdapter && this.cache.adapter.promises.has(data.nonce)) {
77
+ const cacheData = this.cache.adapter.promises.get(data.nonce);
78
+ clearTimeout(cacheData.timeout);
79
+ cacheData.resolve(data.result);
59
80
  this.cache.adapter.promises.delete(data.nonce);
60
81
  }
61
82
  break;
@@ -72,6 +93,7 @@ class WorkerClient extends base_1.BaseClient {
72
93
  node_worker_threads_1.parentPort.postMessage({
73
94
  type: 'RESULT_PAYLOAD',
74
95
  nonce: data.nonce,
96
+ workerId: this.workerId,
75
97
  });
76
98
  }
77
99
  break;
@@ -90,6 +112,7 @@ class WorkerClient extends base_1.BaseClient {
90
112
  {
91
113
  const cache = this.cache;
92
114
  const onPacket = this.onPacket.bind(this);
115
+ const handlePayload = this.options?.handlePayload?.bind(this);
93
116
  for (const id of workerData.shards) {
94
117
  let shard = this.shards.get(id);
95
118
  if (!shard) {
@@ -100,6 +123,7 @@ class WorkerClient extends base_1.BaseClient {
100
123
  compress: data.compress,
101
124
  debugger: this.debugger,
102
125
  async handlePayload(shardId, payload) {
126
+ await handlePayload?.(shardId, payload);
103
127
  await cache.onPacket(payload);
104
128
  await onPacket?.(payload, shardId);
105
129
  node_worker_threads_1.parentPort.postMessage({
@@ -131,6 +155,7 @@ class WorkerClient extends base_1.BaseClient {
131
155
  ...generateShardInfo(shard),
132
156
  nonce: data.nonce,
133
157
  type: 'SHARD_INFO',
158
+ workerId: this.workerId,
134
159
  });
135
160
  }
136
161
  break;
@@ -145,60 +170,145 @@ class WorkerClient extends base_1.BaseClient {
145
170
  }
146
171
  break;
147
172
  case 'BOT_READY':
148
- if (this.events.values.BOT_READY &&
149
- (this.events.values.BOT_READY.fired ? !this.events.values.BOT_READY.data.once : true)) {
150
- this.events.values.BOT_READY.fired = true;
151
- await this.events.values.BOT_READY.run(this.me, this, -1);
173
+ await this.events.runEvent('BOT_READY', this, this.me, -1);
174
+ break;
175
+ case 'API_RESPONSE':
176
+ {
177
+ const promise = this.rest.workerPromises.get(data.nonce);
178
+ if (!promise)
179
+ return;
180
+ this.rest.workerPromises.delete(data.nonce);
181
+ if (data.error)
182
+ return promise.reject(data.error);
183
+ promise.resolve(data.response);
184
+ }
185
+ break;
186
+ case 'EXECUTE_EVAL':
187
+ {
188
+ let result;
189
+ try {
190
+ // biome-ignore lint/security/noGlobalEval: yes
191
+ result = await eval(`
192
+ (${data.func})(this)
193
+ `);
194
+ }
195
+ catch (e) {
196
+ result = e;
197
+ }
198
+ node_worker_threads_1.parentPort.postMessage({
199
+ type: 'EVAL_RESPONSE',
200
+ response: result,
201
+ workerId: workerData.workerId,
202
+ nonce: data.nonce,
203
+ });
204
+ }
205
+ break;
206
+ case 'EVAL_RESPONSE':
207
+ {
208
+ const evalResponse = this.promises.get(data.nonce);
209
+ if (!evalResponse)
210
+ return;
211
+ this.promises.delete(data.nonce);
212
+ clearTimeout(evalResponse.timeout);
213
+ evalResponse.resolve(data.response);
152
214
  }
153
215
  break;
154
216
  }
155
217
  }
218
+ generateNonce(large = true) {
219
+ const uuid = (0, node_crypto_1.randomUUID)();
220
+ const nonce = large ? uuid : uuid.split('-')[0];
221
+ if (this.promises.has(nonce))
222
+ return this.generateNonce(large);
223
+ return nonce;
224
+ }
225
+ generateSendPromise(nonce, message = 'Timeout') {
226
+ let resolve = (_) => {
227
+ /**/
228
+ };
229
+ let timeout = -1;
230
+ const promise = new Promise((res, rej) => {
231
+ resolve = res;
232
+ timeout = setTimeout(() => {
233
+ this.promises.delete(nonce);
234
+ rej(new Error(message));
235
+ }, 60e3);
236
+ });
237
+ this.promises.set(nonce, { resolve, timeout });
238
+ return promise;
239
+ }
240
+ tellWorker(workerId, func) {
241
+ const nonce = this.generateNonce();
242
+ node_worker_threads_1.parentPort.postMessage({
243
+ type: 'EVAL',
244
+ func: func.toString(),
245
+ toWorkerId: workerId,
246
+ workerId: workerData.workerId,
247
+ nonce,
248
+ });
249
+ return this.generateSendPromise(nonce);
250
+ }
156
251
  async onPacket(packet, shardId) {
252
+ await this.events.execute('RAW', packet, this, shardId);
157
253
  switch (packet.t) {
158
- case 'READY':
159
- for (const g of packet.d.guilds) {
160
- this.__handleGuilds.add(g.id);
161
- }
162
- this.botId = packet.d.user.id;
163
- this.applicationId = packet.d.application.id;
164
- this.me = new structures_1.ClientUser(this, packet.d.user, packet.d.application);
165
- if (!this.__handleGuilds.size) {
166
- if ([...this.shards.values()].every(shard => shard.data.session_id) &&
167
- this.events.values.WORKER_READY &&
168
- (this.events.values.WORKER_READY.fired ? !this.events.values.WORKER_READY.data.once : true)) {
169
- node_worker_threads_1.parentPort.postMessage({
170
- type: 'WORKER_READY',
171
- workerId: this.workerId,
172
- });
173
- this.events.values.WORKER_READY.fired = true;
174
- await this.events.values.WORKER_READY.run(this.me, this, -1);
175
- }
176
- }
177
- this.debugger?.debug(`#${shardId} [${packet.d.user.username}](${this.botId}) is online...`);
254
+ case 'GUILD_MEMBER_UPDATE':
255
+ await this.events.execute(packet.t, packet, this, shardId);
256
+ await this.cache.onPacket(packet);
178
257
  break;
179
- case 'INTERACTION_CREATE': {
180
- await (0, oninteraction_1.onInteraction)(shardId, packet.d, this);
258
+ case 'PRESENCE_UPDATE':
259
+ await this.events.execute(packet.t, packet, this, shardId);
260
+ await this.cache.onPacket(packet);
181
261
  break;
182
- }
183
- case 'GUILD_CREATE': {
184
- if (this.__handleGuilds.has(packet.d.id)) {
185
- this.__handleGuilds.delete(packet.d.id);
186
- if (!this.__handleGuilds.size &&
187
- [...this.shards.values()].every(shard => shard.data.session_id) &&
188
- this.events.values.WORKER_READY &&
189
- (this.events.values.WORKER_READY.fired ? !this.events.values.WORKER_READY.data.once : true)) {
190
- node_worker_threads_1.parentPort.postMessage({
191
- type: 'WORKER_READY',
192
- workerId: this.workerId,
193
- });
194
- this.events.values.WORKER_READY.fired = true;
195
- await this.events.values.WORKER_READY.run(this.me, this, -1);
262
+ //rest of the events
263
+ default:
264
+ {
265
+ switch (packet.t) {
266
+ case 'READY':
267
+ for (const g of packet.d.guilds) {
268
+ this.__handleGuilds?.add(g.id);
269
+ }
270
+ this.botId = packet.d.user.id;
271
+ this.applicationId = packet.d.application.id;
272
+ this.me = new structures_1.ClientUser(this, packet.d.user, packet.d.application);
273
+ if (!this.__handleGuilds?.size ||
274
+ !((workerData.intents & common_1.GatewayIntentBits.Guilds) === common_1.GatewayIntentBits.Guilds)) {
275
+ if ([...this.shards.values()].every(shard => shard.data.session_id)) {
276
+ node_worker_threads_1.parentPort.postMessage({
277
+ type: 'WORKER_READY',
278
+ workerId: this.workerId,
279
+ });
280
+ await this.events.runEvent('WORKER_READY', this, this.me, -1);
281
+ }
282
+ delete this.__handleGuilds;
283
+ }
284
+ this.debugger?.debug(`#${shardId} [${packet.d.user.username}](${this.botId}) is online...`);
285
+ break;
286
+ case 'INTERACTION_CREATE':
287
+ await (0, oninteractioncreate_1.onInteractionCreate)(this, packet.d, shardId);
288
+ break;
289
+ case 'MESSAGE_CREATE':
290
+ await (0, onmessagecreate_1.onMessageCreate)(this, packet.d, shardId);
291
+ break;
292
+ case 'GUILD_CREATE': {
293
+ if (this.__handleGuilds?.has(packet.d.id)) {
294
+ this.__handleGuilds.delete(packet.d.id);
295
+ if (!this.__handleGuilds.size && [...this.shards.values()].every(shard => shard.data.session_id)) {
296
+ node_worker_threads_1.parentPort.postMessage({
297
+ type: 'WORKER_READY',
298
+ workerId: this.workerId,
299
+ });
300
+ await this.events.runEvent('WORKER_READY', this, this.me, -1);
301
+ }
302
+ if (!this.__handleGuilds.size)
303
+ delete this.__handleGuilds;
304
+ return;
305
+ }
306
+ }
196
307
  }
197
- return;
308
+ await this.events.execute(packet.t, packet, this, shardId);
198
309
  }
199
- }
310
+ break;
200
311
  }
201
- await this.events.execute(packet.t, packet, this, shardId);
202
312
  }
203
313
  }
204
314
  exports.WorkerClient = WorkerClient;
@@ -142,7 +142,7 @@ export declare class LimitedCollection<K, V> {
142
142
  private readonly data;
143
143
  private readonly options;
144
144
  private timeout;
145
- constructor(options: Partial<LimitedCollectionOptions>);
145
+ constructor(options?: Partial<LimitedCollectionOptions>);
146
146
  /**
147
147
  * Adds an element to the limited collection.
148
148
  * @param key The key of the element.