discord-sb.js 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 (366) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +2 -0
  3. package/package.json +91 -0
  4. package/src/WebSocket.js +39 -0
  5. package/src/client/BaseClient.js +86 -0
  6. package/src/client/Client.js +978 -0
  7. package/src/client/WebhookClient.js +61 -0
  8. package/src/client/actions/Action.js +116 -0
  9. package/src/client/actions/ActionsManager.js +80 -0
  10. package/src/client/actions/ApplicationCommandPermissionsUpdate.js +34 -0
  11. package/src/client/actions/AutoModerationActionExecution.js +27 -0
  12. package/src/client/actions/AutoModerationRuleCreate.js +28 -0
  13. package/src/client/actions/AutoModerationRuleDelete.js +32 -0
  14. package/src/client/actions/AutoModerationRuleUpdate.js +30 -0
  15. package/src/client/actions/ChannelCreate.js +23 -0
  16. package/src/client/actions/ChannelDelete.js +39 -0
  17. package/src/client/actions/ChannelUpdate.js +43 -0
  18. package/src/client/actions/GuildAuditLogEntryCreate.js +29 -0
  19. package/src/client/actions/GuildBanAdd.js +20 -0
  20. package/src/client/actions/GuildBanRemove.js +25 -0
  21. package/src/client/actions/GuildChannelsPositionUpdate.js +21 -0
  22. package/src/client/actions/GuildDelete.js +65 -0
  23. package/src/client/actions/GuildEmojiCreate.js +20 -0
  24. package/src/client/actions/GuildEmojiDelete.js +21 -0
  25. package/src/client/actions/GuildEmojiUpdate.js +20 -0
  26. package/src/client/actions/GuildEmojisUpdate.js +34 -0
  27. package/src/client/actions/GuildIntegrationsUpdate.js +19 -0
  28. package/src/client/actions/GuildMemberRemove.js +33 -0
  29. package/src/client/actions/GuildMemberUpdate.js +44 -0
  30. package/src/client/actions/GuildRoleCreate.js +25 -0
  31. package/src/client/actions/GuildRoleDelete.js +31 -0
  32. package/src/client/actions/GuildRoleUpdate.js +39 -0
  33. package/src/client/actions/GuildRolesPositionUpdate.js +21 -0
  34. package/src/client/actions/GuildScheduledEventCreate.js +27 -0
  35. package/src/client/actions/GuildScheduledEventDelete.js +31 -0
  36. package/src/client/actions/GuildScheduledEventUpdate.js +30 -0
  37. package/src/client/actions/GuildScheduledEventUserAdd.js +32 -0
  38. package/src/client/actions/GuildScheduledEventUserRemove.js +32 -0
  39. package/src/client/actions/GuildStickerCreate.js +20 -0
  40. package/src/client/actions/GuildStickerDelete.js +21 -0
  41. package/src/client/actions/GuildStickerUpdate.js +20 -0
  42. package/src/client/actions/GuildStickersUpdate.js +34 -0
  43. package/src/client/actions/GuildUpdate.js +33 -0
  44. package/src/client/actions/InviteCreate.js +28 -0
  45. package/src/client/actions/InviteDelete.js +30 -0
  46. package/src/client/actions/MessageCreate.js +50 -0
  47. package/src/client/actions/MessageDelete.js +32 -0
  48. package/src/client/actions/MessageDeleteBulk.js +46 -0
  49. package/src/client/actions/MessagePollVoteAdd.js +33 -0
  50. package/src/client/actions/MessagePollVoteRemove.js +33 -0
  51. package/src/client/actions/MessageReactionAdd.js +68 -0
  52. package/src/client/actions/MessageReactionRemove.js +50 -0
  53. package/src/client/actions/MessageReactionRemoveAll.js +33 -0
  54. package/src/client/actions/MessageReactionRemoveEmoji.js +28 -0
  55. package/src/client/actions/MessageUpdate.js +26 -0
  56. package/src/client/actions/PresenceUpdate.js +50 -0
  57. package/src/client/actions/StageInstanceCreate.js +28 -0
  58. package/src/client/actions/StageInstanceDelete.js +33 -0
  59. package/src/client/actions/StageInstanceUpdate.js +30 -0
  60. package/src/client/actions/ThreadCreate.js +24 -0
  61. package/src/client/actions/ThreadDelete.js +32 -0
  62. package/src/client/actions/ThreadListSync.js +59 -0
  63. package/src/client/actions/ThreadMemberUpdate.js +30 -0
  64. package/src/client/actions/ThreadMembersUpdate.js +34 -0
  65. package/src/client/actions/TypingStart.js +29 -0
  66. package/src/client/actions/UserUpdate.js +35 -0
  67. package/src/client/actions/VoiceStateUpdate.js +50 -0
  68. package/src/client/actions/WebhooksUpdate.js +20 -0
  69. package/src/client/voice/ClientVoiceManager.js +151 -0
  70. package/src/client/voice/VoiceConnection.js +1249 -0
  71. package/src/client/voice/dispatcher/AnnexBDispatcher.js +120 -0
  72. package/src/client/voice/dispatcher/AudioDispatcher.js +145 -0
  73. package/src/client/voice/dispatcher/BaseDispatcher.js +459 -0
  74. package/src/client/voice/dispatcher/VPxDispatcher.js +54 -0
  75. package/src/client/voice/dispatcher/VideoDispatcher.js +68 -0
  76. package/src/client/voice/networking/VoiceUDPClient.js +173 -0
  77. package/src/client/voice/networking/VoiceWebSocket.js +286 -0
  78. package/src/client/voice/player/MediaPlayer.js +321 -0
  79. package/src/client/voice/player/processing/AnnexBNalSplitter.js +244 -0
  80. package/src/client/voice/player/processing/IvfSplitter.js +106 -0
  81. package/src/client/voice/player/processing/PCMInsertSilence.js +37 -0
  82. package/src/client/voice/receiver/PacketHandler.js +260 -0
  83. package/src/client/voice/receiver/Receiver.js +96 -0
  84. package/src/client/voice/receiver/Recorder.js +173 -0
  85. package/src/client/voice/util/Function.js +116 -0
  86. package/src/client/voice/util/PlayInterface.js +122 -0
  87. package/src/client/voice/util/Secretbox.js +64 -0
  88. package/src/client/voice/util/Silence.js +16 -0
  89. package/src/client/voice/util/Socket.js +62 -0
  90. package/src/client/voice/util/VolumeInterface.js +104 -0
  91. package/src/client/websocket/WebSocketManager.js +392 -0
  92. package/src/client/websocket/WebSocketShard.js +907 -0
  93. package/src/client/websocket/handlers/APPLICATION_COMMAND_CREATE.js +18 -0
  94. package/src/client/websocket/handlers/APPLICATION_COMMAND_DELETE.js +20 -0
  95. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +5 -0
  96. package/src/client/websocket/handlers/APPLICATION_COMMAND_UPDATE.js +20 -0
  97. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +5 -0
  98. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +5 -0
  99. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +5 -0
  100. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +5 -0
  101. package/src/client/websocket/handlers/CALL_CREATE.js +14 -0
  102. package/src/client/websocket/handlers/CALL_DELETE.js +11 -0
  103. package/src/client/websocket/handlers/CALL_UPDATE.js +11 -0
  104. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -0
  105. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -0
  106. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +22 -0
  107. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_ADD.js +19 -0
  108. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_REMOVE.js +16 -0
  109. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +16 -0
  110. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +5 -0
  111. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +5 -0
  112. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +5 -0
  113. package/src/client/websocket/handlers/GUILD_CREATE.js +52 -0
  114. package/src/client/websocket/handlers/GUILD_DELETE.js +5 -0
  115. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -0
  116. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +5 -0
  117. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +39 -0
  118. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +20 -0
  119. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -0
  120. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -0
  121. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -0
  122. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -0
  123. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +5 -0
  124. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +5 -0
  125. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -0
  126. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +5 -0
  127. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -0
  128. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -0
  129. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -0
  130. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  131. package/src/client/websocket/handlers/INTERACTION_MODAL_CREATE.js +12 -0
  132. package/src/client/websocket/handlers/INVITE_CREATE.js +5 -0
  133. package/src/client/websocket/handlers/INVITE_DELETE.js +5 -0
  134. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  135. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  136. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  137. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_ADD.js +5 -0
  138. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_REMOVE.js +5 -0
  139. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  140. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  141. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  142. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  143. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +16 -0
  144. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +5 -0
  145. package/src/client/websocket/handlers/READY.js +121 -0
  146. package/src/client/websocket/handlers/RELATIONSHIP_ADD.js +19 -0
  147. package/src/client/websocket/handlers/RELATIONSHIP_REMOVE.js +17 -0
  148. package/src/client/websocket/handlers/RELATIONSHIP_UPDATE.js +41 -0
  149. package/src/client/websocket/handlers/RESUMED.js +14 -0
  150. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  151. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  152. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  153. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  154. package/src/client/websocket/handlers/THREAD_DELETE.js +5 -0
  155. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +5 -0
  156. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  157. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +5 -0
  158. package/src/client/websocket/handlers/THREAD_UPDATE.js +16 -0
  159. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  160. package/src/client/websocket/handlers/USER_GUILD_SETTINGS_UPDATE.js +6 -0
  161. package/src/client/websocket/handlers/USER_NOTE_UPDATE.js +5 -0
  162. package/src/client/websocket/handlers/USER_REQUIRED_ACTION_UPDATE.js +78 -0
  163. package/src/client/websocket/handlers/USER_SETTINGS_UPDATE.js +5 -0
  164. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  165. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +16 -0
  166. package/src/client/websocket/handlers/VOICE_CHANNEL_STATUS_UPDATE.js +12 -0
  167. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +6 -0
  168. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +5 -0
  169. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +5 -0
  170. package/src/client/websocket/handlers/index.js +84 -0
  171. package/src/errors/DJSError.js +61 -0
  172. package/src/errors/Messages.js +217 -0
  173. package/src/errors/index.js +4 -0
  174. package/src/index.js +172 -0
  175. package/src/managers/ApplicationCommandManager.js +264 -0
  176. package/src/managers/ApplicationCommandPermissionsManager.js +417 -0
  177. package/src/managers/AutoModerationRuleManager.js +296 -0
  178. package/src/managers/BaseGuildEmojiManager.js +80 -0
  179. package/src/managers/BaseManager.js +19 -0
  180. package/src/managers/BillingManager.js +66 -0
  181. package/src/managers/CachedManager.js +71 -0
  182. package/src/managers/ChannelManager.js +148 -0
  183. package/src/managers/ClientUserSettingManager.js +372 -0
  184. package/src/managers/DataManager.js +61 -0
  185. package/src/managers/DeveloperManager.js +254 -0
  186. package/src/managers/GuildBanManager.js +250 -0
  187. package/src/managers/GuildChannelManager.js +488 -0
  188. package/src/managers/GuildEmojiManager.js +171 -0
  189. package/src/managers/GuildEmojiRoleManager.js +118 -0
  190. package/src/managers/GuildForumThreadManager.js +108 -0
  191. package/src/managers/GuildInviteManager.js +213 -0
  192. package/src/managers/GuildManager.js +338 -0
  193. package/src/managers/GuildMemberManager.js +599 -0
  194. package/src/managers/GuildMemberRoleManager.js +195 -0
  195. package/src/managers/GuildScheduledEventManager.js +314 -0
  196. package/src/managers/GuildSettingManager.js +155 -0
  197. package/src/managers/GuildStickerManager.js +179 -0
  198. package/src/managers/GuildTextThreadManager.js +98 -0
  199. package/src/managers/InteractionManager.js +39 -0
  200. package/src/managers/MessageManager.js +423 -0
  201. package/src/managers/PermissionOverwriteManager.js +164 -0
  202. package/src/managers/PresenceManager.js +71 -0
  203. package/src/managers/QuestManager.js +353 -0
  204. package/src/managers/ReactionManager.js +67 -0
  205. package/src/managers/ReactionUserManager.js +73 -0
  206. package/src/managers/RelationshipManager.js +278 -0
  207. package/src/managers/RoleManager.js +448 -0
  208. package/src/managers/SessionManager.js +66 -0
  209. package/src/managers/StageInstanceManager.js +162 -0
  210. package/src/managers/ThreadManager.js +175 -0
  211. package/src/managers/ThreadMemberManager.js +186 -0
  212. package/src/managers/UserManager.js +136 -0
  213. package/src/managers/UserNoteManager.js +53 -0
  214. package/src/managers/VoiceStateManager.js +59 -0
  215. package/src/rest/APIRequest.js +154 -0
  216. package/src/rest/APIRouter.js +53 -0
  217. package/src/rest/DiscordAPIError.js +119 -0
  218. package/src/rest/HTTPError.js +62 -0
  219. package/src/rest/RESTManager.js +67 -0
  220. package/src/rest/RateLimitError.js +55 -0
  221. package/src/rest/RequestHandler.js +466 -0
  222. package/src/sharding/Shard.js +444 -0
  223. package/src/sharding/ShardClientUtil.js +279 -0
  224. package/src/sharding/ShardingManager.js +319 -0
  225. package/src/structures/AnonymousGuild.js +98 -0
  226. package/src/structures/ApplicationCommand.js +593 -0
  227. package/src/structures/ApplicationRoleConnectionMetadata.js +48 -0
  228. package/src/structures/AutoModerationActionExecution.js +89 -0
  229. package/src/structures/AutoModerationRule.js +294 -0
  230. package/src/structures/AutocompleteInteraction.js +107 -0
  231. package/src/structures/Base.js +43 -0
  232. package/src/structures/BaseCommandInteraction.js +211 -0
  233. package/src/structures/BaseGuild.js +116 -0
  234. package/src/structures/BaseGuildEmoji.js +56 -0
  235. package/src/structures/BaseGuildTextChannel.js +191 -0
  236. package/src/structures/BaseGuildVoiceChannel.js +241 -0
  237. package/src/structures/BaseMessageComponent.js +181 -0
  238. package/src/structures/ButtonInteraction.js +11 -0
  239. package/src/structures/CallState.js +63 -0
  240. package/src/structures/CategoryChannel.js +85 -0
  241. package/src/structures/Channel.js +284 -0
  242. package/src/structures/ClientPresence.js +77 -0
  243. package/src/structures/ClientUser.js +655 -0
  244. package/src/structures/CommandInteraction.js +41 -0
  245. package/src/structures/CommandInteractionOptionResolver.js +276 -0
  246. package/src/structures/ContainerComponent.js +68 -0
  247. package/src/structures/ContextMenuInteraction.js +65 -0
  248. package/src/structures/DMChannel.js +219 -0
  249. package/src/structures/DirectoryChannel.js +20 -0
  250. package/src/structures/Emoji.js +148 -0
  251. package/src/structures/FileComponent.js +49 -0
  252. package/src/structures/ForumChannel.js +31 -0
  253. package/src/structures/GroupDMChannel.js +394 -0
  254. package/src/structures/Guild.js +1791 -0
  255. package/src/structures/GuildAuditLogs.js +746 -0
  256. package/src/structures/GuildBan.js +59 -0
  257. package/src/structures/GuildBoost.js +108 -0
  258. package/src/structures/GuildChannel.js +470 -0
  259. package/src/structures/GuildEmoji.js +161 -0
  260. package/src/structures/GuildMember.js +636 -0
  261. package/src/structures/GuildPreview.js +191 -0
  262. package/src/structures/GuildPreviewEmoji.js +27 -0
  263. package/src/structures/GuildScheduledEvent.js +536 -0
  264. package/src/structures/GuildTemplate.js +236 -0
  265. package/src/structures/Integration.js +188 -0
  266. package/src/structures/IntegrationApplication.js +96 -0
  267. package/src/structures/Interaction.js +290 -0
  268. package/src/structures/InteractionCollector.js +248 -0
  269. package/src/structures/InteractionWebhook.js +43 -0
  270. package/src/structures/Invite.js +358 -0
  271. package/src/structures/InviteGuild.js +23 -0
  272. package/src/structures/InviteStageInstance.js +86 -0
  273. package/src/structures/MediaChannel.js +11 -0
  274. package/src/structures/MediaGalleryComponent.js +41 -0
  275. package/src/structures/MediaGalleryItem.js +47 -0
  276. package/src/structures/Message.js +1252 -0
  277. package/src/structures/MessageActionRow.js +105 -0
  278. package/src/structures/MessageAttachment.js +216 -0
  279. package/src/structures/MessageButton.js +166 -0
  280. package/src/structures/MessageCollector.js +146 -0
  281. package/src/structures/MessageComponentInteraction.js +120 -0
  282. package/src/structures/MessageContextMenuInteraction.js +20 -0
  283. package/src/structures/MessageEmbed.js +596 -0
  284. package/src/structures/MessageMentions.js +273 -0
  285. package/src/structures/MessagePayload.js +354 -0
  286. package/src/structures/MessageReaction.js +181 -0
  287. package/src/structures/MessageSelectMenu.js +141 -0
  288. package/src/structures/Modal.js +161 -0
  289. package/src/structures/ModalSubmitFieldsResolver.js +53 -0
  290. package/src/structures/ModalSubmitInteraction.js +119 -0
  291. package/src/structures/NewsChannel.js +32 -0
  292. package/src/structures/OAuth2Guild.js +28 -0
  293. package/src/structures/PermissionOverwrites.js +198 -0
  294. package/src/structures/Poll.js +108 -0
  295. package/src/structures/PollAnswer.js +88 -0
  296. package/src/structures/Presence.js +1157 -0
  297. package/src/structures/ReactionCollector.js +229 -0
  298. package/src/structures/ReactionEmoji.js +31 -0
  299. package/src/structures/Role.js +590 -0
  300. package/src/structures/SectionComponent.js +48 -0
  301. package/src/structures/SelectMenuInteraction.js +21 -0
  302. package/src/structures/SeparatorComponent.js +48 -0
  303. package/src/structures/Session.js +81 -0
  304. package/src/structures/StageChannel.js +104 -0
  305. package/src/structures/StageInstance.js +208 -0
  306. package/src/structures/Sticker.js +310 -0
  307. package/src/structures/StickerPack.js +95 -0
  308. package/src/structures/StoreChannel.js +56 -0
  309. package/src/structures/Team.js +118 -0
  310. package/src/structures/TeamMember.js +80 -0
  311. package/src/structures/TextChannel.js +33 -0
  312. package/src/structures/TextDisplayComponent.js +40 -0
  313. package/src/structures/TextInputComponent.js +132 -0
  314. package/src/structures/ThreadChannel.js +605 -0
  315. package/src/structures/ThreadMember.js +105 -0
  316. package/src/structures/ThreadOnlyChannel.js +249 -0
  317. package/src/structures/ThumbnailComponent.js +57 -0
  318. package/src/structures/Typing.js +74 -0
  319. package/src/structures/UnfurledMediaItem.js +29 -0
  320. package/src/structures/User.js +640 -0
  321. package/src/structures/UserContextMenuInteraction.js +29 -0
  322. package/src/structures/VoiceChannel.js +110 -0
  323. package/src/structures/VoiceChannelEffect.js +69 -0
  324. package/src/structures/VoiceRegion.js +53 -0
  325. package/src/structures/VoiceState.js +354 -0
  326. package/src/structures/WebEmbed.js +373 -0
  327. package/src/structures/Webhook.js +478 -0
  328. package/src/structures/WelcomeChannel.js +60 -0
  329. package/src/structures/WelcomeScreen.js +48 -0
  330. package/src/structures/Widget.js +87 -0
  331. package/src/structures/WidgetMember.js +99 -0
  332. package/src/structures/interfaces/Application.js +953 -0
  333. package/src/structures/interfaces/Collector.js +300 -0
  334. package/src/structures/interfaces/InteractionResponses.js +313 -0
  335. package/src/structures/interfaces/TextBasedChannel.js +821 -0
  336. package/src/util/APITypes.js +59 -0
  337. package/src/util/ActivityFlags.js +44 -0
  338. package/src/util/ApplicationFlags.js +76 -0
  339. package/src/util/AttachmentFlags.js +38 -0
  340. package/src/util/BitField.js +170 -0
  341. package/src/util/ChannelFlags.js +45 -0
  342. package/src/util/Constants.js +1914 -0
  343. package/src/util/DataResolver.js +146 -0
  344. package/src/util/Formatters.js +228 -0
  345. package/src/util/GuildMemberFlags.js +43 -0
  346. package/src/util/Intents.js +74 -0
  347. package/src/util/InviteFlags.js +34 -0
  348. package/src/util/LimitedCollection.js +131 -0
  349. package/src/util/MessageFlags.js +63 -0
  350. package/src/util/Options.js +358 -0
  351. package/src/util/Permissions.js +202 -0
  352. package/src/util/PremiumUsageFlags.js +31 -0
  353. package/src/util/PurchasedFlags.js +33 -0
  354. package/src/util/RemoteAuth.js +415 -0
  355. package/src/util/RoleFlags.js +37 -0
  356. package/src/util/SnowflakeUtil.js +92 -0
  357. package/src/util/Speaking.js +33 -0
  358. package/src/util/Sweepers.js +466 -0
  359. package/src/util/SystemChannelFlags.js +55 -0
  360. package/src/util/ThreadMemberFlags.js +30 -0
  361. package/src/util/UserFlags.js +104 -0
  362. package/src/util/Util.js +1048 -0
  363. package/typings/enums.d.ts +439 -0
  364. package/typings/index.d.ts +8505 -0
  365. package/typings/index.test-d.ts +0 -0
  366. package/typings/rawDataTypes.d.ts +403 -0
@@ -0,0 +1,1048 @@
1
+ 'use strict';
2
+
3
+ const { Agent } = require('node:http');
4
+ const { parse } = require('node:path');
5
+ const process = require('node:process');
6
+ const { setTimeout } = require('node:timers');
7
+ const { Collection } = require('@discordjs/collection');
8
+ const { fetch } = require('undici');
9
+ const { Colors, Events } = require('./Constants');
10
+ const { Error: DiscordError, RangeError, TypeError } = require('../errors');
11
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
12
+ const isObject = d => typeof d === 'object' && d !== null;
13
+
14
+ let deprecationEmittedForSplitMessage = false;
15
+ let deprecationEmittedForRemoveMentions = false;
16
+ let deprecationEmittedForResolveAutoArchiveMaxLimit = false;
17
+
18
+ const TextSortableGroupTypes = ['GUILD_TEXT', 'GUILD_ANNOUCMENT', 'GUILD_FORUM'];
19
+ const VoiceSortableGroupTypes = ['GUILD_VOICE', 'GUILD_STAGE_VOICE'];
20
+ const CategorySortableGroupTypes = ['GUILD_CATEGORY'];
21
+
22
+ const payloadTypes = [
23
+ {
24
+ name: 'opus',
25
+ type: 'audio',
26
+ priority: 1000,
27
+ payload_type: 120,
28
+ },
29
+ {
30
+ name: 'AV1',
31
+ type: 'video',
32
+ priority: 1000,
33
+ payload_type: 101,
34
+ rtx_payload_type: 102,
35
+ encode: false,
36
+ decode: false,
37
+ },
38
+ {
39
+ name: 'H265',
40
+ type: 'video',
41
+ priority: 2000,
42
+ payload_type: 103,
43
+ rtx_payload_type: 104,
44
+ encode: false,
45
+ decode: false,
46
+ },
47
+ {
48
+ name: 'H264',
49
+ type: 'video',
50
+ priority: 3000,
51
+ payload_type: 105,
52
+ rtx_payload_type: 106,
53
+ encode: true,
54
+ decode: true,
55
+ },
56
+ {
57
+ name: 'VP8',
58
+ type: 'video',
59
+ priority: 4000,
60
+ payload_type: 107,
61
+ rtx_payload_type: 108,
62
+ encode: true,
63
+ decode: false,
64
+ },
65
+ {
66
+ name: 'VP9',
67
+ type: 'video',
68
+ priority: 5000,
69
+ payload_type: 109,
70
+ rtx_payload_type: 110,
71
+ encode: false,
72
+ decode: false,
73
+ },
74
+ ];
75
+
76
+ /**
77
+ * Contains various general-purpose utility methods.
78
+ */
79
+ class Util extends null {
80
+ /**
81
+ * Flatten an object. Any properties that are collections will get converted to an array of keys.
82
+ * @param {Object} obj The object to flatten.
83
+ * @param {...Object<string, boolean|string>} [props] Specific properties to include/exclude.
84
+ * @returns {Object}
85
+ */
86
+ static flatten(obj, ...props) {
87
+ if (!isObject(obj)) return obj;
88
+
89
+ const objProps = Object.keys(obj)
90
+ .filter(k => !k.startsWith('_'))
91
+ .map(k => ({ [k]: true }));
92
+
93
+ props = objProps.length ? Object.assign(...objProps, ...props) : Object.assign({}, ...props);
94
+
95
+ const out = {};
96
+
97
+ for (let [prop, newProp] of Object.entries(props)) {
98
+ if (!newProp) continue;
99
+ newProp = newProp === true ? prop : newProp;
100
+
101
+ const element = obj[prop];
102
+ const elemIsObj = isObject(element);
103
+ const valueOf = elemIsObj && typeof element.valueOf === 'function' ? element.valueOf() : null;
104
+ const hasToJSON = elemIsObj && typeof element.toJSON === 'function';
105
+
106
+ // If it's a Collection, make the array of keys
107
+ if (element instanceof Collection) out[newProp] = Array.from(element.keys());
108
+ // If the valueOf is a Collection, use its array of keys
109
+ else if (valueOf instanceof Collection) out[newProp] = Array.from(valueOf.keys());
110
+ // If it's an array, call toJSON function on each element if present, otherwise flatten each element
111
+ else if (Array.isArray(element)) out[newProp] = element.map(e => e.toJSON?.() ?? Util.flatten(e));
112
+ // If it's an object with a primitive `valueOf`, use that value
113
+ else if (typeof valueOf !== 'object') out[newProp] = valueOf;
114
+ // If it's an object with a toJSON function, use the return value of it
115
+ else if (hasToJSON) out[newProp] = element.toJSON();
116
+ // If element is an object, use the flattened version of it
117
+ else if (typeof element === 'object') out[newProp] = Util.flatten(element);
118
+ // If it's a primitive
119
+ else if (!elemIsObj) out[newProp] = element;
120
+ }
121
+
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * Options for splitting a message.
127
+ * @typedef {Object} SplitOptions
128
+ * @property {number} [maxLength=2000] Maximum character length per message piece
129
+ * @property {string|string[]|RegExp|RegExp[]} [char='\n'] Character(s) or Regex(es) to split the message with,
130
+ * an array can be used to split multiple times
131
+ * @property {string} [prepend=''] Text to prepend to every piece except the first
132
+ * @property {string} [append=''] Text to append to every piece except the last
133
+ */
134
+
135
+ /**
136
+ * Splits a string into multiple chunks at a designated character that do not exceed a specific length.
137
+ * @param {string} text Content to split
138
+ * @param {SplitOptions} [options] Options controlling the behavior of the split
139
+ * @deprecated This will be removed in the next major version.
140
+ * @returns {string[]}
141
+ */
142
+ static splitMessage(text, { maxLength = 2_000, char = '\n', prepend = '', append = '' } = {}) {
143
+ if (!deprecationEmittedForSplitMessage) {
144
+ process.emitWarning(
145
+ 'The Util.splitMessage method is deprecated and will be removed in the next major version.',
146
+ 'DeprecationWarning',
147
+ );
148
+
149
+ deprecationEmittedForSplitMessage = true;
150
+ }
151
+
152
+ text = Util.verifyString(text);
153
+ if (text.length <= maxLength) return [text];
154
+ let splitText = [text];
155
+ if (Array.isArray(char)) {
156
+ while (char.length > 0 && splitText.some(elem => elem.length > maxLength)) {
157
+ const currentChar = char.shift();
158
+ if (currentChar instanceof RegExp) {
159
+ splitText = splitText.flatMap(chunk => chunk.match(currentChar));
160
+ } else {
161
+ splitText = splitText.flatMap(chunk => chunk.split(currentChar));
162
+ }
163
+ }
164
+ } else {
165
+ splitText = text.split(char);
166
+ }
167
+ if (splitText.some(elem => elem.length > maxLength)) throw new RangeError('SPLIT_MAX_LEN');
168
+ const messages = [];
169
+ let msg = '';
170
+ for (const chunk of splitText) {
171
+ if (msg && (msg + char + chunk + append).length > maxLength) {
172
+ messages.push(msg + append);
173
+ msg = prepend;
174
+ }
175
+ msg += (msg && msg !== prepend ? char : '') + chunk;
176
+ }
177
+ return messages.concat(msg).filter(m => m);
178
+ }
179
+
180
+ /**
181
+ * Options used to escape markdown.
182
+ * @typedef {Object} EscapeMarkdownOptions
183
+ * @property {boolean} [codeBlock=true] Whether to escape code blocks
184
+ * @property {boolean} [inlineCode=true] Whether to escape inline code
185
+ * @property {boolean} [bold=true] Whether to escape bolds
186
+ * @property {boolean} [italic=true] Whether to escape italics
187
+ * @property {boolean} [underline=true] Whether to escape underlines
188
+ * @property {boolean} [strikethrough=true] Whether to escape strikethroughs
189
+ * @property {boolean} [spoiler=true] Whether to escape spoilers
190
+ * @property {boolean} [codeBlockContent=true] Whether to escape text inside code blocks
191
+ * @property {boolean} [inlineCodeContent=true] Whether to escape text inside inline code
192
+ * @property {boolean} [escape=true] Whether to escape escape characters
193
+ * @property {boolean} [heading=false] Whether to escape headings
194
+ * @property {boolean} [bulletedList=false] Whether to escape bulleted lists
195
+ * @property {boolean} [numberedList=false] Whether to escape numbered lists
196
+ * @property {boolean} [maskedLink=false] Whether to escape masked links
197
+ */
198
+
199
+ /**
200
+ * Escapes any Discord-flavour markdown in a string.
201
+ * @param {string} text Content to escape
202
+ * @param {EscapeMarkdownOptions} [options={}] Options for escaping the markdown
203
+ * @returns {string}
204
+ */
205
+ static escapeMarkdown(
206
+ text,
207
+ {
208
+ codeBlock = true,
209
+ inlineCode = true,
210
+ bold = true,
211
+ italic = true,
212
+ underline = true,
213
+ strikethrough = true,
214
+ spoiler = true,
215
+ codeBlockContent = true,
216
+ inlineCodeContent = true,
217
+ escape = true,
218
+ heading = false,
219
+ bulletedList = false,
220
+ numberedList = false,
221
+ maskedLink = false,
222
+ } = {},
223
+ ) {
224
+ if (!codeBlockContent) {
225
+ return text
226
+ .split('```')
227
+ .map((subString, index, array) => {
228
+ if (index % 2 && index !== array.length - 1) return subString;
229
+ return Util.escapeMarkdown(subString, {
230
+ inlineCode,
231
+ bold,
232
+ italic,
233
+ underline,
234
+ strikethrough,
235
+ spoiler,
236
+ inlineCodeContent,
237
+ escape,
238
+ heading,
239
+ bulletedList,
240
+ numberedList,
241
+ maskedLink,
242
+ });
243
+ })
244
+ .join(codeBlock ? '\\`\\`\\`' : '```');
245
+ }
246
+ if (!inlineCodeContent) {
247
+ return text
248
+ .split(/(?<=^|[^`])`(?=[^`]|$)/g)
249
+ .map((subString, index, array) => {
250
+ if (index % 2 && index !== array.length - 1) return subString;
251
+ return Util.escapeMarkdown(subString, {
252
+ codeBlock,
253
+ bold,
254
+ italic,
255
+ underline,
256
+ strikethrough,
257
+ spoiler,
258
+ escape,
259
+ heading,
260
+ bulletedList,
261
+ numberedList,
262
+ maskedLink,
263
+ });
264
+ })
265
+ .join(inlineCode ? '\\`' : '`');
266
+ }
267
+ if (escape) text = Util.escapeEscape(text);
268
+ if (inlineCode) text = Util.escapeInlineCode(text);
269
+ if (codeBlock) text = Util.escapeCodeBlock(text);
270
+ if (italic) text = Util.escapeItalic(text);
271
+ if (bold) text = Util.escapeBold(text);
272
+ if (underline) text = Util.escapeUnderline(text);
273
+ if (strikethrough) text = Util.escapeStrikethrough(text);
274
+ if (spoiler) text = Util.escapeSpoiler(text);
275
+ if (heading) text = Util.escapeHeading(text);
276
+ if (bulletedList) text = Util.escapeBulletedList(text);
277
+ if (numberedList) text = Util.escapeNumberedList(text);
278
+ if (maskedLink) text = Util.escapeMaskedLink(text);
279
+ return text;
280
+ }
281
+
282
+ /**
283
+ * Escapes code block markdown in a string.
284
+ * @param {string} text Content to escape
285
+ * @returns {string}
286
+ */
287
+ static escapeCodeBlock(text) {
288
+ return text.replaceAll('```', '\\`\\`\\`');
289
+ }
290
+
291
+ /**
292
+ * Escapes inline code markdown in a string.
293
+ * @param {string} text Content to escape
294
+ * @returns {string}
295
+ */
296
+ static escapeInlineCode(text) {
297
+ return text.replace(/(?<=^|[^`])``?(?=[^`]|$)/g, match => (match.length === 2 ? '\\`\\`' : '\\`'));
298
+ }
299
+
300
+ /**
301
+ * Escapes italic markdown in a string.
302
+ * @param {string} text Content to escape
303
+ * @returns {string}
304
+ */
305
+ static escapeItalic(text) {
306
+ let i = 0;
307
+ text = text.replace(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => {
308
+ if (match === '**') return ++i % 2 ? `\\*${match}` : `${match}\\*`;
309
+ return `\\*${match}`;
310
+ });
311
+ i = 0;
312
+ return text.replace(/(?<=^|[^_])_([^_]|__|$)/g, (_, match) => {
313
+ if (match === '__') return ++i % 2 ? `\\_${match}` : `${match}\\_`;
314
+ return `\\_${match}`;
315
+ });
316
+ }
317
+
318
+ /**
319
+ * Escapes bold markdown in a string.
320
+ * @param {string} text Content to escape
321
+ * @returns {string}
322
+ */
323
+ static escapeBold(text) {
324
+ let i = 0;
325
+ return text.replace(/\*\*(\*)?/g, (_, match) => {
326
+ if (match) return ++i % 2 ? `${match}\\*\\*` : `\\*\\*${match}`;
327
+ return '\\*\\*';
328
+ });
329
+ }
330
+
331
+ /**
332
+ * Escapes underline markdown in a string.
333
+ * @param {string} text Content to escape
334
+ * @returns {string}
335
+ */
336
+ static escapeUnderline(text) {
337
+ let i = 0;
338
+ return text.replace(/__(_)?/g, (_, match) => {
339
+ if (match) return ++i % 2 ? `${match}\\_\\_` : `\\_\\_${match}`;
340
+ return '\\_\\_';
341
+ });
342
+ }
343
+
344
+ /**
345
+ * Escapes strikethrough markdown in a string.
346
+ * @param {string} text Content to escape
347
+ * @returns {string}
348
+ */
349
+ static escapeStrikethrough(text) {
350
+ return text.replaceAll('~~', '\\~\\~');
351
+ }
352
+
353
+ /**
354
+ * Escapes spoiler markdown in a string.
355
+ * @param {string} text Content to escape
356
+ * @returns {string}
357
+ */
358
+ static escapeSpoiler(text) {
359
+ return text.replaceAll('||', '\\|\\|');
360
+ }
361
+
362
+ /**
363
+ * Escapes escape characters in a string.
364
+ * @param {string} text Content to escape
365
+ * @returns {string}
366
+ */
367
+ static escapeEscape(text) {
368
+ return text.replaceAll('\\', '\\\\');
369
+ }
370
+
371
+ /**
372
+ * Escapes heading characters in a string.
373
+ * @param {string} text Content to escape
374
+ * @returns {string}
375
+ */
376
+ static escapeHeading(text) {
377
+ return text.replaceAll(/^( {0,2}[*-] +)?(#{1,3} )/gm, '$1\\$2');
378
+ }
379
+
380
+ /**
381
+ * Escapes bulleted list characters in a string.
382
+ * @param {string} text Content to escape
383
+ * @returns {string}
384
+ */
385
+ static escapeBulletedList(text) {
386
+ return text.replaceAll(/^( *)[*-]( +)/gm, '$1\\-$2');
387
+ }
388
+
389
+ /**
390
+ * Escapes numbered list characters in a string.
391
+ * @param {string} text Content to escape
392
+ * @returns {string}
393
+ */
394
+ static escapeNumberedList(text) {
395
+ return text.replaceAll(/^( *\d+)\./gm, '$1\\.');
396
+ }
397
+
398
+ /**
399
+ * Escapes masked link characters in a string.
400
+ * @param {string} text Content to escape
401
+ * @returns {string}
402
+ */
403
+ static escapeMaskedLink(text) {
404
+ return text.replaceAll(/\[.+\]\(.+\)/gm, '\\$&');
405
+ }
406
+
407
+ /**
408
+ * @typedef {Object} FetchRecommendedShardsOptions
409
+ * @property {number} [guildsPerShard=1000] Number of guilds assigned per shard
410
+ * @property {number} [multipleOf=1] The multiple the shard count should round up to. (16 for large bot sharding)
411
+ */
412
+
413
+ static fetchRecommendedShards() {
414
+ throw new DiscordError('INVALID_USER_API');
415
+ }
416
+
417
+ /**
418
+ * Parses emoji info out of a string. The string must be one of:
419
+ * * A UTF-8 emoji (no id)
420
+ * * A URL-encoded UTF-8 emoji (no id)
421
+ * * A Discord custom emoji (`<:name:id>` or `<a:name:id>`)
422
+ * @param {string} text Emoji string to parse
423
+ * @returns {APIEmoji} Object with `animated`, `name`, and `id` properties
424
+ * @private
425
+ */
426
+ static parseEmoji(text) {
427
+ if (text.includes('%')) text = decodeURIComponent(text);
428
+ if (!text.includes(':')) return { animated: false, name: text, id: null };
429
+ const match = text.match(/<?(?:(a):)?(\w{2,32}):(\d{17,19})?>?/);
430
+ return match && { animated: Boolean(match[1]), name: match[2], id: match[3] ?? null };
431
+ }
432
+
433
+ /**
434
+ * Resolves a partial emoji object from an {@link EmojiIdentifierResolvable}, without checking a Client.
435
+ * @param {EmojiIdentifierResolvable} emoji Emoji identifier to resolve
436
+ * @returns {?RawEmoji}
437
+ * @private
438
+ */
439
+ static resolvePartialEmoji(emoji) {
440
+ if (!emoji) return null;
441
+ if (typeof emoji === 'string') return /^\d{17,19}$/.test(emoji) ? { id: emoji } : Util.parseEmoji(emoji);
442
+ const { id, name, animated } = emoji;
443
+ if (!id && !name) return null;
444
+ return { id, name, animated: Boolean(animated) };
445
+ }
446
+
447
+ /**
448
+ * Shallow-copies an object with its class/prototype intact.
449
+ * @param {Object} obj Object to clone
450
+ * @returns {Object}
451
+ * @private
452
+ */
453
+ static cloneObject(obj) {
454
+ return Object.assign(Object.create(obj), obj);
455
+ }
456
+
457
+ /**
458
+ * Sets default properties on an object that aren't already specified.
459
+ * @param {Object} def Default properties
460
+ * @param {Object} given Object to assign defaults to
461
+ * @returns {Object}
462
+ * @private
463
+ */
464
+ static mergeDefault(def, given) {
465
+ if (!given) return def;
466
+ for (const key in def) {
467
+ if (!has(given, key) || given[key] === undefined) {
468
+ given[key] = def[key];
469
+ } else if (given[key] === Object(given[key])) {
470
+ given[key] = Util.mergeDefault(def[key], given[key]);
471
+ }
472
+ }
473
+
474
+ return given;
475
+ }
476
+
477
+ /**
478
+ * Options used to make an error object.
479
+ * @typedef {Object} MakeErrorOptions
480
+ * @property {string} name Error type
481
+ * @property {string} message Message for the error
482
+ * @property {string} stack Stack for the error
483
+ */
484
+
485
+ /**
486
+ * Makes an Error from a plain info object.
487
+ * @param {MakeErrorOptions} obj Error info
488
+ * @returns {Error}
489
+ * @private
490
+ */
491
+ static makeError(obj) {
492
+ const err = new Error(obj.message);
493
+ err.name = obj.name;
494
+ err.stack = obj.stack;
495
+ return err;
496
+ }
497
+
498
+ /**
499
+ * Makes a plain error info object from an Error.
500
+ * @param {Error} err Error to get info from
501
+ * @returns {MakeErrorOptions}
502
+ * @private
503
+ */
504
+ static makePlainError(err) {
505
+ return {
506
+ name: err.name,
507
+ message: err.message,
508
+ stack: err.stack,
509
+ };
510
+ }
511
+
512
+ /**
513
+ * Moves an element in an array *in place*.
514
+ * @param {Array<*>} array Array to modify
515
+ * @param {*} element Element to move
516
+ * @param {number} newIndex Index or offset to move the element to
517
+ * @param {boolean} [offset=false] Move the element by an offset amount rather than to a set index
518
+ * @returns {number}
519
+ * @private
520
+ */
521
+ static moveElementInArray(array, element, newIndex, offset = false) {
522
+ const index = array.indexOf(element);
523
+ newIndex = (offset ? index : 0) + newIndex;
524
+ if (newIndex > -1 && newIndex < array.length) {
525
+ const removedElement = array.splice(index, 1)[0];
526
+ array.splice(newIndex, 0, removedElement);
527
+ }
528
+ return array.indexOf(element);
529
+ }
530
+
531
+ /**
532
+ * Verifies the provided data is a string, otherwise throws provided error.
533
+ * @param {string} data The string resolvable to resolve
534
+ * @param {Function} [error] The Error constructor to instantiate. Defaults to Error
535
+ * @param {string} [errorMessage] The error message to throw with. Defaults to "Expected string, got <data> instead."
536
+ * @param {boolean} [allowEmpty=true] Whether an empty string should be allowed
537
+ * @returns {string}
538
+ */
539
+ static verifyString(
540
+ data,
541
+ error = Error,
542
+ errorMessage = `Expected a string, got ${data} instead.`,
543
+ allowEmpty = true,
544
+ ) {
545
+ if (typeof data !== 'string') throw new error(errorMessage);
546
+ if (!allowEmpty && data.length === 0) throw new error(errorMessage);
547
+ return data;
548
+ }
549
+
550
+ /**
551
+ * Can be a number, hex string, a {@link Color}, or an RGB array like:
552
+ * ```js
553
+ * [255, 0, 255] // purple
554
+ * ```
555
+ * @typedef {string|Color|number|number[]} ColorResolvable
556
+ */
557
+
558
+ /**
559
+ * Resolves a ColorResolvable into a color number.
560
+ * @param {ColorResolvable} color Color to resolve
561
+ * @returns {number} A color
562
+ */
563
+ static resolveColor(color) {
564
+ if (typeof color === 'string') {
565
+ if (color === 'RANDOM') return Math.floor(Math.random() * (0xffffff + 1));
566
+ if (color === 'DEFAULT') return 0;
567
+ color = Colors[color] ?? parseInt(color.replace('#', ''), 16);
568
+ } else if (Array.isArray(color)) {
569
+ color = (color[0] << 16) + (color[1] << 8) + color[2];
570
+ }
571
+
572
+ if (color < 0 || color > 0xffffff) throw new RangeError('COLOR_RANGE');
573
+ else if (Number.isNaN(color)) throw new TypeError('COLOR_CONVERT');
574
+
575
+ return color;
576
+ }
577
+
578
+ /**
579
+ * Sorts by Discord's position and id.
580
+ * @param {Collection} collection Collection of objects to sort
581
+ * @returns {Collection}
582
+ */
583
+ static discordSort(collection) {
584
+ const isGuildChannel = collection.first() instanceof GuildChannel;
585
+ return collection.toSorted(
586
+ isGuildChannel
587
+ ? (a, b) => a.rawPosition - b.rawPosition || Number(BigInt(a.id) - BigInt(b.id))
588
+ : (a, b) => a.rawPosition - b.rawPosition || Number(BigInt(b.id) - BigInt(a.id)),
589
+ );
590
+ }
591
+
592
+ /**
593
+ * Sets the position of a Channel or Role.
594
+ * @param {Channel|Role} item Object to set the position of
595
+ * @param {number} position New position for the object
596
+ * @param {boolean} relative Whether `position` is relative to its current position
597
+ * @param {Collection<string, Channel|Role>} sorted A collection of the objects sorted properly
598
+ * @param {APIRouter} route Route to call PATCH on
599
+ * @param {string} [reason] Reason for the change
600
+ * @returns {Promise<Channel[]|Role[]>} Updated item list, with `id` and `position` properties
601
+ * @private
602
+ */
603
+ static async setPosition(item, position, relative, sorted, route, reason) {
604
+ let updatedItems = [...sorted.values()];
605
+ Util.moveElementInArray(updatedItems, item, position, relative);
606
+ updatedItems = updatedItems.map((r, i) => ({ id: r.id, position: i }));
607
+ await route.patch({ data: updatedItems, reason });
608
+ return updatedItems;
609
+ }
610
+
611
+ /**
612
+ * Alternative to Node's `path.basename`, removing query string after the extension if it exists.
613
+ * @param {string} path Path to get the basename of
614
+ * @param {string} [ext] File extension to remove
615
+ * @returns {string} Basename of the path
616
+ * @private
617
+ */
618
+ static basename(path, ext) {
619
+ const res = parse(path);
620
+ return ext && res.ext.startsWith(ext) ? res.name : res.base.split('?')[0];
621
+ }
622
+
623
+ /**
624
+ * Breaks user, role and everyone/here mentions by adding a zero width space after every @ character
625
+ * @param {string} str The string to sanitize
626
+ * @returns {string}
627
+ * @deprecated Use {@link BaseMessageOptions#allowedMentions} instead.
628
+ */
629
+ static removeMentions(str) {
630
+ if (!deprecationEmittedForRemoveMentions) {
631
+ process.emitWarning(
632
+ 'The Util.removeMentions method is deprecated. Use MessageOptions#allowedMentions instead.',
633
+ 'DeprecationWarning',
634
+ );
635
+
636
+ deprecationEmittedForRemoveMentions = true;
637
+ }
638
+
639
+ return Util._removeMentions(str);
640
+ }
641
+
642
+ static _removeMentions(str) {
643
+ return str.replaceAll('@', '@\u200b');
644
+ }
645
+
646
+ /**
647
+ * The content to have all mentions replaced by the equivalent text.
648
+ * <warn>When {@link Util.removeMentions} is removed, this method will no longer sanitize mentions.
649
+ * Use {@link BaseMessageOptions#allowedMentions} instead to prevent mentions when sending a message.</warn>
650
+ * @param {string} str The string to be converted
651
+ * @param {TextBasedChannels} channel The channel the string was sent in
652
+ * @returns {string}
653
+ */
654
+ static cleanContent(str, channel) {
655
+ str = str
656
+ .replace(/<@!?[0-9]+>/g, input => {
657
+ const id = input.replace(/<|!|>|@/g, '');
658
+ if (channel.type === 'DM') {
659
+ const user = channel.client.users.cache.get(id);
660
+ return user ? Util._removeMentions(`@${user.username}`) : input;
661
+ }
662
+
663
+ const member = channel.guild?.members.cache.get(id);
664
+ if (member) {
665
+ return Util._removeMentions(`@${member.displayName}`);
666
+ } else {
667
+ const user = channel.client.users.cache.get(id);
668
+ return user ? Util._removeMentions(`@${user.username}`) : input;
669
+ }
670
+ })
671
+ .replace(/<#[0-9]+>/g, input => {
672
+ const mentionedChannel = channel.client.channels.cache.get(input.replace(/<|#|>/g, ''));
673
+ return mentionedChannel ? `#${mentionedChannel.name}` : input;
674
+ })
675
+ .replace(/<@&[0-9]+>/g, input => {
676
+ if (channel.type === 'DM') return input;
677
+ const role = channel.guild.roles.cache.get(input.replace(/<|@|>|&/g, ''));
678
+ return role ? `@${role.name}` : input;
679
+ });
680
+ return str;
681
+ }
682
+
683
+ /**
684
+ * The content to put in a code block with all code block fences replaced by the equivalent backticks.
685
+ * @param {string} text The string to be converted
686
+ * @returns {string}
687
+ */
688
+ static cleanCodeBlockContent(text) {
689
+ return text.replaceAll('```', '`\u200b``');
690
+ }
691
+
692
+ /**
693
+ * Creates a sweep filter that sweeps archived threads
694
+ * @param {number} [lifetime=14400] How long a thread has to be archived to be valid for sweeping
695
+ * @deprecated When not using with `makeCache` use `Sweepers.archivedThreadSweepFilter` instead
696
+ * @returns {SweepFilter}
697
+ */
698
+ static archivedThreadSweepFilter(lifetime = 14400) {
699
+ const filter = require('./Sweepers').archivedThreadSweepFilter(lifetime);
700
+ filter.isDefault = true;
701
+ return filter;
702
+ }
703
+
704
+ /**
705
+ * Resolves the maximum time a guild's thread channels should automatically archive in case of no recent activity.
706
+ * @param {Guild} guild The guild to resolve this limit from.
707
+ * @deprecated This will be removed in the next major version.
708
+ * @returns {number}
709
+ */
710
+ static resolveAutoArchiveMaxLimit() {
711
+ if (!deprecationEmittedForResolveAutoArchiveMaxLimit) {
712
+ process.emitWarning(
713
+ // eslint-disable-next-line max-len
714
+ "The Util.resolveAutoArchiveMaxLimit method and the 'MAX' option are deprecated and will be removed in the next major version.",
715
+ 'DeprecationWarning',
716
+ );
717
+ deprecationEmittedForResolveAutoArchiveMaxLimit = true;
718
+ }
719
+ return 10080;
720
+ }
721
+
722
+ /**
723
+ * Transforms an API guild forum tag to camel-cased guild forum tag.
724
+ * @param {APIGuildForumTag} tag The tag to transform
725
+ * @returns {GuildForumTag}
726
+ * @ignore
727
+ */
728
+ static transformAPIGuildForumTag(tag) {
729
+ return {
730
+ id: tag.id,
731
+ name: tag.name,
732
+ moderated: tag.moderated,
733
+ emoji:
734
+ tag.emoji_id ?? tag.emoji_name
735
+ ? {
736
+ id: tag.emoji_id,
737
+ name: tag.emoji_name,
738
+ }
739
+ : null,
740
+ };
741
+ }
742
+
743
+ /**
744
+ * Transforms a camel-cased guild forum tag to an API guild forum tag.
745
+ * @param {GuildForumTag} tag The tag to transform
746
+ * @returns {APIGuildForumTag}
747
+ * @ignore
748
+ */
749
+ static transformGuildForumTag(tag) {
750
+ return {
751
+ id: tag.id,
752
+ name: tag.name,
753
+ moderated: tag.moderated,
754
+ emoji_id: tag.emoji?.id ?? null,
755
+ emoji_name: tag.emoji?.name ?? null,
756
+ };
757
+ }
758
+
759
+ /**
760
+ * Transforms an API guild forum default reaction object to a
761
+ * camel-cased guild forum default reaction object.
762
+ * @param {APIGuildForumDefaultReactionEmoji} defaultReaction The default reaction to transform
763
+ * @returns {DefaultReactionEmoji}
764
+ * @ignore
765
+ */
766
+ static transformAPIGuildDefaultReaction(defaultReaction) {
767
+ return {
768
+ id: defaultReaction.emoji_id,
769
+ name: defaultReaction.emoji_name,
770
+ };
771
+ }
772
+
773
+ /**
774
+ * Transforms a camel-cased guild forum default reaction object to an
775
+ * API guild forum default reaction object.
776
+ * @param {DefaultReactionEmoji} defaultReaction The default reaction to transform
777
+ * @returns {APIGuildForumDefaultReactionEmoji}
778
+ * @ignore
779
+ */
780
+ static transformGuildDefaultReaction(defaultReaction) {
781
+ return {
782
+ emoji_id: defaultReaction.id,
783
+ emoji_name: defaultReaction.name,
784
+ };
785
+ }
786
+
787
+ /**
788
+ * Transforms a guild scheduled event recurrence rule object to a snake-cased variant.
789
+ * @param {GuildScheduledEventRecurrenceRuleOptions} recurrenceRule The recurrence rule to transform
790
+ * @returns {APIGuildScheduledEventRecurrenceRule}
791
+ * @ignore
792
+ */
793
+ static transformGuildScheduledEventRecurrenceRule(recurrenceRule) {
794
+ return {
795
+ start: new Date(recurrenceRule.startAt).toISOString(),
796
+ frequency: recurrenceRule.frequency,
797
+ interval: recurrenceRule.interval,
798
+ by_weekday: recurrenceRule.byWeekday,
799
+ by_n_weekday: recurrenceRule.byNWeekday,
800
+ by_month: recurrenceRule.byMonth,
801
+ by_month_day: recurrenceRule.byMonthDay,
802
+ };
803
+ }
804
+
805
+ /**
806
+ * Transforms API incidents data to a camel-cased variant.
807
+ * @param {APIIncidentsData} data The incidents data to transform
808
+ * @returns {IncidentActions}
809
+ * @ignore
810
+ */
811
+ static transformAPIIncidentsData(data) {
812
+ return {
813
+ invitesDisabledUntil: data.invites_disabled_until ? new Date(data.invites_disabled_until) : null,
814
+ dmsDisabledUntil: data.dms_disabled_until ? new Date(data.dms_disabled_until) : null,
815
+ dmSpamDetectedAt: data.dm_spam_detected_at ? new Date(data.dm_spam_detected_at) : null,
816
+ raidDetectedAt: data.raid_detected_at ? new Date(data.raid_detected_at) : null,
817
+ };
818
+ }
819
+
820
+ /**
821
+ * Gets an array of the channel types that can be moved in the channel group. For example, a GuildText channel would
822
+ * return an array containing the types that can be ordered within the text channels (always at the top), and a voice
823
+ * channel would return an array containing the types that can be ordered within the voice channels (always at the
824
+ * bottom).
825
+ * @param {ChannelType} type The type of the channel
826
+ * @returns {ChannelType[]}
827
+ * @ignore
828
+ */
829
+ static getSortableGroupTypes(type) {
830
+ switch (type) {
831
+ case 'GUILD_TEXT':
832
+ case 'GUILD_ANNOUNCEMENT':
833
+ case 'GUILD_FORUM':
834
+ return TextSortableGroupTypes;
835
+ case 'GUILD_VOICE':
836
+ case 'GUILD_STAGE_VOICE':
837
+ return VoiceSortableGroupTypes;
838
+ case 'GUILD_CATEGORY':
839
+ return CategorySortableGroupTypes;
840
+ default:
841
+ return [type];
842
+ }
843
+ }
844
+
845
+ /**
846
+ * Calculates the default avatar index for a given user id.
847
+ * @param {Snowflake} userId - The user id to calculate the default avatar index for
848
+ * @returns {number}
849
+ */
850
+ static calculateUserDefaultAvatarIndex(userId) {
851
+ return Number(BigInt(userId) >> 22n) % 6;
852
+ }
853
+
854
+ static async getUploadURL(client, channelId, files) {
855
+ if (!files.length) return [];
856
+ files = files.map((file, i) => ({
857
+ filename: file.name,
858
+ // 25MB = 26_214_400bytes
859
+ file_size: Math.floor((26_214_400 / 10) * Math.random()),
860
+ id: `${i}`,
861
+ }));
862
+ const { attachments } = await client.api.channels[channelId].attachments.post({
863
+ data: {
864
+ files,
865
+ },
866
+ });
867
+ return attachments;
868
+ }
869
+
870
+ static uploadFile(data, url) {
871
+ return new Promise((resolve, reject) => {
872
+ fetch(url, {
873
+ method: 'PUT',
874
+ body: data,
875
+ duplex: 'half', // Node.js v20
876
+ })
877
+ .then(res => {
878
+ if (res.ok) {
879
+ resolve(res);
880
+ } else {
881
+ reject(res);
882
+ }
883
+ })
884
+ .catch(reject);
885
+ });
886
+ }
887
+
888
+ /**
889
+ * Lazily evaluates a callback function (yea it's v14 :yay:)
890
+ * @param {Function} cb The callback to lazily evaluate
891
+ * @returns {Function}
892
+ * @example
893
+ * const User = lazy(() => require('./User'));
894
+ * const user = new (User())(client, data);
895
+ */
896
+ static lazy(cb) {
897
+ let defaultValue;
898
+ return () => (defaultValue ??= cb());
899
+ }
900
+
901
+ /**
902
+ * Hacking check object instanceof Proxy-agent
903
+ * @param {Object} object any
904
+ * @returns {boolean}
905
+ */
906
+ static verifyProxyAgent(object) {
907
+ return typeof object == 'object' && object.httpAgent instanceof Agent && object.httpsAgent instanceof Agent;
908
+ }
909
+
910
+ static checkUndiciProxyAgent(data) {
911
+ if (typeof data === 'string') {
912
+ return {
913
+ uri: data,
914
+ };
915
+ }
916
+ if (data instanceof URL) {
917
+ return {
918
+ uri: data.toString(),
919
+ };
920
+ }
921
+ if (typeof data === 'object' && typeof data.uri === 'string') return data;
922
+ return false;
923
+ }
924
+
925
+ static createPromiseInteraction(client, nonce, timeoutMs = 5_000, isHandlerDeferUpdate = false, parent) {
926
+ return new Promise((resolve, reject) => {
927
+ // Waiting for MsgCreate / ModalCreate
928
+ let dataFromInteractionSuccess;
929
+ let dataFromNormalEvent;
930
+ const handler = data => {
931
+ // UnhandledPacket
932
+ if (isHandlerDeferUpdate && data.d?.nonce == nonce && data.t == 'INTERACTION_SUCCESS') {
933
+ // Interaction#deferUpdate
934
+ client.removeListener(Events.MESSAGE_CREATE, handler);
935
+ client.removeListener(Events.UNHANDLED_PACKET, handler);
936
+ client.removeListener(Events.INTERACTION_MODAL_CREATE, handler);
937
+ dataFromInteractionSuccess = parent;
938
+ }
939
+ if (data.nonce !== nonce) return;
940
+ clearTimeout(timeout);
941
+ client.removeListener(Events.MESSAGE_CREATE, handler);
942
+ client.removeListener(Events.INTERACTION_MODAL_CREATE, handler);
943
+ if (isHandlerDeferUpdate) client.removeListener(Events.UNHANDLED_PACKET, handler);
944
+ client.decrementMaxListeners();
945
+ dataFromNormalEvent = data;
946
+ resolve(data);
947
+ };
948
+ const timeout = setTimeout(() => {
949
+ if (dataFromInteractionSuccess || dataFromNormalEvent) {
950
+ resolve(dataFromNormalEvent || dataFromInteractionSuccess);
951
+ return;
952
+ }
953
+ client.removeListener(Events.MESSAGE_CREATE, handler);
954
+ client.removeListener(Events.INTERACTION_MODAL_CREATE, handler);
955
+ if (isHandlerDeferUpdate) client.removeListener(Events.UNHANDLED_PACKET, handler);
956
+ client.decrementMaxListeners();
957
+ reject(new DiscordError('INTERACTION_FAILED'));
958
+ }, timeoutMs).unref();
959
+ client.incrementMaxListeners();
960
+ client.on(Events.MESSAGE_CREATE, handler);
961
+ client.on(Events.INTERACTION_MODAL_CREATE, handler);
962
+ if (isHandlerDeferUpdate) client.on(Events.UNHANDLED_PACKET, handler);
963
+ });
964
+ }
965
+
966
+ static clearNullOrUndefinedObject(object) {
967
+ const data = {};
968
+ const keys = Object.keys(object);
969
+
970
+ for (const key of keys) {
971
+ const value = object[key];
972
+ if (value === undefined || value === null || (Array.isArray(value) && value.length === 0)) {
973
+ continue;
974
+ } else if (!Array.isArray(value) && typeof value === 'object') {
975
+ const cleanedValue = Util.clearNullOrUndefinedObject(value);
976
+ if (cleanedValue !== undefined) {
977
+ data[key] = cleanedValue;
978
+ }
979
+ } else {
980
+ data[key] = value;
981
+ }
982
+ }
983
+
984
+ return Object.keys(data).length > 0 ? data : undefined;
985
+ }
986
+
987
+ static getAllPayloadType() {
988
+ return payloadTypes;
989
+ }
990
+
991
+ /**
992
+ * Get the payload type of the codec
993
+ * @param {'opus' | 'H264' | 'H265' | 'VP8' | 'VP9' | 'AV1'} codecName - Codec name
994
+ * @returns {number}
995
+ */
996
+ static getPayloadType(codecName) {
997
+ return payloadTypes.find(p => p.name === codecName).payload_type;
998
+ }
999
+
1000
+ static getSDPCodecName(portUdpH264, portUdpH265, portUdpOpus) {
1001
+ const payloadTypeH264 = Util.getPayloadType('H264');
1002
+ const payloadTypeH265 = Util.getPayloadType('H265');
1003
+ const payloadTypeOpus = Util.getPayloadType('opus');
1004
+ let sdpData = `v=0
1005
+ o=- 0 0 IN IP4 0.0.0.0
1006
+ s=-
1007
+ c=IN IP4 0.0.0.0
1008
+ t=0 0
1009
+ a=tool:libavformat 61.1.100
1010
+ m=video ${portUdpH264} RTP/AVP ${payloadTypeH264}
1011
+ c=IN IP4 127.0.0.1
1012
+ b=AS:1000
1013
+ a=rtpmap:${payloadTypeH264} H264/90000
1014
+ a=fmtp:${payloadTypeH264} profile-level-id=42e01f;sprop-parameter-sets=Z0IAH6tAoAt2AtwEBAaQeJEV,aM4JyA==;packetization-mode=1
1015
+ ${
1016
+ portUdpH265
1017
+ ? `m=video ${portUdpH265} RTP/AVP ${payloadTypeH265}
1018
+ c=IN IP4 127.0.0.1
1019
+ b=AS:1000
1020
+ a=rtpmap:${payloadTypeH265} H265/90000`
1021
+ : ''
1022
+ }
1023
+ m=audio ${portUdpOpus} RTP/AVP ${payloadTypeOpus}
1024
+ c=IN IP4 127.0.0.1
1025
+ b=AS:96
1026
+ a=rtpmap:${payloadTypeOpus} opus/48000/2
1027
+ a=fmtp:${payloadTypeOpus} minptime=10;useinbandfec=1
1028
+ a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
1029
+ a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
1030
+ a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
1031
+ a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid
1032
+ a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay
1033
+ a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type
1034
+ a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing
1035
+ a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space
1036
+ a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id
1037
+ a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id
1038
+ a=extmap:13 urn:3gpp:video-orientation
1039
+ a=extmap:14 urn:ietf:params:rtp-hdrext:toffset
1040
+ `;
1041
+ return sdpData;
1042
+ }
1043
+ }
1044
+
1045
+ module.exports = Util;
1046
+
1047
+ // Fixes Circular
1048
+ const GuildChannel = require('../structures/GuildChannel');