seyfert 0.1.0 → 1.0.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 (193) 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 +39 -0
  18. package/lib/api/api.js +318 -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 +31 -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 +3 -12
  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.js +2 -2
  44. package/lib/cache/adapters/redis.d.ts +2 -3
  45. package/lib/cache/adapters/redis.js +13 -5
  46. package/lib/cache/adapters/workeradapter.d.ts +9 -1
  47. package/lib/cache/adapters/workeradapter.js +7 -3
  48. package/lib/cache/index.d.ts +20 -6
  49. package/lib/cache/index.js +26 -10
  50. package/lib/cache/resources/channels.d.ts +6 -2
  51. package/lib/cache/resources/channels.js +12 -6
  52. package/lib/cache/resources/default/base.d.ts +17 -16
  53. package/lib/cache/resources/default/base.js +25 -24
  54. package/lib/cache/resources/default/guild-based.d.ts +22 -19
  55. package/lib/cache/resources/default/guild-based.js +32 -31
  56. package/lib/cache/resources/default/guild-related.d.ts +22 -19
  57. package/lib/cache/resources/default/guild-related.js +37 -43
  58. package/lib/cache/resources/emojis.d.ts +4 -2
  59. package/lib/cache/resources/emojis.js +8 -6
  60. package/lib/cache/resources/guilds.d.ts +4 -2
  61. package/lib/cache/resources/guilds.js +15 -8
  62. package/lib/cache/resources/members.d.ts +4 -2
  63. package/lib/cache/resources/members.js +16 -13
  64. package/lib/cache/resources/overwrites.d.ts +25 -0
  65. package/lib/cache/resources/overwrites.js +39 -0
  66. package/lib/cache/resources/presence.js +3 -4
  67. package/lib/cache/resources/roles.d.ts +4 -2
  68. package/lib/cache/resources/roles.js +8 -6
  69. package/lib/cache/resources/stickers.d.ts +4 -2
  70. package/lib/cache/resources/stickers.js +8 -6
  71. package/lib/cache/resources/threads.d.ts +4 -2
  72. package/lib/cache/resources/threads.js +8 -6
  73. package/lib/cache/resources/users.d.ts +4 -2
  74. package/lib/cache/resources/users.js +8 -6
  75. package/lib/cache/resources/voice-states.d.ts +3 -3
  76. package/lib/cache/resources/voice-states.js +6 -7
  77. package/lib/client/base.d.ts +49 -16
  78. package/lib/client/base.js +21 -17
  79. package/lib/client/client.d.ts +14 -3
  80. package/lib/client/client.js +21 -21
  81. package/lib/client/httpclient.d.ts +3 -5
  82. package/lib/client/httpclient.js +29 -16
  83. package/lib/client/{oninteraction.d.ts → oninteractioncreate.d.ts} +1 -1
  84. package/lib/client/{oninteraction.js → oninteractioncreate.js} +34 -23
  85. package/lib/client/onmessagecreate.d.ts +3 -0
  86. package/lib/client/onmessagecreate.js +337 -0
  87. package/lib/client/workerclient.d.ts +5 -1
  88. package/lib/client/workerclient.js +67 -44
  89. package/lib/collection.d.ts +1 -1
  90. package/lib/collection.js +9 -6
  91. package/lib/commands/applications/chat.d.ts +32 -25
  92. package/lib/commands/applications/chat.js +51 -34
  93. package/lib/commands/applications/chatcontext.d.ts +34 -16
  94. package/lib/commands/applications/chatcontext.js +99 -20
  95. package/lib/commands/applications/menu.d.ts +9 -8
  96. package/lib/commands/applications/menu.js +14 -5
  97. package/lib/commands/applications/menucontext.d.ts +27 -10
  98. package/lib/commands/applications/menucontext.js +51 -7
  99. package/lib/commands/applications/options.d.ts +13 -13
  100. package/lib/commands/applications/shared.d.ts +7 -2
  101. package/lib/commands/decorators.d.ts +14 -14
  102. package/lib/commands/decorators.js +9 -5
  103. package/lib/commands/handler.d.ts +2 -1
  104. package/lib/commands/handler.js +60 -14
  105. package/lib/commands/index.d.ts +1 -1
  106. package/lib/commands/index.js +2 -1
  107. package/lib/commands/optionresolver.d.ts +6 -5
  108. package/lib/commands/optionresolver.js +10 -6
  109. package/lib/common/bot/watcher.d.ts +3 -3
  110. package/lib/common/bot/watcher.js +3 -1
  111. package/lib/common/index.d.ts +1 -1
  112. package/lib/common/index.js +2 -1
  113. package/lib/common/it/logger.d.ts +11 -0
  114. package/lib/common/it/logger.js +51 -2
  115. package/lib/common/it/utils.d.ts +3 -13
  116. package/lib/common/it/utils.js +9 -30
  117. package/lib/common/shorters/channels.d.ts +55 -5
  118. package/lib/common/shorters/channels.js +59 -0
  119. package/lib/common/shorters/guilds.d.ts +5 -2
  120. package/lib/common/shorters/guilds.js +18 -0
  121. package/lib/common/shorters/messages.js +0 -2
  122. package/lib/common/shorters/overwrites.d.ts +29 -0
  123. package/lib/common/shorters/overwrites.js +63 -0
  124. package/lib/common/shorters/roles.js +3 -3
  125. package/lib/common/shorters/webhook.d.ts +2 -2
  126. package/lib/common/types/util.d.ts +2 -1
  127. package/lib/common/types/write.d.ts +3 -7
  128. package/lib/components/handler.d.ts +12 -18
  129. package/lib/components/handler.js +58 -103
  130. package/lib/components/index.d.ts +0 -1
  131. package/lib/components/index.js +0 -1
  132. package/lib/components/listener.d.ts +2 -2
  133. package/lib/components/listener.js +2 -3
  134. package/lib/events/event.d.ts +2 -2
  135. package/lib/events/handler.d.ts +3 -2
  136. package/lib/events/handler.js +14 -6
  137. package/lib/events/hooks/dispatch.d.ts +2 -1
  138. package/lib/events/hooks/dispatch.js +5 -1
  139. package/lib/events/hooks/thread.d.ts +63 -63
  140. package/lib/index.d.ts +8 -5
  141. package/lib/index.js +20 -10
  142. package/lib/langs/handler.d.ts +6 -4
  143. package/lib/langs/handler.js +10 -8
  144. package/lib/langs/router.d.ts +8 -9
  145. package/lib/langs/router.js +5 -5
  146. package/lib/structures/ClientUser.d.ts +1 -16
  147. package/lib/structures/ClientUser.js +0 -31
  148. package/lib/structures/Guild.d.ts +1 -1
  149. package/lib/structures/GuildMember.d.ts +12 -0
  150. package/lib/structures/GuildMember.js +14 -0
  151. package/lib/structures/GuildRole.d.ts +4 -2
  152. package/lib/structures/GuildRole.js +4 -1
  153. package/lib/structures/GuildTemplate.js +1 -1
  154. package/lib/structures/Interaction.d.ts +2 -0
  155. package/lib/structures/Interaction.js +12 -13
  156. package/lib/structures/Message.d.ts +7 -2
  157. package/lib/structures/Message.js +6 -3
  158. package/lib/structures/Sticker.d.ts +1 -1
  159. package/lib/structures/Sticker.js +1 -1
  160. package/lib/structures/User.d.ts +5 -0
  161. package/lib/structures/User.js +3 -0
  162. package/lib/structures/Webhook.d.ts +1 -1
  163. package/lib/structures/Webhook.js +1 -1
  164. package/lib/structures/channels.d.ts +45 -6
  165. package/lib/structures/channels.js +23 -7
  166. package/lib/structures/extra/BitField.d.ts +9 -6
  167. package/lib/structures/extra/BitField.js +27 -3
  168. package/lib/structures/extra/Permissions.d.ts +6 -1
  169. package/lib/structures/extra/Permissions.js +7 -0
  170. package/lib/websocket/discord/basesocket.js +0 -1
  171. package/lib/websocket/discord/workermanager.d.ts +9 -1
  172. package/lib/websocket/discord/workermanager.js +21 -13
  173. package/package.json +21 -20
  174. package/lib/api/REST.d.ts +0 -127
  175. package/lib/api/REST.js +0 -424
  176. package/lib/api/errors/DiscordAPIError.d.ts +0 -51
  177. package/lib/api/errors/DiscordAPIError.js +0 -81
  178. package/lib/api/errors/HTTPError.d.ts +0 -20
  179. package/lib/api/errors/HTTPError.js +0 -28
  180. package/lib/api/errors/RateLimitError.d.ts +0 -19
  181. package/lib/api/errors/RateLimitError.js +0 -37
  182. package/lib/api/handlers/BurstHandler.d.ts +0 -51
  183. package/lib/api/handlers/BurstHandler.js +0 -124
  184. package/lib/api/handlers/SequentialHandler.d.ts +0 -81
  185. package/lib/api/handlers/SequentialHandler.js +0 -365
  186. package/lib/api/handlers/Shared.d.ts +0 -14
  187. package/lib/api/handlers/Shared.js +0 -125
  188. package/lib/api/interfaces/Handler.d.ts +0 -21
  189. package/lib/api/interfaces/Handler.js +0 -2
  190. package/lib/websocket/discord/handlemessage.d.ts +0 -0
  191. package/lib/websocket/discord/handlemessage.js +0 -1
  192. package/lib/websocket/discord/memberUpdate.d.ts +0 -16
  193. 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
@@ -3,12 +3,14 @@ import type { GatewayDispatchPayload, When } from '../common';
3
3
  import { Logger, type DeepPartial } from '../common';
4
4
  import { EventHandler } from '../events';
5
5
  import { ClientUser } from '../structures';
6
- import { Shard } from '../websocket';
6
+ import { Shard, type ShardManagerOptions } from '../websocket';
7
7
  import type { WorkerShardInfo } from '../websocket/discord/worker';
8
8
  import type { ManagerMessages } from '../websocket/discord/workermanager';
9
9
  import type { BaseClientOptions, StartOptions } from './base';
10
10
  import { BaseClient } from './base';
11
+ import type { Client } from './client';
11
12
  export declare class WorkerClient<Ready extends boolean = boolean> extends BaseClient {
13
+ private __handleGuilds?;
12
14
  logger: Logger;
13
15
  events: EventHandler;
14
16
  me: When<Ready, ClientUser>;
@@ -24,5 +26,7 @@ export declare class WorkerClient<Ready extends boolean = boolean> extends BaseC
24
26
  export declare function generateShardInfo(shard: Shard): WorkerShardInfo;
25
27
  interface WorkerClientOptions extends BaseClientOptions {
26
28
  disabledCache: Cache['disabledCache'];
29
+ commands?: NonNullable<Client['options']>['commands'];
30
+ handlePayload?: ShardManagerOptions['handlePayload'];
27
31
  }
28
32
  export {};
@@ -8,9 +8,11 @@ const events_1 = require("../events");
8
8
  const structures_1 = require("../structures");
9
9
  const websocket_1 = require("../websocket");
10
10
  const base_1 = require("./base");
11
- const oninteraction_1 = require("./oninteraction");
11
+ const oninteractioncreate_1 = require("./oninteractioncreate");
12
+ const onmessagecreate_1 = require("./onmessagecreate");
12
13
  const workerData = node_worker_threads_1.workerData;
13
14
  class WorkerClient extends base_1.BaseClient {
15
+ __handleGuilds;
14
16
  logger = new common_1.Logger({
15
17
  name: `[Worker #${workerData.workerId}]`,
16
18
  });
@@ -19,6 +21,7 @@ class WorkerClient extends base_1.BaseClient {
19
21
  shards = new Map();
20
22
  constructor(options) {
21
23
  super(options);
24
+ this.__handleGuilds = new Set();
22
25
  if (!node_worker_threads_1.parentPort) {
23
26
  throw new Error('WorkerClient cannot spawn without manager');
24
27
  }
@@ -54,8 +57,10 @@ class WorkerClient extends base_1.BaseClient {
54
57
  async handleManagerMessages(data) {
55
58
  switch (data.type) {
56
59
  case 'CACHE_RESULT':
57
- if (this.cache.adapter.promises.has(data.nonce)) {
58
- this.cache.adapter.promises.get(data.nonce)?.(data.result);
60
+ if (this.cache.adapter instanceof cache_1.WorkerAdapter && this.cache.adapter.promises.has(data.nonce)) {
61
+ const cacheData = this.cache.adapter.promises.get(data.nonce);
62
+ clearTimeout(cacheData.timeout);
63
+ cacheData.resolve(data.result);
59
64
  this.cache.adapter.promises.delete(data.nonce);
60
65
  }
61
66
  break;
@@ -90,6 +95,7 @@ class WorkerClient extends base_1.BaseClient {
90
95
  {
91
96
  const cache = this.cache;
92
97
  const onPacket = this.onPacket.bind(this);
98
+ const handlePayload = this.options?.handlePayload?.bind(this);
93
99
  for (const id of workerData.shards) {
94
100
  let shard = this.shards.get(id);
95
101
  if (!shard) {
@@ -100,6 +106,7 @@ class WorkerClient extends base_1.BaseClient {
100
106
  compress: data.compress,
101
107
  debugger: this.debugger,
102
108
  async handlePayload(shardId, payload) {
109
+ await handlePayload?.(shardId, payload);
103
110
  await cache.onPacket(payload);
104
111
  await onPacket?.(payload, shardId);
105
112
  node_worker_threads_1.parentPort.postMessage({
@@ -147,58 +154,74 @@ class WorkerClient extends base_1.BaseClient {
147
154
  case 'BOT_READY':
148
155
  if (this.events.values.BOT_READY &&
149
156
  (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);
157
+ await this.events.runEvent('BOT_READY', this, this.me, -1);
152
158
  }
153
159
  break;
154
160
  }
155
161
  }
156
162
  async onPacket(packet, shardId) {
163
+ await this.events.execute('RAW', packet, this, shardId);
157
164
  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...`);
165
+ case 'GUILD_MEMBER_UPDATE':
166
+ await this.events.execute(packet.t, packet, this, shardId);
167
+ await this.cache.onPacket(packet);
178
168
  break;
179
- case 'INTERACTION_CREATE': {
180
- await (0, oninteraction_1.onInteraction)(shardId, packet.d, this);
169
+ case 'PRESENCE_UPDATE':
170
+ await this.events.execute(packet.t, packet, this, shardId);
171
+ await this.cache.onPacket(packet);
181
172
  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);
173
+ //rest of the events
174
+ default:
175
+ {
176
+ switch (packet.t) {
177
+ case 'READY':
178
+ for (const g of packet.d.guilds) {
179
+ this.__handleGuilds?.add(g.id);
180
+ }
181
+ this.botId = packet.d.user.id;
182
+ this.applicationId = packet.d.application.id;
183
+ this.me = new structures_1.ClientUser(this, packet.d.user, packet.d.application);
184
+ if (!this.__handleGuilds?.size) {
185
+ if ([...this.shards.values()].every(shard => shard.data.session_id) &&
186
+ this.events.values.WORKER_READY &&
187
+ (this.events.values.WORKER_READY.fired ? !this.events.values.WORKER_READY.data.once : true)) {
188
+ node_worker_threads_1.parentPort.postMessage({
189
+ type: 'WORKER_READY',
190
+ workerId: this.workerId,
191
+ });
192
+ await this.events.runEvent('WORKER_READY', this, this.me, -1);
193
+ delete this.__handleGuilds;
194
+ }
195
+ }
196
+ this.debugger?.debug(`#${shardId} [${packet.d.user.username}](${this.botId}) is online...`);
197
+ break;
198
+ case 'INTERACTION_CREATE':
199
+ await (0, oninteractioncreate_1.onInteractionCreate)(this, packet.d, shardId);
200
+ break;
201
+ case 'MESSAGE_CREATE':
202
+ await (0, onmessagecreate_1.onMessageCreate)(this, packet.d, shardId);
203
+ break;
204
+ case 'GUILD_CREATE': {
205
+ if (this.__handleGuilds?.has(packet.d.id)) {
206
+ this.__handleGuilds.delete(packet.d.id);
207
+ if (!this.__handleGuilds.size &&
208
+ [...this.shards.values()].every(shard => shard.data.session_id) &&
209
+ this.events.values.WORKER_READY &&
210
+ (this.events.values.WORKER_READY.fired ? !this.events.values.WORKER_READY.data.once : true)) {
211
+ node_worker_threads_1.parentPort.postMessage({
212
+ type: 'WORKER_READY',
213
+ workerId: this.workerId,
214
+ });
215
+ await this.events.runEvent('WORKER_READY', this, this.me, -1);
216
+ }
217
+ return;
218
+ }
219
+ }
196
220
  }
197
- return;
221
+ await this.events.execute(packet.t, packet, this, shardId);
198
222
  }
199
- }
223
+ break;
200
224
  }
201
- await this.events.execute(packet.t, packet, this, shardId);
202
225
  }
203
226
  }
204
227
  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.
package/lib/collection.js CHANGED
@@ -203,7 +203,7 @@ class LimitedCollection {
203
203
  data = new Map();
204
204
  options;
205
205
  timeout = undefined;
206
- constructor(options) {
206
+ constructor(options = {}) {
207
207
  this.options = (0, common_1.MergeOptions)(LimitedCollection.default, options);
208
208
  }
209
209
  /**
@@ -233,7 +233,7 @@ class LimitedCollection {
233
233
  this.delete(iter.next().value);
234
234
  }
235
235
  }
236
- if (this.closer.expireOn >= expireOn) {
236
+ if (this.closer.expireOn === expireOn) {
237
237
  this.resetTimeout();
238
238
  }
239
239
  }
@@ -263,10 +263,11 @@ class LimitedCollection {
263
263
  get(key) {
264
264
  const data = this.data.get(key);
265
265
  if (this.options.resetOnDemand && data && data.expire !== -1) {
266
- if (this.closer?.expireOn === data.expireOn) {
267
- setImmediate(() => this.resetTimeout());
268
- }
266
+ const oldExpireOn = data.expireOn;
269
267
  data.expireOn = Date.now() + data.expire;
268
+ if (this.closer.expireOn === oldExpireOn) {
269
+ this.resetTimeout();
270
+ }
270
271
  }
271
272
  return data?.value;
272
273
  }
@@ -294,7 +295,9 @@ class LimitedCollection {
294
295
  * console.log(collection.delete(2)); // Output: false
295
296
  */
296
297
  delete(key) {
297
- setImmediate(() => this.resetTimeout());
298
+ const value = this.raw(key);
299
+ if (value && value.expireOn === this.closer.expireOn)
300
+ setImmediate(() => this.resetTimeout());
298
301
  return this.data.delete(key);
299
302
  }
300
303
  /**