seyfert 1.3.3 → 1.5.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 (138) hide show
  1. package/README.md +7 -7
  2. package/lib/api/Router.js +3 -1
  3. package/lib/api/Routes/guilds.d.ts +4 -1
  4. package/lib/api/api.js +13 -7
  5. package/lib/builders/Attachment.d.ts +1 -4
  6. package/lib/builders/Attachment.js +4 -4
  7. package/lib/cache/adapters/workeradapter.js +7 -3
  8. package/lib/cache/index.d.ts +6 -2
  9. package/lib/cache/index.js +18 -0
  10. package/lib/cache/resources/bans.d.ts +12 -0
  11. package/lib/cache/resources/bans.js +35 -0
  12. package/lib/cache/resources/default/base.d.ts +1 -2
  13. package/lib/cache/resources/default/guild-based.d.ts +1 -2
  14. package/lib/cache/resources/members.js +4 -4
  15. package/lib/cache/resources/messages.js +8 -6
  16. package/lib/client/base.d.ts +33 -7
  17. package/lib/client/base.js +80 -21
  18. package/lib/client/client.d.ts +18 -6
  19. package/lib/client/client.js +45 -37
  20. package/lib/client/collectors.d.ts +36 -0
  21. package/lib/client/collectors.js +85 -0
  22. package/lib/client/httpclient.d.ts +7 -8
  23. package/lib/client/httpclient.js +96 -17
  24. package/lib/client/oninteractioncreate.d.ts +2 -2
  25. package/lib/client/oninteractioncreate.js +15 -7
  26. package/lib/client/onmessagecreate.d.ts +12 -2
  27. package/lib/client/onmessagecreate.js +105 -82
  28. package/lib/client/workerclient.d.ts +5 -2
  29. package/lib/client/workerclient.js +66 -63
  30. package/lib/collection.d.ts +2 -2
  31. package/lib/collection.js +2 -2
  32. package/lib/commands/applications/chat.d.ts +11 -10
  33. package/lib/commands/applications/chat.js +23 -8
  34. package/lib/commands/applications/chatcontext.d.ts +1 -1
  35. package/lib/commands/applications/chatcontext.js +2 -2
  36. package/lib/commands/applications/menu.d.ts +8 -7
  37. package/lib/commands/applications/menu.js +3 -50
  38. package/lib/commands/applications/menucontext.d.ts +1 -1
  39. package/lib/commands/applications/menucontext.js +3 -3
  40. package/lib/commands/applications/options.d.ts +3 -1
  41. package/lib/commands/applications/shared.d.ts +12 -0
  42. package/lib/commands/basecontext.d.ts +26 -0
  43. package/lib/commands/{basecontex.js → basecontext.js} +24 -0
  44. package/lib/commands/decorators.d.ts +11 -17
  45. package/lib/commands/decorators.js +7 -14
  46. package/lib/commands/handler.d.ts +6 -1
  47. package/lib/commands/handler.js +161 -29
  48. package/lib/common/bot/watcher.d.ts +1 -2
  49. package/lib/common/bot/watcher.js +9 -4
  50. package/lib/common/index.d.ts +1 -0
  51. package/lib/common/index.js +3 -1
  52. package/lib/common/it/formatter.d.ts +155 -0
  53. package/lib/common/it/formatter.js +184 -0
  54. package/lib/common/it/logger.d.ts +1 -1
  55. package/lib/common/it/logger.js +14 -13
  56. package/lib/common/it/utils.d.ts +2 -0
  57. package/lib/common/it/utils.js +21 -9
  58. package/lib/common/shorters/bans.d.ts +43 -0
  59. package/lib/common/shorters/bans.js +78 -0
  60. package/lib/common/shorters/emojis.d.ts +1 -1
  61. package/lib/common/shorters/emojis.js +4 -3
  62. package/lib/common/shorters/interaction.js +9 -7
  63. package/lib/common/shorters/messages.js +2 -2
  64. package/lib/common/shorters/webhook.js +2 -2
  65. package/lib/components/componentcommand.d.ts +22 -0
  66. package/lib/components/{command.js → componentcommand.js} +3 -5
  67. package/lib/components/componentcontext.d.ts +20 -16
  68. package/lib/components/componentcontext.js +27 -9
  69. package/lib/components/handler.d.ts +11 -6
  70. package/lib/components/handler.js +106 -32
  71. package/lib/components/index.d.ts +3 -1
  72. package/lib/components/index.js +3 -1
  73. package/lib/components/modalcommand.d.ts +16 -0
  74. package/lib/components/modalcommand.js +10 -0
  75. package/lib/components/modalcontext.d.ts +104 -0
  76. package/lib/components/modalcontext.js +132 -0
  77. package/lib/events/event.d.ts +4 -3
  78. package/lib/events/handler.d.ts +12 -6
  79. package/lib/events/handler.js +60 -20
  80. package/lib/events/hooks/application_command.d.ts +2 -2
  81. package/lib/events/hooks/auto_moderation.d.ts +5 -5
  82. package/lib/events/hooks/channel.d.ts +5 -5
  83. package/lib/events/hooks/custom.d.ts +3 -3
  84. package/lib/events/hooks/dispatch.d.ts +4 -4
  85. package/lib/events/hooks/entitlement.d.ts +4 -4
  86. package/lib/events/hooks/guild.d.ts +41 -96
  87. package/lib/events/hooks/guild.js +6 -6
  88. package/lib/events/hooks/integration.d.ts +61 -4
  89. package/lib/events/hooks/interactions.d.ts +2 -2
  90. package/lib/events/hooks/invite.d.ts +6 -3
  91. package/lib/events/hooks/message.d.ts +23 -18
  92. package/lib/events/hooks/message.js +1 -1
  93. package/lib/events/hooks/presence.d.ts +11 -3
  94. package/lib/events/hooks/presence.js +2 -2
  95. package/lib/events/hooks/stage.d.ts +7 -13
  96. package/lib/events/hooks/stage.js +2 -2
  97. package/lib/events/hooks/thread.d.ts +21 -10
  98. package/lib/events/hooks/thread.js +2 -2
  99. package/lib/events/hooks/typing.d.ts +3 -2
  100. package/lib/events/hooks/user.d.ts +2 -2
  101. package/lib/events/hooks/user.js +2 -2
  102. package/lib/events/hooks/voice.d.ts +5 -45
  103. package/lib/events/hooks/voice.js +4 -7
  104. package/lib/events/hooks/webhook.d.ts +2 -2
  105. package/lib/index.d.ts +4 -4
  106. package/lib/index.js +11 -5
  107. package/lib/langs/handler.d.ts +4 -1
  108. package/lib/langs/handler.js +3 -3
  109. package/lib/structures/Guild.d.ts +9 -1
  110. package/lib/structures/Guild.js +2 -0
  111. package/lib/structures/GuildBan.d.ts +25 -0
  112. package/lib/structures/GuildBan.js +36 -0
  113. package/lib/structures/GuildEmoji.d.ts +1 -1
  114. package/lib/structures/GuildMember.d.ts +7 -2
  115. package/lib/structures/GuildMember.js +4 -4
  116. package/lib/structures/Interaction.d.ts +4 -3
  117. package/lib/structures/Interaction.js +29 -12
  118. package/lib/structures/Message.d.ts +69 -8
  119. package/lib/structures/Message.js +59 -17
  120. package/lib/structures/Sticker.d.ts +3 -3
  121. package/lib/structures/User.d.ts +1 -0
  122. package/lib/structures/User.js +4 -1
  123. package/lib/structures/VoiceState.d.ts +6 -5
  124. package/lib/structures/VoiceState.js +6 -3
  125. package/lib/structures/channels.d.ts +4 -1
  126. package/lib/structures/channels.js +37 -6
  127. package/lib/structures/extra/functions.js +1 -1
  128. package/lib/websocket/discord/basesocket.d.ts +1 -0
  129. package/lib/websocket/discord/basesocket.js +17 -0
  130. package/lib/websocket/discord/shard.d.ts +1 -0
  131. package/lib/websocket/discord/shard.js +6 -0
  132. package/lib/websocket/discord/sharder.js +10 -3
  133. package/lib/websocket/discord/shared.d.ts +1 -0
  134. package/lib/websocket/discord/workermanager.d.ts +2 -3
  135. package/lib/websocket/discord/workermanager.js +4 -2
  136. package/package.json +7 -7
  137. package/lib/commands/basecontex.d.ts +0 -15
  138. package/lib/components/command.d.ts +0 -24
@@ -9,6 +9,8 @@ const handler_1 = require("../commands/handler");
9
9
  const common_1 = require("../common");
10
10
  const handler_2 = require("../components/handler");
11
11
  const handler_3 = require("../langs/handler");
12
+ const node_fs_1 = require("node:fs");
13
+ const bans_1 = require("../common/shorters/bans");
12
14
  class BaseClient {
13
15
  rest;
14
16
  cache;
@@ -23,6 +25,7 @@ class BaseClient {
23
25
  reactions = new common_1.ReactionShorter(this);
24
26
  emojis = new common_1.EmojiShorter(this);
25
27
  threads = new common_1.ThreadShorter(this);
28
+ bans = new bans_1.BanShorter(this);
26
29
  interactions = new common_1.InteractionShorter(this);
27
30
  debugger;
28
31
  logger = new common_1.Logger({
@@ -43,6 +46,8 @@ class BaseClient {
43
46
  return Buffer.from(token.split('.')[0], 'base64').toString('ascii');
44
47
  }
45
48
  options;
49
+ /**@internal */
50
+ static _seyfertConfig;
46
51
  constructor(options) {
47
52
  this.options = (0, common_1.MergeOptions)({
48
53
  commands: {
@@ -67,13 +72,39 @@ class BaseClient {
67
72
  },
68
73
  },
69
74
  },
75
+ components: {
76
+ defaults: {
77
+ onRunError(context, error) {
78
+ context.client.logger.fatal('ComponentCommand.<onRunError>', context.author.id, error);
79
+ },
80
+ onMiddlewaresError(context, error) {
81
+ context.client.logger.fatal('ComponentCommand.<onMiddlewaresError>', context.author.id, error);
82
+ },
83
+ onInternalError(client, error) {
84
+ client.logger.fatal(error);
85
+ },
86
+ },
87
+ },
88
+ modals: {
89
+ defaults: {
90
+ onRunError(context, error) {
91
+ context.client.logger.fatal('ComponentCommand.<onRunError>', context.author.id, error);
92
+ },
93
+ onMiddlewaresError(context, error) {
94
+ context.client.logger.fatal('ComponentCommand.<onMiddlewaresError>', context.author.id, error);
95
+ },
96
+ onInternalError(client, error) {
97
+ client.logger.fatal(error);
98
+ },
99
+ },
100
+ },
70
101
  }, options);
71
102
  }
72
103
  set botId(id) {
73
104
  this._botId = id;
74
105
  }
75
106
  get botId() {
76
- return this._botId ?? BaseClient.getBotIdFromToken(this.rest.options.token);
107
+ return (this._botId ?? BaseClient.getBotIdFromToken(this.rest.options.token));
77
108
  }
78
109
  set applicationId(id) {
79
110
  this._applicationId = id;
@@ -84,7 +115,7 @@ class BaseClient {
84
115
  get proxy() {
85
116
  return new api_1.Router(this.rest).createProxy();
86
117
  }
87
- setServices({ rest, cache, langs, middlewares, handlers }) {
118
+ setServices({ rest, cache, langs, middlewares, handlers, }) {
88
119
  if (rest) {
89
120
  this.rest = rest;
90
121
  }
@@ -101,7 +132,9 @@ class BaseClient {
101
132
  }
102
133
  else if (typeof handlers.components === 'function') {
103
134
  this.components ??= new handler_2.ComponentHandler(this.logger, this);
104
- this.components.setHandlers({ callback: handlers.components });
135
+ this.components.setHandlers({
136
+ callback: handlers.components,
137
+ });
105
138
  }
106
139
  else {
107
140
  this.components = handlers.components;
@@ -168,23 +201,32 @@ class BaseClient {
168
201
  debug: (await this.getRC()).debug,
169
202
  });
170
203
  }
171
- if (!this.cache) {
172
- this.cache = new cache_1.Cache(0, new cache_1.MemoryAdapter(), [], this);
204
+ if (this.cache) {
205
+ this.cache.__setClient(this);
173
206
  }
174
207
  else {
175
- this.cache.__setClient(this);
208
+ this.cache = new cache_1.Cache(0, new cache_1.MemoryAdapter(), [], this);
176
209
  }
177
210
  }
178
211
  async onPacket(..._packet) {
179
212
  throw new Error('Function not implemented');
180
213
  }
214
+ shouldUploadCommands(cachePath) {
215
+ return this.commands.shouldUpload(cachePath).then(async (should) => {
216
+ if (should)
217
+ await node_fs_1.promises.writeFile(cachePath, JSON.stringify(this.commands.values.map((x) => x.toJSON())));
218
+ return should;
219
+ });
220
+ }
181
221
  async uploadCommands(applicationId) {
182
- applicationId ??= await this.getRC().then(x => x.applicationId ?? this.applicationId);
222
+ applicationId ??= await this.getRC().then((x) => x.applicationId ?? this.applicationId);
183
223
  BaseClient.assertString(applicationId, 'applicationId is not a string');
184
224
  const commands = this.commands.values;
185
- const filter = (0, common_1.filterSplit)(commands, command => !command.guildId);
225
+ const filter = (0, common_1.filterSplit)(commands, (command) => !command.guildId);
186
226
  await this.proxy.applications(applicationId).commands.put({
187
- body: filter.expect.filter(cmd => !('ignore' in cmd) || cmd.ignore !== shared_1.IgnoreCommand.Slash).map(x => x.toJSON()),
227
+ body: filter.expect
228
+ .filter((cmd) => !('ignore' in cmd) || cmd.ignore !== shared_1.IgnoreCommand.Slash)
229
+ .map((x) => x.toJSON()),
188
230
  });
189
231
  const guilds = new Set();
190
232
  for (const command of filter.never) {
@@ -198,27 +240,29 @@ class BaseClient {
198
240
  .guilds(guild)
199
241
  .commands.put({
200
242
  body: filter.never
201
- .filter(cmd => cmd.guildId?.includes(guild) && (!('ignore' in cmd) || cmd.ignore !== shared_1.IgnoreCommand.Slash))
202
- .map(x => x.toJSON()),
243
+ .filter((cmd) => cmd.guildId?.includes(guild) &&
244
+ (!('ignore' in cmd) ||
245
+ cmd.ignore !== shared_1.IgnoreCommand.Slash))
246
+ .map((x) => x.toJSON()),
203
247
  });
204
248
  }
205
249
  }
206
250
  async loadCommands(dir) {
207
- dir ??= await this.getRC().then(x => x.commands);
251
+ dir ??= await this.getRC().then((x) => x.commands);
208
252
  if (dir && this.commands) {
209
253
  await this.commands.load(dir, this);
210
254
  this.logger.info('CommandHandler loaded');
211
255
  }
212
256
  }
213
257
  async loadComponents(dir) {
214
- dir ??= await this.getRC().then(x => x.components);
258
+ dir ??= await this.getRC().then((x) => x.components);
215
259
  if (dir && this.components) {
216
260
  await this.components.load(dir);
217
261
  this.logger.info('ComponentHandler loaded');
218
262
  }
219
263
  }
220
264
  async loadLangs(dir) {
221
- dir ??= await this.getRC().then(x => x.langs);
265
+ dir ??= await this.getRC().then((x) => x.langs);
222
266
  if (dir && this.langs) {
223
267
  await this.langs.load(dir);
224
268
  this.logger.info('LangsHandler loaded');
@@ -228,18 +272,33 @@ class BaseClient {
228
272
  return this.langs.get(locale);
229
273
  }
230
274
  async getRC() {
231
- const { locations, debug, ...env } = (await (0, common_1.magicImport)((0, node_path_1.join)(process.cwd(), 'seyfert.config.js')).then(x => x.default ?? x));
232
- return {
275
+ const seyfertConfig = (BaseClient._seyfertConfig ||
276
+ (await this.options.getRC?.()) ||
277
+ (await (0, common_1.magicImport)((0, node_path_1.join)(process.cwd(), 'seyfert.config.js')).then((x) => x.default ?? x)));
278
+ const { locations, debug, ...env } = seyfertConfig;
279
+ const obj = {
233
280
  debug: !!debug,
234
281
  ...env,
235
- templates: locations.templates ? (0, node_path_1.join)(process.cwd(), locations.base, locations.templates) : undefined,
236
- langs: locations.langs ? (0, node_path_1.join)(process.cwd(), locations.output, locations.langs) : undefined,
237
- events: 'events' in locations && locations.events ? (0, node_path_1.join)(process.cwd(), locations.output, locations.events) : undefined,
238
- components: locations.components ? (0, node_path_1.join)(process.cwd(), locations.output, locations.components) : undefined,
239
- commands: locations.commands ? (0, node_path_1.join)(process.cwd(), locations.output, locations.commands) : undefined,
282
+ templates: locations.templates
283
+ ? (0, node_path_1.join)(process.cwd(), locations.base, locations.templates)
284
+ : undefined,
285
+ langs: locations.langs
286
+ ? (0, node_path_1.join)(process.cwd(), locations.output, locations.langs)
287
+ : undefined,
288
+ events: 'events' in locations && locations.events
289
+ ? (0, node_path_1.join)(process.cwd(), locations.output, locations.events)
290
+ : undefined,
291
+ components: locations.components
292
+ ? (0, node_path_1.join)(process.cwd(), locations.output, locations.components)
293
+ : undefined,
294
+ commands: locations.commands
295
+ ? (0, node_path_1.join)(process.cwd(), locations.output, locations.commands)
296
+ : undefined,
240
297
  base: (0, node_path_1.join)(process.cwd(), locations.base),
241
298
  output: (0, node_path_1.join)(process.cwd(), locations.output),
242
299
  };
300
+ BaseClient._seyfertConfig = seyfertConfig;
301
+ return obj;
243
302
  }
244
303
  }
245
304
  exports.BaseClient = BaseClient;
@@ -1,6 +1,6 @@
1
- import { type GatewayDispatchPayload, type GatewayPresenceUpdateData } from 'discord-api-types/v10';
2
- import type { Command, CommandContext, Message, SubCommand } from '..';
3
- import type { DeepPartial, If } from '../common';
1
+ import { type APIApplicationCommandInteractionDataOption, type GatewayMessageCreateDispatchData, type GatewayDispatchPayload, type GatewayPresenceUpdateData } from 'discord-api-types/v10';
2
+ import type { Command, CommandContext, ContextOptionsResolved, Message, MessageCommandOptionErrors, SubCommand, UsingClient } from '..';
3
+ import { type Awaitable, type MakeRequired, type DeepPartial, type If } from '../common';
4
4
  import { EventHandler } from '../events';
5
5
  import { ClientUser } from '../structures';
6
6
  import { ShardManager, type ShardManagerOptions } from '../websocket';
@@ -8,14 +8,18 @@ import { MemberUpdateHandler } from '../websocket/discord/events/memberUpdate';
8
8
  import { PresenceUpdateHandler } from '../websocket/discord/events/presenceUpdate';
9
9
  import type { BaseClientOptions, ServicesOptions, StartOptions } from './base';
10
10
  import { BaseClient } from './base';
11
+ import { Collectors } from './collectors';
11
12
  export declare class Client<Ready extends boolean = boolean> extends BaseClient {
12
13
  private __handleGuilds?;
13
14
  gateway: ShardManager;
14
- events?: EventHandler | undefined;
15
15
  me: If<Ready, ClientUser>;
16
- options: ClientOptions | undefined;
16
+ options: Omit<ClientOptions, 'commands'> & {
17
+ commands: MakeRequired<NonNullable<ClientOptions['commands']>, 'argsParser' | 'optionsParser'>;
18
+ };
17
19
  memberUpdateHandler: MemberUpdateHandler;
18
20
  presenceUpdateHandler: PresenceUpdateHandler;
21
+ collectors: Collectors;
22
+ events?: EventHandler | undefined;
19
23
  constructor(options?: ClientOptions);
20
24
  setServices({ gateway, ...rest }: ServicesOptions & {
21
25
  gateway?: ShardManager;
@@ -46,7 +50,15 @@ export interface ClientOptions extends BaseClientOptions {
46
50
  prefix?: (message: Message) => Promise<string[]> | string[];
47
51
  deferReplyResponse?: (ctx: CommandContext) => Parameters<Message['write']>[0];
48
52
  reply?: (ctx: CommandContext) => boolean;
49
- argsParser?: (content: string, command: SubCommand | Command) => Record<string, string>;
53
+ argsParser?: (content: string, command: SubCommand | Command, message: Message) => Record<string, string>;
54
+ optionsParser?: (self: UsingClient, command: Command | SubCommand, message: GatewayMessageCreateDispatchData, args: Partial<Record<string, string>>, resolved: MakeRequired<ContextOptionsResolved>) => Awaitable<{
55
+ errors: {
56
+ name: string;
57
+ error: string;
58
+ fullError: MessageCommandOptionErrors;
59
+ }[];
60
+ options: APIApplicationCommandInteractionDataOption[];
61
+ }>;
50
62
  };
51
63
  handlePayload?: ShardManagerOptions['handlePayload'];
52
64
  }
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Client = void 0;
4
4
  const v10_1 = require("discord-api-types/v10");
5
- const node_worker_threads_1 = require("node:worker_threads");
5
+ const common_1 = require("../common");
6
6
  const events_1 = require("../events");
7
7
  const structures_1 = require("../structures");
8
8
  const websocket_1 = require("../websocket");
@@ -11,15 +11,25 @@ const presenceUpdate_1 = require("../websocket/discord/events/presenceUpdate");
11
11
  const base_1 = require("./base");
12
12
  const oninteractioncreate_1 = require("./oninteractioncreate");
13
13
  const onmessagecreate_1 = require("./onmessagecreate");
14
+ const collectors_1 = require("./collectors");
15
+ let parentPort;
14
16
  class Client extends base_1.BaseClient {
15
17
  __handleGuilds = new Set();
16
18
  gateway;
17
- events = new events_1.EventHandler(this.logger);
18
19
  me;
19
20
  memberUpdateHandler = new memberUpdate_1.MemberUpdateHandler();
20
21
  presenceUpdateHandler = new presenceUpdate_1.PresenceUpdateHandler();
22
+ collectors = new collectors_1.Collectors();
23
+ events = new events_1.EventHandler(this);
21
24
  constructor(options) {
22
25
  super(options);
26
+ this.options = (0, common_1.MergeOptions)({
27
+ commands: {
28
+ argsParser: options?.commands?.argsParser ?? onmessagecreate_1.defaultArgsParser,
29
+ optionsParser: options?.commands?.optionsParser ??
30
+ onmessagecreate_1.defaultOptionsParser,
31
+ },
32
+ }, this.options);
23
33
  }
24
34
  setServices({ gateway, ...rest }) {
25
35
  super.setServices(rest);
@@ -37,7 +47,7 @@ class Client extends base_1.BaseClient {
37
47
  this.events = undefined;
38
48
  }
39
49
  else if (typeof rest.handlers.events === 'function') {
40
- this.events = new events_1.EventHandler(this.logger);
50
+ this.events = new events_1.EventHandler(this);
41
51
  this.events.setHandlers({
42
52
  callback: rest.handlers.events,
43
53
  });
@@ -48,7 +58,7 @@ class Client extends base_1.BaseClient {
48
58
  }
49
59
  }
50
60
  async loadEvents(dir) {
51
- dir ??= await this.getRC().then(x => x.events);
61
+ dir ??= await this.getRC().then((x) => x.events);
52
62
  if (dir && this.events) {
53
63
  await this.events.load(dir);
54
64
  this.logger.info('EventHandler loaded');
@@ -56,11 +66,12 @@ class Client extends base_1.BaseClient {
56
66
  }
57
67
  async execute(options = {}) {
58
68
  await super.execute(options);
59
- if (!node_worker_threads_1.workerData?.__USING_WATCHER__) {
60
- await this.gateway.spawnShards();
69
+ const worker_threads = (0, common_1.lazyLoadPackage)('node:worker_threads');
70
+ if (worker_threads?.parentPort) {
71
+ parentPort = worker_threads.parentPort;
61
72
  }
62
- else {
63
- node_worker_threads_1.parentPort?.on('message', (data) => {
73
+ if (worker_threads?.workerData?.__USING_WATCHER__) {
74
+ parentPort?.on('message', (data) => {
64
75
  switch (data.type) {
65
76
  case 'PAYLOAD':
66
77
  this.gateway.options.handlePayload(data.shardId, data.payload);
@@ -71,11 +82,14 @@ class Client extends base_1.BaseClient {
71
82
  }
72
83
  });
73
84
  }
85
+ else {
86
+ await this.gateway.spawnShards();
87
+ }
74
88
  }
75
89
  async start(options = {}, execute = true) {
76
90
  await super.start(options);
77
91
  await this.loadEvents(options.eventsDir);
78
- const { token: tokenRC, intents: intentsRC, debug: debugRC } = await this.getRC();
92
+ const { token: tokenRC, intents: intentsRC, debug: debugRC, } = await this.getRC();
79
93
  const token = options?.token ?? tokenRC;
80
94
  const intents = options?.connection?.intents ?? intentsRC;
81
95
  if (!this.gateway) {
@@ -93,7 +107,10 @@ class Client extends base_1.BaseClient {
93
107
  shardStart: this.options?.shards?.start,
94
108
  shardEnd: this.options?.shards?.end ?? this.options?.shards?.total,
95
109
  totalShards: this.options?.shards?.total ?? this.options?.shards?.end,
96
- properties: { ...this.options?.gateway?.properties, ...websocket_1.properties },
110
+ properties: {
111
+ ...websocket_1.properties,
112
+ ...this.options?.gateway?.properties,
113
+ },
97
114
  compress: this.options?.gateway?.compress,
98
115
  });
99
116
  }
@@ -114,28 +131,30 @@ class Client extends base_1.BaseClient {
114
131
  return;
115
132
  }
116
133
  await this.events?.execute(packet.t, packet, this, shardId);
117
- await this.cache.onPacket(packet);
118
134
  break;
119
135
  case 'PRESENCE_UPDATE':
120
136
  if (!this.presenceUpdateHandler.check(packet.d)) {
121
137
  return;
122
138
  }
123
139
  await this.events?.execute(packet.t, packet, this, shardId);
124
- await this.cache.onPacket(packet);
125
- break;
126
- case 'MESSAGE_UPDATE':
127
- case 'MESSAGE_DELETE_BULK':
128
- case 'MESSAGE_DELETE':
129
- await this.events?.execute(packet.t, packet, this, shardId);
130
- await this.cache.onPacket(packet);
131
140
  break;
132
- case 'GUILD_DELETE':
133
- case 'CHANNEL_UPDATE':
141
+ case 'GUILD_CREATE': {
142
+ if (this.__handleGuilds?.has(packet.d.id)) {
143
+ this.__handleGuilds.delete(packet.d.id);
144
+ if (!this.__handleGuilds.size &&
145
+ [...this.gateway.values()].every((shard) => shard.data.session_id)) {
146
+ await this.events?.runEvent('BOT_READY', this, this.me, -1);
147
+ }
148
+ if (!this.__handleGuilds.size)
149
+ delete this.__handleGuilds;
150
+ return this.cache.onPacket(packet);
151
+ }
134
152
  await this.events?.execute(packet.t, packet, this, shardId);
135
153
  break;
154
+ }
136
155
  //rest of the events
137
156
  default: {
138
- await this.cache.onPacket(packet);
157
+ await this.events?.execute(packet.t, packet, this, shardId);
139
158
  switch (packet.t) {
140
159
  case 'INTERACTION_CREATE':
141
160
  await (0, oninteractioncreate_1.onInteractionCreate)(this, packet.d, shardId);
@@ -150,29 +169,18 @@ class Client extends base_1.BaseClient {
150
169
  this.botId = packet.d.user.id;
151
170
  this.applicationId = packet.d.application.id;
152
171
  this.me = new structures_1.ClientUser(this, packet.d.user, packet.d.application);
153
- if (!this.__handleGuilds?.size ||
154
- !((this.gateway.options.intents & v10_1.GatewayIntentBits.Guilds) === v10_1.GatewayIntentBits.Guilds)) {
155
- if ([...this.gateway.values()].every(shard => shard.data.session_id)) {
172
+ if (!(this.__handleGuilds?.size &&
173
+ (this.gateway.options.intents &
174
+ v10_1.GatewayIntentBits.Guilds) ===
175
+ v10_1.GatewayIntentBits.Guilds)) {
176
+ if ([...this.gateway.values()].every((shard) => shard.data.session_id)) {
156
177
  await this.events?.runEvent('BOT_READY', this, this.me, -1);
157
178
  }
158
179
  delete this.__handleGuilds;
159
180
  }
160
181
  this.debugger?.debug(`#${shardId}[${packet.d.user.username}](${this.botId}) is online...`);
161
182
  break;
162
- case 'GUILD_CREATE': {
163
- if (this.__handleGuilds?.has(packet.d.id)) {
164
- this.__handleGuilds.delete(packet.d.id);
165
- if (!this.__handleGuilds.size && [...this.gateway.values()].every(shard => shard.data.session_id)) {
166
- await this.events?.runEvent('BOT_READY', this, this.me, -1);
167
- }
168
- if (!this.__handleGuilds.size)
169
- delete this.__handleGuilds;
170
- return;
171
- }
172
- break;
173
- }
174
183
  }
175
- await this.events?.execute(packet.t, packet, this, shardId);
176
184
  break;
177
185
  }
178
186
  }
@@ -0,0 +1,36 @@
1
+ /// <reference types="node" />
2
+ import type { Awaitable, CamelCase } from '../common';
3
+ import type { CallbackEventHandler, CustomEventsKeys, GatewayEvents } from '../events';
4
+ export type AllClientEvents = CustomEventsKeys | GatewayEvents;
5
+ export type ParseClientEventName<T extends AllClientEvents> = T extends CustomEventsKeys ? T : CamelCase<T>;
6
+ type RunData<T extends AllClientEvents> = {
7
+ options: {
8
+ event: T;
9
+ idle?: number;
10
+ timeout?: number;
11
+ onStop?: (reason: string) => unknown;
12
+ onStopError?: (reason: string, error: unknown) => unknown;
13
+ filter: (arg: Awaited<Parameters<CallbackEventHandler[ParseClientEventName<T>]>[0]>) => Awaitable<boolean>;
14
+ run: (arg: Awaited<Parameters<CallbackEventHandler[ParseClientEventName<T>]>[0]>, stop: (reason?: string) => void) => unknown;
15
+ onRunError?: (arg: Awaited<Parameters<CallbackEventHandler[ParseClientEventName<T>]>[0]>, error: unknown, stop: (reason?: string) => void) => unknown;
16
+ };
17
+ idle?: NodeJS.Timeout;
18
+ timeout?: NodeJS.Timeout;
19
+ nonce: string;
20
+ };
21
+ export declare class Collectors {
22
+ readonly values: Map<AllClientEvents, RunData<any>[]>;
23
+ private generateRandomUUID;
24
+ create<T extends AllClientEvents>(options: RunData<T>['options']): {
25
+ event: T;
26
+ idle?: number | undefined;
27
+ timeout?: number | undefined;
28
+ onStop?: ((reason: string) => unknown) | undefined;
29
+ onStopError?: ((reason: string, error: unknown) => unknown) | undefined;
30
+ filter: (arg: Awaited<Parameters<CallbackEventHandler[ParseClientEventName<T>]>[0]>) => Awaitable<boolean>;
31
+ run: (arg: Awaited<Parameters<CallbackEventHandler[ParseClientEventName<T>]>[0]>, stop: (reason?: string | undefined) => void) => unknown;
32
+ onRunError?: ((arg: Awaited<Parameters<CallbackEventHandler[ParseClientEventName<T>]>[0]>, error: unknown, stop: (reason?: string | undefined) => void) => unknown) | undefined;
33
+ };
34
+ private delete;
35
+ }
36
+ export {};
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Collectors = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_console_1 = require("node:console");
6
+ class Collectors {
7
+ values = new Map();
8
+ generateRandomUUID(name) {
9
+ const collectors = this.values.get(name);
10
+ if (!collectors)
11
+ return '*';
12
+ let nonce = (0, node_crypto_1.randomUUID)();
13
+ while (collectors.find(x => x.nonce === nonce)) {
14
+ nonce = (0, node_crypto_1.randomUUID)();
15
+ }
16
+ return nonce;
17
+ }
18
+ create(options) {
19
+ const nonce = this.generateRandomUUID(options.event);
20
+ if (!this.values.has(options.event)) {
21
+ this.values.set(options.event, []);
22
+ }
23
+ this.values.get(options.event).push({
24
+ options: {
25
+ ...options,
26
+ name: options.event,
27
+ },
28
+ idle: options.idle && options.idle > 0
29
+ ? setTimeout(() => {
30
+ return this.delete(options.event, nonce, 'idle');
31
+ }, options.idle)
32
+ : undefined,
33
+ timeout: options.timeout && options.timeout > 0
34
+ ? setTimeout(() => {
35
+ return this.delete(options.event, nonce, 'timeout');
36
+ }, options.timeout)
37
+ : undefined,
38
+ nonce,
39
+ });
40
+ return options;
41
+ }
42
+ async delete(name, nonce, reason = 'unknown') {
43
+ const collectors = this.values.get(name);
44
+ if (!collectors?.length) {
45
+ if (collectors)
46
+ this.values.delete(name);
47
+ return;
48
+ }
49
+ const index = collectors.findIndex(x => x.nonce === nonce);
50
+ if (index === -1)
51
+ return;
52
+ const collector = collectors[index];
53
+ clearTimeout(collector.idle);
54
+ clearTimeout(collector.timeout);
55
+ collectors.splice(index, 1);
56
+ try {
57
+ await collector.options.onStop?.(reason);
58
+ }
59
+ catch (e) {
60
+ await collector.options.onStopError?.(reason, node_console_1.error);
61
+ }
62
+ }
63
+ /**@internal */
64
+ async run(name, data) {
65
+ const collectors = this.values.get(name);
66
+ if (!collectors)
67
+ return;
68
+ for (const i of collectors) {
69
+ if (await i.options.filter(data)) {
70
+ i.idle?.refresh();
71
+ const stop = (reason = 'unknown') => {
72
+ return this.delete(i.options.event, i.nonce, reason);
73
+ };
74
+ try {
75
+ await i.options.run(data, stop);
76
+ }
77
+ catch (e) {
78
+ await i.options.onRunError?.(data, e, stop);
79
+ }
80
+ break;
81
+ }
82
+ }
83
+ }
84
+ }
85
+ exports.Collectors = Collectors;
@@ -1,20 +1,19 @@
1
1
  /// <reference types="node" />
2
2
  import { type APIInteraction } from 'discord-api-types/v10';
3
3
  import type { HttpRequest, HttpResponse } from 'uWebSockets.js';
4
- import type { DeepPartial } from '../common';
4
+ import { type DeepPartial } from '../common';
5
5
  import type { BaseClientOptions, StartOptions } from './base';
6
6
  import { BaseClient } from './base';
7
7
  export declare class HttpClient extends BaseClient {
8
- app: ReturnType<typeof import('uWebSockets.js').App>;
8
+ app?: ReturnType<typeof import('uWebSockets.js').App>;
9
9
  publicKey: string;
10
10
  publicKeyHex: Buffer;
11
11
  constructor(options?: BaseClientOptions);
12
12
  protected static readJson<T extends Record<string, any>>(res: HttpResponse): Promise<T>;
13
- protected execute(options?: {
14
- publicKey?: string;
15
- port?: number;
16
- }): Promise<void>;
17
- start(options?: DeepPartial<Omit<StartOptions, 'connection'>>): Promise<void>;
13
+ protected execute(options: DeepPartial<StartOptions['httpConnection']>): Promise<void>;
14
+ start(options?: DeepPartial<Omit<StartOptions, 'connection' | 'eventsDir'>>): Promise<void>;
15
+ protected verifySignatureGenericRequest(req: Request): Promise<APIInteraction | undefined>;
18
16
  protected verifySignature(res: HttpResponse, req: HttpRequest): Promise<APIInteraction | undefined>;
19
- onPacket(res: HttpResponse, req: HttpRequest): Promise<void>;
17
+ fetch(req: Request): Promise<Response>;
18
+ protected onPacket(res: HttpResponse, req: HttpRequest): Promise<void>;
20
19
  }