lolka.js 0.1.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 (337) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +148 -0
  3. package/package.json +104 -0
  4. package/src/client/Client.js +943 -0
  5. package/src/client/actions/Action.js +151 -0
  6. package/src/client/actions/ActionsManager.js +75 -0
  7. package/src/client/actions/ChannelCreate.js +25 -0
  8. package/src/client/actions/ChannelDelete.js +24 -0
  9. package/src/client/actions/ChannelUpdate.js +42 -0
  10. package/src/client/actions/GuildChannelsPositionUpdate.js +21 -0
  11. package/src/client/actions/GuildEmojiCreate.js +21 -0
  12. package/src/client/actions/GuildEmojiDelete.js +20 -0
  13. package/src/client/actions/GuildEmojiUpdate.js +21 -0
  14. package/src/client/actions/GuildEmojisUpdate.js +34 -0
  15. package/src/client/actions/GuildMemberRemove.js +33 -0
  16. package/src/client/actions/GuildMemberUpdate.js +45 -0
  17. package/src/client/actions/GuildRoleCreate.js +27 -0
  18. package/src/client/actions/GuildRoleDelete.js +30 -0
  19. package/src/client/actions/GuildRolesPositionUpdate.js +21 -0
  20. package/src/client/actions/GuildScheduledEventDelete.js +32 -0
  21. package/src/client/actions/GuildScheduledEventUserAdd.js +33 -0
  22. package/src/client/actions/GuildScheduledEventUserRemove.js +33 -0
  23. package/src/client/actions/GuildSoundboardSoundDelete.js +30 -0
  24. package/src/client/actions/GuildStickerCreate.js +21 -0
  25. package/src/client/actions/GuildStickerDelete.js +20 -0
  26. package/src/client/actions/GuildStickerUpdate.js +21 -0
  27. package/src/client/actions/GuildStickersUpdate.js +34 -0
  28. package/src/client/actions/GuildUpdate.js +34 -0
  29. package/src/client/actions/InteractionCreate.js +110 -0
  30. package/src/client/actions/MessageCreate.js +43 -0
  31. package/src/client/actions/MessageDelete.js +33 -0
  32. package/src/client/actions/MessageDeleteBulk.js +49 -0
  33. package/src/client/actions/MessagePollVoteAdd.js +41 -0
  34. package/src/client/actions/MessagePollVoteRemove.js +39 -0
  35. package/src/client/actions/MessageReactionAdd.js +72 -0
  36. package/src/client/actions/MessageReactionRemove.js +51 -0
  37. package/src/client/actions/MessageReactionRemoveAll.js +34 -0
  38. package/src/client/actions/MessageReactionRemoveEmoji.js +29 -0
  39. package/src/client/actions/MessageUpdate.js +26 -0
  40. package/src/client/actions/StageInstanceCreate.js +29 -0
  41. package/src/client/actions/StageInstanceDelete.js +32 -0
  42. package/src/client/actions/StageInstanceUpdate.js +31 -0
  43. package/src/client/actions/ThreadCreate.js +26 -0
  44. package/src/client/actions/ThreadMembersUpdate.js +49 -0
  45. package/src/client/actions/TypingStart.js +30 -0
  46. package/src/client/actions/UserUpdate.js +37 -0
  47. package/src/client/voice/ClientVoiceManager.js +48 -0
  48. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +30 -0
  49. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +18 -0
  50. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +19 -0
  51. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +22 -0
  52. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +21 -0
  53. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -0
  54. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -0
  55. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +23 -0
  56. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +17 -0
  57. package/src/client/websocket/handlers/ENTITLEMENT_CREATE.js +15 -0
  58. package/src/client/websocket/handlers/ENTITLEMENT_DELETE.js +19 -0
  59. package/src/client/websocket/handlers/ENTITLEMENT_UPDATE.js +17 -0
  60. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +20 -0
  61. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +16 -0
  62. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +21 -0
  63. package/src/client/websocket/handlers/GUILD_CREATE.js +35 -0
  64. package/src/client/websocket/handlers/GUILD_DELETE.js +37 -0
  65. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -0
  66. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +16 -0
  67. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +41 -0
  68. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +18 -0
  69. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -0
  70. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -0
  71. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -0
  72. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -0
  73. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +22 -0
  74. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +18 -0
  75. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -0
  76. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +20 -0
  77. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -0
  78. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -0
  79. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js +25 -0
  80. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js +19 -0
  81. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_DELETE.js +5 -0
  82. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js +21 -0
  83. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -0
  84. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  85. package/src/client/websocket/handlers/INTERACTION_CREATE.js +5 -0
  86. package/src/client/websocket/handlers/INVITE_CREATE.js +21 -0
  87. package/src/client/websocket/handlers/INVITE_DELETE.js +24 -0
  88. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  89. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  90. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  91. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_ADD.js +5 -0
  92. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_REMOVE.js +5 -0
  93. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  94. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  95. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  96. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  97. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +17 -0
  98. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +43 -0
  99. package/src/client/websocket/handlers/RATE_LIMITED.js +24 -0
  100. package/src/client/websocket/handlers/READY.js +30 -0
  101. package/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js +25 -0
  102. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  103. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  104. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  105. package/src/client/websocket/handlers/SUBSCRIPTION_CREATE.js +15 -0
  106. package/src/client/websocket/handlers/SUBSCRIPTION_DELETE.js +17 -0
  107. package/src/client/websocket/handlers/SUBSCRIPTION_UPDATE.js +17 -0
  108. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  109. package/src/client/websocket/handlers/THREAD_DELETE.js +18 -0
  110. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +52 -0
  111. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  112. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +26 -0
  113. package/src/client/websocket/handlers/THREAD_UPDATE.js +17 -0
  114. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  115. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  116. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +17 -0
  117. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +33 -0
  118. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +38 -0
  119. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +17 -0
  120. package/src/client/websocket/handlers/index.js +78 -0
  121. package/src/errors/DJSError.js +52 -0
  122. package/src/errors/ErrorCodes.js +280 -0
  123. package/src/errors/Messages.js +159 -0
  124. package/src/errors/index.js +7 -0
  125. package/src/index.js +261 -0
  126. package/src/managers/ApplicationCommandManager.js +305 -0
  127. package/src/managers/ApplicationCommandPermissionsManager.js +452 -0
  128. package/src/managers/ApplicationEmojiManager.js +152 -0
  129. package/src/managers/AutoModerationRuleManager.js +310 -0
  130. package/src/managers/BaseManager.js +21 -0
  131. package/src/managers/CachedManager.js +68 -0
  132. package/src/managers/CategoryChannelChildManager.js +85 -0
  133. package/src/managers/ChannelManager.js +197 -0
  134. package/src/managers/DMMessageManager.js +19 -0
  135. package/src/managers/DataManager.js +66 -0
  136. package/src/managers/EntitlementManager.js +185 -0
  137. package/src/managers/GuildApplicationCommandManager.js +31 -0
  138. package/src/managers/GuildBanManager.js +224 -0
  139. package/src/managers/GuildChannelManager.js +556 -0
  140. package/src/managers/GuildEmojiManager.js +264 -0
  141. package/src/managers/GuildEmojiRoleManager.js +136 -0
  142. package/src/managers/GuildForumThreadManager.js +88 -0
  143. package/src/managers/GuildInviteManager.js +239 -0
  144. package/src/managers/GuildManager.js +268 -0
  145. package/src/managers/GuildMemberManager.js +622 -0
  146. package/src/managers/GuildMemberRoleManager.js +232 -0
  147. package/src/managers/GuildMessageManager.js +35 -0
  148. package/src/managers/GuildScheduledEventManager.js +333 -0
  149. package/src/managers/GuildSoundboardSoundManager.js +226 -0
  150. package/src/managers/GuildStickerManager.js +195 -0
  151. package/src/managers/GuildTextThreadManager.js +95 -0
  152. package/src/managers/MessageManager.js +355 -0
  153. package/src/managers/PartialGroupDMMessageManager.js +19 -0
  154. package/src/managers/PermissionOverwriteManager.js +177 -0
  155. package/src/managers/PollAnswerVoterManager.js +62 -0
  156. package/src/managers/PresenceManager.js +63 -0
  157. package/src/managers/ReactionManager.js +75 -0
  158. package/src/managers/ReactionUserManager.js +85 -0
  159. package/src/managers/RoleManager.js +446 -0
  160. package/src/managers/StageInstanceManager.js +169 -0
  161. package/src/managers/SubscriptionManager.js +86 -0
  162. package/src/managers/ThreadManager.js +213 -0
  163. package/src/managers/ThreadMemberManager.js +197 -0
  164. package/src/managers/UserManager.js +149 -0
  165. package/src/managers/VoiceStateManager.js +64 -0
  166. package/src/sharding/Shard.js +506 -0
  167. package/src/sharding/ShardClientUtil.js +292 -0
  168. package/src/sharding/ShardingManager.js +390 -0
  169. package/src/structures/ActionRow.js +34 -0
  170. package/src/structures/ActivityInstance.js +52 -0
  171. package/src/structures/ActivityLocation.js +65 -0
  172. package/src/structures/AnnouncementChannel.js +29 -0
  173. package/src/structures/AnonymousGuild.js +107 -0
  174. package/src/structures/ApplicationCommand.js +657 -0
  175. package/src/structures/ApplicationEmoji.js +186 -0
  176. package/src/structures/ApplicationRoleConnectionMetadata.js +52 -0
  177. package/src/structures/Attachment.js +181 -0
  178. package/src/structures/AuthorizingIntegrationOwners.js +64 -0
  179. package/src/structures/AutoModerationActionExecution.js +131 -0
  180. package/src/structures/AutoModerationRule.js +317 -0
  181. package/src/structures/AutocompleteInteraction.js +112 -0
  182. package/src/structures/Base.js +45 -0
  183. package/src/structures/BaseChannel.js +188 -0
  184. package/src/structures/BaseGuild.js +134 -0
  185. package/src/structures/BaseGuildEmoji.js +111 -0
  186. package/src/structures/BaseGuildTextChannel.js +225 -0
  187. package/src/structures/BaseGuildVoiceChannel.js +265 -0
  188. package/src/structures/BaseInteraction.js +378 -0
  189. package/src/structures/BaseInvite.js +187 -0
  190. package/src/structures/BaseSelectMenuComponent.js +62 -0
  191. package/src/structures/ButtonComponent.js +72 -0
  192. package/src/structures/ButtonInteraction.js +12 -0
  193. package/src/structures/CategoryChannel.js +50 -0
  194. package/src/structures/ChannelSelectMenuComponent.js +22 -0
  195. package/src/structures/ChannelSelectMenuInteraction.js +36 -0
  196. package/src/structures/ChatInputCommandInteraction.js +45 -0
  197. package/src/structures/ClientApplication.js +463 -0
  198. package/src/structures/ClientPresence.js +89 -0
  199. package/src/structures/ClientUser.js +221 -0
  200. package/src/structures/CommandInteraction.js +188 -0
  201. package/src/structures/CommandInteractionOptionResolver.js +336 -0
  202. package/src/structures/Component.js +62 -0
  203. package/src/structures/ContainerComponent.js +66 -0
  204. package/src/structures/ContextMenuCommandInteraction.js +69 -0
  205. package/src/structures/DMChannel.js +162 -0
  206. package/src/structures/DirectoryChannel.js +40 -0
  207. package/src/structures/Embed.js +254 -0
  208. package/src/structures/Emoji.js +115 -0
  209. package/src/structures/Entitlement.js +199 -0
  210. package/src/structures/FileComponent.js +44 -0
  211. package/src/structures/ForumChannel.js +34 -0
  212. package/src/structures/GroupDMInvite.js +37 -0
  213. package/src/structures/Guild.js +1557 -0
  214. package/src/structures/GuildAuditLogs.js +97 -0
  215. package/src/structures/GuildAuditLogsEntry.js +552 -0
  216. package/src/structures/GuildBan.js +65 -0
  217. package/src/structures/GuildChannel.js +511 -0
  218. package/src/structures/GuildEmoji.js +160 -0
  219. package/src/structures/GuildInvite.js +223 -0
  220. package/src/structures/GuildMember.js +650 -0
  221. package/src/structures/GuildOnboarding.js +71 -0
  222. package/src/structures/GuildOnboardingPrompt.js +88 -0
  223. package/src/structures/GuildOnboardingPromptOption.js +96 -0
  224. package/src/structures/GuildPreview.js +213 -0
  225. package/src/structures/GuildPreviewEmoji.js +30 -0
  226. package/src/structures/GuildScheduledEvent.js +579 -0
  227. package/src/structures/GuildTemplate.js +221 -0
  228. package/src/structures/Integration.js +243 -0
  229. package/src/structures/IntegrationApplication.js +82 -0
  230. package/src/structures/InteractionCallback.js +83 -0
  231. package/src/structures/InteractionCallbackResource.js +57 -0
  232. package/src/structures/InteractionCallbackResponse.js +36 -0
  233. package/src/structures/InteractionCollector.js +256 -0
  234. package/src/structures/InteractionWebhook.js +67 -0
  235. package/src/structures/InviteGuild.js +24 -0
  236. package/src/structures/LabelComponent.js +54 -0
  237. package/src/structures/MediaChannel.js +12 -0
  238. package/src/structures/MediaGalleryComponent.js +34 -0
  239. package/src/structures/MediaGalleryItem.js +56 -0
  240. package/src/structures/MentionableSelectMenuComponent.js +12 -0
  241. package/src/structures/MentionableSelectMenuInteraction.js +76 -0
  242. package/src/structures/Message.js +1203 -0
  243. package/src/structures/MessageCollector.js +157 -0
  244. package/src/structures/MessageComponentInteraction.js +128 -0
  245. package/src/structures/MessageContextMenuCommandInteraction.js +22 -0
  246. package/src/structures/MessageMentions.js +323 -0
  247. package/src/structures/MessagePayload.js +346 -0
  248. package/src/structures/MessageReaction.js +214 -0
  249. package/src/structures/ModalComponentResolver.js +269 -0
  250. package/src/structures/ModalSubmitInteraction.js +274 -0
  251. package/src/structures/OAuth2Guild.js +31 -0
  252. package/src/structures/PartialGroupDMChannel.js +146 -0
  253. package/src/structures/PermissionOverwrites.js +221 -0
  254. package/src/structures/Poll.js +190 -0
  255. package/src/structures/PollAnswer.js +98 -0
  256. package/src/structures/Presence.js +429 -0
  257. package/src/structures/PrimaryEntryPointCommandInteraction.js +12 -0
  258. package/src/structures/ReactionCollector.js +246 -0
  259. package/src/structures/ReactionEmoji.js +33 -0
  260. package/src/structures/Role.js +539 -0
  261. package/src/structures/RoleSelectMenuComponent.js +12 -0
  262. package/src/structures/RoleSelectMenuInteraction.js +36 -0
  263. package/src/structures/SKU.js +59 -0
  264. package/src/structures/SectionComponent.js +46 -0
  265. package/src/structures/SeparatorComponent.js +33 -0
  266. package/src/structures/SoundboardSound.js +220 -0
  267. package/src/structures/StageChannel.js +121 -0
  268. package/src/structures/StageInstance.js +170 -0
  269. package/src/structures/Sticker.js +292 -0
  270. package/src/structures/StickerPack.js +107 -0
  271. package/src/structures/StringSelectMenuComponent.js +22 -0
  272. package/src/structures/StringSelectMenuInteraction.js +23 -0
  273. package/src/structures/Subscription.js +131 -0
  274. package/src/structures/Team.js +129 -0
  275. package/src/structures/TeamMember.js +77 -0
  276. package/src/structures/TextChannel.js +36 -0
  277. package/src/structures/TextDisplayComponent.js +22 -0
  278. package/src/structures/TextInputComponent.js +32 -0
  279. package/src/structures/ThreadChannel.js +662 -0
  280. package/src/structures/ThreadMember.js +124 -0
  281. package/src/structures/ThreadOnlyChannel.js +270 -0
  282. package/src/structures/ThumbnailComponent.js +54 -0
  283. package/src/structures/Typing.js +82 -0
  284. package/src/structures/UnfurledMediaItem.js +36 -0
  285. package/src/structures/User.js +505 -0
  286. package/src/structures/UserContextMenuCommandInteraction.js +32 -0
  287. package/src/structures/UserSelectMenuComponent.js +12 -0
  288. package/src/structures/UserSelectMenuInteraction.js +55 -0
  289. package/src/structures/VoiceChannel.js +123 -0
  290. package/src/structures/VoiceChannelEffect.js +88 -0
  291. package/src/structures/VoiceRegion.js +51 -0
  292. package/src/structures/VoiceState.js +338 -0
  293. package/src/structures/Webhook.js +520 -0
  294. package/src/structures/WelcomeChannel.js +67 -0
  295. package/src/structures/WelcomeScreen.js +54 -0
  296. package/src/structures/Widget.js +107 -0
  297. package/src/structures/WidgetMember.js +114 -0
  298. package/src/structures/interfaces/Application.js +173 -0
  299. package/src/structures/interfaces/Collector.js +368 -0
  300. package/src/structures/interfaces/InteractionResponses.js +385 -0
  301. package/src/structures/interfaces/TextBasedChannel.js +431 -0
  302. package/src/util/APITypes.js +700 -0
  303. package/src/util/ActivityFlagsBitField.js +29 -0
  304. package/src/util/ApplicationFlagsBitField.js +46 -0
  305. package/src/util/AttachmentFlagsBitField.js +29 -0
  306. package/src/util/BitField.js +197 -0
  307. package/src/util/ChannelFlagsBitField.js +46 -0
  308. package/src/util/Channels.js +173 -0
  309. package/src/util/Colors.js +73 -0
  310. package/src/util/Components.js +329 -0
  311. package/src/util/Constants.js +253 -0
  312. package/src/util/DataResolver.js +161 -0
  313. package/src/util/Enums.js +14 -0
  314. package/src/util/Events.js +179 -0
  315. package/src/util/GuildMemberFlagsBitField.js +46 -0
  316. package/src/util/IntentsBitField.js +38 -0
  317. package/src/util/InviteFlagsBitField.js +29 -0
  318. package/src/util/Invites.js +31 -0
  319. package/src/util/LimitedCollection.js +75 -0
  320. package/src/util/LolkaSnowflake.js +47 -0
  321. package/src/util/MessageFlagsBitField.js +46 -0
  322. package/src/util/Options.js +221 -0
  323. package/src/util/Partials.js +51 -0
  324. package/src/util/PermissionsBitField.js +117 -0
  325. package/src/util/RoleFlagsBitField.js +29 -0
  326. package/src/util/SKUFlagsBitField.js +29 -0
  327. package/src/util/ShardEvents.js +27 -0
  328. package/src/util/Status.js +17 -0
  329. package/src/util/Sweepers.js +533 -0
  330. package/src/util/Symbols.js +3 -0
  331. package/src/util/SystemChannelFlagsBitField.js +48 -0
  332. package/src/util/ThreadMemberFlagsBitField.js +36 -0
  333. package/src/util/Transformers.js +124 -0
  334. package/src/util/UserFlagsBitField.js +36 -0
  335. package/src/util/Util.js +609 -0
  336. package/typings/index.d.mts +7512 -0
  337. package/typings/index.d.ts +7512 -0
@@ -0,0 +1,292 @@
1
+ /* eslint-disable promise/prefer-await-to-callbacks, promise/prefer-await-to-then */
2
+ 'use strict';
3
+
4
+ const process = require('node:process');
5
+ const { calculateShardId } = require('@discordjs/util');
6
+ const { WebSocketShardEvents } = require('@discordjs/ws');
7
+ const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js');
8
+ const { Events } = require('../util/Events.js');
9
+ const { makeError, makePlainError } = require('../util/Util.js');
10
+
11
+ /**
12
+ * Helper class for sharded clients spawned as a child process/worker, such as from a {@link ShardingManager}.
13
+ * Utilizes IPC to send and receive data to/from the master process and other shards.
14
+ */
15
+ class ShardClientUtil {
16
+ constructor(client, mode) {
17
+ /**
18
+ * Client for the shard
19
+ *
20
+ * @type {Client}
21
+ */
22
+ this.client = client;
23
+
24
+ /**
25
+ * Mode the shard was spawned with
26
+ *
27
+ * @type {ShardingManagerMode}
28
+ */
29
+ this.mode = mode;
30
+
31
+ /**
32
+ * Message port for the master process (only when {@link ShardClientUtil#mode} is `worker`)
33
+ *
34
+ * @type {?MessagePort}
35
+ */
36
+ this.parentPort = null;
37
+
38
+ switch (mode) {
39
+ case 'process':
40
+ process.on('message', this._handleMessage.bind(this));
41
+ client.on(Events.ClientReady, () => {
42
+ process.send({ _ready: true });
43
+ });
44
+ client.ws.on(WebSocketShardEvents.Closed, () => {
45
+ process.send({ _disconnect: true });
46
+ });
47
+ client.ws.on(WebSocketShardEvents.Resumed, () => {
48
+ process.send({ _resume: true });
49
+ });
50
+ break;
51
+ case 'worker':
52
+ this.parentPort = require('node:worker_threads').parentPort;
53
+ this.parentPort.on('message', this._handleMessage.bind(this));
54
+ client.on(Events.ClientReady, () => {
55
+ this.parentPort.postMessage({ _ready: true });
56
+ });
57
+ client.ws.on(WebSocketShardEvents.Closed, () => {
58
+ this.parentPort.postMessage({ _disconnect: true });
59
+ });
60
+ client.ws.on(WebSocketShardEvents.Resumed, () => {
61
+ this.parentPort.postMessage({ _resume: true });
62
+ });
63
+ break;
64
+ default:
65
+ break;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Sends a message to the master process.
71
+ *
72
+ * @param {*} message Message to send
73
+ * @returns {Promise<void>}
74
+ * @emits Shard#message
75
+ */
76
+ async send(message) {
77
+ return new Promise((resolve, reject) => {
78
+ switch (this.mode) {
79
+ case 'process':
80
+ process.send(message, err => {
81
+ if (err) reject(err);
82
+ else resolve();
83
+ });
84
+ break;
85
+ case 'worker':
86
+ this.parentPort.postMessage(message);
87
+ resolve();
88
+ break;
89
+ default:
90
+ break;
91
+ }
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Fetches a client property value of each shard, or a given shard.
97
+ *
98
+ * @param {string} prop Name of the client property to get, using periods for nesting
99
+ * @param {number} [shard] Shard to fetch property from, all if undefined
100
+ * @returns {Promise<*|Array<*>>}
101
+ * @example
102
+ * client.shard.fetchClientValues('guilds.cache.size')
103
+ * .then(results => console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`))
104
+ * .catch(console.error);
105
+ * @see {@link ShardingManager#fetchClientValues}
106
+ */
107
+ async fetchClientValues(prop, shard) {
108
+ return new Promise((resolve, reject) => {
109
+ const parent = this.parentPort ?? process;
110
+
111
+ const listener = message => {
112
+ if (message?._sFetchProp !== prop || message._sFetchPropShard !== shard) return;
113
+ parent.removeListener('message', listener);
114
+ this.decrementMaxListeners(parent);
115
+ if (message._error) reject(makeError(message._error));
116
+ else resolve(message._result);
117
+ };
118
+
119
+ this.incrementMaxListeners(parent);
120
+ parent.on('message', listener);
121
+
122
+ this.send({ _sFetchProp: prop, _sFetchPropShard: shard }).catch(error => {
123
+ parent.removeListener('message', listener);
124
+ this.decrementMaxListeners(parent);
125
+ reject(error);
126
+ });
127
+ });
128
+ }
129
+
130
+ /**
131
+ * Evaluates a script or function on all shards, or a given shard, in the context of the {@link Client}s.
132
+ *
133
+ * @param {Function} script JavaScript to run on each shard
134
+ * @param {BroadcastEvalOptions} [options={}] The options for the broadcast
135
+ * @returns {Promise<*|Array<*>>} Results of the script execution
136
+ * @example
137
+ * client.shard.broadcastEval(client => client.guilds.cache.size)
138
+ * .then(results => console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`))
139
+ * .catch(console.error);
140
+ * @see {@link ShardingManager#broadcastEval}
141
+ */
142
+ async broadcastEval(script, options = {}) {
143
+ return new Promise((resolve, reject) => {
144
+ const parent = this.parentPort ?? process;
145
+ if (typeof script !== 'function') {
146
+ reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
147
+ return;
148
+ }
149
+
150
+ const evalScript = `(${script})(this, ${JSON.stringify(options.context)})`;
151
+
152
+ const listener = message => {
153
+ if (message?._sEval !== evalScript || message._sEvalShard !== options.shard) return;
154
+ parent.removeListener('message', listener);
155
+ this.decrementMaxListeners(parent);
156
+ if (message._error) reject(makeError(message._error));
157
+ else resolve(message._result);
158
+ };
159
+
160
+ this.incrementMaxListeners(parent);
161
+ parent.on('message', listener);
162
+ this.send({ _sEval: evalScript, _sEvalShard: options.shard }).catch(error => {
163
+ parent.removeListener('message', listener);
164
+ this.decrementMaxListeners(parent);
165
+ reject(error);
166
+ });
167
+ });
168
+ }
169
+
170
+ /**
171
+ * Requests a respawn of all shards.
172
+ *
173
+ * @param {MultipleShardRespawnOptions} [options] Options for respawning shards
174
+ * @returns {Promise<void>} Resolves upon the message being sent
175
+ * @see {@link ShardingManager#respawnAll}
176
+ */
177
+ async respawnAll({ shardDelay = 5_000, respawnDelay = 500, timeout = 30_000 } = {}) {
178
+ return this.send({ _sRespawnAll: { shardDelay, respawnDelay, timeout } });
179
+ }
180
+
181
+ /**
182
+ * Handles an IPC message.
183
+ *
184
+ * @param {*} message Message received
185
+ * @private
186
+ */
187
+ async _handleMessage(message) {
188
+ if (!message) return;
189
+ if (message._fetchProp) {
190
+ try {
191
+ const props = message._fetchProp.split('.');
192
+ let value = this.client;
193
+ for (const prop of props) value = value[prop];
194
+ this._respond('fetchProp', { _fetchProp: message._fetchProp, _result: value });
195
+ } catch (error) {
196
+ this._respond('fetchProp', { _fetchProp: message._fetchProp, _error: makePlainError(error) });
197
+ }
198
+ } else if (message._eval) {
199
+ try {
200
+ this._respond('eval', { _eval: message._eval, _result: await this.client._eval(message._eval) });
201
+ } catch (error) {
202
+ this._respond('eval', { _eval: message._eval, _error: makePlainError(error) });
203
+ }
204
+ }
205
+ }
206
+
207
+ /**
208
+ * Sends a message to the master process, emitting an error from the client upon failure.
209
+ *
210
+ * @param {string} type Type of response to send
211
+ * @param {*} message Message to send
212
+ * @private
213
+ */
214
+ _respond(type, message) {
215
+ this.send(message).catch(error_ => {
216
+ const error = new Error(`Error when sending ${type} response to master process: ${error_.message}`);
217
+ error.stack = error_.stack;
218
+ /**
219
+ * Emitted when the client encounters an error.
220
+ * <warn>Errors thrown within this event do not have a catch handler, it is
221
+ * recommended to not use async functions as `error` event handlers. See the
222
+ * {@link https://nodejs.org/api/events.html#capture-rejections-of-promises Node.js documentation}
223
+ * for details.)</warn>
224
+ *
225
+ * @event Client#error
226
+ * @param {Error} error The error encountered
227
+ */
228
+ this.client.emit(Events.Error, error);
229
+ });
230
+ }
231
+
232
+ /**
233
+ * Creates/gets the singleton of this class.
234
+ *
235
+ * @param {Client} client The client to use
236
+ * @param {ShardingManagerMode} mode Mode the shard was spawned with
237
+ * @returns {ShardClientUtil}
238
+ */
239
+ static singleton(client, mode) {
240
+ if (this._singleton) {
241
+ client.emit(
242
+ Events.Warn,
243
+ 'Multiple clients created in child process/worker; only the first will handle sharding helpers.',
244
+ );
245
+ } else {
246
+ this._singleton = new this(client, mode);
247
+ }
248
+
249
+ return this._singleton;
250
+ }
251
+
252
+ /**
253
+ * Get the shard id for a given guild id.
254
+ *
255
+ * @param {Snowflake} guildId Snowflake guild id to get shard id for
256
+ * @param {number} shardCount Number of shards
257
+ * @returns {number}
258
+ */
259
+ static shardIdForGuildId(guildId, shardCount) {
260
+ const shard = calculateShardId(guildId, shardCount);
261
+ if (shard < 0) throw new DiscordjsError(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount);
262
+ return shard;
263
+ }
264
+
265
+ /**
266
+ * Increments max listeners by one for a given emitter, if they are not zero.
267
+ *
268
+ * @param {Worker|ChildProcess} emitter The emitter that emits the events.
269
+ * @private
270
+ */
271
+ incrementMaxListeners(emitter) {
272
+ const maxListeners = emitter.getMaxListeners();
273
+ if (maxListeners !== 0) {
274
+ emitter.setMaxListeners(maxListeners + 1);
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Decrements max listeners by one for a given emitter, if they are not zero.
280
+ *
281
+ * @param {Worker|ChildProcess} emitter The emitter that emits the events.
282
+ * @private
283
+ */
284
+ decrementMaxListeners(emitter) {
285
+ const maxListeners = emitter.getMaxListeners();
286
+ if (maxListeners !== 0) {
287
+ emitter.setMaxListeners(maxListeners - 1);
288
+ }
289
+ }
290
+ }
291
+
292
+ exports.ShardClientUtil = ShardClientUtil;
@@ -0,0 +1,390 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const process = require('node:process');
6
+ const { setTimeout: sleep } = require('node:timers/promises');
7
+ const { Collection } = require('@discordjs/collection');
8
+ const { range } = require('@discordjs/util');
9
+ const { AsyncEventEmitter } = require('@vladfrangu/async_event_emitter');
10
+ const { APIVersion } = require('discord-api-types/v10');
11
+ const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors/index.js');
12
+ const { fetchRecommendedShardCount } = require('../util/Util.js');
13
+ const { Shard } = require('./Shard.js');
14
+
15
+ /**
16
+ * This is a utility class that makes multi-process sharding of a bot an easy and painless experience.
17
+ * It works by spawning a self-contained {@link ChildProcess} or {@link Worker} for each individual shard, each
18
+ * containing its own instance of your bot's {@link Client}. They all have a line of communication with the master
19
+ * process, and there are several useful methods that utilize it in order to simplify tasks that are normally difficult
20
+ * with sharding. It can spawn a specific number of shards or the amount that Discord suggests for the bot, and takes a
21
+ * path to your main bot script to launch for each one.
22
+ *
23
+ * @extends {AsyncEventEmitter}
24
+ */
25
+ class ShardingManager extends AsyncEventEmitter {
26
+ /**
27
+ * The mode to spawn shards with for a {@link ShardingManager}. Can be either one of:
28
+ * - 'process' to use child processes
29
+ * - 'worker' to use {@link Worker} threads
30
+ *
31
+ * @typedef {string} ShardingManagerMode
32
+ */
33
+
34
+ /**
35
+ * The options to spawn shards with for a {@link ShardingManager}.
36
+ *
37
+ * @typedef {Object} ShardingManagerOptions
38
+ * @property {string|number} [totalShards='auto'] Number of total shards of all shard managers or "auto"
39
+ * @property {string|number[]} [shardList='auto'] List of shards to spawn or "auto"
40
+ * @property {ShardingManagerMode} [mode='process'] Which mode to use for shards
41
+ * @property {boolean} [respawn=true] Whether shards should automatically respawn upon exiting
42
+ * @property {boolean} [silent=false] Whether to pass the silent flag to child process
43
+ * (only available when mode is set to 'process')
44
+ * @property {string[]} [shardArgs=[]] Arguments to pass to the shard script when spawning
45
+ * @property {string[]} [execArgv=[]] Arguments to pass to the shard script executable when spawning
46
+ * @property {string} [token] Token to use for automatic shard count and passing to shards
47
+ * @property {string} [api='https://discord.com/api'] The base API URL
48
+ * @property {string} [version='10'] The API version to use
49
+ */
50
+
51
+ /**
52
+ * @param {string} file Path to your shard script file
53
+ * @param {ShardingManagerOptions} [options] Options for the sharding manager
54
+ */
55
+ constructor(file, options) {
56
+ super();
57
+ const _options = {
58
+ totalShards: 'auto',
59
+ mode: 'process',
60
+ respawn: true,
61
+ silent: false,
62
+ shardArgs: [],
63
+ execArgv: [],
64
+ token: process.env.DISCORD_TOKEN,
65
+ ...options,
66
+ };
67
+
68
+ /**
69
+ * Path to the shard script file
70
+ *
71
+ * @type {string}
72
+ */
73
+ this.file = file;
74
+ if (!file) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'specified.');
75
+ if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file);
76
+ // eslint-disable-next-line n/no-sync
77
+ const stats = fs.statSync(this.file);
78
+ if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'a file');
79
+
80
+ /**
81
+ * List of shards this sharding manager spawns
82
+ *
83
+ * @type {string|number[]}
84
+ */
85
+ this.shardList = _options.shardList ?? 'auto';
86
+ if (this.shardList !== 'auto') {
87
+ if (!Array.isArray(this.shardList)) {
88
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array.');
89
+ }
90
+
91
+ this.shardList = [...new Set(this.shardList)];
92
+ if (this.shardList.length < 1) {
93
+ throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'shardList', 'at least 1 id.');
94
+ }
95
+
96
+ if (
97
+ this.shardList.some(
98
+ shardId => typeof shardId !== 'number' || Number.isNaN(shardId) || !Number.isInteger(shardId) || shardId < 0,
99
+ )
100
+ ) {
101
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array of positive integers.');
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Amount of shards that all sharding managers spawn in total
107
+ *
108
+ * @type {number}
109
+ */
110
+ this.totalShards = _options.totalShards || 'auto';
111
+ if (this.totalShards !== 'auto') {
112
+ if (typeof this.totalShards !== 'number' || Number.isNaN(this.totalShards)) {
113
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
114
+ }
115
+
116
+ if (this.totalShards < 1) {
117
+ throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
118
+ }
119
+
120
+ if (!Number.isInteger(this.totalShards)) {
121
+ throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Mode for shards to spawn with
127
+ *
128
+ * @type {ShardingManagerMode}
129
+ */
130
+ this.mode = _options.mode;
131
+ if (this.mode !== 'process' && this.mode !== 'worker') {
132
+ throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Sharding mode', '"process" or "worker"');
133
+ }
134
+
135
+ /**
136
+ * Whether shards should automatically respawn upon exiting
137
+ *
138
+ * @type {boolean}
139
+ */
140
+ this.respawn = _options.respawn;
141
+
142
+ /**
143
+ * Whether to pass the silent flag to child process (only when {@link ShardingManager#mode} is `process`)
144
+ *
145
+ * @type {boolean}
146
+ */
147
+ this.silent = _options.silent;
148
+
149
+ /**
150
+ * An array of arguments to pass to shards (only when {@link ShardingManager#mode} is `process`)
151
+ *
152
+ * @type {string[]}
153
+ */
154
+ this.shardArgs = _options.shardArgs;
155
+
156
+ /**
157
+ * An array of arguments to pass to the executable (only when {@link ShardingManager#mode} is `process`)
158
+ *
159
+ * @type {string[]}
160
+ */
161
+ this.execArgv = _options.execArgv;
162
+
163
+ /**
164
+ * Token to use for obtaining the automatic shard count, and passing to shards
165
+ *
166
+ * @type {?string}
167
+ */
168
+ this.token = _options.token?.replace(/^bot\s*/i, '') ?? null;
169
+
170
+ /**
171
+ * The base API URL
172
+ *
173
+ * @type {string}
174
+ */
175
+ this.api = _options.api ?? 'https://discord.com/api';
176
+
177
+ /**
178
+ * The API version to use
179
+ *
180
+ * @type {string}
181
+ */
182
+ this.version = _options.version ?? APIVersion;
183
+
184
+ /**
185
+ * A collection of shards that this manager has spawned
186
+ *
187
+ * @type {Collection<number, Shard>}
188
+ */
189
+ this.shards = new Collection();
190
+
191
+ process.env.SHARDING_MANAGER = true;
192
+ process.env.SHARDING_MANAGER_MODE = this.mode;
193
+ process.env.DISCORD_TOKEN = this.token;
194
+ }
195
+
196
+ /**
197
+ * Creates a single shard.
198
+ * <warn>Using this method is usually not necessary if you use the spawn method.</warn>
199
+ *
200
+ * @param {number} [id=this.shards.size] Id of the shard to create
201
+ * <info>This is usually not necessary to manually specify.</info>
202
+ * @returns {Shard} Note that the created shard needs to be explicitly spawned using its spawn method.
203
+ */
204
+ createShard(id = this.shards.size) {
205
+ const shard = new Shard(this, id);
206
+ this.shards.set(id, shard);
207
+ /**
208
+ * Emitted upon creating a shard.
209
+ *
210
+ * @event ShardingManager#shardCreate
211
+ * @param {Shard} shard Shard that was created
212
+ */
213
+ this.emit('shardCreate', shard);
214
+ return shard;
215
+ }
216
+
217
+ /**
218
+ * Options used to spawn multiple shards.
219
+ *
220
+ * @typedef {Object} MultipleShardSpawnOptions
221
+ * @property {number|string} [amount=this.totalShards] Number of shards to spawn
222
+ * @property {number} [delay=5500] How long to wait in between spawning each shard (in milliseconds)
223
+ * @property {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready
224
+ */
225
+
226
+ /**
227
+ * Spawns multiple shards.
228
+ *
229
+ * @param {MultipleShardSpawnOptions} [options] Options for spawning shards
230
+ * @returns {Promise<Collection<number, Shard>>}
231
+ */
232
+ async spawn({ amount = this.totalShards, delay = 5_500, timeout = 30_000 } = {}) {
233
+ // Obtain/verify the number of shards to spawn
234
+ let shardAmount = amount;
235
+ if (shardAmount === 'auto') {
236
+ // eslint-disable-next-line require-atomic-updates
237
+ shardAmount = await fetchRecommendedShardCount(this.token, {
238
+ api: this.api,
239
+ version: this.version,
240
+ });
241
+ } else {
242
+ if (typeof shardAmount !== 'number' || Number.isNaN(shardAmount)) {
243
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
244
+ }
245
+
246
+ if (shardAmount < 1) {
247
+ throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
248
+ }
249
+
250
+ if (!Number.isInteger(shardAmount)) {
251
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
252
+ }
253
+ }
254
+
255
+ // Make sure this many shards haven't already been spawned
256
+ if (this.shards.size >= shardAmount) throw new DiscordjsError(ErrorCodes.ShardingAlreadySpawned, this.shards.size);
257
+ if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== shardAmount) {
258
+ this.shardList = [...range(shardAmount)];
259
+ }
260
+
261
+ if (this.totalShards === 'auto' || this.totalShards !== shardAmount) {
262
+ this.totalShards = shardAmount;
263
+ }
264
+
265
+ if (this.shardList.some(shardId => shardId >= shardAmount)) {
266
+ throw new DiscordjsRangeError(
267
+ ErrorCodes.ClientInvalidOption,
268
+ 'Amount of shards',
269
+ 'bigger than the highest shardId in the shardList option.',
270
+ );
271
+ }
272
+
273
+ // Spawn the shards
274
+ for (const shardId of this.shardList) {
275
+ const promises = [];
276
+ const shard = this.createShard(shardId);
277
+ promises.push(shard.spawn(timeout));
278
+ if (delay > 0 && this.shards.size !== this.shardList.length) promises.push(sleep(delay));
279
+ await Promise.all(promises);
280
+ }
281
+
282
+ return this.shards;
283
+ }
284
+
285
+ /**
286
+ * Sends a message to all shards.
287
+ *
288
+ * @param {*} message Message to be sent to the shards
289
+ * @returns {Promise<Shard[]>}
290
+ */
291
+ async broadcast(message) {
292
+ const promises = [];
293
+ for (const shard of this.shards.values()) promises.push(shard.send(message));
294
+ return Promise.all(promises);
295
+ }
296
+
297
+ /**
298
+ * Options for {@link ShardingManager#broadcastEval} and {@link ShardClientUtil#broadcastEval}.
299
+ *
300
+ * @typedef {Object} BroadcastEvalOptions
301
+ * @property {number} [shard] Shard to run script on, all if undefined
302
+ * @property {*} [context] The JSON-serializable values to call the script with
303
+ */
304
+
305
+ /**
306
+ * Evaluates a script on all shards, or a given shard, in the context of the {@link Client}s.
307
+ *
308
+ * @param {Function} script JavaScript to run on each shard
309
+ * @param {BroadcastEvalOptions} [options={}] The options for the broadcast
310
+ * @returns {Promise<*|Array<*>>} Results of the script execution
311
+ */
312
+ async broadcastEval(script, options = {}) {
313
+ if (typeof script !== 'function') {
314
+ throw new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast);
315
+ }
316
+
317
+ return this._performOnShards('eval', [`(${script})(this, ${JSON.stringify(options.context)})`], options.shard);
318
+ }
319
+
320
+ /**
321
+ * Fetches a client property value of each shard, or a given shard.
322
+ *
323
+ * @param {string} prop Name of the client property to get, using periods for nesting
324
+ * @param {number} [shard] Shard to fetch property from, all if undefined
325
+ * @returns {Promise<*|Array<*>>}
326
+ * @example
327
+ * manager.fetchClientValues('guilds.cache.size')
328
+ * .then(results => console.log(`${results.reduce((prev, val) => prev + val, 0)} total guilds`))
329
+ * .catch(console.error);
330
+ */
331
+ async fetchClientValues(prop, shard) {
332
+ return this._performOnShards('fetchClientValue', [prop], shard);
333
+ }
334
+
335
+ /**
336
+ * Runs a method with given arguments on all shards, or a given shard.
337
+ *
338
+ * @param {string} method Method name to run on each shard
339
+ * @param {Array<*>} args Arguments to pass through to the method call
340
+ * @param {number} [shard] Shard to run on, all if undefined
341
+ * @returns {Promise<*|Array<*>>} Results of the method execution
342
+ * @private
343
+ */
344
+ async _performOnShards(method, args, shard) {
345
+ if (this.shards.size === 0) throw new DiscordjsError(ErrorCodes.ShardingNoShards);
346
+
347
+ if (typeof shard === 'number') {
348
+ if (this.shards.has(shard)) return this.shards.get(shard)[method](...args);
349
+ throw new DiscordjsError(ErrorCodes.ShardingShardNotFound, shard);
350
+ }
351
+
352
+ if (this.shards.size !== this.shardList.length) {
353
+ throw new DiscordjsError(ErrorCodes.ShardingInProcess);
354
+ }
355
+
356
+ const promises = [];
357
+ for (const sh of this.shards.values()) promises.push(sh[method](...args));
358
+ return Promise.all(promises);
359
+ }
360
+
361
+ /**
362
+ * Options used to respawn all shards.
363
+ *
364
+ * @typedef {Object} MultipleShardRespawnOptions
365
+ * @property {number} [shardDelay=5000] How long to wait between shards (in milliseconds)
366
+ * @property {number} [respawnDelay=500] How long to wait between killing a shard's process and restarting it
367
+ * (in milliseconds)
368
+ * @property {number} [timeout=30000] The amount in milliseconds to wait for a shard to become ready before
369
+ * continuing to another (`-1` or `Infinity` for no wait)
370
+ */
371
+
372
+ /**
373
+ * Kills all running shards and respawns them.
374
+ *
375
+ * @param {MultipleShardRespawnOptions} [options] Options for respawning shards
376
+ * @returns {Promise<Collection<number, Shard>>}
377
+ */
378
+ async respawnAll({ shardDelay = 5_000, respawnDelay = 500, timeout = 30_000 } = {}) {
379
+ let shardCounter = 0;
380
+ for (const shard of this.shards.values()) {
381
+ const promises = [shard.respawn({ delay: respawnDelay, timeout })];
382
+ if (++shardCounter < this.shards.size && shardDelay > 0) promises.push(sleep(shardDelay));
383
+ await Promise.all(promises);
384
+ }
385
+
386
+ return this.shards;
387
+ }
388
+ }
389
+
390
+ exports.ShardingManager = ShardingManager;